Skip to main content

einvoice_validator/
report.rs

1//! The result of validating one document.
2
3use std::fmt;
4
5use roxmltree::{Node, ParsingOptions};
6
7pub use einvoice_xsd::{ErrorKind as SchemaErrorKind, ValidationError as SchemaError};
8
9use crate::Error;
10
11/// The SVRL namespace.
12const SVRL_NS: &str = "http://purl.oclc.org/dsdl/svrl";
13
14/// The overall verdict on a document.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum Verdict {
17    /// No schema error and no finding with severity [`Severity::Fatal`].
18    Valid,
19    /// At least one schema error or one fatal finding.
20    Invalid,
21}
22
23impl Verdict {
24    /// `valid` or `invalid`.
25    #[must_use]
26    pub const fn as_str(self) -> &'static str {
27        match self {
28            Self::Valid => "valid",
29            Self::Invalid => "invalid",
30        }
31    }
32}
33
34impl fmt::Display for Verdict {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(self.as_str())
37    }
38}
39
40/// The severity of a finding, from its Schematron `flag`, as the official rule sets use
41/// it.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
43pub enum Severity {
44    /// `flag="fatal"`: the document does not conform; the verdict is
45    /// [`Verdict::Invalid`].
46    Fatal,
47    /// `flag="warning"`: reported, the document still conforms.
48    Warning,
49    /// Any other flag, or none: reported, the document still conforms.
50    Other,
51}
52
53impl Severity {
54    /// The severity a Schematron flag stands for.
55    #[must_use]
56    pub fn from_flag(flag: Option<&str>) -> Self {
57        match flag {
58            Some("fatal") => Self::Fatal,
59            Some("warning") => Self::Warning,
60            _ => Self::Other,
61        }
62    }
63
64    /// `fatal`, `warning` or `other`.
65    #[must_use]
66    pub const fn as_str(self) -> &'static str {
67        match self {
68            Self::Fatal => "fatal",
69            Self::Warning => "warning",
70            Self::Other => "other",
71        }
72    }
73}
74
75impl fmt::Display for Severity {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(self.as_str())
78    }
79}
80
81/// What a finding is in the SVRL report.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83pub enum FindingKind {
84    /// `svrl:failed-assert`: an assertion that does not hold.
85    FailedAssert,
86    /// `svrl:successful-report`: a report whose condition holds.
87    SuccessfulReport,
88}
89
90impl FindingKind {
91    /// `failed-assert` or `successful-report`.
92    #[must_use]
93    pub const fn as_str(self) -> &'static str {
94        match self {
95            Self::FailedAssert => "failed-assert",
96            Self::SuccessfulReport => "successful-report",
97        }
98    }
99}
100
101impl fmt::Display for FindingKind {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(self.as_str())
104    }
105}
106
107/// A failed assert or a successful report of a stylesheet, as the SVRL report states it.
108#[derive(Debug, Clone, PartialEq, Eq)]
109#[non_exhaustive]
110pub struct Finding {
111    /// Failed assert or successful report.
112    pub kind: FindingKind,
113    /// The rule id (`BR-02`), if the rule has one.
114    pub id: Option<String>,
115    /// The Schematron flag (`fatal`, `warning`), if any.
116    pub flag: Option<String>,
117    /// The severity the flag stands for.
118    pub severity: Severity,
119    /// The Schematron role, if any.
120    pub role: Option<String>,
121    /// The XPath of the node concerned, as the stylesheet writes it.
122    pub location: String,
123    /// The context of the rule that fired (its `svrl:fired-rule/@context`).
124    pub context: Option<String>,
125    /// The id of the pattern the rule belongs to (`svrl:active-pattern/@id`).
126    pub pattern: Option<String>,
127    /// The XPath test of the assert or report.
128    pub test: String,
129    /// The message, whitespace normalised.
130    pub text: String,
131}
132
133/// What one stylesheet of the rule set reported on a document.
134#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct StylesheetReport {
137    /// The stylesheet, by its name in the bundle.
138    pub name: String,
139    /// The version of the rule set it implements.
140    pub version: String,
141    /// The SHA-256 of the stylesheet that ran.
142    pub sha256: String,
143    /// The SVRL report, exactly as the stylesheet wrote it.
144    pub svrl: String,
145    /// Its failed asserts and successful reports, in report order.
146    pub findings: Vec<Finding>,
147    /// Recoverable conditions the transformation reported (ambiguous rule matches,
148    /// dynamic errors raised while matching a pattern, after which the rule did not
149    /// match), as the reference engine reports them: each distinct message once.
150    pub warnings: Vec<String>,
151    /// The dynamic error that stopped the stylesheet, if it did not finish: then
152    /// `svrl` is empty and there are no findings. This only happens in a report with
153    /// schema errors (see [`Validator::validate_with`](crate::Validator::validate_with)).
154    pub failure: Option<StylesheetFailure>,
155    pub(crate) document_uri: Option<String>,
156}
157
158/// A dynamic error raised by a stylesheet on a document (the reference engine raises it
159/// as well), which stopped the stylesheet.
160#[derive(Debug, Clone, PartialEq, Eq)]
161#[non_exhaustive]
162pub struct StylesheetFailure {
163    /// The XPath or XSLT error code (`FORG0001`, ...).
164    pub code: String,
165    /// The line of the stylesheet instruction, when known.
166    pub line: Option<u32>,
167    /// The explanation.
168    pub message: String,
169}
170
171impl StylesheetReport {
172    /// The SVRL report in the canonical text form of the `einvoice-svrl` crate (version
173    /// 1), in which the document's URI is written `{document}`: the form the expected
174    /// results of the reference engine are stored in.
175    ///
176    /// # Errors
177    ///
178    /// [`Error::Transform`] when the stylesheet did not finish (there is no report);
179    /// [`Error::Internal`] when the report holds something the canonical form cannot
180    /// represent.
181    pub fn canonical_svrl(&self) -> Result<String, Error> {
182        if let Some(failure) = &self.failure {
183            return Err(Error::Transform {
184                stylesheet: self.name.clone(),
185                code: failure.code.clone(),
186                line: failure.line,
187                message: failure.message.clone(),
188            });
189        }
190        let uri = self.document_uri.as_deref();
191        einvoice_svrl::canonicalize(&self.svrl, &|u| Some(u) == uri)
192            .map_err(|e| Error::internal(format!("stylesheet {}: {e}", self.name)))
193    }
194
195    pub(crate) fn new(
196        entry: &crate::StylesheetEntry,
197        svrl: String,
198        warnings: Vec<String>,
199        document_uri: Option<&str>,
200    ) -> Result<Self, Error> {
201        // A stylesheet that does not write SVRL is not a validation stylesheet: the
202        // bundle is wrong.
203        let findings = findings(&svrl).map_err(|m| {
204            Error::bundle(format!(
205                "stylesheet {}: its result is not an SVRL report: {m}",
206                entry.name()
207            ))
208        })?;
209        Ok(Self {
210            name: entry.name().to_owned(),
211            version: entry.version().to_owned(),
212            sha256: entry.sha256().to_owned(),
213            svrl,
214            findings,
215            warnings,
216            failure: None,
217            document_uri: document_uri.map(str::to_owned),
218        })
219    }
220
221    pub(crate) fn failed(
222        entry: &crate::StylesheetEntry,
223        failure: StylesheetFailure,
224        document_uri: Option<&str>,
225    ) -> Self {
226        Self {
227            name: entry.name().to_owned(),
228            version: entry.version().to_owned(),
229            sha256: entry.sha256().to_owned(),
230            svrl: String::new(),
231            findings: Vec::new(),
232            warnings: Vec::new(),
233            failure: Some(failure),
234            document_uri: document_uri.map(str::to_owned),
235        }
236    }
237}
238
239/// The rule set a report was produced with.
240#[derive(Debug, Clone, PartialEq, Eq)]
241#[non_exhaustive]
242pub struct RuleSetVersion {
243    /// Its short name (`cen-ubl`).
244    pub name: String,
245    /// Its title.
246    pub title: String,
247    /// Its version (`1.3.17`).
248    pub version: String,
249    /// The schema the document was validated against, if any.
250    pub schema: Option<crate::SchemaId>,
251}
252
253/// The result of validating one document: the schema errors, then what each stylesheet
254/// of the rule set reported.
255#[derive(Debug, Clone, PartialEq, Eq)]
256#[non_exhaustive]
257pub struct Report {
258    /// The rule set used.
259    pub rule_set: RuleSetVersion,
260    /// The URI the document was given, if any (`document-uri(/)` in the stylesheets).
261    pub document_uri: Option<String>,
262    /// The schema validity errors, sorted by position; empty when the document is valid
263    /// against the schema, or when the rule set has no schema.
264    pub schema_errors: Vec<SchemaError>,
265    /// One report per stylesheet, in the order they ran.
266    pub stylesheets: Vec<StylesheetReport>,
267}
268
269impl Report {
270    /// [`Verdict::Valid`] if there is no schema error and no fatal finding.
271    #[must_use]
272    pub fn verdict(&self) -> Verdict {
273        if self.schema_errors.is_empty() && self.count(Severity::Fatal) == 0 {
274            Verdict::Valid
275        } else {
276            Verdict::Invalid
277        }
278    }
279
280    /// Whether every stylesheet ran to the end (see [`StylesheetReport::failure`]).
281    #[must_use]
282    pub fn is_complete(&self) -> bool {
283        self.stylesheets.iter().all(|s| s.failure.is_none())
284    }
285
286    /// Whether the verdict is [`Verdict::Valid`].
287    #[must_use]
288    pub fn is_valid(&self) -> bool {
289        self.verdict() == Verdict::Valid
290    }
291
292    /// Every finding of every stylesheet, in order.
293    pub fn findings(&self) -> impl Iterator<Item = &Finding> {
294        self.stylesheets.iter().flat_map(|s| s.findings.iter())
295    }
296
297    /// The number of findings with the given severity.
298    #[must_use]
299    pub fn count(&self, severity: Severity) -> usize {
300        self.findings().filter(|f| f.severity == severity).count()
301    }
302}
303
304/// The failed asserts and successful reports of an SVRL report, with the context of the
305/// last fired rule and the id of the last active pattern before each.
306fn findings(svrl: &str) -> Result<Vec<Finding>, String> {
307    let options = ParsingOptions {
308        allow_dtd: false,
309        nodes_limit: u32::MAX,
310        ..ParsingOptions::default()
311    };
312    let doc = roxmltree::Document::parse_with_options(svrl, options).map_err(|e| e.to_string())?;
313    let root = doc.root_element();
314    if !is_svrl(root, "schematron-output") {
315        return Err("the root is not svrl:schematron-output".to_owned());
316    }
317    let mut out = Vec::new();
318    let mut pattern: Option<String> = None;
319    let mut context: Option<String> = None;
320    for child in root.children().filter(Node::is_element) {
321        if child.tag_name().namespace() != Some(SVRL_NS) {
322            continue;
323        }
324        let attribute = |name: &str| child.attribute(name).map(str::to_owned);
325        let kind = match child.tag_name().name() {
326            "active-pattern" => {
327                pattern = attribute("id").or_else(|| attribute("name"));
328                context = None;
329                continue;
330            }
331            "fired-rule" => {
332                context = attribute("context");
333                continue;
334            }
335            "failed-assert" => FindingKind::FailedAssert,
336            "successful-report" => FindingKind::SuccessfulReport,
337            _ => continue,
338        };
339        let text: String = child
340            .children()
341            .filter(|n| is_svrl(*n, "text"))
342            .flat_map(|n| {
343                n.descendants()
344                    .filter(Node::is_text)
345                    .filter_map(|d| d.text())
346            })
347            .collect();
348        let flag = attribute("flag");
349        out.push(Finding {
350            kind,
351            id: attribute("id"),
352            severity: Severity::from_flag(flag.as_deref()),
353            flag,
354            role: attribute("role"),
355            location: attribute("location").unwrap_or_default(),
356            context: context.clone(),
357            pattern: pattern.clone(),
358            test: attribute("test").unwrap_or_default(),
359            text: einvoice_svrl::normalize_space(&text),
360        });
361    }
362    Ok(out)
363}
364
365fn is_svrl(node: Node<'_, '_>, name: &str) -> bool {
366    node.is_element()
367        && node.tag_name().namespace() == Some(SVRL_NS)
368        && node.tag_name().name() == name
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374
375    #[test]
376    fn reads_findings_with_their_rule_and_pattern() {
377        let svrl = r#"<svrl:schematron-output xmlns:svrl="http://purl.oclc.org/dsdl/svrl">
378  <svrl:active-pattern id="P1"/>
379  <svrl:fired-rule context="/a"/>
380  <svrl:failed-assert id="R-1" flag="fatal" location="/a[1]" test="b">
381    <svrl:text>  [R-1] two
382      lines </svrl:text>
383  </svrl:failed-assert>
384  <svrl:active-pattern name="P2"/>
385  <svrl:successful-report id="R-2" flag="warning" role="r" location="/" test="c"><svrl:text/></svrl:successful-report>
386  <svrl:fired-rule context="/z"/>
387  <svrl:failed-assert location="/" test="d"/>
388</svrl:schematron-output>"#;
389        let f = findings(svrl).unwrap();
390        assert_eq!(f.len(), 3);
391        assert_eq!(f[0].kind, FindingKind::FailedAssert);
392        assert_eq!(f[0].id.as_deref(), Some("R-1"));
393        assert_eq!(f[0].severity, Severity::Fatal);
394        assert_eq!(f[0].context.as_deref(), Some("/a"));
395        assert_eq!(f[0].pattern.as_deref(), Some("P1"));
396        assert_eq!(f[0].text, "[R-1] two lines");
397        assert_eq!(f[1].kind, FindingKind::SuccessfulReport);
398        assert_eq!(f[1].severity, Severity::Warning);
399        assert_eq!(f[1].role.as_deref(), Some("r"));
400        assert_eq!(f[1].context, None);
401        assert_eq!(f[1].pattern.as_deref(), Some("P2"));
402        assert_eq!(f[2].severity, Severity::Other);
403        assert_eq!(f[2].id, None);
404        assert_eq!(f[2].context.as_deref(), Some("/z"));
405    }
406
407    #[test]
408    fn refuses_what_is_not_svrl() {
409        assert!(findings("<a/>").is_err());
410        assert!(findings("<a").is_err());
411    }
412
413    #[test]
414    fn severities() {
415        assert_eq!(Severity::from_flag(Some("fatal")), Severity::Fatal);
416        assert_eq!(Severity::from_flag(Some("warning")), Severity::Warning);
417        assert_eq!(Severity::from_flag(Some("information")), Severity::Other);
418        assert_eq!(Severity::from_flag(None), Severity::Other);
419    }
420}