3 Commits b89ac9e86c ... 7464e0ab26

Autor SHA1 Mensaje Fecha
  David Gómez 7464e0ab26 Cambiar parametros en recibo hace 2 meses
  David Gómez 79fedbf44e agregar achivo para precuenta de caja hace 2 meses
  David Gómez c73d44da16 agregar archivos para comandas hace 2 meses
Se han modificado 4 ficheros con 753 adiciones y 318 borrados
  1. 179 0
      comanda_movil.php
  2. 174 186
      precuenta.php
  3. 205 0
      precuenta_movil.php
  4. 195 132
      recibo.php

+ 179 - 0
comanda_movil.php

@@ -0,0 +1,179 @@
+<?php
+/**
+ * Archivo para imprimir comandas desde app móvil
+ * Recibe datos vía POST y los distribuye a las impresoras según cocina
+ * Usa librería: mike42/escpos-php
+ */
+
+if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
+    header("Access-Control-Allow-Origin: *");
+    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
+    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
+    http_response_code(204);
+    exit;
+}
+
+header("Access-Control-Allow-Origin: *");
+header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
+header("Access-Control-Allow-Headers: Content-Type, Authorization");
+header('Content-Type: application/json; charset=utf-8');
+
+error_reporting(E_ALL);
+ini_set('display_errors', 0);
+ini_set('log_errors', 1);
+ini_set('error_log', 'logs/error.log');
+
+require __DIR__ . '/vendor/autoload.php';
+use Mike42\Escpos\Printer;
+use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
+
+// Recibir datos
+$dataPrint = null;
+
+if(isset($_POST["dataPrint"])){
+    if(is_string($_POST["dataPrint"])){
+        $dataPrint = json_decode($_POST["dataPrint"], true);
+    } else {
+        $dataPrint = $_POST["dataPrint"];
+    }
+}
+
+if(!$dataPrint){
+    echo json_encode(['success' => false, 'status' => 'error', 'message' => 'No se recibieron datos para imprimir', 'errores' => []]);
+    exit;
+}
+
+if (!isset($dataPrint['impresos']) || empty($dataPrint['impresos'])) {
+    echo json_encode(['success' => false, 'status' => 'error', 'message' => 'No hay comandas para imprimir', 'errores' => []]);
+    exit;
+}
+
+$impresos = $dataPrint['impresos'];
+$errores = array();
+$exitos = array();
+
+// Iterar sobre cada impresora/cocina
+foreach ($impresos as $nombreImpresora => $datosComanda) {
+    try {
+        // Crear connector según el nombre de la impresora
+        $connector = new WindowsPrintConnector($nombreImpresora);
+        $printer = new Printer($connector);
+        
+        // ENCABEZADO
+        $printer->setJustification(Printer::JUSTIFY_CENTER);
+        $printer->setTextSize(2, 2);
+        $printer->text($datosComanda['cocina'] . "\n");
+        $printer->setTextSize(1, 1);
+        $printer->text(str_repeat("=", 45) . "\n");
+        $printer->setEmphasis(true);
+        $printer->text("ORDEN #" . (isset($datosComanda['num_orden']) ? $datosComanda['num_orden'] : $datosComanda['id_orden']) . "\n");
+        $printer->setEmphasis(false);
+        $printer->text(str_repeat("=", 45) . "\n");
+        
+        // INFORMACIÓN DE LA ORDEN
+        $printer->setJustification(Printer::JUSTIFY_LEFT);
+        $printer->setEmphasis(true);
+        $printer->text("Fecha: ");
+        $printer->setEmphasis(false);
+        $printer->text(date('d/m/Y H:i', strtotime($datosComanda['fecha'])) . "\n");
+        
+        
+        $printer->setEmphasis(true);
+        $printer->text("Mesa: ");
+        $printer->setEmphasis(false);
+        $printer->text($datosComanda['mesa'] . "\n");
+        
+        /*
+        $printer->setEmphasis(true);
+        $printer->text("Mesero: ");
+        $printer->setEmphasis(false);
+        $printer->text($datosComanda['mesero'] . "\n");
+        
+        $printer->setEmphasis(true);
+        $printer->text("Cliente: ");
+        $printer->setEmphasis(false);
+        $printer->text($datosComanda['cliente'] . "\n");*/
+        
+        $printer->setEmphasis(true);
+        $printer->text("Servicio: ");
+        $printer->setEmphasis(false);
+        $printer->text($datosComanda['servicio'] . "\n");
+        
+        $printer->text(str_repeat("-", 45) . "\n");
+        
+        // PLATOS
+        $printer->setEmphasis(true);
+        $printer->text("PLATOS:\n");
+        $printer->setEmphasis(false);
+        $printer->text(str_repeat("-", 45) . "\n");
+        
+        foreach ($datosComanda['platos'] as $plato) {
+            // $plato es un array con [cant, nombre, acompanamientos, notas]
+            $cant = $plato[0];
+            $nombre = $plato[1];
+            $acompanamientos = isset($plato[2]) ? $plato[2] : '';
+            $notas = isset($plato[3]) ? $plato[3] : '';
+            
+            // Cantidad y nombre del plato
+            $printer->setEmphasis(true);
+            $printer->setTextSize(1, 1);
+            $printer->text(number_format($cant, 0) . "x " . $nombre . "\n");
+            $printer->setEmphasis(false);
+            
+            // Acompañamientos
+            if (!empty($acompanamientos)) {
+                $printer->text("   " . $acompanamientos . "\n");
+            }
+            
+            // Notas del plato
+            if (!empty($notas)) {
+                $printer->text("   Notas: " . $notas . "\n");
+            }
+            
+            $printer->text("\n");
+        }
+        
+        $printer->text(str_repeat("=", 45) . "\n");
+        
+        // NOTAS GENERALES DE LA ORDEN
+        if (!empty($datosComanda['notas'])) {
+            $printer->text("\n");
+            $printer->setEmphasis(true);
+            $printer->setTextSize(1, 1);
+            $printer->text("*** NOTAS ***\n");
+            $printer->setTextSize(1, 1);
+            $printer->setEmphasis(false);
+            $printer->text($datosComanda['notas'] . "\n");
+            $printer->text(str_repeat("=", 45) . "\n");
+        }
+        
+        $printer->feed(3);
+        $printer->cut();
+        $printer->close();
+        
+        $exitos[] = $nombreImpresora . " (" . $datosComanda['cocina'] . ")";
+        
+    } catch (Exception $e) {
+        $errores[] = array(
+            'impresora' => $nombreImpresora,
+            'cocina' => isset($datosComanda['cocina']) ? $datosComanda['cocina'] : 'N/A',
+            'error' => $e->getMessage()
+        );
+    }
+}
+
+// Respuesta
+$response = array(
+    'success' => count($errores) == 0,
+    'status' => count($errores) == 0 ? 'success' : 'partial',
+    'exitos' => $exitos,
+    'errores' => $errores,
+    'total_impresos' => count($impresos),
+    'total_exitos' => count($exitos),
+    'total_errores' => count($errores),
+    'message' => count($errores) == 0 
+        ? 'Todas las comandas se imprimieron correctamente' 
+        : 'Algunas comandas no se pudieron imprimir'
+);
+
+echo json_encode($response);

