<?php
namespace App\Controller;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\FormationSession;
use App\Entity\FormationSessionMotivation;
use App\Entity\FormationMotivationType;
use App\Entity\FormationSessionDocument;
use App\Entity\FormationType;
use App\Entity\ParametrageTexte;
use App\Entity\Utilisateur;
use App\Entity\UtilisateurInformation;
use App\Entity\Workflow;
use App\Entity\RefRole;
use App\Entity\RefGabarit;
use App\Form\FormationSessionType;
use App\Form\FormationTypeType;
use App\Form\FormationSessionDocumentType;
use App\Form\FormationSessionMotivationType;
use App\Services\AccessRule;
use App\Services\ExportFormation;
use App\Services\Mailer;
use App\Services\GeneratePdf;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Twig\Environment;
use App\Services\Lib\EmailSHDecision;
use App\Entity\RFederation;
class FormationSessionController extends AbstractController
{
final public const ERROR_VALIDATION_FORM = 'Erreur lors de la validation du formulaire';
final public const ERROR_OCCURED = 'Une erreur est survenue';
final public const ERROR_FILE = 'Fichier introuvable';
private ManagerRegistry $doctrine;
private AccessRule $accessRule;
private ExportFormation $exportFormation;
private MailerInterface $mailer;
private GeneratePdf $generatePdf;
private $twig;
private $emailSHDecision;
public function __construct(ManagerRegistry $doctrine, AccessRule $accessRule, ExportFormation $exportFormation, MailerInterface $mailer, Environment $twig, GeneratePdf $generatePdf, EmailSHDecision $emailSHDecision)
{
$this->doctrine = $doctrine;
$this->accessRule = $accessRule;
$this->exportFormation = $exportFormation;
$this->mailer = $mailer;
$this->generatePdf = $generatePdf;
$this->twig = $twig;
$this->emailSHDecision = $emailSHDecision;
}
private function arrayOfElement($fs)
{
$data = [];
if (isset($fs) && !empty($fs)) {
$data = [
'id' => isset($fs['id_formation_session']) ? $fs['id_formation_session'] : "",
'id_utilisateur' => isset($fs['id_utilisateur']) ? $fs['id_utilisateur'] : "",
'civilite' => isset($fs['civilite']) ? $fs['civilite'] : "",
'nom' => isset($fs['nom']) ? $fs['nom'] : "",
'prenom' => isset($fs['prenom']) ? $fs['prenom'] : "",
'affectation_id' => isset($fs['affectation_id']) ? $fs['affectation_id'] : "",
'libelle_affectation' => isset($fs['libelle_affectation']) ? $fs['libelle_affectation'] : "",
'id_federation' => isset($fs['id_federation']) ? $fs['id_federation'] : "",
'r_ser_libl' => isset($fs['r_ser_libl']) ? $fs['r_ser_libl'] : "",
'libelle_poste' => isset($fs['libelle_poste']) ? $fs['libelle_poste'] : "",
'titre' => isset($fs['titre']) ? $fs['titre'] : "",
'libelle_organisme' => isset($fs['libelle_organisme']) ? $fs['libelle_organisme'] : "",
'titre_session' => isset($fs['titre_session']) ? $fs['titre_session'] : "",
'type_formation' => isset($fs['libelle_formation']) ? $fs['libelle_formation'] : "",
'id_formation_type' => isset($fs['id_formation_type']) ? $fs['id_formation_type'] : "",
'id_workflow' => isset($fs['id_workflow']) ? $fs['id_workflow'] : "",
'libelle_action' => isset($fs['libelle_action']) ? $fs['libelle_action'] : "",
'date_debut' => isset($fs['date_debut']) ? $fs['date_debut'] : "",
'date_fin' => isset($fs['date_fin']) ? $fs['date_fin'] : "",
'nb_jours' => isset($fs['nb_jours']) ? $fs['nb_jours'] : "",
'avis_dtn' => isset($fs['avis_dtn']) ? $fs['avis_dtn'] : "",
'avis_sh' => isset($fs['avis_sh']) ? $fs['avis_sh'] : "",
'lieu_formation' => isset($fs['lieu_formation']) ? $fs['lieu_formation'] : "",
'responsable' => [
'nom_responsable' => isset($fs['nom_responsable']) ? $fs['nom_responsable'] : "",
'mail_responsable' => isset($fs['mail_responsable']) ? $fs['mail_responsable'] : "",
'telephone_responsable' => isset($fs['telephone_responsable']) ? $fs['telephone_responsable'] : "",
],
'presentation' => isset($fs['presentation']) ? $fs['presentation'] : "",
'lien' => isset($fs['lien']) ? $fs['lien'] : "",
'certification' => isset($fs['certification']) ? $fs['certification'] : null,
'commentaire_dtn' => isset($fs['commentaire_dtn']) ? $fs['commentaire_dtn'] : "",
'commentaire_sh' => isset($fs['commentaire_sh']) ? $fs['commentaire_sh'] : "",
'date_avis_dtn' => isset($fs['date_avis_dtn']) ? $fs['date_avis_dtn'] : "",
'date_sgn_sh' => isset($fs['date_sgn_sh']) ? $fs['date_sgn_sh'] : "",
];
}
return $data;
}
private function fillSessions($sessions, $sessions_motivations, $number_of_motivation_types)
{
$toFill = [];
$accents = ['é' => 'e'];
if (isset($sessions) && !empty($sessions)) {
for ($i = 0; $i < (is_countable($sessions) ? count($sessions) : 0); $i++) {
$motivations_array = [];
if (!empty($sessions_motivations) && isset($sessions_motivations[$i])) {
for (
$j = $i * $number_of_motivation_types;
$j < $i * $number_of_motivation_types + $number_of_motivation_types && $j < count($sessions_motivations);
$j++
) {
$motivation = $sessions_motivations[$j];
$libelle_motivation = strtr(
strtolower(str_replace(' ', '_', (string) $motivation['libelle_motivation'])),
$accents
);
$motivations_array[$libelle_motivation] = $motivation['valeur'];
}
}
$session = $this->arrayOfElement($sessions[$i]);
$session['motivation'] = $motivations_array;
$toFill[] = $session;
}
}
return $toFill;
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/modifier-formation-types/{id}', name: 'ctsweb_modifier_formation_types')]
public function modifierFormationTypes(Request $request, FormationType $formationtype)
{
$form = $this->handleRequestType($request, $formationtype, 'all', 'post');
if ($form->isSubmitted() && $form->isValid()) {
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$libelle = $data['libelle'];
$code = $data['code'];
if (empty($data['libelle'])) {
$result = ['success' => false, 'info' => 'Le champ libellé est obligatoire.'];
$status = JsonResponse::HTTP_OK;
} elseif (empty($data['code'])) {
$result = ['success' => false, 'info' => 'Le champ code est obligatoire.'];
$status = JsonResponse::HTTP_OK;
} else {
$formationtype->setLibelleFormation($libelle);
$formationtype->setCode($code);
$entityManager = $this->doctrine->getManager();
$entityManager->persist($formationtype);
$entityManager->flush();
$result = ['success' => true];
$status = JsonResponse::HTTP_OK;
}
} else {
$result = [
'success' => false,
'data' => self::ERROR_VALIDATION_FORM,
'error' => (string) $form->getErrors(true, false)
];
$status = JsonResponse::HTTP_BAD_REQUEST;
}
return new JsonResponse($result, $status);
}
#[Route(path: '/api/supprimer_type_formation/{id}', name: 'ctsweb_formations_supprimer_type_formation')]
public function supprimerTypeFormation(Request $request, FormationType $formationType)
{
try {
// $form = $this->handleRequestType($request, $formationType, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(FormationType::class);
$cg = $repository->countFormationTypeId($formationType->getIdFormationType());
if (count($cg) > 0) {
$data = ['success' => false, 'data' => 'Ce type de formation est déjà utilisé. Il ne peut être supprimé'];
return new JsonResponse($data);
} else {
$repository->deleteFormationType($formationType->getIdFormationType());
$data = ['success' => true, 'data' => 'Le Type a été supprimé'];
return new JsonResponse($data);
}
} catch (\Exception $e) {
$data = ['success' => false, 'data' => $e->getMessage()];
return new JsonResponse($data);
}
}
/* Assertions for the function that get the formations:
- Let n = the number of formation types
For each formation session, there are n formation types
- Results not involving motivations are sorted by id_formation_session DESC
- Results involving motivations are sorted by id_formation_motivation ASC
These assertions are fairly easy to preserve, but breaking any of these assertion will break
the algorithm. It was written this way to prevent doing a query to the database when
getting motivations for each formation session since they are in another table.
*/
#[Route(path: '/api/create-FormationType/', name: 'ctsweb_formations_creer_types_formation')]
public function createFormationType(Request $request)
{
$formationtype = new FormationType();
$form = $this->handleRequestType($request, $formationtype, 'all', 'post');
try {
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->doctrine->getManager();
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$libelle = $data['libelle'] ?? null;
$code = $data['code'] ?? null;
if (!$libelle) {
return new JsonResponse(
['success' => false, 'info' => 'Le champ libellé est obligatoire.'],
JsonResponse::HTTP_OK
);
}
if (!$code) {
return new JsonResponse(
['success' => false, 'info' => 'Le champ code est obligatoire.'],
JsonResponse::HTTP_OK
);
}
$formationtype->setLibelleFormation($libelle);
$formationtype->setCode($code);
$entityManager->persist($formationtype);
$entityManager->flush();
return new JsonResponse(
[
'success' => true,
'Formation' => $formationtype->getIdFormationType()
],
JsonResponse::HTTP_CREATED
);
} else {
$result = [
'success' => false,
'data' => self::ERROR_VALIDATION_FORM,
'error' => (string) $form->getErrors(true, false)
];
}
} catch (\Exception $e) {
// echo $e->getMessage();
$result = [
'success' => false,
'data' => self::ERROR_OCCURED
];
}
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
#[Route(path: '/api/get_liste_types_formation', name: 'ctsweb_formations_liste_types_formation')]
public function getListeTypesFormation()
{
$em = $this->doctrine->getManager();
$getListeTypesFormation = $em->getRepository(FormationType::class)
->getSessionFormationType();
return new JsonResponse(['success' => true, 'data' => $getListeTypesFormation]);
}
#[Route(path: '/api/liste_formation_en_ecriture', name: 'ctsweb_mes_formations_en_attente')]
public function mesFormationsEnAttente()
{
$em = $this->doctrine->getManager();
$user = $this->getUser();
$number_of_motivation_types = 0;
$types = $em->getRepository(FormationMotivationType::class)->getNumberOfTypes();
if (!empty($types) && isset($types[0]['count'])) {
$number_of_motivation_types = $types[0]['count'];
}
$id_user = $user->getIdUtilisateur();
$pending_filter = $em->getRepository(FormationSession::class)
->getPendingFilter();
$pending_sessions = $em->getRepository(FormationSession::class)
->getSessionsOfUserWithWorkflow($id_user, $pending_filter);
$pending_sessions_motivations = $em->getRepository(FormationSession::class)
->getMotivationsOfUserSessionsWithWorkflow($id_user, $pending_filter);
$pending = $this->fillSessions(
$pending_sessions,
$pending_sessions_motivations,
$number_of_motivation_types
);
return new JsonResponse(['success' => true, 'data' => $pending]);
}
#[Route(path: '/api/mes_formations_en_cours', name: 'ctsweb_mes_formations_en_cours')]
public function mesFormationsEnCours()
{
$em = $this->doctrine->getManager();
$user = $this->getUser();
$number_of_motivation_types = $em->getRepository(FormationMotivationType::class)
->getNumberOfTypes()[0]['count'];
$id_user = $user->getIdUtilisateur();
$ongoing_filter = $em->getRepository(FormationSession::class)
->getOngoingFilter();
$ongoing_sessions = $em->getRepository(FormationSession::class)
->getSessionsOfUserWithWorkflow($id_user, $ongoing_filter);
$ongoing_sessions_motivations = $em->getRepository(FormationSession::class)
->getMotivationsOfUserSessionsWithWorkflow($id_user, $ongoing_filter);
$ongoing = $this->fillSessions(
$ongoing_sessions,
$ongoing_sessions_motivations,
$number_of_motivation_types
);
return new JsonResponse(['success' => true, 'data' => $ongoing]);
}
#[Route(path: '/api/liste_formation_enAttente', name: 'ctsweb_formations_en_attente')]
public function formationsEnAttente()
{
$pending_sessions = null;
$pending_sessions_motivations = null;
$em = $this->doctrine->getManager();
$user = $this->getUser();
$number_of_motivation_types = $em->getRepository(FormationMotivationType::class)
->getNumberOfTypes()[0]['count'];
$id_role = $user->getUtilisateur()->getIdRole();
$id_affectation = $user->getIdAffectation() == null ? 1 : $user->getIdAffectation()->getIdAffectation();
$id_federation = $user->getIdFederation() == null ? null : $user->getIdFederation()->getIdFederation();
$pending_filter = $em->getRepository(FormationSession::class)
->getPendingFilter();
switch ($id_role) {
case RefRole::ROLE_FEDE:
case RefRole::ROLE_FEDE_INVITE:
$pending_sessions =
$em->getRepository(FormationSession::class)
->getSessionsOfFederationWithWorkflow($id_federation, $pending_filter);
$pending_sessions_motivations =
$em->getRepository(FormationSession::class)
->getMotivationsOfFederationSessionsWithWorkflow($id_federation, $pending_filter);
break;
case RefRole::ROLE_DR:
case RefRole::ROLE_DR_SIGNATAIRE:
$pending_sessions =
$em->getRepository(FormationSession::class)
->getSessionsOfAffectationWithWorkflow($id_affectation, $pending_filter);
$pending_sessions_motivations =
$em->getRepository(FormationSession::class)
->getMotivationsOfAffectationSessionsWithWorkflow($id_affectation, $pending_filter);
break;
case RefRole::ROLE_DS_ADMIN:
case RefRole::ROLE_DS_INVITE:
case RefRole::ROLE_DS_SIGNATAIRE:
case RefRole::ROLE_LECTEUR:
$pending_sessions =
$em->getRepository(FormationSession::class)
->getSessionsWithWorkflow($pending_filter);
$pending_sessions_motivations =
$em->getRepository(FormationSession::class)
->getMotivationsOfSessionsWithWorkflow($pending_filter);
break;
}
$pending = $this->fillSessions(
$pending_sessions,
$pending_sessions_motivations,
$number_of_motivation_types
);
return new JsonResponse(['success' => true, 'data' => $pending]);
}
#[Route(path: '/api/liste_formation_enCours', name: 'ctsweb_formations_en_cours')]
public function formationsEnCours()
{
$ongoing_sessions = null;
$ongoing_sessions_motivations = null;
$em = $this->doctrine->getManager();
$user = $this->getUser();
$number_of_motivation_types = $em->getRepository(FormationMotivationType::class)
->getNumberOfTypes()[0]['count'];
$id_role = $user->getUtilisateur()->getIdRole();
$id_affectation = $user->getIdAffectation() == null ? 1 : $user->getIdAffectation()->getIdAffectation();
$id_federation = $user->getIdFederation() == null ? null : $user->getIdFederation()->getIdFederation();
$ongoing_filter = $em->getRepository(FormationSession::class)
->getOngoingFilter();
switch ($id_role) {
case RefRole::ROLE_FEDE:
case RefRole::ROLE_FEDE_INVITE:
$ongoing_sessions =
$em->getRepository(FormationSession::class)
->getSessionsOfFederationWithWorkflow($id_federation, $ongoing_filter);
$ongoing_sessions_motivations =
$em->getRepository(FormationSession::class)
->getMotivationsOfFederationSessionsWithWorkflow($id_federation, $ongoing_filter);
break;
case RefRole::ROLE_DR:
case RefRole::ROLE_DR_SIGNATAIRE:
$ongoing_sessions =
$em->getRepository(FormationSession::class)
->getSessionsOfAffectationWithWorkflow($id_affectation, $ongoing_filter);
$ongoing_sessions_motivations =
$em->getRepository(FormationSession::class)
->getMotivationsOfAffectationSessionsWithWorkflow($id_affectation, $ongoing_filter);
break;
case RefRole::ROLE_DS_ADMIN:
case RefRole::ROLE_DS_INVITE:
case RefRole::ROLE_DS_SIGNATAIRE:
case RefRole::ROLE_LECTEUR:
$ongoing_sessions =
$em->getRepository(FormationSession::class)
->getSessionsWithWorkflow($ongoing_filter);
$ongoing_sessions_motivations =
$em->getRepository(FormationSession::class)
->getMotivationsOfSessionsWithWorkflow($ongoing_filter);
break;
}
$ongoing = $this->fillSessions(
$ongoing_sessions,
$ongoing_sessions_motivations,
$number_of_motivation_types
);
return new JsonResponse(['success' => true, 'data' => $ongoing]);
}
#[Route(path: '/api/formation/consulter/{id}', name: 'ctsweb_consulter_formation')]
public function consulter(FormationSession $sessionFormation)
{
$data = [];
$dataMotivation = [];
$idFormationSession = $sessionFormation->getIdFormationSession();
$em = $this->doctrine->getManager();
$listeDocuments = $em->getRepository(FormationSessionDocument::class)->getDocumentBySessionFormation($idFormationSession);
$motivations = $em->getRepository(FormationSessionMotivation::class)->getMotivationsBySessionFormation($idFormationSession);
$formations = $em->getRepository(FormationSession::class)->getSessionFormation($idFormationSession);
$workflow_filter = " fs.id_workflow =" . $formations[0]['id_workflow'];
$data['user'] = $em->getRepository(FormationSession::class)->getSessionsOfUserWithWorkflow($sessionFormation->getIdUtilisateur()->getIdUtilisateur(), $workflow_filter);
$data['user']['0']['telephonePortable'] = isset($data['user']['0']['telephoneportable']) ? $data['user']['0']['telephoneportable'] : "";
foreach ($motivations as $motivation) {
$dataMotivation[$motivation['id_formation_motivation']] = $motivation['valeur'];
}
try {
if ($sessionFormation instanceof FormationSession) {
$data[] = [
"id" => $sessionFormation->getIdFormationSession(),
"id_utilisateur" => $sessionFormation->getIdUtilisateur()->getIdUtilisateur(),
"organisme_formation" => $sessionFormation->getLibelleOrganisme(),
"titre" => $sessionFormation->getTitre(),
"titre_session" => $sessionFormation->getTitreSession(),
"certification" => $sessionFormation->getCertification(),
"libelle_formation" => $sessionFormation->getLibelleFormation(),
"id_formation_type" => $formations[0]['id_formation_type'],
"nb_jours" => $sessionFormation->getNbJours(),
"avis_dtn" => $sessionFormation->getAvisDtn(),
"avis_sh" => $sessionFormation->getAvisSh(),
"presentation_formation" => $sessionFormation->getPresentation(),
"id_workflow" => $formations[0]['id_workflow'],
"date_debut" => $sessionFormation->getDateDebut(),
"date_fin" => $sessionFormation->getDateFin(),
"lien_formation" => $sessionFormation->getLienFormation(),
"liste_documents" => (isset($listeDocuments[0]['liste_documents']) && !empty($listeDocuments[0]['liste_documents'])) ? json_decode((string) $listeDocuments[0]['liste_documents'], true, 512, JSON_THROW_ON_ERROR) : [],
"lieuFormation" => $sessionFormation->getLieuFormation(),
"responsable" => ["nom_prenom" => $sessionFormation->getPrenomResponsable() . " " . $sessionFormation->getNomResponsable(), "mail" => $sessionFormation->getMailResponsable(), "tel" => $sessionFormation->getTelephoneResponsable()],
"motivation" => $this->tab_motivation($dataMotivation),
'commentaire_dtn' => $sessionFormation->getCommentaireDtn(),
'commentaire_sh' => $sessionFormation->getCommentaireSh(),
'date_avis_dtn' => $sessionFormation->getDateAvisDtn(),
'date_sgn_sh' => $sessionFormation->getDateSgnSh(),
];
// -idFormationSession: 1
// -idFormationType: FormationType {#2099 ▶}
// -idUtilisateur: Utilisateur {#2098 ▶}
// -idWorkflow: Workflow {#2127 ▶}
// -titre: null
// -dateDebut: DateTime @1661990400 {#2079 ▶}
// -dateFin: DateTime @1662163200 {#2080 ▶}
// -libelleOrganisme: "IPOS"
// -lien: null
// -nbJours: 3
// -avisDtn: true
// -avisSh: null
// -lieuFormation: "Roubaix"
// -nomResponsable: "Gilbert"
// -prenomResponsable: "Coco"
// -mailResponsable: "coco@gilbert.com"
// -telephoneResponsable: "0612345678"
// $data[] = array(
// "idEvenement" => $idEvenement,
// "idWorkflow" => $odm->getWorkflow()->getIdWorkflow(),
// "dateDebut" => $dateDebut,
// "dateFin" => $dateFin,
// "ville" => $ville,
// "pays" => $pays->getIdPays(),
// "paysLibelle" => $pays->getLibellePays(),
// "euro" => $pays->getUnionEuropeenne(),
// "motif" => $motif,
// "statut" => $statut,
// "espace_libre_DTN" => $odm->getespace_libre_DTN(),
// "espace_libre_HS" => $odm->getespace_libre_SH(),
// "avisdtn" => $avisdtn,
// "organisme" => $organisme,
// "avisDefaut" => $avisDefaut,
// "modifyOrDeleteEvent" => ($modifyOrDeleteEvent) ? $modifyOrDeleteEvent : false,
// "idUtilisateur" => $user->getIdUtilisateur(),
// "courrielUtilisateur" => $user->getCourriel(),
// "adresseUtilisateur" => $userInformation->getAdresse(),
// "prenomNomUtilisateur" => $prenomNomagent,
// "libellePoste"=> $userInformation->getIdPoste()->getLibellePoste()
// );
}
$result = ['success' => true, 'data' => $data];
} catch (\Exception $e) {
$result = ['success' => false, 'data' => $e->getMessage()];
}
return new JsonResponse($result);
}
#[Route(path: '/api/formation/modifier/{id}', name: 'ctsweb_modifier_formation')]
public function modifierFormation(Request $request, FormationSession $formation)
{
// Utilisez la méthode 'json' pour renvoyer une réponse JSON avec les données que vous voulez déboguer
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$id_role = $this->getUser()->getUtilisateur()->getIdRole();
$em = $this->doctrine->getManager();
if (($id_role == RefRole::ROLE_DR || $id_role == RefRole::ROLE_DR_SIGNATAIRE)) {
if (!is_null($data['increment_workflow']) && $data['increment_workflow'] == true && $data['avis_sh'] == true) {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::FO_SIGNE);
$formation->setAvisSh(true);
$formation->setIdWorkflow($workflow);
} elseif ($data['avis_sh'] == false) {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::FO_REFUSE);
$formation->setAvisSh(false);
$formation->setIdWorkflow($workflow);
}
if (isset($data['commentaire_sh'])) {
$formation->setCommentaireSh($data['commentaire_sh']);
}
if (isset($data['date_debut'])) {
$newDateDebut = date_create_from_format("Y-m-d", $data['date_debut']);
$formation->setDateDebut($newDateDebut);
}
if (isset($data['date_fin'])) {
$newDateFin = date_create_from_format("Y-m-d", $data['date_fin']);
$formation->setDateFin($newDateFin);
}
$formation->setDateSgnSh(new \DateTime());
// Appel function update document
$this->updateDocument($formation, $request);
$em->persist($formation);
$em->flush();
// Appel signature
$this->initSignatureFormations($formation->getIdFormationSession(), $workflow->getIdWorkflow());
$result = ['success' => true];
$status = JsonResponse::HTTP_OK;
return new JsonResponse($result, $status);
}
// AVISDTN
elseif (($id_role == RefRole::ROLE_FEDE || $id_role == RefRole::ROLE_FEDE_INVITE)) {
if (!is_null($data['avis_dtn']) && $data['avis_dtn'] == true) {
$formation->setAvisDtn(true);
} else {
$formation->setAvisDtn(false);
}
if (isset($data['commentaire_dtn'])) {
$formation->setCommentaireDtn($data['commentaire_dtn']);
}
if (isset($data['date_debut'])) {
$newDateDebut = date_create_from_format("Y-m-d", $data['date_debut']);
$formation->setDateDebut($newDateDebut);
}
if (isset($data['date_fin'])) {
$newDateFin = date_create_from_format("Y-m-d", $data['date_fin']);
$formation->setDateFin($newDateFin);
}
$formation->setDateAvisDtn(new \DateTime());
$formation->setSignataireValidationfonctionelle($this->getUser()->getUtilisateur()->getIdUtilisateur());
// Appel function update document
$this->updateDocument($formation, $request);
if (($formation->getIdUtilisateur()->getRole()->getIdRole() == RefRole::ROLE_FEDE || $formation->getIdUtilisateur()->getRole()->getIdRole() == RefRole::ROLE_FEDE_INVITE) && (is_null($data['is_gerer_formation']) || $data['is_gerer_formation'] == false)) {
$form = $this->handleRequest($request, $formation, 'all', 'post');
$repository = $em->getRepository(FormationType::class);
$formationType = $repository->findOneBy(['idFormationType' => (int) $formation->getIdFormationType()]);
$formation->setIdFormationType($formationType);
$idFormationSession = $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
$this->updateMotivation($data, $idFormationSession);
}
$em->persist($formation);
$em->flush();
$result = ['success' => true];
$status = JsonResponse::HTTP_OK;
return new JsonResponse($result, $status);
} elseif (($id_role == RefRole::ROLE_DS_ADMIN || $id_role == RefRole::ROLE_DS_SIGNATAIRE || $id_role == RefRole::ROLE_DS_INVITE)) {
if (!is_null($data['avis_dtn']) && $data['avis_dtn'] == true) {
$formation->setAvisDtn(true);
} elseif ($data['avis_dtn'] == false && !is_null($data['avis_dtn'])) {
$formation->setAvisDtn(false);
}
if (!is_null($data['increment_workflow']) && $data['increment_workflow'] == true) {
if (!is_null($data['avis_sh']) && $data['avis_sh'] == true) {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::FO_SIGNE);
$formation->setAvisSh(true);
$formation->setIdWorkflow($workflow);
// Appel signature
} elseif ($data['avis_sh'] == false && !is_null($data['avis_sh'])) {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::FO_REFUSE);
$formation->setAvisSh(false);
$formation->setIdWorkflow($workflow);
}
$formation->setDateSgnSh(new \DateTime());
// Appel function update document
$this->updateDocument($formation, $request);
$em->persist($formation);
$em->flush();
// Appel signature
$this->initSignatureFormations($formation->getIdFormationSession(), $workflow->getIdWorkflow());
$result = ['success' => true];
$status = JsonResponse::HTTP_OK;
return new JsonResponse($result, $status);
}
$em->persist($formation);
$em->flush();
$result = ['success' => true];
$status = JsonResponse::HTTP_OK;
return new JsonResponse($result, $status);
}
$form = $this->handleRequest($request, $formation, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(FormationSession::class);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->doctrine->getManager();
if (($id_role == RefRole::ROLE_CTS)) {
if (Workflow::FO_SIGNE == $formation->getIdWorkflow()->getIdWorkflow() || Workflow::FO_REFUSE == $formation->getIdWorkflow()->getIdWorkflow()) {
$workflow = $em->getRepository(Workflow::class)->find($formation->getIdWorkflow()->getIdWorkflow());
$formation->setIdWorkflow($workflow);
} else {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::FO_EN_ATTENTE_DE_VALIDATION);
$formation->setIdWorkflow($workflow);
}
}
$entityManager = $this->doctrine->getManager();
if (!$repository->check_datedebutfin($formation)) {
$result = [
'success' => false,
'error' => 'Date de fin de la formation doit être supérieure ou égale à la date début de formation '
];
return new JsonResponse($result, JsonResponse::HTTP_OK);
}
$repository = $em->getRepository(FormationType::class);
$formationType = $repository->findOneBy(['idFormationType' => (int) $formation->getIdFormationType()]);
$formation->setIdFormationType($formationType);
$entityManager->persist($formation);
$entityManager->flush();
// Document
$document = new FormationSessionDocument();
$form = $this->handleRequestdocument($request, $document, 'all', 'post');
$idFormationSession = $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
$document->setIdFormationSessionDocument($idFormationSession);
$listeDocuments = $em->getRepository(FormationSessionDocument::class)->getDocumentBySessionFormation($formation->getIdFormationSession());
if ($listeDocuments && (is_countable($listeDocuments) ? count($listeDocuments) : 0) > 0) {
$document->setIdDocumentFormation($listeDocuments[0]['id_document_formation']);
}
$entityDocument = $this->doctrine->getManager();
$document->setLien($document->getLien());
$entityDocument->merge($document);
$entityDocument->flush();
$this->updateMotivation($data, $idFormationSession);
$result = ['success' => true];
$status = JsonResponse::HTTP_OK;
} else {
$result = [
'success' => false,
'data' => self::ERROR_VALIDATION_FORM,
'error' => (string) $form->getErrors(true, false)
];
$status = JsonResponse::HTTP_BAD_REQUEST;
}
return new JsonResponse($result, $status);
}
public function updateDocument($formation, $request)
{
$em = $this->doctrine->getManager();
$document = new FormationSessionDocument();
$form = $this->handleRequestdocument($request, $document, 'all', 'post');
$idFormationSession = $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
$document->setIdFormationSessionDocument($idFormationSession);
$listeDocuments = $em->getRepository(FormationSessionDocument::class)->getDocumentBySessionFormation($formation->getIdFormationSession());
if ($listeDocuments && (is_countable($listeDocuments) ? count($listeDocuments) : 0) > 0) {
$document->setIdDocumentFormation($listeDocuments[0]['id_document_formation']);
}
$entityDocument = $this->doctrine->getManager();
$document->setLien($document->getLien());
$entityDocument->merge($document);
$entityDocument->flush();
}
public function updateMotivation($data, $idFormationSession)
{
$em = $this->doctrine->getManager();
// $data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$datamotivation = $this->motivations($data);
foreach ($datamotivation as $motiv) {
$motivation = new FormationSessionMotivation();
$idformationmotivationType = $em->getRepository(FormationMotivationType::class)->findOneBy(['idFormationMotivation' => $motiv]);
$motivation->setIdFormationMotivation($idformationmotivationType);
$motivation->setIdFormationSession($idFormationSession);
$valeur = TRUE;
$motivation->setValeur($valeur);
$entitymotivation = $this->doctrine->getManager();
$entitymotivation->persist($motivation);
$entitymotivation->flush();
}
}
public function tab_motivation($motivations)
{
$motivation_array = ['1' => "formation_professionelle", '2' => "adaptation_immediate", '3' => "adaptation_previsible", '4' => "developement_qualification"];
foreach ($motivation_array as $v => $value) {
if (isset($motivations[$v])) {
$data[$value] = true;
} else
$data[$value] = false;
}
return $data;
}
#[Route(path: '/api/fs/{id}', name: 'api_fs_delete')]
public function delete(Request $request, FormationSession $formationSession)
{
$em = null;
$formation = null;
$entitymotivation = null;
try {
$form = $this->createDeleteForm($formationSession);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$accessRuleService = $this->accessRule;
$accessRuleService->readerFirewall();
$em = $this->doctrine->getManager();
$em->remove($formationSession);
$em->flush();
}
// Document
$document = new FormationSessionDocument();
$form = $this->handleRequestdocument($request, $document, 'all', 'post');
$idFormationSession = $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
$entityDocument = $this->doctrine->getManager();
$entityDocument->remove($document);
$entityDocument->flush();
// MOTIVATION
$motivation = new FormationSessionMotivation();
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$datamotivation = $this->motivations($data);
foreach ($datamotivation as $motiv) {
$idformationmotivationType = $em->getRepository(FormationMotivationType::class)->findOneBy(['idFormationMotivation' => $motiv]);
$motivation->setIdFormationMotivation($idformationmotivationType);
$motivation->setIdFormationSession($idFormationSession);
$valeur = TRUE;
$motivation->setValeur($valeur);
$entitymotivation = $this->doctrine->getManager();
$entitymotivation->remove($motivation);
}
$entitymotivation->flush();
$data = ['success' => true, 'data' => 'Delete Ok'];
} catch (\Exception $e) {
$data = ['success' => false, 'data' => $e->getMessage()];
}
return new JsonResponse($data);
}
/**
*
* @param FormationSession $fs The fs entity
*
* @return \Symfony\Component\Form\Form
*/
private function createDeleteForm(FormationSession $formationSession)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('api_fs_delete', ['id' => $formationSession->getIdFormationSession()]))
->setMethod(\Symfony\Component\HttpFoundation\Request::METHOD_DELETE)
->getForm();
}
/**
* @return objectFormation
*/
private function getServiceAccessRule()
{
return $this->accessRule;
}
#[Route(path: '/api/creation_formation', name: 'ctsweb_create_formations', methods: ['POST'])]
public function create(Request $request)
{
$utilisateurInformation = $this->getUser();
$utilisateur = $utilisateurInformation->getUtilisateur();
$idRole = $utilisateur->getIdRole();
$uid = $this->getUser()->getUtilisateur()->getIdUtilisateur();
$accessRuleService = $this->getServiceAccessRule();
if (!$accessRuleService->hasRightForTakingDayOff()) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
$formation = new FormationSession();
$form = $this->handleRequest($request, $formation, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(FormationSession::class);
try {
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->doctrine->getManager();
if (!$repository->check_datedebutfin($formation)) {
$result = [
'success' => false,
'error' => 'Date de fin de la formation doit être supérieure ou égale à la date début de formation '
];
return new JsonResponse($result, JsonResponse::HTTP_OK);
}
if (FormationSession::DTN === $request->request->get('from')) {
$formation->setAvisDtn(true);
$formation->setDateAvisDtn(new \DateTime());
}
$repository = $em->getRepository(FormationType::class);
$formationType = $repository->findOneBy(['idFormationType' => (int) $formation->getIdFormationType()]);
$formation->setIdFormationType($formationType);
$repository = $em->getRepository(Workflow::class);
if ($idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
$formation->setAvisDtn(true);
$formation->setDateAvisDtn(new \DateTime());
}
$workflow = $repository->findOneBy(['idWorkflow' => Workflow::FO_EN_ATTENTE_DE_VALIDATION]);
$formation->setIdWorkflow($workflow); // ajout workflow
$IdUtilisateur = $em->getRepository(Utilisateur::class)->findOneBy(['idUtilisateur' => $uid]);
$formation->setIdUtilisateur($IdUtilisateur); //
$formation->setLibelleFormation($formation->getTitre());
$entityManager->persist($formation);
$entityManager->flush();
// Document
$document = new FormationSessionDocument();
$form = $this->handleRequestdocument($request, $document, 'all', 'post');
$idFormationSession = $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
$document->setIdFormationSessionDocument($idFormationSession);
$entityDocument = $this->doctrine->getManager();
$entityDocument->persist($document);
$entityDocument->flush();
// MOTIVATION
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$datamotivation = $this->motivations($data);
foreach ($datamotivation as $motiv) {
$motivation = new FormationSessionMotivation();
$idformationmotivationType = $em->getRepository(FormationMotivationType::class)->findOneBy(['idFormationMotivation' => $motiv]);
$motivation->setIdFormationMotivation($idformationmotivationType);
$motivation->setIdFormationSession($idFormationSession);
$valeur = TRUE;
$motivation->setValeur($valeur);
$entitymotivation = $this->doctrine->getManager();
$entitymotivation->persist($motivation);
$entitymotivation->flush();
}
if ($idRole == RefRole::ROLE_CTS || $idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
$this->sendMailNotification($formation);
}
return new JsonResponse(
[
'success' => true,
'Formation' => $formation->getIdFormationSession()
],
JsonResponse::HTTP_CREATED
);
} else {
$result = [
'success' => false,
'data' => self::ERROR_VALIDATION_FORM,
'error' => (string) $form->getErrors(true, false)
];
}
} catch (\Exception $e) {
echo $e->getMessage();
$result = [
'success' => false,
'data' => self::ERROR_OCCURED
];
}
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
private function motivations($data)
{
$datamotivation = [];
$datamotivation['formation_professionelle'] = (isset($data['motivation']['formation_professionelle']) && (!$data['motivation']['formation_professionelle'])) ? false : 1;
$datamotivation['adaptation_immediate'] = (isset($data['motivation']['adaptation_immediate']) && (!$data['motivation']['adaptation_immediate'])) ? false : 2;
$datamotivation['adaptation_previsible'] = (isset($data['motivation']['adaptation_previsible']) && (!$data['motivation']['adaptation_previsible'])) ? false : 3;
$datamotivation['developement_qualification'] = (isset($data['motivation']['developement_qualification']) && (!$data['motivation']['developement_qualification'])) ? false : 4;
return array_filter($datamotivation);
}
private function sendMailNotification($formationObj)
{
$em = $this->doctrine->getManager();
$gabRep = $em->getRepository(RefGabarit::class);
$ui = $this->getUser();
$uid = $this->getUser()->getUtilisateur()->getIdUtilisateur();
$uimail = $em->getRepository(Utilisateur::class)->findBy(['idUtilisateur' => $uid])[0]->getCourriel();
$role = $this->getUser()->getUtilisateur()->getIdRole();
$subject = sprintf('CTS-WEB : Formation à valider - %s %s', $ui->getNom(), $ui->getPrenom());
$emailMailer = $this->getParameter('mailer_user');
$expediteurMail = (filter_var($emailMailer, FILTER_VALIDATE_EMAIL)) ? $emailMailer : 'donotreply@sports.gouv.fr';
//$host = $this->getParameter('host');
$mail_contact = null;
$mail_ass_info = $this->doctrine->getManager()->getRepository(ParametrageTexte::class)->getByCode('COURRIEL_ASSISTANCE_INFO');
if ((is_countable($mail_ass_info) ? count($mail_ass_info) : 0) > 0)
$mail_contact = $mail_ass_info[0]->getTexte();
if (RefRole::ROLE_FEDE === $role || RefRole::ROLE_FEDE_INVITE === $role || RefRole::ROLE_CTS === $role) {
$federation = $ui->getIdFederation()->getIdFederation();
$affectation = $ui->getIdAffectation()->getIdAffectation();
} else {
$federation = null;
$affectation = $ui->getIdAffectation()->getIdAffectation();
}
$recipients = $gabRep->emailNotification($federation, $affectation, 'emailFo');
// if (!filter_var($recipients, FILTER_VALIDATE_EMAIL)) {
// $recipients = [];
// }
if (!empty($recipients)) {
$message = (new Email())
->subject($subject)
->from($expediteurMail)
->to(...$recipients)
->html(
$this->twig->render(
'Notification/notification_formation_dtn.html.twig',
['host' => $mail_contact, 'civility' => $ui->getCivilite(), 'lastname' => $ui->getNom(), 'firstname' => $ui->getPrenom(), 'mailDemandeur' => $expediteurMail]
),
'text/html'
);
$pdfData = $this->generatePdf->generatePdfFormation($formationObj, false, $affectation, false);
$filename = sha1($formationObj->getIdFormationSession()) . '.pdf';
$pdfFilePath = $this->getParameter('dir_file_formations') . $filename;
file_put_contents($pdfFilePath, $pdfData);
if (file_exists($pdfFilePath)) {
$pieceJointe = $pdfFilePath;
} else {
$pieceJointe = false;
}
if ($pieceJointe) {
// Path to the PDF file to attach
if (file_exists($pdfFilePath)) {
// Create a attach for the attachment
chmod($pdfFilePath, 0644);
$message->attach(fopen($pdfFilePath, 'r'), $filename);
}
}
$this->mailer->send($message);
// Supprimer le fichier PDF temporaire après l'envoi de l'email (facultatif)
unlink($pdfFilePath);
}
}
/**
* @param FormationSession $formation
* @return \Symfony\Component\Form\FormInterface
*/
private function handleRequestType(
Request $request,
FormationType $formationType,
string $label,
string $validationGroup
) {
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$request->request->replace(is_array($data) ? $data : []);
$form = $this->createForm(
FormationTypeType::class,
$formationType,
['label' => $label, 'validation_groups' => $validationGroup]
);
$form->handleRequest($request);
return $form;
}
/**
* @return \Symfony\Component\Form\FormInterface
*/
private function handleRequest(
Request $request,
FormationSession $formation,
string $label,
string $validationGroup
) {
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
if ('status' != $label) {
$data['nom_responsable'] = $data['responsable']['nom_responsable'];
$data['mail_responsable'] = $data['responsable']['mail_responsable'];
$data['telephone_responsable'] = $data['responsable']['telephone_responsable'];
}
$request->request->replace(is_array($data) ? $data : []);
$form = $this->createForm(
FormationSessionType::class,
$formation,
['label' => $label, 'validation_groups' => $validationGroup]
);
$form->handleRequest($request);
return $form;
}
/**
* @return \Symfony\Component\Form\FormInterface
*/
private function handleRequestdocument(
Request $request,
FormationSessionDocument $document,
string $label,
string $validationGroup
) {
$datadocument = [];
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$datadocument['lien'] = json_encode($data['liste_documents'], JSON_THROW_ON_ERROR);
$request->request->replace(is_array($datadocument) ? $datadocument : []);
$form = $this->createForm(
FormationSessionDocumentType::class,
$document,
['label' => $label, 'validation_groups' => $validationGroup]
);
$form->handleRequest($request);
return $form;
}
/**
* @return \Symfony\Component\Form\FormInterface
*/
private function handleRequestmotivation(
Request $request,
FormationSessionMotivation $motivation,
string $label,
string $validationGroup
) {
$datamotivation = [];
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$datamotivation['formation_professionelle'] = isset($data['motivation']['formation_professionelle']) ? 1 : false;
$datamotivation['adaptation_immediate'] = isset($data['motivation']['adaptation_immediate']) ? 2 : false;
$datamotivation['adaptation_previsible'] = isset($data['motivation']['adaptation_previsible']) ? 3 : false;
$datamotivation['developement_qualification'] = isset($data['motivation']['developement_qualification']) ? 4 : false;
$request->request->replace(is_array($datamotivation) ? $datamotivation : []);
$form = $this->createForm(
FormationSessionMotivationType::class,
$motivation,
['label' => $label, 'validation_groups' => $validationGroup]
);
$form->handleRequest($request);
return $form;
}
/**
* Get a user from the Security Token Storage.
*
* @return UserInterface|object|null
*
* @throws \LogicException If SecurityBundle is not available
*
* @see TokenInterface::getUser()
*
* @final since version 3.4
*/
protected function getUser()
{
if (!$this->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}
if (null === $token = $this->get('security.token_storage')->getToken()) {
return null;
}
if (!\is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return null;
}
return $user;
}
#[Route(path: '/api/delete_formation/{id}', name: 'ctsweb_delete_formations')]
public function deleteFormations(Request $request, FormationSession $formationSession)
{
//$idFormationSession = $sessionFormation->getIdFormationSession();
try {
// $form = $this->handleRequest($request, $formationSession, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(FormationSession::class);
$cg = $repository->findOneBy(['idFormationSession' => $formationSession->getIdFormationSession()]);
$role = $this->getUser()->getUtilisateur()->getIdRole();
if ($cg) {
if ($cg->getIdWorkflow()->getIdWorkflow() == Workflow::FO_SIGNE) {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::FO_ANNULATION);
$formationSession->setIdWorkflow($workflow);
$em->persist($formationSession);
$em->flush();
$data = ['success' => true, 'data' => 'La formation a été annulé'];
return new JsonResponse($data);
} else {
$filename = sha1($formationSession->getIdFormationSession());
$repository->deleteformation($formationSession->getIdFormationSession());
$repertoire = $this->getParameter('dir_file_formations');
$nomFichier = $filename . '.pdf';
$this->supprimerFichier($repertoire, $nomFichier);
$data = ['success' => true, 'data' => 'La formation a été supprimée'];
return new JsonResponse($data);
}
}
} catch (\Exception $e) {
$data = ['success' => false, 'data' => $e->getMessage()];
return new JsonResponse($data);
}
}
public function supprimerFichier($repertoire, $nomFichier)
{
$cheminFichier = $repertoire . $nomFichier;
// Vérifiez si le fichier existe avant de le supprimer
if (file_exists($cheminFichier)) {
if (unlink($cheminFichier)) {
// return "Le fichier $nomFichier a été supprimé avec succès.";
} else {
// return "Une erreur s'est produite lors de la suppression du fichier.";
}
} else {
// return "Le fichier $nomFichier n'existe pas dans le répertoire.";
}
}
/**
* @return Response
*/
#[Route(path: '/api/export_pdf_mes_Formations/{id}', name: 'ctsweb_export_pdf_mes_Formations')]
public function exportpdfFormations(FormationSession $formation)
{
if (
Workflow::FO_SIGNE === $formation->getIdWorkflow()->getIdWorkflow()
) {
$filename = sha1($formation->getIdFormationSession()) . '.pdf';
$path = $this->getParameter('dir_file_formations') . $filename;
if (file_exists($path)) {
$content = file_get_contents($path, FILE_USE_INCLUDE_PATH);
$response = $this->getResponse($content, $filename);
} else {
$response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
}
} else {
$serviceGeneratePdf = $this->generatePdf;
$content = $serviceGeneratePdf->generatePdfFormation($formation, false);
$filename = sha1($formation->getIdFormationSession()) . '.pdf';
$response = $this->getResponse($content, $filename);
}
return $response;
}
public function getResponse(string $content, string $filename): Response
{
return new Response(
$content,
Response::HTTP_OK,
[
'Content-Type' => 'application/pdf',
'Content-Length' => strlen($content),
'Content-Disposition' => "attachment;filename=\"{$filename}",
'Accept-Ranges' => 'bytes'
]
);
}
/**
* @param Utilisateur $utilisateur
* @return JsonResponse
*/
#[Route(path: '/api/formations/archive/{idUser}', name: 'ctsweb_formations_archive', requirements: ['idUser' => '\d+'])]
public function findMyArchive($idUser)
{
$idUtilisateur = ($idUser == 0) ? $this->getUser()->getIdUtilisateur() : $idUser;
$repository = $this->doctrine->getManager()->getRepository(FormationSession::class);
$accepted = Workflow::FO_SIGNE;
$refused = Workflow::FO_REFUSE;
$filter = " fs.id_workflow IN (" . $accepted . ", " . $refused . ")";
// les formations validées/refusées de plus d’un an sont visibles uniquement dans les synthèses et archives cf. 7.2.4 et 7.3.5)
//@todo:A verifier
$formationListe = $repository->getSessiondocument($idUtilisateur, $filter);
if (isset($formationListe[0]) && isset($formationListe[0]['liste_documents'])) {
$formationListe[0]['liste_documents'] = json_decode((string) $formationListe[0]['liste_documents'], true, 512, JSON_THROW_ON_ERROR);
}
if (isset($formationListe[0]) && isset($formationListe[0]['id'])) {
$formationListe[0]['id'] = $formationListe[0]['id'];
}
try {
$data = ['success' => true, 'data' => $formationListe];
} catch (\Exception $e) {
$data = ['success' => false, 'error' => $e->getMessage()];
}
return new JsonResponse($data);
}
#[Route(path: '/api/export_formations_enCours', name: 'ctsweb_export_csv_formation_en_cours')]
public function exportFormationsEnCour()
{
$em = $this->doctrine->getManager();
$user = $this->getUser();
$federation = $user->getIdFederation();
$affectation = $user->getIdAffectation();
$listformationEnCours = $this->formationsEnCours();
$data_retour = [];
$data = (array) $listformationEnCours;
$dataValues = array_values($data)[1];
$dataArray = json_decode((string) $dataValues, true, 512, JSON_THROW_ON_ERROR);
foreach ($dataArray["data"] as $key => $value) {
$value['motivation'] = $em->getRepository(FormationSessionMotivation::class)->getMotivationsBySessionFormationtype($value['id']);
$data_retour['data'][] = $value;
}
$response = $this->exportFormation->exportListEncoursAttente((array) $data_retour, $affectation, $federation, 'en cours');
$handle = fopen('php://memory', 'r+');
$fileName = 'Formations_En_Cours_' . date('d_m_Y');
rewind($handle);
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$fileName . '.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
}
#[Route(path: '/api/export_formations_enAttente', name: 'ctsweb_export_csv_formation_en_attente')]
public function exportFormationsEnAttente()
{
$em = $this->doctrine->getManager();
$user = $this->getUser();
$federation = $user->getIdFederation();
$affectation = $user->getIdAffectation();
$listformationEnAttente = $this->formationsEnAttente();
$data_retour = [];
$data = (array) $listformationEnAttente;
$dataValues = array_values($data)[1];
$dataArray = json_decode((string) $dataValues, true, 512, JSON_THROW_ON_ERROR);
foreach ($dataArray["data"] as $key => $value) {
$value['motivation'] = $em->getRepository(FormationSessionMotivation::class)->getMotivationsBySessionFormationtype($value['id']);
$data_retour['data'][] = $value;
}
$response = $this->exportFormation->exportListEncoursAttente((array) $data_retour, $affectation, $federation, 'en attente');
$handle = fopen('php://memory', 'r+');
$fileName = 'Formations_En_Attente_'. date('d_m_Y');
rewind($handle);
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$fileName . '.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
}
function AffichageFormationArchivesAction($idUser)
{
$idUtilisateur = ($idUser == 0) ? $this->getUser()->getIdUtilisateur() : $idUser;
$em = $this->doctrine->getManager();
$repository = $em->getRepository(FormationSession::class);
$workflow_filter = $em->getRepository(FormationSession::class)->getOngoingFilter();
try {
$Liste = $repository->getSessionsOfUserWithWorkflow($idUtilisateur, $workflow_filter);
$data = ['success' => true, 'data' => $Liste];
} catch (\Exception $e) {
$data = ['success' => false, 'error' => $e->getMessage()];
}
return new JsonResponse($data);
}
public function initSignatureFormations($idformation, $idWorkflow)
{
try {
$em = $this->doctrine->getManager();
$FormationRepo = $em->getRepository(FormationSession::class);
$utilisateurRepository = $em->getRepository(Utilisateur::class);
$formationObj = $FormationRepo->find($idformation);
$info_signature = $this->getInfosSignatureSh($formationObj);
$signatureDtn = $this->getInfosSignatureDtn($formationObj);
$signature_Dtn = (isset($signatureDtn) && !empty($signatureDtn)) ? $signatureDtn : false;
$info_signature['signatureDtn'] = $signature_Dtn;
$idUtilisateur = $formationObj->getIdUtilisateur()->getIdUtilisateur();
$affectation = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdAffectation()->getIdAffectation();
$formationObj = $FormationRepo->find($idformation);
$formationObj->setDateSgnSh(new \DateTime());
$idUtilisateur = $formationObj->getIdUtilisateur()->getIdUtilisateur();
$emails = $utilisateurRepository->findCourrielById($idUtilisateur);
$email = isset($emails[0]['courriel']) ? $emails[0]['courriel'] : null;
$em->persist($formationObj);
$em->flush();
$this->generatePdf->generatePdfFormation($formationObj, false, $affectation, $info_signature);
$filename = sha1($formationObj->getIdFormationSession()) . '.pdf';
$pdfFilePath = $this->getParameter('dir_file_formations') . $filename;
if (file_exists($pdfFilePath)) {
$pieceJointe = $pdfFilePath;
} else {
$pieceJointe = false;
}
if ($idWorkflow == Workflow::FO_SIGNE) {
$decision = EmailSHDecision::SIGNED;
} else {
$decision = EmailSHDecision::REFUSED;
}
$beginDate = $formationObj->getDateDebut();
$mail = $this->emailSHDecision->getMailFormation(
$decision,
EmailSHDecision::FO,
$email,
$beginDate,
$pieceJointe,
$filename
);
if ($mail) {
$this->mailer->send($mail);
}
$message = 'Tous les conges ont été signés avec succès.';
$return = array(
'success' => true,
'data' => $message
);
} catch (\Exception $e) {
$message = 'Un ou plusieurs congés n\'ont pu être signés.';
$return = array(
'success' => false,
'data' => $e->getMessage()
);
}
return new JsonResponse(
$return,
JsonResponse::HTTP_CREATED
);
}
public function getInfosSignatureSh($formationObj)
{
$em = $this->doctrine->getManager();
$idSignataire = $this->getUser()->getUtilisateur()->getIdUtilisateur();
$affectationSignataire = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idSignataire)->getIdAffectation()->getIdAffectation();
$idUtilisateur = $formationObj->getIdUtilisateur()->getIdUtilisateur();
$affectation = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdAffectation()->getIdAffectation();
# TODO : Valider la logique de sélection du signataire en fonction de l'affectation.
/* if ($affectationSignataire == $affectation) {
$signataire = $em->getRepository(UtilisateurInformation::class)->findOneBy(['utilisateur' => $idSignataire]);
} else {
if ($affectation != 1) {
$drsignataire = $em->getRepository(UtilisateurInformation::class)->findDrSuperieur($affectation);
} else {
$drsignataire = $em->getRepository(UtilisateurInformation::class)->findDsSuperieur($affectation);
}
$signataire = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($drsignataire);
}
$path = $signataire->getScan() ? $this->getParameter('dir_file_signature') . $signataire->getScan()->getAbsolutePath() : '';*/
if ($affectation != 1) {
$drsignataire = $em->getRepository(UtilisateurInformation::class)->findDrSuperieur($affectation);
} else {
$drsignataire = $em->getRepository(UtilisateurInformation::class)->findDsSuperieur($affectation);
}
$signataire = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($drsignataire);
$path = $signataire->getScan() ? $this->getParameter('dir_file_signature') . $signataire->getScan()->getAbsolutePath() : '';
if ($path && file_exists($path)) {
chmod($path, 0644);
$content = file_get_contents($path);
if ($content !== false) {
$pathvrai = $path;
} else {
// Gérer l'erreur si le contenu n'a pas pu être lu
$pathvrai = "";
}
} else {
// Gérer l'erreur si le fichier n'existe pas
$pathvrai = "";
}
$info_signature = [
'nom' => $signataire->getNom(),
'prenom' => $signataire->getPrenom(),
'dateSignature' => date("d/m/Y"),
'sup' => true,
'fonction' => $signataire->getFonction(),
'path' => $pathvrai,
'civilite' => $signataire->getCivilite(),
'signatureDtn' => false
];
return $info_signature;
}
public function getInfosSignatureDtn($formationObj)
{
$em = $this->doctrine->getManager();
$idUtilisateur = $formationObj->getIdUtilisateur()->getIdUtilisateur();
$signatureDtn = [];
if (!is_null($formationObj->getSignataireValidationfonctionelle())) {
$informationSignataireDTN = $em->getRepository(UtilisateurInformation::class)->findOneBy(['utilisateur' => $formationObj->getSignataireValidationfonctionelle()]);
if ($informationSignataireDTN && !is_null($informationSignataireDTN->getIdPoste())) {
if ($informationSignataireDTN->getIdFederation()) {
$oFede = $em->getRepository(RFederation::class)->getRFederationByRefFederation($informationSignataireDTN->getIdFederation()->getIdFederation());
$libelleFedertation = $oFede->getRSerLibl();
}
$signatureDtn = [
'nom' => $informationSignataireDTN->getNom(),
'prenom' => $informationSignataireDTN->getPrenom(),
'fonction' => $informationSignataireDTN->getFonction(),
'path' => $informationSignataireDTN->getScan() ? $this->getParameter('dir_file_signature') . $informationSignataireDTN->getScan()->getAbsolutePath() : false,
'federation' => $libelleFedertation ?: '',
'civilite' => $informationSignataireDTN->getCivilite()
];
}
} else {
$idFederation = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdFederation()->getIdFederation();
$UserInfoDTN = $em->getRepository(UtilisateurInformation::class)->getUserInfoDTN($idFederation, 3);
if (isset($UserInfoDTN[0]) && is_array($UserInfoDTN[0])) {
$libelleFedertation = $UserInfoDTN[0]['r_ser_libl'];
$idsignDtn = $UserInfoDTN[0]['id_utilisateur'];
$infSignataireDTN = $em->getRepository(UtilisateurInformation::class)->findOneBy(array('utilisateur' => $idsignDtn));
$path = $infSignataireDTN->getScan() ? $this->getParameter('dir_file_signature') . $infSignataireDTN->getScan()->getAbsolutePath() : '';
if ($path && file_exists($path)) {
chmod($path, 0644);
$content = file_get_contents($path);
if ($content !== false) {
$pathvrai = $path;
} else {
// Gérer l'erreur si le contenu n'a pas pu être lu
$pathvrai = "";
}
} else {
// Gérer l'erreur si le fichier n'existe pas
$pathvrai = "";
}
$signatureDtn = array(
'nom' => $infSignataireDTN->getNom(),
'prenom' => $infSignataireDTN->getPrenom(),
'fonction' => $infSignataireDTN->getFonction(),
'path' => $pathvrai,
'federation' => $libelleFedertation ? $libelleFedertation : '',
'civilite' => $infSignataireDTN->getCivilite()
);
}
}
return (isset($signatureDtn) && !empty($signatureDtn)) ? $signatureDtn : false;
}
#[Route('/api/formation/update_state/{id}', name: 'cts_update_formation_state', methods: ['POST'])]
/**
* Cette méthode met à jour le statut d'une formation existante.
*
* @param Request $request La requête contenant les données de la formation à mettre à jour.
* @param int $id L'ID de la formation à mettre à jour.
* @return JsonResponse Retourne un JSON contenant l'ID de la formation mis à jour ou un message d'erreur si la mise à jour échoue.
*/
public function updateStateForm(Request $request, FormationSession $formation): JsonResponse
{
// Initialisation du gestionnaire d'entités
$em = $this->doctrine->getManager();
// Décodage des données reçues en JSON
$formData = json_decode($request->getContent(), true);
// Création et traitement du formulaire
//TODO : à vérifier la soumission du formulaire
#$form = $this->handleRequest($request, $formation, 'status', 'post');
// Récupération du workflow associé à la formation
$workflow = $em->getRepository(Workflow::class)->find($formData['idWorkflow']);
try {
$formation->setIdWorkflow($workflow);
// Si le workflow est 'signé' ou 'refusé'
if ((Workflow::FO_SIGNE == $workflow->getIdWorkflow()) || (Workflow::FO_REFUSE == $workflow->getIdWorkflow())) {
// Appel de la méthode de signature
//TODO : à bien vérifier
$this->initSignatureFormations($formation->getIdFormationSession(), $workflow->getIdWorkflow());
// Mise à jour de la date de signature
$formation->setDateSgnSh(new \DateTime());
}
//mettre à jour l'avis du SH
if (Workflow::FO_SIGNE == $workflow->getIdWorkflow()) {
$formation->setAvisSh(true);
} elseif (Workflow::FO_REFUSE == $workflow->getIdWorkflow()) {
$formation->setAvisSh(false);
}
// Enregistrement des modifications dans la base de données
$em->persist($formation);
$em->flush();
$data = [
'success' => true,
'message' => 'La formation a été mise à jour avec succès'
];
} catch (\Exception $e) {
// Gestion des erreurs inattendues
$data = [
'status' => Response::HTTP_INTERNAL_SERVER_ERROR,
'message' => 'Une erreur est survenue lors de la mise à jour de la formation. Veuillez réessayer ultérieurement. ' . $e->getMessage()
];
}
return new JsonResponse($data);
}
function retirerAccents($str)
{
$str = str_replace(
['à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ'],
['a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y'],
$str
);
return strtolower(str_replace(" ", "", $str));
}
}