// SPDX-License-Identifier: EUPL-1.2 // Validation orchestrator. Pure and deterministic: the same bytes and profile always give // the same result. No clock, no randomness, no I/O. import { canonicalContent } from "./content-digest"; import { DocIndex, all, first, locate, valueAt } from "./query"; import { RULE_INDEX } from "./registry"; import { ENGINE_VERSION, RULESET_RELEASES } from "./releases"; import { runModelRules } from "./rules-en16931"; import { runVatRules } from "./rules-en16931-vat"; import { runPeppolRules } from "./rules-peppol"; import { runSyntaxRules } from "./rules-ubl-syntax"; import { runStructureChecks } from "./structure"; import type { CenRelease, Finding, RuleContext } from "./types"; import { CUSTOMER_PARTY, SUPPLIER_PARTY, isVat } from "./ubl"; import type { XmlLimits, XmlNode } from "./xml"; import { DEFAULT_XML_LIMITS, NS, parseXml } from "./xml"; export type RulesetChoice = "auto" | "en16931" | "peppol-bis-3"; export type AppliedRuleset = "en16931" | "peppol-bis-3"; import type { RequirableTerm } from "./terms"; import { REQUIRABLE_TERMS } from "./terms"; export type { RequirableTerm } from "./terms"; export { REQUIRABLE_TERMS, REQUIRABLE_TERM_IDS } from "./terms"; /** * A profile can only make validation stricter: it may hide warnings, turn warnings into * a failing verdict, and require extra fields. It can never hide a fatal finding. */ export interface ValidationProfile { readonly ruleset: RulesetChoice; readonly treatWarningsAsErrors: boolean; readonly suppressedWarnings: readonly string[]; readonly requiredTerms: readonly RequirableTerm[]; } export const DEFAULT_PROFILE: ValidationProfile = { ruleset: "auto", treatWarningsAsErrors: false, suppressedWarnings: [], requiredTerms: [] }; export interface PartySummary { readonly name: string; readonly country: string; readonly vatId: string; } export interface DocumentSummary { readonly kind: "Invoice" | "CreditNote"; readonly number: string; readonly issueDate: string; readonly typeCode: string; readonly currency: string; readonly customizationId: string; readonly profileId: string; readonly seller: PartySummary; readonly buyer: PartySummary; readonly lineCount: number; readonly totalWithoutVat: string; readonly totalWithVat: string; readonly amountDue: string; } export interface OmittedFindings { readonly ruleId: string; readonly count: number; } export interface EngineResult { readonly engineVersion: string; readonly appliedRuleset: AppliedRuleset; readonly rulesets: readonly { readonly id: string; readonly release: string }[]; readonly document: DocumentSummary | null; readonly verdict: "pass" | "fail"; readonly counts: { readonly fatal: number; readonly warning: number; readonly suppressed: number }; readonly findings: readonly Finding[]; readonly omitted: readonly OmittedFindings[]; /** Canonical text of the parsed document (content-digest.ts), or null when it could not be parsed. Not part of the report. */ readonly canonicalContent: string | null; } export const MAX_FINDINGS_PER_RULE = 20; const SUMMARY_FIELD_LIMIT = 200; const PEPPOL_MARKER = "urn:fdc:peppol.eu:2017:poacc:billing:3.0"; const clip = (text: string): string => (text.length > SUMMARY_FIELD_LIMIT ? `${text.slice(0, SUMMARY_FIELD_LIMIT)}…` : text); function summariseParty(root: XmlNode, partyPath: string): PartySummary { const party = first(root, partyPath); const vatScheme = all(party, "cac:PartyTaxScheme").find(isVat); return { name: clip(valueAt(party, "cac:PartyLegalEntity/cbc:RegistrationName") || valueAt(party, "cac:PartyName/cbc:Name")), country: clip(valueAt(party, "cac:PostalAddress/cac:Country/cbc:IdentificationCode")), vatId: clip(valueAt(vatScheme, "cbc:CompanyID")) }; } function summarise(root: XmlNode, isCreditNote: boolean): DocumentSummary { const totals = first(root, "cac:LegalMonetaryTotal"); return { kind: isCreditNote ? "CreditNote" : "Invoice", number: clip(valueAt(root, "cbc:ID")), issueDate: clip(valueAt(root, "cbc:IssueDate")), typeCode: clip(valueAt(root, isCreditNote ? "cbc:CreditNoteTypeCode" : "cbc:InvoiceTypeCode")), currency: clip(valueAt(root, "cbc:DocumentCurrencyCode")), customizationId: clip(valueAt(root, "cbc:CustomizationID")), profileId: clip(valueAt(root, "cbc:ProfileID")), seller: summariseParty(root, SUPPLIER_PARTY), buyer: summariseParty(root, CUSTOMER_PARTY), lineCount: all(root, isCreditNote ? "cac:CreditNoteLine" : "cac:InvoiceLine").length, totalWithoutVat: clip(valueAt(totals, "cbc:TaxExclusiveAmount")), totalWithVat: clip(valueAt(totals, "cbc:TaxInclusiveAmount")), amountDue: clip(valueAt(totals, "cbc:PayableAmount")) }; } interface Collected { readonly finding: Finding; readonly order: number; } function finish( collected: readonly Collected[], omittedCounts: ReadonlyMap, profile: ValidationProfile, appliedRuleset: AppliedRuleset, document: DocumentSummary | null, content: string | null ): EngineResult { const suppressed = new Set(profile.suppressedWarnings); let suppressedCount = 0; const kept: Collected[] = []; for (const item of collected) { if (item.finding.severity === "warning" && suppressed.has(item.finding.ruleId)) suppressedCount += 1; else kept.push(item); } kept.sort( (a, b) => a.finding.line - b.finding.line || (a.finding.ruleId < b.finding.ruleId ? -1 : a.finding.ruleId > b.finding.ruleId ? 1 : 0) || a.order - b.order ); const findings = kept.map((item) => item.finding); const fatal = findings.filter((finding) => finding.severity === "fatal").length; const warning = findings.length - fatal; const omitted = [...omittedCounts] .map(([ruleId, count]) => ({ ruleId, count })) .sort((a, b) => (a.ruleId < b.ruleId ? -1 : 1)); const cen = appliedRuleset === "peppol-bis-3" ? RULESET_RELEASES.en16931Peppol : RULESET_RELEASES.en16931; const rulesets: { id: string; release: string }[] = [{ id: cen.id, release: cen.release }]; if (appliedRuleset === "peppol-bis-3") rulesets.push({ id: RULESET_RELEASES.peppol.id, release: RULESET_RELEASES.peppol.release }); return { engineVersion: ENGINE_VERSION, appliedRuleset, rulesets, document, verdict: fatal > 0 || (profile.treatWarningsAsErrors && warning > 0) ? "fail" : "pass", counts: { fatal, warning, suppressed: suppressedCount }, findings, omitted, canonicalContent: content }; } /** Result for input that is not valid UTF-8 and therefore cannot be parsed at all. */ export function invalidEncodingResult(profile: ValidationProfile = DEFAULT_PROFILE): EngineResult { const rule = RULE_INDEX.get("RS-XML-03"); if (!rule) throw new Error("Unknown rule id: RS-XML-03"); const finding: Finding = { ruleId: rule.id, severity: rule.severity, location: "/", line: 1, message: `${rule.message} The bytes are not valid UTF-8.` }; return finish([{ finding, order: 0 }], new Map(), profile, profile.ruleset === "peppol-bis-3" ? "peppol-bis-3" : "en16931", null, null); } export function validateInvoiceXml( xml: string, profile: ValidationProfile = DEFAULT_PROFILE, limits: XmlLimits = DEFAULT_XML_LIMITS ): EngineResult { const collected: Collected[] = []; const perRule = new Map(); const omitted = new Map(); const record = (ruleId: string, location: string, line: number, detail?: string): void => { const rule = RULE_INDEX.get(ruleId); if (!rule) throw new Error(`Unknown rule id: ${ruleId}`); const seen = (perRule.get(ruleId) ?? 0) + 1; perRule.set(ruleId, seen); if (seen > MAX_FINDINGS_PER_RULE) { omitted.set(ruleId, (omitted.get(ruleId) ?? 0) + 1); return; } collected.push({ finding: { ruleId, severity: rule.severity, location, line, message: detail === undefined ? rule.message : `${rule.message} ${detail}.` }, order: collected.length }); }; const fallbackRuleset: AppliedRuleset = profile.ruleset === "peppol-bis-3" ? "peppol-bis-3" : "en16931"; const parsed = parseXml(xml, limits); if (!parsed.ok) { const ruleId = parsed.code === "dtd_forbidden" ? "RS-XML-02" : parsed.code === "unsupported_encoding" ? "RS-XML-03" : parsed.code === "limit_exceeded" ? "RS-XML-04" : "RS-XML-01"; record(ruleId, "/", parsed.line, parsed.message.replace(/\.$/, "")); return finish(collected, omitted, profile, fallbackRuleset, null, null); } const root = parsed.root; const isInvoice = root.local === "Invoice" && root.namespace === NS.invoice; const isCreditNote = root.local === "CreditNote" && root.namespace === NS.creditNote; if (!isInvoice && !isCreditNote) { const crossIndustry = root.local === "CrossIndustryInvoice"; record( "RS-UBL-01", `/${root.q}`, root.line, crossIndustry ? "This is a UN/CEFACT CII document, which this validator does not support" : `Found <${root.local}> in namespace "${root.namespace}"` ); return finish(collected, omitted, profile, fallbackRuleset, null, null); } const customization = valueAt(root, "cbc:CustomizationID"); const appliedRuleset: AppliedRuleset = profile.ruleset === "auto" ? (customization.includes(PEPPOL_MARKER) ? "peppol-bis-3" : "en16931") : profile.ruleset; const cen: CenRelease = appliedRuleset === "peppol-bis-3" ? "1.3.16" : "1.3.17"; const context: RuleContext = { root, isCreditNote, index: new DocIndex(root), cen, emit: (ruleId, node, detail) => record(ruleId, locate(node), node.line, detail) }; runStructureChecks(context); runModelRules(context); runVatRules(context); runSyntaxRules(context); if (appliedRuleset === "peppol-bis-3") runPeppolRules(context); for (const term of profile.requiredTerms) { const definition = REQUIRABLE_TERMS[term]; const path = isCreditNote ? definition.creditNote : definition.invoice; if (valueAt(root, path) === "") record("RS-PRF-01", locate(root), root.line, `${definition.label} (${term})`); } return finish(collected, omitted, profile, appliedRuleset, summarise(root, isCreditNote), canonicalContent(root)); }