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
//! Dynamic report value.
//!
//! JSON/TOON payloads are dynamic by design. This enum mirrors the Python
//! value model closely enough to preserve the formatting, ordering and
//! comparison semantics of the original library, while adding native
//! date/datetime/decimal variants for the Arrow/Polars/DuckDB/SQLite inputs.
//!
//! Dates are serialized as ISO-8601 strings and decimals as strings. JSON and
//! TOON input never auto-parses those strings back into dates: strings stay
//! strings, exactly like the Python library.

use std::fmt;

use chrono::{DateTime, FixedOffset, NaiveDate};
use indexmap::IndexMap;
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::pyops;

/// A dynamic report value.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Value {
    #[default]
    Null,
    Bool(bool),
    Int(i64),
    UInt(u64),
    Float(f64),
    Decimal(Decimal),
    String(String),
    Date(NaiveDate),
    DateTime(DateTime<FixedOffset>),
    Array(Vec<Value>),
    Object(IndexMap<String, Value>),
}

impl Value {
    pub fn object() -> IndexMap<String, Value> {
        IndexMap::new()
    }

    pub fn from_object(object: IndexMap<String, Value>) -> Self {
        Self::Object(object)
    }

    pub fn from_array(array: Vec<Value>) -> Self {
        Self::Array(array)
    }

    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    pub fn is_number(&self) -> bool {
        matches!(
            self,
            Self::Bool(_) | Self::Int(_) | Self::UInt(_) | Self::Float(_) | Self::Decimal(_)
        )
    }

    pub fn is_string(&self) -> bool {
        matches!(self, Self::String(_))
    }

    pub fn is_array(&self) -> bool {
        matches!(self, Self::Array(_))
    }

    pub fn is_object(&self) -> bool {
        matches!(self, Self::Object(_))
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&Vec<Value>> {
        match self {
            Self::Array(value) => Some(value),
            _ => None,
        }
    }

    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
        match self {
            Self::Array(value) => Some(value),
            _ => None,
        }
    }

    pub fn as_object(&self) -> Option<&IndexMap<String, Value>> {
        match self {
            Self::Object(value) => Some(value),
            _ => None,
        }
    }

    pub fn as_object_mut(&mut self) -> Option<&mut IndexMap<String, Value>> {
        match self {
            Self::Object(value) => Some(value),
            _ => None,
        }
    }

    pub fn get(&self, key: &str) -> Option<&Value> {
        self.as_object().and_then(|object| object.get(key))
    }

    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
        self.as_object_mut().and_then(|object| object.get_mut(key))
    }

    pub fn contains_key(&self, key: &str) -> bool {
        self.as_object().is_some_and(|object| object.contains_key(key))
    }

    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<Value>) -> Option<Value> {
        self.as_object_mut().and_then(|object| object.insert(key.into(), value.into()))
    }

    pub fn push(&mut self, value: impl Into<Value>) {
        if let Some(array) = self.as_array_mut() {
            array.push(value.into());
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        pyops::py_float(self).ok()
    }

    pub fn as_i64(&self) -> Option<i64> {
        pyops::py_int(self).ok()
    }

    pub fn py_str(&self) -> String {
        pyops::py_str(self)
    }

    pub fn py_repr(&self) -> String {
        pyops::py_repr(self)
    }

    pub fn truthy(&self) -> bool {
        pyops::py_truthy(self)
    }

    /// Convert to a `serde_json::Value` (dates/decimals become strings, NaN/inf
    /// become null).
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            Self::Null => serde_json::Value::Null,
            Self::Bool(value) => serde_json::Value::Bool(*value),
            Self::Int(value) => serde_json::Value::Number((*value).into()),
            Self::UInt(value) => serde_json::Value::Number((*value).into()),
            Self::Float(value) => {
                if value.is_finite() {
                    serde_json::Number::from_f64(*value)
                        .map(serde_json::Value::Number)
                        .unwrap_or(serde_json::Value::Null)
                } else {
                    serde_json::Value::Null
                }
            }
            Self::Decimal(value) => serde_json::Value::String(value.to_string()),
            Self::String(value) => serde_json::Value::String(value.clone()),
            Self::Date(value) => serde_json::Value::String(value.format("%Y-%m-%d").to_string()),
            Self::DateTime(value) => serde_json::Value::String(value.to_rfc3339()),
            Self::Array(values) => serde_json::Value::Array(values.iter().map(Value::to_json).collect()),
            Self::Object(values) => {
                let mut object = serde_json::Map::with_capacity(values.len());
                for (key, value) in values {
                    object.insert(key.clone(), value.to_json());
                }
                serde_json::Value::Object(object)
            }
        }
    }

    /// Convert from a `serde_json::Value` preserving object order.
    pub fn from_json(value: serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => Self::Null,
            serde_json::Value::Bool(value) => Self::Bool(value),
            serde_json::Value::Number(number) => {
                if let Some(value) = number.as_i64() {
                    Self::Int(value)
                } else if let Some(value) = number.as_u64() {
                    Self::UInt(value)
                } else {
                    Self::Float(number.as_f64().unwrap_or(f64::NAN))
                }
            }
            serde_json::Value::String(value) => Self::String(value),
            serde_json::Value::Array(values) => Self::Array(values.into_iter().map(Self::from_json).collect()),
            serde_json::Value::Object(values) => {
                let mut object = IndexMap::with_capacity(values.len());
                for (key, value) in values {
                    object.insert(key, Self::from_json(value));
                }
                Self::Object(object)
            }
        }
    }

    pub fn to_json_string(&self) -> String {
        serde_json::to_string(&self.to_json()).unwrap_or_else(|_| "null".to_string())
    }
}

