use std::borrow::Cow;
use std::io::Write;
use indexmap::IndexMap;
use crate::error::{Error, Result};
#[cfg(feature = "xlsx")]
use crate::export::write_workbook;
use crate::export::{build_workbook, collect_tables, render_csv, write_csv as write_csv_tables};
use crate::options::{CsvOptions, RenderOptions, TextOptions, XlsxOptions};
use crate::payload::{Limits, Meta};
use crate::service::{prepare_report, PreparedReport, ReportService};
use crate::text::{sanitize_text, wrap_report_text};
use crate::value::Value;
#[derive(Debug, Clone, Default)]
pub struct ReportBuilder {
meta: IndexMap<String, Value>,
layout: Option<Value>,
data: Option<Value>,
rows: Vec<Value>,
sections: Option<Value>,
extra_sections: Vec<Value>,
limits: Option<Limits>,
}
fn extend_array(value: Option<Value>, extra: Vec<Value>, method: &str, key: &str) -> Result<Option<Value>> {
if extra.is_empty() {
return Ok(value);
}
match value {
None => Ok(Some(Value::Array(extra))),
Some(Value::Array(mut array)) => {
array.extend(extra);
Ok(Some(Value::Array(array)))
}
Some(_) => Err(Error::option(format!(
"{method}() requires the existing {key} value to be an array"
))),
}
}
impl ReportBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.meta.insert("title".to_string(), Value::String(title.into()));
self
}
pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
self.meta.insert("sub_title".to_string(), Value::String(subtitle.into()));
self
}
pub fn company(mut self, company: impl Into<String>) -> Self {
self.meta.insert("company".to_string(), Value::String(company.into()));
self
}
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.meta.insert("locale".to_string(), Value::String(locale.into()));
self
}
pub fn currency(mut self, currency: impl Into<String>) -> Self {
self.meta.insert("currency".to_string(), Value::String(currency.into()));
self
}
pub fn direction(mut self, direction: impl Into<String>) -> Self {
self.meta.insert("direction".to_string(), Value::String(direction.into()));
self
}
pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.meta.insert(key.into(), value.into());
self
}
pub fn layout(mut self, layout: impl Into<Value>) -> Self {
self.layout = Some(layout.into());
self
}
pub fn data(mut self, data: impl Into<Value>) -> Self {
self.data = Some(data.into());
self.rows.clear();
self
}
pub fn row(mut self, row: impl Into<Value>) -> Self {
self.rows.push(row.into());
self
}
pub fn rows<I, T>(mut self, rows: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Value>,
{
self.data = Some(Value::Array(rows.into_iter().map(Into::into).collect()));
self.rows.clear();
self
}
pub fn sections(mut self, sections: impl Into<Value>) -> Self {
self.sections = Some(sections.into());
self.extra_sections.clear();
self
}
pub fn section(mut self, section: impl Into<Value>) -> Self {
self.extra_sections.push(section.into());
self
}
pub fn limits(mut self, limits: Limits) -> Self {
self.limits = Some(limits);
self
}
pub fn build(self) -> Result<Report> {
let data = extend_array(self.data, self.rows, "row", "data")?;
let sections = extend_array(self.sections, self.extra_sections, "section", "sections")?;
let mut payload = IndexMap::new();
if !self.meta.is_empty() {
payload.insert("meta".to_string(), Value::Object(self.meta));
}
if let Some(layout) = self.layout {
payload.insert("layout".to_string(), layout);
}
if let Some(data) = data {
payload.insert("data".to_string(), data);
}
if let Some(sections) = sections {
payload.insert("sections".to_string(), sections);
}
let payload = Value::Object(payload);
let prepared = prepare_report(&payload, self.limits)?;
Ok(Report {
payload,
prepared,
limits: self.limits,
})
}
}
#[derive(Debug, Clone)]
pub struct Report {
payload: Value,
prepared: PreparedReport,
limits: Option<Limits>,
}
impl Report {
pub fn builder() -> ReportBuilder {
ReportBuilder::new()
}
pub fn from_value(payload: Value) -> Result<Self> {
Self::try_from(payload)
}
pub fn from_json(payload: serde_json::Value) -> Result<Self> {
Self::from_value(Value::from_json(payload))
}
pub fn from_toon(text: &str) -> Result<Self> {
Self::from_value(crate::toon::parse_toon(text)?)
}
pub fn from_rows<I, T>(rows: I) -> Result<Self>
where
I: IntoIterator<Item = T>,
T: Into<Value>,
{
Self::builder().rows(rows).build()
}
pub fn payload(&self) -> &Value {
&self.payload
}
pub fn prepared(&self) -> &PreparedReport {
&self.prepared
}
pub fn meta(&self) -> &Meta {
&self.prepared.meta
}
fn prepared_with(&self, limits: Option<Limits>) -> Result<Cow<'_, PreparedReport>> {
let effective = limits.map(|extra| match self.limits {
Some(base) => base.tightened_with(extra),
None => extra,
});
match effective {
Some(limits) => Ok(Cow::Owned(prepare_report(&self.payload, Some(limits))?)),
None => Ok(Cow::Borrowed(&self.prepared)),
}
}
pub fn render_html(&self, options: &RenderOptions) -> Result<String> {
let prepared = self.prepared_with(options.limits)?;
let service = ReportService {
template_dir: options.template_dir.clone(),
template_name: options.template_name.clone(),
inline_css: options.inline_css,
limits: options.limits,
#[cfg(feature = "pdf")]
pdf_options: None,
};
service.render_prepared_html(&prepared)
}
pub fn render_html_default(&self) -> Result<String> {
self.render_html(&RenderOptions::default())
}
pub fn write_csv<W: Write>(&self, mut writer: W, options: CsvOptions) -> Result<()> {
let prepared = self.prepared_with(options.limits)?;
let meta = prepared.meta.to_value();
let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
if options.bom {
writer
.write_all(b"\xef\xbb\xbf")
.map_err(|error| Error::message(format!("CSV write error: {error}")))?;
}
write_csv_tables(&tables, &summaries, Some(&meta), options.delimiter, writer)
}
pub fn export_csv(&self, options: CsvOptions) -> Result<String> {
let mut bytes = Vec::new();
self.write_csv(&mut bytes, options)?;
String::from_utf8(bytes).map_err(|error| Error::message(format!("CSV is not UTF-8: {error}")))
}
pub fn write_text<W: Write>(&self, mut writer: W, options: TextOptions) -> Result<()> {
let prepared = self.prepared_with(options.limits)?;
let meta = prepared.meta.to_value();
let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
let text = render_csv(&tables, &summaries, Some(&meta), ',')?;
let text = if options.sanitize { sanitize_text(&text) } else { text };
writer
.write_all(wrap_report_text(&text).as_bytes())
.map_err(|error| Error::message(format!("Text write error: {error}")))
}
pub fn export_text(&self, options: TextOptions) -> Result<String> {
let mut bytes = Vec::new();
self.write_text(&mut bytes, options)?;
String::from_utf8(bytes).map_err(|error| Error::message(format!("Text is not UTF-8: {error}")))
}
pub fn render_text(&self, sanitize: bool) -> Result<String> {
self.export_text(TextOptions::default().with_sanitize(sanitize))
}
#[cfg(feature = "xlsx")]
pub fn write_xlsx<W: Write + Send>(&self, writer: W, options: XlsxOptions) -> Result<()> {
let prepared = self.prepared_with(options.limits)?;
let meta = prepared.meta.to_value();
let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
write_workbook(&tables, &summaries, Some(&meta), writer)
}
pub fn export_xlsx(&self, options: XlsxOptions) -> Result<Vec<u8>> {
let prepared = self.prepared_with(options.limits)?;
let meta = prepared.meta.to_value();
let (tables, summaries) = collect_tables(&prepared.dataset, &prepared.layout, Some(&meta));
build_workbook(&tables, &summaries, Some(&meta))
}
#[cfg(feature = "pdf")]
pub fn export_pdf(&self, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
self.export_pdf_with(&RenderOptions::default(), options)
}
#[cfg(feature = "pdf")]
pub fn export_pdf_with(&self, render: &RenderOptions, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
let prepared = self.prepared_with(render.limits)?;
let service = ReportService {
template_dir: render.template_dir.clone(),
template_name: render.template_name.clone(),
inline_css: render.inline_css,
limits: render.limits,
pdf_options: Some(options.clone()),
};
service.generate_pdf_prepared(&prepared, options)
}
#[cfg(feature = "pdf")]
pub async fn export_pdf_async(&self, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
self.export_pdf_with_async(&RenderOptions::default(), options).await
}
#[cfg(feature = "pdf")]
pub async fn export_pdf_with_async(&self, render: &RenderOptions, options: &crate::pdf_backend::PdfOptions) -> Result<Vec<u8>> {
let prepared = self.prepared_with(render.limits)?;
let service = ReportService {
template_dir: render.template_dir.clone(),
template_name: render.template_name.clone(),
inline_css: render.inline_css,
limits: render.limits,
pdf_options: Some(options.clone()),
};
service.generate_pdf_prepared_async(&prepared, options).await
}
}
impl TryFrom<Value> for Report {
type Error = crate::error::Error;
fn try_from(payload: Value) -> Result<Self> {
let prepared = prepare_report(&payload, None)?;
Ok(Self {
payload,
prepared,
limits: None,
})
}
}
impl TryFrom<serde_json::Value> for Report {
type Error = crate::error::Error;
fn try_from(payload: serde_json::Value) -> Result<Self> {
Self::from_json(payload)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::payload::Meta;
use serde_json::json;
fn sample() -> ReportBuilder {
Report::builder()
.title("Sales")
.subtitle("Quarterly")
.company("ACME")
.locale("en-US")
.currency("USD")
.layout(json!({
"product": {"label": "Product", "format_mask": "str"},
"total": {"label": "Total", "format_mask": "currency"}
}))
}
#[test]
fn builder_sets_metadata_and_validates() {
let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
assert_eq!(report.meta().title(), Some("Sales"));
assert_eq!(report.meta().sub_title(), Some("Quarterly"));
assert_eq!(report.meta().company(), Some("ACME"));
assert_eq!(report.meta().locale(), "en-US");
assert_eq!(report.meta().currency(), Some("USD"));
assert_eq!(report.meta().direction(), "ltr");
assert_eq!(
report.payload().get("meta").and_then(|m| m.get("title")).and_then(Value::as_str),
Some("Sales")
);
assert!(report.prepared().dataset.get("groups").is_some());
}
#[test]
fn builder_rejects_invalid_payloads() {
assert!(Report::builder().layout(json!("not-an-object")).build().is_err());
assert!(Report::builder().data(json!({"not": "an array"})).build().is_err());
assert!(Report::builder().sections(json!("not-an-array")).build().is_err());
assert!(Report::builder().meta("bogus", 1).build().is_err());
assert!(Report::builder()
.limits(Limits {
max_rows: Some(1),
max_bytes: None
})
.data(json!([{"a": 1}, {"a": 2}]))
.build()
.is_err());
}
#[test]
fn rows_and_sections_append() {
let report = Report::builder()
.title("Rows")
.row(json!({"a": 1}))
.row(json!({"a": 2}))
.build()
.unwrap();
assert_eq!(
report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
Some(2)
);
let report = Report::builder().data(json!([{"b": 0}])).row(json!({"a": 1})).build().unwrap();
assert_eq!(
report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
Some(2)
);
let error = Report::builder()
.data(json!({"template": "summary"}))
.row(json!({"a": 1}))
.build()
.unwrap_err();
assert!(error.to_string().contains("row() requires"));
let rows = vec![json!({"a": 1}), json!({"a": 2})];
let report = Report::from_rows(rows).unwrap();
assert_eq!(report.meta().title(), None);
let report = Report::builder().row(json!({"a": 1})).data(json!([{"b": 2}])).build().unwrap();
assert_eq!(
report.prepared().dataset.get("groups").and_then(Value::as_array).map(Vec::len),
Some(1)
);
let section = json!({"type": "table", "data": [{"a": 1}]});
let report = Report::builder()
.sections(json!([section.clone()]))
.section(json!({"type": "table", "data": [{"a": 2}]}))
.build()
.unwrap();
assert_eq!(
report.prepared().dataset.get("sections").and_then(Value::as_array).map(Vec::len),
Some(2)
);
let error = Report::builder()
.sections(json!({"type": "text", "paragraphs": ["x"]}))
.section(section)
.build()
.unwrap_err();
assert!(error.to_string().contains("section() requires"));
}
#[test]
fn render_and_export_paths() {
let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
let html = report.render_html_default().unwrap();
assert!(html.contains("Sales"));
assert!(html.contains("Pen"));
#[cfg(feature = "email")]
{
let html = report.render_html(&RenderOptions::default().with_inline_css(true)).unwrap();
assert!(html.contains("<style") || html.contains("style="));
}
#[cfg(not(feature = "email"))]
{
let error = report.render_html(&RenderOptions::default().with_inline_css(true)).unwrap_err();
assert!(error.to_string().contains("email"));
}
let csv = report.export_csv(CsvOptions::default()).unwrap();
assert!(csv.contains("Pen"));
let csv = report.export_csv(CsvOptions::new().with_delimiter(';').with_bom(true)).unwrap();
assert!(csv.starts_with('\u{feff}'));
assert!(csv.contains(';'));
let text = report.render_text(true).unwrap();
assert!(text.contains("Pen"));
assert!(report.render_text(false).unwrap().contains("Pen"));
let text = report.export_text(TextOptions::new().with_sanitize(false)).unwrap();
assert!(text.contains("Pen"));
}
#[test]
fn writer_methods_match_export_methods() {
let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
let expected = report.export_csv(CsvOptions::default()).unwrap();
let mut bytes = Vec::new();
report.write_csv(&mut bytes, CsvOptions::default()).unwrap();
assert_eq!(String::from_utf8(bytes).unwrap(), expected);
let options = CsvOptions::new().with_delimiter(';').with_bom(true);
let expected = report.export_csv(options.clone()).unwrap();
let mut bytes = Vec::new();
report.write_csv(&mut bytes, options).unwrap();
assert_eq!(String::from_utf8(bytes).unwrap(), expected);
let expected = report.export_text(TextOptions::default()).unwrap();
let mut bytes = Vec::new();
report.write_text(&mut bytes, TextOptions::default()).unwrap();
assert_eq!(String::from_utf8(bytes).unwrap(), expected);
#[cfg(feature = "xlsx")]
{
let expected = report.export_xlsx(XlsxOptions::default()).unwrap();
let mut bytes = Vec::new();
report.write_xlsx(&mut bytes, XlsxOptions::default()).unwrap();
assert!(expected.starts_with(b"PK"));
assert!(bytes.starts_with(b"PK"));
assert_eq!(bytes.len(), expected.len());
}
}
#[test]
fn export_options_tighten_limits() {
let report = sample()
.data(json!([{"product": "Pen", "total": 12.5}, {"product": "Pencil", "total": 3.0}]))
.build()
.unwrap();
let csv = CsvOptions::new().with_limits(Limits {
max_rows: Some(1),
max_bytes: None,
});
assert!(report.export_csv(csv).is_err());
assert!(report
.export_xlsx(XlsxOptions::new().with_limits(Limits {
max_rows: Some(1),
max_bytes: None
}))
.is_err());
let render = RenderOptions::new().with_limits(Limits {
max_rows: Some(1),
max_bytes: None,
});
assert!(report.render_html(&render).is_err());
assert!(report.render_html(&RenderOptions::default()).is_ok());
assert!(report
.export_text(TextOptions::new().with_limits(Limits {
max_rows: Some(1),
max_bytes: None
}))
.is_err());
}
#[cfg(feature = "xlsx")]
#[test]
fn exports_xlsx_bytes() {
let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
let bytes = report.export_xlsx(XlsxOptions::default()).unwrap();
assert!(bytes.starts_with(b"PK"));
}
#[test]
fn parses_json_value_and_toon() {
let report = Report::from_json(json!({
"meta": {"title": "JSON"},
"data": [{"a": 1}]
}))
.unwrap();
assert_eq!(report.meta().title(), Some("JSON"));
let report = Report::from_value(Value::from_json(json!({
"meta": {"title": "Value"},
"data": [{"a": 1}]
})))
.unwrap();
assert_eq!(report.meta().title(), Some("Value"));
let report = Report::from_toon("meta:\n title: TOON\ndata[1]{a}:\n 1").unwrap();
assert_eq!(report.meta().title(), Some("TOON"));
assert!(Report::try_from(Value::from_json(json!({"bogus": true}))).is_err());
assert!(Report::try_from(json!({"bogus": true})).is_err());
assert!(Report::from_toon("meta: [").is_err());
let text = include_str!("../examples/sales_order.toon");
let report = Report::from_toon(text).unwrap();
assert!(report.meta().title().is_some());
}
#[test]
fn meta_chainable_setters() {
let meta = Meta::new()
.with_title("T")
.with_subtitle("S")
.with_company("C")
.with_locale("pt-BR")
.with_currency("BRL")
.with_direction("rtl")
.with_accent_color("#123456")
.with_source_note("Source")
.with_meta("mode", "summary");
assert_eq!(meta.title(), Some("T"));
assert_eq!(meta.sub_title(), Some("S"));
assert_eq!(meta.company(), Some("C"));
assert_eq!(meta.locale(), "pt-BR");
assert_eq!(meta.currency(), Some("BRL"));
assert_eq!(meta.direction(), "rtl");
assert_eq!(meta.accent_color(), Some("#123456"));
assert_eq!(meta.source_note(), Some("Source"));
assert_eq!(meta.mode(), Some("summary"));
}
#[cfg(feature = "pdf")]
#[test]
#[ignore = "requires a local Chromium/Chrome installation"]
fn exports_real_pdfs() {
let report = sample().data(json!([{"product": "Pen", "total": 12.5}])).build().unwrap();
let options = crate::pdf_backend::PdfOptions::default();
let pdf = report.export_pdf(&options).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let pdf = report
.export_pdf_with(&RenderOptions::default().with_template_name("tabular.jinja"), &options)
.unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let pdf = futures::executor::block_on(report.export_pdf_async(&options)).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let pdf = futures::executor::block_on(report.export_pdf_with_async(&RenderOptions::default(), &options)).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
crate::pdf_backend::shutdown_pdf_pool();
}
}