<?php
namespace App\Controller;
use App\Entity\Formula;
use App\Entity\Models\FrontModels\ColorDTO;
use App\Form\FormulaType;
use App\Repository\FormulaRepository;
use App\Service\ColorService;
use App\Service\FormulaService;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use JMS\Serializer\SerializationContext;
use FOS\RestBundle\Controller\Annotations as Rest;
use JMS\Serializer\SerializerInterface;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use JMS\Serializer\SerializerBuilder;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class FormulaController extends AbstractFOSRestController
{
private $service;
private $serviceColor;
private $log ;
/**
* FormulaController constructor.
*/
public function __construct(
FormulaService $service,
ColorService $serviceColor,
LoggerInterface $logger,
string $projectDir
)
{
$this->service = $service;
$this ->serviceColor= $serviceColor;
$this->projectDir = $projectDir;
$this->log = $logger;
}
/**
* @Rest\Get("api/obtenerFormulas", name="obtener_formulas_convertidor")
* @param idColor Clave del color del que queremos extraer las fórmulas.
*/
public function obtenerFormulas(Request $request)
{
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
$idColor = $request->get('idColor');
$idTipo = $request->get('tipo');
$plomo = $request->get('plomo');
$prueba = $request->get('prueba');
$usr= $this->get('security.token_storage')->getToken()->getUser();
if(isset($idColor)&&isset($idTipo)) {
$data = $this->service->getAllByColor($idColor,$usr,$idTipo,$plomo);
$code = Response::HTTP_OK;
} elseif (isset($prueba)) {
// TODO: TERMINAR PROCEDIMINTO
$data = $this->service->getAllByPrueba();
$code = Response::HTTP_OK;
}else{
$data = ['error' => 'Faltan parámetros en el criterio de búsqueda'];
$code = Response::HTTP_FAILED_DEPENDENCY;
}
if($data)
{
$code = Response::HTTP_OK;
}else{
$data = [];
}
$serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula']);
$response = new Response($serializer->serialize($data, "json",$serializacion),$code);
$response->headers->set('Content-Type', 'json');
$response->prepare($request);
return $response;
}
/**
* @Rest\Get("/formula", name="formula_index")
*/
public function index(FormulaRepository $formulaRepository): Response
{
return $this->render('formula/index.html.twig', ['formulas' => $formulaRepository->findAll()]);
}
/**
* @Rest\Post("/api/formulasPersonalesUpdate", name="formulasPersonalesUpdate")
*/
public function createFormulasPersonal(Request $request, SerializerInterface $serializer){
$usr = $this->get('security.token_storage')->getToken()->getUser();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$requestObject= json_decode($request->getContent(), true);
if(isset($requestObject['color'],$requestObject['formula'])) {
//Le añadimos los ids de cuenta y usuario, para reutilizar otros metodos
$requestObject['color']['cuenta']['id'] = $usr->getId();
$requestObject['color']['tipo'] = 2;
$requestObject['formula']['cuenta']['id'] = $usr->getId();
// $requestObject['formula']['userId'] = 128;
//guardamos color si la formula es nueva y no se ha elegido sobreescribir
if ($requestObject['formula']['overwritePF'] === false) {
try{
$color = $this->serviceColor->nuevoColor($requestObject['color']);
}catch (\Exception $e){
$response = new Response('KO', Response::HTTP_CONFLICT);
/*
return [
'code' => $e->getCode() ?: 999,
'message' => $e->getMessage()?:'API Exception',
];
*/
return $response;
}
if($color == null){
$response = new Response(Response::HTTP_CONFLICT,Response::HTTP_CONFLICT);
return $response;
}
}
//creamos o editamos la formula
if ($requestObject['formula']['overwritePF'] === false) {
$colorId = $color->getId();
} else {
$colorId = $requestObject['color']['id'];
}
$formulaId = $this->service->nuevaFormulaPersonal($requestObject['formula'], $colorId);
// Si se está sobreescribiendo la formula, para devolver el mismo color, hay que buscarlo antes
if ($requestObject['formula']['overwritePF'] === true) {
$color = $this->serviceColor->findByIdPersonal($colorId);
}
$return = new ColorDTO();
$return->setId($color->getId());
$return->setCodigo($color->getCodigo());
$return->setNombre($color->getNombre());
$return->setPosicionCT('');
$return->setCliente($color->getClienteFinal()->getNombre());
$return->setTipo(2);
$return->setDisponible(true);
$return->setActivo(true);
$return->setFormulaId($formulaId);
$response = new Response($serializer->serialize($return, 'json'),Response::HTTP_OK);
return $response;
}else{
$response = new Response(Response::HTTP_BAD_REQUEST);
return $response;
}
}else{
$response = new Response(Response::HTTP_BAD_REQUEST);
return $response;
}
}
/*
* ADMINISTRADOR
*/
/**
* @Route("/api/admin/formulaObject", name="formulaById", methods="GET")
*/
public function getFormulaOficial(Request $request){
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
$response = new Response(Response::HTTP_BAD_REQUEST);
if ($request->query->get('idFormula') != null && $request->query->get('idFormula') != "") {
$correcto = $this->service->findById($request->query->get('idFormula') );
}
if ($request->query->get('codigoFormula') != null && $request->query->get('codigoFormula') != "") {
$correcto = $this->service->findByCodigo($request->query->get('codigoFormula') );
}
$serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
$response = new Response($serializer->serialize($correcto, 'json', $serializacion),Response::HTTP_OK);
// $response = new Response($serializer->serialize($correcto, 'json', SerializationContext::create()->setGroups('listAdminFormula')),Response::HTTP_OK);
//$response = new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
$response->headers->set('Content-Type', 'json'); //xml
$response->prepare($request);
return $response;
}
/**
* @Route("/api/admin/formulasOficiales", name="list_formulas_oficiales", methods="GET")
*/
public function getFormulasOficiales(Request $request){
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
$response = new Response(Response::HTTP_BAD_REQUEST);
if ($request ->query ->get('idColor')!=null && $request ->query ->get('idColor')!="") {
$correcto = $this ->serviceColor ->findById($request ->query ->get('idColor') );
}
$serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
$response = new Response($serializer->serialize($correcto, 'json',$serializacion),Response::HTTP_OK);
//$response = new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
$response->headers->set('Content-Type', 'json'); //xml
$response->prepare($request);
return $response;
}
/**
* @Route("/api/admin/formulasPrueba", name="formulaByPrueba", methods="GET")
*/
public function getFormulasPrueba(Request $request){
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
$response = new Response(Response::HTTP_BAD_REQUEST);
$correcto = $this->service->getAllByPrueba();
$serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
$response = new Response($serializer->serialize($correcto, 'json', $serializacion),Response::HTTP_OK);
// $response = new Response($serializer->serialize($correcto, 'json', SerializationContext::create()->setGroups('listAdminFormula')),Response::HTTP_OK);
//$response = new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
$response->headers->set('Content-Type', 'json'); //xml
$response->prepare($request);
return $response;
}
/**
* @Route("/api/admin/formulasPersonales", name="list_getFormulasPersonales", methods="GET")
*/
public function getFormulasPersonales(Request $request){
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
if ($request ->query ->get('idColor')!=null && $request ->query ->get('idColor')!="") {
$correcto = $this ->serviceColor ->findByIdPersonal($request ->query ->get('idColor') );
}
$serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
$response = new Response($serializer->serialize($correcto, 'json',$serializacion),Response::HTTP_OK);
//$response = new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
$response->headers->set('Content-Type', 'json'); //xml
$response->prepare($request);
return $response;
}
/**
* @Rest\Post("/api/admin/formulasOficialesAssociate", name="AssociateFormulasOficiales")
*/
public function asociarFormulasOficiales(Request $request){
$correcto = null;
$response = new Response(Response::HTTP_BAD_REQUEST);
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$datos= json_decode($request->getContent(), true);
if (isset($datos['colorId']) && isset($datos['formulaId']) && !isset($datos['unlink'])) {
//$correcto= null;
$correcto = $this ->service ->asociarFormulaOficial($datos);
} else if (isset($datos['unlink']) ){
//Tenemos unlink por lo que es una desasociacion
$correcto = $this ->service ->desAsociarFormulaOficial($datos);
}
}
if($correcto != 0){
$response = new Response(Response::HTTP_OK);
}else{
$response = new Response(Response::HTTP_BAD_REQUEST);
}
$response->prepare($request);
return $response;
}
/**
* @Rest\Post("/api/admin/formulasOficialesUpate", name="CreateOrUpdateFormulasOficiales")
*/
public function updateFormulasOficiales(Request $request){
$correcto = null;
$response = new Response(Response::HTTP_BAD_REQUEST);
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$formula= json_decode($request->getContent(), true);
if(isset($formula['idColor']) && empty($formula['id'])){
//$correcto= null;
$correcto = $this ->service ->nuevaFormulaOficial($formula);
}else if(isset($formula['id']) ){
//Tenemos Id por lo que es una actulizacion
$correcto = $this ->service ->modificaFormulaOficial($formula);
}
}
if($correcto != null){
$response = new Response(Response::HTTP_OK);
}else{
$response = new Response(Response::HTTP_BAD_REQUEST);
}
$response->prepare($request);
return $response;
}
/**
* @Route("/api/admin/formulasPersonalesUpdate", name="updateFormulasPersonal_Admin", methods="POST")
*/
public function updateFormulasPersonal(Request $request){
$usr = $this->get('security.token_storage')->getToken()->getUser();
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$requestObject= json_decode($request->getContent(), true);
if(isset($requestObject['idColor'],$requestObject['formula'])) {
//Le añadimos los ids de usuario, para reutilizar otros metodos
$requestObject['formula']['userId'] = $usr->getId();
//guardamos formula
$this->service->nuevaFormulaPersonal($requestObject['formula'],$requestObject['idColor']);
$response = new Response(Response::HTTP_OK);
return $response;
}else{
$response = new Response(Response::HTTP_BAD_REQUEST);
return $response;
}
}else{
$response = new Response(Response::HTTP_BAD_REQUEST);
return $response;
}
}
/**
* @Route("/api/admin/obtenerFormulasExpertis", name="obtenerFormulas_Expertis", methods="GET")
*/
public function obtenerFormulasParaExpertis(Request $request) {
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
$usr = $this->get('security.token_storage')->getToken()->getUser();
if($usr != 'anon.') {
$colores = $this ->serviceColor->getByActivo();
$serializacion = SerializationContext::create()->setGroups(['detalle','componenteFormula','listAdminFormula']);
$response = new Response($serializer->serialize($colores, 'json', $serializacion),Response::HTTP_OK);
//$response = new Response($serializer->serialize($data, 'json'),Response::HTTP_OK);
$response->headers->set('Content-Type', 'json'); //xml
$response->prepare($request);
return $response;
} else {
$response = new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
return $response;
}
}
/**
* @Route("/api/admin/obtenerFormulasCartasExpertis", name="obtenerFormulasCartas_Expertis", methods="GET")
*/
public function obtenerFormulasCartasParaExpertis(Request $request) {
$serializer = SerializerBuilder::create()->setPropertyNamingStrategy(
new \JMS\Serializer\Naming\SerializedNameAnnotationStrategy(
new \JMS\Serializer\Naming\IdenticalPropertyNamingStrategy()
)
)->build();
$usr = $this->get('security.token_storage')->getToken()->getUser();
if($usr != 'anon.') {
$formulasCartas = $this ->service->getExportFormulasCT();
$response = new Response($serializer->serialize($formulasCartas, 'json'),Response::HTTP_OK);
$response->headers->set('Content-Type', 'json'); //xml
$response->prepare($request);
return $response;
} else {
$response = new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
return $response;
}
}
/**
* @Route("/api/admin/generaExportExcel", name="generaExportExcel_Admin", methods="GET")
*/
public function generaExcelFormula(Request $request){
$usr = $this->get('security.token_storage')->getToken()->getUser();
if($usr != 'anon.') {
$logDir = $this->projectDir;
$nameLog = $logDir."/var/log/".date_format(new \DateTime(), 'Ymd_His') . "generaExcelFormula.log";
$this->log = new Logger($nameLog);
$this->log->pushHandler(new StreamHandler($nameLog, Logger::INFO));
$this->log->info("El usuario que solicita la exportacion tiene el id: " . $usr->getId());
$nombreFichero = "Exportacion_de_formulas_".date_format(new \DateTime(), 'Ymd_His');
try {
$this->log->info("DEBUG 1");
$excel = $this->service->generaExcelExportFormulas();
$this->log->info("DEBUG 2");
$writer = new Xlsx($excel);
//Definimos su ruta
$excelFilepath = $logDir."/var/tmp_upload/".date_format(new \DateTime(), 'Ymd_His').$nombreFichero.".xlsx";
//Lo guardamos
$writer->save($excelFilepath);
$this->log->info("DEBUG 3");
$response = new BinaryFileResponse($excelFilepath);
$response->headers->set('Content-Type', 'application/vnd.ms-excel'); //xml
$response->headers->set('Content-Disposition', 'attachment; filename="' . $nombreFichero . '.xlsx"'); //xml
$this->log->info("DEBUG 4");
return $response;
} catch (\Exception $e) {
$this->log->error($e->getMessage());
$response = new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
return $response;
}
}else{
$response = new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
return $response;
}
}
/**
* @Route("/api/admin/generaExportExcelCT", name="generaExportExcelCT_Admin", methods="GET")
*/
public function generaExportExcelCT(Request $request){
$usr = $this->get('security.token_storage')->getToken()->getUser();
if($usr != 'anon.') {
$logDir = $this->projectDir;
$nameLog = $logDir."/var/log/".date_format(new \DateTime(), 'Ymd_His') . "generaExcelFormula.log";
$this->log = new Logger($nameLog);
$this->log->pushHandler(new StreamHandler($nameLog, Logger::INFO));
$this->log->info("El usuario que solicita la exportacion tiene el id: " . $usr->getId());
$nombreFichero = "Exportacion_de_formulas_cartas";
try {
$excel = $this->service->generaExcelExportFormulasCT();
$writer = new Xlsx($excel);
//Definimos su ruta
$excelFilepath = $logDir."/var/tmp_upload/".$nombreFichero.".xlsx";
//Lo guardamos
$writer->save($excelFilepath);
$response = new BinaryFileResponse($excelFilepath);
$response->headers->set('Content-Type', 'application/vnd.ms-excel'); //xml
$response->headers->set('Content-Disposition', 'attachment; filename="' . $nombreFichero . '.xlsx"'); //xml
return $response;
} catch (\Exception $e) {
$this->log->error($e->getMessage());
$response = new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
return $response;
}
}else{
$response = new Response(Response::HTTP_BAD_REQUEST,Response::HTTP_BAD_REQUEST);
return $response;
}
}
/**
* @Route("/api/importFormulaPersonales", name="import_access_personal", methods="POST")
*/
public function setAccessFormulaPersonal(Request $request){
}
}