From 2638d17684b90421f12b464f92428038ab22f47f Mon Sep 17 00:00:00 2001 From: nickpons666 Date: Sat, 10 Jan 2026 01:08:52 -0600 Subject: [PATCH] =?UTF-8?q?Cuentas=20por=20Pagar:=20correcciones=20vista?= =?UTF-8?q?=20Global=20y=20respuesta=20AJAX\n-=20Evitar=20subtabla=20de=20?= =?UTF-8?q?Notas=20en=20vista=20Global=20y=20simplificar=20fila=20(colspan?= =?UTF-8?q?=3D11)\n-=20Prevenir=20cierres=20hu=C3=A9rfanos=20en=20paginaci?= =?UTF-8?q?=C3=B3n=20(pages=5Fnew.tpl)=20con=20bandera=20skipClosures\n-?= =?UTF-8?q?=20Cambiar=20AJAX=20a=20devolver=20HTML=20plano=20(no=20JSON)?= =?UTF-8?q?=20para=20alinearse=20con=20cuentas-pagar.js\n-=20Ajustes=20s?= =?UTF-8?q?=C3=B3lo=20de=20marcado/flujo;=20sin=20cambios=20de=20l=C3=B3gi?= =?UTF-8?q?ca=20de=20negocio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ajax/cuentas-pagar.php | 255 +++++++++++++++++++++++++ templates/items/cuentas-pagar-base.tpl | 67 +++---- templates/lists/pages_new.tpl | 4 +- 3 files changed, 287 insertions(+), 39 deletions(-) diff --git a/ajax/cuentas-pagar.php b/ajax/cuentas-pagar.php index e69de29..3c47deb 100755 --- a/ajax/cuentas-pagar.php +++ b/ajax/cuentas-pagar.php @@ -0,0 +1,255 @@ +AuthUser(); + error_log('Usuario autenticado correctamente'); + + // Inicializar objetos necesarios + $cuentaPagar = new CuentaPagar(); + $proveedor = new Proveedor(); + $cuentaBancaria = new CuentaBancaria(); + $metodoPago = new MetodoPago(); + + $action = $_POST['action'] ?? ''; + $proveedorId = $_POST['proveedorId2'] ?? 0; + $global = isset($_POST['global']) ? 1 : 0; + + error_log('Parámetros recibidos - action: ' . $action . ', proveedorId: ' . $proveedorId . ', global: ' . $global); + + switch($action) { + case 'search': + case 'search2': + error_log('Iniciando búsqueda - tipo: ' . $action); + + $cuentaPagar->setPage(1); + error_log('Página establecida a 1'); + + if($proveedorId) { + error_log('Estableciendo proveedor ID: ' . $proveedorId); + $cuentaPagar->setProveedorId($proveedorId); + } + + try { + if($global) { + error_log('Buscando proveedores globales'); + $resCuenta = $cuentaPagar->EnumerateProveedores(); + } else { + error_log('Buscando cuentas por pagar'); + $resCuenta = $cuentaPagar->Enumerate(); + } + + error_log('Resultado de la búsqueda: ' . print_r($resCuenta, true)); + + if(!is_array($resCuenta)) { + throw new Exception('El resultado no es un array'); + } + + if(!isset($resCuenta['items'])) { + throw new Exception('No se encontró el índice "items" en el resultado'); + } + + $items = []; + foreach($resCuenta['items'] as $res) { + if(!is_array($res) || empty($res)) { + continue; + } + + if(isset($res['folioProv']) && preg_match('/FOLIO/i', $res['folioProv'])) { + continue; + } + + $proveedor->setProveedorId($res['proveedorId']); + $res['proveedor'] = $proveedor->GetNameById(); + + // Verificar si es una vista global de proveedores + if (isset($resCuenta['esVistaGlobal']) && $resCuenta['esVistaGlobal']) { + // Ya está todo calculado en la consulta SQL + $res['abonos'] = $res['totalPagos'] ?? 0; + $res['saldo'] = $res['total'] - $res['abonos']; + $res['totalDescuentos'] = 0; // No aplica en vista global + $resPagos = []; // No mostramos pagos individuales en vista global + } else { + // Manejo normal para vista detallada de pedidos + if (!isset($res['pedidoId'])) { + error_log('Error: pedidoId no está definido en el resultado'); + $res['pedidoId'] = 0; // Valor por defecto + } + + // Obtener abonos realizados + $cuentaPagar->setPedidoId($res['pedidoId']); + $res['abonos'] = $cuentaPagar->GetTotalPagos(); + + // Calcular total de descuentos + $totalDesc = ($res['totalPub'] ?? 0) + ($res['totalDes'] ?? 0) + ($res['totalFlete'] ?? 0) + ($res['totalEsp'] ?? 0); + $res['totalDescuentos'] = number_format($totalDesc, 2, '.', ''); + + // Calcular saldo + $res['saldo'] = ($res['total'] ?? 0) - ($res['abonos'] ?? 0) - ($res['bonificaciones'] ?? 0) - ($res['devoluciones'] ?? 0) - $res['totalDescuentos']; + + // Obtener pagos solo si hay un pedidoId válido + $resPagos = []; + if ($res['pedidoId'] > 0) { + $cuentaPagar->setPedidoId($res['pedidoId']); + $resPagos = $cuentaPagar->EnumPagos(); + } + } + + $pagos = []; + foreach($resPagos as $val) { + $cuentaBancaria->setCuentaBancariaId($val['cuentaBancariaId']); + $val['cuentaBancaria'] = $cuentaBancaria->GetNameById(); + + $metodoPago->setMetodoPagoId($val['metodoPagoId']); + $val['metodoPago'] = $metodoPago->GetNameById(); + + $val['fecha'] = date('d-m-Y', strtotime($val['fecha'])); + + $pagos[] = $val; + } + $res['pagos'] = $pagos; + + $items[] = $res; + } + + $resCuenta['items'] = $items; + + // Preparar los datos para la plantilla + $cuentasPagar = [ + 'items' => $resCuenta['items'], + 'pages' => $resCuenta['pagination']['totalPages'] ?? 1, + 'pagination' => $resCuenta['pagination'] ?? [ + 'total' => count($resCuenta['items']), + 'totalPages' => 1, + 'currentPage' => 1, + 'itemsPerPage' => count($resCuenta['items']) + ] + ]; + + // Asignar las variables a la plantilla + $smarty->assign('cuentasPagar', $cuentasPagar); + $smarty->assign('tipo', 'search'); + + // Registrar en el log para depuración + error_log("Datos recibidos en AJAX: " . print_r($resCuenta, true)); + + // Asignar a Smarty + $smarty->assign("cuentasPagar", $resCuenta); + $smarty->assign("tipo", "search"); + $smarty->assign("esVistaGlobal", $resCuenta['esVistaGlobal'] ?? false); + + // Preparar los totales + $totales = [ + 'total' => 0, + 'totalAbonos' => 0, + 'totalNotas' => 0, + 'totalDesc' => 0, + 'totalBonif' => 0, + 'totalDev' => 0, + 'totalSaldo' => 0 + ]; + + // Si es vista global, usar los totales del resultado + if ($resCuenta['esVistaGlobal'] && isset($resCuenta['info'])) { + $totales = [ + 'total' => $resCuenta['info']['total'] ?? 0, + 'totalAbonos' => $resCuenta['info']['totalAbonos'] ?? 0, + 'totalNotas' => $resCuenta['info']['totalNotas'] ?? 0, + 'totalDesc' => $resCuenta['info']['totalDesc'] ?? 0, + 'totalBonif' => $resCuenta['info']['totalBonif'] ?? 0, + 'totalDev' => $resCuenta['info']['totalDev'] ?? 0, + 'totalSaldo' => $resCuenta['info']['totalSaldo'] ?? 0 + ]; + } + // Si no es vista global, calcular los totales manualmente + elseif (isset($resCuenta['items']) && is_array($resCuenta['items'])) { + foreach ($resCuenta['items'] as $item) { + $totales['total'] += (float)($item['total'] ?? 0); + $totales['totalAbonos'] += (float)($item['abonos'] ?? 0); + $totales['totalNotas'] += (float)($item['totalNotas'] ?? 0); + $totales['totalDesc'] += (float)($item['totalDescuentos'] ?? 0); + $totales['totalBonif'] += (float)($item['bonificaciones'] ?? 0); + $totales['totalDev'] += (float)($item['devoluciones'] ?? 0); + $totales['totalSaldo'] += (float)($item['saldo'] ?? 0); + } + } + + // Asignar los totales a Smarty + $smarty->assign("info", $totales); + + $smarty->assign('DOC_ROOT', DOC_ROOT); + $smarty->assign('WEB_ROOT', WEB_ROOT); + // Evitar que pages_new.tpl emita cierres de wrappers en contenido AJAX + $smarty->assign('skipClosures', true); + + // Registrar las variables para depuración + error_log('Items a mostrar: ' . count($resCuenta['items'])); + error_log('Páginas totales: ' . ($resCuenta['pagination']['totalPages'] ?? 1)); + + // Generar el HTML de la tabla + $page = 'lists/cuentas-pagar.tpl'; + $html = $smarty->fetch($page); + + // Verificar si el HTML se generó correctamente + if (empty(trim($html))) { + throw new Exception('La plantilla no generó ningún contenido'); + } + + // Devolver HTML plano (el JS de la pantalla espera HTML, no JSON) + header('Content-Type: text/html; charset=UTF-8'); + echo $html; + exit; + + } catch (Exception $e) { + $errorMsg = 'Error en cuentas-pagar.php: ' . $e->getMessage() . ' en ' . $e->getFile() . ':' . $e->getLine(); + error_log($errorMsg); + error_log('Trace: ' . $e->getTraceAsString()); + + // Devolver el error como JSON para mejor manejo en el frontend + header('Content-Type: application/json'); + echo json_encode([ + 'success' => false, + 'error' => $errorMsg, + 'trace' => $e->getTraceAsString() + ]); + exit; + } + break; + + default: + echo "Acción no válida"; + break; + } +} catch (Exception $e) { + $errorMsg = 'Error general en cuentas-pagar.php: ' . $e->getMessage() . ' en ' . $e->getFile() . ':' . $e->getLine(); + error_log($errorMsg); + error_log('Trace: ' . $e->getTraceAsString()); + + // Devolver el error como JSON para mejor manejo en el frontend + header('Content-Type: application/json'); + echo json_encode([ + 'success' => false, + 'error' => $errorMsg, + 'trace' => $e->getTraceAsString() + ]); + exit; +} + +?> \ No newline at end of file diff --git a/templates/items/cuentas-pagar-base.tpl b/templates/items/cuentas-pagar-base.tpl index ced59a2..856bf68 100755 --- a/templates/items/cuentas-pagar-base.tpl +++ b/templates/items/cuentas-pagar-base.tpl @@ -1,48 +1,39 @@ - -
{$item.noPedido}
-
{$item.proveedor}
-
${$item.total|number_format:2:'.':','}
-
${$item.abonos|number_format:2:'.':','}
-
${$item.totalNotas|number_format:2:'.':','}
-
${$item.totalDescuentos|number_format:2:'.':','}
-
${$item.bonificaciones|number_format:2:'.':','}
-
${$item.devoluciones|number_format:2:'.':','}
-
${$item.saldo|number_format:2:'.':','}
+ +
{$item.noPedido}
+
{$item.proveedor}
+
${$item.total|number_format:2:'.':','}
+
${$item.abonos|number_format:2:'.':','}
+
${$item.totalNotas|number_format:2:'.':','}
+
${$item.totalDescuentos|number_format:2:'.':','}
+
${$item.bonificaciones|number_format:2:'.':','}
+
${$item.devoluciones|number_format:2:'.':','}
+
${$item.saldo|number_format:2:'.':','}
-
- - - -
-
- - - -
- - -
- {if $item.pagado}Pagado{else}Pendiente{/if} + -
- - - -
+
+ {if $item.pagado} + Pagado + {else} + Pendiente + {/if} +
- -   -   -   -   -   -   - +{if !$esVistaGlobal} + +
{include file="{$DOC_ROOT}/templates/lists/cuentas-notas.tpl"}
- \ No newline at end of file + +{/if} diff --git a/templates/lists/pages_new.tpl b/templates/lists/pages_new.tpl index c0f0392..e79540f 100755 --- a/templates/lists/pages_new.tpl +++ b/templates/lists/pages_new.tpl @@ -19,10 +19,12 @@ +{if \!$skipClosures}
- \ No newline at end of file +{/if} +