Files
web/contabilidad.html
2026-03-01 13:17:19 +00:00

346 lines
21 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contabilidad - IntegraReparaPro</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
.fade-in { animation: fadeIn 0.3s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased overflow-hidden">
<div class="flex h-screen overflow-hidden text-left">
<div id="sidebar-container" class="h-full shrink-0"></div>
<div class="flex-1 flex flex-col overflow-hidden relative">
<div id="header-container"></div>
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-slate-50/50 p-6 relative">
<div class="max-w-6xl mx-auto fade-in">
<div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-4 mb-6">
<div>
<h2 class="text-2xl font-black text-slate-800 flex items-center gap-3">
<span class="bg-emerald-500 p-2.5 rounded-xl text-white shadow-lg shadow-emerald-200"><i data-lucide="wallet"></i></span>
Finanzas y Cobros
</h2>
<p class="text-sm text-slate-500 mt-1 font-medium">Gestiona la facturación mensual y el estado de los pagos.</p>
</div>
<button class="bg-white border-2 border-indigo-100 text-indigo-400 px-5 py-2.5 rounded-xl font-black flex items-center gap-2 text-xs uppercase tracking-widest cursor-not-allowed opacity-70" title="Próximamente">
<i data-lucide="bot" class="w-4 h-4"></i> Robot Contable PDF <span class="bg-indigo-100 text-indigo-600 px-1.5 py-0.5 rounded text-[8px] ml-1">BETA</span>
</button>
</div>
<div class="flex gap-2 border-b border-slate-200 mb-6">
<button class="px-6 py-3 font-black text-sm text-emerald-600 border-b-2 border-emerald-500 flex items-center gap-2">
<i data-lucide="coins" class="w-4 h-4"></i> Cobros a Clientes/Cías
</button>
<button class="px-6 py-3 font-bold text-sm text-slate-400 hover:text-slate-600 transition-colors flex items-center gap-2 cursor-not-allowed">
<i data-lucide="file-spreadsheet" class="w-4 h-4"></i> Presupuestos <span class="text-[9px] bg-slate-100 px-2 py-0.5 rounded uppercase tracking-widest ml-1">Pendiente</span>
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<div class="bg-white p-5 rounded-[1.5rem] border border-slate-200 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-full bg-blue-50 text-blue-500 flex items-center justify-center shrink-0"><i data-lucide="sigma"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Total Facturado</p>
<p class="text-2xl font-black text-slate-800" id="kpi-total">0.00 €</p>
</div>
</div>
<div class="bg-white p-5 rounded-[1.5rem] border border-slate-200 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-full bg-emerald-50 text-emerald-500 flex items-center justify-center shrink-0"><i data-lucide="check-circle-2"></i></div>
<div>
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Total Cobrado</p>
<p class="text-2xl font-black text-emerald-600" id="kpi-paid">0.00 €</p>
</div>
</div>
<div class="bg-white p-5 rounded-[1.5rem] border border-red-100 shadow-sm flex items-center gap-4 relative overflow-hidden">
<div class="absolute right-0 top-0 bottom-0 w-2 bg-red-400"></div>
<div class="w-12 h-12 rounded-full bg-red-50 text-red-500 flex items-center justify-center shrink-0"><i data-lucide="clock"></i></div>
<div>
<p class="text-[10px] font-black text-red-400 uppercase tracking-widest">Pendiente de Cobro</p>
<p class="text-2xl font-black text-red-600" id="kpi-pending">0.00 €</p>
</div>
</div>
</div>
<div class="bg-white p-4 rounded-2xl border border-slate-200 shadow-sm mb-6 flex flex-wrap gap-3 items-center">
<div class="flex-1 min-w-[200px] relative">
<i data-lucide="search" class="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-slate-400"></i>
<input type="text" id="searchBox" oninput="renderList()" placeholder="Buscar por cliente, referencia..." class="w-full pl-11 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-emerald-500 outline-none transition-all">
</div>
<div class="flex flex-wrap gap-2">
<div class="flex items-center bg-slate-50 border border-slate-200 rounded-xl overflow-hidden">
<div class="px-3 text-slate-400 border-r border-slate-200"><i data-lucide="calendar-days" class="w-4 h-4"></i></div>
<input type="month" id="filterMonth" onchange="renderList()" class="bg-transparent text-xs font-black px-3 py-2.5 outline-none text-slate-600 uppercase tracking-widest cursor-pointer">
</div>
<select id="filterCompany" onchange="renderList()" class="bg-slate-50 border border-slate-200 text-[10px] font-black px-4 py-2.5 rounded-xl outline-none focus:ring-2 focus:ring-emerald-500 uppercase tracking-widest max-w-[200px]">
<option value="ALL">TODAS LAS COMPAÑÍAS</option>
</select>
<select id="filterStatus" onchange="renderList()" class="bg-slate-50 border border-slate-200 text-[10px] font-black px-4 py-2.5 rounded-xl outline-none focus:ring-2 focus:ring-emerald-500 uppercase tracking-widest">
<option value="ALL">ESTADO DE COBRO</option>
<option value="paid">PAGADOS</option>
<option value="pending">PENDIENTES</option>
</select>
</div>
</div>
<div class="bg-white border border-slate-200 rounded-[2rem] shadow-sm overflow-hidden mb-10">
<div class="grid grid-cols-12 gap-4 p-4 bg-slate-50 border-b border-slate-100 text-[10px] font-black uppercase tracking-widest text-slate-400">
<div class="col-span-4 pl-2">Servicio / Cliente / Fecha</div>
<div class="col-span-2">Compañía</div>
<div class="col-span-2 text-center">Importe (€)</div>
<div class="col-span-2">Método de Pago</div>
<div class="col-span-2 text-center">Estado</div>
</div>
<div id="financialList" class="divide-y divide-slate-100">
<div class="p-10 text-center text-slate-400 flex flex-col items-center">
<i data-lucide="loader-2" class="w-8 h-8 animate-spin mb-3"></i>
<span class="font-bold text-sm tracking-widest uppercase">Cargando contabilidad...</span>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
<div id="toast" class="fixed bottom-8 right-8 bg-slate-900 text-white px-6 py-3 rounded-2xl shadow-2xl hidden z-[200] font-bold text-sm flex items-center gap-2 transition-all"></div>
<script src="js/layout.js"></script>
<script>
let allFinancials = [];
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
// Establecer el mes actual por defecto en el filtro
const now = new Date();
const currentMonthStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
document.getElementById('filterMonth').value = currentMonthStr;
setTimeout(loadFinancials, 200);
});
async function loadFinancials() {
try {
const res = await fetch(`${API_URL}/financials`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
// Filtrar los bloqueos de agenda por si acaso vienen cruzados
allFinancials = data.financials.filter(f => f.service_ref && !f.service_ref.includes('BLOCK-'));
// Extraer compañías únicas para el filtro
const compSelect = document.getElementById('filterCompany');
const currentVal = compSelect.value;
const uniqueCompanies = [...new Set(allFinancials.map(f => {
const raw = f.raw_data || {};
return (raw['Compañía'] || raw['COMPAÑIA'] || "Particular").toString().toUpperCase().trim();
}))].sort();
compSelect.innerHTML = '<option value="ALL">TODAS LAS COMPAÑÍAS</option>';
uniqueCompanies.forEach(c => compSelect.innerHTML += `<option value="${c}">${c}</option>`);
compSelect.value = currentVal; // Mantener selección si se recarga
renderList();
}
} catch (error) {
console.error("Error cargando contabilidad:", error);
}
}
function renderList() {
const container = document.getElementById('financialList');
const searchTerm = document.getElementById('searchBox').value.toLowerCase();
const filterCompany = document.getElementById('filterCompany').value;
const filterStatus = document.getElementById('filterStatus').value;
const filterMonth = document.getElementById('filterMonth').value; // Formato "YYYY-MM"
// Filtrado del array
const filtered = allFinancials.filter(f => {
const raw = f.raw_data || {};
const name = (raw['Nombre Cliente'] || raw['CLIENTE'] || "").toLowerCase();
const ref = (f.service_ref || "").toLowerCase();
const company = (raw['Compañía'] || raw['COMPAÑIA'] || "Particular").toUpperCase().trim();
// Extraer el mes del servicio para el filtro
let serviceMonth = "";
if (raw.scheduled_date) {
// formato asumido YYYY-MM-DD
serviceMonth = raw.scheduled_date.substring(0, 7);
} else if (f.created_at) {
serviceMonth = f.created_at.substring(0, 7);
}
// Condiciones
const matchSearch = name.includes(searchTerm) || ref.includes(searchTerm);
const matchCompany = filterCompany === 'ALL' || company === filterCompany;
const matchStatus = filterStatus === 'ALL' || (filterStatus === 'paid' ? f.is_paid : !f.is_paid);
const matchMonth = !filterMonth || serviceMonth === filterMonth; // Si no hay mes seleccionado, muestra todo
return matchSearch && matchCompany && matchStatus && matchMonth;
});
// Variables para KPIs
let totalFacturado = 0;
let totalCobrado = 0;
container.innerHTML = '';
if (filtered.length === 0) {
container.innerHTML = `
<div class="p-16 text-center flex flex-col items-center">
<div class="w-16 h-16 bg-slate-100 text-slate-300 rounded-full flex items-center justify-center mb-4">
<i data-lucide="inbox" class="w-8 h-8"></i>
</div>
<p class="font-bold text-slate-500 mb-1">No se encontraron cobros</p>
<p class="text-xs text-slate-400">Prueba a cambiar los filtros o el mes de búsqueda.</p>
</div>`;
updateKPIs(0, 0);
lucide.createIcons();
return;
}
filtered.forEach(f => {
const raw = f.raw_data || {};
const name = raw['Nombre Cliente'] || raw['CLIENTE'] || "Sin Nombre";
const company = raw['Compañía'] || raw['COMPAÑIA'] || "Particular";
// Formatear Fecha
let fechaVis = "Sin fecha";
if(raw.scheduled_date) {
const [y, m, d] = raw.scheduled_date.split('-');
fechaVis = `${d}/${m}/${y}`;
}
// Cálculos matemáticos
const amt = parseFloat(f.amount || 0);
totalFacturado += amt;
if (f.is_paid) totalCobrado += amt;
// Selector de estado visual
const statusBadge = f.is_paid
? `<span class="bg-emerald-100 text-emerald-700 px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest flex items-center justify-center gap-1 border border-emerald-200"><i data-lucide="check-circle-2" class="w-3 h-3"></i> Pagado</span>`
: `<span class="bg-red-50 text-red-600 px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest flex items-center justify-center gap-1 border border-red-200"><i data-lucide="clock" class="w-3 h-3"></i> Pendiente</span>`;
container.innerHTML += `
<div class="grid grid-cols-12 gap-4 p-4 items-center hover:bg-slate-50 transition-colors group">
<div class="col-span-4 pl-2 min-w-0">
<p class="text-xs font-black text-slate-800 uppercase truncate" title="${name}">${name}</p>
<div class="flex items-center gap-2 mt-1 text-[10px] font-bold text-slate-400">
<span class="bg-slate-100 px-1.5 py-0.5 rounded border border-slate-200">#${f.service_ref}</span>
<span><i data-lucide="calendar" class="w-3 h-3 inline mr-0.5"></i> ${fechaVis}</span>
</div>
</div>
<div class="col-span-2 min-w-0">
<span class="bg-blue-50 text-blue-700 border border-blue-100 px-2 py-1 rounded text-[9px] font-black uppercase tracking-widest truncate max-w-full inline-block">
${company}
</span>
</div>
<div class="col-span-2 relative">
<span class="absolute right-4 top-1/2 -translate-y-1/2 text-sm font-black text-slate-400 pointer-events-none">€</span>
<input type="number" step="0.01" id="amt-${f.scraped_id}" value="${f.amount}"
class="w-full bg-white border border-slate-200 pl-3 pr-8 py-2.5 rounded-xl text-sm font-black text-right outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100 transition-all ${f.is_paid ? 'text-emerald-700 bg-emerald-50/30' : 'text-slate-700'}">
</div>
<div class="col-span-2">
<select id="method-${f.scraped_id}" class="w-full bg-white border border-slate-200 px-2 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest text-slate-600 outline-none focus:border-emerald-500 cursor-pointer">
<option value="Pendiente" ${f.payment_method === 'Pendiente' ? 'selected' : ''}>⏳ Pendiente</option>
<option value="Cobro Banco" ${f.payment_method === 'Cobro Banco' ? 'selected' : ''}>🏦 Banco</option>
<option value="Efectivo" ${f.payment_method === 'Efectivo' ? 'selected' : ''}>💵 Efectivo</option>
<option value="Tarjeta" ${f.payment_method === 'Tarjeta' ? 'selected' : ''}>💳 Tarjeta</option>
<option value="Transferencia" ${f.payment_method === 'Transferencia' ? 'selected' : ''}>🔄 Transfer.</option>
</select>
</div>
<div class="col-span-2 flex items-center justify-between gap-2">
<div id="badge-container-${f.scraped_id}" class="flex-1">${statusBadge}</div>
<button onclick="savePayment(${f.scraped_id})" class="bg-slate-100 text-slate-500 border border-slate-200 hover:bg-emerald-500 hover:border-emerald-600 hover:text-white p-2 rounded-xl transition-all shrink-0 active:scale-95 shadow-sm" title="Guardar Cambios">
<i data-lucide="save" class="w-4 h-4"></i>
</button>
</div>
</div>
`;
});
updateKPIs(totalFacturado, totalCobrado);
lucide.createIcons();
}
function updateKPIs(facturado, cobrado) {
const pendiente = facturado - cobrado;
document.getElementById('kpi-total').innerText = facturado.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
document.getElementById('kpi-paid').innerText = cobrado.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
document.getElementById('kpi-pending').innerText = pendiente.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
}
async function savePayment(scrapedId) {
const amountInput = document.getElementById(`amt-${scrapedId}`);
const methodInput = document.getElementById(`method-${scrapedId}`);
const amount = amountInput.value;
const method = methodInput.value;
// Bloquear inputs mientras guarda
amountInput.disabled = true;
methodInput.disabled = true;
try {
const res = await fetch(`${API_URL}/financials/${scrapedId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ amount, payment_method: method })
});
const data = await res.json();
if (data.ok) {
showToast("Cobro actualizado");
// Actualizar el array local para que los KPIs se recalculen sin recargar de BD
const fIndex = allFinancials.findIndex(f => f.scraped_id === scrapedId);
if (fIndex > -1) {
allFinancials[fIndex].amount = parseFloat(amount || 0);
allFinancials[fIndex].payment_method = method;
allFinancials[fIndex].is_paid = data.is_paid;
}
// Refrescar lista visualmente
renderList();
} else {
showToast("Error al guardar.");
}
} catch (error) {
showToast("Error de conexión.");
} finally {
amountInput.disabled = false;
methodInput.disabled = false;
}
}
function showToast(msg) {
const t = document.getElementById('toast');
t.innerHTML = `<i data-lucide="check-circle" class="w-5 h-5 text-emerald-400"></i> ${msg}`;
lucide.createIcons();
t.classList.remove('hidden');
setTimeout(() => t.classList.add('hidden'), 3000);
}
</script>
</body>
</html>