<?php
namespace App\Controller\Publico;
use App\Entity\Ajustes\HistComisiones;
use App\Entity\Ajustes\Pedido;
use App\Form\Privado\Filtros\Catalogo\PedidoFilterType;
use App\Form\Publico\Pedido\PedidoPaso2Type;
use App\Form\Publico\Pedido\PedidoPaso3Type;
use App\Form\Publico\Pedido\PedidoUsuarioType;
use App\Repository\Ajustes\ConfigRepository;
use App\Repository\Ajustes\PedidoRepository;
use App\Service\EmailService;
use App\Service\PDFService;
use App\Utils\FilterSession;
use App\Utils\HelperUtil;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sonata\SeoBundle\Seo\SeoPageInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;
use Sermepa\Tpv\Tpv;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* @Route("/carrito", name="usu_pedidos_")
*/
class PedidosPublicController extends AbstractController
{
public const BASEDIR = Pedido::BASEDIRUSER;
public const ICON = Pedido::ICON;
protected $em;
protected $bd;
protected $bag;
protected $pag;
protected $hlp;
protected $repo;
protected $trans;
protected $seo;
protected $sec;
protected $email;
protected $repoConf;
protected $pdf;
public function __construct(EntityManagerInterface $em, Breadcrumbs $bd, PaginatorInterface $pg, PedidoRepository $repo, HelperUtil $hlp, ParameterBagInterface $pb, TranslatorInterface $trans, SeoPageInterface $seo, Security $sec, EmailService $email, ConfigRepository $repoConf, PDFService $pdf)
{
$this->em = $em;
$this->bd = $bd;
$this->bag = $pb;
$this->pag = $pg;
$this->repo = $repo;
$this->hlp = $hlp;
$this->trans = $trans;
$this->seo = $seo;
$this->sec = $sec;
$this->SendMail = $email;
$this->repoConf = $repoConf;
$this->pdf = $pdf;
}
/**
* @Route("/historico_pedidos", name="index", options={"expose"=true})
* @IsGranted("ROLE_PEDIDOS_LIST")
*/
public function indexAction(Request $request): Response
{
// Filter data
$default_values = ['sort' => 'pedido.id', 'order' => 'desc', 'page' => 1, 'limit' => 12];
$filtro = new FilterSession($request, $default_values, 'pedido_filter', $this->bag);
$data_Sesio = $filtro->checkFiltroForm();
$form_filtro = $this->createForm(PedidoFilterType::class, $data_Sesio);
$data = $form_filtro->handleRequest($request)->getData();
if ($form_filtro->isSubmitted() && $form_filtro->isValid()) {
$filtro->aƱadirFiltrosForm($data);
}
// Pagination values
$resultBD = $this->repo->filter(array_merge($data, ['user' => $this->getUser()]), ['getQuery' => true]);
$pagination = $this->pag->paginate(
$resultBD, // query NOT result
$filtro->getPage(), // page number
$filtro->getLimit(), // limit per page
$filtro->getSortKnp()
);
//SEO
$titulo =$this->trans->trans('pedido.usuario.index.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.index.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
return $this->render(self::BASEDIR.'/ped_index.html.twig', [
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
'pagination' => $pagination,
'form_filtro' => $form_filtro->createView(),
'p_filter' => $filtro->getData(),
]);
}
/**
* @Route("/crear", name="new", methods = {"GET", "POST"}, options={"expose"=true})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function new(Request $request): Response
{
//Averiguar si el usuario ya tiene un Pedido en Pendiente, es decir sin verificar
//Si es el caso, reedirigir al carrito
$pedidosUser = $this->repo->findPedidoCarrito();
if ($pedidosUser){
return $this->redirectToRoute('usu_pedidos_finish');
}
//Comprovar el rol del client per a ficar la pantalla fullwidth perque sino no cap
if($this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL')){
$profesional = true;
}else{
$profesional = false;
}
//Pasos del pedido
$stepper=[
'1' => "current",
'2' => "",
'3' => "",
'4' => "",
"5" => "",
];
$entity = new Pedido();
$form = $this->createForm(PedidoUsuarioType::class, $entity);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
$this->addFlash('danger', $this->trans->trans('pedido.new.error1', [], 'pedido'));
}else{
try {
if($entity->getPedUsuario() == null){
$entity->setPedUsuario($this->getUser());
}
//if($entity->getUsuFullName() == null || $entity->getUsuFullName() == null)
$entity->setPedEstado(Pedido::ESTADO_PENDIENTE);
$this->em->persist($entity);
$this->em->flush();
if ($form->getClickedButton() && 'guardarvolver' === $form->getClickedButton()->getName()) {
return $this->redirectToRoute('usu_pedidos_finish');
}
return $this->redirectToRoute('usu_pedidos_paso2');
} catch (\Exception $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error2', [], 'pedido') );
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
}
}
} else {
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
}
}
//SEO
$titulo =$this->trans->trans('pedido.new.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.new.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
return $this->render(self::BASEDIR.'/ped_new.html.twig', [
'profesional' => $profesional,
'stepper' => $stepper,
'pedido' => $entity,
'form' => $form->createView(),
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
/**
* @Route("/finalizar", name = "finish", methods = {"GET", "POST"}, options={"expose"=true})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function finish(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
//Comprovar el rol del client per a ficar la pantalla fullwidth perque sino no cap
if($this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL')){
$profesional = true;
}else{
$profesional = false;
}
$stepper=[
'1' => "current",
'2' => "",
'3' => "",
'4' => "",
"5" => "",
];
$form = $this->createForm(PedidoUsuarioType::class, $entity);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
$this->addFlash('danger', $this->trans->trans('pedido.new.error1', [], 'pedido'));
}else{
try {
foreach($entity->getPedGradeadasLineas() as $Card){
$entity->addPedGradeadasLinea($Card);
}
//Per asegurarmos que entra al listener
$entity->setUpdatedAt(new DateTime());
$this->em->flush();
if ($form->getClickedButton() && 'guardarvolver' === $form->getClickedButton()->getName()) {
return $this->redirectToRoute('usu_pedidos_finish');
}
return $this->redirectToRoute('usu_pedidos_paso2');
} catch (\Exception $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error2', [], 'pedido') );
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
}
}
} else {
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
}
}
//SEO
$titulo =$this->trans->trans('pedido.usuario.carrito.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.carrito.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
return $this->render(self::BASEDIR.'/ped_new.html.twig', [
'profesional' => $profesional,
'stepper' => $stepper,
'pedido' => $entity,
'form' => $form->createView(),
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
/**
* @Route("/paso/2", name = "paso2", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function paso2(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
$stepper=[
'1' => "completed",
'2' => "current",
'3' => "",
'4' => "",
"5" => "",
];
$form = $this->createForm(PedidoPaso2Type::class, $entity);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
try {
if($entity->getPedDireccionFacturacion() == '' || $entity->getPedDireccionFacturacion() == null){
$entity->setPedDireccionFacturacion($entity->getUsuAddress());
}
//Per asegurarmos que entra al listener
$entity->setUpdatedAt(new DateTime());
$this->em->flush();
if ($form->getClickedButton() && 'guardarvolver' === $form->getClickedButton()->getName()) {
return $this->redirectToRoute('usu_pedidos_finish');
}
return $this->redirectToRoute('usu_pedidos_paso3');
} catch (\Exception $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error2', [], 'pedido') );
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
}
} else {
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
}
}
//SEO
$titulo =$this->trans->trans('pedido.usuario.carrito.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.carrito.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
return $this->render(self::BASEDIR.'/ped_new.html.twig', [
'stepper' => $stepper,
'pedido' => $entity,
'form' => $form->createView(),
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
/**
* @Route("/paso/3", name = "paso3", methods = {"GET", "POST"}, options={"expose"=true})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function paso3(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
//Comprovar el rol del client per a ficar la pantalla fullwidth perque sino no cap
//Quan estiga el pass de pagar modificar esta funcio
if($this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL')){
$profesional = true;
if($this->sec->getUser()->getUsuComentarioDescuento() != null){
$this->addFlash('info', $this->sec->getUser()->getUsuComentarioDescuento());
}
}else{
$profesional = false;
}
$stepper=[
'1' => "completed",
'2' => "completed",
'3' => "current",
'4' => "",
"5" => "",
];
$form = $this->createForm(PedidoPaso3Type::class, $entity);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
try {
if ($form->getClickedButton() && 'guardarvolver' === $form->getClickedButton()->getName()) {
return $this->redirectToRoute('usu_pedidos_paso2');
}
$entity->setPedVerificado(true);
$this->em->flush();
if($profesional){
return $this->redirectToRoute('usu_pedidos_paso5');
}else{
return $this->redirectToRoute('usu_pedidos_paso4');
}
} catch (\Exception $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error2', [], 'pedido') );
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
}
} else {
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
}
}
//SEO
$titulo =$this->trans->trans('pedido.usuario.carrito.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.carrito.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
if($profesional){
//cargar vista profesional, masa diferencies per a fer-ho tot en una
return $this->render(self::BASEDIR.'/ped_new_paso3_pro.html.twig', [
'stepper' => $stepper,
'pedido' => $entity,
'form' => $form->createView(),
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}else{
return $this->render(self::BASEDIR.'/ped_new_paso3.html.twig', [
'stepper' => $stepper,
'pedido' => $entity,
'form' => $form->createView(),
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
}
/**
* @Route("/paso/4", name = "paso4", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function paso4(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
$stepper=[
'1' => "completed",
'2' => "completed",
'3' => "completed",
'4' => "current",
"5" => "",
];
//SEO
$titulo =$this->trans->trans('pedido.usuario.carrito.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.carrito.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
return $this->render(self::BASEDIR.'/ped_new_paso4.html.twig', [
'stepper' => $stepper,
'pedido' => $entity,
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
/**
* @Route("/paso/5", name = "paso5", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function paso5(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
if($entity->getPedFechaPago() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
$stepper=[
'1' => "completed",
'2' => "completed",
'3' => "completed",
'4' => "completed",
"5" => "current",
];
if($this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL')){
$entity->setPedEstado(Pedido::ESTADO_PAGO_PENDIENTE);
}else{
$entity->setPedEstado(Pedido::ESTADO_PAGADO);
}
$this->em->flush();
//Calcular historico
$historico = new HistComisiones();
$historico->setHistComPedido($entity);
$this->em->persist($historico);
$this->em->flush();
$this->addFlash('success', $this->trans->trans('pedido.new.success2', [], 'pedido'));
//Enviar correu de confirmació al client
if($this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL')){
$this->enviarEmailPedidoPro($entity);
}else{
$this->enviarEmailPedido($entity);
}
//SEO
$titulo =$this->trans->trans('pedido.usuario.carrito.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.carrito.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
return $this->render(self::BASEDIR.'/ped_new_paso5.html.twig', [
'stepper' => $stepper,
'pedido' => $entity,
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
/**
* @Route("/paso/pago_tpv", name = "pago_tpv", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function pagoTpv(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
try{
$key = $this->repoConf->getValue('TPV_KEY', ['type' => 'string', 'default' => 'sq7HjrUOBfKmC576ILgskD5srU870gJ7']);
$redsys = new Tpv();
$redsys->setAmount($entity->getPedPrecioTotal());
$redsys->setOrder(time());
$redsys->setMerchantcode($this->repoConf->getValue('TPV_MERCHANT_CODE', ['type' => 'string', 'default' => '356860510']));
$redsys->setCurrency($this->repoConf->getValue('TPV_MERCHANT_CURRENCY', ['type' => 'string', 'default' => '978']));
$redsys->setTransactiontype($this->repoConf->getValue('TPV_MERCHANT_TRANSACTION', ['type' => 'string', 'default' => '0']));
$redsys->setTerminal($this->repoConf->getValue('TPV_MERCHANT_TERMINAL', ['type' => 'string', 'default' => '001']));
$redsys->setMethod('C');
$redsys->setNotification($this->generateUrl('usu_pedidos_verificar_tpv', array(), UrlGeneratorInterface::ABSOLUTE_URL)); //Url de notificacion
$redsys->setUrlOk($this->generateUrl('usu_pedidos_verificar_tpv', array(), UrlGeneratorInterface::ABSOLUTE_URL)); //Url OK
$redsys->setUrlKo($this->generateUrl('usu_pedidos_verificar_tpv', array(), UrlGeneratorInterface::ABSOLUTE_URL)); //Url KO
$redsys->setVersion('HMAC_SHA256_V1');
$redsys->setTradeName('European Grading S.L');
$redsys->setTitular('European Grading S.L');
$redsys->setProductDescription('Pedido nĀŗ:'.$entity->getId());
$redsys->setEnvironment('test'); //Entorno test
$signature = $redsys->generateMerchantSignature($key);
$redsys->setMerchantSignature($signature);
$redsys->executeRedirection();
} catch (\Sermepa\Tpv\TpvException $e) {
$this->hlp->error($e);
}
}
/**
* @Route("/paso/verificar_tpv", name = "verificar_tpv", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function verificarTpv(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
try{
$redsys = new Tpv();
$key = $this->repoConf->getValue('TPV_KEY', ['type' => 'string', 'default' => 'sq7HjrUOBfKmC576ILgskD5srU870gJ7']);
$parameters = $redsys->getMerchantParameters($request->query->get('Ds_MerchantParameters'));
$DsResponse = $parameters["Ds_Response"];
$DsResponse += 0;
if ($redsys->check($key, $request->query->all()) && $DsResponse <= 99) {
//acciones a realizar si es correcto, por ejemplo validar una reserva, mandar un mail de OK, guardar en bbdd o contactar con mensajerĆa para preparar un pedido
$entity->setPedFechaPago(new \DateTime());
$this->em->flush();
return $this->redirectToRoute('usu_pedidos_paso5');
} else {
//acciones a realizar si ha sido erroneo
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
} catch (\Sermepa\Tpv\TpvException $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
}
}
/**
* @Route("/paso/pago_paypal", name = "pago_paypal", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function pagoPaypal(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
try{
//Inicializar datos
$user = $this->repoConf->getValue('PAYPAL_USER', ['type' => 'string', 'default' => 'info_api1.europeangrading.com']);
$pass = $this->repoConf->getValue('PAYPAL_PASS', ['type' => 'string', 'default' => '8ZWFV777J3XR5CK7']);
$signature = $this->repoConf->getValue('PAYPAL_SIGNATURE', ['type' => 'string', 'default' => 'ABtIJdd337osVy9aV9FPXbFKhbaDAuT1JQwgQT3JV9R4tU0BEUiQxkeL']);
$version = $this->repoConf->getValue('PAYPAL_VERSION', ['type' => 'string', 'default' => '95.0']);
$method = $this->repoConf->getValue('PAYPAL_METHOD', ['type' => 'string', 'default' => 'SetExpressCheckout']);
$urlAPI = $this->repoConf->getValue('PAYPAL_API_URL', ['type' => 'string', 'default' => 'https://api-3t.paypal.com/nvp']);
$venta = "Sale";
$total = $entity->getPedPrecioTotal();
$currency = "EUR";
$orderName = 'Pedido nĀŗ:'.$entity->getId();
$orderNumber = time();
$qty = 1;
$returnURL = $cancelURL = $this->generateUrl('usu_pedidos_verificar_paypal', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$clientEmail = $entity->getUsuEmail();
//Crear string para la peticion
$datosString =
"USER=$user&PWD=$pass&SIGNATURE=$signature&VERSION=$version&PAYMENTREQUEST_0_PAYMENTACTION=$venta&L_PAYMENTREQUEST_0_NAME0=$orderName&"
. "L_PAYMENTREQUEST_0_NUMBER0=$orderNumber&L_PAYMENTREQUEST_0_DESC0=$orderName&L_PAYMENTREQUEST_0_AMT0=$total&"
. "L_PAYMENTREQUEST_0_QTY0=$qty&PAYMENTREQUEST_0_ITEMAMT=$total&PAYMENTREQUEST_0_AMT=$total&"
. "PAYMENTREQUEST_0_CURRENCYCODE=$currency&RETURNURL=$returnURL&CANCELURL=$cancelURL&EMAIL=$clientEmail&METHOD=$method"
;
$datos = explode("&", $datosString);
//Peticion curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $urlAPI);
curl_setopt($curl, CURLOPT_POST, count($datos));
curl_setopt($curl, CURLOPT_POSTFIELDS, $datosString);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$remote_server_output = curl_exec ($curl);
$remote_server_output = urldecode($remote_server_output);
curl_close ($curl);
if($remote_server_output != ""){
parse_str($remote_server_output, $result);
if(isset($result['ACK'])){
if(strtolower($result['ACK']) == "success"){
$token = urldecode($result['TOKEN']);
if($token != null){
header("Location: https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" . $token );
exit();
}else{
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
}else{
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $result);
}
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
}
}else{
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
} catch (Exception $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
return $this->redirectToRoute('usu_pedidos_paso4');
}
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
/**
* @Route("/paso/verificar_paypal", name = "verificar_paypal", methods = {"GET", "POST"})
* @IsGranted("ROLE_PEDIDO_CREATE")
*/
public function verificarPaypal(Request $request): Response
{
$entity = $this->repo->findPedidoCarrito();
if($entity == null){
return $this->redirectToRoute('usu_pedidos_new');
}
if(count($entity->getPedGradeadasLineas()) == 0 && count($entity->getPedProductoLineas()) == 0){
return $this->redirectToRoute('usu_pedidos_finish');
}
if($entity->getUsuAddress() == null || ($entity->getPedPayMethod() == null && $this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL') == false) || $entity->getPedEnvioMetodo() == null ){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso2');
}
if($entity->getPedVerificado() == false){
$this->addFlash('danger', $this->trans->trans('pedido.new.error3', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso3');
}
try{
$token = $request->query->get('token');
$payerID = $request->query->get('PayerID');
if(null != $token && null != $payerID){
//PAGO CORRECTO
$entity->setPedFechaPago(new \DateTime());
$this->em->flush();
return $this->redirectToRoute('usu_pedidos_paso5');
}else{
//Pago cancelado
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
return $this->redirectToRoute('usu_pedidos_paso4');
}
} catch (Exception $e) {
$this->hlp->error($e);
$this->addFlash('danger', $this->trans->trans('pedido.new.error4', [], 'pedido'));
if ($this->isGranted('ROLE_SYSTEM_INFO')) {
$this->addFlash('danger', $e->getMessage());
}
}
}
/**
* @Route("/{id}/ver", name="view", methods = {"GET"}, requirements = {"id"="\d+"})
* @IsGranted("ROLE_PEDIDO_VIEW")
*/
public function view(Pedido $entity): Response
{
if($entity->getPedUsuario() != $this->getUser()){
throw $this->createAccessDeniedException();
}
if($this->sec->isGranted('ROLE_PEDIDOS_CREATE_PROFESIONAL')){
$profesional = true;
}else{
$profesional = false;
}
//SEO
$titulo =$this->trans->trans('pedido.usuario.view.seo.title', [], 'pedido');
$descripcion =$this->trans->trans('pedido.usuario.view.seo.desc', [], 'pedido');
$this->seo
->setTitle($titulo)
->addMeta('name', 'description', $descripcion)
->addMeta('property', 'og:title', $titulo)
->addMeta('property', 'og:description', $descripcion)
;
if($profesional){
//cargar vista profesional, masa diferencies per a fer-ho tot en una
return $this->render(self::BASEDIR.'/ped_view_pro.html.twig', [
'pedido' => $entity,
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}else{
return $this->render(self::BASEDIR.'/ped_view.html.twig', [
'pedido' => $entity,
'BaseDir' => self::BASEDIR,
'ICON' => self::ICON,
]);
}
}
public function enviarEmailPedido(Pedido $entity)
{
$emails = $this->sec->getUser()->getEmail();
$emails = explode(',', $emails);
$params = [
'asunto' => $this->trans->trans('pedido.usuario.email.asunto', [], 'pedido'),
'to' => $emails,
'plantilla' => '/emails/email_pedido.html.twig',
'plantilla_params' => [
'pedido' => $entity,
'raw' => true,
],
'importance' => null,
'adjuntos_base_pdf' => [
[
'nombre' => 'pedido_albaran.pdf',
'mime' => 'application/pdf',
'base_64' => $this->pdf->generateAlbaran($entity, true),
],
],
];
if ($this->SendMail->envioBasico($params)) {
return true;
}
return false;
}
public function enviarEmailPedidoPro(Pedido $entity)
{
$emails = $this->sec->getUser()->getEmail();
$emails = explode(',', $emails);
$params = [
'asunto' => $this->trans->trans('pedido.usuario.email.asunto', [], 'pedido'),
'to' => $emails,
'plantilla' => '/emails/email_pedido_pro.html.twig',
'plantilla_params' => [
'pedido' => $entity,
'raw' => true,
],
'importance' => null,
'adjuntos_base_pdf' => [
[
'nombre' => 'pedido_albaran.pdf',
'mime' => 'application/pdf',
'base_64' => $this->pdf->generateAlbaran($entity, true),
],
],
];
if ($this->SendMail->envioBasico($params)) {
return true;
}
return false;
}
/**
* @Route("/{id}/pdf_albaran", name="albaran", methods={"GET"}, requirements = {"id" = "\d+"})
* @IsGranted("ROLE_PEDIDOS_CREATE_ALBARAN_CLIENTE")
*/
public function callAlbaran(Pedido $entity)
{
if($entity->getPedUsuario() != $this->getUser()){
throw $this->createAccessDeniedException();
}
return $this->pdf->generateAlbaran($entity);
}
/**
* @Route("/{id}/pdf_factura", name="factura", methods={"GET"}, requirements = {"id" = "\d+"})
* @IsGranted("ROLE_PEDIDOS_CREATE_FACTURA_CLIENTE")
*/
public function callFactura(Pedido $entity)
{
if($entity->getPedUsuario() != $this->getUser()){
throw $this->createAccessDeniedException();
}
return $this->pdf->pdfFactura($entity);
}
}