1
//! The Templates tab through the real key dispatch: list, delete and cancelled delete.
2

            
3
use super::edit::options_wire;
4
use crate::app::App;
5
use crate::modal::Modal;
6
use crate::route::{RouteCtx, TemplateRoute};
7
use crate::tabs::fetch::Fetch;
8
use crate::tabs::nms_eval::double::Sent;
9
use crate::test_support::{ctrl, key, press};
10
use crate::view::Tab;
11
use ratatui::crossterm::event::KeyCode;
12

            
13
pub(super) const RENT: &str = "aaaaaaaa-0000-0000-0000-000000000001";
14
pub(super) const SALARY: &str = "bbbbbbbb-0000-0000-0000-000000000002";
15

            
16
27
pub(super) fn templates_app() -> (App, Sent) {
17
27
    let mut app = crate::test_support::app();
18
27
    let sent = app.attach_echo();
19
27
    app.switch_tab(Tab::Templates);
20
27
    (app, sent)
21
27
}
22

            
23
21
fn loading_id(app: &App) -> anyhow::Result<i64> {
24
21
    match app.templates().state {
25
21
        Fetch::Loading { id } => Ok(id),
26
        ref other => anyhow::bail!("not loading: {other:?}"),
27
    }
28
21
}
29

            
30
18
pub(super) fn load(app: &mut App, templates: &[(&str, &str)]) -> anyhow::Result<()> {
31
18
    let id = loading_id(app)?;
32
18
    let wire = options_wire(templates).replacen(":id 2", &format!(":id {id}"), 1);
33
18
    app.route_reply(id, &wire);
34
18
    Ok(())
35
18
}
36

            
37
3
fn pending_delete(app: &App) -> Option<(i64, String)> {
38
3
    app.pending_routes
39
3
        .iter()
40
2
        .find_map(|(id, route)| match &route.ctx {
41
2
            RouteCtx::Template(TemplateRoute::Delete { label }) => Some((*id, label.clone())),
42
            _ => None,
43
2
        })
44
3
}
45

            
46
4
fn shown(app: &App) -> Vec<&str> {
47
4
    app.templates()
48
4
        .rows()
49
4
        .iter()
50
6
        .map(|row| row.name.as_str())
51
        .collect()
52
4
}
53

            
54
#[tokio::test]
55
1
async fn opening_the_tab_lists_the_templates() -> anyhow::Result<()> {
56
1
    let (mut app, sent) = templates_app();
57
1
    load(&mut app, &[(RENT, "rent"), (SALARY, "salary")])?;
58
1
    assert_eq!(shown(&app), ["rent", "salary"]);
59
1
    tokio::task::yield_now().await;
60
1
    app.drain_eval();
61
1
    let echoed = sent.frames().join("\n");
62
1
    assert!(echoed.contains(r#"(form-options "templates")"#), "{echoed}");
63
2
    Ok(())
64
1
}
65

            
66
#[tokio::test]
67
1
async fn a_list_error_shows_in_the_tab() -> anyhow::Result<()> {
68
1
    let (mut app, _) = templates_app();
69
1
    let id = loading_id(&app)?;
70
1
    app.route_reply(
71
1
        id,
72
1
        &format!(r#"(:id {id} :error (:code db :message "connection refused"))"#),
73
1
    );
74
1
    assert!(matches!(&app.templates().state, Fetch::Error(m) if m.contains("connection refused")));
75
2
    Ok(())
76
1
}
77

            
78
#[tokio::test]
79
1
async fn a_stale_list_reply_is_dropped() -> anyhow::Result<()> {
80
1
    let (mut app, _) = templates_app();
81
1
    let stale = loading_id(&app)?;
82
1
    app.fetch_templates(app.window_of(crate::view::ViewId::Templates));
83
1
    let current = loading_id(&app)?;
84
2
    let reply = |id: i64, name: &str| {
85
2
        options_wire(&[(RENT, name)]).replacen(":id 2", &format!(":id {id}"), 1)
86
2
    };
87
1
    app.route_reply(stale, &reply(stale, "old"));
88
1
    assert!(app.templates().rows().is_empty());
89
1
    app.route_reply(current, &reply(current, "new"));
90
1
    assert_eq!(shown(&app), ["new"]);
91
2
    Ok(())
92
1
}
93

            
94
#[tokio::test]
95
1
async fn the_number_key_and_r_reach_the_tab() -> anyhow::Result<()> {
96
1
    let (mut app, _) = templates_app();
97
1
    load(&mut app, &[(RENT, "rent")])?;
98
1
    press(&mut app, ctrl(KeyCode::Char('r')));
99
1
    assert!(app.templates().any_loading());
100
1
    app.switch_tab(Tab::Accounts);
101
1
    press(&mut app, key(KeyCode::Char('8')));
102
1
    assert_eq!(app.front_kind(), Some(Tab::Templates));
103
2
    Ok(())
104
1
}
105

            
106
#[tokio::test]
107
1
async fn d_without_a_selection_says_so() {
108
1
    let (mut app, _) = templates_app();
109
1
    press(&mut app, key(KeyCode::Char('d')));
110
1
    assert_eq!(app.status, "no template selected");
111
1
    assert!(app.overlays.is_empty());
112
1
}
113

            
114
#[tokio::test]
115
1
async fn d_asks_naming_the_template_and_n_cancels() -> anyhow::Result<()> {
116
1
    let (mut app, _) = templates_app();
117
1
    load(&mut app, &[(RENT, "rent"), (SALARY, "salary")])?;
118
1
    press(&mut app, key(KeyCode::Char('j')));
119

            
120
1
    press(&mut app, key(KeyCode::Char('d')));
121
1
    let Some(Modal::Confirm { prompt, .. }) = app.overlays.top() else {
122
        anyhow::bail!("no confirm");
123
    };
124
1
    assert_eq!(prompt, "Delete template salary?");
125

            
126
1
    press(&mut app, key(KeyCode::Char('n')));
127
1
    assert!(app.overlays.is_empty());
128
1
    assert!(pending_delete(&app).is_none());
129
1
    assert_eq!(shown(&app), ["rent", "salary"]);
130
2
    Ok(())
131
1
}
132

            
133
#[tokio::test]
134
1
async fn enter_confirms_the_delete_over_delete_template_and_refreshes() -> anyhow::Result<()> {
135
1
    let (mut app, sent) = templates_app();
136
1
    load(&mut app, &[(RENT, "rent"), (SALARY, "salary")])?;
137
1
    press(&mut app, key(KeyCode::Char('d')));
138

            
139
1
    press(&mut app, key(KeyCode::Enter));
140
1
    let (id, label) = pending_delete(&app).ok_or_else(|| anyhow::anyhow!("delete not sent"))?;
141
1
    assert_eq!(label, "rent");
142
1
    tokio::task::yield_now().await;
143
1
    app.drain_eval();
144
1
    let echoed = sent.frames().join("\n");
145
1
    assert!(
146
1
        echoed.contains(&format!(r#"(delete-template "{RENT}")"#)),
147
        "{echoed}"
148
    );
149

            
150
1
    app.route_reply(id, &format!("(:id {id} :value t)"));
151
1
    assert_eq!(app.status, "deleted rent");
152
1
    load(&mut app, &[(SALARY, "salary")])?;
153
1
    assert_eq!(shown(&app), ["salary"]);
154
2
    Ok(())
155
1
}
156

            
157
#[tokio::test]
158
1
async fn a_failed_delete_shows_the_servers_message_and_does_not_refetch() -> anyhow::Result<()> {
159
1
    let (mut app, _) = templates_app();
160
1
    load(&mut app, &[(RENT, "rent")])?;
161
1
    press(&mut app, key(KeyCode::Char('d')));
162
1
    press(&mut app, key(KeyCode::Char('y')));
163
1
    let (id, _) = pending_delete(&app).ok_or_else(|| anyhow::anyhow!("delete not sent"))?;
164

            
165
1
    app.route_reply(
166
1
        id,
167
1
        &format!(r#"(:id {id} :error (:code not-found :message "no such template"))"#),
168
1
    );
169

            
170
1
    assert!(app.status.contains("no such template"), "{}", app.status);
171
1
    assert!(!app.templates().any_loading());
172
2
    Ok(())
173
1
}