<?php
namespace App\Controller;
use App\Entity\Notifications;
use App\Entity\NotificationsSeen;
use App\Form\PartSearchType;
use App\Repository\CompanyRepository;
use App\Repository\LibraryRepository;
use App\Repository\NotificationsRepository;
use App\Repository\OrderRepository;
use App\Repository\PartRepository;
use App\Repository\SupplierRepository;
use App\Repository\CompanySupplierRepository;
use App\Repository\UserRepository;
use App\Entity\License;
use App\Entity\User;
use App\Service\UtilService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Doctrine\Persistence\ManagerRegistry;
use Zxing\QrReader;
use Symfony\Component\Filesystem\Filesystem;
class IndexController extends AbstractController
{
private $translator;
private $util;
private $em;
private $projectDir;
private $url;
/**
* IndexController constructor.
*/
public function __construct(
TranslatorInterface $translator,
UtilService $utilService,
ManagerRegistry $doctrine,
string $projectDir,
string $addvance3dUrl)
{
$this->translator = $translator;
$this->em = $doctrine->getManager();
$this->util = $utilService;
$this->projectDir = $projectDir;
$this->url = $addvance3dUrl;
}
/**
* @Route("/", name="app_home")
*/
public function home(Security $security): Response
{
$user =$security->getUser();
if ($user)
{
return $this->redirectToRoute('app_index');
} else
{
return $this->redirectToRoute('app_login');
}
}
/**
* @Route({"en": "/index",
* "es": "/inicio"}, name="app_index")
*/
public function index(Security $security, Request $request, PartRepository $partRepository, OrderRepository $orderRepository, LibraryRepository $libraryRepository, SupplierRepository $supplierRepository, UserRepository $userRepository, NotificationsRepository $notificationsRepository): Response
{
$user = $security->getUser();
$company = $this->getUser()->getCompany();
$roleUser = $user->getRole();
if ($user)
{
if($request->isMethod('POST')){
if(!empty($request->request->get('qr_option_webcam_snapshot'))){
$fs = new Filesystem();
$ds = DIRECTORY_SEPARATOR;
$filepath = $this->projectDir. $ds . 'public' . $ds . 'tmp' . $ds . 'snapshot_' . uniqid() . '.png';
$snapshot = base64_decode($request->request->get('qr_option_webcam_snapshot'));
$fs->dumpFile($filepath, $snapshot);
$qrcode = new QrReader($filepath);
$url = $qrcode->text();
$url_ = preg_replace("(^https?://)", "", $url);
$url_addvance = preg_replace("(^https?://)", "", $this->url );
$fs->remove(($filepath));
if(empty($url)){
$this->addFlash('error', $this->translator->trans('No se ha podido leer el QR.'));
return $this->redirect($request->headers->get('referer'));
}
elseif(stripos($url_,$url_addvance)===0){
return $this->redirect($url);
}
else{
$this->addFlash('error', $this->translator->trans('La URL no es correcta.'));
return $this->redirect($request->headers->get('referer'));
}
}
elseif(!empty($request->request->get('qr_option_lector_input'))){
$url = $request->request->get('qr_option_lector_input');
$url_ = preg_replace("(^https?://)", "", $url);
$url_addvance = preg_replace("(^https?://)", "", $this->url );
if(stripos($url_,$url_addvance)===0){
return $this->redirect($url);
}
else{
$this->addFlash('error', $this->translator->trans('La URL no es correcta.'));
return $this->redirect($request->headers->get('referer'));
}
}
}
$parts = $partRepository->buscarTodos($user);
$ordersRequested = $orderRepository->buscarPorEstado($user,[0]);
$ordersPending = $orderRepository->buscarPorEstado($user,[1,2]);
$ordersForthcoming = $orderRepository->buscarPorEstado($user,[3]);
$ordersDelivery = $orderRepository->buscarPorEstado($user,[4]);
$ordersCompleted = $orderRepository->buscarPorEstado($user,[5]);
$ordersRejected = $orderRepository->buscarPorEstado($user,[6]);
$libraries = $libraryRepository->buscarTodos($user);
$suppliers = $supplierRepository->buscarTodos($user);
$users = $userRepository->buscarUsuarios($user);
$denied = 0;
$generatedParts = $orderRepository->searchGeneratedParts($user);
$partsByTech = $partRepository->findPartsByTech($user);
if($roleUser == 'ROLE_SUPPLIER' || $roleUser == 'ROLE_SUPPLIER_CHIEF'){
$denied = 1;
}elseif($roleUser == 'ROLE_USER'){
$denied = 2;
}
$oIni = count($ordersRequested->execute());
$oPen = count($ordersPending->execute());
$oFor = count($ordersForthcoming->execute());
$oDel = count($ordersDelivery->execute());
$oCom = count($ordersCompleted->execute());
$oRej = count($ordersRejected->execute());
$ordersChart = [
$this->translator->trans('Iniciadas') => $oIni,
$this->translator->trans('Presupuestadas') => $oPen,
$this->translator->trans('En preparación') => $oFor,
$this->translator->trans('En entrega') => $oDel,
$this->translator->trans('Completadas') => $oCom,
$this->translator->trans('Rechazadas') => $oRej
];
$ordersActive = $oIni + $oPen + $oFor + $oDel;
$ordersByTechChart = $orderRepository->findActiveOrdersByTech($user);
$ordersBySupplierChart = $orderRepository->findActiveOrdersBySupplier($user);
$corporateColor = $company->getCorporateColor() ? $company->getCorporateColor() : '#DD9933';
$historicalPartsLoaded = $partRepository->historicalPartsLoaded($user, $corporateColor);
$historicalOrdersLoaded = $orderRepository->historicalOrdersLoaded($user, $corporateColor);
return $this->render('index/index.html.twig', [
'parts' => count($parts->execute()),
'libraries' => count($libraries->execute()),
'suppliers' => count($suppliers->execute()),
'users' => count($users->execute()),
'user' => $this->getUser(),
'denied' => $denied,
'role' => $roleUser,
'generatedParts' => $generatedParts,
'ordersActive' => $ordersActive,
'partsByTechChart' => json_encode($partsByTech),
'ordersChart' => json_encode($ordersChart),
'ordersByTechChart' => json_encode($ordersByTechChart),
'ordersBySupplierChart' => json_encode($ordersBySupplierChart),
'historicalPartsLoadedChart' => json_encode($historicalPartsLoaded),
'historicalOrdersLoadedChart' => json_encode($historicalOrdersLoaded),
'controller_name' => 'IndexController',
'corporateColor' => $company->getCorporateColor() ? $this->util->fromHexToRgb($company->getCorporateColor()) : '241,139,55',
'navbarTitle' => $this->translator->trans("Tablero")
]);
} else
{
return $this->redirectToRoute('app_login');
}
}
/**
* @Route({"en": "/notifications",
* "es": "/notificaciones"}, name="app_notifications", methods={"GET", "POST"})
*/
public function notifications(Request $request, NotificationsRepository $notificationsRepository): Response
{
$result = ['error'=>false,'msg'=>'','data'=>['nsids'=>[],'html'=>'']];
$user = $this->getUser();
$company = $user->getCompany();
$roleUser = $user->getRole();
$trans = $this->translator;
$from = $request->request->get('from');
$size = $request->request->get('size');
$section = $request->request->get('section');
$action = $request->request->get('action');
if($company->getType()==1 && in_array($roleUser,['ROLE_SUPPLIER','ROLE_SUPPLIER_CHIEF'])){
$notifications = $notificationsRepository->findInternalSupplier($company, $user->getSupplier(), $from, $size);
}
elseif($roleUser=='ROLE_CLIENT' && $user->getCompanyClient()){
$notifications = $notificationsRepository->findClient($company, $user->getCompanyClient());
}
else{
$notifications = $this->em->getRepository(Notifications::class)->findBy(['company' => $company], ['id' => 'DESC'], $size, $from);
}
//process data
$messages = [];
foreach($notifications as $k=>$v){
if($v->getMessageAux()){
$message = $trans->trans($v->getMessage(),['{aux}'=>$v->getMessageAux()]);
}
else{
$message = $trans->trans($v->getMessage());
}
$name = $v->getName();
$ref = $v->getReference();
$pName = $v->getPathName();
$pParams = $v->getPathParameters();
if($name){
$message.='. '.$name;
}
if($ref){
$message.='. Ref.:'.$ref;
}
if($pName){
$params = [];
if($pParams){
try {
foreach(explode(',',$pParams) as $p){
$pArray = explode(':',$p);
if(count($pArray)===2){
$params[$pArray[0]]=$pArray[1];
}
}
} catch (\Exception $e) {}
}
$message= '<a href="'.$this->generateUrl($pName, $params, UrlGeneratorInterface::ABSOLUTE_URL).'">'.$message.'</a>';
}
$messages[$v->getId()]=$message;
}
$notificationsNotSeen = [];
$nsids = [];
foreach($notifications as $n){
$nnss = $n->getNotificationsSeens();
if(count($nnss)==0){
$notificationsNotSeen[] = $n;
$nsids[] = $n->getId();
}
else{
$seen = false;
foreach($nnss as $ns){
if($ns->getUser()->getId()==$user->getId()){
$seen = true;
break;
}
}
if(!$seen){
$notificationsNotSeen[] = $n;
$nsids[] = $n->getId();
}
}
}
if($action==2 && $notificationsNotSeen){
$now = new \DateTime();
foreach($notificationsNotSeen as $n){
$ns = new NotificationsSeen();
$ns->setNotifications($n);
$ns->setUser($user);
$ns->setSeenAt($now);
$this->em->persist($ns);
$this->em->flush();
}
}
$template = $section == 'menu' ? 'common/notifications.html.twig' : 'index/notifications.html.twig';
$result['data'] = [
'total'=> count($notifications),
'nsids'=>$nsids,
'html'=>$this->renderView($template, ['notifications' => $notifications, 'messages' => $messages,'user' => $user])
];
return new JsonResponse($result);
}
/**
* @Route({"en": "/landing",
* "es": "/info"}, name="app_landing")
*/
public function landing(Request $request): Response
{
$qb1 = $this->em->createQueryBuilder();
$qb2 = $this->em->createQueryBuilder();
$supplierLicenses = $qb1->select('l')->from(License::class,'l')->where('l.type IN (1,2)')->getQuery()->getResult();
$clientLicenses = $qb2->select('l')->from(License::class,'l')->where('l.type IN (3,4,7)')->getQuery()->getResult();
if($request->query->get('error')==1){
$this->addFlash('error', $this->translator->trans('Error inesperado'));
return $this->redirectToRoute('app_landing');
}
if($request->getMethod()=='POST'){
$type = $request->request->get("type");
$name = $request->request->get("name");
$surnames = $request->request->get("surnames");
$email = $request->request->get("email");
$telephone = $request->request->get("telephone");
$comment = $request->request->get("comment");
if($type=='contact'){
$title = 'Contacto';
$subject = $this->translator->trans('Contacto');
$flashMsg = $this->translator->trans('Email enviado correctamente');
}
elseif($type=='demo'){
$title = 'Solicitud de Demo';
$subject = $this->translator->trans('Demo');
$flashMsg = $this->translator->trans('Solicitud de demo enviada correctamente');
}
elseif($type=='0'){
$title = 'Solicitud de contratación de licencia ENTERPRISE';
$subject = $this->translator->trans('Solicitud licencia');
$flashMsg = $this->translator->trans('Solicitud de contratación de licencia enviada correctamente');
}
else{
$license = $this->em->getRepository(License::class)->findOneBy(['type'=>$type]);
if(empty($license)){
$this->addFlash('error', $this->translator->trans('Error inesperado'));
return $this->redirectToRoute('app_landing');
}
$title = 'Solicitud de contratación de licencia '.$license->getName();
$subject = $this->translator->trans('Solicitud licencia');
$flashMsg = $this->translator->trans('Solicitud de contratación de licencia enviada correctamente');
}
$msg = <<<EOT
<div>
<p>$title</p>
<ul>
<li>
Nombre y apellidos : $name $surnames
</li>
<li>
Email : $email
</li>
<li>
Teléfono : $telephone
</li>
</ul>
<p>Comentario : <br> $comment</p>
</div>
EOT;
$admins = $this->em->getRepository(User::class)->findBy(['role'=>'ROLE_ADMIN']);
$adminsEmail = [];
foreach($admins as $admin){
$adminsEmail[] = $admin->getEmail();
}
$to = array_shift($adminsEmail);
$context = ['msg' => $msg];
$this->util->email($to, $subject, $context, 'common/email.html.twig', null, $adminsEmail);
$this->addFlash('success', $flashMsg);
return $this->redirectToRoute('app_landing');
}
return $this->render('index/landing.html.twig', [
'locale'=>$this->translator->getLocale(),
'clientLicenses'=>$clientLicenses,
'supplierLicenses'=>$supplierLicenses,
]);
}
/**
* @Route("/phpinfo", name="app_phpinfo")
*/
public function app_phpinfo()
{
if($this->getParameter('kernel.environment')=='dev'){
phpinfo();
exit;
}
else{
return $this->redirectToRoute('app_index');
}
}
}