Skip to main content

isis_report_lib/
report.rs

1//! Typed report builder and one-shot render/export entry points.
2//!
3//! [`Report`] owns a validated payload and the prepared dataset, layout and
4//! metadata produced by the same pipeline used by the free functions and by
5//! [`ReportService`]. The builder is additive sugar: it
6//! does not change payload validation, formatting or export semantics.
7//!
8//! ```
9//! use isis_report_lib::{CsvOptions, RenderOptions, Report};
10//! use serde_json::json;
11//!
12//! let report = Report::builder()
13//!     .title("Sales")
14//!     .locale("en-US")
15//!     .layout(json!({
16//!         "product": {"label": "Product", "format_mask": "str"},
17//!         "total": {"label": "Total", "format_mask": "currency"}
18//!     }))
19//!     .data(json!([{"product": "Pen", "total": 12.5}]))
20//!     .build()?;
21//!
22//! let html = report.render_html(&RenderOptions::default())?;
23//! let csv = report.export_csv(CsvOptions::default())?;
24//! assert!(html.contains("Sales"));
25//! assert!(csv.contains("Pen"));
26//! # Ok::<(), isis_report_lib::Error>(())
27//! ```
28
29use std::borrow::Cow;
30
31use indexmap::IndexMap;
32
33use crate::error::{Error, Result};
34use crate::export::{build_workbook, collect_tables, render_csv};
35use crate::options::{CsvOptions, RenderOptions, TextOptions, XlsxOptions};
36use crate::payload::{Limits, Meta};
37use crate::service::{prepare_report, PreparedReport, ReportService};
38use crate::text::{sanitize_text, wrap_report_text};
39use crate::value::Value;
40
41/// Builder for a validated [`Report`].
42///
43/// Metadata keys follow the payload schema (`title`, `sub_title`, `company`,
44/// `locale`, `currency`, `direction`, ...). `layout`, `data` and `sections`
45/// accept anything that converts into [`Value`], including
46/// `serde_json::Value`, [`Value`] and index maps.
47#[derive(Debug, Clone, Default)]
48pub struct ReportBuilder {
49    meta: IndexMap<String, Value>,
50    layout: Option<Value>,
51    data: Option<Value>,
52    rows: Vec<Value>,
53    sections: Option<Value>,
54    extra_sections: Vec<Value>,
55    limits: Option<Limits>,
56}
57
58fn extend_array(value: Option<Value>, extra: Vec<Value>, method: &str, key: &str) -> Result<Option<Value>> {
59    if extra.is_empty() {
60        return Ok(value);
61    }
62    match value {
63        None => Ok(Some(Value::Array(extra))),
64        Some(Value::Array(mut array)) => {
65            array.extend(extra);
66            Ok(Some(Value::Array(array)))
67        }
68        Some(_) => Err(Error::option(format!(
69            "{method}() requires the existing {key} value to be an array"
70        ))),
71    }
72}
73
74impl ReportBuilder {
75    /// Start an empty builder.
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    /// Set the report title.
81    pub fn title(mut self, title: impl Into<String>) -> Self {
82        self.meta.insert("title".to_string(), Value::String(title.into()));
83        self
84    }
85
86    /// Set the report subtitle (payload key `sub_title`).
87    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
88        self.meta.insert("sub_title".to_string(), Value::String(subtitle.into()));
89        self
90    }
91
92    /// Set the company shown in the header.
93    pub fn company(mut self, company: impl Into<String>) -> Self {
94        self.meta.insert("company".to_string(), Value::String(company.into()));
95        self
96    }
97
98    /// Set the BCP-47 locale used by formatting and localized labels.
99    pub fn locale(mut self, locale: impl Into<String>) -> Self {
100        self.meta.insert("locale".to_string(), Value::String(locale.into()));
101        self
102    }
103
104    /// Set the default currency (ISO-4217 code).
105    pub fn currency(mut self, currency: impl Into<String>) -> Self {
106        self.meta.insert("currency".to_string(), Value::String(currency.into()));
107        self
108    }
109
110    /// Set the text direction (`ltr` or `rtl`).
111    pub fn direction(mut self, direction: impl Into<String>) -> Self {
112        self.meta.insert("direction".to_string(), Value::String(direction.into()));
113        self
114    }
115
116    /// Set any other metadata key accepted by the payload schema.
117    pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
118        self.meta.insert(key.into(), value.into());
119        self
120    }
121
122    /// Replace the hierarchical layout.
123    pub fn layout(mut self, layout: impl Into<Value>) -> Self {
124        self.layout = Some(layout.into());
125        self
126    }
127
128    /// Replace the report data array. Clears any rows queued with [`row`](Self::row).
129    pub fn data(mut self, data: impl Into<Value>) -> Self {
130        self.data = Some(data.into());
131        self.rows.clear();
132        self
133    }
134
135    /// Append one data row.
136    ///
137    /// When `data` was set to a non-array value, [`build`](Self::build) fails
138    /// instead of silently wrapping it in an array.
139    pub fn row(mut self, row: impl Into<Value>) -> Self {
140        self.rows.push(row.into());
141        self
142    }
143
144    /// Replace the data array from an iterator of rows.
145    pub fn rows<I, T>(mut self, rows: I) -> Self
146    where
147        I: IntoIterator<Item = T>,
148        T: Into<Value>,
149    {
150        self.data = Some(Value::Array(rows.into_iter().map(Into::into).collect()));
151        self.rows.clear();
152        self
153    }
154
155    /// Replace the composed `sections` array. Clears sections queued with
156    /// [`section`](Self::section).
157    pub fn sections(mut self, sections: impl Into<Value>) -> Self {
158        self.sections = Some(sections.into());
159        self.extra_sections.clear();
160        self
161    }
162
163    /// Append one composed section.
164    ///
165    /// When `sections` was set to a non-array value, [`build`](Self::build)
166    /// fails instead of silently wrapping it in an array.
167    pub fn section(mut self, section: impl Into<Value>) -> Self {
168        self.extra_sections.push(section.into());
169        self
170    }
171
172    /// Apply operator quotas. Payload `meta.limits` can only tighten them.
173    pub fn limits(mut self, limits: Limits) -> Self {
174        self.limits = Some(limits);
175        self
176    }
177
178    /// Validate the payload and build a [`Report`].
179    ///
180    /// Validation matches [`normalize_payload`](crate::normalize_payload):
181    /// unknown keys, mistyped metadata and non-array `data`/`sections` fail
182    /// here instead of at the first export.
183    pub fn build(self) -> Result<Report> {
184        let data = extend_array(self.data, self.rows, "row", "data")?;
185        let sections = extend_array(self.sections, self.extra_sections, "section", "sections")?;
186        let mut payload = IndexMap::new();
187        if !self.meta.is_empty() {
188            payload.insert("meta".to_string(), Value::Object(self.meta));
189        }
190        if let Some(layout) = self.layout {
191            payload.insert("layout".to_string(), layout);
192        }
193        if let Some(data) = data {
194            payload.insert("data".to_string(), data);
195        }
196        if let Some(sections) = sections {
197            payload.insert("sections".to_string(), sections);
198        }
199        let payload = Value::Object(payload);
200        let prepared = prepare_report(&payload, self.limits)?;
201        Ok(Report {
202            payload,
203            prepared,
204            limits: self.limits,
205        })
206    }
207}
208
209/// A validated report payload with its prepared dataset, layout and metadata.
210///
211/// Exports reuse the prepared report built by [`Report::builder`] or
212/// [`Report::try_from`]. Options that carry explicit limits re-run the payload
213/// checks with the tighter caps before exporting.
214#[derive(Debug, Clone)]
215pub struct Report {
216    payload: Value,
217    prepared: PreparedReport,
218    limits: Option<Limits>,
219}
220
221impl Report {
222    /// Start a builder.
223    pub fn builder() -> ReportBuilder {
224        ReportBuilder::new()
225    }
226
227    /// Validate an existing payload.
228    pub fn from_value(payload: Value) -> Result<Self> {
229        Self::try_from(payload)
230    }
231
232    /// Validate a JSON payload.
233    pub fn from_json(payload: serde_json::Value) -> Result<Self> {
234        Self::from_value(Value::from_json(payload))
235    }
236
237    /// Parse and validate a `.toon` payload.
238    pub fn from_toon(text: &str) -> Result<Self> {
239        Self::from_value(crate::toon::parse_toon(text)?)
240    }
241
242    /// Build a report from an iterator of rows, inferring the layout.
243    pub fn from_rows<I, T>(rows: I) -> Result<Self>
244    where
245        I: IntoIterator<Item = T>,
246        T: Into<Value>,
247    {
248        Self::builder().rows(rows).build()
249    }
250
251    /// The validated payload.
252    pub fn payload(&self) -> &Value {
253        &self.payload
254    }
255
256    /// The prepared dataset, layout and metadata.
257    pub fn prepared(&self) -> &PreparedReport {
258        &self.prepared
259    }
260
261    /// The normalized metadata (including generated defaults).
262    pub fn meta(&self) -> &Meta {
263        &self.prepared.meta
264    }
265
266    fn prepared_with(&self, limits: Option<Limits>) -> Result<Cow<'_, PreparedReport>> {
267        let effective = limits.map(|extra| match self.limits {
268            Some(base) => base.tightened_with(extra),
269            None => extra,
270        });
271        match effective {
272            Some(limits) => Ok(Cow::Owned(prepare_report(&self.payload, Some(limits))?)),
273            None => Ok(Cow::Borrowed(&self.prepared)),
274        }
275    }
276
277    /// Render the HTML output with explicit options.
278    pub fn render_html(&self, options: &RenderOptions) -> Result<String> {
279        let prepared = self.prepared_with(options.limits)?;
280        let service = ReportService {
281            template_dir: options.template_dir.clone(),
282            template_name: options.template_name.clone(),
283            inline_css: options.inline_css,
284            limits: options.limits,
285            #[cfg(feature = "pdf")]
286            pdf_options: None,
287        };
288        service.render_prepared_html(&prepared)
289    }
290
291    /// Render the HTML output with default options.
292    pub fn render_html_default(&self) -> Result<String> {
293        self.render_html(&RenderOptions::default())
294    }
295
296    /// Export CSV with explicit options.
297    pub fn export_csv(&self, options: CsvOptions) -> Result<String> {
298        let prepared = self.prepared_with(options.limits)?;
299        let meta = prepared.meta.to_value();
300        let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
301        let text = render_csv(&tables, &summaries, Some(&meta), options.delimiter)?;
302        Ok(if options.bom { format!("\u{feff}{text}") } else { text })
303    }
304
305    /// Render the visible-only plain-text export with explicit options.
306    pub fn export_text(&self, options: TextOptions) -> Result<String> {
307        let prepared = self.prepared_with(options.limits)?;
308        let meta = prepared.meta.to_value();
309        let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
310        let text = render_csv(&tables, &summaries, Some(&meta), ',')?;
311        let text = if options.sanitize { sanitize_text(&text) } else { text };
312        Ok(wrap_report_text(&text))
313    }
314
315    /// Shortcut for [`export_text`](Self::export_text) with default options and
316    /// an explicit sanitize flag.
317    pub fn render_text(&self, sanitize: bool) -> Result<String> {
318        self.export_text(TextOptions::default().with_sanitize(sanitize))
319    }
320
321    /// Export an `.xlsx` workbook with explicit options.
322    pub fn export_xlsx(&self, options: XlsxOptions) -> Result<Vec<u8>> {
323        let prepared = self.prepared_with(options.limits)?;
324        let meta = prepared.meta.to_value();
325        let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
326        build_workbook(&tables, &summaries, Some(&meta))
327    }
328
329    /// Generate a PDF with default HTML render options. Requires the `pdf`
330    /// feature and a Chromium/Chrome installation.
331    #[cfg(feature = "pdf")]
332    pub fn export_pdf(&self, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
333        self.export_pdf_with(&RenderOptions::default(), options)
334    }
335
336    /// Generate a PDF with explicit HTML and PDF options.
337    #[cfg(feature = "pdf")]
338    pub fn export_pdf_with(&self, render: &RenderOptions, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
339        let prepared = self.prepared_with(render.limits)?;
340        let service = ReportService {
341            template_dir: render.template_dir.clone(),
342            template_name: render.template_name.clone(),
343            inline_css: render.inline_css,
344            limits: render.limits,
345            pdf_options: Some(options.clone()),
346        };
347        service.generate_pdf_prepared(&prepared, options)
348    }
349
350    /// Generate a PDF asynchronously with default HTML render options.
351    #[cfg(feature = "pdf")]
352    pub async fn export_pdf_async(&self, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
353        self.export_pdf_with_async(&RenderOptions::default(), options).await
354    }
355
356    /// Generate a PDF asynchronously with explicit HTML and PDF options.
357    #[cfg(feature = "pdf")]
358    pub async fn export_pdf_with_async(&self, render: &RenderOptions, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
359        let prepared = self.prepared_with(render.limits)?;
360        let service = ReportService {
361            template_dir: render.template_dir.clone(),
362            template_name: render.template_name.clone(),
363            inline_css: render.inline_css,
364            limits: render.limits,
365            pdf_options: Some(options.clone()),
366        };
367        service.generate_pdf_prepared_async(&prepared, options).await
368    }
369}
370
371impl TryFrom<Value> for Report {
372    type Error = crate::error::Error;
373
374    fn try_from(payload: Value) -> Result<Self> {
375        let prepared = prepare_report(&payload, None)?;
376        Ok(Self {
377            payload,
378            prepared,
379            limits: None,
380        })
381    }
382}
383
384impl TryFrom<serde_json::Value> for Report {
385    type Error = crate::error::Error;
386
387    fn try_from(payload: serde_json::Value) -> Result<Self> {
388        Self::from_json(payload)
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::payload::Meta;
396    use serde_json::json;
397
398    fn sample() -> ReportBuilder {
399        Report::builder()
400            .title("Sales")
401            .subtitle("Quarterly")
402            .company("ACME")
403            .locale("en-US")
404            .currency("USD")
405            .layout(json!({
406                "product": {"label": "Product", "format_mask": "str"},
407                "total": {"label": "Total", "format_mask": "currency"}
408            }))
409    }
410
411    #[test]
412    fn builder_sets_metadata_and_validates() {
413        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
414
415        assert_eq!(report.meta().title(), Some("Sales"));
416        assert_eq!(report.meta().sub_title(), Some("Quarterly"));
417        assert_eq!(report.meta().company(), Some("ACME"));
418        assert_eq!(report.meta().locale(), "en-US");
419        assert_eq!(report.meta().currency(), Some("USD"));
420        assert_eq!(report.meta().direction(), "ltr");
421        assert_eq!(
422            report.payload().get("meta").and_then(|m| m.get("title")).and_then(Value::as_str),
423            Some("Sales")
424        );
425        assert!(report.prepared().dataset.get("groups").is_some());
426    }
427
428    #[test]
429    fn builder_rejects_invalid_payloads() {
430        assert!(Report::builder().layout(json!("not-an-object")).build().is_err());
431        assert!(Report::builder().data(json!({"not": "an array"})).build().is_err());
432        assert!(Report::builder().sections(json!("not-an-array")).build().is_err());
433        assert!(Report::builder().meta("bogus", 1).build().is_err());
434        assert!(Report::builder()
435            .limits(Limits {
436                max_rows: Some(1),
437                max_bytes: None
438            })
439            .data(json!([{"a": 1}, {"a": 2}]))
440            .build()
441            .is_err());
442    }
443
444    #[test]
445    fn rows_and_sections_append() {
446        let report = Report::builder()
447            .title("Rows")
448            .row(json!({"a": 1}))
449            .row(json!({"a": 2}))
450            .build()
451            .unwrap();
452        assert_eq!(
453            report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
454            Some(2)
455        );
456
457        let report = Report::builder().data(json!([{"b": 0}])).row(json!({"a": 1})).build().unwrap();
458        assert_eq!(
459            report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
460            Some(2)
461        );
462
463        let error = Report::builder()
464            .data(json!({"template": "summary"}))
465            .row(json!({"a": 1}))
466            .build()
467            .unwrap_err();
468        assert!(error.to_string().contains("row() requires"));
469
470        let rows = vec![json!({"a": 1}), json!({"a": 2})];
471        let report = Report::from_rows(rows).unwrap();
472        assert_eq!(report.meta().title(), None);
473
474        // `data()` replaces rows queued earlier.
475        let report = Report::builder().row(json!({"a": 1})).data(json!([{"b": 2}])).build().unwrap();
476        assert_eq!(
477            report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
478            Some(1)
479        );
480
481        let section = json!({"type": "table", "data": [{"a": 1}]});
482        let report = Report::builder()
483            .sections(json!([section.clone()]))
484            .section(json!({"type": "table", "data": [{"a": 2}]}))
485            .build()
486            .unwrap();
487        assert_eq!(
488            report.prepared().dataset.get("sections").and_then(Value::as_array).map(Vec::len),
489            Some(2)
490        );
491
492        let error = Report::builder()
493            .sections(json!({"type": "text", "paragraphs": ["x"]}))
494            .section(section)
495            .build()
496            .unwrap_err();
497        assert!(error.to_string().contains("section() requires"));
498    }
499
500    #[test]
501    fn render_and_export_paths() {
502        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
503
504        let html = report.render_html_default().unwrap();
505        assert!(html.contains("Sales"));
506        assert!(html.contains("Pen"));
507
508        #[cfg(feature = "email")]
509        {
510            let html = report.render_html(&RenderOptions::default().with_inline_css(true)).unwrap();
511            assert!(html.contains("<style") || html.contains("style="));
512        }
513        #[cfg(not(feature = "email"))]
514        {
515            let error = report.render_html(&RenderOptions::default().with_inline_css(true)).unwrap_err();
516            assert!(error.to_string().contains("email"));
517        }
518
519        let csv = report.export_csv(CsvOptions::default()).unwrap();
520        assert!(csv.contains("Pen"));
521        let csv = report.export_csv(CsvOptions::new().with_delimiter(';').with_bom(true)).unwrap();
522        assert!(csv.starts_with('\u{feff}'));
523        assert!(csv.contains(';'));
524
525        let text = report.render_text(true).unwrap();
526        assert!(text.contains("Pen"));
527        assert!(report.render_text(false).unwrap().contains("Pen"));
528        let text = report.export_text(TextOptions::new().with_sanitize(false)).unwrap();
529        assert!(text.contains("Pen"));
530    }
531
532    #[test]
533    fn export_options_tighten_limits() {
534        let report = sample()
535            .data(json!([{"product": "Pen", "total": 12.5}, {"product": "Pencil", "total": 3.0}]))
536            .build()
537            .unwrap();
538
539        let csv = CsvOptions::new().with_limits(Limits {
540            max_rows: Some(1),
541            max_bytes: None,
542        });
543        assert!(report.export_csv(csv).is_err());
544        assert!(report
545            .export_xlsx(XlsxOptions::new().with_limits(Limits {
546                max_rows: Some(1),
547                max_bytes: None
548            }))
549            .is_err());
550
551        let render = RenderOptions::new().with_limits(Limits {
552            max_rows: Some(1),
553            max_bytes: None,
554        });
555        assert!(report.render_html(&render).is_err());
556        assert!(report.render_html(&RenderOptions::default()).is_ok());
557        assert!(report
558            .export_text(TextOptions::new().with_limits(Limits {
559                max_rows: Some(1),
560                max_bytes: None
561            }))
562            .is_err());
563    }
564
565    #[cfg(feature = "xlsx")]
566    #[test]
567    fn exports_xlsx_bytes() {
568        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
569        let bytes = report.export_xlsx(XlsxOptions::default()).unwrap();
570        assert!(bytes.starts_with(b"PK"));
571    }
572
573    #[test]
574    fn parses_json_value_and_toon() {
575        let report = Report::from_json(json!({
576            "meta": {"title": "JSON"},
577            "data": [{"a": 1}]
578        }))
579        .unwrap();
580        assert_eq!(report.meta().title(), Some("JSON"));
581
582        let report = Report::from_value(Value::from_json(json!({
583            "meta": {"title": "Value"},
584            "data": [{"a": 1}]
585        })))
586        .unwrap();
587        assert_eq!(report.meta().title(), Some("Value"));
588
589        let report = Report::from_toon("meta:\n  title: TOON\ndata[1]{a}:\n  1").unwrap();
590        assert_eq!(report.meta().title(), Some("TOON"));
591
592        assert!(Report::try_from(Value::from_json(json!({"bogus": true}))).is_err());
593        assert!(Report::try_from(json!({"bogus": true})).is_err());
594        assert!(Report::from_toon("meta: [").is_err());
595
596        let text = include_str!("../examples/sales_order.toon");
597        let report = Report::from_toon(text).unwrap();
598        assert!(report.meta().title().is_some());
599    }
600
601    #[test]
602    fn meta_chainable_setters() {
603        let meta = Meta::new()
604            .with_title("T")
605            .with_subtitle("S")
606            .with_company("C")
607            .with_locale("pt-BR")
608            .with_currency("BRL")
609            .with_direction("rtl")
610            .with_accent_color("#123456")
611            .with_source_note("Source")
612            .with_meta("mode", "summary");
613        assert_eq!(meta.title(), Some("T"));
614        assert_eq!(meta.sub_title(), Some("S"));
615        assert_eq!(meta.company(), Some("C"));
616        assert_eq!(meta.locale(), "pt-BR");
617        assert_eq!(meta.currency(), Some("BRL"));
618        assert_eq!(meta.direction(), "rtl");
619        assert_eq!(meta.accent_color(), Some("#123456"));
620        assert_eq!(meta.source_note(), Some("Source"));
621        assert_eq!(meta.mode(), Some("summary"));
622    }
623
624    #[cfg(feature = "pdf")]
625    #[test]
626    #[ignore = "requires a local Chromium/Chrome installation"]
627    fn exports_real_pdfs() {
628        let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
629        let options = crate::pdf_backend::PdfOptions::default();
630
631        let pdf = report.export_pdf(&options).unwrap();
632        assert!(pdf.starts_with(b"%PDF-"));
633
634        let pdf = report
635            .export_pdf_with(&RenderOptions::default().with_template_name("tabular.jinja"), &options)
636            .unwrap();
637        assert!(pdf.starts_with(b"%PDF-"));
638
639        let pdf = futures::executor::block_on(report.export_pdf_async(&options)).unwrap();
640        assert!(pdf.starts_with(b"%PDF-"));
641
642        let pdf = futures::executor::block_on(report.export_pdf_with_async(&RenderOptions::default(), &options)).unwrap();
643        assert!(pdf.starts_with(b"%PDF-"));
644        crate::pdf_backend::shutdown_pdf_pool();
645    }
646}