255 lines
11 KiB
PHP
Executable File
255 lines
11 KiB
PHP
Executable File
<?php
|
|
|
|
// Habilitar todos los errores para depuración
|
|
error_reporting(E_ALL);
|
|
ini_set('display_errors', 1);
|
|
ini_set('log_errors', 1);
|
|
ini_set('error_log', '/var/www/html/ventas/logs/php_errors.log');
|
|
|
|
try {
|
|
include_once('../init.php');
|
|
include_once('../config.php');
|
|
include_once(DOC_ROOT.'/libraries.php');
|
|
|
|
// Registrar que se ha iniciado el script
|
|
error_log('Iniciando ajax/cuentas-pagar.php');
|
|
|
|
// Verificar si la empresa está autenticada
|
|
if (!isset($empresa) || !method_exists($empresa, 'AuthUser')) {
|
|
throw new Exception('Error de autenticación: Objeto empresa no válido');
|
|
}
|
|
|
|
$empresa->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;
|
|
}
|
|
|
|
?>
|