Files
Autoparts-DB/pos/static/js/invoicing.js
2026-03-31 04:10:48 +00:00

228 lines
9.8 KiB
JavaScript

// /home/Autopartes/pos/static/js/invoicing.js
// Invoicing module: CFDI queue management, cancel, PDF
const Invoicing = (() => {
const API = '/pos/api/invoicing';
function token() {
return localStorage.getItem('pos_token') || '';
}
function headers() {
return { 'Authorization': `Bearer ${token()}`, 'Content-Type': 'application/json' };
}
async function api(path, opts = {}) {
const res = await fetch(`${API}${path}`, { headers: headers(), ...opts });
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(err.error || 'Request failed');
}
return res.json();
}
function fmt(n) {
return parseFloat(n || 0).toLocaleString('es-MX', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function badgeClass(status) {
return {
pending: 'badge-pending',
sending: 'badge-sending',
stamped: 'badge-stamped',
failed: 'badge-failed',
cancelled: 'badge-cancelled',
}[status] || '';
}
function badgeLabel(status) {
return {
pending: 'Pendiente',
sending: 'Enviando',
stamped: 'Timbrado',
failed: 'Fallido',
cancelled: 'Cancelado',
}[status] || status;
}
// ─── Queue List ────────────────────────────────
async function loadQueue() {
try {
const status = document.getElementById('filter-status').value;
const type = document.getElementById('filter-type').value;
let qs = '?per_page=50';
if (status) qs += `&status=${status}`;
if (type) qs += `&type=${type}`;
const res = await api(`/queue${qs}`);
renderQueue(res.data || []);
updateStats(res.data || []);
} catch (e) {
document.getElementById('queue-list').innerHTML =
`<p style="color:var(--danger);">Error: ${e.message}</p>`;
}
}
function updateStats(items) {
const counts = { pending: 0, sending: 0, stamped: 0, failed: 0, cancelled: 0 };
items.forEach(i => { if (counts[i.status] !== undefined) counts[i.status]++; });
document.getElementById('queue-stats').innerHTML = `
<div class="stat-card"><div class="number">${counts.pending}</div><div class="label">Pendientes</div></div>
<div class="stat-card"><div class="number">${counts.sending}</div><div class="label">Enviando</div></div>
<div class="stat-card"><div class="number">${counts.stamped}</div><div class="label">Timbrados</div></div>
<div class="stat-card"><div class="number">${counts.failed}</div><div class="label">Fallidos</div></div>
<div class="stat-card"><div class="number">${counts.cancelled}</div><div class="label">Cancelados</div></div>`;
}
function renderQueue(items) {
const container = document.getElementById('queue-list');
if (!items.length) { container.innerHTML = '<p>No hay CFDIs en la cola.</p>'; return; }
let html = `<table class="queue-table">
<thead><tr>
<th>#</th><th>Venta</th><th>Tipo</th><th>Folio</th>
<th>UUID</th><th>Estado</th><th>Reintentos</th><th>Fecha</th><th>Acciones</th>
</tr></thead><tbody>`;
for (const item of items) {
const uuid = item.uuid_fiscal
? `${item.uuid_fiscal.substring(0, 8)}...`
: '-';
html += `<tr>
<td>${item.id}</td>
<td>#${item.sale_id}</td>
<td>${item.type}</td>
<td>${item.provisional_folio || '-'}</td>
<td title="${item.uuid_fiscal || ''}">${uuid}</td>
<td><span class="badge ${badgeClass(item.status)}">${badgeLabel(item.status)}</span></td>
<td>${item.retry_count || 0}</td>
<td>${item.created_at ? new Date(item.created_at).toLocaleDateString('es-MX') : ''}</td>
<td>
<button class="btn btn-secondary" style="padding:0.2rem 0.4rem;font-size:0.8rem;"
onclick="Invoicing.showDetail(${item.id})">Ver</button>
${item.status === 'stamped' ? `<button class="btn btn-danger" style="padding:0.2rem 0.4rem;font-size:0.8rem;"
onclick="Invoicing.showCancelModal(${item.id})">Cancelar</button>` : ''}
${item.sale_id ? `<a href="/pos/api/invoicing/${item.sale_id}/pdf" target="_blank"
class="btn btn-secondary" style="padding:0.2rem 0.4rem;font-size:0.8rem;">PDF</a>` : ''}
</td>
</tr>`;
}
html += '</tbody></table>';
container.innerHTML = html;
}
// ─── Detail ────────────────────────────────────
async function showDetail(cfdiId) {
try {
const item = await api(`/queue/${cfdiId}`);
let html = `<h3>CFDI #${item.id}</h3>
<div class="detail-grid">
<div class="detail-item"><label>Venta</label><span>#${item.sale_id}</span></div>
<div class="detail-item"><label>Tipo</label><span>${item.type}</span></div>
<div class="detail-item"><label>Estado</label><span class="badge ${badgeClass(item.status)}">${badgeLabel(item.status)}</span></div>
<div class="detail-item"><label>Folio Provisional</label><span>${item.provisional_folio || '-'}</span></div>
<div class="detail-item"><label>UUID Fiscal</label><span>${item.uuid_fiscal || '-'}</span></div>
<div class="detail-item"><label>Reintentos</label><span>${item.retry_count}</span></div>
<div class="detail-item"><label>Creado</label><span>${item.created_at || '-'}</span></div>
<div class="detail-item"><label>Timbrado</label><span>${item.stamped_at || '-'}</span></div>
</div>`;
if (item.error_message) {
html += `<p style="color:var(--danger);"><strong>Error:</strong> ${item.error_message}</p>`;
}
if (item.cancel_motive) {
html += `<p><strong>Motivo cancelacion:</strong> ${item.cancel_motive}</p>`;
}
// XML preview
const xml = item.xml_signed || item.xml_unsigned;
if (xml) {
html += `<h4>XML</h4><div class="xml-preview">${escapeHtml(xml)}</div>`;
}
document.getElementById('detail-content').innerHTML = html;
document.getElementById('detail-modal').classList.add('active');
} catch (e) {
alert('Error: ' + e.message);
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// ─── Process Queue ─────────────────────────────
async function processQueue() {
if (!confirm('Procesar todos los CFDIs pendientes?')) return;
try {
const result = await api('/queue/process', { method: 'POST' });
alert(`Procesados: ${result.processed}, Timbrados: ${result.stamped}, Fallidos: ${result.failed}`);
loadQueue();
} catch (e) {
alert('Error: ' + e.message);
}
}
// ─── Cancel ────────────────────────────────────
function showCancelModal(cfdiId) {
document.getElementById('cancel-cfdi-id').value = cfdiId;
document.getElementById('cancel-motive').value = '';
document.getElementById('cancel-replacement-uuid').value = '';
document.getElementById('replacement-uuid-group').style.display = 'none';
document.getElementById('cancel-modal').classList.add('active');
}
function onMotiveChange() {
const motive = document.getElementById('cancel-motive').value;
document.getElementById('replacement-uuid-group').style.display =
motive === '01' ? 'block' : 'none';
}
async function confirmCancel() {
const cfdiId = document.getElementById('cancel-cfdi-id').value;
const motive = document.getElementById('cancel-motive').value;
const replacementUuid = document.getElementById('cancel-replacement-uuid').value;
if (!motive) { alert('Selecciona un motivo de cancelacion.'); return; }
if (motive === '01' && !replacementUuid) { alert('UUID sustituto requerido para motivo 01.'); return; }
if (!confirm('Confirmar cancelacion ante el SAT?')) return;
try {
const body = { motive };
if (replacementUuid) body.replacement_uuid = replacementUuid;
await api(`/cancel/${cfdiId}`, { method: 'POST', body: JSON.stringify(body) });
closeModal('cancel-modal');
loadQueue();
alert('CFDI cancelado exitosamente.');
} catch (e) {
alert('Error: ' + e.message);
}
}
// ─── Modal helpers ─────────────────────────────
function closeModal(id) {
document.getElementById(id).classList.remove('active');
}
// ─── Init ──────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
loadQueue();
});
return {
loadQueue, processQueue, showDetail, showCancelModal,
onMotiveChange, confirmCancel, closeModal,
};
})();