/* ============================================================
AFIP / ARCA — Configuración y Autorización de comprobantes
============================================================ */
async function loadAfipConfig() {
try {
const res = await apiFetch('/api/afip/config');
if (!res) return;
renderAfipConfig(res);
} catch (e) {
console.warn('AFIP config no disponible:', e);
}
}
function renderAfipConfig(cfg) {
const set = (id, val) => {
const el = document.getElementById(id);
if (el) el.value = val ?? '';
};
set('afip-cuit', cfg.cuit);
set('afip-razon-social', cfg.razon_social);
set('afip-domicilio-comercial', cfg.domicilio_comercial);
set('afip-tipo-contribuyente', cfg.tipo_contribuyente);
set('afip-punto-venta', cfg.punto_venta ?? 1);
set('afip-access-token', cfg.access_token);
set('afip-certificado', cfg.certificado);
set('afip-clave-privada', cfg.clave_privada);
set('afip-iibb', cfg.iibb);
set('afip-inicio-actividades', cfg.inicio_actividades);
const habEl = document.getElementById('afip-habilitado');
if (habEl) habEl.checked = !!+cfg.habilitado;
const entorno = cfg.entorno ?? 'testing';
const radio = document.querySelector(`input[name="afip-entorno"][value="${entorno}"]`);
if (radio) {
radio.checked = true;
document.getElementById('aviso-produccion')?.classList.toggle('hidden', entorno !== 'production');
}
}
async function saveAfipConfig(e) {
if (e) e.preventDefault();
const entorno = document.querySelector('input[name="afip-entorno"]:checked')?.value ?? 'testing';
const payload = {
cuit: document.getElementById('afip-cuit')?.value.trim() ?? '',
razon_social: document.getElementById('afip-razon-social')?.value.trim() ?? '',
domicilio_comercial: document.getElementById('afip-domicilio-comercial')?.value.trim() ?? '',
tipo_contribuyente: document.getElementById('afip-tipo-contribuyente')?.value ?? 'responsable_inscripto',
punto_venta: parseInt(document.getElementById('afip-punto-venta')?.value ?? '1', 10),
entorno,
access_token: document.getElementById('afip-access-token')?.value.trim() ?? '',
certificado: document.getElementById('afip-certificado')?.value.trim() ?? '',
clave_privada: document.getElementById('afip-clave-privada')?.value.trim() ?? '',
habilitado: document.getElementById('afip-habilitado')?.checked ? 1 : 0,
iibb: document.getElementById('afip-iibb')?.value.trim() ?? '',
inicio_actividades: document.getElementById('afip-inicio-actividades')?.value ?? '',
};
try {
await apiFetch('/api/afip/config', { method: 'PUT', body: JSON.stringify(payload) });
showToast('Configuración AFIP guardada', 'success');
} catch (err) {
showToast('Error al guardar: ' + (err.message ?? err), 'error');
}
}
async function testAfipConnection() {
const badge = document.getElementById('afip-status-badge');
const msg = document.getElementById('afip-status-msg');
const btn = document.getElementById('btn-test-afip');
if (btn) btn.disabled = true;
if (badge) badge.innerHTML = ' Verificando...';
if (msg) msg.textContent = '';
try {
const res = await apiFetch('/api/afip/test', { method: 'POST', body: '{}' });
if (res.ok) {
if (badge) badge.innerHTML = ' Conectado';
if (badge) badge.className = 'inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700';
if (msg) msg.textContent = res.msg ?? 'Conexión exitosa';
} else {
if (badge) badge.innerHTML = ' Error';
if (badge) badge.className = 'inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-700';
if (msg) msg.textContent = res.msg ?? 'Error de conexión';
}
} catch (err) {
if (badge) badge.innerHTML = ' Error';
if (badge) badge.className = 'inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-700';
if (msg) msg.textContent = err.message ?? 'Error desconocido';
} finally {
if (btn) btn.disabled = false;
}
}
/**
* Autoriza una factura con AFIP/ARCA y ejecuta callback con la factura actualizada.
* @param {string} invoiceId
* @param {Function} onSuccess - recibe el invoice actualizado (con CAE)
*/
async function autorizarFactura(invoiceId, onSuccess) {
showToast('Solicitando CAE a ARCA...', 'info');
try {
const res = await apiFetch(`/api/afip/autorizar/${invoiceId}`, { method: 'POST', body: '{}' });
if (res.error) throw new Error(res.error);
showToast(`CAE obtenido: ${res.cae}`, 'success');
if (typeof onSuccess === 'function') onSuccess(res);
} catch (err) {
showToast('Error al autorizar: ' + (err.message ?? err), 'error');
}
}
/**
* Estado de AFIP para mostrar botón en POS (se cachea 60s).
*/
let _afipEnabled = null;
let _afipEnabledTs = 0;
async function isAfipEnabled() {
const now = Date.now();
if (_afipEnabled !== null && now - _afipEnabledTs < 60000) return _afipEnabled;
try {
const cfg = await apiFetch('/api/afip/config');
_afipEnabled = !!cfg && !!+cfg.habilitado;
_afipEnabledTs = now;
} catch {
_afipEnabled = false;
}
return _afipEnabled;
}