src/Controller/IndexController.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Notifications;
  4. use App\Entity\NotificationsSeen;
  5. use App\Form\PartSearchType;
  6. use App\Repository\CompanyRepository;
  7. use App\Repository\LibraryRepository;
  8. use App\Repository\NotificationsRepository;
  9. use App\Repository\OrderRepository;
  10. use App\Repository\PartRepository;
  11. use App\Repository\SupplierRepository;
  12. use App\Repository\CompanySupplierRepository;
  13. use App\Repository\UserRepository;
  14. use App\Entity\License;
  15. use App\Entity\User;
  16. use App\Service\UtilService;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  24. use Symfony\Contracts\Translation\TranslatorInterface;
  25. use Doctrine\Persistence\ManagerRegistry;
  26. use Zxing\QrReader;
  27. use Symfony\Component\Filesystem\Filesystem;
  28. class IndexController extends AbstractController
  29. {
  30.     private $translator;
  31.     private $util;
  32.     private $em;
  33.     private $projectDir;
  34.     private $url;
  35.     /**
  36.      * IndexController constructor.
  37.      */
  38.     public function __construct(
  39.         TranslatorInterface $translator,
  40.         UtilService $utilService,
  41.         ManagerRegistry $doctrine,
  42.         string $projectDir,
  43.         string $addvance3dUrl)
  44.     {
  45.         $this->translator $translator;
  46.         $this->em $doctrine->getManager();
  47.         $this->util $utilService;
  48.         $this->projectDir $projectDir;
  49.         $this->url $addvance3dUrl;
  50.     }
  51.     /**
  52.      * @Route("/", name="app_home")
  53.      */
  54.     public function home(Security $security): Response
  55.     {
  56.         $user =$security->getUser();
  57.         if ($user)
  58.         {
  59.             return $this->redirectToRoute('app_index');
  60.         } else
  61.         {
  62.             return $this->redirectToRoute('app_login');
  63.         }
  64.     }
  65.     /**
  66.      * @Route({"en": "/index",
  67.      *         "es": "/inicio"}, name="app_index")
  68.      */
  69.     public function index(Security $securityRequest $requestPartRepository $partRepositoryOrderRepository $orderRepositoryLibraryRepository $libraryRepositorySupplierRepository $supplierRepositoryUserRepository $userRepositoryNotificationsRepository $notificationsRepository): Response
  70.     {
  71.         $user $security->getUser();
  72.         $company $this->getUser()->getCompany();
  73.         $roleUser $user->getRole();
  74.         if ($user)
  75.         {
  76.             if($request->isMethod('POST')){
  77.                 if(!empty($request->request->get('qr_option_webcam_snapshot'))){
  78.                     $fs = new Filesystem();
  79.                     $ds DIRECTORY_SEPARATOR;
  80.                     $filepath $this->projectDir$ds 'public' $ds 'tmp' $ds 'snapshot_' uniqid() . '.png';
  81.                     $snapshot base64_decode($request->request->get('qr_option_webcam_snapshot'));
  82.                     $fs->dumpFile($filepath$snapshot);
  83.                     $qrcode = new QrReader($filepath);
  84.                     $url $qrcode->text();
  85.                     $url_ preg_replace("(^https?://)"""$url);
  86.                     $url_addvance preg_replace("(^https?://)"""$this->url );
  87.                     $fs->remove(($filepath));
  88.                     if(empty($url)){
  89.                         $this->addFlash('error'$this->translator->trans('No se ha podido leer el QR.'));
  90.                         return $this->redirect($request->headers->get('referer'));
  91.                     }
  92.                     elseif(stripos($url_,$url_addvance)===0){
  93.                         return $this->redirect($url);
  94.                     }
  95.                     else{
  96.                         $this->addFlash('error'$this->translator->trans('La URL no es correcta.'));
  97.                         return $this->redirect($request->headers->get('referer'));
  98.                     }
  99.                 }
  100.                 elseif(!empty($request->request->get('qr_option_lector_input'))){
  101.                     $url $request->request->get('qr_option_lector_input');
  102.                     $url_ preg_replace("(^https?://)"""$url);
  103.                     $url_addvance preg_replace("(^https?://)"""$this->url );
  104.                     if(stripos($url_,$url_addvance)===0){
  105.                         return $this->redirect($url);
  106.                     }
  107.                     else{
  108.                         $this->addFlash('error'$this->translator->trans('La URL no es correcta.'));
  109.                         return $this->redirect($request->headers->get('referer'));
  110.                     }
  111.                 }
  112.             }
  113.             $parts $partRepository->buscarTodos($user);
  114.             $ordersRequested $orderRepository->buscarPorEstado($user,[0]);
  115.             $ordersPending =   $orderRepository->buscarPorEstado($user,[1,2]);
  116.             $ordersForthcoming $orderRepository->buscarPorEstado($user,[3]);
  117.             $ordersDelivery $orderRepository->buscarPorEstado($user,[4]);
  118.             $ordersCompleted $orderRepository->buscarPorEstado($user,[5]);
  119.             $ordersRejected $orderRepository->buscarPorEstado($user,[6]);
  120.             $libraries $libraryRepository->buscarTodos($user);
  121.             $suppliers $supplierRepository->buscarTodos($user);
  122.             $users $userRepository->buscarUsuarios($user);
  123.             $denied 0;
  124.             $generatedParts $orderRepository->searchGeneratedParts($user);
  125.             $partsByTech $partRepository->findPartsByTech($user);
  126.             if($roleUser == 'ROLE_SUPPLIER' || $roleUser == 'ROLE_SUPPLIER_CHIEF'){
  127.                 $denied 1;
  128.             }elseif($roleUser == 'ROLE_USER'){
  129.                 $denied 2;
  130.             }
  131.             $oIni count($ordersRequested->execute());
  132.             $oPen count($ordersPending->execute());
  133.             $oFor count($ordersForthcoming->execute());
  134.             $oDel count($ordersDelivery->execute());
  135.             $oCom count($ordersCompleted->execute());
  136.             $oRej count($ordersRejected->execute());
  137.             $ordersChart = [
  138.                 $this->translator->trans('Iniciadas') => $oIni,
  139.                 $this->translator->trans('Presupuestadas') => $oPen,
  140.                 $this->translator->trans('En preparación') => $oFor,
  141.                 $this->translator->trans('En entrega') => $oDel,
  142.                 $this->translator->trans('Completadas') => $oCom,
  143.                 $this->translator->trans('Rechazadas') => $oRej
  144.             ];
  145.             $ordersActive $oIni $oPen $oFor $oDel;
  146.             $ordersByTechChart $orderRepository->findActiveOrdersByTech($user);
  147.             $ordersBySupplierChart $orderRepository->findActiveOrdersBySupplier($user);
  148.             $corporateColor $company->getCorporateColor() ? $company->getCorporateColor() : '#DD9933';
  149.             $historicalPartsLoaded $partRepository->historicalPartsLoaded($user$corporateColor);
  150.             $historicalOrdersLoaded $orderRepository->historicalOrdersLoaded($user$corporateColor);
  151.             return $this->render('index/index.html.twig', [
  152.                 'parts' => count($parts->execute()),
  153.                 'libraries' => count($libraries->execute()),
  154.                 'suppliers' => count($suppliers->execute()),
  155.                 'users' => count($users->execute()),
  156.                 'user' => $this->getUser(),
  157.                 'denied' => $denied,
  158.                 'role' => $roleUser,
  159.                 'generatedParts' => $generatedParts,
  160.                 'ordersActive' => $ordersActive,
  161.                 'partsByTechChart' => json_encode($partsByTech),
  162.                 'ordersChart' => json_encode($ordersChart),
  163.                 'ordersByTechChart' => json_encode($ordersByTechChart),
  164.                 'ordersBySupplierChart' => json_encode($ordersBySupplierChart),
  165.                 'historicalPartsLoadedChart' => json_encode($historicalPartsLoaded),
  166.                 'historicalOrdersLoadedChart' => json_encode($historicalOrdersLoaded),
  167.                 'controller_name' => 'IndexController',
  168.                 'corporateColor' => $company->getCorporateColor() ? $this->util->fromHexToRgb($company->getCorporateColor()) : '241,139,55',
  169.                 'navbarTitle' => $this->translator->trans("Tablero")
  170.             ]);
  171.         } else
  172.         {
  173.             return $this->redirectToRoute('app_login');
  174.         }
  175.     }
  176.     /**
  177.      * @Route({"en": "/notifications",
  178.      *         "es": "/notificaciones"}, name="app_notifications", methods={"GET", "POST"})
  179.      */
  180.     public function notifications(Request $requestNotificationsRepository $notificationsRepository): Response
  181.     {
  182.         $result = ['error'=>false,'msg'=>'','data'=>['nsids'=>[],'html'=>'']];
  183.         $user $this->getUser();
  184.         $company $user->getCompany();
  185.         $roleUser $user->getRole();
  186.         $trans $this->translator;
  187.         $from $request->request->get('from');
  188.         $size $request->request->get('size');
  189.         $section $request->request->get('section');
  190.         $action $request->request->get('action');
  191.         if($company->getType()==&& in_array($roleUser,['ROLE_SUPPLIER','ROLE_SUPPLIER_CHIEF'])){
  192.             $notifications $notificationsRepository->findInternalSupplier($company$user->getSupplier(), $from$size);
  193.         }
  194.         elseif($roleUser=='ROLE_CLIENT' && $user->getCompanyClient()){
  195.             $notifications $notificationsRepository->findClient($company$user->getCompanyClient());
  196.         }
  197.         else{
  198.             $notifications $this->em->getRepository(Notifications::class)->findBy(['company' => $company], ['id' => 'DESC'], $size$from);
  199.         }
  200.         //process data
  201.         $messages = [];
  202.         foreach($notifications as $k=>$v){
  203.             if($v->getMessageAux()){
  204.                 $message $trans->trans($v->getMessage(),['{aux}'=>$v->getMessageAux()]);
  205.             }
  206.             else{
  207.                 $message $trans->trans($v->getMessage());
  208.             }
  209.             $name $v->getName();
  210.             $ref $v->getReference();
  211.             $pName $v->getPathName();
  212.             $pParams $v->getPathParameters();
  213.             if($name){
  214.                 $message.='. '.$name;
  215.             }
  216.             if($ref){
  217.                 $message.='. Ref.:'.$ref;
  218.             }
  219.             if($pName){
  220.                 $params = [];
  221.                 if($pParams){
  222.                     try {
  223.                         foreach(explode(',',$pParams) as $p){
  224.                             $pArray explode(':',$p);
  225.                             if(count($pArray)===2){
  226.                                 $params[$pArray[0]]=$pArray[1];
  227.                             }
  228.                         }
  229.                     } catch (\Exception $e) {}
  230.                 }
  231.                 $message'<a href="'.$this->generateUrl($pName$paramsUrlGeneratorInterface::ABSOLUTE_URL).'">'.$message.'</a>';
  232.             }
  233.             $messages[$v->getId()]=$message;
  234.         }
  235.         $notificationsNotSeen = [];
  236.         $nsids = [];
  237.         foreach($notifications as $n){
  238.             $nnss $n->getNotificationsSeens();
  239.             if(count($nnss)==0){
  240.                 $notificationsNotSeen[] = $n;
  241.                 $nsids[] = $n->getId();
  242.             }
  243.             else{
  244.                 $seen false;
  245.                 foreach($nnss as $ns){
  246.                     if($ns->getUser()->getId()==$user->getId()){
  247.                         $seen true;
  248.                         break;
  249.                     }
  250.                 }
  251.                 if(!$seen){
  252.                     $notificationsNotSeen[] = $n;
  253.                     $nsids[] = $n->getId();
  254.                 }
  255.             }
  256.         }
  257.         if($action==&& $notificationsNotSeen){
  258.             $now = new \DateTime();
  259.             foreach($notificationsNotSeen as $n){
  260.                 $ns = new NotificationsSeen();
  261.                 $ns->setNotifications($n);
  262.                 $ns->setUser($user);
  263.                 $ns->setSeenAt($now);
  264.                 $this->em->persist($ns);
  265.                 $this->em->flush();
  266.             }
  267.         }
  268.         $template $section == 'menu' 'common/notifications.html.twig' 'index/notifications.html.twig';
  269.         $result['data'] = [
  270.             'total'=> count($notifications),
  271.             'nsids'=>$nsids,
  272.             'html'=>$this->renderView($template, ['notifications' => $notifications'messages' => $messages,'user' => $user])
  273.         ];
  274.         return new JsonResponse($result);
  275.     }
  276.     /**
  277.      * @Route({"en": "/landing",
  278.      *         "es": "/info"}, name="app_landing")
  279.      */
  280.     public function landing(Request $request): Response
  281.     {
  282.         $qb1 $this->em->createQueryBuilder();
  283.         $qb2 $this->em->createQueryBuilder();
  284.         $supplierLicenses $qb1->select('l')->from(License::class,'l')->where('l.type IN (1,2)')->getQuery()->getResult();
  285.         $clientLicenses $qb2->select('l')->from(License::class,'l')->where('l.type IN (3,4,7)')->getQuery()->getResult();
  286.         if($request->query->get('error')==1){
  287.             $this->addFlash('error'$this->translator->trans('Error inesperado'));
  288.             return $this->redirectToRoute('app_landing');
  289.         }
  290.         if($request->getMethod()=='POST'){
  291.             $type $request->request->get("type");
  292.             $name $request->request->get("name");
  293.             $surnames $request->request->get("surnames");
  294.             $email $request->request->get("email");
  295.             $telephone $request->request->get("telephone");
  296.             $comment $request->request->get("comment");
  297.             if($type=='contact'){
  298.                 $title 'Contacto';
  299.                 $subject $this->translator->trans('Contacto');
  300.                 $flashMsg $this->translator->trans('Email enviado correctamente');
  301.             }
  302.             elseif($type=='demo'){
  303.                 $title 'Solicitud de Demo';
  304.                 $subject $this->translator->trans('Demo');
  305.                 $flashMsg $this->translator->trans('Solicitud de demo enviada correctamente');
  306.             }
  307.             elseif($type=='0'){
  308.                 $title 'Solicitud de contratación de licencia ENTERPRISE';
  309.                 $subject $this->translator->trans('Solicitud licencia');
  310.                 $flashMsg $this->translator->trans('Solicitud de contratación de licencia enviada correctamente');
  311.             }
  312.             else{
  313.                 $license $this->em->getRepository(License::class)->findOneBy(['type'=>$type]);
  314.                 if(empty($license)){
  315.                     $this->addFlash('error'$this->translator->trans('Error inesperado'));
  316.                     return $this->redirectToRoute('app_landing');
  317.                 }
  318.                 $title 'Solicitud de contratación de licencia '.$license->getName();
  319.                 $subject $this->translator->trans('Solicitud licencia');
  320.                 $flashMsg $this->translator->trans('Solicitud de contratación de licencia enviada correctamente');
  321.             }
  322.             $msg = <<<EOT
  323.                 <div>
  324.                     <p>$title</p>
  325.                     <ul>
  326.                         <li>
  327.                             Nombre y apellidos : $name $surnames
  328.                         </li>
  329.                         <li>
  330.                             Email : $email
  331.                         </li>
  332.                         <li>
  333.                             Teléfono : $telephone
  334.                         </li>
  335.                     </ul>
  336.                     <p>Comentario : <br> $comment</p>
  337.                 </div>
  338.             EOT;
  339.             $admins $this->em->getRepository(User::class)->findBy(['role'=>'ROLE_ADMIN']);
  340.             $adminsEmail = [];
  341.             foreach($admins as $admin){
  342.                 $adminsEmail[] = $admin->getEmail();
  343.             }
  344.             $to array_shift($adminsEmail);
  345.             $context = ['msg' => $msg];
  346.             $this->util->email($to$subject$context'common/email.html.twig'null$adminsEmail);
  347.             $this->addFlash('success'$flashMsg);
  348.             return $this->redirectToRoute('app_landing');
  349.         }
  350.         return $this->render('index/landing.html.twig', [
  351.             'locale'=>$this->translator->getLocale(),
  352.             'clientLicenses'=>$clientLicenses,
  353.             'supplierLicenses'=>$supplierLicenses,
  354.         ]);
  355.     }
  356.     /**
  357.      * @Route("/phpinfo", name="app_phpinfo")
  358.      */
  359.     public function app_phpinfo()
  360.     {
  361.         if($this->getParameter('kernel.environment')=='dev'){
  362.             phpinfo();
  363.             exit;
  364.         }
  365.         else{
  366.             return $this->redirectToRoute('app_index');
  367.         }
  368.     }
  369. }