use std::collections::HashSet;
use indexmap::IndexMap;
use crate::error::{Error, Result};
use crate::formatting::{format_value, sparkline_text};
use crate::pyops;
use crate::value::Value;
#[derive(Debug, Clone)]
pub struct Column {
pub key: String,
pub label: String,
pub mask: String,
pub rules: Vec<Value>,
pub field: Value,
}
impl Column {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
key: key.into(),
label: label.into(),
mask: "str".to_string(),
rules: Vec::new(),
field: Value::Null,
}
}
}
#[derive(Debug, Clone)]
pub struct Table {
pub key: String,
pub columns: Vec<Column>,
pub rows: Vec<IndexMap<String, Value>>,
pub total_rows: HashSet<usize>,
pub note: String,
pub notes: Vec<(String, String)>,
pub chart: Option<Value>,
}
impl Table {
pub fn new(key: impl Into<String>, columns: Vec<Column>) -> Self {
Self {
key: key.into(),
columns,
rows: Vec::new(),
total_rows: HashSet::new(),
note: String::new(),
notes: Vec::new(),
chart: None,
}
}
}
#[derive(Debug, Clone)]
pub struct SummaryRow {
pub label: String,
pub value: Value,
pub mask: String,
}
fn column_from_field(field: &Value) -> Column {
let object = field.as_object();
let key = object
.and_then(|object| object.get("name"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let label = object
.and_then(|object| object.get("label"))
.map(pyops::py_str)
.unwrap_or_else(|| key.clone());
let mask = object
.and_then(|object| object.get("format_mask"))
.and_then(Value::as_str)
.unwrap_or("str")
.to_string();
let rules = object
.and_then(|object| object.get("cell_rules"))
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
Column {
key,
label,
mask,
rules,
field: field.clone(),
}
}
fn merge_columns(context: &[Column], table_fields: &[Value]) -> Vec<Column> {
let mut columns = context.to_vec();
let mut seen: HashSet<String> = columns.iter().map(|column| column.key.clone()).collect();
for field in table_fields {
let column = column_from_field(field);
if seen.insert(column.key.clone()) {
columns.push(column);
}
}
columns
}
fn notes_from_field_dicts(fields: &[Value]) -> Vec<(String, String)> {
let mut notes = Vec::new();
let mut seen = HashSet::new();
for field in fields {
let Some(note) = 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;
}
notes.push((
mark.to_string(),
note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
));
}
notes
}
fn notes_from_columns(columns: &[Column]) -> Vec<(String, String)> {
notes_from_field_dicts(&columns.iter().map(|column| column.field.clone()).collect::<Vec<_>>())
}
fn section_notes(section: &Value) -> Vec<(String, String)> {
section
.get("source")
.and_then(Value::as_str)
.filter(|source| !source.is_empty())
.map(|source| vec![("source".to_string(), source.to_string())])
.unwrap_or_default()
}
fn attach_notes(table: &mut Table, notes: Vec<(String, String)>) {
let mut known: HashSet<String> = table.notes.iter().map(|(ref_, _)| ref_.clone()).collect();
for (ref_, text) in notes {
if known.insert(ref_.clone()) {
table.notes.push((ref_, text));
}
}
}
fn column_mark(column: &Column) -> Option<&str> {
column
.field
.get("footnote")
.and_then(|note| note.get("mark"))
.and_then(Value::as_str)
.filter(|mark| !mark.is_empty())
}
fn column_label(column: &Column) -> String {
match column_mark(column) {
Some(mark) => format!("{} [{}]", column.label, mark),
None => column.label.clone(),
}
}
#[cfg(feature = "xlsx")]
fn sheet_name(base: &str, used: &mut HashSet<String>) -> String {
let clean: String = base.chars().map(|ch| if "\\/*?:[]".contains(ch) { '-' } else { ch }).collect();
let clean = clean.trim();
let clean = if clean.is_empty() { "Sheet" } else { clean };
let mut name = clean.chars().take(31).collect::<String>();
let mut index = 2usize;
while used.contains(&name) {
let suffix = format!("_{index}");
let available = 31usize.saturating_sub(suffix.len());
name = format!("{}{suffix}", clean.chars().take(available).collect::<String>());
index += 1;
}
used.insert(name.clone());
name
}
fn crosstab_table(crosstab: &Value, meta: Option<&Value>) -> Table {
let object = crosstab.as_object().cloned().unwrap_or_default();
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
let row_field = object.get("row_field").cloned().unwrap_or(Value::Null);
let col_field = object.get("col_field").cloned().unwrap_or(Value::Null);
let measure_field = object.get("measure_field").cloned().unwrap_or(Value::Null);
let mask = object.get("mask").and_then(Value::as_str).unwrap_or("str").to_string();
let row_label = object.get("row_label").and_then(Value::as_str).unwrap_or(" ");
let total_label = object.get("total_label").and_then(Value::as_str).unwrap_or("Total");
let totals = object.get("totals").and_then(Value::as_bool).unwrap_or(true);
let has_data = object.get("has_data").and_then(Value::as_bool).unwrap_or(false);
let col_headers = object.get("col_headers").and_then(Value::as_array).cloned().unwrap_or_default();
let col_mask = col_field.get("format_mask").and_then(Value::as_str).unwrap_or("str");
let mut columns = vec![Column {
key: "__row__".to_string(),
label: row_label.to_string(),
mask: "str".to_string(),
rules: Vec::new(),
field: row_field,
}];
for (index, header) in col_headers.iter().enumerate() {
let label = format_value(header, col_mask, locale, currency, Some(&col_field)).unwrap_or_else(|_| pyops::py_str(header));
columns.push(Column {
key: format!("__c{index}__"),
label,
mask: mask.clone(),
rules: Vec::new(),
field: measure_field.clone(),
});
}
if totals {
columns.push(Column {
key: "__total__".to_string(),
label: total_label.to_string(),
mask: mask.clone(),
rules: Vec::new(),
field: measure_field.clone(),
});
}
let empty_text = object.get("empty_text").and_then(Value::as_str).unwrap_or_default();
let mut table = Table::new("crosstab", columns);
table.note = if has_data { String::new() } else { empty_text.to_string() };
let row_headers = object.get("row_headers").and_then(Value::as_array).cloned().unwrap_or_default();
let cells = object.get("cells").and_then(Value::as_array).cloned().unwrap_or_default();
let row_totals = object.get("row_totals").and_then(Value::as_array).cloned().unwrap_or_default();
for (index, row_header) in row_headers.iter().enumerate() {
let mut record = IndexMap::new();
record.insert("__row__".to_string(), row_header.clone());
if let Some(cells) = cells.get(index).and_then(Value::as_array) {
for (cell_index, cell) in cells.iter().enumerate() {
record.insert(format!("__c{cell_index}__"), cell.clone());
}
}
if totals {
record.insert("__total__".to_string(), row_totals.get(index).cloned().unwrap_or(Value::Null));
}
table.rows.push(record);
}
if totals && has_data {
let mut record = IndexMap::new();
record.insert("__row__".to_string(), Value::String(total_label.to_string()));
if let Some(col_totals) = object.get("col_totals").and_then(Value::as_array) {
for (index, total) in col_totals.iter().enumerate() {
record.insert(format!("__c{index}__"), total.clone());
}
}
record.insert("__total__".to_string(), object.get("grand_total").cloned().unwrap_or(Value::Null));
table.rows.push(record);
table.total_rows.insert(table.rows.len() - 1);
}
table
}
fn collect_inner(dataset: &Value, layout: &Value, meta: Option<&Value>, default_name: &str) -> (Vec<Table>, Vec<SummaryRow>) {
let mut summaries = Vec::new();
let mut by_key: IndexMap<String, Table> = IndexMap::new();
fn table_for<'a>(by_key: &'a mut IndexMap<String, Table>, key: &str, columns: &[Column]) -> &'a mut Table {
by_key.entry(key.to_string()).or_insert_with(|| Table::new(key, columns.to_vec()))
}
fn visit(
items: &[Value],
fragment: &Value,
context: &[(Column, Value)],
by_key: &mut IndexMap<String, Table>,
summaries: &mut Vec<SummaryRow>,
) {
let header = fragment.get("header").and_then(Value::as_array).cloned().unwrap_or_default();
for item in items {
let Some(item) = item.as_object() else {
continue;
};
let fields = item.get("fields").and_then(Value::as_object).cloned().unwrap_or_default();
let mut ctx = context.to_vec();
for field in &header {
let column = column_from_field(field);
let value = fields.get(&column.key).cloned().unwrap_or(Value::Null);
ctx.push((column, value));
}
let details = item.get("details").and_then(Value::as_object).cloned().unwrap_or_default();
let layouts = fragment.get("details").and_then(Value::as_object).cloned().unwrap_or_default();
for (table_key, table_layout) in &layouts {
let table_data = details.get(table_key).and_then(Value::as_object).cloned().unwrap_or_default();
let rows: Vec<Value> = table_data
.get("rows")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
.into_iter()
.filter(Value::is_object)
.collect();
let footer = table_data.get("footer").and_then(Value::as_object).cloned();
let empty_text = table_data.get("empty_text").and_then(Value::as_str);
if rows.is_empty() && footer.is_none() && empty_text.is_none() {
continue;
}
let table_fields = table_layout.as_array().cloned().unwrap_or_default();
let columns = merge_columns(&ctx.iter().map(|(column, _)| column.clone()).collect::<Vec<_>>(), &table_fields);
let sheet = table_for(by_key, table_key, &columns);
if let Some(empty_text) = empty_text {
sheet.note = empty_text.to_string();
}
attach_notes(sheet, notes_from_columns(&columns));
let mut base = IndexMap::new();
for (column, value) in &ctx {
base.insert(column.key.clone(), value.clone());
}
for row in &rows {
let mut record: IndexMap<String, Value> = columns.iter().map(|column| (column.key.clone(), Value::Null)).collect();
record.extend(base.clone());
if let Some(row) = row.as_object() {
record.extend(row.clone());
}
sheet.rows.push(record);
}
if let Some(footer) = footer {
sheet.rows.push(footer.clone());
sheet.total_rows.insert(sheet.rows.len() - 1);
}
}
if let Some(groups) = item.get("groups").and_then(Value::as_array) {
if let Some(child_fragment) = fragment.get("groups") {
visit(groups, child_fragment, &ctx, by_key, summaries);
}
}
if let Some(footer) = item.get("footer").and_then(Value::as_object) {
if let Some(footer_layout) = fragment.get("footer").and_then(Value::as_array) {
let path = ctx
.iter()
.filter(|(_, value)| !value.is_null() && !matches!(value, Value::String(text) if text.is_empty()))
.map(|(_, value)| pyops::py_str(value))
.collect::<Vec<_>>()
.join(" / ");
for field in footer_layout {
let Some(name) = field.get("name").and_then(Value::as_str) else {
continue;
};
let Some(value) = footer.get(name) else {
continue;
};
if value.is_null() || matches!(value, Value::String(text) if text.is_empty()) {
continue;
}
let label = field.get("label").map(pyops::py_str).unwrap_or_else(|| name.to_string());
let label = if path.is_empty() { label } else { format!("{path} / {label}") };
summaries.push(SummaryRow {
label,
value: value.clone(),
mask: field.get("format_mask").and_then(Value::as_str).unwrap_or("str").to_string(),
});
}
}
}
}
}
let top = dataset.get("groups").and_then(Value::as_array).cloned().unwrap_or_default();
let root = layout.get("groups").cloned().unwrap_or(Value::Null);
visit(&top, &root, &[], &mut by_key, &mut summaries);
if let Some(summary) = dataset.get("summary").and_then(Value::as_object) {
if let Some(summary_layout) = layout.get("summary").and_then(Value::as_array) {
for field in summary_layout {
let Some(name) = field.get("name").and_then(Value::as_str) else {
continue;
};
if let Some(value) = summary.get(name) {
summaries.push(SummaryRow {
label: field.get("label").map(pyops::py_str).unwrap_or_else(|| name.to_string()),
value: value.clone(),
mask: field.get("format_mask").and_then(Value::as_str).unwrap_or("str").to_string(),
});
}
}
}
}
if let Some(sections) = dataset.get("sections").and_then(Value::as_array) {
for section in sections {
let Some(section) = section.as_object() else {
continue;
};
let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table");
match section_type {
"table" => {
let title = section.get("title").and_then(Value::as_str);
let sub_dataset = section.get("dataset").cloned().unwrap_or(Value::Null);
let sub_layout = section.get("layout").cloned().unwrap_or(Value::Null);
let (sub_tables, sub_summaries) = collect_inner(&sub_dataset, &sub_layout, meta, title.unwrap_or("table"));
for mut table in sub_tables {
let key = match title {
Some(title) if !title.is_empty() && table.key != title => {
format!("{title} - {}", table.key)
}
_ => table.key.clone(),
};
let mut suffix = key.clone();
let mut index = 2usize;
while by_key.contains_key(&suffix) {
suffix = format!("{key}_{index}");
index += 1;
}
table.key = suffix.clone();
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(suffix, table);
}
for row in sub_summaries {
summaries.push(SummaryRow {
label: match title {
Some(title) if !title.is_empty() => format!("{title} / {}", row.label),
_ => row.label,
},
value: row.value,
mask: row.mask,
});
}
}
"text" => {
let paragraphs: Vec<String> = section
.get("paragraphs")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
.iter()
.filter_map(|value| value.as_str().map(str::to_string))
.collect();
if !paragraphs.is_empty() {
let key = section.get("title").and_then(Value::as_str).unwrap_or("notes").to_string();
let mut table = Table::new(key.clone(), vec![Column::new("text", "Text")]);
table.rows = paragraphs
.into_iter()
.map(|paragraph| {
let mut row = IndexMap::new();
row.insert("text".to_string(), Value::String(paragraph));
row
})
.collect();
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(key, table);
}
}
"kpi" => {
let items = section.get("items").and_then(Value::as_array).cloned().unwrap_or_default();
let rows: Vec<IndexMap<String, Value>> = items
.iter()
.filter_map(Value::as_object)
.map(|item| {
let mut row = IndexMap::new();
row.insert("label".to_string(), item.get("label").cloned().unwrap_or(Value::Null));
row.insert("value".to_string(), item.get("value").cloned().unwrap_or(Value::Null));
row
})
.collect();
if !rows.is_empty() {
let key = section.get("title").and_then(Value::as_str).unwrap_or("kpi").to_string();
let mut table = Table::new(key.clone(), vec![Column::new("label", "Label"), Column::new("value", "Value")]);
table.rows = rows;
attach_notes(&mut table, notes_from_field_dicts(&items));
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(key, table);
}
}
"chart" => {
let spec = section.get("chart").and_then(Value::as_object).cloned().unwrap_or_default();
let labels = spec.get("labels").and_then(Value::as_array).cloned().unwrap_or_default();
let values = spec.get("values").and_then(Value::as_array).cloned().unwrap_or_default();
let mut rows = Vec::new();
for (label, value) in labels.iter().zip(values.iter()) {
let mut row = IndexMap::new();
row.insert("label".to_string(), label.clone());
row.insert("value".to_string(), value.clone());
rows.push(row);
}
if !rows.is_empty() {
let key = section
.get("title")
.and_then(Value::as_str)
.or_else(|| spec.get("title").and_then(Value::as_str))
.unwrap_or("chart")
.to_string();
let mut table = Table::new(key.clone(), vec![Column::new("label", "Label"), Column::new("value", "Value")]);
table.rows = rows;
let mut chart = IndexMap::new();
chart.insert(
"kind".to_string(),
spec.get("kind").cloned().unwrap_or_else(|| Value::String("bar".to_string())),
);
chart.insert("title".to_string(), Value::String(key.clone()));
chart.insert("color".to_string(), spec.get("color").cloned().unwrap_or(Value::Null));
chart.insert("orientation".to_string(), spec.get("orientation").cloned().unwrap_or(Value::Null));
table.chart = Some(Value::Object(chart));
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(key, table);
}
}
"image" => {
let label = section
.get("alt")
.and_then(Value::as_str)
.or_else(|| section.get("caption").and_then(Value::as_str))
.unwrap_or("image");
let key = section.get("title").and_then(Value::as_str).unwrap_or("image");
let mut suffix = key.to_string();
let mut index = 2usize;
while by_key.contains_key(&suffix) {
suffix = format!("{key}_{index}");
index += 1;
}
let mut table = Table::new(suffix.clone(), vec![Column::new("image", "Image")]);
let mut row = IndexMap::new();
row.insert("image".to_string(), Value::String(label.to_string()));
table.rows.push(row);
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(suffix, table);
}
"toc" => {
let rows: Vec<IndexMap<String, Value>> = section
.get("items")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_object)
.filter_map(|item| item.get("title"))
.filter(|value| value.truthy())
.map(|title| {
let mut row = IndexMap::new();
row.insert("section".to_string(), title.clone());
row
})
.collect();
if !rows.is_empty() {
let key = section.get("title").and_then(Value::as_str).unwrap_or("contents");
let mut suffix = key.to_string();
let mut index = 2usize;
while by_key.contains_key(&suffix) {
suffix = format!("{key}_{index}");
index += 1;
}
let mut table = Table::new(suffix.clone(), vec![Column::new("section", "Section")]);
table.rows = rows;
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(suffix, table);
}
}
"crosstab" => {
if let Some(crosstab) = section.get("crosstab") {
let mut table = crosstab_table(crosstab, meta);
if !table.rows.is_empty() || !table.note.is_empty() {
let title = section.get("title").and_then(Value::as_str);
let key = title.unwrap_or(table.key.as_str()).to_string();
let mut suffix = key.clone();
let mut index = 2usize;
while by_key.contains_key(&suffix) {
suffix = format!("{key}_{index}");
index += 1;
}
table.key = suffix.clone();
let notes = notes_from_columns(&table.columns);
attach_notes(&mut table, notes);
attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
by_key.insert(suffix, table);
}
}
}
_ => {}
}
}
}
if by_key.is_empty() && !top.is_empty() {
let header = layout
.get("groups")
.and_then(|groups| groups.get("header"))
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let columns: Vec<Column> = header.iter().map(column_from_field).collect();
if !columns.is_empty() {
let mut sheet = Table::new(default_name, columns.clone());
attach_notes(&mut sheet, notes_from_columns(&columns));
for item in &top {
let Some(fields) = item.get("fields").and_then(Value::as_object) else {
continue;
};
let mut row = IndexMap::new();
for column in &columns {
row.insert(column.key.clone(), fields.get(&column.key).cloned().unwrap_or(Value::Null));
}
sheet.rows.push(row);
}
by_key.insert(default_name.to_string(), sheet);
}
}
(by_key.into_values().collect(), summaries)
}
pub fn collect_tables(dataset: &Value, layout: &Value, meta: Option<&Value>) -> (Vec<Table>, Vec<SummaryRow>) {
collect_inner(dataset, layout, meta, "data")
}
fn guard_formula(value: &str, raw: &Value) -> String {
let numeric = matches!(
raw,
Value::Int(_) | Value::UInt(_) | Value::Float(_) | Value::Decimal(_) | Value::Bool(_)
);
if !numeric && value.starts_with(['=', '+', '-', '@', '\t', '\r']) {
format!("'{value}")
} else {
value.to_string()
}
}
fn cell_text(row: &IndexMap<String, Value>, column: &Column, meta: Option<&Value>) -> Result<String> {
let value = row.get(&column.key).unwrap_or(&Value::Null);
if column.mask == "sparkline" {
return Ok(sparkline_text(value));
}
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
format_value(value, &column.mask, locale, currency, Some(&column.field))
}
pub fn render_csv(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>, delimiter: char) -> Result<String> {
if !delimiter.is_ascii() {
return Err(Error::option(format!(
"Invalid CSV delimiter (must be a single ASCII character): {delimiter:?}"
)));
}
let mut writer = csv::WriterBuilder::new()
.delimiter(delimiter as u8)
.terminator(csv::Terminator::Any(b'\n'))
.quote_style(csv::QuoteStyle::Necessary)
.flexible(true)
.from_writer(Vec::new());
let title = meta.and_then(|meta| meta.get("title")).and_then(Value::as_str);
if let Some(title) = title {
writer.write_record([format!("# {title}")])?;
}
if let Some(source_note) = meta.and_then(|meta| meta.get("source_note")).and_then(Value::as_str) {
writer.write_record([format!("# [source] {source_note}")])?;
}
for table in tables {
writer.write_record([format!("# table: {}", table.key)])?;
writer.write_record(table.columns.iter().map(column_label))?;
if table.rows.is_empty() && !table.note.is_empty() {
writer.write_record([format!("# {}", table.note)])?;
}
for row in &table.rows {
let mut record = Vec::with_capacity(table.columns.len());
for column in &table.columns {
let raw = row.get(&column.key).cloned().unwrap_or(Value::Null);
let text = cell_text(row, column, meta)?;
record.push(guard_formula(&text, &raw));
}
writer.write_record(record)?;
}
for (ref_, text) in &table.notes {
writer.write_record([format!("# [{ref_}] {text}")])?;
}
}
if !summaries.is_empty() {
writer.write_record(["# summary"])?;
writer.write_record(["Item", "Value"])?;
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
for row in summaries {
let text = format_value(&row.value, &row.mask, locale, currency, None)?;
writer.write_record([row.label.clone(), guard_formula(&text, &row.value)])?;
}
}
let bytes = writer
.into_inner()
.map_err(|error| Error::message(format!("CSV writer error: {error}")))?;
String::from_utf8(bytes).map_err(|error| Error::message(format!("CSV is not UTF-8: {error}")))
}
#[cfg(feature = "xlsx")]
pub fn build_workbook(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>) -> Result<Vec<u8>> {
xlsx_impl::build_workbook(tables, summaries, meta)
}
#[cfg(not(feature = "xlsx"))]
pub fn build_workbook(_tables: &[Table], _summaries: &[SummaryRow], _meta: Option<&Value>) -> Result<Vec<u8>> {
Err(Error::FeatureDisabled("XLSX export requires the 'xlsx' feature (rust_xlsxwriter)"))
}
#[cfg(any())]
mod xlsx {
use super::*;
use rust_xlsxwriter::{Chart, ChartType, Color, Format, FormatAlign, FormatBorder, Workbook, Worksheet};
fn argb(spec: &str) -> String {
let hex = spec.trim_start_matches('#');
let hex = if hex.len() == 3 {
hex.chars().flat_map(|ch| [ch, ch]).collect::<String>()
} else {
hex.to_string()
};
if hex.len() == 6 {
format!("FF{hex}")
} else {
hex
}
}
fn number_format(mask: &str, currency_symbol: &str) -> Option<&'static str> {
match mask {
"int" => Some("#,##0"),
"float" => Some("#,##0.00"),
"percent" => Some("0.00%"),
"currency" => {
let _ = currency_symbol;
None
}
"date" => Some("yyyy-mm-dd"),
_ => None,
}
}
fn currency_symbol(meta: Option<&Value>) -> String {
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let code = meta
.and_then(|meta| meta.get("currency"))
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| crate::formatting::default_currency(locale).ok())
.unwrap_or_else(|| "USD".to_string());
crate::formatting::format_currency(0.0, &code, locale)
.ok()
.map(|text| {
text.chars()
.filter(|ch| !ch.is_ascii_digit() && !matches!(ch, ',' | '.' | '-' | '\u{a0}' | ' '))
.collect::<String>()
})
.filter(|symbol| !symbol.is_empty())
.unwrap_or_else(|| "$".to_string())
}
fn apply_cell_style(cell: &mut rust_xlsxwriter::Cell, raw: &Value, column: &Column, base: &Format) -> Result<()> {
let style = crate::formatting::cell_style_dict(
raw,
&Value::Object(
[("cell_rules".to_string(), Value::Array(column.rules.clone()))]
.into_iter()
.collect(),
),
)?;
let mut format = base.clone();
if let Some(color) = style.color {
format = format.set_font_color(Color::RGB(u32::from_str_radix(&argb(&color)[2..], 16).unwrap_or(0)));
}
if style.bold {
format = format.set_bold();
}
if style.italic {
format = format.set_italic();
}
if let Some(background) = style.background.or_else(|| crate::formatting::scale_fill(raw, &column.field)) {
format = format.set_background_color(Color::RGB(u32::from_str_radix(&argb(&background)[2..], 16).unwrap_or(0xFFFFFF)));
}
cell.set_format(format);
Ok(())
}
pub fn build_workbook(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>) -> Result<Vec<u8>> {
let mut workbook = Workbook::new();
let mut used = HashSet::new();
let title = meta.and_then(|meta| meta.get("title")).and_then(Value::as_str);
let sub_title = meta.and_then(|meta| meta.get("sub_title")).and_then(Value::as_str);
let symbol = currency_symbol(meta);
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
let header_format = Format::new()
.set_bold()
.set_font_color(Color::White)
.set_background_color(Color::RGB(0x0A2F46));
let note_format = Format::new().set_italic().set_font_color(Color::RGB(0x6B7280));
let total_format = Format::new().set_bold().set_border_top(FormatBorder::Thin);
let title_format = Format::new().set_bold().set_font_size(14);
if tables.is_empty() && summaries.is_empty() {
let sheet = workbook.add_worksheet();
let name = sheet_name(title.unwrap_or("Report"), &mut used);
sheet.set_name(&name)?;
sheet.write_string_with_format(0, 0, title.unwrap_or("Report"), &title_format)?;
return workbook
.save_to_buffer()
.map_err(|error| Error::message(format!("XLSX error: {error}")));
}
for table in tables {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name(&table.key, &mut used))?;
let mut row_index: u32 = 0;
if let Some(title) = title {
sheet.write_string_with_format(row_index, 0, title, &title_format)?;
row_index += 1;
}
if let Some(sub_title) = sub_title {
sheet.write_string(row_index, 0, sub_title)?;
row_index += 1;
}
let header_row = row_index;
let mut widths: Vec<usize> = vec![0; table.columns.len()];
for (column_index, column) in table.columns.iter().enumerate() {
let label = column_label(column);
sheet.write_string_with_format(row_index, column_index as u16, &label, &header_format)?;
widths[column_index] = widths[column_index].max(label.chars().count());
}
if !table.columns.is_empty() {
sheet.set_freeze_panes(header_row + 1, 0)?;
sheet.set_autofilter(header_row, 0, header_row, (table.columns.len() - 1) as u16)?;
sheet.set_print_title_rows(header_row, header_row)?;
}
if table.rows.is_empty() && !table.note.is_empty() {
row_index += 1;
sheet.write_string_with_format(row_index, 0, &table.note, ¬e_format)?;
if let Some(width) = widths.first_mut() {
*width = (*width).max(table.note.chars().count());
}
}
for (position, record) in table.rows.iter().enumerate() {
row_index += 1;
let is_total = table.total_rows.contains(&position);
for (column_index, column) in table.columns.iter().enumerate() {
let raw = record.get(&column.key).cloned().unwrap_or(Value::Null);
let mapped = crate::formatting::field_text(&raw, Some(&column.field))?;
let value = mapped.unwrap_or_else(|| match &raw {
Value::Null => String::new(),
Value::Date(date) => date.format("%Y-%m-%d").to_string(),
Value::DateTime(datetime) => datetime.to_rfc3339(),
Value::Int(value) => value.to_string(),
Value::UInt(value) => value.to_string(),
Value::Float(value) => value.to_string(),
Value::Decimal(value) => value.to_string(),
Value::Bool(value) => {
if *value {
"Yes".to_string()
} else {
"No".to_string()
}
}
Value::String(value) => value.clone(),
other => pyops::py_str(other),
});
let value = guard_formula(&value, &raw);
let cell = sheet.write_string(row_index, column_index as u16, &value)?;
if is_total {
cell.set_format(total_format.clone());
}
apply_cell_style(cell, &raw, column, &Format::new())?;
if let Some(format) = number_format(&column.mask, &symbol) {
if let Ok(number) = value.replace(',', ".").parse::<f64>() {
let cell = sheet.write_number(row_index, column_index as u16, number)?;
cell.set_format(Format::new().set_num_format(format));
}
} else if column.mask == "currency" {
if let Ok(number) = value.replace('.', "").replace(',', ".").parse::<f64>() {
let cell = sheet.write_number(row_index, column_index as u16, number)?;
cell.set_format(Format::new().set_num_format(format!("\"{symbol}\"#,##0.00")));
}
}
widths[column_index] = widths[column_index].max(value.chars().count());
}
}
for (column_index, width) in widths.iter().enumerate() {
let width = (*width + 2).clamp(10, 50) as f64;
sheet.set_column_width(column_index as u16, width)?;
}
if let Some(chart) = &table.chart {
let _ = chart;
}
let _: &Worksheet = sheet;
let _ = locale;
let _ = currency;
}
if !summaries.is_empty() {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name("Summary", &mut used))?;
let mut row_index: u32 = 0;
if let Some(title) = title {
sheet.write_string_with_format(row_index, 0, title, &title_format)?;
row_index += 1;
}
sheet.write_string_with_format(row_index, 0, "Item", &header_format)?;
sheet.write_string_with_format(row_index, 1, "Value", &header_format)?;
let mut widths = [4usize, 5usize];
for row in summaries {
row_index += 1;
sheet.write_string(row_index, 0, &row.label)?;
let text = format_value(&row.value, &row.mask, locale, currency, None)?;
sheet.write_string(row_index, 1, &text)?;
widths[0] = widths[0].max(row.label.chars().count());
widths[1] = widths[1].max(text.chars().count());
}
sheet.set_column_width(0, widths[0].clamp(4, 60) as f64)?;
sheet.set_column_width(1, widths[1].clamp(5, 30) as f64)?;
}
let mut note_rows: Vec<(String, String, String)> = Vec::new();
if let Some(source_note) = meta.and_then(|meta| meta.get("source_note")).and_then(Value::as_str) {
note_rows.push((String::new(), "source".to_string(), source_note.to_string()));
}
for table in tables {
for (ref_, text) in &table.notes {
note_rows.push((table.key.clone(), ref_.clone(), text.clone()));
}
}
if !note_rows.is_empty() {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name("Notes", &mut used))?;
sheet.write_string_with_format(0, 0, "Table", &header_format)?;
sheet.write_string_with_format(0, 1, "Ref", &header_format)?;
sheet.write_string_with_format(0, 2, "Note", &header_format)?;
let mut widths = [5usize, 3usize, 4usize];
for (index, (table, ref_, text)) in note_rows.iter().enumerate() {
let row = index as u32 + 1;
sheet.write_string(row, 0, table)?;
sheet.write_string(row, 1, ref_)?;
sheet.write_string(row, 2, text)?;
widths[0] = widths[0].max(table.chars().count());
widths[1] = widths[1].max(ref_.chars().count());
widths[2] = widths[2].max(text.chars().count());
}
sheet.set_column_width(0, widths[0].clamp(5, 40) as f64)?;
sheet.set_column_width(1, widths[1].clamp(3, 12) as f64)?;
sheet.set_column_width(2, widths[2].clamp(4, 80) as f64)?;
}
workbook
.save_to_buffer()
.map_err(|error| Error::message(format!("XLSX error: {error}")))
}
#[allow(dead_code)]
fn _chart_placeholder() -> Chart {
Chart::new(ChartType::Bar)
}
}
#[cfg(feature = "xlsx")]
mod xlsx_impl {
use super::*;
use rust_xlsxwriter::{
Chart, ChartFormat, ChartLine, ChartSolidFill, ChartType, Color, ConditionalFormatDataBar, ConditionalFormatType, Format,
FormatBorder, Workbook, Worksheet,
};
fn rgb(spec: &str) -> Color {
let hex = spec.trim_start_matches('#');
let hex = if hex.len() == 3 {
hex.chars().flat_map(|ch| [ch, ch]).collect::<String>()
} else {
hex.to_string()
};
Color::RGB(u32::from_str_radix(&hex, 16).unwrap_or(0))
}
fn number_format(mask: &str, symbol: &str) -> Option<String> {
match mask {
"int" => Some("#,##0".to_string()),
"float" => Some("#,##0.00".to_string()),
"percent" => Some("0.00%".to_string()),
"currency" => Some(format!("\"{symbol}\"#,##0.00")),
"date" => Some("yyyy-mm-dd".to_string()),
_ => None,
}
}
fn currency_symbol(meta: Option<&Value>) -> String {
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let code = meta
.and_then(|meta| meta.get("currency"))
.and_then(Value::as_str)
.unwrap_or_default();
let symbol = crate::formatting::xlsx_currency_symbol(code, locale);
if symbol.is_empty() {
"$".to_string()
} else {
symbol
}
}
fn numeric_value(raw: &Value, mask: &str) -> Option<f64> {
match mask {
"int" => pyops::py_int(raw).ok().map(|value| value as f64),
"float" | "percent" | "currency" => pyops::py_float(raw).ok(),
_ => match raw {
Value::Int(value) => Some(*value as f64),
Value::UInt(value) => Some(*value as f64),
Value::Float(value) => Some(*value),
Value::Decimal(value) => value.to_string().parse::<f64>().ok(),
_ => None,
},
}
}
enum NativeCell {
Empty,
Bool(bool),
Number(f64),
DateTime(rust_xlsxwriter::ExcelDateTime),
Text(String),
}
fn boolean_text(raw: &Value) -> String {
let truthy = match raw {
Value::String(value) => matches!(value.trim().to_lowercase().as_str(), "true" | "yes" | "y" | "1"),
other => other.truthy(),
};
if truthy { "Yes" } else { "No" }.to_string()
}
fn excel_datetime(raw: &Value) -> Option<rust_xlsxwriter::ExcelDateTime> {
use chrono::{Datelike, Timelike};
match raw {
Value::Date(date) => rust_xlsxwriter::ExcelDateTime::from_ymd(date.year() as u16, date.month() as u8, date.day() as u8).ok(),
Value::DateTime(datetime) => {
let local = datetime.naive_local();
rust_xlsxwriter::ExcelDateTime::from_ymd(local.year() as u16, local.month() as u8, local.day() as u8)
.ok()?
.and_hms(local.hour() as u16, local.minute() as u8, local.second() as f64)
.ok()
}
_ => None,
}
}
fn native_cell(raw: &Value, column: &Column, meta: Option<&Value>) -> Result<NativeCell> {
if let Some(mapped) = crate::formatting::field_text(raw, Some(&column.field))? {
return Ok(NativeCell::Text(mapped));
}
match column.mask.as_str() {
"sparkline" => return Ok(NativeCell::Text(sparkline_text(raw))),
"bool" => return Ok(NativeCell::Text(boolean_text(raw))),
_ => {}
}
if let Some(datetime) = excel_datetime(raw) {
return Ok(NativeCell::DateTime(datetime));
}
if let Some(number) = numeric_value(raw, &column.mask) {
return Ok(NativeCell::Number(number));
}
Ok(match raw {
Value::Null => NativeCell::Empty,
Value::Bool(value) => NativeCell::Bool(*value),
other => NativeCell::Text(display_text(other, column, meta)?),
})
}
fn base_format(raw: &Value, column: &Column, total: bool) -> Format {
let mut format = Format::new();
if total {
format = format.set_bold().set_border_top(FormatBorder::Thin);
}
if let Ok(style) = crate::formatting::cell_style_dict(raw, &column.field) {
if let Some(color) = style.color {
format = format.set_font_color(rgb(&color));
}
if style.bold {
format = format.set_bold();
}
if style.italic {
format = format.set_italic();
}
if let Some(background) = style.background.or_else(|| crate::formatting::scale_fill(raw, &column.field)) {
format = format.set_background_color(rgb(&background));
}
}
format
}
fn display_text(raw: &Value, column: &Column, meta: Option<&Value>) -> Result<String> {
if let Some(mapped) = crate::formatting::field_text(raw, Some(&column.field))? {
return Ok(mapped);
}
let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
if column.mask == "sparkline" {
return Ok(sparkline_text(raw));
}
crate::formatting::format_value(raw, &column.mask, locale, currency, Some(&column.field))
}
fn add_data_bars(sheet: &mut Worksheet, header_row: u32, table: &Table) -> Result<()> {
if table.rows.is_empty() {
return Ok(());
}
for (column_index, column) in table.columns.iter().enumerate() {
let Some(field) = column.field.as_object() else {
continue;
};
if field.get("data_bar") != Some(&Value::Bool(true)) {
continue;
}
let numbers: Vec<f64> = table
.rows
.iter()
.filter_map(|record| record.get(&column.key))
.filter(|value| !matches!(value, Value::Bool(_)))
.filter_map(|value| pyops::py_float(value).ok())
.collect();
if numbers.len() < 2 {
continue;
}
let min = numbers.iter().copied().fold(f64::INFINITY, f64::min);
let max = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
if min >= max {
continue;
}
let format = ConditionalFormatDataBar::new()
.set_minimum(ConditionalFormatType::Number, min)
.set_maximum(ConditionalFormatType::Number, max)
.set_fill_color(Color::RGB(0x0A2F46));
sheet.add_conditional_format(
header_row + 1,
column_index as u16,
header_row + table.rows.len() as u32,
column_index as u16,
&format,
)?;
}
Ok(())
}
fn add_native_chart(sheet: &mut Worksheet, header_row: u32, table: &Table) -> Result<()> {
let Some(spec) = table.chart.as_ref().and_then(Value::as_object) else {
return Ok(());
};
if table.rows.is_empty() || table.columns.len() < 2 {
return Ok(());
}
let kind = spec.get("kind").and_then(Value::as_str).unwrap_or("bar");
let horizontal = spec.get("orientation").and_then(Value::as_str) == Some("horizontal");
let chart_type = match kind {
"line" => ChartType::Line,
"pie" => ChartType::Pie,
"donut" | "doughnut" => ChartType::Doughnut,
_ if horizontal => ChartType::Bar,
_ => ChartType::Column,
};
let mut chart = Chart::new(chart_type);
let last_row = header_row + table.rows.len() as u32;
let sheet_name = sheet.name().to_string();
let series_label = column_label(&table.columns[1]);
let series_format = spec
.get("color")
.and_then(Value::as_str)
.filter(|color| matches!(color.trim_start_matches('#').len(), 3 | 6))
.and_then(|color| {
let color = rgb(color);
let mut format = ChartFormat::new();
match kind {
"line" => {
let mut line = ChartLine::new();
line.set_color(color).set_width(2.25);
format.set_line(&line);
}
"bar" => {
let mut fill = ChartSolidFill::new();
fill.set_color(color);
format.set_solid_fill(&fill);
}
_ => return None,
}
Some(format)
});
let series = chart.add_series();
series
.set_name(series_label.as_str())
.set_values((sheet_name.as_str(), header_row + 1, 1, last_row, 1))
.set_categories((sheet_name.as_str(), header_row + 1, 0, last_row, 0));
if let Some(mut format) = series_format {
series.set_format(&mut format);
}
let title = spec.get("title").and_then(Value::as_str).unwrap_or(&table.key);
chart.title().set_name(title);
chart.set_style(10).set_width(600).set_height(300);
sheet.insert_chart(header_row, 3, &chart)?;
Ok(())
}
pub fn build_workbook(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>) -> Result<Vec<u8>> {
let mut workbook = Workbook::new();
let mut used = HashSet::new();
let title = meta.and_then(|meta| meta.get("title")).and_then(Value::as_str);
let sub_title = meta.and_then(|meta| meta.get("sub_title")).and_then(Value::as_str);
let symbol = currency_symbol(meta);
let header_format = Format::new()
.set_bold()
.set_font_color(Color::White)
.set_background_color(Color::RGB(0x0A2F46));
let note_format = Format::new().set_italic().set_font_color(Color::RGB(0x6B7280));
let title_format = Format::new().set_bold().set_font_size(14);
if tables.is_empty() && summaries.is_empty() {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name(title.unwrap_or("Report"), &mut used))?;
sheet.write_string_with_format(0, 0, title.unwrap_or("Report"), &title_format)?;
return workbook
.save_to_buffer()
.map_err(|error| Error::message(format!("XLSX error: {error}")));
}
for table in tables {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name(&table.key, &mut used))?;
let mut row_index: u32 = 0;
if let Some(title) = title {
sheet.write_string_with_format(row_index, 0, title, &title_format)?;
row_index += 1;
}
if let Some(sub_title) = sub_title {
sheet.write_string(row_index, 0, sub_title)?;
row_index += 1;
}
let header_row = row_index;
let mut widths: Vec<usize> = vec![0; table.columns.len()];
for (column_index, column) in table.columns.iter().enumerate() {
let label = column_label(column);
sheet.write_string_with_format(row_index, column_index as u16, &label, &header_format)?;
widths[column_index] = widths[column_index].max(label.chars().count());
}
if !table.columns.is_empty() {
sheet.set_freeze_panes(header_row + 1, 0)?;
sheet.autofilter(header_row, 0, header_row, (table.columns.len() - 1) as u16)?;
sheet.set_repeat_rows(header_row, header_row)?;
}
if table.rows.is_empty() && !table.note.is_empty() {
row_index += 1;
sheet.write_string_with_format(row_index, 0, &table.note, ¬e_format)?;
if let Some(width) = widths.first_mut() {
*width = (*width).max(table.note.chars().count());
}
}
for (position, record) in table.rows.iter().enumerate() {
row_index += 1;
let is_total = table.total_rows.contains(&position);
for (column_index, column) in table.columns.iter().enumerate() {
let raw = record.get(&column.key).cloned().unwrap_or(Value::Null);
let format = base_format(&raw, column, is_total);
let format = match number_format(&column.mask, &symbol) {
Some(number_format) => format.set_num_format(number_format),
None => format,
};
let cell = native_cell(&raw, column, meta)?;
let width_text = match &cell {
NativeCell::Number(number) => number.to_string(),
NativeCell::DateTime(_) => pyops::py_str(&raw),
NativeCell::Bool(value) => value.to_string(),
NativeCell::Text(text) => text.clone(),
NativeCell::Empty => String::new(),
};
match cell {
NativeCell::Number(number) => {
sheet.write_number_with_format(row_index, column_index as u16, number, &format)?;
}
NativeCell::DateTime(datetime) => {
sheet.write_datetime_with_format(row_index, column_index as u16, &datetime, &format)?;
}
NativeCell::Bool(value) => {
sheet.write_boolean_with_format(row_index, column_index as u16, value, &format)?;
}
NativeCell::Text(text) => {
let text = guard_formula(&text, &raw);
sheet.write_string_with_format(row_index, column_index as u16, &text, &format)?;
}
NativeCell::Empty => {
sheet.write_blank(row_index, column_index as u16, &format)?;
}
}
widths[column_index] = widths[column_index].max(width_text.chars().count());
}
}
for (column_index, width) in widths.iter().enumerate() {
sheet.set_column_width(column_index as u16, (*width + 2).clamp(10, 50) as f64)?;
}
add_data_bars(sheet, header_row, table)?;
add_native_chart(sheet, header_row, table)?;
}
if !summaries.is_empty() {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name("Summary", &mut used))?;
let mut row_index: u32 = 0;
if let Some(title) = title {
sheet.write_string_with_format(row_index, 0, title, &title_format)?;
row_index += 1;
}
sheet.write_string_with_format(row_index, 0, "Item", &header_format)?;
sheet.write_string_with_format(row_index, 1, "Value", &header_format)?;
let mut widths = [4usize, 5usize];
for row in summaries {
row_index += 1;
sheet.write_string(row_index, 0, &row.label)?;
if let Some(number) = numeric_value(&row.value, &row.mask) {
let format = number_format(&row.mask, &symbol)
.map(|format| Format::new().set_num_format(format))
.unwrap_or_default();
sheet.write_number_with_format(row_index, 1, number, &format)?;
} else {
let text = display_text(
&row.value,
&Column {
key: String::new(),
label: String::new(),
mask: row.mask.clone(),
rules: Vec::new(),
field: Value::Null,
},
meta,
)?;
sheet.write_string(row_index, 1, &text)?;
}
widths[0] = widths[0].max(row.label.chars().count());
widths[1] = widths[1].max(16);
}
sheet.set_column_width(0, widths[0].clamp(4, 60) as f64)?;
sheet.set_column_width(1, widths[1].clamp(5, 30) as f64)?;
}
let mut note_rows: Vec<(String, String, String)> = Vec::new();
if let Some(source_note) = meta.and_then(|meta| meta.get("source_note")).and_then(Value::as_str) {
note_rows.push((String::new(), "source".to_string(), source_note.to_string()));
}
for table in tables {
for (ref_, text) in &table.notes {
note_rows.push((table.key.clone(), ref_.clone(), text.clone()));
}
}
if !note_rows.is_empty() {
let sheet = workbook.add_worksheet();
sheet.set_name(sheet_name("Notes", &mut used))?;
sheet.write_string_with_format(0, 0, "Table", &header_format)?;
sheet.write_string_with_format(0, 1, "Ref", &header_format)?;
sheet.write_string_with_format(0, 2, "Note", &header_format)?;
let mut widths = [5usize, 3usize, 4usize];
for (index, (table, ref_, text)) in note_rows.iter().enumerate() {
let row = index as u32 + 1;
sheet.write_string(row, 0, table)?;
sheet.write_string(row, 1, ref_)?;
sheet.write_string(row, 2, text)?;
widths[0] = widths[0].max(table.chars().count());
widths[1] = widths[1].max(ref_.chars().count());
widths[2] = widths[2].max(text.chars().count());
}
sheet.set_column_width(0, widths[0].clamp(5, 40) as f64)?;
sheet.set_column_width(1, widths[1].clamp(3, 12) as f64)?;
sheet.set_column_width(2, widths[2].clamp(4, 80) as f64)?;
}
workbook
.save_to_buffer()
.map_err(|error| Error::message(format!("XLSX error: {error}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::service::prepare_report;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
fn prepared(payload: serde_json::Value) -> (Value, Value, Value) {
let payload = value(payload);
let prepared = prepare_report(&payload, None).unwrap();
(prepared.dataset, prepared.layout, prepared.meta.to_value())
}
#[test]
fn collects_tables_structure() {
let (dataset, layout, _meta) = prepared(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"},
"items": {
"qty": {"label": "Qty", "format_mask": "int", "alignment": "right", "aggregate": "sum"},
"unit_price": {"label": "Unit", "format_mask": "float", "alignment": "right"}
}
}
},
"data": [{"company": "ACME", "orders": [
{"order": 1, "total": 4000, "items": [{"qty": 1, "unit_price": 1500}, {"qty": 2, "unit_price": 1250}]},
{"order": 2, "total": 2000, "items": [{"qty": 4, "unit_price": 500}]}
]}]
}));
let (tables, summaries) = collect_tables(&dataset, &layout, None);
assert_eq!(tables.len(), 1);
let items = &tables[0];
assert_eq!(items.key, "items");
assert_eq!(
items.columns.iter().map(|column| column.label.clone()).collect::<Vec<_>>(),
["Company", "Code", "Total", "Qty", "Unit"]
);
assert_eq!(items.rows.len(), 5);
assert_eq!(items.total_rows, HashSet::from([2, 4]));
assert!(summaries.iter().any(|row| row.label == "ACME / Total"));
assert!(summaries.iter().any(|row| row.label == "Total"));
}
#[test]
fn csv_content_and_delimiter() {
let (dataset, layout, meta) = prepared(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 (tables, summaries) = collect_tables(&dataset, &layout, Some(&meta));
let text = render_csv(&tables, &summaries, Some(&meta), ',').unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines[0], "# Order");
assert_eq!(lines[1], "# table: orders");
assert_eq!(lines[2], "Company,Code,Total");
assert!(text.contains("ACME,750,\"4.000,00\""));
assert!(text.contains("# summary"));
let semi = render_csv(&tables, &summaries, Some(&meta), ';').unwrap();
assert!(semi.contains("Company;Code;Total"));
}
#[test]
fn csv_guards_formulas_but_not_numbers() {
let (dataset, layout, meta) = prepared(json!({
"meta": {"title": "T"},
"layout": {"a": {"label": "A"}, "n": {"label": "N", "format_mask": "float"}},
"data": [{"a": "=1+1", "n": -5}, {"a": "@SUM(A1)", "n": 3}]
}));
let (tables, summaries) = collect_tables(&dataset, &layout, Some(&meta));
let text = render_csv(&tables, &summaries, Some(&meta), ',').unwrap();
assert!(text.contains("'=1+1"));
assert!(text.contains("'@SUM(A1)"));
assert!(!text.contains("'-5"));
}
#[test]
fn sections_export() {
let (dataset, layout, meta) = prepared(json!({
"meta": {"title": "Board Pack", "mode": "exact"},
"sections": [
{"type": "text", "title": "Intro", "paragraphs": ["Hello."]},
{"type": "table", "title": "Sales", "layout": {"product": {"label": "Product", "format_mask": "str", "alignment": "left"}}, "data": [{"product": "Pen"}]},
{"type": "kpi", "title": "Totals", "items": [{"label": "Orders", "value": 42}]},
{"type": "chart", "title": "Trend", "chart": {"kind": "bar", "labels": ["Jan", "Feb"], "values": [10, 20]}}
]
}));
let (tables, _summaries) = collect_tables(&dataset, &layout, Some(&meta));
let keys: HashSet<String> = tables.iter().map(|table| table.key.clone()).collect();
assert!(keys.contains("Sales"));
assert!(keys.contains("Intro"));
assert!(keys.contains("Totals"));
assert!(keys.contains("Trend"));
let text = render_csv(&tables, &_summaries, Some(&meta), ',').unwrap();
assert!(text.contains("# table: Sales"));
assert!(text.contains("Pen"));
}
}