src/Controller/DefaultController.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Repository\FeCreDirCuotasRepository;
  4. use App\Repository\FeParametrosRepository;
  5. use App\Repository\FeSucursalesRepository;
  6. use App\Repository\FeVenDetallesRepository;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\Response;
  11. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use App\Entity\User;
  15. class DefaultController extends AbstractController
  16. {
  17.     /**
  18.      * @Route({
  19.      *     "en": "/",
  20.      *     "es": "/"
  21.      * }, name="home")
  22.      */
  23.     public function indexAction(FeParametrosRepository $feParametrosRepository)
  24.     {
  25.         if($_ENV['SRI']=="INACTIVO"){
  26.             return $this->render('backend.html.twig', [
  27.                 'parametros'=>null,
  28.             ]);
  29.         }
  30.         $user $this->getUser();
  31.         if (is_object($user)) {
  32.             if(in_array("SUPER_ADMINISTRADOR",$user->getRoles())) {
  33.                 return $this->render('base.html.twig', [
  34.                     'parametros'=>null,
  35.                 ]);
  36.             }else{
  37.                 return $this->render('base.html.twig', [
  38.                     'parametros'=>$feParametrosRepository->getParametrosByComercio($user->getComercio()->getId()),
  39.                 ]);
  40.             }
  41.         } else {
  42.             return $this->redirectToRoute('fos_user_security_login', ['_locale' => 'es']);
  43.         }
  44.     }
  45.     /** Cambia el idioma
  46.      * @Route("/cambia-idioma", name="default_cambia_idioma", methods={"POST","GET"})
  47.      */
  48.     public function cambiaIdioma(Request $request)
  49.     {
  50.         $lang $_POST['lang'];
  51.         $route $_POST['route'];
  52.         $parameters json_decode($_POST['parameters'],true);
  53.         unset($parameters['_locale']);
  54.         $parameters['_locale']=$lang;
  55.         return $this->redirectToRoute($route,$parameters);
  56.     }
  57.     /** Genera XLSX
  58.      * @Route("/exportar-xls", name="default_exportar_xls", methods={"POST"})
  59.      */
  60.     public function exportarXls(FeSucursalesRepository $feSucursalesRepositoryFeVenDetallesRepository $feVenDetallesRepositoryFeCreDirCuotasRepository $creDirCuotasRepository): Response
  61.     {
  62.         $user $this->getUser();
  63.         $spreadsheet = new Spreadsheet();
  64.         /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  65.         $data json_decode($_POST['data']);
  66.         //dd($data);
  67.         $colNames json_decode($_POST['colNames']);
  68.         $titulo $_POST['titulo'];
  69.         if(isset($_POST['reporte'])) {
  70.             $reporte $_POST['reporte'];
  71.         }else{
  72.             $reporte "";
  73.         }
  74.         $sucursal $feSucursalesRepository->find($_POST['sucursalId']);
  75.         $sheet $spreadsheet->getActiveSheet();
  76.         $sheet->setTitle($titulo);
  77.         $sheet->setCellValue('A1''Comercio: '$user->getComercio()->getComNomComercial());
  78.         if($sucursal){
  79.             $sheet->setCellValue('A2''Sucursal: '$sucursal->getSucNomComercial());
  80.         }else{
  81.             $sheet->setCellValue('A2''Sucursal: Todas');
  82.         }
  83.         $sheet->setCellValue('A3''Fecha Reporte: 'date('Y-m-d'));
  84.         $line 4;
  85.         $col "A";
  86.         for($i=0;$i<count($colNames);$i++){
  87.             $sheet->setCellValue($col $line$colNames[$i]);
  88.             $sheet->getColumnDimension($col)->setAutoSize(true);
  89.             $col++;
  90.         }
  91.         $sheet->mergeCells('A1:'.$col.'1');
  92.         $sheet->mergeCells('A2:'.$col.'2');
  93.         $sheet->mergeCells('A3:'.$col.'3');
  94.         $styleArray = array(
  95.             'borders' => array(
  96.                 'allBorders' => array(
  97.                     'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  98.                     'color' => array('argb' => '000000'),
  99.                 ),
  100.                 'outline' => array(
  101.                     'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  102.                     'color' => array('argb' => '000000'),
  103.                 ),
  104.             ),
  105.         );
  106.         $sheet->getStyle('A1:'$col $line)->applyFromArray($styleArray)->getFont()->setBoldtrue );
  107.         $line++;
  108.         $col "A";
  109.         foreach ($data as $row){
  110.             $row = (array)$row;
  111.             //dd($row);
  112.             unset($row['dataindex']);
  113.             $i=0;
  114.             foreach($row as $column){
  115.                 if($i<count($colNames)){
  116.                     $sheet->setCellValue($col $line$column);
  117.                     $col++;
  118.                 }
  119.                 $i++;
  120.             }
  121.             $colC $col;
  122.             $col "A";
  123.             $line++;
  124.             //Detalle ventas
  125.             if($reporte == 'reporte_ventas_detalle'){
  126.                 $col "B";
  127.                 $sheet->setCellValue($col $line"Detalle:");
  128.                 $sheet->mergeCells($col.$line.':'.$colC.$line);
  129.                 //echo $col.$line.':'.$colC.$line;
  130.                 $sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBoldtrue );
  131.                 $line++;
  132.                 $sheet->setCellValue($col $line"Código:");
  133.                 $col++;
  134.                 $sheet->setCellValue($col $line"Nombre:");
  135.                 $col++;
  136.                 $sheet->setCellValue($col $line"Cantidad:");
  137.                 $col++;
  138.                 $sheet->setCellValue($col $line"Descuento:");
  139.                 $col++;
  140.                 $sheet->setCellValue($col $line"Subtotal:");
  141.                 $col "B";
  142.                 $sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBoldtrue );
  143.                 $line++;
  144.                 $detalles $feVenDetallesRepository->findBy(['ventas'=> $row['id']]);
  145.                 foreach($detalles as $detalle) {
  146.                     $sheet->setCellValue($col $line$detalle->getVenDetCodProducto());
  147.                     $col++;
  148.                     $sheet->setCellValue($col $line$detalle->getVenDetNomProducto());
  149.                     $col++;
  150.                     $sheet->setCellValue($col $line$detalle->getVenDetCantidad());
  151.                     $col++;
  152.                     $sheet->setCellValue($col $line$detalle->getVenDetDescuento());
  153.                     $col++;
  154.                     $sheet->setCellValue($col $line$detalle->getVenDetSubtotal());
  155.                     $col "B";
  156.                     $sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBoldfalse );
  157.                     $line++;
  158.                 }
  159.                 $line++;
  160.                 $col "A";
  161.             }
  162.             //Detalle creditos
  163.             if($reporte == 'reporte_creditos_detalle'){
  164.                 $col "B";
  165.                 $sheet->setCellValue($col $line"Cuotas:");
  166.                 $sheet->mergeCells($col.$line.':'.$colC.$line);
  167.                 //echo $col.$line.':'.$colC.$line;
  168.                 $sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBoldtrue );
  169.                 $line++;
  170.                 $sheet->setCellValue($col $line"Fecha Vencimiento:");
  171.                 $col++;
  172.                 $sheet->setCellValue($col $line"Valor Cuota:");
  173.                 $col++;
  174.                 $sheet->setCellValue($col $line"Valor Abonos:");
  175.                 $col++;
  176.                 $sheet->setCellValue($col $line"Valor Saldo:");
  177.                 $col++;
  178.                 $sheet->setCellValue($col $line"Estado:");
  179.                 $col "B";
  180.                 $sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBoldtrue );
  181.                 $line++;
  182.                 $detalles $creDirCuotasRepository->findBy(['credirecto'=>$row['id']]);
  183.                 foreach($detalles as $detalle) {
  184.                     $sheet->setCellValue($col $line$detalle->getCreDirCuoFecVencimiento());
  185.                     $col++;
  186.                     $sheet->setCellValue($col $line$detalle->getCreDirCuoValor());
  187.                     $col++;
  188.                     $sheet->setCellValue($col $line$detalle->getCreDirCuoAbono());
  189.                     $col++;
  190.                     $sheet->setCellValue($col $line$detalle->getCreDirCuoSaldo());
  191.                     $col++;
  192.                     $sheet->setCellValue($col $line$detalle->getCreDirCuoEstado());
  193.                     $col "B";
  194.                     $sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBoldfalse );
  195.                     $line++;
  196.                 }
  197.                 $line++;
  198.                 $col "A";
  199.             }
  200.         }
  201.         $line--;
  202.         //$sheet->getStyle('A5:'. $colC . $line)->applyFromArray($styleArray)->getFont()->setBold( false );
  203.         // Create your Office 2007 Excel (XLSX Format)
  204.         $writer = new Xlsx($spreadsheet);
  205.         ob_start();
  206.         $writer->save("php://output");
  207.         $xlsData ob_get_contents();
  208.         ob_end_clean();
  209.         $response =  array(
  210.             'op' => 'ok',
  211.             'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($xlsData)
  212.         );
  213.         // Return the excel file as an attachment
  214.         return new Response(json_encode($response),200, array('Content-Type' => 'application/json'));
  215.     }
  216.     /**
  217.      * autoriza pago.
  218.      *
  219.      * @Route("/AUTORIZA/autoriza-pago", name="user_autoriza_pago", methods={"GET", "POST"})
  220.      */
  221.     public function acuPagoAction(Request $request)
  222.     {
  223.         date_default_timezone_set('America/Guayaquil');
  224.         //////////////////////////////////////////////////////////////////////////////////        //AUTORIZACION
  225.         $facId $_POST['facId'];
  226.         $tipoAmbiente $this->container->getParameter('fac_ambiente');
  227.         $usuario $this->container->getParameter('database_user');
  228.         $contrasena $this->container->getParameter('database_password');
  229.         $servidor $this->container->getParameter('database_host');
  230.         $basededatos $this->container->getParameter('database_name');
  231.         $conexion mysqli_connect$servidor$usuario$contrasena ) or die ("No se ha podido conectar al servidor de Base de datos");
  232.         $db mysqli_select_db$conexion$basededatos );
  233.         $sql "Select * From utfacturas Where id = '"$facId ."'";
  234.         $resultado mysqli_query$conexion$sql );
  235.         while($row $resultado->fetch_assoc()) {
  236.             $rowsfac2[]=$row;
  237.         }
  238.         $factura $rowsfac2;
  239.         //$factura = $resultado->fetch_all(MYSQLI_ASSOC);
  240.         $claveautorizacion $factura[0]['FAC_CLAVE'];
  241.         $archivo $ruta 'facturas_generadas/'.$claveautorizacion.'.xml';
  242.         ini_set('soap.wsdl_cache_enabled''1');
  243.         ini_set('soap.wsdl_cache_ttl''1');
  244.         ini_set('default_socket_timeout'600);
  245.         if ($tipoAmbiente == "1") {
  246.             $url "https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline?wsdl";
  247.         } else if ($tipoAmbiente == "2") {
  248.             $url "https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline?wsdl"// AMBIENTE PRODUCCION ACTIVAR AL ESTAR SEGUROS
  249.         }
  250.         $stream_context stream_context_create([
  251.             'ssl' => [
  252.                 'verify_peer'       => false,
  253.                 'verify_peer_name'  => false,
  254.                 'allow_self_signed' => true
  255.             ]
  256.         ]);
  257.         $options = array(
  258.             'exceptions' => true,
  259.             'trace' => 1,
  260.             'stream_context' => $stream_context
  261.         );
  262.         $client = new \SoapClient($url$options);
  263.         $x = array();
  264.         $x['xml'] = file_get_contents($ruta);
  265.         $result "";
  266.         $result $client->validarComprobante($x);
  267.         //unlink("comprobante.xml");
  268.         $array json_decode(json_encode($result), True);
  269.         if (@$array['RespuestaRecepcionComprobante']['estado'] == "RECIBIDA") {
  270.             $mensaje "El comprobante ha sido RECIBIDO";
  271.             $sql "UPDATE utfacturas SET  fac_estado = 'REC', fac_log = '"$mensaje ."' Where fac_clave = '"$claveautorizacion."'";
  272.             if(mysqli_query($conexion$sql) === FALSE) {
  273.                 $mensaje "update".mysqli_error($conexion);
  274.                 $conexion->close();
  275.                 $response json_encode($mensaje);
  276.                 return new Response($response,200, array( 'Content-Type' => 'application/json' ));
  277.             }
  278.         } else {
  279.             if (@$array['RespuestaRecepcionComprobante']['estado'] == "DEVUELTA") {
  280.                 if (@$array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['mensaje'] == "CLAVE ACCESO REGISTRADA") {
  281.                     $mensaje "Este comprobante ya ha sido enviado.";
  282.                 } else {
  283.                     $mensaje $array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['mensaje'] . " -> " $array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['informacionAdicional'];
  284.                     //echo "<pre>"; print_r($result) ;echo "<pre>";
  285.                 }
  286.                 $sql "UPDATE utfacturas SET  fac_estado = 'DEV', fac_log = '"$mensaje."' Where fac_clave = '"$claveautorizacion."'";
  287.                 if(mysqli_query($conexion$sql) === FALSE) {
  288.                     $mensaje "update".mysqli_error($conexion);
  289.                     $conexion->close();
  290.                     $response json_encode($mensaje);
  291.                     return new Response($response,200, array( 'Content-Type' => 'application/json' ));
  292.                 }
  293.             } else {
  294.                 $sql "UPDATE utfacturas SET  fac_estado = 'ERR', fac_log = '"$array['RespuestaRecepcionComprobante']['estado'] ."'  Where fac_clave = '"$claveautorizacion."'";
  295.                 if(mysqli_query($conexion$sql) === FALSE) {
  296.                     $mensaje "update".mysqli_error($conexion);
  297.                     $conexion->close();
  298.                     $response json_encode($mensaje);
  299.                     return new Response($response,200, array( 'Content-Type' => 'application/json' ));
  300.                 }
  301.                 $mensaje $array['RespuestaRecepcionComprobante']['estado'];
  302.             }
  303.             $response json_encode($mensaje);
  304.             return new Response($response200, array('Content-Type' => 'application/json'));
  305.         }
  306.         //VALIDAR LA AUTORIzACION DE LA FIRMA
  307.         if ($tipoAmbiente == "1") {
  308.             $urlAutorizacion "https://celcer.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantesOffline?wsdl";
  309.         } else if ($tipoAmbiente == "2") {
  310.             $urlAutorizacion "https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantesOffline?wsdl"// AMBIENTE PRODUCCION ACTIVAR AL ESTAR SEGUROS
  311.         }
  312.         $client = new \SoapClient($urlAutorizacion$options);
  313.         $peticion = array(
  314.             "autorizacionComprobante" => array(
  315.                 "claveAccesoComprobante" => $claveautorizacion,
  316.             )
  317.         );
  318.         $resultAutorizacion $client->__soapCall("autorizacionComprobante"$peticion);
  319.         //    echo "<pre>"; print_r ($resultAutorizacion); echo "</pre>";
  320.         $array json_decode(json_encode($resultAutorizacion), True);
  321.         if ($array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['estado'] == "AUTORIZADO") {
  322.             $mensaje "El Comprobante ha sido AUTORIZADO";
  323.             //print_r ($resultAutorizacion->RespuestaAutorizacionComprobante);
  324.             //print "<pre>";print_r($resultAutorizacion);print "</pre>";
  325.             $doc = new \DOMDocument('1.0''UTF-8');
  326.             $root $doc->createElement("autorizacion");
  327.             $doc->appendChild($root);
  328.             $estado $doc->createElement("estado"$array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['estado']);
  329.             $root->appendChild($estado);
  330.             $numeroAutorizacion $doc->createElement("numeroAutorizacion"$array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['numeroAutorizacion']);
  331.             $root->appendChild($numeroAutorizacion);
  332.             $fechaAutorizacion $doc->createElement("fechaAutorizacion"$array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['fechaAutorizacion']);
  333.             $root->appendChild($fechaAutorizacion);
  334.             $ambiente $doc->createElement("ambiente"$array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['ambiente']);
  335.             $root->appendChild($ambiente);
  336.             $prefijo "<";
  337.             $posfijo ">";
  338.             $comprobanteconcdata htmlspecialchars($prefijo "![CDATA[" $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['comprobante'] . "]]" $posfijo);
  339.             $comprobante $doc->createElement("comprobante"$comprobanteconcdata);
  340.             $root->appendChild($comprobante);
  341.             if (!file_exists('facturas_autorizadas')) {
  342.                 mkdir('facturas_autorizadas'0755true);
  343.             }
  344.             $doc->save("./facturas_autorizadas/" $claveautorizacion ".xml");
  345.             $sql "UPDATE utfacturas SET  fac_estado = 'AUT', fac_est_migracion = 'AUT', fac_log = '"$mensaje."' Where fac_clave = '" $claveautorizacion "'";
  346.             if (mysqli_query($conexion$sql) === FALSE) {
  347.                 $mensaje "update" mysqli_error($conexion);
  348.                 $conexion->close();
  349.                 $response json_encode($mensaje);
  350.                 return new Response($response200, array('Content-Type' => 'application/json'));
  351.             }
  352.         } else {
  353.             $mensaje $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['mensajes']['mensaje']['mensaje'] . " -> " $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['mensajes']['mensaje']['informacionAdicional'];
  354.             $sql "UPDATE utfacturas SET  fac_estado = 'AUT - ERR', fac_log = '"$mensaje."' Where fac_clave = '" $claveautorizacion "'";
  355.             if (mysqli_query($conexion$sql) === FALSE) {
  356.                 $mensaje "update" mysqli_error($conexion);
  357.                 $conexion->close();
  358.                 $response json_encode($mensaje);
  359.                 return new Response($response200, array('Content-Type' => 'application/json'));
  360.             }
  361.         }
  362. //////////////////////////////////////////////////////////////////////////////////        //FIN AUTORIZACION
  363.         $response json_encode($mensaje);
  364.         return new Response($response200, array('Content-Type' => 'application/json'));
  365.     }
  366. }