Files
App/presupuestos.html
2026-03-25 08:38:42 +00:00

490 lines
27 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Presupuestos - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
/* VARIABLES CORPORATIVAS DINÁMICAS (Igual que en el menú) */
:root {
--primary: #2563eb;
--secondary: #f59e0b;
--app-bg: #f4f7f9;
}
body { background-color: var(--app-bg); -webkit-tap-highlight-color: transparent; }
.fade-in { animation: fadeIn 0.3s ease-out forwards; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.main-content { padding-bottom: calc(env(safe-area-inset-bottom) + 80px); }
/* Clases CSS dinámicas */
.bg-primary-dynamic { background-color: var(--primary) !important; }
.text-primary-dynamic { color: var(--primary) !important; }
.border-primary-dynamic { border-color: var(--primary) !important; }
.ring-primary-dynamic:focus { outline: none; box-shadow: 0 0 0 2px var(--primary) !important; }
</style>
</head>
<body class="text-slate-800 font-sans antialiased h-screen flex flex-col overflow-hidden relative">
<div class="absolute top-0 left-0 w-full h-40 bg-primary-dynamic rounded-b-[2.5rem] z-0 transition-colors duration-500"></div>
<header class="px-6 pt-safe mt-8 pb-6 z-10 relative text-white shrink-0">
<div class="flex items-center justify-between mb-2">
<button onclick="window.location.href='menu.html'" class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center active:scale-95 transition-transform backdrop-blur-md">
<i data-lucide="arrow-left" class="w-5 h-5"></i>
</button>
<h1 class="text-xl font-black tracking-tight leading-none text-center">Mis Presupuestos</h1>
<div class="w-10"></div> </div>
</header>
<main id="viewList" class="flex-1 overflow-y-auto px-5 pt-4 main-content z-10 relative fade-in">
<div class="flex justify-end mb-4">
<button onclick="showCreateView()" class="bg-white text-slate-700 px-4 py-3 rounded-2xl shadow-sm border border-slate-100 text-xs font-black flex items-center gap-2 active:scale-95 transition-transform uppercase tracking-widest">
<i data-lucide="plus" class="w-4 h-4 text-primary-dynamic"></i> Nuevo Presupuesto
</button>
</div>
<div id="budgetsList" class="space-y-4 pb-10">
<div class="text-center text-slate-400 py-10 text-sm font-medium">
<i data-lucide="loader-2" class="w-8 h-8 animate-spin mx-auto mb-2 text-primary-dynamic"></i> Cargando...
</div>
</div>
</main>
<main id="viewCreate" class="hidden flex-1 overflow-y-auto px-5 pt-6 main-content z-20 fade-in bg-[var(--app-bg)] absolute inset-0 mt-[6rem] rounded-t-[2.5rem] shadow-[0_-10px_40px_rgba(0,0,0,0.1)]">
<div class="flex justify-between items-center mb-6">
<h2 class="text-lg font-black text-slate-800">Generar Nuevo</h2>
<button onclick="hideCreateView()" class="w-8 h-8 bg-slate-200 text-slate-600 rounded-full flex items-center justify-center active:scale-95"><i data-lucide="x" class="w-4 h-4"></i></button>
</div>
<form id="budgetForm" class="space-y-5">
<div class="bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm space-y-4">
<h3 class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-1 flex items-center gap-1"><i data-lucide="user" class="w-3 h-3"></i> Cliente</h3>
<input type="text" id="c_name" required placeholder="Nombre del Cliente" class="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-sm font-bold text-slate-700 ring-primary-dynamic transition-all">
<input type="tel" id="c_phone" required placeholder="Teléfono" class="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-sm font-bold text-slate-700 ring-primary-dynamic transition-all">
<input type="text" id="c_address" placeholder="Dirección (Opcional)" class="w-full px-4 py-3 bg-slate-50 border border-slate-100 rounded-xl text-sm font-bold text-slate-700 ring-primary-dynamic transition-all">
</div>
<div class="bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm space-y-4">
<h3 class="text-[10px] font-black text-primary-dynamic uppercase tracking-widest mb-1 flex items-center gap-1"><i data-lucide="shopping-cart" class="w-3 h-3"></i> Conceptos</h3>
<div id="itemsContainer" class="space-y-3 empty:hidden mb-3"></div>
<div class="grid grid-cols-12 gap-2 bg-slate-50 p-3 rounded-xl border border-slate-100">
<div class="col-span-12">
<input type="text" id="item_concept" list="articlesList" placeholder="Añadir artículo o mano de obra..." class="w-full px-3 py-2 bg-white rounded-lg text-sm font-medium border border-slate-200 ring-primary-dynamic">
<datalist id="articlesList"></datalist>
</div>
<div class="col-span-4">
<input type="number" id="item_qty" placeholder="Cant." value="1" min="1" step="0.01" class="w-full px-3 py-2 bg-white rounded-lg text-sm font-bold text-center border border-slate-200 ring-primary-dynamic">
</div>
<div class="col-span-5">
<input type="number" id="item_price" placeholder="Precio €" min="0" step="0.01" class="w-full px-3 py-2 bg-white rounded-lg text-sm font-bold text-right border border-slate-200 ring-primary-dynamic">
</div>
<div class="col-span-3 flex items-center justify-end">
<button type="button" onclick="addItem()" class="w-full h-full bg-primary-dynamic text-white rounded-lg flex items-center justify-center active:scale-95 shadow-md"><i data-lucide="plus" class="w-5 h-5"></i></button>
</div>
</div>
</div>
<div class="bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm relative overflow-hidden">
<div class="absolute top-0 left-0 w-1 h-full bg-primary-dynamic"></div>
<div class="flex justify-between text-sm font-medium text-slate-500 mb-1 pl-2">
<span>Subtotal:</span> <span id="lbl_subtotal">0.00 €</span>
</div>
<div class="flex justify-between text-sm font-medium text-slate-500 mb-3 pb-3 border-b border-slate-100 pl-2">
<span>IVA (21%):</span> <span id="lbl_tax">0.00 €</span>
</div>
<div class="flex justify-between text-xl font-black text-slate-800 pl-2">
<span>TOTAL:</span> <span id="lbl_total" class="text-primary-dynamic">0.00 €</span>
</div>
</div>
<button type="button" onclick="saveBudget()" id="btnSave" class="w-full bg-primary-dynamic text-white font-black py-4 rounded-2xl shadow-lg hover:opacity-90 active:scale-95 transition-all uppercase tracking-widest text-xs flex justify-center items-center gap-2 mt-2 mb-10">
<i data-lucide="save" class="w-4 h-4"></i> Generar Presupuesto
</button>
</form>
</main>
<div id="toast" class="fixed bottom-5 left-1/2 -translate-x-1/2 bg-slate-800 text-white px-6 py-3 rounded-full text-xs font-bold tracking-wide shadow-2xl opacity-0 pointer-events-none transition-opacity z-50 flex items-center gap-2">
<i data-lucide="info" class="w-4 h-4"></i> <span id="toastMsg">Mensaje</span>
</div>
<script>
const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
? 'http://localhost:3000'
: 'https://integrarepara-api.integrarepara.es';
let catalog = [];
let currentItems = [];
let allBudgets = [];
// ------------------ INICIALIZACIÓN Y TEMA CORPORATIVO ------------------
async function applyTheme() {
try {
let theme = JSON.parse(localStorage.getItem('app_theme'));
const res = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok && data.config && data.config.portal_settings && data.config.portal_settings.app_settings) {
theme = data.config.portal_settings.app_settings;
localStorage.setItem('app_theme', JSON.stringify(theme));
}
if(theme) {
document.documentElement.style.setProperty('--primary', theme.primary);
document.documentElement.style.setProperty('--secondary', theme.secondary);
document.documentElement.style.setProperty('--app-bg', theme.bg);
}
} catch (e) { console.warn("Usando tema por defecto"); }
}
document.addEventListener("DOMContentLoaded", async () => {
if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; }
await applyTheme();
lucide.createIcons();
await fetchArticles();
await fetchBudgets();
document.getElementById('item_concept').addEventListener('change', (e) => {
const art = catalog.find(a => a.name === e.target.value);
if(art) document.getElementById('item_price').value = art.price;
});
});
// ------------------ NAVEGACIÓN Y TOASTS ------------------
function showCreateView() {
document.getElementById('viewList').classList.add('hidden');
document.getElementById('viewCreate').classList.remove('hidden');
currentItems = [];
document.getElementById('budgetForm').reset();
renderItems();
}
function hideCreateView() {
document.getElementById('viewCreate').classList.add('hidden');
document.getElementById('viewList').classList.remove('hidden');
}
function showToast(msg) {
const toast = document.getElementById('toast');
document.getElementById('toastMsg').innerText = msg;
toast.classList.remove('opacity-0');
setTimeout(() => toast.classList.add('opacity-0'), 3000);
}
// ------------------ API CALLS ------------------
async function fetchArticles() {
try {
const res = await fetch(`${API_URL}/articles`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
catalog = data.articles;
const dl = document.getElementById('articlesList');
dl.innerHTML = '';
catalog.forEach(a => {
const opt = document.createElement('option');
opt.value = a.name;
dl.appendChild(opt);
});
}
} catch(e) {}
}
async function fetchBudgets() {
try {
const res = await fetch(`${API_URL}/budgets`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
allBudgets = data.budgets;
renderBudgetsList(allBudgets);
}
} catch(e) {
document.getElementById('budgetsList').innerHTML = `<div class="text-center text-rose-500 py-6 text-sm font-bold">Error de conexión</div>`;
}
}
// ------------------ ACCIONES DE LOS PRESUPUESTOS ------------------
async function updateStatus(id, newStatus) {
try {
const res = await fetch(`${API_URL}/budgets/${id}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ status: newStatus })
});
const data = await res.json();
if (data.ok) {
showToast(newStatus === 'accepted' ? "¡Presupuesto Aceptado!" : "Presupuesto Rechazado");
fetchBudgets();
} else { showToast("Error al actualizar"); }
} catch (e) { showToast("Error de conexión"); }
}
async function deleteBudget(id) {
if (!confirm("¿Seguro que quieres borrar este presupuesto?")) return;
try {
const res = await fetch(`${API_URL}/budgets/${id}`, {
method: 'DELETE',
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok) {
showToast("Presupuesto borrado correctamente");
fetchBudgets();
} else {
showToast(data.error || "No se puede borrar este presupuesto");
}
} catch (e) { showToast("Error de conexión"); }
}
// FUNCIÓN PARA GENERAR Y DESCARGAR PDF BÁSICO
function downloadPDF(id) {
const b = allBudgets.find(x => x.id === id);
if(!b) return;
// Creamos un HTML limpio imprimible
let itemsHtml = (b.items || []).map(i => `
<tr>
<td style="padding: 8px; border-bottom: 1px solid #ddd;">${i.concept}</td>
<td style="padding: 8px; border-bottom: 1px solid #ddd; text-align: center;">${i.qty}</td>
<td style="padding: 8px; border-bottom: 1px solid #ddd; text-align: right;">${parseFloat(i.price).toFixed(2)}€</td>
<td style="padding: 8px; border-bottom: 1px solid #ddd; text-align: right;">${parseFloat(i.total).toFixed(2)}€</td>
</tr>
`).join('');
const companyName = localStorage.getItem('userName') || 'Empresa Instaladora';
const dateStr = new Date(b.created_at).toLocaleDateString('es-ES');
const printContent = `
<html>
<head>
<title>Presupuesto PRE-${b.id}</title>
<style>
body { font-family: Arial, sans-serif; padding: 40px; color: #333; }
.header { display: flex; justify-content: space-between; margin-bottom: 40px; border-bottom: 2px solid #2563eb; padding-bottom: 20px; }
h1 { color: #2563eb; margin: 0; }
table { w-full; border-collapse: collapse; margin-top: 30px; width: 100%; }
th { background-color: #f8fafc; padding: 10px; text-align: left; border-bottom: 2px solid #ddd; }
.totals { margin-top: 30px; width: 50%; float: right; border-top: 2px solid #333; padding-top: 10px; }
.totals div { display: flex; justify-content: space-between; margin-bottom: 5px; }
.totals .final { font-size: 1.2em; font-weight: bold; color: #2563eb; }
</style>
</head>
<body>
<div class="header">
<div>
<h1>PRESUPUESTO PRE-${b.id}</h1>
<p>Fecha: ${dateStr}</p>
<p>Emitido por: <strong>${companyName}</strong></p>
</div>
<div style="text-align: right;">
<h3>Datos del Cliente</h3>
<p><strong>${b.client_name}</strong></p>
<p>Tel: ${b.client_phone}</p>
<p>${b.client_address || ''}</p>
</div>
</div>
<table>
<thead>
<tr>
<th>Concepto</th>
<th style="text-align:center;">Cant.</th>
<th style="text-align:right;">Precio/U</th>
<th style="text-align:right;">Total</th>
</tr>
</thead>
<tbody>${itemsHtml}</tbody>
</table>
<div class="totals">
<div><span>Subtotal:</span> <span>${parseFloat(b.subtotal).toFixed(2)}€</span></div>
<div><span>IVA (21%):</span> <span>${parseFloat(b.tax).toFixed(2)}€</span></div>
<div class="final"><span>TOTAL:</span> <span>${parseFloat(b.total).toFixed(2)}€</span></div>
</div>
<script>
window.onload = function() { window.print(); }
<\/script>
</body>
</html>
`;
// Abre una ventana nueva oculta y lanza el diálogo de imprimir nativo del móvil (que permite guardar como PDF)
const printWindow = window.open('', '_blank');
printWindow.document.write(printContent);
printWindow.document.close();
}
// ------------------ RENDERIZAR LA LISTA EN PANTALLA ------------------
function renderBudgetsList(budgets) {
const container = document.getElementById('budgetsList');
if(budgets.length === 0) {
container.innerHTML = `
<div class="text-center bg-white border border-slate-100 p-8 rounded-[2rem] shadow-sm">
<div class="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-3"><i data-lucide="file-x-2" class="w-8 h-8 text-slate-300"></i></div>
<h3 class="text-sm font-black text-slate-700 mb-1">No hay presupuestos</h3>
<p class="text-xs text-slate-400 font-medium">Aún no has generado ninguno.</p>
</div>`;
lucide.createIcons();
return;
}
container.innerHTML = budgets.map(b => {
let statusColor = "bg-amber-50 text-amber-600";
let statusText = "Pendiente";
let icon = "clock";
if(b.status === 'accepted' || b.status === 'converted') { statusColor = "bg-emerald-50 text-emerald-600"; statusText = "Aceptado"; icon = "check-circle"; }
else if(b.status === 'rejected') { statusColor = "bg-rose-50 text-rose-600"; statusText = "Rechazado"; icon = "x-circle"; }
const d = new Date(b.created_at).toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: '2-digit' });
return `
<div class="bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm flex flex-col gap-4 relative overflow-hidden">
<div class="absolute top-0 left-0 w-1 h-full bg-slate-200"></div>
<div class="flex justify-between items-start pl-2">
<div class="w-[60%]">
<span class="text-[10px] font-black text-slate-400 uppercase tracking-widest block mb-1">PRE-${b.id}${d}</span>
<h3 class="text-sm font-bold text-slate-800 truncate">${b.client_name || 'Sin Nombre'}</h3>
<p class="text-xs text-slate-500 font-medium mt-0.5"><i data-lucide="phone" class="w-3 h-3 inline pb-0.5"></i> ${b.client_phone}</p>
</div>
<div class="text-right">
<p class="text-xl font-black text-slate-800">${parseFloat(b.total).toFixed(2)}€</p>
<span class="${statusColor} text-[9px] font-black px-2.5 py-1 rounded-md uppercase tracking-wider flex items-center justify-end gap-1 w-max ml-auto mt-1">
<i data-lucide="${icon}" class="w-3 h-3"></i> ${statusText}
</span>
</div>
</div>
<div class="pt-3 border-t border-slate-100 flex justify-between items-center pl-2">
<div class="flex gap-2">
${ b.status === 'pending' ? `
<button onclick="updateStatus(${b.id}, 'accepted')" title="Aceptar" class="w-9 h-9 bg-emerald-50 text-emerald-600 rounded-full flex items-center justify-center active:scale-95 transition-transform"><i data-lucide="check" class="w-5 h-5"></i></button>
<button onclick="updateStatus(${b.id}, 'rejected')" title="Rechazar" class="w-9 h-9 bg-rose-50 text-rose-600 rounded-full flex items-center justify-center active:scale-95 transition-transform"><i data-lucide="x" class="w-5 h-5"></i></button>
` : `<span class="text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center">Ya gestionado</span>` }
</div>
<div class="flex gap-2">
<button onclick="downloadPDF(${b.id})" title="Descargar PDF" class="w-9 h-9 bg-slate-50 border border-slate-100 text-slate-600 rounded-full flex items-center justify-center active:scale-95 transition-transform"><i data-lucide="download" class="w-4 h-4"></i></button>
<button onclick="deleteBudget(${b.id})" title="Borrar" class="w-9 h-9 bg-slate-50 border border-slate-100 text-rose-500 rounded-full flex items-center justify-center active:scale-95 transition-transform hover:bg-rose-50"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
</div>
</div>
</div>
`;
}).join('');
lucide.createIcons();
}
// ------------------ CREACIÓN DE PRESUPUESTO (ITEMS) ------------------
function addItem() {
const conceptInput = document.getElementById('item_concept');
const qtyInput = document.getElementById('item_qty');
const priceInput = document.getElementById('item_price');
const concept = conceptInput.value.trim();
const qty = parseFloat(qtyInput.value);
const price = parseFloat(priceInput.value);
if(!concept || isNaN(qty) || isNaN(price)) {
showToast("Rellena concepto y precio.");
return;
}
currentItems.push({ concept, qty, price, total: qty * price });
conceptInput.value = '';
qtyInput.value = '1';
priceInput.value = '';
conceptInput.focus();
renderItems();
}
function removeItem(index) {
currentItems.splice(index, 1);
renderItems();
}
function renderItems() {
const cont = document.getElementById('itemsContainer');
cont.innerHTML = currentItems.map((item, idx) => `
<div class="flex justify-between items-center bg-slate-50 p-3 rounded-xl border border-slate-100 text-sm">
<div class="w-[60%]">
<p class="font-bold text-slate-700 truncate">${item.concept}</p>
<p class="text-[10px] text-slate-400 font-medium uppercase">${item.qty} ud x ${item.price.toFixed(2)}€</p>
</div>
<div class="flex items-center gap-3">
<span class="font-black text-slate-800">${item.total.toFixed(2)}€</span>
<button type="button" onclick="removeItem(${idx})" class="w-7 h-7 bg-white shadow-sm border border-slate-100 text-rose-500 rounded-full flex items-center justify-center active:scale-90"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
</div>
</div>
`).join('');
lucide.createIcons();
calcTotals();
}
function calcTotals() {
let sub = 0;
currentItems.forEach(i => sub += i.total);
let tax = sub * 0.21; // IVA 21%
let tot = sub + tax;
document.getElementById('lbl_subtotal').innerText = `${sub.toFixed(2)}`;
document.getElementById('lbl_tax').innerText = `${tax.toFixed(2)}`;
document.getElementById('lbl_total').innerText = `${tot.toFixed(2)}`;
return { sub, tax, tot };
}
async function saveBudget() {
if(currentItems.length === 0) { showToast("Añade al menos 1 artículo."); return; }
const cName = document.getElementById('c_name').value.trim();
const cPhone = document.getElementById('c_phone').value.trim();
const cAddress = document.getElementById('c_address').value.trim();
if(!cName || !cPhone) { showToast("Nombre y teléfono obligatorios."); return; }
const btn = document.getElementById('btnSave');
btn.disabled = true;
btn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> Generando...';
lucide.createIcons();
const totals = calcTotals();
const payload = {
client_name: cName,
client_phone: cPhone,
client_address: cAddress,
items: currentItems,
subtotal: totals.sub,
tax: totals.tax,
total: totals.tot
};
try {
const res = await fetch(`${API_URL}/budgets`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(payload)
});
const data = await res.json();
if(data.ok) {
showToast("¡Presupuesto Creado!");
hideCreateView();
fetchBudgets();
} else {
showToast("Error al guardar.");
}
} catch(e) {
showToast("Fallo de conexión.");
} finally {
btn.disabled = false;
btn.innerHTML = '<i data-lucide="save" class="w-4 h-4"></i> Generar Presupuesto';
lucide.createIcons();
}
}
</script>
</body>
</html>