use std::cmp::Ordering;
use std::collections::HashSet;
use indexmap::IndexMap;
use crate::error::{Error, Result};
use crate::formatting::{normalize_color_scale, normalize_footnote};
use crate::layout::{aggregate_values, color_domain, AGGREGATIONS};
use crate::payload::type_name;
use crate::pyops;
use crate::value::Value;
pub const FUNCTIONS: [&str; 7] = AGGREGATIONS;
#[derive(Debug, Clone)]
pub struct Crosstab {
pub row_headers: Vec<Value>,
pub col_headers: Vec<Value>,
pub cells: Vec<Vec<Value>>,
pub row_totals: Vec<Value>,
pub col_totals: Vec<Value>,
pub grand_total: Value,
pub totals: bool,
pub row_label: String,
pub col_label: String,
pub total_label: String,
pub mask: String,
pub measure_field: Value,
pub row_field: Value,
pub col_field: Value,
pub empty_text: String,
}
impl Crosstab {
pub fn has_data(&self) -> bool {
!self.row_headers.is_empty() && !self.col_headers.is_empty()
}
pub fn to_value(&self) -> Value {
let mut object = IndexMap::new();
object.insert("row_headers".to_string(), Value::Array(self.row_headers.clone()));
object.insert("col_headers".to_string(), Value::Array(self.col_headers.clone()));
object.insert(
"cells".to_string(),
Value::Array(self.cells.iter().map(|row| Value::Array(row.clone())).collect()),
);
object.insert("row_totals".to_string(), Value::Array(self.row_totals.clone()));
object.insert("col_totals".to_string(), Value::Array(self.col_totals.clone()));
object.insert("grand_total".to_string(), self.grand_total.clone());
object.insert("totals".to_string(), Value::Bool(self.totals));
object.insert("row_label".to_string(), Value::String(self.row_label.clone()));
object.insert("col_label".to_string(), Value::String(self.col_label.clone()));
object.insert("total_label".to_string(), Value::String(self.total_label.clone()));
object.insert("mask".to_string(), Value::String(self.mask.clone()));
object.insert("measure_field".to_string(), self.measure_field.clone());
object.insert("row_field".to_string(), self.row_field.clone());
object.insert("col_field".to_string(), self.col_field.clone());
object.insert("empty_text".to_string(), Value::String(self.empty_text.clone()));
object.insert("has_data".to_string(), Value::Bool(self.has_data()));
Value::Object(object)
}
}
fn field_def(spec: &Value, kind: &str) -> Result<Value> {
match spec {
Value::String(field) => {
let mut object = IndexMap::new();
object.insert("field".to_string(), Value::String(field.clone()));
object.insert("label".to_string(), Value::String(field.clone()));
Ok(Value::Object(object))
}
Value::Object(object) => {
let Some(field) = object.get("field").and_then(Value::as_str) else {
return Err(Error::option(format!(
"Invalid crosstab {kind} (need a field name or {{field, ...}}): {}",
pyops::py_str(spec)
)));
};
let mut out = IndexMap::new();
out.insert("field".to_string(), Value::String(field.to_string()));
out.insert(
"label".to_string(),
object.get("label").cloned().unwrap_or_else(|| Value::String(field.to_string())),
);
for key in ["format_mask", "alignment", "missing_text", "substitutions", "cell_rules"] {
if let Some(value) = object.get(key) {
out.insert(key.to_string(), value.clone());
}
}
if let Some(note) = object.get("footnote") {
let note = normalize_footnote(note, &format!("crosstab {kind} {field:?}"))?;
out.insert("footnote".to_string(), note.to_value());
}
if let Some(scale) = object.get("color_scale") {
let scale = normalize_color_scale(scale, &format!("crosstab {kind} {field:?}"))?;
out.insert("color_scale".to_string(), scale.to_value());
}
if let Some(data_bar) = object.get("data_bar") {
let Some(flag) = data_bar.as_bool() else {
return Err(Error::option(format!(
"Invalid data_bar for crosstab {kind} {field:?} (must be true/false): {data_bar:?}"
)));
};
out.insert("data_bar".to_string(), Value::Bool(flag));
}
Ok(Value::Object(out))
}
_ => Err(Error::option(format!(
"Invalid crosstab {kind} (need a field name or {{field, ...}}): {}",
pyops::py_str(spec)
))),
}
}
#[derive(Debug, Clone, PartialEq)]
enum BucketKey {
Number(f64),
Text(String),
Null,
}
impl Eq for BucketKey {}
impl PartialOrd for BucketKey {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BucketKey {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(BucketKey::Null, BucketKey::Null) => Ordering::Equal,
(BucketKey::Null, _) => Ordering::Greater,
(_, BucketKey::Null) => Ordering::Less,
(BucketKey::Number(left), BucketKey::Number(right)) => left.partial_cmp(right).unwrap_or(Ordering::Equal),
(BucketKey::Number(_), BucketKey::Text(_)) => Ordering::Less,
(BucketKey::Text(_), BucketKey::Number(_)) => Ordering::Greater,
(BucketKey::Text(left), BucketKey::Text(right)) => left.cmp(right),
}
}
}
fn bucket_key(value: &Value) -> BucketKey {
if value.is_null() {
BucketKey::Null
} else if value.is_number() {
BucketKey::Number(pyops::py_float(value).unwrap_or(f64::NAN))
} else {
BucketKey::Text(pyops::py_str(value))
}
}
fn cell_value(records: &[Value], measure: &str, func: &str) -> Result<Value> {
if records.is_empty() {
return Ok(if matches!(func, "count" | "sum") {
Value::Int(0)
} else {
Value::String(String::new())
});
}
aggregate_values(records, measure, func)
}
fn field_name(field: &Value) -> Result<&str> {
field
.get("field")
.and_then(Value::as_str)
.ok_or_else(|| Error::option("Crosstab field is missing a field name"))
}
pub fn build_crosstab(data: &[Value], spec: &Value) -> Result<Crosstab> {
let Some(spec) = spec.as_object() else {
return Err(Error::option(format!(
"Invalid crosstab spec (must be an object): {}",
pyops::py_str(spec)
)));
};
let row_def = field_def(spec.get("rows").unwrap_or(&Value::Null), "rows")?;
let col_def = field_def(spec.get("columns").unwrap_or(&Value::Null), "columns")?;
let func = spec.get("function").and_then(Value::as_str).unwrap_or("sum");
if !FUNCTIONS.contains(&func) {
return Err(Error::option(format!(
"Unknown crosstab function: {func:?} (expected one of {FUNCTIONS:?})"
)));
}
let measure = spec.get("measure").filter(|value| !value.is_null());
if measure.is_none() && func != "count" {
return Err(Error::option(format!("Crosstab {func:?} needs a measure field")));
}
let measure_def = match measure {
Some(measure) => field_def(measure, "measure")?,
None => {
let mut object = IndexMap::new();
object.insert("field".to_string(), Value::String(String::new()));
object.insert("label".to_string(), Value::String("Count".to_string()));
Value::Object(object)
}
};
let mut measure_def = measure_def.as_object().cloned().unwrap_or_default();
measure_def
.entry("format_mask".to_string())
.or_insert_with(|| Value::String(if func == "count" { "int" } else { "float" }.to_string()));
let measure = field_name(&Value::Object(measure_def.clone()))?.to_string();
let totals = spec.get("totals").cloned().unwrap_or(Value::Bool(true));
let Some(totals) = totals.as_bool() else {
return Err(Error::option(format!("Invalid crosstab totals (must be true/false): {totals:?}")));
};
let rows: Vec<&Value> = data.iter().filter(|row| row.is_object()).collect();
let row_name = field_name(&row_def)?.to_string();
let col_name = field_name(&col_def)?.to_string();
let mut row_values: Vec<Value> = Vec::new();
let mut seen_rows = HashSet::new();
for row in &rows {
let value = row.get(&row_name).cloned().unwrap_or(Value::Null);
if seen_rows.insert(pyops::distinct_key(&value).unwrap_or_else(|| "null".to_string())) {
row_values.push(value);
}
}
row_values.sort_by_key(bucket_key);
let mut col_values: Vec<Value> = Vec::new();
let mut seen_cols = HashSet::new();
for row in &rows {
let value = row.get(&col_name).cloned().unwrap_or(Value::Null);
if seen_cols.insert(pyops::distinct_key(&value).unwrap_or_else(|| "null".to_string())) {
col_values.push(value);
}
}
col_values.sort_by_key(bucket_key);
let mut cells = Vec::new();
let mut row_totals = Vec::new();
for row_value in &row_values {
let band: Vec<Value> = rows
.iter()
.filter(|row| pyops::py_eq(row.get(&row_name).unwrap_or(&Value::Null), row_value))
.map(|row| (*row).clone())
.collect();
let mut row_cells = Vec::new();
for col_value in &col_values {
let records: Vec<Value> = band
.iter()
.filter(|row| pyops::py_eq(row.get(&col_name).unwrap_or(&Value::Null), col_value))
.cloned()
.collect();
row_cells.push(cell_value(&records, &measure, func)?);
}
cells.push(row_cells);
row_totals.push(cell_value(&band, &measure, func)?);
}
let mut col_totals = Vec::new();
for col_value in &col_values {
let records: Vec<Value> = rows
.iter()
.filter(|row| pyops::py_eq(row.get(&col_name).unwrap_or(&Value::Null), col_value))
.map(|row| (*row).clone())
.collect();
col_totals.push(cell_value(&records, &measure, func)?);
}
let all_rows: Vec<Value> = rows.iter().map(|row| (*row).clone()).collect();
let grand_total = cell_value(&all_rows, &measure, func)?;
let mut measure_def = measure_def;
if measure_def.contains_key("color_scale") {
let mut flat = Vec::new();
for row in &cells {
for value in row {
if !matches!(value, Value::String(text) if text.is_empty()) {
flat.push(value.clone());
}
}
}
for value in &row_totals {
if !matches!(value, Value::String(text) if text.is_empty()) {
flat.push(value.clone());
}
}
for value in &col_totals {
if !matches!(value, Value::String(text) if text.is_empty()) {
flat.push(value.clone());
}
}
if !matches!(&grand_total, Value::String(text) if text.is_empty()) {
flat.push(grand_total.clone());
}
if let Some((low, high)) = color_domain(&flat) {
measure_def.insert(
"color_domain".to_string(),
Value::Array(vec![Value::Float(low), Value::Float(high)]),
);
}
}
let empty_text = spec.get("empty_text").cloned().unwrap_or(Value::String(String::new()));
let empty_text = match empty_text {
Value::Null => String::new(),
Value::String(text) => text,
other => {
return Err(Error::option(format!(
"Invalid crosstab empty_text (must be a string): {}",
type_name(&other)
)))
}
};
Ok(Crosstab {
row_headers: row_values,
col_headers: col_values,
cells,
row_totals,
col_totals,
grand_total,
totals,
row_label: row_def.get("label").and_then(Value::as_str).unwrap_or_default().to_string(),
col_label: col_def.get("label").and_then(Value::as_str).unwrap_or_default().to_string(),
total_label: spec.get("total_label").and_then(Value::as_str).unwrap_or("Total").to_string(),
mask: measure_def.get("format_mask").and_then(Value::as_str).unwrap_or("str").to_string(),
measure_field: Value::Object(measure_def),
row_field: row_def,
col_field: col_def,
empty_text,
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
const DATA: &str = r#"[{"region":"N","q":"Q1","total":10},{"region":"N","q":"Q2","total":20},{"region":"S","q":"Q1","total":5}]"#;
fn data() -> Vec<Value> {
value(serde_json::from_str(DATA).unwrap()).as_array().unwrap().clone()
}
#[test]
fn matrix_and_totals() {
let spec = value(json!({"rows": "region", "columns": "q", "measure": "total", "function": "sum"}));
let ct = build_crosstab(&data(), &spec).unwrap();
assert_eq!(ct.row_headers, vec![Value::String("N".into()), Value::String("S".into())]);
assert_eq!(ct.col_headers, vec![Value::String("Q1".into()), Value::String("Q2".into())]);
assert_eq!(ct.cells[0][0].as_f64(), Some(10.0));
assert_eq!(ct.cells[0][1].as_f64(), Some(20.0));
assert_eq!(ct.cells[1][0].as_f64(), Some(5.0));
assert_eq!(ct.cells[1][1].as_i64(), Some(0));
assert_eq!(ct.row_totals[0].as_f64(), Some(30.0));
assert_eq!(ct.grand_total.as_f64(), Some(35.0));
assert!(ct.has_data());
}
#[test]
fn count_needs_no_measure() {
let ct = build_crosstab(&data(), &value(json!({"rows": "region", "columns": "q", "function": "count"}))).unwrap();
assert_eq!(ct.cells[0][0].as_i64(), Some(1));
assert_eq!(ct.cells[1][1].as_i64(), Some(0));
assert_eq!(ct.grand_total.as_i64(), Some(3));
}
#[test]
fn avg_and_max() {
let spec = value(json!({"rows": "region", "columns": "q", "measure": "total", "function": "avg"}));
let ct = build_crosstab(&data(), &spec).unwrap();
assert_eq!(ct.cells[0][0].as_f64(), Some(10.0));
assert!((ct.grand_total.as_f64().unwrap() - 35.0 / 3.0).abs() < 1e-9);
let spec = value(json!({"rows": "region", "columns": "q", "measure": "total", "function": "max"}));
let ct = build_crosstab(&data(), &spec).unwrap();
assert_eq!(ct.cells[1][1], Value::String(String::new()));
assert_eq!(ct.grand_total.as_f64(), Some(20.0));
}
#[test]
fn sorting_and_no_totals() {
let data = value(json!([
{"r": "b", "c": 2, "v": 1},
{"r": "a", "c": 10, "v": 2},
{"r": null, "c": 1, "v": 3}
]));
let ct = build_crosstab(
data.as_array().unwrap(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "function": "sum", "totals": false})),
)
.unwrap();
assert_eq!(
ct.row_headers,
vec![Value::String("a".into()), Value::String("b".into()), Value::Null]
);
assert_eq!(ct.col_headers, vec![Value::Int(1), Value::Int(2), Value::Int(10)]);
assert!(!ct.totals);
}
#[test]
fn validation() {
assert!(build_crosstab(&data(), &value(json!({"rows": "r", "columns": "c", "function": "sum"}))).is_err());
assert!(build_crosstab(&data(), &value(json!({"rows": "r", "columns": "c", "function": "mode"}))).is_err());
assert!(build_crosstab(&data(), &value(json!({"rows": {"label": "x"}, "columns": "q"}))).is_err());
assert!(build_crosstab(
&data(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "totals": "yes"}))
)
.is_err());
}
#[test]
fn field_defs() {
let ct = build_crosstab(
&data(),
&value(json!({
"rows": {"field": "region", "label": "Region"},
"columns": {"field": "q", "label": "Quarter"},
"measure": {"field": "total", "label": "Sales", "format_mask": "currency"},
"function": "sum",
"total_label": "All"
})),
)
.unwrap();
assert_eq!(ct.row_label, "Region");
assert_eq!(ct.total_label, "All");
assert_eq!(ct.mask, "currency");
}
}
#[cfg(test)]
mod extra_tests {
use super::*;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
fn data() -> Vec<Value> {
value(json!([
{"r": "N", "c": "Q1", "v": 10},
{"r": "N", "c": "Q1", "v": 20},
{"r": "S", "c": "Q2", "v": 5},
"not-a-row",
42
]))
.as_array()
.unwrap()
.clone()
}
#[test]
fn aggregates_and_empty_text() {
for (func, expected) in [("min", 5.0), ("max", 20.0), ("median", 10.0)] {
let spec = value(json!({"rows": "r", "columns": "c", "measure": "v", "function": func}));
let ct = build_crosstab(&data(), &spec).unwrap();
assert_eq!(ct.grand_total.as_f64(), Some(expected), "{func}");
}
let distinct = build_crosstab(
&data(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "function": "distinct"})),
)
.unwrap();
assert_eq!(distinct.grand_total, Value::UInt(3));
let ct = build_crosstab(
&data(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "function": "sum", "empty_text": "none"})),
)
.unwrap();
assert_eq!(ct.empty_text, "none");
assert_eq!(ct.cells[0][1], Value::Int(0));
let null_text = build_crosstab(
&data(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "function": "sum", "empty_text": null})),
)
.unwrap();
assert_eq!(null_text.empty_text, "");
assert!(build_crosstab(
&data(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "function": "sum", "empty_text": 1}))
)
.is_err());
}
#[test]
fn color_scale_and_measure_definitions() {
let ct = build_crosstab(
&data(),
&value(json!({
"rows": "r",
"columns": "c",
"measure": {"field": "v", "label": "Sales", "format_mask": "float", "color_scale": {"min": "#000000", "max": "#ffffff"}},
"function": "sum"
})),
)
.unwrap();
assert_eq!(ct.mask, "float");
let domain = ct.measure_field.get("color_domain").and_then(Value::as_array).unwrap();
assert_eq!(domain.len(), 2);
assert_eq!(domain[0].as_f64(), Some(0.0));
assert_eq!(domain[1].as_f64(), Some(35.0));
let ct = build_crosstab(&[], &value(json!({"rows": "r", "columns": "c", "function": "count"}))).unwrap();
assert!(!ct.has_data());
assert!(ct.row_headers.is_empty());
assert!(ct.col_headers.is_empty());
}
#[test]
fn count_with_measure_and_non_object_data() {
let ct = build_crosstab(
&data(),
&value(json!({"rows": "r", "columns": "c", "measure": "v", "function": "count"})),
)
.unwrap();
assert_eq!(ct.grand_total.as_i64(), Some(3));
assert!(build_crosstab(&[Value::Int(1)], &value(json!({"rows": "r", "columns": "c", "function": "count"}))).is_ok());
}
}