1
//! Deleting the marked transactions: one `delete-transaction` per id, as Emacs does.
2

            
3
use cli_core::eval::build_delete_transaction_form;
4
use cli_core::render::{RenderError, WireValue, parse_wire};
5

            
6
use rpc::ErrorCode;
7

            
8
use super::App;
9
use crate::modal::{ConfirmAction, Modal};
10
use crate::route::RouteCtx;
11
use crate::tabs::list::ListTab;
12
use crate::tabs::seq::Seq;
13
use crate::view::ViewId;
14
use crate::viewer::Source;
15
use crate::window::WindowId;
16

            
17
/// The bulk delete in flight.
18
#[derive(Default)]
19
pub(super) struct BulkDelete {
20
    seq: Seq,
21
    total: usize,
22
    pending: usize,
23
    /// The window the delete was confirmed in; its marks go as the deletes succeed.
24
    origin: Option<WindowId>,
25
    deleted: usize,
26
    failures: Vec<String>,
27
    /// Whether a delete of an abandoned bulk went through, so the list is stale.
28
    orphan_deleted: bool,
29
}
30

            
31
impl BulkDelete {
32
16
    fn start(&mut self, total: usize, origin: WindowId) -> u64 {
33
16
        let mut seq = self.seq;
34
16
        let id = seq.advance();
35
16
        *self = Self {
36
16
            seq,
37
16
            total,
38
16
            pending: total,
39
16
            origin: Some(origin),
40
16
            ..Self::default()
41
16
        };
42
16
        id
43
16
    }
44

            
45
14
    fn summary(&self) -> String {
46
14
        let mut text = format!("deleted {} of {} transactions", self.deleted, self.total);
47
14
        if !self.failures.is_empty() {
48
5
            text.push_str(&format!("; failed: {}", self.failures.join("; ")));
49
9
        }
50
14
        if self.pending > 0 {
51
7
            text.push_str(&format!("; outcome unknown for {}", self.pending));
52
7
        }
53
14
        text
54
14
    }
55

            
56
    /// Gives up on the unanswered deletes; the partial outcome, or `None` when nothing ran.
57
8
    pub(super) fn abandon(&mut self) -> Option<String> {
58
8
        if self.pending == 0 {
59
1
            return None;
60
7
        }
61
7
        let text = self.summary();
62
7
        let mut seq = self.seq;
63
7
        seq.advance();
64
7
        *self = Self {
65
7
            seq,
66
7
            orphan_deleted: self.orphan_deleted,
67
7
            ..Self::default()
68
7
        };
69
7
        Some(text)
70
8
    }
71
}
72

            
73
enum Outcome {
74
    Deleted,
75
    Gone,
76
    Failed(String),
77
}
78

            
79
20
fn reply_outcome(wire: &str) -> Outcome {
80
20
    match parse_wire(wire) {
81
8
        Err(RenderError::Server(reply)) if reply.code == ErrorCode::NOT_FOUND => Outcome::Gone,
82
7
        Err(e) => Outcome::Failed(e.to_string()),
83
12
        Ok(WireValue::Value(value)) if value.is_nil() => Outcome::Failed("not deleted".into()),
84
11
        Ok(_) => Outcome::Deleted,
85
    }
86
20
}
87

            
88
impl App {
89
14
    pub fn open_delete_marked(&mut self) {
90
14
        let Some(window) = self.front_or_say(ViewId::Transactions) else {
91
1
            return;
92
        };
93
13
        let ids = self
94
13
            .win::<ListTab>(window)
95
13
            .map(ListTab::marked_ids)
96
13
            .unwrap_or_default();
97
13
        if ids.is_empty() {
98
1
            self.set_status("no marked transactions");
99
1
            return;
100
12
        }
101
12
        if self.bulk.pending > 0 {
102
1
            self.set_status("a bulk delete is still running");
103
1
            return;
104
11
        }
105
11
        if self.dialog_free("delete of marked transactions") {
106
11
            self.open_dialog_in(
107
11
                window,
108
11
                Modal::confirm(
109
11
                    format!("Delete {} marked transactions?", ids.len()),
110
11
                    ConfirmAction::DeleteMarked(ids),
111
11
                ),
112
11
            );
113
        }
114
14
    }
115

            
116
16
    pub(crate) fn submit_delete_marked(&mut self, ids: Vec<String>) {
117
16
        if self.console_eval.is_none() {
118
            self.set_status("console not connected");
119
            return;
120
16
        }
121
16
        let Some(window) = self.dialog_window() else {
122
            return;
123
        };
124
16
        let seq = self.bulk.start(ids.len(), window);
125
16
        for id in ids {
126
27
            let ctx = RouteCtx::BulkDelete {
127
27
                seq,
128
27
                id: id.clone(),
129
27
            };
130
27
            let form = build_delete_transaction_form(&id);
131
27
            if self.dispatch_eval(window, ctx, form).is_none() {
132
                self.record_bulk_reply(&id, Outcome::Failed("not sent".into()));
133
27
            }
134
        }
135
16
    }
136

            
137
14
    pub(super) fn deliver_bulk_delete_reply(&mut self, seq: u64, id: &str, wire: &str) {
138
14
        if self.bulk.seq.awaits(seq) {
139
13
            self.record_bulk_reply(id, reply_outcome(wire));
140
1
        }
141
14
    }
142

            
143
    /// A reply of a bulk delete whose window closed: the list refreshes once the last one is
144
    /// in, if any delete went through.
145
7
    pub(super) fn settle_orphan_bulk(&mut self, wire: &str) {
146
7
        self.bulk.orphan_deleted |= matches!(reply_outcome(wire), Outcome::Deleted);
147
7
        let more = self
148
7
            .pending_routes
149
7
            .values()
150
8
            .any(|route| matches!(route.ctx, RouteCtx::BulkDelete { .. }));
151
7
        if !more && std::mem::take(&mut self.bulk.orphan_deleted) {
152
3
            self.refresh_windows(ViewId::Transactions);
153
4
        }
154
7
    }
155

            
156
    /// A deleted transaction leaves its list's marks and closes its open detail.
157
13
    pub(super) fn forget_transaction(&mut self, window: Option<WindowId>, id: &str) {
158
13
        let list = window.and_then(|window| self.win_mut::<ListTab>(window));
159
13
        if let Some(list) = list {
160
13
            list.unmark(id);
161
        }
162
13
        if let Some(detail) = self.viewer_of(&Source::Detail { id: id.to_string() }) {
163
2
            self.close_window(detail);
164
11
        }
165
13
    }
166

            
167
13
    fn record_bulk_reply(&mut self, id: &str, outcome: Outcome) {
168
13
        match outcome {
169
            Outcome::Deleted => {
170
7
                self.forget_transaction(self.bulk.origin, id);
171
7
                self.bulk.deleted += 1;
172
            }
173
            Outcome::Gone => {
174
1
                self.forget_transaction(self.bulk.origin, id);
175
1
                self.bulk.failures.push(format!("{id}: not found"));
176
            }
177
5
            Outcome::Failed(reason) => self.bulk.failures.push(format!("{id}: {reason}")),
178
        }
179
13
        self.bulk.pending = self.bulk.pending.saturating_sub(1);
180
13
        if self.bulk.pending == 0 {
181
7
            let summary = self.bulk.summary();
182
7
            self.set_status(summary);
183
7
            self.refresh_windows(ViewId::Transactions);
184
6
        }
185
13
    }
186
}