1
//! Schema-driven projection of typed entity plist replies into display rows.
2

            
3
use std::collections::HashMap;
4

            
5
use nomiscript::{Value, format_value, list_to_vec};
6

            
7
use crate::render::{ListRow, account_order};
8

            
9
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10
pub enum ColumnKind {
11
    Plain,
12
    ParentName,
13
}
14

            
15
pub struct Column {
16
    pub header: &'static str,
17
    pub key: &'static str,
18
    pub kind: ColumnKind,
19
}
20

            
21
pub struct EntitySchema {
22
    pub columns: &'static [Column],
23
    /// Order the records by account path, then id.
24
    pub by_account_path: bool,
25
}
26

            
27
pub 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

            
48
pub 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`.
65
4274
pub fn headers(schema: &EntitySchema) -> Vec<&'static str> {
66
12821
    schema.columns.iter().map(|c| c.header).collect()
67
4274
}
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.
73
2053
pub fn project_rows(value: &Value, schema: &EntitySchema) -> Vec<ListRow> {
74
2053
    match value {
75
37
        Value::Nil => vec![],
76
        Value::Pair(_) => {
77
1955
            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
1955
            if elements.is_empty() {
84
                return vec![];
85
1955
            }
86
1955
            if elements
87
1955
                .first()
88
1955
                .is_some_and(|e| matches!(e, Value::Pair(_)))
89
            {
90
1955
                if schema.by_account_path {
91
1954
                    account_order::sort_by_path(&mut elements);
92
1
                }
93
1955
                let id_to_name = build_name_map(&elements);
94
1955
                elements
95
1955
                    .iter()
96
29478
                    .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
61
        other => vec![ListRow {
104
61
            id: None,
105
61
            cells: vec![format_value(other)],
106
61
        }],
107
    }
108
2053
}
109

            
110
1955
fn build_name_map(elements: &[Value]) -> HashMap<String, String> {
111
1955
    elements
112
1955
        .iter()
113
29478
        .filter_map(|e| {
114
29478
            let id = super::row_id(e)?;
115
29478
            let name = crate::eval::plist_field(e, ":name")?;
116
29478
            Some((id, name))
117
29478
        })
118
        .collect()
119
1955
}
120

            
121
fn 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

            
128
29478
fn project_element(
129
29478
    element: &Value,
130
29478
    schema: &EntitySchema,
131
29478
    id_to_name: &HashMap<String, String>,
132
29478
) -> ListRow {
133
29478
    let id = super::row_id(element);
134
29478
    let cells = schema
135
29478
        .columns
136
29478
        .iter()
137
88433
        .map(|col| {
138
88433
            let raw = crate::eval::plist_field(element, col.key).unwrap_or_default();
139
88433
            match col.kind {
140
58956
                ColumnKind::Plain => raw,
141
                ColumnKind::ParentName => {
142
29477
                    if raw.is_empty() {
143
29410
                        String::new()
144
                    } else {
145
67
                        id_to_name.get(&raw).cloned().unwrap_or_default()
146
                    }
147
                }
148
            }
149
88433
        })
150
        .collect();
151
29478
    ListRow { id, cells }
152
29478
}
153

            
154
#[cfg(test)]
155
mod tests {
156
    use nomiscript::{Number, Value};
157

            
158
    use super::*;
159
    use crate::render::reparse_list;
160

            
161
6
    fn accounts_list() -> Value {
162
6
        reparse_list(
163
6
            r#"((:account :id "uuid-1" :name "Checking" :parent "") (:account :id "uuid-2" :name "Savings" :parent "uuid-1"))"#,
164
6
        )
165
6
        .expect("accounts list parses")
166
6
    }
167

            
168
    #[test]
169
1
    fn project_rows_nil_returns_empty() {
170
1
        assert_eq!(project_rows(&Value::Nil, &ACCOUNTS), vec![]);
171
1
    }
172

            
173
    #[test]
174
1
    fn project_rows_accounts_cell_count_matches_columns() {
175
1
        let rows = project_rows(&accounts_list(), &ACCOUNTS);
176
1
        assert_eq!(rows.len(), 2);
177
1
        for row in &rows {
178
2
            assert_eq!(row.cells.len(), ACCOUNTS.columns.len());
179
        }
180
1
    }
181

            
182
    #[test]
183
1
    fn project_rows_accounts_correct_name_value() {
184
1
        let rows = project_rows(&accounts_list(), &ACCOUNTS);
185
1
        assert_eq!(rows[0].cells[0], "Checking");
186
1
    }
187

            
188
    #[test]
189
1
    fn project_rows_blank_when_type_key_absent() {
190
1
        let rows = project_rows(&accounts_list(), &ACCOUNTS);
191
1
        assert_eq!(rows[0].cells[1], "");
192
1
    }
193

            
194
    #[test]
195
1
    fn project_rows_parent_name_resolved_from_list() {
196
        // uuid-2 has :parent "uuid-1" (Checking), ParentName resolves to "Checking"
197
1
        let rows = project_rows(&accounts_list(), &ACCOUNTS);
198
1
        assert_eq!(rows[1].cells[0], "Savings");
199
1
        assert_eq!(rows[1].cells[2], "Checking");
200
1
    }
201

            
202
    #[test]
203
1
    fn project_rows_parent_name_blank_for_empty_parent() {
204
1
        let rows = project_rows(&accounts_list(), &ACCOUNTS);
205
1
        assert_eq!(rows[0].cells[2], "");
206
1
    }
207

            
208
    #[test]
209
1
    fn project_rows_parent_name_blank_for_unknown_parent() {
210
        let value =
211
1
            reparse_list(r#"((:account :id "x" :name "Orphan" :parent "no-such-uuid"))"#).unwrap();
212
1
        let rows = project_rows(&value, &ACCOUNTS);
213
1
        assert_eq!(rows[0].cells[2], "");
214
1
    }
215

            
216
    #[test]
217
1
    fn project_rows_id_in_row_id_not_in_cells() {
218
1
        let rows = project_rows(&accounts_list(), &ACCOUNTS);
219
1
        assert_eq!(rows[0].id.as_deref(), Some("uuid-1"));
220
1
        for cell in &rows[0].cells {
221
3
            assert_ne!(cell, "uuid-1");
222
        }
223
1
    }
224

            
225
    #[test]
226
1
    fn project_rows_blank_when_key_absent() {
227
1
        let value = reparse_list(r#"((:account :id "x" :name "NoType"))"#).unwrap();
228
1
        let rows = project_rows(&value, &ACCOUNTS);
229
1
        assert_eq!(rows.len(), 1);
230
1
        assert_eq!(rows[0].cells[1], "");
231
1
        assert_eq!(rows[0].cells[2], "");
232
1
    }
233

            
234
    #[test]
235
1
    fn project_rows_commodities_schema() {
236
        let value =
237
1
            reparse_list(r#"((:commodity :id "c-1" :symbol "USD" :name "US Dollar"))"#).unwrap();
238
1
        let rows = project_rows(&value, &COMMODITIES);
239
1
        assert_eq!(rows.len(), 1);
240
1
        assert_eq!(rows[0].cells.len(), COMMODITIES.columns.len());
241
1
        assert_eq!(rows[0].cells[0], "USD");
242
1
        assert_eq!(rows[0].cells[1], "US Dollar");
243
1
    }
244

            
245
    #[test]
246
1
    fn project_rows_scalar_number_fallback() {
247
1
        let value = Value::Number(Number::Index(42));
248
1
        let rows = project_rows(&value, &ACCOUNTS);
249
1
        assert_eq!(rows.len(), 1);
250
1
        assert_eq!(rows[0].id, None);
251
1
        assert_eq!(rows[0].cells, vec!["42"]);
252
1
    }
253

            
254
    #[test]
255
1
    fn headers_returns_account_column_headers() {
256
1
        assert_eq!(headers(&ACCOUNTS), vec!["Name", "Type", "Parent"]);
257
1
    }
258

            
259
    #[test]
260
1
    fn headers_returns_commodity_column_headers() {
261
1
        assert_eq!(headers(&COMMODITIES), vec!["Symbol", "Name"]);
262
1
    }
263

            
264
    #[test]
265
1
    fn project_rows_accounts_type_extracted_when_present() {
266
1
        let value = reparse_list(r#"((:account :id "a-1" :name "Bank" :type "asset" :parent ""))"#)
267
1
            .unwrap();
268
1
        let rows = project_rows(&value, &ACCOUNTS);
269
1
        assert_eq!(rows.len(), 1);
270
1
        assert_eq!(rows[0].cells[0], "Bank");
271
1
        assert_eq!(rows[0].cells[1], "asset");
272
1
    }
273
}