Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 59.60 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Factura\Controller;
  4.  
  5. use BigFish\PDF417\PDF417;
  6. use BigFish\PDF417\Renderers\ImageRenderer;
  7. use Factura\Model\Entity\DetalleModel;
  8. use Factura\Model\Entity\FacturaModel;
  9. use Principal\Plugin\PDFPlugin;
  10. use Zend\Mvc\Controller\AbstractActionController;
  11. use Zend\View\Model\ViewModel;
  12.  
  13. class IndexController extends AbstractActionController
  14. {
  15.  
  16. public function indexAction()
  17. {
  18. return new ViewModel();
  19. }
  20.  
  21. public function crearAction()
  22. {
  23. $id = $this->params()->fromRoute("id", null);
  24. $this->dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');
  25. $FacturaCabecera = new FacturaModel($this->dbAdapter);
  26. $FacturaDetalle = new DetalleModel($this->dbAdapter);
  27. $Documento = $FacturaCabecera->getUnaFactura($id);
  28. if($Documento{0}[detalle].length==0){
  29. $Detalles = $FacturaDetalle->getUnDetalleTotal($id);
  30. }else{
  31. $Detalles = $FacturaDetalle->getUnDetalleCompartido($id);
  32. var_dump($Detalles[0]['detalle']);
  33. exit();
  34. }
  35.  
  36. $FacturaCabecera->envioSunat($id);
  37. //Datos del Cliente
  38. $RUC_Emisor = '20565381785';
  39. $RazonSocialEmisor = 'CRUCERISTA CENTER E.I.R.L.';
  40. $TipoDocumentoEmisor = "6";
  41. $UbigeoEmisor = 999;
  42. $DireccionEmisor = 'JR. JULIAN PINEIRO NRO. 113 INT. 178 C.C. 7 DE AGOSTO';
  43. $DepartamentoEmisor = 'LIMA';
  44. $ProvinciaEmisor = 'LIMA';
  45. $DistritoEmisor = 'RIMAC';
  46. $PaisEmisor = "PE";
  47. //Datos del Adquiriente
  48. $RUCAdquiriente = $Documento[0]['dni'];
  49. $RazonSocialAdquiriente = $Documento[0]['nombre'];
  50. //Datos del Documento
  51. $Serie = $Documento[0]['serie'];
  52. $Numero = $Documento[0]['numero'];
  53. $FacturaNumero = $Serie . "-" . $Numero;
  54. $FechaEmision = $Documento[0]['fecha'];
  55. $FechaVencimiento = $Documento[0]['fecha'];
  56. $TipoDocumento = $Documento[0]['tipodoc'];
  57. $TotalGeneral = $Documento[0]['monto'];
  58. $Gravada = $Documento[0]['subtotal'];
  59. $SumatoriaIGV_Total = $Documento[0]['igv'];
  60. $Letras = $this->Letras();
  61. $MontoLetras = $Letras->num2letras($TotalGeneral, 1);
  62.  
  63. $xml = new \DomDocument("1.0", "UTF-8");
  64. $xml->formatOutput = true;
  65. //Cabecera de la Factura
  66. $Invoice = $xml->createElementNS("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2", "Invoice");
  67. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
  68. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
  69. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ccts", "urn:un:unece:uncefact:documentation:2");
  70. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
  71. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
  72. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
  73. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
  74. $Invoice->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
  75.  
  76. $UBLExtensiones = $xml->createElement("ext:UBLExtensions");
  77. $UBLExtension = $UBLExtensiones->appendChild($xml->createElement("ext:UBLExtension"));
  78. $UBLExtension->appendChild($xml->createElement("ext:ExtensionContent"));
  79. $UBLExtensiones->appendChild($UBLExtension);
  80. $Invoice->appendChild($UBLExtensiones);
  81. $Invoice->appendChild($xml->createElement("cbc:UBLVersionID", "2.1"));
  82. $Invoice->appendChild($xml->createElement("cbc:CustomizationID", "2.0"));
  83. $Invoice->appendChild($xml->createElement("cbc:ID", $FacturaNumero));
  84. $Invoice->appendChild($xml->createElement("cbc:IssueDate", date("Y-m-d", strtotime($FechaEmision))));
  85. $Invoice->appendChild($xml->createElement("cbc:IssueTime", date("H:i:s")));
  86. $Invoice->appendChild($xml->createElement("cbc:DueDate", date("Y-m-d", strtotime($FechaVencimiento))));
  87. $InvoiceTypeCode = $Invoice->appendChild($xml->createElement("cbc:InvoiceTypeCode", $TipoDocumento));
  88. $InvoiceTypeCode->setAttribute("listID", "0101");
  89. $InvoiceTypeCode->setAttribute("listAgencyName", "PE:SUNAT");
  90. $InvoiceTypeCode->setAttribute("listName", "SUNAT:Identificador de Tipo de Documento");
  91. $InvoiceTypeCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01");
  92. $Note = $Invoice->appendChild($xml->createElement("cbc:Note", $MontoLetras));
  93. $Note->setAttribute("languageLocaleID", "1000");
  94. $DocumentCurrencyCode = $Invoice->appendChild($xml->createElement("cbc:DocumentCurrencyCode", "PEN"));
  95. $DocumentCurrencyCode->setAttribute("listID", "ISO 4217 Alpha");
  96. $DocumentCurrencyCode->setAttribute("listName", "Currency");
  97. $DocumentCurrencyCode->setAttribute("listAgencyName", "United Nations Economic Commission for Europe");
  98. $Invoice->appendChild($xml->createElement("cbc:LineCountNumeric", 1));
  99. //Firma Digital
  100. $Signature = $Invoice->appendChild($xml->createElement("cac:Signature"));
  101. $Signature->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
  102. $SignatoryParty = $Signature->appendChild($xml->createElement("cac:SignatoryParty"));
  103. $PartyIdentification = $SignatoryParty->appendChild($xml->createElement("cac:PartyIdentification"));
  104. $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
  105. $PartyName = $SignatoryParty->appendChild($xml->createElement("cac:PartyName"));
  106. $PartyName->appendChild($xml->createElement("cbc:Name", $RazonSocialEmisor));
  107. $DigitalSignatureAttachment = $Signature->appendChild($xml->createElement("cac:DigitalSignatureAttachment"));
  108. $ExternalReference = $DigitalSignatureAttachment->appendChild($xml->createElement("cac:ExternalReference"));
  109. $ExternalReference->appendChild($xml->createElement("cbc:URI", $RazonSocialEmisor));
  110. //Fin Firma Digital
  111. $AccountingSupplierParty = $xml->createElement("cac:AccountingSupplierParty");
  112. $Party = $AccountingSupplierParty->appendChild($xml->createElement("cac:Party"));
  113. $PartyIdentification = $Party->appendChild($xml->createElement("cac:PartyIdentification"));
  114. $ID = $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
  115. $ID->setAttribute("schemeID", $TipoDocumentoEmisor);
  116. $ID->setAttribute("schemeName", "SUNAT:Identificador de Documento de Identidad");
  117. $ID->setAttribute("schemeAgencyName", "PE:SUNAT");
  118. $ID->setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06");
  119. $PartyName = $Party->appendChild($xml->createElement("cac:PartyName"));
  120. $PartyName->appendChild($xml->createElement("cbc:Name", $RazonSocialEmisor));
  121. $PartyLegalEntity = $Party->appendChild($xml->createElement("cac:PartyLegalEntity"));
  122. $PartyLegalEntity->appendChild($xml->createElement("cbc:RegistrationName", $RazonSocialEmisor));
  123. $RegistrationAddress = $PartyLegalEntity->appendChild($xml->createElement("cac:RegistrationAddress"));
  124. $RegistrationAddress->appendChild($xml->createElement("cbc:ID", $UbigeoEmisor));
  125. $RegistrationAddress->appendChild($xml->createElement("cbc:AddressTypeCode", "0001"));
  126. $RegistrationAddress->appendChild($xml->createElement("cbc:CitySubdivisionName", "NONE"));
  127. $RegistrationAddress->appendChild($xml->createElement("cbc:CityName", $DepartamentoEmisor));
  128. $RegistrationAddress->appendChild($xml->createElement("cbc:CountrySubentity", $ProvinciaEmisor));
  129. $RegistrationAddress->appendChild($xml->createElement("cbc:District", $DistritoEmisor));
  130. $AddressLine = $RegistrationAddress->appendChild($xml->createElement("cac:AddressLine"));
  131. $AddressLine->appendChild($xml->createElement("cbc:Line", $DireccionEmisor));
  132. $Country = $RegistrationAddress->appendChild($xml->createElement("cac:Country"));
  133. $Country->appendChild($xml->createElement("cbc:IdentificationCode", $PaisEmisor));
  134. $PartyLegalEntity->appendChild($RegistrationAddress);
  135. $Invoice->appendChild($AccountingSupplierParty);
  136. $AccountingCustomerParty = $xml->createElement("cac:AccountingCustomerParty");
  137. $Party = $AccountingCustomerParty->appendChild($xml->createElement("cac:Party"));
  138. $PartyIdentification = $Party->appendChild($xml->createElement("cac:PartyIdentification"));
  139. $ID = $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUCAdquiriente));
  140. $ID->setAttribute("schemeID", "6");
  141. $ID->setAttribute("schemeName", "SUNAT:Identificador de Documento de Identidad");
  142. $ID->setAttribute("schemeAgencyName", "PE:SUNAT");
  143. $ID->setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06");
  144. $PartyLegalEntity = $Party->appendChild($xml->createElement("cac:PartyLegalEntity"));
  145. $PartyLegalEntity->appendChild($xml->createElement("cbc:RegistrationName", $RazonSocialAdquiriente));
  146. $RegistrationAddress = $PartyLegalEntity->appendChild($xml->createElement("cac:RegistrationAddress"));
  147. $AddressLine = $RegistrationAddress->appendChild($xml->createElement("cac:AddressLine"));
  148. $AddressLine->appendChild($xml->createElement("cbc:Line", $DireccionEmisor));
  149. $Country = $RegistrationAddress->appendChild($xml->createElement("cac:Country"));
  150. $Country->appendChild($xml->createElement("cbc:IdentificationCode", $PaisEmisor));
  151. $PartyLegalEntity->appendChild($RegistrationAddress);
  152. $Invoice->appendChild($AccountingCustomerParty);
  153. //Sumatoria IGV
  154. $TaxTotal0 = $xml->createElement("cac:TaxTotal");
  155. $TaxAmount0 = $TaxTotal0->appendChild($xml->createElement("cbc:TaxAmount", $SumatoriaIGV_Total));
  156. $TaxAmount0->setAttribute("currencyID", "PEN");
  157. $TaxSubtotal = $TaxTotal0->appendChild($xml->createElement("cac:TaxSubtotal"));
  158. $TaxableAmount = $TaxSubtotal->appendChild($xml->createElement("cbc:TaxableAmount", $Gravada));
  159. $TaxableAmount->setAttribute("currencyID", "PEN");
  160. $TaxAmount = $TaxSubtotal->appendChild($xml->createElement("cbc:TaxAmount", $SumatoriaIGV_Total));
  161. $TaxAmount->setAttribute("currencyID", "PEN");
  162. $TaxCategory1 = $TaxSubtotal->appendChild($xml->createElement("cac:TaxCategory"));
  163. $ID = $TaxCategory1->appendChild($xml->createElement("cbc:ID", "S"));
  164. $ID->setAttribute("schemeID", "UN/ECE 5305");
  165. $ID->setAttribute("schemeName", "Tax Category Identifier");
  166. $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
  167. $TaxScheme = $TaxCategory1->appendChild($xml->createElement("cac:TaxScheme"));
  168. $ID = $TaxScheme->appendChild($xml->createElement("cbc:ID", 1000));
  169. $ID->setAttribute("schemeID", "UN/ECE 5305");
  170. $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
  171. $TaxScheme->appendChild($xml->createElement("cbc:Name", "IGV"));
  172. $TaxScheme->appendChild($xml->createElement("cbc:TaxTypeCode", "VAT"));
  173. $Invoice->appendChild($TaxTotal0);
  174. $LegalMonetaryTotal = $xml->createElement("cac:LegalMonetaryTotal");
  175. $LineExtensionAmount = $xml->createElement("cbc:LineExtensionAmount", $Gravada);
  176. $LineExtensionAmount->setAttribute("currencyID", "PEN");
  177. $PayableAmount = $xml->createElement("cbc:PayableAmount", $TotalGeneral);
  178. $PayableAmount->setAttribute("currencyID", "PEN");
  179. $LegalMonetaryTotal->appendChild($LineExtensionAmount);
  180. $LegalMonetaryTotal->appendChild($PayableAmount);
  181. $Invoice->appendChild($LegalMonetaryTotal);
  182. //---------------------------------------------------------------------------------------------
  183. if($Documento{0}[detalle].length==0){
  184. $Item = 0;
  185. foreach ($Detalles as $Detalle) {
  186. //Variables
  187. $Item++;
  188. $Cantidad = $Detalle["cant"];
  189. $PrecioVenta = $Detalle["precio"];
  190. $TotalItem = $Detalle["totallinea"]; //agregar total linea
  191. $CodigoPrecio = "01";
  192. $TributoID = 1000;
  193. $TributoName = "IGV";
  194. $TributoTax = "VAT";
  195. $ProductoDescripcion = $Detalle["codigo"] . " " . $Detalle["detalle"] . " " . $Detalle["detadicional"];
  196. $PrecioBruto = $Detalle["precio"];
  197. $IGVItem = $Detalle["igvlinea"];
  198. $AfectadoXIGV = 10;
  199. ////Detalle de Item de la Factura
  200. $InvoiceLine = $xml->createElement("cac:InvoiceLine");
  201. $InvoiceLine->appendChild($xml->createElement("cbc:ID", $Item));
  202. $InvoicedQuantity = $InvoiceLine->appendChild($xml->createElement("cbc:InvoicedQuantity", $Cantidad));
  203. $InvoicedQuantity->setAttribute("unitCode", "NIU");
  204. $InvoicedQuantity->setAttribute("unitCodeListID", "UN/ECE rec 20");
  205. $InvoicedQuantity->setAttribute("unitCodeListAgencyName", "United Nations Economic Commission for Europe");
  206. $LineExtensionAmount = $xml->createElement("cbc:LineExtensionAmount", $PrecioVenta);
  207. $LineExtensionAmount->setAttribute("currencyID", "PEN");
  208. $InvoiceLine->appendChild($LineExtensionAmount);
  209. $PricingReference = $xml->createElement("cac:PricingReference");
  210. $AlternativeConditionPrice = $xml->createElement("cac:AlternativeConditionPrice");
  211. $PriceAmount = $xml->createElement("cbc:PriceAmount", $TotalItem);
  212. $PriceAmount->setAttribute("currencyID", "PEN");
  213. $PriceTypeCode = $xml->createElement("cbc:PriceTypeCode", $CodigoPrecio);
  214. $PriceTypeCode->setAttribute("listName", "SUNAT:Indicador de tipo de Precio");
  215. $PriceTypeCode->setAttribute("listAgencyName", "PE:SUNAT");
  216. $PriceTypeCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16");
  217. $AlternativeConditionPrice->appendChild($PriceAmount);
  218. $AlternativeConditionPrice->appendChild($PriceTypeCode);
  219. $PricingReference->appendChild($AlternativeConditionPrice);
  220. $InvoiceLine->appendChild($PricingReference);
  221. $Invoice->appendChild($InvoiceLine);
  222.  
  223. //Subtotalizar Item
  224. $TaxTotal2 = $xml->createElement("cac:TaxTotal");
  225. $TaxAmount2 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
  226. $TaxAmount2->setAttribute("currencyID", "PEN");
  227. $TaxTotal2->appendChild($TaxAmount2);
  228. $TaxSubtotal2 = $xml->createElement("cac:TaxSubtotal");
  229. $TaxableAmount = $xml->createElement("cbc:TaxableAmount", $PrecioVenta);
  230. $TaxableAmount->setAttribute("currencyID", "PEN");
  231. $TaxAmount3 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
  232. $TaxAmount3->setAttribute("currencyID", "PEN");
  233. $TaxSubtotal2->appendChild($TaxableAmount);
  234. $TaxSubtotal2->appendChild($TaxAmount3);
  235. $TaxCategory = $xml->createElement("cac:TaxCategory");
  236. $ID = $TaxCategory->appendChild($xml->createElement("cbc:ID", "S"));
  237. $ID->setAttribute("schemeID", "UN/ECE 5305");
  238. $ID->setAttribute("schemeName", "Tax Category Identifier");
  239. $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
  240. $TaxCategory->appendChild($xml->createElement("cbc:Percent", 18.00));
  241. $TaxExemptionReasonCode = $TaxCategory->appendChild($xml->createElement("cbc:TaxExemptionReasonCode", $AfectadoXIGV));
  242. $TaxExemptionReasonCode->setAttribute("listAgencyName", "PE:SUNAT");
  243. $TaxExemptionReasonCode->setAttribute("listName", "SUNAT:Codigo de Tipo de Afectacion del IGV");
  244. $TaxExemptionReasonCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07");
  245. $TaxScheme2 = $TaxCategory->appendChild($xml->createElement("cac:TaxScheme"));
  246. $ID = $TaxScheme2->appendChild($xml->createElement("cbc:ID", $TributoID));
  247. $ID->setAttribute("schemeID", "UN/ECE 5153");
  248. $ID->setAttribute("schemeName", "Tax Sheme Identifier");
  249. $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
  250. $TaxScheme2->appendChild($xml->createElement("cbc:Name", $TributoName));
  251. $TaxScheme2->appendChild($xml->createElement("cbc:TaxTypeCode", $TributoTax));
  252. $TaxCategory->appendChild($TaxScheme2);
  253. $TaxSubtotal2->appendChild($TaxCategory);
  254. $TaxTotal2->appendChild($TaxSubtotal2);
  255. $InvoiceLine->appendChild($TaxTotal2);
  256.  
  257. //Detalle Item
  258. $Item2 = $xml->createElement("cac:Item");
  259. $Description = $xml->createElement("cbc:Description", $ProductoDescripcion);
  260. $Item2->appendChild($Description);
  261. $SellersItemIdentification = $xml->createElement("cac:SellersItemIdentification");
  262. $SellersItemIdentification->appendChild($xml->createElement("cbc:ID", $CodigoPrecio));
  263. $Item2->appendChild($SellersItemIdentification);
  264. $InvoiceLine->appendChild($Item2);
  265. $Price = $xml->createElement("cac:Price");
  266. $PriceAmount2 = $xml->createElement("cbc:PriceAmount", $PrecioBruto);
  267. $PriceAmount2->setAttribute("currencyID", "PEN");
  268. $Price->appendChild($PriceAmount2);
  269. $InvoiceLine->appendChild($Price);
  270. $Invoice->appendChild($InvoiceLine);
  271. $xml->appendChild($Invoice);
  272. }
  273. }else{
  274. //$Detalles = $FacturaDetalle->getUnDetalleCompartido($id);
  275. $Item = 1;
  276. //Variables
  277. $Cantidad = 1;
  278. $PrecioVenta = $Documento["subtotal"];
  279. $TotalItem = $Documento["monto"]; //agregar total linea
  280. $CodigoPrecio = "01";
  281. $TributoID = 1000;
  282. $TributoName = "IGV";
  283. $TributoTax = "VAT";
  284. $codigo = "0300";
  285. $ProductoDescripcion = $Documento["codigo"] . " " . $Detalles["detalle"];
  286. $PrecioBruto = $Documento["subtotal"];
  287. $IGVItem = $Documento["igv"];
  288. $AfectadoXIGV = 10;
  289. ////Detalle de Item de la Factura
  290. $InvoiceLine = $xml->createElement("cac:InvoiceLine");
  291. $InvoiceLine->appendChild($xml->createElement("cbc:ID", $Item));
  292. $InvoicedQuantity = $InvoiceLine->appendChild($xml->createElement("cbc:InvoicedQuantity", $Cantidad));
  293. $InvoicedQuantity->setAttribute("unitCode", "NIU");
  294. $InvoicedQuantity->setAttribute("unitCodeListID", "UN/ECE rec 20");
  295. $InvoicedQuantity->setAttribute("unitCodeListAgencyName", "United Nations Economic Commission for Europe");
  296. $LineExtensionAmount = $xml->createElement("cbc:LineExtensionAmount", $PrecioVenta);
  297. $LineExtensionAmount->setAttribute("currencyID", "PEN");
  298. $InvoiceLine->appendChild($LineExtensionAmount);
  299. $PricingReference = $xml->createElement("cac:PricingReference");
  300. $AlternativeConditionPrice = $xml->createElement("cac:AlternativeConditionPrice");
  301. $PriceAmount = $xml->createElement("cbc:PriceAmount", $TotalItem);
  302. $PriceAmount->setAttribute("currencyID", "PEN");
  303. $PriceTypeCode = $xml->createElement("cbc:PriceTypeCode", $CodigoPrecio);
  304. $PriceTypeCode->setAttribute("listName", "SUNAT:Indicador de tipo de Precio");
  305. $PriceTypeCode->setAttribute("listAgencyName", "PE:SUNAT");
  306. $PriceTypeCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16");
  307. $AlternativeConditionPrice->appendChild($PriceAmount);
  308. $AlternativeConditionPrice->appendChild($PriceTypeCode);
  309. $PricingReference->appendChild($AlternativeConditionPrice);
  310. $InvoiceLine->appendChild($PricingReference);
  311. $Invoice->appendChild($InvoiceLine);
  312.  
  313. //Subtotalizar Item
  314. $TaxTotal2 = $xml->createElement("cac:TaxTotal");
  315. $TaxAmount2 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
  316. $TaxAmount2->setAttribute("currencyID", "PEN");
  317. $TaxTotal2->appendChild($TaxAmount2);
  318. $TaxSubtotal2 = $xml->createElement("cac:TaxSubtotal");
  319. $TaxableAmount = $xml->createElement("cbc:TaxableAmount", $PrecioVenta);
  320. $TaxableAmount->setAttribute("currencyID", "PEN");
  321. $TaxAmount3 = $xml->createElement("cbc:TaxAmount", number_format($IGVItem, 2));
  322. $TaxAmount3->setAttribute("currencyID", "PEN");
  323. $TaxSubtotal2->appendChild($TaxableAmount);
  324. $TaxSubtotal2->appendChild($TaxAmount3);
  325. $TaxCategory = $xml->createElement("cac:TaxCategory");
  326. $ID = $TaxCategory->appendChild($xml->createElement("cbc:ID", "S"));
  327. $ID->setAttribute("schemeID", "UN/ECE 5305");
  328. $ID->setAttribute("schemeName", "Tax Category Identifier");
  329. $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
  330. $TaxCategory->appendChild($xml->createElement("cbc:Percent", 18.00));
  331. $TaxExemptionReasonCode = $TaxCategory->appendChild($xml->createElement("cbc:TaxExemptionReasonCode", $AfectadoXIGV));
  332. $TaxExemptionReasonCode->setAttribute("listAgencyName", "PE:SUNAT");
  333. $TaxExemptionReasonCode->setAttribute("listName", "SUNAT:Codigo de Tipo de Afectacion del IGV");
  334. $TaxExemptionReasonCode->setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07");
  335. $TaxScheme2 = $TaxCategory->appendChild($xml->createElement("cac:TaxScheme"));
  336. $ID = $TaxScheme2->appendChild($xml->createElement("cbc:ID", $TributoID));
  337. $ID->setAttribute("schemeID", "UN/ECE 5153");
  338. $ID->setAttribute("schemeName", "Tax Sheme Identifier");
  339. $ID->setAttribute("schemeAgencyName", "United Nations Economic Commission for Europe");
  340. $TaxScheme2->appendChild($xml->createElement("cbc:Name", $TributoName));
  341. $TaxScheme2->appendChild($xml->createElement("cbc:TaxTypeCode", $TributoTax));
  342. $TaxCategory->appendChild($TaxScheme2);
  343. $TaxSubtotal2->appendChild($TaxCategory);
  344. $TaxTotal2->appendChild($TaxSubtotal2);
  345. $InvoiceLine->appendChild($TaxTotal2);
  346.  
  347. //Detalle Item
  348. $Item2 = $xml->createElement("cac:Item");
  349. $Description = $xml->createElement("cbc:Description", $ProductoDescripcion);
  350. $Item2->appendChild($Description);
  351. $SellersItemIdentification = $xml->createElement("cac:SellersItemIdentification");
  352. $SellersItemIdentification->appendChild($xml->createElement("cbc:ID", $CodigoPrecio));
  353. $Item2->appendChild($SellersItemIdentification);
  354. $InvoiceLine->appendChild($Item2);
  355. $Price = $xml->createElement("cac:Price");
  356. $PriceAmount2 = $xml->createElement("cbc:PriceAmount", $PrecioBruto);
  357. $PriceAmount2->setAttribute("currencyID", "PEN");
  358. $Price->appendChild($PriceAmount2);
  359. $InvoiceLine->appendChild($Price);
  360. $Invoice->appendChild($InvoiceLine);
  361. $xml->appendChild($Invoice);
  362. }
  363. }
  364.  
  365.  
  366. $NomArch = $RUC_Emisor . "-" . $TipoDocumento . "-" . $FacturaNumero;
  367. $xml->save("public/sinfirmar/" . $NomArch . ".xml");
  368. chmod("public/sinfirmar/" . $NomArch . ".xml", 0777);
  369.  
  370. $Funciones = $this->Funciones();
  371. $Funciones->firmar("public/sinfirmar/", $NomArch, "public/firmados/");
  372.  
  373. header('Content-Type: text/html; charset=UTF-8');
  374. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 16pt; color: #000000; margin-bottom: 10px;">';
  375. echo 'SUNAT. Facturación electrónica Perú.<br>';
  376. echo '<span style="color: #6A0888; font-size: 15pt;">';
  377. echo 'Envío de factura electrónica al servidor de SUNAT<br>';
  378. echo 'y obtención de la Constancia de Recepción (CDR).';
  379. echo '</span>';
  380. echo '<hr width="100%"></div>';
  381. // NOMBRE DE ARCHIVO A PROCESAR.
  382. ## =============================================================================
  383. ## Creación del archivo .ZIP
  384. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-bottom: 10px;">';
  385. echo 'Archivo .XML (factura electrónica) a comprimir.<br>';
  386. echo '<span style="color: #000000;">' . $NomArch . '.xml</span>';
  387. echo '</div>';
  388.  
  389. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-bottom: 10px;">';
  390. echo 'Archivo .ZIP (conteniendo el doc. electrónico) a enviar al servidor de SUNAT.<br>';
  391. echo '<span style="color: #000000;">' . $NomArch . '.zip</span>';
  392. echo '</div>';
  393.  
  394. $zip = new \PclZip("public/zipeados/" . $NomArch . ".zip");
  395. $zip->create("public/firmados/" . $NomArch . ".xml", PCLZIP_OPT_REMOVE_ALL_PATH);
  396. chmod("public/zipeados/" . $NomArch . ".zip", 0777);
  397.  
  398. # ==============================================================================
  399. # Procedimiento para enviar comprobante a la SUNAT
  400. //URL para enviar las solicitudes a SUNAT
  401. $wsdlURL = 'https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService?wsdl';
  402. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-bottom: 10px;">';
  403. echo 'URL Beta de SUNAT:<br>';
  404. echo '<span style="color: #000000;">' . $wsdlURL . '</span>';
  405. echo '</div>';
  406. //Estructura del XML para la conexión
  407. $XMLString = '<?xml version="1.0" encoding="UTF-8"?>
  408. <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">
  409. <soapenv:Header>
  410. <wsse:Security>
  411. <wsse:UsernameToken Id="ABC-123">
  412. <wsse:Username>20565381785MODDATOS</wsse:Username>
  413. <wsse:Password>MODDATOS</wsse:Password>
  414. </wsse:UsernameToken>
  415. </wsse:Security>
  416. </soapenv:Header>
  417. <soapenv:Body>
  418. <ser:sendBill>
  419. <fileName>' . $NomArch . '.zip</fileName>
  420. <contentFile>' . base64_encode(file_get_contents("public/zipeados/" . $NomArch . '.zip')) . '</contentFile>
  421. </ser:sendBill>
  422. </soapenv:Body>
  423. </soapenv:Envelope>';
  424. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099;">';
  425. echo 'SOAP de envío al servidor de SUNAT con el método sendBill.';
  426. echo '</div>';
  427. echo $XMLString;
  428.  
  429. //Realizamos la llamada a nuestra función
  430. $result = $Funciones->soapCall($wsdlURL, $callFunction = "sendBill", $XMLString);
  431.  
  432. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-top: 10px;">';
  433. echo 'Respuesta del servidor de SUNAT:<br>';
  434. echo '<span style="color: #000000;">' . $result . '</span>';
  435. echo '</div>';
  436.  
  437. //Descargamos el Archivo Response
  438. $archivo = fopen("public/zipeados/" . "C" . $NomArch . '.xml', 'w+');
  439. fputs($archivo, $result);
  440. fclose($archivo);
  441.  
  442. /* LEEMOS EL ARCHIVO XML */
  443. $xml = simplexml_load_file("public/zipeados/" . "C" . $NomArch . '.xml');
  444. foreach ($xml->xpath('//applicationResponse') as $response) {
  445. }
  446.  
  447. /* AQUI DESCARGAMOS EL ARCHIVO CDR(CONSTANCIA DE RECEPCIÓN) */
  448. $cdr = base64_decode($response);
  449. $archivo = fopen("public/zipeados/" . 'R-' . $NomArch . '.zip', 'w+');
  450. fputs($archivo, $cdr);
  451. fclose($archivo);
  452. chmod("public/zipeados/" . 'R-' . $NomArch . '.zip', 0777);
  453.  
  454. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-top: 10px;">';
  455. echo 'Archivo .zip recibido.<br>';
  456. echo '<span style="color: #000000;">R-' . $NomArch . '.zip</span>';
  457. echo '</div>';
  458.  
  459. $archive = new \PclZip("public/zipeados/" . 'R-' . $NomArch . '.zip');
  460. if ($archive->extract(PCLZIP_OPT_PATH, 'public/cdr') == 0) {
  461. die("Error : " . $archive->errorInfo(true));
  462. } //else {
  463. // chmod('zipeados/' . 'R-' . $NomArch . '.xml', 0777);
  464. // }
  465.  
  466. echo '<div style="font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12pt; color: #000099; margin-top: 10px;">';
  467. echo 'Archivo .XML constancia de recepción (CRD) ya descomprimido.<br>';
  468. echo '<span style="color: #A70202;">R-' . $NomArch . '.xml</span>';
  469. echo '</div>';
  470.  
  471. /* Eliminamos el Archivo Response */
  472. unlink("public/zipeados/" . 'C' . $NomArch . '.xml');
  473. return null;
  474. }
  475.  
  476. public function generaPdfAction()
  477. {
  478. $NomArchPDF = $this->params()->fromRoute("id", null);
  479. header('Content-Type: text/html; charset=UTF-8');
  480. // Variables correspondientes a la factura.
  481. $RUC = ""; // RUC.
  482. $NomRazSoc = ""; // Nombre o Razón social.
  483. $FecEmi = ""; // Fecha de emisión.
  484. $Domicilio = ""; // Domicilio.
  485. $CodHash = ""; // Código Hash.
  486. $TipoDoc = ""; // Tipo de documento.
  487. $TotGrav = 0; // Total gravado.
  488. $TotIGV = 0; // Total IGV.
  489. $TotMonto = 0; // Total importe.
  490. // Variables correspondientes a los productos o servicios de la factura.
  491. $CodProdServ = ""; // Código.
  492. $ProdServ = ""; // Descripción.
  493. $Cant = 0; // Cantidad.
  494. $UniMed = ""; // Unidad de medida.
  495. $Precio = 0; // Precio unitario.
  496. $Importe = 0; // Importe.
  497. // Obteniendo datos del archivo .XML (factura electrónica)======================
  498. $Ruta = "public/firmados/";
  499. $xml = file_get_contents($Ruta . $NomArchPDF . ".xml");
  500.  
  501. #== Obteniendo datos del archivo .XML
  502. $DOM = new \DomDocument("1.0", "UTF-8");
  503. $DOM->preserveWhiteSpace = false;
  504. $DOM->loadXML($xml);
  505. ### DATOS DE LA FACTURA ####################################################
  506. // Obteniendo RUC.
  507. $DocXML = $DOM->getElementsByTagName('CustomerAssignedAccountID');
  508. foreach ($DocXML as $Nodo) {
  509. $RUC = $Nodo->nodeValue;
  510. }
  511. // Obteniendo Fecha de emisión.
  512. $DocXML = $DOM->getElementsByTagName('IssueDate');
  513. foreach ($DocXML as $Nodo) {
  514. $FecEmi = $Nodo->nodeValue;
  515. }
  516. // Obteniendo Nombre o Razón social.
  517. $DocXML = $DOM->getElementsByTagName('RegistrationName');
  518. $i = 0;
  519. foreach ($DocXML as $Nodo) {
  520. if ($i == 0) {
  521. $NomRazSoc = $Nodo->nodeValue;
  522. }
  523. $i++;
  524. }
  525. // Obteniendo domicilio.
  526. $DocXML = $DOM->getElementsByTagName('StreetName');
  527. $i = 0;
  528. foreach ($DocXML as $Nodo) {
  529. if ($i == 0) {
  530. $Domicilio = $Nodo->nodeValue;
  531. }
  532. $i++;
  533. }
  534. // Obteniendo Codigo Hash.
  535. $DocXML = $DOM->getElementsByTagName('DigestValue');
  536. $i = 0;
  537. foreach ($DocXML as $Nodo) {
  538. if ($i == 0) {
  539. $CodHash = $Nodo->nodeValue;
  540. }
  541. $i++;
  542. }
  543. // Clave del tipo de documento.
  544. $DocXML = $DOM->getElementsByTagName('InvoiceTypeCode');
  545. $i = 0;
  546. foreach ($DocXML as $Nodo) {
  547. if ($i == 0) {
  548. $TipoDoc = $Nodo->nodeValue;
  549. }
  550. $i++;
  551. }
  552. ### DATOS DEL PRODUCTO O SERVICIO. #########################################
  553. // Código del producto o servicio.
  554. $DocXML = $DOM->getElementsByTagName('PriceTypeCode');
  555. $i = 0;
  556. foreach ($DocXML as $Nodo) {
  557. if ($i == 0) {
  558. $CodProdServ = $Nodo->nodeValue;
  559. }
  560. $i++;
  561. }
  562. // Descripción del producto o servicio.
  563. $DocXML = $DOM->getElementsByTagName('Description');
  564. $i = 0;
  565. foreach ($DocXML as $Nodo) {
  566. if ($i == 0) {
  567. $ProdServ = $Nodo->nodeValue;
  568. }
  569. $i++;
  570. }
  571. // Cantidad de producto o servicio.
  572. $DocXML = $DOM->getElementsByTagName('InvoicedQuantity');
  573. $i = 0;
  574. foreach ($DocXML as $Nodo) {
  575. if ($i == 0) {
  576. $Cant = $Nodo->nodeValue;
  577. }
  578. $i++;
  579. }
  580. // Unidad de medida del producto o servicio.
  581. $DocXML = $DOM->getElementsByTagName('InvoicedQuantity');
  582. $i = 0;
  583. foreach ($DocXML as $Nodo) {
  584. if ($i == 0) {
  585. //$UniMed = $Nodo->nodeValue;
  586. $UniMed = $Nodo->getAttribute('unitCode');
  587. }
  588. $i++;
  589. }
  590. // Precio unitario.
  591. $DocXML = $DOM->getElementsByTagName('PriceAmount');
  592. $i = 0;
  593. foreach ($DocXML as $Nodo) {
  594. if ($i == 1) {
  595. $Precio = $Nodo->nodeValue;
  596. }
  597. $i++;
  598. }
  599. // Importe.
  600. $DocXML = $DOM->getElementsByTagName('LineExtensionAmount');
  601. $i = 0;
  602. foreach ($DocXML as $Nodo) {
  603. if ($i == 0) {
  604. $Importe = $Nodo->nodeValue;
  605. }
  606. $i++;
  607. }
  608. ### TOTALES DE LA FACTURA ##################################################
  609. // Total gravado.
  610. $DocXML = $DOM->getElementsByTagName('PayableAmount');
  611. $i = 0;
  612. foreach ($DocXML as $Nodo) {
  613. if ($i == 1) {
  614. $TotGrav = $Nodo->nodeValue;
  615. }
  616. $i++;
  617. }
  618. // Total IGV.
  619. $DocXML = $DOM->getElementsByTagName('TaxAmount');
  620. $i = 0;
  621. foreach ($DocXML as $Nodo) {
  622. $TotIGV = $Nodo->nodeValue;
  623. }
  624. // Monto total.
  625. $DocXML = $DOM->getElementsByTagName('PayableAmount');
  626. $i = 0;
  627. foreach ($DocXML as $Nodo) {
  628. $TotMonto = $Nodo->nodeValue;
  629. }
  630. //var_dump($RUC,$NomRazSoc,$FecEmi,$Domicilio,$CodHash,$TipoDoc,$TotGrav,$TotIGV,$TotMonto,$CodProdServ,$ProdServ,$Cant,$UniMed,$Precio,$Importe);
  631. // Crear el gráfico con el código de barras
  632. $textoCodBar = "| $TipoDoc | A | 123 | $TotIGV | $TotMonto | $FecEmi | $TipoDoc | F002-026 | VALOR RESUMEN | $CodHash |";
  633. //var_dump($textoCodBar);
  634. $pdf417 = new PDF417();
  635. $codigo_barra = $pdf417->encode($textoCodBar);
  636. // Create a PNG image
  637. $renderer = new ImageRenderer([
  638. 'format' => 'png',
  639. ]);
  640. $image = $renderer->render($codigo_barra);
  641. $image->save("public/img/" . $NomArchPDF . ".png");
  642.  
  643. //= Creación del documetno .PDF
  644. $pdf = new PDFPlugin('P', 'cm', 'Letter');
  645. $pdf->AliasNbPages();
  646. $pdf->AddPage();
  647. $pdf->AddFont('IDAutomationHC39M', '', 'IDAutomationHC39M.php');
  648. $pdf->AddFont('verdana', '', 'verdana.php');
  649. $pdf->SetAutoPageBreak(true);
  650. $pdf->SetMargins(0, 0, 0);
  651. $pdf->SetLineWidth(0.02);
  652. $pdf->SetFillColor(0, 0, 0);
  653.  
  654. $pdf->image("public/img/Membrete_Fact.jpg", 1, 1, 10, 2.5);
  655. $pdf->image("public/img/" . $NomArchPDF . ".png", 0.7, 10, 9, 3);
  656. $pdf->SetTextColor(0, 0, 0);
  657. $pdf->SetFont('arial', '', 10);
  658. $pdf->SetXY(1.2, 13);
  659. $pdf->Cell(8, 0.25, utf8_decode("Representación impresa de la factura electrónica."), 0, 1, 'C', 0);
  660. $pdf->RoundedRect(12, 1, 8, 2.5, 0.2, '');
  661. $pdf->SetTextColor(170, 0, 0);
  662. $pdf->SetFont('arial', '', 14);
  663. $pdf->SetXY(12, 1.5);
  664. $pdf->Cell(8, 0.25, "RUC: 20138998780", 0, 1, 'C', 0);
  665. $pdf->SetTextColor(0, 0, 0);
  666. $pdf->SetFont('arial', 'B', 14);
  667. $pdf->SetXY(12, 2.2);
  668. $pdf->Cell(8, 0.25, utf8_decode("FACTURA ELECTRÓNICA"), 0, 1, 'C', 0);
  669. $pdf->SetTextColor(0, 0, 150);
  670. $pdf->SetFont('arial', '', 14);
  671. $pdf->SetXY(12, 2.9);
  672. $pdf->Cell(8, 0.25, "F002-026", 0, 1, 'C', 0);
  673. $pdf->RoundedRect(1, 4, 19, 3.2, 0.2, '');
  674. $pdf->SetTextColor(0, 0, 0);
  675. $pdf->SetFont('arial', 'B', 10);
  676. $pdf->SetXY(1.1, 4.2);
  677. $pdf->Cell(1, 0.35, utf8_decode("Señores: "), 0, 1, 'L', 0);
  678. $pdf->SetXY(1.1, 4.2 + 0.6);
  679. $pdf->Cell(1, 0.35, utf8_decode("Dirección: "), 0, 1, 'L', 0);
  680. $pdf->SetXY(1.1, 4.2 + (0.6 * 2));
  681. $pdf->Cell(1, 0.35, utf8_decode("RUC: "), 0, 1, 'L', 0);
  682. $pdf->SetXY(1.1, 4.2 + (0.6 * 3));
  683. $pdf->Cell(1, 0.35, utf8_decode("Fecha de emisión: "), 0, 1, 'L', 0);
  684. $pdf->SetXY(1.1, 4.2 + (0.6 * 4));
  685. $pdf->Cell(1, 0.35, utf8_decode("Moneda: "), 0, 1, 'L', 0);
  686. $pdf->SetTextColor(0, 0, 0);
  687. $pdf->SetFont('arial', '', 10);
  688. $pdf->SetXY(4.7, 4.2);
  689. $pdf->Cell(1, 0.35, utf8_decode($NomRazSoc), 0, 1, 'L', 0);
  690. $pdf->SetXY(4.7, 4.2 + 0.6);
  691. $pdf->Cell(1, 0.35, utf8_decode($Domicilio), 0, 1, 'L', 0);
  692. $pdf->SetXY(4.7, 4.2 + (0.6 * 2));
  693. $pdf->Cell(1, 0.35, utf8_decode($RUC), 0, 1, 'L', 0);
  694. $pdf->SetXY(4.7, 4.2 + (0.6 * 3));
  695. $pdf->Cell(1, 0.35, utf8_decode($FecEmi), 0, 1, 'L', 0);
  696. $pdf->SetXY(4.7, 4.2 + (0.6 * 4));
  697. $pdf->Cell(1, 0.35, utf8_decode("SOL"), 0, 1, 'L', 0);
  698. $X = 0;
  699. $Y = 0;
  700. $pdf->SetTextColor(0, 0, 0);
  701. $pdf->SetFont('arial', '', 10);
  702. $pdf->SetXY($X + 1, $Y + 8);
  703. $pdf->Cell(2.5, 0.5, utf8_decode("Código"), 1, 1, 'L', 0);
  704. $pdf->SetXY($X + 3.5, $Y + 8);
  705. $pdf->Cell(6.65, 0.5, utf8_decode("Descripción"), 1, 1, 'L', 0);
  706. $pdf->SetXY($X + 10.15, $Y + 8);
  707. $pdf->Cell(2, 0.5, utf8_decode("Cantidad"), 1, 1, 'C', 0);
  708. $pdf->SetXY($X + 12.15, $Y + 8);
  709. $pdf->Cell(2.65, 0.5, utf8_decode("Unidad"), 1, 1, 'L', 0);
  710. $pdf->SetXY($X + 14.8, $Y + 8);
  711. $pdf->Cell(2.7, 0.5, utf8_decode("Precio unitario"), 1, 1, 'R', 0);
  712. $pdf->SetXY($X + 17.5, $Y + 8);
  713. $pdf->Cell(2.5, 0.5, utf8_decode("Precio venta"), 1, 1, 'R', 0);
  714. $Y = $Y + 0.5;
  715. $pdf->SetXY($X + 1, $Y + 8);
  716. $pdf->Cell(2.5, 0.8, utf8_decode($CodProdServ), 1, 1, 'L', 0);
  717. $pdf->SetXY($X + 3.5, $Y + 8);
  718. $pdf->Cell(6.65, 0.8, utf8_decode($ProdServ), 1, 1, 'L', 0);
  719. $pdf->SetXY($X + 10.15, $Y + 8);
  720. $pdf->Cell(2, 0.8, utf8_decode($Cant), 1, 1, 'C', 0);
  721. $pdf->SetXY($X + 12.15, $Y + 8);
  722. $pdf->Cell(2.65, 0.8, utf8_decode($UniMed), 1, 1, 'L', 0);
  723. $pdf->SetXY($X + 14.8, $Y + 8);
  724. $pdf->Cell(2.7, 0.8, number_format($Precio, 2), 1, 1, 'R', 0);
  725. $pdf->SetXY($X + 17.5, $Y + 8);
  726. $pdf->Cell(2.5, 0.8, number_format($Importe, 2), 1, 1, 'R', 0);
  727. $pdf->SetTextColor(0, 0, 0);
  728. $pdf->SetFont('arial', '', 10);
  729. $pdf->SetXY(9.9, 10);
  730. $pdf->Cell(7.6, 0.5, utf8_decode("Total Valor de Venta - Operaciones Gravadas:"), 1, 1, 'R', 0);
  731. $pdf->SetXY(17.5, 10);
  732. $pdf->Cell(2.5, 0.5, number_format($TotGrav, 2), 1, 1, 'R', 0);
  733. $pdf->SetXY(9.9, 10 + 0.5);
  734. $pdf->Cell(7.6, 0.5, utf8_decode("IGV:"), 1, 1, 'R', 0);
  735. $pdf->SetXY(17.5, 10 + 0.5);
  736. $pdf->Cell(2.5, 0.5, number_format($TotIGV, 2), 1, 1, 'R', 0);
  737. $pdf->SetXY(9.9, 10 + (0.5 * 2));
  738. $pdf->Cell(7.6, 0.5, utf8_decode("Importe Total:"), 1, 1, 'R', 0);
  739. $pdf->SetXY(17.5, 10 + (0.5 * 2));
  740. $pdf->Cell(2.5, 0.5, number_format($TotMonto, 2), 1, 1, 'R', 0);
  741. $pdf->line(1, 24.8, 20.5, 24.8);
  742. $pdf->SetTextColor(0, 0, 0);
  743. $pdf->SetFont('arial', '', 9);
  744. $pdf->SetXY(1, 25);
  745. $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');
  746. $pdf->Output("/facturasPDF/" . $NomArchPDF . ".pdf", "F");
  747. chmod("/facturasPDF/" . $NomArchPDF . ".pdf", 0777);
  748. }
  749.  
  750. public function anularAction()
  751. {
  752. $id = $this->params()->fromRoute("id", null);
  753. $this->dbAdapter = $this->getServiceLocator()->get('ZendDbAdapterAdapter');
  754. $FacturaCabecera = new FacturaModel($this->dbAdapter);
  755. $Documento = $FacturaCabecera->getUnaFactura($id);
  756. $FacturaCabecera->anulacionSunat($id);
  757.  
  758. //Datos del Cliente
  759. $RUC_Emisor = '20565381785';
  760. $RazonSocialEmisor = 'CRUCERISTA CENTER E.I.R.L.';
  761. $TipoDocumentoEmisor = "6";
  762. $Factura = "F";
  763. //$Serie = $Documento[0]['serie'];
  764. $Serie = "001";
  765. $Numero = $Documento[0]['numero'];
  766. $FacturaNumero = $Factura . $Serie . "-" . $Numero;
  767. $FechaEmision = date("Ymd");
  768. $Motivo = "CANCELACION";
  769.  
  770. $ruta = 'public/bajas/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
  771. if (!file_exists($ruta)) {
  772. mkdir($ruta, 755, true);
  773. }
  774. $i = 1;
  775. while (file_exists($ruta . $RUC_Emisor . '-RA-' . date('Ymd') . '-' . $i . '.xml')) {
  776. $i++;
  777. // el valor de i es el actual que se va crear
  778. }
  779.  
  780. $xml = new \DomDocument("1.0", "ISO-8859-1");
  781. $xml->standalone = false;
  782. $xml->formatOutput = true;
  783. //Cabecera de la Factura
  784. $Anulacion = $xml->createElementNS("urn:sunat:names:specification:ubl:peru:schema:xsd:VoidedDocuments-1", "VoidedDocuments");
  785. $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
  786. $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
  787. $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
  788. $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
  789. $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
  790. $Anulacion->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
  791.  
  792. //Totales de la Factura
  793. $UBLExtensiones = $xml->createElement("ext:UBLExtensions");
  794. $UBLExtension = $UBLExtensiones->appendChild($xml->createElement("ext:UBLExtension"));
  795. $UBLExtension->appendChild($xml->createElement("ext:ExtensionContent"));
  796. $UBLExtensiones->appendChild($UBLExtension);
  797. $Anulacion->appendChild($UBLExtensiones);
  798.  
  799. $Anulacion->appendChild($xml->createElement("cbc:UBLVersionID", "2.0"));
  800. $Anulacion->appendChild($xml->createElement("cbc:CustomizationID", "1.0"));
  801. $Anulacion->appendChild($xml->createElement("cbc:ID", 'RA-' . date('Ymd') . '-' . $i));
  802. $Anulacion->appendChild($xml->createElement("cbc:ReferenceDate", date("Y-m-d", strtotime($FechaEmision))));
  803. $Anulacion->appendChild($xml->createElement("cbc:IssueDate", date("Y-m-d", strtotime($FechaEmision))));
  804. //---------------------------------------------------------------------------------------
  805. //Firma Digital
  806. $Signature = $Anulacion->appendChild($xml->createElement("cac:Signature"));
  807. $Signature->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
  808. $SignatoryParty = $Signature->appendChild($xml->createElement("cac:SignatoryParty"));
  809. $PartyIdentification = $SignatoryParty->appendChild($xml->createElement("cac:PartyIdentification"));
  810. $PartyIdentification->appendChild($xml->createElement("cbc:ID", $RUC_Emisor));
  811. $PartyName = $SignatoryParty->appendChild($xml->createElement("cac:PartyName"));
  812. $PartyName->appendChild($xml->createElement("cbc:Name", $RazonSocialEmisor));
  813. $DigitalSignatureAttachment = $Signature->appendChild($xml->createElement("cac:DigitalSignatureAttachment"));
  814. $ExternalReference = $DigitalSignatureAttachment->appendChild($xml->createElement("cac:ExternalReference"));
  815. $ExternalReference->appendChild($xml->createElement("cbc:URI", $RUC_Emisor));
  816. //-----------------------------------------------------------------------------------------
  817. //Razon Social o Nombres y Apellidos del Emisor
  818. $Empresa = $xml->createElement("cac:AccountingSupplierParty");
  819. $Empresa->appendChild($xml->createElement("cbc:CustomerAssignedAccountID", $RUC_Emisor));
  820. $Empresa->appendChild($xml->createElement("cbc:AdditionalAccountID", $TipoDocumentoEmisor));
  821. $Party = $xml->createElement("cac:Party");
  822. $PartyLegalEntity = $Party->appendChild($xml->createElement("cac:PartyLegalEntity"));
  823. $PartyLegalEntity->appendChild($xml->createElement("cbc:RegistrationName", $RazonSocialEmisor));
  824. $Party->appendChild($PartyLegalEntity);
  825. $Empresa->appendChild($Party);
  826. $Anulacion->appendChild($Empresa);
  827.  
  828. $VoidedDocumentsLine1 = $xml->createElement("sac:VoidedDocumentsLine");
  829. $VoidedDocumentsLine1->appendChild($xml->createElement("cbc:LineID", "1"));
  830. $VoidedDocumentsLine1->appendChild($xml->createElement("cbc:DocumentTypeCode", "01"));
  831. $VoidedDocumentsLine1->appendChild($xml->createElement("sac:DocumentSerialID", $Serie));
  832. $VoidedDocumentsLine1->appendChild($xml->createElement("sac:DocumentNumberID", $Numero));
  833. $VoidedDocumentsLine1->appendChild($xml->createElement("sac:VoidReasonDescription", $Motivo));
  834. $Anulacion->appendChild($VoidedDocumentsLine1);
  835. $xml->appendChild($Anulacion);
  836.  
  837. $xml->save($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.xml');
  838. chmod($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.xml', 0777);
  839.  
  840. $Funciones = $this->Funciones();
  841. $Funciones->firmar($ruta, $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i), $ruta);
  842.  
  843. $zip = new \PclZip($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip');
  844. $zip->create($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.xml', PCLZIP_OPT_REMOVE_ALL_PATH);
  845. chmod($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip', 0777);
  846. $wsdlURL = 'https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService?wsdl';
  847. $XMLString = '<?xml version="1.0" encoding="UTF-8"?>
  848. <soapenv:Envelope
  849. xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  850. xmlns:ser="http://service.sunat.gob.pe"
  851. xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  852. <soapenv:Header>
  853. <wsse:Security>
  854. <wsse:UsernameToken Id="ABC-123">
  855. <wsse:Username>20565381785MODDATOS</wsse:Username>
  856. <wsse:Password>MODDATOS</wsse:Password>
  857. </wsse:UsernameToken>
  858. </wsse:Security>
  859. </soapenv:Header>
  860. <soapenv:Body>
  861. <ser:sendSummary>
  862. <fileName>' . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip</fileName>
  863. <contentFile>' . base64_encode(file_get_contents($ruta . $RUC_Emisor . '-' . 'RA-' . date('Ymd') . '-' . ($i) . '.zip')) . '</contentFile>
  864. </ser:sendSummary>
  865. </soapenv:Body>
  866. </soapenv:Envelope>';
  867.  
  868. //Realizamos la llamada a nuestra función
  869. $Funciones = $this->Funciones();
  870. $result = $Funciones->soapCall($wsdlURL, $callFunction = "sendSummary", $XMLString);
  871. echo 'La Factura ' . $FacturaNumero . ' ha sido dado de baja';
  872. return null;
  873. }
  874.  
  875. public function generapdfinvoice($Encabezado = array(), $NumDocumento, $Datos, $productos = array(), $MontoLetras, $nombre_archivo, $firma = '', $NHabitacion = '')
  876. {
  877.  
  878. $arr = $Encabezado;
  879. $medidas = array(90, 217); // Ajustar aqui segun los milimetros necesarios;
  880.  
  881. $pdf = new \Pdf('P', 'mm', $medidas, true, 'UTF-8', false);
  882. $pdf->setPageFormat($medidas, $orientation = 'P');
  883.  
  884. $pdf->RUCEmpresa = $arr['Encabezado']['Emisor']['RUCEmisor'];
  885. $pdf->NumDocumento = $NumDocumento;
  886.  
  887. $pdf->SetCreator(PDF_CREATOR);
  888. $pdf->SetAuthor('Erwin Torres León');
  889. $pdf->SetTitle($nombre_archivo);
  890.  
  891. switch ($Datos['tipo_documento']) {
  892. case "01":
  893. $pdf->NomDocumento = 'FACTURA ELECTRÓNICA';
  894. break;
  895. case "03":
  896. $pdf->NomDocumento = 'BOLETA ELECTRÓNICA';
  897. break;
  898. case "07":
  899. $pdf->NomDocumento = 'NOTA DE CRÉDITO ELECTRÓNICA';
  900. break;
  901. case "08":
  902. $pdf->NomDocumento = 'NOTA DE DÉDITO ELECTRÓNICA';
  903. break;
  904. }
  905. // Establecer el tipo de letra
  906.  
  907. //Si tienes que imprimir carácteres ASCII estándar, puede utilizar las fuentes básicas como
  908. // Helvetica para reducir el tamaño del archivo.
  909. $pdf->SetFont('Helvetica', '', 12, '', true);
  910.  
  911. // Añadir una página
  912. // Este método tiene varias opciones, consulta la documentación para más información.
  913. $pdf->Open();
  914. $pdf->AddPage();
  915. // ponemos los márgenes
  916. //$pdf->SetMargins(15,15);
  917.  
  918. /* incluimos un rectángulo relleno para contener datos del cliente */
  919. //$pdf->Rect(15,47,180,22,'FD','',array(255,255,255));
  920. $pdf->SetFont('Helvetica', 'B', 8);
  921. $pdf->SetXY(2, 24);
  922. $pdf->Cell(2, 48, "RUC/DNI:", 0, 0, 'L');
  923. $pdf->SetFont('Helvetica', '', 8);
  924. $pdf->SetXY(20, 24);
  925. $pdf->Cell(10, 48, $arr['Encabezado']['Receptor']['RUCReceptor'], 0, 0, 'L');
  926. $pdf->SetFont('Helvetica', 'B', 10);
  927.  
  928. $pdf->SetFont('Helvetica', 'B', 8);
  929. $pdf->Ln(7);
  930. $pdf->SetXY(2, 28);
  931. $pdf->Cell(17, 48, "Cliente:", 0, 0, 'L');
  932. $pdf->SetFont('Helvetica', '', 8);
  933. $pdf->SetXY(20, 28);
  934. $pdf->Cell(17, 48, $arr['Encabezado']['Receptor']['RznSoc'], 0, 0, 'L');
  935. $pdf->Ln(5);
  936. $pdf->SetFont('Helvetica', 'B', 8);
  937. $pdf->SetXY(2, 32);
  938. $pdf->Cell(17, 48, "Dirección:", 0, 0, 'L');
  939. $pdf->SetXY(20, 32);
  940. $pdf->SetFont('Helvetica', '', 8);
  941. $pdf->Cell(190, 48, $arr['Encabezado']['Receptor']['Direccion'], 0, 'L');
  942. $pdf->SetFont('Helvetica', 'B', 8);
  943. $pdf->SetXY(2, 36);
  944. $pdf->Cell(30, 48, "Fecha de Emisión:", 0, 0, 'L');
  945. $pdf->SetFont('Helvetica', '', 8);
  946. $pdf->SetXY(30, 36);
  947. $pdf->Cell(30, 48, $Datos['fecharegistro'], 0, 0, 'L');
  948. $pdf->SetFont('Helvetica', 'B', 8);
  949. $pdf->SetXY(2, 40);
  950. $pdf->Cell(30, 48, "Moneda:", 0, 0, 'L');
  951. $pdf->SetFont('Helvetica', '', 8);
  952. $pdf->SetXY(30, 40);
  953. $pdf->Cell(30, 48, 'Soles', 0, 0, 'L');
  954.  
  955. $pdf->SetFont('Helvetica', 'B', 8);
  956. $pdf->SetXY(2, 44);
  957. $pdf->Cell(30, 48, "Nº Habitación:", 0, 0, 'L');
  958. $pdf->SetFont('Helvetica', '', 8);
  959. $pdf->SetXY(30, 44);
  960. $pdf->Cell(30, 48, $NHabitacion, 0, 0, 'L');
  961.  
  962. $pdf->Ln(4);
  963. $pdf->SetX(1);
  964. $pdf->Cell(100, 52, "------------------------------------------------------------------------------------", 0, 0, 'L');
  965. $pdf->Ln();
  966. // Anchuras de las columnas
  967. //$w = array(10, 20, 16, 95,18,22);
  968. $w = array(8, 50);
  969. // Títulos de las columnas
  970. $pdf->SetFont('Helvetica', 'B', 8);
  971. $header = array('Cod.', 'Descripción');
  972. $pdf->SetXY(2, 69);
  973.  
  974. // Cabeceras
  975. for ($i = 0; $i < count($header); $i++) {
  976. $pdf->Cell($w[$i], 7, $header[$i], 0, 0, 'L', 0);
  977. }
  978.  
  979. $pdf->Ln();
  980. // Datos
  981. $i = 1;
  982. $pdf->SetFont('Helvetica', '', 7);
  983.  
  984. if ($Datos['Moneda'] == 'PEN'):
  985. $CodMoneda = 'S/.';
  986. else:
  987. $CodMoneda = '$';
  988. endif;
  989.  
  990. foreach ($productos as $row) {
  991. $pdf->SetX(2);
  992. $pdf->Cell($w[0], 4, $i, '0');
  993.  
  994. $y = $pdf->GetY();
  995. $acotado = $row['pro_desc'];
  996. $pdf->MultiCell($w[1], 4, $acotado, 0, ‘L’);
  997. $pdf->SetXY(149, $y);
  998.  
  999. $pdf->Ln();
  1000.  
  1001. $pdf->SetFont('Helvetica', 'B', 7);
  1002. $pdf->Cell(60, 1, $CodMoneda . ' ' . number_format(round($row['pro_total']), 2), 0, 0, 'R');
  1003. $pdf->Ln();
  1004. $i++;
  1005. $pdf->SetFont('Helvetica', '', 7);
  1006. }
  1007.  
  1008. /*TOTALES*/
  1009. $pdf->TotGravadas = $CodMoneda . " " . number_format($Datos['TotGravada'], 2);
  1010. $pdf->TotGratuitas = $CodMoneda . " " . number_format($Datos['TotGratuitas'], 2);
  1011. $pdf->TotExoneradas = $CodMoneda . " " . number_format($Datos['TotExoneradas'], 2);
  1012. $pdf->TotInafectas = $CodMoneda . " " . number_format($Datos['TotInafectas'], 2);
  1013.  
  1014. //$pdf->Ln();
  1015.  
  1016. //VALIDACION PARA EL DESCUENTO GLOBAL
  1017.  
  1018. if ($Datos['DescuentoGlobal'] > 0) {
  1019. $Datos['TotVenta'] = number_format($Datos['TotVenta'] - $Datos['DescuentoGlobal'], 2);
  1020. $Datos['TotGravada'] = $Datos['TotVenta'] / 1.18;
  1021. $Datos['TotIgv'] = $Datos['TotVenta'] - $Datos['TotGravada'];
  1022. }
  1023.  
  1024. $pdf->SetX(0);
  1025. $pdf->Cell(100, 5, "------------------------------------------------------------------------------------------------", 0, 0, 'L');
  1026. $pdf->Ln();
  1027. $pdf->SetFont('Helvetica', '', 7);
  1028. $pdf->Cell(17, 5, "OP. GRAVADAS: " . $CodMoneda, 0, 0, 'R');
  1029. $pdf->SetFont('Helvetica', 'B', 7);
  1030. $pdf->Cell(48, 5, number_format($Datos['TotGravada'], 2), 0, 0, 'R');
  1031. $pdf->Ln();
  1032. $pdf->SetFont('Helvetica', '', 7);
  1033. $pdf->Cell(20, 5, "OP. EXONERADAS: " . $CodMoneda, 0, 0, 'R');
  1034. $pdf->SetFont('Helvetica', 'B', 7);
  1035. $pdf->Cell(45, 5, number_format($Datos['TotExoneradas'], 2), 0, 0, 'R');
  1036. $pdf->Ln();
  1037. $pdf->SetFont('Helvetica', '', 7);
  1038. $pdf->Cell(17, 5, "OP. INAFECTAS: " . $CodMoneda, 0, 0, 'R');
  1039. $pdf->SetFont('Helvetica', 'B', 7);
  1040. $pdf->Cell(48, 5, number_format($Datos['TotInafectas'], 2), 0, 0, 'R');
  1041. $pdf->Ln();
  1042. $pdf->SetFont('Helvetica', '', 7);
  1043. $pdf->Cell(17, 5, "OP. GRATUITAS: " . $CodMoneda, 0, 0, 'R');
  1044. $pdf->SetFont('Helvetica', 'B', 7);
  1045. $pdf->Cell(48, 5, number_format($Datos['TotGratuitas'], 2), 0, 0, 'R');
  1046. $pdf->Ln();
  1047. $pdf->SetFont('Helvetica', '', 7);
  1048. $pdf->Cell(17, 5, "IGV: " . $CodMoneda, 0, 0, 'R');
  1049. $pdf->SetFont('Helvetica', 'B', 7);
  1050. $pdf->Cell(48, 5, number_format($Datos['TotIgv'], 2), 0, 0, 'R');
  1051. $pdf->Ln();
  1052. $pdf->SetFont('Helvetica', '', 7);
  1053. $pdf->Cell(17, 5, "DESCUENTO: " . $CodMoneda, 0, 0, 'R');
  1054. $pdf->SetFont('Helvetica', 'B', 7);
  1055. $pdf->Cell(48, 5, number_format($Datos['DescuentoGlobal'], 2), 0, 0, 'R');
  1056. $pdf->Ln();
  1057. $pdf->SetFont('Helvetica', '', 7);
  1058. $pdf->Cell(17, 5, "TOTAL: " . $CodMoneda, 0, 0, 'R');
  1059. $pdf->SetFont('Helvetica', 'B', 7);
  1060. $pdf->Cell(48, 5, number_format($Datos['TotVenta'], 2), 0, 0, 'R');
  1061. //$pdf->Ln();
  1062.  
  1063. $datosAdicionales_CDB = $arr['Encabezado']['Emisor']['RUCEmisor'] . "|" . $Datos['tipo_documento'] . "|" . $NumDocumento . "|" . $Datos['TotIgv'] . "|" . $Datos['TotVenta'] . "|" . $Datos['fecharegistro'] . "|" . $arr['Encabezado']['Receptor']['TipoDocumento'] . "|" . $arr['Encabezado']['Receptor']['RUCReceptor'];
  1064.  
  1065. // set style for barcode
  1066. $style = array(
  1067. 'border' => 0,
  1068. 'vpadding' => 'auto',
  1069. 'hpadding' => 'auto',
  1070. 'fgcolor' => array(0, 0, 0),
  1071. 'bgcolor' => false, //array(255,255,255)
  1072. 'module_width' => 1, // width of a single module in points
  1073. 'module_height' => 1, // height of a single module in points
  1074. );
  1075. $pdf->CodBarras = $datosAdicionales_CDB;
  1076. $pdf->SetX(2);
  1077. $pdf->Ln();
  1078. $pdf->SetX(15);
  1079. //$pdf->Cell(15,5,$firma,0,'C');
  1080.  
  1081. $pdf->Cell(2, 5, 'Representación impresa de la ' . ucwords(strtolower($pdf->strtolower_utf8($pdf->NomDocumento))) . '', 0, 'J');
  1082. $pdf->Ln();
  1083. $alto = $pdf->GetY();
  1084. $pdf->SetX(20);
  1085. $pdf->Cell(2, 5, $pdf->write2DBarcode($datosAdicionales_CDB, 'PDF417', 10, $alto, 135, 20, $style, 'N'), 0, 'J');
  1086. $pdf->Ln();
  1087. $pdf->SetX(26);
  1088. $pdf->Cell(2, 5, 'Forma de Pago: ' . $Datos['formapago'], 0, 'J');
  1089. //$pdf->Line(10,10,200,10);
  1090.  
  1091. //$nombre_archivo='prueba.pdf';
  1092. $pdf->Output('PDF/' . $nombre_archivo . '.pdf', 'F');
  1093. }
  1094. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement