almeira-web/facturacion-dian-hub/frontend/src/api/hubApi.ts

73 lines
2.2 KiB
TypeScript

import { Invoice, TenantInfo, DianResolutionInfo, FiscalMetrics } from '../types/index.js';
const API_BASE = '/api/v1';
const MASTER_API_KEY = 'dev_master_key_innovacion_2026_secure';
async function fetchWithAuth(url: string, options: RequestInit = {}) {
const headers = {
'Content-Type': 'application/json',
'x-api-key': MASTER_API_KEY,
...(options.headers || {}),
};
const response = await fetch(`${API_BASE}${url}`, {
...options,
headers,
});
if (!response.ok) {
const errorBody = await response.json().catch(() => ({ message: 'Error de conexión' }));
throw new Error(errorBody.message || `Error HTTP ${response.status}`);
}
return response.json();
}
export const hubApi = {
async getMetrics(tenantId?: string): Promise<FiscalMetrics> {
const query = tenantId && tenantId !== 'all' ? `?tenantId=${tenantId}` : '';
const res = await fetchWithAuth(`/invoices/metrics${query}`);
return res.data;
},
async getInvoices(tenantId?: string, search?: string): Promise<{ items: Invoice[]; total: number }> {
const params = new URLSearchParams();
if (tenantId && tenantId !== 'all') params.append('tenantId', tenantId);
if (search) params.append('busqueda', search);
const qs = params.toString() ? `?${params.toString()}` : '';
const res = await fetchWithAuth(`/invoices${qs}`);
return { items: res.data, total: res.total };
},
async getTenants(): Promise<TenantInfo[]> {
const res = await fetchWithAuth('/tenants');
return res.data;
},
async getResolutions(): Promise<DianResolutionInfo[]> {
const res = await fetchWithAuth('/resolutions');
return res.data;
},
async emitInvoice(payload: any, tenantId: string): Promise<Invoice> {
const res = await fetchWithAuth('/invoices', {
method: 'POST',
body: JSON.stringify({ ...payload, tenantId }),
});
return res.data;
},
async getXml(invoiceId: string): Promise<string> {
const response = await fetch(`${API_BASE}/invoices/${invoiceId}/xml`, {
headers: { 'x-api-key': MASTER_API_KEY },
});
if (!response.ok) throw new Error('No se pudo obtener el XML');
return response.text();
},
getPdfUrl(invoiceId: string): string {
return `${API_BASE}/invoices/${invoiceId}/pdf`;
},
};