factura_electronica.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  3. header("Access-Control-Allow-Origin: *");
  4. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
  5. header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
  6. http_response_code(204); // Sin contenido
  7. exit;
  8. }
  9. header("Access-Control-Allow-Origin: *");
  10. header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
  11. header("Access-Control-Allow-Headers: Content-Type, Authorization");
  12. error_reporting(E_ALL);
  13. ini_set('display_errors', 0);
  14. ini_set('log_errors', 1);
  15. ini_set('error_log', '/logs/error.log');
  16. require __DIR__ . '/vendor/autoload.php';
  17. use Mike42\Escpos\Printer;
  18. use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
  19. use Mike42\Escpos\EscposImage;
  20. use Mike42\Escpos\PrintConnectors\FilePrintConnector;
  21. // Recibir datos - puede venir como JSON string o como objeto serializado por jQuery
  22. $dataPrint = null;
  23. if(isset($_POST["dataPrint"])){
  24. // Si es string JSON, decodificar
  25. if(is_string($_POST["dataPrint"])){
  26. $dataPrint = json_decode($_POST["dataPrint"]);
  27. } else {
  28. // Si jQuery ya lo deserializó como array, convertir a objeto
  29. $dataPrint = json_decode(json_encode($_POST["dataPrint"]));
  30. }
  31. }
  32. if($dataPrint){
  33. //Printer Name
  34. $PRINTER_NAME = $dataPrint->printer ?? 'POS-80C';
  35. //CONFIGURACIONES
  36. $maxDescripcion = 25; //Maximo de caracteres por linea para la descripcion del producto
  37. $iscEmpresa = $dataPrint->isc ?? "demo";
  38. //DATOS
  39. $nombreEmpresa = $dataPrint->nombre_empresa;
  40. $razonSocial = $dataPrint->rsocial_empresa;
  41. $giro = $dataPrint->giro_empresa;
  42. $documentoDueno = "NRC: ".$dataPrint->nrc_empresa." | NIT: ".$dataPrint->nit_empresa;
  43. $direccion = $dataPrint->direcion_empresa;
  44. $documento = strToUpper($dataPrint->documento) ?? null;
  45. $fecha = $dataPrint->fecha;
  46. $caja = $dataPrint->caja;
  47. $clienteNombre = $dataPrint->cliente;
  48. $clienteDocumento = $dataPrint->clienteDoc ?? null;
  49. if($clienteDocumento && $dataPrint->clienteDocNum){
  50. $clienteDocumento = $clienteDocumento.": ".$dataPrint->clienteDocNum;
  51. }
  52. $clienteNRC = $dataPrint->clienteNRC ?? null;
  53. $productos = $dataPrint->productos_normal;
  54. $totalGravado = $dataPrint->totalGrabadas;
  55. $totalExento = $dataPrint->totalExento;
  56. $totalNoSujeto = $dataPrint->totalNS;
  57. $totalFinal = floatval(str_replace(',', '', $dataPrint->totales->totalTotal));
  58. $totalCambio = floatval($dataPrint->efectivo) - $totalFinal;
  59. $dteNControl = $dataPrint->dte_numero_control;
  60. $dteCodGen = $dataPrint->dte_codigo_generacion;
  61. $disclaimer = "Este comprobante no es un documento fiscal. Su DTE será enviado al correo electrónico proporcionado.";
  62. $qrMessage = "También puedes escanear el código QR para ver y descargar tu factura electrónica en línea.";
  63. $mensaje = $dataPrint->mensaje_ticket." \n ¡Gracias por su compra!" ?? "¡Gracias por su compra!";
  64. $urlQR = "https://consultadte.factuexpress.com.sv/$iscEmpresa/$dteCodGen";
  65. $numeroReferencia = $dataPrint->referencia;
  66. try {
  67. $connector = new WindowsPrintConnector($PRINTER_NAME);
  68. $printer = new Printer($connector);
  69. // ENCABEZADO
  70. $printer->setJustification(Printer::JUSTIFY_CENTER);
  71. $printer->setTextSize(2, 2);
  72. $printer->text("$nombreEmpresa\n");
  73. $printer->setTextSize(1, 1);
  74. $printer->text("$razonSocial\n");
  75. $printer->text("$giro\n");
  76. $printer->text("$documentoDueno\n");
  77. $printer->text("$direccion\n");
  78. $printer->text(str_repeat("-", 45) . "\n");
  79. //DOCUMENTO
  80. if($documento){
  81. $printer->setEmphasis(true);
  82. $printer->text("$documento\n");
  83. $printer->setEmphasis(false);
  84. $printer->text(str_repeat("-", 45) . "\n");
  85. }
  86. //GENERAL
  87. $printer->setJustification(Printer::JUSTIFY_LEFT);
  88. $printer->setEmphasis(true);
  89. $printer->text("Fecha: ");
  90. $printer->setEmphasis(false);
  91. $printer->text("$fecha");
  92. $printer->setEmphasis(true);
  93. $printer->text(" Caja: ");
  94. $printer->setEmphasis(false);
  95. $printer->text("$caja\n");
  96. //CLIENTE
  97. if($clienteNombre && $clienteNombre != ""){
  98. $printer->setEmphasis(true);
  99. $printer->text("Cliente:\n");
  100. $printer->setEmphasis(false);
  101. $printer->text("$clienteNombre\n");
  102. }
  103. if($clienteDocumento){
  104. $printer->text("$clienteDocumento\n");
  105. }
  106. if($clienteNRC){
  107. $printer->text("NRC: $clienteNRC\n");
  108. }
  109. $printer->text("\n");
  110. //PRODUCTOS
  111. $printer->setEmphasis(true);
  112. $printer->text("Cant Descripcion Precio Total\n");
  113. $printer->text(str_repeat("-", 45) . "\n");
  114. $printer->setEmphasis(false);
  115. foreach ($productos as $producto) {
  116. $totalUnitario = $producto->cant * $producto->costo;
  117. $cantidad = str_pad(number_format($producto->cant, 2), 4, " ", STR_PAD_RIGHT);
  118. $precio = str_pad(number_format($producto->costo, 2), 7, " ", STR_PAD_LEFT);
  119. $descuento = $producto->descuento && $producto->descuento > 0 ? $producto->descuento : null;
  120. $total = str_pad(number_format($totalUnitario, 2), 7, " ", STR_PAD_LEFT);
  121. // Dividir la descripción en líneas
  122. $descripcion = wordwrap($producto->sku.' '.$producto->desc, $maxDescripcion, "\n", true);
  123. $lineasDescripcion = explode("\n", $descripcion);
  124. // Imprimir primera línea con cantidad, precio y total
  125. $printer->text("$cantidad " . str_pad($lineasDescripcion[0], $maxDescripcion, " ") . " $precio $total\n");
  126. // Imprimir líneas adicionales de la descripción (si hay más)
  127. for ($i = 1; $i < count($lineasDescripcion); $i++) {
  128. $printer->text(" " . str_pad($lineasDescripcion[$i], $maxDescripcion) . "\n");
  129. }
  130. // Imprimir línea de descuento si existe
  131. if ($descuento) {
  132. $printer->text(str_pad(" Descuento:", $maxDescripcion, " ") . str_pad("-" . number_format($descuento, 2), 21, " ", STR_PAD_LEFT) . "\n");
  133. }
  134. }
  135. $printer->text(str_repeat("-", 45) . "\n");
  136. // TOTALES
  137. $printer->setJustification(Printer::JUSTIFY_RIGHT);
  138. // Propina (si aplica)
  139. $propina = floatval($dataPrint->totales->propina ?? 0);
  140. if ($propina > 0) {
  141. // Si hay propina, mostrar subtotal primero
  142. $subtotal = $totalFinal - $propina;
  143. $printer->text("SUBTOTAL $" . number_format($subtotal, 2) . "\n");
  144. $printer->text("PROPINA $" . number_format($propina, 2) . "\n");
  145. }
  146. $printer->setEmphasis(true);
  147. $printer->setTextSize(2, 1);
  148. $printer->text("TOTAL $" . number_format($totalFinal, 2) . "\n");
  149. $printer->setTextSize(1, 1);
  150. $printer->setEmphasis(false);
  151. // FORMA DE PAGO
  152. $efectivo = floatval($dataPrint->efectivo ?? 0);
  153. $pos = floatval($dataPrint->pos ?? 0);
  154. if ($efectivo > 0 && $pos > 0) {
  155. // Pago mixto
  156. $printer->text("EFECTIVO $" . number_format($efectivo, 2) . "\n");
  157. $printer->text("POS $" . number_format($pos, 2) . "\n");
  158. $totalCambio = max(0, $efectivo - ($totalFinal - $pos));
  159. $printer->text("CAMBIO $" . number_format($totalCambio, 2) . "\n");
  160. } elseif ($pos > 0) {
  161. // Solo POS
  162. $printer->text("POS $" . number_format($pos, 2) . "\n");
  163. $printer->text("CAMBIO $0.00\n");
  164. } else {
  165. // Solo efectivo
  166. $printer->text("EFECTIVO $" . number_format($efectivo, 2) . "\n");
  167. $totalCambio = max(0, $efectivo - $totalFinal);
  168. $printer->text("CAMBIO $" . number_format($totalCambio, 2) . "\n");
  169. }
  170. $printer->text(str_repeat("_", 45) . "\n");
  171. //DTE
  172. $printer->setJustification(Printer::JUSTIFY_LEFT);
  173. $printer->text("NUMERO DE CONTROL: \n$dteNControl\n");
  174. $printer->text("CÓDIGO DE GENERACION: \n$dteCodGen\n\n");
  175. $printer->setJustification(Printer::JUSTIFY_CENTER);
  176. // DISCLAIMER
  177. $lineasDisclaimer = wordwrap($disclaimer, 45, "\n", true);
  178. foreach (explode("\n", $lineasDisclaimer) as $linea) {
  179. $printer->text($linea . "\n");
  180. }
  181. // CÓDIGO QR
  182. $printer->text("$qrMessage\n");
  183. $printer->qrCode($urlQR, Printer::QR_ECLEVEL_L, 5);
  184. $printer->text("\n$mensaje\n");
  185. // REFERENCIA
  186. $printer->text("\nRef: $numeroReferencia\n");
  187. $printer->setBarcodeHeight(40);
  188. $printer->setBarcodeWidth(4);
  189. $printer->barcode($numeroReferencia, Printer::BARCODE_CODE39);
  190. // CORTAR PAPEL Y CERRAR IMPRESORA
  191. $printer->feed(2);
  192. $printer->cut();
  193. $printer->pulse(); //Abrir gaveta
  194. $printer->close();
  195. //echo "Ticket impreso correctamente.";
  196. echo json_encode([
  197. "status" => "success",
  198. "message" => "Ticket impreso correctamente."
  199. ]);
  200. } catch (Exception $e) {
  201. //echo "Error al imprimir: " . $e->getMessage();
  202. echo json_encode([
  203. "status" => "error",
  204. "message" => "Error al imprimir: " . $e->getMessage()
  205. ]);
  206. }
  207. }else{
  208. echo json_encode([
  209. "status" => "error",
  210. "message" => "No se recibieron datos para imprimir."
  211. ]);
  212. }