File size: 9,168 Bytes
fc556c4 ceebd34 aa4fc68 5f08c00 ceebd34 fc556c4 ceebd34 fc556c4 ceebd34 aa4fc68 5f08c00 aa4fc68 5f08c00 ceebd34 5f08c00 ceebd34 fc556c4 ceebd34 fc556c4 ceebd34 fc556c4 5f08c00 ceebd34 5f08c00 ceebd34 5f08c00 ceebd34 5f08c00 ceebd34 5f08c00 ceebd34 fc556c4 ceebd34 fc556c4 ceebd34 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | window.addEventListener('DOMContentLoaded', () => {
const CLP = new Intl.NumberFormat('es-CL', { style: 'currency', currency: 'CLP', maximumFractionDigits: 0 });
// --- Selección de Elementos del DOM ---
const invoiceInput = document.getElementById('invoice-input');
const budgetInput = document.getElementById('budget-input');
const dropzone = document.getElementById('dropzone');
const budgetDropzone = document.getElementById('budget-dropzone');
const tbody = document.getElementById('tbody');
const totalSpan = document.getElementById('total');
const errorEl = document.getElementById('error');
const budgetErrorEl = document.getElementById('budget-error');
const processBtn = document.getElementById('process-btn');
const resetBtn = document.getElementById('reset-btn');
const recordsTbody = document.getElementById('records-tbody');
const summaryBudgetEl = document.getElementById('summary-budget');
const summarySpentEl = document.getElementById('summary-spent');
const summaryVariationEl = document.getElementById('summary-variation');
const budgetProgressBar = document.getElementById('budget-progress-bar');
// Este es el elemento que causaba el problema, ahora debería existir en tu HTML
const summaryBudgetFilenameEl = document.getElementById('summary-budget-filename');
// --- Almacenamiento de Datos en Memoria ---
const docs = [];
const records = [];
let budgetFile = null;
// --- Funciones de Simulación y Ayuda ---
const formatDate = isoString => new Date(isoString).toLocaleDateString('es-CL');
const randomAmount = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const randomFolio = () => 'F' + Math.floor(100000 + Math.random() * 900000);
const parseCSVForAmount = content => {
const lines = content.split('\n');
for (const line of lines) {
const matches = line.match(/(\d{1,3}(?:\.\d{3})*|\d+)/g);
if (matches && matches.length > 0) {
const amount = parseInt(matches[0].replace(/\./g, ''));
if (!isNaN(amount) && amount > 1000) return amount;
}
}
return null;
};
// --- Funciones para Actualizar la Interfaz (Render) ---
const renderDocs = () => {
totalSpan.textContent = `${docs.length} en total`;
tbody.innerHTML = '';
if (docs.length === 0) {
tbody.innerHTML = `<tr><td colspan="5" class="empty">Aún no hay documentos.</td></tr>`;
} else {
docs.forEach((doc, index) => {
const tr = document.createElement('tr');
let documentCell = doc.name;
if (doc.file && doc.file.type.startsWith('image/')) {
const imageURL = URL.createObjectURL(doc.file);
documentCell = `<img src="${imageURL}" alt="${doc.name}" class="thumbnail" />`;
}
tr.innerHTML = `
<td>${index + 1}</td>
<td>${doc.folio}</td>
<td>${documentCell}</td>
<td>${formatDate(doc.loadedAt)}</td>
<td>${CLP.format(doc.amount)}</td>`;
tbody.appendChild(tr);
});
}
};
const updateSummary = () => {
const totalDocsAmount = docs.reduce((sum, doc) => sum + (doc.amount || 0), 0);
const budgetAmount = budgetFile ? budgetFile.amount : 0;
const variation = budgetAmount - totalDocsAmount;
summaryBudgetEl.textContent = CLP.format(budgetAmount);
summarySpentEl.textContent = CLP.format(totalDocsAmount);
summaryVariationEl.textContent = CLP.format(variation);
summaryVariationEl.style.color = variation < 0 ? 'var(--red)' : 'var(--green)';
// Esta sección ahora funcionará porque el elemento existe
if (budgetFile && summaryBudgetFilenameEl) {
summaryBudgetFilenameEl.textContent = budgetFile.name;
} else if (summaryBudgetFilenameEl) {
summaryBudgetFilenameEl.textContent = '';
}
if (budgetAmount > 0) {
const usagePercent = Math.max(0, (totalDocsAmount / budgetAmount) * 100);
budgetProgressBar.style.width = `${Math.min(usagePercent, 100)}%`;
if (usagePercent > 100) {
budgetProgressBar.style.backgroundColor = 'var(--red)';
} else if (usagePercent > 80) {
budgetProgressBar.style.backgroundColor = 'var(--yellow)';
} else {
budgetProgressBar.style.backgroundColor = 'var(--green)';
}
} else {
budgetProgressBar.style.width = '0%';
}
};
const renderRecords = () => {
recordsTbody.innerHTML = '';
if (records.length === 0) {
recordsTbody.innerHTML = `<tr><td class="empty" colspan="5">No hay registros todavía.</td></tr>`;
} else {
records.forEach((record, index) => {
const tr = document.createElement('tr');
const variationColor = record.diff < 0 ? 'var(--red)' : 'var(--green)';
const sign = record.diff >= 0 ? '+' : '';
tr.innerHTML = `
<td>${record.docsCount}</td>
<td>${CLP.format(record.docsSum)}</td>
<td>${CLP.format(record.budget)}</td>
<td style="color: ${variationColor}; font-weight: bold;">${sign}${CLP.format(record.diff)}</td>
<td><button class="delete-btn" data-index="${index}">Eliminar</button></td>`;
recordsTbody.appendChild(tr);
});
}
};
const addInvoiceFiles = files => {
errorEl.textContent = '';
Array.from(files).forEach(file => {
docs.unshift({
name: file.name,
loadedAt: new Date().toISOString(),
file: file,
amount: randomAmount(10000, 250000),
folio: randomFolio()
});
});
renderDocs();
updateSummary();
};
const setBudgetFile = file => {
if (!file || !file.name.toLowerCase().endsWith('.csv')) {
budgetErrorEl.textContent = 'Solo se permite un archivo CSV.'; return;
}
budgetErrorEl.textContent = '';
const reader = new FileReader();
reader.onload = e => {
const content = e.target.result;
let amount = parseCSVForAmount(content) || randomAmount(200000, 2000000);
budgetFile = { name: file.name, loadedAt: new Date().toISOString(), amount: amount, file: file };
updateSummary();
};
reader.readAsText(file);
};
// --- Asignación de Eventos ---
invoiceInput.addEventListener('change', () => { addInvoiceFiles(invoiceInput.files); invoiceInput.value = ''; });
budgetInput.addEventListener('change', () => { if (budgetInput.files.length > 0) { setBudgetFile(budgetInput.files[0]); budgetInput.value = ''; } });
['dragenter', 'dragover'].forEach(e => dropzone.addEventListener(e, evt => { evt.preventDefault(); evt.stopPropagation(); dropzone.classList.add('drag'); }));
['dragleave', 'drop'].forEach(e => dropzone.addEventListener(e, evt => {
evt.preventDefault(); evt.stopPropagation(); dropzone.classList.remove('drag');
if (e === 'drop') addInvoiceFiles(evt.dataTransfer.files);
}));
['dragenter', 'dragover'].forEach(e => budgetDropzone.addEventListener(e, evt => { evt.preventDefault(); evt.stopPropagation(); budgetDropzone.classList.add('drag'); }));
['dragleave', 'drop'].forEach(e => budgetDropzone.addEventListener(e, evt => {
evt.preventDefault(); evt.stopPropagation(); budgetDropzone.classList.remove('drag');
if (e === 'drop' && evt.dataTransfer.files.length > 0) setBudgetFile(evt.dataTransfer.files[0]);
}));
processBtn.addEventListener('click', async () => {
if (!budgetFile || docs.length === 0) { alert('Carga un presupuesto y al menos un documento.'); return; }
const totalDocs = docs.reduce((sum, d) => sum + d.amount, 0);
records.push({ docsCount: docs.length, docsSum: totalDocs, budget: budgetFile.amount, diff: budgetFile.amount - totalDocs });
renderRecords();
});
resetBtn.addEventListener('click', () => {
if (confirm('¿Estás seguro? Se borrarán todos los datos de la simulación.')) {
docs.length = 0;
records.length = 0;
budgetFile = null;
errorEl.textContent = '';
budgetErrorEl.textContent = '';
renderDocs();
updateSummary();
renderRecords();
}
});
recordsTbody.addEventListener('click', e => {
if (e.target.classList.contains('delete-btn')) {
const index = parseInt(e.target.dataset.index, 10);
if (!isNaN(index)) { records.splice(index, 1); renderRecords(); }
}
});
// --- Estado Inicial ---
updateSummary();
renderDocs();
renderRecords();
}); |