1
//! Paging state of the Transactions tab over the `transaction-query` form.
2

            
3
use std::ops::Range;
4

            
5
use cli_core::render::ListRow;
6
use cli_core::transaction::{Page, submit_call};
7
use forms::{FormValues, PAGING_KEYS, TRANSACTION_QUERY};
8
use tvui::range_text;
9

            
10
pub const PAGE_SIZE: u64 = 20;
11

            
12
#[derive(Debug, Clone, Default, PartialEq, Eq)]
13
pub struct Pager {
14
    offset: u64,
15
    total: Option<u64>,
16
    has_more: bool,
17
    filter: FormValues,
18
    summary: String,
19
}
20

            
21
/// The filtering values of `values`: the non-empty ones, paging keys left out.
22
#[must_use]
23
53
pub fn filter_of(values: &FormValues) -> FormValues {
24
53
    let mut filter = FormValues::default();
25
53
    TRANSACTION_QUERY
26
53
        .filter_fields()
27
159
        .filter_map(|field| Some((field.key, values.text(field.key)?)))
28
95
        .filter(|(_, text)| !text.is_empty())
29
54
        .for_each(|(key, text)| filter.set(key, text));
30
53
    filter
31
53
}
32

            
33
/// Short note of a filter: the account label and the `from–to` range.
34
#[must_use]
35
24
pub fn filter_summary(account_label: &str, filter: &FormValues) -> String {
36
24
    let (from, to) = (filter.text("from"), filter.text("to"));
37
24
    let range = (from.is_some() || to.is_some())
38
15
        .then(|| format!("{}\u{2013}{}", from.unwrap_or(""), to.unwrap_or("")));
39
24
    let account = filter.text("account").map(|_| account_label.to_string());
40
24
    [account, range]
41
24
        .into_iter()
42
24
        .flatten()
43
24
        .collect::<Vec<_>>()
44
24
        .join(" ")
45
24
}
46

            
47
279
fn query_call(filter: &FormValues, offset: u64) -> String {
48
279
    let mut values = filter.clone();
49
279
    let [limit_key, offset_key] = PAGING_KEYS;
50
279
    values.set(limit_key, &PAGE_SIZE.to_string());
51
279
    values.set(offset_key, &offset.to_string());
52
279
    submit_call(&TRANSACTION_QUERY, &values)
53
279
}
54

            
55
impl Pager {
56
    /// The `submit-form` call that fetches the current page.
57
    #[must_use]
58
257
    pub fn request(&self) -> String {
59
257
        query_call(&self.filter, self.offset)
60
257
    }
61

            
62
    /// The call that fetches the first page of `filter`, which is not applied yet.
63
    #[must_use]
64
22
    pub fn request_filtered(filter: &FormValues) -> String {
65
22
        query_call(&filter_of(filter), 0)
66
22
    }
67

            
68
    /// Show the first page of `filter` from now on.
69
24
    pub fn set_filter(&mut self, filter: &FormValues, summary: String) {
70
24
        *self = Self {
71
24
            filter: filter_of(filter),
72
24
            summary,
73
24
            ..Self::default()
74
24
        };
75
24
    }
76

            
77
    /// Drop the filter and go back to the first page.
78
8
    pub fn clear_filter(&mut self) {
79
8
        *self = Self::default();
80
8
    }
81

            
82
    #[must_use]
83
45
    pub fn filter(&self) -> &FormValues {
84
45
        &self.filter
85
45
    }
86

            
87
    #[must_use]
88
534
    pub fn summary(&self) -> &str {
89
534
        &self.summary
90
534
    }
91

            
92
    /// Step to the next page; `false` when the last one is showing.
93
42
    pub fn advance(&mut self) -> bool {
94
42
        let moved = self.has_more;
95
42
        if moved {
96
37
            self.offset = self.offset.saturating_add(PAGE_SIZE);
97
5
        }
98
42
        moved
99
42
    }
100

            
101
    /// Step to the previous page; `false` when the first one is showing.
102
12
    pub fn retreat(&mut self) -> bool {
103
12
        let moved = self.offset > 0;
104
12
        self.offset = self.offset.saturating_sub(PAGE_SIZE);
105
12
        moved
106
12
    }
107

            
108
    /// Record a received page. `true` when it is empty past the first page
109
    /// (rows were deleted), after which the offset points at the last page.
110
103
    pub fn accept(&mut self, page: &Page) -> bool {
111
103
        self.total = page.total;
112
103
        self.has_more = page.has_more;
113
103
        let overshot = page.rows.is_empty() && self.offset > 0;
114
103
        if overshot {
115
3
            let rows = page.total.unwrap_or(0);
116
3
            self.offset = rows.saturating_sub(1) / PAGE_SIZE * PAGE_SIZE;
117
100
        }
118
103
        overshot
119
103
    }
120

            
121
    /// The rows in all, when known, and the index of the page's first row among them.
122
    #[must_use]
123
25
    pub fn extent(&self, loaded: usize) -> (usize, usize) {
124
25
        let first = usize::try_from(self.offset).unwrap_or(usize::MAX);
125
25
        let total = self.total.and_then(|total| usize::try_from(total).ok());
126
25
        (total.unwrap_or(first.saturating_add(loaded)), first)
127
25
    }
128

            
129
    /// `n–m of total` for the `visible` rows of the page.
130
    #[must_use]
131
32
    pub fn range(&self, visible: Range<usize>) -> Option<String> {
132
32
        let total = usize::try_from(self.total?).ok()?;
133
25
        let first = usize::try_from(self.offset).ok()?;
134
25
        range_text(
135
25
            first.saturating_add(visible.start)..first.saturating_add(visible.end),
136
25
            total,
137
25
        )
138
32
    }
139
}
140

            
141
/// The display row of every transaction of the page.
142
#[must_use]
143
88
pub fn rows(page: &Page) -> Vec<ListRow> {
144
88
    page.rows
145
88
        .iter()
146
        .map(|row| ListRow {
147
287
            id: Some(row.id.clone()),
148
287
            cells: vec![row.date.clone(), row.note.clone(), row.amount.clone()],
149
287
        })
150
        .collect()
151
88
}
152

            
153
#[cfg(test)]
154
mod filter_tests;
155
#[cfg(test)]
156
mod tests;