<?php
namespace App\Controller;
use App\Entity\AttributeCharge;
use App\Entity\Charge;
use App\Entity\DetailFichier;
use App\Entity\DetailMission;
use App\Entity\DifficulteTechnique;
use App\Entity\InfosModelFichier;
use App\Entity\PointageUser;
use App\Repository\PointageUserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\ValidateService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use App\Entity\Utilisateur;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use App\Repository\UtilisateurRepository;
use App\Repository\MissionRepository;
use App\Repository\StockMissionRepository;
use App\Entity\Mission;
use App\Entity\InfosDetailFichier;
use App\Entity\Images;
use App\Entity\Notifications;
use App\Entity\SousTache;
use App\Entity\StockDetailFichier;
use App\Entity\StockMission;
use App\Entity\Tache;
use Symfony\Component\HttpFoundation\File\File;
use App\Repository\TacheRepository;
use Symfony\Component\Notifier\Notification\Notification;
use App\Entity\Marche;
use App\Entity\MouvementStock;
use App\Entity\Piece;
use App\Entity\StockReception;
use App\Entity\TachePj;
use App\Entity\TacheUtilisateur;
use App\Service\BaseService;
use Doctrine\DBAL\Connection;
class WebServiceController extends AbstractController
{
public $baseService;
public $pointageRepo;
public function __construct(BaseService $baseService , PointageUserRepository $pointageRepo, Connection $conn
)
{
$this->baseService = $baseService;
$this->pointageRepo = $pointageRepo;
$this->conn = $conn;
}
#[Route('/webService/login', name: 'webServiceLogin')]
public function webServiceLogin(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,UtilisateurRepository $UtilisateurRepository): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$email=$request->get('email');
$password=$request->get('password');
$token=$request->get('token');
if(trim($email) == "" || trim($password) == "" )
{
$codeStatut = "ERROR-EMPTY-PARAMS";
$response = "L'email ou le mot de passe est vide";
}
else
{
$utilisateur = $entityManager->getRepository(Utilisateur::class)->findOneBy(array("emaiUtil" => $email,"passUtil" => sha1($password)));
if($utilisateur)
{
$data = [
'userId' => $utilisateur->getId(),
];
$bureaux = $UtilisateurRepository->getUserBureaux($utilisateur->getId());
if($token != "" and $token != null)
{
$utilisateur->setTokenDevice($token);
$entityManager->flush();
}
$tokenJWT = $jwtManager->encode($data);
$responseObjects['user'] = $utilisateur;
$responseObjects['bureaux'] = $bureaux;
$response = "ok";
$codeStatut = "OK";
}
else
{
$response = "L'email ou le mot de passe est incorrect";
$codeStatut = "ERROR-PARAMS";
}
}
}
catch(\Exception $e)
{
$codeStatut = $e->getMessage() ;
$response = "une erreur s'est produite!";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getData', name: 'webServicGetData')]
public function webServicGetData(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,MissionRepository $missionRepository,StockMissionRepository $stockMissionRepository): JsonResponse
{
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$decoded = "";
$allMissions = [];
$userImage= null;
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
//$data = $missionRepository->getData($id);
$allMissions = $entityManager->getRepository(Mission::class)->findBy(array("etatMiss" => [1,2] ,"idAgent" => $id ));
$utilisateur = $entityManager->getRepository(Utilisateur::class)->find($id);
if($utilisateur)
{
$userPATH = $this->getParameter('kernel.project_dir') . '/public/assets/images/Users/' . $utilisateur->getLogoUtil();
$userImage = new File($userPATH);
}
foreach ($allMissions as $mission) {
$marche = $entityManager->getRepository(Marche::class)->find($mission->getIdMarche());
if(!empty($mission->getImagArti()))
{
$filePath = $this->getParameter('kernel.project_dir') . '/public/assets/images/IconsMarche/' . $mission->getImagArti();
}
else
{
$filePath = $this->getParameter('kernel.project_dir') . '/public/assets/images/IconsMarche/main.jpg';
}
$file = new File($filePath);
if ($marche) {
$missionData = [
'marchename' => $marche->getNumeMarc(),
'id' => $mission->getId(),
'etatMiss' => $mission->getEtatMiss(),
'NumeMiss' => $mission->getNumeMiss(),
'dateCreation' => $mission->getDateCreation(),
'dateFin' => $mission->getDateFin(),
'code' => $mission->getCodeArti(),
'image' => $file,
'idMarche' => $marche->getId(),
];
// Add the mission data to the $missions array
$missions[] = $missionData;
}
}
$files = [];
$stockUtilise = [];
$stock = [];
$diffs = [];
foreach($missions as $mission)
{
$detailMission = $entityManager->getRepository(DetailMission::class)->findBy(array("idMission" => $mission["id"]));
foreach($detailMission as $dt)
{
$details[] = $dt;
$data[] = $missionRepository->getForm($dt->getIdDetail());
$images = $entityManager->getRepository(Images::class)->findBy(array("idDetailFichier" => $dt->getIdDetail()));
foreach ($images as $image) {
$filePath = $this->getParameter('kernel.project_dir') . '/public' . $image->getUrlImage();
$file = new File($filePath);
// Construct the response array
$toSend['id'] = $image->getId();
$toSend['idDetailFichier'] = $image->getIdDetailFichier();
$toSend['imageData'] = $file;
$files[] = $toSend;
}
$sU = $entityManager->getRepository(StockDetailFichier::class)->findBy(array("idDetail" => $dt->getIdDetail()));
if($sU)
{
$stockUtilise[] = $sU;
}
}
$stc = $stockMissionRepository->getStock($mission["id"]);
if($stc)
{
$stock[] =$stc;
}
$diffs[] = $entityManager->getRepository(DifficulteTechnique::class)->findBy(['idMarche' => [$mission["idMarche"], 0]]);
}
$depenses = [];
$allDepenses = $entityManager->getRepository(Charge::class)->findBy(['idAgent' => $id]);
$categories = $entityManager->getRepository(AttributeCharge::class)->findAll();
foreach ($allDepenses as $depense) {
$filePath = $this->getParameter('kernel.project_dir') . '/public' . $depense->getImg();
$file = new File($filePath);
$depenseData = [
'id' => $depense->getId(),
'idAttCha' => $depense->getIdAttCha(),
'modePaie' => $depense->getModePaie(),
'dateCreation' => $depense->getDateCreation(),
'observation' => $depense->getObservation(),
'titrChar' => $depense->getTitrChar(),
'img' => $file,
'totalHt' => $depense->getTotalHt(),
'totalTtc' => $depense->getTotalTtc()
];
$depenses[] = $depenseData;
}
$responseObjects['missions'] = $missions;
$responseObjects['details'] = $details;
$responseObjects['data'] = $data;
$responseObjects['images'] = $files;
$responseObjects['stock'] = $stock;
$responseObjects['stockUtilise'] = $stockUtilise;
$responseObjects['difficultes'] = $diffs;
$responseObjects['utilisateur'] = $utilisateur;
$responseObjects['logo'] = $userImage;
$responseObjects['categories'] = $categories;
$responseObjects['depenses'] = $depenses;
$codeStatut = 'OK';
$response = "ok";
}
catch(\Exception $e)
{
$codeStatut = $e->getMessage() ;
$response = "une erreur s'est produite!";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $decoded;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$response = new JsonResponse($json, 200, [], true);
return $response;
}
#[Route('/webService/getMissions', name: 'getMissions')]
public function getMissions(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$chckAccess = $baseService->RoleMobile(82,$id);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
if($response == '')
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$missions = [];
$Allmissions = $entityManager->getRepository(Mission::class)->findBy(['idAgent' => $id, "etatMiss" => [1,2]]);
foreach ($Allmissions as $mission) {
$marche = $entityManager->getRepository(Marche::class)->find($mission->getIdMarche());
if(!empty($mission->getImagArti()))
{
$filePath = $this->getParameter('kernel.project_dir') . '/public/assets/images/IconsMarche/' . $mission->getImagArti();
}
else
{
$filePath = $this->getParameter('kernel.project_dir') . '/public/assets/images/IconsMarche/main.jpg';
}
$file = new File($filePath);
if ($marche) {
$missionData = [
'marchename' => $marche->getNumeMarc(),
'id' => $mission->getId(),
'etatMiss' => $mission->getEtatMiss(),
'NumeMiss' => $mission->getNumeMiss(),
'dateCreation' => $mission->getDateCreation(),
'dateFin' => $mission->getDateFin(),
'code' => $mission->getCodeArti(),
'image' => $file,
];
// Add the mission data to the $missions array
$missions[] = $missionData;
}
}
$responseObjects = $missions;
$codeStatut = "OK";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getDetailsMissions', name: 'getDetailsMissions')]
public function getDetailsMissions(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$idMission =$request->get('id');
$details = $entityManager->getRepository(DetailMission::class)->findBy(array('idMission' => $idMission));
$responseObjects = $details;
$codeStatut = "OK";
$codeStatut = "OK";
}
catch(\Exception $e)
{
$response = "une erreur s'est produite!";
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getFormDetail', name: 'getFormDetail')]
public function getFormDetail(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,MissionRepository $missionRepository,StockMissionRepository $stockMissionRepository): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$idDetail =$request->get('id');
$detail = $entityManager->getRepository(DetailMission::class)->find($idDetail);
if($detail)
{
$stockUtilise = $entityManager->getRepository(StockDetailFichier::class)->findBy(array("idDetail" => $detail->getIdDetail()));
$mission = $entityManager->getRepository(Mission::class)->find($detail->getIdMission());
$stock = $stockMissionRepository->getStock($detail->getIdMission());
$data = $missionRepository->getForm($detail->getIdDetail());
$files = [];
$images = $entityManager->getRepository(Images::class)->findBy(array("idDetailFichier" => $detail->getIdDetail()));
foreach($images as $image)
{
$filePath = $this->getParameter('kernel.project_dir') . '/public' . $image->getUrlImage();
$file = new File($filePath);
$toSend['id'] = $image->getId();
$toSend['file'] = $file;
$files[] = $toSend;
}
$diffs = $entityManager->getRepository(DifficulteTechnique::class)->findBy(['idMarche' => [$mission->getIdMarche(), 0]]);
$responseObjects["detail"] = $detail;
$responseObjects["form"] = $data;
$responseObjects["images"] = $files;
$responseObjects["stock"] = $stock;
$responseObjects["stockUtilise"] = $stockUtilise;
$responseObjects["difficultes"] = $diffs;
$response = "OK";
$codeStatut = "OK";
}
else
{
$codeStatut = "ERROR-DET";
$response = "Desolé, ce detail est introuvable !!";
}
}
catch(\Exception $e)
{
$codeStatut = "ERROR-EXE";
$response = $e->getMessage();
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/sendFormData', name: 'sendFormData')]
public function sendFormData(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$date = new \DateTime();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$id = $request->get('id');
$formJson = $request->get('form');
$form = json_decode($formJson, true);
$stockJson = $request->get('stockUtilise');
$stock = json_decode($stockJson, true);
$longitude = $request->get('longitude');
$latitude = $request->get('latitude');
$detailMission = $entityManager->getRepository(DetailMission::class)->find($id);
if($detailMission)
{
if($longitude == "" || $latitude == "")
{
$codeStatut = "ERROR-GPS";
$response = "Veuillez activer le GPS pour obtenir les points de localisation";
}
else
{
foreach ($form as $formItem) {
$id = $formItem['id'];
$valueInfo = $formItem['value_info'];
// Retrieve InfosDetailFicher entity by id
$infosDetailFicher = $entityManager->getRepository(InfosDetailFichier::class)->find($id);
if ($infosDetailFicher) {
// Update the valueInfo property
$infosDetailFicher->setValueInfo($valueInfo);
// Persist the changes to the database
$entityManager->persist($infosDetailFicher);
}
}
$detailFichier = $entityManager->getRepository(DetailFichier::class)->find($infosDetailFicher->getIdDetail());
$images = $entityManager->getRepository(Images::class)->findBy(array("idDetailFichier" => $detailMission->getIdDetail()));
foreach($images as $image)
{
$entityManager->remove($image);
}
$imageFolder = $this->getParameter('kernel.project_dir') . '/public/assets/imagesMissions/';
for ($i = 0; $request->files->has("capturedPhoto$i"); $i++) {
$file = $request->files->get("capturedPhoto$i");
// Generate a unique filename
$filename = md5(uniqid()) . '.' . $file->getClientOriginalExtension();
// Move the file to the target directory
$file->move($imageFolder, $filename);
// Create a new Image object
$image = new Images();
$image->setUrlImage('/assets/imagesMissions/' . $filename); // Assuming the path is relative to the public directory
$image->setIdDetailFichier($detailMission->getIdDetail());
$image->setIdFichier($infosDetailFicher->getIdFichier());
// Persist the Image object to the database
$entityManager->persist($image);
}
foreach ($stock as $article) {
$stockMission = $entityManager->getRepository(StockMission::class)->findOneBy(array("idMission" => $detailMission->getIdMission(),"idPiece" => $article['idPiec']));
if($stockMission)
{
$qte = $stockMission->getQte();
$stockDetail = $entityManager->getRepository(StockDetailFichier::class)->findOneBy(array("idDetail" => $detailMission->getIdDetail(),"idPiece" => $article['idPiec']));
if($stockDetail)
{
$qte = $qte+$stockDetail->getQte();
$entityManager->remove($stockDetail);
}
if( $article['qte'] > 0)
{
$newQte = $qte - $article['qte'];
if($newQte>= 0)
{
$stockMission->setQte($newQte);
$detailStock = new StockDetailFichier();
$detailStock->setIdDetail($detailMission->getIdDetail());
$detailStock->setIdMission($detailMission->getIdMission());
$detailStock->setIdPiece($article['idPiec']);
$detailStock->setQte($article['qte']);
$detailStock->setDateCreation(new \DateTime());
$entityManager->persist($detailStock);
$entityManager->flush();
}
}
}
}
$detailFichier->setEtatDeta(2);
$detailMission->setDateFin($date);
$detailFichier->setLongitude($longitude);
$detailFichier->setLatitude($latitude);
$detailMission->setLongitude($longitude);
$detailMission->setLatitude($latitude);
$detailMission->setEtatDeta(1);
$date = new \DateTime();
$formattedDate = $date->format('Y-m-d H:i:s');
$sql='UPDATE `infos_detail_fichier` d SET d.`value_info`=:value where d.id_detail = :idDetail and d.id_info in (select i.id from infos_model_fichier i where i.type_info = :idInfo) ';
$stmt = $this->conn->prepare($sql);
$stmt->bindValue(":idDetail",$detailMission->getIdDetail());
$stmt->bindValue(":value",$formattedDate);
$stmt->bindValue(":idInfo",7);
$stmt = $stmt->executeQuery();
$detailsMissionNoCompelt = $entityManager->getRepository(DetailMission::class)->findBy(array("idMission" => $detailMission->getIdMission(),"etatDeta" => 0) );
if(count($detailsMissionNoCompelt) <= 1)
{
$mission = $entityManager->getRepository(Mission::class)->find($detailMission->getIdMission());
$mission->setEtatMiss(2);
$stockMission = $entityManager->getRepository(StockMission::class)->findBy(array("idMission" => $mission->getId()));
foreach($stockMission as $stock)
{
if($stock->getQte() > 0)
{
$mouvement = new MouvementStock();
$mouvement->setIdPiec($stock->getIdPiece());
$mouvement->setDateMouv(new \DateTime());
$mouvement->setToStock($stock->getFromStock());
$mouvement->setQte($stock->getQte());
$mouvement->setFromStock(-1);
$mouvement->setMotifMouv('Retroure de stock mission');
$mouvement->setEtatMouv(0);
$entityManager->persist($mouvement);
$entityManager->flush();
if($stock->getFromStock() == 0)
{
$article = $entityManager->getRepository(Piece::class)->find($stock->getIdPiece());
$inStokc = $article->getInStock();
$qteArticle = $inStokc + $stock->getQte();
$article->setInStock($qteArticle);
}
else
{
$stockR = new StockReception();
$stockR->setIdBure($stock->getFromStock());
$stockR->setIdPiec($stock->getIdPiece());
$stockR->setQte($stock->getQte());
$stockR->setIdMouv($mouvement->getId());
$entityManager->persist($stockR);
}
}
}
}
$entityManager->flush();
$response = "OK";
$codeStatut = "OK";
}
}
else
{
$codeStatut = "ERROR-DET";
$response = "Desolé, ce detail de mission est introuvable !!";
}
}
catch(\Exception $e)
{
$codeStatut = "ERROR-EXE";
$response = $e->getMessage();
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/sendFormDataDeff', name: 'sendFormDataDeff')]
public function sendFormDataDeff(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$id = $request->get('id');
$defTech = $request->get('defTech');
$observation = $request->get('observation');
$longitude = $request->get('longitude');
$latitude = $request->get('latitude');
$detailMission = $entityManager->getRepository(DetailMission::class)->find($id);
if($detailMission)
{
if($longitude == "" || $latitude == "")
{
$codeStatut = "ERROR-GPS";
$response = "Veuillez activer le GPS pour obtenir les points de localisation";
}
else
{
$detailFichier = $entityManager->getRepository(DetailFichier::class)->find($detailMission->getIdDetail());
$detailMission->setDeffTech($defTech);
$detailMission->setObseDeff($observation);
$images = $entityManager->getRepository(Images::class)->findBy(array("idDetailFichier" => $detailMission->getIdDetail()));
foreach($images as $image)
{
$entityManager->remove($image);
}
$imageFolder = $this->getParameter('kernel.project_dir') . '/public/assets/imagesMissions/';
for ($i = 0; $request->files->has("capturedPhoto$i"); $i++){
$file = $request->files->get("capturedPhoto$i");
// Generate a unique filename
$filename = md5(uniqid()) . '.' . $file->getClientOriginalExtension();
// Move the file to the target directory
$file->move($imageFolder, $filename);
// Create a new Image object
$image = new Images();
$image->setUrlImage('/assets/imagesMissions/' . $filename); // Assuming the path is relative to the public directory
$image->setIdDetailFichier($detailFichier->getId());
$image->setIdFichier($detailFichier->getIdFichier());
// Persist the Image object to the database
$entityManager->persist($image);
}
$detailFichier->setEtatDeta(2);
$detailMission->setDateFin(new \DateTime());
$detailFichier->setLongitude($longitude);
$detailFichier->setLatitude($latitude);
$detailMission->setLongitude($longitude);
$detailMission->setLatitude($latitude);
$detailMission->setEtatDeta(1);
$date = new \DateTime();
$formattedDate = $date->format('Y-m-d H:i:s');
$sql='UPDATE `infos_detail_fichier` d SET d.`value_info`=:value where d.id_detail = :idDetail and d.id_info in (select i.id from infos_model_fichier i where i.type_info = :idInfo) ';
$stmt = $this->conn->prepare($sql);
$stmt->bindValue(":idDetail",$detailMission->getIdDetail());
$stmt->bindValue(":value",$formattedDate);
$stmt->bindValue(":idInfo",7);
$stmt = $stmt->executeQuery();
$detailsMissionNoCompelt = $entityManager->getRepository(DetailMission::class)->findBy(array("idMission" => $detailMission->getIdMission(),"etatDeta" => 0) );
if(count($detailsMissionNoCompelt) <= 1)
{
$mission = $entityManager->getRepository(Mission::class)->find($detailMission->getIdMission());
$mission->setEtatMiss(2);
$stockMission = $entityManager->getRepository(StockMission::class)->findBy(array("idMission" => $mission->getId()));
foreach($stockMission as $stock)
{
if($stock->getQte() > 0)
{
$mouvement = new MouvementStock();
$mouvement->setIdPiec($stock->getIdPiece());
$mouvement->setDateMouv(new \DateTime());
$mouvement->setToStock($stock->getFromStock());
$mouvement->setQte($stock->getQte());
$mouvement->setFromStock(-1);
$mouvement->setMotifMouv('Retroure de stock mission');
$mouvement->setEtatMouv(0);
$entityManager->persist($mouvement);
$entityManager->flush();
if($stock->getFromStock() == 0)
{
$article = $entityManager->getRepository(Piece::class)->find($stock->getIdPiece());
$inStokc = $article->getInStock();
$qteArticle = $inStokc + $stock->getQte();
$article->setInStock($qteArticle);
}
else
{
$stockR = new StockReception();
$stockR->setIdBure($stock->getFromStock());
$stockR->setIdPiec($stock->getIdPiece());
$stockR->setQte($stock->getQte());
$stockR->setIdMouv($mouvement->getId());
$entityManager->persist($stockR);
}
}
}
}
$entityManager->flush();
$response = "OK";
$codeStatut = "OK";
}
}
else
{
$codeStatut = "ERROR-DET";
$response = "Desolé, ce detail de mission est introuvable !!";
}
}
catch(\Exception $e)
{
$codeStatut = "ERROR-EXE";
$response = "une erreur s'est produite!";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getTaches', name: 'getTachesWs')]
public function getTaches(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
UtilisateurRepository $repoUser,TacheRepository $tacheRepository,JWTEncoderInterface $jwtManager , BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$tachesWithSousTaches = [];
$affectationUser = false;
$affectationAjoutUser = false;
$dataUsers = [];
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$user = $entityManager->getRepository(Utilisateur::class)->find($id);
$chckAccess = $baseService->RoleMobile(90,$id);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
$dataUsers = $repoUser->getUsersBureau2($user->getId());
if($response == '')
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$taches = $tacheRepository->getTacheUser($id,null);
foreach ($taches as $t) {
// Use findBy to get all SousTaches for each Tache
$sousTaches = $entityManager->getRepository(SousTache::class)->findBy(['idTache' => $t->getId()]);
// Merge Tache with associated SousTaches
$tachesWithSousTaches[] = [
'tache' => $t,
'sousTaches' => $sousTaches,
];
}
$dataUsers = $repoUser->getUsersBureau2($user->getId());
$responseObjects = $tachesWithSousTaches;
$codeStatut = "OK";
}
$affectationUser = true;
if($user->getTypeUtil() != 0){
$chckAccess = $baseService->RoleMobile(126,$id);
if($chckAccess == 1 ){
$codeStatut = "OK";
$dataUsers = $repoUser->getUsersBureau2($user->getId());
}else{
$affectationUser = false;
}
}
$affectationAjoutUser = true;
if($user->getTypeUtil() != 0){
$chckAccess = $baseService->RoleMobile(91,$id);
if($chckAccess != 1){
$affectationAjoutUser = false;
}else{
$codeStatut = "OK";
}
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $baseService->RoleMobile(126,$id);;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$resp["data"] = $dataUsers;
$resp["affectationUser"] = $affectationUser;
$resp["affectationAjoutUser"] = $affectationAjoutUser;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getTache/{id}', name: 'getOneTache')]
public function getTache(Request $request, EntityManagerInterface $entityManager, JWTEncoderInterface $jwtManager ,BaseService $baseService , SerializerInterface $serializer, $id): Response
{
$response = "";
$codeStatut = "";
$data = [];
try {
// Get Tache entity
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$chckAccess = $baseService->RoleMobile(90,$idUser);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}{
$tache = $entityManager->getRepository(Tache::class)->find($id);
if (!$tache) {
return new JsonResponse(['error' => 'Tache not found.'], 404);
}
// Get related SousTache entities
$sousTaches = $entityManager->getRepository(SousTache::class)->findByIdTache($id);
$tacheUsers = $entityManager->getRepository(TacheUtilisateur::class)->findByIdTach($id);
$tache_pj = $entityManager->getRepository(TachePj::class)->findBy(["id_tache"=>$id]);
// Create an array with information about both entities
$data = [
'tache' => $tache,
'sousTaches' => $sousTaches,
'users' => $tacheUsers,
'taches_pj'=>$tache_pj
];
$codeStatut = "OK";
// Serialize the array to JSON
$jsonData = $serializer->serialize($data, 'json');
// Return the JSON response
}
} catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["object"] = $data;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/setEtatTache', name: 'setEtatTache')]
public function setEtatTache(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$idTache = $request->get('id');
$etat = (int)$request->get('etat');
$tache = $entityManager->getRepository(tache::class)->find($idTache);
if($tache)
{
$tache->setEtatTach($etat);
$entityManager->flush();
$codeStatut = "OK";
$response = "ok";
}
else
{
$codeStatut = "ERROR-TAC";
$response = "Desolé, cette tache est introuvable !!";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/sendDepense', name: 'sendDepense')]
public function sendDepense(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$chckAccess = $baseService->RoleMobile(35,$id);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
if($response == '')
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$dataJson = $request->get('data');
$data = json_decode($dataJson, true);
$file = $request->files->get("capturedPhoto");
$totalHt = str_replace(',', '.', $data['totalHt']);
$totalTtc = str_replace(',', '.', $data['totalTtc']);
$charge = new Charge();
$charge->setTitrChar($data['objet']);
$charge->setDateCreation(new \DateTime($data['dateCreation']));
$charge->setIdAttCha($data['categorie']);
$charge->setTotalHt( $totalHt);
$charge->setTotalTtc($totalTtc);
$charge->setObservation($data['observation']);
$charge->setIdFour(0);
$charge->setIdBure(0);
$charge->setModePaie($data['modePaiement']);
$charge->setIdAgent($id);
$charge->setIdUtil($idUser);
$imageFolder = $this->getParameter('kernel.project_dir') . '/public/assets/images/Charges/';
// Generate a unique filename
$filename = md5(uniqid()) . '.' . $file->getClientOriginalExtension();
// Move the file to the target directory
$file->move($imageFolder, $filename);
$charge->setImg('/assets/images/Charges/' . $filename);
// Persist the Charge entity and flush it to the database
$entityManager->persist($charge);
$entityManager->flush();
$response = "OK";
$codeStatut = "OK";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getDepenses', name: 'getDepenses')]
public function getDepenses(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$chckAccess = $baseService->RoleMobile(34,$id);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
if($response == '')
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$depenses = $entityManager->getRepository(Charge::class)->findBy(['idAgent' => $id]);
$categories = $entityManager->getRepository(AttributeCharge::class)->findAll();
$responseObjects['depenses'] = $depenses;
$responseObjects['categories'] = $categories;
$codeStatut = "OK";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getNotifications', name: 'getNotifications')]
public function getNotifications(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$notifications = $entityManager->getRepository(Notifications::class)->findBy(array('idUser' => $id,'etat' => 1));
$responseObjects = $notifications;
$response = 'ok';
$codeStatut = "OK";
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/setNotifLu', name: 'setNotifLu')]
public function setNotifLu(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$from = $request->get("all");
if($from == '0')
{
$notifications = $entityManager->getRepository(Notifications::class)->findBy(array('idUser' => $id,'etat' => 1));
foreach($notifications as $notif)
{
$notif->setEtat(0);
}
$entityManager->flush();
}
else
{
$notification = $entityManager->getRepository(Notifications::class)->find($from);
$notification->setEtat(0);
$entityManager->flush();
}
$response = 'ok';
$codeStatut = "OK";
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/removeDepense', name: 'removeDepense')]
public function removeDepense(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
try
{
$chckAccess = $baseService->RoleMobile(101,$id);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
if($response == '')
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $request->get("id");
$charge = $entityManager->getRepository(Charge::class)->find($id);
if($charge)
{
$entityManager->remove($charge);
$entityManager->flush();
$response = 'ok';
$codeStatut = "OK";
}
else
{
$codeStatut = "ERROR-CHA";
$response = "Desolé, cette depense est introuvable !!";
}
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/addPieceTache', name: 'addPieceTache')]
public function addPieceTache(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
/*$chckAccess = $baseService->RoleMobile(101,2);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}*/
if($response == '')
{
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
// $id = $decoded['userId'];
$id = $request->get("id");
$tache = $entityManager->getRepository(Tache::class)->find($id);
if (!$tache) {
$codeStatut = "ERROR-TAC";
$response = "Désolé, cette tâche est introuvable !!";
} else {
// Handle file uploads
$files = $request->files->get('files');
$imageFolder = $this->getParameter('kernel.project_dir') . '/public/assets/tache_pj/';
if ($files) {
foreach ($files as $file) {
// Generate a unique filename
$filename = md5(uniqid()) . '.' . $file->getClientOriginalExtension();
// Move the file to the target directory
$file->move($imageFolder, $filename);
$fille = new TachePj();
$fille->setIdUser($id);
$fille->setIdTache($id);
$fille->setUrl("/assets/tache_pj/" . $filename);
$entityManager->persist($fille);
$entityManager->flush();
}
$codeStatut = "OK";
$response = "Files uploaded successfully.";
} else {
$response = "No files uploaded.";
}
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getTachePiece', name: 'getTachePiece')]
public function getTachePiece(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
// $id = $decoded['userId'];
$id = $request->get("id");
$tache = $entityManager->getRepository(Tache::class)->find($id);
if($tache)
{
$responseObjects['tache'] = $tache;
$files = [];
$images = $entityManager->getRepository(TachePj::class)->findBy(array('id_tache' => $id));
foreach($images as $image)
{
$filePath = $this->getParameter('kernel.project_dir') . '/public' . $image->getUrl();
$file = new File($filePath);
$toSend['id'] = $image->getId();
$toSend['file'] = $file;
$files[] = $toSend;
}
$responseObjects['files'] = $files;
$response = 'ok';
$codeStatut = "OK";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/removePiece', name: 'removePiece')]
public function removePiece(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
/*$chckAccess = $baseService->RoleMobile(101,2);
if($chckAccess == 0){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
else if ($chckAccess == 2)
{
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}*/
if($response == '')
{
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
// $id = $decoded['userId'];
$id = $request->get("id");
$piece = $entityManager->getRepository(TachePj::class)->find($id);
if($piece)
{
if($piece->getIdUser() == $id)
{
$entityManager->remove($piece);
$entityManager->flush();
$response = 'ok';
$codeStatut = "OK";
}
else
{
$codeStatut = "ERROR-ACC";
$response = "Desolé, vous n'avez pas pu supprimer ce fichier !!";
}
}
else
{
$codeStatut = "ERROR-PIE";
$response = "Desolé, cette piece est introuvable !!";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/syncData', name: 'syncData')]
public function syncData(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository,BaseService $baseService): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$missionsJson = $request->get('missions');
$missions = json_decode($missionsJson, true);
$detailsJson = $request->get('details');
$details = json_decode($detailsJson, true);
$infosJson = $request->get('infos');
$infos = json_decode($infosJson, true);
$stockJson = $request->get('stockMission');
$stock = json_decode($stockJson, true);
$imagesJson = $request->get('images');
$images = json_decode($imagesJson, true);
$stockUtiliseJson = $request->get('stockUtilise');
$stockUtilise = json_decode($stockUtiliseJson, true);
$depensesJson = $request->get('depenses');
$depenses = json_decode($depensesJson, true);
$missToR = array();
$detaToR = array();
$infoToR = array();
$imagToR = array();
$stocToR = array();
$stdtToR = array();
$depeToR = array();
foreach($missions as $ms)
{
if($ms["sync"] == 1)
{
$mission = $entityManager->getRepository(Mission::class)->find($ms["id"]);
$mission->setDateFin(new \DateTime($ms["dateFin"]));
$mission->setEtatMiss($ms["etatMiss"]);
$entityManager->flush();
array_push($missToR, $ms["id"]);
}
}
$responseObjects["missToR"] = $missToR;
foreach($details as $dt)
{
if($dt["sync"] == 1)
{
$detail = $entityManager->getRepository(DetailMission::class)->find($dt["id"]);
$dateFin = $dt["dateFin"];
// Step 1: Remove the part in parentheses (e.g., (UTC+01:00))
$cleanedDateFin = preg_replace('/\s\(.*\)$/', '', $dateFin); // Result: "Thu Dec 05 2024 14:51:15 GMT+0100"
$detail->setDateFin(new \DateTime($cleanedDateFin));
$detail->setEtatDeta($dt["etatDeta"]);
$detail->setDeffTech($dt["deffTech"]);
$detail->setObseDeff($dt["obseDeff"]);
$detail->setLongitude($dt["longitude"]);
$detail->setLatitude($dt["latitude"]);
$entityManager->flush();
array_push($detaToR, $dt["id"]);
}
}
$responseObjects["detaToR"] = $detaToR;
foreach($infos as $inf)
{
if($inf["sync"] == 1)
{
$info = $entityManager->getRepository(InfosDetailFichier::class)->find($inf["id"]);
$info->setValueInfo($inf["value_info"]);
$entityManager->flush();
array_push($infoToR, $inf["id"]);
}
}
$responseObjects["infoToR"] = $infoToR;
foreach($stock as $s)
{
if($s["sync"] == 1)
{
$stockMiss = $entityManager->getRepository(StockMission::class)->find($s["id"]);
$stockMiss->setQte($s["qte"]);
$entityManager->flush();
array_push($stocToR, $s["id"]);
}
}
$responseObjects["stocToR"] = $stocToR;
$imageFolder = $this->getParameter('kernel.project_dir') . '/public/assets/imagesMissions/';
$seenIdDetailFichiers = array();
foreach ($images as $image) {
$idDetailFichier = $image['idDetailFichier'];
if (!in_array($idDetailFichier, $seenIdDetailFichiers)) {
$seenIdDetailFichiers[] = $idDetailFichier;
}
}
$allImagesRelated = $entityManager->getRepository(Images::class)->findBy(['idDetailFichier' => $seenIdDetailFichiers]);
foreach ($allImagesRelated as $imR) {
$entityManager->remove($imR);
}
foreach ($images as $imageData) {
// Extract data
$base64Data = $imageData['file'];
$idDetailFichier = $imageData['idDetailFichier'];
// Remove the header from the base64 data
$base64Data = preg_replace('/^data:image\/\w+;base64,/', '', $base64Data);
// Decode base64 data
$imageBase = base64_decode($base64Data);
// Generate a unique filename
$filename = md5(uniqid()) . '.jpeg'; // Assuming JPEG format
// Save the image to the desired location
$imagePath = $imageFolder . $filename; // Update with your desired path
file_put_contents($imagePath, $imageBase);
$image = new Images();
$image->setUrlImage('/assets/imagesMissions/' . $filename); // Assuming the path is relative to the public directory
$image->setIdDetailFichier($idDetailFichier);
$image->setIdFichier(0);
// Persist the Image object to the database
$entityManager->persist($image);
$entityManager->flush();
array_push($imagToR, $idDetailFichier);
}
$responseObjects["imagToR"] = $imagToR;
$seenIdDetail = array();
foreach ($stockUtilise as $stockData) {
$idDetail = $stockData['idDetail'];
if (!in_array($idDetail, $seenIdDetail)) {
$seenIdDetail[] = $idDetail;
}
}
$allIsRelated = $entityManager->getRepository(StockDetailFichier::class)->findBy(['idDetail' => $seenIdDetail]);
foreach ($allIsRelated as $imR) {
$entityManager->remove($imR);
}
foreach ($stockUtilise as $stockData) {
$stockDetailFichier = new StockDetailFichier();
$stockDetailFichier->setIdDetail($stockData["idDetail"]);
$stockDetailFichier->setIdMission($stockData["idMission"]);
$stockDetailFichier->setIdPiece($stockData["idPiec"]);
$stockDetailFichier->setQte($stockData["qte"]);
$stockDetailFichier->setDateCreation(new \DateTime($stockData["dateCreation"]));
// Persist the Stock Detail object to the database
$entityManager->persist($stockDetailFichier);
$entityManager->flush();
array_push($stdtToR, $stockData["idDetail"]);
$entityManager->flush();
}
$responseObjects["stdtToR"] = $stdtToR;
$oldDepenses = $entityManager->getRepository(Charge::class)->findBy(array("idAgent" => $id));
// Array to keep track of old expenses that need to be removed
$expensesToRemove = array();
// Remove old expenses that are not present in the new list
foreach ($oldDepenses as $oldDepense) {
$found = false;
foreach ($depenses as $de) {
if ($oldDepense->getId() == $de['id']) {
$found = true;
break;
}
}
if (!$found) {
// Mark the old expense for removal
$expensesToRemove[] = $oldDepense;
}
}
// Remove old expenses that are not present in the new list
foreach ($expensesToRemove as $expenseToRemove) {
$entityManager->remove($expenseToRemove);
}
// Add or update new expenses
foreach ($depenses as $de) {
if($de['sync'] == '1')
{
$found = false;
foreach ($oldDepenses as $oldDepense) {
if ($oldDepense->getId() == $de['id']) {
// Update the existing expense
$oldDepense->setTitrChar($de['titrChar']);
$oldDepense->setDateCreation(new \DateTime($de['dateCreation']));
$oldDepense->setIdAttCha($de['idAttCha']);
$oldDepense->setTotalHt($de['totalHt']);
$oldDepense->setTotalTtc($de['totalTtc']);
$oldDepense->setObservation($de['observation']);
$oldDepense->setModePaie($de['modePaie']);
$oldDepense->setIdAgent($id);
$found = true;
break;
}
}
if (!$found) {
// Add new expense
$charge = new Charge();
$charge->setTitrChar($de['titrChar']);
$charge->setDateCreation(new \DateTime($de['dateCreation']));
$charge->setIdAttCha($de['idAttCha']);
$charge->setTotalHt($de['totalHt']);
$charge->setTotalTtc($de['totalTtc']);
$charge->setObservation($de['observation']);
$charge->setIdFour(0);
$charge->setIdBure(0);
$charge->setModePaie($de['modePaie']);
$charge->setIdAgent($id);
$charge->setIdUtil($id);
$imageFolder = $this->getParameter('kernel.project_dir') . '/public/assets/images/Charges/';
$base64Data = $de['img'];
// Remove the header from the base64 data
$base64Data = preg_replace('/^data:image\/\w+;base64,/', '', $base64Data);
// Decode base64 data
$imageBase = base64_decode($base64Data);
// Generate a unique filename
$filename = md5(uniqid()) . '.jpeg'; // Assuming JPEG format
// Save the image to the desired location
$imagePath = $imageFolder . $filename;
file_put_contents($imagePath, $imageBase);
$charge->setImg("/assets/images/Charges/".$filename);
// Persist the Charge entity and flush it to the database
$entityManager->persist($charge);
}
$entityManager->flush();
array_push($depeToR, $de["id"]);
}
}
$responseObjects["depeToR"] = $depeToR;
// Flush changes to the database
$codeStatut = "OK";
$response = "ok";
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/getAllNotifications', name: 'getAllNotifications')]
public function getAllNotifications(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
JWTEncoderInterface $jwtManager,TacheRepository $tacheRepository): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$notifications = $entityManager->getRepository(Notifications::class)->findBy(
array('idUser' => $id),
array('id' => 'DESC'),
50 // Maximum number of results
);
$responseObjects = $notifications;
$response = 'ok';
$codeStatut = "OK";
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
//Tache:
#[Route('/webService/addTache', name: 'webServiceAddTache')]
public function addTache(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
TacheRepository $tacheRepository,BaseService $baseService,ValidateService $validateService , JWTEncoderInterface $jwtManager): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$chckAccess = $baseService->RoleMobile(92,$id);
if($chckAccess != 1){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
// else if ($chckAccess == 2)
// {
// $codeStatut = "ERROR-ACCES";
// $response = "erreur access";
// }
if($response == '')
{
try
{
$user = $entityManager->getRepository(Utilisateur::class)->find($id);
$dateCreation = new \DateTime();
$nomTach=$request->get('nomTach');
$prioTach=$request->get('prioTach');
$typeTach=$request->get('typeTach');
$dateEcheance=$request->get('dateEcheance');
$users=json_decode($request->get('users'));
$idMarche=$request->get('idMarche');
$objetDetail=$request->get('objetDetail');
$etatTach=$request->get('etatTach');
// $files = $_FILES['files'];
$dateDebut=$request->get('DateDebut');
$contraintes = array(
"nomTach" => array("val" => $nomTach, "length" => 255, "type" => "string", "isBlank" => true),
);
$valideBonCommande= $validateService->validateur($contraintes);
if ($valideBonCommande === true)
{
define('TARGET', './assets/tache_pj/'); // Repertoire cible
define('MAX_SIZE', 100000000); // Taille max en octets du fichier
define('WIDTH_MAX', 4000); // Largeur max de l'image en pixels
define('HEIGHT_MAX', 3000); // Hauteur max de l'image en pixels
// Tableaux de donnees
$tabExt = array('pdf', 'zip', 'png', 'gif','jpeg','jpg'); // Extensions autorisees
$affectationUser = true;
if($user->getTypeUtil() != 0){
//$chckAccess = $this->baseService->Role(126);
$chckAccess = $baseService->RoleMobile(126,$id);
if(!$chckAccess != 1){
$affectationUser = false;
}
}
$tache = new Tache();
$tache->setNomTach($nomTach);
$tache->setTypeTach($typeTach);
$tache->setDateCreation($dateCreation);
if($dateEcheance != "undefined"){
$tache->setDateEcheance(new \DateTime($dateEcheance));
}
if($dateDebut != "undefined"){
$tache->setDateDebut(new \DateTime($dateDebut));
}
$tache->setEtatTach($etatTach);
$tache->setPrioTach($prioTach);
$tache->setIdMarche($idMarche);
$entityManager->persist($tache);
$entityManager->flush();
$text = 'Veuillez consulter votre tâche affectée';
if($affectationUser != true )
{
$tacheUser = new TacheUtilisateur();
$tacheUser->setidUtil($user->getId());
$tacheUser->setIdTach($tache->getId());
$entityManager->persist($tacheUser);
$entityManager->flush();
//Notification util
$baseService->addNotifications($text , 1 , $tache->getId() , $user->getId(),0);
}
else
{
if (isset($users) && is_array($users) && count($users) > 0) {
foreach ($users as $u)
{
$tacheUser = new TacheUtilisateur();
$tacheUser->setidUtil($u);
$tacheUser->setIdTach($tache->getId());
$entityManager->persist($tacheUser);
$entityManager->flush();
//Notification util
$baseService->addNotifications($text , 1 , $tache->getId() , $u,0);
}
}else{
$tacheUser = new TacheUtilisateur();
$tacheUser->setidUtil($user->getId());
$tacheUser->setIdTach($tache->getId());
$entityManager->persist($tacheUser);
$entityManager->flush();
//Notification util
$baseService->addNotifications($text , 1 , $tache->getId() , $user->getId(),0);
}
}
if($user->getTypeUtil() == 0 && !$users){
//Notification util
$baseService->addNotifications($text , 1 , $tache->getId() , $user->getId(),0);
}
if (isset($objetDetail) && is_array($objetDetail) && count($objetDetail) > 0) {
for($i=0;$i<count($objetDetail);$i++)
{
$sousTache=new SousTache();
$sousTache->setIdTache($tache->getId());
$sousTache->setObjet($objetDetail[$i]);
$entityManager->persist($sousTache);
}
}
// for ($i = 0; $i < count($files['name']); $i++){
// $fille = new TachePj();
// $fille->setIdUser($user->getId());
// $fille->setIdTache($tache->getId());
// if (!empty($files['name'][$i])) {
// // Recuperation de l'extension du fichier
// $extension = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
// // On verifie l'extension du fichier
// if (in_array(strtolower($extension), $tabExt)) {
// $file_temp = $files['tmp_name'][$i];
// if (!empty($file_temp)) {
// // On recupere les dimensions du fichier
// $infosImg = getimagesize($files['tmp_name'][$i]);
// // On verifie les dimensions et taille de l'image
// if (filesize($files['tmp_name'][$i]) <= MAX_SIZE) {
// // Parcours du tableau d'erreurs
// if (isset($files['error'][$i]) && UPLOAD_ERR_OK === $files['error'][$i]) {
// // On renomme le fichier
// $nomImage = md5(uniqid()) . '.' . $extension;
// // Si c'est OK, on teste l'upload
// if (move_uploaded_file($files['tmp_name'][$i], TARGET . $nomImage))
// {
// $url = "/assets/tache_pj/" . $nomImage;
// $fille->setUrl($url);
// $entityManager->persist($fille);
// }
// }
// }
// }
// }
// }
// }
$entityManager->flush();
$responseObjects['id']=$tache->getId();
$response = "OK";
}
else
{
$response = 'Veuillez vérifier vos informations, un des champs est incorrect !';
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
}
$resp["codeStatut"] = $response;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/updateTache', name: 'webServiceUpdateTache')]
public function updateTache(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,
TacheRepository $tacheRepository,BaseService $baseService,ValidateService $validateService , JWTEncoderInterface $jwtManager): JsonResponse
{
$tokenJWT = "";
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$id = $decoded['userId'];
$idUser = $decoded['userId'];
$chckAccess = $baseService->RoleMobile(92,$idUser);
if($chckAccess != 1){
$codeStatut = "ERROR-ACCES";
$response = "erreur access";
}
if($response == '')
{
try
{
$user = $entityManager->getRepository(Utilisateur::class)->find($id);
$dateCreation = new \DateTime();
$idTach=$request->get('idTach');
$nomTach=$request->get('nomTach');
$prioTach=$request->get('prioTach');
$typeTach=$request->get('typeTach');
$dateEcheance=$request->get('dateEcheanceUp');
$users=json_decode($request->get('users'));
$idMarche=$request->get('idMarche');
$etatTach=$request->get('etatTachUp');
$objetDetail=$request->get('objetDetailUp');
$dateDebut=$request->get('dateDebutUp');
$tache = $entityManager->getRepository(Tache::class)->find($idTach);
if(!$tache)
{
$response = 'Desolé, cette tache est introuvable !';
}
else
{
$contraintes = array(
"nomTach" => array("val" => $nomTach, "length" => 255, "type" => "string", "isBlank" => true),
);
$valideBonCommande= $validateService->validateur($contraintes);
if ($valideBonCommande === true)
{
$sousTaches = $entityManager->getRepository(SousTache::class)->findByIdTache($idTach);
$tacheUsers = $entityManager->getRepository(TacheUtilisateur::class)->findByIdTach($idTach);
// Remove the tache
foreach($sousTaches as $s)
{
$entityManager->remove($s);
}
foreach($tacheUsers as $t)
{
$entityManager->remove($t);
}
$entityManager->flush();
$tache->setNomTach($nomTach);
$tache->setTypeTach($typeTach);
$tache->setDateCreation($dateCreation);
$tache->setDateEcheance(new \DateTime($dateEcheance));
$tache->setEtatTach($etatTach);
$tache->setPrioTach($prioTach);
$tache->setIdMarche($idMarche);
$tache->setDateDebut(new \DateTime($dateDebut));
$entityManager->persist($tache);
$entityManager->flush();
define('TARGET', './assets/tache_pj/'); // Repertoire cible
define('MAX_SIZE', 100000000); // Taille max en octets du fichier
define('WIDTH_MAX', 4000); // Largeur max de l'image en pixels
define('HEIGHT_MAX', 3000); // Hauteur max de l'image en pixels
// Tableaux de donnees
$tabExt = array('pdf', 'zip', 'png', 'gif','jpeg','jpg'); // Extensions autorisees
if($user->getTypeUtil() != 0)
{
$tacheUser = new TacheUtilisateur();
$tacheUser->setidUtil($user->getId());
$tacheUser->setIdTach($tache->getId());
$entityManager->persist($tacheUser);
$entityManager->flush();
}
else
{
if($users)
foreach ($users as $u)
{
$tacheUser = new TacheUtilisateur();
$tacheUser->setidUtil($u);
$tacheUser->setIdTach($tache->getId());
$entityManager->persist($tacheUser);
$entityManager->flush();
}
}
if(isset($objetDetail)){
for($i=0;$i<count($objetDetail);$i++)
{
$sousTache=new SousTache();
$sousTache->setIdTache($tache->getId());
$sousTache->setObjet($objetDetail[$i]);
$entityManager->persist($sousTache);
}
}
if(isset($files))
for ($i = 0; $i < count($files['name']); $i++){
$fille = new TachePj();
$fille->setIdUser($user->getId());
$fille->setIdTache($tache->getId());
if (isset($files) && !empty($files['name'][$i])) {
// Recuperation de l'extension du fichier
$extension = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
// On verifie l'extension du fichier
if (in_array(strtolower($extension), $tabExt)) {
$file_temp = $files['tmp_name'][$i];
if (!empty($file_temp)) {
// On recupere les dimensions du fichier
$infosImg = getimagesize($files['tmp_name'][$i]);
// On verifie les dimensions et taille de l'image
if (filesize($files['tmp_name'][$i]) <= MAX_SIZE) {
// Parcours du tableau d'erreurs
if (isset($files['error'][$i]) && UPLOAD_ERR_OK === $files['error'][$i]) {
// On renomme le fichier
$nomImage = md5(uniqid()) . '.' . $extension;
// Si c'est OK, on teste l'upload
if (move_uploaded_file($files['tmp_name'][$i], TARGET . $nomImage))
{
$url = "/assets/tache_pj/" . $nomImage;
$fille->setUrl($url);
$entityManager->persist($fille);
}
}
}
}
}
}
}
$entityManager->flush();
$response = 'ok';
}
else
{
$response = 'Veuillez vérifier vos informations, un des champs est incorrect !';
}
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
}
$resp["codeStatut"] = $response;
$resp["message"] = $response;
$resp["token"] = $tokenJWT;
$resp["object"] = $responseObjects;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/taskMail', name: 'taskMail')]
public function taskMail(Request $request,SerializerInterface $serializer,EntityManagerInterface $entityManager,BaseService $baseService): JsonResponse
{
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
//Task due
$query = $entityManager->createQuery(
'SELECT tu
FROM App\Entity\TacheUtilisateur tu where tu.idTach in (SELECT t.id
FROM App\Entity\Tache t where t.etatTach != 3 and t.dateEcheance < :dateNow )
'
);
$query->setParameter('dateNow', new \DateTime());
$resultDue = $query->getResult();
foreach ($resultDue as $value) {
$user = $entityManager->getRepository(Utilisateur::class)->find($value->getIdUtil());
$tache = $entityManager->getRepository(Tache::class)->find($value->getIdTach());
$nomUser = $user->getPrenUtil()." ".$user->getNomUtil();
$baseService->taskMail($user->getId(),$nomUser , 3 , $tache , $user->getEmaiUtil());
}
//Task in progress
$query = $entityManager->createQuery(
'SELECT tu
FROM App\Entity\TacheUtilisateur tu where tu.idTach in (SELECT t.id
FROM App\Entity\Tache t where t.etatTach = 2 )
'
);
$resultProgress = $query->getResult();
foreach ($resultProgress as $value) {
$user = $entityManager->getRepository(Utilisateur::class)->find($value->getIdUtil());
$tache = $entityManager->getRepository(Tache::class)->find($value->getIdTach());
$nomUser = $user->getPrenUtil()." ".$user->getNomUtil();
$baseService->taskMail($user->getId(),$nomUser , 2 , $tache , $user->getEmaiUtil());
}
$codeStatut = "OK";
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/addPointage', name: 'addPointage' , methods:['POST'])]
public function addPointage(Request $request, SerializerInterface $serializer,EntityManagerInterface $entityManager,BaseService $baseService , JWTEncoderInterface $jwtManager): JsonResponse
{
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$type = $request->get('type');
$arrayType = ['1','2','3','4'];
$datetime = new \DateTime();
$dateDay = $datetime->format('Y-m-d');
$check = true;
if(in_array($type , $arrayType)){
if($type == '1'){
if($this->pointageRepo->checkDebut($idUser , $dateDay) != false){
$check = false;
$response = "Veuillez pointer une manière correcte !";
};
}else if($type == '2' || $type == '3'){
if($this->pointageRepo->checkPause($idUser , $dateDay , $type) == false){
$check = false;
$response = "Veuillez pointer une manière correcte !";
};
}else if($type == '4'){
if($this->pointageRepo->checkFin($idUser , $dateDay ) == false){
$check = false;
$response = "Veuillez pointer une manière correcte !";
};
}
if($check == true){
$latitude = $request->get('latitude');
$longitude = $request->get('longitude');
if($latitude != "" && $latitude != "" ){
$pointage = new PointageUser();
$pointage->setDateAction(new \DateTime());
$pointage->setIdUser($idUser);
$pointage->setTypePointage($type);
$pointage->setLatitude($latitude);
$pointage->setLongitude($longitude);
$entityManager->persist($pointage);
$entityManager->flush();
$text = "Status de présence : ";
if($type == '1'){
$this->pointageRepo->insertWorkTime($idUser , $dateDay , 1);
$text .= 'Début de travail';
}else if($type == '2'){
$text .= 'Début de pause';
}else if($type == '3'){
$text .= 'Fin de pause';
}else if($type == '4'){
$text .= 'Fin de travail';
}
$response = $text;
if($type == '4'){
$this->pointageRepo->insertWorkTime2($idUser , $dateDay , 1);
// if($this->pointageRepo->checkAllType($idUser , $dateDay)){
// $this->pointageRepo->insertWorkTime($idUser , $dateDay , 1);
// }else if($this->pointageRepo->checkAllType2($idUser , $dateDay)){
// $this->pointageRepo->insertWorkTime($idUser , $dateDay , 2);
// }
}
$codeStatut = "OK";
}else{
$codeStatut = "ERREUR_MAPS";
$response = "Veuillez activer la localisation !";
}
}
}else{
$codeStatut="ERROR_DATA";
$response = "Veuillez vérifier vos données !";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/listeWorkPointage', name: 'listeWorkPointage' ,methods:['POST'])]
public function listeWorkPointage(Request $request, SerializerInterface $serializer,EntityManagerInterface $entityManager,BaseService $baseService , JWTEncoderInterface $jwtManager): JsonResponse
{
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$liste = [];
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$resp["date"] = $request->get('date');
$chckAccess = $baseService->RoleMobile(128,$idUser);
if($chckAccess == 1){
if($idUser ){
$datetime = new \DateTime($request->get('date'));
$dateDay = $datetime->format('Y-m-d');
if($datetime > new \DateTime()){
$codeStatut='ERROR_DATE';
$response='Veuillez vérifier la date saisie !';
}
else{
$liste = $this->pointageRepo->workTimeListe($dateDay);
$codeStatut = "OK";
}
}else{
$codeStatut="ERROR_DATA";
$response = "Veuillez vérifier vos données !";
}
}else{
$codeStatut="ERROR_ACCESS";
$response = "ERROR_ACCESS";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["data"] = $liste;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
#[Route('/webService/detailsPointageByDay', name: 'detailsPointageByDay' ,methods:['POST'])]
public function detailsPointageByDay(Request $request, SerializerInterface $serializer,EntityManagerInterface $entityManager,BaseService $baseService , JWTEncoderInterface $jwtManager): JsonResponse
{
$codeStatut = "ERROR";
$response = "";
$responseObjects = array();
$liste = [];
try
{
$jwt = $request->headers->get('Authorization');
$jwt = substr($jwt, 7);
$decoded = $jwtManager->decode($jwt);
$idUser = $decoded['userId'];
$date = $request->get('date');
$id = $request->get('id');
$chckAccess = $baseService->RoleMobile(128,$idUser);
if($idUser ){
$datetime = new \DateTime($date);
$dateDay = $datetime->format('Y-m-d');
$liste = $this->pointageRepo->workTimeListeByDay($id,$dateDay);
$codeStatut = "OK";
}else{
$codeStatut="ERROR_DATA";
$response = "Veuillez vérifier vos données !";
}
}
catch(\Exception $e)
{
$response = $e->getMessage();
$codeStatut = "ERROR-EXE";
}
$resp["codeStatut"] = $codeStatut;
$resp["message"] = $response;
$resp["data"] = $liste;
$resp["chckAccess"] = $chckAccess;
$json = $serializer->serialize($resp, 'json');
$jsonResponse = new JsonResponse($json, 200, [], true);
$jsonResponse->headers->set('Access-Control-Allow-Origin', '*');
$jsonResponse->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
$jsonResponse->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$jsonResponse->headers->set('Access-Control-Max-Age', 3600);
return $jsonResponse;
}
}