function detallista(&$ComplementoNode, $complemento, &$dom)
{
    $CONST_LIV_AC = array("AA" => "AA", "AJ" => "AJ", "ADO" => "AJ");
    $CONST_LIV_PROVS = array("DIREC" => "0000000", "OFICIN" => "0000000", "GDIOF" => "56288", "RDIOF" => "95782", "TIMOF" => "107310", "PDIOF" => "114456", "GDCOF" => "56288", "RDCOF" => "95782", "TDCOF" => "107310");
    if (count($complemento->hashtable) > 0) {
        $factura = $complemento->hashtable['facturaobj'];
        //$complemento -> hashtable = $factura->addendaht;
        //HIJO DETALLISTA
        $detallistaNode = $dom->createElement("detallista:detallista");
        $detallistaNode = $ComplementoNode->appendChild($detallistaNode);
        $detallistaNode->setAttribute("type", "SimpleInvoiceType");
        $detallistaNode->setAttribute("documentStructureVersion", "AMC8.1");
        $detallistaNode->setAttribute("documentStatus", "ORIGINAL");
        $detallistaNode->setAttribute("contentVersion", "1.3.1");
        $requestForPaymentIdentification = $dom->createElement("detallista:requestForPaymentIdentification");
        $requestForPaymentIdentification = $detallistaNode->appendChild($requestForPaymentIdentification);
        $entityType = $dom->createElement("detallista:entityType");
        $entityType = $requestForPaymentIdentification->appendChild($entityType);
        $entityType->appendChild($dom->createTextNode("INVOICE"));
        $specialInstruction = $dom->createElement("detallista:specialInstruction");
        $specialInstruction = $detallistaNode->appendChild($specialInstruction);
        $specialInstruction->setAttribute("code", "ZZZ");
        $text = $dom->createElement("detallista:text");
        $text = $specialInstruction->appendChild($text);
        $text->appendChild($dom->createTextNode("MONTO CON LETRA"));
        $orderIdentification = $dom->createElement("detallista:orderIdentification");
        $orderIdentification = $detallistaNode->appendChild($orderIdentification);
        $referenceIdentification = $dom->createElement("detallista:referenceIdentification");
        $referenceIdentification = $orderIdentification->appendChild($referenceIdentification);
        $referenceIdentification->setAttribute("type", "ON");
        //orden de compra, pedido.
        $ON = "A_PO_ID";
        $value = trim($complemento->hashtable['po_id']);
        if (isset($complemento->hashtable['po_id']) & !empty($value)) {
            $ON = $value;
        }
        $referenceIdentification->appendChild($dom->createTextNode($ON));
        $ReferenceDate = $dom->createElement("detallista:ReferenceDate");
        $ReferenceDate = $orderIdentification->appendChild($ReferenceDate);
        //fecha del pedido.
        $fecha = "A_PO_DAT";
        $value = trim($complemento->hashtable['po_dat']);
        if (isset($complemento->hashtable['po_dat']) & !empty($value)) {
            $fecha = $value;
        }
        $ReferenceDate->appendChild($dom->createTextNode($fecha));
        $AdditionalInformation = $dom->createElement("detallista:AdditionalInformation");
        $AdditionalInformation = $detallistaNode->appendChild($AdditionalInformation);
        $referenceIdentification = $dom->createElement("detallista:referenceIdentification");
        $referenceIdentification = $AdditionalInformation->appendChild($referenceIdentification);
        $referenceIdentification->setAttribute("type", "ATZ");
        $referenceIdentification->appendChild($dom->createTextNode($factura->foliosaprob['noaprob']));
        $DeliveryNote = $dom->createElement("detallista:DeliveryNote");
        $DeliveryNote = $detallistaNode->appendChild($DeliveryNote);
        $referenceIdentification_dn = $dom->createElement("detallista:referenceIdentification");
        $referenceIdentification_dn = $DeliveryNote->appendChild($referenceIdentification_dn);
        //contrarecibo de entrega.
        $dnid = "A_DN_ID";
        $value = trim($complemento->hashtable['dn_id']);
        if (isset($complemento->hashtable['dn_id']) & !empty($value)) {
            $dnid = $value;
        }
        $referenceIdentification_dn->appendChild($dom->createTextNode($dnid));
        $ReferenceDate_dn = $dom->createElement("detallista:ReferenceDate");
        $ReferenceDate_dn = $DeliveryNote->appendChild($ReferenceDate_dn);
        //fecha de entrega.
        $dndat = "A_DN_DAT";
        $value = $complemento->hashtable['dn_dat'];
        if (isset($complemento->hashtable['dn_dat']) & !empty($value) && $value != '0000-00-00') {
            $dndat = $value;
        }
        $ReferenceDate_dn->appendChild($dom->createTextNode($dndat));
        $buyer = $dom->createElement("detallista:buyer");
        $buyer = $detallistaNode->appendChild($buyer);
        $gln = $dom->createElement("detallista:gln");
        $gln = $buyer->appendChild($gln);
        $gln->appendChild($dom->createTextNode("0007504000107"));
        $contactInformation = $dom->createElement("detallista:contactInformation");
        $contactInformation = $buyer->appendChild($contactInformation);
        $personOrDepartmentName = $dom->createElement("detallista:personOrDepartmentName");
        $personOrDepartmentName = $contactInformation->appendChild($personOrDepartmentName);
        $text = $dom->createElement("detallista:text");
        $text = $personOrDepartmentName->appendChild($text);
        //comprador.
        $buyerper = "A_BUYER_PER";
        $value = trim($complemento->hashtable['bu_per']);
        if (isset($complemento->hashtable['bu_per']) & !empty($value)) {
            $buyerper = $value;
        }
        $text->appendChild($dom->createTextNode($buyerper));
        $seller = $dom->createElement("detallista:seller");
        $seller = $detallistaNode->appendChild($seller);
        $gln = $dom->createElement("detallista:gln");
        $gln = $seller->appendChild($gln);
        $gln->appendChild($dom->createTextNode("5896125468333"));
        $alternatePartyIdentification = $dom->createElement("detallista:alternatePartyIdentification");
        $alternatePartyIdentification = $seller->appendChild($alternatePartyIdentification);
        $alternatePartyIdentification->setAttribute("type", "SELLER_ASSIGNED_IDENTIFIER_FOR_A_PARTY");
        $alternatePartyIdentification->appendChild($dom->createTextNode($CONST_LIV_PROVS[$factura->encabezado->sucursal]));
        if (count($factura->descuentos) > 0) {
            foreach ($factura->descuentos as $descuentoglobal) {
                if ($descuentoglobal->porcentaje > 0) {
                    $allowanceCharge = $dom->createElement("detallista:allowanceCharge");
                    $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
                    $allowanceCharge->setAttribute("allowanceChargeType", "ALLOWANCE_GLOBAL");
                    $allowanceCharge->setAttribute("settlementType", "BILL_BACK");
                    $specialServicesType = $dom->createElement("detallista:specialServicesType");
                    $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
                    $specialServicesType->appendChild($dom->createTextNode($CONST_LIV_AC[$descuentoglobal->motivo]));
                    $monetaryAmountOrPercentage = $dom->createElement("detallista:monetaryAmountOrPercentage");
                    $monetaryAmountOrPercentage = $allowanceCharge->appendChild($monetaryAmountOrPercentage);
                    $rate = $dom->createElement("detallista:rate");
                    $rate = $monetaryAmountOrPercentage->appendChild($rate);
                    $rate->setAttribute("base", "INVOICE_VALUE");
                    $percentage = $dom->createElement("detallista:percentage");
                    $percentage = $rate->appendChild($percentage);
                    $percentage->appendChild($dom->createTextNode(satNumber($descuentoglobal->porcentaje)));
                }
            }
        } else {
            $allowanceCharge = $dom->createElement("detallista:allowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceChargeType", "ALLOWANCE_GLOBAL");
            $allowanceCharge->setAttribute("settlementType", "BILL_BACK");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AA"));
            $monetaryAmountOrPercentage = $dom->createElement("detallista:monetaryAmountOrPercentage");
            $monetaryAmountOrPercentage = $allowanceCharge->appendChild($monetaryAmountOrPercentage);
            $rate = $dom->createElement("detallista:rate");
            $rate = $monetaryAmountOrPercentage->appendChild($rate);
            $rate->setAttribute("base", "INVOICE_VALUE");
            $percentage = $dom->createElement("detallista:percentage");
            $percentage = $rate->appendChild($percentage);
            $percentage->appendChild($dom->createTextNode("0.00"));
            $allowanceCharge = $dom->createElement("detallista:allowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceChargeType", "ALLOWANCE_GLOBAL");
            $allowanceCharge->setAttribute("settlementType", "BILL_BACK");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AJ"));
            $monetaryAmountOrPercentage = $dom->createElement("detallista:monetaryAmountOrPercentage");
            $monetaryAmountOrPercentage = $allowanceCharge->appendChild($monetaryAmountOrPercentage);
            $rate = $dom->createElement("detallista:rate");
            $rate = $monetaryAmountOrPercentage->appendChild($rate);
            $rate->setAttribute("base", "INVOICE_VALUE");
            $percentage = $dom->createElement("detallista:percentage");
            $percentage = $rate->appendChild($percentage);
            $percentage->appendChild($dom->createTextNode("0.00"));
        }
        //fin descuentos
        //DETALLE
        $totalAmount = 0;
        $lines = 0;
        $partidan = 0;
        $i = 0;
        $cantidadArts = 0;
        foreach ($factura->partidas as $partida) {
            $partidan++;
            $cantidadArts = $partida->cantidad;
            $totalAmount += $partida->valorlleno;
            $lineItem = $dom->createElement("detallista:lineItem");
            $lineItem = $detallistaNode->appendChild($lineItem);
            $lineItem->setAttribute("type", "SimpleInvoiceLineItemType");
            $lineItem->setAttribute("number", $partidan);
            $tradeItemIdentification = $dom->createElement("detallista:tradeItemIdentification");
            $tradeItemIdentification = $lineItem->appendChild($tradeItemIdentification);
            $gtin = $dom->createElement("detallista:gtin");
            $gtin = $tradeItemIdentification->appendChild($gtin);
            $gtin->appendChild($dom->createTextNode(substr(limpiaespacios($partida->ean), 0, 14)));
            $alternateTradeItemIdentification = $dom->createElement("detallista:alternateTradeItemIdentification");
            $alternateTradeItemIdentification = $lineItem->appendChild($alternateTradeItemIdentification);
            $alternateTradeItemIdentification->setAttribute("type", "BUYER_ASSIGNED");
            $alternateTradeItemIdentification->appendChild($dom->createTextNode(cleanStrXML($partida->sku)));
            $tradeItemDescriptionInformation = $dom->createElement("detallista:tradeItemDescriptionInformation");
            $tradeItemDescriptionInformation = $lineItem->appendChild($tradeItemDescriptionInformation);
            $tradeItemDescriptionInformation->setAttribute("language", "ES");
            $longText = $dom->createElement("detallista:longText");
            $longText = $tradeItemDescriptionInformation->appendChild($longText);
            $longText->appendChild($dom->createTextNode(cleanStrXML(substr($partida->concepto, 0, 35))));
            $invoicedQuantity = $dom->createElement("detallista:invoicedQuantity");
            $invoicedQuantity = $lineItem->appendChild($invoicedQuantity);
            $invoicedQuantity->setAttribute("unitOfMeasure", "PZ");
            $invoicedQuantity->appendChild($dom->createTextNode($cantidadArts));
            $grossPrice = $dom->createElement("detallista:grossPrice");
            $grossPrice = $lineItem->appendChild($grossPrice);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $grossPrice->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->unitariolleno)));
            $netPrice = $dom->createElement("detallista:netPrice");
            $netPrice = $lineItem->appendChild($netPrice);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $netPrice->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->unitariolleno)));
            $totalLineAmount = $dom->createElement("detallista:totalLineAmount");
            $totalLineAmount = $lineItem->appendChild($totalLineAmount);
            $grossAmount = $dom->createElement("detallista:grossAmount");
            $grossAmount = $totalLineAmount->appendChild($grossAmount);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $grossAmount->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->valorlleno)));
            $netAmount = $dom->createElement("detallista:netAmount");
            $netAmount = $totalLineAmount->appendChild($netAmount);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $netAmount->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->valorlleno)));
        }
        //RESUMEN
        $totalAmount = $dom->createElement("detallista:totalAmount");
        $totalAmount = $detallistaNode->appendChild($totalAmount);
        $Amount = $dom->createElement("detallista:Amount");
        $Amount = $totalAmount->appendChild($Amount);
        $Amount->appendChild($dom->createTextNode(satNumber($factura->encabezado->subtotal)));
        /*	  	$totalDescuentos=0;
        		 $descuentosCnt=count($factura->descuentos);
        		 if($descuentosCnt>0){
        		 $motivosDescuento="";
        		 for($d=0;$d<$descuentosCnt;$d++){
        		 $descuentoObj=$factura->descuentos[$d];
        		 $totalDescuentos+=$descuentoObj->monto;
        		 if(exists($descuentoObj->motivo))
        		 $motivosDescuento.=" ".cleanStrXML($descuentoObj->motivo);
        		 }
        		 }
        		 */
        if (count($factura->descuentos) > 0) {
            foreach ($factura->descuentos as $descuentoglobal) {
                if ($descuentoglobal->porcentaje > 0) {
                    $allowanceCharge = $dom->createElement("detallista:TotalAllowanceCharge");
                    $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
                    $allowanceCharge->setAttribute("allowanceOrChargeType", "ALLOWANCE");
                    $specialServicesType = $dom->createElement("detallista:specialServicesType");
                    $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
                    $specialServicesType->appendChild($dom->createTextNode($CONST_LIV_AC[$descuentoglobal->motivo]));
                    $Amount = $dom->createElement("detallista:Amount");
                    $Amount = $allowanceCharge->appendChild($Amount);
                    $Amount->appendChild($dom->createTextNode(satNumber($descuentoglobal->monto)));
                }
            }
        } else {
            $allowanceCharge = $dom->createElement("detallista:TotalAllowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceOrChargeType", "ALLOWANCE");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AA"));
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $allowanceCharge->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode("0.00"));
            $allowanceCharge = $dom->createElement("detallista:TotalAllowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceOrChargeType", "ALLOWANCE");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AJ"));
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $allowanceCharge->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode("0.00"));
        }
    }
    return $ComplementoNode;
}
示例#2
0
function domSATV32($factura)
{
    global $tiposDoctoFiscal, $COMPLEMENTOS_NS, $COMPLEMENTOS_XSLT, $COMPLEMENTOS_XSD;
    //valida emisor.
    if (empty($factura->emisor['rfc'])) {
        echo "1ERROR EN EMPRESA PROCESANDO FACTURA ";
        return null;
    } else {
        if (strlen($factura->emisor['rfc']) < 12 || strlen($factura->emisor['rfc']) > 13) {
            echo "1ERROR EN EMPRESA PROCESANDO FACTURA ";
            return null;
        }
    }
    if (empty($factura->encabezado->metodoPago)) {
        echo "2ERROR EN METODO DE PAGO ";
        return null;
    }
    if (empty($factura->encabezado->lugarExpedicion)) {
        echo "3ERROR EN LUGAR DE EXPEDICION ";
        return null;
    }
    $dom = new DomDocument('1.0', 'UTF-8');
    //RAIZ: elemento raiz.
    $cfd = $dom->createElement("cfdi:Comprobante");
    $cfd = $dom->appendChild($cfd);
    //atributos del elemento raiz comprobante
    //determina si tiene complemento.
    $complementoNS = "";
    $complementoSLocation = "";
    $complementoHeader = "";
    if ($factura->complemento != NULL) {
        $complementoNS = $COMPLEMENTOS_NS[$factura->complemento->complemento];
        $complementoSLocation = $COMPLEMENTOS_XSD[$factura->complemento->complemento];
        $complementoHeader = str_replace("http://www.sat.gob.mx/", "", $complementoNS);
    }
    $cfd->setAttribute('xmlns:cfdi', 'http://www.sat.gob.mx/cfd/3');
    if (!empty($complementoNS)) {
        $cfd->setAttribute('xmlns:' . $complementoHeader, $complementoNS);
    }
    $schemaLocation = "http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd";
    if (!empty($complementoNS)) {
        $schemaLocation .= " {$complementoNS} {$complementoSLocation}";
    }
    $cfd->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
    $cfd->setAttribute('xsi:schemaLocation', $schemaLocation);
    $cfd->setAttribute('version', '3.2');
    if (isset($factura->encabezado->serie) && !empty($factura->encabezado->serie)) {
        $cfd->setAttribute('serie', $factura->encabezado->serie);
    }
    $cfd->setAttribute('folio', $factura->encabezado->folio);
    $cfd->setAttribute('fecha', $factura->encabezado->fechaemision . "T" . $factura->encabezado->horaemision);
    $cfd->setAttribute('sello', '%SELLO%');
    //PARA SER REMPLAZADO DESPUES.
    if ($factura->encabezado->formaDePago == 1 || empty($factura->encabezado->formaDePago)) {
        $factura->encabezado->formaDePago = "PAGO EN UNA SOLA EXHIBICION";
    }
    $cfd->setAttribute('formaDePago', cleanStrXML($factura->encabezado->formaDePago));
    $cfd->setAttribute('noCertificado', $factura->sello['noseriehex']);
    $cfd->setAttribute('certificado', $factura->sello['sello']);
    if (exists($factura->encabezado->condicionesPago)) {
        $cfd->setAttribute('condicionesDePago', cleanStrXML($factura->encabezado->condicionesPago));
    }
    $cfd->setAttribute('subTotal', satNumber($factura->encabezado->subtotal));
    $descuentosCnt = count($factura->descuentos);
    if ($descuentosCnt > 0) {
        $totalDescuentos = 0;
        $motivosDescuento = "";
        for ($d = 0; $d < $descuentosCnt; $d++) {
            $descuentoObj = $factura->descuentos[$d];
            $totalDescuentos += $descuentoObj->monto;
            if (exists($descuentoObj->motivo)) {
                $motivosDescuento .= " " . cleanStrXML($descuentoObj->motivo);
            }
        }
        if ($totalDescuentos > 0) {
            $cfd->setAttribute('descuento', satNumber($totalDescuentos));
        }
        $motivosDescuento = trim($motivosDescuento);
        if (exists($motivosDescuento)) {
            $cfd->setAttribute('motivoDescuento', cleanStrXML($motivosDescuento));
        }
    }
    $cfd->setAttribute('TipoCambio', satNumber($factura->encabezado->tipocambio));
    $cfd->setAttribute('Moneda', $factura->encabezado->moneda);
    $cfd->setAttribute('total', satNumber($factura->encabezado->total));
    $cfd->setAttribute('tipoDeComprobante', $tiposDoctoFiscal[$factura->encabezado->tipocfd]);
    //NUEVOS CAMPOS.
    $cfd->setAttribute('metodoDePago', cleanStrXML($factura->encabezado->metodoPago));
    $cfd->setAttribute('LugarExpedicion', cleanStrXML($factura->encabezado->lugarExpedicion));
    if (exists($factura->encabezado->numCtaPago)) {
        $cfd->setAttribute('NumCtaPago', cleanStrXML($factura->encabezado->numCtaPago));
    }
    if (exists($factura->encabezado->folioFiscalOrig)) {
        $cfd->setAttribute('FolioFiscalOrig', cleanStrXML($factura->encabezado->folioFiscalOrig));
    }
    if (exists($factura->encabezado->serieFolioFiscalOrig)) {
        $cfd->setAttribute('SerieFolioFiscalOrig', cleanStrXML($factura->encabezado->serieFolioFiscalOrig));
    }
    if (exists($factura->encabezado->fechaFolioFiscalOrig) && $factura->encabezado->fechaFolioFiscalOrig != "0000-00-00 00:00:00") {
        $fechaFFOrig = str_replace(" ", "T", trim($factura->encabezado->fechaFolioFiscalOrig));
        $cfd->setAttribute('FechaFolioFiscalOrig', cleanStrXML($fechaFFOrig));
    }
    if (exists($factura->encabezado->montoFolioFiscalOrig)) {
        $cfd->setAttribute('MontoFolioFiscalOrig', cleanStrXML($factura->encabezado->montoFolioFiscalOrig));
    }
    //HIJO: Emisor ->DomicilioFiscal  / ->ExpedidoEn
    $Emisor = $dom->createElement("cfdi:Emisor");
    $Emisor->setAttribute("rfc", cleanStrXML($factura->emisor['rfc']));
    if (exists($factura->emisor['razonsocial'])) {
        $Emisor->setAttribute("nombre", cleanStrXML($factura->emisor['razonsocial']));
    }
    $Emisor = $cfd->appendChild($Emisor);
    /*
    	2DO: ************ VOLVER OPCIONAL ******************
    */
    if (exists($factura->emisor['calle'])) {
        //domicilio fiscal del emisor
        $domiciliof = $dom->createElement("cfdi:DomicilioFiscal");
        $domiciliof = $cfd->appendChild($domiciliof);
        $domiciliof->setAttribute('calle', cleanStrXML($factura->emisor['calle']));
        if (exists($factura->emisor['noext'])) {
            $domiciliof->setAttribute('noExterior', cleanStrXML($factura->emisor['noext']));
        }
        if (exists($factura->emisor['noint'])) {
            $domiciliof->setAttribute('noInterior', cleanStrXML($factura->emisor['noint']));
        }
        if (exists($factura->emisor['Colonia'])) {
            $domiciliof->setAttribute('colonia', cleanStrXML($factura->emisor['Colonia']));
        }
        if (exists($factura->emisor['localidad'])) {
            $domiciliof->setAttribute('localidad', cleanStrXML($factura->emisor['localidad']));
        }
        if (exists($factura->emisor['referencia'])) {
            $domiciliof->setAttribute('referencia', cleanStrXML($factura->emisor['referencia']));
        }
        $domiciliof->setAttribute('municipio', cleanStrXML($factura->emisor['municipio']));
        $domiciliof->setAttribute('estado', cleanStrXML($factura->emisor['estado']));
        $domiciliof->setAttribute('pais', cleanStrXML($factura->emisor['pais']));
        $domiciliof->setAttribute('codigoPostal', cleanStrXML($factura->emisor['cp']));
        $domiciliof = $Emisor->appendChild($domiciliof);
        $Emisor = $cfd->appendChild($Emisor);
        //Expedido en, si existe sucursal.
        if (isset($factura->sucursal) && count($factura->sucursal) > 0) {
            //domicilio de la sucursal.
            $expedidoen = $dom->createElement("cfdi:ExpedidoEn");
            $expedidoen = $cfd->appendChild($expedidoen);
            if (exists($factura->sucursal['calle'])) {
                $expedidoen->setAttribute('calle', cleanStrXML($factura->sucursal['calle']));
            }
            if (exists($factura->sucursal['noext'])) {
                $expedidoen->setAttribute('noExterior', cleanStrXML($factura->sucursal['noext']));
            }
            if (exists($factura->sucursal['noint'])) {
                $expedidoen->setAttribute('noInterior', cleanStrXML($factura->sucursal['noint']));
            }
            if (exists($factura->sucursal['colonia'])) {
                $expedidoen->setAttribute('colonia', cleanStrXML($factura->sucursal['colonia']));
            }
            if (exists($factura->sucursal['localidad'])) {
                $expedidoen->setAttribute('localidad', cleanStrXML($factura->sucursal['localidad']));
            }
            if (exists($factura->sucursal['referencia'])) {
                $expedidoen->setAttribute('referencia', cleanStrXML($factura->sucursal['referencia']));
            }
            if (exists($factura->sucursal['municipio'])) {
                $expedidoen->setAttribute('municipio', cleanStrXML($factura->sucursal['municipio']));
            }
            if (exists($factura->sucursal['estado'])) {
                $expedidoen->setAttribute('estado', cleanStrXML($factura->sucursal['estado']));
            }
            $expedidoen->setAttribute('pais', cleanStrXML($factura->sucursal['pais']));
            if (exists($factura->sucursal['codigopostal'])) {
                $expedidoen->setAttribute('codigoPostal', cleanStrXML($factura->sucursal['codigopostal']));
            }
            $expedidoen = $Emisor->appendChild($expedidoen);
            $Emisor = $cfd->appendChild($Emisor);
        }
    }
    $regimenFiscal = $dom->createElement("cfdi:RegimenFiscal");
    $regimenFiscal = $cfd->appendChild($regimenFiscal);
    $regimenFiscal->setAttribute('Regimen', cleanStrXML($factura->emisor['regimen1']));
    $regimenFiscal = $Emisor->appendChild($regimenFiscal);
    $Emisor = $cfd->appendChild($Emisor);
    if (!empty($factura->emisor['regimen2'])) {
        $regimenFiscal = $dom->createElement("cfdi:RegimenFiscal");
        $regimenFiscal = $cfd->appendChild($regimenFiscal);
        $regimenFiscal->setAttribute('Regimen', cleanStrXML($factura->emisor['regimen2']));
        $regimenFiscal = $Emisor->appendChild($regimenFiscal);
        $Emisor = $cfd->appendChild($Emisor);
    }
    if (!empty($factura->emisor['regimen3'])) {
        $regimenFiscal = $dom->createElement("cfdi:RegimenFiscal");
        $regimenFiscal = $cfd->appendChild($regimenFiscal);
        $regimenFiscal->setAttribute('Regimen', cleanStrXML($factura->emisor['regimen3']));
        $regimenFiscal = $Emisor->appendChild($regimenFiscal);
        $Emisor = $cfd->appendChild($Emisor);
    }
    //fin del hijo EMISOR.
    //HIJO: RECEPTOR
    $Receptor = $dom->createElement("cfdi:Receptor");
    $Receptor = $cfd->appendChild($Receptor);
    $Receptor->setAttribute("rfc", $factura->encabezado->rfc);
    if (exists($factura->encabezado->razonsocial)) {
        $Receptor->setAttribute("nombre", cleanStrXML($factura->encabezado->razonsocial));
    }
    /*
    	2DO: ************ VOLVER OPCIONAL ******************
    */
    if (exists($factura->encabezado->calle)) {
        //Domicilio
        $domicilior = $dom->createElement("cfdi:Domicilio");
        $domicilior = $cfd->appendChild($domicilior);
        if (exists($factura->encabezado->calle)) {
            $domicilior->setAttribute('calle', cleanStrXML($factura->encabezado->calle));
        }
        if (exists($factura->encabezado->numeroext)) {
            $domicilior->setAttribute('noExterior', cleanStrXML($factura->encabezado->numeroext));
        }
        if (exists($factura->encabezado->numeroint)) {
            $domicilior->setAttribute('noInterior', cleanStrXML($factura->encabezado->numeroint));
        }
        if (exists($factura->encabezado->colonia)) {
            $domicilior->setAttribute('colonia', cleanStrXML($factura->encabezado->colonia));
        }
        if (exists($factura->encabezado->localidad)) {
            $domicilior->setAttribute('localidad', cleanStrXML($factura->encabezado->localidad));
        }
        if (exists($factura->encabezado->referencia)) {
            $domicilior->setAttribute('referencia', cleanStrXML($factura->encabezado->referencia));
        }
        if (exists($factura->encabezado->municipio)) {
            $domicilior->setAttribute('municipio', cleanStrXML($factura->encabezado->municipio));
        }
        if (exists($factura->encabezado->estado)) {
            $domicilior->setAttribute('estado', cleanStrXML($factura->encabezado->estado));
        }
        $domicilior->setAttribute('pais', cleanStrXML($factura->encabezado->pais));
        if (exists($factura->encabezado->cp)) {
            $domicilior->setAttribute('codigoPostal', cleanStrXML($factura->encabezado->cp));
        }
        $domicilior = $Receptor->appendChild($domicilior);
        $Receptor = $cfd->appendChild($Receptor);
    }
    $Receptor = $cfd->appendChild($Receptor);
    //fin del hijo Receptor.
    //HIJO CONCEPTOS.
    $ConceptosNode = $dom->createElement("cfdi:Conceptos");
    $ConceptosNode = $cfd->appendChild($ConceptosNode);
    //Nieto concepto
    foreach ($factura->partidas as $partida) {
        //Concepto
        if (empty($partida->concepto)) {
            echo "p1ERROR EN CONCEPTO DE LA PARTIDA, PROCESANDO FACTURA ";
            return null;
        }
        if (empty($partida->unitario)) {
            echo "p1ERROR EN PRECIO UNITARIO DE LA PARTIDA, PROCESANDO FACTURA ";
            return null;
        }
        if (empty($partida->valor)) {
            echo "p1ERROR EN IMPORTE DE LA PARTIDA, PROCESANDO FACTURA ";
            return null;
        }
        if (empty($partida->unidad)) {
            echo "p1ERROR EN UNIDAD DE LA PARTIDA, PROCESANDO FACTURA ";
            return null;
        }
        $item = $dom->createElement("cfdi:Concepto");
        $item = $ConceptosNode->appendChild($item);
        $item->setAttribute("cantidad", satNumber($partida->cantidad));
        if (exists($partida->unidad)) {
            $item->setAttribute("unidad", cleanStrXML($partida->unidad));
        }
        //número de identificación busca primero el EAN, si no hay el SKU.
        if (exists($partida->ean)) {
            $item->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($partida->ean)));
        } elseif (exists($partida->sku)) {
            $item->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($partida->sku)));
        }
        $item->setAttribute("descripcion", cleanStrXML($partida->concepto . " " . $partida->descripcion));
        $item->setAttribute("valorUnitario", satNumber($partida->unitario));
        $item->setAttribute("importe", satNumber($partida->importe));
        //PEDIMENTOS ADUANALES DE LA PARTIDA.
        if (!empty($partida->numaduana) && !empty($partida->fechaaduana)) {
            $pedimento = $dom->createElement("cfdi:InformacionAduanera");
            $pedimento = $item->appendChild($pedimento);
            $pedimento->setAttribute("numero", cleanStrXML($partida->numaduana));
            $pedimento->setAttribute("fecha", $partida->fechaaduana);
            if (!empty($partida->aduana)) {
                $pedimento->setAttribute("aduana", cleanStrXML($partida->aduana));
            }
        }
        //PEDIMENTOS ADICIONALES
        if (count($partida->otrospedimentos) > 0) {
            foreach ($partida->otrospedimentos as $ped) {
                $pedimento = $dom->createElement("cfdi:InformacionAduanera");
                $pedimento = $item->appendChild($pedimento);
                $pedimento->setAttribute("numero", $ped->aduananum);
                $pedimento->setAttribute("fecha", $ped->fechaaduana);
                if (!empty($ped->aduana)) {
                    $pedimento->setAttribute("aduana", cleanStrXML($ped->aduana));
                }
            }
        }
        //CUENTA PREDIAL.
        if (!empty($partida->ctaPredial)) {
            $ctaPredial = $dom->createElement("cfdi:CuentaPredial");
            $ctaPredial = $item->appendChild($ctaPredial);
            $ctaPredial->setAttribute("numero", $partida->ctaPredial);
        }
        //COMPLEMENTOS AL CONCEPTO.
        if (!empty($partida->descripcionextra)) {
            $complemento = $dom->createElement("cfdi:ComplementoConcepto");
            $complemento = $item->appendChild($complemento);
            $complemento->appendChild($dom->createTextNode($partida->descripcionextra));
        }
        //PARTES DE LA PARTIDA.
        if (count($partida->partes) > 0) {
            foreach ($partida->partes as $parte) {
                $partedom = $dom->createElement("cfdi:Parte");
                $partedom = $item->appendChild($partedom);
                $partedom->setAttribute("cantidad", satNumber($parte->cantidad));
                if (!empty($parte->unidad)) {
                    $partedom->setAttribute("unidad", $parte->unidad);
                }
                if (!empty($parte->ean)) {
                    $partedom->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($parte->ean)));
                } elseif (!empty($parte->sku)) {
                    $partedom->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($parte->sku)));
                }
                $partedom->setAttribute("descripcion", cleanStrXML($parte->descripcion));
                if (!empty($parte->unitario)) {
                    $partedom->setAttribute("valorUnitario", satNumber($parte->valorUnitario));
                }
                if (!empty($parte->importe)) {
                    $partedom->setAttribute("importe", satNumber($parte->importe));
                }
                //PEDIMENTO DE LA PARTE.
                if (!empty($parte->pedimento) && !empty($parte->fechapedimento)) {
                    $pedimento = $dom->createElement("cfdi:InformacionAduanera");
                    $pedimento = $partedom->appendChild($pedimento);
                    $pedimento->setAttribute("numero", $parte->pedimento);
                    $pedimento->setAttribute("fecha", $parte->fechapedimento);
                    if (!empty($parte->aduana)) {
                        $pedimento->setAttribute("aduana", cleanStrXML($parte->aduana));
                    }
                }
            }
        }
        //fin de partes de la partida.
    }
    //fin de conceptos
    //HIJO IMPUESTOS
    $ImpuestosNode = $dom->createElement("cfdi:Impuestos");
    $ImpuestosNode = $cfd->appendChild($ImpuestosNode);
    //calcula total retenciones y traslados
    if ($factura->encabezado->totalRetenciones != 0) {
        $ImpuestosNode->setAttribute("totalImpuestosRetenidos", satNumber($factura->encabezado->totalRetenciones));
    }
    if ($factura->encabezado->totaliva != 00) {
        $ImpuestosNode->setAttribute("totalImpuestosTrasladados", satNumber($factura->encabezado->totaliva));
    }
    //Impuestos Retenidos.
    if (count($factura->impuestosRetenidos) > 0) {
        $ImpuestosRet = $dom->createElement("cfdi:Retenciones");
        $ImpuestosRet = $ImpuestosNode->appendChild($ImpuestosRet);
        foreach ($factura->impuestosRetenidos as $imp) {
            $Ret = $dom->createElement("cfdi:Retencion");
            $Ret = $ImpuestosRet->appendChild($Ret);
            $Ret->setAttribute("impuesto", strtoupper($imp->tipo));
            $Ret->setAttribute("importe", satNumber($imp->monto));
        }
    }
    //Impuestos Trasladados.
    if (count($factura->impuestosTrasladados) > 0) {
        $ImpuestosTras = $dom->createElement("cfdi:Traslados");
        $ImpuestosTras = $ImpuestosNode->appendChild($ImpuestosTras);
        foreach ($factura->impuestosTrasladados as $imp) {
            $Tras = $dom->createElement("cfdi:Traslado");
            $Tras = $ImpuestosTras->appendChild($Tras);
            $Tras->setAttribute("impuesto", strtoupper($imp->tipo));
            $Tras->setAttribute("tasa", satNumber($imp->porcentaje));
            $Tras->setAttribute("importe", satNumber($imp->monto));
        }
    }
    //ANEXA COMPLEMENTO SI ES REQUERIDO.
    if ($factura->complemento != NULL) {
        $ComplementoNode = $dom->createElement("cfdi:Complemento");
        anexaComplemento($ComplementoNode, $factura->complemento, $dom);
        $ComplementoNode = $cfd->appendChild($ComplementoNode);
    }
    // we want a nice output (agregado por andres)
    $dom->formatOutput = true;
    //finaliza el documento.
    return $dom->saveXML();
}
示例#3
0
            $map_items .= "</gtin>\r\n\t\t\t\t\t\t\t</tradeItemIdentification>\r\n\t\t\t\t\t\t\t<alternateTradeItemIdentification type=\"BUYER_ASSIGNED\">" . cleanStrXML($partida->ean) . "</alternateTradeItemIdentification>\r\n\t\t\t\t\t\t\t<tradeItemDescriptionInformation language=\"ES\">\r\n\t\t\t\t\t\t\t\t<longText>" . substr(cleanStrXML($partida->concepto), 0, 35) . "</longText>\r\n\t\t\t\t\t\t\t</tradeItemDescriptionInformation>\r\n\t\t\t\t\t\t\t<invoicedQuantity unitOfMeasure= \"" . $partida->unidad . "\">" . $cantidadArts . "</invoicedQuantity>\r\n\t\t\t\t\t\t\t<grossPrice>\r\n\t\t\t\t\t           <Amount>" . satNumber($partida->unitariolleno) . "</Amount>\r\n\t\t\t\t            </grossPrice>\r\n\t\t\t\t            <palletInformation>\r\n\t\t\t\t\t<palletQuantity>1</palletQuantity>\r\n\t\t\t\t\t<description type=\"EXCHANGE_PALLETS\">Pallet</description>\r\n\t\t\t\t\t<transport>\r\n\t\t\t\t\t\t<methodOfPayment>PREPAID_BY_SELLER</methodOfPayment>\r\n\t\t\t\t\t</transport>\r\n\t\t\t\t</palletInformation>";
            if ($impuestoPartida != null) {
                $map_items .= "<tradeItemTaxInformation>\r\n\t\t\t\t\t\t\t     <taxTypeDescription>" . 'VAT' . "</taxTypeDescription>\r\n\t\t\t\t\t\t\t\t <tradeItemTaxAmount>\r\n\t\t\t\t\t\t\t\t    <taxPercentage>" . satNumber($impuestoPartida->porcentaje) . "</taxPercentage>\r\n                    <taxAmount>" . satNumber($impuestoPartida->monto) . "</taxAmount>\r\n\t\t\t\t\t\t\t\t </tradeItemTaxAmount>\r\n\t\t\t\t\t\t\t</tradeItemTaxInformation>";
            }
            $map_items .= "<totalLineAmount>\r\n\t\t\t\t\t\t\t\t<netAmount>\r\n\t\t\t\t\t\t\t\t\t<Amount>" . satNumber($partida->valor) . "</Amount>\r\n\t\t\t\t\t\t\t\t</netAmount>\r\n\t\t\t\t\t\t\t</totalLineAmount>\r\n\t\t\t\t\t\t</lineItem>";
        }
    }
    $totalDescuentos = 0;
    $descuentosCnt = count($factura->descuentos);
    if ($descuentosCnt > 0) {
        $motivosDescuento = "";
        for ($d = 0; $d < $descuentosCnt; $d++) {
            $descuentoObj = $factura->descuentos[$d];
            $totalDescuentos += $descuentoObj->monto;
            if (exists($descuentoObj->motivo)) {
                $motivosDescuento .= " " . cleanStrXML($descuentoObj->motivo);
            }
        }
    }
    $map_post = "\t<TotalAllowanceCharge allowanceOrChargeType=\"ALLOWANCE\">\r\n\t\t\t\t<Amount>" . satNumber($totalDescuentos) . "</Amount>\r\n\t\t\t</TotalAllowanceCharge>\r\n\t\t\t<baseAmount>\r\n\t\t\t\t<Amount>" . satNumber($factura->encabezado->subtotal) . "</Amount>\r\n\t\t\t</baseAmount>";
    $impstraslados = $factura->impuestosTrasladados;
    foreach ($impstraslados as $imp) {
        $map_post .= "<tax type=\"" . $CONST_LIV_TAXES[$imp->tipo] . "\">\r\n\t\t\t\t\t<taxPercentage>" . satNumber($imp->porcentaje) . "</taxPercentage>\r\n\t\t\t\t\t<taxAmount>" . satNumber($imp->monto) . "</taxAmount>\r\n\t\t\t\t</tax>";
    }
    $map_post .= "<payableAmount>\r\n\t\t\t\t<Amount>" . satNumber($factura->encabezado->total) . "</Amount>\r\n\t\t\t</payableAmount>\r\n\t\t</requestForPayment>";
    $map = $map_pre . $map_items . $map_post;
    //Registra adenda.
    $ADDENDA_MAPS["XML"] = $map;
}
//ADDENDA DE WALMART
if (isset($CADENASVSMAPAS[$HASHTABLE['addenda']]) && $CADENASVSMAPAS[$HASHTABLE['addenda']] == "EDIFACTD01B") {
function domSATDetallista($factura, $variables)
{
    global $tiposDoctoFiscal;
    $HASHTABLE = array_change_key_case($factura->addendaht, CASE_LOWER);
    global $CONST_LIV_AC;
    global $CONST_LIV_PROVS;
    $dom = new DomDocument('1.0', 'UTF-8');
    //RAIZ: elemento raiz.
    $cfd = $dom->createElement("Comprobante");
    $cfd = $dom->appendChild($cfd);
    //atributos del elemento raiz comprobante
    $cfd->setAttribute('xmlns', 'http://www.sat.gob.mx/cfd/2');
    $cfd->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
    $cfd->setAttribute('xmlns:detallista', "http://www.sat.gob.mx/detallista");
    $cfd->setAttribute('xsi:schemaLocation', "http://www.sat.gob.mx/cfd/2 http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv2.xsd http://www.sat.gob.mx/detallista http://www.sat.gob.mx/sitio_internet/cfd/detallista/detallista.xsd");
    $cfd->setAttribute('version', '2.0');
    $cfd->setAttribute('serie', $factura->encabezado->serie);
    $cfd->setAttribute('folio', $factura->encabezado->folio);
    $cfd->setAttribute('fecha', $factura->encabezado->fechaemision . "T" . $factura->encabezado->horaemision);
    $cfd->setAttribute('sello', '%SELLO%');
    //PARA SER REMPLAZADO DESPUES.
    $cfd->setAttribute('noAprobacion', $factura->foliosaprob['noaprob']);
    $cfd->setAttribute('anoAprobacion', $factura->foliosaprob['anoaprob']);
    $cfd->setAttribute('formaDePago', $factura->encabezado->formaDePago);
    $cfd->setAttribute('noCertificado', $factura->sello['noseriehex']);
    $cfd->setAttribute('certificado', $factura->sello['sello']);
    if (exists($factura->encabezado->condicionesPago)) {
        $cfd->setAttribute('condicionesDePago', cleanStrXML($factura->encabezado->condicionesPago));
    }
    $cfd->setAttribute('subTotal', satNumber($factura->encabezado->subtotal));
    $descuentosCnt = count($factura->descuentos);
    if ($descuentosCnt > 0) {
        $totalDescuentos = 0;
        $motivosDescuento = "";
        for ($d = 0; $d < $descuentosCnt; $d++) {
            $descuentoObj = $factura->descuentos[$d];
            $totalDescuentos += $descuentoObj->monto;
            if (exists($descuentoObj->motivo)) {
                $motivosDescuento .= " " . cleanStrXML($descuentoObj->motivo);
            }
        }
        if ($totalDescuentos > 0) {
            $cfd->setAttribute('descuento', satNumber($totalDescuentos));
        }
        $motivosDescuento = trim($motivosDescuento);
        if (exists($motivosDescuento)) {
            $cfd->setAttribute('motivoDescuento', cleanStrXML($motivosDescuento));
        }
    }
    $cfd->setAttribute('total', satNumber($factura->encabezado->total));
    if (exists($factura->encabezado->metodoPago)) {
        $cfd->setAttribute('metodoDePago', cleanStrXML($factura->encabezado->metodoPago));
    }
    $cfd->setAttribute('tipoDeComprobante', $tiposDoctoFiscal[$factura->encabezado->tipocfd]);
    //HIJO: Emisor ->DomicilioFiscal  / ->ExpedidoEn
    $Emisor = $dom->createElement("Emisor");
    $Emisor->setAttribute("rfc", cleanStrXML($factura->emisor['rfc']));
    $Emisor->setAttribute("nombre", cleanStrXML($factura->emisor['razonsocial']));
    $Emisor = $cfd->appendChild($Emisor);
    //domicilio fiscal del emisor
    $domiciliof = $dom->createElement("DomicilioFiscal");
    $domiciliof = $cfd->appendChild($domiciliof);
    $domiciliof->setAttribute('calle', cleanStrXML($factura->emisor['calle']));
    if (exists($factura->emisor['noExt'])) {
        $domiciliof->setAttribute('noExterior', cleanStrXML($factura->emisor['noExt']));
    }
    if (exists($factura->emisor['noInt'])) {
        $domiciliof->setAttribute('noInterior', cleanStrXML($factura->emisor['noInt']));
    }
    if (exists($factura->emisor['Colonia'])) {
        $domiciliof->setAttribute('colonia', cleanStrXML($factura->emisor['Colonia']));
    }
    if (exists($factura->emisor['localidad'])) {
        $domiciliof->setAttribute('localidad', cleanStrXML($factura->emisor['localidad']));
    }
    if (exists($factura->emisor['referencia'])) {
        $domiciliof->setAttribute('referencia', cleanStrXML($factura->emisor['referencia']));
    }
    $domiciliof->setAttribute('municipio', cleanStrXML($factura->emisor['municipio']));
    $domiciliof->setAttribute('estado', cleanStrXML($factura->emisor['estado']));
    $domiciliof->setAttribute('pais', cleanStrXML($factura->emisor['pais']));
    $domiciliof->setAttribute('codigoPostal', cleanStrXML($factura->emisor['cp']));
    $domiciliof = $Emisor->appendChild($domiciliof);
    $Emisor = $cfd->appendChild($Emisor);
    //Expedido en, si existe sucursal.
    if (isset($factura->sucursal) && count($factura->sucursal) > 0) {
        //domicilio de la sucursal.
        $expedidoen = $dom->createElement("ExpedidoEn");
        $expedidoen = $cfd->appendChild($expedidoen);
        if (exists($factura->sucursal['calle'])) {
            $expedidoen->setAttribute('calle', cleanStrXML($factura->sucursal['calle']));
        }
        if (exists($factura->sucursal['noext'])) {
            $expedidoen->setAttribute('noExterior', cleanStrXML($factura->sucursal['noext']));
        }
        if (exists($factura->sucursal['noint'])) {
            $expedidoen->setAttribute('noInterior', cleanStrXML($factura->sucursal['noint']));
        }
        if (exists($factura->sucursal['colonia'])) {
            $expedidoen->setAttribute('colonia', cleanStrXML($factura->sucursal['colonia']));
        }
        if (exists($factura->sucursal['localidad'])) {
            $expedidoen->setAttribute('localidad', cleanStrXML($factura->sucursal['localidad']));
        }
        if (exists($factura->sucursal['referencia'])) {
            $expedidoen->setAttribute('referencia', cleanStrXML($factura->sucursal['referencia']));
        }
        if (exists($factura->sucursal['municipio'])) {
            $expedidoen->setAttribute('municipio', cleanStrXML($factura->sucursal['municipio']));
        }
        if (exists($factura->sucursal['estado'])) {
            $expedidoen->setAttribute('estado', cleanStrXML($factura->sucursal['estado']));
        }
        $expedidoen->setAttribute('pais', cleanStrXML($factura->sucursal['pais']));
        if (exists($factura->sucursal['codigopostal'])) {
            $expedidoen->setAttribute('codigoPostal', cleanStrXML($factura->sucursal['codigopostal']));
        }
        $expedidoen = $Emisor->appendChild($expedidoen);
        $Emisor = $cfd->appendChild($Emisor);
    }
    //fin del hijo EMISOR.
    //HIJO: RECEPTOR
    $Receptor = $dom->createElement("Receptor");
    $Receptor = $cfd->appendChild($Receptor);
    $Receptor->setAttribute("rfc", $factura->encabezado->rfc);
    if (exists($factura->encabezado->razonsocial)) {
        $Receptor->setAttribute("nombre", $factura->encabezado->razonsocial);
    }
    //echo "--".$factura->encabezado->razonsocial."--";
    //Domicilio
    $domicilior = $dom->createElement("Domicilio");
    $domicilior = $cfd->appendChild($domicilior);
    if (exists($factura->encabezado->calle)) {
        $domicilior->setAttribute('calle', cleanStrXML($factura->encabezado->calle));
    }
    if (exists($factura->encabezado->numeroext)) {
        $domicilior->setAttribute('noExterior', cleanStrXML($factura->encabezado->numeroext));
    }
    if (exists($factura->encabezado->numeroint)) {
        $domicilior->setAttribute('noInterior', cleanStrXML($factura->encabezado->numeroint));
    }
    if (exists($factura->encabezado->colonia)) {
        $domicilior->setAttribute('colonia', cleanStrXML($factura->encabezado->colonia));
    }
    if (exists($factura->encabezado->localidad)) {
        $domicilior->setAttribute('localidad', cleanStrXML($factura->encabezado->localidad));
    }
    if (exists($factura->encabezado->referencia)) {
        $domicilior->setAttribute('referencia', cleanStrXML($factura->encabezado->referencia));
    }
    if (exists($factura->encabezado->municipio)) {
        $domicilior->setAttribute('municipio', cleanStrXML($factura->encabezado->municipio));
    }
    if (exists($factura->encabezado->estado)) {
        $domicilior->setAttribute('estado', cleanStrXML($factura->encabezado->estado));
    }
    $domicilior->setAttribute('pais', cleanStrXML($factura->encabezado->pais));
    if (exists($factura->encabezado->cp)) {
        $domicilior->setAttribute('codigoPostal', cleanStrXML($factura->encabezado->cp));
    }
    $domicilior = $Receptor->appendChild($domicilior);
    $Receptor = $cfd->appendChild($Receptor);
    $Receptor = $cfd->appendChild($Receptor);
    //fin del hijo Receptor.
    //HIJO CONCEPTOS.
    $ConceptosNode = $dom->createElement("Conceptos");
    $ConceptosNode = $cfd->appendChild($ConceptosNode);
    //Nieto concepto
    foreach ($factura->partidas as $partida) {
        //Concepto
        $item = $dom->createElement("Concepto");
        $item = $ConceptosNode->appendChild($item);
        $item->setAttribute("cantidad", $partida->cantidad);
        if (exists($partida->unidad)) {
            $item->setAttribute("unidad", $partida->unidad);
        }
        //número de identificación busca primero el EAN, si no hay el SKU.
        if (exists($partida->ean)) {
            $item->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($partida->ean)));
        } elseif (exists($partida->sku)) {
            $item->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($partida->sku)));
        }
        $item->setAttribute("descripcion", cleanStrXML($partida->concepto . " " . $partida->descripcion2));
        $item->setAttribute("valorUnitario", satNumber($partida->unitariolleno));
        $item->setAttribute("importe", satNumber($partida->valorlleno));
        //PEDIMENTOS ADUANALES DE LA PARTIDA.
        if (!empty($partida->numaduana) && !empty($partida->fechaaduana) && !empty($partida->aduana)) {
            $pedimento = $dom->createElement("InformacionAduanera");
            $pedimento = $item->appendChild($pedimento);
            $pedimento->setAttribute("numero", $partida->numaduana);
            $pedimento->setAttribute("fecha", $partida->fechaaduana);
            $pedimento->setAttribute("aduana", cleanStrXML($partida->aduana));
        }
        //PEDIMENTOS ADICIONALES
        if (count($partida->otrospedimentos) > 0) {
            foreach ($partida->otrospedimentos as $ped) {
                $pedimento = $dom->createElement("InformacionAduanera");
                $pedimento = $item->appendChild($pedimento);
                $pedimento->setAttribute("numero", $ped->aduananum);
                $pedimento->setAttribute("fecha", $ped->fechaaduana);
                $pedimento->setAttribute("aduana", cleanStrXML($ped->aduana));
            }
        }
        //CUENTA PREDIAL.
        if (!empty($partida->ctaPredial)) {
            $ctaPredial = $dom->createElement("CuentaPredial");
            $ctaPredial = $item->appendChild($ctaPredial);
            $ctaPredial->setAttribute("numero", $partida->ctaPredial);
        }
        //COMPLEMENTOS AL CONCEPTO.
        if (!empty($partida->descripcionextra)) {
            $complemento = $dom->createElement("ComplementoConcepto");
            $complemento = $item->appendChild($complemento);
            $complemento->appendChild($dom->createTextNode($partida->descripcionextra));
        }
        //PARTES DE LA PARTIDA.
        if (count($partida->partes) > 0) {
            foreach ($partida->partes as $parte) {
                $partedom = $dom->createElement("Parte");
                $partedom = $item->appendChild($partedom);
                $partedom->setAttribute("cantidad", $parte->cantidad);
                if (!empty($parte->unidad)) {
                    $partedom->setAttribute("unidad", $parte->unidad);
                }
                if (!empty($parte->ean)) {
                    $partedom->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($parte->ean)));
                } elseif (!empty($parte->sku)) {
                    $partedom->setAttribute("noIdentificacion", cleanStrXML(limpiaespacios($parte->sku)));
                }
                $partedom->setAttribute("descripcion", cleanStrXML($parte->descripcion));
                if (!empty($parte->unitario)) {
                    $partedom->setAttribute("valorUnitario", satNumber($parte->unitario));
                }
                if (!empty($parte->importe)) {
                    $partedom->setAttribute("importe", satNumber($parte->importe));
                }
                //PEDIMENTO DE LA PARTE.
                if (!empty($parte->aduana) && !empty($parte->pedimento) && !empty($parte->fechapedimento)) {
                    $pedimento = $dom->createElement("InformacionAduanera");
                    $pedimento = $partedom->appendChild($pedimento);
                    $pedimento->setAttribute("numero", $parte->pedimento);
                    $pedimento->setAttribute("fecha", $parte->fechapedimento);
                    $pedimento->setAttribute("aduana", cleanStrXML($parte->aduana));
                }
            }
        }
        //fin de partes de la partida.
    }
    //fin de conceptos
    //HIJO IMPUESTOS
    $ImpuestosNode = $dom->createElement("Impuestos");
    $ImpuestosNode = $cfd->appendChild($ImpuestosNode);
    //calcula total retenciones y traslados
    if ($factura->encabezado->totalRetenciones > 0) {
        $ImpuestosNode->setAttribute("totalImpuestosRetenidos", satNumber($factura->encabezado->totalRetenciones));
    }
    if ($factura->encabezado->totalTraslados > 0) {
        $ImpuestosNode->setAttribute("totalImpuestosTrasladados", satNumber($factura->encabezado->totalTraslados));
    }
    //Impuestos Retenidos.
    if (count($factura->impuestosRetenidos) > 0) {
        $ImpuestosRet = $dom->createElement("Retenciones");
        $ImpuestosRet = $ImpuestosNode->appendChild($ImpuestosRet);
        foreach ($factura->impuestosRetenidos as $imp) {
            $Ret = $dom->createElement("Retencion");
            $Ret = $ImpuestosRet->appendChild($Ret);
            $Ret->setAttribute("impuesto", strtoupper($imp->tipo));
            $Ret->setAttribute("importe", satNumber($imp->monto));
        }
    }
    //Impuestos Trasladados.
    if (count($factura->impuestosTrasladados) > 0) {
        $ImpuestosTras = $dom->createElement("Traslados");
        $ImpuestosTras = $ImpuestosNode->appendChild($ImpuestosTras);
        foreach ($factura->impuestosTrasladados as $imp) {
            $Tras = $dom->createElement("Traslado");
            $Tras = $ImpuestosTras->appendChild($Tras);
            $Tras->setAttribute("impuesto", strtoupper($imp->tipo));
            $Tras->setAttribute("tasa", satNumber($imp->porcentaje));
            $Tras->setAttribute("importe", satNumber($imp->monto));
        }
    }
    //COMPLEMENTO [PENDIENTE DE DEFINICION SAT]
    //DETALLISTA
    if (count($factura->addendaht) > 0) {
        //HIJO DETALLISTA
        $ComplementoNode = $dom->createElement("Complemento");
        $ComplementoNode = $cfd->appendChild($ComplementoNode);
        $detallistaNode = $dom->createElement("detallista:detallista");
        $detallistaNode = $ComplementoNode->appendChild($detallistaNode);
        $detallistaNode->setAttribute("type", "SimpleInvoiceType");
        $detallistaNode->setAttribute("documentStructureVersion", "AMC8.1");
        $detallistaNode->setAttribute("documentStatus", "ORIGINAL");
        $detallistaNode->setAttribute("contentVersion", "1.3.1");
        $requestForPaymentIdentification = $dom->createElement("detallista:requestForPaymentIdentification");
        $requestForPaymentIdentification = $detallistaNode->appendChild($requestForPaymentIdentification);
        $entityType = $dom->createElement("detallista:entityType");
        $entityType = $requestForPaymentIdentification->appendChild($entityType);
        $entityType->appendChild($dom->createTextNode("INVOICE"));
        $specialInstruction = $dom->createElement("detallista:specialInstruction");
        $specialInstruction = $detallistaNode->appendChild($specialInstruction);
        $specialInstruction->setAttribute("code", "ZZZ");
        $text = $dom->createElement("detallista:text");
        $text = $specialInstruction->appendChild($text);
        $text->appendChild($dom->createTextNode($HASHTABLE['tx_amo']));
        $orderIdentification = $dom->createElement("detallista:orderIdentification");
        $orderIdentification = $detallistaNode->appendChild($orderIdentification);
        $referenceIdentification = $dom->createElement("detallista:referenceIdentification");
        $referenceIdentification = $orderIdentification->appendChild($referenceIdentification);
        $referenceIdentification->setAttribute("type", "ON");
        //orden de compra, pedido.
        $ON = "A_PO_ID";
        $value = trim($HASHTABLE['po_id']);
        if (isset($HASHTABLE['po_id']) & !empty($value)) {
            $ON = $value;
        }
        $referenceIdentification->appendChild($dom->createTextNode($ON));
        $ReferenceDate = $dom->createElement("detallista:ReferenceDate");
        $ReferenceDate = $orderIdentification->appendChild($ReferenceDate);
        //fecha del pedido.
        $fecha = "A_PO_DAT";
        $value = trim($HASHTABLE['po_dat']);
        if (isset($HASHTABLE['po_dat']) & !empty($value)) {
            $fecha = $value;
        }
        $ReferenceDate->appendChild($dom->createTextNode($fecha));
        $AdditionalInformation = $dom->createElement("detallista:AdditionalInformation");
        $AdditionalInformation = $detallistaNode->appendChild($AdditionalInformation);
        $referenceIdentification = $dom->createElement("detallista:referenceIdentification");
        $referenceIdentification = $AdditionalInformation->appendChild($referenceIdentification);
        $referenceIdentification->setAttribute("type", "ATZ");
        $referenceIdentification->appendChild($dom->createTextNode($factura->foliosaprob['noaprob']));
        $DeliveryNote = $dom->createElement("detallista:DeliveryNote");
        $DeliveryNote = $detallistaNode->appendChild($DeliveryNote);
        $referenceIdentification_dn = $dom->createElement("detallista:referenceIdentification");
        $referenceIdentification_dn = $DeliveryNote->appendChild($referenceIdentification_dn);
        //contrarecibo de entrega.
        $dnid = "A_DN_ID";
        $value = trim($HASHTABLE['dn_id']);
        if (isset($HASHTABLE['dn_id']) & !empty($value)) {
            $dnid = $value;
        }
        $referenceIdentification_dn->appendChild($dom->createTextNode($dnid));
        $ReferenceDate_dn = $dom->createElement("detallista:ReferenceDate");
        $ReferenceDate_dn = $DeliveryNote->appendChild($ReferenceDate_dn);
        //fecha de entrega.
        $dndat = "A_DN_DAT";
        $value = $HASHTABLE['dn_dat'];
        if (isset($HASHTABLE['dn_dat']) & !empty($value) && $value != '0000-00-00') {
            $dndat = $value;
        }
        $ReferenceDate_dn->appendChild($dom->createTextNode($dndat));
        $buyer = $dom->createElement("detallista:buyer");
        $buyer = $detallistaNode->appendChild($buyer);
        $gln = $dom->createElement("detallista:gln");
        $gln = $buyer->appendChild($gln);
        $gln->appendChild($dom->createTextNode("0007504000107"));
        $contactInformation = $dom->createElement("detallista:contactInformation");
        $contactInformation = $buyer->appendChild($contactInformation);
        $personOrDepartmentName = $dom->createElement("detallista:personOrDepartmentName");
        $personOrDepartmentName = $contactInformation->appendChild($personOrDepartmentName);
        $text = $dom->createElement("detallista:text");
        $text = $personOrDepartmentName->appendChild($text);
        //comprador.
        $buyerper = "A_BUYER_PER";
        $value = trim($HASHTABLE['bu_per']);
        if (isset($HASHTABLE['bu_per']) & !empty($value)) {
            $buyerper = $value;
        }
        $text->appendChild($dom->createTextNode($buyerper));
        $seller = $dom->createElement("detallista:seller");
        $seller = $detallistaNode->appendChild($seller);
        $gln = $dom->createElement("detallista:gln");
        $gln = $seller->appendChild($gln);
        $gln->appendChild($dom->createTextNode("5896125468333"));
        $alternatePartyIdentification = $dom->createElement("detallista:alternatePartyIdentification");
        $alternatePartyIdentification = $seller->appendChild($alternatePartyIdentification);
        $alternatePartyIdentification->setAttribute("type", "SELLER_ASSIGNED_IDENTIFIER_FOR_A_PARTY");
        $alternatePartyIdentification->appendChild($dom->createTextNode($CONST_LIV_PROVS[$factura->encabezado->sucursal]));
        if (count($factura->descuentos) > 0) {
            foreach ($factura->descuentos as $descuentoglobal) {
                if ($descuentoglobal->porcentaje > 0) {
                    $allowanceCharge = $dom->createElement("detallista:allowanceCharge");
                    $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
                    $allowanceCharge->setAttribute("allowanceChargeType", "ALLOWANCE_GLOBAL");
                    $allowanceCharge->setAttribute("settlementType", "BILL_BACK");
                    $specialServicesType = $dom->createElement("detallista:specialServicesType");
                    $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
                    $specialServicesType->appendChild($dom->createTextNode($CONST_LIV_AC[$descuentoglobal->motivo]));
                    $monetaryAmountOrPercentage = $dom->createElement("detallista:monetaryAmountOrPercentage");
                    $monetaryAmountOrPercentage = $allowanceCharge->appendChild($monetaryAmountOrPercentage);
                    $rate = $dom->createElement("detallista:rate");
                    $rate = $monetaryAmountOrPercentage->appendChild($rate);
                    $rate->setAttribute("base", "INVOICE_VALUE");
                    $percentage = $dom->createElement("detallista:percentage");
                    $percentage = $rate->appendChild($percentage);
                    $percentage->appendChild($dom->createTextNode(satNumber($descuentoglobal->porcentaje)));
                }
            }
        } else {
            $allowanceCharge = $dom->createElement("detallista:allowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceChargeType", "ALLOWANCE_GLOBAL");
            $allowanceCharge->setAttribute("settlementType", "BILL_BACK");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AA"));
            $monetaryAmountOrPercentage = $dom->createElement("detallista:monetaryAmountOrPercentage");
            $monetaryAmountOrPercentage = $allowanceCharge->appendChild($monetaryAmountOrPercentage);
            $rate = $dom->createElement("detallista:rate");
            $rate = $monetaryAmountOrPercentage->appendChild($rate);
            $rate->setAttribute("base", "INVOICE_VALUE");
            $percentage = $dom->createElement("detallista:percentage");
            $percentage = $rate->appendChild($percentage);
            $percentage->appendChild($dom->createTextNode("0.00"));
            $allowanceCharge = $dom->createElement("detallista:allowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceChargeType", "ALLOWANCE_GLOBAL");
            $allowanceCharge->setAttribute("settlementType", "BILL_BACK");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AJ"));
            $monetaryAmountOrPercentage = $dom->createElement("detallista:monetaryAmountOrPercentage");
            $monetaryAmountOrPercentage = $allowanceCharge->appendChild($monetaryAmountOrPercentage);
            $rate = $dom->createElement("detallista:rate");
            $rate = $monetaryAmountOrPercentage->appendChild($rate);
            $rate->setAttribute("base", "INVOICE_VALUE");
            $percentage = $dom->createElement("detallista:percentage");
            $percentage = $rate->appendChild($percentage);
            $percentage->appendChild($dom->createTextNode("0.00"));
        }
        //fin descuentos
        //DETALLE
        $totalAmount = 0;
        $lines = 0;
        $partidan = 0;
        $i = 0;
        $cantidadArts = 0;
        foreach ($factura->partidas as $partida) {
            $partidan++;
            $cantidadArts = $partida->cantidad;
            $totalAmount += $partida->valorlleno;
            $lineItem = $dom->createElement("detallista:lineItem");
            $lineItem = $detallistaNode->appendChild($lineItem);
            $lineItem->setAttribute("type", "SimpleInvoiceLineItemType");
            $lineItem->setAttribute("number", $partidan);
            $tradeItemIdentification = $dom->createElement("detallista:tradeItemIdentification");
            $tradeItemIdentification = $lineItem->appendChild($tradeItemIdentification);
            $gtin = $dom->createElement("detallista:gtin");
            $gtin = $tradeItemIdentification->appendChild($gtin);
            $gtin->appendChild($dom->createTextNode(limpiaespacios($partida->ean)));
            $alternateTradeItemIdentification = $dom->createElement("detallista:alternateTradeItemIdentification");
            $alternateTradeItemIdentification = $lineItem->appendChild($alternateTradeItemIdentification);
            $alternateTradeItemIdentification->setAttribute("type", "BUYER_ASSIGNED");
            $alternateTradeItemIdentification->appendChild($dom->createTextNode(cleanStrXML($partida->sku)));
            $tradeItemDescriptionInformation = $dom->createElement("detallista:tradeItemDescriptionInformation");
            $tradeItemDescriptionInformation = $lineItem->appendChild($tradeItemDescriptionInformation);
            $tradeItemDescriptionInformation->setAttribute("language", "ES");
            $longText = $dom->createElement("detallista:longText");
            $longText = $tradeItemDescriptionInformation->appendChild($longText);
            $longText->appendChild($dom->createTextNode(cleanStrXML(substr($partida->concepto, 0, 35))));
            $invoicedQuantity = $dom->createElement("detallista:invoicedQuantity");
            $invoicedQuantity = $lineItem->appendChild($invoicedQuantity);
            $invoicedQuantity->setAttribute("unitOfMeasure", "PZ");
            $invoicedQuantity->appendChild($dom->createTextNode($cantidadArts));
            $grossPrice = $dom->createElement("detallista:grossPrice");
            $grossPrice = $lineItem->appendChild($grossPrice);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $grossPrice->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->unitariolleno)));
            $netPrice = $dom->createElement("detallista:netPrice");
            $netPrice = $lineItem->appendChild($netPrice);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $netPrice->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->unitariolleno)));
            $totalLineAmount = $dom->createElement("detallista:totalLineAmount");
            $totalLineAmount = $lineItem->appendChild($totalLineAmount);
            $grossAmount = $dom->createElement("detallista:grossAmount");
            $grossAmount = $totalLineAmount->appendChild($grossAmount);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $grossAmount->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->valorlleno)));
            $netAmount = $dom->createElement("detallista:netAmount");
            $netAmount = $totalLineAmount->appendChild($netAmount);
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $netAmount->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode(satNumber($partida->valorlleno)));
        }
        //RESUMEN
        $totalAmount = $dom->createElement("detallista:totalAmount");
        $totalAmount = $detallistaNode->appendChild($totalAmount);
        $Amount = $dom->createElement("detallista:Amount");
        $Amount = $totalAmount->appendChild($Amount);
        $Amount->appendChild($dom->createTextNode(satNumber($factura->encabezado->subtotal)));
        /*	  	$totalDescuentos=0;
        			$descuentosCnt=count($factura->descuentos);
        				if($descuentosCnt>0){
        					$motivosDescuento="";
        					for($d=0;$d<$descuentosCnt;$d++){
        						$descuentoObj=$factura->descuentos[$d];
        						$totalDescuentos+=$descuentoObj->monto;
        						if(exists($descuentoObj->motivo))
        							$motivosDescuento.=" ".cleanStrXML($descuentoObj->motivo);
        					}
        				}
        */
        if (count($factura->descuentos) > 0) {
            foreach ($factura->descuentos as $descuentoglobal) {
                if ($descuentoglobal->porcentaje > 0) {
                    $allowanceCharge = $dom->createElement("detallista:TotalAllowanceCharge");
                    $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
                    $allowanceCharge->setAttribute("allowanceOrChargeType", "ALLOWANCE");
                    $specialServicesType = $dom->createElement("detallista:specialServicesType");
                    $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
                    $specialServicesType->appendChild($dom->createTextNode($CONST_LIV_AC[$descuentoglobal->motivo]));
                    $Amount = $dom->createElement("detallista:Amount");
                    $Amount = $allowanceCharge->appendChild($Amount);
                    $Amount->appendChild($dom->createTextNode(satNumber($descuentoglobal->monto)));
                }
            }
        } else {
            $allowanceCharge = $dom->createElement("detallista:TotalAllowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceOrChargeType", "ALLOWANCE");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AA"));
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $allowanceCharge->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode("0.00"));
            $allowanceCharge = $dom->createElement("detallista:TotalAllowanceCharge");
            $allowanceCharge = $detallistaNode->appendChild($allowanceCharge);
            $allowanceCharge->setAttribute("allowanceOrChargeType", "ALLOWANCE");
            $specialServicesType = $dom->createElement("detallista:specialServicesType");
            $specialServicesType = $allowanceCharge->appendChild($specialServicesType);
            $specialServicesType->appendChild($dom->createTextNode("AJ"));
            $Amount = $dom->createElement("detallista:Amount");
            $Amount = $allowanceCharge->appendChild($Amount);
            $Amount->appendChild($dom->createTextNode("0.00"));
        }
    }
    //finaliza el documento.
    $xmlBody = $dom->saveXML();
    if (count($variables) > 0) {
        $A_DE_DAT = $variables['A_DE_DAT'];
        $A_PO_ID = $variables['A_PO_ID'];
        $A_DN_ID = $variables['A_DN_ID'];
        $A_DN_DAT = $variables['A_DN_DAT'];
        $A_BUYER_PER = $variables['A_BUYER_PER'];
        $A_SH_KNO = $variables['A_SH_KNO'];
        $A_PO_DAT = $variables['A_PO_DAT'];
        $xmlBody = str_replace('A_DE_DAT', $A_DE_DAT, $xmlBody);
        $xmlBody = str_replace('A_PO_ID', $A_PO_ID, $xmlBody);
        $xmlBody = str_replace('A_PO_DAT', $A_PO_DAT, $xmlBody);
        $xmlBody = str_replace('A_DN_ID', $A_DN_ID, $xmlBody);
        $xmlBody = str_replace('A_DN_DAT', $A_DN_DAT, $xmlBody);
        $xmlBody = str_replace('A_BUYER_PER', $A_BUYER_PER, $xmlBody);
        $xmlBody = str_replace('A_SH_KNO', $A_SH_KNO, $xmlBody);
    }
    return $xmlBody;
}