isis-report-lib 0.1.0

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Dynamic pivot tables: rows x columns matrix with aggregated measures.
//!
//! A crosstab declares row/column buckets plus a measure and function; the grid
//! shape comes from the data. Totals and the grand total are computed the same
//! way. Unobserved cells show `""`, except `count`/`sum`, which are faithfully
//! `0`.

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;

/// Normalized pivot: headers, raw cell values, totals and display defs.
#[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()
    }

    /// Template/export representation of the pivot.
    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"))
}

/// Build a crosstab from raw records and a `rows`/`columns`/measure spec.
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());
    }
}