use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use indexmap::IndexMap;
use crate::error::{Error, Result};
use crate::formatting::{
assign_footnote_mark, assign_footnote_marks, field_visible, format_field, match_rule, normalize_color_scale, normalize_footnote,
scale_fill, CellStyle, FootnoteState,
};
use crate::payload::type_name;
use crate::pyops;
use crate::value::Value;
pub const AGGREGATIONS: [&str; 7] = ["sum", "count", "avg", "min", "max", "median", "distinct"];
fn is_field_def(value: &Value) -> bool {
value.as_object().is_some_and(|object| object.contains_key("label"))
}
fn is_group_node(value: &Value) -> bool {
value.as_object().is_some_and(|object| !object.contains_key("label"))
}
pub fn split_layout_node(node: &IndexMap<String, Value>) -> (IndexMap<String, Value>, IndexMap<String, Value>, IndexMap<String, Value>) {
let mut fields = IndexMap::new();
let mut groups = IndexMap::new();
let mut options = IndexMap::new();
for (key, value) in node {
if let Some(option) = key.strip_prefix('$') {
options.insert(option.to_string(), value.clone());
} else if is_field_def(value) {
fields.insert(key.clone(), value.clone());
} else if is_group_node(value) {
groups.insert(key.clone(), value.clone());
}
}
(fields, groups, options)
}
pub fn evaluate_condition(row: &Value, condition: &IndexMap<String, Value>) -> Result<bool> {
let Some(field) = condition.get("field").and_then(Value::as_str) else {
return Err(Error::option(format!(
"Condition needs a field name: {}",
pyops::py_str(&Value::Object(condition.clone()))
)));
};
let value = row.get(field).unwrap_or(&Value::Null);
match_rule(value, condition)
}
pub fn filter_rows(rows: &[Value], print_when: Option<&Value>) -> Result<Vec<Value>> {
let Some(print_when) = print_when.filter(|value| value.truthy()) else {
return Ok(rows.to_vec());
};
let Some(condition) = print_when.as_object() else {
return Err(Error::option(format!(
"Invalid $print_when condition: {}",
pyops::py_str(print_when)
)));
};
if !condition.contains_key("field") {
return Err(Error::option(format!(
"Invalid $print_when condition: {}",
pyops::py_str(print_when)
)));
}
let mut out = Vec::new();
for row in rows {
if row.is_object() && evaluate_condition(row, condition)? {
out.push(row.clone());
}
}
Ok(out)
}
pub fn sort_rows(rows: &[Value], order_by: Option<&Value>) -> Result<Vec<Value>> {
let Some(order_by) = order_by.filter(|value| value.truthy()) else {
return Ok(rows.to_vec());
};
let specs: Vec<&Value> = match order_by {
Value::Array(values) => values.iter().collect(),
other => vec![other],
};
let mut result = rows.to_vec();
for spec in specs.into_iter().rev() {
let (field, direction) = match spec {
Value::Object(object) => {
let field = object.get("field").and_then(Value::as_str);
let direction = object.get("direction").and_then(Value::as_str).unwrap_or("asc");
(field, direction)
}
Value::String(text) => {
if let Some(field) = text.strip_prefix('-') {
(Some(field), "desc")
} else {
(Some(text.as_str()), "asc")
}
}
_ => return Err(Error::option(format!("Invalid $order_by spec: {}", pyops::py_str(spec)))),
};
let Some(field) = field else {
return Err(Error::option(format!(
"Invalid $order_by spec (needs a field name): {}",
pyops::py_str(spec)
)));
};
if !matches!(direction, "asc" | "desc") {
return Err(Error::option(format!("Invalid sort direction: {direction:?}")));
}
result.sort_by(|left, right| {
let left = left.get(field).unwrap_or(&Value::Null);
let right = right.get(field).unwrap_or(&Value::Null);
pyops::sort_key(left).cmp(&pyops::sort_key(right))
});
if direction == "desc" {
let mut non_null = Vec::new();
let mut nulls = Vec::new();
for row in result {
if row.get(field).is_some_and(|value| !value.is_null()) {
non_null.push(row);
} else {
nulls.push(row);
}
}
non_null.reverse();
non_null.extend(nulls);
result = non_null;
}
}
Ok(result)
}
fn child_records(record: &Value, key: &str) -> Result<Vec<Value>> {
let value = record.get(key);
match value {
None | Some(Value::Null) => Ok(Vec::new()),
Some(value) if value.is_object() || !value.is_array() => Err(Error::option(format!(
"Group field {key:?} must be a list of records, got {}",
type_name(value)
))),
Some(value) => Ok(value
.as_array()
.map(|rows| rows.iter().filter(|row| row.is_object()).cloned().collect())
.unwrap_or_default()),
}
}
fn field_visible_checked(field_def: &Value, rows: &[Value]) -> Result<bool> {
field_visible(field_def, rows)
}
pub fn aggregate_values(rows: &[Value], field: &str, func: &str) -> Result<Value> {
if !AGGREGATIONS.contains(&func) {
return Err(Error::option(format!(
"Unknown aggregate: {func:?} (expected one of {AGGREGATIONS:?})"
)));
}
if func == "count" {
return Ok(Value::UInt(rows.iter().filter(|row| row.is_object()).count() as u64));
}
if func == "distinct" {
let mut seen = HashSet::new();
for row in rows {
let Some(object) = row.as_object() else {
continue;
};
let Some(value) = object.get(field) else {
continue;
};
if value.is_null() {
continue;
}
if let Some(key) = pyops::distinct_key(value) {
seen.insert(key);
}
}
return Ok(Value::UInt(seen.len() as u64));
}
let mut numbers = Vec::new();
for row in rows {
let Some(object) = row.as_object() else {
continue;
};
let Some(value) = object.get(field) else {
continue;
};
if let Ok(number) = pyops::py_float(value) {
numbers.push(number);
}
}
if numbers.is_empty() {
return Ok(Value::String(String::new()));
}
let value = match func {
"sum" => numbers.iter().sum(),
"avg" => numbers.iter().sum::<f64>() / numbers.len() as f64,
"min" => numbers.iter().copied().fold(f64::INFINITY, f64::min),
"max" => numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max),
"median" => {
let mut sorted = numbers.clone();
sorted.sort_by(|left, right| left.partial_cmp(right).unwrap_or(Ordering::Equal));
let middle = sorted.len() / 2;
if sorted.len() % 2 == 0 {
(sorted[middle - 1] + sorted[middle]) / 2.0
} else {
sorted[middle]
}
}
_ => unreachable!("aggregate validated"),
};
Ok(Value::Float(value))
}
pub fn color_domain(values: &[Value]) -> Option<(f64, f64)> {
let mut numbers = Vec::new();
for value in values {
match value {
Value::Int(value) => numbers.push(*value as f64),
Value::UInt(value) => numbers.push(*value as f64),
Value::Float(value) => numbers.push(*value),
_ => {}
}
}
if numbers.is_empty() {
None
} else {
Some((
numbers.iter().copied().fold(f64::INFINITY, f64::min),
numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max),
))
}
}
fn apply_color_domains(fields: &mut [Value], rows: &[Value]) {
for field in fields {
let Some(object) = field.as_object() else {
continue;
};
if !object.contains_key("color_scale") {
continue;
}
let Some(name) = object.get("name").and_then(Value::as_str) else {
continue;
};
let values: Vec<Value> = rows.iter().filter_map(|row| row.get(name).cloned()).collect();
if let Some((low, high)) = color_domain(&values) {
if let Some(object) = field.as_object_mut() {
object.insert(
"color_domain".to_string(),
Value::Array(vec![Value::Float(low), Value::Float(high)]),
);
}
}
}
}
fn py_title(value: &str) -> String {
let mut out = String::with_capacity(value.len());
let mut previous_cased = false;
for ch in value.chars() {
if ch.is_alphabetic() {
if previous_cased {
out.extend(ch.to_lowercase());
} else {
out.extend(ch.to_uppercase());
}
previous_cased = true;
} else {
out.push(ch);
previous_cased = false;
}
}
out
}
pub fn convert_layout(layout_raw: &IndexMap<String, Value>) -> Result<Value> {
let mut header = Vec::new();
let mut groups: Option<IndexMap<String, Value>> = None;
for (key, value) in layout_raw {
if is_field_def(value) {
header.push(format_field(key, value.as_object().unwrap())?);
} else if let Some(object) = value.as_object() {
let mut field_header = Vec::new();
let mut detail = Vec::new();
for (sub_key, sub_value) in object {
if is_field_def(sub_value) {
field_header.push(format_field(sub_key, sub_value.as_object().unwrap())?);
} else if let Some(sub_object) = sub_value.as_object() {
for (inner_key, inner_value) in sub_object {
if is_field_def(inner_value) {
detail.push(format_field(inner_key, inner_value.as_object().unwrap())?);
}
}
}
}
let groups = groups.get_or_insert_with(IndexMap::new);
groups.insert("header".to_string(), Value::Array(field_header));
if !detail.is_empty() {
groups.insert("detail".to_string(), Value::Array(detail));
}
}
}
let mut result = IndexMap::new();
result.insert("header".to_string(), Value::Array(header));
if let Some(groups) = groups {
result.insert("groups".to_string(), Value::Object(groups));
}
let mut root = IndexMap::new();
root.insert("groups".to_string(), Value::Object(result));
Ok(Value::Object(root))
}
pub fn is_template_format(data: &[Value]) -> bool {
data.first()
.and_then(Value::as_object)
.is_some_and(|object| object.contains_key("fields"))
}
pub fn convert_data(data_raw: &[Value], layout_raw: &IndexMap<String, Value>) -> Result<Value> {
if is_template_format(data_raw) {
let mut root = IndexMap::new();
root.insert("groups".to_string(), Value::Array(data_raw.to_vec()));
return Ok(Value::Object(root));
}
let group_keys: IndexMap<String, Value> = layout_raw
.iter()
.filter(|(_, value)| is_group_node(value))
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let mut items = Vec::new();
for record in data_raw {
let Some(record) = record.as_object() else {
return Err(Error::option("Invalid data record (must be an object)"));
};
let mut fields = IndexMap::new();
let mut groups = Vec::new();
for (key, value) in record {
if let Some(sub_layout) = group_keys.get(key) {
let sub_layout = sub_layout.as_object().expect("group object");
let detail_key = sub_layout
.iter()
.find(|(_, value)| is_group_node(value))
.map(|(key, _)| key.clone());
let Some(sub_items) = value.as_array() else {
return Err(Error::option(format!("Group field {key:?} must be a list of records")));
};
for sub_item in sub_items {
let Some(sub_item) = sub_item.as_object() else {
continue;
};
let mut sub_fields = IndexMap::new();
for sub_key in sub_layout.keys() {
if Some(sub_key) == detail_key.as_ref() {
continue;
}
if let Some(value) = sub_item.get(sub_key) {
sub_fields.insert(sub_key.clone(), value.clone());
}
}
let detail = detail_key
.as_ref()
.and_then(|key| sub_item.get(key))
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut group_entry = IndexMap::new();
group_entry.insert("fields".to_string(), Value::Object(sub_fields));
if !detail.is_empty() {
group_entry.insert("detail".to_string(), Value::Array(detail));
}
groups.push(Value::Object(group_entry));
}
} else {
fields.insert(key.clone(), value.clone());
}
}
let mut item = IndexMap::new();
item.insert("fields".to_string(), Value::Object(fields));
if !groups.is_empty() {
item.insert("groups".to_string(), Value::Array(groups));
}
items.push(Value::Object(item));
}
let mut root = IndexMap::new();
root.insert("groups".to_string(), Value::Array(items));
Ok(Value::Object(root))
}
pub fn infer_layout(data: &[Value]) -> Value {
let sample = data.first().and_then(Value::as_object).cloned().unwrap_or_default();
let mut header = Vec::new();
for (key, value) in &sample {
if value.is_array() {
continue;
}
let (dtype, alignment) = match value {
Value::Int(_) | Value::UInt(_) => ("int", "right"),
Value::Float(_) | Value::Decimal(_) => ("float", "right"),
_ => ("str", "left"),
};
let mut field = IndexMap::new();
field.insert("name".to_string(), Value::String(key.clone()));
field.insert("label".to_string(), Value::String(py_title(&key.replace('_', " "))));
field.insert("format_mask".to_string(), Value::String(dtype.to_string()));
field.insert("alignment".to_string(), Value::String(alignment.to_string()));
header.push(Value::Object(field));
}
let mut groups = IndexMap::new();
groups.insert("header".to_string(), Value::Array(header));
let mut root = IndexMap::new();
root.insert("groups".to_string(), Value::Object(groups));
Value::Object(root)
}
pub fn template_header_layout(data: &[Value]) -> Result<Value> {
let sample = data
.first()
.and_then(Value::as_object)
.and_then(|object| object.get("fields"))
.and_then(Value::as_object)
.cloned()
.unwrap_or_default();
let mut header = Vec::new();
for key in sample.keys() {
header.push(format_field(key, &IndexMap::new())?);
}
let mut groups = IndexMap::new();
groups.insert("header".to_string(), Value::Array(header));
let mut root = IndexMap::new();
root.insert("groups".to_string(), Value::Object(groups));
Ok(Value::Object(root))
}
pub fn build_report(data_raw: &[Value], layout_raw: &IndexMap<String, Value>) -> Result<(Value, Value)> {
for (index, record) in data_raw.iter().enumerate() {
if !record.is_object() {
return Err(Error::option(format!("Invalid data record at index {index} (must be an object)")));
}
}
let filtered = filter_rows(data_raw, layout_raw.get("$print_when"))?;
let rows = sort_rows(&filtered, layout_raw.get("$order_by"))?;
let mut items = Vec::with_capacity(rows.len());
for record in &rows {
items.push(convert_item(record, layout_raw)?);
}
let inner = build_layout(layout_raw, &rows)?;
let (summary, summary_defs) = collect_summary(&rows, layout_raw)?;
let mut dataset = IndexMap::new();
dataset.insert("groups".to_string(), Value::Array(items));
dataset.insert(
"summary".to_string(),
if summary.is_empty() { Value::Null } else { Value::Object(summary) },
);
let mut layout = IndexMap::new();
layout.insert("groups".to_string(), inner);
if !summary_defs.is_empty() {
let mut summary_layout = Vec::new();
for (field, definition) in summary_defs {
summary_layout.push(format_field(&field, definition.as_object().expect("field object"))?);
}
layout.insert("summary".to_string(), Value::Array(summary_layout));
}
Ok((Value::Object(dataset), Value::Object(layout)))
}
fn meaningful(values: IndexMap<String, Value>) -> Option<IndexMap<String, Value>> {
if values.is_empty() {
return None;
}
if values
.values()
.any(|value| !value.is_null() && !matches!(value, Value::String(text) if text.is_empty()))
{
Some(values)
} else {
None
}
}
fn has_nested_groups(node: &IndexMap<String, Value>) -> bool {
node.iter().any(|(key, value)| !key.starts_with('$') && is_group_node(value))
}
fn collect_summary(rows: &[Value], node: &IndexMap<String, Value>) -> Result<(IndexMap<String, Value>, IndexMap<String, Value>)> {
let (field_defs, group_nodes, _) = split_layout_node(node);
let mut summary = IndexMap::new();
let mut defs = IndexMap::new();
for (field, definition) in &field_defs {
let Some(func) = definition.get("aggregate").and_then(Value::as_str) else {
continue;
};
let value = aggregate_values(rows, field, func)?;
if !value.is_null() && !matches!(&value, Value::String(text) if text.is_empty()) {
summary.insert(field.clone(), value);
defs.insert(field.clone(), definition.clone());
}
}
for (group_key, sub) in &group_nodes {
let mut kids = Vec::new();
for row in rows {
kids.extend(child_records(row, group_key)?);
}
let sub = sub.as_object().expect("group object");
let (sub_summary, sub_defs) = collect_summary(&kids, sub)?;
for (field, value) in sub_summary {
if !summary.contains_key(&field) {
if let Some(definition) = sub_defs.get(&field) {
summary.insert(field.clone(), value);
defs.insert(field, definition.clone());
}
}
}
}
Ok((summary, defs))
}
fn visible_fields(field_defs: &IndexMap<String, Value>, rows: &[Value]) -> Result<Vec<String>> {
let mut out = Vec::new();
for (name, definition) in field_defs {
if field_visible_checked(definition, rows)? {
out.push(name.clone());
}
}
Ok(out)
}
fn convert_item(record: &Value, node: &IndexMap<String, Value>) -> Result<Value> {
let (field_defs, group_nodes, _) = split_layout_node(node);
let mut fields = IndexMap::new();
for key in field_defs.keys() {
if let Some(value) = record.get(key) {
fields.insert(key.clone(), value.clone());
}
}
let mut groups = Vec::new();
let mut details = IndexMap::new();
let mut footer_funcs: IndexMap<String, String> = IndexMap::new();
let mut footer_rows: IndexMap<String, Vec<Value>> = IndexMap::new();
for (key, sub_node) in &group_nodes {
let sub_node = sub_node.as_object().expect("group object");
let mut children = child_records(record, key)?;
children = filter_rows(&children, sub_node.get("$print_when"))?;
children = sort_rows(&children, sub_node.get("$order_by"))?;
let (sub_fields, _, _) = split_layout_node(sub_node);
children = apply_running_balance(&children, &sub_fields)?;
if has_nested_groups(sub_node) {
for (field, definition) in &sub_fields {
if definition.get("aggregate").is_some() && !footer_funcs.contains_key(field) {
if let Some(func) = definition.get("aggregate").and_then(Value::as_str) {
footer_funcs.insert(field.clone(), func.to_string());
footer_rows.insert(field.clone(), children.clone());
}
}
}
for child in &children {
groups.push(convert_item(child, sub_node)?);
}
} else {
let mut table = IndexMap::new();
table.insert("rows".to_string(), Value::Array(children.clone()));
let mut table_footer = IndexMap::new();
for (field, definition) in &sub_fields {
if let Some(func) = definition.get("aggregate").and_then(Value::as_str) {
table_footer.insert(field.clone(), aggregate_values(&children, field, func)?);
}
}
if let Some(footer) = meaningful(table_footer) {
table.insert("footer".to_string(), Value::Object(footer));
}
if let Some(empty_text) = sub_node.get("empty_text").and_then(Value::as_str) {
if !empty_text.is_empty() {
table.insert("empty_text".to_string(), Value::String(empty_text.to_string()));
}
}
if !children.is_empty() || table.contains_key("empty_text") {
details.insert(key.clone(), Value::Object(table));
}
}
}
let mut item = IndexMap::new();
item.insert("fields".to_string(), Value::Object(fields));
if !groups.is_empty() {
item.insert("groups".to_string(), Value::Array(groups));
}
if !details.is_empty() {
item.insert("details".to_string(), Value::Object(details));
}
let mut computed_footer = IndexMap::new();
for (field, func) in &footer_funcs {
if let Some(rows) = footer_rows.get(field) {
computed_footer.insert(field.clone(), aggregate_values(rows, field, func)?);
}
}
if let Some(footer) = meaningful(computed_footer) {
item.insert("footer".to_string(), Value::Object(footer));
}
Ok(Value::Object(item))
}
fn apply_running_balance(rows: &[Value], field_defs: &IndexMap<String, Value>) -> Result<Vec<Value>> {
let mut specs: IndexMap<String, (String, f64)> = IndexMap::new();
for (key, definition) in field_defs {
let Some(spec) = definition.get("running_balance") else {
continue;
};
match spec {
Value::String(source) => {
specs.insert(key.clone(), (source.clone(), 0.0));
}
Value::Object(object) if object.get("of").and_then(Value::as_str).is_some() => {
let source = object.get("of").and_then(Value::as_str).unwrap_or_default().to_string();
let start = object.get("start").filter(|value| value.truthy());
let start = match start {
Some(value) => pyops::py_float(value)
.map_err(|_| Error::option(format!("Invalid running_balance start for {key:?}: {}", pyops::py_str(spec))))?,
None => 0.0,
};
specs.insert(key.clone(), (source, start));
}
Value::Null => {}
_ => {
return Err(Error::option(format!(
"Invalid running_balance spec for {key:?}: {}",
pyops::py_str(spec)
)))
}
}
}
if specs.is_empty() || rows.is_empty() {
return Ok(rows.to_vec());
}
let mut balances: HashMap<String, f64> = HashMap::new();
let mut out = Vec::with_capacity(rows.len());
for row in rows {
let mut row = row.clone();
if let Some(object) = row.as_object_mut() {
for (key, (source, start)) in &specs {
let balance = balances.entry(key.clone()).or_insert(*start);
let delta = object
.get(source)
.filter(|value| value.truthy())
.and_then(|value| pyops::py_float(value).ok())
.unwrap_or(0.0);
*balance += delta;
object.insert(key.clone(), Value::Float(*balance));
}
}
out.push(row);
}
Ok(out)
}
fn build_layout(node: &IndexMap<String, Value>, rows: &[Value]) -> Result<Value> {
let (field_defs, group_nodes, _) = split_layout_node(node);
let visible = visible_fields(&field_defs, rows)?;
let mut header = Vec::new();
for name in &visible {
header.push(format_field(name, field_defs.get(name).and_then(Value::as_object).expect("field"))?);
}
apply_color_domains(&mut header, rows);
let mut child_rows: IndexMap<String, Vec<Value>> = IndexMap::new();
for group_key in group_nodes.keys() {
let mut kids = Vec::new();
for row in rows {
kids.extend(child_records(row, group_key)?);
}
child_rows.insert(group_key.clone(), kids);
}
let mut footer = Vec::new();
let mut seen = HashSet::new();
for (group_key, sub) in &group_nodes {
let sub = sub.as_object().expect("group object");
if !has_nested_groups(sub) {
continue;
}
let (sub_fields, _, _) = split_layout_node(sub);
let kids = child_rows.get(group_key).cloned().unwrap_or_default();
for field in visible_fields(&sub_fields, &kids)? {
if sub_fields.get(&field).and_then(|definition| definition.get("aggregate")).is_some() && seen.insert(field.clone()) {
footer.push(format_field(
&field,
sub_fields.get(&field).and_then(Value::as_object).expect("field"),
)?);
}
}
}
let nested_key = group_nodes
.iter()
.find(|(_, value)| has_nested_groups(value.as_object().expect("group object")))
.map(|(key, _)| key.clone());
let child_layout = match nested_key {
Some(key) => {
let sub = group_nodes.get(&key).and_then(Value::as_object).expect("group object");
let kids = child_rows.get(&key).cloned().unwrap_or_default();
Some(build_layout(sub, &kids)?)
}
None => None,
};
let mut details = IndexMap::new();
for (group_key, sub) in &group_nodes {
let sub = sub.as_object().expect("group object");
if has_nested_groups(sub) {
continue;
}
let (sub_fields, _, _) = split_layout_node(sub);
let kids = child_rows.get(group_key).cloned().unwrap_or_default();
let mut columns = Vec::new();
for field in visible_fields(&sub_fields, &kids)? {
columns.push(format_field(
&field,
sub_fields.get(&field).and_then(Value::as_object).expect("field"),
)?);
}
apply_color_domains(&mut columns, &kids);
details.insert(group_key.clone(), Value::Array(columns));
}
let mut fragment = IndexMap::new();
fragment.insert("header".to_string(), Value::Array(header));
if let Some(child_layout) = child_layout {
fragment.insert("groups".to_string(), child_layout);
}
if !details.is_empty() {
fragment.insert("details".to_string(), Value::Object(details));
}
if !footer.is_empty() {
fragment.insert("footer".to_string(), Value::Array(footer));
}
Ok(Value::Object(fragment))
}
fn take_footnotes(fields: Option<&Value>, found: &mut Vec<(String, String)>, seen: &mut HashSet<String>) {
let Some(fields) = fields.and_then(Value::as_array) else {
return;
};
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;
}
found.push((
mark.to_string(),
note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
));
}
}
pub fn collect_footnotes(fragment: &Value) -> Vec<(String, String)> {
let mut found = Vec::new();
let mut seen = HashSet::new();
fn visit(fragment: &Value, found: &mut Vec<(String, String)>, seen: &mut HashSet<String>) {
let Some(object) = fragment.as_object() else {
return;
};
take_footnotes(object.get("header"), found, seen);
if let Some(details) = object.get("details").and_then(Value::as_object) {
for fields in details.values() {
take_footnotes(Some(fields), found, seen);
}
}
if let Some(groups) = object.get("groups") {
visit(groups, found, seen);
}
take_footnotes(object.get("footer"), found, seen);
}
if let Some(object) = fragment.as_object() {
visit(object.get("groups").unwrap_or(fragment), &mut found, &mut seen);
take_footnotes(object.get("summary"), &mut found, &mut seen);
}
found
}
pub fn assign_report_footnotes(layout: &mut Value, sections: Option<&mut Vec<Value>>) -> Result<()> {
let mut state = FootnoteState::default();
fn visit(fragment: &mut Value, state: &mut FootnoteState) -> Result<()> {
let Some(object) = fragment.as_object_mut() else {
return Ok(());
};
if let Some(header) = object.get_mut("header").and_then(Value::as_array_mut) {
assign_footnote_marks(header, state)?;
}
if let Some(details) = object.get_mut("details").and_then(Value::as_object_mut) {
for fields in details.values_mut() {
if let Some(fields) = fields.as_array_mut() {
assign_footnote_marks(fields, state)?;
}
}
}
if let Some(groups) = object.get_mut("groups") {
visit(groups, state)?;
}
if let Some(footer) = object.get_mut("footer").and_then(Value::as_array_mut) {
assign_footnote_marks(footer, state)?;
}
Ok(())
}
if layout.is_object() {
if layout.get("groups").is_some() {
if let Some(groups) = layout.get_mut("groups") {
visit(groups, &mut state)?;
}
} else {
visit(layout, &mut state)?;
}
if let Some(summary) = layout.get_mut("summary").and_then(Value::as_array_mut) {
assign_footnote_marks(summary, &mut state)?;
}
}
if let Some(sections) = sections {
for section in sections {
let Some(section) = section.as_object_mut() else {
continue;
};
let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table").to_string();
match section_type.as_str() {
"table" => {
if let Some(section_layout) = section.get_mut("layout") {
if section_layout.is_object() {
if section_layout.get("groups").is_some() {
if let Some(groups) = section_layout.get_mut("groups") {
visit(groups, &mut state)?;
}
} else {
visit(section_layout, &mut state)?;
}
if let Some(summary) = section_layout.get_mut("summary").and_then(Value::as_array_mut) {
assign_footnote_marks(summary, &mut state)?;
}
}
}
}
"crosstab" => {
if let Some(crosstab) = section.get_mut("crosstab").and_then(Value::as_object_mut) {
for key in ["row_field", "col_field", "measure_field"] {
if let Some(field) = crosstab.get_mut(key) {
assign_footnote_mark(field, &mut state)?;
}
}
}
}
"kpi" => {
if let Some(items) = section.get_mut("items").and_then(Value::as_array_mut) {
assign_footnote_marks(items, &mut state)?;
}
}
_ => {}
}
}
}
Ok(())
}
pub fn color_scale(spec: &Value, where_: &str) -> Result<Value> {
Ok(normalize_color_scale(spec, where_)?.to_value())
}
pub fn footnote(spec: &Value, where_: &str) -> Result<Value> {
Ok(normalize_footnote(spec, where_)?.to_value())
}
pub fn field_scale_fill(value: &Value, field: &Value) -> Option<String> {
scale_fill(value, field)
}
pub fn field_cell_style(value: &Value, field: &Value) -> Result<CellStyle> {
crate::formatting::cell_style_dict(value, field)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
fn object(value: serde_json::Value) -> IndexMap<String, Value> {
Value::from_json(value).as_object().unwrap().clone()
}
#[test]
fn empty_layout() {
assert_eq!(
convert_layout(&IndexMap::new()).unwrap().to_json(),
json!({"groups": {"header": []}})
);
}
#[test]
fn simple_layout_and_infer() {
let layout = object(json!({
"name": {"label": "Name", "format_mask": "str", "alignment": "left"},
"age": {"label": "Age", "format_mask": "int", "alignment": "right"}
}));
let result = convert_layout(&layout).unwrap();
assert_eq!(
result
.get("groups")
.and_then(|groups| groups.get("header"))
.and_then(Value::as_array)
.map(|v| v.len()),
Some(2)
);
let inferred = infer_layout(&[value(
json!({"name": "John", "age": 30, "price": 9.9, "active": true, "items": [1]}),
)]);
let header = inferred
.get("groups")
.and_then(|groups| groups.get("header"))
.and_then(Value::as_array)
.unwrap();
let masks: HashMap<&str, &str> = header
.iter()
.map(|field| {
(
field.get("name").and_then(Value::as_str).unwrap(),
field.get("format_mask").and_then(Value::as_str).unwrap(),
)
})
.collect();
assert_eq!(masks.get("age"), Some(&"int"));
assert_eq!(masks.get("price"), Some(&"float"));
assert_eq!(masks.get("active"), Some(&"str"));
assert!(!masks.contains_key("items"));
}
#[test]
fn build_report_footers_and_summary() {
let layout = object(json!({
"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"}
}
}
}));
let data = vec![value(json!({
"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 (dataset, layout) = build_report(&data, &layout).unwrap();
let company = &dataset.get("groups").and_then(Value::as_array).unwrap()[0];
assert_eq!(
company.get("footer").and_then(|f| f.get("total")).and_then(Value::as_f64),
Some(6000.0)
);
let first = &company.get("groups").and_then(Value::as_array).unwrap()[0];
assert_eq!(
first
.get("details")
.and_then(|d| d.get("items"))
.and_then(|t| t.get("footer"))
.and_then(|f| f.get("qty"))
.and_then(Value::as_i64),
Some(3)
);
assert_eq!(
dataset.get("summary").and_then(|s| s.get("total")).and_then(Value::as_f64),
Some(6000.0)
);
assert_eq!(dataset.get("summary").and_then(|s| s.get("qty")).and_then(Value::as_i64), Some(7));
assert_eq!(layout.get("summary").and_then(Value::as_array).map(|v| v.len()), Some(2));
}
#[test]
fn print_when_and_order_by() {
let layout = object(json!({
"company": {"label": "Company", "format_mask": "str", "alignment": "left"},
"orders": {
"order": {"label": "Code", "format_mask": "int", "alignment": "right"},
"$print_when": {"field": "status", "not_equals": "cancelled"},
"$order_by": "-order"
}
}));
let data = vec![value(json!({
"company": "ACME",
"orders": [
{"order": 1, "status": "paid"},
{"order": 3, "status": "cancelled"},
{"order": 2, "status": "paid"}
]
}))];
let (dataset, _) = build_report(&data, &layout).unwrap();
let rows = dataset.get("groups").and_then(Value::as_array).unwrap()[0]
.get("details")
.and_then(|details| details.get("orders"))
.and_then(|table| table.get("rows"))
.and_then(Value::as_array)
.unwrap();
let orders: Vec<i64> = rows.iter().filter_map(|row| row.get("order").and_then(Value::as_i64)).collect();
assert_eq!(orders, [2, 1]);
}
#[test]
fn running_balance() {
let rows = vec![
value(json!({"amount": 100})),
value(json!({"amount": -30})),
value(json!({"amount": "x"})),
value(json!({"other": 1})),
];
let field_defs = object(json!({"balance": {"label": "Balance", "running_balance": "amount"}}));
let result = apply_running_balance(&rows, &field_defs).unwrap();
let balances: Vec<Option<f64>> = result.iter().map(|row| row.get("balance").and_then(Value::as_f64)).collect();
assert_eq!(balances, [Some(100.0), Some(70.0), Some(70.0), Some(70.0)]);
}
#[test]
fn aggregates_and_conditions() {
let rows = vec![
value(json!({"v": 10})),
value(json!({"v": 20})),
value(json!({"v": null})),
value(json!({"x": 1})),
];
assert_eq!(aggregate_values(&rows, "v", "sum").unwrap().as_f64(), Some(30.0));
assert_eq!(aggregate_values(&rows, "v", "count").unwrap().as_i64(), Some(4));
assert_eq!(aggregate_values(&rows, "v", "avg").unwrap().as_f64(), Some(15.0));
assert_eq!(aggregate_values(&rows, "v", "median").unwrap().as_f64(), Some(15.0));
assert_eq!(aggregate_values(&rows, "v", "distinct").unwrap(), Value::UInt(2));
let condition = object(json!({"field": "v", "gt": 15}));
assert!(evaluate_condition(&value(json!({"v": 20})), &condition).unwrap());
}
#[test]
fn footnotes_assigned_in_render_order() {
let mut layout = Value::Object(object(json!({
"groups": {
"header": [
{"name": "a", "label": "A", "footnote": {"mark": null, "text": "First"}},
{"name": "b", "label": "B", "footnote": {"mark": null, "text": "Second"}},
{"name": "c", "label": "C", "footnote": {"mark": null, "text": "First"}}
]
}
})));
assign_report_footnotes(&mut layout, None).unwrap();
let header = layout
.get("groups")
.and_then(|g| g.get("header"))
.and_then(Value::as_array)
.unwrap();
let marks: Vec<&str> = header
.iter()
.map(|field| field.get("footnote").and_then(|n| n.get("mark")).and_then(Value::as_str).unwrap())
.collect();
assert_eq!(marks, ["*", "†", "*"]);
let collected = collect_footnotes(&layout);
assert_eq!(
collected,
vec![("*".to_string(), "First".to_string()), ("†".to_string(), "Second".to_string())]
);
}
}