<?php
namespace App\Controller;
use finfo;
use App\Entity\Clients;
use App\Service\Securizer;
use App\Library\GraphOneDrive;
use App\Repository\ClientsRepository;
use App\Repository\ContactsRepository;
use App\Repository\ContratsRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
class ClientController extends AbstractController
{
function calculateHotlineCompteur($client, ContratsRepository $repoContrats)
{
$contratEnCours = $repoContrats->getContratsActifBy($client->getId(), "Télémaintenance");
$sum = 0;
foreach ($contratEnCours as $key => $contrat) {
$lignes = $contrat->getLigneDeContrats();
for ($i = 0; $i < count($lignes); $i++) {
if ($lignes[$i]->getIdTypeIntervention()->gettype() === "Télémaintenance")
$sum += $lignes[$i]->getQuantitePrevus() - $lignes[$i]->getQuantiteConsome();
}
}
$client->setHotlineCompteur($sum - $client->getHotlineCompteur());
return $client;
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function index(ClientsRepository $repoClient, ContratsRepository $repoContrats, AccessDecisionManagerInterface $accessDecisionManager): Response
{
// Retourne tous les clients if->role_tech or seulement le meme client if->role_client
$securizer = new Securizer($accessDecisionManager);
$clients = $repoClient->findClientTous($this->getUser(), $securizer);
foreach ($clients as $client) {
$client = $this->calculateHotlineCompteur($client, $repoContrats);
}
return $this->json($clients, 200, [], ['groups' => 'affichageClient']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function actif(ClientsRepository $repoClient, ContratsRepository $repoContrats, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir la liste des clients actif
$securizer = new Securizer($accessDecisionManager);
$clients = $repoClient->findClientActif($this->getUser(), $securizer);
foreach ($clients as $client) {
$client = $this->calculateHotlineCompteur($client, $repoContrats);
}
return $this->json($clients, 200, [], ['groups' => 'affichageClient']);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function archiver(ClientsRepository $repoClient, ContratsRepository $repoContrats, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir la liste des clients archivé
$securizer = new Securizer($accessDecisionManager);
$clients = $repoClient->findClientArchiver($this->getUser(), $securizer);
foreach ($clients as $client) {
$client = $this->calculateHotlineCompteur($client, $repoContrats);
}
return $this->json($clients, 200, [], ['groups' => 'affichageClient']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function voir($id, ClientsRepository $repoClient, ContratsRepository $repoContrats, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//voir un client par $id
$securizer = new Securizer($accessDecisionManager);
//recupere l'id du ou des client qu'il est possible d'afficher
$clients = $repoClient->findClientTous($this->getUser(), $securizer);
//verifi que le client que l'on cherche fait bien partie de la liste de ceux qu'il est possible d'afficher
if (in_array($repoClient->find($id), $clients)) {
$client = $repoClient->find($id);
$client = $this->calculateHotlineCompteur($client, $repoContrats);
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter ce client"
], 400);
}
return $this->json($client, 200, [], ['groups' => ['affichageClient', 'affichageInfoClient']]);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function searchClient($search, ClientsRepository $repoClient, ContratsRepository $repoContrats, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$securizer = new Securizer($accessDecisionManager);
$clients = $repoClient->globalSearch($search, $this->getUser(), $securizer);
return $this->json($clients, 200, [], ['groups' => 'affichageClient']);
}
/**
* @IsGranted("ROLE_CLIENT")
*/
public function logoClient(Request $request, $id, ClientsRepository $repoClient, ContactsRepository $repoContacts, EntityManagerInterface $manager, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$securizer = new Securizer($accessDecisionManager);
$client = $repoClient->find($id);
if (!$securizer->isGranted($this->getUser(), "ROLE_TECH") && $client->getId() !== $repoContacts->findOneBy(["mail" => $this->getUser()->getUserIdentifier()])->getIdClient()->getId())
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez modifier le logo de ce client"
], 400);
//le dossier de destination du fichier telecharger
$destination = $this->getParameter('kernel.project_dir') . '/public/img/logo_client';
//le fichier a telecharger
$img = $request->files->get("myFile");
//tableau des extention acceptées
$extensions = array('.png', '.gif', '.jpg', '.jpeg');
$extension = strrchr($_FILES['myFile']['name'], '.');
if (!in_array($extension, $extensions)) {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez uploder que des fichiers de type .png, .gif, .jpeg, .jpg"
], 400);
}
//tableau des type MINE accepter
$mineTypes = array('image/png', 'image/gif', 'image/jpg', 'image/jpeg');
$finfo = new finfo(FILEINFO_MIME_TYPE, NULL);
$fileMineType = $finfo->file($_FILES['myFile']['tmp_name']);
//renvoie un json d'erreur si le MINE type n'est pas dans le tableau
if (!in_array($fileMineType, $mineTypes)) {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez uploder que des fichiers de type .png, .gif, .jpeg, .jpg"
], 400);
}
//renomage du fichier pour qu'il soit unique sur la serveur
$newFilename = uniqid() . '-' . $img->getClientOriginalName();
//enregistrement du fichier dans le dossier de destination
$img->move($destination, $newFilename);
$client->setLogo("img/logo_client/" . $newFilename);
$manager->persist($client);
$manager->flush();
//json de retour pour envoi de l'url en base
return $this->json([
'status' => 200,
'url' => 'img' . '/' . $newFilename
], 200);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function creer(Request $request, ValidatorInterface $validator, SerializerInterface $serializer, EntityManagerInterface $manager): Response
{
//creer un nouveau client, seul les roles commercial et admin peuvent accer a cette url
$jsonRecu = $request->getContent();
try {
$client = $serializer->deserialize($jsonRecu, Clients::class, 'json');
$graph = new GraphOneDrive();
$idDrive = "b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi";
$folderClient = $graph->createFolderInDrive($idDrive, $client->getNom());
$folderPhotos = $graph->createDriveFolder($idDrive, $folderClient->getId(), "photos");
$client->setGraphFolderId($folderPhotos->getId());
$errors = $validator->validate($client);
if (count($errors) > 0)
return $this->json($errors, 400);
$manager->persist($client);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($client, 201, [], ['groups' => 'affichageClient']);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function modif($id, Request $request, ClientsRepository $repoClient, SerializerInterface $serializer, EntityManagerInterface $manager): Response
{
//modifi un client existant, seul les roles commercial et admin peuvent accer a cette url
$client = $repoClient->find($id);
if ($client == null) {
return $this->json([
'status' => 400,
'message' => "le client à modifier n'existe pas"
], 400);
}
$jsonRecu = json_decode($request->getContent(), true);
// effacer vars = null
foreach ($jsonRecu as $key => $value) {
if ($value === null) unset($jsonRecu[$key]);
}
unset($jsonRecu["commercialReferent"]);
unset($jsonRecu["contactReferent"]);
unset($jsonRecu["contacts"]);
if (isset($jsonRecu["hotlineCompteur"])) unset($jsonRecu["hotlineCompteur"]);
$jsonRecu = json_encode($jsonRecu);
try {
$serializer->deserialize($jsonRecu, Clients::class, 'json', ['object_to_populate' => $client]);
$manager->persist($client);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($client, 201, [], ['groups' => ['affichageClient', 'affichageInfoClient']]);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function setContactReferent($id, Request $request, ClientsRepository $repoClient, ContactsRepository $repoContacts, EntityManagerInterface $manager): Response
{
//modifi le contact referent de un client existant, seul les roles commercial et admin peuvent accer a cette url
$client = $repoClient->find($id);
if ($client == null)
return $this->json([
'status' => 400,
'message' => "le client à modifier n'existe pas"
], 400);
$jsonRecu = json_decode($request->getContent());
$contact = $repoContacts->findOneBy(["id" => $jsonRecu->contactId]);
try {
$client->setContactReferent($contact);
$manager->persist($client);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($client, 201, [], ['groups' => ['affichageClient', 'affichageInfoClient']]);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function setCommercialRef($id, Request $request, ClientsRepository $repoClient, ContactsRepository $repoContacts, EntityManagerInterface $manager): Response
{
//modifi le comercial referent de un client existant, seul les roles commercial et admin peuvent accer a cette url
$client = $repoClient->find($id);
if ($client == null)
return $this->json([
'status' => 400,
'message' => "le client à modifier n'existe pas"
], 400);
$jsonRecu = json_decode($request->getContent());
$commercial = $repoContacts->findOneBy(["id" => $jsonRecu->commercialId]);
if ($commercial != null && !in_array("ROLE_COMMERCIAL", $commercial->getRoles())) {
return $this->json([
'status' => 400,
'message' => "Le contact à ajouter n’a pas de rôle commercial"
], 400);
}
try {
$client->setCommercialReferent($commercial);
$manager->persist($client);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($client, 201, [], ['groups' => ['affichageClient', 'affichageInfoClient']]);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function setTechnicienRef($id, Request $request, ClientsRepository $repoClient, ContactsRepository $repoContacts, EntityManagerInterface $manager): Response
{
//modifi le technicien referent de un client existant, seul les roles commercial et admin peuvent accer a cette url
$client = $repoClient->find($id);
if ($client == null)
return $this->json([
'status' => 400,
'message' => "le client à modifier n'existe pas"
], 400);
$jsonRecu = json_decode($request->getContent());
$technicien = $repoContacts->findOneBy(["id" => $jsonRecu->technicienId]);
if ($technicien != null && !in_array("ROLE_TECH", $technicien->getRoles())) {
return $this->json([
'status' => 400,
'message' => "Le contact à ajouter n’a pas de rôle technicien"
], 400);
}
try {
$client->setTechnicienReferent($technicien);
$manager->persist($client);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($client, 201, [], ['groups' => ['affichageClient', 'affichageInfoClient']]);
}
/**
* @IsGranted("ROLE_COMMERCIAL")
*/
public function hotlineCompteur(ClientsRepository $repoClient, ContratsRepository $repoContrats, EntityManagerInterface $manager, AccessDecisionManagerInterface $accessDecisionManager): Response
{
// permet de mettre à jour les valeurs de hotlineCompteur sur les contracts de Télémaintenance
$securizer = new Securizer($accessDecisionManager);
$clients = $repoClient->findClientTous($this->getUser(), $securizer);
foreach ($clients as $client) {
$contratEnCours = $repoContrats->getContratsActifBy($client->getId(), "Télémaintenance");
if (count($contratEnCours) > 0) {
foreach ($contratEnCours[0]->getLigneDeContrats() as $ligne) {
$compteur = $client->getHotlineCompteur();
$prevus = $ligne->getQuantitePrevus();
$consome = $ligne->getQuantiteConsome();
if ($compteur > 0 && $ligne->getIdTypeIntervention()->getType() === "Télémaintenance" && $consome < $prevus) {
$ligne->setQuantiteConsome($consome + $compteur > $prevus ? $prevus : $consome + $compteur);
$client->setHotlineCompteur($consome + $compteur > $prevus ? $consome + $compteur - $prevus : 0);
$manager->persist($ligne);
$manager->persist($client);
}
}
}
}
$manager->flush();
return $this->json(true, 200, [], ['groups' => 'affichageClient']);
}
/**
* @IsGranted("ROLE_ADMIN")
*/
public function setIdOneDrive(Request $request, ClientsRepository $repoClient, EntityManagerInterface $manager, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$securizer = new Securizer($accessDecisionManager);
if (!$securizer->isGranted($this->getUser(), "ROLE_ADMIN"))
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
$jsonRecu = json_decode($request->getContent());
$client = $repoClient->find($jsonRecu->idClient);
$idOneDrive = $jsonRecu->idOneDrive;
if (!isset($client) || !isset($idOneDrive)) {
return $this->json([
'status' => 400,
'message' => "L'id du client ou l'id one drive ne sont pas correctes"
], 400);
}
try {
$client->setGraphFolderId($idOneDrive);
$manager->persist($client);
$manager->flush();
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json(true, 200, []);
}
}