src/Controller/FormulaController.php line 54

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Formula;
  4. use App\Entity\Models\FrontModels\ColorDTO;
  5. use App\Form\FormulaType;
  6. use App\Repository\FormulaRepository;
  7. use App\Service\ColorService;
  8. use App\Service\FormulaService;
  9. use FOS\RestBundle\Controller\AbstractFOSRestController;
  10. use JMS\Serializer\SerializationContext;
  11. use FOS\RestBundle\Controller\Annotations as Rest;
  12. use JMS\Serializer\SerializerInterface;
  13. use Monolog\Handler\StreamHandler;
  14. use Monolog\Logger;
  15. use Psr\Log\LoggerInterface;
  16. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use JMS\Serializer\SerializerBuilder;
  21. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  22. class FormulaController extends AbstractFOSRestController
  23. {
  24.     private $service;
  25.     private $serviceColor;
  26.     private $log ;
  27.     /**
  28.      * FormulaController constructor.
  29.      */
  30.     public function __construct(
  31.         FormulaService $service,
  32.         ColorService $serviceColor,
  33.         LoggerInterface $logger,
  34.         string $projectDir
  35.     )
  36.     {
  37.         $this->service      = $service;
  38.         $this ->serviceColor= $serviceColor;
  39.         $this->projectDir = $projectDir;
  40.         $this->log = $logger;
  41.     }
  42.     /**
  43.      * @Rest\Get("api/obtenerFormulas", name="obtener_formulas_convertidor")
  44.      * @param idColor
  45.      * Clave del color del que queremos extraer las fórmulas.
  46.      */
  47.     public function obtenerFormulas(Request $request)
  48.     {
  49.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  50.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  51.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  52.             )
  53.         )->build();
  54.         $idColor = $request->get('idColor');
  55.         $idTipo  = $request->get('tipo');
  56.         $plomo  = $request->get('plomo');
  57.         $oficial  = $request->get('oficial');
  58.         $formulaId  = $request->get('formulaId');
  59.         $usr= $this->get('security.token_storage')->getToken()->getUser();
  60.         if (isset($idColor) && isset($idTipo) && isset($oficial) && $oficial != 'false' && $oficial != false) {
  61.             $data = $this->service->getAllByColor($idColor,$usr,$idTipo,$plomo);
  62.             $code =  Response::HTTP_OK;
  63.         } elseif (isset($oficial) && ($oficial == false || $oficial == 'false')) {
  64.             $data = $this->service->getAllByPrueba($formulaId,$usr,$idTipo,$plomo);
  65.             $code =  Response::HTTP_OK;
  66.         }else{
  67.             $data = ['error' => 'Faltan parámetros en el criterio de búsqueda'];
  68.             $code = Response::HTTP_FAILED_DEPENDENCY;
  69.         }
  70.         if($data)
  71.         {
  72.             $code = Response::HTTP_OK;
  73.         }else{
  74.             $data = [];
  75.         }
  76.         $serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula']);
  77.         $response =  new Response($serializer->serialize($data, "json",$serializacion),$code);
  78.         $response->headers->set('Content-Type', 'json');
  79.         $response->prepare($request);
  80.         return $response;
  81.     }
  82.     /**
  83.      * @Rest\Get("/formula", name="formula_index")
  84.      */
  85.     public function index(FormulaRepository $formulaRepository): Response
  86.     {
  87.         return $this->render('formula/index.html.twig', ['formulas' => $formulaRepository->findAll()]);
  88.     }
  89.    /**
  90.     * @Rest\Post("/api/formulasPersonalesUpdate", name="formulasPersonalesUpdate")
  91.     */
  92.     public function createFormulasPersonal(Request $request, SerializerInterface $serializer){
  93.         $usr = $this->get('security.token_storage')->getToken()->getUser();
  94.         if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
  95.             $requestObject= json_decode($request->getContent(), true);
  96.             if(isset($requestObject['color'],$requestObject['formula'])) {
  97.                 //Le añadimos los ids de cuenta y usuario, para reutilizar otros metodos
  98.                 $requestObject['color']['cuenta']['id'] = $usr->getId();
  99.                 $requestObject['color']['tipo'] = 2;
  100.                 $requestObject['formula']['cuenta']['id'] = $usr->getId();
  101.                 // $requestObject['formula']['userId'] = 128;
  102.                 //guardamos color si la formula es nueva y no se ha elegido sobreescribir
  103.                 if ($requestObject['formula']['overwritePF'] === false) {
  104.                     try{
  105.                         $color = $this->serviceColor->nuevoColor($requestObject['color']);
  106.                     }catch (\Exception $e){
  107.                         $response =  new Response('KO', Response::HTTP_CONFLICT);
  108.                         /*
  109.                         return [
  110.                             'code' => $e->getCode() ?: 999,
  111.                             'message' => $e->getMessage()?:'API Exception',
  112.                         ];
  113.                         */
  114.                         return $response;
  115.                     }
  116.                     if($color == null){
  117.                         $response =  new Response(Response::HTTP_CONFLICT,Response::HTTP_CONFLICT);
  118.                         return $response;
  119.                     }
  120.                 }
  121.                 //creamos o editamos la formula
  122.                 if ($requestObject['formula']['overwritePF'] === false) {
  123.                     $colorId = $color->getId();
  124.                 } else {
  125.                     $colorId = $requestObject['color']['id'];
  126.                 }
  127.                 $formulaId = $this->service->nuevaFormulaPersonal($requestObject['formula'], $colorId);
  128.                 // Si se está sobreescribiendo la formula, para devolver el mismo color, hay que buscarlo antes
  129.                 if ($requestObject['formula']['overwritePF'] === true) {
  130.                     $color = $this->serviceColor->findByIdPersonal($colorId);
  131.                 }
  132.                 $return = new ColorDTO();
  133.                 $return->setId($color->getId());
  134.                 $return->setCodigo($color->getCodigo());
  135.                 $return->setNombre($color->getNombre());
  136.                 $return->setPosicionCT('');
  137.                 $return->setCliente($color->getClienteFinal()->getNombre()); 
  138.                 $return->setTipo(2);
  139.                 $return->setDisponible(true);
  140.                 $return->setActivo(true);
  141.                 $return->setFormulaId($formulaId);
  142.                 $response =  new Response($serializer->serialize($return, 'json'),Response::HTTP_OK);
  143.                 return $response;
  144.             }else{
  145.                 $response =  new Response(Response::HTTP_BAD_REQUEST);
  146.                 return $response;
  147.             }
  148.         }else{
  149.             $response =  new Response(Response::HTTP_BAD_REQUEST);
  150.             return $response;
  151.         }
  152.     }
  153.     /*
  154.      *     ADMINISTRADOR
  155.      */
  156.     /**
  157.      * @Route("/api/admin/formulaObject", name="formulaById", methods="GET")
  158.      */
  159.     public function getFormulaOficial(Request $request){
  160.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  161.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  162.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  163.             )
  164.         )->build();
  165.         $response =  new Response(Response::HTTP_BAD_REQUEST);
  166.         if ($request->query->get('idFormula') != null && $request->query->get('idFormula') != "") {
  167.             $correcto = $this->service->findById($request->query->get('idFormula') );
  168.         }
  169.         if ($request->query->get('codigoFormula') != null && $request->query->get('codigoFormula') != "") {
  170.             $correcto = $this->service->findByCodigo($request->query->get('codigoFormula') );
  171.         }
  172.         $serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
  173.         $response =  new Response($serializer->serialize($correcto, 'json', $serializacion),Response::HTTP_OK);
  174.         // $response =  new Response($serializer->serialize($correcto, 'json', SerializationContext::create()->setGroups('listAdminFormula')),Response::HTTP_OK);
  175.         //$response =  new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
  176.         $response->headers->set('Content-Type', 'json'); //xml
  177.         $response->prepare($request);
  178.         return $response;
  179.     }
  180.     /**
  181.      * @Route("/api/admin/formulasOficiales", name="list_formulas_oficiales", methods="GET")
  182.      */
  183.     public function getFormulasOficiales(Request $request){
  184.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  185.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  186.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  187.             )
  188.         )->build();
  189.         $response =  new Response(Response::HTTP_BAD_REQUEST);
  190.         if ($request ->query ->get('idColor')!=null && $request ->query ->get('idColor')!="") {
  191.                 $correcto = $this ->serviceColor ->findById($request ->query ->get('idColor') );
  192.         }
  193.         $serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
  194.         $response =  new Response($serializer->serialize($correcto, 'json',$serializacion),Response::HTTP_OK);
  195.         //$response =  new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
  196.         $response->headers->set('Content-Type', 'json'); //xml
  197.         $response->prepare($request);
  198.         return $response;
  199.     }
  200.     /**
  201.      * @Route("/api/admin/formulasPrueba", name="formulaByPrueba", methods="GET")
  202.      */
  203.     public function getFormulasPrueba(Request $request){
  204.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  205.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  206.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  207.             )
  208.         )->build();
  209.         $response =  new Response(Response::HTTP_BAD_REQUEST);
  210.         $correcto = $this->service->getAllFormulasPrueba();
  211.         $serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
  212.         $response =  new Response($serializer->serialize($correcto, 'json', $serializacion),Response::HTTP_OK);
  213.         // $response =  new Response($serializer->serialize($correcto, 'json', SerializationContext::create()->setGroups('listAdminFormula')),Response::HTTP_OK);
  214.         //$response =  new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
  215.         $response->headers->set('Content-Type', 'json'); //xml
  216.         $response->prepare($request);
  217.         return $response;
  218.     }
  219.     /**
  220.      * @Route("/api/admin/formulasPersonales", name="list_getFormulasPersonales", methods="GET")
  221.      */
  222.     public function getFormulasPersonales(Request $request){
  223.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  224.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  225.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  226.             )
  227.         )->build();
  228.         if ($request ->query ->get('idColor')!=null && $request ->query ->get('idColor')!="") {
  229.             $correcto = $this ->serviceColor ->findByIdPersonal($request ->query ->get('idColor') );
  230.         }
  231.         $serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
  232.         $response =  new Response($serializer->serialize($correcto, 'json',$serializacion),Response::HTTP_OK);
  233.         //$response =  new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
  234.         $response->headers->set('Content-Type', 'json'); //xml
  235.         $response->prepare($request);
  236.         return $response;
  237.     }
  238.     /**
  239.      * @Rest\Post("/api/admin/formulasOficialesAssociate", name="AssociateFormulasOficiales")
  240.      */
  241.     public function asociarFormulasOficiales(Request $request){
  242.         $correcto = null;
  243.         $response =  new Response(Response::HTTP_BAD_REQUEST);
  244.         if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
  245.             $datos= json_decode($request->getContent(), true);
  246.             if (isset($datos['colorId']) && isset($datos['formulaId']) && !isset($datos['unlink'])) {
  247.                 //$correcto= null;
  248.                 $correcto = $this ->service ->asociarFormulaOficial($datos);
  249.             } else if (isset($datos['unlink']) ){
  250.                 //Tenemos unlink por lo que es una desasociacion
  251.                 $correcto = $this ->service ->desAsociarFormulaOficial($datos);
  252.             }
  253.         }
  254.         if($correcto != 0){
  255.             $response =  new Response(Response::HTTP_OK);
  256.         }else{
  257.             $response =  new Response(Response::HTTP_BAD_REQUEST);
  258.         }
  259.         $response->prepare($request);
  260.         return $response;
  261.     }
  262.     /**
  263.      * @Rest\Post("/api/admin/formulasOficialesUpate", name="CreateOrUpdateFormulasOficiales")
  264.      */
  265.     public function updateFormulasOficiales(Request $request){
  266.         $correcto = null;
  267.         $response =  new Response(Response::HTTP_BAD_REQUEST);
  268.         if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
  269.             $formula= json_decode($request->getContent(), true);
  270.             if(isset($formula['idColor']) && empty($formula['id'])){
  271.                 //$correcto= null;
  272.                 $correcto = $this ->service ->nuevaFormulaOficial($formula);
  273.             }else if(isset($formula['id']) ){
  274.                 //Tenemos Id por lo que es una actulizacion
  275.                 $correcto = $this ->service ->modificaFormulaOficial($formula);
  276.             }
  277.         }
  278.         if($correcto != null){
  279.             $response =  new Response(Response::HTTP_OK);
  280.         }else{
  281.             $response =  new Response(Response::HTTP_BAD_REQUEST);
  282.         }
  283.         $response->prepare($request);
  284.         return $response;
  285.     }
  286.     /**
  287.      * @Route("/api/admin/formulasPersonalesUpdate", name="updateFormulasPersonal_Admin", methods="POST")
  288.      */
  289.     public function updateFormulasPersonal(Request $request){
  290.         $usr = $this->get('security.token_storage')->getToken()->getUser();
  291.         if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
  292.             $requestObject= json_decode($request->getContent(), true);
  293.             if(isset($requestObject['idColor'],$requestObject['formula'])) {
  294.                 //Le añadimos los ids de usuario, para reutilizar otros metodos
  295.                 $requestObject['formula']['userId'] = $usr->getId();
  296.                 //guardamos formula
  297.                 $this->service->nuevaFormulaPersonal($requestObject['formula'],$requestObject['idColor']);
  298.                 $response =  new Response(Response::HTTP_OK);
  299.                 return $response;
  300.             }else{
  301.                 $response =  new Response(Response::HTTP_BAD_REQUEST);
  302.                 return $response;
  303.             }
  304.         }else{
  305.             $response =  new Response(Response::HTTP_BAD_REQUEST);
  306.             return $response;
  307.         }
  308.     }
  309.     /**
  310.      * @Route("/api/admin/obtenerFormulasExpertis", name="obtenerFormulas_Expertis", methods="GET")
  311.      */
  312.     public function obtenerFormulasParaExpertis(Request $request) {
  313.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  314.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  315.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  316.             )
  317.         )->build();
  318.         $usr = $this->get('security.token_storage')->getToken()->getUser();
  319.         if($usr != 'anon.') {
  320.             $colores = $this ->serviceColor->getByActivo();
  321.             $serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
  322.             $response =  new Response($serializer->serialize($colores, 'json', $serializacion),Response::HTTP_OK);
  323.             //$response =  new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
  324.             $response->headers->set('Content-Type', 'json'); //xml
  325.             $response->prepare($request);
  326.             return $response;
  327.         } else {
  328.             $response =  new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
  329.             return $response;
  330.         }
  331.     }
  332.     /**
  333.      * @Route("/api/admin/obtenerFormulasCartasExpertis", name="obtenerFormulasCartas_Expertis", methods="GET")
  334.      */
  335.     public function obtenerFormulasCartasParaExpertis(Request $request) {
  336.         $serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
  337.             new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
  338.                 new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
  339.             )
  340.         )->build();
  341.         $usr = $this->get('security.token_storage')->getToken()->getUser();
  342.         if($usr != 'anon.') {
  343.             $formulasCartas = $this ->service->getExportFormulasCT();
  344.             $response =  new Response($serializer->serialize($formulasCartas, 'json'),Response::HTTP_OK);
  345.             $response->headers->set('Content-Type', 'json'); //xml
  346.             $response->prepare($request);
  347.             return $response;
  348.         } else {
  349.             $response =  new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
  350.             return $response;
  351.         }
  352.     }
  353.     /**
  354.      * @Route("/api/admin/generaExportExcel", name="generaExportExcel_Admin", methods="GET")
  355.      */
  356.     public function generaExcelFormula(Request $request){
  357.         $usr = $this->get('security.token_storage')->getToken()->getUser();
  358.         if($usr != 'anon.') {
  359.             $logDir = $this->projectDir;
  360.             $nameLog = $logDir."/var/log/".date_format(new \DateTime(), 'Ymd_His') . "generaExcelFormula.log";
  361.             $this->log = new Logger($nameLog);
  362.             $this->log->pushHandler(new StreamHandler($nameLog, Logger::INFO));
  363.             $this->log->info("El usuario que solicita la exportacion tiene el id: " . $usr->getId());
  364.             $nombreFichero = "Exportacion_de_formulas_".date_format(new \DateTime(), 'Ymd_His');
  365.             try {
  366.                 $this->log->info("DEBUG 1");
  367.                 $excel = $this->service->generaExcelExportFormulas();
  368.                 $this->log->info("DEBUG 2");
  369.                 $writer = new Xlsx($excel);
  370.                 //Definimos su ruta
  371.                 $excelFilepath = $logDir."/var/tmp_upload/".date_format(new \DateTime(), 'Ymd_His').$nombreFichero.".xlsx";
  372.                 //Lo guardamos
  373.                 $writer->save($excelFilepath);
  374.                 $this->log->info("DEBUG 3");
  375.                 $response = new BinaryFileResponse($excelFilepath);
  376.                 $response->headers->set('Content-Type', 'application/vnd.ms-excel'); //xml
  377.                 $response->headers->set('Content-Disposition', 'attachment; filename="' . $nombreFichero . '.xlsx"'); //xml
  378.                 $this->log->info("DEBUG 4");
  379.                 return $response;
  380.             } catch (\Exception $e) {
  381.                 $this->log->error($e->getMessage());
  382.                 $response =  new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
  383.                 return $response;
  384.             }
  385.         }else{
  386.             $response =  new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
  387.             return $response;
  388.         }
  389.     }
  390.     /**
  391.      * @Route("/api/admin/generaExportExcelCT", name="generaExportExcelCT_Admin", methods="GET")
  392.      */
  393.     public function generaExportExcelCT(Request $request){
  394.         $usr = $this->get('security.token_storage')->getToken()->getUser();
  395.         if($usr != 'anon.') {
  396.             $logDir = $this->projectDir;
  397.             $nameLog = $logDir."/var/log/".date_format(new \DateTime(), 'Ymd_His') . "generaExcelFormula.log";
  398.             $this->log = new Logger($nameLog);
  399.             $this->log->pushHandler(new StreamHandler($nameLog, Logger::INFO));
  400.             $this->log->info("El usuario que solicita la exportacion tiene el id: " . $usr->getId());
  401.             $nombreFichero = "Exportacion_de_formulas_cartas";
  402.             try {
  403.                 $excel = $this->service->generaExcelExportFormulasCT();
  404.                 $writer = new Xlsx($excel);
  405.                 //Definimos su ruta
  406.                 $excelFilepath = $logDir."/var/tmp_upload/".$nombreFichero.".xlsx";
  407.                 //Lo guardamos
  408.                 $writer->save($excelFilepath);
  409.                 $response = new BinaryFileResponse($excelFilepath);
  410.                 $response->headers->set('Content-Type', 'application/vnd.ms-excel'); //xml
  411.                 $response->headers->set('Content-Disposition', 'attachment; filename="' . $nombreFichero . '.xlsx"'); //xml
  412.                 return $response;
  413.             } catch (\Exception $e) {
  414.                 $this->log->error($e->getMessage());
  415.                 $response =  new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
  416.                 return $response;
  417.             }
  418.         }else{
  419.             $response =  new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
  420.             return $response;
  421.         }
  422.     }
  423.     /**
  424.      * @Route("/api/importFormulaPersonales", name="import_access_personal", methods="POST")
  425.      */
  426.      public function setAccessFormulaPersonal(Request $request){
  427.      }
  428. }