Skip to main content

cli_core/render/
schema.rs

1//! Schema-driven projection of typed entity plist replies into display rows.
2
3use std::collections::HashMap;
4
5use nomiscript::{Value, format_value, list_to_vec};
6
7use crate::render::{ListRow, account_order};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum ColumnKind {
11    Plain,
12    ParentName,
13}
14
15pub struct Column {
16    pub header: &'static str,
17    pub key: &'static str,
18    pub kind: ColumnKind,
19}
20
21pub struct EntitySchema {
22    pub columns: &'static [Column],
23    /// Order the records by account path, then id.
24    pub by_account_path: bool,
25}
26
27pub static ACCOUNTS: EntitySchema = EntitySchema {
28    by_account_path: true,
29    columns: &[
30        Column {
31            header: "Name",
32            key: ":name",
33            kind: ColumnKind::Plain,
34        },
35        Column {
36            header: "Type",
37            key: ":type",
38            kind: ColumnKind::Plain,
39        },
40        Column {
41            header: "Parent",
42            key: ":parent",
43            kind: ColumnKind::ParentName,
44        },
45    ],
46};
47
48pub static COMMODITIES: EntitySchema = EntitySchema {
49    by_account_path: false,
50    columns: &[
51        Column {
52            header: "Symbol",
53            key: ":symbol",
54            kind: ColumnKind::Plain,
55        },
56        Column {
57            header: "Name",
58            key: ":name",
59            kind: ColumnKind::Plain,
60        },
61    ],
62};
63
64/// Return the header label for each column in `schema`.
65pub fn headers(schema: &EntitySchema) -> Vec<&'static str> {
66    schema.columns.iter().map(|c| c.header).collect()
67}
68
69/// Project a reply [`Value`] into schema-aligned [`ListRow`]s.
70///
71/// Each row has exactly `schema.columns.len()` cells; absent keys produce blank cells.
72/// The `:id` field is extracted into `ListRow.id` but never appears as a cell.
73pub fn project_rows(value: &Value, schema: &EntitySchema) -> Vec<ListRow> {
74    match value {
75        Value::Nil => vec![],
76        Value::Pair(_) => {
77            let Some(mut elements) = list_to_vec(value) else {
78                return vec![ListRow {
79                    id: None,
80                    cells: vec![format_value(value)],
81                }];
82            };
83            if elements.is_empty() {
84                return vec![];
85            }
86            if elements
87                .first()
88                .is_some_and(|e| matches!(e, Value::Pair(_)))
89            {
90                if schema.by_account_path {
91                    account_order::sort_by_path(&mut elements);
92                }
93                let id_to_name = build_name_map(&elements);
94                elements
95                    .iter()
96                    .map(|e| project_element(e, schema, &id_to_name))
97                    .collect()
98            } else {
99                let id_to_name = single_name_map(value);
100                vec![project_element(value, schema, &id_to_name)]
101            }
102        }
103        other => vec![ListRow {
104            id: None,
105            cells: vec![format_value(other)],
106        }],
107    }
108}
109
110fn build_name_map(elements: &[Value]) -> HashMap<String, String> {
111    elements
112        .iter()
113        .filter_map(|e| {
114            let id = super::row_id(e)?;
115            let name = crate::eval::plist_field(e, ":name")?;
116            Some((id, name))
117        })
118        .collect()
119}
120
121fn single_name_map(value: &Value) -> HashMap<String, String> {
122    super::row_id(value)
123        .zip(crate::eval::plist_field(value, ":name"))
124        .into_iter()
125        .collect()
126}
127
128fn project_element(
129    element: &Value,
130    schema: &EntitySchema,
131    id_to_name: &HashMap<String, String>,
132) -> ListRow {
133    let id = super::row_id(element);
134    let cells = schema
135        .columns
136        .iter()
137        .map(|col| {
138            let raw = crate::eval::plist_field(element, col.key).unwrap_or_default();
139            match col.kind {
140                ColumnKind::Plain => raw,
141                ColumnKind::ParentName => {
142                    if raw.is_empty() {
143                        String::new()
144                    } else {
145                        id_to_name.get(&raw).cloned().unwrap_or_default()
146                    }
147                }
148            }
149        })
150        .collect();
151    ListRow { id, cells }
152}
153
154#[cfg(test)]
155mod tests {
156    use nomiscript::{Number, Value};
157
158    use super::*;
159    use crate::render::reparse_list;
160
161    fn accounts_list() -> Value {
162        reparse_list(
163            r#"((:account :id "uuid-1" :name "Checking" :parent "") (:account :id "uuid-2" :name "Savings" :parent "uuid-1"))"#,
164        )
165        .expect("accounts list parses")
166    }
167
168    #[test]
169    fn project_rows_nil_returns_empty() {
170        assert_eq!(project_rows(&Value::Nil, &ACCOUNTS), vec![]);
171    }
172
173    #[test]
174    fn project_rows_accounts_cell_count_matches_columns() {
175        let rows = project_rows(&accounts_list(), &ACCOUNTS);
176        assert_eq!(rows.len(), 2);
177        for row in &rows {
178            assert_eq!(row.cells.len(), ACCOUNTS.columns.len());
179        }
180    }
181
182    #[test]
183    fn project_rows_accounts_correct_name_value() {
184        let rows = project_rows(&accounts_list(), &ACCOUNTS);
185        assert_eq!(rows[0].cells[0], "Checking");
186    }
187
188    #[test]
189    fn project_rows_blank_when_type_key_absent() {
190        let rows = project_rows(&accounts_list(), &ACCOUNTS);
191        assert_eq!(rows[0].cells[1], "");
192    }
193
194    #[test]
195    fn project_rows_parent_name_resolved_from_list() {
196        // uuid-2 has :parent "uuid-1" (Checking), ParentName resolves to "Checking"
197        let rows = project_rows(&accounts_list(), &ACCOUNTS);
198        assert_eq!(rows[1].cells[0], "Savings");
199        assert_eq!(rows[1].cells[2], "Checking");
200    }
201
202    #[test]
203    fn project_rows_parent_name_blank_for_empty_parent() {
204        let rows = project_rows(&accounts_list(), &ACCOUNTS);
205        assert_eq!(rows[0].cells[2], "");
206    }
207
208    #[test]
209    fn project_rows_parent_name_blank_for_unknown_parent() {
210        let value =
211            reparse_list(r#"((:account :id "x" :name "Orphan" :parent "no-such-uuid"))"#).unwrap();
212        let rows = project_rows(&value, &ACCOUNTS);
213        assert_eq!(rows[0].cells[2], "");
214    }
215
216    #[test]
217    fn project_rows_id_in_row_id_not_in_cells() {
218        let rows = project_rows(&accounts_list(), &ACCOUNTS);
219        assert_eq!(rows[0].id.as_deref(), Some("uuid-1"));
220        for cell in &rows[0].cells {
221            assert_ne!(cell, "uuid-1");
222        }
223    }
224
225    #[test]
226    fn project_rows_blank_when_key_absent() {
227        let value = reparse_list(r#"((:account :id "x" :name "NoType"))"#).unwrap();
228        let rows = project_rows(&value, &ACCOUNTS);
229        assert_eq!(rows.len(), 1);
230        assert_eq!(rows[0].cells[1], "");
231        assert_eq!(rows[0].cells[2], "");
232    }
233
234    #[test]
235    fn project_rows_commodities_schema() {
236        let value =
237            reparse_list(r#"((:commodity :id "c-1" :symbol "USD" :name "US Dollar"))"#).unwrap();
238        let rows = project_rows(&value, &COMMODITIES);
239        assert_eq!(rows.len(), 1);
240        assert_eq!(rows[0].cells.len(), COMMODITIES.columns.len());
241        assert_eq!(rows[0].cells[0], "USD");
242        assert_eq!(rows[0].cells[1], "US Dollar");
243    }
244
245    #[test]
246    fn project_rows_scalar_number_fallback() {
247        let value = Value::Number(Number::Index(42));
248        let rows = project_rows(&value, &ACCOUNTS);
249        assert_eq!(rows.len(), 1);
250        assert_eq!(rows[0].id, None);
251        assert_eq!(rows[0].cells, vec!["42"]);
252    }
253
254    #[test]
255    fn headers_returns_account_column_headers() {
256        assert_eq!(headers(&ACCOUNTS), vec!["Name", "Type", "Parent"]);
257    }
258
259    #[test]
260    fn headers_returns_commodity_column_headers() {
261        assert_eq!(headers(&COMMODITIES), vec!["Symbol", "Name"]);
262    }
263
264    #[test]
265    fn project_rows_accounts_type_extracted_when_present() {
266        let value = reparse_list(r#"((:account :id "a-1" :name "Bank" :type "asset" :parent ""))"#)
267            .unwrap();
268        let rows = project_rows(&value, &ACCOUNTS);
269        assert_eq!(rows.len(), 1);
270        assert_eq!(rows[0].cells[0], "Bank");
271        assert_eq!(rows[0].cells[1], "asset");
272    }
273}