<?php
namespace App\Controller;
use App\Controller\Admin\DemandeAffectationCrudController;
use App\Controller\Admin\DemandeNoteCrudController;
use App\Controller\Admin\DemandeServiceCrudController;
use App\Entity\DemandeAffectation;
use App\Entity\DemandeNote;
use App\Entity\DemandeService;
use App\Entity\DemandeServiceCandidat;
use App\Entity\DocDemandeClient;
use App\Entity\FormationsService;
use App\Entity\InterventionEntrepriseService;
use App\Entity\ProgrammeFormationService;
use App\Entity\Service;
use App\Entity\User;
use App\Form\DemandeServiceType;
use App\Form\DocDemandeClientType;
use App\Model\Globals;
use App\Service\FileUploader;
use App\Service\NotificationManager;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use ZipArchive;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DemandeServiceController extends AbstractController
{
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* @var RequestStack
*/
private $request;
/**
* @var FileUploader
*/
protected $fileUploader;
/**
* @var AdminUrlGenerator
*/
private $adminUrlGenerator;
private $notificationManager;
/**
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em, FileUploader $fileUploader,
RequestStack $request, AdminUrlGenerator $adminUrlGenerator, NotificationManager $notificationManager)
{
$this->em = $em;
$this->request = $request;
$this->fileUploader = $fileUploader;
$this->adminUrlGenerator = $adminUrlGenerator;
$this->notificationManager = $notificationManager;
}
/**
* @param int $serviceId
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
#[Route('/new/demande/{serviceId}/{demandeId}', name: 'new_demande')]
public function newDemande(int $serviceId,EntityManagerInterface $entityManager,
int $demandeId, Request $request, NotificationManager $notificationManager , UrlGeneratorInterface $urlGenerator)
{
if (null === $this->getUser()) {
return $this->redirectToRoute('login');
}
$service = $this->em->getRepository(Service::class)->find($serviceId);
$dataOptions['attr_translation_parameters']['service'] = $service;
$dataOptions['attr_translation_parameters']['user'] = $this->getUser();
$demandeServiceData = ($demandeId === 0) ? new DemandeService() : $this->em->getRepository(DemandeService::class)->find($demandeId) ;
if ( ( true === $demandeServiceData->isIsVerified() ) && 0 !== $demandeId ) {
$this->addFlash('error', 'Votre demande a été bien reçue');
return $this->redirectToRoute('app_list_demande');
}
foreach ($this->getUser()->getAdresses() as $value) {
$address = $value;
}
$form = $this->createForm(DemandeServiceType::class, $demandeServiceData, $dataOptions);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$demandeService = $form->getData();
$demandeService->setIsDeleted(false);
$demandeService->setIsVerified(false);
$demandeService->setIsValid(false);
$demandeService->setEnabled(true);
$demandeService->setAcceptDocuments(false);
if ($demandeId === 0) {
// if ($service instanceof InterventionEntrepriseService) {
$demandeService->setEtat(Globals::DEMANDE_ETAT_EN_COURS);
// } else {
// $demandeService->setEtat(Globals::DEMANDE_ETAT_ATTENTE_VALIDATION);
// }
$demandeService->setCreatedBy($this->getUser()->getId());
$demandeService->setService($service);
if( $demandeService->getPrestation() ){
$demandeService->setRubrique($demandeService->getPrestation()->getRubrique());
}elseif( $service->getRubriques() ){
$demandeService->setRubrique( $service->getRubriques()[0] );
$demandeService->setPrestation( $service->getRubriques()[0]->getPrestations()[0] );
}
$demandeService->setUser($this->getUser());
} else {
$demandeService->setUpdatedBy($this->getUser()->getId());
$demandeService->setUpdatedAt(new \DateTime());
}
if ($service instanceof FormationsService) {
$demandeService->setProcessType(Globals::FORMATION_PROCESS_TYPE);
}
$this->em->persist($demandeService);
$this->em->flush();
if ($service instanceof FormationsService) {
$demandeServiceCandidatData = $this->em->getRepository(DemandeServiceCandidat::class)->findBy(['demandeService' => $demandeService]);
if (0 < count($demandeServiceCandidatData)) {
foreach ($demandeServiceCandidatData as $candidat) {
$this->em->getRepository(DemandeServiceCandidat::class)->remove($candidat, true);
}
}
if (true === array_key_exists('candidats', $this->request->getCurrentRequest()->request->all())) {
$candidats = $this->request->getCurrentRequest()->request->all()['candidats'];
$demandeServiceCandidat = [];
foreach ($candidats['name'] as $i => $name) {
$demandeServiceCandidat[$i] = new DemandeServiceCandidat();
$demandeServiceCandidat[$i]->setNomPrenom($name);
$demandeServiceCandidat[$i]->setDemandeService($demandeService);
$demandeServiceCandidat[$i]->setDeleted(false);
$demandeServiceCandidat[$i]->setCreatedBy($this->getUser()->getId());
$demandeServiceCandidat[$i]->setCreatedAt(new \DateTime());
}
foreach ($candidats['email'] as $i => $email) {
$demandeServiceCandidat[$i]->setEmail($email);
}
foreach ($candidats['niveauInstruction'] as $i => $niveauInstruction) {
$demandeServiceCandidat[$i]->setNiveauInstruction($niveauInstruction);
}
foreach ($candidats['affectation'] as $i => $aff) {
$demandeServiceCandidat[$i]->setAffectation($aff);
}
foreach ($candidats['anciennete'] as $i => $anciennete) {
$demandeServiceCandidat[$i]->setAnciennete($anciennete);
$this->em->persist($demandeServiceCandidat[$i]);
$this->em->flush();
}
}
}
$this->addFlash('success', 'Demande enregistrée avec succès');
// Send Comment
$url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
// Variables définies pour l'URL
$encodedReferrerUrl = urlencode($url);
$crudControllerFqcn = 'App\Controller\Admin\DemandeServiceCrudController';
$entityFqcn = 'App\Entity\DemandeService';
$filterComparison = '=';
$filterValue = $demandeService->getId();
$filterValue2 = ''; // Assuming this is an empty value
// Génération de l'URL avec les paramètres supplémentaires
$edit_demande_url = $this->adminUrlGenerator
->setController($crudControllerFqcn)
->setAction(Action::INDEX)
->set('referrer', $encodedReferrerUrl)
->set('crudAction', 'index')
->set('crudControllerFqcn', $crudControllerFqcn)
->set('entityFqcn', $entityFqcn)
->set('filters[id][comparison]', $filterComparison)
->set('filters[id][value]', $filterValue)
->set('filters[id][value2]', $filterValue2)
->generateUrl();
$notification_message = 'Mise à jour de demande ';
$repository = $entityManager->getRepository(User::class);
$queryBuilder = $repository->createQueryBuilder('u');
$daes = $entityManager->getRepository(User::class)->findByRole('ROLE_DAE');
$CAs = $entityManager->getRepository(User::class)->findByRole('ROLE_CHARGE_ASSISTANCE');
foreach($daes as $dae) {
$notificationManager->pushMessage($notification_message, $notification_message, $dae, $edit_demande_url);
}
foreach($CAs as $ca) {
if($ca->getUniteRegional()->getAdresse()->getGouvernorat() == $demandeService->getGouvernorat() ){
$notificationManager->pushMessage($notification_message, $notification_message, $ca, $edit_demande_url);
}
}
// End send comment
return $this->redirectToRoute('app_list_demande');
}
return $this->render('service/demande/new.html.twig', [
'user' => $this->getUser(),
'userRole' => $this->getUser()->getRoles(),
'service' => $service,
'isInstanceofFormation' => ($service instanceof FormationsService),
'isInstanceOfInterventionEntreprise' => ($service instanceof InterventionEntrepriseService),
'isInstanceOfProgrammeFormation' => ($service instanceof ProgrammeFormationService),
'form' => $form->createView(),
'demandeId' => $demandeId,
'address' => $address,
'etatRefus' => Globals::DEMANDE_ETAT_REFUSER,
'demande' => $demandeServiceData,
'show' => false
]);
}
/**
* @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
#[Route('/comment/demande/{demandeId}', name: 'comment_demande')]
public function listCommentDemande( int $demandeId, Request $request , EntityManagerInterface $entityManager)
{
$listCommentDemande = $this->em->getRepository(DemandeNote :: class)->findBy(['demande' => $demandeId]);
if (null === $this->getUser()) {
return $this->redirectToRoute('login');
}
$referrerUrl = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction('index')
->set('entityFqcn', 'App\\Entity\\DemandeService')
->generateUrl();
$edit_demande_url = $this->adminUrlGenerator
->setController(DemandeNoteCrudController::class)
->setAction('index')
->set('demandeServiceId', $demandeId)
->set('referrer', $referrerUrl)
->generateUrl();
$notification_message = 'Nouvelle Note / Note modifiée ! ';
$currentUser = $this->getUser();
$admins = $entityManager->getRepository(User::class)
->createQueryBuilder('u')
->where('u != :currentUser')
->setParameter('currentUser', $currentUser)
->andWhere('u.roles LIKE :role1 OR u.roles LIKE :role2 ')
->setParameter('role1', '%ROLE_CHARGE_ASSISTANCE%')
->setParameter('role2', '%ROLE_DAE%')
->getQuery()
->getResult();
$listAffectations = $entityManager->getRepository(DemandeAffectation::class)->findBy(['demandeService'=> $demandeId]);
foreach ($admins as $admin) {
$this->notificationManager->pushMessage('Nouvelle Note / Note modifiée! ', $notification_message, $admin, $edit_demande_url);
}
return $this->render('service/demande/note_list.html.twig', [
'listCommentDemandes' => $listCommentDemande,
'demandeId' => $demandeId
]);
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
#[Route('/demande/list', name: 'app_list_demande')]
public function listDemande()
{
$demandesDates = [];
$demandes = $this->em->getRepository(DemandeService::class)->findBy(['user' => $this->getUser(), 'isDeleted' => false]);
foreach( $demandes as $demande ){
$dateDebut = null;
$dateFin = null;
if( $demande->getGroupeDemande() ){
$demandesModules = $this->em->getRepository(DemandeService::class)->getDemandesModuleOfGroupe( $demande->getGroupeDemande()->getId() );
dump( $demande->getId(), $demandesModules);
foreach ( $demandesModules as $demandeModule ){
if ( $demandeModule->getTachExecutionDateDebut() and $dateDebut == null){
$dateDebut = $demandeModule->getTachExecutionDateDebut();
}
$dateFin = $demandeModule->getTachExecutionDateFin();
}
}
$demandesDates[ $demande->getId() ] = [
'dateDebut' => $dateDebut,
'dateFin' => $dateFin,
];
}
return $this->render('service/demande/list.html.twig', [
'demandes' => $demandes,
'demandesDates' => $demandesDates,
'etatDocValid' => Globals::DOC_ETAT_VALIDE,
'etatEncours' => Globals::DEMANDE_ETAT_EN_COURS,
'etatEnAttente' => Globals::DEMANDE_ETAT_ATTENTE_VALIDATION,
'etatRefuser' => Globals::DEMANDE_ETAT_REFUSER,
'etatCloturer' => Globals::DEMANDE_ETAT_CLOTURER,
]);
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/delete/{id}', name: 'app_delete_demande')]
public function deleteDemande(int $id)
{
$demande = $this->em->getRepository(DemandeService::class)->find($id);
if ( true === $demande->isIsVerified() ) {
$this->addFlash('error', 'Votre demande a été bien reçue');
return $this->redirectToRoute('app_list_demande');
}
$demande->setIsDeleted(true);
$demande->setDeletedAt(new \DateTime());
$this->em->persist($demande);
$this->em->flush();
$edit_demande_url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
$notification_message = 'Demande supprimée! ';
$currentUser = $this->getUser();
$admins = $this->em->getRepository(User::class)
->createQueryBuilder('u')
->where('u != :currentUser')
->setParameter('currentUser', $currentUser)
->andWhere('u.roles LIKE :role1 OR u.roles LIKE :role2 ')
->setParameter('role1', '%ROLE_CHARGE_ASSISTANCE%')
->setParameter('role2', '%ROLE_DAE%')
->getQuery()
->getResult();
foreach ($admins as $admin) {
$this->notificationManager->pushMessage('Demande supprimée ! ', $notification_message, $admin, $edit_demande_url);
}
$this->addFlash('success', 'Demande supprimé avec succès');
return $this->redirectToRoute('app_list_demande');
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\Response
*/
#[Route('/demande/show/{id}', name: 'app_show_demande')]
public function showDemande(int $id)
{
$demandeServiceData = $this->em->getRepository(DemandeService::class)->find($id);
$dataOptions['attr_translation_parameters']['service'] = $demandeServiceData->getService();
$dataOptions['attr_translation_parameters']['user'] = $demandeServiceData->getUser();
$dataOptions['row_attr']['show'] = true;
$form = $this->createForm(DemandeServiceType::class, $demandeServiceData, $dataOptions);
return $this->render('service/demande/new.html.twig', [
'user' => $demandeServiceData->getUser(),
'service' => $demandeServiceData->getService(),
'isInstanceofFormation' => ($demandeServiceData->getService() instanceof FormationsService),
'isInstanceOfInterventionEntreprise' => ($demandeServiceData->getService() instanceof InterventionEntrepriseService),
'isInstanceOfProgrammeFormation' => ($demandeServiceData->getService() instanceof ProgrammeFormationService),
'form' => $form->createView(),
'demandeId' => $demandeServiceData->getId(),
'demande' => $demandeServiceData,
'show' => true
]);
}
#[Route('/demande/verif/{id}', name: 'app_verif_demande')]
public function verifDemande(int $id)
{
$url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
$demandeService = $this->em->getRepository(DemandeService::class)->find($id);
if (true === $this->isGranted('ROLE_CHARGE_ASSISTANCE') || true === $this->isGranted('ROLE_DAE')) {
$demandeService->setIsverified(true);
$demandeService->setVerifiedBy($this->getUser()->getId());
$demandeService->setVerifiedAt(new \DateTime());
$demandeService->setEtat(Globals::DEMANDE_ETAT_ATTENTE_VALIDATION);
$this->em->persist($demandeService);
$this->em->flush($demandeService);
$this->addFlash('success', "Demande vérifié avec succès");
return $this->redirect($url);
} else {
$this->addFlash('error', 'Accès interdit');
return $this->redirect($url);
}
}
#[Route('/demande/print/{id}', name: 'app_print_demande')]
public function printDemande(int $id)
{
$demande = $this->em->getRepository(DemandeService::class)->find($id);
return $this->render('service/demande/print_demande.html.twig', [
'demande' => $demande
]);
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/valider/{id}', name: 'valid_demande')]
public function validerDemande(int $id)
{
$url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
$demande = $this->em->getRepository(DemandeService::class)->find($id);
if (true === $this->isGranted('ROLE_DAE')) {
$demande->setIsValid(true);
$demande->setValidBy($this->getUser()->getId());
$demande->setValidAt(new \DateTime());
$demande->setEtat(Globals::DEMANDE_ETAT_VALIDE);
$this->em->persist($demande);
$this->em->flush($demande);
$this->addFlash('success', "Demande Validée avec succès");
return $this->redirect($url);
} else {
$this->addFlash('error', 'Accès interdit');
return $this->redirect($url);
}
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
#[Route('/demande/download/{id}', name: 'download_doc_demande')]
public function downloadDocDemande(int $id)
{
$demande = $this->em->getRepository(DemandeService::class)->find($id);
$zipArchive = new ZipArchive();
$zipArchive->open($this->getParameter('uploads_directory').'/affectations/doc_demande_zip_'.$demande->getId().'.zip', ZipArchive::CREATE);
if (0 < count($demande->getDemandeAffectation())) {
foreach ($demande->getDemandeAffectation() as $affectation) {
if (0 < count($affectation->getDocDemandeService())) {
foreach ($affectation->getDocDemandeService() as $file) {
if (true === in_array('ROLE_AGENT_INTERNE', $file->getUser()->getRoles()) && true === $file->isExterne() && 'import_conseiller' === $file->getType() && Globals::DOC_ETAT_VALIDE === $file->getEtat()) {
$zipArchive->addFile($this->getParameter('uploads_directory') . '/affectations/' . $affectation->getId() . '/' . $file->getFileName(), $file->getOriginalFileName());
}
}
}
}
}
$zipArchive->close();
if (true === file_exists($this->getParameter('uploads_directory').'/affectations/doc_demande_zip_'.$demande->getId().'.zip')) {
return $this->file($this->getParameter('uploads_directory').'/affectations/doc_demande_zip_'.$demande->getId().'.zip')->deleteFileAfterSend();
}
$this->addFlash('error', 'Documents : accès interdit ! ');
return $this->redirectToRoute('app_list_demande');
}
/**
* @param int $demandeId
* @return \Symfony\Component\HttpFoundation\Response
*/
#[Route('/demande/doc/list/{demandeId}', name: 'list_doc_demande')]
public function docList(int $demandeId)
{
$demande = $this->em->getRepository(DemandeService::class)->find($demandeId);
$docDemandeClient = $this->em->getRepository(DocDemandeClient::class)->findBy(['demandeService' => $demande, 'deleted' => false]);
return $this->render('service/demande/doc_list.html.twig', [
'demande' => $demande,
'docs' => $docDemandeClient
]);
}
/**
* @param int $demandeId
* @return \Symfony\Component\HttpFoundation\Response
*/
#[Route('/demande/doc/add/{demandeId}/{docId}', name: 'add_doc_demande')]
public function addDoc(int $demandeId, int $docId = 0, Request $request,NotificationManager $notificationManager,)
{
$docDemandeClient = ($docId === 0) ? new DocDemandeClient() : $this->em->getRepository(DocDemandeClient::class)->find($docId);
$oldFileName = '';
if ($docId !== 0) {
$oldFileName = $this->em->getRepository(DocDemandeClient::class)->find($docId)->getFileName();
}
$form = $this->createForm(DocDemandeClientType::class, $docDemandeClient);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$demande = $this->em->getRepository(DemandeService::class)->find($demandeId);
$edit_demande_url = "";
$docDemandeClient = $form->getData();
$docDemandeClient->setDemandeService($demande);
$docDemandeClient->setCreatedBy($this->getUser()->getId());
$docDemandeClient->setCreatedAt(new \DateTime());
$docDemandeClient->setDeleted(false);
$file = $this->request->getCurrentRequest()->files->get('doc_demande_client')['fileName'];
if (null !== $file) {
$docDemandeClient->setOriginalFileName($file->getClientOriginalName());
$newFileName = $this->fileUploader->upload($file, '/demandes/' . $demande->getId(), 'docaff' );
$docDemandeClient->setFileName($newFileName);
if ($docId !== 0 && true === file_exists($this->getParameter('uploads_directory').'/demandes/'.$docDemandeClient->getDemandeService()->getId().'/'.$oldFileName)) {
unlink($this->getParameter('uploads_directory').'/demandes/'.$docDemandeClient->getDemandeService()->getId().'/'.$oldFileName);
}
}
$this->em->persist($docDemandeClient);
$this->em->flush();
$edit_demande_url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->set('filters[id][comparison]', '=')
->set('filters[id][value]', $demande->getId())
->generateUrl();
$notification_message ="Mise à jour de document d'une demande !";
$daes = $this->em->getRepository(User::class)->findByRole('ROLE_DAE');
$CAs = $this->em->getRepository(User::class)->findByRole('ROLE_CHARGE_ASSISTANCE');
foreach($daes as $dae) {
$notificationManager->pushMessage($notification_message, $notification_message, $dae, $edit_demande_url);
}
foreach($CAs as $ca) {
if($ca->getUniteRegional()->getAdresse()->getGouvernorat() == $demande->getGouvernorat() ){
$notificationManager->pushMessage($notification_message, $notification_message, $ca, $edit_demande_url);
}
}
$this->addFlash('success', 'Documents ajouté avec succès');
return $this->redirectToRoute('list_doc_demande', ['demandeId' => $demande->getId()]);
}
return $this->render('service/demande/add_doc.html.twig', [
'form' => $form->createView()
]);
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/doc/download/{id}', name: 'download_doc_client')]
public function downloadDocClient(int $id)
{
$docDemande = $this->em->getRepository(DocDemandeClient::class)->find($id);
if (true === file_exists($this->getParameter('uploads_directory').'/demandes/'.$docDemande->getDemandeService()->getId().'/'.$docDemande->getFileName())) {
return $this->file($this->getParameter('uploads_directory').'/demandes/'.$docDemande->getDemandeService()->getId().'/'.$docDemande->getFileName());
}
$this->addFlash('error', 'Document introuvable ! ');
return $this->redirectToRoute('list_doc_demande', [ 'demandeId' => $docDemande->getDemandeService()->getId() ]);
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/doc/delete/{id}', name: 'app_delete_doc')]
public function deleteDocClient(int $id)
{
$docDemande = $this->em->getRepository(DocDemandeClient::class)->find($id);
$docDemande->setDeleted(true);
$this->em->persist($docDemande);
$this->em->flush();
$this->addFlash('error', 'Documents : supprimé avec succès ! ');
return $this->redirectToRoute('list_doc_demande', ['demandeId' => $docDemande->getDemandeService()->getId()]);
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/doc/accept/{id}', name: 'accept_document')]
public function acceptDocDeamnde(int $id)
{
$demande = $this->em->getRepository(DemandeService::class)->find($id);
$demande->setAcceptDocuments(true);
$this->em->persist($demande);
$this->em->flush();
$this->addFlash('error', 'Documents : accepté avec succès ! ');
return $this->redirectToRoute('app_list_demande');
}
/**
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/back', name: 'admin_list')]
public function backToAdminList()
{
$url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
if (true === $this->isGranted('ROLE_AGENT_INTERNE')) {
$url = $this->adminUrlGenerator
->setController(DemandeAffectationCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
}
return $this->redirect($url);
}
/**
* @param int $id
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
#[Route('/demande/refuser/{id}', name: 'refuser_demande')]
public function refuserDemande(int $id)
{
$motifRefus = $this->request->getCurrentRequest()->request->all()['motifRefus'];
$demande = $this->em->getRepository(DemandeService::class)->find($id);
$url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
if (true === $this->isGranted('ROLE_DAE')) {
$demande->setRefusedBy($this->getUser()->getId());
$demande->setRefusedAt(new \DateTime());
$demande->setMotifRefus($motifRefus);
$demande->setEtat(Globals::DEMANDE_ETAT_REFUSER);
$this->em->persist($demande);
$this->em->flush($demande);
$this->addFlash('success', "Demande refusée avec succès");
$edit_demande_url = $this->adminUrlGenerator
->setController(DemandeServiceCrudController::class)
->set('demandeServiceId', $demande)
->setAction(Action::INDEX)
->generateUrl();
$notification_message = 'Nouvelle Demande a été acceptée ! ';
$currentUser = $this->getUser();
$admins = $this->em->getRepository(User::class)
->createQueryBuilder('u')
->where('u != :currentUser')
->setParameter('currentUser', $currentUser)
->andWhere('u.roles LIKE :role1 OR u.roles LIKE :role2 ')
->setParameter('role1', '%ROLE_CHARGE_ASSISTANCE%')
->setParameter('role2', '%ROLE_DAE%')
->getQuery()
->getResult();
foreach ($admins as $admin) {
$this->notificationManager->pushMessage(' Demande a été refusée! ', $notification_message, $admin, $edit_demande_url);
}
$userExp = $this->em->getRepository(User::class)->findOneBy(['id'=> $demande->getUser()->getId()]);
$url_user_front = '/demande/list';
$this->notificationManager->pushMessage('Demande a été refusée! ', $notification_message, $userExp, $url_user_front);
return $this->redirect($url);
} else {
$this->addFlash('error', 'Accès interdit');
return $this->redirect($url);
}
}
/**
* @Route("/note/add", name="add_note", methods={"POST"})
*/
public function addComment(Request $request, EntityManagerInterface $entityManager): Response
{
$id = (int)$request->request->get('demandeIdName');
$demande = $entityManager->getRepository(DemandeService::class)->find($id);
if (!$demande) {
return $this->json(['error' => 'Commentaire not found.'], Response::HTTP_NOT_FOUND);
}
$noteDemande = new DemandeNote;
// Update the properties of the DemandeNote entity based on the form data
$noteDemande->setDescription($request->request->get('commentName'));
$noteDemande->setDemande($demande);
$noteDemande->setIsPublic(true);
// Persist and flush the changes to the database
$entityManager->persist($noteDemande);
$entityManager->flush();
$this->addFlash('success', 'Commentaire a été ajoutée avec succès');
return $this->redirectToRoute('comment_demande', ['demandeId' => $id ]);
}
/**
* @Route("/note/update/{id}", name="update_note", methods={"POST"})
*/
public function updateNote(Request $request, int $id, EntityManagerInterface $entityManager): Response
{
$demandeNote = $entityManager->getRepository(DemandeNote::class)->find($id);
if (!$demandeNote) {
return $this->json(['error' => 'Commentaire not found.'], Response::HTTP_NOT_FOUND);
}
$formData = json_decode($request->getContent(), true);
// Check if 'editComment' key exists in formData
if (isset($formData['editComment'])) {
$editComment = $formData['editComment'];
$demandeNote->setDescription($editComment);
} else {
return $this->json(['error' => 'editComment key is missing in formData.'], Response::HTTP_BAD_REQUEST);
}
// Persist and flush the changes to the database
$entityManager->persist($demandeNote);
$entityManager->flush();
$response = [
'success' => true,
'messages' => 'Commentaire a été mis à jour avec succès.',
];
return $this->json($response);
}
#[Route('/note/delete/{id}/{demandeId}', name: 'delete_note')]
public function deleteAction($id,$demandeId, EntityManagerInterface $entityManager)
{
$note = $entityManager->getRepository(DemandeNote::class);
$note = $note->find($id);
if (!$note) {
throw $this->createNotFoundException(
'Il n\'y a aucun commentaire avec l\'identifiant suivant : ' . $id
);
}
$entityManager->remove($note);
$entityManager->flush();
$response = [
'success' => true,
'messages' => 'suppression effectuée avec succès.',
];
$this->addFlash('success', 'suppression effectuée avec succès');
return $this->redirectToRoute('comment_demande', ['demandeId' => $demandeId ]);
}
/**
* @Route("/note/fetchData/{id}", name="fetch_note_data", methods={"GET"})
*/
public function fetchData(int $id, EntityManagerInterface $entityManager): Response
{
$demandeNote = $entityManager->getRepository(DemandeNote::class)->find($id);
if (!$demandeNote) {
return $this->json(['error' => 'Subject not found.'], Response::HTTP_NOT_FOUND);
}
$response = [
'id' => $demandeNote->getId(),
'description' => $demandeNote->getDescription()
];
return $this->json($response);
}
/**
* @Route("/get_candidat_form", name="fcandidat_form", methods={"GET"})
*/
public function getCandidatForm(Request $request): Response
{
$index = $request->query->get('i');
$content = $this->renderView('include/add_condidat_form.html.twig', ['index' => $index]);
return new Response($content);
}
}