src/Controller/CallcenterController.php line 64

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Cabecera;
  4. use App\Entity\Configuracion;
  5. use App\Entity\CabeceraStatus;
  6. use App\Entity\CabeceraLinkdepago;
  7. use App\Entity\Domicilios;
  8. use App\Entity\Lineas;
  9. use App\Entity\Sucursal;
  10. use App\Form\Type\CabeceraType;
  11. use App\Form\Type\Cabecera2Type;
  12. use App\Form\Type\CabeceraEmailLinkdepagoType;
  13. use App\Form\Type\LineasType;
  14. use App\Repository\ArticulosRepository;
  15. use App\Repository\ClientesRepository;
  16. use App\Repository\FavoritoscabRepository;
  17. use App\Repository\LineasRepository;
  18. use App\Repository\ModificadoreslinRepository;
  19. use App\Repository\SucursalRepository;
  20. use App\Utils\Status;
  21. use App\Utils\Xml;
  22. use Doctrine\ORM\EntityManagerInterface;
  23. use Doctrine\Persistence\ManagerRegistry;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\Filesystem\Filesystem;
  26. use Symfony\Component\Form\Extension\Core\Type\TextType;
  27. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  28. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  29. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Symfony\Component\HttpFoundation\Response;
  32. // use Symfony\Component\HttpFoundation\Session\Session;
  33. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use App\Controller\Admin\CabeceraCrudController;
  36. use App\Repository\ImpuestosRepository;
  37. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  38. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  39. use App\Service\ClienteManager;
  40. use App\Service\GlobalPayService;
  41. use App\Service\MailerService;
  42. use App\Service\XmlGeneratorService;
  43. // use ParagonIE\Halite\KeyFactory;
  44. class CallcenterController extends AbstractController
  45. {
  46.     use Status;
  47.     private $adminUrlGenerator;
  48.     public function __construct(private ManagerRegistry $doctrineAdminUrlGenerator $adminUrlGenerator)
  49.     {
  50.         $this->doctrine $doctrine;
  51.         $this->adminUrlGenerator $adminUrlGenerator;
  52.     }
  53.     #[Route('/'name'callcenter')]
  54.     public function index(Request $request): Response
  55.     {
  56.         // $keyPath = $this->getParameter('kernel.project_dir') . '/config/encryption.key';
  57.         // if (file_exists($keyPath)) {
  58.         //     return new Response('La clave de cifrado ya existe. No se generó una nueva clave.', 403);
  59.         // }
  60.         // $encryptionKey = KeyFactory::generateEncryptionKey();
  61.         // KeyFactory::save($encryptionKey, $keyPath);
  62.         // $keyPath = $this->getParameter('encryption_key_path');
  63.         // dd($keyPath);
  64.         $dataFromRequest  $request->get('data');
  65.         $formData = [];
  66.         if ($dataFromRequest) {
  67.             $formData = [
  68.                 'type' => $dataFromRequest['type'], // Usar valores por defecto si las claves no existen
  69.                 'text' => $dataFromRequest['text'] ?? '',
  70.                 'factura_electronica' => $dataFromRequest['fe'] ? true false,
  71.             ];
  72.         }
  73.         if (!array_key_exists('type'$formData)) {
  74.             $formData['type'] = 1;
  75.         }
  76.         $form $this->createFormBuilder($formData)
  77.             ->add('type'ChoiceType::class, [
  78.                 'choices' => [
  79.                     'Telefono' => 1,
  80.                     'Documento' => 2
  81.                 ],
  82.                 'expanded' => true,
  83.                 'multiple' => false,
  84.             ])
  85.             ->add('text'TextType::class)
  86.             ->add('factura_electronica'CheckboxType::class, [
  87.                 'required' => false,
  88.             ])
  89.             ->add('buscar'SubmitType::class)
  90.             ->getForm();
  91.         $form->handleRequest($request);
  92.         if ($form->isSubmitted() && $form->isValid()) {
  93.             $data $form->getData();
  94.             return $this->redirectToRoute(
  95.                 'seleccionCliente',
  96.                 array(
  97.                     'type' => $data['type'],
  98.                     'text' => $data['text'],
  99.                     'fe' => $data['factura_electronica'] ? '1' '0',
  100.                 )
  101.             );
  102.         }
  103.         return $this->render('callcenter/index.html.twig', [
  104.             'form' => $form->createView(),
  105.         ]);
  106.     }
  107.     #[Route('/selecciondecliente/{type}/{text}/{fe}'name'seleccionCliente')]
  108.     public function seleccionCliente(int $typestring $textstring $feClientesRepository $clienteRepositorySessionInterface $session): Response
  109.     {
  110.         $feBool filter_var($feFILTER_VALIDATE_BOOLEAN);
  111.         $data = ['type' => $type'text' => $text'fe' => $feBool];
  112.         $cliente $clienteRepository->findClient($data);
  113.         if (empty($cliente)) {
  114.             if ($feBool) {
  115.                 $qrRoute 'https://qrmde.crepesywaffles.com/qrcc/qrmde.php';
  116.                 $this->addFlash(
  117.                     'notice',
  118.                     'DEBES CREAR EL CLIENTE PRIMERO EN EL QR PARA FACTURA ELECTRÓNICA <a class="alert-link" href="' $qrRoute '" target="_blank">Crear QR</a>'
  119.                 );
  120.                 return $this->redirectToRoute('callcenter', ['data' => $data]);
  121.             } else {
  122.                 $session->set('clienteData'$data); // Guardar en sesión
  123.                 $session->set('fe'$data['fe']); // Guardar en sesión
  124.                 return $this->redirectToRoute('cliente');
  125.             }
  126.         } elseif (count($cliente) === 1) {
  127.             $session->set('clienteData'$cliente[0]); // Guardar en sesión
  128.             $session->set('fe'$data['fe']); // Guardar en sesión
  129.             return $this->redirectToRoute('cliente');
  130.         }
  131.         $session->set('clienteData'$cliente);
  132.         return $this->render('callcenter/clienteSelect.html.twig', ['clientes' => $cliente'data' => $data]);
  133.     }
  134.     #[Route('/cliente'name'cliente')]
  135.     public function cliente(Request $requestSessionInterface $sessionClienteManager $clienteManagerSucursalRepository $sucursalRepository): Response
  136.     {
  137.         $clientesData $session->get('clienteData');
  138.         $fe $session->get('fe');
  139.         $clienteData $clientesData[$request->get('index')]  ?? $clientesData;
  140.         $cabecera $clienteManager->procesarDatosCliente($clienteData);
  141.         $cabecera->setFacturaelectronica($fe 0);
  142.         $editable = isset($clienteData['alias']) ? !($clienteData['alias'] === "1") : true;
  143.         $form $this->createForm(CabeceraType::class, $cabecera, ['editable_mode' => $editable]);
  144.         $form->handleRequest($request);
  145.         if ($form->isSubmitted() && $form->isValid()) {
  146.             if ($cabecera->getNombreReceptor() === null || $cabecera->getNombreReceptor() === '') {
  147.                 $cabecera->setNombreReceptor($cabecera->getNombrecliente());
  148.             }
  149.             if ($cabecera->getTelefonoReceptor() === null || $cabecera->getTelefonoReceptor() === '') {
  150.                 $cabecera->setTelefonoReceptor($cabecera->getTelefonocliente());
  151.             }
  152.             $clienteManager->guardarCabecera($cabecera$this->getuser());
  153.             return $this->redirectToRoute('cc_favoritos', ['id' => $cabecera->getId()]);
  154.         }
  155.         $sucursales $sucursalRepository->findAvailable();
  156.         return $this->render('callcenter/cliente.html.twig', [
  157.             'cliente' => $clienteData,
  158.             'form' => $form->createView(),
  159.             'sucursales' => $sucursales,
  160.         ]);
  161.     }
  162.     #[Route('/cabecera/{id}/editar'name'cliente_editar')]
  163.     public function clienteEdit(SucursalRepository $sucursalRepositoryRequest $requestint $id): Response
  164.     {
  165.         $cabecera $this->doctrine->getRepository(Cabecera::class)->find($id);
  166.         $editable $cabecera->getAlias() === "1" false true;
  167.         if (!$cabecera) {
  168.             throw $this->createNotFoundException(
  169.                 'Cabecera no encontrada'
  170.             );
  171.         }
  172.         $estados = array('INICIADO''EDICION');
  173.         if (!in_array($cabecera->getEstado(), $estados)) {
  174.             throw $this->createNotFoundException(
  175.                 'NO SE PUEDE EDITAR ESTE PEDIDO'
  176.             );
  177.         }
  178.         $sucursales $sucursalRepository->findAvailable();
  179.         $form $this->createForm(CabeceraType::class, $cabecera, ['editable_mode' => $editable]);
  180.         $form->handleRequest($request);
  181.         if ($form->isSubmitted() && $form->isValid()) {
  182.             $cabecera $form->getData();
  183.             $entityManager $this->doctrine->getManager();
  184.             $entityManager->persist($cabecera);
  185.             $entityManager->flush();
  186.             return $this->redirectToRoute('cc_favoritos', [
  187.                 'id' => $cabecera->getId()
  188.             ]);
  189.         }
  190.         return $this->render('callcenter/cliente.html.twig', [
  191.             'cliente' => $cabecera,
  192.             'form' => $form->createView(),
  193.             'sucursales' => $sucursales,
  194.         ]);
  195.     }
  196.     #[Route('/cabecera/{id}/favoritos'name'cc_favoritos')]
  197.     public function favoritos(LineasRepository $lineasrepFavoritoscabRepository $favoritoscabRequest $requestint $id): Response
  198.     {
  199.         $cabecera $this->doctrine
  200.             ->getRepository(Cabecera::class)
  201.             ->find($id);
  202.         if (!$cabecera) {
  203.             throw $this->createNotFoundException(
  204.                 'Pedido no encontrado'
  205.             );
  206.         }
  207.         if ($cabecera->getIsFinalizada()) {
  208.             throw $this->createNotFoundException(
  209.                 'Pedido finalizado'
  210.             );
  211.         }
  212.         $status = array('INICIADO''PROGRAMADO''EDICION');
  213.         if (!in_array($cabecera->getEstado(), $status)) {
  214.             throw $this->createNotFoundException(
  215.                 'Este pedido no se puede editar'
  216.             );
  217.         }
  218.         //log
  219.         if ($cabecera->getEstado() == 'PROGRAMADO') {
  220.             $entityManager $this->doctrine->getManager();
  221.             $status $this->createStatus($cabecera'EDICION'$this->getUser());
  222.             $entityManager->persist($status);
  223.             $entityManager->flush();
  224.         }
  225.         //log
  226.         $favoritos $favoritoscab->findAllByTerminal(2);
  227.         return $this->render('callcenter/pedido.html.twig', [
  228.             'favoritos' => $favoritos,
  229.             'cabecera' => $cabecera
  230.         ]);
  231.     }
  232.     #[Route('/buscar-productos-modal'name'buscar_productos_modal'methods: ['GET'])]
  233.     public function loadModal(): Response
  234.     {
  235.         return $this->render('callcenter/search_modal.html.twig');
  236.     }
  237.     #[Route('/buscar-productos'name'buscar_productos'methods: ['GET'])]
  238.     public function buscarProductos(ArticulosRepository $articulosRepositoryRequest $request): Response
  239.     {
  240.         $query $request->query->get('query');
  241.         $sucursal $this->doctrine
  242.             ->getRepository(Sucursal::class)
  243.             ->findOneBy(array('nombre' => $request->query->get('sucursal')));
  244.         $sucursal $sucursal->getCodalmvent() ?? '';
  245.         $articulos $articulosRepository->findArticulosByName($query$sucursal);
  246.         return $this->render('callcenter/search_results.html.twig', [
  247.             'articulos' => $articulos,
  248.             'query' => strtoupper($request->query->get('query')),
  249.         ]);
  250.     }
  251.     #[Route('/articulos'name'cc_articulos')]
  252.     public function articulos(ArticulosRepository $articulosRepositoryRequest $request): Response
  253.     {
  254.         // $template = $request->query->get('ajax') ? '_articulos.html.twig' : 'fav.html.twig';
  255.         $favorito $request->query->get('fav');
  256.         $sucursal $this->doctrine
  257.             ->getRepository(Sucursal::class)
  258.             ->findOneBy(array('nombre' => $request->query->get('sucursal')));
  259.         // $sucursal = $sucursal ? $sucursal->getCodalmvent() : '';
  260.         $sucursal $sucursal->getCodalmvent() ?? '';
  261.         $articulos $articulosRepository->findArticulosByFavorito($favorito$sucursal);
  262.         return $this->render('callcenter/_articulos.html.twig', [
  263.             'articulos' => $articulos,
  264.         ]);
  265.     }
  266.     #[Route('/articulo'name'cc_articulo')]
  267.     public function articulo(ArticulosRepository $articulosRepositoryRequest $request): Response
  268.     {
  269.         $id $request->query->get('codarticulo');
  270.         $fav $request->query->get('fav');
  271.         $articulo $articulosRepository->findArticulo($id$fav);
  272.         if (!$articulo) {
  273.             throw $this->createNotFoundException(
  274.                 'Artículo no encontrado'
  275.             );
  276.         }
  277.         $modsbyarticulo $articulosRepository->findModificadoresByArticulo($id);
  278.         $mods = array();
  279.         foreach ($modsbyarticulo as $item) {
  280.             $mods[] = $articulosRepository->findModificadores($item['codmodificador']);
  281.         }
  282.         $inicialstate $articulosRepository->validadorArticulos($modsbyarticulo);
  283.         return $this->render('callcenter/_articulo.html.twig', [
  284.             'articulo' => $articulo,
  285.             'modsbyarticulo' => $modsbyarticulo,
  286.             'mods' => $mods,
  287.             'jsonmodsbyarticulo' => json_encode($modsbyarticulo),
  288.             'jsonmods' => json_encode($mods),
  289.             'inicialstate' => $inicialstate,
  290.         ]);
  291.     }
  292.     #[Route('/crearlistas'name'cc_crearlistas')]
  293.     public function crearlistas(ArticulosRepository $articulosRepositoryModificadoreslinRepository $mlinRepositoryRequest $requestEntityManagerInterface $entityManager): response
  294.     {
  295.         $cabeceraId $request->query->get('cabecera');
  296.         $parentId $request->query->get('parent');
  297.         $q intval($request->query->get('q'));
  298.         $fav $request->query->get('fav');
  299.         $childs explode(","$request->query->get('childs'));
  300.         $modcabs explode(","$request->query->get('modcabs'));
  301.         $cabecera $entityManager->getRepository(Cabecera::class)->find($cabeceraId);
  302.         $parent $articulosRepository->findArticulo($parentId$fav);
  303.         // Crear línea principal y líneas hijas
  304.         $parentLine $this->createParentLine($cabecera$parent$q$fav);
  305.         $entityManager->persist($parentLine);
  306.         $childTotalPrice 0;
  307.         if (!empty($childs[0])) {
  308.             $childTotalPrice $this->createChildLines($childs$modcabs$parent$q$parentLine$mlinRepository$entityManager);
  309.         }
  310.         // Actualizar totales en línea principal y Cabecera
  311.         $this->updateParentLineTotal($parentLine$childTotalPrice);
  312.         $this->updateCabeceraTotals($cabecera$parentLine$childTotalPrice);
  313.         $entityManager->flush();
  314.         return $this->render('callcenter/_lineas.html.twig', [
  315.             'cabecera' => $cabecera,
  316.         ]);
  317.     }
  318.     private function createParentLine($cabecera$parent$q$fav): Lineas
  319.     {
  320.         $linePrice $parent['pneto'] * $q;
  321.         $line = new Lineas();
  322.         $line->setCabecera($cabecera);
  323.         $line->setCodarticulo($parent['codarticulo']);
  324.         $line->setDescripcion($parent['descripcion']);
  325.         $line->setPrecio($linePrice);
  326.         $line->setPreciounidad($parent['pneto']);
  327.         $line->setPreciototal($parent['pneto']);
  328.         $line->setUnidades($q);
  329.         $line->setCodfavoritos($fav);
  330.         $line->setCodImpuesto($parent['tipoiva']);
  331.         $parentPriceWithoutTax $this->calcularPrecioSinImpuesto($linePrice$line->getCodImpuesto());
  332.         $line->setPreciosiniva($parentPriceWithoutTax);
  333.         return $line;
  334.     }
  335.     private function createChildLines($childs$modcabs$parent$q$parentLine$mlinRepositoryEntityManagerInterface $entityManager): float
  336.     {
  337.         $parentLine->setNumlineasmodif(count($childs));
  338.         $childTotalPrice 0;
  339.         $childData = [];
  340.         foreach ($childs as $key => $child) {
  341.             $childArticle $mlinRepository->findModificador($child$parent['codarticulo'], $modcabs[$key]);
  342.             $linePrice $childArticle['incprecio'] * $q;
  343.             // Almacena toda la información relevante
  344.             $childData[] = [
  345.                 'childArticle' => $childArticle,
  346.                 'linePrice' => $linePrice,
  347.                 'quantity' => $q,
  348.             ];
  349.         }
  350.         usort($childData, function ($a$b) {
  351.             return $a['childArticle']['posicion'] - $b['childArticle']['posicion'];
  352.         });
  353.         foreach ($childData as $data) {
  354.             $childArticle $data['childArticle'];
  355.             $linePrice $data['linePrice'];
  356.             $q $data['quantity'];
  357.             $line = new Lineas();
  358.             $line->setCabecera($parentLine->getCabecera());
  359.             $line->setParent($parentLine);
  360.             $line->setCodarticulo($childArticle['codarticulocom']);
  361.             $line->setDescripcion($childArticle['descripcion']);
  362.             $line->setPrecio($linePrice);
  363.             $line->setUnidades($q);
  364.             $line->setNumlineasmodif(null);
  365.             $line->setCodImpuesto($childArticle['tipoiva']);
  366.             $line->setPreciosiniva($this->calcularPrecioSinImpuesto($linePrice$childArticle['tipoiva']));
  367.             $line->setPosicion($childArticle['posicion']);
  368.             $childTotalPrice += $linePrice;
  369.             $entityManager->persist($line);
  370.         }
  371.         // $entityManager->flush();
  372.         return $childTotalPrice;
  373.     }
  374.     private function updateParentLineTotal($parentLinefloat $childTotalPrice): void
  375.     {
  376.         // $parentLine->setPreciototal($parentLine->getPrecio() + $childTotalPrice);
  377.         $totalPrice $parentLine->getPrecio() + $childTotalPrice;
  378.         $parentLine->setPreciototal($totalPrice);
  379.         $parentPriceWithoutTax $this->calcularPrecioSinImpuesto($totalPrice$parentLine->getCodImpuesto());
  380.         $parentLine->setPreciosiniva($parentPriceWithoutTax);
  381.     }
  382.     private function updateCabeceraTotals($cabecera$parentLinefloat $childTotalPrice): void
  383.     {
  384.         $cabecera->setTotal($cabecera->getTotal() + $parentLine->getPrecio() + $childTotalPrice);
  385.         $cabecera->setTotalsiniva($cabecera->getTotalsiniva() + $parentLine->getPreciosiniva());
  386.         // $cabecera->setTotalsiniva($cabecera->getTotalsiniva() + $parentLine->getPreciosiniva() + $this->calcularPrecioSinImpuesto($childTotalPrice, $parentLine->getCodImpuesto()));
  387.     }
  388.     private function calcularPrecioSinImpuesto($precioConImpuesto$porcentajeImpuesto)
  389.     {
  390.         return $precioConImpuesto / (+ ($porcentajeImpuesto 100));
  391.     }
  392.     #[Route('/agregarcomentario/{parent}'name'cc_agregarcomentario')]
  393.     public function addComent(EntityManagerInterface $emLineasRepository $lRequest $requestint $parent): response
  394.     {
  395.         $p $l->findOneBy(['id' => $parent]);
  396.         $linea = new Lineas;
  397.         $form $this->createForm(LineasType::class, $linea);
  398.         $form->handleRequest($request);
  399.         if ($form->isSubmitted() && $form->isValid()) {
  400.             $linea $form->getData();
  401.             $linea->setCodarticulo(0);
  402.             $linea->setPrecio(0);
  403.             $linea->setCodfavoritos(0);
  404.             // $linea->setParent($p);
  405.             $linea->setCabecera($p->getCabecera());
  406.             $root $p->getRoot();
  407.             $n $root->getNumlineasmodif() + 1;
  408.             $root->setNumlineasmodif($n);
  409.             // $l->persistAsFirstChildOf($linea, $p);
  410.             $l->persistAsLastChildOf($linea$p);
  411.             $em->persist($root);
  412.             $em->flush();
  413.             // if($countComment > 0){
  414.             //     $l->moveUp($linea, $countComment);
  415.             // }
  416.             return $this->redirectToRoute('cc_favoritos', [
  417.                 'id' => $p->getCabecera()->getId(),
  418.             ]);
  419.         }
  420.         return $this->render('callcenter/_comentarios.html.twig', [
  421.             'form' => $form->createView(),
  422.             'parent' => $p
  423.         ]);
  424.     }
  425.     #[Route('/borrarlista/{id}'name'cc_borrarlista')]
  426.     public function borrarlista(LineasRepository $lRequest $requestint $id): response
  427.     {
  428.         $entityManager $this->doctrine->getManager();
  429.         // Linea que se quiere borrar
  430.         $linea $l->find($id);
  431.         if (!$linea) {
  432.             throw $this->createNotFoundException('Linea no encontrada.');
  433.         }
  434.         $cabecera $linea->getCabecera();
  435.         $precioTotal $linea->getPrecio();
  436.         $precioSinIVA $linea->getPreciosiniva();
  437.         if ($linea->getParent() === null && $linea->getNumlineasmodif() > 0) {
  438.             list($childPriceTotal$childPriceWithoutTax) = $this->removeChildLines($linea$l$entityManager);
  439.             $precioTotal += $childPriceTotal;
  440.             $precioSinIVA += $childPriceWithoutTax;
  441.         } elseif ($linea->getParent() !== null) {
  442.             $parentLine $linea->getRoot();
  443.             $parentLine->setNumlineasmodif($parentLine->getNumlineasmodif() - 1);
  444.             $parentLine->setPreciototal($parentLine->getPreciototal() - ($precioTotal $linea->getUnidades()));
  445.             $parentLine->setPreciosiniva($parentLine->getPreciosiniva() - $precioSinIVA); // Añadido para actualizar el preciosiniva del parent
  446.             $entityManager->persist($parentLine);
  447.         }
  448.         $cabecera->setTotal($cabecera->getTotal() - $precioTotal);
  449.         $cabecera->setTotalsiniva($cabecera->getTotalsiniva() - $precioSinIVA);
  450.         $entityManager->remove($linea);
  451.         $entityManager->persist($cabecera);
  452.         $entityManager->flush();
  453.         return $this->redirectToRoute('cc_favoritos', ['id' => $cabecera->getId()]);
  454.     }
  455.     private function removeChildLines(Lineas $parentLineLineasRepository $lEntityManagerInterface $entityManager): array
  456.     {
  457.         $childLines $l->findBy(['parent' => $parentLine->getId()]);
  458.         $childPriceTotal 0;
  459.         $childPriceWithoutTax 0;
  460.         foreach ($childLines as $child) {
  461.             $childPriceTotal += $child->getPrecio();
  462.             $childPriceWithoutTax += $child->getPreciosiniva();
  463.             $entityManager->remove($child);
  464.         }
  465.         return [$childPriceTotal$childPriceWithoutTax];
  466.     }
  467.     // #[Route('/borrarlista/{id}', name: 'cc_borrarlista')]
  468.     // public function borrarlista(LineasRepository $l, Request $request, int $id): response
  469.     // {
  470.     //     // $favoritos = $favoritoscab->findAllByTerminal(2);
  471.     //     $entityManager = $this->doctrine->getManager();
  472.     //     //linea que se quiere borrar
  473.     //     $linea = $this->doctrine
  474.     //         ->getRepository(Lineas::class)
  475.     //         ->find($id);
  476.     //     $cabecera = $linea->getCabecera();
  477.     //     $total = $cabecera->getTotal();
  478.     //     if ($linea->getParent() === null) {
  479.     //         if ($linea->getNumlineasmodif() > 0) {
  480.     //             $childs = $l->findby(['parent' => $linea->getId()]);
  481.     //             foreach ($childs as $key => $child) {
  482.     //                 $total = $total - $child->getPrecio();
  483.     //                 $entityManager->remove($child);
  484.     //             }
  485.     //         }
  486.     //     } else {
  487.     //         $p = $linea->getRoot();
  488.     //         $countChild = $l->childCount($linea);
  489.     //         $count = $countChild + 1;
  490.     //         $n = $p->getNumlineasmodif() - $count;
  491.     //         $p->setNumlineasmodif($n);
  492.     //         //probando
  493.     //         $p->setPreciototal($p->getPreciototal() - ($linea->getPrecio() / $linea->getUnidades()));
  494.     //         $entityManager->persist($p);
  495.     //     }
  496.     //     $total = $total - $linea->getPrecio();
  497.     //     $cabecera->setTotal($total);
  498.     //     $entityManager->remove($linea);
  499.     //     $entityManager->persist($cabecera);
  500.     //     $entityManager->flush();
  501.     //     return $this->redirectToRoute('cc_favoritos', array('id' => $linea->getCabecera()->getId()));
  502.     // }
  503.     #[Route('/enespera'name'cc_enespera')]
  504.     public function esperarpago(): response
  505.     {
  506.         return $this->render('callcenter/enespera.html.twig');
  507.     }
  508.     #[Route('/hacerpedido/{id}'name'cc_hacerpedido')]
  509.     public function generarxml(int $idXmlGeneratorService $xml): response
  510.     {
  511.         $cab $this->doctrine
  512.             ->getRepository(Cabecera::class)
  513.             ->find($id);
  514.         $estadoinicial $cab->getEstado();
  515.         $entityManager $this->doctrine->getManager();
  516.         if ($this->isReservation($cab) === false) {
  517.             $filename $xml->generatorXML($cab);
  518.             $cab->setFilename($filename);
  519.             $cab->setIsFinalizada(true);
  520.             $status $this->createStatus($cab'PROCESANDO'$this->getUser());
  521.         } else {
  522.             $cab->setIsFinalizada(false);
  523.             $status $this->createStatus($cab'PROGRAMADO'$this->getUser());
  524.         }
  525.         $entityManager->persist($status);
  526.         $entityManager->persist($cab);
  527.         $entityManager->flush();
  528.         if ($estadoinicial == 'EDICION') {
  529.             $url $this->adminUrlGenerator
  530.                 ->setController(CabeceraCrudController::class)
  531.                 ->setAction(Action::DETAIL)
  532.                 ->setEntityId($cab->getId())
  533.                 ->generateUrl();
  534.             return $this->redirect($url);
  535.         } else {
  536.             return $this->render('callcenter/finalizarpedido.html.twig', [
  537.                 'cabecera' => $cab
  538.             ]);
  539.         }
  540.     }
  541.     // #[Route('/hacerpedido/{id}', name: 'cc_hacerpedido')]
  542.     // public function generarxml(int $id, Xml $xml): response
  543.     // {
  544.     //     $cab = $this->doctrine
  545.     //         ->getRepository(Cabecera::class)
  546.     //         ->find($id);
  547.     //     $estadoinicial = $cab->getEstado();
  548.     //     if ($this->isReservation($cab) === false) {
  549.     //         $datetime['fecha'] = $cab->getUpdatedAt()->format('dm');
  550.     //         $datetime['hora'] = $cab->getUpdatedAt()->format('His');
  551.     //         $filename = substr($cab->getSucursal(), 0, 3) . $datetime['fecha'] . $datetime['hora'] . '-' . $cab->getId();
  552.     //         $cab->setFilename($filename);
  553.     //         $cab->setIsFinalizada(true);
  554.     //         $entityManager = $this->doctrine->getManager();
  555.     //         //log
  556.     //         $status = $this->createStatus($cab, 'PROCESANDO', $this->getUser());
  557.     //         $entityManager->persist($status);
  558.     //         //log
  559.     //         $entityManager->persist($cab);
  560.     //         $numlineas = 2;
  561.     //         foreach ($cab->getLineas() as $key => $linea) {
  562.     //             if ($linea->getParent() == null) {
  563.     //                 $numlineas++;
  564.     //             }
  565.     //         }
  566.     //         $xmlText = $xml->generarXml($cab, $datetime, $numlineas, $filename);
  567.     //         // SIRVE PARA GUARDAR EL ARCHIVO EN PUBLIC/UPLOADS*****
  568.     //         $filenameext = $filename . '.xml';
  569.     //         $path1 = $this->getParameter('kernel.project_dir') . '/public/uploads/' . $filenameext;
  570.     //         $path2 = $this->getParameter('kernel.project_dir') . '/public/respaldoXML/' . $filenameext;
  571.     //         $fileSystem = new Filesystem();
  572.     //         $fileSystem->dumpFile($path1, $xmlText);
  573.     //         $fileSystem->dumpFile($path2, $xmlText);
  574.     //     } else {
  575.     //         $cab->setIsFinalizada(false);
  576.     //         $entityManager = $this->doctrine->getManager();
  577.     //         //log
  578.     //         $status = $this->createStatus($cab, 'PROGRAMADO', $this->getUser());
  579.     //         $entityManager->persist($status);
  580.     //         //log
  581.     //         $entityManager->persist($cab);
  582.     //     }
  583.     //     $entityManager->flush();
  584.     //     if ($estadoinicial == 'EDICION') {
  585.     //         $url = $this->adminUrlGenerator
  586.     //             ->setController(CabeceraCrudController::class)
  587.     //             ->setAction(Action::DETAIL)
  588.     //             ->setEntityId($cab->getId())
  589.     //             ->generateUrl();
  590.     //         return $this->redirect($url);
  591.     //     } else {
  592.     //         return $this->render('callcenter/finalizarpedido.html.twig', [
  593.     //             'cabecera' => $cab
  594.     //         ]);
  595.     //     }
  596.     // }
  597.     #[Route('/confirmarpedido/{id}'name'cc_confirmarpedido')]
  598.     public function confirmarpedido(int $idRequest $requestGlobalPayService $globalPayService): response
  599.     {
  600.         $cab $this->doctrine
  601.             ->getRepository(Cabecera::class)
  602.             ->find($id);
  603.         $form $this->createForm(Cabecera2Type::class, $cab);
  604.         $form->handleRequest($request);
  605.         if ($form->isSubmitted() && $form->isValid()) {
  606.             $cab $form->getData();
  607.             $propinatotal $cab->getPropinatotal();
  608.             if (is_numeric($propinatotal) && $propinatotal 0) {
  609.                 $cab->setPropinatotal(floor($propinatotal 100) * 100);
  610.             } else {
  611.                 $cab->setPropinatotal(0);
  612.                 $cab->setPropinaporcentaje(0);
  613.             }
  614.             if ((int) $cab->getMetododepago() === (int) Cabecera::PAY_METHOD['CALL CENTER PREPAGADA']) {
  615.                 $data $globalPayService->prepareGlobalpayData([
  616.                     'nifcliente' => $cab->getNifcliente(),
  617.                     'emailcliente' => $cab->getEmailLinkdepago(),
  618.                     'nombres' => $cab->getNombres(),
  619.                     'apellidos' => ($cab->getApellidos() === null or $cab->getApellidos() === '') ? '_' $cab->getApellidos(),
  620.                     'id' => $cab->getId(),
  621.                     'total' => $cab->getTotal() + $cab->getPropinatotal(),
  622.                     'totalsiniva' => $cab->getTotalsiniva(),
  623.                     'sucursal' => $cab->getSucursal(),
  624.                 ]);
  625.                 $response $globalPayService->enviarDatos($data);
  626.                 $content json_decode($response['content'], true);
  627.                 $cab->setLinkdepago($content['data']['payment']['payment_url']);
  628.                 $entityManager $this->doctrine->getManager();
  629.                 $entityManager->persist($cab);
  630.                 $entityManager->flush();
  631.                 return $this->redirectToRoute('cc_linkdepago', [
  632.                     'id' => $cab->getId()
  633.                 ]);
  634.             }
  635.             $entityManager $this->doctrine->getManager();
  636.             $entityManager->persist($cab);
  637.             $entityManager->flush();
  638.             return $this->redirectToRoute('cc_hacerpedido', [
  639.                 'id' => $cab->getId()
  640.             ]);
  641.         }
  642.         return $this->render('callcenter/confirmarpedido.html.twig', [
  643.             'cabecera' => $cab,
  644.             'form' => $form->createView(),
  645.         ]);
  646.     }
  647.     #[Route('/linkdepago/{id}'name'cc_linkdepago')]
  648.     public function linkdepago(int $idRequest $requestMailerService $mailerService): response
  649.     {
  650.         $entityManager $this->doctrine->getManager();
  651.         $cabecera $entityManager->getRepository(Cabecera::class)->find($id);
  652.         if (!$cabecera) {
  653.             // Manejar el caso de que la cabecera no se encuentre
  654.             $this->addFlash('error''No se encontró el pedido solicitado.');
  655.             return $this->redirectToRoute('call_center');
  656.         }
  657.         if ($cabecera->getEmailLinkdepago() === null) {
  658.             $cabecera->setEmailLinkdepago($cabecera->getEmailcliente() ?? '');
  659.         }
  660.         // $estado = $entityManager->getRepository(CabeceraLinkdepago::class)->findOneBy(
  661.         //     ['Cabecera' => $cabecera->getId()],
  662.         //     ['createdAt' => 'DESC']
  663.         // );
  664.         $form $this->createForm(CabeceraEmailLinkdepagoType::class, $cabecera);
  665.         $form->handleRequest($request);
  666.         if ($form->isSubmitted() && $form->isValid()) {
  667.             $config $entityManager->getRepository(Configuracion::class)->findOneBy([]);
  668.             try {
  669.                 $mailerService->sendEmail(
  670.                     $cabecera->getEmailLinkdepago(),
  671.                     "Crepes & Waffles - Tu link de pago seguro",
  672.                     "emails/linkdepago.html.twig",
  673.                     ['cabecera' => $cabecera'timeout' => $config->getLinkdepagoTimeout() ?? 5],
  674.                 );
  675.             } catch (\Exception $e) {
  676.                 $this->addFlash('notice''No se pudo enviar el correo: ' $e->getMessage());
  677.                 return $this->render('callcenter/linkdepago.html.twig', [
  678.                     'cabecera' => $cabecera,
  679.                     'estado' => null,
  680.                     'form' => $form->createView(),
  681.                 ]);
  682.             }
  683.             $cabecera $form->getData();
  684.             // $entityManager->persist($cabecera);
  685.             $entityManager->flush();
  686.             return $this->redirectToRoute('cc_enespera');
  687.             // return $this->redirectToRoute('cc_hacerpedido', ['id' => $cabecera->getId()]);
  688.         }
  689.         return $this->render('callcenter/linkdepago.html.twig', [
  690.             'cabecera' => $cabecera,
  691.             // 'estado' => $estado,
  692.             'estado' => null,
  693.             'form' => $form->createView(),
  694.         ]);
  695.     }
  696.     private function isReservation(Cabecera $cabecera): bool
  697.     {
  698.         if ($cabecera->getFechareserva() != null) {
  699.             //fecha actual mas el tiempo de preparacion
  700.             if ($cabecera->getTipodeservicio() ==  16) {
  701.                 $paramtimebc $this->getParameter('app.bc.horaclienterecoge');
  702.             } else {
  703.                 $paramtimebc $this->getParameter('app.bc.horareserva');
  704.             }
  705.             $time date("Y-m-d H:i:s"strtotime($paramtimebc ' minutes'));
  706.             //Si la fecha de reserva es mayor que $time, Sí es reserva
  707.             if ($cabecera->getFechareserva()->format('Y-m-d H:i:s') > $time) {
  708.                 // Es reserva
  709.                 return true;
  710.             } else {
  711.                 // No es reserva
  712.                 return false;
  713.             }
  714.         } else {
  715.             return false;
  716.         }
  717.     }
  718.     #[Route('/cambiarestado/{id}/{action}'name'cambiar_estado')]
  719.     public function cambiarEstado(int $id$action)
  720.     {
  721.         $cab $this->doctrine
  722.             ->getRepository(Cabecera::class)
  723.             ->find($id);
  724.         if (!$cab) {
  725.             throw $this->createNotFoundException(
  726.                 'Pedido no encontrado'
  727.             );
  728.         }
  729.         $entityManager $this->doctrine->getManager();
  730.         switch ($action) {
  731.             case 'cancelar':
  732.                 $status $this->createStatus($cab'CANCELADO'$this->getUser());
  733.                 $flash 'Pedido Cancelado';
  734.                 $cab->setIsFinalizada(true);
  735.                 $cab->setLinkdepago(null);
  736.                 $entityManager->persist($cab);
  737.                 break;
  738.             case 'anular':
  739.                 $status $this->createStatus($cab'ANULADO'$this->getUser());
  740.                 $flash 'Pedido anulado';
  741.                 $cab->setLinkdepago(null);
  742.                 $entityManager->persist($cab);
  743.                 break;
  744.         }
  745.         $entityManager->persist($status);
  746.         $entityManager->flush();
  747.         $url $this->adminUrlGenerator
  748.             ->setController(CabeceraCrudController::class)
  749.             ->setAction(Action::DETAIL)
  750.             ->setEntityId($id)
  751.             ->removeReferrer()
  752.             ->generateUrl();
  753.         $this->addFlash('success'$flash);
  754.         return $this->redirect($url);
  755.     }
  756. }
  757. // $ppk = $this->getParameter('kernel.project_dir') . '/public/uploads/idisftp.ppk';
  758. // $key = PublicKeyLoader::load(file_get_contents($ppk), $password = false);
  759. // $sftp = new SFTP('64.76.58.172', 222);
  760. // $sftp_login = $sftp->login('idisftp', $key);
  761. // if($sftp_login) {
  762. //     // return $this->render('default/test.html.twig', array(
  763. //     // 'path' => $sftp->exec('pwd'),
  764. //     // ));
  765. //     // $sftp->enablePTY();
  766. //     dd($sftp->nlist());
  767. //     dd($sftp->put('filename.remote', 'xxx'));
  768. // }
  769. // else throw new \Exception('Cannot login into your server !');