<?php
namespace App\Controller;
use DateTime;
use DateInterval;
use DateTimeZone;
use Dompdf\Dompdf;
use App\Entity\Rdv;
use Dompdf\Options;
use App\Entity\Lieu;
use App\Entity\Audio;
use App\Entity\Motif;
use App\Entity\Token;
use Twig\Environment;
use App\Entity\Centre;
use App\Entity\Client;
use \IntlDateFormatter;
use App\Entity\EtatRdv;
use App\Entity\LeadRdv;
use App\Entity\Proches;
use App\Entity\LieuTier;
use App\Entity\RdvEvent;
use App\Entity\AudioMotif;
use App\Entity\CentreTier;
use App\Entity\ClientTemp;
use App\Entity\LeadStatus;
use App\Entity\Remplacant;
use App\Entity\TestClient;
use App\Entity\AudioCentre;
use App\Service\SmsHandler;
use App\Entity\AccessCentre;
use App\Entity\ClientStatus;
use App\Entity\ClientBlocked;
use App\Entity\CentreMutuelle;
use App\Entity\LieuPrestation;
use App\Entity\AudioSpecialite;
use App\Service\PublicFunction;
use App\Entity\CentrePrestation;
use App\Entity\RegionDepartment;
use App\Repository\RdvRepository;
use Symfony\Component\Mime\Email;
use App\Entity\Device\ClientDevice;
use App\Entity\Notification\RdvSms;
use App\Service\Lead\TwilioService;
use App\Service\Lead\WhatsappService;
use App\Entity\SynchronisationSetting;
use App\Service\Lead\ElevenLabsService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Cache\ItemInterface;
use App\Service\Cosium\ClientCosiumService;
use App\Service\Notification\RdvSmsService;
use Symfony\Contracts\Cache\CacheInterface;
use App\Entity\Synchronisation\CosiumCenter;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\Common\Collections\ArrayCollection;
use App\EasyAdmin\Controller\DashboardController;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\EasyAdmin\Controller\LeadRdvCrudController;
use App\Service\AdsCompany\RepresentativeCdaService;
use App\Entity\Synchronisation\SynchronisationCosium;
use App\Service\GoogleCalendar\GoogleCalendarService;
use App\Service\Notification\EmailNotificationService;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class RdvController extends AbstractController
{
private $emailNotificationService;
private $clientCosiumService;
private $rdvRepository;
private $entityManager;
private $cache;
private $twig;
private AdminUrlGenerator $adminUrlGenerator;
private WhatsappService $whatsapp;
public function __construct(CacheInterface $cache, EntityManagerInterface $entityManager, EmailNotificationService $emailNotificationService, ClientCosiumService $clientCosiumService, RdvRepository $rdvRepository, Environment $twig, AdminUrlGenerator $adminUrlGenerator, WhatsappService $whatsapp)
{
$this->entityManager = $entityManager;
$this->emailNotificationService = $emailNotificationService;
$this->clientCosiumService = $clientCosiumService;
$this->rdvRepository = $rdvRepository;
$this->cache = $cache;
$this->twig = $twig;
$this->adminUrlGenerator = $adminUrlGenerator;
$this->whatsapp = $whatsapp;
}
/**
* @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
*/
public function deleteRdvByID(Request $request, Rdv $rdv, GoogleCalendarService $googleCalendar)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
$entityManager->remove($rdv);
$entityManager->flush();
return new Response(json_encode(([
'message' => "Rdv has been successfully deleted",
"status" => 200,
])));
}
/**
* @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
*/
public function getRdvByID(Request $request, Rdv $rdv, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
/** @var AudioCentre */
$liaison = $this->getDoctrine()->getRepository(AudioCentre::class)
->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
// Motif filter
/** @var AudioMotif[] */
$motifs = $this->getDoctrine()->getRepository(AudioMotif::class)
->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
$resultMotif = new ArrayCollection();
foreach ($motifs as $motif) {
$resultMotif->add([
"id" => $motif->getIdMotif()->getId(),
"titre" => $motif->getIdMotif()->getTitre(),
"consigne" => $motif->getConsigne(),
"duration" => $motif->getDuration(),
]);
}
// Specialities
/** @var AudioSpecialite[] */
$specialities = $this->getDoctrine()->getRepository(AudioSpecialite::class)
->findBy(array('id_audio' => $rdv->getIdAudio()));
$resultSpeciality = new ArrayCollection();
foreach ($specialities as $speciality) {
$resultSpeciality->add([
"id" => $speciality->getIdSpecialite()->getId(),
"titre" => $speciality->getIdSpecialite()->getLibelle(),
]);
}
if ($rdv->getIdCentre())
/** @var AccessCentre*/
{
$accessCentre = $this->getDoctrine()->getRepository(AccessCentre::class)
->findOneBy(array('id_centre' => $rdv->getIdCentre()));
} else
/** @var AccessCentre*/
{
$accessCentre = $this->getDoctrine()->getRepository(AccessCentre::class)
->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
}
if ($rdv->getIdCentre())
/** @var CentrePrestation[]*/
{
$prestations = $this->getDoctrine()->getRepository(CentrePrestation::class)
->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
} else
/** @var LieuPrestation[]*/
{
$prestations = $this->getDoctrine()->getRepository(LieuPrestation::class)
->findBy(array('id_lieu' => $rdv->getIdLieu()));
}
$resultPrestation = new ArrayCollection();
foreach ($prestations as $prestation) {
$resultPrestation->add([
"id" => $prestation->getIdPrestation()->getId(),
"titre" => $prestation->getIdPrestation()->getLibelle(),
]);
}
$mutuelles = $this->getDoctrine()->getRepository(CentreMutuelle::class)
->findBy(array('id_centre' => $rdv->getIdCentre()));
$resultMutuelle = new ArrayCollection();
foreach ($mutuelles as $mutuelle) {
$resultMutuelle->add([
"id" => $mutuelle->getIdMutuelle()->getId(),
"titre" => $mutuelle->getIdMutuelle()->getLibelle(),
]);
}
if ($rdv->getIdCentre())
/** @var CentreTier[]*/
{
$tiers = $this->getDoctrine()->getRepository(CentreTier::class)
->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
} else
/** @var LieuTier[]*/
{
$tiers = $this->getDoctrine()->getRepository(LieuTier::class)
->findBy(array('id_lieu' => $rdv->getIdLieu()));
}
$resultTier = new ArrayCollection();
foreach ($tiers as $tier) {
$resultTier->add([
"id" => $tier->getIdTier()->getId(),
"titre" => $tier->getIdTier()->getLibelle(),
]);
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$audioRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsAudio($rdv->getIdAudio()->getId());
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
// Comment
/** @var Rdv[] */
$rdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findBy(array('id_audio' => $rdv->getIdAudio()));
$comments = [];
foreach ($rdvs as $rdv)
if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
array_push($comments, [
"id" => $rdv->getIdClient()->getId(),
"name" => $rdv->getIdClient()->getName() . " " . $rdv->getIdClient()->getLastname()[0] . ".",
"comment" => $rdv->getComment(),
"isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
"review" => $rdv->getReview(),
]);
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_titre" => $rdv->getIdMotif()->getTitre(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"client_id" => $rdv->getIdClient()->getId(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
"note" => $rdv->getNote(),
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"comments" => $comments,
"audio" => [
"id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
"civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
"name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
"lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
"imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
"mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
"phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
"adeli" => $rdv->getIdAudio()->getAdeli(),
"pin" => $rdv->getIdAudio()->getPin(),
"description" => $rdv->getIdAudio()->getDescription(),
"averageRating" => $publicFunction->calculateRating($audioRdvs),
"nbrReview" => count($audioRdvs),
"motifs" => $resultMotif->toArray(),
"specialities" => $resultSpeciality->toArray(),
],
"centre" => [
"id" => $rdvCentre->getId(),
"audio_id" => $rdvCentre->getIdGerant()->getId(),
"name" => $rdvCentre->getName(),
"imgUrl" => $rdvCentre->getImgUrl(),
"isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"finess" => $rdvCentre->getFiness(),
"siret" => $rdvCentre->getSiret(),
"website" => $rdvCentre->getWebsite(),
"phone" => $rdvCentre->getPhone(),
"isHandicap" => $rdvCentre->getIsHandicap(),
"longitude" => $rdvCentre->getLongitude(),
"latitude" => $rdvCentre->getLatitude(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"tram" => $accessCentre->getTram(),
"rer" => $accessCentre->getRer(),
"metro" => $accessCentre->getMetro(),
"bus" => $accessCentre->getBus(),
"parking" => $accessCentre->getParkingPublic(),
"description" => $rdv->getIdCentre()->getDescription(),
"parkingPrivate" => $accessCentre->getParkingPrivate(),
"other" => $accessCentre->getOther(),
"prestations" => $resultPrestation->toArray(),
"mutuelles" => $resultMutuelle->toArray(),
"tiers" => $resultTier->toArray(),
"isLieu" => false,
"schedule" => $rdv->getIdAudio()->getIsIndie() == false ? $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
],
"status" => 200,
])));
}
/**
* @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
*/
public function getRdvsByClientID(Request $request, Client $client, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($token->getIdClient()) {
if ($client != $token->getIdClient()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else if ($token->getIdAudio()) {
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Rdv::class)
->findOneBy(['id_client' => $client, 'id_audio' => $token->getIdAudio()]);
if ($client != $token->getIdClient()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
if ($request->query->get('audio')) {
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
$rdvResult = new ArrayCollection();
} else {
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_client' => $client->getId()]);
$rdvResult = new ArrayCollection();
}
if ($request->query->get('old')) {
$oldRdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
if ($rdv->getIdEtat()->getId() != 1) {
continue;
}
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
if (!$audioMotif) {
continue;
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " . $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastname(),
"client_id" => $rdv->getIdClient()->getId(),
"client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " . $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " . $rdv->getIdClient()->getLastname(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdvCentre->getName(),
"phone" => $rdvCentre->getPhone(),
"imgUrl" => $rdvCentre->getImgUrl(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"etat_id" => $rdvCentre->getId(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
];
if ($rdv->getDate() >= new DateTime()) {
$rdvResult->add($rdvItem);
} else if ($request->query->get('old')) {
$oldRdvResult->add($rdvItem);
}
}
if ($request->query->get('old')) {
if ($request->query->get('onlyOld')) {
if (count($rdvResult) > 0 || count($oldRdvResult) > 0) {
return new Response(json_encode(([
"oldRdv" => $oldRdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
"test" => "count:" . count($rdvs),
'path' => 'src/Controller/RdvController.php',
"rdv" => array(),
"oldRdv" => array(),
"status" => 404,
])));
}
} else {
if (count($rdvResult) > 0 || count($oldRdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"oldRdv" => $oldRdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
"test" => "count:" . count($rdvs),
'path' => 'src/Controller/RdvController.php',
"rdv" => array(),
"oldRdv" => array(),
"status" => 404,
])));
}
}
} else {
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"content" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
"test" => "count2:" . count($rdvs),
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
}
/**
* @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
*/
public function getRdvsByClientIDForCentre(Request $request, Client $client, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $request->query->get('audio')]);
$audioCentre = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_audio' => $audio]);
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($token->getIdClient()) {
if ($client != $token->getIdClient()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else if ($token->getIdAudio()) {
/** @var Token */
if ($token->getIdAudio() != $audio) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
if ($request->query->get('centre')) {
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
$rdvResult = new ArrayCollection();
} else {
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_client' => $client->getId()]);
$rdvResult = new ArrayCollection();
}
if ($request->query->get('old')) {
$oldRdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
/*if ($rdv->getIdEtat()->getId() != 1) {
continue;
}*/
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
if (!$audioMotif) {
continue;
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " . $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastname(),
"client_id" => $rdv->getIdClient()->getId(),
"client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " . $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " . $rdv->getIdClient()->getLastname(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdvCentre->getName(),
"phone" => $rdvCentre->getPhone(),
"imgUrl" => $rdvCentre->getImgUrl(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"etat_id" => $rdvCentre->getId(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
"status" => $rdv->getIdEtat()->getLibelle()
];
// dd(new DateTime());
if ($rdv->getDate() >= new DateTime()) {
$rdvResult->add($rdvItem);
} else if ($request->query->get('old')) {
$oldRdvResult->add($rdvItem);
}
}
if ($request->query->get('old')) {
if (count($rdvResult) > 0 || count($oldRdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"oldRdv" => $oldRdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
"test" => "count:" . count($rdvs),
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])), 404);
}
} else {
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"content" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
"test" => "count2:" . count($rdvs),
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
}
/////// CRON
/**
* @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
*/
public function confirmRdvSms(PublicFunction $publicFunction): Response
{
$date = new DateTime();
$minutes_to_add = 30;
$date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$date->setTimezone(new DateTimeZone('Europe/Paris'));
$currentDate = $date->format('Y-m-d H:i:00');
$toSend = $this->getDoctrine()->getRepository(Rdv::class)
->findRdvsIn10Mins($currentDate);
$entityManager = $this->getDoctrine()->getManager();
$rdvResult = new ArrayCollection();
foreach ($toSend as $rdv) {
$date = $rdv->getDate();
// $smsDate = $date->format('d-m-Y H:i');
//$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
//$sms = "Vous avez votre RDV du " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", taper 1 si vous confirmer votre arrivé au centre auditif ou 2 si vous avez un empêchement.";
// // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
//$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
//$another_response = explode(" | ", $response);
// $idSms = trim($another_response[2]);
// $rdv->setIdSms($idSms);
//$entityManager->persist($rdv);
// $entityManager->flush();
}
return new Response(json_encode([
// "test" => $idSms,
"currentDate" => $currentDate
]));
}
/////// CRON
/**
* @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
*/
public function validateRdvSms(Request $request, PublicFunction $publicFunction): Response
{
$smsId = $request->query->get('token');
$message = $request->query->get('message');
$rdv = $this->getDoctrine()
->getRepository(Rdv::class)
->findOneBy(['id_sms' => $smsId]);
$date = $rdv->getDate();
$currentDate = date('Y-m-d H:i:s');
$smsDate = $date->format('d-m-Y H:i');
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$entityManager = $this->getDoctrine()->getManager();
if ($date > $currentDate) {
if ($message == "1") {
$sms = "Parfait, votre audioprothésiste est averti de votre venue. Présentez-vous à l'accueil du centre, il vous recevra dans quelques minutes.\nNe pas répondre";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
} else if ($message == "2") {
$sms = "Votre absence est bien enregistrée, votre audioprothésiste est averti. Contactez votre centre pour reprogrammer un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => 2]);
$rdv->setIdEtat($etat);
$entityManager->persist($rdv);
$entityManager->flush();
} else {
return new Response(json_encode([
"message" => "La réponse spécifiée est incorrecte",
"status" => 401,
]), 401);
}
} else {
return new Response(json_encode([
"message" => "Le rendez-vous est déjà passé, vous ne pouvez plus répondre à ce sms !",
"status" => 401,
]), 401);
}
return new Response(json_encode([
"smsId" => $smsId,
"message" => $currentDate
]));
}
/**
* @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
*/
public function getOldRdvsByClientId(Request $request, Client $client, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($token->getIdClient()) {
if ($client != $token->getIdClient()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else if ($token->getIdAudio()) {
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Rdv::class)
->findOneBy(['id_client' => $client, 'id_audio' => $token->getIdAudio()]);
if ($client != $token->getIdClient()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
if ($request->query->get('audio')) {
/** @var ActivityRepository */
$activityRepo = $this->getDoctrine();
if ($request->query->get('limit')) {
/** @var Rdv[] */
$rdvs = $activityRepo
->getRepository(Rdv::class)
->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
$rdvResult = new ArrayCollection();
} else {
/** @var Rdv[] */
$rdvs = $activityRepo
->getRepository(Rdv::class)
->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
$rdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
/*if ($rdv->getIdEtat()->getId() != 1) {
continue;
}*/
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
if (!$audioMotif) {
continue;
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id" => $rdv->getIdClient()->getId(),
"client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " . $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " . $rdv->getIdClient()->getLastname(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdvCentre->getName(),
"phone" => $rdvCentre->getPhone(),
"imgUrl" => $rdvCentre->getImgUrl(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"etat_id" => $rdvCentre->getId(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
];
$rdvResult->add($rdvItem);
}
}
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous a venir!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
/**
* @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
*/
public function getOldRdvsByClientIdForCentre(Request $request, Client $client, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $request->query->get('audio')]);
$audioCentre = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_audio' => $audio]);
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($token->getIdClient()) {
if ($client != $token->getIdClient()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else if ($token->getIdAudio()) {
/** @var Token */
if ($token->getIdAudio() != $audio) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
} else {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
"status" => 404,
]), 404);
}
if ($request->query->get('audio')) {
/** @var ActivityRepository */
$activityRepo = $this->getDoctrine();
if ($request->query->get('limit')) {
/** @var Rdv[] */
$rdvs = $activityRepo
->getRepository(Rdv::class)
->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
$rdvResult = new ArrayCollection();
} else {
/** @var Rdv[] */
$rdvs = $activityRepo
->getRepository(Rdv::class)
->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
$rdvResult = new ArrayCollection();
}
//dd($rdvs);
foreach ($rdvs as $rdv) {
// we comment this becoz it was just the validate , we implment other choice select
/* if ($rdv->getIdEtat()->getId() != 5) {
continue;
}*/
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
if (!$audioMotif) {
continue;
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id" => $rdv->getIdClient()->getId(),
"client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " . $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " . $rdv->getIdClient()->getLastname(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdvCentre->getName(),
"phone" => $rdvCentre->getPhone(),
"imgUrl" => $rdvCentre->getImgUrl(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"etat_id" => $rdvCentre->getId(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
"status" => $rdv->getIdEtat()->getLibelle()
];
$rdvResult->add($rdvItem);
}
}
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
private function getOpeningHours($centerId)
{
$center = $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
$audioCentre = $this->getDoctrine()->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
$schedule = $audioCentre->getHoraire();
$availableHours = [];
if (isset($schedule['fixed'])) {
foreach ($schedule['fixed'] as $day => $hours) {
$dayInFrench = strtolower($day);
$slots = [];
foreach ($hours as $period) {
$start = strtotime($period['open']);
$end = strtotime($period['close']);
while ($start < $end) {
$slots[] = date('H:i', $start);
$start = strtotime('+30 minutes', $start);
}
}
$availableHours[$dayInFrench] = $slots;
}
}
if (isset($schedule['exceptionalOpened'])) {
foreach ($schedule['exceptionalOpened'] as $exception) {
$dayOfWeek = strtolower(date('l', strtotime($exception['open'])));
$start = strtotime($exception['open']);
$end = strtotime($exception['close']);
$exceptionSlots = [];
while ($start < $end) {
$exceptionSlots[] = date('H:i', $start);
$start = strtotime('+30 minutes', $start);
}
$availableHours[$dayOfWeek] = array_merge(
$availableHours[$dayOfWeek] ?? [],
$exceptionSlots
);
}
}
if (isset($schedule['exceptionalClosed'])) {
foreach ($schedule['exceptionalClosed'] as $exception) {
$dayOfWeek = strtolower(date('l', strtotime($exception['open'])));
unset($availableHours[$dayOfWeek]);
}
}
return $availableHours;
}
private function getBookedSlotsForDate($centerId, $date)
{
$bookedSlots = $this->getDoctrine()
->getRepository(Rdv::class)
->getBookedSlotsForDate($centerId, $date);
return $bookedSlots;
}
private function getAvailableSlotsForDate($openingHours, $centerId, $date)
{
$dayOfWeek = date('l', strtotime($date));
$dayInFrench = $this->convertDayToFrench($dayOfWeek);
if (!$dayInFrench) {
throw new \Exception("Invalid day of the week: $dayOfWeek");
}
$slots = $openingHours[$dayInFrench] ?? [];
$bookedSlots = $this->getBookedSlotsForDate($centerId, $date);
$bookedTimes = [];
foreach ($bookedSlots as $bookedSlot) {
$startTime = $bookedSlot['date'];
$duration = $bookedSlot['duration'];
$endTime = (clone $startTime)->modify("+$duration minutes");
$bookedTimes[] = ['start' => $startTime, 'end' => $endTime];
}
$availableSlots = [];
foreach ($slots as $slot) {
$slotTime = \DateTime::createFromFormat('H:i', $slot);
$slotTime->setDate(date('Y', strtotime($date)), date('m', strtotime($date)), date('d', strtotime($date)));
if (!$slotTime) {
continue;
}
$isAvailable = true;
foreach ($bookedTimes as $bookedTime) {
if ($slotTime >= $bookedTime['start'] && $slotTime < $bookedTime['end']) {
$isAvailable = false;
break;
}
}
if ($isAvailable) {
$availableSlots[] = $slot;
}
}
return $availableSlots;
}
private function convertDayToFrench($englishDay)
{
$daysMap = [
'monday' => 'lundi',
'tuesday' => 'mardi',
'wednesday' => 'mercredi',
'thursday' => 'jeudi',
'friday' => 'vendredi',
'saturday' => 'samedi',
'sunday' => 'dimanche'
];
return $daysMap[strtolower($englishDay)] ?? null;
}
/**
* @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
*/
public function getAudioRdvs(Request $request, Audio $audio)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($audio != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
$centre = (int)$request->query->get('centre');
if (($request->query->get('debut')) && ($request->query->get('fin'))) {
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBetweenDate(
$audio->getId(),
new DateTime($request->query->get('debut')),
new DateTime($request->query->get('fin')),
$centre // Le centre est maintenant un entier
);
} else {
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_audio' => $audio->getId()]);
}
$rdvResult = new ArrayCollection();
$centerId = $request->query->get('centre');
// $openingHours = $this->getOpeningHours($centerId);
$centerId = $request->query->get('centre');
$dateCache = new \DateTime();
$openingHours = $this->cache->get('centre_' . $centerId . '_horaires_' . $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId, $dateCache) {
$item->expiresAfter(7200);
return $this->getOpeningHours($centerId);
});
//dd($openingHours);
foreach ($rdvs as $rdv) {
if ($rdv->getIdEtat()->getId() != null) {
if ($rdv->getIsAbsence() != 1) {
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
if (!isset($audioMotif)) {
continue;
}
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
if ($rdv->getIdClientTemp()) {
$confiance = "";
} else {
$confiance = $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
}
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
$dateFin = $dateFin->add(new DateInterval("PT" . $duration . "M"));
if ($rdv->getIdClientTemp()) {
$findNextRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client_temp" => $rdv->getIdClientTemp(),
"id_motif" => ['106', '107', '108', '109']
]);
} else {
$findNextRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client_temp" => $rdv->getIdClient(),
"id_motif" => ['106', '107', '108', '109']
]);
}
$finalRdv = null;
/*if ($rdv->getRdvParent()) {
$finalRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->find($rdv->getRdvParent());
}*/
//if($client->getClientDevices())
//{
//if ($client->getClientDevices()->first()) {
/*$nextRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->find($finalRdv->getClientDevice()->getRdv()->getId());*/
// }
//}
if ($rdv->getIsAbsence() != 1) {
if ($rdv->getIdClientTemp()) {
$nextRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client_temp" => $client,
"id_motif" => ['106', '107', '108', '109']
]);
} else {
$nextRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client" => $client,
"id_motif" => ['106', '107', '108', '109']
]);
}
if ($client->getClientDevices()) {
if ($client->getClientDevices()->first()) {
if (empty($nextRdvs)) {
$isNextRdv = false;
$initialRdvDate = $rdv->getDate();
$availableSlots = [
'Suivie de l’essai' => $this->findFirstAvailableSlot($centerId, $initialRdvDate, 7),
'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId, $initialRdvDate, 14),
'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId, $initialRdvDate, 21),
'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId, $initialRdvDate, 30),
'duration' => "30"
];
$mappedNextRdvs = [
'Suivie de l’essai' => $this->findAvailableDay($centerId, $initialRdvDate, 7),
'Confirmation de l’essai' => $this->findAvailableDay($centerId, $initialRdvDate, 14),
'Validation de l’appareillage' => $this->findAvailableDay($centerId, $initialRdvDate, 21),
'Facturation de l’appareillage' => $this->findAvailableDay($centerId, $initialRdvDate, 30),
'duration' => "30"
];
} else {
$isNextRdv = true;
$initialRdvDate = $rdv->getDate();
// Available slots for each follow-up date
$availableSlots = [];
if (isset($nextRdvs[0])) {
$availableSlots['Suivie de l’essai'] = $this->getAvailableSlotsForDate(
$openingHours,
$centerId,
$nextRdvs[0]->getDate()->format('Y-m-d')
);
}
if (isset($nextRdvs[1])) {
$availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
$openingHours,
$centerId,
$nextRdvs[1]->getDate()->format('Y-m-d')
);
}
if (isset($nextRdvs[2])) {
$availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
$openingHours,
$centerId,
$nextRdvs[2]->getDate()->format('Y-m-d')
);
}
if (isset($nextRdvs[3])) {
$availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
$openingHours,
$centerId,
$nextRdvs[3]->getDate()->format('Y-m-d')
);
}
$mappedNextRdvs = array_map(function ($rdv) {
return [
'id' => $rdv->getId(),
'date' => $rdv->getDate()->format('d-m-Y'),
'hours' => $rdv->getDate()->format('H:i'),
'duration' => $rdv->getDuration(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_titre" => $rdv->getIdMotif()->getTitre(),
];
}, $nextRdvs);
}
}
}
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_titre" => $motif->getTitre(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id" => $client->getId(),
"isClient" => ($client instanceof Client) ? 1 : 0,
"client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
"client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
"client_mail" => $client->getMail(),
"client_tel" => $client->getPhone(),
"client_fixe" => $client->getPhoneFixe(),
"confiance" => $confiance,
"client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre()->getId(),
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
"centerName" => $rdv->getIdCentre()->getName(),
"phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
"etat_id" => $rdv->getIdEtat()->getId(),
"clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"isTemp" => $rdv->getIdClientTemp() ? 1 : 0,
"isAbsence" => $rdv->getIsAbsence(),
"device" => $client->getClientDevices()->first() ? [
"isDevice" => true,
"isNextRdv" => $isNextRdv,
"deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
"clientDeviceID" => $client->getClientDevices()->first()->getId(),
"deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
"settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
"settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
"settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
"nextRdvs" => $mappedNextRdvs,
"available_slots" => $availableSlots
] : [
"isDevice" => false
]
];
} else {
// $clientDevice = $client->getClientDevices()->first();
$rdvItem = [
"id" => $rdv->getId(),
"duration" => $duration,
"color" => $rdv->getColor() ? $rdv->getColor() . '66' : '#ffb2b266',
"audio_id" => $rdv->getIdAudio()->getId(),
"client_id" => "",
"isClient" => false,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"centre_id" => $rdv->getIdCentre()->getId(),
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
"phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
"etat_id" => $rdv->getIdEtat()->getId(),
"clientEtatId" => "",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"device" => "",
"centerName" => $rdv->getIdCentre()->getName(),
"isTemp" => $rdv->getIdClientTemp() ? 1 : 0,
"isAbsence" => $rdv->getIsAbsence(),
"motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
];
}
// if ($rdv->getDate() >= new DateTime())
$rdvResult->add($rdvItem);
}
}
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"content" => $rdvResult->toArray(),
"status" => 200,
"datefin" => $dateFin
])));
} else {
$rdvItem = [];
//$rdvResult->add($rdvItem);
return new Response(json_encode(([
"content" => $rdvResult->toArray(),
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
private function findAvailableDay(int $centerId, \DateTime $initialRdvDate, int $offset): string
{
$currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
while (true) {
$formattedDate = $currentDate->format('Y-m-d');
$slots = $this->getAvailableSlotsForDate(
$this->getOpeningHoursList($centerId, $formattedDate),
$centerId,
$formattedDate
);
if (!empty($slots)) {
return $formattedDate;
}
$currentDate->modify('+1 day');
}
}
private function findFirstAvailableSlot(int $centerId, \DateTime $initialRdvDate, int $offset): array
{
$currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
while (true) {
$formattedDate = $currentDate->format('Y-m-d');
$slots = $this->getAvailableSlotsForDate(
$this->getOpeningHoursList($centerId, $formattedDate),
$centerId,
$formattedDate
);
if (!empty($slots)) {
return $slots;
}
$currentDate->modify('+1 day');
}
}
private function getOpeningHoursList($centerId, $date)
{
$center = $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
$audioCentre = $this->getDoctrine()->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
$schedule = $audioCentre->getHoraire();
$availableHours = [];
$holidayDates = [
'JourdelAn' => '01-01',
'LundidePâques' => '21-04',
'FêteduTravail' => '01-05',
'Victoire1945' => '08-05',
'Ascension' => '29-05',
'LundidePentecôte' => '09-06',
'FêteNationale' => '14-07',
'Assomption' => '15-08',
'Toussaint' => '01-11',
'Armistice1918' => '11-11',
'Noël' => '25-12',
];
$holidays = $center->getHorairesHoliday();
$requestDate = date('d-m', strtotime($date));
$englishToFrenchDays = [
'monday' => 'lundi',
'tuesday' => 'mardi',
'wednesday' => 'mercredi',
'thursday' => 'jeudi',
'friday' => 'vendredi',
'saturday' => 'samedi',
'sunday' => 'dimanche',
];
$dayOfWeek = strtolower(date('l', strtotime($date)));
$dayInFrench = $englishToFrenchDays[$dayOfWeek];
if (isset($schedule['fixed'])) {
foreach ($schedule['fixed'] as $day => $hours) {
$dayKey = strtolower($day);
$slots = [];
foreach ($hours as $period) {
$start = strtotime($period['open']);
$end = strtotime($period['close']);
while ($start < $end) {
$slots[] = date('H:i', $start);
$start = strtotime('+30 minutes', $start);
}
}
$availableHours[$dayKey] = $slots;
}
}
foreach ($holidays['fixed'] as $holiday => $hours) {
if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
$holidaySlots = [];
if (!empty($hours)) {
foreach ($hours as $period) {
$start = strtotime($period['open']);
$end = strtotime($period['close']);
while ($start < $end) {
$holidaySlots[] = date('H:i', $start);
$start = strtotime('+30 minutes', $start);
}
}
$availableHours[$dayInFrench] = $holidaySlots;
} else {
$availableHours[$dayInFrench] = [];
}
break;
}
}
return $availableHours;
}
/**
* @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
*/
public function getAudioRdvsTest(Request $request, Audio $audio)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($audio != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
/** @var Rdv[] */
if (($request->query->get('debut')) && ($request->query->get('fin'))) {
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
} else {
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_audio' => $audio->getId()]);
}
$rdvResult = new ArrayCollection();
foreach ($rdvs as $rdv) {
if ($rdv->getIdEtat()->getId() != null) {
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
if (!isset($audioMotif)) {
continue;
}
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
$dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
$dateFin = $dateFin->add(new DateInterval("PT" . $audioMotif->getDuration() . "M"));
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$name = $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
$lastName = $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
$rdvItem = [
"id" => $rdv->getId(),
"title" => $lastName . ' ' . $name,
"start" => $rdv->getDate()->format('Y-m-d H:i:s'),
"end" => $dateFin->format('Y-m-d H:i:s'),
"backgroundColor" => $audioMotif->getColor(),
"editable" => true,
"durationEditable" => false,
"resourceEditable" => true,
"cache" => false,
"motif_id" => $rdv->getIdMotif()->getId(),
"motif" => $motif->getTitre(),
"duree" => $audioMotif->getDuration(),
"color" => $audioMotif->getColor(),
"color_motif" => $audioMotif->getColor(),
"client_id" => $client->getId(),
"clientName" => $name,
"clientLastName" => $lastName,
"mail" => $client->getMail(),
"telephone" => $client->getPhone(),
"birthday" => $client->getBirthdate(),
"etat_id" => $rdv->getIdEtat()->getId(),
"dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
"dateFin" => $dateFin->format('Y-m-d H:i:s'),
"commentaire" => $rdv->getNote(),
"event_title" => "<b>" . $lastName . "</b> " . $name,
];
// if ($rdv->getDate() >= new DateTime())
$rdvResult->add($rdvItem);
}
}
if (count($rdvResult) > 0) {
return new Response(json_encode(
$rdvResult->toArray(),
));
} else {
$rdvItem = [];
//$rdvResult->add($rdvItem);
return new Response(json_encode(
$rdvResult->toArray(),
));
}
}
/**
* @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
*/
public function getCountAudioRdvs(Request $request, Audio $audio)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($audio != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_audio' => $audio->getId()]);
return new Response(json_encode(([
"content" => count($rdvs),
"status" => 200,
])));
}
/**
* @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
*/
public function getCountAudioRdvsBetweenDate(Request $request, Audio $audio)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($audio != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
/** @var Rdv[] */
$allRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
/** @var Rdv[] */
$rdvsWithTest = $this->getDoctrine()
->getRepository(Rdv::class)
->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
/** @var Rdv[] */
$allRdvsCanceled = $this->getDoctrine()
->getRepository(Rdv::class)
->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
/** @var Rdv[] */
$allRdvsCanceledCentre = $this->getDoctrine()
->getRepository(Rdv::class)
->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
/** @var Rdv[] */
$rdvsClosed = $this->getDoctrine()
->getRepository(Rdv::class)
->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myLead = 0;
$rdvsCanceled = $this->getDoctrine()
->getRepository(Rdv::class)
->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
foreach ($rdvsCanceled as $rdvc) {
if (!is_null($rdvc->getIdClient())) {
$rdvClient = $this->getDoctrine()
->getRepository(Rdv::class)
->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
if (count($rdvClient) == 0) {
$myLead = $myLead + 1;
}
}
}
$myLeadAdvanced = 0;
$rdvsCanceledA = $this->getDoctrine()
->getRepository(Rdv::class)
->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
foreach ($rdvsCanceledA as $rdvc) {
if (!is_null($rdvc->getIdClient())) {
$rdvClient = $this->getDoctrine()
->getRepository(Rdv::class)
->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
if (count($rdvClient) == 0) {
$myLeadAdvanced = $myLeadAdvanced + 1;
}
}
}
/**** MY RDV Centre****/
$myrdvCentre = 0;
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myrdvCentre = count($rdvs);
/**** MY RDV ADVANCED ****/
$myRdvAdvancedCentre = 0;
$rdvsA = $this->getDoctrine()
->getRepository(Rdv::class)
->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myRdvAdvancedCentre = count($rdvsA);
/**** FIRST RDV BY MOTIF PREMIER RDV ****/
$myFirstRdv = 0;
$rdvsFirst = $this->getDoctrine()
->getRepository(Rdv::class)
->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myFirstRdv = count($rdvsFirst);
/**** RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
$myAudioRdv = 0;
$audioRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myAudioRdv = count($audioRdv);
/**** RDV BY GENDER ****/
$myRdvByGender = 0;
$audioRdvGender = $this->getDoctrine()
->getRepository(Rdv::class)
->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myRdvByGender = $audioRdvGender;
/**** RDV BY AGE ****/
$myRdvByAge = 0;
$audioRdvAge = $this->getDoctrine()
->getRepository(Rdv::class)
->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
$myRdvByAge = $audioRdvAge;
// dd($myRdvByAge);
/**** MY LEAD ****/
$myLeadCentre = 0;
$rdvsCanceled = $this->getDoctrine()
->getRepository(Rdv::class)
->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
foreach ($rdvsCanceled as $rdvc) {
if (!is_null($rdvc->getIdClient())) {
$rdvClient = $this->getDoctrine()
->getRepository(Rdv::class)
->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
if (count($rdvClient) == 0) {
$myLeadCentre = $myLeadCentre + 1;
}
}
}
/**** MY LEAD ADVANCED****/
$myLeadAdvancedCentre = 0;
$rdvsCanceledA = $this->getDoctrine()
->getRepository(Rdv::class)
->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
foreach ($rdvsCanceledA as $rdvc) {
if (!is_null($rdvc->getIdClient())) {
$rdvClient = $this->getDoctrine()
->getRepository(Rdv::class)
->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
if (count($rdvClient) == 0) {
$myLeadAdvancedCentre = $myLeadAdvancedCentre + 1;
}
}
}
return $this->json([
"rdvs" => count($rdvs),
"rdvsFromTest" => count($rdvsWithTest),
"allRdvs" => count($allRdvs),
"rdvsCanceled" => count($allRdvsCanceled),
"rdvsClosed" => $rdvsClosed,
"myRdvByGender" => $myRdvByGender,
"myLead" => $myLead,
"myRdvByAge" => $myRdvByAge,
"myAudioRdv" => $myAudioRdv,
"myLeadAdvanced" => $myLeadAdvanced,
"myRDVCentre" => $myrdvCentre,
"myRDVAdancedCentre" => $myRdvAdvancedCentre,
"myLeadCentre" => $myLeadCentre,
"myLeadAdvancedCentre" => $myLeadAdvancedCentre,
"rdvsCanceledCentre" => count($allRdvsCanceledCentre),
"myFirstRdv" => $myFirstRdv,
"status" => 200,
]);
}
/**
* @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
*/
public function getOldRdvsByClientTempId(Request $request, ClientTemp $clientTemp, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
if ($request->query->get('audio')) {
/** @var ActivityRepository */
$activityRepo = $this->getDoctrine()->getRepository(Rdv::class);
if ($request->query->get('limit')) {
/** @var Rdv[] */
$rdvs = $activityRepo
->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
$rdvResult = new ArrayCollection();
} else {
/** @var Rdv[] */
$rdvs = $activityRepo
->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
$rdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
if ($rdv->getIdEtat()->getId() != 1) {
continue;
}
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
if (!$audioMotif) {
continue;
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id_temp" => $rdv->getIdClientTemp()->getId(),
"client_name" => $rdv->getIdClientTemp()->getName() . " " . $rdv->getIdClientTemp()->getLastname(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdvCentre->getName(),
"phone" => $rdvCentre->getPhone(),
"imgUrl" => $rdvCentre->getImgUrl(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"etat_id" => $rdvCentre->getId(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
];
$rdvResult->add($rdvItem);
}
}
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
/**
* @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
*/
public function getOldRdvsByClientTempIdByCentre(Request $request, ClientTemp $clientTemp, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
$audioCentre = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_audio' => $token->getIdAudio()]);
// we add the multi-centre so we wil desable the autorisation
/*
if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
*/
/** @var ActivityRepository */
$activityRepo = $this->getDoctrine()->getRepository(Rdv::class);
if ($request->query->get('limit')) {
/** @var Rdv[] */
$rdvs = $activityRepo
->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
$rdvResult = new ArrayCollection();
} else {
/** @var Rdv[] */
$rdvs = $activityRepo
->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
$rdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
/*if ($rdv->getIdEtat()->getId() != 1) {
continue;
}*/
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
if (!$audioMotif) {
continue;
}
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvCentre = $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdvCentre->getId());
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id_temp" => $rdv->getIdClientTemp()->getId(),
"client_name" => $rdv->getIdClientTemp()->getName() . " " . $rdv->getIdClientTemp()->getLastname(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"name" => $rdvCentre->getName(),
"phone" => $rdvCentre->getPhone(),
"imgUrl" => $rdvCentre->getImgUrl(),
"address" => $rdvCentre->getAddress(),
"postale" => $rdvCentre->getPostale(),
"city" => $rdvCentre->getCity(),
"etat_id" => $rdvCentre->getId(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"note" => $rdv->getNote(),
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
"status" => $rdv->getIdEtat()->getLibelle()
];
$rdvResult->add($rdvItem);
}
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
/**
* @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
*/
public function getRdvsByClientTempID(Request $request, ClientTemp $clientTemp, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
$rdvResult = new ArrayCollection();
if ($request->query->get('old')) {
$oldRdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
if ($rdv->getIdEtat()->getId() != null) {
if ($rdv->getIdEtat()->getId() == 1) {
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdv->getIdCentre()->getId());
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"client_name" => $rdv->getIdClientTemp()->getName() . " " . $rdv->getIdClientTemp()->getLastname(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"name" => $rdv->getIdCentre()->getName(),
"imgUrl" => $rdv->getIdCentre()->getImgUrl(),
"address" => $rdv->getIdCentre()->getAddress(),
"phone" => $rdv->getIdCentre()->getPhone(),
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"review" => $rdv->getReview(),
];
if ($rdv->getDate() >= new DateTime()) {
$rdvResult->add($rdvItem);
} else if ($request->query->get('old')) {
$oldRdvResult->add($rdvItem);
}
}
}
}
if ($request->query->get('old')) {
if (count($rdvResult) > 0 || count($oldRdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"oldRdv" => $oldRdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
} else {
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"content" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
}
/**
* @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
*/
public function getRdvsByClientTempIDByCentre(Request $request, ClientTemp $clientTemp, PublicFunction $publicFunction)
{
if (!$request->query->get('token')) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $request->query->get('token')]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
$audioCentre = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_audio' => $token->getIdAudio()]);
// we add the multi-centre so we wil desable the autorisation
/*
if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
"status" => 404,
]), 404);
}*/
/** @var Rdv[] */
$rdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
$rdvResult = new ArrayCollection();
if ($request->query->get('old')) {
$oldRdvResult = new ArrayCollection();
}
foreach ($rdvs as $rdv) {
if ($rdv->getIdEtat()->getId() != null) {
if ($rdv->getIdEtat()->getId() != 6) {
// if ($rdv->getIdEtat()->getId() == 1) {
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
/** @var Rdv[] */
$centreRdvs = $this->getDoctrine()->getRepository(Rdv::class)
->findAllReviewsCentre($rdv->getIdCentre()->getId());
$duration = '';
if (is_null($rdv->getDuration())) {
$duration = $audioMotif->getDuration();
} else {
$duration = $rdv->getDuration();
}
$rdvItem = [
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"duration" => $duration,
"color" => $audioMotif->getColor(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"client_name" => $rdv->getIdClientTemp()->getName() . " " . $rdv->getIdClientTemp()->getLastname(),
"averageRating" => $publicFunction->calculateRating($centreRdvs),
"nbrReview" => count($centreRdvs),
"acceptedCurrency" => "CB Chèque",
"name" => $rdv->getIdCentre()->getName(),
"imgUrl" => $rdv->getIdCentre()->getImgUrl(),
"address" => $rdv->getIdCentre()->getAddress(),
"phone" => $rdv->getIdCentre()->getPhone(),
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"review" => $rdv->getReview(),
"status" => $rdv->getIdEtat()->getLibelle()
];
if ($rdv->getDate() >= new DateTime()) {
$rdvResult->add($rdvItem);
} else if ($request->query->get('old')) {
$oldRdvResult->add($rdvItem);
}
}
}
}
if ($request->query->get('old')) {
if (count($rdvResult) > 0 || count($oldRdvResult) > 0) {
return new Response(json_encode(([
"rdv" => $rdvResult->toArray(),
"oldRdv" => $oldRdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
} else {
if (count($rdvResult) > 0) {
return new Response(json_encode(([
"content" => $rdvResult->toArray(),
"status" => 200,
])));
} else {
return new Response(json_encode(([
"message" => "Aucun rendez-vous n'a été trouvé!",
'path' => 'src/Controller/RdvController.php',
"status" => 404,
])));
}
}
}
/**
* @Route("/rdv", name="postRdv", methods={"POST"})
*/
public function postRdv(Request $request, PublicFunction $publicFunction, GoogleCalendarService $googleCalendar, RdvSmsService $rdvSms): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
// makes the rdv
$rdv = new Rdv();
if ($token->getIdAudio()) {
//if the token if for an audio
$audio = $token->getIdAudio();
if ((isset($data["client_id"]))) {
$client = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $data["client_id"]]);
} else {
$client = $this->getDoctrine()
->getRepository(ClientTemp::class)
->findOneBy(['id' => $data["client_id_temp"]]);
}
if ($client == null) {
return new Response(json_encode(([
'message' => 'Error, no client found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} elseif ($token->getIdClient()) {
//if the token if for a client
$client = $token->getIdClient();
/** @var ActivityRepository */
$activityRepo = $this->getDoctrine();
/** @var TestClient */
$testClient = $activityRepo
->getRepository(TestClient::class)
->getLatestTestClient($client);
// add the test to the rdv if the client had one
if ($testClient)
// add the test to the rdv if the test isn't already on another rdv
{
if (!$testClient->getRdv()) {
$rdv->setTestClient($testClient);
}
}
/** @var Audio */
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $data["audio_id"]]);
if (isset($data["proche_id"])) {
$proche = $this->getDoctrine()
->getRepository(Proches::class)
->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
}
if (!$audio) {
return new Response(json_encode(([
'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
'path' => 'src/Controller/RdvController.php',
])), 400);
}
/** @var ClientBlocked */
$clientBlocked = $this->getDoctrine()
->getRepository(ClientBlocked::class)
->findOneBy(["id_audio" => $audio, "id_client" => $client]);
if ($clientBlocked) {
return new Response(json_encode(([
'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
'path' => 'src/Controller/RdvController.php',
])), 400);
}
// set the rdv test
} else {
return new Response(json_encode(([
'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
'path' => 'src/Controller/RdvController.php',
])), 400);
}
$rdv->setIdAudio($audio);
if (isset($proche)) {
$rdv->setIdProche($proche);
}
if (isset($data["client_id_temp"])) {
$rdv->setIdClientTemp($client);
} else {
$rdv->setIdClient($client);
}
if (isset($data["isMyaudio"])) {
$rdv->setIsMyaudio(true);
}
if (isset($data["isRdvLead"])) {
$rdv->setIsRdvLp(true);
}
if (isset($data["isRdvRapide"])) {
$rdv->setIsRdvRapide(true);
}
if (isset($data["duree"])) {
$rdv->setDuration($data["duree"]);
}
if (isset($data["color"])) {
$rdv->setColor($data["color"]);
}
if (isset($data["lead"])) {
$lead = $this->getDoctrine()
->getRepository(LeadRdv::class)
->find($data["lead"]);
$lead->setRdv($rdv);
$leadStatus = $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
if ($leadStatus) {
$lead->setLeadStatus($leadStatus);
}
}
/** @var Centre */
if (isset($data["centre_id"])) {
$centre = $this->getDoctrine()
->getRepository(Centre::class)
->findOneBy(['id' => $data["centre_id"]]);
if ($centre == null) {
return new Response(json_encode(([
'message' => 'Error, no centre found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdCentre($centre);
} elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
// tries to set the lieu if it's an audio indie
$lieu = $this->getDoctrine()
->getRepository(Lieu::class)
->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
if ($lieu == null) {
return new Response(json_encode(([
'message' => 'Error, no lieu found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdLieu($lieu);
} else {
return new Response(json_encode(([
'message' => 'Error, no lieu/centre id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var Motif */
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->find($data["motif_id"]);
if ($motif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
// test if the audio is available
if ($audio->getIsIndie()) {
if (isset($data["centre_id"])) {
if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre) == false) {
return new Response(json_encode(([
'message' => 'Error, no timestamp found at this time. Line n°' . __LINE__,
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$remplacant_id = $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
} else {
if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), null, $lieu) == false) {
return new Response(json_encode(([
'message' => 'Error, no timestamp found at this time. Line n°' . __LINE__,
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$remplacant_id = $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
}
} else {
if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/* if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
return new Response(json_encode(([
'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);*/
$remplacant_id = $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i", $data["date"]));
}
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$existingRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->findOneBy([
'date' => $date,
'id_audio' => $audio,
'id_centre' => $rdv->getIdCentre() ?? null,
'id_lieu' => $rdv->getIdLieu() ?? null,
]);
if ($existingRdv) {
return new Response(json_encode([
'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
'status' => 400,
]), 400);
}
$rdv->setDate($date);
$rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i", date('d/m/Y H:i')));
/** @var EtatRdv */
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
$rdv->setIdMotif($motif);
$rdv->setIsAbsence(0);
$rdv->setCacher(0);
if ($remplacant_id != -1) {
$remplacant = $this->getDoctrine()
->getRepository(Remplacant::class)
->find($remplacant_id);
$rdv->setRemplacant($remplacant);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($rdv);
$entityManager->flush();
/// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$client->setIdCentre($rdv->getIdCentre());
$client->setIdAudio($rdv->getIdAudio());
$entityManager->persist($client);
$entityManager->flush();
// client notif mail Sms
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$responses = [
'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", ", $data['situations']) : null,
'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
];
$paramsSourceLead = [
'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
];
$params = array(
"lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"RdvDate" => $smsDateLongFormat,
'telCentre' => $rdv->getIdCentre()->getPhone(),
"centerName" => $rdv->getIdCentre()->getName(),
"prenom" => $client->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' . $rdv->getIdCentre()->getPostale() . ' ' . $rdv->getIdCentre()->getCity(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
'motif' => $rdv->getIdMotif()->getTitre(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"audioName" => $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
'titre' => "Votre rendez-vous est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15),
"position" => $rdv->getIdCentre()->getAddress() . ' ' . $rdv->getIdCentre()->getPostale() . ' ' . $rdv->getIdCentre()->getCity(),
"address" => $rdv->getIdCentre()->getAddress(),
"postal" => $rdv->getIdCentre()->getPostale(),
"city" => $rdv->getIdCentre()->getCity(),
"clientEmail" => $client->getMail(),
"clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
"clientAddress" => $client->getAddress(),
"clientPostal" => $client->getPostal(),
"clientCity" => $client->getCity(),
"audioName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
"frenchDate" => $frenchDate,
"heure" => substr($smsDate, 11, 15),
"centerName" => $rdv->getIdCentre()->getName(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
);
$paramsPatient = $params;
$isNew = false;
if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
$subject = "✅Rendez-vous My Audio confirmé le " . $smsDateLongFormat;
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 189);
$isNew = true;
} else {
$subject = "Rendez-vous My Audio confirmé le " . $smsDateLongFormat;
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 181);
}
$sms = "Votre RDV est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
// audio Notif mail SMS
$birthday = $rdv->getIdClient()->getBirthdate();
$params = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"date" => substr($smsDate, 0, 10),
"heure" => substr($smsDate, 11, 15),
"mail" => $client->getMail(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'telClient' => $client->getPhone(),
'phone' => $client->getPhone(),
'clientCivilite' => $client->getCivilite(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
'clientPhone' => $client->getPhone(),
'motif' => $rdv->getIdMotif()->getTitre(),
'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
'titre' => 'Vous avez un nouveau RDV le : ' . substr($smsDate, 0, 10) . ' à ' . substr($smsDate, 11, 15),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'idPatient' => $client->getId(),
'proUrl' => "{$_ENV['BASE_logiciel']}",
'frenchDate' => $frenchDate,
'responses' => $responses,
);
$templateEmail = 182;
if (!empty($data['canMove'])) {
$templateEmail = 197;
}
$subject = "✅Nouveau Rendez-vous My Audio le " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, $templateEmail);
$sms = "Vous avez un nouveau RDV le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'aléas contactez votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
// send notif to admin
$paramsAdmin = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"RdvDate" => substr($smsDate, 0, 10),
"heure" => substr($smsDate, 11, 15),
"clientMail" => $client->getMail(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'telClient' => $client->getPhone(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientCivilite' => $client->getCivilite(),
'clientPostal' => $client->getPostal(),
'clientPhone' => $client->getPhone(),
'motif' => $rdv->getIdMotif()->getTitre(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'telCentre' => $rdv->getIdCentre()->getPhone(),
'titre' => 'Vous avez un nouveau RDV le : ' . substr($smsDate, 0, 10) . ' à ' . substr($smsDate, 11, 15),
'date' => substr($smsDate, 0, 10),
'urlApi' => "{$_ENV['BASE_API']}",
'clientId' => $client->getId(),
'centerId' => $rdv->getIdCentre()->getId(),
'frenchDate' => $frenchDate,
'responses' => $responses,
'paramsSourceLead' => $paramsSourceLead
);
$subject = "Nouveau RDV MA | RR - " . $rdv->getIdCentre()->getName();
$templateEmail = 183;
if (!empty($data['canMove'])) {
$templateEmail = 190;
}
if (!isset($data["isLead"])) {
$publicFunction->sendEmail($paramsAdmin, "lead.myaudio@gmail.com", "my audio", $subject, $templateEmail);
}
//$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
$publicFunction->sendEmail($paramsAdmin, "mickael.aubard@myaudio.fr", "my audio", $subject, $templateEmail);
$publicFunction->sendEmail($paramsAdmin, "mickael@aubard.me", "my audio", $subject, $templateEmail);
// google calendar post
$synchronisations = $this->getDoctrine()->getRepository(SynchronisationSetting::class)
->findBy(array('audio' => $audio->getId()));
$data['rdv'] = $rdv->getId();
if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
$rdvLead = $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
if ($rdvLead) {
$leadStatus = $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
if ($leadStatus) {
$rdvLead->setLeadStatus($leadStatus);
$rdvLead->setRdv($rdv);
$this->entityManager->flush();
}
}
}
foreach ($synchronisations as $synchronisation) {
if (!$synchronisation->getIsDeleted()) {
$googleCalendar->checkAndRefreshAccessToken($synchronisation);
$googleCalendar->createEvent($synchronisation, $data);
}
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $remplacant_id == -1 ? null : $remplacant_id,
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"duration" => $audioMotif->getDuration(),
"consigne" => $audioMotif->getConsigne(),
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"centerName" => $rdv->getIdCentre()->getName(),
"review" => $rdv->getReview(),
"note" => $rdv->getNote(),
"status" => 200,
"paramsPatient" => $paramsPatient,
"isNew" => $isNew,
])));
}
/**
* @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
*/
public function contactTrustedUser(Request $request, PublicFunction $publicFunction)
{
$pastDate = $rdv->getDate();
$data = json_decode($request->getContent(), true);
$entityManager = $this->getDoctrine()->getManager();
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
if (isset($data["date"])) {
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($rdv->getIdAudio()->getIsIndie()) {
if ($rdv->getIdCentre()) {
// regular centre audio indie
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
// return new Response(json_encode(([
// 'message' => 'Error, no timestamp found at this time',
// 'path' => 'src/Controller/RdvController.php',
// "status" => 400,
// ])),400);
// }
} else {
// lieu audio indie
if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
// return new Response(json_encode(([
// 'message' => 'Error, no timestamp found at this time',
// 'path' => 'src/Controller/RdvController.php',
// "status" => 400,
// ])),400);
// }
}
} else {
// regular centre
if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
// return new Response(json_encode(([
// 'message' => 'Error, no timestamp found at this time',
// 'path' => 'src/Controller/RdvController.php',
// "status" => 400,
// ])),400);
// }
}
$rdv->setDate($date);
}
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$oldDate = $pastDate->format('d-m-Y H:i');
$publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $rdv->getIdClient()->getIdPersonneConfiance()->getMail(), "My Audio: Confirmation RDV", "<p>Le RDV de votre proche est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'aléa contactez le centre " . $rdv->getIdCentre()->getPhone() . " pour modifier sa consultation.</p>");
return new Response(json_encode(([
"id" => $rdv->getId(),
"status" => 200,
])));
}
/**
* @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
*/
public function editRdvByID(PublicFunction $publicFunction, Rdv $rdv, Request $request, GoogleCalendarService $googleCalendar, RdvSmsService $rdvSms): Response
{
$pastDate = $rdv->getDate();
$pastDuration = $rdv->getDuration();
$data = json_decode($request->getContent(), true);
$entityManager = $this->getDoctrine()->getManager();
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
if (isset($data["etat_id"])) {
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
}
if (isset($data["audio_id"])) {
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $data["audio_id"]]);
if ($audio == null) {
return new Response(json_encode(([
'message' => 'Error, no audio found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdAudio($audio);
}
if (isset($data["motif_id"])) {
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->find($data["motif_id"]);
if ($motif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdMotif($motif);
}
if (isset($data["client_id"])) {
$client = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $data["client_id"]]);
if ($client == null) {
return new Response(json_encode(([
'message' => 'Error, no client found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdClient($client);
}
// set client status
if (isset($data["client_status_id"])) {
$status = $this->getDoctrine()
->getRepository(ClientStatus::class)
->findOneBy(['id' => $data["client_status_id"]]);
if ($status == null) {
return new Response(json_encode(([
'message' => 'Error, no status found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$client->setClientStatus($status);
$client->setLastUpdateStatus(new \DateTimeImmutable);
}
if (isset($data["date"])) {
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$dateInput = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($rdv->getIdAudio()->getIsIndie()) {
if ($rdv->getIdCentre()) {
// regular centre audio indie
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} else {
// lieu audio indie
if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}
} else {
// regular centre
if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}
$rdv->setDate($date);
}
if (isset($data["comment"]) && $token->getIdClient()) {
$rdv->setComment($data["comment"]);
}
if (isset($data["review"]) && $token->getIdClient()) {
$rdv->setReview($data["review"]);
}
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
if (isset($data["duree"])) {
$rdv->setDuration($data["duree"]);
}
////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$oldDate = $pastDate->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
// notif client
if ($rdv->getIdEtat()->getId() != 2) {
if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
if ($data["sms"]) {
$params = array(
"lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"heure" => substr($smsDate, 11, 15),
"motif" => $rdv->getIdMotif()->getTitre(),
"centerName" => $rdv->getIdCentre()->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"centerPhone" => $rdv->getIdCentre()->getPhone(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le',
'frenchDate' => $frenchDate,
);
$subject = "Rendez-vous My Audio modifié pour " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 184);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
}
}
}
// //// == suppression
else if ($rdv->getIdEtat()->getId() == 2) {
// delete google agenda event
$rdvEvents = $this->getDoctrine()->getRepository(RdvEvent::class)
->findBy(array('rdv' => $rdv));
foreach ($rdvEvents as $rdvEvent) {
$googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
if ($googleCalendar) {
$googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
$entityManager->remove($rdvEvent);
$entityManager->flush();
}
}
//if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
//if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}search",
"heure" => substr($smsDate, 11, 15),
"patientName" => $client->getLastName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 188);
if ($data["sms"]) {
$sms = "Votre RDV a été annulé, contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
}
//}
}
// set center
if (isset($data["centre_id"])) {
$entityManager = $this->getDoctrine()->getManager();
$centreId = $data["centre_id"];
$centre = $entityManager->getRepository(Centre::class)->find($centreId);
if (!$centre) {
return $this->json([
'message' => 'Error, no Centre found with this ID',
'path' => 'src/Controller/YourController.php',
]);
}
$rdv->setIdCentre($centre);
}
$rdv->setGoogleAgendaImported(false);
//notif Audio
if ($rdv->getIdEtat()->getId() != 2) {
if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
if ($data["sms"]) {
$params = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"date" => substr($smsDate, 0, 10),
"frenchDate" => $frenchDate,
"heure" => substr($smsDate, 11, 15),
'motif' => $rdv->getIdMotif()->getTitre(),
'clientPhone' => $client->getPhone(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientCivilite' => $client->getCivilite(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'idPatient' => $client->getId(),
'proUrl' => "{$_ENV['BASE_logiciel']}",
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le :'
);
$subject = "🔀 Rendez-vous My Audio modifié du " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 186);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
}
}
} else if ($rdv->getIdEtat()->getId() == 2) {
if ($data["sms"]) {
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}search",
"heure" => substr($smsDate, 11, 15),
"patientName" => $client->getLastName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 188);
$sms = "Votre RDV du " . substr($oldDate, 0, 10) . " à " . substr($oldDate, 11, 15) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" . $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
}
}
$entityManager->flush();
if ((isset($data["prenom_patient"])) || (isset($data["nom_patient"])) || (isset($data["birthday_patient"])) || (isset($data["mail_patient"])) || (isset($data["portable_patient"])) || (isset($data["fixe_patient"]))) {
if (is_null($rdv->getIdClientTemp())) {
$clientRDV = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $rdv->getIdClient()->getId()]);
$clientRDV->setName($data["prenom_patient"]);
$clientRDV->setLastname($data["nom_patient"]);
$clientRDV->setMail($data["mail_patient"]);
$clientRDV->setPhone($data["portable_patient"]);
$clientRDV->setPhoneFixe($data["fixe_patient"]);
} else {
$clientRDV = $this->getDoctrine()
->getRepository(ClientTemp::class)
->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
$clientRDV->setName($data["prenom_patient"]);
$clientRDV->setLastname($data["nom_patient"]);
$clientRDV->setMail($data["mail_patient"]);
$clientRDV->setPhone($data["portable_patient"]);
$clientRDV->setPhoneFixe($data["fixe_patient"]);
}
if (!empty($data["birthday_patient"])) {
$birth = \DateTime::createFromFormat("Y-m-d", $data["birthday_patient"]);
$clientRDV->setBirthdate($birth);
}
$entityManager->flush();
}
if (is_null($rdv->getIdClient())) {
$prenom_patient = $rdv->getIdClientTemp()->getName();
$nom_patient = $rdv->getIdClientTemp()->getLastname();
$mail_patient = $rdv->getIdClientTemp()->getMail();
$portable_patient = $rdv->getIdClientTemp()->getPhone();
$fixe_patient = $rdv->getIdClientTemp()->getPhoneFixe();
$birthday = $rdv->getIdClientTemp()->getBirthdate();
} elseif (is_null($rdv->getIdClientTemp())) {
$prenom_patient = $rdv->getIdClient()->getName();
$nom_patient = $rdv->getIdClient()->getLastname();
$mail_patient = $rdv->getIdClient()->getMail();
$portable_patient = $rdv->getIdClient()->getPhone();
$fixe_patient = $rdv->getIdClient()->getPhoneFixe();
$birthday = $rdv->getIdClient()->getBirthdate();
} else {
$prenom_patient = "";
$nom_patient = "";
$mail_patient = "";
$portable_patient = "";
$fixe_patient = "";
$birthday = "";
}
/* generate sms notif on update */
// update sms notification
$rdvSms->updateRdvSms($rdv);
// google calendar update
$synchronisations = $this->getDoctrine()->getRepository(SynchronisationSetting::class)
->findBy(array('audio' => $rdv->getIdAudio()));
$data['rdv'] = $rdv->getId();
if ($rdv->getIdClient() !== null) {
$data["client_id"] = $rdv->getIdClient()->getId();
}
if ($rdv->getIdClientTemp() !== null) {
$data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
}
$rdvEvents = $this->getDoctrine()->getRepository(RdvEvent::class)
->findBy(array('rdv' => $rdv));
foreach ($rdvEvents as $rdvEvent) {
$googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
$googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
}
$synchronisationCosium = $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
$cosiumCenter = $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium, "center" => $rdv->getIdCentre()]);
if ($cosiumCenter) {
$this->clientCosiumService->deleteRdv($synchronisationCosium, $rdv);
$this->clientCosiumService->createAgenda($synchronisationCosium, $rdv, $cosiumCenter);
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_libelle" => $rdv->getIdMotif()->getTitre(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
"fullName" => $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastname(),
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"review" => $rdv->getReview(),
"clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
"prenom_patient" => $prenom_patient,
"nom_patient" => $nom_patient,
"mail_patient" => $mail_patient,
"portable_patient" => $portable_patient,
"fixe_patient" => $fixe_patient,
"birthday" => $birthday,
"status" => 200,
])));
}
/**
* @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
*/
public function editRdvByIDFromPatient(PublicFunction $publicFunction, Rdv $rdv, Request $request): Response
{
$pastDate = $rdv->getDate();
$pastDuration = $rdv->getDuration();
$data = json_decode($request->getContent(), true);
$entityManager = $this->getDoctrine()->getManager();
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
if (isset($data["etat_id"])) {
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
}
if (isset($data["audio_id"])) {
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $data["audio_id"]]);
if ($audio == null) {
return new Response(json_encode(([
'message' => 'Error, no audio found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdAudio($audio);
}
if (isset($data["motif_id"])) {
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->find($data["motif_id"]);
if ($motif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdMotif($motif);
}
if (isset($data["client_id"])) {
$client = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $data["client_id"]]);
if ($client == null) {
return new Response(json_encode(([
'message' => 'Error, no client found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdClient($client);
}
if (isset($data["date"])) {
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$dateInput = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($rdv->getIdAudio()->getIsIndie()) {
if ($rdv->getIdCentre()) {
// regular centre audio indie
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} else {
// lieu audio indie
if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}
} else {
// regular centre
if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}
$rdv->setDate($date);
}
if (isset($data["comment"]) && $token->getIdClient()) {
$rdv->setComment($data["comment"]);
}
if (isset($data["review"]) && $token->getIdClient()) {
$rdv->setReview($data["review"]);
}
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
if (isset($data["duree"])) {
$rdv->setDuration($data["duree"]);
}
////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$oldDate = $pastDate->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
// notif client
if ($rdv->getIdEtat()->getId() != 2) {
if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
$params = array(
"lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"heure" => substr($smsDate, 11, 15),
"motif" => $rdv->getIdMotif()->getTitre(),
"centerName" => $rdv->getIdCentre()->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"centerPhone" => $rdv->getIdCentre()->getPhone(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le',
'frenchDate' => $frenchDate,
);
$subject = "Rendez-vous My Audio modifié pour " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 184);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
}
}
// //// == suppression
else if ($rdv->getIdEtat()->getId() == 2) {
//if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
//if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
"heure" => substr($smsDate, 11, 15),
"patientName" => $client->getLastName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 203);
$sms = "Votre RDV a été annulé, contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
//}
}
// set center
if (isset($data["centre_id"])) {
$entityManager = $this->getDoctrine()->getManager();
$centreId = $data["centre_id"];
$centre = $entityManager->getRepository(Centre::class)->find($centreId);
if (!$centre) {
return $this->json([
'message' => 'Error, no Centre found with this ID',
'path' => 'src/Controller/YourController.php',
]);
}
$rdv->setIdCentre($centre);
}
$rdv->setGoogleAgendaImported(false);
//notif Audio
if ($rdv->getIdEtat()->getId() != 2) {
if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
$params = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"date" => $pastDate->format("y-m-d"),
"heure" => $pastDate->format("H:i"),
'clientPhone' => $client->getPhone(),
'clientCivilite' => $client->getCivilite(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
"birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
"mail" => $rdv->getIdClient()->getMail(),
"phone" => $rdv->getIdClient()->getPhone(),
"motif" => $rdv->getIdMotif()->getTitre(),
"address" => $rdv->getIdCentre()->getAddress(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getLastName() . ' ' . $rdv->getIdAudio()->getName(),
"newRdvDate" => substr($smsDate, 0, 10),
"newRdvHour" => substr($smsDate, 11, 15),
"centerName" => $rdv->getIdCentre()->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
"urlPro" => "{$_ENV['BASE_logiciel']}",
"idPatient" => $rdv->getIdClient()->getId(),
);
$subject = "🔀 Rendez-vous My Audio modifié par " . $client->getCivilite() . " " . $client->getName() . " " . $client->getLastname();
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 185);
$subjectMyAudio = "🔀 Le patient " . $client->getCivilite() . " " . $client->getName() . " " . $client->getLastname() . " a modifié son rendez-vous My Audio";
$publicFunction->sendEmail($params, "lead.myaudio@gmail.com", $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subjectMyAudio, 204);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
}
} else if ($rdv->getIdEtat()->getId() == 2) {
$params = array(
"date" => substr($smsDate, 0, 10),
"heure" => substr($smsDate, 11, 15),
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
"motif" => $rdv->getIdMotif()->getTitre(),
"centerAddress" => $rdv->getIdCentre()->getAddress(),
"centerPostal" => $rdv->getIdCentre()->getPostale(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"centerName" => $rdv->getIdCentre()->getName(),
"clientNom" => $rdv->getIdClient()->getLastname(),
"clientPrenom" => $rdv->getIdClient()->getName(),
"clientMail" => $rdv->getIdClient()->getMail(),
"clientPhone" => $rdv->getIdClient()->getPhone(),
'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
"proUrl" => "{$_ENV['BASE_logiciel']}",
"idPatient" => $rdv->getIdClient()->getId(),
);
$subject = "❌ Annulation du rendez-vous par le patient " . $client->getCivilite() . " " . $client->getName() . " " . $client->getLastname();
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 187);
$subject = "❌ Annulation du rendez-vous par le patient " . $client->getCivilite() . " " . $client->getName() . " " . $client->getLastname();
$publicFunction->sendEmail($params, "lead.myaudio@gmail.com", $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 195);
$sms = "Votre RDV du " . substr($oldDate, 0, 10) . " à " . substr($oldDate, 11, 15) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" . $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
}
$entityManager->flush();
if ((isset($data["prenom_patient"])) || (isset($data["nom_patient"])) || (isset($data["birthday_patient"])) || (isset($data["mail_patient"])) || (isset($data["portable_patient"])) || (isset($data["fixe_patient"]))) {
$birth = \DateTime::createFromFormat("Y-m-d", $data["birthday_patient"]);
if (is_null($rdv->getIdClientTemp())) {
$clientRDV = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $rdv->getIdClient()->getId()]);
$clientRDV->setName($data["prenom_patient"]);
$clientRDV->setLastname($data["nom_patient"]);
$clientRDV->setBirthdate($birth);
$clientRDV->setMail($data["mail_patient"]);
$clientRDV->setPhone($data["portable_patient"]);
$clientRDV->setPhoneFixe($data["fixe_patient"]);
} else {
$clientRDV = $this->getDoctrine()
->getRepository(ClientTemp::class)
->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
$clientRDV->setName($data["prenom_patient"]);
$clientRDV->setLastname($data["nom_patient"]);
$clientRDV->setBirthdate($birth);
$clientRDV->setMail($data["mail_patient"]);
$clientRDV->setPhone($data["portable_patient"]);
$clientRDV->setPhoneFixe($data["fixe_patient"]);
}
$entityManager->flush();
}
if (is_null($rdv->getIdClient())) {
$prenom_patient = $rdv->getIdClientTemp()->getName();
$nom_patient = $rdv->getIdClientTemp()->getLastname();
$mail_patient = $rdv->getIdClientTemp()->getMail();
$portable_patient = $rdv->getIdClientTemp()->getPhone();
$fixe_patient = $rdv->getIdClientTemp()->getPhoneFixe();
$birthday = $rdv->getIdClientTemp()->getBirthdate();
} elseif (is_null($rdv->getIdClientTemp())) {
$prenom_patient = $rdv->getIdClient()->getName();
$nom_patient = $rdv->getIdClient()->getLastname();
$mail_patient = $rdv->getIdClient()->getMail();
$portable_patient = $rdv->getIdClient()->getPhone();
$fixe_patient = $rdv->getIdClient()->getPhoneFixe();
$birthday = $rdv->getIdClient()->getBirthdate();
} else {
$prenom_patient = "";
$nom_patient = "";
$mail_patient = "";
$portable_patient = "";
$fixe_patient = "";
$birthday = "";
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_libelle" => $rdv->getIdMotif()->getTitre(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
"fullName" => $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastname(),
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"review" => $rdv->getReview(),
"prenom_patient" => $prenom_patient,
"nom_patient" => $nom_patient,
"mail_patient" => $mail_patient,
"portable_patient" => $portable_patient,
"fixe_patient" => $fixe_patient,
"birthday" => $birthday,
"status" => 200,
])));
}
/**
* @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
*/
public function suppRdvByID(PublicFunction $publicFunction, Rdv $rdv, Request $request, GoogleCalendarService $googleCalendar, RdvSmsService $rdvSms): Response
{
$pastDate = $rdv->getDate();
$data = json_decode($request->getContent(), true);
$entityManager = $this->getDoctrine()->getManager();
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
// delete google agenda event
$rdvEvents = $this->getDoctrine()->getRepository(RdvEvent::class)
->findBy(array('rdv' => $rdv));
//dd($rdvEvents);
$synchronisationCosium = $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
$cosiumCenter = $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium, "center" => $rdv->getIdCentre()]);
if ($cosiumCenter) {
$this->clientCosiumService->deleteRdv($synchronisationCosium, $rdv);
}
foreach ($rdvEvents as $rdvEvent) {
$googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
$googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
$entityManager->remove($rdvEvent);
$entityManager->flush();
}
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => 2]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
$rdv->setCacher(1);
////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$oldDate = $pastDate->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
// notif client
if ($rdv->getIdEtat()->getId() != 2) {
$params = array(
"lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"heure" => substr($smsDate, 11, 15),
"motif" => $rdv->getIdMotif()->getTitre(),
"centerName" => $rdv->getIdCentre()->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"centerPhone" => $rdv->getIdCentre()->getPhone(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"clientEmail" => $client->getMail(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le',
'frenchDate' => $frenchDate
);
$subject = "Rendez-vous My Audio modifié pour " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 205);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
// creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
$subjectMyaudio = "Rendez-vous My Audio a été modifié par l'audioprothésiste " . $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName();
$publicFunction->sendEmail($params, "lead.myaudio@gmail.com", $client->getName() . ' ' . $client->getLastName(), $subjectMyaudio, 206);
}
// //// == suppression
else if ($rdv->getIdEtat()->getId() == 2) {
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}search",
"heure" => substr($smsDate, 11, 15),
"patientName" => $client->getLastName() . ' ' . $client->getName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
"clientEmail" => $client->getMail() ?? '',
"clientPhone" => $client->getPhone() ?? '',
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 188);
$sms = "Votre RDV a été annulé, contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
// creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
$subjectMyaudio = $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " . $client->getName() . ' ' . $client->getLastName();
$publicFunction->sendEmail($params, "lead.myaudio@gmail.com", $client->getName() . ' ' . $client->getLastName(), $subjectMyaudio, 207);
}
//notif Audio
if ($rdv->getIdEtat()->getId() != 2) {
$params = array(
"lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"date" => substr($smsDate, 0, 10),
"frenchDate" => $frenchDate,
"heure" => substr($smsDate, 11, 15),
'motif' => $rdv->getIdMotif()->getTitre(),
'clientPhone' => $client->getPhone(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientCivilite' => $client->getCivilite(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'idPatient' => $client->getId(),
'proUrl' => "{$_ENV['BASE_logiciel']}",
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le :'
);
$subject = "🔀 Rendez-vous My Audio modifié du " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 186);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
} else if ($rdv->getIdEtat()->getId() == 2) {
/* $params = array(
"date" => substr($smsDate, 0, 10),
"lien"=> "{$_ENV['BASE_client']}search",
"heure" =>substr($smsDate, 11, 15),
"patientName" => $client->getLastName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
$sms = "Votre RDV du " . substr($oldDate, 0, 10) . " à " . substr($oldDate, 11, 15) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" . $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
*/
}
// delete sms notification
$rdvSms->deleteAssociatedRdvSms($rdv);
// delete client device
/*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
if($clientDevice)
{
if ($client instanceof Client) {
$nextRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client" => $rdv->getIdClient(),
"id_motif" => ['106', '107', '108', '109']
]);
$client->setClientStatus(null);
} elseif ($client instanceof ClientTemp) {
$nextRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client_temp" => $rdv->getIdClientTemp(),
"id_motif" => ['106', '107', '108', '109']
]);
$client->setClientStatus(null);
}
$locale = 'fr_FR';
$fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
$fmt->setPattern("EEEE dd MMMM yyyy");
if($nextRdvs){
$params = array(
"title" => "Affectation de votre appareil et programmation de vos rendez-vous",
"centerName" => "{$rdv->getIdCentre()->getName()}",
"audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
"centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
"device" => "{$clientDevice->getDevice()->getModel()}",
"ears" => "{$clientDevice->getSettingDevice()->getName()}",
"rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
"rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
"rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
"rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
"rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
"rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
"rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
"rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
);
$publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
}
foreach($nextRdvs as $rdv)
{
$entityManager->remove($rdv);
}
$entityManager->persist($client);
$entityManager->remove($clientDevice);
$entityManager->flush();
}*/
$entityManager->flush();
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_libelle" => $rdv->getIdMotif()->getTitre(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
"fullName" => $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastname(),
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"review" => $rdv->getReview(),
"status" => 200,
])));
}
/**
* @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
*/
public function postRdvCalendar(Request $request, PublicFunction $publicFunction, GoogleCalendarService $googleCalendar, RdvSmsService $rdvSms): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
// makes the rdv
$rdv = new Rdv();
if ($token->getIdAudio()) {
//if the token if for an audio
$audio = $token->getIdAudio();
if ((isset($data["client_id"]))) {
$client = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $data["client_id"]]);
} else {
$client = $this->getDoctrine()
->getRepository(ClientTemp::class)
->findOneBy(['id' => $data["client_id_temp"]]);
}
if ($client == null) {
return new Response(json_encode(([
'message' => 'Error, no client found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} elseif ($token->getIdClient()) {
//if the token if for a client
$client = $token->getIdClient();
/** @var Audio */
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $data["audio_id"]]);
if (isset($data["proche_id"])) {
$proche = $this->getDoctrine()
->getRepository(Proches::class)
->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
}
if ($audio == null) {
return new Response(json_encode(([
'message' => 'Error, no audio found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} else {
return new Response(json_encode(([
'message' => 'Error, token is not an audio token',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdAudio($audio);
if (isset($proche)) {
$rdv->setIdProche($proche);
}
if (isset($data["client_id_temp"])) {
$rdv->setIdClientTemp($client);
} else {
$rdv->setIdClient($client);
}
$rdv->setCacher(0);
/** @var Centre */
if (isset($data["centre_id"])) {
$centre = $this->getDoctrine()
->getRepository(Centre::class)
->findOneBy(['id' => $data["centre_id"]]);
if ($centre == null) {
return new Response(json_encode(([
'message' => 'Error, no centre found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdCentre($centre);
} elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
// tries to set the lieu if it's an audio indie
$lieu = $this->getDoctrine()
->getRepository(Lieu::class)
->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
if ($lieu == null) {
return new Response(json_encode(([
'message' => 'Error, no lieu found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdLieu($lieu);
} else {
return new Response(json_encode(([
'message' => 'Error, no lieu/centre id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var Motif */
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->find($data["motif_id"]);
if ($motif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
// test if the audio is available
/* if (isset($data["lieu_id"]) && $audio->getIsIndie()){
if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
return new Response(json_encode(([
'message' => 'Error, no timestamp found at this time',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} else {
if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
return new Response(json_encode(([
'message' => 'Error, no timestamp found at this time',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}*/
$rdv->setDate($date);
$rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i", date('d/m/Y H:i')));
/** @var EtatRdv */
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
$rdv->setIdMotif($motif);
$rdv->setDuration($data["duree"]);
$rdv->setIsAbsence($data["is_absence"]);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($rdv);
$entityManager->flush();
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
// client notif mail Sms
// we send parametre for the trait methid
//$params = $this->emailNotificationService->prepareEmailParams($user);
// send email notifcation
//$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$params = array(
"lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"prenom" => $client->getName(),
//"heure" => $smsDatee,
'telCentre' => $rdv->getIdCentre()->getPhone(),
"centerName" => $rdv->getIdCentre()->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' . $rdv->getIdCentre()->getPostale() . ' ' . $rdv->getIdCentre()->getCity(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"motif" => $rdv->getIdMotif()->getTitre(),
"RdvDate" => substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15),
"audioName" => $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
"clientMail" => $client->getMail(),
"clientPhone" => $client->getPhone(),
'titre' => "Votre rendez-vous est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15),
"address" => $rdv->getIdCentre()->getAddress(),
"postal" => $rdv->getIdCentre()->getPostale(),
"city" => $rdv->getIdCentre()->getCity(),
"clientEmail" => $client->getMail(),
"clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
"clientAddress" => $client->getAddress(),
"clientPostal" => $client->getPostal(),
"clientCity" => $client->getCity(),
"audioName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
"frenchDate" => $frenchDate,
"heure" => substr($smsDate, 11, 15),
"centerName" => $rdv->getIdCentre()->getName(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
);
$subject = "Rendez-vous My Audio confirmé le " . $smsDateLongFormat;
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 181);
$sms = "Votre RDV est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
// $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
// audio Notif mail SMS
/* $params = array(
"lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
"lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
"date" => substr($smsDate, 0, 10),
"heure" =>substr($smsDate, 11, 15),
'motif' => $rdv->getIdMotif()->getTitre(),
'clientPhone'=> $client->getPhone(),
'clientNom' =>$client->getLastname(),
'clientPrenom' =>$client->getName(),
'clientCivilite' => $client->getCivilite(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'idPatient' => $client->getId(),
'proUrl' => "{$_ENV['BASE_logiciel']}",
'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le :'
);
$subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
$sms = "Vous avez un nouveau RDV le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'aléas contactez votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
// google calendar post
$synchronisations = $this->getDoctrine()->getRepository(SynchronisationSetting::class)
->findBy(array('audio' => $audio->getId()));
$data['rdv'] = $rdv->getId();
$synchronisationCosium = $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
$cosiumCenter = $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium, "center" => $rdv->getIdCentre()]);
if ($cosiumCenter) {
$this->clientCosiumService->createAgenda($synchronisationCosium, $rdv, $cosiumCenter);
}
foreach ($synchronisations as $synchronisation) {
if (!$synchronisation->getIsDeleted()) {
try {
$googleCalendar->checkAndRefreshAccessToken($synchronisation);
$googleCalendar->createEvent($synchronisation, $data);
} catch (\Exception $e) {
error_log('Error refreshing access token or creating event: ' . $e->getMessage());
}
}
}
// create schedule notification sms
$rdvSms->storeRdvSmsNotifications($rdv);
if ($rdv->getClientDevice()) {
$nextRdv = $this->getDoctrine()
->getRepository(Rdv::class)
->find($rdv->getClientDevice()->getRdv()->getId());
if ($nextRdv->getIdClientTemp()) {
$nextRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client_temp" => $nextRdv->getIdClientTemp(),
"id_motif" => ['106', '107', '108', '109']
]);
} else {
$nextRdvs = $this->getDoctrine()
->getRepository(Rdv::class)
->findBy([
"id_client" => $nextRdv->getIdClient(),
"id_motif" => ['106', '107', '108', '109']
]);
}
$mappedNextRdvs = array_map(function ($rdv) {
return [
'id' => $rdv->getId(),
'date' => $rdv->getDate()->format('d-m-Y'),
'hours' => $rdv->getDate()->format('H:i'),
'duration' => $rdv->getDuration(),
"motif_id" => $rdv->getIdMotif()->getId(),
"motif_titre" => $rdv->getIdMotif()->getTitre(),
"duration" => $rdv->getDuration(),
];
}, $nextRdvs);
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"centerName" => $rdv->getIdCentre()->getName(),
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"duration" => $data["duree"],
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
"isClient" => ($client instanceof Client) ? 1 : 0,
"device" => $rdv->getClientDevice() ? [
"isDevice" => true,
"deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
"clientDeviceID" => $rdv->getClientDevice()->getId(),
"deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
"settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
"settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
"settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
"nextRdvs" => $mappedNextRdvs
] : [
"isDevice" => false
],
"comment" => $rdv->getComment(),
"review" => $rdv->getReview(),
"note" => $rdv->getNote(),
"status" => 200,
])));
}
/**
* @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
*/
public function postAbsenceCalendar(Request $request, PublicFunction $publicFunction, GoogleCalendarService $googleCalendar): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
// makes the rdv
$rdv = new Rdv();
$audio = $token->getIdAudio();
$rdv->setIdAudio($audio);
/** @var Centre */
if (isset($data["centre_id"])) {
$centre = $this->getDoctrine()
->getRepository(Centre::class)
->findOneBy(['id' => $data["centre_id"]]);
if ($centre == null) {
return new Response(json_encode(([
'message' => 'Error, no centre found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdCentre($centre);
} elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
// tries to set the lieu if it's an audio indie
$lieu = $this->getDoctrine()
->getRepository(Lieu::class)
->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
if ($lieu == null) {
return new Response(json_encode(([
'message' => 'Error, no lieu found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdLieu($lieu);
} else {
return new Response(json_encode(([
'message' => 'Error, no lieu/centre id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$rdv->setDate($date);
$rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i", date('d/m/Y H:i')));
/** @var EtatRdv */
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
$rdv->setDuration($data["duree"]);
$rdv->setIsAbsence($data["is_absence"]);
$rdv->setMotifAbsence($data["motif"]);
$rdv->setColor($data["color"]);
$rdv->setNote($data["note"]);
$rdv->setCacher(0);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($rdv);
$entityManager->flush();
// create google calendar absence event
$synchronisations = $this->getDoctrine()->getRepository(SynchronisationSetting::class)
->findBy(array('audio' => $audio->getId()));
$data['rdv'] = $rdv->getId();
$data['motif_absence'] = $rdv->getMotifAbsence() !== '' ? $rdv->getMotifAbsence() : "Absence";
// dd($data);
foreach ($synchronisations as $synchronisation) {
if (!$synchronisation->getIsDeleted()) {
try {
$googleCalendar->checkAndRefreshAccessToken($synchronisation);
$googleCalendar->createAbsenceEvent($synchronisation, $data);
} catch (\Google\Service\Exception $e) {
if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
continue;
}
throw $e;
}
}
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"audio_id" => $rdv->getIdAudio()->getId(),
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"duration" => $data["duree"],
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"status" => 200,
])));
}
/**
* @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
*/
public function putAbsenceCalendar(Request $request, Rdv $rdv, PublicFunction $publicFunction, GoogleCalendarService $googleCalendar): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
// remove the taken schedule by rdv to make sure there is no overlap
if (isset($data["date"])) {
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$rdv->setDate($date);
}
if (isset($data["duree"])) {
$rdv->setDuration($data["duree"]);
}
if (isset($data["motif"])) {
$rdv->setMotifAbsence($data["motif"]);
}
if (isset($data["color"])) {
$rdv->setColor($data["color"]);
}
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
$data['rdv'] = $rdv->getId();
$data['motif_absence'] = $rdv->getMotifAbsence() !== '' ? $rdv->getMotifAbsence() : "Absence";
$data['note'] = $rdv->getNote();
$rdvEvents = $this->getDoctrine()->getRepository(RdvEvent::class)
->findBy(array('rdv' => $rdv));
foreach ($rdvEvents as $rdvEvent) {
$googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
$googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"audio_id" => $rdv->getIdAudio()->getId(),
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"duration" => $rdv->getDuration(),
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"status" => 200,
])));
}
/**
* @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
*/
public function editRdvCalendarByID(SmsHandler $smsHandler, Rdv $rdv, Request $request, GoogleCalendarService $googleCalendar, PublicFunction $publicFunction, RdvSmsService $rdvSms): Response
{
$pastDate = $rdv->getDate();
$data = json_decode($request->getContent(), true);
$entityManager = $this->getDoctrine()->getManager();
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
return new Response(json_encode([
"message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
"status" => 404,
]), 404);
}
if (isset($data["etat_id"])) {
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
}
if (isset($data["audio_id"])) {
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $data["audio_id"]]);
if ($audio == null) {
return new Response(json_encode(([
'message' => 'Error, no audio found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdAudio($audio);
}
if (isset($data["motif_id"])) {
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->find($data["motif_id"]);
if ($motif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdMotif($motif);
}
if (isset($data["client_id"])) {
$client = $this->getDoctrine()
->getRepository(Client::class)
->findOneBy(['id' => $data["client_id"]]);
if ($client == null) {
return new Response(json_encode(([
'message' => 'Error, no client found at this id',
'path' => 'src/Controller/TrustedUserController.php',
"status" => 400,
])), 400);
}
$rdv->setIdClient($client);
}
if (isset($data["date"])) {
// remove the taken schedule by rdv to make sure there is no overlap
$date = \DateTime::createFromFormat("d/m/Y H:i", $data["date"]);
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($rdv->getIdAudio()->getIsIndie()) {
if ($rdv->getIdCentre()) {
// regular centre audio indie
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
} else {
// lieu audio indie
if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}
} else {
// regular centre
if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
return new Response(json_encode(([
'message' => 'Error, no horaire found for this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
}
$rdv->setDate($date);
}
if (isset($data["comment"]) && $token->getIdClient()) {
$rdv->setComment($data["comment"]);
}
if (isset($data["review"]) && $token->getIdClient()) {
$rdv->setReview($data["review"]);
}
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
$entityManager->flush();
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$oldDate = $pastDate->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
// notif client
if ($rdv->getIdEtat()->getId() != 2) {
$params = array(
"lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"heure" => substr($smsDate, 11, 15),
"motif" => $rdv->getIdMotif()->getTitre(),
"centerName" => $rdv->getIdCentre()->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"centerPhone" => $rdv->getIdCentre()->getPhone(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le',
'frenchDate' => $frenchDate,
);
$subject = "Rendez-vous My Audio modifié pour " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 184);
if ($data["sms"]) {
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
}
}
// //// == suppression
else if ($rdv->getIdEtat()->getId() == 2) {
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}search",
"heure" => substr($smsDate, 11, 15),
"patientName" => $client->getLastName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 188);
if ($data["sms"]) {
$sms = "Votre RDV a été annulé, contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
}
}
//notif Audio
if ($rdv->getIdEtat()->getId() != 2) {
if ($data["sms"]) {
$params = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"date" => substr($smsDate, 0, 10),
"frenchDate" => $frenchDate,
"heure" => substr($smsDate, 11, 15),
'motif' => $rdv->getIdMotif()->getTitre(),
'clientPhone' => $client->getPhone(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientCivilite' => $client->getCivilite(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'idPatient' => $client->getId(),
'proUrl' => "{$_ENV['BASE_logiciel']}",
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'titre' => 'Votre rendez-vous est modifié pour le :'
);
$subject = "🔀 Rendez-vous My Audio modifié du " . $frenchDate . " à " . substr($smsDate, 11, 15);
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 186);
$sms = "Votre RDV est modifié pour le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
}
} else if ($rdv->getIdEtat()->getId() == 2) {
if ($data["sms"]) {
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}search",
"heure" => substr($smsDate, 11, 15),
"patientName" => $client->getLastName(),
'titre' => 'Votre rendez-vous est annulé :',
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerPhone' => $rdv->getIdCentre()->getPhone(),
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'audioMail' => $rdv->getIdAudio()->getMail(),
'motif' => $rdv->getIdMotif()->getTitre(),
);
$subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(), $subject, 188);
$sms = "Votre RDV du " . substr($oldDate, 0, 10) . " à " . substr($oldDate, 11, 15) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" . $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
}
}
/* generate sms notif on update */
// update sms notification
$rdvSms->updateRdvSms($rdv);
// google calendar update
$synchronisations = $this->getDoctrine()->getRepository(SynchronisationSetting::class)
->findBy(array('audio' => $rdv->getIdAudio()));
$data['rdv'] = $rdv->getId();
$data['motif_id'] = $rdv->getIdMotif();
$data['note'] = $rdv->getNote();
if ($rdv->getIdClient() !== null) {
$data["client_id"] = $rdv->getIdClient()->getId();
}
if ($rdv->getIdClientTemp() !== null) {
$data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
}
$rdvEvents = $this->getDoctrine()->getRepository(RdvEvent::class)
->findBy(array('rdv' => $rdv));
foreach ($rdvEvents as $rdvEvent) {
$googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
$googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"audio_id" => $rdv->getIdAudio()->getId(),
"remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
"imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
"fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}" : "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"centre_id" => $rdv->getIdCentre()->getId(),
"centerName" => $rdv->getIdCentre()->getName(),
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"note" => $rdv->getNote(),
"review" => $rdv->getReview(),
"status" => 200,
])));
}
/**
* @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
*/
public function deletetAbsenceCalendar(Request $request, Rdv $rdv, GoogleCalendarService $googleCalendar): Response
{
$data = json_decode($request->getContent(), true);
if (!isset($data["token"])) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
$entityManager = $this->getDoctrine()->getManager();
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data["token"]]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
// delete google agenda event
$rdvEvents = $this->getDoctrine()->getRepository(RdvEvent::class)
->findBy(array('rdv' => $rdv));
//dd($rdvEvents);
foreach ($rdvEvents as $rdvEvent) {
$googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
$googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
$entityManager->remove($rdvEvent);
$entityManager->flush();
}
$entityManager->remove($rdv);
$entityManager->flush();
return new Response(json_encode(([
"message" => "Absence Supprime",
"status" => 200,
])));
}
/**
* @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
*/
public function getMyRDV(Request $request): Response
{
/* $date = new DateTime();
$minutes_to_add = 10;
$date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$date->setTimezone(new DateTimeZone('Europe/Paris'));
$currentDate = $date->format('Y-m-d H:i:00');
$toSend = $this->getDoctrine()->getRepository(Rdv::class)
->findRdvsIn10Mins($currentDate);
*/
}
/**
* @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
*/
public function getMyLead(Request $request): Response {}
/**
* @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
*/
public function getRdvCount(Request $request): Response
{
$rdvs = $this->getDoctrine()->getRepository(Rdv::class)->findAll();
return new Response(count($rdvs));
}
/**
* @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
*/
public function updateRelance(Request $request, LeadRdv $lead, EntityManagerInterface $em): JsonResponse
{
$data = json_decode($request->getContent(), true);
$relanceCount = $data['relanceCount'] ?? null;
if ($relanceCount !== null) {
$lead->setRelanceCallCount((int)$relanceCount);
$em->flush();
return new JsonResponse(['success' => true]);
}
return new JsonResponse(['success' => false], 400);
}
/**
* @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
*/
public function postLeadRdv(Request $request, EntityManagerInterface $entityManager, PublicFunction $publicFunction, GoogleCalendarService $googleCalendar): Response
{
$data = json_decode($request->getContent(), true);
$today = new DateTime();
try {
$client = null;
// Gestion du client via token ou création
if (!empty($data['clientToken'])) {
$token = $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
$client = $token ? $token->getIdClient() : null;
} elseif (!empty($data['client'])) {
$clientData = $this->createOrGetClient($data['client']);
$client = $entityManager->getRepository(Client::class)->find($clientData['id']);
}
if (!$client) {
return $this->json(["status" => 400, "message" => "Client non trouvé ou invalide"], 400);
}
// Création du rendez-vous LeadRdv
$rdvLead = new LeadRdv();
$rdvLead->setClient($client);
if (isset($data['titleLead'])) {
$rdvLead->setTitleLead($data['titleLead']);
}
if (isset($data['rangeAge'])) {
$rdvLead->setRangeAge($data['rangeAge']);
}
if (isset($data['situations'])) {
$rdvLead->setSituationsGene($data['situations']);
}
if (isset($data['equipe'])) {
$rdvLead->setEquipeAppareil($data['equipe']);
}
if (isset($data['durationEquipe'])) {
$rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
}
if (isset($data['bilanAuditif'])) {
$rdvLead->setBilanAuditif($data['bilanAuditif']);
}
if (isset($data['ordonance'])) {
$rdvLead->setOrdonance($data['ordonance']);
}
if (isset($data['dateOrdonance'])) {
$rdvLead->setDateOrdonance($data['dateOrdonance']);
}
if (isset($data['canMove'])) {
$rdvLead->setCanMove($data['canMove']);
}
if (isset($data['traffic_source'])) {
$rdvLead->setTrafficSource($data['traffic_source']);
}
if (isset($data['article_name'])) {
$rdvLead->setTrafficLpVersion($data['article_name']);
}
if (isset($data['lp_version'])) {
$rdvLead->setTrafficArticleName($data['lp_version']);
}
if (isset($data['isNewLp'])) {
$rdvLead->setIsNewLp($data['isNewLp']);
$leadStatus = $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
if ($leadStatus) {
$rdvLead->setLeadStatus($leadStatus);
}
}
$rdvLead->setDate($today);
if (!empty($data['audio'])) {
$audio = $entityManager->getRepository(Audio::class)->find($data['audio']);
if ($audio) {
$rdvLead->setAudio($audio);
}
}
if ($client->getPostal()) {
$centerCount = $this->getMatchingCentresCount($client->getPostal());
$rdvLead->setCentersCount($centerCount);
if ($centerCount == 0) {
$leadStatus = $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
if ($leadStatus) {
$rdvLead->setLeadStatus($leadStatus);
}
}
}
// Création du Token
$tokenString = $publicFunction->generateRandomString(30);
$token = (new Token())
->setCreationDate(new DateTime())
->setToken($tokenString)
->setIdClient($client);
$entityManager->persist($rdvLead);
$entityManager->persist($token);
$entityManager->flush();
return $this->json([
"id" => $client->getId(),
"idRdvLead" => $rdvLead->getId(),
"name" => $client->getName(),
"lastname" => $client->getLastname(),
"token" => $tokenString,
"code" => $clientData['password'],
"postalCode" => $client->getPostal() ?? null,
"status" => 200,
]);
} catch (\Exception $e) {
return $this->json(["status" => 500, "message" => $e->getMessage()], 500);
}
}
/**
* @Route("/lead/new/test", name="postLeadRdv_test", methods={"GET", "POST"})
*/
/* public function newLead(
ElevenLabsService $elevenLabs,
TwilioService $twilio
): Response {
$leadPhone = '+33611879183';
$aircallRedirect = '+33743393532';
$audioPath = $this->getParameter('kernel.project_dir') . '/public/assets/audio/message-client.mp3';
if (!file_exists($audioPath)) {
$elevenLabs->generateVoice(
"Bonjour ! Suite à votre demande, un expert va vous rappeler dans quelques instants pour répondre à votre besoin. Restez disponible, l’appel va commencer !",
$audioPath
);
}
$twilio->callLead($leadPhone, "https://fed6-2a01-cb1d-3ac-ef00-9414-9245-af3d-ef55.ngrok-free.app/twilio/message", $aircallRedirect);
return new Response('Lead traité, appel lancé.');
}
*/
/**
* @Route("/twilio/message", name="twilio_message", methods={"GET", "POST"})
*/
/*
public function message(): Response
{
$forwardTo = $_GET['forwardTo'] ?? '';
$twiml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>https://fed6-2a01-cb1d-3ac-ef00-9414-9245-af3d-ef55.ngrok-free.app/assets/audio/message-client.mp3</Play>
<Dial timeout="20">{$forwardTo}
</Dial>
</Response>
XML;
return new Response($twiml, 200, ['Content-Type' => 'text/xml']);
}
*/
/**
* Private method to create a new client or get existing one by phone
*/
private function createOrGetClient(array $data): array
{
$clientRepository = $this->entityManager->getRepository(Client::class);
// check sur le mail et phone
$existingClient = $clientRepository->findOneBy(['mail' => $data['email']]);
if ($existingClient) {
if ($existingClient->getPostal() !== $data['postalCode']) {
$existingClient->setPostal($data['postalCode']);
$this->entityManager->persist($existingClient);
$this->entityManager->flush();
}
return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
}
$randomPassword = $this->generateRandomPassword(12);
$client = new Client();
$client->setLastname($data['lastname']);
$client->setBirthdate(null);
$client->setName($data['firstname']);
$client->setPhone($data['phone']);
$client->setMail($data['email']);
$client->setSignupDate(new \DateTime());
$client->setPassword(password_hash($randomPassword, PASSWORD_DEFAULT));
$client->setPostal($data['postalCode']);
$client->setAddress($data['address'] ?? null);
$client->setCity($data['city'] ?? null);
$client->setDesactivate(false);
if (isset($data['civilite'])) {
$civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' : 'Madame';
$client->setCivilite($civilite);
}
$this->entityManager->persist($client);
$this->entityManager->flush();
return ['id' => $client->getId(), 'password' => $randomPassword];
}
private function generateRandomPassword($length = 10): string
{
return bin2hex(random_bytes($length / 2));
}
private function getMatchingCentresCount($clientPostal): int
{
// Récupérer les coordonnées GPS du code postal du client
$clientCoordinates = $this->entityManager
->getRepository(RegionDepartment::class)
->findOneBy(['codePostal' => $clientPostal]);
$clientLat = $clientCoordinates ? $clientCoordinates->getLatitude() : null;
$clientLon = $clientCoordinates ? $clientCoordinates->getLongitude() : null;
$centres = $this->entityManager->getRepository(Centre::class)->findAll();
$count = 0;
foreach ($centres as $centre) {
if ($centre->getZoneKm()) {
$latitude = $centre->getLatitude();
$longitude = $centre->getLongitude();
$radius = $centre->getZoneKm();
$postals = $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude, $longitude, $radius);
$postalCodes = array_values(array_unique(array_column($postals, 'code_postal')));
if (in_array($clientPostal, $postalCodes)) {
$count++;
}
}
}
return $count;
}
/**
* @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
*/
public function sendEmailWithMap(Request $request, PublicFunction $publicFunction): Response
{
$data = json_decode($request->getContent(), true);
$mail = "";
$name = "";
$centre = "";
if (isset($data['clientToken'])) {
$token = $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
$client = $token->getIdClient();
$mail = $client->getMail();
$name = $client->getLastname() . " " . $client->getName();
$centre = $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
} else {
$mail = $data['email'];
$name = $data['name'];
}
$locale = 'fr_FR';
$dateTime = DateTime::createFromFormat('d/m/Y H:i', $data['date']);
if ($dateTime) {
$fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
$fmt->setPattern("EEEE dd MMMM");
$formattedDate = ucfirst($fmt->format($dateTime));
} else {
$formattedDate = "Date invalide";
}
$params = [
'date' => $data['date'],
'time' => $data['time'],
'frenchDate' => $formattedDate,
'clientAddress' => $data['address'],
'centerName' => $centre->getName(),
'centerAddress' => $centre->getAddress(),
'centerPostal' => $centre->getPostale(),
'centerCity' => $centre->getCity(),
'start' => $data['start'],
'end' => $data['end'],
'urlApi' => "{$_ENV['BASE_client']}",
];
$publicFunction->sendEmail($params, $mail, $name, "Votre Rendez-vous My Audio", 198);
return new Response(json_encode([
"status" => 200,
"params" => $params,
]), 200, ['Content-Type' => 'application/json']);
}
/**
* @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
*/
public function notifCantMove(Request $request, PublicFunction $publicFunction): Response
{
$data = json_decode($request->getContent(), true);
$email = "lead.myaudio@gmail.com";
$centre = "";
$type = "My Audio";
$details = "";
$picto = "❌";
$ordo = "sans ordo";
$subject = "";
if (isset($data['ordonance'])) {
if ($data["ordonance"] == "oui") {
$ordo = "avec ordo";
}
} else {
$ordo = "";
}
if (isset($data['centre'])) {
$centre = $data['centre'];
$subject = $picto . " Lead - demande de contact ne pouvant pas se déplacer " . $data['postal'] . " " . $ordo;
} else {
$centre = "";
$type = "Hors Zone";
$details = "Pas de centre dans la zone";
$subject = $picto . " Lead Hors Zone " . $data['postal'] . " " . $ordo . " ne pouvant pas se déplacer";
}
$responses = [
'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
'situations' => isset($data['situations']) ? $data['situations'] : null,
'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
];
$department = $this->getDepartmentFromPostalCode($data['address']);
$data['departmentCode'] = $department['departmentCode'];
$data['departmentName'] = $department['departmentName'];
$data['regionName'] = $department['regionName'];
$data['city'] = $department['city'];
$params = [
'date' => $data['date'],
'time' => $data['time'],
'address' => $data['address'],
'centre' => $centre,
'type' => $type,
'details' => $details,
'responses' => $responses,
'name' => $data['name'],
'civilite' => $data['civilite'],
'nom' => $data['firstname'],
'prenom' => $data['lastname'],
'codePostal' => $data['address'],
'telephone' => $data['phone'],
'email' => $data['email'],
'departement' => $data['departmentName'],
'ville' => $data['city'],
'region' => $data['regionName'],
'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
'situationVecu' => isset($data['situations']) ? implode(', ', $data['situations']) : null,
'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
];
$publicFunction->sendEmail($params, $email, $data['name'], $subject, 208);
return new Response(json_encode([
"status" => 200,
]), 200, ['Content-Type' => 'application/json']);
}
/**
* @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
*/
public function notifCantMoveV2(Request $request, PublicFunction $publicFunction): Response
{
$data = json_decode($request->getContent(), true);
$email = "lead.myaudio@gmail.com";
$centre = "";
$type = "My Audio";
$details = "";
$picto = "❌";
$subject = "";
$audio = "";
$subject = $picto . " Lead ne pouvant pas se déplacer";
$department = $this->getDepartmentFromPostalCode($data['address']);
$data['departmentCode'] = $department['departmentCode'];
$data['departmentName'] = $department['departmentName'];
$data['regionName'] = $department['regionName'];
$data['city'] = $department['city'];
$password = "";
$params = [
'name' => $data['name'],
'civilite' => $data['civilite'],
'nom' => $data['firstname'],
'prenom' => $data['lastname'],
'codePostal' => $data['address'],
'telephone' => $data['phone'],
'email' => $data['email'],
'password' => $data['clientSecretCookie'],
'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
'situationVecu' => isset($data['situations']) ? implode(', ', $data['situations']) : null,
'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
'urlLogin' => "{$_ENV['BASE_client']}login"
];
// Send email to MyAudio
$publicFunction->sendEmail($params, $email, $data['name'], $subject, 220);
$publicFunction->sendEmail($params, 'mickael.aubard@myaudio.fr"', $data['name'], $subject, 220);
// Send email to patient
$params = [
'clientEmail' => $data['email'],
'clientPassword' => $data['clientSecretCookie'],
'rdv' => "https://www.myaudio.fr/search",
'urlLogin' => "{$_ENV['BASE_client']}login"
];
$publicFunction->sendEmail($params, $data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement', 219);
$rdvLead = $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
if ($rdvLead) {
$leadStatus = $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
if ($leadStatus) {
$rdvLead->setLeadStatus($leadStatus);
$this->entityManager->flush();
}
}
return new Response(json_encode([
"status" => 200,
]), 200, ['Content-Type' => 'application/json']);
}
/**
* @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
*/
public function notifLeadRdv(Request $request, PublicFunction $publicFunction): Response
{
$data = json_decode($request->getContent(), true);
$email = "lead.myaudio@gmail.com";
$centre = "";
$type = "My Audio";
$details = "";
$picto = "❌";
$ordo = "sans ordo";
$subject = "";
$name = "";
$postal = "";
$emailPatient = "";
if (isset($data['clientToken']) && !empty($data['clientToken'])) {
$token = $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
$client = $token->getIdClient();
$name = $client->getLastname() . " " . $client->getName();
$postal = $client->getPostal();
$emailPatient = $client->getMail();
} else {
if (isset($data['postal'])) {
$postal = $data['postal'];
}
if (isset($data['name'])) {
$name = $data['name'];
}
if (isset($data['email'])) {
$email = $data['email'];
}
if (isset($data['email'])) {
$emailPatient = $data['email'];
}
}
if (isset($data["ordonance"])) {
if ($data["ordonance"] == "oui") {
$ordo = "avec ordo";
}
}
if (isset($data['centre'])) {
$centre = $data['centre'];
$picto = "✅";
$subject = $picto . " Lead booké " . $postal . " " . $ordo;
} else {
$centre = "";
$type = "Hors Zone";
$details = "Pas de centre dans la zone";
$subject = $picto . " Lead Hors Zone " . $postal . " " . $ordo;
}
$responses = [
'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
'situations' => isset($data['situations']) ? $data['situations'] : null,
'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
];
$params = [
'date' => $data['date'],
'time' => $data['time'],
'address' => $data['address'],
'centre' => $centre,
'type' => $type,
'details' => $details,
'responses' => $responses,
'name' => $name,
'email' => $emailPatient,
];
$publicFunction->sendEmail($params, $email, $name, $subject, 180);
return new Response(json_encode([
"status" => 200,
"params" => $params,
"responses" => $responses
]), 200, ['Content-Type' => 'application/json']);
}
/**
* Met à jour l'état d'un rendez-vous.
*
* Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
* via une requête PUT. Elle effectue plusieurs vérifications, notamment :
* - La présence et la validité du token d'authentification.
* - L'existence du rendez-vous et du nouvel état.
* - L'expiration du token (plus de 7 jours).
*
* Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
* au client et à l'équipe MyAudio pour les informer.
*
* @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
*/
public function saveEtatRdv(Request $request, PublicFunction $publicFunction): Response
{
$entityManager = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent(), true);
if (!$data['token']) {
return new Response(json_encode([
"message" => "Pas de token n'a été spécifié",
"status" => 401,
]), 401);
}
/** @var Token */
$token = $this->getDoctrine()
->getRepository(Token::class)
->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
if (!$token) {
return new Response(json_encode([
"message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
"status" => 404,
]), 404);
}
// get token age
$dateDiff = $token->getCreationDate()->diff(new DateTime());
// if the token if older than 7 days
if ($dateDiff->d > 7) {
$entityManager->remove($token);
$entityManager->flush();
return $this->json([
'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
'path' => 'src/Controller/ClientController.php',
"status" => 401,
], 401);
}
$rdv = $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
if (!$rdv) {
return new Response(json_encode([
"message" => "Rdv not found.",
"status" => 404,
]), 404);
}
$rdvEtat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->find($data['etat']);
if (!$rdvEtat) {
return new Response(json_encode([
"message" => "Rdv etat not found.",
"status" => 404,
]), 404);
}
$rdv->setIdEtat($rdvEtat);
$entityManager->flush();
$encodedNomDuCentre = rawurlencode($rdv->getIdCentre()->getName());
$urlApi = "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
if ($rdvEtat->getId() == 3) {
// Send email to client
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}" . $urlApi,
"heure" => substr($smsDate, 11, 15),
'centerName' => $rdv->getIdCentre()->getName() ?? '',
'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName() ?? '',
'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
);
$subject = "Vous avez manqué votre rendez-vous MyAudio avec " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 214);
// Send sms to client
$sms = "Vous avez manqué un RDV My Audio le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . " dans votre centre auditif. Contactez le centre dès que possible : " . $rdv->getIdCentre()->getPhone();
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
// Send email to MyAudio
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$params = array(
"date" => substr($smsDate, 0, 10),
"lien" => "{$_ENV['BASE_client']}search",
"heure" => substr($smsDate, 11, 15),
'centerName' => $rdv->getIdCentre()->getName() ?? '',
'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName() ?? '',
'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
'clientName' => $client->getName() . ' ' . $client->getLastName() ?? '',
'clientMail' => $client->getMail() ?? '',
'clientPhone' => $client->getPhone() ?? '',
);
$subject = "Le patient " . $client->getName() . ' ' . $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " . $rdv->getIdCentre()->getName();
$publicFunction->sendEmail($params, "lead.myaudio@gmail.com", $client->getName() . ' ' . $client->getLastName(), $subject, 215);
}
return new Response(json_encode([
"message" => "rdvEtat has been successfully updated",
"status" => 200,
]));
}
/**
*
* @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
*/
public function askToContact(Request $request, PublicFunction $publicFunction): Response
{
$data = json_decode($request->getContent(), true);
$staticToken = "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
$token = $data['token'] ?? null;
if ($token !== $staticToken) {
return new JsonResponse(
[
'status' => 'error',
'code' => 'unauthorized',
'message' => 'Unauthorized access.'
],
JsonResponse::HTTP_UNAUTHORIZED
);
}
$params = [
'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
'clientMail' => isset($data['email']) ? $data['email'] : null,
'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
'situations' => isset($data['situations']) ? implode(', ', $data['situations']) : null,
'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
];
$templateEmailMyAudio = 223;
if (!empty($data['centre'])) {
$centre = $data['centre'];
$audio = $centre['audio'][0];
$params['centerName'] = $centre['name'] ?? null;
$params['centerPostal'] = $centre['postale'] ?? null;
$params['centerCity'] = $centre['city'] ?? null;
$params['centerAddress'] = $centre['address'] ?? null;
$params['centerPhone'] = $centre['phone'] ?? null;
$params['audioproName'] = $audio['civilite'] . ' ' . $audio['lastname'] . ' ' . $audio['name'] ?? null;
$templateEmailMyAudio = 222;
}
// Email to My Audio
$email = "lead.myaudio@gmail.com";
$subject = "Demande de contact - Nouveau Lead À Contacter Hors Zone";
$publicFunction->sendEmail($params, $email, $data['name'], $subject, $templateEmailMyAudio);
$publicFunction->sendEmail($params, 'mickael.aubard@myaudio.f', $data['name'], $subject, $templateEmailMyAudio);
$coordinates = $this->getCoordinatesFromPostalCode($data['postalCode']);
$latitude = $coordinates['latitude'];
$longitude = $coordinates['longitude'];
$params = [
'email' => isset($data['email']) ? $data['email'] : null,
'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
"lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
];
// Email to Client
$subject = "My Audio - Confirmation de demande de contact";
$publicFunction->sendEmail($params, $data['email'], $data['name'], $subject, 221);
$sms = "Votre demande validée ! Un spécialiste vous répondra rapidement et vous orientera vers un centre auditif proche. Contactez-nous au 01.89.71.61.09";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $data['phone']);
if (isset($data['clientRdvLp'])) {
$rdvLead = $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
if ($rdvLead) {
$rdvLead->setSendAskToContact(1);
$rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
$this->entityManager->flush();
$this->sendWhatsApp($data, $rdvLead);
}
}
return new Response(json_encode([
"message" => "Email ask for contact send with success",
"status" => 200,
]));
}
private function sendWhatsApp($data, $lead): void
{
$adminUrl = $this->adminUrlGenerator
->setDashboard(DashboardController::class)
->setController(LeadRdvCrudController::class)
->setAction('detail')
->setEntityId($lead->getId())
->generateUrl();
$relativeUrl = parse_url($adminUrl, PHP_URL_PATH) . '?' . parse_url($adminUrl, PHP_URL_QUERY);
// Supprimer le slash en trop s’il y en a un au début
$relativeUrl = ltrim($relativeUrl, '/');
// 🧑🤝🧑 Tableau des destinataires
$destinataires = [
'33611879183', // Numéro 1
'33667597626', // Numéro 2
'447884128220', // Numéro 3
];
foreach ($destinataires as $numero) {
$this->whatsapp->sendTemplateMessage(
$numero, // Numéro de téléphone du destinataire
'lead_notif_myaudio', // Nom du template WhatsApp
[
'body' => [
['parameter_name' => 'nom_client', 'text' => $data['firstname'] . ' ' . $data['lastname']], // {{nom_client}}
['parameter_name' => 'email_client', 'text' => $data['email'] ?? ' '], // {{email_client}}
['parameter_name' => 'telephone_client', 'text' => $data['phone'] ?? ' '], // {{telephone_client}}
['parameter_name' => 'date_lead', 'text' => $lead->getDate()->format('d/m/Y H:i')], // {{date_lead}}
['parameter_name' => 'code_postal', 'text' => $data['postalCode'] ?? ' '], // {{code_postal}}
['parameter_name' => 'nombre_centres', 'text' => $lead->getCentersCount() ?? '0'], // {{nombre_centres}}
],
'button' => $relativeUrl, // <--- seulement le chemin dynamique
]
);
}
}
/**
* Get coordinates from the postal code using the database.
*/
private function getCoordinatesFromPostalCode(string $postalCode): array
{
$region = $this->entityManager
->getRepository(RegionDepartment::class)
->findOneBy(['codePostal' => $postalCode]);
if ($region) {
return [
'latitude' => $region->getLatitude(),
'longitude' => $region->getLongitude(),
];
}
return [
'latitude' => null,
'longitude' => null,
];
}
/**
* Get the department code from the code postal
*/
private function getDepartmentFromPostalCode(string $postalCode): ?array
{
$region = $this->entityManager
->getRepository(RegionDepartment::class)
->findOneBy(['codePostal' => $postalCode]);
if ($region) {
return [
'departmentCode' => $region->getCodeDepartement(),
'departmentName' => $region->getNomDepartement(),
'regionCode' => $region->getCodeRegion(),
'regionName' => $region->getNomRegion(),
'city' => $region->getNomCommunePostal(),
];
}
return null;
}
/**
*
* @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
*/
public function showLeadCentre(int $leadId, Centre $centreId): Response
{
// dd("tets");
$center = $centres = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $centreId->getId()]);
$audio = $center->getIdAudio();
$motifs = $this->getDoctrine()->getRepository(AudioMotif::class)
->findBy(['id_audio' => $audio, 'isDeleted' => 0]);
return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
'audio' => $audio,
'leadId' => $leadId,
'centreId' => $centreId,
'motifs' => $motifs,
]);
}
/**
* @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
*/
public function postRdvEasyAdmin(Request $request, PublicFunction $publicFunction, GoogleCalendarService $googleCalendar, RdvSmsService $rdvSms): Response
{
$data = json_decode($request->getContent(), true);
$entityManager = $this->getDoctrine()->getManager();
$audio = $this->getDoctrine()
->getRepository(Audio::class)
->findOneBy(['id' => $data["audio_id"]]);
$leadRdv = $this->getDoctrine()->getRepository(LeadRdv::class)
->find($data["lead_id"]);
$client = $this->getDoctrine()->getRepository(Client::class)
->find($leadRdv->getClient());
$responses = [
'rangeAge' => $leadRdv->getRangeAge(),
'situations' => implode(", ", $leadRdv->getSituationsGene()),
'equipeAppareil' => $leadRdv->getEquipeAppareil(),
'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
'bilanAuditif' => $leadRdv->getBilanAuditif(),
'ordonance' => $leadRdv->getOrdonance(),
'dateOrdonance' => $leadRdv->getDateOrdonance(),
'canMove' => $leadRdv->getCanMove(),
];
// makes the rdv
$rdv = new Rdv();
$rdv->setIdAudio($audio);
if (isset($proche)) {
$rdv->setIdProche($proche);
}
if (isset($data["client_id_temp"])) {
$rdv->setIdClientTemp($client);
} else {
$rdv->setIdClient($client);
}
$rdv->setIsMyaudio(true);
if (isset($data["isRdvLead"])) {
$rdv->setIsRdvLp(true);
}
if (isset($data["isRdvRapide"])) {
$rdv->setIsRdvRapide(true);
}
if (isset($data["duree"])) {
$rdv->setDuration($data["duree"]);
}
if (isset($data["color"])) {
$rdv->setColor($data["color"]);
}
/** @var Centre */
if (isset($data["centre_id"])) {
$centre = $this->getDoctrine()
->getRepository(Centre::class)
->findOneBy(['id' => $data["centre_id"]]);
if ($centre == null) {
return new Response(json_encode(([
'message' => 'Error, no centre found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioCentre */
$liaison = $this->getDoctrine()
->getRepository(AudioCentre::class)
->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
if ($liaison == null) {
return new Response(json_encode(([
'message' => 'Error, audio isnt part of the centre',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdCentre($centre);
} elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
// tries to set the lieu if it's an audio indie
$lieu = $this->getDoctrine()
->getRepository(Lieu::class)
->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
if ($lieu == null) {
return new Response(json_encode(([
'message' => 'Error, no lieu found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdLieu($lieu);
} else {
return new Response(json_encode(([
'message' => 'Error, no lieu/centre id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var Motif */
$motif = $this->getDoctrine()
->getRepository(Motif::class)
->find($data["motif_id"]);
if ($motif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
/** @var AudioMotif */
$audioMotif = $this->getDoctrine()
->getRepository(AudioMotif::class)
->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
if ($audioMotif == null) {
return new Response(json_encode(([
'message' => 'Error, no motif of this id found at this audio',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
// remove the taken schedule by rdv to make sure there is no overlap
$data["date"] = str_replace("h", ":", $data["date"]);
$date = \DateTime::createFromFormat("Y-m-d\TH:i", $data["date"]);
if (isset($data["note"])) {
$rdv->setNote($data["note"]);
}
$date = \DateTime::createFromFormat("Y-m-d\TH:i", $data["date"]);
$rdv->setDate($date);
$rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i", date('d/m/Y H:i')));
/** @var EtatRdv */
$etat = $this->getDoctrine()
->getRepository(EtatRdv::class)
->findOneBy(['id' => $data["etat_id"]]);
if ($etat == null) {
return new Response(json_encode(([
'message' => 'Error, no etat found at this id',
'path' => 'src/Controller/RdvController.php',
"status" => 400,
])), 400);
}
$rdv->setIdEtat($etat);
$rdv->setIdMotif($motif);
$rdv->setIsAbsence(0);
$rdv->setCacher(0);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($rdv);
$leadRdv->setRdv($rdv);
$leadStatus = $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
$leadRdv->setLeadStatus($leadStatus);
$entityManager->flush();
/// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
$date = $rdv->getDate();
$smsDate = $date->format('d-m-Y H:i');
$locale = 'fr_FR';
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
null,
IntlDateFormatter::GREGORIAN,
'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
);
$smsDateLongFormat = $formatter->format($date);
$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
$client->setIdCentre($rdv->getIdCentre());
$client->setIdAudio($rdv->getIdAudio());
$entityManager->persist($client);
$entityManager->flush();
// client notif mail Sms
$frenchDate = preg_replace('/^(\w+\s\d+\s\w+).+$/u', '$1', $smsDateLongFormat);
$frenchDate = ucfirst($frenchDate);
$params = array(
"lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
"lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
"date" => $smsDateLongFormat,
"RdvDate" => $smsDateLongFormat,
'telCentre' => $rdv->getIdCentre()->getPhone(),
"centerName" => $rdv->getIdCentre()->getName(),
"prenom" => $client->getName(),
"centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' . $rdv->getIdCentre()->getPostale() . ' ' . $rdv->getIdCentre()->getCity(),
"centerPostalCode" => $rdv->getIdCentre()->getPostale(),
'motif' => $rdv->getIdMotif()->getTitre(),
"centerCity" => $rdv->getIdCentre()->getCity(),
"audioName" => $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
'titre' => "Votre rendez-vous est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15),
"position" => $rdv->getIdCentre()->getAddress() . ' ' . $rdv->getIdCentre()->getPostale() . ' ' . $rdv->getIdCentre()->getCity(),
"address" => $rdv->getIdCentre()->getAddress(),
"postal" => $rdv->getIdCentre()->getPostale(),
"city" => $rdv->getIdCentre()->getCity(),
"clientEmail" => $client->getMail(),
"clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
"clientAddress" => $client->getAddress(),
"clientPostal" => $client->getPostal(),
"clientCity" => $client->getCity(),
"audioName" => $rdv->getIdAudio()->getCivilite() . " " . $rdv->getIdAudio()->getName() . " " . $rdv->getIdAudio()->getLastName(),
"frenchDate" => $frenchDate,
"heure" => substr($smsDate, 11, 15),
"centerName" => $rdv->getIdCentre()->getName(),
"audioMail" => $rdv->getIdAudio()->getMail(),
"modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
);
$paramsPatient = $params;
$isNew = false;
if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
$subject = "✅Rendez-vous My Audio confirmé le " . $smsDateLongFormat;
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 189);
$isNew = true;
} else {
$subject = "Rendez-vous My Audio confirmé le " . $smsDateLongFormat;
$publicFunction->sendEmail($params, $client->getMail(), $client->getName() . ' ' . $client->getLastName(), $subject, 181);
}
$sms = "Votre RDV est validé le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'imprévu contacter votre centre " . $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
// audio Notif mail SMS
$birthday = $rdv->getIdClient()->getBirthdate();
$params = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"date" => substr($smsDate, 0, 10),
"heure" => substr($smsDate, 11, 15),
"mail" => $client->getMail(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'telClient' => $client->getPhone(),
'phone' => $client->getPhone(),
'clientCivilite' => $client->getCivilite(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientPostal' => $client->getPostal(),
'clientMail' => $client->getMail(),
'clientPhone' => $client->getPhone(),
'motif' => $rdv->getIdMotif()->getTitre(),
'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
'titre' => 'Vous avez un nouveau RDV le : ' . substr($smsDate, 0, 10) . ' à ' . substr($smsDate, 11, 15),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'idPatient' => $client->getId(),
'proUrl' => "{$_ENV['BASE_logiciel']}",
'frenchDate' => $frenchDate,
'responses' => $responses,
);
$templateEmail = 182;
if (!empty($data['canMove'])) {
$templateEmail = 197;
}
$subject = "✅ Nouveau Rendez-vous My Audio le " . $frenchDate . " à " . substr($smsDate, 11, 15);
// $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, $templateEmail);
$sms = "Vous avez un nouveau RDV le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'aléas contactez votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
$age = null;
if ($client->getBirthdate()) {
$age = $client->getBirthdate()->diff(new \DateTime())->y;
}
// Génère le PDF à partir d’un template
$pdfContent = $this->generatePdf(
'pdf/rdv_recap.html.twig',
[
'nom' => $client->getName() ?? '',
'prenom' => $client->getLastname() ?? '',
'birthday' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
'age' => $age,
'adresse' => $client->getAddress() ?? '',
'postal' => $client->getPostal() ?? '',
'city' => $client->getCity() ?? '',
'phone' => $client->getPhone() ?? '',
'mail' => $client->getMail() ?? '',
'centerName' => $rdv->getIdCentre()->getName() ?? '',
"date" => substr($smsDate, 0, 10) ?? '',
"heure" => substr($smsDate, 11, 15) ?? '',
'duration' => $rdv->getDuration(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
'deviceModelPref' => implode(", ", $leadRdv->getDeviceModelPreference()),
'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
'accoupheneCote' => $leadRdv->getAcoupheneCote() ?? '',
'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
'diabete' => $leadRdv->getDiabete() ?? '',
'hypertension' => $leadRdv->getHypertension() ?? '',
'mutuelle' => $leadRdv->getMutuelle() ?? '',
'nameMutuelle' => $leadRdv->getNameMutuelle() ?? '',
'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
'budget' => $leadRdv->getBudget() ?? '',
'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
'ordonance' => $leadRdv->getOrdonance() ?? '',
'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
'canMove' => $leadRdv->getCanMove() ?? '',
'comment' => $leadRdv->getComment() ?? '',
],
$this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
);
$this->sendEmailWithPdfAttachmentThenDelete(
$params,
$rdv->getIdAudio()->getMail(),
$client->getName(),
$subject,
$templateEmail, // ID du template Sendinblue
$pdfContent
);
// send notif to admin
$paramsSourceLead = [
'trafficSource' => "EasyAdmin",
];
$paramsAdmin = array(
"lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
"lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
"RdvDate" => substr($smsDate, 0, 10),
"heure" => substr($smsDate, 11, 15),
"clientMail" => $client->getMail(),
"audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' . $rdv->getIdAudio()->getName() . ' ' . $rdv->getIdAudio()->getLastName(),
'telClient' => $client->getPhone(),
'clientNom' => $client->getLastname(),
'clientPrenom' => $client->getName(),
'clientCivilite' => $client->getCivilite(),
'clientPostal' => $client->getPostal(),
'clientPhone' => $client->getPhone(),
'motif' => $rdv->getIdMotif()->getTitre(),
'centerAddress' => $rdv->getIdCentre()->getAddress(),
'centerName' => $rdv->getIdCentre()->getName(),
'centerPostal' => $rdv->getIdCentre()->getPostale(),
'centerCity' => $rdv->getIdCentre()->getCity(),
'telCentre' => $rdv->getIdCentre()->getPhone(),
'titre' => 'Vous avez un nouveau RDV le : ' . substr($smsDate, 0, 10) . ' à ' . substr($smsDate, 11, 15),
'date' => substr($smsDate, 0, 10),
'urlApi' => "{$_ENV['BASE_API']}",
'clientId' => $client->getId(),
'centerId' => $rdv->getIdCentre()->getId(),
'frenchDate' => $frenchDate,
'responses' => $responses,
'paramsSourceLead' => $paramsSourceLead
);
$subject = "Nouveau RDV MA | RR - " . $rdv->getIdCentre()->getName();
$templateEmail = 183;
if (!empty($data['canMove'])) {
$templateEmail = 190;
}
if (!isset($data["isLead"])) {
$publicFunction->sendEmail($paramsAdmin, "lead.myaudio@gmail.com", "my audio", $subject, $templateEmail);
}
//dd($paramsAdmin);
//$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
$publicFunction->sendEmail($paramsAdmin, "mickael.aubard@myaudio.fr", "my audio", $subject, $templateEmail);
$publicFunction->sendEmail($paramsAdmin, "mickael@aubard.me", "my audio", $subject, $templateEmail);
// google calendar post
$synchronisations = $this->getDoctrine()->getRepository(SynchronisationSetting::class)
->findBy(array('audio' => $audio->getId()));
$data['rdv'] = $rdv->getId();
foreach ($synchronisations as $synchronisation) {
if (!$synchronisation->getIsDeleted()) {
$googleCalendar->checkAndRefreshAccessToken($synchronisation);
$googleCalendar->createEvent($synchronisation, $data);
}
}
return new Response(json_encode(([
"id" => $rdv->getId(),
"motif_id" => $rdv->getIdMotif()->getId(),
"audio_id" => $rdv->getIdAudio()->getId(),
"client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
"client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
"proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
"centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
"lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
"testclient" => $rdv->getTestClient() ? [
"result" => $rdv->getTestClient()->getResultTonal(),
"date" => $rdv->getTestClient()->getDate(),
"device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
] : null,
"duration" => $audioMotif->getDuration(),
"consigne" => $audioMotif->getConsigne(),
"etat_id" => $rdv->getIdEtat()->getId(),
"date" => $rdv->getDate(),
"comment" => $rdv->getComment(),
"centerName" => $rdv->getIdCentre()->getName(),
"review" => $rdv->getReview(),
"note" => $rdv->getNote(),
"status" => 200,
"paramsPatient" => $paramsPatient,
"isNew" => $isNew,
])));
}
private function generatePdf(string $template, array $data = [], string $outputPath): string
{
// Render le contenu HTML avec Twig
$html = $this->twig->render($template, $data);
// Configurer Dompdf
$options = new Options();
$options->set('defaultFont', 'Arial');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// Sauvegarder le PDF
file_put_contents($outputPath, $dompdf->output());
return $outputPath; // Renvoie le chemin du fichier PDF généré
}
private function sendEmailWithPdfAttachmentThenDelete(
array $params,
string $mail,
string $name,
string $subject,
int $templateId,
string $pdfFilePath
): void {
// Lire et encoder le contenu du PDF
$attachment = [
"name" => basename($pdfFilePath),
"content" => base64_encode(file_get_contents($pdfFilePath)),
];
// Construire les données pour l’API Sendinblue
$data = [
"sender" => [
"email" => 'noreply@myaudio.fr',
"name" => 'My Audio',
],
"to" => [
[
"email" => $mail,
"name" => $name,
],
],
"subject" => $subject,
"templateId" => $templateId,
"params" => $params,
"attachment" => [$attachment],
];
// Envoi via cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.sendinblue.com/v3/smtp/email');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers = [
'Accept: application/json',
'Api-Key: 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',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Erreur email : ' . curl_error($ch);
}
curl_close($ch);
// Supprimer le PDF après envoi
if (file_exists($pdfFilePath)) {
unlink($pdfFilePath);
}
}
private function formatImploded(array $data): string
{
return implode(', ', array_map(function ($item) {
return str_replace('_', ' ', $item);
}, $data));
}
/**
*
* @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
*/
public function exportPdfForm(Request $request): Response
{
$form = $this->createFormBuilder()
->add('startDate', \Symfony\Component\Form\Extension\Core\Type\DateType::class, [
'label' => 'Date de départ',
'widget' => 'single_text',
'html5' => true,
'required' => true,
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$startDate = $form->getData()['startDate'];
return $this->redirectToRoute('admin_rdv_export_pdf', [
'date' => $startDate->format('Y-m-d'),
]);
}
return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
'form' => $form->createView(),
]);
}
/**
*
* @Route("/admin/rdv/export-pdf/{date}", name="admin_rdv_export_pdf", methods={"GET", "POST"})
*/
public function exportPdfFromDate(string $date): Response
{
$startDate = new \DateTimeImmutable($date);
$today = new \DateTimeImmutable();
$rdvs = $this->rdvRepository->findBySinceDateAndMyAudio($startDate);
$html = "
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
font-size: 13px; /* Taille de police réduite */
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px; /* Taille de police spécifique pour le tableau */
}
th, td {
border: 1px solid #000;
padding: 5px;
text-align: left;
}
th {
font-weight: bold;
}
h1 {
font-size: 14px; /* Taille du titre */
}
</style>
</head>
<body>
<h1>Rendez-vous My Audio depuis le " . $startDate->format('d/m/Y') . "</h1>
<table cellspacing='0' cellpadding='5'>
<thead>
<tr>
<th>ID du RDV</th>
<th>Date du RDV</th>
<th>Jours écoulés</th>
<th>Statut RDV</th>
<th>Nom patient</th>
<th>Téléphone patient</th>
<th>Statut patient</th>
<th>Centre</th>
<th>Téléphone Centre</th>
<th>Adresse</th>
<th>Nom Audio</th>
</tr>
</thead>
<tbody>";
foreach ($rdvs as $rdv) {
$dateRdv = $rdv->getDate();
$joursEcoules = $dateRdv->diff($today)->days;
$client = $rdv->getIdClient();
$centre = $rdv->getIdCentre();
$etat = $rdv->getIdEtat();
$clientName = $client ? htmlspecialchars($client->getName() . ' ' . $client->getLastname()) : '';
$clientPhone = $client ? htmlspecialchars($client->getPhone()) : '';
$clientStatus = $client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini';
$rdvStatus = $etat ? htmlspecialchars($etat->getLibelle()) : 'Non défini';
$centreName = $centre ? htmlspecialchars($centre->getName()) : '';
$centrePhone = $centre ? htmlspecialchars($centre->getPhone()) : '';
$centreAddress = $centre ? htmlspecialchars($centre->getAddress() . ', ' . $centre->getPostale() . ' ' . $centre->getCity()) : '';
$audio = $rdv->getIdAudio();
$audioName = $audio ? htmlspecialchars($audio->getCivilite() . ' ' . $audio->getName() . ' ' . $audio->getLastname()) : '';
$html .= "<tr>
<td>" . $rdv->getId() . "</td>
<td>" . $dateRdv->format('d/m/Y H:i') . "</td>
<td>" . $joursEcoules . " jours</td>
<td>" . $rdvStatus . "</td>
<td>" . $clientName . "</td>
<td>" . $clientPhone . "</td>
<td>" . $clientStatus . "</td>
<td>" . $centreName . "</td>
<td>" . $centrePhone . "</td>
<td>" . $centreAddress . "</td>
<td>" . $audioName . "</td>
</tr>";
}
$html .= "</tbody></table></body></html>";
$options = new Options();
$options->set('defaultFont', 'Arial');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
// Création du dossier s’il n’existe pas
$outputDir = 'public/assets/pdf/rdv';
$filesystem = new Filesystem();
if (!$filesystem->exists($outputDir)) {
$filesystem->mkdir($outputDir, 0775);
}
// Formatage du nom du fichier avec la date
$filenameDate = $startDate->format('Y-m-d');
$outputPath = "$outputDir/rdvs-since-$filenameDate.pdf";
file_put_contents($outputPath, $dompdf->output());
// Optionnel : téléchargement immédiat du fichier
return new Response($dompdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="rdvs-since-' . $filenameDate . '.pdf"',
]);
}
}