1use std::fmt;
4
5use roxmltree::{Node, ParsingOptions};
6
7pub use einvoice_xsd::{ErrorKind as SchemaErrorKind, ValidationError as SchemaError};
8
9use crate::Error;
10
11const SVRL_NS: &str = "http://purl.oclc.org/dsdl/svrl";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum Verdict {
17 Valid,
19 Invalid,
21}
22
23impl Verdict {
24 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
43pub enum Severity {
44 Fatal,
47 Warning,
49 Other,
51}
52
53impl Severity {
54 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83pub enum FindingKind {
84 FailedAssert,
86 SuccessfulReport,
88}
89
90impl FindingKind {
91 #[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#[derive(Debug, Clone, PartialEq, Eq)]
109#[non_exhaustive]
110pub struct Finding {
111 pub kind: FindingKind,
113 pub id: Option<String>,
115 pub flag: Option<String>,
117 pub severity: Severity,
119 pub role: Option<String>,
121 pub location: String,
123 pub context: Option<String>,
125 pub pattern: Option<String>,
127 pub test: String,
129 pub text: String,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct StylesheetReport {
137 pub name: String,
139 pub version: String,
141 pub sha256: String,
143 pub svrl: String,
145 pub findings: Vec<Finding>,
147 pub warnings: Vec<String>,
151 pub failure: Option<StylesheetFailure>,
155 pub(crate) document_uri: Option<String>,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
161#[non_exhaustive]
162pub struct StylesheetFailure {
163 pub code: String,
165 pub line: Option<u32>,
167 pub message: String,
169}
170
171impl StylesheetReport {
172 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 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#[derive(Debug, Clone, PartialEq, Eq)]
241#[non_exhaustive]
242pub struct RuleSetVersion {
243 pub name: String,
245 pub title: String,
247 pub version: String,
249 pub schema: Option<crate::SchemaId>,
251}
252
253#[derive(Debug, Clone, PartialEq, Eq)]
256#[non_exhaustive]
257pub struct Report {
258 pub rule_set: RuleSetVersion,
260 pub document_uri: Option<String>,
262 pub schema_errors: Vec<SchemaError>,
265 pub stylesheets: Vec<StylesheetReport>,
267}
268
269impl Report {
270 #[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 #[must_use]
282 pub fn is_complete(&self) -> bool {
283 self.stylesheets.iter().all(|s| s.failure.is_none())
284 }
285
286 #[must_use]
288 pub fn is_valid(&self) -> bool {
289 self.verdict() == Verdict::Valid
290 }
291
292 pub fn findings(&self) -> impl Iterator<Item = &Finding> {
294 self.stylesheets.iter().flat_map(|s| s.findings.iter())
295 }
296
297 #[must_use]
299 pub fn count(&self, severity: Severity) -> usize {
300 self.findings().filter(|f| f.severity == severity).count()
301 }
302}
303
304fn 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}