<?php
namespace App\Controller;
use JMS\Serializer\SerializationContext;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Conge;
use App\Entity\CongeDroitAnnuel;
use App\Entity\ParametrageTexte;
use App\Entity\RefRole;
use App\Entity\Utilisateur;
use App\Entity\UtilisateurInformation;
use App\Entity\Workflow;
use App\Form\CongeType;
use App\Entity\RefGabarit;
use App\Entity\RefAffectation;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Mailer\MailerInterface;
use App\Services\GeneratePdf;
use App\Services\AccessRule;
use JMS\Serializer\SerializerInterface;
use Symfony\Component\Mime\Email;
use App\Services\Lib\EmailSHDecision;
use App\Entity\CongeType as CongeTypes;
use App\Entity\DemandeReport;
use Twig\Environment;
use App\Entity\RefAffectationCalendrier;
use Symfony\Component\Mime\Part\DataPart;
/**
* Class CongeController
* @package App\Controller
*/
class CongeController 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 $doctrine;
private $mailer;
private $generatePdf;
private $accessRule;
private $serializer;
private $twig;
private $emailSHDecision;
public function __construct(ManagerRegistry $doctrine, MailerInterface $mailer, GeneratePdf $generatePdf, Environment $twig, AccessRule $accessRule, SerializerInterface $serializer, EmailSHDecision $emailSHDecision)
{
$this->doctrine = $doctrine;
$this->mailer = $mailer;
$this->generatePdf = $generatePdf;
$this->accessRule = $accessRule;
$this->serializer = $serializer;
$this->emailSHDecision = $emailSHDecision;
$this->twig = $twig;
}
#[Route(path: '/api/conges/{id}', name: 'ctsweb_get_conge', methods: ['GET'], requirements: ['id' => '\d+'])]
public function detail(Conge $conge): JsonResponse
{
$jsonv = [];
$repositoryUI = $this->doctrine->getManager()->getRepository(UtilisateurInformation::class);
$uid = $conge->getUtilisateur()->getIdUtilisateur();
$utilisateurData = $repositoryUI->findDataForPageProfil($uid);
$accessRuleService = $this->getServiceAccessRule();
if (!$accessRuleService->hasRightTodetailAccess($conge)) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
// Obtenir les données sérialisées de "$conge" et les décoder en tableau associatif
$congeSerialized = $this->serialize($conge);
$congeSerializedArray = json_decode($congeSerialized, true);
// Appeler les méthodes de l'entité "Conge" sur l'objet "$conge"
$uData = $this->serialize($utilisateurData);
$jsonv['items']['conge'] = $congeSerializedArray;
if (isset($jsonv['items']['conge']['items']['pieceMotif'])) {
$jsonv['items']['conge']['items']['pieceMotif'] = (isset($jsonv['items']['conge']['items']['pieceMotif']) && !empty($jsonv['items']['conge']['items']['pieceMotif'])) ? json_decode((string) $jsonv['items']['conge']['items']['pieceMotif'], true, 512, JSON_THROW_ON_ERROR) : [];
}
$jsonv['items']['user'] = json_decode((string) $uData, true, 512, JSON_THROW_ON_ERROR);
$json_merge = json_encode($jsonv);
return new JsonResponse($json_merge, JsonResponse::HTTP_OK, [], true);
}
#[Route(path: '/api/conges/state/{state}', name: 'ctsweb_list_conge', methods: ['GET'])]
public function list(string $state): JsonResponse
{
$validStates = array_keys(Workflow::STATES);
if (!in_array($state, $validStates)) {
return new JsonResponse([], JsonResponse::HTTP_BAD_REQUEST);
}
$entityManager = $this->doctrine->getManager();
$today = new \DateTime();
if (in_array($state, ['accepted', 'rejected'])) {
$conges = $entityManager
->getRepository(Conge::class)
->findAllUntillCurrentDate($this->getUser()->getUtilisateur());
$report = $entityManager
->getRepository(DemandeReport::class)
->findAllUntillCurrentDate($this->getUser()->getUtilisateur());
} else {
$conges = $entityManager
->getRepository(Conge::class)
->findAllUntillCurrentWaiting($this->getUser()->getUtilisateur());
$report = $entityManager
->getRepository(DemandeReport::class)
->findAllUntillCurrentWaiting($this->getUser()->getUtilisateur());
}
$dataconges = array_map(function ($conge) use ($today) {
$congeArray = json_decode((string) $this->serializeto($conge), true, 512, JSON_THROW_ON_ERROR);
$congeArray[0]['dateDebut'] = date_format(date_create($congeArray[0]['dateDebut']), 'Y-m-d');
$congeArray[0]['dateFin'] = date_format(date_create($congeArray[0]['dateFin']), 'Y-m-d');
$congeArray[0]['choixConge'] = 1;
if ($conge->getDateFin() < $today) {
$congeArray[0]['isTooLate'] = true;
}
return $congeArray[0];
}, $conges);
$newReport = $this->createNewReport();
$datareport = array_map(function ($report) use ($newReport) {
$reportArray = json_decode((string) $this->serializeto($report), true, 512, JSON_THROW_ON_ERROR);
return array_merge($reportArray[0], $newReport);
}, $report);
$mergedData = array_merge($dataconges, $datareport);
return new JsonResponse(
$this->serialize($mergedData),
JsonResponse::HTTP_OK,
[],
true
);
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/conges/archive/{utilisateur}', name: 'ctsweb_conges-archive', methods: ['GET'], requirements: ['utilisateur' => '\d+'])]
public function findMyArchive(Utilisateur $utilisateur)
{
$entityManager = $this->doctrine->getManager();
$arhives = $entityManager
->getRepository(Conge::class)
->findBy(
[
'workflow' => [Workflow::CO_SIGN, Workflow::CO_REJECT, Workflow::CO_ANNULE],
'utilisateur' => $utilisateur
],
['dateDebut' => 'DESC']
);
$arhivesreport = $entityManager
->getRepository(DemandeReport::class)
->findBy([
'workflow' => [Workflow::RE_SIGN, Workflow::RE_REJECT, Workflow::RE_ANNULE],
'utilisateur' => $utilisateur
]);
$newReport = $this->createNewReport();
$datareport = array_map(function ($arhivesreport) use ($newReport) {
$reportArray = json_decode((string) $this->serializeto($arhivesreport), true, 512, JSON_THROW_ON_ERROR);
return array_merge($reportArray[0], $newReport);
}, $arhivesreport);
$mergedData = array_merge($arhives, $datareport);
return new JsonResponse(
$this->serialize($mergedData),
JsonResponse::HTTP_OK,
[],
true
);
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/conges/management/state/{state}', name: 'ctsweb_list_for_management_conge', methods: ['GET'])]
public function managementList(string $state)
{
$repositoryUI = $this->doctrine->getManager()->getRepository(UtilisateurInformation::class);
$uid = $this->getUser()->getIdUtilisateur();
$utilisateurData = $repositoryUI->findDataForPageProfil($uid);
$role = $this->getUser()->getUtilisateur()->getIdRole();
if (!in_array($role, Utilisateur::MANAGE)) {
return new JsonResponse([], JsonResponse::HTTP_FORBIDDEN);
}
$states = ['current', 'waiting'];
if (!in_array($state, $states)) {
return new JsonResponse([], JsonResponse::HTTP_BAD_REQUEST);
}
$entityManager = $this->doctrine->getManager();
$affectation = $this->getUser()->getIdAffectation();
$federation = $this->getUser()->getIdFederation();
if ('waiting' == $state) {
$workflow = Workflow::CO_WAITING;
$workflowR = Workflow::RE_WAITING;
//federation on
if (RefRole::ROLE_FEDE === $role || RefRole::ROLE_FEDE_INVITE === $role) {
$affectation = null;
} else if (RefRole::ROLE_DR === $role || RefRole::ROLE_DR_SIGNATAIRE === $role || RefRole::ROLE_GCR === $role) {
$federation = null;
} else {
$federation = null;
$affectation = null;
}
} else {
$workflow = Workflow::CO_ACCEPTED;
$workflowR = Workflow::RE_SIGN;
if (RefRole::ROLE_FEDE === $role || RefRole::ROLE_FEDE_INVITE === $role) {
$affectation = null;
} else if (RefRole::ROLE_DR === $role || RefRole::ROLE_DR_SIGNATAIRE === $role || RefRole::ROLE_GCR === $role) {
$federation = null;
} else {
$affectation = null;
$federation = null;
}
}
if (RefRole::ROLE_DS_ADMIN === $role) {
$conges = $entityManager
->getRepository(Conge::class)
->findByWorkflowAndUserTypeAdmin($workflow, $federation, $affectation);
$report = $entityManager
->getRepository(DemandeReport::class)
->findByWorkflowAndUserTypeAdmin($workflowR, $federation, $affectation);
} else {
$conges = $entityManager
->getRepository(Conge::class)
->findByWorkflowAndUserType($workflow, $federation, $affectation);
$report = $entityManager
->getRepository(DemandeReport::class)
->findByWorkflowAndUserType($workflowR, $federation, $affectation);
}
if (
(Workflow::CO_ACCEPTED === $workflow || Workflow::CO_SIGN === $workflow)
&& (in_array($role, Utilisateur::MANAGER))
) {
$today = (new \DateTime())->format("Y-m-d");
/** @var Conge $conge */
foreach ($conges as $conge) {
$isTooLate = true;
$end = clone $conge['dateFin'];
if (RefRole::ROLE_DS_ADMIN === $role && $end->modify('+3 month')->format("Y-m-d") > $today) {
$isTooLate = false;
} elseif ($end->format("Y-m-d") > $today) {
$isTooLate = false;
}
$conge['isTooLate'] = $isTooLate;
}
}
$dataconges = [];
foreach ($conges as $conge) {
$cong = array();
if (isset($conge)) {
$cong = json_decode((string) $this->serializeto($conge), true, 512, JSON_THROW_ON_ERROR);
if (isset($cong) && (is_countable($cong) ? count($cong) : 0) > 0) {
$cong[0]['dateDebut'] = date_format(date_create($cong[0]['dateDebut']), 'Y-m-d');
$cong[0]['dateFin'] = date_format(date_create($cong[0]['dateFin']), 'Y-m-d');
$dataconges[] = $cong[0];
}
}
}
$datareport = [];
/** @var DemandeReport $report */
foreach ($report as $reports) {
if (isset($reports)) {
$rep = json_decode((string) $this->serializeto($reports), true, 512, JSON_THROW_ON_ERROR);
if (isset($rep) && (is_countable($rep) ? count($rep) : 0) > 0) {
// $datareport[] = $rep[0];
$newReport = $this->createNewReportDtnSH();
}
$datareport[] = array_merge($rep[0], $newReport);
}
};
// Fusionner les tableaux $dataconges et $report
$mergedData = array_merge($dataconges, $datareport);
return new JsonResponse(
$this->serialize($mergedData),
JsonResponse::HTTP_OK,
[],
true
);
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/conges', name: 'ctsweb_create_conge', methods: ['POST'])]
public function create(Request $request)
{
$utilisateurInformation = $this->getUser();
$utilisateur = $utilisateurInformation->getUtilisateur();
$idRole = $utilisateur->getIdRole();
$accessRuleService = $this->getServiceAccessRule();
if (!$accessRuleService->hasRightForTakingDayOff()) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
$conge = new Conge();
$form = $this->handleRequest($request, $conge, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(Conge::class);
$reporeport = $em->getRepository(DemandeReport::class);
try {
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->doctrine->getManager();
// $demande_enCours = $reporeport->countCurrentWaiting($year, $this->getUser());
// if (!$demande_enCours) {
// // $retour['conge'] = false;
// $retour['demande_report'] = false;
// return $retour;
// }
// $today = (new \DateTime());
// $year = $today->format("Y");
// var_dump( $conge->getDateFin());
// var_dump( new \DateTime("$year-09-01"));
// die();
if ($conge->getCongeType()->getCode() == CongeTypes::CAN || $conge->getCongeType()->getCode() == CongeTypes::RTT) {
$id_affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
$requiredCheval = $this->getChevalConge($conge, $id_affectation);
if (!$requiredCheval) {
$result = [
'success' => false,
'error' => sprintf('Votre période de congés est à cheval sur deux années, veuillez déposer une demande par année de gestion')
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
if ($conge->getCongeType()->getCode() == CongeTypes::CEX) {
$requiredFields = $this->getRequiredMotifOrPieceJointeForCexConge($conge);
if (!empty($requiredFields)) {
$result = [
'success' => false,
'error' => sprintf(' %s pour un congé de type CE', $requiredFields)
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
//verifier le soldes des comptes pour le Cet et RAA
if ($conge->getCongeType()->getCode() == CongeTypes::CET || $conge->getCongeType()->getCode() == CongeTypes::RAA) {
if (!$this->verifier_solde_comptes($conge)) {
$result = [
'success' => false,
'error' => sprintf('Le nombre de jours ouvrés demandé doit être égale ou inférieur au solde de votre %s.', $conge->getCongeType()->getLibelle())
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
if ($conge->getCongeType()->getCode() == CongeTypes::RAA) {
$id_affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
if (!$repository->checkDemandeReportAA($conge, $id_affectation)) {
$result = [
'success' => false,
'error' => sprintf('la date de début et la date de fin de congés de %s doivent être incluses dans la période de débit du report année antérieure fixée par le SH', $conge->getCongeType()->getLibelle())
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
if (!$repository->check_chevauchement($conge, $this->getUser()->getIdUtilisateur())) {
$result = [
'success' => false,
'error' => 'Il y a déjà un congé déposé sur cette période'
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
if (Conge::DTN === $request->request->get('from')) {
$conge->setAvisDtn(true);
}
// $IdUtilisateur = $em->getRepository(Utilisateur::class)->findOneBy(['idUtilisateur' => $this->getUser()->getIdUtilisateur()]);
// $conge->setUtilisateur($IdUtilisateur);
$entityManager->persist($conge);
$entityManager->flush();
if ($idRole == RefRole::ROLE_CTS || $idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
$this->sendMailNotification();
}
return new JsonResponse(
[
'success' => true,
'Conge' => $conge->getId()
],
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 sendMailNotification()
{
$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 : Congés à 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, 'emailConges');
// 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_conge_dtn.html.twig',
['host' => $mail_contact, 'civility' => $ui->getCivilite(), 'lastname' => $ui->getNom(), 'firstname' => $ui->getPrenom(), 'mailDemandeur' => $expediteurMail]
),
'text/html'
);
$this->mailer->send($message);
}
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/update_conges/{id}', name: 'ctsweb_update_conge', methods: ['POST'], requirements: ['id' => '\d+'])]
public function update(Request $request, Conge $conge)
{
$utilisateurInformation = $this->getUser();
$accessRuleService = $this->getServiceAccessRule();
$utilisateur = $utilisateurInformation->getUtilisateur();
$idRole = $utilisateur->getIdRole();
if (!$accessRuleService->hashRightToModify($conge)) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
// $conge = new Conge();
$form = $this->handleRequest($request, $conge, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(Conge::class);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->doctrine->getManager();
$workflow = $em->getRepository(Workflow::class)->find(Workflow::CO_WAITING);
if (Workflow::CO_SIGN != $conge->getWorkflow()->getIdWorkflow())
$conge->setWorkflow($workflow);
$entityManager = $this->doctrine->getManager();
// if ($idRole == RefRole::ROLE_CTS || $idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
if ($idRole == RefRole::ROLE_CTS) {
if ($conge->getCongeType()->getCode() == CongeTypes::CAN || $conge->getCongeType()->getCode() == CongeTypes::RTT) {
$id_affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
$requiredCheval = $this->getChevalConge($conge, $id_affectation);
if (!$requiredCheval) {
$result = [
'success' => false,
'error' => sprintf('Votre période de congés est à cheval sur deux années, veuillez déposer une demande par année de gestion')
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
if ($conge->getCongeType()->getCode() == CongeTypes::CEX) {
$requiredFields = $this->getRequiredMotifOrPieceJointeForCexConge($conge);
if (!empty($requiredFields)) {
$result = [
'success' => false,
'error' => sprintf(' %s pour un congé de type CE', $requiredFields)
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
//verifier le soldes des comptes pour le Cet et RAA
if ($conge->getCongeType()->getCode() == CongeTypes::CET || $conge->getCongeType()->getCode() == CongeTypes::RAA) {
if (!$this->verifier_solde_comptes($conge)) {
$result = [
'success' => false,
'error' => sprintf('Le nombre de jours ouvrés demandé doit être égale ou inférieur au solde de votre %s.', $conge->getCongeType()->getLibelle())
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
if ($conge->getCongeType()->getCode() == CongeTypes::RAA) {
$id_affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
if (!$repository->checkDemandeReportAA($conge, $id_affectation)) {
$result = [
'success' => false,
'error' => sprintf('la date de début et la date de fin de congés de %s doivent être incluses dans la période de débit du report année antérieure fixée par le SH', $conge->getCongeType()->getLibelle())
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
if (!$repository->check_chevauchement($conge, $this->getUser()->getIdUtilisateur())) {
$result = [
'success' => false,
'error' => 'Il y a déjà un congé déposé sur cette période'
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
$entityManager->persist($conge);
$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/delete_conges/{id}', name: 'ctsweb_delete_conge', requirements: ['id' => '\d+'])]
public function delete(Conge $conge)
{
try {
$em = $this->doctrine->getManager();
$repository = $em->getRepository(Conge::class);
$cg = $repository->findOneBy(['id' => $conge->getId()]);
if ($cg) {
if ($cg->getWorkflow()->getIdWorkflow() == Workflow::CO_SIGN or $cg->getWorkflow()->getIdWorkflow() == Workflow::CO_ACCEPTED) {
$workflow = $em->getRepository(Workflow::class)->find(Workflow::CO_ANNULE);
$conge->setWorkflow($workflow);
$em->persist($conge);
$em->flush();
$data = ['success' => true, 'data' => 'Le congé a été annulé'];
return new JsonResponse($data);
} else {
$repository->deleteConge($conge->getId());
$data = ['success' => true, 'data' => 'Le congé a été supprimé'];
return new JsonResponse($data);
}
}
} catch (\Exception $e) {
$data = ['success' => false, 'data' => $e->getMessage()];
return new JsonResponse($data);
}
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/conges/{id}/change-status', name: 'ctsweb_change_status_conge', methods: ['POST'], requirements: ['id' => '\d+'])]
public function changeStatus(Request $request, Conge $conge)
{
$accessRuleService = $this->getServiceAccessRule();
if (!$accessRuleService->isAdmin()) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
$form = $this->handleRequest($request, $conge, 'status', 'status');
if ($form->isSubmitted() && $form->isValid()) {
$conge->setFrom(Conge::ADMIN);
$entityManager = $this->doctrine->getManager();
$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);
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/conges/response/{id}', name: 'ctsweb_response_conge', methods: ['POST'], requirements: ['id' => '\d+'])]
public function response(Request $request, Conge $conge)
{
$form = $this->handleRequest(
$request,
$conge,
'response',
'response'
);
$entityManager = $this->doctrine->getManager();
if ($form->isValid()) {
$accessRuleService = $this->getServiceAccessRule();
$this->update($request, $conge);
if (Conge::DTN === $conge->getFrom()) {
if (!$accessRuleService->hashRightToResponse($conge) && !$accessRuleService->isAdmin()) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
$congeId = $conge->getId();
$avisDtn = ($conge->getResponse()) ? 1 : 0;
$update = $entityManager->getRepository(Conge::class)->updateavisDtn($congeId, $avisDtn);
// $conge->setAvisDtn($conge->getResponse());
} elseif (Conge::MANAGER === $conge->getFrom() || Conge::ADMIN === $conge->getFrom()) {
$this->setWorkflow($conge);
}
$entityManager->flush();
if ($conge->getResponse() && !is_null($conge->getId())) {
$role = $this->getUser()->getUtilisateur()->getIdRole();
if (in_array($role, Utilisateur::MANAGER)) {
$this->initSignatureConges($conge->getId());
}
}
$result = ["success" => true];
$response = JsonResponse::HTTP_OK;
} else {
$result = [
'success' => false,
'data' => self::ERROR_VALIDATION_FORM,
'error' => (string) $form->getErrors(true, false)
];
$response = JsonResponse::HTTP_BAD_REQUEST;
}
return new JsonResponse($result, $response);
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/conges/generate-to-print', name: 'ctsweb_print_conge', methods: ['POST'])]
public function generateToPrint(Request $request)
{
$accessRuleService = $this->getServiceAccessRule();
if (!$accessRuleService->hasRightForTakingDayOff()) {
return new JsonResponse('', JsonResponse::HTTP_FORBIDDEN);
}
$conge = new Conge();
$form = $this->handleRequest($request, $conge, 'all', 'post');
$em = $this->doctrine->getManager();
$repository = $em->getRepository(Conge::class);
try {
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->doctrine->getManager();
$conge->setUtilisateur($this->getUser()->getUtilisateur());
$serviceGeneratePdf = $this->generatePdf;
$entityManager->persist($conge);
$content = $serviceGeneratePdf->generatePdf($conge, true);
$filename = sha1($conge->getId()) . '.pdf';
$response = $this->getResponse($content, $filename);
} else {
$response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
}
} catch (\Exception) {
$response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
}
return $response;
}
/**
* @return Response
*/
#[Route(path: '/api/conges/pdf/{id}', name: 'ctsweb_conges_generate-pdf', methods: ['GET'], requirements: ['id' => '\d+'])]
public function pdf(Conge $conge)
{
if (
Workflow::CO_REJECT === $conge->getWorkflow()->getIdWorkflow()
|| Workflow::CO_SIGN === $conge->getWorkflow()->getIdWorkflow()
) {
$filename = sha1($conge->getId()) . '.pdf';
$path = $this->getParameter('dir_file_conge') . $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->generatePdf($conge, false);
$filename = sha1($conge->getId()) . '.pdf';
$response = $this->getResponse($content, $filename);
}
return $response;
}
#[Route(path: '/api/conges/status/list', name: 'ctsweb_conges_status-list-pdf', methods: ['GET'], requirements: ['id' => '\d+'])]
public function statusList(): JsonResponse
{
$entityManager = $this->doctrine->getManager();
$statuses = $entityManager
->getRepository(Workflow::class)
->findBy(['idWorkflow' => Workflow::FILTER]);
return new JsonResponse(
$this->serialize($statuses),
JsonResponse::HTTP_OK,
[],
true
);
}
/**
* @return \Symfony\Component\Form\FormInterface
*/
private function handleRequest(
Request $request,
Conge $conge,
string $label,
string $validationGroup
) {
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
if (isset($data['pieceMotif'])) {
$data['pieceMotif'] = json_encode($data['pieceMotif'], JSON_THROW_ON_ERROR);
}
$request->request->replace(is_array($data) ? $data : []);
$form = $this->createForm(
CongeType::class,
$conge,
['label' => $label, 'validation_groups' => $validationGroup]
);
$form->handleRequest($request);
return $form;
}
/**
* @param array $states
* @return mixed
*/
private function serializeto($item)
{
$data = [$item];
$context = new SerializationContext();
$context->setSerializeNull(true);
return $this->serializer->serialize($data, 'json', $context);
}
/**
* @param array $states
* @return mixed
*/
private function serialize($item)
{
$data = ["items" => $item];
$context = new SerializationContext();
$context->setSerializeNull(true);
return $this->serializer->serialize($data, 'json', $context);
}
/**
* @return object
*/
private function getServiceAccessRule()
{
return $this->accessRule;
}
private function setWorkflow(Conge $conge)
{
$workflow = Workflow::CO_REJECT;
if ($conge->getResponse()) {
$workflow = Workflow::CO_ACCEPTED;
}
$entityManager = $this->doctrine->getManager();
$workflowEntity = $entityManager
->getRepository(Workflow::class)
->find($workflow);
$conge->setWorkflow($workflowEntity);
}
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'
]
);
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/calendrier-conges-info', name: 'ctsweb_calendrier-conges-info', methods: ['GET'])]
public function getCalendrierConges()
{
try {
$utilisateurInformation = $this->getUser();
$affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
$entityManager = $this->doctrine->getManager();
$affectionEntity = $entityManager
->getRepository(RefAffectation::class)
->findOneBy(["idAffectation" => $affectation]);
// $dateBascule = $affectionEntity->getDateBascule();
$today = new \DateTime();
$today = $today->format('Y-m-d');
$getRefCalendrier = $entityManager
->getRepository(RefAffectationCalendrier::class)
->getRefCalendrier($affectation);
$calendrier = $getRefCalendrier['calendrierAffectation'];
$getCheckbox = $entityManager
->getRepository(RefAffectationCalendrier::class)
->findLastByRefAffectationId($affectation);
if (isset($getCheckbox['0']) && !empty($getCheckbox['0'])) {
$Checkbox = $getCheckbox['0']['calendrier_scolaire'];
} else {
$Checkbox = false;
}
$data = ["data" => ["calendrier_scolaire" => $calendrier, "calendrier_checkbox" => $Checkbox]];
$data = json_encode($data);
return new JsonResponse($data, JsonResponse::HTTP_OK, [], true);
} catch (\Exception $e) {
echo $e->getMessage();
$result = [
'success' => false,
'data' => self::ERROR_OCCURED
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/calendrier-conges-info-form', name: 'ctsweb_calendrier-conges-info-form', methods: ['GET'])]
public function getCalendrierCongesForm()
{
try {
$utilisateurInformation = $this->getUser();
$affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
$entityManager = $this->doctrine->getManager();
$getRefCalendrier = $entityManager
->getRepository(RefAffectationCalendrier::class)
->getRefCalendrier($affectation);
$calendrier = $getRefCalendrier['calendrierAffectation'];
$data = ["data" => ["calendrier_scolaire" => $calendrier]];
$data = json_encode($data);
return new JsonResponse($data, JsonResponse::HTTP_OK, [], true);
} catch (\Exception $e) {
echo $e->getMessage();
$result = [
'success' => false,
'data' => self::ERROR_OCCURED
];
return new JsonResponse($result, JsonResponse::HTTP_BAD_REQUEST);
}
}
#[Route(path: '/api/calendrier-conges', name: 'ctsweb_calendrier-conges', methods: ['POST'])]
// ...
public function changerRefAffectationCalendrier(Request $request)
{
try {
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$request->request->replace(is_array($data) ? $data : []);
$params = $request->request->all();
$utilisateurInformation = $this->getUser();
$affectation = $utilisateurInformation->getIdAffectation();
$entityManager = $this->doctrine->getManager();
$aujourdhui = new \DateTime();
$refAffectationCalendrier = new RefAffectationCalendrier();
$refAffectationCalendrier->setIdAff($affectation->getIdAffectation());
$today = (new \DateTime());
$refAffectationCalendrierRepository = $entityManager->getRepository(RefAffectationCalendrier::class);
$currentYear = $today->format("Y");
$nextYear = $currentYear + 1;
$lastbascule = $refAffectationCalendrierRepository->findLastByRefAffectationId($affectation->getIdAffectation());
if (isset($lastbascule[0]) && !empty($lastbascule[0])) {
$lastbasculeCalendrier = isset($lastbascule[0]['calendrier_scolaire']) ? $lastbascule[0]['calendrier_scolaire'] : '';
} else {
$lastbasculeCalendrier = false;
}
if ($params["calendrier_scolaire"]) {
if (!$lastbasculeCalendrier) {
// Si nous sommes après le 1er septembre, fixer la date de bascule au 1er septembre de l'année prochaine
if ($aujourdhui >= new \DateTime('first day of September')) {
$dateBascule = new \DateTime('first day of September next year');
$refAffectationCalendrier->setCalendrierScolaire(true);
$refAffectationCalendrier->setDateBascule($dateBascule);
// Fixer la date de début au lendemain de la date de bascule
$refAffectationCalendrier->setDateDebut($dateBascule);
// Sauvegarder l'objet $RefAffectationCalendrier dans la base de données (EntityManager) pour suivre les changements de RefAffectationCalendrier.
$entityManager->persist($refAffectationCalendrier);
$entityManager->flush();
} else {
if (isset($lastbascule[0]) && !empty($lastbascule[0])) {
$datebasculeCalendrier = $lastbascule[0]['date_bascule'];
// $datebasculeCalendrier = $datebasculeCalendrier->format('Y-m-d');
} else {
$datebasculeCalendrier = false;
}
if ($datebasculeCalendrier < new \DateTime('first day of September')) {
// Vérifier si la dernière ligne correspond à un type d'affectation spécifique
$dateBascule = new \DateTime('first day of September');
$isLastLineForSpecificAffectation = $refAffectationCalendrierRepository->findLastByRefAffectationIdcivile($affectation->getIdAffectation(), $dateBascule);
if (!$isLastLineForSpecificAffectation) {
$dateBascule = new \DateTime('first day of September');
$refAffectationCalendrier->setCalendrierScolaire(true);
$refAffectationCalendrier->setDateBascule($dateBascule);
// Fixer la date de début au lendemain de la date de bascule
$refAffectationCalendrier->setDateDebut($dateBascule);
// Sauvegarder l'objet $RefAffectationCalendrier dans la base de données (EntityManager) pour suivre les changements de RefAffectationCalendrier.
$entityManager->persist($refAffectationCalendrier);
$entityManager->flush();
}
} else {
// SUPPRIMER LE CALENDRIER
if (isset($lastbascule[0]['id']) && !empty($lastbascule[0]['id'])) {
// var_dump($lastbascule[0]['id']);
$this->deleteByIdRefAffectation($lastbascule[0]['id']);
}
}
}
}
} else {
$dateBascule = new \DateTime('first day of January next year');
$isLastLineForSpecificAffectation = $refAffectationCalendrierRepository->findLastByRefAffectationIdcivile($affectation->getIdAffectation(), $dateBascule);
$isLineForSpecificAffectation = $refAffectationCalendrierRepository->findLastByRefAffectationId($affectation->getIdAffectation());
if (!$isLastLineForSpecificAffectation && $isLineForSpecificAffectation) {
// Si nous sommes après le 1er janvier, fixer la date de bascule au 1er janvier de l'année prochaine
if ($aujourdhui >= new \DateTime('first day of January')) {
$dateBascule = new \DateTime('first day of January next year');
$refAffectationCalendrier->setCalendrierScolaire(false);
$refAffectationCalendrier->setDateBascule($dateBascule);
$date_debut = $dateBascule;
$refAffectationCalendrier->setDateDebut($date_debut);
// Sauvegarder l'objet $RefAffectationCalendrier dans la base de données (EntityManager) pour suivre les changements de RefAffectationCalendrier.
$entityManager->persist($refAffectationCalendrier);
$entityManager->flush();
}
}
}
$data = ['success' => true, 'data' => 'Mise à jour effectuée avec succès'];
return new JsonResponse($data);
} catch (\Exception $e) {
echo $e->getMessage();
$data = [
'success' => false,
'data' => self::ERROR_OCCURED
];
}
return new JsonResponse($data, JsonResponse::HTTP_BAD_REQUEST);
}
public function deleteByIdRefAffectation($id)
{
$entityManager = $this->doctrine->getManager();
$entity = $entityManager->getRepository(RefAffectationCalendrier::class)->findOneBy(['id' => $id]);
if ($entity) {
$entityManager->remove($entity);
$entityManager->flush();
return true;
}
return false;
}
public function initSignatureConges($idconges)
{
try {
// $listeConges = explode(',', $request->request->get('listeConges'));
// $listeConges = json_decode($request->getContent(), true);
$em = $this->doctrine->getManager();
$congesRepo = $em->getRepository(Conge::class);
$workflow = $em->getRepository(Workflow::class)->find(Workflow::CO_SIGN);
$jourdhui = (new \DateTime())->format('Y-m-d');
$utilisateurRepository = $em->getRepository(Utilisateur::class);
$congObj = $congesRepo->find($idconges);
$idUtilisateur = $congObj->getUtilisateur()->getIdUtilisateur();
$idSignataire = $this->getUser()->getUtilisateur()->getIdUtilisateur();
$affectationSignataire = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idSignataire)->getIdAffectation()->getIdAffectation();
$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);
}*/
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_get_contents($path)) {
$pathvrai = $path;
} else {
$pathvrai = "";
}
$info_signature = array(
'nom' => $signataire->getNom(),
'prenom' => $signataire->getPrenom(),
'dateSignature' => date("d/m/Y"),
'sup' => true,
'fonction' => $signataire->getFonction(),
'path' => $pathvrai,
'civilite' => $signataire->getCivilite()
);
// foreach ($listeConges as $conge) {
$congObj = $congesRepo->find($idconges);
$congObj->setWorkflow($workflow);
$idUtilisateur = $congObj->getUtilisateur()->getIdUtilisateur();
// $email = $utilisateurRepository->findCourrielById($idUtilisateur)[0]['courriel'];
$emails = $utilisateurRepository->findCourrielById($idUtilisateur);
$email = isset($emails[0]['courriel']) ? $emails[0]['courriel'] : null;
// }
$beginDate = $congObj->getDateDebut();
$mail = $this->emailSHDecision->getMail(
EmailSHDecision::SIGNED,
EmailSHDecision::CONGE,
$email,
$beginDate
);
if ($mail) {
$this->mailer->send($mail);
}
// $info_signature['dateSignature']=$congObj->getDateDerniereModification();
// $em->setDateDeSignature($jourdhui);
// $em->setSignataire($signataire);
$em->persist($congObj);
$em->flush();
$this->generatePdf->generatePdf($congObj, false, $affectation, $info_signature);
$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
);
}
private function getChevalConge($conge, $Idaffectation)
{
$entityManager = $this->doctrine->getManager();
$today = (new \DateTime());
$year = $today->format("Y");
$getRefCalendrier = $entityManager
->getRepository(RefAffectationCalendrier::class)
->getRefCalendrier($Idaffectation);
$dateBasculeCongeSolaire = $getRefCalendrier['dateBascule'];
$congeScolaire = $getRefCalendrier['calendrierScolaire'];
$today = (new \DateTime());
$year = $today->format("Y");;
if (!$congeScolaire) {
if ($conge->getDateFin()->format('Y') != $conge->getDateDebut()->format('Y')) {
return false;
}
} else {
if ((true === $congeScolaire) && ($dateBasculeCongeSolaire < $today) && ($today < new \DateTime("$year-09-01"))) {
$annee = $year;
} else {
$annee = $year + 1;
}
if ((int)$conge->getDateFin()->format('m') >= 9 && (int)$conge->getDateDebut()->format('m') <= 8) {
return false;
}
}
return true;
}
private function getRequiredMotifOrPieceJointeForCexConge($conge)
{
$requiredFields = array();
if ($conge->getCongeType()->getCode() == CongeTypes::CEX) {
if ($conge->getMotifConge() == "") {
$requiredFields[] = "Le Motif de congé doit être renseigné";
}
if ($conge->getPieceMotif() == "") {
$requiredFields[] = "Vous devez joindre un justificatif ";
}
}
return implode(" et ", $requiredFields);
}
#[Route(path: '/api/report-conge', name: 'ctsweb_calendrier-report', methods: ['POST'])]
public function updateCalendrierReport(Request $request)
{
try {
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
$request->request->replace(is_array($data) ? $data : []);
$params = $request->request->all();
// Appeler la fonction pour mettre à jour les dates dans l'entité RefAffectation
$this->updateDatesInRefAffectation($params);
$data = ['success' => true, 'data' => 'Mise à jour effectuée avec succès'];
return new JsonResponse($data);
} catch (\Exception $e) {
$data = [
'success' => false,
'data' => $e->getMessage()
];
}
return new JsonResponse($data, JsonResponse::HTTP_BAD_REQUEST);
}
/**
* Met à jour les dates de l'entité RefAffectation avec les valeurs fournies.
*
* @param array $params Tableau contenant les dates à mettre à jour
*
* @throws \Exception Si une ou plusieurs des dates requises sont manquantes ou nulles
*/
public function updateDatesInRefAffectation(array $params): void
{
// Vérifier si toutes les dates requises sont présentes et non nulles
if (!$this->areDatesValid($params)) {
throw new \Exception('Une ou plusieurs des dates requises sont manquantes ou nulles.');
}
// Créer des objets DateTime à partir des chaînes de dates
$dateDebutCredit = new \DateTime($params['dateDebutCredit']);
$dateFinCredit = new \DateTime($params['dateFinCredit']);
$dateDebutDebit = new \DateTime($params['dateDebutDebit']);
$dateFinDebit = new \DateTime($params['dateFinDebit']);
$utilisateurInformation = $this->getUser();
$affectation = $utilisateurInformation->getIdAffectation();
$entityManager = $this->doctrine->getManager();
$affectionEntity = $entityManager
->getRepository(RefAffectation::class)
->findOneBy(["idAffectation" => $affectation]);
// Mettre à jour les propriétés de dates de l'entité
$affectionEntity->setDateDebutCredit($dateDebutCredit);
$affectionEntity->setDateFinCredit($dateFinCredit);
$affectionEntity->setDateDebutDebit($dateDebutDebit);
$affectionEntity->setDateFinDebit($dateFinDebit);
$entityManager->persist($affectionEntity);
$entityManager->flush();
}
/**
* Vérifie si toutes les dates requises sont présentes, non nulles et valides.
*
* @param array $params Tableau contenant les dates à vérifier
*
* @return bool true si toutes les dates sont valides, false sinon
* @throws \Exception Si une date est manquante, nulle, invalide ou si la date de début est supérieure ou égale à la date de fin
*/
private function areDatesValid(array $params): bool
{
// Liste des dates requises
$requiredDates = [
'dateDebutCredit',
'dateFinCredit',
'dateDebutDebit',
'dateFinDebit'
];
// Vérifier si toutes les dates requises sont présentes, non nulles et valides
foreach ($requiredDates as $dateKey) {
if (!isset($params[$dateKey]) || empty($params[$dateKey])) {
throw new \Exception("La date '$dateKey' est manquante ou nulle.");
}
// Exclure la date '1970-01-01'
if ($params[$dateKey] === '1970-01-01') {
throw new \Exception("La date '$dateKey' est invalide.");
}
// Vérifier le format de la date
if (!strtotime($params[$dateKey])) {
throw new \Exception("La date '$dateKey' est invalide.");
}
// Créer l'objet DateTime
$date = new \DateTime($params[$dateKey]);
// Vérifier si l'objet DateTime a été créé avec succès
if (!$date) {
throw new \Exception("La date '$dateKey' est invalide.");
}
}
// Vérifier la relation entre les dates de début et de fin pour les crédits
$dateDebutCredit = \DateTime::createFromFormat('Y-m-d', $params['dateDebutCredit']);
$dateFinCredit = \DateTime::createFromFormat('Y-m-d', $params['dateFinCredit']);
if ($dateDebutCredit > $dateFinCredit) {
throw new \Exception("La date de début 'dateDebutCredit' doit être inférieure à la date de fin 'dateFinCredit'.");
}
// Vérifier la relation entre les dates de début et de fin pour les débits
$dateDebutDebit = \DateTime::createFromFormat('Y-m-d', $params['dateDebutDebit']);
$dateFinDebit = \DateTime::createFromFormat('Y-m-d', $params['dateFinDebit']);
if ($dateDebutDebit > $dateFinDebit) {
throw new \Exception("La date de début 'dateDebutDebit' doit être inférieure à la date de fin 'dateFinDebit'.");
}
// Débit report année antérieure >= Crédit report année antérieure
if ($dateDebutDebit < $dateDebutCredit) {
throw new \Exception("La date de début 'Date débit report année antérieure' doit être superieure ou égale à la date de fin 'Date crédit report année antérieure'.");
}
return true;
}
/**
* @return JsonResponse
*/
#[Route(path: '/api/calendrier-report-info', name: 'ctsweb_calendrier-report-info', methods: ['GET'])]
public function getCalendrierReport()
{
$jsonv = [];
try {
$utilisateurInformation = $this->getUser();
$affectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
$entityManager = $this->doctrine->getManager();
$affectionEntity = $entityManager
->getRepository(RefAffectation::class)
->findOneBy(["idAffectation" => $affectation]);
$getRefCalendrier = $entityManager
->getRepository(RefAffectationCalendrier::class)
->getRefCalendrier($affectation);
$calendrier = $getRefCalendrier['calendrierAffectation'];
$anneeEnCours = date('Y'); // Récupère l'année en cours
// Si $calendrier est faux, retourne l'année en cours
// Sinon, retourne l'année précédente divisée par l'année en cours
$annee = $calendrier ? ($anneeEnCours - 1) . '/' . $anneeEnCours : $anneeEnCours;
// Récupère les dates 'dateDebutCredit', 'dateFinCredit', 'dateDebutDebit' et 'dateFinDebit' de $affectionEntity si elles existent
$dateDebutCredit = isset($affectionEntity) ? $affectionEntity->getDateDebutCredit() : null;
$dateFinCredit = isset($affectionEntity) ? $affectionEntity->getDateFinCredit() : null;
$dateDebutDebit = isset($affectionEntity) ? $affectionEntity->getDateDebutDebit() : null;
$dateFinDebit = isset($affectionEntity) ? $affectionEntity->getDateFinDebit() : null;
// Crée le tableau items avec les valeurs récupérées
$items = [
'annee' => $annee,
'dateDebutCredit' => isset($dateDebutCredit) ? $dateDebutCredit->format('Y-m-d H:i:s') : null,
'dateFinCredit' => isset($dateFinCredit) ? $dateFinCredit->format('Y-m-d H:i:s') : null,
'dateDebutDebit' => isset($dateDebutDebit) ? $dateDebutDebit->format('Y-m-d H:i:s') : null,
'dateFinDebit' => isset($dateFinDebit) ? $dateFinDebit->format('Y-m-d H:i:s') : null,
];
$jsonv['items'] = $items;
$json_merge = json_encode($jsonv);
return new JsonResponse($json_merge, JsonResponse::HTTP_OK, [], true);
} catch (\Exception $e) {
// Gérer les exceptions
return new JsonResponse(['error' => "Une erreur s'est produite."], JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
}
}
function createNewReport(): array
{
return [
'dateDebut' => "-",
'dateFin' => "-",
'avisDtn' => "-",
"congeType" => [
"id" => 6,
"libelle" => Workflow::STATETYPE[DemandeReport::TYPE_ONE],
"description" => null,
"code" => "DDR",
"nbJourTotal" => null,
"nouveauSolde" => null,
"solde" => null,
],
'dateDebutType' => [
"libelle" => null,
"code" => null
],
'dateFinType' => [
"libelle" => null,
"code" => null
],
'isTooLate' => null,
'motifConge' => null,
'pieceMotif' => null,
'commentaireSh' => null,
'commentaireDtn' => null,
'choixConge' => '2'
];
}
function createNewReportDtnSH(): array
{
return [
'dateDebut' => "-",
'dateFin' => "-",
'avisDtn' => "-",
"libelle" => Workflow::STATETYPE[DemandeReport::TYPE_ONE],
"code" => "DDR",
'dateDebutType' => null,
'dateFinType' => null,
'isTooLate' => null,
'motifConge' => null,
'pieceMotif' => null,
'commentaireSh' => null,
'commentaireDtn' => null,
'choixConge' => '2'
];
}
function verifier_solde_comptes(Conge $conge)
{
$entityManager = $this->doctrine->getManager();
$year = $this->getYear($conge);
$utilisateurInformation = $this->getUser();
$utilisateur = $utilisateurInformation->getUtilisateur();
$recapitulatif = $entityManager
->getRepository(UtilisateurInformation::class)
->getInfos($utilisateur, $year);
if ($conge->getCongeType()->getCode() == CongeTypes::CET) {
$soldecompte = $recapitulatif['totalCet'] - $recapitulatif['givenCet'];
} else {
$soldecompte = $recapitulatif['totalReport'] - $recapitulatif['givenRaa'];
}
if ($soldecompte < $conge->getNbJour()) {
return false;
}
return true;
}
public function getYear($conge)
{
$today = new \DateTime();
$year = $today->format("Y");
$utilisateur = $this->getUser()->getIdUtilisateur();
$entityManager = $this->doctrine->getManager();
$utilisateurInformation = $entityManager
->getRepository(UtilisateurInformation::class)
->findOneBy(["idUtilisateur" => $utilisateur]);
if ($utilisateurInformation) {
$idaffectation = $utilisateurInformation->getIdAffectation()->getIdAffectation();
$affectation = $entityManager
->getRepository(RefAffectation::class)
->findOneBy(["idAffectation" => $idaffectation]);
$getRefCalendrier = $entityManager
->getRepository(RefAffectationCalendrier::class)
->getRefCalendrier($idaffectation);
$calendrierScolaire = $getRefCalendrier['calendrierScolaire'];
$dateBasculeCongeSolaire = $getRefCalendrier['dateBascule'];
if ($affectation) {
// $calendrierScolaire = $affectation->getCalendrierScolaire();
// $dateBasculeCong$dateBasculeCongeSolaire eSolaire = $affectation->getDateBascule();
if ((true === $calendrierScolaire) && ($dateBasculeCongeSolaire < $today) && ($today < new \DateTime("$year-09-01"))) {
return $year - 1;
} else {
return $year;
}
}
}
// Si l'année n'a pas pu être obtenue à partir de l'objet Utilisateur, on retourne l'année en cours
return $year;
}
#[Route(path: '/api/send', name: 'ctsweb_sendEmail', methods: ['GET'])]
public function sendTestEmail(MailerInterface $mailer)
{
chmod($this->getParameter('dir_file_rapport') . "RAA_2023_abboub_ali_vba.pdf", 0644);
$attachmentPath = $this->getParameter('dir_file_rapport') . "RAA_2023_abboub_ali_vba.pdf";
$email = (new Email())
->from('cts-web.assistance@sports.gouv.fr')
->to('dame.sall@soprasteria.com')
->subject('Test Email')
->text('This is a test email sent from Symfony 5.4.')
// ->attachFromPath( $this->getParameter('dir_file_rapport')."RAA_2023_abboub_ali_vba.pdf");
->attach(fopen($attachmentPath, 'r'));
// ->attachFromPath($attachmentPath);
$mailer->send($email);
return new Response('Test email sent.');
}
}