refactor(cfdi): descarga masiva de XMLs por filtros en lugar de checkboxes

- Backend: POST /cfdi/download-xmls acepta CfdiFilters, usa getXmlsByFilters con LIMIT 1000
- Frontend: eliminados checkboxes y estado selectedIds; botón Descargar XMLs usa filtros activos
- Si >1000 resultados, muestra confirm() de advertencia pero permite proceder
- Agregada documentación técnica y changelog
This commit is contained in:
Horux Dev
2026-05-24 21:40:08 +00:00
parent 5c940847af
commit e35eae2a72
6 changed files with 415 additions and 87 deletions

View File

@@ -82,28 +82,33 @@ export async function downloadXmlsZip(req: Request, res: Response, next: NextFun
return next(new AppError(400, 'Tenant no configurado'));
}
const ids = req.body.ids as number[];
if (!Array.isArray(ids) || ids.length === 0) {
return next(new AppError(400, 'Se requiere un array de IDs'));
}
if (ids.length > 1000) {
return next(new AppError(400, 'Máximo 1,000 CFDIs por descarga'));
}
const filters: CfdiFilters = {
tipo: req.body.tipo as any,
tipoComprobante: req.body.tipoComprobante as any,
estado: req.body.estado as any,
fechaInicio: req.body.fechaInicio as string,
fechaFin: req.body.fechaFin as string,
rfc: req.body.rfc as string,
emisor: req.body.emisor as string,
receptor: req.body.receptor as string,
search: req.body.search as string,
contribuyenteId: req.body.contribuyenteId as string,
};
const cfdis = await cfdiService.getXmlsByIds(req.tenantPool, ids);
const cfdis = await cfdiService.getCfdiXmlsForZip(req.tenantPool, filters);
const zip = new AdmZip();
let added = 0;
for (const cfdi of cfdis) {
if (cfdi.xml) {
const filename = `${cfdi.uuid || cfdi.id}.xml`;
const filename = `${cfdi.uuid || 'cfdi'}.xml`;
zip.addFile(filename, Buffer.from(cfdi.xml, 'utf8'));
added++;
}
}
if (added === 0) {
return next(new AppError(404, 'No se encontraron XMLs para los CFDIs seleccionados'));
return next(new AppError(404, 'No se encontraron XMLs para los filtros aplicados'));
}
const zipBuffer = zip.toBuffer();

View File

