Skip to main content

tui/app/
bulk_delete.rs

1//! Deleting the marked transactions: one `delete-transaction` per id, as Emacs does.
2
3use cli_core::eval::build_delete_transaction_form;
4use cli_core::render::{RenderError, WireValue, parse_wire};
5
6use rpc::ErrorCode;
7
8use super::App;
9use crate::modal::{ConfirmAction, Modal};
10use crate::route::RouteCtx;
11use crate::tabs::list::ListTab;
12use crate::tabs::seq::Seq;
13use crate::view::ViewId;
14use crate::viewer::Source;
15use crate::window::WindowId;
16
17/// The bulk delete in flight.
18#[derive(Default)]
19pub(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
31impl BulkDelete {
32    fn start(&mut self, total: usize, origin: WindowId) -> u64 {
33        let mut seq = self.seq;
34        let id = seq.advance();
35        *self = Self {
36            seq,
37            total,
38            pending: total,
39            origin: Some(origin),
40            ..Self::default()
41        };
42        id
43    }
44
45    fn summary(&self) -> String {
46        let mut text = format!("deleted {} of {} transactions", self.deleted, self.total);
47        if !self.failures.is_empty() {
48            text.push_str(&format!("; failed: {}", self.failures.join("; ")));
49        }
50        if self.pending > 0 {
51            text.push_str(&format!("; outcome unknown for {}", self.pending));
52        }
53        text
54    }
55
56    /// Gives up on the unanswered deletes; the partial outcome, or `None` when nothing ran.
57    pub(super) fn abandon(&mut self) -> Option<String> {
58        if self.pending == 0 {
59            return None;
60        }
61        let text = self.summary();
62        let mut seq = self.seq;
63        seq.advance();
64        *self = Self {
65            seq,
66            orphan_deleted: self.orphan_deleted,
67            ..Self::default()
68        };
69        Some(text)
70    }
71}
72
73enum Outcome {
74    Deleted,
75    Gone,
76    Failed(String),
77}
78
79fn reply_outcome(wire: &str) -> Outcome {
80    match parse_wire(wire) {
81        Err(RenderError::Server(reply)) if reply.code == ErrorCode::NOT_FOUND => Outcome::Gone,
82        Err(e) => Outcome::Failed(e.to_string()),
83        Ok(WireValue::Value(value)) if value.is_nil() => Outcome::Failed("not deleted".into()),
84        Ok(_) => Outcome::Deleted,
85    }
86}
87
88impl App {
89    pub fn open_delete_marked(&mut self) {
90        let Some(window) = self.front_or_say(ViewId::Transactions) else {
91            return;
92        };
93        let ids = self
94            .win::<ListTab>(window)
95            .map(ListTab::marked_ids)
96            .unwrap_or_default();
97        if ids.is_empty() {
98            self.set_status("no marked transactions");
99            return;
100        }
101        if self.bulk.pending > 0 {
102            self.set_status("a bulk delete is still running");
103            return;
104        }
105        if self.dialog_free("delete of marked transactions") {
106            self.open_dialog_in(
107                window,
108                Modal::confirm(
109                    format!("Delete {} marked transactions?", ids.len()),
110                    ConfirmAction::DeleteMarked(ids),
111                ),
112            );
113        }
114    }
115
116    pub(crate) fn submit_delete_marked(&mut self, ids: Vec<String>) {
117        if self.console_eval.is_none() {
118            self.set_status("console not connected");
119            return;
120        }
121        let Some(window) = self.dialog_window() else {
122            return;
123        };
124        let seq = self.bulk.start(ids.len(), window);
125        for id in ids {
126            let ctx = RouteCtx::BulkDelete {
127                seq,
128                id: id.clone(),
129            };
130            let form = build_delete_transaction_form(&id);
131            if self.dispatch_eval(window, ctx, form).is_none() {
132                self.record_bulk_reply(&id, Outcome::Failed("not sent".into()));
133            }
134        }
135    }
136
137    pub(super) fn deliver_bulk_delete_reply(&mut self, seq: u64, id: &str, wire: &str) {
138        if self.bulk.seq.awaits(seq) {
139            self.record_bulk_reply(id, reply_outcome(wire));
140        }
141    }
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    pub(super) fn settle_orphan_bulk(&mut self, wire: &str) {
146        self.bulk.orphan_deleted |= matches!(reply_outcome(wire), Outcome::Deleted);
147        let more = self
148            .pending_routes
149            .values()
150            .any(|route| matches!(route.ctx, RouteCtx::BulkDelete { .. }));
151        if !more && std::mem::take(&mut self.bulk.orphan_deleted) {
152            self.refresh_windows(ViewId::Transactions);
153        }
154    }
155
156    /// A deleted transaction leaves its list's marks and closes its open detail.
157    pub(super) fn forget_transaction(&mut self, window: Option<WindowId>, id: &str) {
158        let list = window.and_then(|window| self.win_mut::<ListTab>(window));
159        if let Some(list) = list {
160            list.unmark(id);
161        }
162        if let Some(detail) = self.viewer_of(&Source::Detail { id: id.to_string() }) {
163            self.close_window(detail);
164        }
165    }
166
167    fn record_bulk_reply(&mut self, id: &str, outcome: Outcome) {
168        match outcome {
169            Outcome::Deleted => {
170                self.forget_transaction(self.bulk.origin, id);
171                self.bulk.deleted += 1;
172            }
173            Outcome::Gone => {
174                self.forget_transaction(self.bulk.origin, id);
175                self.bulk.failures.push(format!("{id}: not found"));
176            }
177            Outcome::Failed(reason) => self.bulk.failures.push(format!("{id}: {reason}")),
178        }
179        self.bulk.pending = self.bulk.pending.saturating_sub(1);
180        if self.bulk.pending == 0 {
181            let summary = self.bulk.summary();
182            self.set_status(summary);
183            self.refresh_windows(ViewId::Transactions);
184        }
185    }
186}