1
//! Chart intermediate representation.
2
//!
3
//! This is the one contract that adapters, renderers (SVG, canvas,
4
//! ratatui), and the JSON wire format all share. Serialises cleanly so
5
//! the WASM canvas renderer can consume the same bytes the server
6
//! produces.
7

            
8
use serde::{Deserialize, Serialize};
9

            
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11
#[serde(rename_all = "lowercase")]
12
pub enum ChartKind {
13
    Bar,
14
    /// Bars grow right from a left axis of x labels, one row per label.
15
    HBar,
16
    StackedBar,
17
    Line,
18
}
19

            
20
/// One x/y datum. `y` is carried as a `num`/`denom` pair so the exact
21
/// Rational64 crosses the wire without float drift; each renderer
22
/// converts to `f64` for display.
23
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24
pub struct SeriesPoint {
25
    pub x: String,
26
    pub y_num: i64,
27
    pub y_denom: i64,
28
}
29

            
30
impl SeriesPoint {
31
    /// Best-effort conversion to an `f64` for the renderer. A zero
32
    /// denominator falls back to 0.0 rather than panicking — an
33
    /// invariant violation in the IR shouldn't take down the renderer.
34
    #[must_use]
35
36359
    pub fn y_f64(&self) -> f64 {
36
36359
        if self.y_denom == 0 {
37
1
            return 0.0;
38
36358
        }
39
36358
        self.y_num as f64 / self.y_denom as f64
40
36359
    }
41
}
42

            
43
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44
pub struct Series {
45
    pub label: String,
46
    /// Commodity symbol (e.g. "USD"). Empty when the series is unitless.
47
    pub commodity_symbol: String,
48
    pub points: Vec<SeriesPoint>,
49
}
50

            
51
/// A chart the server has already prepared. Renderers read this
52
/// directly; none of them compute totals, pick top-N, or negate
53
/// signs. All of that lives in the adapters.
54
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55
pub struct ChartSpec {
56
    pub title: String,
57
    pub kind: ChartKind,
58
    pub x_label: String,
59
    pub y_label: String,
60
    pub series: Vec<Series>,
61
    /// Display-time notes (e.g. "Showing USD; 2 other commodities
62
    /// hidden"). Rendered as an info line under the chart.
63
    pub notes: Vec<String>,
64
}
65

            
66
#[cfg(test)]
67
mod tests {
68
    use super::*;
69

            
70
1
    fn sample() -> ChartSpec {
71
1
        ChartSpec {
72
1
            title: "Income vs Expense".to_string(),
73
1
            kind: ChartKind::StackedBar,
74
1
            x_label: "Month".to_string(),
75
1
            y_label: "Amount".to_string(),
76
1
            series: vec![
77
1
                Series {
78
1
                    label: "Income".to_string(),
79
1
                    commodity_symbol: "USD".to_string(),
80
1
                    points: vec![
81
1
                        SeriesPoint {
82
1
                            x: "2026-01".to_string(),
83
1
                            y_num: 3200,
84
1
                            y_denom: 1,
85
1
                        },
86
1
                        SeriesPoint {
87
1
                            x: "2026-02".to_string(),
88
1
                            y_num: 2800,
89
1
                            y_denom: 1,
90
1
                        },
91
1
                    ],
92
1
                },
93
1
                Series {
94
1
                    label: "Expense".to_string(),
95
1
                    commodity_symbol: "USD".to_string(),
96
1
                    points: vec![
97
1
                        SeriesPoint {
98
1
                            x: "2026-01".to_string(),
99
1
                            y_num: 2100,
100
1
                            y_denom: 1,
101
1
                        },
102
1
                        SeriesPoint {
103
1
                            x: "2026-02".to_string(),
104
1
                            y_num: 1900,
105
1
                            y_denom: 1,
106
1
                        },
107
1
                    ],
108
1
                },
109
1
            ],
110
1
            notes: vec!["Showing USD only; 1 other commodity hidden".to_string()],
111
1
        }
112
1
    }
113

            
114
    #[test]
115
1
    fn spec_round_trips_through_json() {
116
1
        let original = sample();
117
1
        let encoded = serde_json::to_string(&original).expect("serialise");
118
1
        let decoded: ChartSpec = serde_json::from_str(&encoded).expect("deserialise");
119
1
        assert_eq!(decoded, original, "wire format must be lossless");
120
1
    }
121

            
122
    #[test]
123
1
    fn chart_kind_serialises_as_lowercase() {
124
1
        let s = serde_json::to_string(&ChartKind::StackedBar).expect("serialise");
125
1
        assert_eq!(s, "\"stackedbar\"");
126
1
    }
127

            
128
    #[test]
129
1
    fn series_point_converts_to_f64() {
130
1
        let p = SeriesPoint {
131
1
            x: "x".to_string(),
132
1
            y_num: 3,
133
1
            y_denom: 2,
134
1
        };
135
1
        assert!((p.y_f64() - 1.5).abs() < f64::EPSILON);
136
1
    }
137

            
138
    #[test]
139
1
    fn series_point_zero_denominator_is_safe() {
140
1
        let p = SeriesPoint {
141
1
            x: "x".to_string(),
142
1
            y_num: 42,
143
1
            y_denom: 0,
144
1
        };
145
1
        assert_eq!(p.y_f64(), 0.0);
146
1
    }
147
}