ctb_formats_dcdata/support/
report.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Validation diagnostics, error reporting, and summary collection.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use std::fmt;
30
31/// Severity level of a validation diagnostic.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ValidationSeverity {
34    Error,
35    Warning,
36}
37
38impl fmt::Display for ValidationSeverity {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            Self::Error => write!(f, "ERROR"),
42            Self::Warning => write!(f, "WARNING"),
43        }
44    }
45}
46
47/// A structured diagnostic message emitted during table validation.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct ValidationDiagnostic {
50    pub file_path: String,
51    pub row_number: Option<usize>,
52    pub column_name: Option<String>,
53    pub severity: ValidationSeverity,
54    pub message: String,
55    pub remediation_hint: Option<String>,
56}
57
58impl fmt::Display for ValidationDiagnostic {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        let mut loc = self.file_path.clone();
61        if let Some(row) = self.row_number {
62            loc.push(':');
63            loc.push_str(&row.to_string());
64        }
65        if let Some(col) = &self.column_name {
66            loc.push_str(&format!(" [{col}]"));
67        }
68
69        write!(f, "* [{}] {loc}: {}", self.severity, self.message)?;
70        if let Some(hint) = &self.remediation_hint {
71            write!(f, " (Hint: {hint})")?;
72        }
73        Ok(())
74    }
75}
76
77/// Aggregated report holding diagnostics from table validation passes.
78#[derive(Debug, Default, Clone)]
79pub struct ValidationReport {
80    pub diagnostics: Vec<ValidationDiagnostic>,
81}
82
83impl ValidationReport {
84    pub fn new() -> Self {
85        Self::default()
86    }
87
88    pub fn add_error(
89        &mut self,
90        file_path: &str,
91        row_number: Option<usize>,
92        column_name: Option<&str>,
93        message: impl Into<String>,
94        remediation_hint: Option<&str>,
95    ) {
96        self.diagnostics.push(ValidationDiagnostic {
97            file_path: file_path.to_string(),
98            row_number,
99            column_name: column_name.map(ToString::to_string),
100            severity: ValidationSeverity::Error,
101            message: message.into(),
102            remediation_hint: remediation_hint.map(ToString::to_string),
103        });
104    }
105
106    pub fn add_warning(
107        &mut self,
108        file_path: &str,
109        row_number: Option<usize>,
110        column_name: Option<&str>,
111        message: impl Into<String>,
112        remediation_hint: Option<&str>,
113    ) {
114        self.diagnostics.push(ValidationDiagnostic {
115            file_path: file_path.to_string(),
116            row_number,
117            column_name: column_name.map(ToString::to_string),
118            severity: ValidationSeverity::Warning,
119            message: message.into(),
120            remediation_hint: remediation_hint.map(ToString::to_string),
121        });
122    }
123
124    pub fn has_errors(&self) -> bool {
125        self.diagnostics
126            .iter()
127            .any(|d| d.severity == ValidationSeverity::Error)
128    }
129
130    pub fn has_warnings(&self) -> bool {
131        self.diagnostics
132            .iter()
133            .any(|d| d.severity == ValidationSeverity::Warning)
134    }
135
136    pub fn error_count(&self) -> usize {
137        self.diagnostics
138            .iter()
139            .filter(|d| d.severity == ValidationSeverity::Error)
140            .count()
141    }
142
143    pub fn warning_count(&self) -> usize {
144        self.diagnostics
145            .iter()
146            .filter(|d| d.severity == ValidationSeverity::Warning)
147            .count()
148    }
149
150    pub fn merge(&mut self, other: ValidationReport) {
151        self.diagnostics.extend(other.diagnostics);
152    }
153
154    pub fn format_report(&self) -> String {
155        if self.diagnostics.is_empty() {
156            return "No validation diagnostics.".to_string();
157        }
158
159        let mut lines = Vec::new();
160        lines.push(format!(
161            "Validation completed with {} error(s) and {} warning(s):",
162            self.error_count(),
163            self.warning_count()
164        ));
165        for diag in &self.diagnostics {
166            lines.push(diag.to_string());
167        }
168        lines.join("\n")
169    }
170
171    pub fn ensure_valid(&self) -> Result<()> {
172        if self.has_errors() {
173            bail!("Validation failed:\n{}", self.format_report());
174        }
175        Ok(())
176    }
177}