xinvoice/ts/formats/utils/format.detector.ts

49 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-04-03 15:53:08 +00:00
import { InvoiceFormat } from '../../interfaces/common.js';
2025-03-17 16:49:49 +00:00
import { DOMParser } from 'xmldom';
/**
2025-04-03 15:53:08 +00:00
* Utility class for detecting invoice formats
2025-03-17 16:49:49 +00:00
*/
2025-04-03 15:53:08 +00:00
export class FormatDetector {
2025-03-17 16:49:49 +00:00
/**
2025-04-03 15:53:08 +00:00
* Detects the format of an XML document
2025-03-17 16:49:49 +00:00
* @param xml XML content to analyze
* @returns Detected invoice format
*/
2025-04-03 15:53:08 +00:00
public static detectFormat(xml: string): InvoiceFormat {
2025-03-17 16:49:49 +00:00
try {
const doc = new DOMParser().parseFromString(xml, 'application/xml');
const root = doc.documentElement;
2025-04-03 16:41:10 +00:00
2025-03-17 16:49:49 +00:00
if (!root) {
return InvoiceFormat.UNKNOWN;
}
2025-04-03 16:41:10 +00:00
2025-03-17 16:49:49 +00:00
// UBL detection (Invoice or CreditNote root element)
if (root.nodeName === 'Invoice' || root.nodeName === 'CreditNote') {
2025-04-03 16:41:10 +00:00
// For simplicity, we'll treat all UBL documents as XRechnung for now
// In a real implementation, we would check for specific customization IDs
return InvoiceFormat.XRECHNUNG;
2025-03-17 16:49:49 +00:00
}
2025-04-03 16:41:10 +00:00
2025-03-17 16:49:49 +00:00
// Factur-X/ZUGFeRD detection (CrossIndustryInvoice root element)
if (root.nodeName === 'rsm:CrossIndustryInvoice' || root.nodeName === 'CrossIndustryInvoice') {
2025-04-03 16:41:10 +00:00
// For simplicity, we'll treat all CII documents as Factur-X for now
// In a real implementation, we would check for specific profiles
return InvoiceFormat.FACTURX;
2025-03-17 16:49:49 +00:00
}
2025-04-03 16:41:10 +00:00
2025-03-17 16:49:49 +00:00
// FatturaPA detection would be implemented here
2025-04-03 16:41:10 +00:00
if (root.nodeName === 'FatturaElettronica' ||
2025-04-03 15:53:08 +00:00
(root.getAttribute('xmlns') && root.getAttribute('xmlns')!.includes('fatturapa.gov.it'))) {
return InvoiceFormat.FATTURAPA;
}
2025-04-03 16:41:10 +00:00
2025-03-17 16:49:49 +00:00
return InvoiceFormat.UNKNOWN;
} catch (error) {
2025-04-03 15:53:08 +00:00
console.error('Error detecting format:', error);
2025-03-17 16:49:49 +00:00
return InvoiceFormat.UNKNOWN;
}
}
2025-04-03 15:53:08 +00:00
}