Skip to main content

isis_report_lib/
layout.rs

1//! Hierarchical layout and data conversion into the template-ready format.
2//!
3//! Mirrors the Python `layout.py`: fields with `label` are columns, objects
4//! without `label` are nested groups, `$` keys are level options, flat child
5//! lists become detail tables, and deeper nesting becomes nested sections.
6//! Aggregates, filters, ordering, visibility, running balances, footnotes and
7//! color scales are applied here.
8
9use std::cmp::Ordering;
10use std::collections::{HashMap, HashSet};
11
12use indexmap::IndexMap;
13
14use crate::error::{Error, Result};
15use crate::formatting::{
16    assign_footnote_mark, assign_footnote_marks, field_visible, format_field, match_rule, normalize_color_scale, normalize_footnote,
17    scale_fill, CellStyle, FootnoteState,
18};
19use crate::payload::type_name;
20use crate::pyops;
21use crate::value::Value;
22
23pub const AGGREGATIONS: [&str; 7] = ["sum", "count", "avg", "min", "max", "median", "distinct"];
24
25fn is_field_def(value: &Value) -> bool {
26    value.as_object().is_some_and(|object| object.contains_key("label"))
27}
28
29fn is_group_node(value: &Value) -> bool {
30    value.as_object().is_some_and(|object| !object.contains_key("label"))
31}
32
33/// Split a layout level into (field defs, child group nodes, `$` options).
34pub fn split_layout_node(node: &IndexMap<String, Value>) -> (IndexMap<String, Value>, IndexMap<String, Value>, IndexMap<String, Value>) {
35    let mut fields = IndexMap::new();
36    let mut groups = IndexMap::new();
37    let mut options = IndexMap::new();
38    for (key, value) in node {
39        if let Some(option) = key.strip_prefix('$') {
40            options.insert(option.to_string(), value.clone());
41        } else if is_field_def(value) {
42            fields.insert(key.clone(), value.clone());
43        } else if is_group_node(value) {
44            groups.insert(key.clone(), value.clone());
45        }
46    }
47    (fields, groups, options)
48}
49
50/// Evaluate a `$print_when`/`visible_when` condition against a row.
51pub fn evaluate_condition(row: &Value, condition: &IndexMap<String, Value>) -> Result<bool> {
52    let Some(field) = condition.get("field").and_then(Value::as_str) else {
53        return Err(Error::option(format!(
54            "Condition needs a field name: {}",
55            pyops::py_str(&Value::Object(condition.clone()))
56        )));
57    };
58    let value = row.get(field).unwrap_or(&Value::Null);
59    match_rule(value, condition)
60}
61
62/// Keep rows matching the `$print_when` condition (all rows when absent).
63pub fn filter_rows(rows: &[Value], print_when: Option<&Value>) -> Result<Vec<Value>> {
64    let Some(print_when) = print_when.filter(|value| value.truthy()) else {
65        return Ok(rows.to_vec());
66    };
67    let Some(condition) = print_when.as_object() else {
68        return Err(Error::option(format!(
69            "Invalid $print_when condition: {}",
70            pyops::py_str(print_when)
71        )));
72    };
73    if !condition.contains_key("field") {
74        return Err(Error::option(format!(
75            "Invalid $print_when condition: {}",
76            pyops::py_str(print_when)
77        )));
78    }
79    let mut out = Vec::new();
80    for row in rows {
81        if row.is_object() && evaluate_condition(row, condition)? {
82            out.push(row.clone());
83        }
84    }
85    Ok(out)
86}
87
88/// Sort rows per `$order_by`; nulls always sort last.
89pub fn sort_rows(rows: &[Value], order_by: Option<&Value>) -> Result<Vec<Value>> {
90    let Some(order_by) = order_by.filter(|value| value.truthy()) else {
91        return Ok(rows.to_vec());
92    };
93    let specs: Vec<&Value> = match order_by {
94        Value::Array(values) => values.iter().collect(),
95        other => vec![other],
96    };
97    let mut result = rows.to_vec();
98    for spec in specs.into_iter().rev() {
99        let (field, direction) = match spec {
100            Value::Object(object) => {
101                let field = object.get("field").and_then(Value::as_str);
102                let direction = object.get("direction").and_then(Value::as_str).unwrap_or("asc");
103                (field, direction)
104            }
105            Value::String(text) => {
106                if let Some(field) = text.strip_prefix('-') {
107                    (Some(field), "desc")
108                } else {
109                    (Some(text.as_str()), "asc")
110                }
111            }
112            _ => return Err(Error::option(format!("Invalid $order_by spec: {}", pyops::py_str(spec)))),
113        };
114        let Some(field) = field else {
115            return Err(Error::option(format!(
116                "Invalid $order_by spec (needs a field name): {}",
117                pyops::py_str(spec)
118            )));
119        };
120        if !matches!(direction, "asc" | "desc") {
121            return Err(Error::option(format!("Invalid sort direction: {direction:?}")));
122        }
123        result.sort_by(|left, right| {
124            let left = left.get(field).unwrap_or(&Value::Null);
125            let right = right.get(field).unwrap_or(&Value::Null);
126            pyops::sort_key(left).cmp(&pyops::sort_key(right))
127        });
128        if direction == "desc" {
129            let mut non_null = Vec::new();
130            let mut nulls = Vec::new();
131            for row in result {
132                if row.get(field).is_some_and(|value| !value.is_null()) {
133                    non_null.push(row);
134                } else {
135                    nulls.push(row);
136                }
137            }
138            non_null.reverse();
139            non_null.extend(nulls);
140            result = non_null;
141        }
142    }
143    Ok(result)
144}
145
146fn child_records(record: &Value, key: &str) -> Result<Vec<Value>> {
147    let value = record.get(key);
148    match value {
149        None | Some(Value::Null) => Ok(Vec::new()),
150        Some(value) if value.is_object() || !value.is_array() => Err(Error::option(format!(
151            "Group field {key:?} must be a list of records, got {}",
152            type_name(value)
153        ))),
154        Some(value) => Ok(value
155            .as_array()
156            .map(|rows| rows.iter().filter(|row| row.is_object()).cloned().collect())
157            .unwrap_or_default()),
158    }
159}
160
161fn field_visible_checked(field_def: &Value, rows: &[Value]) -> Result<bool> {
162    field_visible(field_def, rows)
163}
164
165/// Aggregate a field over sibling rows. Returns `""` when there is nothing to show.
166pub fn aggregate_values(rows: &[Value], field: &str, func: &str) -> Result<Value> {
167    if !AGGREGATIONS.contains(&func) {
168        return Err(Error::option(format!(
169            "Unknown aggregate: {func:?} (expected one of {AGGREGATIONS:?})"
170        )));
171    }
172    if func == "count" {
173        return Ok(Value::UInt(rows.iter().filter(|row| row.is_object()).count() as u64));
174    }
175    if func == "distinct" {
176        let mut seen = HashSet::new();
177        for row in rows {
178            let Some(object) = row.as_object() else {
179                continue;
180            };
181            let Some(value) = object.get(field) else {
182                continue;
183            };
184            if value.is_null() {
185                continue;
186            }
187            if let Some(key) = pyops::distinct_key(value) {
188                seen.insert(key);
189            }
190        }
191        return Ok(Value::UInt(seen.len() as u64));
192    }
193    let mut numbers = Vec::new();
194    for row in rows {
195        let Some(object) = row.as_object() else {
196            continue;
197        };
198        let Some(value) = object.get(field) else {
199            continue;
200        };
201        if let Ok(number) = pyops::py_float(value) {
202            numbers.push(number);
203        }
204    }
205    if numbers.is_empty() {
206        return Ok(Value::String(String::new()));
207    }
208    let value = match func {
209        "sum" => numbers.iter().sum(),
210        "avg" => numbers.iter().sum::<f64>() / numbers.len() as f64,
211        "min" => numbers.iter().copied().fold(f64::INFINITY, f64::min),
212        "max" => numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max),
213        "median" => {
214            let mut sorted = numbers.clone();
215            sorted.sort_by(|left, right| left.partial_cmp(right).unwrap_or(Ordering::Equal));
216            let middle = sorted.len() / 2;
217            if sorted.len() % 2 == 0 {
218                (sorted[middle - 1] + sorted[middle]) / 2.0
219            } else {
220                sorted[middle]
221            }
222        }
223        _ => unreachable!("aggregate validated"),
224    };
225    Ok(Value::Float(value))
226}
227
228/// Min/max over numeric values (bools/strings skipped); `None` when empty.
229pub fn color_domain(values: &[Value]) -> Option<(f64, f64)> {
230    let mut numbers = Vec::new();
231    for value in values {
232        match value {
233            Value::Int(value) => numbers.push(*value as f64),
234            Value::UInt(value) => numbers.push(*value as f64),
235            Value::Float(value) => numbers.push(*value),
236            _ => {}
237        }
238    }
239    if numbers.is_empty() {
240        None
241    } else {
242        Some((
243            numbers.iter().copied().fold(f64::INFINITY, f64::min),
244            numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max),
245        ))
246    }
247}
248
249fn apply_color_domains(fields: &mut [Value], rows: &[Value]) {
250    for field in fields {
251        let Some(object) = field.as_object() else {
252            continue;
253        };
254        if !object.contains_key("color_scale") {
255            continue;
256        }
257        let Some(name) = object.get("name").and_then(Value::as_str) else {
258            continue;
259        };
260        let values: Vec<Value> = rows.iter().filter_map(|row| row.get(name).cloned()).collect();
261        if let Some((low, high)) = color_domain(&values) {
262            if let Some(object) = field.as_object_mut() {
263                object.insert(
264                    "color_domain".to_string(),
265                    Value::Array(vec![Value::Float(low), Value::Float(high)]),
266                );
267            }
268        }
269    }
270}
271
272fn py_title(value: &str) -> String {
273    let mut out = String::with_capacity(value.len());
274    let mut previous_cased = false;
275    for ch in value.chars() {
276        if ch.is_alphabetic() {
277            if previous_cased {
278                out.extend(ch.to_lowercase());
279            } else {
280                out.extend(ch.to_uppercase());
281            }
282            previous_cased = true;
283        } else {
284            out.push(ch);
285            previous_cased = false;
286        }
287    }
288    out
289}
290
291/// Legacy converter: hierarchical layout -> render-ready layout.
292pub fn convert_layout(layout_raw: &IndexMap<String, Value>) -> Result<Value> {
293    let mut header = Vec::new();
294    let mut groups: Option<IndexMap<String, Value>> = None;
295    for (key, value) in layout_raw {
296        if is_field_def(value) {
297            header.push(format_field(key, value.as_object().unwrap())?);
298        } else if let Some(object) = value.as_object() {
299            let mut field_header = Vec::new();
300            let mut detail = Vec::new();
301            for (sub_key, sub_value) in object {
302                if is_field_def(sub_value) {
303                    field_header.push(format_field(sub_key, sub_value.as_object().unwrap())?);
304                } else if let Some(sub_object) = sub_value.as_object() {
305                    for (inner_key, inner_value) in sub_object {
306                        if is_field_def(inner_value) {
307                            detail.push(format_field(inner_key, inner_value.as_object().unwrap())?);
308                        }
309                    }
310                }
311            }
312            let groups = groups.get_or_insert_with(IndexMap::new);
313            groups.insert("header".to_string(), Value::Array(field_header));
314            if !detail.is_empty() {
315                groups.insert("detail".to_string(), Value::Array(detail));
316            }
317        }
318    }
319    let mut result = IndexMap::new();
320    result.insert("header".to_string(), Value::Array(header));
321    if let Some(groups) = groups {
322        result.insert("groups".to_string(), Value::Object(groups));
323    }
324    let mut root = IndexMap::new();
325    root.insert("groups".to_string(), Value::Object(result));
326    Ok(Value::Object(root))
327}
328
329/// True when data is already in template format (records with `fields`).
330pub fn is_template_format(data: &[Value]) -> bool {
331    data.first()
332        .and_then(Value::as_object)
333        .is_some_and(|object| object.contains_key("fields"))
334}
335
336/// Legacy converter: raw data + raw layout -> template `{"groups": [...]}`.
337pub fn convert_data(data_raw: &[Value], layout_raw: &IndexMap<String, Value>) -> Result<Value> {
338    if is_template_format(data_raw) {
339        let mut root = IndexMap::new();
340        root.insert("groups".to_string(), Value::Array(data_raw.to_vec()));
341        return Ok(Value::Object(root));
342    }
343    let group_keys: IndexMap<String, Value> = layout_raw
344        .iter()
345        .filter(|(_, value)| is_group_node(value))
346        .map(|(key, value)| (key.clone(), value.clone()))
347        .collect();
348    let mut items = Vec::new();
349    for record in data_raw {
350        let Some(record) = record.as_object() else {
351            return Err(Error::option("Invalid data record (must be an object)"));
352        };
353        let mut fields = IndexMap::new();
354        let mut groups = Vec::new();
355        for (key, value) in record {
356            if let Some(sub_layout) = group_keys.get(key) {
357                let sub_layout = sub_layout.as_object().expect("group object");
358                let detail_key = sub_layout
359                    .iter()
360                    .find(|(_, value)| is_group_node(value))
361                    .map(|(key, _)| key.clone());
362                let Some(sub_items) = value.as_array() else {
363                    return Err(Error::option(format!("Group field {key:?} must be a list of records")));
364                };
365                for sub_item in sub_items {
366                    let Some(sub_item) = sub_item.as_object() else {
367                        continue;
368                    };
369                    let mut sub_fields = IndexMap::new();
370                    for sub_key in sub_layout.keys() {
371                        if Some(sub_key) == detail_key.as_ref() {
372                            continue;
373                        }
374                        if let Some(value) = sub_item.get(sub_key) {
375                            sub_fields.insert(sub_key.clone(), value.clone());
376                        }
377                    }
378                    let detail = detail_key
379                        .as_ref()
380                        .and_then(|key| sub_item.get(key))
381                        .and_then(Value::as_array)
382                        .cloned()
383                        .unwrap_or_default();
384                    let mut group_entry = IndexMap::new();
385                    group_entry.insert("fields".to_string(), Value::Object(sub_fields));
386                    if !detail.is_empty() {
387                        group_entry.insert("detail".to_string(), Value::Array(detail));
388                    }
389                    groups.push(Value::Object(group_entry));
390                }
391            } else {
392                fields.insert(key.clone(), value.clone());
393            }
394        }
395        let mut item = IndexMap::new();
396        item.insert("fields".to_string(), Value::Object(fields));
397        if !groups.is_empty() {
398            item.insert("groups".to_string(), Value::Array(groups));
399        }
400        items.push(Value::Object(item));
401    }
402    let mut root = IndexMap::new();
403    root.insert("groups".to_string(), Value::Array(items));
404    Ok(Value::Object(root))
405}
406
407/// Infer a simple (header-only) layout from the first data row.
408pub fn infer_layout(data: &[Value]) -> Value {
409    let sample = data.first().and_then(Value::as_object).cloned().unwrap_or_default();
410    let mut header = Vec::new();
411    for (key, value) in &sample {
412        if value.is_array() {
413            continue;
414        }
415        let (dtype, alignment) = match value {
416            Value::Int(_) | Value::UInt(_) => ("int", "right"),
417            Value::Float(_) | Value::Decimal(_) => ("float", "right"),
418            _ => ("str", "left"),
419        };
420        let mut field = IndexMap::new();
421        field.insert("name".to_string(), Value::String(key.clone()));
422        field.insert("label".to_string(), Value::String(py_title(&key.replace('_', " "))));
423        field.insert("format_mask".to_string(), Value::String(dtype.to_string()));
424        field.insert("alignment".to_string(), Value::String(alignment.to_string()));
425        header.push(Value::Object(field));
426    }
427    let mut groups = IndexMap::new();
428    groups.insert("header".to_string(), Value::Array(header));
429    let mut root = IndexMap::new();
430    root.insert("groups".to_string(), Value::Object(groups));
431    Value::Object(root)
432}
433
434/// Header-only layout for data already in template format.
435pub fn template_header_layout(data: &[Value]) -> Result<Value> {
436    let sample = data
437        .first()
438        .and_then(Value::as_object)
439        .and_then(|object| object.get("fields"))
440        .and_then(Value::as_object)
441        .cloned()
442        .unwrap_or_default();
443    let mut header = Vec::new();
444    for key in sample.keys() {
445        header.push(format_field(key, &IndexMap::new())?);
446    }
447    let mut groups = IndexMap::new();
448    groups.insert("header".to_string(), Value::Array(header));
449    let mut root = IndexMap::new();
450    root.insert("groups".to_string(), Value::Object(groups));
451    Ok(Value::Object(root))
452}
453
454/// Build (dataset, layout) with parameters applied.
455pub fn build_report(data_raw: &[Value], layout_raw: &IndexMap<String, Value>) -> Result<(Value, Value)> {
456    for (index, record) in data_raw.iter().enumerate() {
457        if !record.is_object() {
458            return Err(Error::option(format!("Invalid data record at index {index} (must be an object)")));
459        }
460    }
461    let filtered = filter_rows(data_raw, layout_raw.get("$print_when"))?;
462    let rows = sort_rows(&filtered, layout_raw.get("$order_by"))?;
463    let mut items = Vec::with_capacity(rows.len());
464    for record in &rows {
465        items.push(convert_item(record, layout_raw)?);
466    }
467    let inner = build_layout(layout_raw, &rows)?;
468    let (summary, summary_defs) = collect_summary(&rows, layout_raw)?;
469    let mut dataset = IndexMap::new();
470    dataset.insert("groups".to_string(), Value::Array(items));
471    dataset.insert(
472        "summary".to_string(),
473        if summary.is_empty() { Value::Null } else { Value::Object(summary) },
474    );
475    let mut layout = IndexMap::new();
476    layout.insert("groups".to_string(), inner);
477    if !summary_defs.is_empty() {
478        let mut summary_layout = Vec::new();
479        for (field, definition) in summary_defs {
480            summary_layout.push(format_field(&field, definition.as_object().expect("field object"))?);
481        }
482        layout.insert("summary".to_string(), Value::Array(summary_layout));
483    }
484    Ok((Value::Object(dataset), Value::Object(layout)))
485}
486
487fn meaningful(values: IndexMap<String, Value>) -> Option<IndexMap<String, Value>> {
488    if values.is_empty() {
489        return None;
490    }
491    if values
492        .values()
493        .any(|value| !value.is_null() && !matches!(value, Value::String(text) if text.is_empty()))
494    {
495        Some(values)
496    } else {
497        None
498    }
499}
500
501fn has_nested_groups(node: &IndexMap<String, Value>) -> bool {
502    node.iter().any(|(key, value)| !key.starts_with('$') && is_group_node(value))
503}
504
505fn collect_summary(rows: &[Value], node: &IndexMap<String, Value>) -> Result<(IndexMap<String, Value>, IndexMap<String, Value>)> {
506    let (field_defs, group_nodes, _) = split_layout_node(node);
507    let mut summary = IndexMap::new();
508    let mut defs = IndexMap::new();
509    for (field, definition) in &field_defs {
510        let Some(func) = definition.get("aggregate").and_then(Value::as_str) else {
511            continue;
512        };
513        let value = aggregate_values(rows, field, func)?;
514        if !value.is_null() && !matches!(&value, Value::String(text) if text.is_empty()) {
515            summary.insert(field.clone(), value);
516            defs.insert(field.clone(), definition.clone());
517        }
518    }
519    for (group_key, sub) in &group_nodes {
520        let mut kids = Vec::new();
521        for row in rows {
522            kids.extend(child_records(row, group_key)?);
523        }
524        let sub = sub.as_object().expect("group object");
525        let (sub_summary, sub_defs) = collect_summary(&kids, sub)?;
526        for (field, value) in sub_summary {
527            if !summary.contains_key(&field) {
528                if let Some(definition) = sub_defs.get(&field) {
529                    summary.insert(field.clone(), value);
530                    defs.insert(field, definition.clone());
531                }
532            }
533        }
534    }
535    Ok((summary, defs))
536}
537
538fn visible_fields(field_defs: &IndexMap<String, Value>, rows: &[Value]) -> Result<Vec<String>> {
539    let mut out = Vec::new();
540    for (name, definition) in field_defs {
541        if field_visible_checked(definition, rows)? {
542            out.push(name.clone());
543        }
544    }
545    Ok(out)
546}
547
548fn convert_item(record: &Value, node: &IndexMap<String, Value>) -> Result<Value> {
549    let (field_defs, group_nodes, _) = split_layout_node(node);
550    let mut fields = IndexMap::new();
551    for key in field_defs.keys() {
552        if let Some(value) = record.get(key) {
553            fields.insert(key.clone(), value.clone());
554        }
555    }
556    let mut groups = Vec::new();
557    let mut details = IndexMap::new();
558    let mut footer_funcs: IndexMap<String, String> = IndexMap::new();
559    let mut footer_rows: IndexMap<String, Vec<Value>> = IndexMap::new();
560    for (key, sub_node) in &group_nodes {
561        let sub_node = sub_node.as_object().expect("group object");
562        let mut children = child_records(record, key)?;
563        children = filter_rows(&children, sub_node.get("$print_when"))?;
564        children = sort_rows(&children, sub_node.get("$order_by"))?;
565        let (sub_fields, _, _) = split_layout_node(sub_node);
566        children = apply_running_balance(&children, &sub_fields)?;
567        if has_nested_groups(sub_node) {
568            for (field, definition) in &sub_fields {
569                if definition.get("aggregate").is_some() && !footer_funcs.contains_key(field) {
570                    if let Some(func) = definition.get("aggregate").and_then(Value::as_str) {
571                        footer_funcs.insert(field.clone(), func.to_string());
572                        footer_rows.insert(field.clone(), children.clone());
573                    }
574                }
575            }
576            for child in &children {
577                groups.push(convert_item(child, sub_node)?);
578            }
579        } else {
580            let mut table = IndexMap::new();
581            table.insert("rows".to_string(), Value::Array(children.clone()));
582            let mut table_footer = IndexMap::new();
583            for (field, definition) in &sub_fields {
584                if let Some(func) = definition.get("aggregate").and_then(Value::as_str) {
585                    table_footer.insert(field.clone(), aggregate_values(&children, field, func)?);
586                }
587            }
588            if let Some(footer) = meaningful(table_footer) {
589                table.insert("footer".to_string(), Value::Object(footer));
590            }
591            if let Some(empty_text) = sub_node.get("empty_text").and_then(Value::as_str) {
592                if !empty_text.is_empty() {
593                    table.insert("empty_text".to_string(), Value::String(empty_text.to_string()));
594                }
595            }
596            if !children.is_empty() || table.contains_key("empty_text") {
597                details.insert(key.clone(), Value::Object(table));
598            }
599        }
600    }
601    let mut item = IndexMap::new();
602    item.insert("fields".to_string(), Value::Object(fields));
603    if !groups.is_empty() {
604        item.insert("groups".to_string(), Value::Array(groups));
605    }
606    if !details.is_empty() {
607        item.insert("details".to_string(), Value::Object(details));
608    }
609    let mut computed_footer = IndexMap::new();
610    for (field, func) in &footer_funcs {
611        if let Some(rows) = footer_rows.get(field) {
612            computed_footer.insert(field.clone(), aggregate_values(rows, field, func)?);
613        }
614    }
615    if let Some(footer) = meaningful(computed_footer) {
616        item.insert("footer".to_string(), Value::Object(footer));
617    }
618    Ok(Value::Object(item))
619}
620
621fn apply_running_balance(rows: &[Value], field_defs: &IndexMap<String, Value>) -> Result<Vec<Value>> {
622    let mut specs: IndexMap<String, (String, f64)> = IndexMap::new();
623    for (key, definition) in field_defs {
624        let Some(spec) = definition.get("running_balance") else {
625            continue;
626        };
627        match spec {
628            Value::String(source) => {
629                specs.insert(key.clone(), (source.clone(), 0.0));
630            }
631            Value::Object(object) if object.get("of").and_then(Value::as_str).is_some() => {
632                let source = object.get("of").and_then(Value::as_str).unwrap_or_default().to_string();
633                let start = object.get("start").filter(|value| value.truthy());
634                let start = match start {
635                    Some(value) => pyops::py_float(value)
636                        .map_err(|_| Error::option(format!("Invalid running_balance start for {key:?}: {}", pyops::py_str(spec))))?,
637                    None => 0.0,
638                };
639                specs.insert(key.clone(), (source, start));
640            }
641            Value::Null => {}
642            _ => {
643                return Err(Error::option(format!(
644                    "Invalid running_balance spec for {key:?}: {}",
645                    pyops::py_str(spec)
646                )))
647            }
648        }
649    }
650    if specs.is_empty() || rows.is_empty() {
651        return Ok(rows.to_vec());
652    }
653    let mut balances: HashMap<String, f64> = HashMap::new();
654    let mut out = Vec::with_capacity(rows.len());
655    for row in rows {
656        let mut row = row.clone();
657        if let Some(object) = row.as_object_mut() {
658            for (key, (source, start)) in &specs {
659                let balance = balances.entry(key.clone()).or_insert(*start);
660                let delta = object
661                    .get(source)
662                    .filter(|value| value.truthy())
663                    .and_then(|value| pyops::py_float(value).ok())
664                    .unwrap_or(0.0);
665                *balance += delta;
666                object.insert(key.clone(), Value::Float(*balance));
667            }
668        }
669        out.push(row);
670    }
671    Ok(out)
672}
673
674fn build_layout(node: &IndexMap<String, Value>, rows: &[Value]) -> Result<Value> {
675    let (field_defs, group_nodes, _) = split_layout_node(node);
676    let visible = visible_fields(&field_defs, rows)?;
677    let mut header = Vec::new();
678    for name in &visible {
679        header.push(format_field(name, field_defs.get(name).and_then(Value::as_object).expect("field"))?);
680    }
681    apply_color_domains(&mut header, rows);
682
683    let mut child_rows: IndexMap<String, Vec<Value>> = IndexMap::new();
684    for group_key in group_nodes.keys() {
685        let mut kids = Vec::new();
686        for row in rows {
687            kids.extend(child_records(row, group_key)?);
688        }
689        child_rows.insert(group_key.clone(), kids);
690    }
691
692    let mut footer = Vec::new();
693    let mut seen = HashSet::new();
694    for (group_key, sub) in &group_nodes {
695        let sub = sub.as_object().expect("group object");
696        if !has_nested_groups(sub) {
697            continue;
698        }
699        let (sub_fields, _, _) = split_layout_node(sub);
700        let kids = child_rows.get(group_key).cloned().unwrap_or_default();
701        for field in visible_fields(&sub_fields, &kids)? {
702            if sub_fields.get(&field).and_then(|definition| definition.get("aggregate")).is_some() && seen.insert(field.clone()) {
703                footer.push(format_field(
704                    &field,
705                    sub_fields.get(&field).and_then(Value::as_object).expect("field"),
706                )?);
707            }
708        }
709    }
710
711    let nested_key = group_nodes
712        .iter()
713        .find(|(_, value)| has_nested_groups(value.as_object().expect("group object")))
714        .map(|(key, _)| key.clone());
715    let child_layout = match nested_key {
716        Some(key) => {
717            let sub = group_nodes.get(&key).and_then(Value::as_object).expect("group object");
718            let kids = child_rows.get(&key).cloned().unwrap_or_default();
719            Some(build_layout(sub, &kids)?)
720        }
721        None => None,
722    };
723
724    let mut details = IndexMap::new();
725    for (group_key, sub) in &group_nodes {
726        let sub = sub.as_object().expect("group object");
727        if has_nested_groups(sub) {
728            continue;
729        }
730        let (sub_fields, _, _) = split_layout_node(sub);
731        let kids = child_rows.get(group_key).cloned().unwrap_or_default();
732        let mut columns = Vec::new();
733        for field in visible_fields(&sub_fields, &kids)? {
734            columns.push(format_field(
735                &field,
736                sub_fields.get(&field).and_then(Value::as_object).expect("field"),
737            )?);
738        }
739        apply_color_domains(&mut columns, &kids);
740        details.insert(group_key.clone(), Value::Array(columns));
741    }
742
743    let mut fragment = IndexMap::new();
744    fragment.insert("header".to_string(), Value::Array(header));
745    if let Some(child_layout) = child_layout {
746        fragment.insert("groups".to_string(), child_layout);
747    }
748    if !details.is_empty() {
749        fragment.insert("details".to_string(), Value::Object(details));
750    }
751    if !footer.is_empty() {
752        fragment.insert("footer".to_string(), Value::Array(footer));
753    }
754    Ok(Value::Object(fragment))
755}
756
757fn take_footnotes(fields: Option<&Value>, found: &mut Vec<(String, String)>, seen: &mut HashSet<String>) {
758    let Some(fields) = fields.and_then(Value::as_array) else {
759        return;
760    };
761    for field in fields {
762        let Some(note) = field.get("footnote").and_then(Value::as_object) else {
763            continue;
764        };
765        let Some(mark) = note.get("mark").and_then(Value::as_str) else {
766            continue;
767        };
768        if mark.is_empty() || !seen.insert(mark.to_string()) {
769            continue;
770        }
771        found.push((
772            mark.to_string(),
773            note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
774        ));
775    }
776}
777
778/// Collect `(mark, text)` footnotes from a normalized layout fragment.
779pub fn collect_footnotes(fragment: &Value) -> Vec<(String, String)> {
780    let mut found = Vec::new();
781    let mut seen = HashSet::new();
782    fn visit(fragment: &Value, found: &mut Vec<(String, String)>, seen: &mut HashSet<String>) {
783        let Some(object) = fragment.as_object() else {
784            return;
785        };
786        take_footnotes(object.get("header"), found, seen);
787        if let Some(details) = object.get("details").and_then(Value::as_object) {
788            for fields in details.values() {
789                take_footnotes(Some(fields), found, seen);
790            }
791        }
792        if let Some(groups) = object.get("groups") {
793            visit(groups, found, seen);
794        }
795        take_footnotes(object.get("footer"), found, seen);
796    }
797    if let Some(object) = fragment.as_object() {
798        visit(object.get("groups").unwrap_or(fragment), &mut found, &mut seen);
799        take_footnotes(object.get("summary"), &mut found, &mut seen);
800    }
801    found
802}
803
804/// Fill footnote marks across a prepared report (shared numbering, render order).
805pub fn assign_report_footnotes(layout: &mut Value, sections: Option<&mut Vec<Value>>) -> Result<()> {
806    let mut state = FootnoteState::default();
807    fn visit(fragment: &mut Value, state: &mut FootnoteState) -> Result<()> {
808        let Some(object) = fragment.as_object_mut() else {
809            return Ok(());
810        };
811        if let Some(header) = object.get_mut("header").and_then(Value::as_array_mut) {
812            assign_footnote_marks(header, state)?;
813        }
814        if let Some(details) = object.get_mut("details").and_then(Value::as_object_mut) {
815            for fields in details.values_mut() {
816                if let Some(fields) = fields.as_array_mut() {
817                    assign_footnote_marks(fields, state)?;
818                }
819            }
820        }
821        if let Some(groups) = object.get_mut("groups") {
822            visit(groups, state)?;
823        }
824        if let Some(footer) = object.get_mut("footer").and_then(Value::as_array_mut) {
825            assign_footnote_marks(footer, state)?;
826        }
827        Ok(())
828    }
829    if layout.is_object() {
830        if layout.get("groups").is_some() {
831            if let Some(groups) = layout.get_mut("groups") {
832                visit(groups, &mut state)?;
833            }
834        } else {
835            visit(layout, &mut state)?;
836        }
837        if let Some(summary) = layout.get_mut("summary").and_then(Value::as_array_mut) {
838            assign_footnote_marks(summary, &mut state)?;
839        }
840    }
841    if let Some(sections) = sections {
842        for section in sections {
843            let Some(section) = section.as_object_mut() else {
844                continue;
845            };
846            let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table").to_string();
847            match section_type.as_str() {
848                "table" => {
849                    if let Some(section_layout) = section.get_mut("layout") {
850                        if section_layout.is_object() {
851                            if section_layout.get("groups").is_some() {
852                                if let Some(groups) = section_layout.get_mut("groups") {
853                                    visit(groups, &mut state)?;
854                                }
855                            } else {
856                                visit(section_layout, &mut state)?;
857                            }
858                            if let Some(summary) = section_layout.get_mut("summary").and_then(Value::as_array_mut) {
859                                assign_footnote_marks(summary, &mut state)?;
860                            }
861                        }
862                    }
863                }
864                "crosstab" => {
865                    if let Some(crosstab) = section.get_mut("crosstab").and_then(Value::as_object_mut) {
866                        for key in ["row_field", "col_field", "measure_field"] {
867                            if let Some(field) = crosstab.get_mut(key) {
868                                assign_footnote_mark(field, &mut state)?;
869                            }
870                        }
871                    }
872                }
873                "kpi" => {
874                    if let Some(items) = section.get_mut("items").and_then(Value::as_array_mut) {
875                        assign_footnote_marks(items, &mut state)?;
876                    }
877                }
878                _ => {}
879            }
880        }
881    }
882    Ok(())
883}
884
885/// Convenience exposed for export/diagnostics: normalize a color scale spec.
886pub fn color_scale(spec: &Value, where_: &str) -> Result<Value> {
887    Ok(normalize_color_scale(spec, where_)?.to_value())
888}
889
890/// Convenience exposed for diagnostics: normalize a footnote spec.
891pub fn footnote(spec: &Value, where_: &str) -> Result<Value> {
892    Ok(normalize_footnote(spec, where_)?.to_value())
893}
894
895/// Convenience: `scale_fill` re-export used by XLSX/HTML.
896pub fn field_scale_fill(value: &Value, field: &Value) -> Option<String> {
897    scale_fill(value, field)
898}
899
900/// Convenience: `cell_style_dict` re-export used by XLSX.
901pub fn field_cell_style(value: &Value, field: &Value) -> Result<CellStyle> {
902    crate::formatting::cell_style_dict(value, field)
903}
904
905#[cfg(test)]
906mod tests {
907    use super::*;
908    use serde_json::json;
909
910    fn value(value: serde_json::Value) -> Value {
911        Value::from_json(value)
912    }
913
914    fn object(value: serde_json::Value) -> IndexMap<String, Value> {
915        Value::from_json(value).as_object().unwrap().clone()
916    }
917
918    #[test]
919    fn empty_layout() {
920        assert_eq!(
921            convert_layout(&IndexMap::new()).unwrap().to_json(),
922            json!({"groups": {"header": []}})
923        );
924    }
925
926    #[test]
927    fn simple_layout_and_infer() {
928        let layout = object(json!({
929            "name": {"label": "Name", "format_mask": "str", "alignment": "left"},
930            "age": {"label": "Age", "format_mask": "int", "alignment": "right"}
931        }));
932        let result = convert_layout(&layout).unwrap();
933        assert_eq!(
934            result
935                .get("groups")
936                .and_then(|groups| groups.get("header"))
937                .and_then(Value::as_array)
938                .map(|v| v.len()),
939            Some(2)
940        );
941        let inferred = infer_layout(&[value(
942            json!({"name": "John", "age": 30, "price": 9.9, "active": true, "items": [1]}),
943        )]);
944        let header = inferred
945            .get("groups")
946            .and_then(|groups| groups.get("header"))
947            .and_then(Value::as_array)
948            .unwrap();
949        let masks: HashMap<&str, &str> = header
950            .iter()
951            .map(|field| {
952                (
953                    field.get("name").and_then(Value::as_str).unwrap(),
954                    field.get("format_mask").and_then(Value::as_str).unwrap(),
955                )
956            })
957            .collect();
958        assert_eq!(masks.get("age"), Some(&"int"));
959        assert_eq!(masks.get("price"), Some(&"float"));
960        assert_eq!(masks.get("active"), Some(&"str"));
961        assert!(!masks.contains_key("items"));
962    }
963
964    #[test]
965    fn build_report_footers_and_summary() {
966        let layout = object(json!({
967            "company": {"label": "Company", "format_mask": "str", "alignment": "left"},
968            "orders": {
969                "order": {"label": "Code", "format_mask": "int", "alignment": "right"},
970                "total": {"label": "Total", "format_mask": "float", "alignment": "right", "aggregate": "sum"},
971                "items": {
972                    "qty": {"label": "Qty", "format_mask": "int", "alignment": "right", "aggregate": "sum"},
973                    "unit_price": {"label": "Unit", "format_mask": "float", "alignment": "right"}
974                }
975            }
976        }));
977        let data = vec![value(json!({
978            "company": "ACME",
979            "orders": [
980                {"order": 1, "total": 4000, "items": [{"qty": 1, "unit_price": 1500}, {"qty": 2, "unit_price": 1250}]},
981                {"order": 2, "total": 2000, "items": [{"qty": 4, "unit_price": 500}]}
982            ]
983        }))];
984        let (dataset, layout) = build_report(&data, &layout).unwrap();
985        let company = &dataset.get("groups").and_then(Value::as_array).unwrap()[0];
986        assert_eq!(
987            company.get("footer").and_then(|f| f.get("total")).and_then(Value::as_f64),
988            Some(6000.0)
989        );
990        let first = &company.get("groups").and_then(Value::as_array).unwrap()[0];
991        assert_eq!(
992            first
993                .get("details")
994                .and_then(|d| d.get("items"))
995                .and_then(|t| t.get("footer"))
996                .and_then(|f| f.get("qty"))
997                .and_then(Value::as_i64),
998            Some(3)
999        );
1000        assert_eq!(
1001            dataset.get("summary").and_then(|s| s.get("total")).and_then(Value::as_f64),
1002            Some(6000.0)
1003        );
1004        assert_eq!(dataset.get("summary").and_then(|s| s.get("qty")).and_then(Value::as_i64), Some(7));
1005        assert_eq!(layout.get("summary").and_then(Value::as_array).map(|v| v.len()), Some(2));
1006    }
1007
1008    #[test]
1009    fn print_when_and_order_by() {
1010        let layout = object(json!({
1011            "company": {"label": "Company", "format_mask": "str", "alignment": "left"},
1012            "orders": {
1013                "order": {"label": "Code", "format_mask": "int", "alignment": "right"},
1014                "$print_when": {"field": "status", "not_equals": "cancelled"},
1015                "$order_by": "-order"
1016            }
1017        }));
1018        let data = vec![value(json!({
1019            "company": "ACME",
1020            "orders": [
1021                {"order": 1, "status": "paid"},
1022                {"order": 3, "status": "cancelled"},
1023                {"order": 2, "status": "paid"}
1024            ]
1025        }))];
1026        let (dataset, _) = build_report(&data, &layout).unwrap();
1027        let rows = dataset.get("groups").and_then(Value::as_array).unwrap()[0]
1028            .get("details")
1029            .and_then(|details| details.get("orders"))
1030            .and_then(|table| table.get("rows"))
1031            .and_then(Value::as_array)
1032            .unwrap();
1033        let orders: Vec<i64> = rows.iter().filter_map(|row| row.get("order").and_then(Value::as_i64)).collect();
1034        assert_eq!(orders, [2, 1]);
1035    }
1036
1037    #[test]
1038    fn running_balance() {
1039        let rows = vec![
1040            value(json!({"amount": 100})),
1041            value(json!({"amount": -30})),
1042            value(json!({"amount": "x"})),
1043            value(json!({"other": 1})),
1044        ];
1045        let field_defs = object(json!({"balance": {"label": "Balance", "running_balance": "amount"}}));
1046        let result = apply_running_balance(&rows, &field_defs).unwrap();
1047        let balances: Vec<Option<f64>> = result.iter().map(|row| row.get("balance").and_then(Value::as_f64)).collect();
1048        assert_eq!(balances, [Some(100.0), Some(70.0), Some(70.0), Some(70.0)]);
1049    }
1050
1051    #[test]
1052    fn aggregates_and_conditions() {
1053        let rows = vec![
1054            value(json!({"v": 10})),
1055            value(json!({"v": 20})),
1056            value(json!({"v": null})),
1057            value(json!({"x": 1})),
1058        ];
1059        assert_eq!(aggregate_values(&rows, "v", "sum").unwrap().as_f64(), Some(30.0));
1060        assert_eq!(aggregate_values(&rows, "v", "count").unwrap().as_i64(), Some(4));
1061        assert_eq!(aggregate_values(&rows, "v", "avg").unwrap().as_f64(), Some(15.0));
1062        assert_eq!(aggregate_values(&rows, "v", "median").unwrap().as_f64(), Some(15.0));
1063        assert_eq!(aggregate_values(&rows, "v", "distinct").unwrap(), Value::UInt(2));
1064        let condition = object(json!({"field": "v", "gt": 15}));
1065        assert!(evaluate_condition(&value(json!({"v": 20})), &condition).unwrap());
1066    }
1067
1068    #[test]
1069    fn footnotes_assigned_in_render_order() {
1070        let mut layout = Value::Object(object(json!({
1071            "groups": {
1072                "header": [
1073                    {"name": "a", "label": "A", "footnote": {"mark": null, "text": "First"}},
1074                    {"name": "b", "label": "B", "footnote": {"mark": null, "text": "Second"}},
1075                    {"name": "c", "label": "C", "footnote": {"mark": null, "text": "First"}}
1076                ]
1077            }
1078        })));
1079        assign_report_footnotes(&mut layout, None).unwrap();
1080        let header = layout
1081            .get("groups")
1082            .and_then(|g| g.get("header"))
1083            .and_then(Value::as_array)
1084            .unwrap();
1085        let marks: Vec<&str> = header
1086            .iter()
1087            .map(|field| field.get("footnote").and_then(|n| n.get("mark")).and_then(Value::as_str).unwrap())
1088            .collect();
1089        assert_eq!(marks, ["*", "†", "*"]);
1090        let collected = collect_footnotes(&layout);
1091        assert_eq!(
1092            collected,
1093            vec![("*".to_string(), "First".to_string()), ("†".to_string(), "Second".to_string())]
1094        );
1095    }
1096}