Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Factura\Controller;
- use BigFish\PDF417\PDF417;
- use BigFish\PDF417\Renderers\ImageRenderer;
- use Factura\Model\Entity\DetalleModel;
- use Factura\Model\Entity\FacturaModel;
- use Principal\Plugin\PDFPlugin;
- use Zend\Mvc\Controller\AbstractActionController;
- use Zend\View\Model\ViewModel;
- class IndexController extends AbstractActionController
- {
- public function indexAction()
- {
- return new ViewModel();
- }
- public function crearAction()
- {
- $id = $this->params()->fromRoute("id", null);
- $this->dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');
- $FacturaCabecera = new FacturaModel($this->dbAdapter);
- $FacturaDetalle = new DetalleModel($this->dbAdapter);
- $Documento = $FacturaCabecera->getUnaFactura($id);
- if($Documento{0}[detalle].length==0){
- $Detalles = $FacturaDetalle->getUnDetalleTotal($id);
- }else{
- $Detalles = $FacturaDetalle->getUnDetalleCompartido($id);
- var_dump($Detalles[0]['detalle']);
- exit();
- }
- $FacturaCabecera->envioSunat($id);
- //Datos del Cliente
- $RUC_Emisor = '20565381785';
- $RazonSocialEmisor = 'CRUCERISTA CENTER E.I.R.L.';
- $TipoDocumentoEmisor = "6";
- $UbigeoEmisor = 999;
- $DireccionEmisor = 'JR. JULIAN PINEIRO NRO. 113 INT. 178 C.C. 7 DE AGOSTO';
- $DepartamentoEmisor = 'LIMA';
- $ProvinciaEmisor = 'LIMA';
- $DistritoEmisor = 'RIMAC';
- $PaisEmisor = "PE";
- //Datos del Adquiriente
- $RUCAdquiriente = $Documento[0]['dni'];
- $RazonSocialAdquiriente = $Documento[0]['nombre'];
- //Datos del Documento
- $Serie = $Documento[0]['serie'];
- $Numero = $Documento[0]['numero'];
- $FacturaNumero = $Serie . "-" . $Numero;
- $FechaEmision = $Documento[0]['fecha'];
- $FechaVencimiento = $Documento[0]['fecha'];
- $TipoDocumento = $Documento[0]['tipodoc'];
- $TotalGeneral = $Documento[0]['monto'];
- $Gravada = $Documento[0]['subtotal'];
- $SumatoriaIGV_Total = $Documento[0]['igv'];
- $Letras = $this->Letras();
- $MontoLetras = $Letras->num2letras($TotalGeneral, 1);
- $xml = new \DomDocument("1.0", "UTF-8");
- $xml->formatOutput = true;
- //Cabecera de la Factura
- $Invoice = $xml->createElementNS("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2", "Invoice");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ccts", "urn:un:unece:uncefact:documentation:2");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
- $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
- $UBLExtensiones = $xml->createElement("ext:UBLExtensions");
- $UBLExtension = $UBLExtensiones->appendChild($xml->createElement("ext:UBLExtension"));
- $UBLExtension->appendChild($xml->createElement("ext:ExtensionContent"));
- $UBLExtensiones->appendChild($UBLExtension);
- $Invoice->appendChild($UBLExtensiones);
- $Invoice->appendChild($xml->createElement("cbc:UBLVersionID", "2.1"));
- $Invoice->appendChild($xml->createElement("cbc:CustomizationID", "2.0"));
- $Invoice->appendChild($xml->createElement("cbc:ID", $FacturaNumero));
- $Invoice->appendChild($xml->createElement("cbc:IssueDate", date("Y-m-d", strtotime($FechaEmision))));
- $Invoice->appendChild($xml->createElement("cbc:IssueTime", date("H:i:s")));
- $Invoice->appendChild($xml->createElement("cbc:DueDate", date("Y-m-d", strtotime($FechaVencimiento))));
- $InvoiceTypeCode = $Invoice->appendChild($xml->createElement("cbc:InvoiceTypeCode", $TipoDocumento));
- $InvoiceTypeCode->setAttribute("listID", "0101");
- $InvoiceTypeCode->setAttribute("listAgencyName", "PE:SUNAT");
- $InvoiceTypeCode->setAttribute("listName", "SUNAT:Identificador de Tipo de Documento");
- $InvoiceTypeCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01");
- $Note = $Invoice->appendChild($xml->createElement("cbc:Note", $MontoLetras));
- $Note->setAttribute("languageLocaleID", "1000");
- $DocumentCurrencyCode = $Invoice->appendChild($xml->createElement("cbc:DocumentCurrencyCode", "PEN"));
- $DocumentCurrencyCode->setAttribute("listID", "ISO 4217 Alpha");
- $DocumentCurrencyCode->setAttribute("listName", "Currency");
- $DocumentCurrencyCode->setAttribute("listAgencyName", "United Nations Economic Commission for Europe");
- $Invoice->appendChild($xml->createElement("cbc:LineCountNumeric", 1));
- //Firma Digital
- $Signature = $Invoice->appendChild($xml->createElement("cac:Signature"));
- $Signature->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
- $SignatoryParty = $Signature->appendChild($xml->createElement("cac:SignatoryParty"));
- $PartyIdentification = $SignatoryParty->appendChild($xml->createElement("cac:PartyIdentification"));
- $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
- $PartyName = $SignatoryParty->appendChild($xml->createElement("cac:PartyName"));
- $PartyName->appendChild($xml->createElement("cbc:Name", $RazonSocialEmisor));
- $DigitalSignatureAttachment = $Signature->appendChild($xml->createElement("cac:DigitalSignatureAttachment"));
- $ExternalReference = $DigitalSignatureAttachment->appendChild($xml->createElement("cac:ExternalReference"));
- $ExternalReference->appendChild($xml->createElement("cbc:URI", $RazonSocialEmisor));
- //Fin Firma Digital
- $AccountingSupplierParty = $xml->createElement("cac:AccountingSupplierParty");
- $Party = $AccountingSupplierParty->appendChild($xml->createElement("cac:Party"));
- $PartyIdentification = $Party->appendChild($xml->createElement("cac:PartyIdentification"));
- $ID = $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
- $ID->setAttribute("schemeID", $TipoDocumentoEmisor);
- $ID->setAttribute("schemeName", "SUNAT:Identificador de Documento de Identidad");
- $ID->setAttribute("schemeAgencyName", "PE:SUNAT");
- $ID->setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06");
- $PartyName = $Party->appendChild($xml->createElement("cac:PartyName"));
- $PartyName->appendChild($xml->createElement("cbc:Name", $RazonSocialEmisor));
- $PartyLegalEntity = $Party->appendChild($xml->createElement("cac:PartyLegalEntity"));
- $PartyLegalEntity->appendChild($xml->createElement("cbc:RegistrationName", $RazonSocialEmisor));
- $RegistrationAddress = $PartyLegalEntity->appendChild($xml->createElement("cac:RegistrationAddress"));
- $RegistrationAddress->appendChild($xml->createElement("cbc:ID", $UbigeoEmisor));
- $RegistrationAddress->appendChild($xml->createElement("cbc:AddressTypeCode", "0001"));
- $RegistrationAddress->appendChild($xml->createElement("cbc:CitySubdivisionName", "NONE"));
- $RegistrationAddress->appendChild($xml->createElement("cbc:CityName", $DepartamentoEmisor));
- $RegistrationAddress->appendChild($xml->createElement("cbc:CountrySubentity", $ProvinciaEmisor));
- $RegistrationAddress->appendChild($xml->createElement("cbc:District", $DistritoEmisor));
- $AddressLine = $RegistrationAddress->appendChild($xml->createElement("cac:AddressLine"));
- $AddressLine->appendChild($xml->createElement("cbc:Line", $DireccionEmisor));
- $Country = $RegistrationAddress->appendChild($xml->createElement("cac:Country"));
- $Country->appendChild($xml->createElement("cbc:IdentificationCode", $PaisEmisor));
- $PartyLegalEntity->appendChild($RegistrationAddress);
- $Invoice->appendChild($AccountingSupplierParty);
- $AccountingCustomerParty = $xml->createElement("cac:AccountingCustomerParty");
- $Party = $AccountingCustomerParty->appendChild($xml->createElement("cac:Party"));
- $PartyIdentification = $Party->appendChild($xml->createElement("cac:PartyIdentification"));
- $ID = $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUCAdquiriente));
- $ID->setAttribute("schemeID", "6");
- $ID->setAttribute("schemeName", "SUNAT:Identificador de Documento de Identidad");
- $ID->setAttribute("schemeAgencyName", "PE:SUNAT");
- $ID->setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06");
- $PartyLegalEntity = $Party->appendChild($xml->createElement("cac:PartyLegalEntity"));
- $PartyLegalEntity->appendChild($xml->createElement("cbc:RegistrationName", $RazonSocialAdquiriente));
- $RegistrationAddress = $PartyLegalEntity->appendChild($xml->createElement("cac:RegistrationAddress"));
- $AddressLine = $RegistrationAddress->appendChild($xml->createElement("cac:AddressLine"));
- $AddressLine->appendChild($xml->createElement("cbc:Line", $DireccionEmisor));
- $Country = $RegistrationAddress->appendChild($xml->createElement("cac:Country"));
- $Country->appendChild($xml->createElement("cbc:IdentificationCode", $PaisEmisor));
- $PartyLegalEntity->appendChild($RegistrationAddress);
- $Invoice->appendChild($AccountingCustomerParty);
- //Sumatoria IGV
- $TaxTotal0 = $xml->createElement("cac:TaxTotal");
- $TaxAmount0 = $TaxTotal0->appendChild($xml->createElement("cbc:TaxAmount", $SumatoriaIGV_Total));
- $TaxAmount0->setAttribute("currencyID", "PEN");
- $TaxSubtotal = $TaxTotal0->appendChild($xml->createElement("cac:TaxSubtotal"));
- $TaxableAmount = $TaxSubtotal->appendChild($xml->createElement("cbc:TaxableAmount", $Gravada));
- $TaxableAmount->setAttribute("currencyID", "PEN");
- $TaxAmount = $TaxSubtotal->appendChild($xml->createElement("cbc:TaxAmount", $SumatoriaIGV_Total));
- $TaxAmount->setAttribute("currencyID", "PEN");
- $TaxCategory1 = $TaxSubtotal->appendChild($xml->createElement("cac:TaxCategory"));
- $ID = $TaxCategory1->appendChild($xml->createElement("cbc:ID", "S"));
- $ID->setAttribute("schemeID", "UN/ECE 5305");
- $ID->setAttribute("schemeName", "Tax Category Identifier");
- $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
- $TaxScheme = $TaxCategory1->appendChild($xml->createElement("cac:TaxScheme"));
- $ID = $TaxScheme->appendChild($xml->createElement("cbc:ID", 1000));
- $ID->setAttribute("schemeID", "UN/ECE 5305");
- $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
- $TaxScheme->appendChild($xml->createElement("cbc:Name", "IGV"));
- $TaxScheme->appendChild($xml->createElement("cbc:TaxTypeCode", "VAT"));
- $Invoice->appendChild($TaxTotal0);
- $LegalMonetaryTotal = $xml->createElement("cac:LegalMonetaryTotal");
- $LineExtensionAmount = $xml->createElement("cbc:LineExtensionAmount", $Gravada);
- $LineExtensionAmount->setAttribute("currencyID", "PEN");
- $PayableAmount = $xml->createElement("cbc:PayableAmount", $TotalGeneral);
- $PayableAmount->setAttribute("currencyID", "PEN");
- $LegalMonetaryTotal->appendChild($LineExtensionAmount);
- $LegalMonetaryTotal->appendChild($PayableAmount);
- $Invoice->appendChild($LegalMonetaryTotal);
- //---------------------------------------------------------------------------------------------
- if($Documento{0}[detalle].length==0){
- $Item = 0;
- foreach ($Detalles as $Detalle) {
- //Variables
- $Item++;
- $Cantidad = $Detalle["cant"];
- $PrecioVenta = $Detalle["precio"];
- $TotalItem = $Detalle["totallinea"]; //agregar total linea
- $CodigoPrecio = "01";
- $TributoID = 1000;
- $TributoName = "IGV";
- $TributoTax = "VAT";
- $ProductoDescripcion = $Detalle["codigo"] . " " . $Detalle["detalle"] . " " . $Detalle["detadicional"];
- $PrecioBruto = $Detalle["precio"];
- $IGVItem = $Detalle["igvlinea"];
- $AfectadoXIGV = 10;
- ////Detalle de Item de la Factura
- $InvoiceLine = $xml->createElement("cac:InvoiceLine");
- $InvoiceLine->appendChild($xml->createElement("cbc:ID", $Item));
- $InvoicedQuantity = $InvoiceLine->appendChild($xml->createElement("cbc:InvoicedQuantity", $Cantidad));
- $InvoicedQuantity->setAttribute("unitCode", "NIU");
- $InvoicedQuantity->setAttribute("unitCodeListID", "UN/ECE rec 20");
- $InvoicedQuantity->setAttribute("unitCodeListAgencyName", "United Nations Economic Commission for Europe");
- $LineExtensionAmount = $xml->createElement("cbc:LineExtensionAmount", $PrecioVenta);
- $LineExtensionAmount->setAttribute("currencyID", "PEN");
- $InvoiceLine->appendChild($LineExtensionAmount);
- $PricingReference = $xml->createElement("cac:PricingReference");
- $AlternativeConditionPrice = $xml->createElement("cac:AlternativeConditionPrice");
- $PriceAmount = $xml->createElement("cbc:PriceAmount", $TotalItem);
- $PriceAmount->setAttribute("currencyID", "PEN");
- $PriceTypeCode = $xml->createElement("cbc:PriceTypeCode", $CodigoPrecio);
- $PriceTypeCode->setAttribute("listName", "SUNAT:Indicador de tipo de Precio");
- $PriceTypeCode->setAttribute("listAgencyName", "PE:SUNAT");
- $PriceTypeCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16");
- $AlternativeConditionPrice->appendChild($PriceAmount);
- $AlternativeConditionPrice->appendChild($PriceTypeCode);
- $PricingReference->appendChild($AlternativeConditionPrice);
- $InvoiceLine->appendChild($PricingReference);
- $Invoice->appendChild($InvoiceLine);
- //Subtotalizar Item
- $TaxTotal2 = $xml->createElement("cac:TaxTotal");
- $TaxAmount2 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
- $TaxAmount2->setAttribute("currencyID", "PEN");
- $TaxTotal2->appendChild($TaxAmount2);
- $TaxSubtotal2 = $xml->createElement("cac:TaxSubtotal");
- $TaxableAmount = $xml->createElement("cbc:TaxableAmount", $PrecioVenta);
- $TaxableAmount->setAttribute("currencyID", "PEN");
- $TaxAmount3 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
- $TaxAmount3->setAttribute("currencyID", "PEN");
- $TaxSubtotal2->appendChild($TaxableAmount);
- $TaxSubtotal2->appendChild($TaxAmount3);
- $TaxCategory = $xml->createElement("cac:TaxCategory");
- $ID = $TaxCategory->appendChild($xml->createElement("cbc:ID", "S"));
- $ID->setAttribute("schemeID", "UN/ECE 5305");
- $ID->setAttribute("schemeName", "Tax Category Identifier");
- $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
- $TaxCategory->appendChild($xml->createElement("cbc:Percent", 18.00));
- $TaxExemptionReasonCode = $TaxCategory->appendChild($xml->createElement("cbc:TaxExemptionReasonCode", $AfectadoXIGV));
- $TaxExemptionReasonCode->setAttribute("listAgencyName", "PE:SUNAT");
- $TaxExemptionReasonCode->setAttribute("listName", "SUNAT:Codigo de Tipo de Afectacion del IGV");
- $TaxExemptionReasonCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07");
- $TaxScheme2 = $TaxCategory->appendChild($xml->createElement("cac:TaxScheme"));
- $ID = $TaxScheme2->appendChild($xml->createElement("cbc:ID", $TributoID));
- $ID->setAttribute("schemeID", "UN/ECE 5153");
- $ID->setAttribute("schemeName", "Tax Sheme Identifier");
- $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
- $TaxScheme2->appendChild($xml->createElement("cbc:Name", $TributoName));
- $TaxScheme2->appendChild($xml->createElement("cbc:TaxTypeCode", $TributoTax));
- $TaxCategory->appendChild($TaxScheme2);
- $TaxSubtotal2->appendChild($TaxCategory);
- $TaxTotal2->appendChild($TaxSubtotal2);
- $InvoiceLine->appendChild($TaxTotal2);
- //Detalle Item
- $Item2 = $xml->createElement("cac:Item");
- $Description = $xml->createElement("cbc:Description", $ProductoDescripcion);
- $Item2->appendChild($Description);
- $SellersItemIdentification = $xml->createElement("cac:SellersItemIdentification");
- $SellersItemIdentification->appendChild($xml->createElement("cbc:ID", $CodigoPrecio));
- $Item2->appendChild($SellersItemIdentification);
- $InvoiceLine->appendChild($Item2);
- $Price = $xml->createElement("cac:Price");
- $PriceAmount2 = $xml->createElement("cbc:PriceAmount", $PrecioBruto);
- $PriceAmount2->setAttribute("currencyID", "PEN");
- $Price->appendChild($PriceAmount2);
- $InvoiceLine->appendChild($Price);
- $Invoice->appendChild($InvoiceLine);
- $xml->appendChild($Invoice);
- }
- }else{
- //$Detalles = $FacturaDetalle->getUnDetalleCompartido($id);
- $Item = 1;
- //Variables
- $Cantidad = 1;
- $PrecioVenta = $Documento["subtotal"];
- $TotalItem = $Documento["monto"]; //agregar total linea
- $CodigoPrecio = "01";
- $TributoID = 1000;
- $TributoName = "IGV";
- $TributoTax = "VAT";
- $codigo = "0300";
- $ProductoDescripcion = $Documento["codigo"] . " " . $Detalles["detalle"];
- $PrecioBruto = $Documento["subtotal"];
- $IGVItem = $Documento["igv"];
- $AfectadoXIGV = 10;
- ////Detalle de Item de la Factura
- $InvoiceLine = $xml->createElement("cac:InvoiceLine");
- $InvoiceLine->appendChild($xml->createElement("cbc:ID", $Item));
- $InvoicedQuantity = $InvoiceLine->appendChild($xml->createElement("cbc:InvoicedQuantity", $Cantidad));
- $InvoicedQuantity->setAttribute("unitCode", "NIU");
- $InvoicedQuantity->setAttribute("unitCodeListID", "UN/ECE rec 20");
- $InvoicedQuantity->setAttribute("unitCodeListAgencyName", "United Nations Economic Commission for Europe");
- $LineExtensionAmount = $xml->createElement("cbc:LineExtensionAmount", $PrecioVenta);
- $LineExtensionAmount->setAttribute("currencyID", "PEN");
- $InvoiceLine->appendChild($LineExtensionAmount);
- $PricingReference = $xml->createElement("cac:PricingReference");
- $AlternativeConditionPrice = $xml->createElement("cac:AlternativeConditionPrice");
- $PriceAmount = $xml->createElement("cbc:PriceAmount", $TotalItem);
- $PriceAmount->setAttribute("currencyID", "PEN");
- $PriceTypeCode = $xml->createElement("cbc:PriceTypeCode", $CodigoPrecio);
- $PriceTypeCode->setAttribute("listName", "SUNAT:Indicador de tipo de Precio");
- $PriceTypeCode->setAttribute("listAgencyName", "PE:SUNAT");
- $PriceTypeCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16");
- $AlternativeConditionPrice->appendChild($PriceAmount);
- $AlternativeConditionPrice->appendChild($PriceTypeCode);
- $PricingReference->appendChild($AlternativeConditionPrice);
- $InvoiceLine->appendChild($PricingReference);
- $Invoice->appendChild($InvoiceLine);
- //Subtotalizar Item
- $TaxTotal2 = $xml->createElement("cac:TaxTotal");
- $TaxAmount2 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
- $TaxAmount2->setAttribute("currencyID", "PEN");
- $TaxTotal2->appendChild($TaxAmount2);
- $TaxSubtotal2 = $xml->createElement("cac:TaxSubtotal");
- $TaxableAmount = $xml->createElement("cbc:TaxableAmount", $PrecioVenta);
- $TaxableAmount->setAttribute("currencyID", "PEN");
- $TaxAmount3 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
- $TaxAmount3->setAttribute("currencyID", "PEN");
- $TaxSubtotal2->appendChild($TaxableAmount);
- $TaxSubtotal2->appendChild($TaxAmount3);
- $TaxCategory = $xml->createElement("cac:TaxCategory");
- $ID = $TaxCategory->appendChild($xml->createElement("cbc:ID", "S"));
- $ID->setAttribute("schemeID", "UN/ECE 5305");
- $ID->setAttribute("schemeName", "Tax Category Identifier");
- $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
- $TaxCategory->appendChild($xml->createElement("cbc:Percent", 18.00));
- $TaxExemptionReasonCode = $TaxCategory->appendChild($xml->createElement("cbc:TaxExemptionReasonCode", $AfectadoXIGV));
- $TaxExemptionReasonCode->setAttribute("listAgencyName", "PE:SUNAT");
- $TaxExemptionReasonCode->setAttribute("listName", "SUNAT:Codigo de Tipo de Afectacion del IGV");
- $TaxExemptionReasonCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07");
- $TaxScheme2 = $TaxCategory->appendChild($xml->createElement("cac:TaxScheme"));
- $ID = $TaxScheme2->appendChild($xml->createElement("cbc:ID", $TributoID));
- $ID->setAttribute("schemeID", "UN/ECE 5153");
- $ID->setAttribute("schemeName", "Tax Sheme Identifier");
- $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
- $TaxScheme2->appendChild($xml->createElement("cbc:Name", $TributoName));
- $TaxScheme2->appendChild($xml->createElement("cbc:TaxTypeCode", $TributoTax));
- $TaxCategory->appendChild($TaxScheme2);
- $TaxSubtotal2->appendChild($TaxCategory);
- $TaxTotal2->appendChild($TaxSubtotal2);
- $InvoiceLine->appendChild($TaxTotal2);
- //Detalle Item
- $Item2 = $xml->createElement("cac:Item");
- $Description = $xml->createElement("cbc:Description", $ProductoDescripcion);
- $Item2->appendChild($Description);
- $SellersItemIdentification = $xml->createElement("cac:SellersItemIdentification");
- $SellersItemIdentification->appendChild($xml->createElement("cbc:ID", $CodigoPrecio));
- $Item2->appendChild($SellersItemIdentification);
- $InvoiceLine->appendChild($Item2);
- $Price = $xml->createElement("cac:Price");
- $PriceAmount2 = $xml->createElement("cbc:PriceAmount", $PrecioBruto);
- $PriceAmount2->setAttribute("currencyID", "PEN");
- $Price->appendChild($PriceAmount2);
- $InvoiceLine->appendChild($Price);
- $Invoice->appendChild($InvoiceLine);
- $xml->appendChild($Invoice);
- }
- }
- $NomArch = $RUC_Emisor . "-" . $TipoDocumento . "-" . $FacturaNumero;
- $xml->save("public/sinfirmar/" . $NomArch . ".xml");
- chmod("public/sinfirmar/" . $NomArch . ".xml", 0777);
- $Funciones = $this->Funciones();
- $Funciones->firmar("public/sinfirmar/", $NomArch, "public/firmados/");
- header('Content-Type: text/html; charset=UTF-8');
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 16pt; color: #000000; margin-bottom: 10px;">';
- echo 'SUNAT. Facturación electrónica Perú.<br>';
- echo '<span style="color: #6A0888; font-size: 15pt;">';
- echo 'Envío de factura electrónica al servidor de SUNAT<br>';
- echo 'y obtención de la Constancia de Recepción (CDR).';
- echo '</span>';
- echo '<hr width="100%"></div>';
- // NOMBRE DE ARCHIVO A PROCESAR.
- ## =============================================================================
- ## Creación del archivo .ZIP
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-bottom: 10px;">';
- echo 'Archivo .XML (factura electrónica) a comprimir.<br>';
- echo '<span style="color: #000000;">' . $NomArch . '.xml</span>';
- echo '</div>';
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-bottom: 10px;">';
- echo 'Archivo .ZIP (conteniendo el doc. electrónico) a enviar al servidor de SUNAT.<br>';
- echo '<span style="color: #000000;">' . $NomArch . '.zip</span>';
- echo '</div>';
- $zip = new \PclZip("public/zipeados/" . $NomArch . ".zip");
- $zip->create("public/firmados/" . $NomArch . ".xml", PCLZIP_OPT_REMOVE_ALL_PATH);
- chmod("public/zipeados/" . $NomArch . ".zip", 0777);
- # ==============================================================================
- # Procedimiento para enviar comprobante a la SUNAT
- //URL para enviar las solicitudes a SUNAT
- $wsdlURL = 'https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService?wsdl';
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-bottom: 10px;">';
- echo 'URL Beta de SUNAT:<br>';
- echo '<span style="color: #000000;">' . $wsdlURL . '</span>';
- echo '</div>';
- //Estructura del XML para la conexión
- $XMLString = '<?xml version="1.0" encoding="UTF-8"?>
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.sunat.gob.pe" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
- <soapenv:Header>
- <wsse:Security>
- <wsse:UsernameToken Id="ABC-123">
- <wsse:Username>20565381785MODDATOS</wsse:Username>
- <wsse:Password>MODDATOS</wsse:Password>
- </wsse:UsernameToken>
- </wsse:Security>
- </soapenv:Header>
- <soapenv:Body>
- <ser:sendBill>
- <fileName>' . $NomArch . '.zip</fileName>
- <contentFile>' . base64_encode(file_get_contents("public/zipeados/" . $NomArch . '.zip')) . '</contentFile>
- </ser:sendBill>
- </soapenv:Body>
- </soapenv:Envelope>';
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099;">';
- echo 'SOAP de envío al servidor de SUNAT con el método sendBill.';
- echo '</div>';
- echo $XMLString;
- //Realizamos la llamada a nuestra función
- $result = $Funciones->soapCall($wsdlURL, $callFunction = "sendBill", $XMLString);
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-top: 10px;">';
- echo 'Respuesta del servidor de SUNAT:<br>';
- echo '<span style="color: #000000;">' . $result . '</span>';
- echo '</div>';
- //Descargamos el Archivo Response
- $archivo = fopen("public/zipeados/" . "C" . $NomArch . '.xml', 'w+');
- fputs($archivo, $result);
- fclose($archivo);
- /* LEEMOS EL ARCHIVO XML */
- $xml = simplexml_load_file("public/zipeados/" . "C" . $NomArch . '.xml');
- foreach ($xml->xpath('//applicationResponse') as $response) {
- }
- /* AQUI DESCARGAMOS EL ARCHIVO CDR(CONSTANCIA DE RECEPCIÓN) */
- $cdr = base64_decode($response);
- $archivo = fopen("public/zipeados/" . 'R-' . $NomArch . '.zip', 'w+');
- fputs($archivo, $cdr);
- fclose($archivo);
- chmod("public/zipeados/" . 'R-' . $NomArch . '.zip', 0777);
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-top: 10px;">';
- echo 'Archivo .zip recibido.<br>';
- echo '<span style="color: #000000;">R-' . $NomArch . '.zip</span>';
- echo '</div>';
- $archive = new \PclZip("public/zipeados/" . 'R-' . $NomArch . '.zip');
- if ($archive->extract(PCLZIP_OPT_PATH, 'public/cdr') == 0) {
- die("Error : " . $archive->errorInfo(true));
- } //else {
- // chmod('zipeados/' . 'R-' . $NomArch . '.xml', 0777);
- // }
- echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-top: 10px;">';
- echo 'Archivo .XML constancia de recepción (CRD) ya descomprimido.<br>';
- echo '<span style="color: #A70202;">R-' . $NomArch . '.xml</span>';
- echo '</div>';
- /* Eliminamos el Archivo Response */
- unlink("public/zipeados/" . 'C' . $NomArch . '.xml');
- return null;
- }
- public function generaPdfAction()
- {
- $NomArchPDF = $this->params()->fromRoute("id", null);
- header('Content-Type: text/html; charset=UTF-8');
- // Variables correspondientes a la factura.
- $RUC = ""; // RUC.
- $NomRazSoc = ""; // Nombre o Razón social.
- $FecEmi = ""; // Fecha de emisión.
- $Domicilio = ""; // Domicilio.
- $CodHash = ""; // Código Hash.
- $TipoDoc = ""; // Tipo de documento.
- $TotGrav = 0; // Total gravado.
- $TotIGV = 0; // Total IGV.
- $TotMonto = 0; // Total importe.
- // Variables correspondientes a los productos o servicios de la factura.
- $CodProdServ = ""; // Código.
- $ProdServ = ""; // Descripción.
- $Cant = 0; // Cantidad.
- $UniMed = ""; // Unidad de medida.
- $Precio = 0; // Precio unitario.
- $Importe = 0; // Importe.
- // Obteniendo datos del archivo .XML (factura electrónica)======================
- $Ruta = "public/firmados/";
- $xml = file_get_contents($Ruta . $NomArchPDF . ".xml");
- #== Obteniendo datos del archivo .XML
- $DOM = new \DomDocument("1.0", "UTF-8");
- $DOM->preserveWhiteSpace = false;
- $DOM->loadXML($xml);
- ### DATOS DE LA FACTURA ####################################################
- // Obteniendo RUC.
- $DocXML = $DOM->getElementsByTagName('CustomerAssignedAccountID');
- foreach ($DocXML as $Nodo) {
- $RUC = $Nodo->nodeValue;
- }
- // Obteniendo Fecha de emisión.
- $DocXML = $DOM->getElementsByTagName('IssueDate');
- foreach ($DocXML as $Nodo) {
- $FecEmi = $Nodo->nodeValue;
- }
- // Obteniendo Nombre o Razón social.
- $DocXML = $DOM->getElementsByTagName('RegistrationName');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $NomRazSoc = $Nodo->nodeValue;
- }
- $i++;
- }
- // Obteniendo domicilio.
- $DocXML = $DOM->getElementsByTagName('StreetName');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $Domicilio = $Nodo->nodeValue;
- }
- $i++;
- }
- // Obteniendo Codigo Hash.
- $DocXML = $DOM->getElementsByTagName('DigestValue');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $CodHash = $Nodo->nodeValue;
- }
- $i++;
- }
- // Clave del tipo de documento.
- $DocXML = $DOM->getElementsByTagName('InvoiceTypeCode');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $TipoDoc = $Nodo->nodeValue;
- }
- $i++;
- }
- ### DATOS DEL PRODUCTO O SERVICIO. #########################################
- // Código del producto o servicio.
- $DocXML = $DOM->getElementsByTagName('PriceTypeCode');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $CodProdServ = $Nodo->nodeValue;
- }
- $i++;
- }
- // Descripción del producto o servicio.
- $DocXML = $DOM->getElementsByTagName('Description');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $ProdServ = $Nodo->nodeValue;
- }
- $i++;
- }
- // Cantidad de producto o servicio.
- $DocXML = $DOM->getElementsByTagName('InvoicedQuantity');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $Cant = $Nodo->nodeValue;
- }
- $i++;
- }
- // Unidad de medida del producto o servicio.
- $DocXML = $DOM->getElementsByTagName('InvoicedQuantity');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- //$UniMed = $Nodo->nodeValue;
- $UniMed = $Nodo->getAttribute('unitCode');
- }
- $i++;
- }
- // Precio unitario.
- $DocXML = $DOM->getElementsByTagName('PriceAmount');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 1) {
- $Precio = $Nodo->nodeValue;
- }
- $i++;
- }
- // Importe.
- $DocXML = $DOM->getElementsByTagName('LineExtensionAmount');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 0) {
- $Importe = $Nodo->nodeValue;
- }
- $i++;
- }
- ### TOTALES DE LA FACTURA ##################################################
- // Total gravado.
- $DocXML = $DOM->getElementsByTagName('PayableAmount');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- if ($i == 1) {
- $TotGrav = $Nodo->nodeValue;
- }
- $i++;
- }
- // Total IGV.
- $DocXML = $DOM->getElementsByTagName('TaxAmount');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- $TotIGV = $Nodo->nodeValue;
- }
- // Monto total.
- $DocXML = $DOM->getElementsByTagName('PayableAmount');
- $i = 0;
- foreach ($DocXML as $Nodo) {
- $TotMonto = $Nodo->nodeValue;
- }
- //var_dump($RUC,$NomRazSoc,$FecEmi,$Domicilio,$CodHash,$TipoDoc,$TotGrav,$TotIGV,$TotMonto,$CodProdServ,$ProdServ,$Cant,$UniMed,$Precio,$Importe);
- // Crear el gráfico con el código de barras
- $textoCodBar = "| $TipoDoc | A | 123 | $TotIGV | $TotMonto | $FecEmi | $TipoDoc | F002-026 | VALOR RESUMEN | $CodHash |";
- //var_dump($textoCodBar);
- $pdf417 = new PDF417();
- $codigo_barra = $pdf417->encode($textoCodBar);
- // Create a PNG image
- $renderer = new ImageRenderer([
- 'format' => 'png',
- ]);
- $image = $renderer->render($codigo_barra);
- $image->save("public/img/" . $NomArchPDF . ".png");
- //= Creación del documetno .PDF
- $pdf = new PDFPlugin('P', 'cm', 'Letter');
- $pdf->AliasNbPages();
- $pdf->AddPage();
- $pdf->AddFont('IDAutomationHC39M', '', 'IDAutomationHC39M.php');
- $pdf->AddFont('verdana', '', 'verdana.php');
- $pdf->SetAutoPageBreak(true);
- $pdf->SetMargins(0, 0, 0);
- $pdf->SetLineWidth(0.02);
- $pdf->SetFillColor(0, 0, 0);
- $pdf->image("public/img/Membrete_Fact.jpg", 1, 1, 10, 2.5);
- $pdf->image("public/img/" . $NomArchPDF . ".png", 0.7, 10, 9, 3);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', '', 10);
- $pdf->SetXY(1.2, 13);
- $pdf->Cell(8, 0.25, utf8_decode("Representación impresa de la factura electrónica."), 0, 1, 'C', 0);
- $pdf->RoundedRect(12, 1, 8, 2.5, 0.2, '');
- $pdf->SetTextColor(170, 0, 0);
- $pdf->SetFont('arial', '', 14);
- $pdf->SetXY(12, 1.5);
- $pdf->Cell(8, 0.25, "RUC: 20138998780", 0, 1, 'C', 0);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', 'B', 14);
- $pdf->SetXY(12, 2.2);
- $pdf->Cell(8, 0.25, utf8_decode("FACTURA ELECTRÓNICA"), 0, 1, 'C', 0);
- $pdf->SetTextColor(0, 0, 150);
- $pdf->SetFont('arial', '', 14);
- $pdf->SetXY(12, 2.9);
- $pdf->Cell(8, 0.25, "F002-026", 0, 1, 'C', 0);
- $pdf->RoundedRect(1, 4, 19, 3.2, 0.2, '');
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', 'B', 10);
- $pdf->SetXY(1.1, 4.2);
- $pdf->Cell(1, 0.35, utf8_decode("Señores: "), 0, 1, 'L', 0);
- $pdf->SetXY(1.1, 4.2 + 0.6);
- $pdf->Cell(1, 0.35, utf8_decode("Dirección: "), 0, 1, 'L', 0);
- $pdf->SetXY(1.1, 4.2 + (0.6 * 2));
- $pdf->Cell(1, 0.35, utf8_decode("RUC: "), 0, 1, 'L', 0);
- $pdf->SetXY(1.1, 4.2 + (0.6 * 3));
- $pdf->Cell(1, 0.35, utf8_decode("Fecha de emisión: "), 0, 1, 'L', 0);
- $pdf->SetXY(1.1, 4.2 + (0.6 * 4));
- $pdf->Cell(1, 0.35, utf8_decode("Moneda: "), 0, 1, 'L', 0);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', '', 10);
- $pdf->SetXY(4.7, 4.2);
- $pdf->Cell(1, 0.35, utf8_decode($NomRazSoc), 0, 1, 'L', 0);
- $pdf->SetXY(4.7, 4.2 + 0.6);
- $pdf->Cell(1, 0.35, utf8_decode($Domicilio), 0, 1, 'L', 0);
- $pdf->SetXY(4.7, 4.2 + (0.6 * 2));
- $pdf->Cell(1, 0.35, utf8_decode($RUC), 0, 1, 'L', 0);
- $pdf->SetXY(4.7, 4.2 + (0.6 * 3));
- $pdf->Cell(1, 0.35, utf8_decode($FecEmi), 0, 1, 'L', 0);
- $pdf->SetXY(4.7, 4.2 + (0.6 * 4));
- $pdf->Cell(1, 0.35, utf8_decode("SOL"), 0, 1, 'L', 0);
- $X = 0;
- $Y = 0;
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', '', 10);
- $pdf->SetXY($X + 1, $Y + 8);
- $pdf->Cell(2.5, 0.5, utf8_decode("Código"), 1, 1, 'L', 0);
- $pdf->SetXY($X + 3.5, $Y + 8);
- $pdf->Cell(6.65, 0.5, utf8_decode("Descripción"), 1, 1, 'L', 0);
- $pdf->SetXY($X + 10.15, $Y + 8);
- $pdf->Cell(2, 0.5, utf8_decode("Cantidad"), 1, 1, 'C', 0);
- $pdf->SetXY($X + 12.15, $Y + 8);
- $pdf->Cell(2.65, 0.5, utf8_decode("Unidad"), 1, 1, 'L', 0);
- $pdf->SetXY($X + 14.8, $Y + 8);
- $pdf->Cell(2.7, 0.5, utf8_decode("Precio unitario"), 1, 1, 'R', 0);
- $pdf->SetXY($X + 17.5, $Y + 8);
- $pdf->Cell(2.5, 0.5, utf8_decode("Precio venta"), 1, 1, 'R', 0);
- $Y = $Y + 0.5;
- $pdf->SetXY($X + 1, $Y + 8);
- $pdf->Cell(2.5, 0.8, utf8_decode($CodProdServ), 1, 1, 'L', 0);
- $pdf->SetXY($X + 3.5, $Y + 8);
- $pdf->Cell(6.65, 0.8, utf8_decode($ProdServ), 1, 1, 'L', 0);
- $pdf->SetXY($X + 10.15, $Y + 8);
- $pdf->Cell(2, 0.8, utf8_decode($Cant), 1, 1, 'C', 0);
- $pdf->SetXY($X + 12.15, $Y + 8);
- $pdf->Cell(2.65, 0.8, utf8_decode($UniMed), 1, 1, 'L', 0);
- $pdf->SetXY($X + 14.8, $Y + 8);
- $pdf->Cell(2.7, 0.8, number_format($Precio, 2), 1, 1, 'R', 0);
- $pdf->SetXY($X + 17.5, $Y + 8);
- $pdf->Cell(2.5, 0.8, number_format($Importe, 2), 1, 1, 'R', 0);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', '', 10);
- $pdf->SetXY(9.9, 10);
- $pdf->Cell(7.6, 0.5, utf8_decode("Total Valor de Venta - Operaciones Gravadas:"), 1, 1, 'R', 0);
- $pdf->SetXY(17.5, 10);
- $pdf->Cell(2.5, 0.5, number_format($TotGrav, 2), 1, 1, 'R', 0);
- $pdf->SetXY(9.9, 10 + 0.5);
- $pdf->Cell(7.6, 0.5, utf8_decode("IGV:"), 1, 1, 'R', 0);
- $pdf->SetXY(17.5, 10 + 0.5);
- $pdf->Cell(2.5, 0.5, number_format($TotIGV, 2), 1, 1, 'R', 0);
- $pdf->SetXY(9.9, 10 + (0.5 * 2));
- $pdf->Cell(7.6, 0.5, utf8_decode("Importe Total:"), 1, 1, 'R', 0);
- $pdf->SetXY(17.5, 10 + (0.5 * 2));
- $pdf->Cell(2.5, 0.5, number_format($TotMonto, 2), 1, 1, 'R', 0);
- $pdf->line(1, 24.8, 20.5, 24.8);
- $pdf->SetTextColor(0, 0, 0);
- $pdf->SetFont('arial', '', 9);
- $pdf->SetXY(1, 25);
- $pdf->MultiCell(19.5, 0.35, utf8_decode("Representación Impresa de la Factura ElectrónicaCódigo Hash: $CodHash Autorizado para ser Emisor electrónico mediante la Resolución de Intendencia N° 0180050002185/SUNAT Para consultar el comprobante ingresar a : https://portal.efacturacion.pe/appefacturacion"), 0, 'C');
- $pdf->Output("/facturasPDF/" . $NomArchPDF . ".pdf", "F");
- chmod("/facturasPDF/" . $NomArchPDF . ".pdf", 0777);
- }
- public function anularAction()
- {
- $id = $this->params()->fromRoute("id", null);
- $this->dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');
- $FacturaCabecera = new FacturaModel($this->dbAdapter);
- $Documento = $FacturaCabecera->getUnaFactura($id);
- $FacturaCabecera->anulacionSunat($id);
- //Datos del Cliente
- $RUC_Emisor = '20565381785';
- $RazonSocialEmisor = 'CRUCERISTA CENTER E.I.R.L.';
- $TipoDocumentoEmisor = "6";
- $Factura = "F";
- //$Serie = $Documento[0]['serie'];
- $Serie = "001";
- $Numero = $Documento[0]['numero'];
- $FacturaNumero = $Factura . $Serie . "-" . $Numero;
- $FechaEmision = date("Ymd");
- $Motivo = "CANCELACION";
- $ruta = 'public/bajas/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
- if (!file_exists($ruta)) {
- mkdir($ruta, 755, true);
- }
- $i = 1;
- while (file_exists($ruta . $RUC_Emisor . '-RA-' . date('Ymd') . '-' . $i . '.xml')) {
- $i++;
- // el valor de i es el actual que se va crear
- }
- $xml = new \DomDocument("1.0", "ISO-8859-1");
- $xml->standalone = false;
- $xml->formatOutput = true;
- //Cabecera de la Factura
- $Anulacion = $xml->createElementNS("urn:sunat:names:specification:ubl:peru:schema:xsd:VoidedDocuments-1", "VoidedDocuments");
- $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
- $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
- $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
- $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
- $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
- $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
- //Totales de la Factura
- $UBLExtensiones = $xml->createElement("ext:UBLExtensions");
- $UBLExtension = $UBLExtensiones->appendChild($xml->createElement("ext:UBLExtension"));
- $UBLExtension->appendChild($xml->createElement("ext:ExtensionContent"));
- $UBLExtensiones->appendChild($UBLExtension);
- $Anulacion->appendChild($UBLExtensiones);
- $Anulacion->appendChild($xml->createElement("cbc:UBLVersionID", "2.0"));
- $Anulacion->appendChild($xml->createElement("cbc:CustomizationID", "1.0"));
- $Anulacion->appendChild($xml->createElement("cbc:ID", 'RA-' . date('Ymd') . '-' . $i));
- $Anulacion->appendChild($xml->createElement("cbc:ReferenceDate", date("Y-m-d", strtotime($FechaEmision))));
- $Anulacion->appendChild($xml->createElement("cbc:IssueDate", date("Y-m-d", strtotime($FechaEmision))));
- //---------------------------------------------------------------------------------------
- //Firma Digital
- $Signature = $Anulacion->appendChild($xml->createElement("cac:Signature"));
- $Signature->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
- $SignatoryParty = $Signature->appendChild($xml->createElement("cac:SignatoryParty"));
- $PartyIdentification = $SignatoryParty->appendChild($xml->createElement("cac:PartyIdentification"));
- $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
- $PartyName = $SignatoryParty->appendChild($xml->createElement("cac:PartyName"));
- $PartyName->appendChild($xml->createElement("cbc:Name", $RazonSocialEmisor));
- $DigitalSignatureAttachment = $Signature->appendChild($xml->createElement("cac:DigitalSignatureAttachment"));
- $ExternalReference = $DigitalSignatureAttachment->appendChild($xml->createElement("cac:ExternalReference"));
- $ExternalReference->appendChild($xml->createElement("cbc:URI", $RUC_Emisor));
- //-----------------------------------------------------------------------------------------
- //Razon Social o Nombres y Apellidos del Emisor
- $Empresa = $xml->createElement("cac:AccountingSupplierParty");
- $Empresa->appendChild($xml->createElement("cbc:CustomerAssignedAccountID", $RUC_Emisor));
- $Empresa->appendChild($xml->createElement("cbc:AdditionalAccountID", $TipoDocumentoEmisor));
- $Party = $xml->createElement("cac:Party");
- $PartyLegalEntity = $Party->appendChild($xml->createElement("cac:PartyLegalEntity"));
- $PartyLegalEntity->appendChild($xml->createElement("cbc:RegistrationName", $RazonSocialEmisor));
- $Party->appendChild($PartyLegalEntity);
- $Empresa->appendChild($Party);
- $Anulacion->appendChild($Empresa);
- $VoidedDocumentsLine1 = $xml->createElement("sac:VoidedDocumentsLine");
- $VoidedDocumentsLine1->appendChild($xml->createElement("cbc:LineID", "1"));
- $VoidedDocumentsLine1->appendChild($xml->createElement("cbc:DocumentTypeCode", "01"));
- $VoidedDocumentsLine1->appendChild($xml->createElement("sac:DocumentSerialID", $Serie));
- $VoidedDocumentsLine1->appendChild($xml->createElement("sac:DocumentNumberID", $Numero));
- $VoidedDocumentsLine1->appendChild($xml->createElement("sac:VoidReasonDescription", $Motivo));
- $Anulacion->appendChild($VoidedDocumentsLine1);
- $xml->appendChild($Anulacion);
- $xml->save($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.xml');
- chmod($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.xml', 0777);
- $Funciones = $this->Funciones();
- $Funciones->firmar($ruta, $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i), $ruta);
- $zip = new \PclZip($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip');
- $zip->create($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.xml', PCLZIP_OPT_REMOVE_ALL_PATH);
- chmod($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip', 0777);
- $wsdlURL = 'https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService?wsdl';
- $XMLString = '<?xml version="1.0" encoding="UTF-8"?>
- <soapenv:Envelope
- xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
- xmlns:ser="http://service.sunat.gob.pe"
- xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
- <soapenv:Header>
- <wsse:Security>
- <wsse:UsernameToken Id="ABC-123">
- <wsse:Username>20565381785MODDATOS</wsse:Username>
- <wsse:Password>MODDATOS</wsse:Password>
- </wsse:UsernameToken>
- </wsse:Security>
- </soapenv:Header>
- <soapenv:Body>
- <ser:sendSummary>
- <fileName>' . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip</fileName>
- <contentFile>' . base64_encode(file_get_contents($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip')) . '</contentFile>
- </ser:sendSummary>
- </soapenv:Body>
- </soapenv:Envelope>';
- //Realizamos la llamada a nuestra función
- $Funciones = $this->Funciones();
- $result = $Funciones->soapCall($wsdlURL, $callFunction = "sendSummary", $XMLString);
- echo 'La Factura ' . $FacturaNumero . ' ha sido dado de baja';
- return null;
- }
- public function generapdfinvoice($Encabezado = array(), $NumDocumento, $Datos, $productos = array(), $MontoLetras, $nombre_archivo, $firma = '', $NHabitacion = '')
- {
- $arr = $Encabezado;
- $medidas = array(90, 217); // Ajustar aqui segun los milimetros necesarios;
- $pdf = new \Pdf('P', 'mm', $medidas, true, 'UTF-8', false);
- $pdf->setPageFormat($medidas, $orientation = 'P');
- $pdf->RUCEmpresa = $arr['Encabezado']['Emisor']['RUCEmisor'];
- $pdf->NumDocumento = $NumDocumento;
- $pdf->SetCreator(PDF_CREATOR);
- $pdf->SetAuthor('Erwin Torres León');
- $pdf->SetTitle($nombre_archivo);
- switch ($Datos['tipo_documento']) {
- case "01":
- $pdf->NomDocumento = 'FACTURA ELECTRÓNICA';
- break;
- case "03":
- $pdf->NomDocumento = 'BOLETA ELECTRÓNICA';
- break;
- case "07":
- $pdf->NomDocumento = 'NOTA DE CRÉDITO ELECTRÓNICA';
- break;
- case "08":
- $pdf->NomDocumento = 'NOTA DE DÉDITO ELECTRÓNICA';
- break;
- }
- // Establecer el tipo de letra
- //Si tienes que imprimir carácteres ASCII estándar, puede utilizar las fuentes básicas como
- // Helvetica para reducir el tamaño del archivo.
- $pdf->SetFont('Helvetica', '', 12, '', true);
- // Añadir una página
- // Este método tiene varias opciones, consulta la documentación para más información.
- $pdf->Open();
- $pdf->AddPage();
- // ponemos los márgenes
- //$pdf->SetMargins(15,15);
- /* incluimos un rectángulo relleno para contener datos del cliente */
- //$pdf->Rect(15,47,180,22,'FD','',array(255,255,255));
- $pdf->SetFont('Helvetica', 'B', 8);
- $pdf->SetXY(2, 24);
- $pdf->Cell(2, 48, "RUC/DNI:", 0, 0, 'L');
- $pdf->SetFont('Helvetica', '', 8);
- $pdf->SetXY(20, 24);
- $pdf->Cell(10, 48, $arr['Encabezado']['Receptor']['RUCReceptor'], 0, 0, 'L');
- $pdf->SetFont('Helvetica', 'B', 10);
- $pdf->SetFont('Helvetica', 'B', 8);
- $pdf->Ln(7);
- $pdf->SetXY(2, 28);
- $pdf->Cell(17, 48, "Cliente:", 0, 0, 'L');
- $pdf->SetFont('Helvetica', '', 8);
- $pdf->SetXY(20, 28);
- $pdf->Cell(17, 48, $arr['Encabezado']['Receptor']['RznSoc'], 0, 0, 'L');
- $pdf->Ln(5);
- $pdf->SetFont('Helvetica', 'B', 8);
- $pdf->SetXY(2, 32);
- $pdf->Cell(17, 48, "Dirección:", 0, 0, 'L');
- $pdf->SetXY(20, 32);
- $pdf->SetFont('Helvetica', '', 8);
- $pdf->Cell(190, 48, $arr['Encabezado']['Receptor']['Direccion'], 0, 'L');
- $pdf->SetFont('Helvetica', 'B', 8);
- $pdf->SetXY(2, 36);
- $pdf->Cell(30, 48, "Fecha de Emisión:", 0, 0, 'L');
- $pdf->SetFont('Helvetica', '', 8);
- $pdf->SetXY(30, 36);
- $pdf->Cell(30, 48, $Datos['fecharegistro'], 0, 0, 'L');
- $pdf->SetFont('Helvetica', 'B', 8);
- $pdf->SetXY(2, 40);
- $pdf->Cell(30, 48, "Moneda:", 0, 0, 'L');
- $pdf->SetFont('Helvetica', '', 8);
- $pdf->SetXY(30, 40);
- $pdf->Cell(30, 48, 'Soles', 0, 0, 'L');
- $pdf->SetFont('Helvetica', 'B', 8);
- $pdf->SetXY(2, 44);
- $pdf->Cell(30, 48, "Nº Habitación:", 0, 0, 'L');
- $pdf->SetFont('Helvetica', '', 8);
- $pdf->SetXY(30, 44);
- $pdf->Cell(30, 48, $NHabitacion, 0, 0, 'L');
- $pdf->Ln(4);
- $pdf->SetX(1);
- $pdf->Cell(100, 52, "------------------------------------------------------------------------------------", 0, 0, 'L');
- $pdf->Ln();
- // Anchuras de las columnas
- //$w = array(10, 20, 16, 95,18,22);
- $w = array(8, 50);
- // Títulos de las columnas
- $pdf->SetFont('Helvetica', 'B', 8);
- $header = array('Cod.', 'Descripción');
- $pdf->SetXY(2, 69);
- // Cabeceras
- for ($i = 0; $i < count($header); $i++) {
- $pdf->Cell($w[$i], 7, $header[$i], 0, 0, 'L', 0);
- }
- $pdf->Ln();
- // Datos
- $i = 1;
- $pdf->SetFont('Helvetica', '', 7);
- if ($Datos['Moneda'] == 'PEN'):
- $CodMoneda = 'S/.';
- else:
- $CodMoneda = '$';
- endif;
- foreach ($productos as $row) {
- $pdf->SetX(2);
- $pdf->Cell($w[0], 4, $i, '0');
- $y = $pdf->GetY();
- $acotado = $row['pro_desc'];
- $pdf->MultiCell($w[1], 4, $acotado, 0, ‘L’);
- $pdf->SetXY(149, $y);
- $pdf->Ln();
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(60, 1, $CodMoneda . ' ' . number_format(round($row['pro_total']), 2), 0, 0, 'R');
- $pdf->Ln();
- $i++;
- $pdf->SetFont('Helvetica', '', 7);
- }
- /*TOTALES*/
- $pdf->TotGravadas = $CodMoneda . " " . number_format($Datos['TotGravada'], 2);
- $pdf->TotGratuitas = $CodMoneda . " " . number_format($Datos['TotGratuitas'], 2);
- $pdf->TotExoneradas = $CodMoneda . " " . number_format($Datos['TotExoneradas'], 2);
- $pdf->TotInafectas = $CodMoneda . " " . number_format($Datos['TotInafectas'], 2);
- //$pdf->Ln();
- //VALIDACION PARA EL DESCUENTO GLOBAL
- if ($Datos['DescuentoGlobal'] > 0) {
- $Datos['TotVenta'] = number_format($Datos['TotVenta'] - $Datos['DescuentoGlobal'], 2);
- $Datos['TotGravada'] = $Datos['TotVenta'] / 1.18;
- $Datos['TotIgv'] = $Datos['TotVenta'] - $Datos['TotGravada'];
- }
- $pdf->SetX(0);
- $pdf->Cell(100, 5, "------------------------------------------------------------------------------------------------", 0, 0, 'L');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(17, 5, "OP. GRAVADAS: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(48, 5, number_format($Datos['TotGravada'], 2), 0, 0, 'R');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(20, 5, "OP. EXONERADAS: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(45, 5, number_format($Datos['TotExoneradas'], 2), 0, 0, 'R');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(17, 5, "OP. INAFECTAS: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(48, 5, number_format($Datos['TotInafectas'], 2), 0, 0, 'R');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(17, 5, "OP. GRATUITAS: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(48, 5, number_format($Datos['TotGratuitas'], 2), 0, 0, 'R');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(17, 5, "IGV: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(48, 5, number_format($Datos['TotIgv'], 2), 0, 0, 'R');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(17, 5, "DESCUENTO: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(48, 5, number_format($Datos['DescuentoGlobal'], 2), 0, 0, 'R');
- $pdf->Ln();
- $pdf->SetFont('Helvetica', '', 7);
- $pdf->Cell(17, 5, "TOTAL: " . $CodMoneda, 0, 0, 'R');
- $pdf->SetFont('Helvetica', 'B', 7);
- $pdf->Cell(48, 5, number_format($Datos['TotVenta'], 2), 0, 0, 'R');
- //$pdf->Ln();
- $datosAdicionales_CDB = $arr['Encabezado']['Emisor']['RUCEmisor'] . "|" . $Datos['tipo_documento'] . "|" . $NumDocumento . "|" . $Datos['TotIgv'] . "|" . $Datos['TotVenta'] . "|" . $Datos['fecharegistro'] . "|" . $arr['Encabezado']['Receptor']['TipoDocumento'] . "|" . $arr['Encabezado']['Receptor']['RUCReceptor'];
- // set style for barcode
- $style = array(
- 'border' => 0,
- 'vpadding' => 'auto',
- 'hpadding' => 'auto',
- 'fgcolor' => array(0, 0, 0),
- 'bgcolor' => false, //array(255,255,255)
- 'module_width' => 1, // width of a single module in points
- 'module_height' => 1, // height of a single module in points
- );
- $pdf->CodBarras = $datosAdicionales_CDB;
- $pdf->SetX(2);
- $pdf->Ln();
- $pdf->SetX(15);
- //$pdf->Cell(15,5,$firma,0,'C');
- $pdf->Cell(2, 5, 'Representación impresa de la ' . ucwords(strtolower($pdf->strtolower_utf8($pdf->NomDocumento))) . '', 0, 'J');
- $pdf->Ln();
- $alto = $pdf->GetY();
- $pdf->SetX(20);
- $pdf->Cell(2, 5, $pdf->write2DBarcode($datosAdicionales_CDB, 'PDF417', 10, $alto, 135, 20, $style, 'N'), 0, 'J');
- $pdf->Ln();
- $pdf->SetX(26);
- $pdf->Cell(2, 5, 'Forma de Pago: ' . $Datos['formapago'], 0, 'J');
- //$pdf->Line(10,10,200,10);
- //$nombre_archivo='prueba.pdf';
- $pdf->Output('PDF/' . $nombre_archivo . '.pdf', 'F');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement