src/Controller/IndexController.php line 208

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.                     
  84.                     $qrcode = new QrReader($filepath);
  85.                     $url $qrcode->text();
  86.                     $url_ preg_replace("(^https?://)"""$url);
  87.                     $url_addvance preg_replace("(^https?://)"""$this->url );
  88.                     $fs->remove(($filepath));                    
  89.                     if(empty($url)){
  90.                         $this->addFlash('error'$this->translator->trans('No se ha podido leer el QR.'));
  91.                         return $this->redirect($request->headers->get('referer'));
  92.                     }
  93.                     elseif(stripos($url_,$url_addvance)===0){
  94.                         return $this->redirect($url);
  95.                     }
  96.                     else{
  97.                         $this->addFlash('error'$this->translator->trans('La URL no es correcta.'));
  98.                         return $this->redirect($request->headers->get('referer'));                    
  99.                     }
  100.                 }
  101.                 elseif(!empty($request->request->get('qr_option_lector_input'))){
  102.                     $url $request->request->get('qr_option_lector_input');
  103.                     $url_ preg_replace("(^https?://)"""$url);
  104.                     $url_addvance preg_replace("(^https?://)"""$this->url );
  105.                    
  106.                     if(stripos($url_,$url_addvance)===0){
  107.                         return $this->redirect($url);
  108.                     }
  109.                     else{
  110.                         $this->addFlash('error'$this->translator->trans('La URL no es correcta.'));
  111.                         return $this->redirect($request->headers->get('referer'));                    
  112.                     }
  113.                 }
  114.             }            
  115.             $parts $partRepository->buscarTodos($user);
  116.             $ordersRequested $orderRepository->buscarPorEstado($user,[0]);
  117.             $ordersPending =   $orderRepository->buscarPorEstado($user,[1,2]);
  118.             $ordersForthcoming $orderRepository->buscarPorEstado($user,[3]);
  119.             $ordersDelivery $orderRepository->buscarPorEstado($user,[4]);
  120.             $ordersCompleted $orderRepository->buscarPorEstado($user,[5]);
  121.             $ordersRejected $orderRepository->buscarPorEstado($user,[6]);
  122.                         
  123.             $libraries $libraryRepository->buscarTodos($user);
  124.             $suppliers $supplierRepository->buscarTodos($user);
  125.             $users $userRepository->buscarUsuarios($user);
  126.             $denied 0;            
  127.             $generatedParts $orderRepository->searchGeneratedParts($user);
  128.             $partsByTech $partRepository->findPartsByTech($user);
  129.             if($roleUser == 'ROLE_SUPPLIER' || $roleUser == 'ROLE_SUPPLIER_CHIEF'){
  130.                 $denied 1;
  131.             }elseif($roleUser == 'ROLE_USER'){
  132.                 $denied 2;
  133.             }
  134.             $oIni count($ordersRequested->execute());
  135.             $oPen count($ordersPending->execute());
  136.             $oFor count($ordersForthcoming->execute());
  137.             $oDel count($ordersDelivery->execute());
  138.             $oCom count($ordersCompleted->execute());
  139.             $oRej count($ordersRejected->execute());
  140.             $ordersChart = [
  141.                 $this->translator->trans('Iniciadas') => $oIni,
  142.                 $this->translator->trans('Presupuestadas') => $oPen,
  143.                 $this->translator->trans('En preparación') => $oFor,
  144.                 $this->translator->trans('En entrega') => $oDel,
  145.                 $this->translator->trans('Completadas') => $oCom,
  146.                 $this->translator->trans('Rechazadas') => $oRej
  147.             ];
  148.             $ordersActive $oIni $oPen $oFor $oDel;
  149.             $ordersByTechChart $orderRepository->findActiveOrdersByTech($user);
  150.             $ordersBySupplierChart $orderRepository->findActiveOrdersBySupplier($user);
  151.             $corporateColor $company->getCorporateColor() ? $company->getCorporateColor() : '#DD9933';
  152.             $historicalPartsLoaded $partRepository->historicalPartsLoaded($user$corporateColor);
  153.             $historicalOrdersLoaded $orderRepository->historicalOrdersLoaded($user$corporateColor);
  154.             return $this->render('index/index.html.twig', [
  155.                 'parts' => count($parts->execute()),
  156.                 'libraries' => count($libraries->execute()),
  157.                 'suppliers' => count($suppliers->execute()),
  158.                 'users' => count($users->execute()),
  159.                 'user' => $this->getUser(),
  160.                 'denied' => $denied,
  161.                 'role' => $roleUser,
  162.                 'generatedParts' => $generatedParts,
  163.                 'ordersActive' => $ordersActive,
  164.                 'partsByTechChart' => json_encode($partsByTech),
  165.                 'ordersChart' => json_encode($ordersChart),
  166.                 'ordersByTechChart' => json_encode($ordersByTechChart),
  167.                 'ordersBySupplierChart' => json_encode($ordersBySupplierChart),
  168.                 'historicalPartsLoadedChart' => json_encode($historicalPartsLoaded),
  169.                 'historicalOrdersLoadedChart' => json_encode($historicalOrdersLoaded),
  170.                 'controller_name' => 'IndexController',
  171.                 'corporateColor' => $company->getCorporateColor() ? $this->util->fromHexToRgb($company->getCorporateColor()) : '241,139,55',
  172.                 'navbarTitle' => $this->translator->trans("Tablero")
  173.             ]);
  174.         } else 
  175.         {
  176.             return $this->redirectToRoute('app_login');
  177.         }
  178.     }
  179.     /**
  180.      * @Route({"en": "/notifications",
  181.      *         "es": "/notificaciones"}, name="app_notifications", methods={"GET", "POST"})
  182.      */
  183.     public function notifications(Request $requestNotificationsRepository $notificationsRepository): Response
  184.     {
  185.         $result = ['error'=>false,'msg'=>'','data'=>['nsids'=>[],'html'=>'']];
  186.         $user $this->getUser();
  187.         $company $user->getCompany();
  188.         $roleUser $user->getRole();
  189.         $trans $this->translator;
  190.         $from $request->request->get('from');
  191.         $size $request->request->get('size');
  192.         $section $request->request->get('section');
  193.         $action $request->request->get('action');
  194.         if($company->getType()==&& in_array($roleUser,['ROLE_SUPPLIER','ROLE_SUPPLIER_CHIEF'])){
  195.             $notifications $notificationsRepository->findInternalSupplier($company$user->getSupplier(), $from$size);
  196.         }
  197.         elseif($roleUser=='ROLE_CLIENT' && $user->getCompanyClient()){
  198.             $notifications $notificationsRepository->findClient($company$user->getCompanyClient());
  199.         }
  200.         else{
  201.             $notifications $this->em->getRepository(Notifications::class)->findBy(['company' => $company], ['id' => 'DESC'], $size$from);
  202.         }
  203.         //process data
  204.         $messages = [];
  205.         foreach($notifications as $k=>$v){
  206.             if($v->getMessageAux()){
  207.                 $message $trans->trans($v->getMessage(),['{aux}'=>$v->getMessageAux()]);
  208.             }
  209.             else{
  210.                 $message $trans->trans($v->getMessage());
  211.             }
  212.             
  213.             $name $v->getName();
  214.             $ref $v->getReference();
  215.             $pName $v->getPathName();
  216.             $pParams $v->getPathParameters();
  217.             if($name){
  218.                 $message.='. '.$name;
  219.             }
  220.             if($ref){
  221.                 $message.='. Ref.:'.$ref;
  222.             }
  223.            
  224.             if($pName){
  225.                 $params = [];
  226.                 if($pParams){
  227.                     try {
  228.                         foreach(explode(',',$pParams) as $p){
  229.                             $pArray explode(':',$p);
  230.                             if(count($pArray)===2){
  231.                                 $params[$pArray[0]]=$pArray[1];
  232.                             }
  233.                         }
  234.                     } catch (\Exception $e) {}                    
  235.                 }
  236.                 $message'<a href="'.$this->generateUrl($pName$paramsUrlGeneratorInterface::ABSOLUTE_URL).'">'.$message.'</a>';
  237.             }
  238.             $messages[$v->getId()]=$message;
  239.         }
  240.         $notificationsNotSeen = [];
  241.         $nsids = [];
  242.         foreach($notifications as $n){
  243.             $nnss $n->getNotificationsSeens();            
  244.             if(count($nnss)==0){
  245.                 $notificationsNotSeen[] = $n;
  246.                 $nsids[] = $n->getId();
  247.             }
  248.             else{
  249.                 $seen false;
  250.                 foreach($nnss as $ns){
  251.                     if($ns->getUser()->getId()==$user->getId()){
  252.                         $seen true;
  253.                         break;
  254.                     }
  255.                 }
  256.                 if(!$seen){
  257.                     $notificationsNotSeen[] = $n;
  258.                     $nsids[] = $n->getId();
  259.                 }
  260.             }
  261.         }        
  262.         if($action==&& $notificationsNotSeen){
  263.             $now = new \DateTime();
  264.             foreach($notificationsNotSeen as $n){
  265.                 $ns = new NotificationsSeen();
  266.                 $ns->setNotifications($n);
  267.                 $ns->setUser($user);
  268.                 $ns->setSeenAt($now);   
  269.                 $this->em->persist($ns);
  270.                 $this->em->flush();
  271.             }
  272.         }
  273.         $template $section == 'menu' 'common/notifications.html.twig' 'index/notifications.html.twig';
  274.         $result['data'] = [
  275.             'total'=> count($notifications),
  276.             'nsids'=>$nsids,
  277.             'html'=>$this->renderView($template, ['notifications' => $notifications'messages' => $messages,'user' => $user])
  278.         ];
  279.         return new JsonResponse($result);
  280.     }
  281.     /**
  282.      * @Route({"en": "/landing",
  283.      *         "es": "/info"}, name="app_landing")
  284.      */
  285.     public function landing(Request $request): Response
  286.     {
  287.         $qb1 $this->em->createQueryBuilder();
  288.         $qb2 $this->em->createQueryBuilder();
  289.         
  290.         $supplierLicenses $qb1->select('l')->from(License::class,'l')->where('l.type IN (1,2)')->getQuery()->getResult();
  291.         $clientLicenses $qb2->select('l')->from(License::class,'l')->where('l.type IN (3,4,7)')->getQuery()->getResult();
  292.         if($request->query->get('error')==1){
  293.             $this->addFlash('error'$this->translator->trans('Error inesperado'));
  294.             return $this->redirectToRoute('app_landing');
  295.         }
  296.         if($request->getMethod()=='POST'){            
  297.             $type $request->request->get("type");
  298.             $name $request->request->get("name");
  299.             $surnames $request->request->get("surnames");
  300.             $email $request->request->get("email");
  301.             $telephone $request->request->get("telephone");
  302.             $comment $request->request->get("comment");
  303.             if($type=='contact'){
  304.                 $title 'Contacto';
  305.                 $subject $this->translator->trans('Contacto');
  306.                 $flashMsg $this->translator->trans('Email enviado correctamente');
  307.             }
  308.             elseif($type=='demo'){
  309.                 $title 'Solicitud de Demo';
  310.                 $subject $this->translator->trans('Demo');
  311.                 $flashMsg $this->translator->trans('Solicitud de demo enviada correctamente');
  312.             }
  313.             elseif($type=='0'){
  314.                 $title 'Solicitud de contratación de licencia ENTERPRISE';
  315.                 $subject $this->translator->trans('Solicitud licencia');
  316.                 $flashMsg $this->translator->trans('Solicitud de contratación de licencia enviada correctamente');
  317.             }
  318.             else{
  319.                 $license $this->em->getRepository(License::class)->findOneBy(['type'=>$type]);
  320.                 if(empty($license)){
  321.                     $this->addFlash('error'$this->translator->trans('Error inesperado'));
  322.                     return $this->redirectToRoute('app_landing');
  323.                 }
  324.                 $title 'Solicitud de contratación de licencia '.$license->getName();
  325.                 $subject $this->translator->trans('Solicitud licencia');
  326.                 $flashMsg $this->translator->trans('Solicitud de contratación de licencia enviada correctamente');
  327.             }
  328.             
  329.             $msg = <<<EOT
  330.                 <div>
  331.                     <p>$title</p>
  332.                     <ul>
  333.                         <li>
  334.                             Nombre y apellidos : $name $surnames
  335.                         </li>
  336.                         <li>
  337.                             Email : $email
  338.                         </li>
  339.                         <li>
  340.                             Teléfono : $telephone
  341.                         </li>
  342.                     </ul>
  343.                     <p>Comentario : <br> $comment</p>
  344.                 </div>  
  345.             EOT;
  346.             $admins $this->em->getRepository(User::class)->findBy(['role'=>'ROLE_ADMIN']);
  347.             $adminsEmail = [];
  348.             foreach($admins as $admin){
  349.                 $adminsEmail[] = $admin->getEmail();
  350.             }
  351.             $to array_shift($adminsEmail);
  352.             $context = ['msg' => $msg];
  353.             $this->util->email($to$subject$context'common/email.html.twig'null$adminsEmail);
  354.             $this->addFlash('success'$flashMsg);
  355.             return $this->redirectToRoute('app_landing');
  356.         }
  357.         return $this->render('index/landing.html.twig', [
  358.             'locale'=>$this->translator->getLocale(),
  359.             'clientLicenses'=>$clientLicenses,
  360.             'supplierLicenses'=>$supplierLicenses,
  361.         ]);
  362.     }
  363.     /**
  364.      * @Route("/phpinfo", name="app_phpinfo")
  365.      */
  366.     public function app_phpinfo()
  367.     {
  368.         if($this->getParameter('kernel.environment')=='dev'){
  369.             phpinfo();
  370.             exit;
  371.         }
  372.         else{
  373.             return $this->redirectToRoute('app_index');
  374.         }
  375.     }
  376. }