<?php
namespace App\Controller;
use DateTime;
use DateInterval;
use App\Entity\Ligne;
use App\Entity\Centre;
use App\Entity\Marque;
use App\Entity\Modele;
use App\Entity\Adresse;
use App\Entity\Energie;
use App\Entity\MarqueCl;
use App\Entity\ModeleCl;
use phpseclib3\Net\SFTP;
use App\Entity\Promotion;
use App\Form\AdresseType;
use App\Entity\CentreType;
use App\Entity\Partenaire;
use App\Entity\Rendezvous;
use App\Entity\CentreGroupe;
use App\Entity\ClientCompte;
use App\Entity\LigneBlocage;
use App\Entity\LigneHoraire;
use App\Entity\TypeVehicule;
use App\Entity\CentreHoraire;
use App\Form\ClientCompteType;
use App\Entity\ParametreCentre;
use App\Entity\RendezVousInfos;
use App\Entity\CentrePrestation;
use App\Controller\ApiController;
use Symfony\Component\Mime\Email;
use App\Entity\RendezVousVehicule;
use PHPMailer\PHPMailer\Exception;
use Symfony\Component\Finder\Finder;
use App\Entity\CentreCouponPromotion;
use App\Entity\ParametreCentreGroupe;
use Doctrine\Persistence\ObjectManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\RendezVousVehiculeRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class ProController extends AbstractController
{
public $id;
protected $em;
protected $cache;
protected $mois;
protected $jours;
private $passwordHasher;
private $ApiController;
private $session;
protected $mailer;
public function __construct(
ApiController $ApiController,
EntityManagerInterface $entityManager,
CacheInterface $cache,
UserPasswordHasherInterface $passwordHasher,
SessionInterface $session,
MailerInterface $mailer
) {
date_default_timezone_set('Europe/Paris');
$this->jours = array('Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche');
$this->mois = array(1 => "Janvier", 2 => "Février", 3 => "Mars", 4 => "Avril", 5 => "Mai", 6 => "Juin", 7 => "Juillet", 8 => "Août", 9 => "Septembre", 10 => "Octobre", 11 => "Novembre", 12 => "Décembre");
$this->em = $entityManager;
$this->cache = $cache;
$this->passwordHasher = $passwordHasher;
$this->ApiController = $ApiController;
$this->session = $session;
$this->mailer = $mailer;
if (array_key_exists('SERVER_NAME', $_SERVER)) {
$ParametreCentreGroupe = $this->em->getRepository(ParametreCentreGroupe::class)->findOneByUrl($_SERVER['SERVER_NAME']);
} else {
$ParametreCentreGroupe = false;
}
if ($ParametreCentreGroupe) {
$this->id = $ParametreCentreGroupe->getCentreGroupe()->getId();
$this->session->set('centre_groupe', $ParametreCentreGroupe->getCentreGroupe()->getId());
} else {
$this->id = 1;
$this->session->set('centre_groupe', $this->id);
}
}
#[Route('pro/accueil', name: 'app_pro')]
public function accueil(Request $request): Response
{
$centreGroupe = $this->em->getRepository(CentreGroupe::class)->find($request->getSession()->get('centre_groupe'));
$user = $this->getUser();
if(!$user->getCliHasProAccess()){
$this->addFlash('error', 'L\'accès à votre espace pro est désactiver, veuillez contacter le centre.');
return $this->redirectToRoute('app_logout_pro');
}
foreach ($centreGroupe->getCentres() as $key => $centre) {
if (($user->isCliVl() && $centre->getCentreType()->getId() == 1) || ($user->isCliPl() && $centre->getCentreType()->getId() == 2) || ($user->isCliCl() && $centre->getCentreType()->getId() == 4)) {
if ($key == 0) {
$request->getSession()->set('centre_id', $centre->getId());
}
$CentreHoraires = $this->em->getRepository(CentreHoraire::class)->getHoraires($centre->getId());
// $url = "https://maps.googleapis.com/maps/api/place/details/json?key=AIzaSyBs9p5zKlf3sCH5w62p-VAG9dzwzmlLEyw&place_id=ChIJZ6A8G0cSrhIReKHpbVX0Yk4&language=fr-FR";
// $result = file_get_contents($url);
$result = "{}";
// if ($centre->getCtrParametreCentre()->getPcGoogleBuisness()) {
// $url = "https://maps.googleapis.com/maps/api/place/details/json?key=AIzaSyBs9p5zKlf3sCH5w62p-VAG9dzwzmlLEyw&place_id=" . $centre->getCtrParametreCentre()->getPcGoogleBuisness() . "&language=fr-FR";
// $result = file_get_contents($url);
// }
if ($centre->getCtrParametreCentre()->getPcGoogleBuisness()) {
$result = $this->cache->get($centre->getCtrParametreCentre()->getPcGoogleBuisness(), function (ItemInterface $item) use ($centre) {
$item->expiresAfter(DateInterval::createFromDateString('7 days'));
$url = "https://maps.googleapis.com/maps/api/place/details/json?key=AIzaSyBs9p5zKlf3sCH5w62p-VAG9dzwzmlLEyw&place_id=" . $centre->getCtrParametreCentre()->getPcGoogleBuisness() . "&language=fr-FR";
$result = file_get_contents($url);
return $result;
});
}
// $Prestations = $this->cache->get('CentrePrestation_'.$value->getId(), function () use($value){
$CentrePrestations = $this->em->getrepository(CentrePrestation::class)->findByCentreGroupeAndCentreType(
$centre->getCentreGroupe()->getId(),
$centre->getCentreType()->getId()
);
$Prestations = [];
foreach ($CentrePrestations as $key => $CentrePrestation) {
$reduction = $this->ApiController->getTarifPromotionsParHoraire($CentrePrestation->getId(), new datetime(), $CentrePrestation->getPstTarif());
$reduction = $reduction['tarif_final'];
// dd($CentrePrestation->getPstTarif(),$reduction,$CentrePrestation->getPstTypeVisite()->getTypVstLibeleLong() );
if ($reduction < $CentrePrestation->getPstTarif()) {
$tarif_final = $reduction;
}
$Prestations[] = [
'TypeVisite' => $CentrePrestation->getPstTypeVisite()->getTypVstLibeleLong(),
'PrixInitial' => $CentrePrestation->getPstTarif(),
'Duree' => $CentrePrestation->getPstDuree(),
'Reduction' => $reduction < $CentrePrestation->getPstTarif() ? true : false,
'PrixFinal' => $reduction < $CentrePrestation->getPstTarif() ? $tarif_final : $CentrePrestation->getPstTarif(),
'Id' => $CentrePrestation->getId(),
];
}
// return $CentrePrestation;
// });
$array_centres[] = ['Horaires' => $CentreHoraires, 'avis' => json_decode($result, true), 'Prestations' => $Prestations];
$data_centres_user[] = $centre;
}
}
return $this->render('pro/accueil_pro.html.twig', [
'array_centres' => $array_centres,
'data_centres_user' => $data_centres_user,
'countcentres' => Count($data_centres_user),
]);
}
#[Route(path: '/login', name: 'app_login_pro')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$parameters = [];
if ($error) {
$parameters = ['errorLogin'=>true];
}
return $this->redirectToRoute('index',$parameters);
}
#[Route(path: '/logout', name: 'app_logout_pro')]
public function logout(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route('/formulaire_compte', name: 'formulaire_compte')]
public function formulaire_compte()
{
$data_centre_types = $this->cache->get('centre_type' . $this->id, function () {
$data_centre_types = $this->em->getRepository(CentreType::class)->findTypesByCentreGroupeId($this->id);
return $data_centre_types;
});
return $this->render('pro/formulaire_compte.html.twig', [
'centre_types' => $data_centre_types,
]);
}
#[Route('/add_client_compte', name: 'add_client_compte')]
public function add_client_compte(Request $request, UrlGeneratorInterface $urlGenerator)
{
$ClientCompte = $this->em->getrepository(ClientCompte::class)->findOneBy(['cli_email' => $request->get('email_perso'), 'centre_groupe' => $request->getSession()->get('centre_groupe')]);
if ($ClientCompte) {
return new Jsonresponse(["result" => "KO", "Msg" => "L'adresse e-mail existe déjà dans ce centre."]);
}
$client_compte = new ClientCompte;
$idenCheck = $this->em->getrepository(ClientCompte::class)->findby(['cli_username' => $request->get('iden_perso')]);
if ($idenCheck) {
return new Jsonresponse(["result" => "KO", "Msg" => "l'identifiant est déjà utilisé."]);
}
$centre_groupe = $this->em->getrepository(CentreGroupe::class)->find($request->getSession()->get('centre_groupe'));
$client_compte->setCentreGroupe($centre_groupe);
/** @var Centre[] $centres */
$centresM = $centre_groupe->getCentres();
$email = $centresM[0]->getCtrEmail();
$client_compte->setCliVl(false);
$client_compte->setCliPl(false);
$client_compte->setCliCl(false);
foreach ($request->get('type_prestation') as $type_prestation) {
if ($type_prestation == 'VL') {
$client_compte->setCliVl(true);
}
if ($type_prestation == 'PL') {
$client_compte->setCliPl(true);
}
if ($type_prestation == 'CL') {
$client_compte->setCliCl(true);
}
}
$client_compte->setCentreType(null);
// $centre_type = $this->em->getrepository(CentreType::class)->find($request->get('type_prestation'));
// $client_compte->setCentreType($centre_type);
$hashedPassword = $this->passwordHasher->hashPassword(
$client_compte,
$request->get('password1_perso')
);
$client_compte->setCliPassword($hashedPassword);
$client_compte->setCliSalt('');
$client_compte->setCliNomSociete($request->get('nom_societe'));
$client_compte->setCliUsername($request->get('iden_perso'));
$client_compte->setCliNom($request->get('nom_perso'));
$client_compte->setCliPrenom($request->get('prenom_perso'));
$client_compte->setCliEmail($request->get('email_perso') ? $request->get('email_perso') : '');
$client_compte->setCliTelephone($request->get('tel1_perso'));
$client_compte->setCliTelephone2($request->get('tel2_perso'));
$client_compte->setCliFax($request->get('fax_perso'));
$client_compte->setCliTva($request->get('tva_societe'));
$client_compte->setCliSiren($request->get('siret_societe'));
$client_compte->setCliCpl($request->get('cpl_societe'));
$client_compte->setCliContact1Nom($request->get('nom_res_parc'));
$client_compte->setCliContact1Prenom($request->get('prenom_res_parc'));
$client_compte->setCliContact1Email($request->get('email_res_parc'));
$client_compte->setCliContact1Telephone($request->get('tel_res_parc'));
$client_compte->setCliContact2Nom($request->get('nom_res_compta'));
$client_compte->setCliContact2Prenom($request->get('prenom_res_compta'));
$client_compte->setCliContact2Email($request->get('email_res_compta'));
$client_compte->setCliContact2Telephone($request->get('tel_res_compta'));
// demande de cédric et aurélien le 28/05 pour ne pas activer par défaut les compte client pro
// mantis num : 0000928
$client_compte->setCliIsActive(0);
$client_compte->setCliHasProAccess(0);
$adresse = new Adresse;
$adresse->setAdrRue($request->get('rue_societe'));
$adresse->setAdrComplement($request->get('compl_societe'));
$adresse->setAdrCodePostal($request->get('cp_societe'));
$adresse->setAdrVille($request->get('ville_societe'));
$this->em->persist($adresse);
$client_compte->setAdresse($adresse);
if ($request->get('adres_identique')) {
$adresse = new Adresse;
$adresse->setAdrRue($request->get('rue_societe'));
$adresse->setAdrComplement($request->get('compl_societe'));
$adresse->setAdrCodePostal($request->get('cp_societe'));
$adresse->setAdrVille($request->get('ville_societe'));
$this->em->persist($adresse);
$client_compte->setAdresseFacturation($adresse);
} else {
$adresseFact = new Adresse;
$adresseFact->setAdrRue($request->get('rue_fact_societe'));
$adresseFact->setAdrComplement($request->get('compl_fact_societe'));
$adresseFact->setAdrCodePostal($request->get('cp_fact_societe'));
$adresseFact->setAdrVille($request->get('ville_fact_societe'));
$client_compte->setAdresseFacturation($adresseFact);
}
$this->em->persist($client_compte);
$this->em->flush();
$this->cache->delete('client_compte' . $request->getSession()->get('centre_groupe'));
$url = $urlGenerator->generate('index');
if ($_SERVER['APP_ENV'] == 'dev') {
return new Jsonresponse(["result" => "OK", "route" => $url, "Msg" => "La création de votre compte a bien été validée"]);
}
// demande de cédric et aurélien le 28/05 pour ne pas activer par défaut les compte client pro
// mantis num : 0000928
$email = (new Email())
->from('noreply@notification-abs.com')
->to($email)
//->to('h.madi@autobilan-systems.com')
->subject('Validation d\'un nouveau client pro depuis MercureWeb')
->html($this->renderView('email/creation_client_compte.html.twig', ['client' => $client_compte, 'objet' => 'Validation d\'un nouveau client pro depuis MercureWeb']));
$this->mailer->send($email);
return new Jsonresponse(["result" => "OK", "route" => $url, "Msg" => "La création de votre compte a bien été validée"]);
}
#[Route('/mot_de_passe_oublie', name: 'mot_de_passe_oublie')]
public function mot_de_passe_oublie(Request $Request)
{
$ClientCompte = $this->em->getRepository(ClientCompte::class)->findOneBy(['cli_email' => $Request->get('email_oublie')]);
if ($ClientCompte) {
if ($ClientCompte->isCliIsActive() == true) {
$name = $ClientCompte->getCliNom() . ' ' . $ClientCompte->getCliPrenom();
$email = $this->decrypt_encrypt("encrypt", $ClientCompte->getCliEmail());
$id = $this->decrypt_encrypt("encrypt", $ClientCompte->getid());
// return $this->render('email/mot_de_passe_oublie.html.twig', array('name' => $name, 'email' => $email, 'id' => $id));
$email = (new Email())
->from('noreply@notification-abs.com')
->to($ClientCompte->getCliEmail())
//->to('h.madi@autobilan-systems.com')
//->ReplyTo($rdv->getCentre()->getCtrEmail())
->subject('Réinitialisation de votre mot de passe')
->html($this->renderView('email/mot_de_passe_oublie.html.twig', ['name' => $name, 'email' => $email, 'id' => $id]));
$this->mailer->send($email);
$this->addFlash('success', "Un courrier a été envoyé sur votre boite email.");
return $this->redirectToRoute('erreur');
} else {
$this->addFlash("error", "L'utilisateur est désactivé");
return $this->redirectToRoute('erreur');
}
} else {
$this->addFlash("error", "L'adresse email saisie est introuvable dans la base des abonnés");
return $this->redirectToRoute('erreur');
}
return $this->redirectToRoute('index');
}
#[Route('/email_client_compte/{id}', name: 'email_client_compte')]
public function email_client_compte($id, Request $Request, MailerInterface $mailer)
{
$ClientComptes = $this->em->getRepository(ClientCompte::class)->findBy(['centre_groupe' => $id, 'cli_is_active' => 1]);
foreach ($ClientComptes as $key => $ClientCompte) {
$ParametreCentreGroupe = $this->em->getRepository(ParametreCentreGroupe::class)->findOneBy(['centre_groupe' => $id]);
return $this->render('email/email_client_compte.html.twig', [
'centre_groupe' => $ClientCompte->getCentreGroupe(),
'ParametreCentreGroupe' => $ParametreCentreGroupe,
]);
if ($ClientCompte->getCliEmail()) {
$email = (new Email())
->from('noreply@notification-abs.com')
->to($ClientCompte->getCliEmail())
//->to('h.madi@autobilan-systems.com')
//->ReplyTo($rdv->getCentre()->getCtrEmail())
->subject('Mise à jour du site de prise de rendez-vous - ' . $ClientCompte->getCentreGroupe()->getCgNom())
->html($this->renderView('email/email_client_compte.html.twig', ['centre_groupe' => $ClientCompte->getCentreGroupe(), 'ParametreCentreGroupe' => $ParametreCentreGroupe]));
$mailer->send($email);
}
}
return $this->redirectToRoute('index');
}
#[Route('/retour_motdepasse', name: 'retour_motdepasse')]
public function retour_motdepasse(Request $request, ObjectManager $manager)
{
if ($request->request->get('mdp1') and $request->request->get('id')) {
$ClientCompte = $this->em->getRepository(ClientCompte::class)->find($request->request->get('id'));
$hashedPassword = $this->passwordHasher->hashPassword(
$ClientCompte,
$request->get('mdp1')
);
$ClientCompte->setCliPassword($hashedPassword);
$manager->persist($ClientCompte);
$manager->flush();
return $this->redirectToRoute('index');
}
$email = $this->decrypt_encrypt("decrypt", $request->query->get('email'));
$id = $this->decrypt_encrypt("decrypt", $request->query->get('id'));
return $this->render('pro/change_mot_de_passe.html.twig', [
'id' => $id,
'email' => $email,
]);
}
#[Route('pro/prendre_rdv_pro', name: 'prendre_rdv_pro')]
public function prendre_rdv_pro(Request $Request, ApiController $apiController): Response
{
if ($Request->get('id')) {
$id = $Request->get('id');
} else {
$id = $Request->getSession()->get('centre_id');
}
$Request->getSession()->set('centre_id', $id);
$centre = $this->em->getRepository(Centre::class)->find($id);
$centre_id = $Request->getSession()->get('centre_id');
$data_centre = $this->cache->get('Centre_' . $centre_id, function () use ($centre_id) {
$data_centre = $this->em->getRepository(Centre::class)->find($centre_id);
return $data_centre;
});
$bornes_recherche = array();
$bornes_recherche['debut'] = new DateTime();
$bornes_recherche['fin'] = clone $bornes_recherche['debut'];
$DureeMaxRdv = $data_centre->getCtrParametreCentre()->getPcDureeMaxRdv() ? $data_centre->getCtrParametreCentre()->getPcDureeMaxRdv() : 60;
$bornes_recherche['fin']->modify('+' . $DureeMaxRdv . ' days');
$listeMois = $this->ApiController->liste_mois($bornes_recherche['debut']->format('d-m-Y'), $bornes_recherche['fin']->format('d-m-Y'), $this->mois);
$data_marques = $this->cache->get('marque', function () {
$data_marques = $this->em->getrepository(Marque::class)->findBy([], ['ordre' => 'asc', 'marque_libele' => 'asc']);
return $data_marques;
});
$data_marques_cl = $this->cache->get('marque_cl', function () {
$data_marques_cl = $this->em->getRepository(MarqueCl::class)->findBy([], ['ordre' => 'asc', 'marque_libele' => 'asc']);
return $data_marques_cl;
});
$data_energies = $this->cache->get('energie', function () {
$data_energies = $this->em->getrepository(Energie::class)->findAll();
return $data_energies;
});
$centrePrestations = $this->em->getRepository(CentrePrestation::class)->findByCentreGroupeAndCentreType($centre->getCentreGroupe()->getId(), $centre->getCentreType()->getId());
$TypeVehiculesVL = $this->em->getRepository(TypeVehicule::class)->findByCentreGroupeCentreType($centre->getCentreGroupe()->getId(), 1);
$TypeVehiculesPL = $this->em->getRepository(TypeVehicule::class)->findByCentreGroupeCentreType($centre->getCentreGroupe()->getId(), 2);
$TypeVehiculesCL = $this->em->getRepository(TypeVehicule::class)->findByCentreGroupeCentreType($centre->getCentreGroupe()->getId(), 4);
$energiesCentreVl = $this->em->getrepository(ParametreCentre::class)->findEnergiesByCentreGroupeAndCentreType($this->id, 1);
$energiesCentrePl = $this->em->getrepository(ParametreCentre::class)->findEnergiesByCentreGroupeAndCentreType($this->id, 2);
$energiesCentreCl = $this->em->getrepository(ParametreCentre::class)->findEnergiesByCentreGroupeAndCentreType($this->id, 4);
$cleanEnergiesVl = $apiController->getCleanEnergies($energiesCentreVl);
$cleanEnergiesPl = $apiController->getCleanEnergies($energiesCentrePl);
$cleanEnergiesCl = $apiController->getCleanEnergies($energiesCentreCl);
return $this->render('pro/prendre_rdv_pro.html.twig', [
'id_centre' => $id,
'centrePrestations' => $centrePrestations,
'centreType' => $data_centre->getCentreType()->getId(),
'typeVehiculesVL' => $TypeVehiculesVL,
'typeVehiculesPL' => $TypeVehiculesPL,
'typeVehiculesCL' => $TypeVehiculesCL,
'energiesVl' => $cleanEnergiesVl,
'energiesPl' => $cleanEnergiesPl,
'energiesCl' => $cleanEnergiesCl,
'marques' => $data_marques,
'marquesCl' => $data_marques_cl,
'energies' => $data_energies,
'ListeMois' => $listeMois,
'Centre' => $data_centre,
'debut' => $bornes_recherche['debut'],
]);
}
/**
* @Route("/pro/rendez_vous_vehicule_add", name="rendez_vous_vehicule_pro_add")
*/
public function AddRendezVousVehicule_pro(Request $request, ObjectManager $manager)
{
if ($request->get('id_vehicule_add') != '') {
$rendez_vous_vehicules = $this->em->getrepository(RendezVousVehicule::class)->find($request->get('id_vehicule_add'));
} else {
$rendez_vous_vehicules = new RendezVousVehicule();
}
if ($request->get('marque_add')) {
$test_marque = $this->em->getrepository(Marque::class)->find($request->get('marque_add'));
$rendez_vous_vehicules->setMarque($test_marque);
if ($request->get('modele_add')) {
$test_modele = $this->em->getrepository(Modele::class)->find($request->get('modele_add'));
$rendez_vous_vehicules->setModele($test_modele);
}
} else if ($request->get('marque_cl_add')) {
$test_marque = $this->em->getrepository(MarqueCl::class)->find($request->get('marque_cl_add'));
$rendez_vous_vehicules->setMarqueCl($test_marque);
if ($request->get('modele_cl_add')) {
$test_modele = $this->em->getrepository(ModeleCl::class)->find($request->get('modele_cl_add'));
$rendez_vous_vehicules->setModeleCl($test_modele);
}
}
if ($request->get('type_vehicule_add')) {
$test_type_vehicule = $this->em->getrepository(TypeVehicule::class)->find($request->get('type_vehicule_add'));
$rendez_vous_vehicules->setTypeVehicule($test_type_vehicule);
}
$rendez_vous_vehicules->setClientCompte($this->getUser());
if ($request->get('energie_add')) {
$test_energie = $this->em->getrepository(Energie::class)->find($request->get('energie_add'));
$rendez_vous_vehicules->setEnergie($test_energie);
}
$rendez_vous_vehicules->setRdvVhcImmatriculation($request->get('immatriculation_add'));
$rendez_vous_vehicules->setRdvVhcDateEcheance($request->get('date_echeance_ct_add') ? new datetime($request->get('date_echeance_ct_add')) : null);
$rendez_vous_vehicules->setRdvVhcTypeProprietaire($request->get('type_proprietaire'));
$rendez_vous_vehicules->setRdvVhcPrenomClientProprietaire($request->get('prenom_add'));
$rendez_vous_vehicules->setRdvVhcNomClientProprietaire($request->get('nom_add'));
$manager->persist($rendez_vous_vehicules);
$manager->flush();
return new JsonResponse(['id' => $rendez_vous_vehicules->getId(), 'type' => $rendez_vous_vehicules->getTypeVehicule()->getId()]);
}
/**
* @Route("pro/prestation_by_centre_type_pro/{id_centre_type}", name="prestation_by_centre_type_pro", methods={"GET"})
*/
public function getPrestationByCentreTypePro(int $id_centre_type)
{
$data_prestations = $this->em->getrepository(CentrePrestation::class)->findByCentreGroupeAndCentreType($this->id, $id_centre_type);
$prestationsArray = array();
foreach ($data_prestations as $prestation) {
$prestationsArray[] = array(
'id' => $prestation->getId(),
'pst_tarif' => $prestation->getPstTarif(),
'pst_duree' => $prestation->getPstDuree(),
'type_visite' => $prestation->getPstTypeVisite()->getId(),
'type_visite_libele' => $prestation->getPstTypeVisite()->getTypVstLibele(),
'type_visite_libele_long' => $prestation->getPstTypeVisite()->getTypVstLibeleLong(),
'type_controle_libele_long' => $prestation->getPstTypeVehicule()->getTvLibelle(),
// 'centre_groupe' => $prestation->getCentreGroupe()->getId()
);
}
// Retourner les données en format JSON
return new JsonResponse($prestationsArray);
}
/**
* @Route("pro/prestation_by_type_vehicule_pro/{id_type_vehicule}", name="prestation_by_type_vehicule_pro", methods={"GET"})
*/
public function prestationByTypeVehicule($id_type_vehicule, Request $request)
{
$data_prestations = $this->em->getrepository(CentrePrestation::class)->findByCentreGroupeAndTypeVehicule($request->getSession()->get('centre_groupe'), $id_type_vehicule);
$prestationsArray = array();
foreach ($data_prestations as $prestation) {
$prestationsArray[] = array(
'id' => $prestation->getId(),
'pst_tarif' => $prestation->getPstTarif(),
'pst_duree' => $prestation->getPstDuree(),
'type_visite' => $prestation->getPstTypeVisite()->getId(),
'type_visite_libele' => $prestation->getPstTypeVisite()->getTypVstLibele(),
'type_visite_libele_long' => $prestation->getPstTypeVisite()->getTypVstLibeleLong(),
// 'centre_groupe' => $prestation->getCentreGroupe()->getId()
);
}
// Retourner les données en format JSON
return new JsonResponse($prestationsArray);
}
/**
* @Route("/pro/rendez_vous_vehicule_pl_add", name="rendez_vous_vehicule_pl_pro_add")
*/
public function rendez_vous_vehicule_pl_add(Request $request, ObjectManager $manager)
{
if ($request->get('id_vehicule_pl_add') != '') {
$rendez_vous_vehicules = $this->em->getrepository(RendezVousVehicule::class)->find($request->get('id_vehicule_pl_add'));
} else {
$rendez_vous_vehicules = new RendezVousVehicule();
}
if ($request->get('type_vehicule_pl_add')) {
$test_type_vehicule = $this->em->getrepository(TypeVehicule::class)->find($request->get('type_vehicule_pl_add'));
$rendez_vous_vehicules->setTypeVehicule($test_type_vehicule);
}
$rendez_vous_vehicules->setClientCompte($this->getUser());
if ($request->get('energie_pl_add')) {
$test_energie = $this->em->getrepository(Energie::class)->find($request->get('energie_pl_add'));
$rendez_vous_vehicules->setEnergie($test_energie);
}
$test_marque = $this->em->getrepository(Marque::class)->find(1);
$rendez_vous_vehicules->setMarque($test_marque);
$test_modele = $this->em->getrepository(Modele::class)->find(1);
$rendez_vous_vehicules->setModele($test_modele);
$rendez_vous_vehicules->setRdvVhcImmatriculation($request->get('immatriculation_pl_add'));
$rendez_vous_vehicules->setRdvVhcDateEcheance($request->get('date_echeance_ct_pl_add') ? new datetime($request->get('date_echeance_ct_pl_add')) : null);
$rendez_vous_vehicules->setRdvVhcDateChronotachygraphe($request->get('date_chrono_pl_add') ? new datetime($request->get('date_chrono_pl_add')) : null);
$rendez_vous_vehicules->setRdvVhcDateLimiteurVitesse($request->get('date_limiteur_pl_add') ? new datetime($request->get('date_limiteur_pl_add')) : null);
$rendez_vous_vehicules->setRdvVhcTypeProprietaire($request->get('type_proprietaire_pl'));
$rendez_vous_vehicules->setRdvVhcRefParc($request->get('reference_parc_add'));
$rendez_vous_vehicules->setRdvVhcNumSerie($request->get('numero_serie_add'));
$rendez_vous_vehicules->setRdvVhcDescription($request->get('description_add'));
$rendez_vous_vehicules->setRdvVhcZoneSaisie1($request->get('zoneSaisie1'));
$rendez_vous_vehicules->setRdvVhcZoneSaisie2($request->get('zoneSaisie2'));
$rendez_vous_vehicules->setRdvVhcZoneSaisie3($request->get('zoneSaisie3'));
$rendez_vous_vehicules->setRdvVhcDateSaisie1($request->get('dateSaisie1') ? new datetime($request->get('dateSaisie1')) : null);
$rendez_vous_vehicules->setRdvVhcDateSaisie2($request->get('dateSaisie2') ? new datetime($request->get('dateSaisie2')) : null);
$rendez_vous_vehicules->setRdvVhcDateSaisie3($request->get('dateSaisie3') ? new datetime($request->get('dateSaisie3')) : null);
$manager->persist($rendez_vous_vehicules);
$manager->flush();
return new JsonResponse(['id' => $rendez_vous_vehicules->getId(), 'type' => $rendez_vous_vehicules->getTypeVehicule()->getId()]);
}
/**
* @Route("pro/get_vehicules_pro/{", name="get_vehicules_pro", methods={"POST"})
*/
public function get_vehicules_pro(Request $request, RendezVousVehiculeRepository $rdvVehiculeRepo): JsonResponse
{
$marque = '';
$modele = '';
$vehicules = $rdvVehiculeRepo->findByClientAndTypeCentre($request->get('clientId'), $request->get('centreType'));
$vehiculeArray = [];
foreach ($vehicules as $vehicule) {
if ($request->get('centreType') == 1 || $request->get('centreType') == 2) {
$marque = $vehicule->getMarque() ? $vehicule->getMarque()->getMarqueLibele() : '';
$modele = $vehicule->getModele() ? $vehicule->getModele()->getMdlLibele() : '';
} else if( $request->get('centreType') == 4) {
$marque = $vehicule->getMarqueCl() ? $vehicule->getMarqueCl()->getMarqueLibele() : '';
$modele = $vehicule->getModeleCl() ? $vehicule->getModeleCl()->getMdlLibele() : '';
}
$vehiculeArray[] = [
'id' => $vehicule->getId(),
'marque' => $marque,
'modele' => $modele,
'immatriculation' => $vehicule->getRdvVhcImmatriculation(),
'libelle_pl' => $vehicule->getTypeVehicule()->getTvLibelle(),
'id_type_vehicule' => $vehicule->getTypeVehicule()->getId(),
'energie' => $vehicule->getEnergie() ? $vehicule->getEnergie()->getDenomination() : '',
];
}
return $this->json($vehiculeArray);
}
/**
* @Route("/pro/get-vehicule/{vehiculeId}", name="get_vehicule_pro", methods={"GET"})
*/
public function getVehiculeAction($vehiculeId)
{
$vehicule = $this->em->getRepository(RendezVousVehicule::class)->find($vehiculeId);
$response = new JsonResponse([
'vehicule_id' => $vehicule->getId(),
'nom_proprietaire' => $vehicule->getRdvVhcNomClientProprietaire(),
'prenom_proprietaire' => $vehicule->getRdvVhcPrenomClientProprietaire(),
'marque_id' => $vehicule->getMarque() ? $vehicule->getMarque()->getId() : ($vehicule->getMarqueCl() ? $vehicule->getMarqueCl()->getId() : 1),
'modele_id' => $vehicule->getModele() ? $vehicule->getModele()->getId() : ($vehicule->getModeleCl() ? $vehicule->getModeleCl()->getId() : 1),
'energie_id' => $vehicule->getEnergie() ? $vehicule->getEnergie()->getId() : '',
'immatriculation' => $vehicule->getRdvVhcImmatriculation(),
'type_vehicule' => $vehicule->getTypeVehicule() ? $vehicule->getTypeVehicule()->getId() : null,
'nom' => $vehicule->getRdvVhcNomClientProprietaire(),
'prenom' => $vehicule->getRdvVhcPrenomClientProprietaire(),
'reference_parc' => $vehicule->getRdvVhcRefParc(),
'numero_de_serie' => $vehicule->getRdvVhcNumSerie(),
'description' => $vehicule->getRdvVhcDescription(),
'date_echeance' => $vehicule->getRdvVhcDateEcheance() ? $vehicule->getRdvVhcDateEcheance()->format('Y-m-d') : null,
'date_chrono' => $vehicule->getRdvVhcDateChronotachygraphe() ? $vehicule->getRdvVhcDateChronotachygraphe()->format('Y-m-d') : null,
'date_limiteur' => $vehicule->getRdvVhcDateLimiteurVitesse() ? $vehicule->getRdvVhcDateLimiteurVitesse()->format('Y-m-d') : null,
'type_proprietaire' => $vehicule->getRdvVhcTypeProprietaire(),
'zone_de_saisie_1' => $vehicule->getRdvVhcZoneSaisie1(),
'date_de_saisie_1' => $vehicule->getRdvVhcDateSaisie1() ? $vehicule->getRdvVhcDateSaisie1()->format('Y-m-d') : null,
'zone_de_saisie_2' => $vehicule->getRdvVhcZoneSaisie2(),
'date_de_saisie_2' => $vehicule->getRdvVhcDateSaisie2() ? $vehicule->getRdvVhcDateSaisie2()->format('Y-m-d') : null,
'zone_de_saisie_3' => $vehicule->getRdvVhcZoneSaisie3(),
'date_de_saisie_3' => $vehicule->getRdvVhcDateSaisie3() ? $vehicule->getRdvVhcDateSaisie3()->format('Y-m-d') : null,
]);
return $response;
}
/**
* @Route("/pro/remove_vehicule_pro", name="remove_vehicule_pro")
*/
public function remove_vehicule_pro(Request $request, ObjectManager $manager)
{
$vehicule = $this->em->getRepository(RendezVousVehicule::class)->find($request->get('id'));
if (!$vehicule) {
$this->addFlash('error', 'Votre véhicule n\'a pas été trouvé');
} else {
$this->em->remove($vehicule);
$this->em->flush();
$this->addFlash('success', 'Votre véhicule a bien été supprimé.');
}
return $this->redirectToRoute('mes_vehicules');
}
/**
* @Route("/pro/soft_remove_vehicule_pro", name="soft_remove_vehicule_pro")
*/
public function soft_remove_vehicule_pro(Request $request, ObjectManager $manager)
{
$vehicule = $this->em->getRepository(RendezVousVehicule::class)->find($request->get('id'));
if (!$vehicule) {
$this->addFlash('error', 'Votre véhicule n\'a pas été trouvé');
} else {
$vehicule->setIsActive(0);
$this->em->persist($vehicule);
$this->em->flush();
$this->addFlash('success', 'Votre véhicule a bien été supprimé.');
}
return $this->redirectToRoute('mes_vehicules');
}
#[Route('pro/add_rendezvous_pro', name: 'add_rendezvous_pro')]
public function add_rendezvous_pro(Request $Request, UrlGeneratorInterface $urlGenerator)
{
$rendezvous = new Rendezvous;
$centre_id = $Request->getSession()->get('centre_id');
$data_centre = $this->cache->get('Centre_' . $centre_id, function () use ($centre_id) {
$data_centre = $this->em->getRepository(Centre::class)->find($centre_id);
return $data_centre;
});
if ('POST' == $Request->getMethod()) {
$rendezvous->setClientCompte($this->getUser());
$duree = 0;
$tarif = 0;
if ($data_centre->getCentretype()->getId() == 1 || $data_centre->getCentretype()->getId() == 4) {
$id_prestation = $Request->get('prestation_vl');
$data_Prestation = $this->cache->get('Prestation' . $id_prestation, function () use ($id_prestation) {
$data_Prestation = $this->em->getRepository(CentrePrestation::class)->find($id_prestation);
return $data_Prestation;
});
$duree += $data_Prestation->getPstDuree();
$tarif += $data_Prestation->getPstTarif();
$rendezvous_infos = new RendezVousInfos();
$rendezvous_infos->setCentrePrestation($this->em->getrepository(CentrePrestation::class)->find($data_Prestation->getId()));
if ($Request->get('vehicule_vl') == 'vehiculeGenerique') {
$rendez_vous_vehicules = new RendezVousVehicule();
if ($data_centre->getCentretype()->getId() == 1) {
if ($Request->get('selectMarqueGen')) {
$marque = $this->em->getrepository(Marque::class)->find($Request->get('selectMarqueGen'));
if ($Request->get('selectModeleGen')) {
$modele = $this->em->getrepository(Modele::class)->find($Request->get('selectModeleGen'));
}
} else {
$marque = $this->em->getrepository(Marque::class)->find(1);
$modele = $this->em->getrepository(Modele::class)->find(1);
}
$rendez_vous_vehicules->setMarque($marque);
$rendez_vous_vehicules->setModele($modele);
} else if ($data_centre->getCentretype()->getId() == 4) {
if ($Request->get('selectMarqueGen')) {
$marqueCl = $this->em->getrepository(MarqueCl::class)->find($Request->get('selectMarqueGen'));
if ($Request->get('selectModeleGen')) {
$modeleCl = $this->em->getrepository(ModeleCl::class)->find($Request->get('selectModeleGen'));
}
} else {
$marqueCl = $this->em->getrepository(MarqueCl::class)->find(1);
$modeleCl = $this->em->getrepository(ModeleCl::class)->find(1);
}
$rendez_vous_vehicules->setMarqueCl($marqueCl);
$rendez_vous_vehicules->setModeleCl($modeleCl);
}
if ($Request->get('immatriculationGen')) {
$rendez_vous_vehicules->setRdvVhcImmatriculation($Request->get('immatriculationGen'));
}
if ($Request->get('selectEnergieGen')) {
$energie = $this->em->getrepository(Energie::class)->find($Request->get('selectEnergieGen'));
$rendez_vous_vehicules->setEnergie($energie);
}
$rendez_vous_vehicules->setRdvVhcTypeProprietaire('Autre');
$rendez_vous_vehicules->setClientCompte($this->getUser());
$this->em->persist($rendez_vous_vehicules);
} else {
$rendez_vous_vehicules = $this->em->getrepository(RendezVousVehicule::class)->find($Request->get('vehicule_vl'));
}
$rendezvous_infos->setVehicule($rendez_vous_vehicules);
$rendezvous_infos->setRendezvous($rendezvous);
$rendezvous_infos->setRdvInfDepot(false);
$rendezvous_infos->setRdvInfConvoyage(false);
$rendezvous_infos->setRdvInfPret(false);
$this->em->persist($rendezvous_infos);
} else {
foreach ($Request->get('prestation_pl') as $key => $prestation) {
$id_prestation = $prestation['prestation'];
$data_Prestation = $this->cache->get('Prestation' . $id_prestation, function () use ($id_prestation) {
$data_Prestation = $this->em->getRepository(CentrePrestation::class)->find($id_prestation);
return $data_Prestation;
});
$duree += $data_Prestation->getPstDuree();
$tarif += $data_Prestation->getPstTarif();
$rendezvous_infos = new RendezVousInfos();
preg_match_all('/(\d+) : ([^\s]*)(?=\s*\d+ :|\s*$)/', $Request->get('immatriculationGenPl'), $immats);
preg_match_all('/(\d+) : ([^\s]*)(?=\s*\d+ :|\s*$)/', $Request->get('selectEnergieGenPl'), $energies);
if ($Request->get('prestation_pl')[$key]['vehicule_pl'] == 'vehiculeGenerique') {
$rendez_vous_vehicules = new RendezVousVehicule();
$marque = $this->em->getrepository(Marque::class)->find(1);
$modele = $this->em->getrepository(Modele::class)->find(1);
$rendez_vous_vehicules->setMarque($marque);
$rendez_vous_vehicules->setModele($modele);
$rendez_vous_vehicules->setRdvVhcImmatriculation($immats[2][$key]);
if ($energies[2][$key]) {
$energie = $this->em->getrepository(Energie::class)->findOneBy(['denomination' => $energies[2][$key]]);
$rendez_vous_vehicules->setEnergie($energie);
}
if ($immats[2][$key]) {
$rendez_vous_vehicules->setRdvVhcImmatriculation($immats[2][$key]);
}
$rendez_vous_vehicules->setRdvVhcTypeProprietaire('Autre');
$rendez_vous_vehicules->setClientCompte($this->getUser());
$this->em->persist($rendez_vous_vehicules);
} else {
$rendez_vous_vehicules = $this->em->getrepository(RendezVousVehicule::class)->find($Request->get('prestation_pl')[$key]['vehicule_pl']);
}
$rendezvous_infos->setVehicule($rendez_vous_vehicules);
$rendezvous_infos->setCentrePrestation($this->em->getrepository(CentrePrestation::class)->find($data_Prestation->getId()));
$rendezvous_infos->setRendezvous($rendezvous);
$rendezvous_infos->setRdvInfDepot(false);
$rendezvous_infos->setRdvInfConvoyage(false);
$rendezvous_infos->setRdvInfPret(false);
$this->em->persist($rendezvous_infos);
}
}
$rendezvous->setCentre($this->em->getrepository(Centre::class)->find($data_centre->getId()));
$rendezvous->setCentreType($this->em->getrepository(CentreType::class)->find($data_centre->getCentreType()->getId()));
$rendezvous->setTokenRendezVous(md5(uniqid()));
$rendezvous->setRdvDateHeure(new Datetime($Request->get('date_rdv') . ' ' . $Request->get('heure_rdv')));
$rendezvous->setRdvDuree($duree);
$rendezvous->setRdvCommentaire($Request->get('commentaire'));
$rendezvous->setRdvDateCreation(new Datetime());
$rendezvous->setPartenaire($this->em->getrepository(Partenaire::class)->find(2));
if ($rendezvous->getRdvDateHeure() < new DateTime()) {
$this->addFlash('error', 'La date et l\'heure de rendez ne peut être pris dans le passé, veuillez choisir un autre créneau.');
return $this->redirectToRoute('prendre_rdv');
}
$tarif_initial = $tarif;
$tarif_final = $tarif_initial;
if ($Request->get('prestation_vl') or count($Request->get('prestation_pl')) == 1) {
if ($data_centre->getCentreType()->getId() == 1 || $data_centre->getCentreType()->getId() == 4) {
$reduction = $this->ApiController->getTarifPromotionsParHoraire($Request->get('prestation_vl'), $rendezvous->getRdvDateHeure(), $tarif_final);
} else {
$reduction = $this->ApiController->getTarifPromotionsParHoraire($Request->get('prestation_pl')[0]['prestation'], $rendezvous->getRdvDateHeure(), $tarif_final);
}
if ($reduction['tarif_final'] < $tarif_final) {
$rendezvous->setPromotion($this->em->getrepository(Promotion::class)->find($reduction['id_promotion']));
$tarif_final = $reduction['tarif_final'];
} else {
if ($Request->get('code_promo')) {
$CentreCouponPromotion = $this->em->getrepository(CentreCouponPromotion::class)->findByCode_Coupon_prestation($Request->get('marque'));
if ($CentreCouponPromotion) {
$tarif_final = $tarif_final - $CentreCouponPromotion[0]->getCpnPrmMontantRemise();
$CentreCouponPromotion[0]->setCpnPrmNbrUtilisation($CentreCouponPromotion[0]->getCpnPrmNbrUtilisation() + 1);
$this->em->persist($CentreCouponPromotion[0]);
$rendezvous->setCouponPromotion($CentreCouponPromotion[0]);
}
}
}
}
$rendezvous->setRdvTarif($tarif_final);
if ($data_centre->getCtrParametreCentre()->isPcRappelSms()) {
$rendezvous->setRdvDemandeRappelSms(true);
}
$debut = clone $rendezvous->getRdvDateHeure();
$fin = clone $debut;
$fin->modify('+ ' . $duree . ' minutes');
$Lignes = $this->em->getrepository(Ligne::class)->findByLigneDisponible($data_centre->getCentreGroupe()->getid(), $debut, $fin, $data_centre->getCentreType()->getId());
if (!$Lignes or count($Lignes) == 0) {
$this->addFlash('error', 'Ce créneau ' . $rendezvous->getRdvDateHeure()->format('d/m/Y H:i') . ' n\'est plus disponible, veuillez en choisir un autre');
return $this->redirectToRoute('prendre_rdv');
} else {
$Ligne = $this->em->getrepository(Ligne::class)->find($Lignes[0]['id']);
$rendezvous->setLigne($Ligne);
}
$this->em->persist($rendezvous);
$this->em->flush();
// if($data_centre->getCtrParametreCentre()->getPaiementEnLigne()){
// }else{
// }
//envoi rdv a autoplanning
$this->ApiController->sendAddRdvToAutoPlanning($rendezvous);
$this->ApiController->sendAddRdvToCtMalin($rendezvous);
// envoi email de confirmation
if ($Request->get('notifEmail') && $Request->get('vehicule_vl') == 'vehiculeGenerique') {
$this->ApiController->envoi_email_confirmation_client_custom($rendezvous , $Request->get('notifEmail'));
}
$email = $rendezvous->getClientLibre() ? $rendezvous->getClientLibre()->getClEmail() : $rendezvous->getClientCompte()->getCliEmail();
if ($email != "") {
$this->ApiController->envoi_email_confirmation_client($rendezvous);
}
$this->ApiController->envoi_email_confirmation_centre($rendezvous);
//envoi sms de confirmation
if ($rendezvous->getCentre()->getCtrParametreCentre()->isPcEnvoiSmsConfirm() === true) {
if ($Request->get('notifTelephone') && $Request->get('vehicule_vl') == 'vehiculeGenerique') {
$this->ApiController->EnvoiSmsRdvConfirm($rendezvous, $Request->get('notifTelephone'));
}
$this->ApiController->EnvoiSmsRdvConfirm($rendezvous, $Request->get('telephone'));
}
$url = $urlGenerator->generate('confirmation_rdv', [
'id' => $rendezvous->getTokenRendezVous(),
]);
// dd($rendezvous);
}
return new Response($url);
}
/**
* @Route("/pro/mes_vehicules", name="mes_vehicules")
*/
public function mes_vehicules(Request $request, ApiController $apiController, ObjectManager $manager)
{
$data_marques = $this->cache->get('marque', function () {
$data_marques = $this->em->getrepository(Marque::class)->findBy([], ['ordre' => 'asc', 'marque_libele' => 'asc']);
return $data_marques;
});
$data_marques_cl = $this->cache->get('marque_cl', function () {
$data_marques_cl = $this->em->getRepository(MarqueCl::class)->findBy([], ['ordre' => 'asc', 'marque_libele' => 'asc']);
return $data_marques_cl;
});
$data_energies = $this->cache->get('energie', function () {
$data_energies = $this->em->getrepository(Energie::class)->findAll();
return $data_energies;
});
$centres = $this->em->getRepository(Centre::class)->findCentresForClient($this->id, $this->getUser()->getId());
$TypeVehiculesVL = $this->em->getRepository(TypeVehicule::class)->findByCentreGroupeCentreType($request->getSession()->get('centre_groupe'), 1);
$TypeVehiculesPL = $this->em->getRepository(TypeVehicule::class)->findByCentreGroupeCentreType($request->getSession()->get('centre_groupe'), 2);
$TypeVehiculesCL = $this->em->getRepository(TypeVehicule::class)->findByCentreGroupeCentreType($request->getSession()->get('centre_groupe'), 4);
$energiesCentreVl = $this->em->getrepository(ParametreCentre::class)->findEnergiesByCentreGroupeAndCentreType($this->id, 1);
$energiesCentrePl = $this->em->getrepository(ParametreCentre::class)->findEnergiesByCentreGroupeAndCentreType($this->id, 2);
$energiesCentreCl = $this->em->getrepository(ParametreCentre::class)->findEnergiesByCentreGroupeAndCentreType($this->id, 4);
$cleanEnergiesVl = $apiController->getCleanEnergies($energiesCentreVl);
$cleanEnergiesPl = $apiController->getCleanEnergies($energiesCentrePl);
$cleanEnergiesCl = $apiController->getCleanEnergies($energiesCentreCl);
return $this->render('pro/vehicules.html.twig', [
'marques' => $data_marques,
'marquesCl' => $data_marques_cl,
'energiesVl' => $cleanEnergiesVl,
'energiesPl' => $cleanEnergiesPl,
'energiesCl' => $cleanEnergiesCl,
'energies' => $data_energies,
'typeVehiculesVL' => $TypeVehiculesVL,
'typeVehiculesPL' => $TypeVehiculesPL,
'typeVehiculesCL' => $TypeVehiculesCL,
'centres' => $centres,
]);
}
/**
* @Route("/pro/remove_rendezvous_pro", name="remove_rendezvous_pro")
*/
public function remove_rendezvous_pro(Request $request, ObjectManager $manager)
{
if (!$request->get('id')) {
return new Response('cannot_delete_rdv_not_specified');
}
$rendezvous = $this->em->getrepository(Rendezvous::class)->find($request->get('id'));
$rendezVousInfos = $this->em->getrepository(RendezVousInfos::class)->findBy(array('rendezvous' => $rendezvous));
$email = $rendezvous->getClientCompte()->getCliEmail();
if ($email != "" ) {
$this->ApiController->envoi_email_suppression_rdv_centre($rendezvous);
}
foreach ($rendezVousInfos as $rendezVousInfo) {
$manager->remove($rendezVousInfo);
}
// Supprimer les entités
$manager->remove($rendezvous);
$manager->flush();
return $this->redirectToRoute('mes_reservations');
}
/**
* @Route("/pro/remove_rendezvous_pro_calendar/{id}", name="remove_rendezvous_pro_cal")
*/
public function remove_rendezvous_pro_cal(int $id, Request $request, ObjectManager $manager)
{
try {
$rendezvous = $this->em->getrepository(Rendezvous::class)->find($id);
$rendezVousInfos = $this->em->getrepository(RendezVousInfos::class)->findBy(array('rendezvous' => $rendezvous));
$email = $rendezvous->getClientCompte()->getCliEmail();
if ($email != "" ) {
$this->ApiController->envoi_email_suppression_rdv_centre($rendezvous);
}
foreach ($rendezVousInfos as $rendezVousInfo) {
$manager->remove($rendezVousInfo);
}
// Supprimer les entités
$manager->remove($rendezvous);
$manager->flush();
} catch (Exception $exception) {
return new JsonResponse('ko');
}
return new JsonResponse('ok');
}
/**
* @Route("/pro/mes_reservations", name="mes_reservations")
*/
public function mes_reservations(Request $request)
{
$data_centre_groupes = $this->em->getRepository(CentreGroupe::class)->find($request->getSession()->get('centre_groupe'));
$horaireMin = null;
$horaireMax = null;
$joursFermesGlobaux = [];
$nombreDeCentres = 0;
$repositoryCentreHoraire = $this->em->getRepository(CentreHoraire::class);
$rdvVehiculeRepo = $this->em->getRepository(RendezVousVehicule::class);
$centrePrestationsRepository = $this->em->getRepository(CentrePrestation::class);
$centres = $this->em->getRepository(Centre::class)->findCentresForClient($this->id, $this->getUser()->getId());
$vehiculeVL = [];
$vehiculePL = [];
$vehiculeCL = [];
$centrePrestationsVL = [];
$centrePrestationsPL = [];
$centrePrestationsCL = [];
foreach ($data_centre_groupes->getCentres() as $centre) {
if ($centre->getCentreType()->getId() === 2) {
$vehiculePLCurrent = $rdvVehiculeRepo->findByClientAndTypeCentre($this->getUser()->getId(), $centre->getCentreType()->getId());
$vehiculePL = array_merge($vehiculePLCurrent, $vehiculePL);
$centrePrestationsCurrentPL = $centrePrestationsRepository->findByCentreGroupeAndCentreType($data_centre_groupes->getId(), $centre->getCentreType()->getId());
$centrePrestationsPL = array_merge($centrePrestationsCurrentPL, $centrePrestationsPL);
} else if ($centre->getCentreType()->getId() === 4) {
$vehiculeCLCurrent = $rdvVehiculeRepo->findByClientAndTypeCentre($this->getUser()->getId(), $centre->getCentreType()->getId());
$vehiculeCL = array_merge($vehiculeCLCurrent, $vehiculeCL);
$centrePrestationsCurrentCL = $centrePrestationsRepository->findByCentreGroupeAndCentreType($data_centre_groupes->getId(), $centre->getCentreType()->getId());
$centrePrestationsCL = array_merge($centrePrestationsCurrentCL, $centrePrestationsCL);
} else {
$vehiculeVLCurrent = $rdvVehiculeRepo->findByClientAndTypeCentre($this->getUser()->getId(), $centre->getCentreType()->getId());
$vehiculeVL = array_merge($vehiculeVLCurrent, $vehiculeVL);
$centrePrestationsCurrentVL = $centrePrestationsRepository->findByCentreGroupeAndCentreType($data_centre_groupes->getId(), $centre->getCentreType()->getId());
$centrePrestationsVL = array_merge($centrePrestationsCurrentVL, $centrePrestationsVL);
};
$nombreDeCentres++;
$data_centre_horaire = $this->em->getRepository(CentreHoraire::class)->getMinMaxHorairesByCentreId($centre->getId());
if ($horaireMin === null || $data_centre_horaire['horaireMin'] < $horaireMin) {
$horaireMin = $data_centre_horaire['horaireMin'];
}
if ($horaireMax === null || $data_centre_horaire['horaireMax'] > $horaireMax) {
$horaireMax = $data_centre_horaire['horaireMax'];
}
$data_jours_fermes = $repositoryCentreHoraire->getJoursFermes($centre->getId());
$joursFermesGlobaux = array_merge($joursFermesGlobaux, $data_jours_fermes);
}
$joursFermesDansTousLesCentres = array_keys(array_filter(array_count_values($joursFermesGlobaux), function ($count) use ($nombreDeCentres) {
return $count === $nombreDeCentres;
}));
$joursFermesDansTousLesCentres = array_map(function ($jour) {
return $jour === 7 ? 0 : $jour;
}, $joursFermesDansTousLesCentres);
return $this->render('pro/reservations.html.twig', [
'horaire_max' => $horaireMax,
'horaire_min' => $horaireMin,
'jours_fermes' => json_encode($joursFermesDansTousLesCentres),
'vehiculeVls' => $vehiculeVL,
'centrePrestationsVLs' => $centrePrestationsVL,
'vehiculePLs' => $vehiculePL,
'centrePrestationsPLs' => $centrePrestationsPL,
'vehiculeCLs' => $vehiculeCL,
'centrePrestationsCLs' => $centrePrestationsCL,
'centres' => $centres,
]);
}
/**
* @Route("/recup_facture_pv", name="recup_facture_pv")
*/
public function recup_facture_pv(Request $request, ObjectManager $manager)
{
set_time_limit(10000000);
$directory = 'D:/PV_FACT';
// Vérifier si le répertoire existe
if (is_dir($directory)) {
// Utiliser scandir pour lister les fichiers et dossiers
$files = scandir($directory);
// Paramètres de connexion FTP
$ftp_server = "remonte-VL.aquila-infotech.fr"; // Adresse du serveur FTP
$ftp_user_name = "ftp-remonte-VL"; // Nom d'utilisateur FTP
$ftp_user_pass = "KiiAL3zDT8x"; // Mot de passe FTP
// Connexion au serveur FTP
// $conn_id = ftp_connect($ftp_server) or die("Impossible de se connecter à $ftp_server");
// dd($conn_id);
// Connexion avec le nom d'utilisateur et le mot de passe
// $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// dd($files);
// Parcourir chaque fichier/dossier
foreach ($files as $file) {
// Ignorer les entrées "." et ".."
if ($file !== "." && $file !== "..") {
$files1 = scandir($directory.'/'.$file);
$vehicule = $this->em->getRepository(RendezVousVehicule::class)->findOneBy(['rdv_vhc_immatriculation'=>$file],['id'=>'DESC']);
if ($vehicule) {
if($vehicule->getClientCompte()){
$this->copyDirectory($directory.'/'.$file,'D:/PV_FACT_NEW/'.$vehicule->getClientCompte()->getId().'/'.$file);
// dd($vehicule,$file,$files1);
}
}
//$remote_file = "PV_FACT/".$file;
// Supprimer le fichier
// ftp_delete($conn_id, $remote_file);
$fileSource = $directory.'/'.$file;
$this->deleteDirectory($fileSource);
// unlink($fileSource);
}
}
} else {
echo "Le répertoire n'existe pas.";
}
dd($files);
$finder = new Finder();
try {
// $finder->in('ftp://ftp-remonte-VL:YKiiAL3zDT8x@remonte-VL.aquila-infotech.fr/PV_FACT/');
$finder->in('D:\PV_FACT');
} catch (\Exception $e) {
return array(
"vehicule" => $vehicule,
'files' => array(),
);
}
dd($finder->directories());
$finder->date('>= 2023-01-01')->date('<= 2023-01-31');
$finder->sortByName();
// dd($finder->directories());
// $finder->sort(function ($a, $b) {return strcmp($b->getFileName(), $a->getFileName());});
foreach ($finder->directories() as $key => $file) {
dd($file);
}
}
/**
* Fonction pour copier récursivement un répertoire vers un autre
*
* @param string $src Le chemin du répertoire source
* @param string $dst Le chemin du répertoire de destination
*/
function copyDirectory($src, $dst)
{
// Vérifier si le répertoire source existe
if (!is_dir($src)) {
echo "Le répertoire source n'existe pas.";
return;
}
// Si le répertoire de destination n'existe pas, le créer
if (!is_dir($dst)) {
mkdir($dst, 0755, true);
}
// Ouvrir le répertoire source
$dir = opendir($src);
// Parcourir chaque fichier/dossier dans le répertoire source
while (($file = readdir($dir)) !== false) {
// Ignorer les dossiers "." et ".."
if ($file !== '.' && $file !== '..') {
$srcFilePath = $src . '/' . $file;
$dstFilePath = $dst . '/' . $file;
// Si c'est un répertoire, effectuer une copie récursive
if (is_dir($srcFilePath)) {
copyDirectory($srcFilePath, $dstFilePath);
} else {
// Sinon, copier le fichier
copy($srcFilePath, $dstFilePath);
}
}
}
// Fermer le répertoire source
closedir($dir);
}
function deleteDirectory($dir)
{
// Vérifier si le répertoire existe
if (!is_dir($dir)) {
throw new \Exception("Le répertoire n'existe pas.");
}
// Ouvrir le répertoire
$files = array_diff(scandir($dir), ['.', '..']); // Écarter "." et ".."
// Parcourir chaque élément dans le répertoire
foreach ($files as $file) {
$filePath = $dir . DIRECTORY_SEPARATOR . $file;
// Si c'est un répertoire, appel récursif pour supprimer son contenu
if (is_dir($filePath)) {
$this->deleteDirectory($filePath); // Suppression récursive du sous-dossier
} else {
// Supprimer les fichiers
if (!unlink($filePath)) {
throw new \Exception("Impossible de supprimer le fichier : $filePath");
}
}
}
// Supprimer le répertoire lui-même une fois qu'il est vide
if (!rmdir($dir)) {
throw new \Exception("Impossible de supprimer le répertoire : $dir");
}
}
/**
* @Route("/pro/facture_pv", name="facture_pv")
*/
public function facture_pv(Request $request, ObjectManager $manager)
{
$vehicule = $this->em->getRepository(RendezVousVehicule::class)->find($request->get('id'));
if ($vehicule->getClientCompte() != $this->getUser()) {
return $this->redirectToRoute('mes_vehicules');
}
$finder = new Finder();
try {
$finder->in('ftp://ftp-remonte-' . strtolower($vehicule->getTypeVehicule()->getTvCentreType()->getCtDenomination()) . ':YKiiAL3zDT8x@remonte-' . strtolower($vehicule->getTypeVehicule()->getTvCentreType()->getCtDenomination()) . '.aquila-infotech.fr/PV_FACT/' . $this->getUser()->getId() . '/' . $vehicule->getRdvVhcImmatriculation())->name('PV*');
} catch (\Exception $e) {
return array(
"vehicule" => $vehicule,
'files' => array(),
);
}
$finder->sort(function ($a, $b) {return strcmp($b->getFileName(), $a->getFileName());});
$files = array();
// $centreGroupe = $vehicule->getTypeVehicule()->getCentreGroupe();
$i = 0;
foreach ($finder->files() as $key => $file) {
$num_pv = substr($file->getFileName(), 3);
$num_pv = substr($num_pv, 0, -4);
$pv_name = "PV_" . $num_pv . ".pdf";
if (file_exists($file->getPath() . $pv_name)) {
$files[$i]['pv'] = $pv_name;
$files[$i]['lien_pv'] = $file->getPath() . $pv_name;
}
$facture_name = "FA_" . $num_pv . ".pdf";
if (file_exists($file->getPath() . $facture_name)) {
$files[$i]['fa'] = $facture_name;
$files[$i]['lien_fa'] = $file->getPath() . $facture_name;
}
$bl_name = "BL_" . $num_pv . ".pdf";
if (file_exists($file->getPath() . $bl_name)) {
$files[$i]['bl'] = $bl_name;
$files[$i]['lien_bl'] = $file->getPath() . $bl_name;
}
$RendezVousInfos = $this->em->getRepository(RendezVousInfos::class)->getCentreGroupeByNumPV($request->get('centre'), $num_pv);
$files[$i]['vhc'] = [
'visite' => $RendezVousInfos?$RendezVousInfos[0]->getCentrePrestation()->getPstTypeVisite()->getTypVstLibeleLong():'',
'creneau' => $RendezVousInfos?$RendezVousInfos[0]->getRendezVous()->getRdvDateHeure()->format('d/m/Y H:i'):'',
'resultat' => $RendezVousInfos?$RendezVousInfos[0]->getRdvInfResultat():'',
];
$files[$i]['num_pv'] = $num_pv;
$files[$i]['immat'] = $vehicule->getRdvVhcImmatriculation();
$i++;
}
return new JsonResponse(array(
// "vehicule" => $vehicule,
'files' => $files,
));
}
/**
* @Route("/pro/generer_facture_pv/{immat}/{type}/{num_pv}", name="generer_facture_pv")
*/
public function generer_facture_pv(Request $request, ObjectManager $manager)
{
$vehicule = $this->em->getRepository(RendezVousVehicule::class)->findOneBy(
array(
'client_compte' => $this->getUser(),
'rdv_vhc_immatriculation' => $request->get('immat'),
));
if (!$vehicule) {
return $this->redirectToRoute('mes_vehicules');
}
$fileName = $request->get('type') . "_" . $request->get('num_pv') . ".pdf";
//dump('ftp://ftp-remonte-' . strtolower($vehicule->getTypeVehicule()->getTvCentreType()->getCtDenomination()) . ':YKiiAL3zDT8x@remonte-' . strtolower($vehicule->getTypeVehicule()->getTvCentreType()->getCtDenomination()) . '.aquila-infotech.fr/PV_FACT/' . $vehicule->getRdvVhcImmatriculation() . '/' . $fileName);
$data = file_get_contents('ftp://ftp-remonte-' . strtolower($vehicule->getTypeVehicule()->getTvCentreType()->getCtDenomination()) . ':YKiiAL3zDT8x@remonte-' . strtolower($vehicule->getTypeVehicule()->getTvCentreType()->getCtDenomination()) . '.aquila-infotech.fr/PV_FACT/' . $this->getUser()->getId() . '/' . $vehicule->getRdvVhcImmatriculation() . '/' . $fileName);
$response = new Response();
$response->setContent($data);
$response->headers->set('Content-Type', 'application/pdf');
$response->headers->set('Location', '');
$response->headers->set('Content-disposition', 'filename=' . $fileName);
return $response;
}
/**
* @return string
*/
private function decrypt_encrypt($action, $string)
{
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
/**
* @Route("pro/ligne_centre/json/{type}/{centre}/{date}/{dateE}", name="pro_ligne_centre_json")
*/
public function getLigneCentreJson(int $type, int $centre, string $date, string $dateE, Request $request)
{
$startRange = new DateTime($date);
$endRange = new DateTime($dateE);
$centre = $this->em->getRepository(Centre::class)->find($centre);
$holidaysCentre = $this->em->getrepository(ParametreCentre::class)->findHolidaysByCentreGroupeAndCentreType($centre->getCentreGroupe(), $centre->getCentreType());
$holidaysCentreFlat = array_reduce($holidaysCentre, function ($carry, $item) {
return array_merge($carry, $item['holidays']);
}, []);
$holyday = $this->ApiController->getFormateHolidays($holidaysCentreFlat, $startRange->format('Y'));
$blockedDay = [];
foreach ($holyday as $day) {
$dayDT = new DateTime($day);
if ($this->isDateBetweenDates($dayDT, $startRange, $endRange)) {
$blockedDay[] = intval($dayDT->format('N'));
}
}
if ($centre->getCtrParametreCentre()->isIsBlockRdv()) {
$hourEndBlockRdv = new \DateTime();
$hourEndBlockRdv->setTime($centre->getCtrParametreCentre()->getHourStartBlockRdv(), 00);
$hourEndBlockRdv->modify('+ ' . $centre->getCtrParametreCentre()->getNbHoursBlockRdv() . ' hours');
$hourStartBlockRdv = new \DateTime();
$hourStartBlockRdv->setTime($centre->getCtrParametreCentre()->getHourStartBlockRdv(), 00);
if ($hourEndBlockRdv > new DateTime('23:59:59')){
$hourEndBlockRdv = new DateTime('23:59:59');
}
}
$data_ligne_centre = $this->em->getrepository(Ligne::class)->findByCentreGroupeActifAndCentreType($request->getSession()->get('centre_groupe'), $type);
$events = [];
foreach ($data_ligne_centre as $ligne) {
$data_ligne_horaire = $this->em->getrepository(LigneHoraire::class)->findBy(['ligne' => $ligne->getId()]);
$businessHours = array();
$now = new \DateTime();
$currentDay = intval($now->format('N'));
foreach ($data_ligne_horaire as $ligne_horaire) {
if ($ligne_horaire->getLgnHorListeJours() == 7) {
$jours = 0;
} else {
$jours = $ligne_horaire->getLgnHorListeJours();
}
if (!$ligne_horaire->isLgnHorOuvert()){
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => '09:00',
'endTime' => '09:00',
];
continue;
}
if (in_array($jours, $blockedDay)) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => '09:00',
'endTime' => '09:00',
];
} else {
if ($endRange < $now) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => '09:00',
'endTime' => '09:00',
];
} else {
if ($currentDay === $jours && $centre->getCtrParametreCentre()->isIsBlockRdv() && $startRange <= $now) {
$startBloc = $hourStartBlockRdv->format('H:i');
$endBloc = $hourEndBlockRdv->format('H:i');
$start = $ligne_horaire->getLgnHorDebut()->format('H:i');
$end = $ligne_horaire->getLgnHorFin()->format('H:i');
if ($start > $startBloc) {
if ($start > $endBloc) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $start,
'endTime' => $end,
];
} else {
if ($end > $endBloc) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $endBloc,
'endTime' => $end,
];
} else {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => '09:00',
'endTime' => '09:00',
];
}
}
} elseif ($startBloc > $start && $endBloc < $end) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $start,
'endTime' => $startBloc,
];
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $endBloc,
'endTime' => $end,
];
} elseif ($startBloc > $start && $endBloc > $end) {
if ($startBloc < $end) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $start,
'endTime' => $startBloc,
];
} else {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $start,
'endTime' => $end,
];
}
}
} elseif ($jours < $currentDay && $startRange <= $now) {
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => '09:00',
'endTime' => '09:00',
];
} else {
$start = $ligne_horaire->getLgnHorDebut()->format('H:i');
$end = $ligne_horaire->getLgnHorFin()->format('H:i');
$businessHours[] = [
'daysOfWeek' => '[' . $jours . ']',
'startTime' => $start,
'endTime' => $end,
];
}
}
}
};
$events[] = [
'id' => $ligne->getId(),
'title' => $ligne->getlgnnom(),
//'type' => $ligne->getCentreType()->getId(),
'businessHours' => $businessHours,
'extendedProps' => [
'typeVl' => $ligne->isLgnVl(),
'typePl' => $ligne->isLgnPl(),
'typeCl' => $ligne->isLgnCl(),
],
];
}
return new JsonResponse($events);
}
/**
* @param DateTime $date
* @param DateTime $startDate
* @param DateTime $endDate
* @return bool
*/
private function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate)
{
return $date >= $startDate && $date <= $endDate;
}
/**
* @Route("pro/rendez-vous-by-client/json", name="rendez_vous_by_client_json")
*/
public function getRendezVousJson(Request $request)
{
$utilisateur = $this->getUser();
$start = $request->query->get('start');
$end = $request->query->get('end');
$upcomingRendezVousByCentreGroupeAndClient = $this->em->getrepository(Rendezvous::class)->findUpcomingRendezVousByCentreDate(
$this->id,
$start,
$end
);
$upcomingBlocageByCentreGroupeIdAndDates = $this->em->getRepository(LigneBlocage::class)->findUpcomingBlocageByCentreGroupeIdAndDates(
$this->id,
$start,
$end
);
$events = [];
/** @var Rendezvous $rendezVous */
foreach ($upcomingRendezVousByCentreGroupeAndClient as $rendezVous) {
$ligneId = $rendezVous->getLigne()->getId();
if ($rendezVous->getRendezVousInfos()[0] !== null && $rendezVous->getClientCompte() !== null) {
$nom = $rendezVous->getClientCompte()->getCliNomSociete();
$title = array();
$title[] = $nom . ' / ';
$backgroundColor = array();
$typePresta = array();
$vehiculeNom = array();
foreach ($rendezVous->getRendezVousInfos() as $rendezVousInfo) {
$rendesVousVehicule = $rendezVousInfo->getVehicule();
$marque = null;
$modele = null;
if ($rendezVous->getCentreType()->getId() === 1 || $rendezVous->getCentreType()->getId() === 2) {
if ($rendesVousVehicule->getMarque()) {
$marque = $rendesVousVehicule->getMarque()->getMarquelibele();
}
if ($rendesVousVehicule->getModele()) {
$modele = $rendesVousVehicule->getModele()->getMdllibele();
}
} else {
if ($rendesVousVehicule->getMarqueCl()) {
$marque = $rendesVousVehicule->getMarqueCl()->getMarquelibele();
}
if ($rendesVousVehicule->getModeleCl()) {
$modele = $rendesVousVehicule->getModeleCl()->getMdllibele();
}
}
$title[] =
$rendesVousVehicule->getRdvVhcImmatriculation()
.' - '.
$marque
.' - '.
$modele
.' / '.
$rendezVousInfo->getCentrePrestation()->getPsttypevisite()->getTypvstlibele();
$typePresta[] = $rendezVousInfo->getCentrePrestation()->getPstTypeVisite()->getTypVstLibele();
$vehiculeNom[] =
$rendesVousVehicule->getRdvVhcImmatriculation()
.' - '.
$marque
.' - '.
$modele;
}
$backgroundColor = '#00bf00';
} else {
$title = '';
$backgroundColor = '#3c763d';
$vehiculeNom = '';
}
if ($rendezVous->getClientCompte() !== null && $rendezVous->getClientCompte()->getId() === $utilisateur->getId()) {
$immat = [];
foreach ($rendezVous->getRendezVousInfos() as $info) {
$immat[] = $info->getVehicule()->getRdvVhcImmatriculation();
}
$events[] = [
'resourceId' => $ligneId,
'title' => $title,
'start' => $rendezVous->getRdvDateHeure()->format('Y-m-d H:i:s'),
'end' => (clone $rendezVous->getRdvDateHeure())->modify(sprintf('+%d minutes', $rendezVous->getRdvDuree()))->format('Y-m-d H:i:s'),
'backgroundColor' => $backgroundColor,
'extendedProps' => [
'duree' => $rendezVous->getRdvDuree(),
'vehiculeNom' => $vehiculeNom,
'centreType' => $typePresta,
'mine' => true,
'rdvId' => $rendezVous->getId(),
'commentaire' => $rendezVous->getRdvCommentaire(),
'ligneId' => $rendezVous->getLigne()->getId(),
'telephone' => $rendezVous->getClientCompte()->getCliTelephone(),
'immat' => $immat[0]
],
];
} else {
$events[] = [
'resourceId' => $ligneId,
'start' => $rendezVous->getRdvDateHeure()->format('Y-m-d H:i:s'),
'end' => (clone $rendezVous->getRdvDateHeure())->modify(sprintf('+%d minutes', $rendezVous->getRdvDuree()))->format('Y-m-d H:i:s'),
'backgroundColor' => '#cccccc',
'editable' => false,
'selectable' => false,
'extendedProps' => [
'mine' => false,
'ligneId' => $rendezVous->getLigne()->getId()
],
'textColor' => '#cccccc',
'borderColor' => '#cccccc',
];
}
}
/** @var LigneBlocage $blocage */
foreach ($upcomingBlocageByCentreGroupeIdAndDates as $blocage) {
$ligneId = $blocage->getLigne()->getId();
$events[] = [
'resourceId' => $ligneId,
'start' => $blocage->getBlcDebut()->format('Y-m-d H:i:s'),
'end' => $blocage->getBlcFin()->format('Y-m-d H:i:s'),
'backgroundColor' => '#cccccc',
'editable' => false,
'selectable' => false,
'draggable' => false,
'droppable' => false,
'extendedProps' => [
'mine' => false,
'ligneId' => $blocage->getLigne()->getId()
],
'textColor' => '#cccccc',
'borderColor' => '#cccccc',
];
}
return new JsonResponse($events);
}
/**
* @Route("pro/sendRdv", name="sendRdv")
*/
public function sendRdv(Request $request): JsonResponse
{
try {
$dateRdvStr = $request->get('dateRdv') . ' ' . $request->get('hourRdv');
$dateRdv = DateTime::createFromFormat('d/m/Y H:i:s', $dateRdvStr);
$rendezVous = new Rendezvous;
/** @var Ligne $Ligne */
$Ligne = $this->em->getrepository(Ligne::class)->find($request->get('ligneId'));
/** @var Centre $centre */
$dataCentre = $this->em->getrepository(Centre::class)->findOneBy(['centre_type' => $request->get('typeCentre'), 'centre_groupe' => $Ligne->getCentreGroupe()->getId()]);
$rendezVous->setClientCompte($this->getUser());
$dureeTotal = 0;
$tarifTotal = 0;
if (is_array($request->get('prestationId'))) {
$duree = 0;
$tarif = 0;
for ($i = 0; $i < count($request->get('prestationId')); $i++) {
$idPrestation = intval($request->get('prestationId')[$i]);
$dataPrestation = $this->em->getRepository(CentrePrestation::class)->find($idPrestation);
$duree = $duree + $dataPrestation->getPstDuree();
$tarif = $tarif + $dataPrestation->getPstTarif();
$rendezvousInfos = new RendezVousInfos();
$rendezvousInfos->setCentrePrestation($this->em->getrepository(CentrePrestation::class)->find($dataPrestation->getId()));
$rendezvousInfos->setVehicule($this->em->getrepository(RendezVousVehicule::class)->find($request->get('vehiculeId')[$i]));
$rendezvousInfos->setRendezvous($rendezVous);
$rendezvousInfos->setRdvInfDepot(false);
$rendezvousInfos->setRdvInfConvoyage(false);
$rendezvousInfos->setRdvInfPret(false);
$this->em->persist($rendezvousInfos);
}
$dureeTotal = $duree;
$tarifTotal = $tarif;
} else {
$idPrestation = intval($request->get('prestationId'));
$dataPrestation = $this->em->getRepository(CentrePrestation::class)->find($idPrestation);
$dureeTotal += $dataPrestation->getPstDuree();
$tarifTotal += $dataPrestation->getPstTarif();
$rendezvousInfos = new RendezVousInfos();
$rendezvousInfos->setCentrePrestation($this->em->getrepository(CentrePrestation::class)->find($dataPrestation->getId()));
$rendezvousInfos->setVehicule($this->em->getrepository(RendezVousVehicule::class)->find($request->get('vehiculeId')));
$rendezvousInfos->setRendezvous($rendezVous);
$rendezvousInfos->setRdvInfDepot(false);
$rendezvousInfos->setRdvInfConvoyage(false);
$rendezvousInfos->setRdvInfPret(false);
$this->em->persist($rendezvousInfos);
}
$rendezVous->setCentre($this->em->getrepository(Centre::class)->find($dataCentre->getId()));
$rendezVous->setCentreType($this->em->getrepository(CentreType::class)->find($dataCentre->getCentreType()->getId()));
$rendezVous->setRdvCommentaire($request->get('commentaire'));
$rendezVous->setTokenRendezVous(md5(uniqid()));
$rendezVous->setRdvDateHeure($dateRdv);
$rendezVous->setRdvDuree($dureeTotal);
$rendezVous->setRdvDateCreation(new Datetime());
$rendezVous->setPartenaire($this->em->getrepository(Partenaire::class)->find(2));
$tarif_initial = $tarifTotal;
$tarif_final = $tarif_initial;
$rendezVous->setRdvTarif($tarif_final);
if ($dataCentre->getCtrParametreCentre()->isPcRappelSms()) {
$rendezVous->setRdvDemandeRappelSms(true);
}
$debut = clone $rendezVous->getRdvDateHeure();
$fin = clone $debut;
$fin->modify('+ ' . $dureeTotal . ' minutes');
$rendezVousLigneExistants = $this->em->getRepository(Rendezvous::class)->rendezVousExistByLigne($Ligne->getId(), $debut, $fin);
$blocageLigneExistants = $this->em->getRepository(LigneBlocage::class)->blocageExistByLigne($Ligne->getId(), $debut, $fin, '');
// Si des rendez-vous ou blocage existent, rechercher un créneau disponible sur une autre ligne
if (count($rendezVousLigneExistants) > 0 || count($blocageLigneExistants) > 0) {
return new JsonResponse('take');
}
$rendezVous->setLigne($Ligne);
$this->em->persist($rendezVous);
$this->em->flush();
//envoi rdv a autoplanning
$this->ApiController->sendAddRdvToAutoPlanning($rendezVous);
$this->ApiController->sendAddRdvToCtMalin($rendezVous);
$title[] = $rendezVous->getClientCompte()->getCliNomSociete() . ' / ';
$centreType = [];
$vehiculeNom = [];
$rendesVousVehicule = $rendezvousInfos->getVehicule();
$marque = null;
$modele = null;
if ($rendezVous->getCentreType()->getId() === 1 || $rendezVous->getCentreType()->getId() === 2) {
if ($rendesVousVehicule->getMarque()) {
$marque = $rendesVousVehicule->getMarque()->getMarquelibele();
}
if ($rendesVousVehicule->getModele()) {
$modele = $rendesVousVehicule->getModele()->getMdllibele();
}
} else {
if ($rendesVousVehicule->getMarqueCl()) {
$marque = $rendesVousVehicule->getMarqueCl()->getMarquelibele();
}
if ($rendesVousVehicule->getModeleCl()) {
$modele = $rendesVousVehicule->getModeleCl()->getMdllibele();
}
}
$title[] =
$marque
.' - '.
$modele
.' / '.
$rendezvousInfos->getCentrePrestation()->getPsttypevisite()->getTypvstlibele();
$centreType = $rendezvousInfos->getCentrePrestation()->getPstTypeVisite()->getTypVstLibele();
$vehiculeNom[] =
$marque
.' - '.
$modele;
$event = [
'resourceId' => $Ligne->getId(),
'title' => $title,
'start' => $rendezVous->getRdvDateHeure()->format('Y-m-d H:i:s'),
'end' => (clone $rendezVous->getRdvDateHeure())->modify(sprintf('+%d minutes', $rendezVous->getRdvDuree()))->format('Y-m-d H:i:s'),
'backgroundColor' => '#00bf00',
'extendedProps' => [
'duree' => $rendezVous->getRdvDuree(),
'vehiculeNom' => $vehiculeNom,
'centreType' => $centreType,
'mine' => true,
'rdvId' => $rendezVous->getId()
],
];
$email = $rendezVous->getClientCompte()->getCliEmail();
if ($email != "" ) {
$this->ApiController->envoi_email_confirmation_client($rendezVous);
}
if ($rendezVous->getCentre()->getCtrParametreCentre()->isPcEnvoiSmsConfirm() === true) {
$this->ApiController->EnvoiSmsRdvConfirm($rendezVous, $rendezVous->getClientCompte()->getCliTelephone());
}
return new JsonResponse($event);
} catch (Exception $exception){
return new JsonResponse('ko');
}
}
/**
* @Route("pro/prestation_by_type_vehicule_pro/{id_type_vehicule}", name="prestation_by_type_vehicule_pro", methods={"GET"})
*/
public function prestationByTypeVehiculePro(int $id_type_vehicule)
{
$prestationsArray = [];
$data_prestations = $this->em->getrepository(CentrePrestation::class)->findByCentreGroupeAndTypeVehicule($this->id, $id_type_vehicule);
foreach ($data_prestations as $prestation) {
$prestationsArray[] = array(
'id' => $prestation->getId(),
'pst_tarif' => $prestation->getPstTarif(),
'pst_duree' => $prestation->getPstDuree(),
'type_visite' => $prestation->getPstTypeVisite()->getId(),
'type_visite_libele' => $prestation->getPstTypeVisite()->getTypVstLibele(),
'type_visite_libele_long' => $prestation->getPstTypeVisite()->getTypVstLibeleLong(),
// 'centre_groupe' => $prestation->getCentreGroupe()->getId()
);
}
// Retourner les données en format JSON
return new JsonResponse($prestationsArray);
}
/**
* @Route("pro/profil", name="profil", methods={"GET", "POST"})
*/
public function profil(Request $request, Security $security, ObjectManager $manager): Response
{
$user = $security->getUser();
$adresseFact = '';
$adresse = $this->em->getRepository(Adresse::class)->find($user->getAdresse()->getId());
$adresseFact = $this->em->getRepository(Adresse::class)->find($user->getAdresseFacturation()->getId());
$formClientCompte = $this->createForm(ClientCompteType::class, $user);
$formAdresse = $this->createForm(AdresseType::class, $adresse);
$formAdresseFact = $this->createForm(AdresseType::class, $adresseFact);
$formClientCompte->handleRequest($request);
$formAdresse->handleRequest($request);
$formAdresseFact->handleRequest($request);
if ($request->isMethod('POST')) {
$isValidClientCompte = $formClientCompte->isSubmitted() && $formClientCompte->isValid();
$isValidAdresse = $formAdresse->isSubmitted() && $formAdresse->isValid();
$isValidAdressefact = $formAdresseFact->isSubmitted() && $formAdresseFact->isValid();
if ($isValidClientCompte && $isValidAdresse && $isValidAdressefact) {
$manager->flush();
$this->addFlash('success', 'Profil mis à jour avec succès.');
return $this->redirectToRoute('profil');
}
}
return $this->render('pro/profil_pro.html.twig', [
'user' => $user,
'formClientCompte' => $formClientCompte->createView(),
'formAdresse' => $formAdresse->createView(),
'formAdresseFact' => $formAdresseFact->createView()
]);
}
/**
* @Route("pro/rendez_vous_drag_and_drop_pro", name="rendez_vous_drag_and_drop_pro")
*/
public function DragAndDropRendezVous(Request $request, ObjectManager $manager)
{
$rendezvousId = $request->get('rendezvous_id');
if (!$rendezvousId) {
return new Response('cannot_delete_rdv_not_specified');
}
$rendezvous = $this->em->getrepository(Rendezvous::class)->find($rendezvousId);
$ligne = $this->em->getrepository(Ligne::class)->find($request->get('ligneId'));
$typeRdv = $rendezvous->getCentreType()->getId();
$typeArray = [];
$isVl = $ligne->isLgnVl();
$isCl = $ligne->isLgnCl();
$isPl = $ligne->isLgnPl();
if ($isVl) {
$typeArray[] = 1;
}
if ($isCl) {
$typeArray[] = 4;
}
if ($isPl) {
$typeArray[] = 2;
}
if (in_array($typeRdv,$typeArray)) {
$email = $rendezvous->getClientCompte()->getCliEmail();
if ($email != "" ) {
$this->ApiController->envoi_email_modification_rdv_centre($rendezvous);
}
$rendezvous->setRdvDateHeure(new Datetime($request->get('start')));
$rendezvous->setLigne($ligne);
$rendezvous->setRdvDateModification(new Datetime());
$manager->persist($rendezvous);
$manager->flush();
return new Response('ok');
}
return new Response('ko');
}
}