Files
Complejo_Cap1tan/js/Resumen_Ventas.js
T
MarcosFlorSalcedo 8ec55e40fc 1ra Versión
2026-07-14 18:24:27 -03:00

208 lines
6.7 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
const fechaInput = document.getElementById('fecha-resumen');
const totalVerInput = document.getElementById('total-ver');
const tablaVentas = document.getElementById('tabla-ver-ventas');
const tablaDetalle = document.getElementById('tabla-detalle-venta');
const detalleContenedor = document.getElementById('detalle-venta-contenedor');
const tablaPrincipal = document.getElementById('tabla-principal-contenedor');
// --- Estado de la aplicación ---
let state = {
vistaActual: 'principal', // 'principal' o 'detalle'
ventaSeleccionada: null,
ventasDelDia: []
};
// --- Funciones de utilidad ---
function formatMoney(v) {
return '$' + Number(v).toFixed(2);
}
function formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleString('es-AR');
}
// --- Función para cambiar vistas ---
function mostrarVistaPrincipal() {
state.vistaActual = 'principal';
state.ventaSeleccionada = null;
if (tablaPrincipal) tablaPrincipal.style.display = 'block';
if (detalleContenedor) detalleContenedor.style.display = 'none';
}
function mostrarVistaDetalle(idVenta) {
state.vistaActual = 'detalle';
state.ventaSeleccionada = idVenta;
if (tablaPrincipal) tablaPrincipal.style.display = 'none';
if (detalleContenedor) detalleContenedor.style.display = 'block';
}
// --- Carga de Ventas ---
function cargarVentasActuales() {
const fechaSeleccionada = fechaInput.value;
if (fechaSeleccionada) {
console.log("Actualizando vista de ventas para:", fechaSeleccionada);
fetchVentas({ start: fechaSeleccionada, end: fechaSeleccionada });
}
}
function fetchVentas(params) {
const query = new URLSearchParams(params).toString();
fetch(`../php/Obtener_Ventas.php?${query}`)
.then(res => res.json())
.then(data => {
state.ventasDelDia = data || [];
renderTablaVentas(data);
calcularTotalDia(data);
console.log('Ventas cargadas:', data);
})
.catch(err => {
console.error('Error al cargar ventas:', err);
if (tablaVentas) {
tablaVentas.querySelector('tbody').innerHTML =
'<tr><td colspan="4" style="text-align: center; color: red;">Error al cargar ventas</td></tr>';
}
});
}
function renderTablaVentas(ventas) {
if (!tablaVentas) return;
const tbody = tablaVentas.querySelector('tbody');
tbody.innerHTML = '';
if (!ventas || ventas.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">No hay ventas en el período seleccionado</td></tr>';
return;
}
ventas.forEach(venta => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${venta.ID_Venta || '-'}</td>
<td>${venta.fecha_hora ? formatDate(venta.fecha_hora) : '-'}</td>
<td>${formatMoney(venta.monto_total)}</td>
<td>
<button class="btn-ver-detalle" onclick="window.verDetalleVenta(${venta.ID_Venta})" title="Ver detalle">Ver Productos</button>
</td>
`;
tbody.appendChild(row);
});
}
function calcularTotalDia(ventas) {
let total = 0;
if (ventas && Array.isArray(ventas) && ventas.length > 0) {
total = ventas.reduce((sum, v) => sum + Number(v.monto_total || 0), 0);
}
if (totalVerInput) totalVerInput.value = formatMoney(total);
}
// --- Funcionalidad de Detalle ---
function cargarDetalleVenta(idVenta) {
console.log('Cargando detalle para venta:', idVenta);
fetch(`../php/Obtener_Ventas.php?id_venta=${idVenta}`)
.then(res => {
console.log('Respuesta status:', res.status);
if (!res.ok) {
throw new Error(`HTTP Error: ${res.status}`);
}
return res.json();
})
.then(data => {
console.log('Detalle cargado:', data);
// Verificar si hay error en la respuesta
if (data.error) {
console.error('Error del servidor:', data.error);
alert('Error: ' + data.error);
return;
}
// Si la respuesta es un array vacío, mostrar mensaje
if (Array.isArray(data) && data.length === 0) {
console.warn('No hay productos para esta venta');
}
renderDetalleVenta(data);
mostrarVistaDetalle(idVenta);
})
.catch(err => {
console.error('Error completo:', err);
alert('❌ Error al cargar el detalle de la venta: ' + err.message);
});
}
function renderDetalleVenta(data) {
if (!tablaDetalle) return;
// Asumimos que data contiene los productos de la venta
const productos = Array.isArray(data) ? data : (data.productos || []);
let totalVenta = 0;
const tbody = tablaDetalle.querySelector('tbody');
tbody.innerHTML = '';
if (productos.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">No hay productos en esta venta</td></tr>';
return;
}
productos.forEach(prod => {
const cantidad = Number(prod.cantidad || 0);
const precio = Number(prod.precio_unitario || prod.precio || 0);
const subtotal = cantidad * precio;
totalVenta += subtotal;
const row = document.createElement('tr');
row.innerHTML = `
<td>${prod.nombre || prod.descripcion || '-'}</td>
<td style="text-align: center;">${cantidad}</td>
<td style="text-align: right;">${formatMoney(precio)}</td>
<td style="text-align: right;">${formatMoney(subtotal)}</td>
`;
tbody.appendChild(row);
});
// Agregar fila de total
const rowTotal = document.createElement('tr');
rowTotal.style.fontWeight = 'bold';
rowTotal.style.borderTop = '2px solid #333';
rowTotal.innerHTML = `
<td colspan="3" style="text-align: right;">TOTAL GENERAL:</td>
<td style="text-align: right;">${formatMoney(totalVenta)}</td>
`;
tbody.appendChild(rowTotal);
}
// --- Exponemos función global para el onclick ---
window.verDetalleVenta = function(idVenta) {
cargarDetalleVenta(idVenta);
};
// --- Botón Volver ---
const btnVolver = document.getElementById('btn-volver-ventas');
if (btnVolver) {
btnVolver.addEventListener('click', mostrarVistaPrincipal);
}
// --- Inicialización ---
const hoyStr = new Date().toISOString().slice(0, 10);
if (fechaInput) {
fechaInput.value = hoyStr;
cargarVentasActuales();
fechaInput.addEventListener('change', () => {
mostrarVistaPrincipal();
cargarVentasActuales();
});
}
window.addEventListener("hashchange", () => {
if (window.location.hash === "#ver_ventas") {
mostrarVistaPrincipal();
cargarVentasActuales();
}
});
});