+ 174 - 186
precuenta.php

@@ -1,4 +1,11 @@
 <?php
+/**
+ * Archivo para imprimir precuentas
+ * Este archivo debe copiarse al servidor de impresión (printserver)
+ * Imprime en la impresora de caja (normalmente POS-80C)
+ * Usa librería: mike42/escpos-php
+ */
+
 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
     header("Access-Control-Allow-Origin: *");
     header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
@@ -10,6 +17,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
 header("Access-Control-Allow-Headers: Content-Type, Authorization");
+header('Content-Type: application/json; charset=utf-8');
 
 error_reporting(E_ALL);
 ini_set('display_errors', 0);
@@ -20,218 +28,198 @@ require __DIR__ . '/vendor/autoload.php';
 use Mike42\Escpos\Printer;
 use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
 
-// Helper functions
-function printLinea($printer, $char = "-", $width = 48) {
-    $printer->text(str_repeat($char, $width) . "\n");
-}
+// Recibir datos
+$dataPrint = null;
 
-function cutString($text, $maxLength) {
-    return substr($text, 0, $maxLength);
+if(isset($_POST["dataPrint"])){
+    // jQuery envía el objeto como está, necesitamos convertirlo a array
+    $dataPrint = is_array($_POST["dataPrint"]) ? $_POST["dataPrint"] : json_decode(json_encode($_POST["dataPrint"]), true);
 }
 
-function printAlignedText($printer, $leftText, $rightText, $width = 48) {
-    $rightLen = strlen($rightText);
-    $leftLen = $width - $rightLen;
-    $leftPadded = str_pad($leftText, $leftLen, " ", STR_PAD_RIGHT);
-    $printer->text($leftPadded . $rightText . "\n");
+if(!$dataPrint){
+    echo json_encode([
+        'success' => false,
+        'status' => 'error', 
+        'message' => 'No se recibieron datos para imprimir'
+    ]);
+    exit;
 }
 
-function printAlignedTextBold($printer, $leftLabel, $leftValue, $rightLabel, $rightValue, $width = 48) {
-    // Imprimir etiqueta izquierda en negrita
-    $printer->setEmphasis(true);
-    $printer->text($leftLabel);
-    $printer->setEmphasis(false);
-    
-    // Calcular espacios necesarios
-    $rightText = $rightLabel . $rightValue;
-    $rightLen = strlen($rightText);
-    $leftTotal = strlen($leftLabel . $leftValue);
-    $spaces = $width - $leftTotal - $rightLen;
+try {
+    // Nombre de la impresora de caja
+    $nombreImpresora = isset($dataPrint['printer']) ? $dataPrint['printer'] : "POS-80C";
     
-    // Imprimir valor izquierdo y espacios
-    $printer->text($leftValue . str_repeat(" ", $spaces));
+    $connector = new WindowsPrintConnector($nombreImpresora);
+    $printer = new Printer($connector);
     
-    // Imprimir etiqueta derecha en negrita
-    $printer->setEmphasis(true);
-    $printer->text($rightLabel);
-    $printer->setEmphasis(false);
-    $printer->text($rightValue . "\n");
-}
-
-function printTextBold($printer, $label, $value) {
+    // ENCABEZADO
+    $printer->setJustification(Printer::JUSTIFY_CENTER);
+    $printer->setTextSize(2, 2);
+    $printer->text($dataPrint['nombre_empresa'] . "\n");
+    $printer->setTextSize(1, 1);
+    $printer->text(str_repeat("=", 45) . "\n");
     $printer->setEmphasis(true);
-    $printer->text($label);
+    $printer->text("PRECUENTA\n");
     $printer->setEmphasis(false);
-    $printer->text($value . "\n");
-}
-
-// Get data from POST
-$dataPrint = null;
-
-if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["dataPrint"])) {
-    // Si es string JSON, decodificar
-    if(is_string($_POST["dataPrint"])){
-        $dataPrint = json_decode($_POST["dataPrint"]);
-    } else {
-        // Si jQuery ya lo deserializó como array, convertir a objeto
-        $dataPrint = json_decode(json_encode($_POST["dataPrint"]));
-    }
-}
-
-if ($dataPrint) {
-    $PRINTER_NAME = $dataPrint->printer ?? 'POS-80C';
+    $printer->text(str_repeat("=", 45) . "\n");
     
-    try {
-        $connector = new WindowsPrintConnector($PRINTER_NAME);
-        $printer = new Printer($connector);
-        
-        // COMPANY HEADER
-        $printer->setJustification(Printer::JUSTIFY_CENTER);
-        $printer->setTextSize(2, 2);
-        $printer->text(cutString(strtoupper($dataPrint->nombre_empresa), 24) . "\n");
-        
-        $printer->setTextSize(1, 1);
-        //$printer->text(cutString(strtoupper($dataPrint->giro_empresa ?? ''), 48) . "\n");
-        //$printer->text(cutString(strtoupper($dataPrint->direcion_empresa), 48) . "\n");
-        //$printer->text(cutString(strtoupper($dataPrint->rsocial_empresa), 48) . "\n");
-        //$printer->text("NRC: " . $dataPrint->nrc_empresa . " - NIT: " . $dataPrint->nit_empresa . "\n");
-        
-        printLinea($printer);
-        
-        // DOCUMENT INFO
-        $printer->setJustification(Printer::JUSTIFY_LEFT);
-        //$printer->text("Control de Ticket Interno");
-        printAlignedTextBold($printer, "Fecha: ", $dataPrint->fecha, "Caja: ", $dataPrint->caja);
-        printAlignedTextBold($printer, "Vendedor: ", $dataPrint->vendedor, "Mesa: ", $dataPrint->mesa_orden);
-        printTextBold($printer, "Servicio: ", $dataPrint->servicio);
-
-        
-        printLinea($printer);
+    // INFORMACIÓN DE LA ORDEN
+    $printer->setJustification(Printer::JUSTIFY_LEFT);
+    
+    if (isset($dataPrint['orden'])) {
+        $orden = is_object($dataPrint['orden']) ? (array)$dataPrint['orden'] : $dataPrint['orden'];
         
-        // CUSTOMER INFO
-        if (isset($dataPrint->cliente) && $dataPrint->cliente != "") {
-            $printer->setJustification(Printer::JUSTIFY_LEFT);
-            $printer->text("Cliente: " . $dataPrint->cliente . "\n");
-            if (isset($dataPrint->direccion_cliente) && $dataPrint->direccion_cliente != "") {
-                $printer->text("Direccion: " . $dataPrint->direccion_cliente . "\n");
-            }
-            printLinea($printer);
+        if (!empty($orden['num_orden'])) {
+            $printer->setEmphasis(true);
+            $printer->text("Orden #: ");
+            $printer->setEmphasis(false);
+            $printer->text($orden['num_orden'] . "\n");
         }
         
-        // PRODUCTS TABLE
-        $printer->setJustification(Printer::JUSTIFY_LEFT);
-        $printer->setEmphasis(true);
-        $printer->text("CANT  DESCRIPCION               PRECIO  TOTAL\n");
-        printLinea($printer);
-        $printer->setEmphasis(false);
-        
-        foreach ($dataPrint->productos_normal as $producto) {
-            $cantidad = str_pad(number_format($producto->cant, 2), 5, " ", STR_PAD_RIGHT);
-            $precio = str_pad(number_format($producto->costo, 2), 7, " ", STR_PAD_LEFT);
-            $total = str_pad(number_format($producto->costo * $producto->cant, 2), 7, " ", STR_PAD_LEFT);
-            
-            $descripcion = wordwrap(strtoupper($producto->desc), 23, "\n", true);
-            $lineasDescripcion = explode("\n", $descripcion);
-            
-            $printer->text("$cantidad " . str_pad($lineasDescripcion[0], 23, " ") . " $precio $total\n");
-            
-            for ($i = 1; $i < count($lineasDescripcion); $i++) {
-                $printer->text("      " . $lineasDescripcion[$i] . "\n");
-            }
-            
-            // Imprimir acompañamientos si existen
-            if (isset($producto->acompanamientos) && $producto->acompanamientos != "") {
-                $printer->setEmphasis(true);
-                $printer->text("      CON: ");
-                $printer->setEmphasis(false);
-                $printer->text(strtoupper($producto->acompanamientos) . "\n");
-            }
-            
-            // Imprimir notas si existen
-            if (isset($producto->notas) && $producto->notas != "") {
-                $printer->setEmphasis(true);
-                $printer->text("      NOTA: ");
-                $printer->setEmphasis(false);
-                $printer->text(strtoupper($producto->notas) . "\n");
-            }
+        if (!empty($orden['fecha'])) {
+            $printer->setEmphasis(true);
+            $printer->text("Fecha: ");
+            $printer->setEmphasis(false);
+            $printer->text(date('d/m/Y H:i', strtotime($orden['fecha'])) . "\n");
         }
         
-        printLinea($printer);
-        
-        // TOTALS
-        $printer->setJustification(Printer::JUSTIFY_RIGHT);
-        $printer->setEmphasis(true);
-        $printer->setTextSize(1, 2);
-        $printer->text("TOTAL $" . number_format($dataPrint->totales->totalTotal, 2) . "\n");
-        $printer->setTextSize(1, 1);
-        $printer->setEmphasis(false);
-        
-        $printer->text("EFECTIVO $" . number_format($dataPrint->efectivo, 2) . "\n");
-        $printer->text("CAMBIO $" . number_format($dataPrint->cambio, 2) . "\n");
-        
-        if (isset($dataPrint->pos) && floatval($dataPrint->pos) > 0) {
-            $printer->text("POS $" . number_format($dataPrint->pos, 2) . "\n");
-        }
-
-        printLinea($printer);
-
-        // NOTAS DE ORDEN
-        if (isset($dataPrint->notas_orden) && $dataPrint->notas_orden != "") {
-            $printer->setJustification(Printer::JUSTIFY_LEFT);
+        if (!empty($orden['salon'])) {
             $printer->setEmphasis(true);
-            $printer->text("NOTAS ORDEN:\n");
+            $printer->text("Salon: ");
             $printer->setEmphasis(false);
-            $notasLines = wordwrap($dataPrint->notas_orden, 48, "\n", true);
-            foreach (explode("\n", $notasLines) as $linea) {
-                $printer->text($linea . "\n");
-            }
+            $printer->text($orden['salon'] . "\n");
         }
         
-        printLinea($printer);
-
-        $printer->setJustification(Printer::JUSTIFY_CENTER);
-        $printer->text("\n");
-        $printer->text("REF.: " . ($dataPrint->referencia) . "\n");
-        
-        /*
-        if (isset($dataPrint->notas) && $dataPrint->notas != "") {
-            $printer->setJustification(Printer::JUSTIFY_LEFT);
-            $printer->text("Notas: " . $dataPrint->notas . "\n");
-            printLinea($printer);
+        if (!empty($orden['mesa'])) {
+            $printer->setEmphasis(true);
+            $printer->text("Mesa: ");
+            $printer->setEmphasis(false);
+            $printer->text($orden['mesa'] . "\n");
         }
-        */
         /*
-        $printer->setJustification(Printer::JUSTIFY_CENTER);
-        $printer->text("\n");
+        if (!empty($orden['mesero'])) {
+            $printer->setEmphasis(true);
+            $printer->text("Mesero: ");
+            $printer->setEmphasis(false);
+            $printer->text($orden['mesero'] . "\n");
+        }*/
         
-        if (isset($dataPrint->mensaje_ticket) && $dataPrint->mensaje_ticket != "") {
-            $mensajeLines = wordwrap($dataPrint->mensaje_ticket, 48, "\n", true);
-            foreach (explode("\n", $mensajeLines) as $linea) {
-                $printer->text($linea . "\n");
-            }
+        if (!empty($orden['cliente'])) {
+            $printer->setEmphasis(true);
+            $printer->text("Cliente: ");
+            $printer->setEmphasis(false);
+            $printer->text($orden['cliente'] . "\n");
         }
-        */
-        
-        // FINISH
-        $printer->feed(2);
-        $printer->cut();
-        $printer->close();
-        
-        echo json_encode([
-            "status" => "success",
-            "message" => "Recibo impreso correctamente."
-        ]);
         
-    } catch (Exception $e) {
-        echo json_encode([
-            "status" => "error",
-            "message" => "Error al imprimir: " . $e->getMessage()
-        ]);
+        if (!empty($orden['servicio'])) {
+            $printer->setEmphasis(true);
+            $printer->text("Servicio: ");
+            $printer->setEmphasis(false);
+            $printer->text($orden['servicio'] . "\n");
+        }
+    }
+    
+    $printer->text(str_repeat("-", 45) . "\n");
+    
+    // ENCABEZADO DE TABLA
+    $printer->setEmphasis(true);
+    $printer->text("CANT  DESCRIPCION               TOTAL\n");
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("-", 45) . "\n");
+    
+    // PLATOS
+    $subtotal = 0;
+    if (isset($dataPrint['platos']) && is_array($dataPrint['platos'])) {
+        foreach ($dataPrint['platos'] as $plato) {
+            // Convertir objeto a array si es necesario
+            $platoArray = is_object($plato) ? (array)$plato : $plato;
+            
+            $cant = isset($platoArray['cant']) ? number_format($platoArray['cant'], 0) : '0';
+            $nombre = isset($platoArray['nombre']) ? $platoArray['nombre'] : '';
+            $precio = isset($platoArray['precio']) ? floatval($platoArray['precio']) : 0;
+            $cantNum = isset($platoArray['cant']) ? floatval($platoArray['cant']) : 0;
+            $total = $cantNum * $precio;
+            $subtotal += $total;
+            
+            // Línea del plato - cant y nombre
+            $cantPad = str_pad($cant, 4);
+            $nombreCorto = substr($nombre, 0, 25);
+            $totalStr = "$" . number_format($total, 2);
+            
+            $printer->text($cantPad . "x " . str_pad($nombreCorto, 27) . str_pad($totalStr, 10, " ", STR_PAD_LEFT) . "\n");
+            
+            // Acompañamientos
+            if (isset($platoArray['acompanamientos']) && is_array($platoArray['acompanamientos']) && count($platoArray['acompanamientos']) > 0) {
+                foreach ($platoArray['acompanamientos'] as $acomp) {
+                    $acompArray = is_object($acomp) ? (array)$acomp : $acomp;
+                    if (isset($acompArray['acompanamiento'])) {
+                        $printer->text("     + " . $acompArray['acompanamiento'] . "\n");
+                    }
+                }
+            }
+            
+            /*
+            if (!empty($platoArray['notas'])) {
+                $printer->text("     Nota: " . $platoArray['notas'] . "\n");
+            }*/
+        }
+    }
+    
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    // TOTALES
+    $printer->setJustification(Printer::JUSTIFY_RIGHT);
+    
+    $ordenSubtotal = 0;
+    $ordenDescuento = 0;
+    $ordenPropina = 0;
+    
+    if (isset($dataPrint['orden'])) {
+        $orden = is_object($dataPrint['orden']) ? (array)$dataPrint['orden'] : $dataPrint['orden'];
+        $ordenSubtotal = isset($orden['subtotal']) ? floatval($orden['subtotal']) : $subtotal;
+        $ordenDescuento = isset($orden['descuento']) ? floatval($orden['descuento']) : 0;
+        $ordenPropina = isset($orden['propina']) ? floatval($orden['propina']) : 0;
+    }
+    
+    $printer->text("Subtotal:  $" . number_format($ordenSubtotal, 2) . "\n");
+    
+    if ($ordenDescuento > 0) {
+        $printer->text("Descuento: -$" . number_format($ordenDescuento, 2) . "\n");
     }
-} else {
+    
+    if ($ordenPropina > 0) {
+        $printer->text("Propina:   $" . number_format($ordenPropina, 2) . "\n");
+    }
+    
+    $total = $ordenSubtotal - $ordenDescuento + $ordenPropina;
+    
+    $printer->text(str_repeat("-", 45) . "\n");
+    $printer->setEmphasis(true);
+    $printer->setTextSize(2, 1);
+    $printer->text("TOTAL: $" . number_format($total, 2) . "\n");
+    $printer->setTextSize(1, 1);
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    $printer->setJustification(Printer::JUSTIFY_CENTER);
+    $printer->text("\n¡Gracias por su preferencia!\n");
+    $printer->text("Esta NO es una factura\n");
+    
+    $printer->feed(3);
+    $printer->cut();
+    $printer->close();
+    
+    echo json_encode([
+        'success' => true,
+        'status' => 'success',
+        'message' => 'Precuenta impresa correctamente en ' . $nombreImpresora
+    ]);
+    
+} catch (Exception $e) {
     echo json_encode([
-        "status" => "error",
-        "message" => "No se recibieron datos para imprimir."
+        'success' => false,
+        'status' => 'error',
+        'message' => 'Error al imprimir: ' . $e->getMessage()
     ]);
 }
 ?>

+ 205 - 0
precuenta_movil.php

@@ -0,0 +1,205 @@
+<?php
+/**
+ * Archivo para imprimir precuentas desde app móvil
+ * Imprime solo en la impresora de caja (normalmente POS-80C)
+  * Usa librería: mike42/escpos-php
+ */
+
+if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
+    header("Access-Control-Allow-Origin: *");
+    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
+    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
+    http_response_code(204);
+    exit;
+}
+
+header("Access-Control-Allow-Origin: *");
+header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
+header("Access-Control-Allow-Headers: Content-Type, Authorization");
+header('Content-Type: application/json; charset=utf-8');
+
+error_reporting(E_ALL);
+ini_set('display_errors', 0);
+ini_set('log_errors', 1);
+ini_set('error_log', 'logs/error.log');
+
+require __DIR__ . '/vendor/autoload.php';
+use Mike42\Escpos\Printer;
+use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
+
+// Recibir datos
+$dataPrint = null;
+
+if(isset($_POST["dataPrint"])){
+    if(is_string($_POST["dataPrint"])){
+        $dataPrint = json_decode($_POST["dataPrint"], true);
+    } else {
+        $dataPrint = $_POST["dataPrint"];
+    }
+}
+
+if(!$dataPrint){
+    echo json_encode([
+        'success' => false,
+        'status' => 'error', 
+        'message' => 'No se recibieron datos para imprimir'
+    ]);
+    exit;
+}
+
+try {
+    // Nombre de la impresora de caja (ajustar según tu configuración)
+    $nombreImpresora = isset($dataPrint['printer']) ? $dataPrint['printer'] : "POS-80C";
+    
+    $connector = new WindowsPrintConnector($nombreImpresora);
+    $printer = new Printer($connector);
+    
+    $anchoPapel = isset($dataPrint['anchopapel']) ? intval($dataPrint['anchopapel']) : 80;
+    
+    // ENCABEZADO
+    $printer->setJustification(Printer::JUSTIFY_CENTER);
+    $printer->setTextSize(2, 2);
+    $printer->text($dataPrint['empresa']['nombre_empresa'] . "\n");
+    $printer->setTextSize(1, 1);
+    $printer->text($dataPrint['empresa']['direccion_empresa'] . "\n");
+    $printer->text("Tel: " . $dataPrint['empresa']['telefono_empresa'] . "\n");
+    $printer->text(str_repeat("=", 45) . "\n");
+    $printer->setEmphasis(true);
+    $printer->text("PRECUENTA\n");
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    // INFORMACIÓN DE LA ORDEN
+    $printer->setJustification(Printer::JUSTIFY_LEFT);
+    $printer->setEmphasis(true);
+    $printer->text("Orden #: ");
+    $printer->setEmphasis(false);
+    $printer->text($dataPrint['num_orden'] . "\n");
+    
+    $printer->setEmphasis(true);
+    $printer->text("Fecha: ");
+    $printer->setEmphasis(false);
+    $printer->text(date('d/m/Y H:i', strtotime($dataPrint['fecha'])) . "\n");
+    
+    if (!empty($dataPrint['salon'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Salon: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['salon'] . "\n");
+    }
+    
+    if (!empty($dataPrint['mesa'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Mesa: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['mesa'] . "\n");
+    }
+    
+    /*
+    if (!empty($dataPrint['mesero'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Mesero: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['mesero'] . "\n");
+    }*/
+    
+    if (!empty($dataPrint['cliente'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Cliente: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['cliente'] . "\n");
+    }
+    
+    if (!empty($dataPrint['servicio'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Servicio: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['servicio'] . "\n");
+    }
+    
+    $printer->text(str_repeat("-", 45) . "\n");
+    
+    // ENCABEZADO DE TABLA
+    $printer->setEmphasis(true);
+    $printer->text("CANT  DESCRIPCION               TOTAL\n");
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("-", 45) . "\n");
+    
+    // PLATOS
+    $subtotal = 0;
+    foreach ($dataPrint['platos'] as $plato) {
+        // Convertir objeto a array si es necesario
+        $platoArray = is_object($plato) ? (array)$plato : $plato;
+        
+        $cant = number_format($platoArray['cant'], 0);
+        $nombre = $platoArray['nombre'];
+        $precio = $platoArray['precio'];
+        $total = $platoArray['cant'] * $platoArray['precio'];
+        $subtotal += $total;
+        
+        // Línea del plato - cant y nombre
+        $cantPad = str_pad($cant, 4);
+        $nombreCorto = substr($nombre, 0, 25);
+        $totalStr = "$" . number_format($total, 2);
+        
+        $printer->text($cantPad . "x " . str_pad($nombreCorto, 27) . str_pad($totalStr, 10, " ", STR_PAD_LEFT) . "\n");
+        
+        // Acompañamientos
+        if (isset($platoArray['acompanamientos']) && is_array($platoArray['acompanamientos']) && count($platoArray['acompanamientos']) > 0) {
+            foreach ($platoArray['acompanamientos'] as $acomp) {
+                $acompArray = is_object($acomp) ? (array)$acomp : $acomp;
+                $printer->text("     + " . $acompArray['acompanamiento'] . "\n");
+            }
+        }
+        
+        /*
+        if (!empty($platoArray['notas'])) {
+            $printer->text("     Nota: " . $platoArray['notas'] . "\n");
+        }*/
+    }
+    
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    // TOTALES
+    $printer->setJustification(Printer::JUSTIFY_RIGHT);
+    $printer->text("Subtotal:  $" . number_format($dataPrint['subtotal'], 2) . "\n");
+    
+    if (isset($dataPrint['descuento']) && $dataPrint['descuento'] > 0) {
+        $printer->text("Descuento: -$" . number_format($dataPrint['descuento'], 2) . "\n");
+    }
+    
+    if (isset($dataPrint['propina']) && $dataPrint['propina'] > 0) {
+        $printer->text("Propina:   $" . number_format($dataPrint['propina'], 2) . "\n");
+    }
+    
+    $total = $dataPrint['subtotal'] - (isset($dataPrint['descuento']) ? $dataPrint['descuento'] : 0) + (isset($dataPrint['propina']) ? $dataPrint['propina'] : 0);
+    
+    $printer->text(str_repeat("-", 45) . "\n");
+    $printer->setEmphasis(true);
+    $printer->setTextSize(2, 1);
+    $printer->text("TOTAL: $" . number_format($total, 2) . "\n");
+    $printer->setTextSize(1, 1);
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    $printer->setJustification(Printer::JUSTIFY_CENTER);
+    $printer->text("\n¡Gracias por su preferencia!\n");
+    $printer->text("Esta NO es una factura\n");
+    
+    $printer->feed(3);
+    $printer->cut();
+    $printer->close();
+    
+    echo json_encode([
+        'success' => true,
+        'status' => 'success',
+        'message' => 'Precuenta impresa correctamente en ' . $nombreImpresora
+    ]);
+    
+} catch (Exception $e) {
+    echo json_encode([
+        'success' => false,
+        'status' => 'error',
+        'message' => 'Error al imprimir: ' . $e->getMessage()
+    ]);
+}

+ 195 - 132
recibo.php

@@ -1,4 +1,11 @@
 <?php
+/**
+ * Archivo para imprimir recibos de venta
+ * Este archivo debe copiarse al servidor de impresión (printserver)
+ * Imprime en la impresora de caja (normalmente POS-80C)
+ * Usa librería: mike42/escpos-php
+ */
+
 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
     header("Access-Control-Allow-Origin: *");
     header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
@@ -10,6 +17,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
 header("Access-Control-Allow-Headers: Content-Type, Authorization");
+header('Content-Type: application/json; charset=utf-8');
 
 error_reporting(E_ALL);
 ini_set('display_errors', 0);
@@ -20,152 +28,207 @@ require __DIR__ . '/vendor/autoload.php';
 use Mike42\Escpos\Printer;
 use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
 
-// Helper functions
-function printLinea($printer, $char = "-", $width = 48) {
-    $printer->text(str_repeat($char, $width) . "\n");
-}
-
-function cutString($text, $maxLength) {
-    return substr($text, 0, $maxLength);
-}
+// Recibir datos
+$dataPrint = null;
+$isc = '';
 
-function printAlignedText($printer, $leftText, $rightText, $width = 48) {
-    $rightLen = strlen($rightText);
-    $leftLen = $width - $rightLen;
-    $leftPadded = str_pad($leftText, $leftLen, " ", STR_PAD_RIGHT);
-    $printer->text($leftPadded . $rightText . "\n");
+if(isset($_POST["dataPrint"])){
+    // jQuery envía el objeto como está, necesitamos convertirlo a array
+    $dataPrint = is_array($_POST["dataPrint"]) ? $_POST["dataPrint"] : json_decode(json_encode($_POST["dataPrint"]), true);
 }
 
-// Get data from POST
-$dataPrint = null;
-if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["dataPrint"])) {
-    $dataPrint = json_decode($_POST["dataPrint"]);
+if(!$dataPrint){
+    echo json_encode([
+        'success' => false,
+        'status' => 'error', 
+        'message' => 'No se recibieron datos para imprimir'
+    ]);
+    exit;
 }
 
-if ($dataPrint) {
-    $PRINTER_NAME = $dataPrint->printer ?? 'POS-80C';
-    
-    try {
-        $connector = new WindowsPrintConnector($PRINTER_NAME);
-        $printer = new Printer($connector);
-        
-        // COMPANY HEADER
-        $printer->setJustification(Printer::JUSTIFY_CENTER);
-        $printer->setTextSize(2, 2);
-        $printer->text(cutString(strtoupper($dataPrint->nombre_empresa), 24) . "\n");
-        
-        $printer->setTextSize(1, 1);
-        //$printer->text(cutString(strtoupper($dataPrint->giro_empresa ?? ''), 48) . "\n");
-        //$printer->text(cutString(strtoupper($dataPrint->direcion_empresa), 48) . "\n");
-        //$printer->text(cutString(strtoupper($dataPrint->rsocial_empresa), 48) . "\n");
-        //$printer->text("NRC: " . $dataPrint->nrc_empresa . " - NIT: " . $dataPrint->nit_empresa . "\n");
-        
-        printLinea($printer);
-        
-        // DOCUMENT INFO
-        $printer->setJustification(Printer::JUSTIFY_LEFT);
-        printAlignedText($printer, "Fecha: " . $dataPrint->fecha, "Caja: " . $dataPrint->caja);
-        printAlignedText($printer, "Vendedor: " . $dataPrint->vendedor, "Cajero: " . $dataPrint->cajero);
-        
-        $printer->setJustification(Printer::JUSTIFY_CENTER);
+try {
+    // Nombre de la impresora de caja
+    $nombreImpresora = isset($dataPrint['printer']) ? $dataPrint['printer'] : "POS-80C";
+    
+    $connector = new WindowsPrintConnector($nombreImpresora);
+    $printer = new Printer($connector);
+    
+    // ENCABEZADO
+    $printer->setJustification(Printer::JUSTIFY_CENTER);
+    $printer->setTextSize(2, 2);
+    $printer->text($dataPrint['nombre_empresa'] . "\n");
+    $printer->setTextSize(1, 1);
+    
+    if (!empty($dataPrint['direcion_empresa'])) {
+        $printer->text($dataPrint['direcion_empresa'] . "\n");
+    }
+    
+    if (!empty($dataPrint['nit_empresa'])) {
+        $printer->text("NIT: " . $dataPrint['nit_empresa'] . "\n");
+    }
+    
+    if (!empty($dataPrint['nrc_empresa'])) {
+        $printer->text("NRC: " . $dataPrint['nrc_empresa'] . "\n");
+    }
+    
+    $printer->text(str_repeat("=", 45) . "\n");
+    $printer->setEmphasis(true);
+    $printer->text("R E C I B O\n");
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    // INFORMACIÓN DEL RECIBO
+    $printer->setJustification(Printer::JUSTIFY_LEFT);
+    
+    if (!empty($dataPrint['doc_numero'])) {
         $printer->setEmphasis(true);
-        $printer->text("RECIBO\n");
-        $printer->text("No. " . $dataPrint->doc_numero . "\n");
+        $printer->text("Recibo #: ");
         $printer->setEmphasis(false);
-        
-        printLinea($printer);
-        
-        // CUSTOMER INFO
-        if (isset($dataPrint->cliente) && $dataPrint->cliente != "") {
-            $printer->setJustification(Printer::JUSTIFY_LEFT);
-            $printer->text("Cliente: " . $dataPrint->cliente . "\n");
-            if (isset($dataPrint->direccion_cliente) && $dataPrint->direccion_cliente != "") {
-                $printer->text("Direccion: " . $dataPrint->direccion_cliente . "\n");
-            }
-            printLinea($printer);
-        }
-        
-        // PRODUCTS TABLE
-        $printer->setJustification(Printer::JUSTIFY_LEFT);
+        $printer->text($dataPrint['doc_numero'] . "\n");
+    }
+    
+    if (!empty($dataPrint['fecha'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Fecha: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['fecha'] . "\n");
+    }
+    
+    if (!empty($dataPrint['referencia'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Referencia: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['referencia'] . "\n");
+    }
+    
+    if (!empty($dataPrint['cliente'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Cliente: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['cliente'] . "\n");
+    }
+    
+    if (!empty($dataPrint['vendedor'])) {
+        $printer->setEmphasis(true);
+        $printer->text("Vendedor: ");
+        $printer->setEmphasis(false);
+        $printer->text($dataPrint['vendedor'] . "\n");
+    }
+    
+    if (!empty($dataPrint['caja'])) {
         $printer->setEmphasis(true);
-        $printer->text("CANT  DESCRIPCION               PRECIO  TOTAL\n");
-        printLinea($printer);
+        $printer->text("Caja: ");
         $printer->setEmphasis(false);
-        
-        foreach ($dataPrint->productos_normal as $producto) {
-            $cantidad = str_pad(number_format($producto->cant, 2), 5, " ", STR_PAD_RIGHT);
-            $precio = str_pad(number_format($producto->costo, 2), 7, " ", STR_PAD_LEFT);
-            $total = str_pad(number_format($producto->costo * $producto->cant, 2), 7, " ", STR_PAD_LEFT);
+        $printer->text($dataPrint['caja'] . "\n");
+    }
+    
+    $printer->text(str_repeat("-", 45) . "\n");
+    
+    // ENCABEZADO DE TABLA
+    $printer->setEmphasis(true);
+    $printer->text("CANT  DESCRIPCION               TOTAL\n");
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("-", 45) . "\n");
+    
+    // PRODUCTOS
+    $subtotal = 0;
+    if (isset($dataPrint['productos_normal']) && is_array($dataPrint['productos_normal'])) {
+        foreach ($dataPrint['productos_normal'] as $producto) {
+            // Convertir objeto a array si es necesario
+            $productoArray = is_object($producto) ? (array)$producto : $producto;
             
-            $descripcion = wordwrap(strtoupper($producto->desc), 23, "\n", true);
-            $lineasDescripcion = explode("\n", $descripcion);
+            $cant = isset($productoArray['cant']) ? number_format($productoArray['cant'], 0) : '0';
+            $desc = isset($productoArray['desc']) ? $productoArray['desc'] : '';
+            $costo = isset($productoArray['costo']) ? floatval($productoArray['costo']) : 0;
+            $cantNum = isset($productoArray['cant']) ? floatval($productoArray['cant']) : 0;
+            $total = $cantNum * $costo;
+            $subtotal += $total;
             
-            $printer->text("$cantidad " . str_pad($lineasDescripcion[0], 23, " ") . " $precio $total\n");
+            // Línea del producto - cant y descripción
+            $cantPad = str_pad($cant, 4);
+            $descCorto = substr($desc, 0, 25);
+            $totalStr = "$" . number_format($total, 2);
             
-            for ($i = 1; $i < count($lineasDescripcion); $i++) {
-                $printer->text("      " . $lineasDescripcion[$i] . "\n");
-            }
-        }
-        
-        printLinea($printer);
-        
-        // TOTALS
-        $printer->setJustification(Printer::JUSTIFY_RIGHT);
-        $printer->setEmphasis(true);
-        $printer->setTextSize(1, 2);
-        $printer->text("TOTAL $" . number_format($dataPrint->totales->totalTotal, 2) . "\n");
-        $printer->setTextSize(1, 1);
-        $printer->setEmphasis(false);
-        
-        $printer->text("EFECTIVO $" . number_format($dataPrint->efectivo, 2) . "\n");
-        
-        if (isset($dataPrint->pos) && floatval($dataPrint->pos) > 0) {
-            $printer->text("POS $" . number_format($dataPrint->pos, 2) . "\n");
-        }
-        
-        $printer->setJustification(Printer::JUSTIFY_LEFT);
-        printAlignedText($printer, "REF.: " . $dataPrint->referencia, "CAMBIO $" . number_format($dataPrint->cambio, 2));
-        
-        printLinea($printer);
-        
-        // NOTES
-        if (isset($dataPrint->notas) && $dataPrint->notas != "") {
-            $printer->setJustification(Printer::JUSTIFY_LEFT);
-            $printer->text("Notas: " . $dataPrint->notas . "\n");
-            printLinea($printer);
+            $printer->text($cantPad . "x " . str_pad($descCorto, 27) . str_pad($totalStr, 10, " ", STR_PAD_LEFT) . "\n");
         }
-        
-        // FINAL MESSAGE
-        $printer->setJustification(Printer::JUSTIFY_CENTER);
-        $printer->text("\n");
-        
-        if (isset($dataPrint->mensaje_ticket) && $dataPrint->mensaje_ticket != "") {
-            $mensajeLines = wordwrap($dataPrint->mensaje_ticket, 48, "\n", true);
-            foreach (explode("\n", $mensajeLines) as $linea) {
-                $printer->text($linea . "\n");
-            }
-        }
-        
-        // FINISH
-        $printer->feed(2);
-        $printer->cut();
-        $printer->close();
-        
-        echo json_encode([
-            "status" => "success",
-            "message" => "Recibo impreso correctamente."
-        ]);
-        
-    } catch (Exception $e) {
-        echo json_encode([
-            "status" => "error",
-            "message" => "Error al imprimir: " . $e->getMessage()
-        ]);
-    }
-} else {
+    }
+    
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    // TOTALES
+    $printer->setJustification(Printer::JUSTIFY_RIGHT);
+    
+    $totales = isset($dataPrint['totales']) && is_array($dataPrint['totales']) ? $dataPrint['totales'] : [];
+    
+    $totalGrabadas = isset($totales['totalGrabadas']) ? floatval(str_replace(',', '', $totales['totalGrabadas'])) : $subtotal;
+    $descuento = isset($totales['descuento']) ? floatval(str_replace(',', '', $totales['descuento'])) : 0;
+    $propina = isset($totales['propina']) ? floatval(str_replace(',', '', $totales['propina'])) : 0;
+    $totalTotal = isset($totales['totalTotal']) ? floatval(str_replace(',', '', $totales['totalTotal'])) : 0;
+    
+    $printer->text("Subtotal:  $" . number_format($totalGrabadas, 2) . "\n");
+    
+    if ($descuento > 0) {
+        $printer->text("Descuento: -$" . number_format($descuento, 2) . "\n");
+    }
+    
+    if ($propina > 0) {
+        $printer->text("Propina:   $" . number_format($propina, 2) . "\n");
+    }
+    
+
+    
+    // FORMA DE PAGO
+    $printer->setJustification(Printer::JUSTIFY_RIGHT);
+    
+    $efectivo = isset($dataPrint['efectivo']) ? floatval($dataPrint['efectivo']) : 0;
+    $pos = isset($dataPrint['pos']) ? floatval($dataPrint['pos']) : 0;
+    $cambio = isset($dataPrint['cambio']) ? floatval($dataPrint['cambio']) : 0;
+    
+    if ($efectivo > 0) {
+        $printer->text("Efectivo:  $" . number_format($efectivo, 2) . "\n");
+    }
+    
+    if ($pos > 0) {
+        $printer->text("POS/Tarjeta: $" . number_format($pos, 2) . "\n");
+    }
+    
+    if ($cambio > 0) {
+        $printer->text("Cambio:    $" . number_format($cambio, 2) . "\n");
+    }
+    
+    $printer->text(str_repeat("-", 45) . "\n");
+    $printer->setEmphasis(true);
+    $printer->setTextSize(2, 1);
+    $printer->text("TOTAL: $" . number_format($totalTotal, 2) . "\n");
+    $printer->setTextSize(1, 1);
+    $printer->setEmphasis(false);
+    $printer->text(str_repeat("=", 45) . "\n");
+    
+    // MENSAJE FINAL
+    $printer->setJustification(Printer::JUSTIFY_CENTER);
+    
+    if (!empty($dataPrint['mensaje_ticket'])) {
+        $printer->text($dataPrint['mensaje_ticket'] . "\n");
+    }
+    
+    $printer->text("\n¡Gracias por su compra!\n");
+    $printer->text("Este es un recibo, NO factura\n");
+    
+    $printer->feed(3);
+    $printer->cut();
+    $printer->close();
+    
+    echo json_encode([
+        'success' => true,
+        'status' => 'success',
+        'message' => 'Recibo impreso correctamente en ' . $nombreImpresora
+    ]);
+    
+} catch (Exception $e) {
     echo json_encode([
-        "status" => "error",
-        "message" => "No se recibieron datos para imprimir."
+        'success' => false,
+        'status' => 'error',
+        'message' => 'Error al imprimir: ' . $e->getMessage()
     ]);
 }
 ?>