src/Controller/ModComercio/Ventas/CuentasController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller\ModComercio\Ventas;
  3. use App\Entity\Catalogos\{EntidadFinancieraMedioPagoEstadoCuenta};
  4. use App\Entity\Comercio\{CuentaDatosComercioOrdenMenuReservaReservaOrdenMenu};
  5. use App\Entity\Contabilidad\{DatosFacturaNoUsuarioSistemaDescuentosDetallePagosPagosPagoCuentaPagoFidelizacionPagoReserva};
  6. use App\Entity\Documentos\DocumentosDetallePagos;
  7. use App\Entity\Fidelizacion\{CategoriaClienteCategoriaClientePersonaParametrosFidelizacionFidelizacion};
  8. use App\Entity\Karaoke\CancionesCuenta;
  9. use App\Entity\Persona\Persona;
  10. use App\Entity\Producto\Menu;
  11. use App\Entity\Seguridades\Usuario;
  12. use App\Service\{CacheServiceDocumentsService};
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Exception;
  17. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use Symfony\Component\HttpFoundation\{RequestResponseHeaderBag};
  20. use Symfony\Component\Security\Core\User\UserInterface;
  21. class CuentasController extends AbstractController {
  22.   private $em;
  23.   private $msgCreate;
  24.   private $msgUpdate;
  25.   private $msgDelete;
  26.   private $cache;
  27.   public function __construct(EntityManagerInterface $emCacheService $cache) {
  28.     date_default_timezone_set('America/Guayaquil');
  29.     $this->em $em;
  30.     $this->msgCreate "Registro creado exitosamente.";
  31.     $this->msgUpdate "Registro actualizado exitosamente.";
  32.     $this->msgDelete "Registro eliminado exitosamente.";
  33.     $this->cache $cache;
  34.   }
  35.   // * READ FUNCTIONS *
  36.   /*1-Apertura 2-Pendiente pago
  37.       3-Pagado 4-Reserva
  38.       5-Cancelado 6-Solicitud apertura cuenta
  39.     */
  40.     /**
  41.      * @Route("/getInitialCuentas", name="getInitialCuentas")
  42.      */
  43.     public function getInitialCuentas(Request $request) {
  44.       $this->cache->delete('excelListCuentas');
  45.       $filtro $request->request->get('filtro');
  46.       $estadoCuentas = ($filtro == "12") ? [12] : [46];
  47.       $datosComercio $this->em->getRepository(DatosComercio::class)->find(1);
  48.       $cuentas $this->em->getRepository(Cuenta::class)->findBy(['idEstadoCuenta' => $estadoCuentas], ['id' => 'DESC']);
  49.       if ($cuentas) :
  50.         foreach ($cuentas as $indice => $cuenta) {
  51.           $persona $cuenta->getIdUsuario()->getIdPersona();
  52.           $nombresApellidos "{$persona->getNombres()} {$persona->getApellidos()}";
  53.           $spanColor $this->getSpanColor($cuenta->getIdEstadoCuenta()->getNombre());
  54.           $valor $this->getPagosValorEnCuenta($cuenta->getId(), $datosComercio);
  55.           $isReserva = (bool) $this->em->getRepository(Reserva::class)->findOneBy(['idCuenta' => $cuenta->getId()]);
  56.           $isPagosParciales = (bool) $this->em->getRepository(PagoCuenta::class)->findOneBy(['idCuenta' => $cuenta->getId()]);
  57.           $list[] = [
  58.             'indice' => $indice 1,
  59.             'id' => $cuenta->getId(),
  60.             'idUsuario' => $cuenta->getIdUsuario()->getId(),
  61.             'codigoCuenta' => $cuenta->getCodigoCuenta(),
  62.             'nombresApellidos' => $nombresApellidos,
  63.             'numeroIdentificacion' => $persona->getNumeroIdentificacion(),
  64.             'mailPersonal' => $persona->getMailPersonal(),
  65.             'numeroMesa' => $cuenta->getNumeroMesa() ?? '',
  66.             'estadoCuenta' => $cuenta->getIdEstadoCuenta()->getNombre(),
  67.             'spanColor' => $spanColor,
  68.             'valor' => $valor,
  69.             'activa' => $cuenta->getActiva(),
  70.             'isReserva' => $isReserva,
  71.             'isPagosParciales' => $isPagosParciales,
  72.             'fechaApertura' => $cuenta->getFechaHoraAperturaString()
  73.           ];
  74.         }
  75.         $this->cache->add('excelListCuentas'$list);
  76.         return $this->json(['data' => $list], 200);
  77.       endif;
  78.       return $this->json(['data' => []], 200);
  79.     }
  80.     /**
  81.      * @Route("/getHistorialCuentas", name="getHistorialCuentas")
  82.      */
  83.     public function getHistorialCuentas(Request $request) {
  84.       $this->cache->delete('excelListCuentasHistorial');
  85.       $FI $request->request->get('FI''');
  86.       $FF $request->request->get('FF''');
  87.       $HI $request->request->get('HI''');
  88.       $HF $request->request->get('HF''');
  89.       if (empty($FI) && empty($FF) && empty($HI) && empty($HF)) :
  90.         $anio date('Y');  $mes date('m');
  91.         $dias date("d"mktime(000$mes 10$anio));
  92.         $fechaInicio "$anio-$mes-01";
  93.         $fechaFin "$anio-$mes-$dias";
  94.         $inicio = new \DateTime("$fechaInicio 00:00:00");
  95.         $fin = new \DateTime("$fechaFin 23:59:59");
  96.       else:
  97.         $fechaInicio $HI "$FI $HI:00" "$FI 00:00:00";
  98.         $fechaFin $HF "$FF $HF:00" "$FF 23:59:59";
  99.         $inicio = new \DateTime("$fechaInicio");
  100.         $fin = new \DateTime("$fechaFin");
  101.       endif;
  102.       $datosComercio $this->em->getRepository(DatosComercio::class)->find(1);
  103.       $cuentas $this->dqlQueryCuentas($inicio$fin$datosComercio);
  104.       $pagos $this->dqlQueryPagosCuentas($cuentas);
  105.       $descuentos $this->dqlQueryDescuentos($cuentas);
  106.       $pagoFidelizacion $this->dqlQueryPagoFidelizacion($cuentas);
  107.       $valCuentasPendientes $this->dqlQueryCuentasPendientes($inicio$fin$datosComercio->getIdPorcentajeIva()->getPorcentaje());
  108.       $this->cache->add('excelListCuentasHistorial'$cuentas);
  109.       return $this->json([
  110.         'data' => $cuentas,
  111.         'cuentas' => count($cuentas),
  112.         'valCuentasPendientes' => $valCuentasPendientes,
  113.         'efectivo' => $pagos['efectivo'],
  114.         'transferencia' => $pagos['transferencia'],
  115.         'descuentos' => $descuentos $pagoFidelizacion,
  116.         'total' => doubleval($pagos['efectivo'] + $pagos['transferencia'])
  117.       ], 200);
  118.     }
  119.     private function dqlQueryCuentas($fechaInicio$fechaFin$datosComercio)  {
  120.       $dql "SELECT cuenta FROM App\Entity\Comercio\Cuenta cuenta WHERE cuenta.fechaHoraApertura BETWEEN :fechaIn AND :fechaFi";
  121.       $params = ['fechaIn' => $fechaInicio->format('Y-m-d H:i:s')];
  122.       if ($fechaFin) :
  123.         $params['fechaFi'] = $fechaFin->format('Y-m-d H:i:s');
  124.       endif;
  125.       $dql .= " ORDER BY cuenta.fechaHoraApertura ASC";
  126.       $query $this->em->createQuery($dql)->setParameters($params);
  127.       $cuentas = [];
  128.       foreach ($query->getResult() as $cuenta) {
  129.         $cuentas $this->setArrayCuentas($cuentas$cuenta$datosComercio);
  130.       }
  131.       return $cuentas;
  132.     }
  133.     private function dqlQueryCuentasPendientes($fechaInicio$fechaFin$iva)  {
  134.       $dql "SELECT cuenta FROM App\Entity\Comercio\Cuenta cuenta WHERE cuenta.idEstadoCuenta = :idEstadoCuenta AND cuenta.fechaHoraApertura BETWEEN :fechaIn AND :fechaFi";
  135.       $params = ['fechaIn' => $fechaInicio->format('Y-m-d H:i:s'), 'idEstadoCuenta' => 2];
  136.       if ($fechaFin) :
  137.         $params['fechaFi'] = $fechaFin->format('Y-m-d H:i:s');
  138.       endif;
  139.       $dql .= " ORDER BY cuenta.fechaHoraApertura ASC";
  140.       $query $this->em->createQuery($dql)->setParameters($params);
  141.       $valCuenta 0;
  142.       foreach ($query->getResult() as $cuenta) {
  143.         $ordenesMenu $this->em->getRepository(OrdenMenu::class)->findBy(['idCuenta' => $cuenta->getId(), 'cortesia' => false]);
  144.         if ($ordenesMenu) :
  145.           foreach ($ordenesMenu as $pedido) {
  146.             $valIva doubleval(($pedido->getPrecioUnitarioMenu() * $iva) / 100);
  147.             $total doubleval($valIva $pedido->getPrecioUnitarioMenu()) * $pedido->getCantidad();
  148.             $valCuenta $valCuenta $total;
  149.           }
  150.         endif;
  151.       }
  152.       return $valCuenta;
  153.     }
  154.     private function dqlQueryPagosCuentas($cuentas) {
  155.       $list = []; $efectivo 0$transferencia 0;
  156.       foreach ($cuentas as $cuenta) {
  157.         $qb $this->em->createQueryBuilder();
  158.         $qb
  159.           ->from(PagoCuenta::class, 'pc')
  160.           ->select('DISTINCT p.id AS idPago, p.valor')
  161.           ->join('pc.idPagos''p')
  162.           ->where('pc.idCuenta = :idCuenta')
  163.         ;
  164.         $resultado $qb->setParameter('idCuenta'$cuenta['id'])->getQuery()->getResult();
  165.         if ($resultado) :
  166.           foreach ($resultado as $item) {
  167.             $list[] = ['idPago' => $item['idPago']];
  168.           }
  169.         endif;
  170.       }
  171.       
  172.       foreach ($list as $pago) {
  173.         $detallePago $this->em->getRepository(DetallePagos::class)->findBy(['idPagos' => $pago['idPago']]);
  174.         foreach ($detallePago as $detalle) {
  175.           if ($detalle->getIdMedioPago()->getId() == 2) :
  176.             $efectivo $efectivo doubleval($detalle->getValor());
  177.           endif;
  178.           if ($detalle->getIdMedioPago()->getId() == 1) :
  179.             $transferencia $transferencia doubleval($detalle->getValor());
  180.           endif;
  181.         }
  182.       }
  183.       
  184.       return ['efectivo' => $efectivo'transferencia' => $transferencia];
  185.     }
  186.     private function dqlQueryDescuentos($cuentas) {
  187.       $list = []; $valorDescuento 0$descuentos = [];
  188.       foreach ($cuentas as $cuenta) {
  189.         $qb $this->em->createQueryBuilder();
  190.         $qb
  191.           ->from(PagoCuenta::class, 'pc')
  192.           ->select('DISTINCT p.id AS idPago, p.valor')
  193.           ->join('pc.idPagos''p')
  194.           ->where('pc.idCuenta = :idCuenta')
  195.         ;
  196.         $resultado $qb->setParameter('idCuenta'$cuenta['id'])->getQuery()->getResult();
  197.         if ($resultado) :
  198.           foreach ($resultado as $item) {
  199.             $list[] = ['idPago' => $item['idPago']];
  200.           }
  201.         endif;
  202.       }
  203.       foreach ($list as $pago) {
  204.         $descuento $this->em->getRepository(Descuentos::class)->findOneBy(['idPagos' => $pago['idPago']]);
  205.         if ($descuento) :
  206.           $descuentos[] = ['valor' => doubleval($descuento->getValor())];
  207.         endif;
  208.       }
  209.       foreach ($descuentos as $item) {
  210.         $valorDescuento += $item['valor'];
  211.       }
  212.       return $valorDescuento;
  213.     }
  214.     private function dqlQueryPagoFidelizacion($cuentas) {
  215.       $list = []; $fidelizacion 0;
  216.       foreach ($cuentas as $cuenta) {
  217.         $qb $this->em->createQueryBuilder();
  218.         $qb
  219.           ->from(PagoCuenta::class, 'pc')
  220.           ->select('DISTINCT p.id AS idPago, p.valor')
  221.           ->join('pc.idPagos''p')
  222.           ->where('pc.idCuenta = :idCuenta')
  223.         ;
  224.         $resultado $qb->setParameter('idCuenta'$cuenta['id'])->getQuery()->getResult();
  225.         if ($resultado) :
  226.           foreach ($resultado as $item) {
  227.             $list[] = ['idPago' => $item['idPago']];
  228.           }
  229.         endif;
  230.       }
  231.       foreach ($list as $pago) {
  232.         $fidelizacionQ $this->em->getRepository(PagoFidelizacion::class)->findOneBy(['idPagos' => $pago['idPago']]);
  233.         if ($fidelizacionQ) :
  234.           $fidelizacion $fidelizacion doubleval($fidelizacionQ->getValor());
  235.         endif;
  236.       }
  237.       return $fidelizacion;
  238.     }
  239.     private function setArrayCuentas($listCuenta $cuenta$datosComercio) {
  240.       $persona $cuenta->getIdUsuario()->getIdPersona();
  241.       $nombres mb_convert_encoding($persona->getNombres(), 'UTF-8''auto');
  242.       $apellidos mb_convert_encoding($persona->getApellidos(), 'UTF-8''auto');
  243.       $nombresApellidos "{$nombres} {$apellidos}";
  244.       $str_substr substr($this->quitarTildes($nombresApellidos), 020);
  245.       $nombresApellidosFinales "{$str_substr}...";
  246.       $spanColor $this->getSpanColor($cuenta->getIdEstadoCuenta()->getNombre());
  247.       $valor $this->getPagosValorEnCuenta($cuenta->getId(), $datosComercio);
  248.       $isReserva = (bool) $this->em->getRepository(Reserva::class)->findOneBy(['idCuenta' => $cuenta->getId()]);
  249.       $descuentos $this->getDescuentosCuenta($cuenta->getId());
  250.       $list[] = [
  251.         'id' => $cuenta->getId(),
  252.         'idUsuario' => $cuenta->getIdUsuario()->getId(),
  253.         'codigoCuenta' => $cuenta->getCodigoCuenta(),
  254.         'nombresApellidos' => $nombresApellidos,
  255.         'str_substr' => $nombresApellidosFinales,
  256.         'numeroIdentificacion' => $persona->getNumeroIdentificacion(),
  257.         'mailPersonal' => $persona->getMailPersonal(),
  258.         'numeroMesa' => $cuenta->getNumeroMesa() ?? '',
  259.         'estadoCuenta' => $cuenta->getIdEstadoCuenta()->getNombre(),
  260.         'idEstadoCuenta' => $cuenta->getIdEstadoCuenta()->getId(),
  261.         'spanColor' => $spanColor,
  262.         'valor' => $valor,
  263.         'activa' => $cuenta->getActiva(),
  264.         'isReserva' => $isReserva,
  265.         'fechaApertura' => $cuenta->getFechaHoraAperturaString(),
  266.         'fechaCierre' => $cuenta->getFechaHoraCierreString(),
  267.         'descuentos' => $descuentos,
  268.         'total' => $valor $descuentos
  269.       ];
  270.       return $list;
  271.     }
  272.     private function quitarTildes($cadena) {
  273.       $acentos = array('á''é''í''ó''ú''Á''É''Í''Ó''Ú''ñ''Ñ');
  274.       $sinAcentos = array('a''e''i''o''u''A''E''I''O''U''n''N');
  275.       return str_replace($acentos$sinAcentos$cadena);
  276.     }
  277.     private function getSpanColor($estadoCuenta) {
  278.       $colors = [
  279.         'Solicitud cuenta' => 'bg-secondary',
  280.         'Apertura cuenta' => 'bg-primary',
  281.         'Pendiente pago' => 'bg-warning text-dark',
  282.         'Pagado' => 'bg-success',
  283.         'Reserva' => 'bg-info text-dark',
  284.       ];
  285.       return $colors[$estadoCuenta] ?? 'bg-light text-dark';
  286.     }
  287.     public function getPagosValorEnCuenta($idCuenta$datosComercio) {
  288.       $ordenesMenus $this->em->getRepository(OrdenMenu::class)->findBy(['idCuenta' => $idCuenta]);
  289.       if (!$ordenesMenus) : return 0; endif;
  290.       $iva $datosComercio->getIdPorcentajeIva()->getPorcentaje();
  291.       return array_reduce($ordenesMenus, function ($valor$orden) use ($iva) {
  292.         if (!$orden->getCortesia() && $orden->getEstado() === 'Entregado') :
  293.           $pvp $orden->getPrecioUnitarioMenu() * ($iva 100);
  294.           return $valor + ($orden->getCantidad() * $pvp);
  295.         endif;
  296.         return $valor;
  297.       }, 0);
  298.     }
  299.     private function getDescuentosCuenta($idCuenta) {
  300.       $list = [];
  301.       $qb $this->em->createQueryBuilder();
  302.       $qb
  303.         ->from(PagoCuenta::class, 'pc')
  304.         ->select('DISTINCT p.id AS idPago, p.valor')
  305.         ->join('pc.idPagos''p')
  306.         ->where('pc.idCuenta = :idCuenta')
  307.       ;
  308.       $resultado $qb->setParameter('idCuenta'$idCuenta)->getQuery()->getResult();
  309.       if ($resultado) :
  310.         foreach ($resultado as $item) {
  311.           $list[] = ['idPago' => $item['idPago']];
  312.         }
  313.       endif;
  314.       return $this->calcularValoresFidelizacion($list);
  315.     }
  316.     private function calcularValoresFidelizacion($list) {
  317.       $valorDescuento 0$descuentos = [];
  318.       $valorFidelizacion 0$fidelizacions = [];
  319.       foreach ($list as $pago) {
  320.         $descuento $this->em->getRepository(Descuentos::class)->findOneBy(['idPagos' => $pago['idPago']]);
  321.         if ($descuento) :
  322.           $descuentos[] = ['valor' => doubleval($descuento->getValor())];
  323.         endif;
  324.       }
  325.       foreach ($descuentos as $item) {
  326.         $valorDescuento += $item['valor'];
  327.       }
  328.       foreach ($list as $pago) {
  329.         $fidelizacion $this->em->getRepository(PagoFidelizacion::class)->findOneBy(['idPagos' => $pago['idPago']]);
  330.         if ($fidelizacion) :
  331.           $fidelizacions[] = ['valor' => doubleval($fidelizacion->getValor())];
  332.         endif;
  333.       }
  334.       foreach ($fidelizacions as $item) {
  335.         $valorFidelizacion += $item['valor'];
  336.       }
  337.       
  338.       return $valorDescuento $valorFidelizacion;
  339.     }
  340.     /**
  341.          * @Route("/getInitialPagosCuenta", name="getInitialPagosCuenta")
  342.          */
  343.     public function getInitialPagosCuenta(Request $request) {
  344.       $idCuenta $request->request->get('id');
  345.       $reserva $this->em->getRepository(Reserva::class)->findOneBy(['idCuenta' => $idCuenta]);
  346.       $isReserva $reserva true false;
  347.       $ordenesMenu $this->em->getRepository(OrdenMenu::class)->findBy(['idCuenta' => $idCuenta'cortesia' => false'estado' => "Entregado"]);
  348.       $ordenesMenu $this->agrupaOrdenesMenu($ordenesMenu);
  349.       $valoresOrden $this->getValoresEnOrden($idCuenta);
  350.       $list = []; $valorPendiente 0;
  351.       foreach ($ordenesMenu as $orden) {
  352.         $menu $orden->getIdMenu();
  353.         $pu doubleval($orden->getPrecioUnitarioMenu());
  354.         $pagosMenu $this->getPagosEnMenu($valoresOrden['pagosCuenta'], $menu->getId(), $orden->getCantidad());
  355.         $valorPendiente += doubleval($orden->getPrecioUnitarioMenu() * $pagosMenu['cantidadPendiente']);
  356.         if ($pagosMenu['cantidadPendiente'] > 0) {
  357.           $list[] = [
  358.             'id' => $orden->getId(),
  359.             'nombre' => $menu->getNombre(),
  360.             'idMenu' => $menu->getId(),
  361.             'cantidad' => $orden->getCantidad(),
  362.             'pagado' => $pagosMenu['cantidadPagada'],
  363.             'pendiente' => $pagosMenu['cantidadPendiente'],
  364.             'pu' => $pu
  365.           ];
  366.         }
  367.       }
  368.       $pagos $this->getPagosCuenta($idCuenta$isReserva);
  369.       $pagosReserva $this->getPagosReserva($reserva$isReserva);
  370.       if ($valorPendiente == 0) : $this->cerrarCuenta($idCuenta); endif;
  371.       return $this->json([
  372.         'list' => $list,
  373.         'porCobrar' => $valorPendiente,
  374.         'pagos' => $pagos,
  375.         'pagosReserva' => $pagosReserva,
  376.         'isReserva' => $isReserva
  377.       ]);
  378.     }
  379.     private function agrupaOrdenesMenu($ordenesMenus) {
  380.       $ordenesAgrupadas = [];
  381.       foreach ($ordenesMenus as $orden) {
  382.         $menuId $orden->getIdMenu()->getId();
  383.         if (!isset($ordenesAgrupadas[$menuId])) :
  384.           $ordenesAgrupadas[$menuId] = clone $orden;
  385.         else:
  386.           $ordenesAgrupadas[$menuId]->setCantidad($ordenesAgrupadas[$menuId]->getCantidad() + $orden->getCantidad());
  387.         endif;
  388.       }
  389.       return array_values($ordenesAgrupadas);
  390.     }
  391.     private function getValoresEnOrden($idCuenta) {
  392.       $cantidadPagada 0;
  393.       $pagosCuenta $this->em->getRepository(PagoCuenta::class)->findBy(['idCuenta' => $idCuenta]);
  394.       foreach ($pagosCuenta as $pagos) {  $cantidadPagada += $pagos->getCantidadPagada(); }
  395.       return ['cantidadPagada' => $cantidadPagada'pagosCuenta' => $pagosCuenta];
  396.     }
  397.     private function getPagosEnMenu($pagosCuenta$idMenu$cantidad) {
  398.       $cantidadPagada array_reduce($pagosCuenta, function ($total$pagoCuenta) use ($idMenu) {
  399.         return $total + ($pagoCuenta->getIdMenu()->getId() === $idMenu $pagoCuenta->getCantidadPagada() : 0);
  400.       }, 0);
  401.       return [
  402.         'cantidadPagada' => $cantidadPagada,
  403.         'cantidadPendiente' => $cantidad $cantidadPagada
  404.       ];
  405.     }
  406.     private function getPagosCuenta($idCuenta$isReserva)  {
  407.       $pagos = [];
  408.       $pagoCuenta $this->em->getRepository(PagoCuenta::class)->findBy(['idCuenta' => $idCuenta]);
  409.       $resultado $this->unique_multidim_array($pagoCuenta);
  410.       foreach ($resultado as $pago) {
  411.         $persona $pago->getIdPagos()->getIdUsuario()->getIdPersona();
  412.         $nombresApellidos $persona->getNombres() . " " $persona->getApellidos();
  413.         $transferencia $this->getDetallePago($pago1);
  414.         $efectivo $this->getDetallePago($pago2);
  415.         $pagos[] = [
  416.           'idPagos' => $pago->getIdPagos()->getId(),
  417.           'idCuenta' => $pago->getIdCuenta()->getId(),
  418.           'idUsuario' => $pago->getIdPagos()->getIdUsuario()->getId(),
  419.           'codigoCuenta' => $pago->getIdCuenta()->getCodigoCuenta(),
  420.           'nombresApellidos' => $nombresApellidos,
  421.           'efectivo' => $efectivo,
  422.           'transferencia' => $transferencia,
  423.           'isReserva' => $isReserva,
  424.           'documentos' => ""
  425.         ];
  426.       }
  427.       return $pagos;
  428.     }
  429.     private function unique_multidim_array($array)  {
  430.       $uniqueObjects = [];  $seenIdPagos = [];
  431.       foreach ($array as $obj) {
  432.         $idPagos $obj->getIdPagos()->getId();
  433.         if (!in_array($idPagos$seenIdPagos)) :
  434.           $uniqueObjects[] = $obj;
  435.           $seenIdPagos[] = $idPagos;
  436.         endif;
  437.       }
  438.       return $uniqueObjects;
  439.     }
  440.     private function getDetallePago($pago$medioPagoId)  {
  441.       $detallePago $this->em->getRepository(DetallePagos::class)->findOneBy(['idPagos' => $pago->getIdPagos()->getId(), 'idMedioPago' => $medioPagoId]);
  442.       return $detallePago $detallePago->getValor() : 0;
  443.     }
  444.     private function getPagosReserva($reserva$isReserva)  {
  445.       $pagosReserva = [];
  446.       if ($reserva) :
  447.         $documentos = [];
  448.         $pagoReserva $this->em->getRepository(PagoReserva::class)->findBy(['idReserva' => $reserva->getId()]);
  449.         foreach ($pagoReserva as $pago) {
  450.           $transferencia $this->getDetallePago($pago1);
  451.           $efectivo $this->getDetallePago($pago2);
  452.           if ($transferencia) :
  453.             $documentosDetallesPagos $this->em->getRepository(DocumentosDetallePagos::class)->findBy(['idDetallePagos' => $transferencia->getId()]);
  454.             foreach ($documentosDetallesPagos as $documento) {
  455.               $documentos[] = [ 'url' => $documento->getIdCargaDocumento()->getUrl()  ];
  456.             }
  457.           endif;
  458.           $pagosReserva[] = [
  459.             'idPagos' => "",
  460.             'idCuenta' => "",
  461.             'idUsuario' => "",
  462.             'codigoCuenta' => "",
  463.             'nombresApellidos' => "Abono",
  464.             'efectivo' => $efectivo,
  465.             'transferencia' => $transferencia,
  466.             'isReserva' => $isReserva,
  467.             'documentos' => $documentos
  468.           ];
  469.         }
  470.       endif;
  471.       return $pagosReserva;
  472.     }
  473.     private function cerrarCuenta($idCuenta)  {
  474.       $cuenta $this->em->getRepository(Cuenta::class)->find($idCuenta);
  475.       $estadoCuenta $this->em->getRepository(EstadoCuenta::class)->find(3);
  476.       $cuenta->setActiva(false)
  477.         ->setIdEstadoCuenta($estadoCuenta)
  478.         ->setFechaHoraCierre(new \DateTime());
  479.       $this->em->persist($cuenta);
  480.       $this->em->flush();
  481.     }
  482.     /**
  483.      * @Route("/getFindUsuarioFacturacion", name="getFindUsuarioFacturacion")
  484.      */
  485.     public function getFindUsuarioFacturacion(Request $request) {
  486.       $list = [];
  487.       $personas $this->em->getRepository(Persona::class)->findBy([], ['apellidos' => 'ASC']);
  488.       foreach ($personas as $persona) {
  489.         $usuario $this->em->getRepository(Usuario::class)->findOneBy(['idPersona' => $persona->getId()]);
  490.         array_push($list, [
  491.           'apellidos' => $persona->getApellidos(),
  492.           'correoElectronico' => $persona->getMailPersonal(),
  493.           'id' => $persona->getId(),
  494.           'idUsuario' => $usuario->getId(),
  495.           'nombres' => $persona->getNombres(),
  496.           'nombresApellidos' => $persona->getNombres().' '.$persona->getApellidos(),
  497.           'numeroIdentificacion' => $persona->getNumeroIdentificacion(),
  498.           'sectorDireccion' => $persona->getDireccionSector(),
  499.           'telefono' => $persona->getTelCelular(),
  500.           'tipoIdentificacion' => $persona->getTipoIdentificacion(),
  501.           'tipoPersona' => 'NATURAL'
  502.         ]);
  503.       }
  504.       $personasOther $this->em->getRepository(DatosFacturaNoUsuarioSistema::class)->findBy([], ['apellidos' => 'ASC']);
  505.       foreach ($personasOther as $personaOther) {
  506.         array_push($list, [
  507.           'apellidos' => $personaOther->getApellidos(),
  508.           'correoElectronico' => $personaOther->getCorreoElectronico(),
  509.           'id' => $personaOther->getId(),
  510.           'idUsuario' => 0,
  511.           'nombres' => $personaOther->getNombre(),
  512.           'nombresApellidos' => $personaOther->getNombres().' '.$personaOther->getApellidos(),
  513.           'numeroIdentificacion' => $personaOther->getNumeroIdentificacion(),
  514.           'sectorDireccion' => $personaOther->getSectorDireccion(),
  515.           'telefono' => $personaOther->getTelefono(),
  516.           'tipoIdentificacion' => $personaOther->getTipoIdentificacion(),
  517.           'tipoPersona' => $personaOther->getTipoPersona()
  518.         ]);
  519.       }
  520.       return $this->json(['data' => $list], 200);
  521.     }
  522.     /**
  523.      * @Route("/getFindDetallePago", name="getFindDetallePago")
  524.      */
  525.     public function getFindDetallePago(Request $request) {
  526.       $list = [];
  527.       $idPagos $request->request->get('idPagos');
  528.       $datosComercio $this->em->getRepository(DatosComercio::class)->find(1);
  529.       $iva $datosComercio->getIdPorcentajeIva()->getPorcentaje();
  530.       $pagos $this->em->getRepository(Pagos::class)->find($idPagos);
  531.       $pagoCuenta $this->em->getRepository(PagoCuenta::class)->findBy(['idPagos' => $pagos->getId()]);
  532.       $count 1;
  533.       foreach ($pagoCuenta as $pago) {
  534.         $ordenMenu $this->em->getRepository(OrdenMenu::class)->findOneBy(['idCuenta' => $pago->getIdCuenta()->getId(), 'idMenu' => $pago->getIdMenu()->getId()]);
  535.         $vu $ordenMenu->getPrecioUnitarioMenu();
  536.         $ivaVal doubleval(($vu $iva) / 100);
  537.         $pvp doubleval($vu $ivaVal);
  538.         array_push($list, [
  539.           'nro' => $count,
  540.           'descripcion' => $ordenMenu->getIdMenu()->getNombre(),
  541.           'cantidad' => $pago->getCantidadPagada(),
  542.           'pvp' => round($pvp2)
  543.         ]);
  544.         $count++;
  545.       }
  546.       return $this->json($list200);
  547.     }
  548.     /**
  549.      * @Route("/getFindDetalleCuenta", name="getFindDetalleCuenta")
  550.      */
  551.     public function getFindDetalleCuenta(Request $request) {
  552.       $list = [];
  553.       $id $request->request->get('id');
  554.       $datosComercio $this->em->getRepository(DatosComercio::class)->find(1);
  555.       $iva $datosComercio->getIdPorcentajeIva()->getPorcentaje();
  556.       $ordenMenu $this->em->getRepository(OrdenMenu::class)->findBy(['idCuenta' => $id]);
  557.       foreach ($ordenMenu as $indice => $orden) {
  558.         $vu $orden->getPrecioUnitarioMenu();
  559.         $ivaVal doubleval(($vu $iva) / 100);
  560.         $pvp doubleval($vu $ivaVal);
  561.         array_push($list, [
  562.           'nro' => $indice 1,
  563.           'fechaPedido' => $orden->getFechaHoraPedidoString(),
  564.           'descripcion' => $orden->getIdMenu()->getNombre(),
  565.           'cantidad' => $orden->getCantidad(),
  566.           'pvp' => round($pvp2)
  567.         ]);
  568.       }
  569.       return $this->json($list200);
  570.     }
  571.     /**
  572.      * @Route("/getDisponibilidadMesa", name="getDisponibilidadMesa")
  573.      */
  574.     public function getDisponibilidadMesa(Request $request) {
  575.       $valor $request->request->get('valor');
  576.       $cuenta $this->em->getRepository(Cuenta::class)->findOneBy(['numeroMesa' => $valor'activa' => true]);
  577.       if ($cuenta) {
  578.         return $this->json(['response' => false'message' => 'La mesa ya se encuentra en uso']);
  579.       } else {
  580.         return $this->json(['response' => true]);
  581.       }
  582.     }
  583.     /**
  584.      * @Route("/getPagosCuentaHistorial", name="getPagosCuentaHistorial")
  585.      */
  586.     public function getPagosCuentaHistorial(Request $request) {
  587.       $idCuenta $request->request->get('id');
  588.       $qb $this->em->createQueryBuilder();
  589.       $qb->select('p')
  590.         ->from(PagoCuenta::class, 'p')
  591.         ->where('p.id IN (
  592.             SELECT MIN(p2.id)
  593.             FROM ' PagoCuenta::class . ' p2
  594.             INNER JOIN p2.idCuenta c2
  595.             WHERE c2.id = :idCuenta
  596.             GROUP BY p2.idPagos
  597.         )')
  598.         ->setParameter('idCuenta'$idCuenta);
  599.       $pagos $qb->getQuery()->getResult();
  600.       // Formatear resultados a JSON
  601.       $data = [];
  602.       foreach ($pagos as $pago) {
  603.         $efectivo 0$transferencia 0$documento "";
  604.         if ($pago->getIdPagos()) :
  605.           $detallePagos $this->em->getRepository(DetallePagos::class)->findBy(['idPagos' => $pago->getIdPagos()->getId()]);
  606.           foreach ($detallePagos as $detalle) {
  607.             if ($detalle->getIdMedioPago()->getId() == 1) :
  608.               $transferencia $detalle->getValor();
  609.               $documentosDetallePagos $this->em->getRepository(DocumentosDetallePagos::class)->findOneBy(['idDetallePagos' => $detalle->getId()]);
  610.               $documento $documentosDetallePagos->getIdCargaDocumento()->getUrl();
  611.             else:
  612.               $efectivo $detalle->getValor();
  613.             endif;
  614.           }
  615.         endif;
  616.         $data[] = [
  617.           'idPagoCuenta' => $pago->getId(),
  618.           'cantidadPagada' => $pago->getCantidadPagada(),
  619.           'idPagos' => $pago->getIdPagos() ? $pago->getIdPagos()->getId() : null,
  620.           'idMenu' => $pago->getIdMenu() ? $pago->getIdMenu()->getId() : null,
  621.           'idCuenta' => $pago->getIdCuenta() ? $pago->getIdCuenta()->getId() : null,
  622.           'efectivo' => $efectivo,
  623.           'transferencia' => $transferencia,
  624.           'documento' => $documento
  625.         ];
  626.       }
  627.       return $this->json($data200);
  628.     }
  629.   // * CREATE OR UPDATE FUNCTIONS *
  630.     /*1-Apertura 2-Pendiente pago
  631.       3-Pagado 4-Reserva
  632.       5-Cancelado 6-Solicitud apertura cuenta
  633.     */
  634.     /**
  635.      * @Route("/addPagosCuenta", name="addPagosCuenta")
  636.      */
  637.     public function addPagosCuenta(Request $requestUserInterface $userDocumentsService $documentsService) {
  638.       try {
  639.         $data $request->request->get('pagos_cuenta');
  640.         //return $this->json($data, 200);
  641.         $efectivo doubleval($data['efectivo']); $transferencia doubleval($data['transferencia']);
  642.         if ($data['pagosParcialesList'] == "[]") :
  643.           $ordersCuenta $this->getOrdersCuenta($data['idCuenta']);
  644.           $verify $this->em->getRepository(PagoCuenta::class)->findOneBy(['idCuenta' => $data['idCuenta']]);
  645.           $cuenta $this->em->getRepository(Cuenta::class)->find($data['idCuenta']);
  646.           $pagos $this->setDataPagos($efectivo$transferencia$cuenta->getIdUsuario(), $user$verify false true);
  647.           $this->em->persist($pagos);
  648.           foreach ($ordersCuenta as $orden) {
  649.             $pagoCuenta $this->setDataPagoCuenta($orden['idMenu'], $orden['cantidad'], $pagos$cuenta);
  650.             $this->em->persist($pagoCuenta);
  651.           }
  652.           if ($efectivo 0) :
  653.               $detallePagos $this->setDataDetallePagos(2$efectivo$pagos$user);
  654.               $this->em->persist($detallePagos);
  655.           endif;
  656.           if ($transferencia 0) :
  657.             $detallePagos $this->setDataDetallePagos(1$transferencia$pagos$user$data['entidadFinanciera']);
  658.             $this->em->persist($detallePagos);
  659.             if ($_FILES['pagos_cuenta']['error']['comprobante'][0] != 4) :
  660.               $this->setComprobantesPago($detallePagos$user$documentsService);
  661.             endif;
  662.           endif;
  663.         else:
  664.           $cuenta $this->em->getRepository(Cuenta::class)->find($data['idCuenta']);
  665.           if ($data['idUsuario'] == "" || $data['idUsuario'] == null) : return $this->json(['response' => false'message' => "Lo sentimos, debe ingresar un numero de identificación para el pago parcial"]); endif;
  666.           $usuario $this->em->getRepository(Usuario::class)->find($data['idUsuario']);
  667.           $pagos $this->setDataPagos($efectivo$transferencia$usuario$userfalse);
  668.           $this->em->persist($pagos);
  669.           $pagosParciales json_decode($data['pagosParcialesList'], true);
  670.           foreach ($pagosParciales as $orden) {
  671.             $pagoCuenta $this->setDataPagoCuenta($orden['idMenu'], $orden['cantidad'], $pagos$cuenta);
  672.             $this->em->persist($pagoCuenta);
  673.           }
  674.           if ($efectivo 0) :
  675.             $detallePagos $this->setDataDetallePagos(2$efectivo$pagos$user);
  676.             $this->em->persist($detallePagos);
  677.           endif;
  678.           if ($transferencia 0) :
  679.             $detallePagos $this->setDataDetallePagos(1$transferencia$pagos$user$data['entidadFinanciera']);
  680.             $this->em->persist($detallePagos);
  681.             if ($_FILES['pagos_cuenta']['error']['comprobante'][0] != 4) :
  682.               $this->setComprobantesPago($detallePagos$user$documentsService);
  683.             endif;
  684.           endif;
  685.         endif;
  686.         if ($data['descuento'] != "0.00" || $data['descuento'] != 0) :
  687.           $this->setDescuentos($data$pagos$user);
  688.         else:
  689.           $this->setFidelizacionUser($efectivo$transferencia$data$user$pagos);
  690.         endif;
  691.         $this->em->flush();
  692.         return $this->json(['response' => true'message' => $this->msgCreate]);
  693.       } catch (Exception $e) {
  694.         return $this->json(['response' => false'message' => "<b>{$e->getMessage()}</b> error al realizar el registro dentro de la petición <i>addPagosCuenta</i>"]);
  695.       }
  696.     }
  697.     private function getOrdersCuenta($id) {
  698.       $list = [];
  699.       $ordenMenu $this->em->getRepository(OrdenMenu::class)->findBy(['idCuenta' => $id'cortesia' => false'estado' => "Entregado"]);
  700.       foreach ($ordenMenu as $orden) :
  701.         $idMenu $orden->getIdMenu()->getId();
  702.         $pagosCuenta $this->em->getRepository(PagoCuenta::class)->findOneBy(['idCuenta' => $id'idMenu' => $idMenu]);
  703.         if ($pagosCuenta) :
  704.           if ($pagosCuenta->getCantidadPagada() != $orden->getCantidad()) :
  705.             $cantidadPagar $orden->getCantidad() - $pagosCuenta->getCantidadPagada();
  706.             array_push($list, [
  707.               'cantidad' => $cantidadPagar,
  708.               'id' => $orden->getId(),
  709.               'idCuenta' => $orden->getIdCuenta()->getId(),
  710.               'idMenu' => $orden->getIdMenu(),
  711.             ]);
  712.           endif;
  713.         else:
  714.           array_push($list, [
  715.             'cantidad' => $orden->getCantidad(),
  716.             'id' => $orden->getId(),
  717.             'idCuenta' => $orden->getIdCuenta()->getId(),
  718.             'idMenu' => $orden->getIdMenu(),
  719.           ]);
  720.         endif;
  721.       endforeach;
  722.       return $list;
  723.     }
  724.     private function setDataPagos($efectivo$transferencia$usuarioUserInterface $user$total) {
  725.       $pagos = new Pagos;
  726.       $valor round(doubleval($efectivo $transferencia), 2);
  727.       $pagos
  728.         ->setValor($valor)
  729.         ->setFechaHoraPago(new \DateTime())
  730.         ->setPagoTotal($total)
  731.         ->setIdUsuario($usuario)
  732.       ;
  733.       $pagos $this->setGenericData($user$pagos);
  734.       return $pagos;
  735.     }
  736.     private function setDataPagoCuenta($id$cantidad$pagos$cuenta) {
  737.       $pagoCuenta = new PagoCuenta;
  738.       $idMenu $this->em->getRepository(Menu::class)->find($id);
  739.       $pagoCuenta
  740.         ->setCantidadPagada($cantidad)
  741.         ->setIdPagos($pagos)
  742.         ->setIdMenu($idMenu)
  743.         ->setIdCuenta($cuenta)
  744.       ;
  745.       return $pagoCuenta;
  746.     }
  747.     private function setDataDetallePagos($id$valor$pagosUserInterface $user$entidadFinanciera "") {
  748.       $idMedioPago $this->em->getRepository(MedioPago::class)->find($id);
  749.       $detallePagos = new DetallePagos;
  750.       $detallePagos
  751.         ->setValor($valor)
  752.         ->setIdMedioPago($idMedioPago)
  753.         ->setIdPagos($pagos)
  754.       ;
  755.       if ($entidadFinanciera != "") :
  756.         $idEntidadFinanciera $this->em->getRepository(EntidadFinanciera::class)->find($entidadFinanciera);
  757.         $detallePagos->setIdEntidadFinanciera($idEntidadFinanciera);
  758.       endif;
  759.       $efectivoDetallePagos $this->setGenericData($user$detallePagos);
  760.       return $efectivoDetallePagos;
  761.     }
  762.     private function setComprobantesPago($transferencia_detallePagos$user$documentsService) {
  763.       $type $_FILES['pagos_cuenta']['type'];
  764.       $size $_FILES['pagos_cuenta']['size'];
  765.       $tmp_name $_FILES['pagos_cuenta']['tmp_name'];
  766.       $name $_FILES['pagos_cuenta']['name'];
  767.       $countComprobantes count($_FILES['pagos_cuenta']['name']['comprobante']);
  768.       if ($countComprobantes 0) :
  769.         for ($i 0$i $countComprobantes$i++) {
  770.           $comprobante $documentsService->getEstructureDocument($name['comprobante'][$i], $size['comprobante'][$i], $tmp_name['comprobante'][$i], $type['comprobante'][$i]);
  771.           $documentName $documentsService->flushDocument($comprobante"COMP_PAGO"'docs_directory');
  772.           $addDocument $documentsService->addDocument($comprobante$documentName"images/documents/$documentName"true$usernull);
  773.           $documentosDetallePagos = new DocumentosDetallePagos;
  774.           $documentosDetallePagos
  775.             ->setIdCargaDocumento($addDocument)
  776.             ->setIdDetallePagos($transferencia_detallePagos)
  777.           ;
  778.           $documentosDetallePagos $this->setGenericData($user$documentosDetallePagos);
  779.           $this->em->persist($documentosDetallePagos);
  780.         }
  781.       endif;
  782.     }
  783.     private function setFidelizacionUser($efectivo$transferencia$data$user$pago) {
  784.       $valor intval(doubleval($efectivo) + doubleval($transferencia));
  785.       $userId = ($data['pagosParcialesList'] === "[]")
  786.         ? $this->em->getRepository(Cuenta::class)->find($data['idCuenta'])->getIdUsuario()
  787.         : $this->em->getRepository(Usuario::class)->find($data['idUsuario']);
  788.       $dql "SELECT SUM(pagos.valor) FROM App\Entity\Contabilidad\Pagos pagos WHERE pagos.idUsuario = :userId";
  789.       $params = ['userId' => $userId->getId()];
  790.       $pagos $this->em->createQuery($dql)->setParameters($params);
  791.       $valAllPagos intval($pagos->getOneOrNullResult()[1]);
  792.       $newNivel null;
  793.       $persona $userId->getIdPersona();
  794.       $categoria_cliente_persona $this->em->getRepository(CategoriaClientePersona::class)->findOneBy(['activo' => true'idPersona' => $persona->getId()]);
  795.       $parametrosFidelizacion $categoria_cliente_persona->getIdCategoriaCliente()->getIdParametrosFidelizacion();
  796.       if ($categoria_cliente_persona->getIdCategoriaCliente()->getNivel() != 3) :
  797.         $baseSiguienteNivel $this->em->getRepository(CategoriaCliente::class)->findOneBy(['idParametrosFidelizacion' => $parametrosFidelizacion->getId(), 'nivel' => $categoria_cliente_persona->getIdCategoriaCliente()->getNivel() + 1]);
  798.         $baseCategoria intval($baseSiguienteNivel->getBase());
  799.         if ($valAllPagos $baseCategoria) :
  800.           $newNivel $categoria_cliente_persona->getIdCategoriaCliente()->getNivel() + 1;
  801.           $parametrosFidelizacionActivo $this->em->getRepository(ParametrosFidelizacion::class)->findOneBy(['activo' => true]);
  802.           $categoriaCliente $this->em->getRepository(CategoriaCliente::class)->findOneBy(['nivel' => $newNivel'idParametrosFidelizacion' => $parametrosFidelizacionActivo->getId()]);
  803.           $updateCategoria $this->em->getRepository(Persona::class)->find($persona->getId());
  804.           $updateCategoria->setIdCategoriaCliente($categoriaCliente);
  805.           $updateCategoria $this->setGenericData($user$updateCategoria);
  806.           $this->em->persist($updateCategoria);
  807.           $updateCategoriaClientePersona $this->em->getRepository(CategoriaClientePersona::class)->findOneBy(['idPersona' => $persona->getId()]);
  808.           $updateCategoriaClientePersona->setActivo(false);
  809.           $this->em->persist($updateCategoria);
  810.           $categoriaClientePersona = new CategoriaClientePersona;
  811.           $categoriaClientePersona $this->setCategoriaClientePersona  ($persona$categoriaClientePersona$user$newNivel);
  812.           $this->em->persist($categoriaClientePersona);
  813.         endif;
  814.       endif;
  815.       $categoria_cliente $categoria_cliente_persona->getIdCategoriaCliente();
  816.       $valor_fidelizacion floor($valor) * $parametrosFidelizacion->getValorDinero() * $categoria_cliente->getPuntosPorDolar();
  817.       $puntos_asignados $valor_fidelizacion $parametrosFidelizacion->getValorDinero();
  818.       if ($valor_fidelizacion != 0) :
  819.         $fidelizacion = new Fidelizacion;
  820.         $fidelizacion
  821.           ->setValor($valor_fidelizacion)
  822.           ->setPuntosAsignados($puntos_asignados)
  823.           ->setFechaRegistro(new \DateTime())
  824.           ->setIdPagos($pago)
  825.           ->setIdCategoriaCliente($categoria_cliente)
  826.         ;
  827.         $fidelizacion $this->setGenericData($user$fidelizacion);
  828.         $this->em->persist($fidelizacion);
  829.       endif;
  830.     }
  831.     private function setCategoriaClientePersona($persona$categoriaClientePersona$user$newNivel) {
  832.             $parametroFidelizacionActivo $this->em->getRepository(ParametrosFidelizacion::class)->findOneBy(['activo' => true]);
  833.             $categoriaClientePersona
  834.                 ->setFechaAsignacionCategoria(new \DateTime())
  835.                 ->setActivo(true)
  836.                 ->setIdCategoriaCliente($this->em->getRepository(CategoriaCliente::class)->findOneBy(['idParametrosFidelizacion' => $parametroFidelizacionActivo->getId(), 'nivel' => $newNivel]))
  837.                 ->setIdPersona($persona)
  838.                 ;
  839.             $categoriaClientePersona $this->setGenericData($user$categoriaClientePersona);
  840.             return $categoriaClientePersona;
  841.         }
  842.     private function setDescuentos($data$pago$user) {
  843.       if ($data['tipo_descuento'] == "fidelizacion") :
  844.         $pagoFidelizacion = new PagoFidelizacion;
  845.         $pagoFidelizacion
  846.           ->setValor($data['descuento'])
  847.           ->setObservacion($data['observacion'])
  848.           ->setIdPagos($pago)
  849.         ;
  850.         $pagoFidelizacion $this->setGenericData($user$pagoFidelizacion);
  851.         $this->em->persist($pagoFidelizacion);
  852.       else:
  853.         $descuentos = new Descuentos;
  854.         $descuentos
  855.           ->setPorcentaje($data['textDescuento'])
  856.           ->setValor($data['descuento'])
  857.           ->setObservacion($data['observacion'])
  858.           ->setIdPagos($pago)
  859.         ;
  860.         $descuentos $this->setGenericData($user$descuentos);
  861.         $this->em->persist($descuentos);
  862.       endif;
  863.     }
  864.     /**
  865.      * @Route("/setActivateCuentaUsuario", name="setActivateCuentaUsuario")
  866.      */
  867.     public function setActivateCuentaUsuario(UserInterface $userRequest $request) {
  868.       try {
  869.         $data $request->request->get('data');
  870.         $usuario $this->em->getRepository(Usuario::class)->findOneBy(['id' => $data['idUsuario']]);
  871.         $cuenta = new Cuenta();
  872.         /*1-Apertura 2-Pendiente pago
  873.           3-Pagado 4-Reserva
  874.           5-Cancelado 6-Solicitud apertura cuenta
  875.         */
  876.         $estadoCuenta $this->em->getRepository(EstadoCuenta::class)->find(1);
  877.         $codigoCuenta $this->generateCodigoCuenta($usuario);
  878.         $cuenta
  879.           ->setActiva(true)
  880.           ->setNumeroMesa($data['mesa'])
  881.           ->setIdEstadoCuenta($estadoCuenta)
  882.           ->setIdUsuario($usuario)
  883.           ->setCodigoCuenta($codigoCuenta)
  884.           ->setFechaHoraApertura(new \DateTime())
  885.         ;
  886.         $cuenta $this->setGenericData($user$cuenta);
  887.         $this->em->persist($cuenta);
  888.         $this->em->flush();
  889.         return $this->json(['response' => true'message' => $this->msgCreate]);
  890.       } catch (Exception $e) {
  891.         return $this->json(['response' => false'message' => "<b>{$e->getMessage()}</b> error al realizar el registro dentro de la petición <i>setActivateCuentaUsuario</i>"]);
  892.       }
  893.     }
  894.     /**
  895.      * @Route("/setActivacionCuenta", name="setActivacionCuenta")
  896.      */
  897.     public function setActivacionCuenta(UserInterface $userRequest $request) {
  898.       try {
  899.         $data $request->request->get('data');
  900.         $reserva $this->em->getRepository(Reserva::class)->findOneBy(['idCuenta' => $data['id']]);
  901.         if ($reserva) :
  902.           $reservaOrdenMenu $this->em->getRepository(ReservaOrdenMenu::class)->findOneBy(['idReserva' => $reserva->getId()]);
  903.           if (!$reservaOrdenMenu) :
  904.             return $this->json(['response' => false'message' => "Lo sentimos, no se puede activar por la reserva no cuenta con pedidos asignados."]);
  905.           endif;
  906.           $ordenMenu $this->em->getRepository(OrdenMenu::class)->findBy(['idCuenta' => $data['id']]);
  907.           foreach ($ordenMenu as $orden) {
  908.             $orden->setEstado("Confirmado");
  909.             $orden $this->setGenericData($user$orden);
  910.             $this->em->persist($orden);
  911.           }
  912.         endif;
  913.         $cuenta $this->em->getRepository(Cuenta::class)->find($data['id']);
  914.         $estadoCuenta $this->em->getRepository(EstadoCuenta::class)->find(1);
  915.         $cuenta
  916.           ->setActiva(true)
  917.           ->setNumeroMesa($data['mesa'])
  918.           ->setIdEstadoCuenta($estadoCuenta)
  919.         ;
  920.         $cuenta $this->setGenericData($user$cuenta);
  921.         $this->em->persist($cuenta);
  922.         $this->em->flush();
  923.         return $this->json(['response' => true'message' => $this->msgUpdate]);
  924.       } catch (Exception $e) {
  925.         return $this->json(['response' => false'message' => "<b>{$e->getMessage()}</b> error al realizar el registro dentro de la petición <i>setActivateCuentaUsuario</i>"]);
  926.       }
  927.     }
  928.     public function generateCodigoCuenta($user) {
  929.       $ci $user->getIdPersona()->getNumeroIdentificacion();
  930.       $cuentasUser $this->em->getRepository(Cuenta::class)->findBy(['idUsuario' => $user->getId()]);
  931.       $count $cuentasUser count($cuentasUser) : 0;
  932.       $count++;
  933.       $codigo "{$ci}_$count";
  934.       return $codigo;
  935.     }
  936.     private function setGenericData($user null$entity) {
  937.       $entity
  938.         ->setIdUsuarioModificacion($user != null $user->getId() : '1')
  939.         ->setFechaModificacion(new \DateTime())
  940.         ->setIpModificacion($_SERVER['REMOTE_ADDR'])
  941.       ;
  942.       return $entity;
  943.     }
  944.   // * DELETE FUNCTIONS *
  945.     /**
  946.      * @Route("/deleteCuenta", name="deleteCuenta")
  947.      */
  948.     public function deleteCuenta(Request $request) {
  949.       try {
  950.         $id $request->request->get('id');
  951.         $cuenta $this->em->getRepository(Cuenta::class)->find($id);
  952.         // * VALIDACIONES
  953.           $pagoCuenta $this->em->getRepository(PagoCuenta::class)->findOneBy(['idCuenta' => $id]);
  954.           if ($pagoCuenta) : return $this->json(['response' => false'exception' => false], 200); endif;
  955.           $reserva $this->em->getRepository(Reserva::class)->findOneBy(['idCuenta' => $id]);
  956.           if ($reserva) : return $this->json(['response' => false'exception' => false], 200); endif;
  957.           $ordenMenu $this->em->getRepository(OrdenMenu::class)->findOneBy(['idCuenta' => $id]);
  958.           if ($ordenMenu) : return $this->json(['response' => false'exception' => false], 200); endif;
  959.           $cancionesCuenta $this->em->getRepository(CancionesCuenta::class)->findOneBy(['idCuenta' => $id]);
  960.           if ($cancionesCuenta) : return $this->json(['response' => false'exception' => false], 200); endif;
  961.         $this->em->remove($cuenta);
  962.         $this->em->flush();
  963.         return $this->json(['response' => true'message' => $this->msgDelete'exception' => false], 200);
  964.       } catch (Exception $e) {
  965.         return $this->json(['response' => false'message' => "<b>{$e->getMessage()}</b> error al realizar el registro dentro de la petición <i>deleteCuenta</i>"'exception' => true]);
  966.       }
  967.     }
  968.   // * EXPORTS *
  969.     /**
  970.      * @Route("/getExcelCuentas", name="getExcelCuentas")
  971.      */
  972.     public function getExcelCuentas(){
  973.       $spreadsheet = new Spreadsheet();
  974.       $sheet $spreadsheet->getActiveSheet();
  975.       $sheet->setTitle("Cuentas");
  976.       $headers = ['id''cod. cuenta''nombres apellidos''nro. identificacion''correo''mesa''estado''valor''activa''reserva'];
  977.       $sheet->fromArray$headersNULL'A1' );
  978.       $lista $this->cache->get('excelListCuentas');
  979.       $lista = !$lista ? [] : $lista;
  980.       if(count($lista) != 0):
  981.         $data array_map(function ($cuenta) {
  982.           return [
  983.             $cuenta['id'],
  984.             $cuenta['codigoCuenta'],
  985.             $cuenta['nombresApellidos'],
  986.             $cuenta['numeroIdentificacion'],
  987.             $cuenta['mailPersonal'],
  988.             $cuenta['numeroMesa'],
  989.             $cuenta['estadoCuenta'],
  990.             round($cuenta['valor'], 2),
  991.             $cuenta['activa'] ? 'Sí' 'No',
  992.             $cuenta['isReserva'] ? 'Sí' 'No'
  993.           ];
  994.         }, $lista);
  995.       endif;
  996.       $sheet->fromArray($datanull'A2');
  997.       $writer = new Xlsx($spreadsheet);
  998.       $fileName 'cuentas.xlsx';
  999.       $temp_file tempnam(sys_get_temp_dir(), $fileName);
  1000.       $writer->save($temp_file);
  1001.       return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  1002.     }
  1003.     /**
  1004.      * @Route("/getExcelCuentasHistorial", name="getExcelCuentasHistorial")
  1005.      */
  1006.     public function getExcelCuentasHistorial(){
  1007.       $spreadsheet = new Spreadsheet();
  1008.       $sheet $spreadsheet->getActiveSheet();
  1009.       $sheet->setTitle("Cuentas");
  1010.       $headers = [
  1011.         'id',
  1012.         'cod',
  1013.         'f. apertura',
  1014.         'f. cierre',
  1015.         'nombres apellidos',
  1016.         'nro. identificacion',
  1017.         'mesa',
  1018.         'estado',
  1019.         'vcta',
  1020.         'dscto',
  1021.         'total'
  1022.       ];
  1023.       $sheet->fromArray$headersNULL'A1' );
  1024.       $lista $this->cache->get('excelListCuentasHistorial');
  1025.       $lista = !$lista ? [] : $lista;
  1026.       if(count($lista) != 0):
  1027.         $data array_map(function ($cuenta) {
  1028.           return [
  1029.             $cuenta['id'],
  1030.             $cuenta['codigoCuenta'],
  1031.             $cuenta['fechaApertura'],
  1032.             $cuenta['fechaCierre'],
  1033.             $cuenta['nombresApellidos'],
  1034.             $cuenta['numeroIdentificacion'],
  1035.             $cuenta['numeroMesa'],
  1036.             $cuenta['estadoCuenta'],
  1037.             round($cuenta['valor'], 2),
  1038.             round($cuenta['descuentos'], 2),
  1039.             round($cuenta['total'], 2)
  1040.           ];
  1041.         }, $lista);
  1042.       endif;
  1043.       $sheet->fromArray($datanull'A2');
  1044.       $writer = new Xlsx($spreadsheet);
  1045.       $fileName 'cuentas.xlsx';
  1046.       $temp_file tempnam(sys_get_temp_dir(), $fileName);
  1047.       $writer->save($temp_file);
  1048.       return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  1049.     }
  1050. }