impl fmt::Display for Value {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.py_str())
    }
}

impl Serialize for Value {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_json().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Value {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        Ok(Self::from_json(value))
    }
}

impl From<serde_json::Value> for Value {
    fn from(value: serde_json::Value) -> Self {
        Self::from_json(value)
    }
}

impl From<Value> for serde_json::Value {
    fn from(value: Value) -> Self {
        value.to_json()
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<i64> for Value {
    fn from(value: i64) -> Self {
        Self::Int(value)
    }
}

impl From<i32> for Value {
    fn from(value: i32) -> Self {
        Self::Int(value as i64)
    }
}

impl From<u64> for Value {
    fn from(value: u64) -> Self {
        Self::UInt(value)
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Self::Float(value)
    }
}

impl From<Decimal> for Value {
    fn from(value: Decimal) -> Self {
        Self::Decimal(value)
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Self::String(value.to_string())
    }
}

impl From<NaiveDate> for Value {
    fn from(value: NaiveDate) -> Self {
        Self::Date(value)
    }
}

impl From<DateTime<FixedOffset>> for Value {
    fn from(value: DateTime<FixedOffset>) -> Self {
        Self::DateTime(value)
    }
}

impl<T> From<Vec<T>> for Value
where
    T: Into<Value>,
{
    fn from(value: Vec<T>) -> Self {
        Self::Array(value.into_iter().map(Into::into).collect())
    }
}

impl<T> From<Option<T>> for Value
where
    T: Into<Value>,
{
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => value.into(),
            None => Self::Null,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::DateTime;
    use rust_decimal::Decimal;
    use serde_json::json;

    fn object() -> Value {
        let mut map = Value::object();
        map.insert("a".to_string(), Value::Int(1));
        Value::from_object(map)
    }

    #[test]
    fn predicates_accessors_and_mutators() {
        let mut value = object();
        assert!(value.is_object());
        assert!(value.contains_key("a"));
        assert_eq!(value.get("a"), Some(&Value::Int(1)));
        *value.get_mut("a").unwrap() = Value::Int(2);
        assert_eq!(value.get("a"), Some(&Value::Int(2)));
        assert_eq!(value.insert("b", true), None);
        assert_eq!(value.insert("b", 3), Some(Value::Bool(true)));
        assert!(!value.is_array());
        assert!(value.as_array().is_none());
        assert!(value.as_array_mut().is_none());
        assert!(value.as_bool().is_none());
        assert!(value.as_str().is_none());

        let mut array = Value::from_array(vec![Value::Int(1)]);
        assert!(array.is_array());
        array.push(2);
        assert_eq!(array.as_array().unwrap().len(), 2);
        array.as_array_mut().unwrap().push(Value::Int(3));
        assert_eq!(array.as_array().unwrap().len(), 3);
        array.push(Value::Null); // ignored for non-object/array? array accepts.
        assert_eq!(array.as_array().unwrap().len(), 4);

        assert!(Value::Null.is_null());
        assert!(Value::Bool(true).is_number());
        assert!(Value::Decimal(Decimal::new(15, 1)).is_number());
        assert!(Value::String("x".into()).is_string());
    }

    #[test]
    fn numeric_and_python_accessors() {
        assert_eq!(Value::Int(10).as_f64(), Some(10.0));
        assert_eq!(Value::Float(10.5).as_i64(), Some(10));
        assert_eq!(Value::String("3".into()).as_i64(), Some(3));
        assert_eq!(Value::Null.as_f64(), None);
        assert_eq!(Value::String("hello".into()).py_str(), "hello");
        assert_eq!(Value::String("hello".into()).py_repr(), "'hello'");
        assert!(Value::Int(1).truthy());
        assert!(!Value::Int(0).truthy());
        assert!(!Value::Null.truthy());
        assert_eq!(Value::Int(1).to_string(), "1");
    }

    #[test]
    fn json_roundtrip_for_every_variant() {
        let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
        let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
        let decimal = Decimal::new(12345, 2);
        let values = vec![
            Value::Null,
            Value::Bool(true),
            Value::Int(-1),
            Value::UInt(1),
            Value::Float(1.5),
            Value::Float(f64::NAN),
            Value::Float(f64::INFINITY),
            Value::Decimal(decimal),
            Value::String("x".into()),
            Value::Date(date),
            Value::DateTime(datetime),
            Value::Array(vec![Value::Int(1), Value::Null]),
            object(),
        ];
        for value in values {
            let json = value.to_json();
            let parsed = Value::from_json(json);
            if matches!(value, Value::Float(f) if !f.is_finite()) {
                assert!(parsed.is_null());
            } else if let Value::Decimal(decimal) = value {
                assert_eq!(parsed, Value::String(decimal.to_string()));
            } else if let Value::UInt(value) = value {
                assert_eq!(parsed, Value::Int(value as i64));
            } else if let Value::Date(date) = value {
                assert_eq!(parsed, Value::String(date.format("%Y-%m-%d").to_string()));
            } else if let Value::DateTime(datetime) = value {
                assert_eq!(parsed, Value::String(datetime.to_rfc3339()));
            } else {
                assert_eq!(parsed, value);
            }
            assert!(!value.to_json_string().is_empty());
        }
        assert_eq!(
            Value::from_json(json!({"a": [1, 2]})).get("a").unwrap().as_array().unwrap().len(),
            2
        );
        assert_eq!(Value::from_json(json!(1.25)), Value::Float(1.25));
        assert_eq!(Value::from_json(json!(u64::MAX)), Value::UInt(u64::MAX));
    }

    #[test]
    fn conversions_and_serde() {
        assert_eq!(Value::from(true), Value::Bool(true));
        assert_eq!(Value::from(1_i64), Value::Int(1));
        assert_eq!(Value::from(1_i32), Value::Int(1));
        assert_eq!(Value::from(1_u64), Value::UInt(1));
        assert_eq!(Value::from(1.5_f64), Value::Float(1.5));
        assert_eq!(Value::from("x"), Value::String("x".into()));
        assert_eq!(Value::from(String::from("x")), Value::String("x".into()));
        assert_eq!(Value::from(Some(1_i64)), Value::Int(1));
        assert_eq!(Value::from(None::<i64>), Value::Null);
        assert_eq!(Value::from(vec![1_i64, 2]), Value::Array(vec![Value::Int(1), Value::Int(2)]));

        let decimal = Decimal::new(15, 1);
        assert_eq!(Value::from(decimal), Value::Decimal(decimal));
        let date = NaiveDate::from_ymd_opt(2024, 1, 2).unwrap();
        assert_eq!(Value::from(date), Value::Date(date));
        let datetime = DateTime::parse_from_rfc3339("2024-01-02T03:04:05+00:00").unwrap();
        assert_eq!(Value::from(datetime), Value::DateTime(datetime));

        let value = object();
        let encoded = serde_json::to_string(&value).unwrap();
        let decoded: Value = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded, value);
        assert_eq!(serde_json::Value::from(value.clone()), value.to_json());
    }
}