@@ -364,6 +364,74 @@ export async function getXmlsByIds(pool: Pool, ids: number[]): Promise<{ id: num
return rows.map((r: any) => ({ id: r.id, uuid: r.uuid, xml: r.xml_original || null }));
}
export async function getCfdiXmlsForZip(
pool: Pool,
filters: CfdiFilters
): Promise<{ uuid: string; xml: string | null }[]> {
let whereClause = 'WHERE xml_original IS NOT NULL';
const params: any[] = [];
let paramIndex = 1;
if (filters.tipo && !filters.contribuyenteId) {
whereClause += ` AND type = $${paramIndex++}`;
params.push(filters.tipo);
}
if (filters.tipoComprobante) {
whereClause += ` AND tipo_comprobante = $${paramIndex++}`;
params.push(filters.tipoComprobante);
}
if (filters.estado) {
whereClause += ` AND status = $${paramIndex++}`;
params.push(filters.estado);
}
if (filters.fechaInicio) {
whereClause += ` AND COALESCE(fecha_efectiva, fecha_emision - interval '1 hour') >= $${paramIndex++}::date`;
params.push(filters.fechaInicio);
}
if (filters.fechaFin) {
whereClause += ` AND COALESCE(fecha_efectiva, fecha_emision - interval '1 hour') <= ($${paramIndex++}::date + interval '1 day')`;
params.push(filters.fechaFin);
}
if (filters.rfc) {
whereClause += ` AND (rfc_emisor ILIKE $${paramIndex} OR rfc_receptor ILIKE $${paramIndex++})`;
params.push(`%${filters.rfc}%`);
}
if (filters.emisor) {
whereClause += ` AND (rfc_emisor ILIKE $${paramIndex} OR nombre_emisor ILIKE $${paramIndex++})`;
params.push(`%${filters.emisor}%`);
}
if (filters.receptor) {
whereClause += ` AND (rfc_receptor ILIKE $${paramIndex} OR nombre_receptor ILIKE $${paramIndex++})`;
params.push(`%${filters.receptor}%`);
}
if (filters.search) {
whereClause += ` AND (uuid ILIKE $${paramIndex} OR nombre_emisor ILIKE $${paramIndex} OR nombre_receptor ILIKE $${paramIndex} OR rfc_emisor ILIKE $${paramIndex} OR rfc_receptor ILIKE $${paramIndex++})`;
params.push(`%${filters.search}%`);
}
if (filters.contribuyenteId) {
if (filters.tipo === 'EMITIDO') {
whereClause += ` AND rfc_emisor = (SELECT rfc FROM contribuyentes WHERE entidad_id = $${paramIndex++})`;
params.push(filters.contribuyenteId);
} else if (filters.tipo === 'RECIBIDO') {
whereClause += ` AND rfc_receptor = (SELECT rfc FROM contribuyentes WHERE entidad_id = $${paramIndex++})`;
params.push(filters.contribuyenteId);
} else {
whereClause += ` AND (contribuyente_id = $${paramIndex} OR rfc_emisor = (SELECT rfc FROM contribuyentes WHERE entidad_id = $${paramIndex}) OR rfc_receptor = (SELECT rfc FROM contribuyentes WHERE entidad_id = $${paramIndex++}))`;
params.push(filters.contribuyenteId);
}
}
params.push(1000);
const { rows } = await pool.query(`
SELECT uuid, xml_original FROM cfdis
${whereClause}
ORDER BY fecha_emision DESC
LIMIT $${paramIndex++}
`, params);
return rows.map((r: any) => ({ uuid: r.uuid, xml: r.xml_original || null }));
}
export interface CreateCfdiData {
uuid: string;
type: 'EMITIDO' | 'RECIBIDO';

View File

@@ -261,7 +261,6 @@ export default function CfdiPage() {
const [loadingEmisor, setLoadingEmisor] = useState(false);
const [loadingReceptor, setLoadingReceptor] = useState(false);
const [showForm, setShowForm] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const [downloadingXmls, setDownloadingXmls] = useState(false);
// Debounced values for autocomplete
@@ -1762,54 +1761,48 @@ export default function CfdiPage() {
<FileText className="h-4 w-4" />
CFDIs ({data?.total || 0})
</CardTitle>
<div className="flex items-center gap-2">
{selectedIds.size > 0 && (
<>
<span className="text-xs text-muted-foreground">
{selectedIds.size} seleccionados
</span>
<Button
variant="outline"
size="sm"
onClick={async () => {
if (selectedIds.size > 1000) {
alert('Máximo 1,000 CFDIs por descarga');
return;
}
try {
setDownloadingXmls(true);
const blob = await downloadXmlsZip(Array.from(selectedIds));
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cfdis-xml-${Date.now()}.zip`;
a.click();
URL.revokeObjectURL(url);
} catch (err: any) {
alert(err?.response?.data?.message || err?.message || 'Error al descargar XMLs');
} finally {
setDownloadingXmls(false);
}
}}
disabled={downloadingXmls}
>
{downloadingXmls ? (
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<Download className="h-4 w-4 mr-1" />
)}
Descargar XMLs
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedIds(new Set())}
>
Limpiar
</Button>
</>
<Button
variant="outline"
size="sm"
onClick={async () => {
if ((data?.total || 0) > 1000) {
if (!confirm('Solo se descargarán los primeros 1,000 XMLs. ¿Continuar?')) return;
}
try {
setDownloadingXmls(true);
const blob = await downloadXmlsZip({
tipo: filters.tipo,
tipoComprobante: filters.tipoComprobante,
estado: filters.estado,
fechaInicio: filters.fechaInicio,
fechaFin: filters.fechaFin,
rfc: filters.rfc,
emisor: filters.emisor,
receptor: filters.receptor,
search: filters.search,
contribuyenteId: filters.contribuyenteId,
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cfdis-xml-${Date.now()}.zip`;
a.click();
URL.revokeObjectURL(url);
} catch (err: any) {
alert(err?.response?.data?.message || err?.message || 'Error al descargar XMLs');
} finally {
setDownloadingXmls(false);
}
}}
disabled={downloadingXmls || !data?.total}
>
{downloadingXmls ? (
<Loader2 className="h-4 w-4 mr-1 animate-spin" />
) : (
<Download className="h-4 w-4 mr-1" />
)}
</div>
Descargar XMLs
</Button>
{hasActiveColumnFilters && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span>Filtros activos:</span>
@@ -1867,19 +1860,6 @@ export default function CfdiPage() {
<table className="w-full">
<thead>
<tr className="border-b text-center text-sm text-muted-foreground">
<th className="pb-3 w-8">
<input
type="checkbox"
checked={data?.data.length ? selectedIds.size === data.data.length : false}
onChange={() => {
if (selectedIds.size === data?.data.length) {
setSelectedIds(new Set());
} else {
setSelectedIds(new Set(data?.data.map((c: any) => c.id) || []));
}
}}
/>
</th>
<th className="pb-3 font-medium">
<div className="flex items-center gap-1 justify-center">
Fecha
@@ -2055,20 +2035,6 @@ export default function CfdiPage() {
<tbody className="text-sm text-center">
{data?.data.map((cfdi) => (
<tr key={cfdi.id} className="border-b hover:bg-muted/50">
<td className="py-3">
<input
type="checkbox"
checked={selectedIds.has(cfdi.id)}
onChange={() => {
setSelectedIds(prev => {
const next = new Set(prev);
if (next.has(cfdi.id)) next.delete(cfdi.id);
else next.add(cfdi.id);
return next;
});
}}
/>
</td>
<td className="py-3">{formatDate(cfdi.fechaEmision)}</td>
<td className="py-3">
<span className="text-xs" title={formatTipoComprobante(cfdi.tipoComprobante)}>

View File

@@ -91,8 +91,8 @@ export async function getCfdiById(id: string): Promise<Cfdi> {
return response.data;
}
export async function downloadXmlsZip(ids: number[]): Promise<Blob> {
const response = await apiClient.post('/cfdi/download-xmls', { ids }, { responseType: 'blob' });
export async function downloadXmlsZip(filters: CfdiFilters): Promise<Blob> {
const response = await apiClient.post('/cfdi/download-xmls', filters, { responseType: 'blob' });
return response.data;
}