einvoice/ts/formats/factories/decoder.factory.ts

63 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-04-03 15:53:08 +00:00
import { BaseDecoder } from '../base/base.decoder.js';
import { InvoiceFormat } from '../../interfaces/common.js';
import { FormatDetector } from '../utils/format.detector.js';
// Import specific decoders
2025-04-03 16:41:10 +00:00
import { XRechnungDecoder } from '../ubl/xrechnung/xrechnung.decoder.js';
2025-04-03 15:53:08 +00:00
import { FacturXDecoder } from '../cii/facturx/facturx.decoder.js';
import { ZUGFeRDDecoder } from '../cii/zugferd/zugferd.decoder.js';
import { ZUGFeRDV1Decoder } from '../cii/zugferd/zugferd.v1.decoder.js';
2025-04-03 15:53:08 +00:00
/**
* Factory to create the appropriate decoder based on the XML format
*/
export class DecoderFactory {
/**
* Creates a decoder for the specified XML content
* @param xml XML content to decode
2025-05-28 08:40:26 +00:00
* @param skipValidation Whether to skip EN16931 validation
2025-04-03 15:53:08 +00:00
* @returns Appropriate decoder instance
*/
2025-05-28 08:40:26 +00:00
public static createDecoder(xml: string, skipValidation: boolean = false): BaseDecoder {
2025-04-03 15:53:08 +00:00
const format = FormatDetector.detectFormat(xml);
switch (format) {
case InvoiceFormat.UBL:
case InvoiceFormat.XRECHNUNG:
2025-05-28 08:40:26 +00:00
return new XRechnungDecoder(xml, skipValidation);
2025-04-03 15:53:08 +00:00
case InvoiceFormat.CII:
// For now, use Factur-X decoder for generic CII
2025-05-28 08:40:26 +00:00
return new FacturXDecoder(xml, skipValidation);
2025-04-03 15:53:08 +00:00
case InvoiceFormat.ZUGFERD:
// Determine if it's ZUGFeRD v1 or v2 based on root element
if (xml.includes('CrossIndustryDocument') ||
xml.includes('urn:ferd:CrossIndustryDocument:invoice:1p0') ||
(xml.includes('ZUGFeRD') && !xml.includes('CrossIndustryInvoice'))) {
2025-05-28 08:40:26 +00:00
return new ZUGFeRDV1Decoder(xml, skipValidation);
} else {
2025-05-28 08:40:26 +00:00
return new ZUGFeRDDecoder(xml, skipValidation);
}
2025-04-03 15:53:08 +00:00
case InvoiceFormat.FACTURX:
2025-05-28 08:40:26 +00:00
return new FacturXDecoder(xml, skipValidation);
2025-04-03 15:53:08 +00:00
case InvoiceFormat.FATTURAPA:
// return new FatturaPADecoder(xml);
throw new Error('FatturaPA decoder not yet implemented');
default:
// If format is unknown but contains CrossIndustryInvoice, try ZUGFeRD decoder
if (xml.includes('CrossIndustryInvoice')) {
2025-05-28 08:40:26 +00:00
return new ZUGFeRDDecoder(xml, skipValidation);
}
// If format is unknown but contains CrossIndustryDocument, try ZUGFeRD v1 decoder
if (xml.includes('CrossIndustryDocument')) {
2025-05-28 08:40:26 +00:00
return new ZUGFeRDV1Decoder(xml, skipValidation);
}
2025-04-03 15:53:08 +00:00
throw new Error(`Unsupported invoice format: ${format}`);
}
}
}