use std::path::{Path, PathBuf};
use indexmap::IndexMap;
use crate::charts::build_chart;
use crate::crosstab::{build_crosstab, Crosstab};
use crate::error::{Error, Result};
use crate::formatting::normalize_footnote;
use crate::layout::{assign_report_footnotes, build_report, collect_footnotes, infer_layout, is_template_format, template_header_layout};
use crate::media::normalize_image_src;
use crate::payload::{normalize_payload, Limits, Meta, Payload};
use crate::pyops;
use crate::rendering::render_report_html;
use crate::value::Value;
#[cfg(feature = "pdf")]
use crate::pdf_backend::{Margins, PageFormat, PdfBackend, PdfOptions};
#[derive(Debug, Clone)]
pub struct PreparedReport {
pub dataset: Value,
pub layout: Value,
pub meta: Meta,
}
fn footnotes_value(footnotes: &[(String, String)]) -> Value {
Value::Array(
footnotes
.iter()
.map(|(mark, text)| Value::Array(vec![Value::String(mark.clone()), Value::String(text.clone())]))
.collect(),
)
}
fn section_source(section: &IndexMap<String, Value>) -> Result<String> {
match section.get("source") {
None | Some(Value::Null) => Ok(String::new()),
Some(Value::String(source)) if source.is_empty() => Ok(String::new()),
Some(Value::String(source)) => Ok(source.clone()),
Some(_) => Err(Error::option("Invalid section source (must be a string)")),
}
}
fn crosstab_footnotes(crosstab: &Value) -> Vec<(String, String)> {
let mut found = Vec::new();
let mut seen = std::collections::HashSet::new();
let Some(crosstab) = crosstab.as_object() else {
return found;
};
for key in ["row_field", "col_field", "measure_field"] {
let Some(note) = crosstab.get(key).and_then(|field| field.get("footnote")).and_then(Value::as_object) else {
continue;
};
let Some(mark) = note.get("mark").and_then(Value::as_str) else {
continue;
};
if mark.is_empty() || !seen.insert(mark.to_string()) {
continue;
}
found.push((
mark.to_string(),
note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
));
}
found
}
fn item_footnotes(items: &[Value]) -> Vec<(String, String)> {
let mut found = Vec::new();
let mut seen = std::collections::HashSet::new();
for item in items {
let Some(note) = item.get("footnote").and_then(Value::as_object) else {
continue;
};
let Some(mark) = note.get("mark").and_then(Value::as_str) else {
continue;
};
if mark.is_empty() || !seen.insert(mark.to_string()) {
continue;
}
found.push((
mark.to_string(),
note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
));
}
found
}
#[cfg(feature = "pdf")]
fn margin_value(value: Option<&Value>, default: &str) -> Result<String> {
match value {
None | Some(Value::Null) => Ok(default.to_string()),
Some(Value::String(value)) if !value.trim().is_empty() => Ok(value.clone()),
Some(Value::Int(value)) if *value >= 0 => Ok(format!("{value}in")),
Some(Value::UInt(value)) => Ok(format!("{value}in")),
Some(Value::Float(value)) if *value >= 0.0 => Ok(format!("{value}in")),
Some(_) => Err(Error::option("Invalid page margin (expected a positive CSS length)")),
}
}
fn prepare_sections(sections: &[IndexMap<String, Value>], _meta: &Meta) -> Result<(Value, Value)> {
let mut built: Vec<Value> = Vec::new();
for section in sections {
let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table");
if matches!(section_type, "table" | "crosstab") {
match section.get("data") {
None | Some(Value::Null) => {}
Some(Value::Array(_)) => {}
Some(_) => {
return Err(Error::option(format!(
"Invalid {section_type} section data (must be a list of records)"
)))
}
}
}
match section_type {
"table" => {
let data = section.get("data").and_then(Value::as_array).cloned().unwrap_or_default();
let layout_raw = match section.get("layout") {
None | Some(Value::Null) => IndexMap::new(),
Some(Value::Object(object)) => object.clone(),
Some(_) => return Err(Error::option("Invalid table section layout (must be an object)")),
};
let (dataset, layout) = build_report(&data, &layout_raw)?;
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("table".to_string()));
entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
entry.insert("dataset".to_string(), dataset);
entry.insert("layout".to_string(), layout);
if let Some(empty_text) = section.get("empty_text").and_then(Value::as_str) {
if !empty_text.is_empty() {
entry.insert("empty_text".to_string(), Value::String(empty_text.to_string()));
}
}
built.push(Value::Object(entry));
}
"text" => {
let paragraphs = match section.get("paragraphs") {
Some(value) => value.clone(),
None => match section.get("body") {
Some(body) if !body.is_null() => Value::Array(vec![body.clone()]),
_ => Value::Array(Vec::new()),
},
};
let Some(paragraphs) = paragraphs.as_array() else {
return Err(Error::option("Invalid text section (need paragraphs: [...])"));
};
if !paragraphs.iter().all(Value::is_string) {
return Err(Error::option("Invalid text section (need paragraphs: [...])"));
}
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("text".to_string()));
entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
entry.insert("paragraphs".to_string(), Value::Array(paragraphs.clone()));
built.push(Value::Object(entry));
}
"kpi" => {
let Some(raw_items) = section.get("items").and_then(Value::as_array) else {
return Err(Error::option("Invalid kpi section (need items: [...])"));
};
let mut items = Vec::new();
for (index, raw) in raw_items.iter().enumerate() {
let Some(raw) = raw.as_object() else {
return Err(Error::option("Invalid kpi item (need at least a label)"));
};
if !raw.contains_key("label") {
return Err(Error::option("Invalid kpi item (need at least a label)"));
}
let mut item = raw.clone();
if let Some(note) = item.get("footnote").cloned() {
let note = normalize_footnote(¬e, &format!("kpi item {}", index + 1))?;
item.insert("footnote".to_string(), note.to_value());
}
items.push(Value::Object(item));
}
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("kpi".to_string()));
entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
entry.insert("items".to_string(), Value::Array(items));
built.push(Value::Object(entry));
}
"chart" => {
let chart_spec = match section.get("chart") {
Some(Value::Object(object)) => object.clone(),
_ => IndexMap::new(),
};
let svg = build_chart(&chart_spec)?;
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("chart".to_string()));
let title = section
.get("title")
.filter(|value| value.truthy())
.or_else(|| chart_spec.get("title"))
.cloned()
.unwrap_or(Value::Null);
entry.insert("title".to_string(), title);
entry.insert("svg".to_string(), Value::String(svg));
entry.insert("chart".to_string(), Value::Object(chart_spec));
built.push(Value::Object(entry));
}
"crosstab" => {
let spec = Value::Object(section.clone());
let crosstab = build_crosstab(
section.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]),
&spec,
)?;
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("crosstab".to_string()));
entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
entry.insert("crosstab".to_string(), crosstab.to_value());
built.push(Value::Object(entry));
}
"image" => {
let src = normalize_image_src(section.get("src").unwrap_or(&Value::Null), "image section src")?;
let alt = match section.get("alt") {
None | Some(Value::Null) => String::new(),
Some(Value::String(alt)) => alt.clone(),
Some(_) => return Err(Error::option("Invalid image section alt (must be a string)")),
};
let caption = match section.get("caption") {
None | Some(Value::Null) => String::new(),
Some(Value::String(caption)) => caption.clone(),
Some(_) => return Err(Error::option("Invalid image section caption (must be a string)")),
};
let width = match section.get("width") {
None | Some(Value::Null) => None,
Some(Value::Int(width)) if (16..=1600).contains(width) => Some(*width),
Some(Value::UInt(width)) if (16..=1600).contains(width) => Some(*width as i64),
Some(_) => return Err(Error::option("Invalid image section width (must be an integer 16..1600)")),
};
let align = section.get("align").and_then(Value::as_str).unwrap_or("center");
if !matches!(align, "left" | "center" | "right") {
return Err(Error::option("Invalid image section align (expected left|center|right)"));
}
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("image".to_string()));
entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
entry.insert("src".to_string(), Value::String(src));
entry.insert("alt".to_string(), Value::String(alt));
entry.insert("caption".to_string(), Value::String(caption));
entry.insert("width".to_string(), width.map(Value::Int).unwrap_or(Value::Null));
entry.insert("align".to_string(), Value::String(align.to_string()));
built.push(Value::Object(entry));
}
"toc" => {
let mut entry = IndexMap::new();
entry.insert("type".to_string(), Value::String("toc".to_string()));
entry.insert("title".to_string(), section.get("title").cloned().unwrap_or(Value::Null));
entry.insert("items".to_string(), Value::Array(Vec::new()));
built.push(Value::Object(entry));
}
other => {
let _ = other;
return Err(Error::option(
"Unknown section type (expected table|text|kpi|chart|crosstab|image|toc)",
));
}
}
}
let mut anchors: Vec<Value> = Vec::new();
let mut anchor_index = 0usize;
for entry in &mut built {
let Some(entry) = entry.as_object_mut() else {
continue;
};
let has_title = entry.get("title").is_some_and(Value::truthy);
let is_toc = entry.get("type").and_then(Value::as_str) == Some("toc");
if has_title && !is_toc {
anchor_index += 1;
let anchor = format!("section-{anchor_index}");
entry.insert("anchor".to_string(), Value::String(anchor.clone()));
let mut item = IndexMap::new();
item.insert("title".to_string(), entry.get("title").cloned().unwrap_or(Value::Null));
item.insert("anchor".to_string(), Value::String(anchor));
anchors.push(Value::Object(item));
}
}
for entry in &mut built {
let Some(entry) = entry.as_object_mut() else {
continue;
};
if entry.get("type").and_then(Value::as_str) == Some("toc") {
entry.insert("items".to_string(), Value::Array(anchors.clone()));
}
}
for (entry, section) in built.iter_mut().zip(sections) {
let source = section_source(section)?;
if !source.is_empty() {
if let Some(object) = entry.as_object_mut() {
object.insert("source".to_string(), Value::String(source));
}
}
}
let mut layout_object = IndexMap::new();
let mut header = IndexMap::new();
header.insert("header".to_string(), Value::Array(Vec::new()));
layout_object.insert("groups".to_string(), Value::Object(header));
let mut layout = Value::Object(layout_object);
assign_report_footnotes(&mut layout, Some(&mut built))?;
for section in &mut built {
let Some(object) = section.as_object_mut() else {
continue;
};
let section_type = object.get("type").and_then(Value::as_str).unwrap_or("table").to_string();
let footnotes = match section_type.as_str() {
"table" => object.get("layout").map(collect_footnotes).unwrap_or_default(),
"crosstab" => object.get("crosstab").map(crosstab_footnotes).unwrap_or_default(),
"kpi" => object
.get("items")
.and_then(Value::as_array)
.map(|items| item_footnotes(items))
.unwrap_or_default(),
_ => Vec::new(),
};
object.insert("footnotes".to_string(), footnotes_value(&footnotes));
}
let mut dataset = IndexMap::new();
dataset.insert("sections".to_string(), Value::Array(built));
Ok((Value::Object(dataset), layout))
}
pub fn prepare_report(payload: &Value, operator_limits: Option<Limits>) -> Result<PreparedReport> {
let payload: Payload = normalize_payload(payload, operator_limits)?;
if let Some(sections) = &payload.sections {
let (dataset, layout) = prepare_sections(sections, &payload.meta)?;
return Ok(PreparedReport {
dataset,
layout,
meta: payload.meta,
});
}
let data = &payload.data;
let layout_raw = payload.layout.as_ref().filter(|layout| !layout.is_empty());
let (mut dataset, mut layout) = if let Some(layout_raw) = layout_raw {
build_report(data, layout_raw)?
} else if is_template_format(data) {
let layout = template_header_layout(data)?;
let mut dataset = IndexMap::new();
dataset.insert("groups".to_string(), Value::Array(data.clone()));
dataset.insert("summary".to_string(), Value::Null);
(Value::Object(dataset), layout)
} else {
let layout = infer_layout(data);
let groups: Vec<Value> = data
.iter()
.map(|row| {
let mut fields = IndexMap::new();
if let Some(object) = row.as_object() {
for (key, value) in object {
fields.insert(key.clone(), value.clone());
}
} else {
fields.insert("value".to_string(), row.clone());
}
let mut item = IndexMap::new();
item.insert("fields".to_string(), Value::Object(fields));
Value::Object(item)
})
.collect();
let mut dataset = IndexMap::new();
dataset.insert("groups".to_string(), Value::Array(groups));
dataset.insert("summary".to_string(), Value::Null);
(Value::Object(dataset), layout)
};
assign_report_footnotes(&mut layout, None)?;
let footnotes = collect_footnotes(&layout);
if let Some(object) = layout.as_object_mut() {
object.insert("footnotes".to_string(), footnotes_value(&footnotes));
}
if let Some(object) = dataset.as_object_mut() {
object.entry("summary".to_string()).or_insert(Value::Null);
}
Ok(PreparedReport {
dataset,
layout,
meta: payload.meta,
})
}
#[derive(Debug, Clone)]
pub struct ReportService {
pub template_dir: Option<PathBuf>,
pub template_name: String,
pub inline_css: bool,
pub limits: Option<Limits>,
#[cfg(feature = "pdf")]
pub pdf_options: Option<PdfOptions>,
}
impl Default for ReportService {
fn default() -> Self {
Self {
template_dir: None,
template_name: "tabular.jinja".to_string(),
inline_css: false,
limits: None,
#[cfg(feature = "pdf")]
pdf_options: None,
}
}
}
impl ReportService {
pub fn new() -> Self {
Self::default()
}
pub fn with_template_dir(mut self, directory: impl Into<PathBuf>) -> Self {
self.template_dir = Some(directory.into());
self
}
pub fn with_template_name(mut self, name: impl Into<String>) -> Self {
self.template_name = name.into();
self
}
pub fn with_inline_css(mut self, inline_css: bool) -> Self {
self.inline_css = inline_css;
self
}
pub fn with_limits(mut self, limits: Limits) -> Self {
self.limits = Some(limits);
self
}
#[cfg(feature = "pdf")]
pub fn with_pdf_options(mut self, options: PdfOptions) -> Self {
self.pdf_options = Some(options);
self
}
#[cfg(feature = "pdf")]
pub fn resolve_pdf_options(&self, meta: &Meta) -> Result<PdfOptions> {
let mut options = PdfOptions {
outline: true,
..PdfOptions::default()
};
if let Some(page) = meta.page() {
if let Some(size) = page.get("size") {
let size = size
.as_str()
.ok_or_else(|| Error::option("Invalid page size (must be a string such as A4)"))?;
options.format = size.parse::<PageFormat>().map_err(|error| Error::option(error.to_string()))?;
}
match page.get("orientation").and_then(Value::as_str) {
None | Some("portrait") => {}
Some("landscape") => options.landscape = true,
Some(_) => return Err(Error::option("Invalid page orientation (expected portrait|landscape)")),
}
if let Some(margins) = page.get("margins") {
let margins = margins
.as_object()
.ok_or_else(|| Error::option("Invalid page margins (must be an object)"))?;
options.margin = Margins {
top: margin_value(margins.get("top"), ".15in")?,
bottom: margin_value(margins.get("bottom"), ".4in")?,
left: margin_value(margins.get("left"), ".15in")?,
right: margin_value(margins.get("right"), ".15in")?,
};
}
}
if let Some(explicit) = &self.pdf_options {
options = explicit.clone();
}
if options.backend != PdfBackend::ExternalWeasyPrint && options.display_header_footer && options.footer_template.is_none() {
options.footer_template = Some(crate::pdf_backend::default_footer(
meta.printed_at_text().as_deref(),
&meta.locale(),
));
}
if options.backend == PdfBackend::ExternalWeasyPrint && options.header_template.is_none() && options.footer_template.is_none() {
options.display_header_footer = false;
}
Ok(options)
}
pub fn render_prepared_html(&self, prepared: &PreparedReport) -> Result<String> {
let mut template_name = self.template_name.clone();
if prepared.dataset.get("sections").is_some() && template_name == "tabular.jinja" {
template_name = "sections.jinja".to_string();
}
render_report_html(
&prepared.dataset,
&prepared.layout,
&prepared.meta.to_value(),
&template_name,
self.template_dir.as_deref(),
self.inline_css,
)
}
#[cfg(feature = "pdf")]
pub fn generate_pdf(&self, payload: &Value) -> Result<Vec<u8>> {
let prepared = self.prepare(payload)?;
let options = self.resolve_pdf_options(&prepared.meta)?;
self.generate_pdf_prepared(&prepared, &options)
}
#[cfg(feature = "pdf")]
pub fn generate_pdf_prepared(&self, prepared: &PreparedReport, options: &PdfOptions) -> Result<Vec<u8>> {
let html = self.render_prepared_html(prepared)?;
let options = options.clone();
let outcome = std::thread::spawn(move || -> std::result::Result<Vec<u8>, String> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|error| format!("Cannot start the PDF runtime: {error}"))?;
runtime
.block_on(crate::pdf_backend::render_html_to_pdf(&html, &options))
.map_err(|error| error.to_string())
})
.join()
.map_err(|_| Error::pdf("PDF worker thread panicked"))?;
outcome.map_err(Error::pdf)
}
#[cfg(feature = "pdf")]
pub async fn generate_pdf_async(&self, payload: &Value) -> Result<Vec<u8>> {
let prepared = self.prepare(payload)?;
let options = self.resolve_pdf_options(&prepared.meta)?;
self.generate_pdf_prepared_async(&prepared, &options).await
}
#[cfg(feature = "pdf")]
pub async fn generate_pdf_prepared_async(&self, prepared: &PreparedReport, options: &PdfOptions) -> Result<Vec<u8>> {
let html = self.render_prepared_html(prepared)?;
crate::pdf_backend::render_html_to_pdf(&html, options)
.await
.map_err(|error| Error::pdf(error.to_string()))
}
pub fn prepare(&self, payload: &Value) -> Result<PreparedReport> {
prepare_report(payload, self.limits)
}
pub fn render_html(&self, payload: &Value) -> Result<String> {
let prepared = self.prepare(payload)?;
self.render_prepared_html(&prepared)
}
}
pub type TabularReportService = ReportService;
pub fn meta_value(meta: &Meta) -> Value {
meta.to_value()
}
pub fn crosstab_value(crosstab: &Crosstab) -> Value {
crosstab.to_value()
}
pub fn validate_section_source(section: &IndexMap<String, Value>) -> Result<String> {
section_source(section)
}
pub fn value_text(value: &Value) -> String {
pyops::py_str(value)
}
pub fn validate_template_dir(directory: Option<&Path>) -> Result<Option<PathBuf>> {
match directory {
None => Ok(None),
Some(directory) if directory.is_dir() => Ok(Some(directory.to_path_buf())),
Some(directory) => Err(Error::TemplateDirNotFound(directory.to_path_buf())),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
#[test]
fn prepares_tabular_report() {
let payload = value(json!({
"meta": {"title": "Order", "mode": "exact"},
"layout": {
"company": {"label": "Company", "format_mask": "str", "alignment": "left"},
"orders": {
"order": {"label": "Code", "format_mask": "int", "alignment": "right"},
"total": {"label": "Total", "format_mask": "float", "alignment": "right", "aggregate": "sum"}
}
},
"data": [{"company": "ACME", "orders": [{"order": 750, "total": 4000}]}]
}));
let prepared = prepare_report(&payload, None).unwrap();
assert!(prepared.dataset.get("groups").is_some());
assert!(prepared.layout.get("footnotes").is_some());
assert_eq!(prepared.meta.title(), Some("Order"));
}
#[test]
fn prepares_sections_and_toc() {
let payload = value(json!({
"meta": {"title": "Board Pack"},
"sections": [
{"type": "toc", "title": "Contents"},
{"type": "text", "title": "Intro", "paragraphs": ["Hello."]},
{"type": "kpi", "title": "Totals", "items": [{"label": "Orders", "value": 42}]}
]
}));
let prepared = prepare_report(&payload, None).unwrap();
let sections = prepared.dataset.get("sections").and_then(Value::as_array).unwrap();
assert_eq!(sections.len(), 3);
assert_eq!(sections[1].get("anchor").and_then(Value::as_str), Some("section-1"));
let toc_items = sections[0].get("items").and_then(Value::as_array).unwrap();
assert_eq!(toc_items.len(), 2);
}
#[test]
fn renders_html_through_service() {
let payload = value(json!({"meta": {"title": "T"}, "data": [{"a": 1}]}));
let html = ReportService::new().render_html(&payload).unwrap();
assert!(html.contains("T"));
assert!(html.contains("1"));
}
#[test]
fn quotas_apply_in_prepare() {
let payload = value(json!({"meta": {"title": "T", "limits": {"max_rows": 1}}, "data": [{"a": 1}, {"a": 2}]}));
assert!(prepare_report(&payload, None).is_err());
}
#[cfg(feature = "pdf")]
#[test]
fn resolves_pdf_page_options_from_meta() {
let payload = value(json!({
"meta": {
"title": "T",
"locale": "en-US",
"printed_at": "2026-12-02 10:00",
"page": {
"size": "Letter",
"orientation": "landscape",
"margins": {"top": "1cm", "bottom": ".5in", "left": "10mm", "right": "20px"}
}
},
"data": [{"a": 1}]
}));
let prepared = prepare_report(&payload, None).unwrap();
let options = ReportService::default().resolve_pdf_options(&prepared.meta).unwrap();
assert_eq!(options.format, crate::pdf_backend::PageFormat::Letter);
assert!(options.landscape);
assert!(options.outline);
assert_eq!(options.margin.top, "1cm");
assert_eq!(options.margin.bottom, ".5in");
assert_eq!(options.margin.left, "10mm");
assert_eq!(options.margin.right, "20px");
let footer = options.footer_template.unwrap();
assert!(footer.contains("Printed on 2026-12-02 10:00"));
assert!(footer.contains("Page"));
}
#[test]
fn helpers_builders_and_section_errors() {
let empty = IndexMap::new();
assert_eq!(validate_section_source(&empty).unwrap(), "");
let null = IndexMap::from([("source".to_string(), Value::Null)]);
assert_eq!(validate_section_source(&null).unwrap(), "");
let text = IndexMap::from([("source".to_string(), Value::String("x".into()))]);
assert_eq!(validate_section_source(&text).unwrap(), "x");
let bad = IndexMap::from([("source".to_string(), Value::Int(1))]);
assert!(validate_section_source(&bad).is_err());
let directory = tempfile::tempdir().unwrap();
assert!(validate_template_dir(None).unwrap().is_none());
assert_eq!(
validate_template_dir(Some(directory.path())).unwrap().as_deref(),
Some(directory.path())
);
assert!(validate_template_dir(Some(&directory.path().join("missing"))).is_err());
let limits = Limits {
max_rows: Some(2),
max_bytes: Some(3),
};
let service = ReportService::new()
.with_template_dir(directory.path())
.with_template_name("custom.jinja")
.with_inline_css(true)
.with_limits(limits);
assert_eq!(service.template_name, "custom.jinja");
assert_eq!(service.template_dir.as_deref(), Some(directory.path()));
assert!(service.inline_css);
assert_eq!(service.limits, Some(limits));
#[cfg(feature = "pdf")]
{
let service = service.with_pdf_options(PdfOptions::default());
assert!(service.pdf_options.is_some());
}
assert_eq!(value_text(&Value::Null), "None");
let meta = normalize_payload(&value(json!({"meta": {"title": "T"}, "data": []})), None)
.unwrap()
.meta;
assert_eq!(meta_value(&meta).get("title").and_then(Value::as_str), Some("T"));
let crosstab = build_crosstab(
&[value(json!({"r": "a", "c": "b", "v": 1}))],
&value(json!({"rows": "r", "columns": "c", "measure": "v"})),
)
.unwrap();
assert!(crosstab_value(&crosstab).get("row_headers").is_some());
for payload in [
json!({"meta": {"title": "T"}, "sections": [{"type": "text", "paragraphs": "x"}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "text", "paragraphs": [1]}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "text", "body": 1}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "kpi", "items": [{"value": 1}]}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "kpi", "items": "x"}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "table", "layout": 1, "data": []}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "unknown"}]}),
json!({"meta": {"title": "T"}, "sections": [{"type": "table", "source": 1, "data": []}]}),
] {
assert!(
prepare_report(&value(payload), Some(Limits::none())).is_err(),
"accepted invalid section"
);
}
let text_body = value(json!({
"meta": {"title": "T"},
"sections": [{"type": "text", "title": "Body", "body": "Plain body"}]
}));
let prepared = prepare_report(&text_body, Some(Limits::none())).unwrap();
let sections = prepared.dataset.get("sections").and_then(Value::as_array).unwrap();
let paragraphs = sections[0].get("paragraphs").and_then(Value::as_array).unwrap();
assert_eq!(paragraphs[0].as_str(), Some("Plain body"));
let empty_text = value(json!({
"meta": {"title": "T"},
"sections": [{"type": "table", "title": "Empty", "data": [], "empty_text": "No rows"}]
}));
let prepared = prepare_report(&empty_text, Some(Limits::none())).unwrap();
let sections = prepared.dataset.get("sections").and_then(Value::as_array).unwrap();
assert_eq!(sections[0].get("empty_text").and_then(Value::as_str), Some("No rows"));
}
#[cfg(feature = "pdf")]
#[test]
#[ignore = "requires a local Chromium/Chrome installation"]
fn service_pdf_paths_generate_real_pdfs() {
let payload = value(json!({"meta": {"title": "Service PDF"}, "data": [{"a": 1}]}));
let service = ReportService::new();
let pdf = service.generate_pdf(&payload).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let prepared = service.prepare(&payload).unwrap();
let options = service.resolve_pdf_options(&prepared.meta).unwrap();
let pdf = service.generate_pdf_prepared(&prepared, &options).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let pdf = futures::executor::block_on(service.generate_pdf_async(&payload)).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
let pdf = futures::executor::block_on(service.generate_pdf_prepared_async(&prepared, &options)).unwrap();
assert!(pdf.starts_with(b"%PDF-"));
crate::pdf_backend::shutdown_pdf_pool();
}
}