<?php
namespace App\Controller;
use App\Entity\FeRetImpuestos;
use App\Entity\UtRetenciones;
use App\Form\UtRetencionesType;
use App\Repository\FeCajasRepository;
use App\Repository\FeComerciosRepository;
use App\Repository\FeRetImpuestosRepository;
use App\Repository\FeRetPorIvaRepository;
use App\Repository\FeRetPorRentaRepository;
use App\Repository\UtFacComprasRepository;
use App\Repository\UtRetencionesRepository;
use Dompdf\Options;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\DateTime;
use PHPMailer\PHPMailer\PHPMailer;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Dompdf\Dompdf;
/**
* @Route("/ut/retenciones")
*/
class UtRetencionesController extends AbstractController
{
/** CAMBIA DE ESTADO AL REGISTRO
*
* @Route("/cambia-estado-registro/{id}/{estado}", name="ut_retenciones_cambia_estado", methods={"GET"})
*/
public function cambiaEstado($id, $estado, UtRetencionesRepository $utRetencionesRepository): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$registro = $em->getRepository(UtRetenciones::class)->find($id);
$registro->setRetEstado($estado);
$em->persist($registro);
$em->flush();
return $this->render('ut_retenciones/index.html.twig', [
'ut_retenciones' => $utRetencionesRepository->getAll($user->getComercio()==null?'All':$user->getComercio()->getId())
]);
}
/**
* @Route("/", name="ut_retenciones_index", methods={"GET"})
*/
public function index(UtRetencionesRepository $utRetencionesRepository): Response
{
$user = $this->getUser();
return $this->render('ut_retenciones/index.html.twig', [
'ut_retenciones' => $utRetencionesRepository->getAll($user->getComercio()==null?'All':$user->getComercio()->getId())
]);
}
/**
* @Route("/new/{facComId}", name="ut_retenciones_new", methods={"GET","POST"})
*/
public function new(Request $request, $facComId, UtFacComprasRepository $utFacComprasRepository, FeRetPorIvaRepository $feRetPorIvaRepository,
FeRetPorRentaRepository $feRetPorRentaRepository, FeCajasRepository $feCajasRepository): Response
{
$utRetencione = new UtRetenciones();
$utRetencione->setFaccompras($utFacComprasRepository->find($facComId));
$form = $this->createForm(UtRetencionesType::class, $utRetencione);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$arreglo = $request->request->all();
//dd($arreglo);
$em = $this->getDoctrine()->getManager();
function generacionCodigoNumerico()
{
for( $i = 1; $i <= 8; $i++ ) {
$cod[$i] = rand(0, 9);
}
return implode( $cod );
}
function invertirCadena( $cadena ) {
$cadenaInvertida = "";
for ( $x = strlen( $cadena ) - 1; $x >= 0; $x-- ) {
$cadenaInvertida = $cadenaInvertida . substr( $cadena, $x, 1 );
}
return $cadenaInvertida;
}
function obtenerSumaPorDigitos( $cadena ) {
$pivote = 2;
$longitudCadena = strlen( $cadena );
$cantidadTotal = 0;
$b = 1;
for ( $i = 0; $i < $longitudCadena; $i++ ) {
if ( $pivote == 8 ) {
$pivote = 2;
}
//$temporal = intval(substr($cadena,$i, $b));
$temporal = intval( substr( $cadena, $i, 1 ) );
$b++;
$temporal = $temporal * $pivote;
$pivote++;
$cantidadTotal = $cantidadTotal + $temporal;
}
$cantidadTotal = 11 - $cantidadTotal % 11;
if ( $cantidadTotal == 11 )
$cantidadTotal = 0;
if ( $cantidadTotal == 10 )
$cantidadTotal = 1;
return $cantidadTotal;
}
if(isset($arreglo['retiva'])){
$impuesto = new FeRetImpuestos();
$impuesto->setRetenciones($utRetencione);
$impuesto->setRetImpBasImponible($arreglo['retIvaValor']);
$impuesto->setRetImpCodigo(2);
$impuesto->setRetImpCodRetencion($arreglo['retIvaCodigo']);
$impuesto->setRetImpCodSustento('01');
$impuesto->setRetImpFecEmiSustento($utRetencione->getFaccompras()->getFacComFecEmision());
$impuesto->setRetImpNumDocSustento($utRetencione->getFaccompras()->getFacComEstablecimiento().$utRetencione->getFaccompras()->getFacComPunEmision().$utRetencione->getFaccompras()->getFacComSecuencial());
$impuesto->setRetImpPorcentaje($arreglo['retIvaPorcentaje']);
$impuesto->setRetImpValRetenido(round($arreglo['retValor'] ,2));
$em->persist($impuesto);
}
if(isset($arreglo['retrenta'])){
$impuesto = new FeRetImpuestos();
$impuesto->setRetenciones($utRetencione);
$impuesto->setRetImpBasImponible($arreglo['retRenValor']);
$impuesto->setRetImpCodigo(1);
$impuesto->setRetImpCodRetencion($arreglo['retRenCodigo']);
$impuesto->setRetImpCodSustento('01');
$impuesto->setRetImpFecEmiSustento($utRetencione->getFaccompras()->getFacComFecEmision());
$impuesto->setRetImpNumDocSustento($utRetencione->getFaccompras()->getFacComEstablecimiento().$utRetencione->getFaccompras()->getFacComPunEmision().$utRetencione->getFaccompras()->getFacComSecuencial());
$impuesto->setRetImpPorcentaje($arreglo['retRenPorcentaje']);
$impuesto->setRetImpValRetenido(round($arreglo['renValor'] ,2));
$em->persist($impuesto);
}
$caja = $feCajasRepository->find($arreglo['retCajid']);
$ticNum = intval($caja->getCajNumRetencion()) + 1;
$caja->setCajNumRetencion($ticNum);
$em->persist($caja);
//GENERA CLAVE
$tipoAmbiente = $utRetencione->getFaccompras()->getSucursales()->getComercios()->getComAmbiente();
$codigoNumerico = generacionCodigoNumerico();
$fecha = (new \DateTime($utRetencione->getRetFecEmision()))->format('dmY');
$tipoComprobante = $utRetencione->getRetCodDoc();
$numRuc = $utRetencione->getRetRuc();
$serie = $utRetencione->getRetEstablecimiento().$utRetencione->getRetPunEmision();
$numeroComprobante = str_pad($ticNum, 9, "0", STR_PAD_LEFT);
$TipoEmision = $utRetencione->getRetTipEmision();
$codigoNume = "$fecha$tipoComprobante$numRuc$tipoAmbiente$serie$numeroComprobante$codigoNumerico$TipoEmision";
$claveautorizacion = "$codigoNume" . obtenerSumaPorDigitos( invertirCadena( $codigoNume ) );
//GUARDA LA RETENCION +
$utRetencione->setRetClave($claveautorizacion);
$utRetencione->setRetSecuencial($numeroComprobante);
$em->persist($utRetencione);
$em->flush();
if($utRetencione->getRetObligado() == 1){
$obligado = "SI";
}else{
$obligado = "NO";
}
//genera xml
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<comprobanteRetencion id="comprobante" version="1.0.0">
<infoTributaria>
<ambiente>'.$tipoAmbiente.'</ambiente>
<tipoEmision>1</tipoEmision>
<razonSocial>'.$utRetencione->getRetRazSocial().'</razonSocial>
<nombreComercial>'.$utRetencione->getRetNomComercial().'</nombreComercial>
<ruc>'.$utRetencione->getRetRuc().'</ruc>
<claveAcceso>'.$claveautorizacion.'</claveAcceso>
<codDoc>'.$utRetencione->getRetCodDoc().'</codDoc>
<estab>'.$utRetencione->getRetEstablecimiento().'</estab>
<ptoEmi>'.$utRetencione->getRetPunEmision().'</ptoEmi>
<secuencial>'.$numeroComprobante.'</secuencial>
<dirMatriz>'.$utRetencione->getRetDirMatriz().'</dirMatriz>
</infoTributaria>
<infoCompRetencion>
<fechaEmision>'. (new \DateTime($utRetencione->getRetFecEmision()))->format('d/m/Y') .'</fechaEmision>
<dirEstablecimiento>'.$utRetencione->getRetDirEstablecimiento().'</dirEstablecimiento>
<obligadoContabilidad>' . $obligado . '</obligadoContabilidad>
<tipoIdentificacionSujetoRetenido>'.$utRetencione->getRetTipIdeSujeto().'</tipoIdentificacionSujetoRetenido>
<razonSocialSujetoRetenido>'.$utRetencione->getRetRazSocSujeto().'</razonSocialSujetoRetenido>
<identificacionSujetoRetenido>'.$utRetencione->getRetIdeSujeto().'</identificacionSujetoRetenido>
<periodoFiscal>'.$utRetencione->getRetPerFiscal().'</periodoFiscal>
</infoCompRetencion>
<impuestos>';
if(isset($arreglo['retiva'])){
$xml .='
<impuesto>
<codigo>2</codigo>
<codigoRetencion>'. $arreglo['retIvaCodigo'] .'</codigoRetencion>
<baseImponible>'.$arreglo['retIvaValor'].'</baseImponible>
<porcentajeRetener>'.$arreglo['retIvaPorcentaje'].'</porcentajeRetener>
<valorRetenido>'.round($arreglo['retValor'] ,2).'</valorRetenido>
<codDocSustento>01</codDocSustento>
<numDocSustento>'.$utRetencione->getFaccompras()->getFacComEstablecimiento().$utRetencione->getFaccompras()->getFacComPunEmision().$utRetencione->getFaccompras()->getFacComSecuencial().'</numDocSustento>
<fechaEmisionDocSustento>'.(new \DateTime($utRetencione->getFaccompras()->getFacComFecEmision()))->format('d/m/Y').'</fechaEmisionDocSustento>
</impuesto>';
}
if(isset($arreglo['retrenta'])){
$xml .='
<impuesto>
<codigo>1</codigo>
<codigoRetencion>'. $arreglo['retRenCodigo'] .'</codigoRetencion>
<baseImponible>'.$arreglo['retRenValor'].'</baseImponible>
<porcentajeRetener>'.$arreglo['retRenPorcentaje'].'</porcentajeRetener>
<valorRetenido>'.round($arreglo['renValor'] ,2).'</valorRetenido>
<codDocSustento>01</codDocSustento>
<numDocSustento>'.$utRetencione->getFaccompras()->getFacComEstablecimiento().$utRetencione->getFaccompras()->getFacComPunEmision().$utRetencione->getFaccompras()->getFacComSecuencial().'</numDocSustento>
<fechaEmisionDocSustento>'.(new \DateTime($utRetencione->getFaccompras()->getFacComFecEmision()))->format('d/m/Y').'</fechaEmisionDocSustento>
</impuesto>';
}
$xml .='
</impuestos>
<infoAdicional>
<campoAdicional nombre="Email">'.$utRetencione->getRetCamAdiEmail().'</campoAdicional>
</infoAdicional>
</comprobanteRetencion>';
$doc = new \DOMDocument(1.0);
$doc->loadXML($xml);
$doc->saveXML();
$doc->save('retenciones_generadas/'.$claveautorizacion.'.xml');
////////////////////////////////////////////////////////////////////////////////// //FIRMA XML
function hex_to_base64( $hex ) {
$return = '';
foreach ( str_split( $hex, 2 ) as $pair ) {
$return .= chr( hexdec( $pair ) );
}
return base64_encode( $return );
}
function getModulo($utRetencione) {
//$numRuc = $_SESSION[ 'rucempresa' ];
$data = openssl_pkey_get_details( openssl_pkey_get_private( file_get_contents( "keys/".$utRetencione->getRetRuc()."/key.pem" ) ) );
$modulus = base64_encode( $data[ 'rsa' ][ 'n' ] );
return $modulus;
}
function getPublicKey($utRetencione) {
//$numRuc = $_SESSION[ 'rucempresa' ];
$data = file_get_contents( "keys/".$utRetencione->getRetRuc()."/cert.pem" );
$begin = "CERTIFICATE-----";
$end = "-----END";
$pem_data = substr( $data, strpos( $data, $begin ) + strlen( $begin ), strpos( $data, $end ) - ( strpos( $data, $begin ) + strlen( $begin ) ) );
return str_replace( "\n", "", $pem_data );
}
function pem2der( $pem_data ) {
$begin = "CERTIFICATE-----";
$end = "-----END";
$pem_data = substr( $pem_data, strpos( $pem_data, $begin ) + strlen( $begin ) );
$pem_data = substr( $pem_data, 0, strpos( $pem_data, $end ) );
$der = base64_decode( $pem_data );
return $der;
}
$pem_data = file_get_contents( "keys/".$utRetencione->getRetRuc()."/cert.pem" );
$pem2der = pem2der( $pem_data );
$ruta = 'retenciones_generadas/'.$claveautorizacion.'.xml';
$doc = new \DOMDocument(1.0);
$doc->load( $ruta, LIBXML_NOEMPTYTAG );
$root = $doc->getElementsByTagName( "comprobanteRetencion" )->item( 0 );
$x = $doc->getElementsByTagName( "comprobanteRetencion" )->item( 0 )->C14N();
$digestRef3 = hex_to_base64( sha1( $x ) );
$llavepublica = wordwrap( getPublicKey($utRetencione), 76, "\n", true );
$modulo = wordwrap( getModulo($utRetencione), 76, "\n", true );
$DigestValueCert = hex_to_base64( sha1( $pem2der ) );
$certdata = array();
$certdata = openssl_x509_parse( file_get_contents( "keys/".$utRetencione->getRetRuc()."/cert.pem" ), 0 );
$ds = "ds:";
$etsi = "etsi:";
function generateRandomNumber( $digits ) {
if ( $digits > 9 ) {
return generateRandomNumber( $digits - 9 ) . generateRandomNumber( 9 );
}
return "" . rand( pow( 10, $digits - 1 ), pow( 10, $digits ) - 1 );
}
$nombreIssuer = "CN=" . $certdata[ 'issuer' ][ 'commonName' ];
//$nombreIssuer .= ",L=".$certdata[ 'issuer' ][ 'localityName' ];
if(isset($certdata[ 'issuer' ][ 'localityName' ])){
$nombreIssuer .= ",L=".$certdata[ 'issuer' ][ 'localityName' ];
}else{
//if(isset($certdata[ 'subject' ][ 'localityName' ])){
// $nombreIssuer .= ",L=".$certdata[ 'subject' ][ 'localityName' ];
//}
}
$nombreIssuer .= ",OU=". $certdata[ 'issuer' ][ 'organizationalUnitName' ] . ",O=" . $certdata[ 'issuer' ][ 'organizationName' ] . ",C=" . $certdata[ 'issuer' ][ 'countryName' ];
$pos = strpos($certdata['issuer']['commonName'], 'ANF');
if($pos !== false) {
$nombreIssuer .= ",2.5.4.5=#130d31373932363031323135303031";
}
$pos = strpos($certdata['issuer']['commonName'], 'UANATACA');
if($pos !== false) {
$nombreIssuer .= ",2.5.4.97=#0c0f56415445532d413636373231343939";
}
$numerodeserie = $certdata[ 'serialNumber' ];
$CertificateNumber = generateRandomNumber( 7 );
$SignatureNumber = generateRandomNumber( 6 );
$SignedPropertiesNumber = generateRandomNumber( 5 );
$SignedInfoNumber = generateRandomNumber( 6 );
$SignedPropertiesIDNumber = generateRandomNumber( 6 );
$ReferenceIDNumber = generateRandomNumber( 6 );
$SignatureValueNumber = generateRandomNumber( 6 );
$ObjectNumber = generateRandomNumber( 6 );
$signature = $doc->createElement( $ds . "Signature" );
$signature->setAttribute( 'xmlns:ds', 'http://www.w3.org/2000/09/xmldsig#' );
$signature->setAttribute( 'xmlns:etsi', 'http://uri.etsi.org/01903/v1.3.2#' );
$signature->setAttribute( 'Id', 'Signature' . $SignatureNumber );
$root->appendChild( $signature );
$SignedInfo = $doc->createElement( $ds . "SignedInfo" );
$SignedInfo->setAttribute( 'Id', 'Signature-SignedInfo' . $SignedInfoNumber );
$signature->appendChild( $SignedInfo );
$CanonicalizationMethod = $doc->createElement( $ds . "CanonicalizationMethod" );
$CanonicalizationMethod->setAttribute( 'Algorithm', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315' );
$SignedInfo->appendChild( $CanonicalizationMethod );
$SignatureMethod = $doc->createElement( $ds . "SignatureMethod" );
$SignatureMethod->setAttribute( 'Algorithm', 'http://www.w3.org/2000/09/xmldsig#rsa-sha1' );
$SignedInfo->appendChild( $SignatureMethod );
$Reference1 = $doc->createElement( $ds . "Reference" );
$Reference1->setAttribute( 'Id', 'SignedPropertiesID' . $SignedPropertiesIDNumber );
$Reference1->setAttribute( 'Type', 'http://uri.etsi.org/01903#SignedProperties' );
$Reference1->setAttribute( 'URI', '#Signature' . $SignatureNumber . '-SignedProperties' . $SignedPropertiesNumber );
$SignedInfo->appendChild( $Reference1 );
$DigestMethod = $doc->createElement( $ds . "DigestMethod", '' );
$Reference1->appendChild( $DigestMethod );
$DigestMethod->setAttribute( 'Algorithm', 'http://www.w3.org/2000/09/xmldsig#sha1' );
$DigestValue1 = $doc->createElement( $ds . "DigestValue" );
$Reference1->appendChild( $DigestValue1 );
$Reference2 = $doc->createElement( $ds . "Reference" );
$Reference2->setAttribute( 'URI', '#Certificate' . $CertificateNumber );
$SignedInfo->appendChild( $Reference2 );
$DigestMethod = $doc->createElement( $ds . "DigestMethod", '' );
$DigestMethod->setAttribute( 'Algorithm', 'http://www.w3.org/2000/09/xmldsig#sha1' );
$Reference2->appendChild( $DigestMethod );
$DigestValue2 = $doc->createElement( $ds . "DigestValue" );
$Reference2->appendChild( $DigestValue2 );
$Reference3 = $doc->createElement( $ds . "Reference" );
$Reference3->setAttribute( 'Id', 'Reference-ID-' . $ReferenceIDNumber );
$Reference3->setAttribute( 'URI', '#comprobante' );
$SignedInfo->appendChild( $Reference3 );
$Transforms = $doc->createElement( $ds . "Transforms" );
$Reference3->appendChild( $Transforms );
$Transform = $doc->createElement( $ds . "Transform" );
$Transform->setAttribute( 'Algorithm', 'http://www.w3.org/2000/09/xmldsig#enveloped-signature' );
$Transforms->appendChild( $Transform );
$DigestMethod = $doc->createElement( $ds . "DigestMethod" );
$DigestMethod->setAttribute( 'Algorithm', 'http://www.w3.org/2000/09/xmldsig#sha1' );
$Reference3->appendChild( $DigestMethod );
$DigestValue3 = $doc->createElement( $ds . "DigestValue", $digestRef3 );
$Reference3->appendChild( $DigestValue3 );
//se acaba el signed info
$SignatureValue = $doc->createElement( $ds . "SignatureValue" );
$SignatureValue->setAttribute( 'Id', 'SignatureValue' . $SignatureValueNumber );
$signature->appendChild( $SignatureValue );
//SE acaba el valor de la firma
$KeyInfo = $doc->createElement( $ds . "KeyInfo" );
$KeyInfo->setAttribute( 'Id', 'Certificate' . $CertificateNumber );
$signature->appendChild( $KeyInfo );
$X509Data = $doc->createElement( $ds . "X509Data" );
$KeyInfo->appendChild( $X509Data );
$X509Certificate = $doc->createElement( $ds . "X509Certificate", "\n" . $llavepublica . "\n" );
$X509Data->appendChild( $X509Certificate );
$KeyValue = $doc->createElement( $ds . "KeyValue" );
$KeyInfo->appendChild( $KeyValue );
$RSAKeyValue = $doc->createElement( $ds . "RSAKeyValue" );
$KeyValue->appendChild( $RSAKeyValue );
$Modulus = $doc->createElement( $ds . "Modulus", "\n" . $modulo . "\n" );
$RSAKeyValue->appendChild( $Modulus );
$Exponent = $doc->createElement( $ds . "Exponent", "AQAB" );
$RSAKeyValue->appendChild( $Exponent );
$SignatureValue = $doc->getElementsByTagName( "SignatureValue" )->item( 0 );
//COMIENZA OBJECT
$doc->save( $ruta, LIBXML_NOEMPTYTAG );
$doc->load( $ruta, LIBXML_NOEMPTYTAG );
$Object = $doc->createElement( $ds . "Object" );
$Object->setAttribute( 'Id', 'Signature' . $SignatureNumber . '-Object' . $ObjectNumber );
$signature = $doc->getElementsByTagName( 'Signature' )->item( 0 );
$signature->appendChild( $Object );
$QualifyingProperties = $doc->createElement( $etsi . "QualifyingProperties" );
$QualifyingProperties->setAttribute( 'Target', '#Signature' . $SignatureNumber );
$Object->appendChild( $QualifyingProperties );
$SignedProperties = $doc->createElement( $etsi . "SignedProperties" );
$SignedProperties->setAttribute( 'Id', 'Signature' . $SignatureNumber . "-SignedProperties" . $SignedPropertiesNumber );
$QualifyingProperties->appendChild( $SignedProperties );
$SignedSignatureProperties = $doc->createElement( $etsi . "SignedSignatureProperties" );
$SignedProperties->appendChild( $SignedSignatureProperties );
$date = new \DateTime( "now", new \DateTimeZone( 'America/Guayaquil' ) );
$SigningTime = $doc->createElement( $etsi . "SigningTime", $date->format( 'c' ) );
$SignedSignatureProperties->appendChild( $SigningTime );
$SigningCertificate = $doc->createElement( $etsi . "SigningCertificate" );
$SignedSignatureProperties->appendChild( $SigningCertificate );
$Cert = $doc->createElement( $etsi . "Cert" );
$SigningCertificate->appendChild( $Cert );
$CertDigest = $doc->createElement( $etsi . "CertDigest" );
$Cert->appendChild( $CertDigest );
$DigestMethod = $doc->createElement( $ds . "DigestMethod" );
$DigestMethod->setAttribute( 'Algorithm', 'http://www.w3.org/2000/09/xmldsig#sha1' );
$CertDigest->appendChild( $DigestMethod );
$DigestValue = $doc->createElement( $ds . "DigestValue", $DigestValueCert );
$CertDigest->appendChild( $DigestValue );
$IssuerSerial = $doc->createElement( $etsi . "IssuerSerial" );
$Cert->appendChild( $IssuerSerial );
$X509IssuerName = $doc->createElement( $ds . "X509IssuerName", $nombreIssuer ); //CAMBIAR RAZON ESTATIOCOS
$IssuerSerial->appendChild( $X509IssuerName );
$X509SerialNumber = $doc->createElement( $ds . "X509SerialNumber", $numerodeserie ); //CAMBIAR RAZON ESTATIOCOS
$IssuerSerial->appendChild( $X509SerialNumber );
$SignedDataObjectProperties = $doc->createElement( $etsi . "SignedDataObjectProperties" );
$SignedProperties->appendChild( $SignedDataObjectProperties );
$DataObjectFormat = $doc->createElement( $etsi . "DataObjectFormat" );
$DataObjectFormat->setAttribute( "ObjectReference", "#Reference-ID-" . $ReferenceIDNumber );
$SignedDataObjectProperties->appendChild( $DataObjectFormat );
$SignedDataObjectProperties = $doc->createElement( $etsi . "Description", 'contenido comprobante' );
$DataObjectFormat->appendChild( $SignedDataObjectProperties );
$SignedDataObjectProperties = $doc->createElement( $etsi . "MimeType", 'text/xml' );
$DataObjectFormat->appendChild( $SignedDataObjectProperties );
if ( $doc->save( $ruta, LIBXML_NOEMPTYTAG ) ) {
$doc->preserveWhiteSpace = true;
$doc->formatOutput = false;
$doc->load( $ruta );
$primerDigestRef = hex_to_base64( sha1( $doc->getElementsByTagName( "SignedProperties" )->item( 0 )->C14N() ) );
$segundoDigestRef = hex_to_base64( sha1( $doc->getElementsByTagName( "KeyInfo" )->item( 0 )->C14N() ) );
$reference1 = $doc->getElementsByTagName( "Reference" )->item( 0 );
$DigestValue1 = $reference1->getElementsByTagName( "DigestValue" )->item( 0 );
$text = $doc->createTextNode( $primerDigestRef );
$text = $DigestValue1->appendChild( $text );
$reference2 = $doc->getElementsByTagName( "Reference" )->item( 1 );
$DigestValue2 = $reference2->getElementsByTagName( "DigestValue" )->item( 0 );
$text = $doc->createTextNode( $segundoDigestRef );
$text = $DigestValue2->appendChild( $text );
$doc->save( $ruta, LIBXML_NOEMPTYTAG );
$doc->load( $ruta );
// VALOR DE SignatureValue
$pkey = file_get_contents( "keys/".$utRetencione->getRetRuc()."/key.pem" );
openssl_sign( $doc->getElementsByTagName( "SignedInfo" )->item( 0 )->C14N(), $sigval, $pkey );
$valorFirma = wordwrap( base64_encode( $sigval ), 76, "\n", true );
$SignatureValue = $doc->getElementsByTagName( "SignatureValue" )->item( 0 );
$text = $doc->createTextNode( "\n" . $valorFirma . "\n" );
$text = $SignatureValue->appendChild( $text );
if ( $doc->save( $ruta, LIBXML_NOEMPTYTAG ) ) {
//GUARDA XML EN BD
$utRetencione->setRetEstado("FIRMADA");
$utRetencione->setRetXml(strval($doc->saveXML()));
$em->persist($utRetencione);
$em->flush();
}
}
////////////////////////////////////////////////////////////////////////////////// //FIN FIRMA XML
return $this->redirectToRoute('ut_retenciones_autorizacion',['id'=>$utRetencione->getId()]);
}
return $this->render('ut_retenciones/new.html.twig', [
'ut_retencione' => $utRetencione,
'fe_retiva' => $feRetPorIvaRepository->getByEstado(1),
'fe_retrenta' => $feRetPorRentaRepository->getByEstado(1),
'form' => $form->createView(),
'fe_cajas' => $feCajasRepository->getBySucursal($utFacComprasRepository->find($facComId)->getSucursales()->getId()),
'facCompra'=> $utFacComprasRepository->find($facComId),
'regDetalles' => $utFacComprasRepository->getRegDetalles($facComId)
]);
}
/**
* @Route("/{id}", name="ut_retenciones_show", methods={"GET"})
*/
public function show(UtRetenciones $utRetencione): Response
{
return $this->render('ut_retenciones/show.html.twig', [
'ut_retencione' => $utRetencione,
]);
}
/**
* @Route("/{id}/edit", name="ut_retenciones_edit", methods={"GET","POST"})
*/
public function edit(Request $request, UtRetenciones $utRetencione): Response
{
$form = $this->createForm(UtRetencionesType::class, $utRetencione);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('ut_retenciones_index');
}
return $this->render('ut_retenciones/edit.html.twig', [
'ut_retencione' => $utRetencione,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}", name="ut_retenciones_delete", methods={"DELETE"})
*/
public function delete(Request $request, UtRetenciones $utRetencione): Response
{
if ($this->isCsrfTokenValid('delete'.$utRetencione->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($utRetencione);
$entityManager->flush();
}
return $this->redirectToRoute('ut_retenciones_index');
}
/**
* proceso de autorizacion de comprobantes de retención
*
* @Route("/manual/autorizacion/{id}", name="ut_retenciones_autorizacion", methods={"GET"})
* @throws \SoapFault
*/
public function autorizacionAction(UtRetenciones $utRetencione, UtRetencionesRepository $utRetencionesRepository, FeComerciosRepository $feComerciosRepository): Response
{
date_default_timezone_set('America/Guayaquil');
$em = $this->getDoctrine()->getManager();
//$utFacturas = $em->getRepository('AppBundle:UtFacturas')->getFacPendientes();
//$ut = $utFacturasRepository->getFacPendientes();
//$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 );
$nombre_archivo = "logscron_retenciones.txt";
file_exists($nombre_archivo);
$log = fopen($nombre_archivo, "a+");
$mensaje = "inicio";
fwrite($log, "-------------". $mensaje. "\n");
fwrite($log, date("d-m-Y H:m:s"). "\n");
//foreach ($utFacturas as $factura) {
//$facId = $factura['id'];
//$utFactura = $utFacturasRepository->find($facId);
$impuestos = $utRetencione->getRetimpuestos();
fwrite($log, "\n id de retencion: ". $utRetencione->getId(). "\n");
$tipoAmbiente = $utRetencione->getFaccompras()->getSucursales()->getComercios()->getComAmbiente();
fwrite($log, "\n Ambiente: ". $tipoAmbiente. "\n");
$claveautorizacion = $utRetencione->getRetClave();
$ruta = 'retenciones_generadas/' . $claveautorizacion . '.xml';
ini_set('soap.wsdl_cache_enabled', '0');
ini_set('soap.wsdl_cache_ttl', '0');
ini_set('default_socket_timeout', 600);
if($utRetencione->getRetEstado() != 'RECIBIDA'){
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);
fwrite($log, "\n Resultado ValidarComprovante: ". json_encode($result). "\n");
$array = json_decode(json_encode($result), True);
$em->flush();
if (@$array['RespuestaRecepcionComprobante']['estado'] == "RECIBIDA") {
$mensaje = "El comprobante de retencion ha sido RECIBIDO";
$utRetencione->setRetEstado('RECIBIDA');
$utRetencione->setRetLog($mensaje);
$em->persist($utRetencione);
$em->flush();
fwrite($log, "\n Comprobante de Retención Recibido \n");
} else {
if (@$array['RespuestaRecepcionComprobante']['estado'] == "DEVUELTA") {
if (@$array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['mensaje'] == "CLAVE ACCESO REGISTRADA") {
$mensaje = "Este comprobante de retención ya ha sido enviado.";
} else {
$mensaje = $array['RespuestaRecepcionComprobante']['comprobantes']['comprobante']['mensajes']['mensaje']['mensaje'] ;
}
$utRetencione->setRetEstado('DEVUELTA');
$utRetencione->setRetLog($mensaje);
$em->persist($utRetencione);
$em->flush();
fwrite($log, "\n Comprobante de Retención Devuelto: ".$mensaje." \n");
} else {
$mensaje = $array['RespuestaRecepcionComprobante']['estado'];
$utRetencione->setRetEstado('ERROR');
$utRetencione->setRetLog($mensaje);
$em->persist($utRetencione);
$em->flush();
fwrite($log, "\n Comprobante de Retención Con Errores: ".$mensaje." \n");
}
$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
}
$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($urlAutorizacion, $options);
$peticion = array(
"autorizacionComprobante" => array(
"claveAccesoComprobante" => $claveautorizacion,
)
);
$resultAutorizacion = $client->__soapCall("autorizacionComprobante", $peticion);
$array = json_decode(json_encode($resultAutorizacion), True);
fwrite($log, "\n Despues de RECIBIDO".json_encode($array['RespuestaAutorizacionComprobante']['autorizaciones'])."\n");
if (isset($array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']) && $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['estado'] == "AUTORIZADO") {
$mensaje = "El Comprobante de Retención ha sido AUTORIZADO";
$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_decode($prefijo . "![CDATA[" . $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['comprobante'] . "]]" . $posfijo);
$comprobante = $doc->createElement("comprobante", $comprobanteconcdata);
$root->appendChild($comprobante);
if (!file_exists('retenciones_autorizadas')) {
mkdir('retenciones_autorizadas', 0755, true);
}
$doc->save("./retenciones_autorizadas/" . $claveautorizacion . ".xml");
$utRetencione->setRetEstado('AUTORIZADA');
$utRetencione->setRetLog("Fue Autorizada");
$utRetencione->setRetFecRespuesta($array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['fechaAutorizacion']);
$em->persist($utRetencione);
$comercio = $feComerciosRepository->find($utRetencione->getFaccompras()->getSucursales()->getComercios()->getId());
$comercio->setComNumDocDisponibles($comercio->getComNumDocDisponibles() - 1);
$em->persist($comercio);
fwrite($log, "\n Comprobante de Retencion Autorizado \n");
$em->flush();
//CREA CODEBAR
$generator = new BarcodeGeneratorPNG();
$barcode = $generator->getBarcode($claveautorizacion, $generator::TYPE_CODE_128);
file_put_contents("./codigos_barra/".$claveautorizacion.'.png', $barcode);
fwrite($log, "\n Código de Barras generado \n");
//CREA PDF RIDE
$options = new Options();
$options->set('isRemoteEnabled',TRUE);
$dompdf = new Dompdf($options);
$contxt = stream_context_create([
'ssl' => [
'verify_peer' => FALSE,
'verify_peer_name' => FALSE,
'allow_self_signed'=> TRUE
]
]);
$dompdf->setHttpContext($contxt);
$dompdf->set_paper('A4');
$html = $this->renderView('ut_retenciones/retencion.html.twig',array(
'utRetencion' => $utRetencione,
'existeLogo' => file_exists("./keys/".$utRetencione->getRetRuc()."/logo.png"),
'impuestos' => $impuestos,
//'fecAutorizacion' => $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['fechaAutorizacion'],
));
// Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'portrait' $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser (inline view) $dompdf->stream("mypdf.pdf", [ "Attachment" => false ]); } }
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents("./retenciones_ride/".$claveautorizacion.".pdf", $output);
fwrite($log, "\n PDF RIDE Generado \n");
//CAMBIA ESTADO AL REGISTRO DE VENTA
$em->flush();
//ENVIO DE CORREO
$mail = new PHPMailer(true);
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
//$mail->SMTPDebug = 2;
//Luego tenemos que iniciar la validación por SMTP:
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = $_ENV['mailer_secure'];
$mail->Host = $_ENV['mailer_host'];
$mail->Username = $_ENV['mailer_user'];
$mail->Password = $_ENV['mailer_password'];
$mail->Port = $_ENV['mailer_port'];
$mail->SMTPKeepAlive = true;
$mail->Mailer = $_ENV['mailer_transport'];
$mail->From = $_ENV['mailer_from'];
$mail->FromName = $utRetencione->getRetNomComercial(); //A RELLENAR Nombre a mostrar del remitente.
$mail->AddAddress("jaimemejiar1980@gmail.com");
$mail->AddAddress($comercio->getComEmail());
if($utRetencione->getRetCamAdiEmail() != '' and $tipoAmbiente == 2) {
$mail->AddAddress($utRetencione->getFaccompras()->getSucursales()->getComercios()->getComEmail());
if (filter_var($utRetencione->getRetCamAdiEmail(), FILTER_VALIDATE_EMAIL)) {
$mail->AddAddress($utRetencione->getRetCamAdiEmail());
}
}
$archivoPDF = "./retenciones_ride/".$claveautorizacion.".pdf";
$archivoXML = "./retenciones_autorizadas/".$claveautorizacion.".xml";
$mail->AddAttachment($archivoXML);
$mail->AddAttachment($archivoPDF);
$mail->IsHTML(true); // El correo se envía como HTML
$fecha = new \DateTime('now');
$mail->Subject = utf8_decode("COMPROBANTE DE RETENCION - DOCUMENTO GENERADO"); // Este es el titulo del email.
$body = $this->renderView('emails/retencion.html.twig',array(
'utRetencion' => $utRetencione,
'existeLogo' => file_exists("./keys/".$utRetencione->getRetRuc()."/logo.png"),
'impuestos' => $impuestos,
//'fecAutorizacion' => $array['RespuestaAutorizacionComprobante']['autorizaciones']['autorizacion']['fechaAutorizacion'],
));
$body .= utf8_decode("<br><br><h3>Este correo es enviado automaticamente, favor no responder</h3>");
$mail->Body = $body; // Mensaje a enviar.
$exito = $mail->Send(); // Envía el correo.
//var_dump($mail);
if ($exito) {
$mensaje = "El correo fue enviado correctamente.";
} else {
$mensaje = "Hubo un problema. Contacta a un administrador.";
}
fwrite($log, "\n ".$mensaje." \n");
} else {
$mensaje = json_encode($array['RespuestaAutorizacionComprobante']['autorizaciones']);
$utRetencione->setRetEstado('ERROR-AUT');
$utRetencione->setRetLog($mensaje);
$em->persist($utRetencione);
fwrite($log, "\n Comprobante de Retención Con Errores en la Autorización \n");
}
//print_r($mensaje);
fwrite($log, $mensaje );
$mensaje = "fin";
fwrite($log, "\n-------------". $mensaje. "\n");
fclose($log);
$response = json_encode($mensaje);
$user = $this->getUser();
return $this->render('ut_retenciones/index.html.twig', [
'ut_retenciones' => $user != null ? $utRetencionesRepository->getAll($user->getComercio()==null?'All':$user->getComercio()->getId()): null
]);
}
/**
* CRON proceso de actualizacion de retenciones
*
* @Route("/autorizacion/cron/", name="utretenciones_autorizacion_cron", methods={"GET"})
* @throws \SoapFault
*/
public function cronAction(UtRetencionesRepository $utRetencionesRepository, FeComerciosRepository $feComerciosRepository )
{
date_default_timezone_set('America/Guayaquil');
$em = $this->getDoctrine()->getManager();
//$utFacturas = $em->getRepository('AppBundle:UtFacturas')->getFacPendientes();
$utRetenciones = $utRetencionesRepository->getRetPendientes();
if(count($utRetenciones) < 1){
$mensaje = "No existen facturas pendientes o recibidas";
$response = json_encode($mensaje);
return new Response($response, 200, array('Content-Type' => 'application/json'));
}
$nombre_archivo = "logscron.txt";
file_exists($nombre_archivo);
$log = fopen($nombre_archivo, "a+");
$mensaje = "inicio ";
fwrite($log, "-------------". $mensaje. "\n");
fwrite($log, date("d-m-Y H:m:s"). "\n");
foreach ($utRetenciones as $retencion) {
$ret = $utRetencionesRepository->find($retencion['id']);
$this->autorizacionAction($ret, $utRetencionesRepository, $feComerciosRepository);
}
$mensaje = "fin";
fwrite($log, "\n-------------". $mensaje. "\n");
fclose($log);
$response = json_encode($mensaje);
return new Response($response, 200, array('Content-Type' => 'application/json'));
}
}