<?php

require_once '../Controller/FacturaController.php';
$path = '../';
$data = "";
$facturaController = new FacturaController($path);
$respuesta = $facturaController->execute("ConsultaFacturaSinUUID", $data);
error_log(print_r($respuesta['respuesta'], TRUE));
foreach ($respuesta['respuesta'] as $key => $value) {
    $data['idfactura'] = "";
    $data['idfactura'] = $value['idfactura'];
    $facturaController->execute("ActualizarFacturaSinUUID", $data);
}
echo "Pruebas de actualziacion";
<?php

require_once '../f4/configuracion/utils.php';
require_once 'constantes/class.zipfile.php';
$path = "../";
$pathQR = "";
$data = "";
$facturaController = new FacturaController($path);
$data = $_GET;
$data['busquedaPersistente'] = $_GET['busquedaPersistente'];
$factura = $facturaController->execute('presentarFactura', $data);
if ($factura['cantidad'] === 1) {
    $tmp = $factura['respuesta'];
    $factura['respuesta'] = "";
    $factura['respuesta'][0] = $tmp;
}
$filename = date("Ymd_His") . "_face-descarga.zip";
$zipfile = new ZipArchive();
if ($zipfile->open($SITE_ROOT . "gui/tmp/" . $filename, ZipArchive::CREATE) !== true) {
    throw new Exception("No se pudo crear el archivo");
}
$download = false;
$downloadfile = "";
$zipfileok = false;
require_once '../f4/extensiones/formatopdfcfdi.php';
foreach ($factura['respuesta'] as $row_factura) {
    // add the binary data stored in the string 'filedata'
    $filedata = base64_decode($row_factura['factura_timbrada']);
    $plain = $row_factura['serie'] . "-" . $row_factura['folio'] . ".xml";
    $formatopdf = $row_factura['serie'] . "-" . $row_factura['folio'] . ".pdf";
    $zipfile->addFromString($plain, $filedata);
 function get_ObjetoFactura($GenerarFacturaRequest)
 {
     require_once 'lib/class.face.txt_amece.php';
     $reporte = "";
     $factura = NULL;
     $msgEmision = "Reporte: <br>\n";
     $msgEmision .= "<br>procesando archivo...";
     $buffer = strtr(base64_decode($GenerarFacturaRequest->cfd), utf8_decode("á,é,í,ó,ú,Á,É,Í,Ó,Ú"), "a,e,i,o,u,A,E,I,O,U");
     $buffer = trim(utf8_encode($buffer));
     $factura = new Factura();
     $factura->bu = $GenerarFacturaRequest->client;
     $factura = getObjetoFactura($buffer, $factura);
     if (is_null($factura)) {
         $reporte .= "EN EL REGISTRO DE LA FACTURA " . $factura->encabezado->serie . $factura->encabezado->folio . "\n\r";
     } else {
         $ROUTETOINCLUDE = '../../../../';
         $empresaController = new EmpresaController($ROUTETOINCLUDE);
         $data['bu'] = $factura->bu;
         $factura->encabezado->bu = $factura->bu;
         $data['status'] = 0;
         $empresa = $empresaController->execute('buStatus', $data);
         if ($empresa['cantidad'] == 0) {
             $reporte .= "ERROR EN EMPRESA PROCESANDO FACTURA ";
             $factura->exito = false;
             $factura->mensaje = $reporte;
             return $factura;
         } else {
             $factura->emisor = $empresa['respuesta'];
             $this->getDatosInternos(&$factura);
             $data['sucursal'] = $factura->encabezado->sucursal;
             $data['serie'] = $factura->encabezado->serie;
             $data['fechahoraemision'] = $factura->encabezado->fechaemision . " " . $factura->encabezado->horaemision;
             $data['idempresa'] = $factura->emisor['idempresa'];
             $factura->encabezado->lugarExpedicion = $factura->emisor['municipio'];
             /**
              * @internal Seleccion de folio (si viene se pone, si no se calcula el folio maximo de FACE)
              */
             if ($factura->encabezado->folio == "getFolio") {
                 $dato = $factura->addenda;
                 $folio = $this->getFolio($factura->emisor['idempresa'], $factura->encabezado->serie);
                 $factura->encabezado->folio = isset($dato['Consecutive']) && trim($dato['Consecutive']) != "" ? $dato['Consecutive'] : intval($folio);
             }
         }
         $sucursalController = new SucursalController($ROUTETOINCLUDE);
         $sucursal = $sucursalController->execute('nombreSucIdempresa', $data);
         if ($sucursal['cantidad'] > 0) {
             $folioController = new FolioController($ROUTETOINCLUDE);
             $data['folio'] = $factura->encabezado->folio;
             $factura->encabezado->folio = $data['folio'];
             $folioA = $folioController->execute('actualizaFolioActual', $data);
             $facturaController = new FacturaController($ROUTETOINCLUDE);
             $facturaExistente = $facturaController->execute('existeRegistro', $data);
             if ($facturaExistente['cantidad'] == 0) {
                 //VALIDAR  CERTIFICADO DE LA SUCURSAL
                 $colname_sello = "0";
                 $selloController = new SelloController($ROUTETOINCLUDE);
                 $sello = $selloController->execute('selloSucursalStatus', $data);
                 if ($sello['cantidad'] > 0) {
                     $factura->sello = $sello['respuesta'];
                     error_log("CS: Objeto Factura completo " . date("Y-m-d H:m:s"));
                     if ($factura->encabezado->mailEntrega != FALSE || $factura->encabezado->mailEntrega != "") {
                         $factura->mail = TRUE;
                         $factura->exito = true;
                     }
                 } else {
                     $factura->exito = false;
                 }
             } else {
                 //Reproceso de facturas, el folio ya existe
                 $reporte .= "verifica si existe el registro " . $factura->encabezado->serie . "-" . $factura->encabezado->folio;
                 $factura->exito = FALSE;
             }
         } else {
             $reporte .= " EN EL REGISTRO DE LA FACTURA SUCURSAL";
             $factura->exito = FALSE;
         }
     }
     $factura->mensaje = $reporte;
     return $factura;
 }
Example #4
0
<?php

$PAGELEVEL = FACTURA;
$AUTH_redirectTo = $NOAU;
pageClearence($PAGELEVEL, $AUTH_redirectTo);
$path = "../";
$data = "";
$facturaController = new FacturaController($path);
$folioController = new FolioController($path);
$sucursalController = new SucursalController($path);
$empresaController = new EmpresaController($path);
$row_empr = $empresaController->execute('all', null);
require_once 'pagn.php';
$nm = "facturas";
$colname_idempresa = base64_decode($_SESSION['idempresa']);
$data = $_GET;
$data['idempresa'] = $colname_idempresa;
$folio = $folioController->execute('soloSerie', $data);
$maxRows_facturas = 20;
$pageNum_facturas = 0;
if (isset($_GET['pageNum_facturas'])) {
    $pageNum_facturas = $_GET['pageNum_facturas'];
}
$startRow_facturas = $pageNum_facturas * $maxRows_facturas;
$data['maxLimit'] = $maxRows_facturas;
$data['minLimit'] = $startRow_facturas;
$factura = $facturaController->execute('presentarFactura', $data);
if ($factura['cantidad'] === 1) {
    $tmp = $factura['respuesta'];
    $factura['respuesta'] = "";
    $factura['respuesta'][0] = $tmp;
Example #5
0
<?php

$PAGELEVEL = FACTURA_CANC;
$AUTH_redirectTo = $NOAU;
pageClearence($PAGELEVEL, $AUTH_redirectTo);
$path = "../";
$data = "";
$facturaController = new FacturaController($path);
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
    $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if (isset($_POST["MM_update"]) && $_POST["MM_update"] == "form1") {
    /*
      $updateSQL = sprintf("UPDATE facturas SET estatus=%s,fechacancelacion=now() WHERE idif=%s",
                           GetSQLValueString($_POST['estatus'], "int"),
                           GetSQLValueString($_POST['idif'], "int"));
    
      mysql_select_db($database_face5, $face5);
      $Result1 = mysql_query($updateSQL, $face5) or die(mysql_error());
    * 
    * chs 20130625
    */
    $data = $_POST;
    $facturaController->execute('cambiarEstatus', $data);
    $updateGoTo = "contenido.php?pr=fact";
    header(sprintf("Location: %s", $updateGoTo));
}
?>
<div id="barr">
  <div class="bari"><a href="contenido.php">Men&uacute; principal</a> :: <a href="contenido.php?pr=fact">Facturas</a> :: Cancelar una factura</div>
function get_ObjetoFactura($GenerarFacturaRequest){		
		require_once(dirname(dirname(__FILE__)).'/kio/lib/class.face.txt_amece.php');
		$path='../';
		$data = "";
		$reporte 	= "";
		$factura 	= NULL;		
		$msgEmision = "Reporte: <br>\n";	
		$msgEmision.= "<br>procesando archivo...";
		$buffer = trim(utf8_encode(utf8_decode(base64_decode($GenerarFacturaRequest->cfd))));
		$buffer = substr($buffer, 1, strlen($buffer));
		$buffer = json_decode($buffer);
		
		$factura = new Factura;
		$factura->bu = $GenerarFacturaRequest->client;
		$factura->bu = 1;//quitar
		$factura = getObjetoFactura($buffer, $factura);
		
		if(!$this->isJson($buffer)){
			$reporte.="ERROR EN JSON ";
			$factura->exito = false; 
			$factura->mensaje=$reporte;
			return $factura;
		}
		
		if(is_null($factura)){
			$reporte.="EN EL REGISTRO DE LA FACTURA ".$factura->encabezado->serie.$factura->encabezado->folio."\n\r";		
		} else {
			$ROUTETOINCLUDE='../../../../';
			$empresaController  = new EmpresaController($ROUTETOINCLUDE);
			$sucursalController = new SucursalController($ROUTETOINCLUDE);
			$facturaController = new FacturaController($ROUTETOINCLUDE);
			$selloController = new SelloController($ROUTETOINCLUDE);
			
			$data['bu'] = $factura->bu;			
			$data['status'] = 1; //chs - 20131111 valida que esten activa la empresa y valida que este activa la factura
			$data['sucursal']=$factura->encabezado->sucursal;
			$data['serie'] =$factura->encabezado->serie;
			$data['folio'] =$factura->encabezado->folio;
			$data['fechahoraemision'] = $factura->encabezado->fechaemision." ".$factura->encabezado->horaemision;	
			
			$empresa = $empresaController -> execute('buStatus',$data);
			
			if($empresa['cantidad'] == 0 ){
				$reporte.="ERROR EN EMPRESA PROCESANDO FACTURA ";
				$factura->exito = false; 
				$factura->mensaje=$reporte;
				return $factura;
			}else{
				$factura->emisor = $empresa['respuesta'];
				$data['idempresa'] = $factura->emisor['idempresa'];
			}
			
			$sucursal = $sucursalController-> execute('nombreSucIdempresa',$data);

			if($sucursal['cantidad'] > 0 ){
				$factura -> sucursal = $sucursal['respuesta'];
				if($factura->encabezado->folio != 0){
					$facturaExistente = $facturaController-> execute('existeRegistro',$data);
					if($facturaExistente['cantidad'] != 0){
						$reporte.=sprintf("El registro %s - %s ya existe",$factura->encabezado->serie,$factura->encabezado->folio);
						$factura -> exito	= FALSE;
						$factura -> mensaje	= $reporte;
						return $factura;
					}
				} 
					
				//VALIDAR  CERTIFICADO DE LA SUCURSAL
				$colname_sello = "0";
				$sello = $selloController-> execute('selloSucursalStatus',$data);
				if($sello['cantidad'] > 0){
					$factura->sello = $sello['respuesta'];
					log_action("CS: Objeto Factura completo ".date("Y-m-d H:m:s"));
					$factura->exito=true;
				}else{
					$reporte = sprintf("No se encontro sello para el documento %s %d",$factura->encabezado->serie,$factura->encabezado->folio);
					$factura->exito=false;						
				}
			}else{
				$reporte.=" EN EL REGISTRO DE LA FACTURA SUCURSAL";
				$factura->exito=FALSE;
			}
		}
		$factura->mensaje=$reporte;
		return $factura;
		}/* {
function creaPDF($ids, $tmpName, $path, $PATHQR, $tmp = "")
{
    require dirname(dirname(dirname(__FILE__))) . '/f4/configuracion/utils.php';
    require dirname(dirname(dirname(__FILE__))) . '/f4/configuracion/importeco.php';
    require dirname(dirname(dirname(__FILE__))) . "/gui/QRCode/qr_imgV2.php";
    $data = "";
    $facturaController = new FacturaController($path);
    $selloController = new SelloController($path);
    $empresaController = new EmpresaController($path);
    $sucursalController = new SucursalController($path);
    $FWK_PDFFONTS = 'pdf/fonts/';
    $FWK_PDFDEFAULTFONT = 'pdf/fonts/Helvetica.afm';
    $FWK_PDFCOURIERFONT = 'pdf/fonts/Courier.afm';
    // Obtener factura y sus anexos
    $TIPOSCOMPROBANTEMXP = array(1 => "Factura", 3 => "Nota de Cr.", 2 => "NOTA DE DEBITO");
    $idconsulta = "";
    $idconsulta = explode(",", trim($ids));
    foreach ($idconsulta as $valor) {
        if (is_null($valor) || $valor == "") {
            array_pop($idconsulta);
        }
    }
    $contadorTotalPaginas = count($idconsulta);
    $contadorPagina = 1;
    // Crea el documento pdf
    $pdf = new Cezpdf('LETTER', 'portrait');
    foreach ($idconsulta as $idfactura) {
        $data['idfactura'] = $idfactura;
        $factura = $facturaController->execute('facturaParaPdf', $data);
        $row_factura = $factura['respuesta'];
        $info_xtra = json_decode($row_factura["info_xtra"]);
        $data['idfacefactura'] = $factura['respuesta']['idface_factura'];
        $data['idempresa'] = $factura['respuesta']['idempresa'];
        $data['idsello'] = $factura['respuesta']['idsello'];
        $version = $factura['respuesta']['version'];
        $addenda = $facturaController->execute('datosAddenda', $data);
        $row_addenda = $addenda['respuesta'];
        $empresa = $empresaController->execute('allId', $data);
        $row_empresa = $empresa['respuesta'];
        $sello = $selloController->execute('obtenerPorIdsello', $data);
        $row_sello = $sello['respuesta'];
        $data['sucursal'] = $sello['respuesta']['sucursal'];
        $sucursal = $sucursalController->execute('nombreSucIdempresa', $data);
        $row_sucursal = $sucursal['respuesta'];
        $xmlArray = xml2array(base64_decode($row_factura['factura']));
        $attr = "_attr";
        if ($version === "3.2") {
            $NSP = "cfdi:";
        } else {
            $NSP = "";
        }
        $comprobante = $NSP . "Comprobante";
        $emisor = $NSP . "Emisor";
        $emisorDomFiscal = $NSP . "DomicilioFiscal";
        $emisorExpedidoEn = $NSP . "ExpedidoEn";
        $receptor = $NSP . "Receptor";
        $domicilio = $NSP . "Domicilio";
        $concepto = $NSP . "Conceptos";
        $conceptoTag = $NSP . "Concepto";
        $impuestos = $NSP . "Impuestos";
        $traslado = $NSP . "Traslados";
        $trasladoTag = $NSP . "Traslado";
        $retencion = $NSP . "Retenciones";
        $retencionTag = $NSP . "Retencion";
        //INICIALIZACIONES
        $comprobanteNode = null;
        $emisorNode = null;
        $emisordomicilioNode = null;
        $expedidoNode = null;
        $receptorNode = null;
        $receptordomicilioNode = null;
        $conceptoNode = null;
        $impuestosNode = null;
        $trasladoNode = null;
        $retencionNode = null;
        // -------------------------------------------------chs --------------------------------------------------------------
        $comprobanteNode = $xmlArray[$comprobante . $attr];
        $emisorNode = $xmlArray[$comprobante][$emisor . $attr];
        $emisordomicilioNode = $xmlArray[$comprobante][$emisor][$emisorDomFiscal . $attr];
        $expedidoNode = isset($xmlArray[$comprobante][$emisor][$emisorExpedidoEn . $attr]) ? $xmlArray[$comprobante][$emisor][$emisorExpedidoEn . $attr] : "";
        $receptorNode = $xmlArray[$comprobante][$receptor . $attr];
        $receptordomicilioNode = $xmlArray[$comprobante][$receptor][$domicilio . $attr];
        $conceptos = $xmlArray[$comprobante][$concepto];
        $impuestosNode = $xmlArray[$comprobante][$impuestos . $attr];
        $traslados = $xmlArray[$comprobante][$impuestos][$traslado];
        $retenciones = isset($xmlArray[$comprobante][$impuestos][$retencion][$retencionTag . $attr]) ? $xmlArray[$comprobante][$impuestos][$retencion][$retencionTag . $attr] : "";
        $regimenFiscal = $xmlArray[$comprobante][$emisor]["cfdi:RegimenFiscal_attr"]["Regimen"];
        // ---------------------------------------------------------------------------------------------------------------
        //descuentos
        $desc1 = 0.0;
        $desc2 = 0.0;
        //==================================================================================================================
        $pdf->ezSetMargins(100, 30, 30, 30);
        $pdf->selectFont($FWK_PDFDEFAULTFONT);
        $pdf->setLineStyle(0.7, '', '', '', 0);
        $pdf->openHere('Fit');
        if ($row_factura['tipocfd'] == 3) {
            $pdf->setStrokeColor(255, 0, 0);
        }
        if ($row_factura['tipocfd'] == 2) {
            $pdf->setStrokeColor(0, 255, 0);
        }
        // Inicia numeracin de paginas.
        $pagina = 1;
        $pdf->ezStartPageNumbers(500, 15, 10, '', '{PAGENUM} de {TOTALPAGENUM}', 1);
        $primeraPagina = $pdf->currentPage;
        // i. Agrega el logo de la empresa
        $pathToLogo = $path == "../" ? "../f4/extensiones/" : "";
        $logofile = "logos/f.jpg";
        //TENDRA QUE VENIR DE UN PARAMETRO EN LA BD.
        /*if(isset($row_empresa['rfc']) && !empty($row_empresa['rfc']))
        		$logofile="logos/".$row_empresa['rfc'].".jpg";*/
        if (isset($sucursal["respuesta"]["sucursal"]) && !empty($sucursal["respuesta"]["sucursal"])) {
            $logofile = "logos/" . strtolower($sucursal["respuesta"]["sucursal"]) . ".jpg";
        }
        error_log($logofile);
        if ($comprobanteNode['serie'] == "X") {
            $logofile = "logos/wingu-xpress.jpg";
        }
        $pdf->addJpegFromFile($pathToLogo . $logofile, 30, 705, 140);
        // i. Agrega la leyenda "cancelada"
        if ($row_factura['estatus'] == 0) {
            $pdf->setColor(0.9, 0.9, 0.9);
            $pdf->addText(180, 200, 65, "<b>CANCELADA</b>", -45);
            $pdf->setColor(0, 0, 0);
        }
        // ------------------------------------------ENCABEZADO ------------------------------------------
        //ENCABEZADO DE LA FACTURA
        $tipoDocto = $row_factura['tipodocumento'];
        $tipoDocto1 = $row_factura['tipodocumento'] == "FACTURA" ? "FACTURA" : "";
        $tipoDocto2 = $row_factura['tipodocumento'] == "NOTA CARGO" ? "FACTURA" : "";
        $tipoDocto3 = $row_factura['tipodocumento'] == "NOTA CREDITO" ? "NOTA DE CREDITO" : "";
        $emisor = utf8_decode($emisorNode['nombre'] . "\n" . $emisorNode['rfc']) . "\n";
        $noInterior = isset($emisordomicilioNode['noInterior']) ? $emisordomicilioNode['noInterior'] : "";
        $noExterior = isset($emisordomicilioNode['noExterior']) ? $emisordomicilioNode['noExterior'] : "";
        $emisor .= utf8_decode($emisordomicilioNode['calle'] . " {$noExterior}");
        $emisor .= utf8_decode($emisordomicilioNode['colonia']);
        if (isset($emisordomicilioNode['localidad'])) {
            $emisor .= "\n" . utf8_decode($emisordomicilioNode['localidad']);
        }
        if ($emisordomicilioNode['municipio'] != "" && isset($emisordomicilioNode['municipio'])) {
            $emisor .= "\n" . utf8_decode($emisordomicilioNode['municipio']);
        }
        if ($emisordomicilioNode['estado'] != "" && isset($emisordomicilioNode['estado'])) {
            $emisor .= ", " . utf8_decode($emisordomicilioNode['estado']);
        }
        if ($emisordomicilioNode['codigoPostal'] != "" && isset($emisordomicilioNode['codigoPostal'])) {
            $emisor .= "\nCP " . utf8_decode($emisordomicilioNode['codigoPostal']);
        }
        $emisor .= " " . utf8_decode($emisordomicilioNode['pais']);
        $telefono = isset($row_empresa['telefono']) ? $row_empresa['telefono'] : "";
        $emisor .= "\nTel: " . $telefono . "\n";
        $mail = isset($row_empresa['mail']) ? $row_empresa['mail'] : "";
        $emisor .= "\n" . $mail;
        $emisor1 = utf8_decode($emisorNode['nombre']);
        $sucursal = "";
        if ($expedidoNode != "") {
            if (utf8_decode($row_sucursal['sucursal']) == "Q") {
                $tipoSucursal = utf8_decode('Querétaro');
            } else {
                if (utf8_decode($row_sucursal['sucursal']) == "F") {
                    $tipoSucursal = utf8_decode('5/6');
                } else {
                    if (utf8_decode($row_sucursal['sucursal']) == "S") {
                        $tipoSucursal = utf8_decode('Santa Fe');
                    }
                }
            }
            $sucursal = "Sucursal " . $tipoSucursal . "\n";
            if (utf8_decode($row_sucursal['sucursal']) != "S") {
                $noInteriorExpedido = isset($expedidoNode['noInterior']) ? $expedidoNode['noInterior'] : "";
                $sucursal .= utf8_decode($expedidoNode['calle'] . " " . $expedidoNode['noExterior'] . " ") . "\n";
                $sucursal .= utf8_decode($expedidoNode['colonia']) . "\n";
                $sucursal .= utf8_decode($expedidoNode['municipio']) . ", " . utf8_decode($expedidoNode['estado']) . "\n";
                $sucursal .= "CP " . utf8_decode($expedidoNode['codigoPostal']) . " " . utf8_decode($expedidoNode['pais']);
            }
        }
        ////////// i. Nombre del emisor
        $colNames = array();
        $tableData = array(array("dato" => $emisor1));
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 200));
        $options = array('showLines' => 0, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(1, 1, 1), 'fontSize' => 9, 'textCol' => array(0, 0, 0), 'rowGap' => 0, 'colGap' => 0, 'xPos' => 200, 'xOrientation' => 'right', 'width' => 200, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla nombre del emisor
        $pdf->ezSetY(765);
        $pdf->ezTable($tableData, $colNames, "", $options);
        ////////// i. Datos del emisor y de la sucursal
        $tableData = array(array("emisor" => $emisor, "espacio" => "", "sucursal" => $sucursal));
        $colOptions = array("emisor" => array('justification' => 'left', 'width' => 150), "espacio" => array('justification' => 'left', 'width' => 3), "sucursal" => array('justification' => 'left', 'width' => 100));
        $options = array('showLines' => 0, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(1, 1, 1), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 0, 'colGap' => 0, 'xPos' => 190, 'xOrientation' => 'right', 'width' => 335, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla
        $pdf->ezTable($tableData, "", "", $options);
        ////////// i. Datos del documento
        $foliodocto = rellena("0", 6, $comprobanteNode['folio']);
        $seriedocto = $comprobanteNode['serie'];
        if (!empty($seriedocto)) {
            $foliodocto = $seriedocto . "-" . rellena("0", 6, $comprobanteNode['folio']);
        }
        $fechastr = $comprobanteNode['fecha'];
        $fechatok = explode("T", $fechastr);
        $toksf = explode("-", $fechatok[0]);
        $fechastr = $toksf[2] . "-" . $toksf[1] . "-" . $toksf[0] . " " . $fechatok[1];
        $fechastrcfdi = $row_factura['FechaTimbrado'];
        $ncert = $comprobanteNode['noCertificado'];
        $aprob = $row_factura['noCertificadoSAT'];
        //chs
        $tableData = array(array("dato" => "<b>" . $tipoDocto1 . $tipoDocto2 . $tipoDocto3 . "</b>"), array("dato" => "<b>" . $foliodocto . "</b>"), array("dato" => "FECHA DE EMISION"), array("dato" => $fechastr), array("dato" => "LUGAR DE EXPEDICION"), array("dato" => utf8_decode($info_xtra->LugarExpedicion)), array("dato" => "FECHA DE CERTIFICACION"), array("dato" => $fechastrcfdi), array("dato" => "No. de Serie del Certificado del Emisor"), array("dato" => $ncert), array("dato" => "No. de Serie del Certificado del SAT"), array("dato" => $aprob), array("dato" => "Folio Fiscal"), array("dato" => $row_factura['uuid']));
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 120));
        /*JASR*/
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(1, 1, 1), 'rowGap' => 2, 'colGap' => 5, 'xPos' => 455, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla datos del documento
        $pdf->ezSetDy(70);
        $pdf->ezTable($tableData, "", "", $options);
        ////////// i. Datos del cliente
        $noInterior = isset($receptordomicilioNode['noInterior']) ? utf8_decode($receptordomicilioNode['noInterior']) : "";
        $municipio = isset($receptordomicilioNode['municipio']) ? $receptordomicilioNode['municipio'] : "";
        $localidadCliente = isset($receptordomicilioNode['localidad']) ? utf8_decode($receptordomicilioNode['localidad']) : "";
        $tableData1 = array(array("cliente" => "<b>Cliente</b>"), array("cliente" => utf8_decode($receptorNode['nombre'])), array("cliente" => "RFC: " . utf8_decode($receptorNode['rfc'])), array("cliente" => utf8_decode($receptordomicilioNode['calle']) . " " . utf8_decode($receptordomicilioNode['noExterior']) . " {$noInterior} "), array("cliente" => utf8_decode($receptordomicilioNode['colonia']) . " " . $localidadCliente), array("cliente" => utf8_decode($municipio) . ", " . utf8_decode($receptordomicilioNode['estado']) . "  " . utf8_decode($receptordomicilioNode['codigoPostal']) . " \n" . utf8_decode($receptordomicilioNode['pais'])), array("cliente" => utf8_decode("Atención: " . $info_xtra->Receptor->contacto . "         Cliente: " . $info_xtra->Receptor->noCliente)), array("cliente" => utf8_decode("Tel: " . $info_xtra->Receptor->telefono)));
        $formaDePago = isset($comprobanteNode['formaDePago']) ? $comprobanteNode['formaDePago'] : "PAGO EN UNA SOLA EXHIBICION";
        $metodoPago = isset($comprobanteNode['metodoDePago']) ? $comprobanteNode['metodoDePago'] : "No Identificado";
        $numeroCuentaPago = isset($comprobanteNode['NumCtaPago']) ? $comprobanteNode['NumCtaPago'] : "No Identificado";
        $tableData2 = array(array("expedido" => "Expedido en: " . utf8_decode($info_xtra->LugarExpedicion)), array("expedido" => "Forma de Pago: " . utf8_decode($formaDePago)), array("expedido" => "Metodo de Pago: " . utf8_decode($metodoPago)), array("expedido" => "No. de Cuenta: " . utf8_decode($numeroCuentaPago)), array("expedido" => "Condiciones de Pago: " . utf8_decode($comprobanteNode['condicionesDePago'])), array("expedido" => "Regimen Fiscal: " . utf8_decode(preg_replace("/Ii/", "II", ucwords(strtolower($regimenFiscal))))), array("expedido" => "Tipo de Cambio: " . $comprobanteNode['TipoCambio'] . "  Moneda: " . $comprobanteNode['Moneda']), array("expedido" => "Elaboro: " . utf8_decode($info_xtra->Vendedor)), array("expedido" => utf8_decode("Póliza: " . $info_xtra->NumeroPoliza . "          SAP No: " . $info_xtra->NumeroPedido)));
        $tableData = array();
        $aux = count($tableData1) >= count($tableData2) ? $tableData1 : $tableData2;
        $cont = 0;
        foreach ($aux as $arr) {
            array_push($tableData, array("cliente" => $tableData1[$cont]["cliente"], "expedido" => $tableData2[$cont]["expedido"]));
            $cont++;
        }
        $colNames = array("cliente" => "", "expedido" => "");
        $colOptions = array("cliente" => array('justification' => 'left', 'width' => 205), "expedido" => array('justification' => 'left', 'width' => 205));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 2, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 410, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        $pdf->ezSetDy(125);
        $pdf->ezTable($tableData, $colNames, "", $options);
        //encabezado
        //error_log(print_r($info_xtra,true));
        $tableData = array(array("dato" => utf8_decode($info_xtra->Consumo->NotaEncabezado)));
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 540));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 5, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        $pdf->ezSetDy(-10);
        $pdf->ezTable($tableData, "", "", $options);
        $actualY = $pdf->y;
        $pdf->setColor(0, 0, 0);
        $pdf->filledRectangle(30, $actualY - 30, 540, 18);
        $pdf->ezSetY($actualY - 15);
        $pdf->setColor(1, 1, 1);
        $pdf->ezText("<b>Codigo</b>", 7, array('left' => 25, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Descripcion</b>", 7, array('left' => 180, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Cant</b>", 7, array('left' => 361, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Unidad</b>", 7, array('left' => 398, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Unitario</b>", 7, array('left' => 445, 'justification' => 'left'));
        $pdf->ezSetY($actualY - 15);
        $pdf->ezText("<b>Importe</b>", 7, array('left' => 497, 'justification' => 'left'));
        ////////// i. Partidas
        $tableData = array();
        $renglones = 0;
        $rowData = array("codigo" => "", "cantidad" => "", "unidad" => "", "descripcion" => "", "unitario" => "", "importe" => "");
        $partidaCnt = 0;
        $cantidadArrayConceptos = count($conceptos);
        foreach ($conceptos as $key => $conceptoNode) {
            if (stristr($key, $attr) && $cantidadArrayConceptos == 2) {
                $partidaCnt++;
                $renglones += 2;
                $currentObj = array();
                $descripcion = $conceptoNode['descripcion'];
                $totalPalabras = strlen($descripcion);
                $totalCaracteres = 4800;
                if ($totalPalabras >= $totalCaracteres) {
                    $pagDesc = ceil($totalPalabras / $totalCaracteres);
                    $aux = 1;
                    $array = array();
                    for ($i = 1; $i <= $pagDesc; $i++) {
                        if ($i == $pagDesc) {
                            $array[] = $totalPalabras;
                        } else {
                            $val = $aux += $totalCaracteres;
                            $array[] = $val;
                        }
                    }
                    $desc = array();
                    $o = 0;
                    foreach ($array as $valor) {
                        $desc[] = substr($descripcion, $o, $valor);
                        $o += $valor - $o;
                    }
                    $cont = 1;
                    foreach ($desc as $descripcionexp) {
                        $currentObj["codigo"] = $info_xtra->Consumo->partidas[$partidaCnt - 1]->codigo;
                        $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode['cantidad'])), 2);
                        //$currentObj["unidad"]= (isset($conceptoNode['unidad'])) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["unidad"] = $conceptoNode['unidad'];
                        //)) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($descripcionexp) . "\n" . utf8_decode($info_xtra->Consumo->partidas[$partidaCnt - 1]->nota));
                        if ($info_xtra->TipoImpresion == "KI2") {
                            $contPartidas = count($info_xtra->Consumo->partidas);
                            for ($i = 1; $i < $contPartidas; $i++) {
                                $currentObj["descripcion"] .= $info_xtra->Consumo->partidas[$i]->codigo . " " . $info_xtra->Consumo->partidas[$i]->cantidad . " " . $info_xtra->Consumo->partidas[$i]->unidad . " " . $info_xtra->Consumo->partidas[$i]->descripcion . " \$" . $info_xtra->Consumo->partidas[$i]->valorUnitario . " \n";
                            }
                        }
                        $currentObj["unitario"] = number_format($conceptoNode['valorUnitario'], 2);
                        $currentObj["importe"] = number_format(doubleval($conceptoNode['importe']), 2);
                        $for = $cont++;
                        log_action("for:::" . $for);
                        if ($for > 1) {
                            $currentObj["codigo"] = "";
                            $currentObj["cantidad"] = "";
                            $currentObj["unidad"] = "";
                            $currentObj["unitario"] = "";
                            $currentObj["importe"] = "";
                        }
                        array_push($tableData, $currentObj);
                    }
                } else {
                    $currentObj["codigo"] = $info_xtra->Consumo->partidas[$partidaCnt - 1]->codigo;
                    $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode['cantidad'])), 2);
                    //$currentObj["unidad"]= (isset($conceptoNode['unidad'])) ? $conceptoNode['unidad'] :  "No Aplica";
                    $currentObj["unidad"] = $conceptoNode['unidad'];
                    //)) ? $conceptoNode['unidad'] :  "No Aplica";
                    $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($descripcion) . "\n" . utf8_decode($info_xtra->Consumo->partidas[$partidaCnt - 1]->nota));
                    if ($info_xtra->TipoImpresion == "KI2") {
                        $contPartidas = count($info_xtra->Consumo->partidas);
                        for ($i = 1; $i < $contPartidas; $i++) {
                            $currentObj["descripcion"] .= utf8_decode($info_xtra->Consumo->partidas[$i]->codigo . " " . $info_xtra->Consumo->partidas[$i]->cantidad . " " . $info_xtra->Consumo->partidas[$i]->unidad . " " . $info_xtra->Consumo->partidas[$i]->descripcion . " " . $info_xtra->Consumo->partidas[$i]->valorUnitario) . " \n";
                        }
                    }
                    $currentObj["unitario"] = number_format($conceptoNode['valorUnitario'], 2);
                    $currentObj["importe"] = number_format(doubleval($conceptoNode['importe']), 2);
                    array_push($tableData, $currentObj);
                }
            } else {
                foreach ($conceptoNode as $key1 => $conceptoNode1) {
                    log_action(print_r($key1, TRUE));
                    if (stristr($key1, $attr)) {
                        $partidaCnt++;
                        $renglones += 2;
                        $currentObj = array();
                        $currentObj["codigo"] = $info_xtra->Consumo->partidas[$partidaCnt - 1]->codigo;
                        $currentObj["cantidad"] = number_format(abs(doubleval($conceptoNode1['cantidad'])), 2);
                        //$currentObj["unidad"]= (isset($conceptoNode['unidad'])) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["unidad"] = $conceptoNode1['unidad'];
                        //)) ? $conceptoNode['unidad'] :  "No Aplica";
                        $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($conceptoNode1['descripcion'] . "\n" . $info_xtra->Consumo->partidas[$partidaCnt - 1]->nota));
                        if ($info_xtra->TipoImpresion == "KI2") {
                            $contPartidas = count($info_xtra->Consumo->partidas);
                            for ($i = 1; $i < $contPartidas; $i++) {
                                $currentObj["descripcion"] .= $info_xtra->Consumo->partidas[$i]->codigo . " " . $info_xtra->Consumo->partidas[$i]->cantidad . " " . $info_xtra->Consumo->partidas[$i]->unidad . " " . $info_xtra->Consumo->partidas[$i]->descripcion . " \$" . $info_xtra->Consumo->partidas[$i]->valorUnitario . " \n";
                            }
                        }
                        $currentObj["unitario"] = number_format($conceptoNode1['valorUnitario'], 2);
                        $currentObj["importe"] = number_format(doubleval($conceptoNode1['importe']), 2);
                        array_push($tableData, $currentObj);
                    }
                }
                //fin foreach 2  chs 20130705
            }
        }
        $currentObj = array();
        $currentObj["codigo"] = "";
        $currentObj["cantidad"] = "";
        $currentObj["unidad"] = "";
        $currentObj["descripcion"] = str_replace("__", "\n", utf8_decode($row_factura["fnotas"]));
        $currentObj["unitario"] = "";
        $currentObj["importe"] = "";
        array_push($tableData, $currentObj);
        if (isset($row_addenda['cl_fld1'])) {
            $currentObj = array();
            $currentObj["cantidad"] = "";
            $currentObj["descripcion"] = $row_addenda['cl_fld1'];
            if (!empty($row_addenda['cl_fld2'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld2'];
            }
            if (!empty($row_addenda['cl_fld3'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld3'];
            }
            if (!empty($row_addenda['cl_fld4'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld4'];
            }
            if (!empty($row_addenda['cl_fld5'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld5'];
            }
            if (!empty($row_addenda['cl_fld6'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld6'];
            }
            if (!empty($row_addenda['cl_fld7'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld7'];
            }
            if (!empty($row_addenda['cl_fld8'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld8'];
            }
            if (!empty($row_addenda['cl_fld9'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld9'];
            }
            if (!empty($row_addenda['cl_fld10'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld10'];
            }
            if (!empty($row_addenda['cl_fld11'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld11'];
            }
            if (!empty($row_addenda['cl_fld12'])) {
                $currentObj["descripcion"] .= "\n" . $row_addenda['cl_fld12'];
            }
            $currentObj["unitario"] = "";
            $currentObj["importe"] = "";
            array_push($tableData, $currentObj);
        }
        $currentObj = array();
        $currentObj["codigo"] = "";
        $currentObj["cantidad"] = "";
        $currentObj["unidad"] = "";
        $currentObj["descripcion"] = "";
        $currentObj["unitario"] = "";
        $currentObj["importe"] = "";
        if ($info_xtra->TipoImpresion == "KI2") {
            for ($renglones; $renglones < 10 - count($info_xtra->Consumo->partidas) * 0.95; $renglones++) {
                array_push($tableData, $currentObj);
            }
        } else {
            if ($renglones < 10) {
                for ($renglones; $renglones < 10; $renglones++) {
                    array_push($tableData, $currentObj);
                }
            }
        }
        $colNames = array("codigo" => "", "descripcion" => "", "cantidad" => "", "unidad" => "", "unitario" => "", "importe" => "");
        $colOptions = array("codigo" => array('justification' => 'center', 'width' => 70), "descripcion" => array('justification' => 'left', 'width' => 280), "cantidad" => array('justification' => 'center', 'width' => 40), "unidad" => array('justification' => 'left', 'width' => 40), "unitario" => array('justification' => 'right', 'width' => 55), "importe" => array('justification' => 'right', 'width' => 55));
        $options = array('showLines' => 1, 'showHeadings' => 1, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 4, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 410, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla partidas
        $pdf->ezSetDy(11);
        $pdf->ezTable($tableData, $colNames, "", $options);
        ////////// i. Cantidad con letra
        $cadena = covertirNumLetras(number_format($comprobanteNode['total'], 2, ".", ''));
        if ($comprobanteNode['Moneda'] == "USD") {
            $cadena = str_replace("M.N.", "USD", $cadena);
            $cadena = str_replace("PESOS", "DOLARES", $cadena);
            $cadena = str_replace("PESO", "DOLAR", $cadena);
        }
        $tableData = array(array("dato" => "<b>Nota:</b>\n" . utf8_decode($info_xtra->Consumo->notaAlPie)), array("dato" => "<b>Total con letra</b>\n" . trim($cadena)));
        $colNames = array("dato" => "<b>Cant</b>");
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 390));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 1, 'shadeCol' => array(0.9, 0.9, 0.9), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 2.5, 'colGap' => 5, 'xPos' => 35, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla cantidad con letra
        $pdf->ezSetDy(0);
        $pdf->ezTable($tableData, "", "", $options);
        ////////// i. Totales
        $f_importe = "\$" . number_format($comprobanteNode['subTotal'], 2);
        //$f_iva_T=$conceptoNode['totalImpuestosTrasladados'];
        $f_total = "\$" . number_format($comprobanteNode['total'], 2);
        $tableData = array();
        $rowData = array("leyenda" => "", "cantidad" => "");
        $subtotal = array("dato" => "Subtotal", "valor" => $f_importe);
        array_push($tableData, $subtotal);
        foreach ($traslados as $key => $trasladoNode) {
            if ($key === $trasladoTag . $attr) {
                $tasaImpuesto = array();
                $tasaImpuesto_t = number_format($trasladoNode['tasa'], 0);
                $tasaImpuesto["dato"] = $trasladoNode['impuesto'] . " " . $tasaImpuesto_t . "%";
                $tasaImpuesto["valor"] = "\$" . number_format($trasladoNode['importe'], 2);
                //array_push($tableData,$tasaImpuesto);
            }
        }
        if (!empty($retenciones)) {
            foreach ($retenciones as $key => $retencionNode) {
                if ($key === $retencionTag . $attr) {
                    $tasaImpuesto = array();
                    $tasaImpuesto_t = number_format($retencionNode['tasa'], 2);
                    $tasaImpuesto["dato"] = "Ret. " . $retencionNode['impuesto'];
                    $tasaImpuesto["valor"] = "\$" . number_format($retencionNode['importe'], 2);
                    //array_push($tableData,$tasaImpuesto);
                }
            }
        }
        //fin if empty
        $iva = array("dato" => "<b>IVA</b>", "valor" => "<b>\$ " . number_format($info_xtra->TotalImpuestosTrasladados, 2) . "</b>");
        array_push($tableData, $iva);
        $total = array("dato" => "<b>Total</b>", "valor" => "<b>" . $f_total . "</b>");
        array_push($tableData, $total);
        $colNames = array("dato" => "<b>Cant</b>", "valor" => "Importe");
        $colOptions = array("dato" => array('justification' => 'right', 'width' => 55), "valor" => array('justification' => 'right', 'width' => 95));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 2, 'shadeCol' => array(1, 1, 1), 'shadeCol2' => array(91, 21, 0), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 3, 'colGap' => 5, 'xPos' => 425, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla totales
        $pdf->ezSetDy(42.5);
        $pdf->ezTable($tableData, $colNames, "", $options);
        $rfce = $row_empresa['rfc'];
        $rfcr = $receptorNode['rfc'];
        $total = $comprobanteNode['total'];
        $uuidsat = $row_factura['uuid'];
        $cadenaQRCode = sprintf("?re=%s&rr=%s&tt=%s&id=%s", $rfce, $rfcr, $total, $uuidsat);
        /*QR Code: Para usar qr_imgV2():  qr_imgV2(d,e,s,v,t);
          d= datos        Cadena o datos a ser codificados.
          e= ECC level    Puede ser L,M,Q,H  (default M)
          s= module size  Para imagen JPEG:8; para PNG:4
          v= version      1-40   8 recomendado.
          t= image type   "J":imagen jpeg, "P" o culaquier otra cosa: imagen PNG */
        $img_filename = qr_imgV2($cadenaQRCode, "M", 8, 8, "J", $PATHQR);
        //v:7-13 8 parece adecuado.
        //$pdf->addJpegFromFile($img_filename,495,$pdf->y,90); //100
        //$pdf->addJpegFromFile($img_filename,32,170,130); //100
        $pdf->addJpegFromFile($img_filename, 32, $pdf->y - 140, 130);
        //100
        unlink($img_filename);
        ////////// i. Sello
        if ($version === "3.2") {
            $tableData = array(array("dato" => "<b>Sello Digital del Emisor</b>\n" . $row_factura['sello']), array("dato" => "<b>Sello Digital del SAT</b>\n" . $row_factura['selloSAT']));
        } else {
            $tableData = array(array("dato" => "<b>Sello Digital</b>\n" . $row_factura['sello']));
        }
        $colNames = array("dato" => "<b>Cant</b>");
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 400));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.8, 0.8, 0.8), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 5, 'colGap' => 5, 'xPos' => 175, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla sello
        $pdf->ezSetDy(-10);
        $pdf->ezTable($tableData, $colNames, "", $options);
        /*$pdf->setColor(91,21,0);
        		$pdf->filledRectangle(30,167,134,151);
        		$pdf->setColor(1,1,1);	
        		$pdf->filledRectangle(31,167.5,132.3,149.5);*/
        ////////// i. Cadena original
        $columnaCadena = "";
        if ($version === "3.2") {
            $columnaCadena = sprintf("||1.0|%s|%s|%s|%s||", $row_factura['uuid'], $row_factura['FechaTimbrado'], $row_factura['selloCFD'], $row_factura['noCertificadoSAT']);
        } else {
            $columnaCadena = sprintf("%s", $row_factura['cadena']);
        }
        $tableData = array(array("dato" => "<b>Cadena original del complemento de certificacion digital del SAT</b>\n" . $columnaCadena), array("dato" => "<b>Folio Fiscal</b>\n" . $row_factura['uuid']));
        $colNames = array("dato" => "<b>Cant</b>");
        $colOptions = array("dato" => array('justification' => 'left', 'width' => 400));
        $options = array('showLines' => 1, 'showHeadings' => 0, 'shaded' => 0, 'shadeCol' => array(0.8, 0.8, 0.8), 'fontSize' => 7, 'textCol' => array(0, 0, 0), 'rowGap' => 5, 'colGap' => 5, 'xPos' => 175, 'xOrientation' => 'right', 'width' => 120, 'cols' => $colOptions, 'innerLineThickness' => 0.3, 'outerLineThickness' => 0.3);
        // Dibuja la tabla cadena original
        $pdf->ezSetDy(-5);
        $pdf->ezTable($tableData, $colNames, "", $options);
        // Leyendas
        $pdf->ezSetDy(-12);
        $leyendas = "ESTE DOCUMENTO ES UNA REPRESENTACION IMPRESA DE UN CFDI.\n";
        $pdf->setColor(0.5, 0.5, 0.5);
        $pdf->ezText($leyendas, 5, array('left' => 50, 'justification' => 'center'));
        $pdf->setColor(0, 0, 0);
        $pdf->ezStream(array("filename" => $row_factura['folio'] . "_" . str_replace(" ", "-", $receptorNode['nombre'])));
        //Necesario para que funcione ezStartPageNumbers
        //REGRESA PARA PONER ENCABEZADO EN PAGINAS 2 ->
        if ($contadorPagina != $contadorTotalPaginas) {
            $pdf->ezNewPage();
            $pdf->ezSetDy(-12);
        }
        $contadorPagina++;
    }
    //fin del foreach para la creacion del objeto pdf
    //ESCRIBE REPORTE AL ARCHIVO.
    //================================================================================
    $pdfcode = $pdf->output();
    error_log($tmpName);
    if ($tmpName === 2 || !$tmpName) {
        $tmpName = !$tmpName ? $tmpName : true;
    } else {
        exit($pdfcode);
    }
    //save the file
    if ($tmpName) {
        $nombrePDF = tempnam($tmp . "tmp/", 'face5') . ".pdf";
        $nombreToks = explode("/", $nombrePDF);
        if (count($nombreToks) < 2) {
            $nombreToks = explode("\\", $nombrePDF);
        }
        $lastTok = count($nombreToks) - 1;
        $nombrePDF = $nombreToks[$lastTok];
        $archivoPDF = $tmp . "tmp/" . $nombrePDF;
        $archivos = array($nombrePDF, $archivoPDF);
        error_log(print_R($archivos, true));
    } else {
        $nombrePDF = $tipoDocto . "_" . $row_factura['serie'] . $row_factura['folio'] . ".pdf";
        //$archivoPDF ="tmp/".$nombrePDF;//chs 20130705
        $archivoPDF = $tmp . "tmp/" . $nombrePDF;
        $archivos = array($nombrePDF, $archivoPDF);
        error_log(2);
        ob_flush();
        ob_clean();
    }
    global $SITE_ROOT;
    error_log($archivoPDF);
    @file_put_contents($SITE_ROOT . "gui/" . $archivoPDF, $pdfcode);
    /*$fp = fopen($archivoPDF,'w+');
    		fwrite($fp,$pdfcode);
    		fclose($fp);*/
    return $archivos;
}
<?php

require_once '../Controller/FacturaController.php';
session_start();
$idempresa = base64_decode($_SESSION['idempresa']);
$path = "../";
$data = "";
$facturaController = new FacturaController($path);
$data = $_GET;
$data['idempresa'] = $idempresa;
$qu = $facturaController->execute('facturasReporte', $data);
exportaCSV($qu, $_GET['archivo'] . ".csv");
function exportaCSV($table, $filename)
{
    $csv = "idempresa,\tserie,\tfolio,\trfc,\trazonsocial,\tfechaemision,\tsubtotal,\ttotal_impuestos,\ttotal,\tuuid,\testatus\n";
    $result = $table['cantidad'];
    $fields_cnt = $table['columnas'];
    foreach ($table['respuesta'] as $row) {
        $idempresa = $row['idempresa'];
        $serie = $row['serie'];
        $folio = $row['folio'];
        $rfc = $row['rfc'];
        $razonsocial = str_replace(",", " ", $row['razonsocial']);
        $fechaemision = $row['fechaemision'];
        $subtotal = $row['subtotal'];
        $total_impuestos = $row['total_impuestos'];
        $total = $row['total'];
        $uuid = $row['uuid'];
        $estatus = $row['estatus'];
        $csv .= "{$idempresa}, {$serie} ,{$folio},{$rfc} ,{$razonsocial}, {$fechaemision}, {$subtotal}, {$total_impuestos}, {$total}, {$uuid}, {$estatus}\n";
    }
Example #9
0
        $msg = '<div id="barr">
						<div class="bari"><a href="contenido.php">Men&uacute; principal</a> :: Facturas</div>
					</div>
					<div id="cont">
						<span class="titt">Facturas</span>
						<!-- Inicia columna izquierda -->
						<div class="coli"><a href="contenido.php?pr=fact">Ver todas las facturas emitidas</a></div>
						<!-- Termina columna izquierda -->
						<!-- Inicia columna derecha -->
						<div class="cold">La factura NO fue enviada</div>
					</div>';
    }
    error_log($msg);
    exit($msg);
}
$facturaController = new FacturaController($path);
$empresaController = new EmpresaController($path);
$data["idempresa"] = base64_decode($_SESSION['idempresa']);
$data["idFactura"] = isset($_GET['fc']) ? $_GET['fc'] : 0;
$datosRespuesta = $facturaController->execute('consultaMailClienteFactura', $data);
$row_factura = $datosRespuesta['respuesta'];
$empresa = $empresaController->execute('smtp', $data);
$row_correo = $empresa['respuesta'];
?>
<script>
	<!--$(document).ready(function() {

		$("#form1").validate();

		$("#xml").click(function() {
			var activa_boton = $("#button");
Example #10
0
<?php

$PAGELEVEL = FACTURA;
$AUTH_redirectTo = $NOAU;
pageClearence($PAGELEVEL, $AUTH_redirectTo);
$path = "../";
$data = "";
$facturaController = new FacturaController($path);
if (isset($_GET['fc'])) {
    $data['idfactura'] = $_GET['fc'];
}
$factura = $facturaController->execute('facturaIdDescarga', $data);
$row_xml = $factura['respuesta'];
$xmlbody = $row_xml['factura_timbrada'];
unset($row_xml['factura_timbrada']);
$xmlPersistente = urlencode(serialize($row_xml));
?>
<div id="barr">
  <div class="bari"><a href="contenido.php">Men&uacute; principal</a> :: <a href="contenido.php?pr=fact">Facturas</a> :: XML</div>
</div>

<div id="cont">
<span class="titt">Facturas - archivo xml</span>


<!-- Inicia columna izquierda -->
<div class="coli">
En algunos casos especiales, es probable que te soliciten el archivo XML de tu factura. Debes descargar el archivo, que tendr&aacute; una extensi&oacute;n .xml y el cual puede transmitirse a trav&eacute;s de los medios electr&oacute;nicos.
</div>
<!-- Termina columna izquierda -->
<!-- Inicia columna derecha -->
function procesaObjeto($objFact)
{
    require_once dirname(dirname(__FILE__)) . '/Controller/FacturaController.php';
    require_once dirname(dirname(__FILE__)) . '/Controller/FolioController.php';
    try {
        //crea el objeto factura.
        $path = '../';
        $data = "";
        $data['serie'] = $objFact->encabezado->serie;
        $data['folio'] = $objFact->encabezado->folio;
        $data['idempresa'] = $objFact->emisor['idempresa'];
        $data['sucursal'] = $objFact->sucursal['sucursal'];
        //POSIBLEMNTE CORECCION A SEMILLA 20131202
        $facturaController = new FacturaController($path);
        $emiteDocumento = sprintf("<br>emite documento %s%d", $data['serie'], $data['folio']);
        echo $emiteDocumento;
        log_action($emiteDocumento);
        //1.- VALIDA DATOS STANDAR DEL CFD  (función de class.face.php)
        $resultado = validaObjetoCFD($objFact);
        if ($resultado == "OK") {
            $res = null;
            $cfd = null;
            $VERSIONCFD = $objFact->emisor['versioncfd'];
            if ($VERSIONCFD == "3.2") {
                //CHS - 20131112  Calcula el folio y establece una conexion viva, para generar transaccionalidad entre folio, facturas y sus tablas relacionales
                if ($objFact->encabezado->folio === 0) {
                    $folioController = new FolioController($path);
                    $folio = $folioController->execute('idempresaSerie', $data);
                    $data['folio'] = $folio['respuesta']['actual'];
                    $objFact->encabezado->folio = $data['folio'];
                }
                $res = procesaXmlV32($objFact, $cfd);
                //coref5
                if ($res === "-1") {
                    throw new Exception($res);
                }
            } else {
                $msg = "La version del Certificado es incorrecta";
                log_action("procesaObjeto.php: {$msg}");
                throw new Exception($msg);
            }
            $errorMsg = "";
            if (isset($cfd['error'])) {
                $errorMsg = trim($cfd['error']);
            }
            if ($res != 0 || $errorMsg != "") {
                log_action($errorMsg);
                throw new Exception($errorMsg);
            } else {
                log_action("XML Creado.");
                $objFact->cfdi = $cfd;
                if ($objFact->emisor['versioncfd'] == "3.2") {
                    //CFDI: ENVIA PARA TIMBRADO AL PAC.
                    log_action("peticion de timbrado");
                    log_action("serie" . $objFact->encabezado->serie . " " . "folio" . $objFact->encabezado->folio);
                    log_action(print_r($cfd['xmlutf8'], TRUE));
                    $respuesta_PAC = SOAP_client($objFact->emisor['rfc'], base64_encode($cfd['xmlutf8']));
                    log_action(print_r($respuesta_PAC, TRUE));
                    //Checar si respuesta es el certificado timbrado o es un error.
                    if (stristr($respuesta_PAC, 'UUID')) {
                        log_action("timbrado exitoso");
                        $objFact->cfdi['respuestaPac'] = $respuesta_PAC;
                        $factura = $facturaController->execute('facturaTimbrada', $objFact);
                        $msgcfdi = 'CFDI Salvado con exito!';
                        if (!empty($objFact->encabezado->mailEntrega) && $objFact->encabezado->mailEntrega != "") {
                            $objFact->mail = TRUE;
                        } else {
                            $objFact->mail = FALSE;
                        }
                        log_action($msgcfdi);
                        return $factura['respuesta'];
                    } else {
                        if (stristr($respuesta_PAC, 'xml')) {
                            //Viene del PAC.
                            $xmlerror_array = xml2array($respuesta_PAC);
                            $err_codigo = $xmlerror_array['Error_attr']['codigo'];
                            $err_msg = $xmlerror_array['Error_attr']['mensaje'];
                            $msgcfdi = 'en el timbrado: ' . 'Codigo de error: ' . $err_codigo . '  Mensaje: ' . $err_msg;
                            log_action($msgcfdi);
                            throw new Exception($msgcfdi);
                        } else {
                            //Excepci�n generada aqu�, no se pudo conectar al PAC.
                            $msgcfdi = 'Al tratar de enviar comprobante, no se pudo contactar al PAC.';
                            log_action($msgcfdi);
                            throw new Exception($msgcfdi);
                        }
                    }
                }
                //fin valida version
            }
            //fin del else que valida xml
        } else {
            throw new Exception("Estructura Invalida {$resultado}");
        }
        //fin if($resultado=="OK")
        throw new Exception("validacion del Objeto factura " . $resultado);
    } catch (Exception $e) {
        log_action("procesaObjeto :" . $e->getMessage());
        return "Error: " . $e->getMessage();
    }
}