<?php
namespace App\Controller;
use App\Repository\FeCreDirCuotasRepository;
use App\Repository\FeParametrosRepository;
use App\Repository\FeSucursalesRepository;
use App\Repository\FeVenDetallesRepository;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\User;
class DefaultController extends AbstractController
{
/**
* @Route({
* "en": "/",
* "es": "/"
* }, name="home")
*/
public function indexAction(FeParametrosRepository $feParametrosRepository)
{
if($_ENV['SRI']=="INACTIVO"){
return $this->render('backend.html.twig', [
'parametros'=>null,
]);
}
$user = $this->getUser();
if (is_object($user)) {
if(in_array("SUPER_ADMINISTRADOR",$user->getRoles())) {
return $this->render('base.html.twig', [
'parametros'=>null,
]);
}else{
return $this->render('base.html.twig', [
'parametros'=>$feParametrosRepository->getParametrosByComercio($user->getComercio()->getId()),
]);
}
} else {
return $this->redirectToRoute('fos_user_security_login', ['_locale' => 'es']);
}
}
/** Cambia el idioma
* @Route("/cambia-idioma", name="default_cambia_idioma", methods={"POST","GET"})
*/
public function cambiaIdioma(Request $request)
{
$lang = $_POST['lang'];
$route = $_POST['route'];
$parameters = json_decode($_POST['parameters'],true);
unset($parameters['_locale']);
$parameters['_locale']=$lang;
return $this->redirectToRoute($route,$parameters);
}
/** Genera XLSX
* @Route("/exportar-xls", name="default_exportar_xls", methods={"POST"})
*/
public function exportarXls(FeSucursalesRepository $feSucursalesRepository, FeVenDetallesRepository $feVenDetallesRepository, FeCreDirCuotasRepository $creDirCuotasRepository): Response
{
$user = $this->getUser();
$spreadsheet = new Spreadsheet();
/* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
$data = json_decode($_POST['data']);
//dd($data);
$colNames = json_decode($_POST['colNames']);
$titulo = $_POST['titulo'];
if(isset($_POST['reporte'])) {
$reporte = $_POST['reporte'];
}else{
$reporte = "";
}
$sucursal = $feSucursalesRepository->find($_POST['sucursalId']);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle($titulo);
$sheet->setCellValue('A1', 'Comercio: '. $user->getComercio()->getComNomComercial());
if($sucursal){
$sheet->setCellValue('A2', 'Sucursal: '. $sucursal->getSucNomComercial());
}else{
$sheet->setCellValue('A2', 'Sucursal: Todas');
}
$sheet->setCellValue('A3', 'Fecha Reporte: '. date('Y-m-d'));
$line = 4;
$col = "A";
for($i=0;$i<count($colNames);$i++){
$sheet->setCellValue($col . $line, $colNames[$i]);
$sheet->getColumnDimension($col)->setAutoSize(true);
$col++;
}
$sheet->mergeCells('A1:'.$col.'1');
$sheet->mergeCells('A2:'.$col.'2');
$sheet->mergeCells('A3:'.$col.'3');
$styleArray = array(
'borders' => array(
'allBorders' => array(
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => array('argb' => '000000'),
),
'outline' => array(
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
'color' => array('argb' => '000000'),
),
),
);
$sheet->getStyle('A1:'. $col . $line)->applyFromArray($styleArray)->getFont()->setBold( true );
$line++;
$col = "A";
foreach ($data as $row){
$row = (array)$row;
//dd($row);
unset($row['dataindex']);
$i=0;
foreach($row as $column){
if($i<count($colNames)){
$sheet->setCellValue($col . $line, $column);
$col++;
}
$i++;
}
$colC = $col;
$col = "A";
$line++;
//Detalle ventas
if($reporte == 'reporte_ventas_detalle'){
$col = "B";
$sheet->setCellValue($col . $line, "Detalle:");
$sheet->mergeCells($col.$line.':'.$colC.$line);
//echo $col.$line.':'.$colC.$line;
$sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBold( true );
$line++;
$sheet->setCellValue($col . $line, "Código:");
$col++;
$sheet->setCellValue($col . $line, "Nombre:");
$col++;
$sheet->setCellValue($col . $line, "Cantidad:");
$col++;
$sheet->setCellValue($col . $line, "Descuento:");
$col++;
$sheet->setCellValue($col . $line, "Subtotal:");
$col = "B";
$sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBold( true );
$line++;
$detalles = $feVenDetallesRepository->findBy(['ventas'=> $row['id']]);
foreach($detalles as $detalle) {
$sheet->setCellValue($col . $line, $detalle->getVenDetCodProducto());
$col++;
$sheet->setCellValue($col . $line, $detalle->getVenDetNomProducto());
$col++;
$sheet->setCellValue($col . $line, $detalle->getVenDetCantidad());
$col++;
$sheet->setCellValue($col . $line, $detalle->getVenDetDescuento());
$col++;
$sheet->setCellValue($col . $line, $detalle->getVenDetSubtotal());
$col = "B";
$sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBold( false );
$line++;
}
$line++;
$col = "A";
}
//Detalle creditos
if($reporte == 'reporte_creditos_detalle'){
$col = "B";
$sheet->setCellValue($col . $line, "Cuotas:");
$sheet->mergeCells($col.$line.':'.$colC.$line);
//echo $col.$line.':'.$colC.$line;
$sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBold( true );
$line++;
$sheet->setCellValue($col . $line, "Fecha Vencimiento:");
$col++;
$sheet->setCellValue($col . $line, "Valor Cuota:");
$col++;
$sheet->setCellValue($col . $line, "Valor Abonos:");
$col++;
$sheet->setCellValue($col . $line, "Valor Saldo:");
$col++;
$sheet->setCellValue($col . $line, "Estado:");
$col = "B";
$sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBold( true );
$line++;
$detalles = $creDirCuotasRepository->findBy(['credirecto'=>$row['id']]);
foreach($detalles as $detalle) {
$sheet->setCellValue($col . $line, $detalle->getCreDirCuoFecVencimiento());
$col++;
$sheet->setCellValue($col . $line, $detalle->getCreDirCuoValor());
$col++;
$sheet->setCellValue($col . $line, $detalle->getCreDirCuoAbono());
$col++;
$sheet->setCellValue($col . $line, $detalle->getCreDirCuoSaldo());
$col++;
$sheet->setCellValue($col . $line, $detalle->getCreDirCuoEstado());
$col = "B";
$sheet->getStyle($col.$line.':'.$colC.$line)->applyFromArray($styleArray)->getFont()->setBold( false );
$line++;
}
$line++;
$col = "A";
}
}
$line--;
//$sheet->getStyle('A5:'. $colC . $line)->applyFromArray($styleArray)->getFont()->setBold( false );
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
ob_start();
$writer->save("php://output");
$xlsData = ob_get_contents();
ob_end_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($xlsData)
);
// Return the excel file as an attachment
return new Response(json_encode($response),200, array('Content-Type' => 'application/json'));
}
/**
* autoriza pago.
*
* @Route("/AUTORIZA/autoriza-pago", name="user_autoriza_pago", methods={"GET", "POST"})
*/
public function acuPagoAction(Request $request)
{
date_default_timezone_set('America/Guayaquil');
////////////////////////////////////////////////////////////////////////////////// //AUTORIZACION
$facId = $_POST['facId'];
$tipoAmbiente = $this->container->getParameter('fac_ambiente');
$usuario = $this->container->getParameter('database_user');
$contrasena = $this->container->getParameter('database_password');
$servidor = $this->container->getParameter('database_host');
$basededatos = $this->container->getParameter('database_name');
$conexion = mysqli_connect( $servidor, $usuario, $contrasena ) or die ("No se ha podido conectar al servidor de Base de datos");
$db = mysqli_select_db( $conexion, $basededatos );
$sql = "Select * From utfacturas Where id = '". $facId ."'";
$resultado = mysqli_query( $conexion, $sql );
while($row = $resultado->fetch_assoc()) {
$rowsfac2[]=$row;
}
$factura = $rowsfac2;
//$factura = $resultado->fetch_all(MYSQLI_ASSOC);
$claveautorizacion = $factura[0]['FAC_CLAVE'];
$archivo = $ruta = 'facturas_generadas/'.$claveautorizacion.'.xml';
ini_set('soap.wsdl_cache_enabled', '1');
ini_set('soap.wsdl_cache_ttl', '1');
ini_set('default_socket_timeout', 600);
if ($tipoAmbiente == "1") {
$url = "https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline?wsdl";
} else if ($tipoAmbiente == "2") {
$url = "https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantesOffline?wsdl"; // AMBIENTE PRODUCCION ACTIVAR AL ESTAR SEGUROS
}
$stream_context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
$options = array(
'exceptions' => true,
'trace' => 1,
'stream_context' => $stream_context
);
$client = new \SoapClient($url, $options);
$x = array();
$x['xml'] = file_get_contents($ruta);
$result = "";
$result = $client->validarComprobante($x);
//unlink("comprobante.xml");
$array = json_decode(json_encode($result), True);
if (@$array['RespuestaRecepcionComprobante']['estado'] == "RECIBIDA") {
$mensaje = "El comprobante ha sido RECIBIDO";
$sql = "UPDATE utfacturas SET fac_estado = 'REC', fac_log = '". $mensaje ."' Where fac_clave = '". $claveautorizacion."'";
if(mysqli_query($conexion, $sql) === FALSE) {
$mensaje = "update".mysqli_error($conexion);
$conexion->close();
$response = json_encode($mensaje);
return new Response($response,200, array( 'Content-Type' => 'application/json' ));
}
} else {
if (@$array['RespuestaRecepcionComprobante']['estado'] == "DEVUELTA") {
if (@$array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['mensaje'] == "CLAVE ACCESO REGISTRADA") {
$mensaje = "Este comprobante ya ha sido enviado.";
} else {
$mensaje = $array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['mensaje'] . " -> " . $array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['informacionAdicional'];
//echo "<pre>"; print_r($result) ;echo "<pre>";
}
$sql = "UPDATE utfacturas SET fac_estado = 'DEV', fac_log = '". $mensaje."' Where fac_clave = '". $claveautorizacion."'";
if(mysqli_query($conexion, $sql) === FALSE) {
$mensaje = "update".mysqli_error($conexion);
$conexion->close();
$response = json_encode($mensaje);
return new Response($response,200, array( 'Content-Type' => 'application/json' ));
}
} else {
$sql = "UPDATE utfacturas SET fac_estado = 'ERR', fac_log = '". $array['RespuestaRecepcionComprobante']['estado'] ."' Where fac_clave = '". $claveautorizacion."'";
if(mysqli_query($conexion, $sql) === FALSE) {
$mensaje = "update".mysqli_error($conexion);
$conexion->close();
$response = json_encode($mensaje);
return new Response($response,200, array( 'Content-Type' => 'application/json' ));
}
$mensaje = $array['RespuestaRecepcionComprobante']['estado'];
}
$response = json_encode($mensaje);
return new Response($response, 200, array('Content-Type' => 'application/json'));
}
//VALIDAR LA AUTORIzACION DE LA FIRMA
if ($tipoAmbiente == "1") {
$urlAutorizacion = "https://celcer.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantesOffline?wsdl";
} else if ($tipoAmbiente == "2") {
$urlAutorizacion = "https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantesOffline?wsdl"; // AMBIENTE PRODUCCION ACTIVAR AL ESTAR SEGUROS
}
$client = new \SoapClient($urlAutorizacion, $options);
$peticion = array(
"autorizacionComprobante" => array(
"claveAccesoComprobante" => $claveautorizacion,
)
);
$resultAutorizacion = $client->__soapCall("autorizacionComprobante", $peticion);
// echo "<pre>"; print_r ($resultAutorizacion); echo "</pre>";
$array = json_decode(json_encode($resultAutorizacion), True);
if ($array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['estado'] == "AUTORIZADO") {
$mensaje = "El Comprobante ha sido AUTORIZADO";
//print_r ($resultAutorizacion->RespuestaAutorizacionComprobante);
//print "<pre>";print_r($resultAutorizacion);print "</pre>";
$doc = new \DOMDocument('1.0', 'UTF-8');
$root = $doc->createElement("autorizacion");
$doc->appendChild($root);
$estado = $doc->createElement("estado", $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['estado']);
$root->appendChild($estado);
$numeroAutorizacion = $doc->createElement("numeroAutorizacion", $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['numeroAutorizacion']);
$root->appendChild($numeroAutorizacion);
$fechaAutorizacion = $doc->createElement("fechaAutorizacion", $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['fechaAutorizacion']);
$root->appendChild($fechaAutorizacion);
$ambiente = $doc->createElement("ambiente", $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['ambiente']);
$root->appendChild($ambiente);
$prefijo = "<";
$posfijo = ">";
$comprobanteconcdata = htmlspecialchars($prefijo . "![CDATA[" . $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['comprobante'] . "]]" . $posfijo);
$comprobante = $doc->createElement("comprobante", $comprobanteconcdata);
$root->appendChild($comprobante);
if (!file_exists('facturas_autorizadas')) {
mkdir('facturas_autorizadas', 0755, true);
}
$doc->save("./facturas_autorizadas/" . $claveautorizacion . ".xml");
$sql = "UPDATE utfacturas SET fac_estado = 'AUT', fac_est_migracion = 'AUT', fac_log = '". $mensaje."' Where fac_clave = '" . $claveautorizacion . "'";
if (mysqli_query($conexion, $sql) === FALSE) {
$mensaje = "update" . mysqli_error($conexion);
$conexion->close();
$response = json_encode($mensaje);
return new Response($response, 200, array('Content-Type' => 'application/json'));
}
} else {
$mensaje = $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['mensajes']['mensaje']['mensaje'] . " -> " . $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['mensajes']['mensaje']['informacionAdicional'];
$sql = "UPDATE utfacturas SET fac_estado = 'AUT - ERR', fac_log = '". $mensaje."' Where fac_clave = '" . $claveautorizacion . "'";
if (mysqli_query($conexion, $sql) === FALSE) {
$mensaje = "update" . mysqli_error($conexion);
$conexion->close();
$response = json_encode($mensaje);
return new Response($response, 200, array('Content-Type' => 'application/json'));
}
}
////////////////////////////////////////////////////////////////////////////////// //FIN AUTORIZACION
$response = json_encode($mensaje);
return new Response($response, 200, array('Content-Type' => 'application/json'));
}
}