<?php
namespace App\Controller;
use App\Form\BubbleEditType;
use App\Model\Bubble;
use App\Utils\DefaultRights;
use App\Form\BubbleType;
use App\Model\Industrial;
use App\Service\SiteBackend;
use App\Service\BubbleBackend;
use App\Form\BubbleAddUserType;
use App\Service\IndustrialBackend;
use App\Utils\SessionUtils;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Model\Structure;
use App\Service\StructureBackend;
/**
* BubbleController
*/
class BubbleController extends AbstractController
{
use SessionUtils;
const ROLE_OBJECTS = ['user', 'site', 'industrial', 'plan', 'eco_model', 'token', 'history', 'quality_control', 'billing', 'job_order', 'printer', 'dashboard', 'structures', 'planning'];
const CRUD_LABELS = ['read', 'create', 'update', 'delete'];
/**
*
* @return Response
*
* @Route("/bubble", name="bubble")
*/
public function bubble()
{
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
if ($profile['user']['read'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
// User is SA
if ($user->getIsSA() == 1) {
$bubbles_infos = $user->getBubblesInfo();
} else {
$bubbles_infos = [];
}
return $this->render('bubble/bubble.html.twig', [
'bubbles_infos' => $bubbles_infos
]);
}
/**
* bubbleAdd
*
* @param TranslatorInterface $translator
* @param Request $request
* @param BubbleBackend $backend
* @return RedirectResponse|Response
*
* @Route("/bubble/add", name="bubble_add")
*/
public function bubbleAdd(
TranslatorInterface $translator,
Request $request,
BubbleBackend $backend
) {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
if ($profiles[$b_key]['user']['create'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$options['request'] = $request;
$form = $this->createForm(BubbleType::class, $options, [
'csrf_protection' => false
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$datas = $form->getData();
if ($datas['has_credits'] == false) {
$datas['number_credit'] = null;
$datas['credit_value'] = null;
$datas['threshold'] = null;
$datas['user_to_notify'] = null;
}
$responseStatus = $backend->postNewBubble($datas);
if ($responseStatus === Response::HTTP_OK) {
$this->addFlash('success', sprintf($translator->trans('La bulle <strong>%s</strong> a été créé.'), $datas['bubble_name']));
return $this->redirectToRoute('bubble');
} elseif ($responseStatus === Response::HTTP_CONFLICT) {
$this->addFlash('warning', sprintf($translator->trans('La bulle <strong>%s</strong> existe déjà . Veuillez essayer un autre nom de bulle.'), $datas['bubble_name']));
return $this->redirectToRoute('bubble_add');
} elseif ($responseStatus === Response::HTTP_UNAUTHORIZED) {
return $this->redirectToRoute('custom_error_403');
} elseif ($responseStatus === Response::HTTP_INTERNAL_SERVER_ERROR) {
$this->addFlash('errors', $translator->trans('Le serveur a rencontré une difficultée, veuillez ré-essayer ultérieurement'));
return $this->redirectToRoute('bubble_add');
} elseif ($responseStatus === Response::HTTP_BAD_REQUEST) {
$this->addFlash('warning', $translator->trans('Veuillez remplir tous les champs du formulaire'));
return $this->redirectToRoute('bubble_add');
} else {
$this->addFlash('errors', $translator->trans('Une erreur s\'est produite durant la création de la bulle. Veuillez ré-essayer ultérieurement.'));
}
}
return $this->render('bubble/bubble_add.html.twig', [
'bubbleForm' => $form->createView(),
]);
}
/**
* bubble update
*
* @param $bId
* @param TranslatorInterface $translator
* @param Request $request
* @param BubbleBackend $backend
* @return RedirectResponse|Response
*
* @Route("/bubble/update/{bId}", name="bubble_update")
*/
public function bubbleUpdate (
$bId,
TranslatorInterface $translator,
Request $request,
BubbleBackend $backend
) {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
if ($profiles[$b_key]['user']['create'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$bubbleResp = $backend->getBubble($user, $bId);
$bubbleRespStatus = $bubbleResp->getStatusCode();
if ($bubbleRespStatus === Response::HTTP_OK) {
$data = $bubbleResp->toArray()['contents'][0];
$bubble = new Bubble();
$bubble->setBName($data['b_name'])
->setBAddress($data['b_address'])
->setBPostalCode($data['b_postal_code'])
->setBCityName($data['b_city_name'])
->setBCountry($data['b_country'])
->setIsQcUpdatable($data['is_qc_updatable'])
->setNumberCredit($data['number_credit'])
->setStripeCustomerId($data['stripe_customer_id'])
->setStripePayMethodId($data['stripe_pay_method_id'])
->setCreditValue($data['credit_value'])
;
} elseif ($bubbleRespStatus === Response::HTTP_UNAUTHORIZED) {
return $this->redirectToRoute('custom_error_403');
} elseif ($bubbleRespStatus === Response::HTTP_INTERNAL_SERVER_ERROR) {
$this->addFlash('errors', $translator->trans('Le serveur a rencontré une difficultée, veuillez ré-essayer ultérieurement'));
return $this->redirectToRoute('bubble_update');
} elseif ($bubbleRespStatus === Response::HTTP_BAD_REQUEST) {
$this->addFlash('warning', $translator->trans('Veuillez remplir tous les champs du formulaire'));
return $this->redirectToRoute('bubble_update');
}
$form = $this->createForm(BubbleEditType::class, $bubble);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$data = $form->getData();
$responseStatus = $backend->updateBubble($data, $bId);
if ($responseStatus == Response::HTTP_OK) {
$this->addFlash('success', sprintf($translator->trans('La bulle<strong>%s</strong> a été modifiéé.'), $data->getBName()));
return $this->redirectToRoute('bubble');
} elseif ($responseStatus == Response::HTTP_UNAUTHORIZED) {
return $this->redirectToRoute('custom_error_403');
} elseif ($responseStatus == Response::HTTP_INTERNAL_SERVER_ERROR) {
$this->addFlash('errors', $translator->trans('Le serveur a rencontré une difficultée, veuillez ré-essayer ultérieurement'));
return $this->redirectToRoute('bubble_update');
} elseif ($responseStatus == Response::HTTP_BAD_REQUEST) {
$this->addFlash('warning', $translator->trans('Veuillez remplir tous les champs du formulaire'));
return $this->redirectToRoute('bubble_update');
} else {
$this->addFlash('errors', $translator->trans('Une erreur s\'est produite durant la modification de la bulle. Veuillez ré-essayer ultérieurement.'));
}
}
return $this->render('bubble/bubble_update.html.twig', [
'bubbleForm' => $form->createView()
]);
}
/**
* bubbleUserList
*
* @param BubbleBackend $backend
* @return Response
*
* @Route("/bubble/users", name="bubble_user_list")
*/
public function bubbleUserList(
BubbleBackend $backend
) {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
$bubbleId = $profile['b_id'];
if ($profiles[$b_key]['user']['read'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$response = $backend->getBubbleProfiles($user, $bubbleId);
if ($response->getStatusCode() == Response::HTTP_OK) {
$result = json_decode($response->getContent(), true);
} elseif ($response->getStatusCode() == Response::HTTP_UNAUTHORIZED) {
return $this->redirectToRoute('custom_error_401');
} elseif ($response->getStatusCode() == Response::HTTP_FORBIDDEN) {
return $this->redirectToRoute('custom_error_403');
} elseif ($response->getStatusCode() == Response::HTTP_NOT_FOUND) {
return $this->redirectToRoute('custom_error_404');
} else {
return $this->redirectToRoute('custom_error_500');
}
$user_profiles = $result['contents'];
$manageProfile = $backend->manageProfile($user_profiles);
return $this->render('bubble/bubble_user_list.html.twig', [
'user_profiles' => $user_profiles,
'profilesBA' => $manageProfile['profilesBA'],
'profilesOP' => $manageProfile['profilesOP'],
'profilesVP' => $manageProfile['profilesVP'],
'profilesMan' => $manageProfile['profilesFAB'],
'profilesIND' => $manageProfile['profilesIND'],
'profilesFM' => $manageProfile['profilesFM'],
'profilesOM' => $manageProfile['profilesOM'],
'profilesCL' => $manageProfile['profilesCL'],
'usersTotal' => count($user_profiles),
'usersBaNb' => count($manageProfile['profilesBA']),
'usersManNb' => count($manageProfile['profilesFAB']),
'usersOpeNb' => count($manageProfile['profilesOP']),
'usersVplanNb' => count($manageProfile['profilesVP']),
'usersIndusNb' => count($manageProfile['profilesIND']),
'usersFmNb' => count($manageProfile['profilesFM']),
'usersOmNb' => count($manageProfile['profilesOM']),
'usersClNb' => count($manageProfile['profilesCL']),
'user' => $user
]);
}
/**
* Update profile roles
*
* @param TranslatorInterface $translator
* @param Request $request
* @param BubbleBackend $backend
* @param $perm_id
* @return Response
*
* @Route("/bubble/profiles/{perm_id}", name="bubble_user_update")
*/
public function bubbleUserUpdate (
$perm_id,
TranslatorInterface $translator,
Request $request,
BubbleBackend $backend
): Response {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$bubbleId = $profiles[$b_key]['b_id'];
if ($profiles[$b_key]['user']['update'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$profileUserId = $request->request->get('profile_user_id');
$nBRoleObjects = self::ROLE_OBJECTS;
$nBCrudLabels = self::CRUD_LABELS;
$permissions = [];
for ($j = 0; $j < count($nBRoleObjects); $j++) {
for ($i = 0; $i < count($nBCrudLabels); $i++) {
$permissions[self::ROLE_OBJECTS[$j]] =
[
'read' => ($request->request->get('read' . $j) == 1) ? 1 : 0,
'create' => ($request->request->get('create' . $j) == 1) ? 1 : 0,
'update' => ($request->request->get('update' . $j) == 1) ? 1 : 0,
'delete' => ($request->request->get('delete' . $j) == 1) ? 1 : 0
];
}
}
/** Block to manage default rigths > */
$inputs_name = json_decode($request->request->get('inputs_name'), true);
if (!is_null($inputs_name)) {
foreach ($permissions as $permission) {
foreach ($inputs_name as $key => $input_name) {
$label_name = substr($key, 0, strpos($key, '_', 0));
if ('ecoModel' == $label_name) {
$label_name = 'eco_model';
$key = 'eco_model';
}
if ('tokenApiAccess' == $label_name) {
$label_name = 'token';
$key = 'token';
}
if ('qualityControl' == $label_name) {
$label_name = 'quality_control';
$key = 'quality_control';
}
if ('jobOrders' == $label_name) {
$label_name = 'job_order';
$key = 'job_order';
}
if ('billingElements' == $label_name) {
$label_name = 'billing';
$key = 'billing';
}
if ('jobHistory' == $label_name) {
$label_name = 'history';
$key = 'history';
}
if ('printers' == $label_name) {
$label_name = 'printer';
$key = 'printer';
}
if ('read' == substr($input_name, 0, 4) && stristr($key, $label_name)) {
unset($permissions[$label_name]['read']);
$permissions[$label_name]['read'] = 1;
}
if ('create' == substr($input_name, 0, 6) && stristr($key, $label_name)) {
unset($permissions[$label_name]['create']);
$permissions[$label_name]['create'] = 1;
}
if ('update' == substr($input_name, 0, 6) && stristr($key, $label_name)) {
unset($permissions[$label_name]['update']);
$permissions[$label_name]['update'] = 1;
}
if ('delete' == substr($input_name, 0, 6) && stristr($key, $label_name)) {
unset($permissions[$label_name]['delete']);
$permissions[$label_name]['delete'] = 1;
}
}
}
}
/** Block to manage default rigths < */
// $permissions['bubble'] = json_decode($request->request->get('bubble'), TRUE);
// $permissions['bc_certification'] = json_decode($request->request->get('bc_certification'), TRUE);
$permissions['bubble'] = $profiles[$b_key]['bubble'];
$permissions['bc_certification'] = $profiles[$b_key]['bc_certification'];
$response = $backend->getBubbleProfiles($user, $bubbleId);
$result = json_decode($response->getContent(), true);
$user_profiles = $result['contents'];
$label = '';
foreach ($user_profiles as $profile) {
if ($profile['perm_id'] == $perm_id) {
$label = $profile['label'];
$u_profile_id = $profile['u_id'];
}
}
$results = $backend->updateProfiles($bubbleId, $permissions, $label, $perm_id, $u_profile_id);
$manageProfile = $backend->manageProfile($user_profiles);
if ($manageProfile['iSnotVpIsNotFab']) {
$this->addFlash('warning', $translator->trans('Rôle non attribué : ') . $manageProfile['labelNorme']);
}
return $this->render('bubble/bubble_user_list.html.twig', [
'user_profiles' => $user_profiles,
'profilesBA' => $manageProfile['profilesBA'],
'profilesOP' => $manageProfile['profilesOP'],
'profilesVP' => $manageProfile['profilesVP'],
'profilesMan' => $manageProfile['profilesFAB'],
'profilesIND' => $manageProfile['profilesIND'],
'profilesFM' => $manageProfile['profilesFM'],
'profilesOM' => $manageProfile['profilesOM'],
'profilesCL' => $manageProfile['profilesCL'],
'usersTotal' => count($user_profiles),
'usersBaNb' => count($manageProfile['profilesBA']),
'usersManNb' => count($manageProfile['profilesOP']),
'usersOpeNb' => count($manageProfile['profilesVP']),
'usersVplanNb' => count($manageProfile['profilesFAB']),
'usersIndusNb' => count($manageProfile['profilesIND']),
'usersFmNb' => count($manageProfile['profilesFM']),
'usersOmNb' => count($manageProfile['profilesOM']),
'usersClNb' => count($manageProfile['profilesCL']),
'user' => $user
]);
}
/**
* Re-activate Account
*
* @param [type] $recipient_u_id
* @param mixed $backend
* @param TranslatorInterface $translator
*
* @return Response
*
* @Route("/bubble/user/activate/{recipient_u_id}/{u_email}", name="re_send_activation")
*/
public function reSendActivation(
$recipient_u_id, $u_email,
BubbleBackend $backend,
TranslatorInterface $translator
) {
$session = $this->sessionByRequestStack();
$recipient_u_id = (int)$recipient_u_id;
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$bubbleId = $profiles[$b_key]['b_id'];
if ($profiles[$b_key]['user']['update'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
if ($recipient_u_id) {
$response = $backend->reActivateAccount($bubbleId, $recipient_u_id);
if ($response == Response::HTTP_OK) {
$this->addFlash("success", $translator->trans("L'utilisateur " . $u_email . $translator->trans(" a reçu un e-mail d'activation" )));
return $this->redirectToRoute('bubble_user_list');
} elseif ($response == Response::HTTP_UNAUTHORIZED) {
$this->addFlash("errors", $translator->trans("Vous n'êtes pas autorisé pour envoyer un e-mail d'activation" ));
return $this->redirectToRoute('bubble_user_list');
} else {
$this->addFlash("errors", $translator->trans("Une erreur s'est produite lors de l'envoi d'un e-mail d'activation pour l'utilisateur " . $u_email . $translator->trans(". Veuillez vérifier les droits d'accès ou interroger l'administrateur." )));
return $this->redirectToRoute('bubble_user_list');
}
} else{
$this->addFlash("errors", $translator->trans("L'utilisateur " . $u_email . $translator->trans(" n'existe pas. Veuillez interroger l'administrateur." )));
return $this->redirectToRoute('bubble_user_list');
}
}
/**
* @param Request $request
* @param BubbleBackend $backend
* @param StructureBackend $structureBackend
* @param SiteBackend $sbackend
* @param IndustrialBackend $indusBackend
* @param TranslatorInterface $translator
* @param SerializerInterface $serializer
* @return Response
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*
* @Route("/bubble/user/add", name="bubble_user_add")
*/
public function bubbleAddUser (
Request $request,
BubbleBackend $backend,
SiteBackend $sbackend,
IndustrialBackend $indusBackend,
StructureBackend $structureBackend,
TranslatorInterface $translator,
SerializerInterface $serializer
) : Response {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$bubbleId = $profiles[$b_key]['b_id'];
$profile = $profiles[$b_key];
if ($profiles[$b_key]['user']['create'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$lng = $request->getLocale();
$sites = $sbackend->getSiteByBubble($bubbleId, $user);
if ($profiles[$b_key]['industrial']['read'] == 1) {
$response = $indusBackend->getIndustrials($bubbleId, $user);
if ($response->getStatusCode() == Response::HTTP_OK) {
$data = json_decode($response->getContent());
$industrials = [];
foreach ($data->contents as $industrial) {
$industrials[] = $serializer->deserialize(json_encode($industrial), Industrial::class, 'json');
}
} elseif ($response->getStatusCode() == Response::HTTP_UNAUTHORIZED) {
return $this->redirectToRoute('custom_error_401');
} elseif ($response->getStatusCode() == Response::HTTP_FORBIDDEN) {
return $this->redirectToRoute('custom_error_403'); //bubble_user_add
} elseif ($response->getStatusCode() == Response::HTTP_NOT_FOUND) {
return $this->redirectToRoute('custom_error_404');
} else {
return $this->redirectToRoute('custom_error_500');
}
// Remove plan with name = fichier interne
foreach ($industrials as $k => $company) {
if ($company->getIndName() == 'Fichier interne') {
unset($industrials[$k]);
}
}
} else {
$industrials = [];
}
$organizations = $structureBackend->getOrganizations($bubbleId);
$organizationsList = [];
if ($organizations->getStatusCode() === Response::HTTP_OK) {
$organizationsArr = json_decode($organizations->getContent());
foreach ($organizationsArr->contents as $organization) {
$organizationsList[] = $serializer->deserialize(json_encode($organization), Structure::class, 'json');
}
}
$formations = $structureBackend->getFormations($bubbleId);
$formationsList = [];
if ($formations->getStatusCode() === Response::HTTP_OK) {
$formationsArr = json_decode($formations->getContent());
foreach ($formationsArr->contents as $formation) {
$formationsList[] = $serializer->deserialize(json_encode($formation), Structure::class, 'json');
}
}
$userRights = json_decode(( $backend->getAllProfileRights($bubbleId, $user))->getContent(), true);
$profilesLabels = [];
foreach ($userRights['contents'] as $p) {
$pId = $p['perm_id'];
if ($p['label'] == 'BA') {
$l = $lng == 'fr' ? 'Administrateur' : 'Administrator';
$profilesLabels[$l] = $pId;
} elseif ($p['label'] == 'OP') {
$l = $lng == 'fr' ? 'Opérateur' : 'Operator';
$profilesLabels[$l] = $pId;
} elseif ($p['label'] == 'IND') {
$l = $lng == 'fr' ? 'Industriel' : 'Industrial';
$profilesLabels[$l] = $pId;
} elseif ($p['label'] == 'MAN') {
$l = $lng == 'fr' ? 'Fabricant' : 'Manufacturer';
$profilesLabels[$l] = $pId;
} elseif ($p['label'] == 'VP') {
$l = $lng == 'fr' ? 'Valideur plan' : 'Plan validator';
$profilesLabels[$l] = $pId;
} elseif ($p['label'] == 'CL') {
$l = $lng == 'fr' ? 'Client' : 'Client';
$profilesLabels[$l] = $pId;
}
}
$options['profiles'] = $profilesLabels;
$options['sites'] = $sites;
$options['companies'] = $industrials;
$options['organizations'] = $organizationsList;
$options['formations'] = $formationsList;
$options['request'] = $request;
$label = 'nouvel utilisateur';
$form = $this->createForm(BubbleAddUserType::class, NULL, $options);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$formData = $form->getData();
$data = [
'b_id' => (int)$bubbleId,
'new_u_email' => $formData['email'],
'u_pref_lang' => $formData['lang'],
'label' => $userRights['contents'][$request->get("hiddenchoice")]['label']
];
if (array_key_exists("site", $formData)) {
if (!is_null($formData['site'])) {
$data['site_id'] = $formData['site']->getSId();
}
}
if (array_key_exists("compagnie", $formData)) {
if (!is_null($formData['compagnie'])) {
$data['ind_id'] = $formData['compagnie']->getIndId();
}
}
if (array_key_exists("form_id", $formData)) {
if (!is_null($formData['form_id'])) {
$data['struct_id'] = $formData['form_id']->getStructId();
}
}
if (array_key_exists("org_id", $formData)) {
if (!is_null($formData['org_id'])) {
$data['struct_id'] = $formData['org_id']->getStructId();
}
}
$response = $backend->addBubbleUser($data);
if ($response == Response::HTTP_OK) {
$this->addFlash('success', sprintf($translator ->trans('L\'utilisateur') . " <strong>%s</strong> " . sprintf($translator ->trans('a été ajouté à votre compte')), $formData['email']));
return $this->redirectToRoute('bubble_user_list');
} elseif ($response == Response::HTTP_CONFLICT) {
$this->addFlash('warning', sprintf($translator ->trans("L’utilisateur %s existe déjà sur cet espace MainChain"), $formData['email']));
return $this->redirectToRoute('bubble_user_list');
} else {
$this->addFlash('errors', sprintf($translator ->trans('Une erreur est survenue lors de l\'ajout de') . ' <strong>%s</strong>', $formData['email']));
return $this->redirectToRoute('bubble_user_list');
}
}
if(empty($sites)){
$url = $this->generateUrl('site_add');
if ($profile['site']['create'] == 1) {
$this -> addFlash('info', $translator -> trans('Votre compte ne contient pas de') . ' <a href="' . $url . '" >' . $translator -> trans('site de production'). '</a>, ' . $translator -> trans('vous ne pourrez pas ajouter de profil "Opérateur".'));
} else {
$this->addFlash('info', $translator->trans('Votre compte ne contient pas de site de production, vous ne pourrez pas ajouter de profil "Opérateur".'));
}
}
return $this->render('bubble/bubble_user_add.html.twig', [
'form' => $form->createView(),
'label' => $label,
'sites' => $sites,
'industrials' => $industrials,
'organizations' => $organizationsList,
'formations' => $formationsList
]);
}
/**
* bubbleDeleteProfile
*
* @param $u_id
* @param BubbleBackend $backend
* @param TranslatorInterface $translator
* @return RedirectResponse
* @throws TransportExceptionInterface
*
* @Route("/bubble/profile/delete/{u_id}", name="bubble_profile_delete")
*/
public function bubbleDeleteProfile (
$u_id,
BubbleBackend $backend,
TranslatorInterface $translator
): RedirectResponse {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
$bubbleId = $profiles[$b_key]['b_id'];
if ($profile['user']['delete'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
if ($u_id) {
$response = $backend->deleteBubbleProfile($bubbleId, $user, $u_id);
if ($response->getStatusCode() == Response::HTTP_OK || $response->getStatusCode() == Response::HTTP_NO_CONTENT) {
$this->addFlash("info", $translator->trans("L'utilisateur a bien été supprimé" ));
return $this->redirectToRoute('bubble_user_list');
} elseif ($response->getStatusCode() == Response::HTTP_UNAUTHORIZED) {
$this->addFlash("errors", $translator->trans("Vous n'êtes pas autorisé à supprimer cette utilisateur" ));
return $this->redirectToRoute('bubble_user_list');
} else {
$this->addFlash("errors", $translator->trans("Une erreur s'est produite lors de la suppression d'utilisateur. Veuillez vérifier les droits d'accès ou interroger l'administrateur." ));
return $this->redirectToRoute('bubble_user_list');
}
} else {
$this->addFlash("errors", $translator->trans("L'utilisateur n'existe pas. Veuillez interroger l'administrateur." ));
return $this->redirectToRoute('bubble_user_list');
}
}
/**
* Display single user right
*
* @param $pem_id
* @param BubbleBackend $backend
* @param TranslatorInterface $translator
* @param Request $request
* @return JsonResponse|RedirectResponse|void
*
* @Route("/bubble/profiles/user/{u_id}", name="single_user_rights")
*/
public function singleUserRights(
$pem_id,
BubbleBackend $backend,
TranslatorInterface $translator,
Request $request
) {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
$bubbleId = $profiles[$b_key]['b_id'];
if ($profile['user']['read'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$profileUserId = $request->request->get('profile_user_id');
if ($pem_id) {
$response = $backend->getOneProfileRights($bubbleId, $profileUserId, $pem_id);
$result = json_decode($response->getContent(), true);
$dataFiltered = $this->dataFiltered($result['contents']);
if ($response->getStatusCode() == Response::HTTP_OK) {
if ($request->isXmlHttpRequest()) {
foreach ($dataFiltered as $row) {
return $this->json([
'content' => $row
], '200');
}
}
return $this->redirectToRoute('bubble_user_list');
} elseif ($response-> getStatusCode() == Response::HTTP_UNAUTHORIZED) {
$this->addFlash("errors", "single_user_rights unauthorized" );
return $this->redirectToRoute('bubble_user_list');
} else {
$this->addFlash("errors", $translator->trans("Une erreur single_user_rights. Veuillez vérifier les droits d'accès ou interroger l'administrateur." ));
return $this->redirectToRoute('bubble_user_list');
}
}
}
/**
* Display user rigths matrice in popup for update
* singleUserProfileRights
*
* @param $perm_id
* @param BubbleBackend $bubbleBackend
* @param TranslatorInterface $translator
* @param Request $request
* @return JsonResponse|RedirectResponse|void
*
* @Route("/bubble/profiles/rights/{perm_id}", name="single_profiles_rights")
*/
public function singleUserProfileRights(
$perm_id,
BubbleBackend $bubbleBackend,
TranslatorInterface $translator,
Request $request
) {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
$bubbleId = $profiles[$b_key]['b_id'];
if ($profile['user']['read'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$profileUserId = $request->request->get('profile_user_id');
if ($perm_id) {
$response = $bubbleBackend->getOneProfileRightsByPermId($bubbleId, $profileUserId, $perm_id);
$result = json_decode($response->getContent(), true);
if ($response->getStatusCode() == Response::HTTP_OK) {
if ($request->isXmlHttpRequest()) {
return $this->json([
'content' => [
'result' => $result['contents'][0],
'inputsName' => DefaultRights::inputsNameByProfile($result['contents'][0])
]
], '200');
}
return $this->redirectToRoute('bubble_user_list');
} elseif ($response-> getStatusCode() == Response::HTTP_UNAUTHORIZED) {
$this->addFlash("errors", "single_user_rights unauthorized" );
return $this->redirectToRoute('bubble_user_list');
} else {
$this->addFlash("errors", $translator->trans("Une erreur single_user_rights. Veuillez vérifier les droits d'accès ou interroger l'administrateur." ));
return $this->redirectToRoute('bubble_user_list');
}
}
}
/**
* Display all user rights
*
* @param BubbleBackend $backend
* @param TranslatorInterface $translator
* @param Request $request
* @return Response
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*
* @return Response
*
* @Route("/bubble/profiles-default", name="all_user_rights")
*/
public function allUserRights(
BubbleBackend $backend,
TranslatorInterface $translator,
Request $request
): Response {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
$bubbleId = $profiles[$b_key]['b_id'];
if ($profile['user']['read'] == 0) {
return $this->redirectToRoute('custom_error_403');
}
$response = $backend->getAllProfileRights($bubbleId, $user);
$result = json_decode($response->getContent(), true);
$dataFiltered = $backend->dataFilteredAll($result['contents']);
if ($response->getStatusCode() == Response::HTTP_OK) {
if ($request->isXmlHttpRequest()) {
$index = $request->request->get('index');
foreach ($dataFiltered as $k => $row) {
if ($result['contents'][$k]['label'] == $index) {
return $this->json([
'content' => $dataFiltered[$k]
], '200');
}
}
}
return $this->redirectToRoute('bubble_user_add');
} elseif ($response->getStatusCode() == Response::HTTP_UNAUTHORIZED) {
$this->addFlash("errors", "all_user_rights unauthorized" );
return $this->redirectToRoute('bubble_user_add');
} else {
$this->addFlash("errors", $translator->trans("Une erreur all_user_rights. Veuillez vérifier les droits d'accès ou interroger l'administrateur." ));
return $this->redirectToRoute('bubble_user_add');
}
}
/**
* Array for filtering profile
*
* @param $data
* @return array
*/
private function dataFiltered($data): array
{
return [
'User' => $data['profiles'][0]['user'],
'Site' => $data['profiles'][0]['site'],
'Industrial' => $data['profiles'][0]['industrial'],
'Plan' => $data['profiles'][0]['plan'],
'Ecomodel' => $data['profiles'][0]['eco_model'],
'Token API Access' => $data['profiles'][0]['token'],
'Job History' => $data['profiles'][0]['history'],
'Quality Control' => $data['profiles'][0]['quality_control'],
'Billing Elements' => $data['profiles'][0]['billing'],
'Job Orders' => $data['profiles'][0]['job_order'],
'Printers' => $data['profiles'][0]['printer'],
'Dashboard' => $data['profiles'][0]['dashboard'],
'Structures' => $data['profiles'][0]['structures'],
'Planning' => $data['profiles'][0]['planning'],
];
}
}