1
//! Transaction commands over the client-form natives.
2

            
3
use forms::{Form, FormValues, TRANSACTION_CREATE, TRANSACTION_QUERY, escape_str, write_payload};
4
use nomiscript::Value;
5
use rpc::Session;
6

            
7
use crate::CommandError;
8
use crate::eval::{
9
    RenderMode, Rendered, build_delete_transaction_form, eval_form, next_id, plist_field,
10
    plist_field_raw, render_error_to_command,
11
};
12
use crate::forms::map_references;
13
use crate::render::{WireValue, parse_wire};
14

            
15
mod edit;
16
mod from_template;
17
mod show;
18
mod split_tags;
19

            
20
pub use edit::{apply, apply_form, edit, parse_loaded_for};
21
pub use from_template::create_from_template;
22
pub use show::{detail_form, render_detail, render_detail_reply, show};
23
pub use split_tags::{check_split_tags, link_split_tags};
24

            
25
#[derive(Debug, Clone, PartialEq, Eq)]
26
pub struct TransactionRow {
27
    pub id: String,
28
    /// The date as the server prints it in the user's zone.
29
    pub date: String,
30
    pub note: String,
31
    pub amount: String,
32
}
33

            
34
#[derive(Debug, Clone, PartialEq, Eq)]
35
pub struct Page {
36
    pub rows: Vec<TransactionRow>,
37
    pub has_more: bool,
38
    pub total: Option<u64>,
39
}
40

            
41
/// The `(submit-form …)` call for `values` against `form`.
42
#[must_use]
43
7163
pub fn submit_call(form: &Form, values: &FormValues) -> String {
44
7163
    format!(
45
        "(submit-form {} {})",
46
7163
        escape_str(form.name),
47
7163
        escape_str(&write_payload(form, values))
48
    )
49
7163
}
50

            
51
644
pub(crate) async fn eval_text(session: &mut Session, call: &str) -> Result<String, CommandError> {
52
644
    match eval_form(session, call, RenderMode::Scalar).await? {
53
636
        Rendered::Lines(lines) => lines
54
636
            .into_iter()
55
636
            .next()
56
            .ok_or_else(|| CommandError::Command("empty reply".to_string())),
57
        _ => Err(CommandError::Command("unexpected reply".to_string())),
58
    }
59
644
}
60

            
61
/// The reply value of evaluating `call`, without rendering it.
62
103
pub(crate) async fn eval_value(session: &mut Session, call: &str) -> Result<Value, CommandError> {
63
103
    let frame = format!("(:id {} :form {call})", next_id());
64
    let WireValue::Value(value) =
65
103
        parse_wire(&session.handle_form(&frame).await).map_err(render_error_to_command)?;
66
102
    Ok(value)
67
103
}
68

            
69
/// Create the transaction and return its id.
70
///
71
/// # Errors
72
/// [`CommandError::Argument`] for an unknown or ambiguous reference,
73
/// [`CommandError::FormInvalid`] with one line per rejected field, or the
74
/// server error.
75
92
pub async fn create(session: &mut Session, values: &FormValues) -> Result<String, CommandError> {
76
92
    let linked = link_split_tags(values)?;
77
92
    let mapped = map_references(session, &TRANSACTION_CREATE, &linked).await?;
78
89
    eval_text(session, &submit_call(&TRANSACTION_CREATE, &mapped)).await
79
92
}
80

            
81
/// # Errors
82
/// [`CommandError::FormInvalid`] for rejected filters, or the server error.
83
8
pub async fn query(session: &mut Session, values: &FormValues) -> Result<Page, CommandError> {
84
8
    let mapped = map_references(session, &TRANSACTION_QUERY, values).await?;
85
7
    parse_page(&eval_value(session, &submit_call(&TRANSACTION_QUERY, &mapped)).await?)
86
8
}
87

            
88
/// # Errors
89
/// The server error, or a command error when nothing was deleted.
90
2
pub async fn delete(session: &mut Session, id: &str) -> Result<(), CommandError> {
91
2
    let form = build_delete_transaction_form(id);
92
2
    match eval_form(session, &form, RenderMode::BoolSuccess).await? {
93
1
        Rendered::Lines(lines) if lines.first().is_some_and(|line| line == "true") => Ok(()),
94
        _ => Err(CommandError::Command(format!(
95
            "transaction {id} was not deleted"
96
        ))),
97
    }
98
2
}
99

            
100
/// # Errors
101
/// [`CommandError::Command`] when `reply` is not a `transaction-query` reply.
102
1096
pub fn parse_page(reply: &Value) -> Result<Page, CommandError> {
103
15
    let malformed = || {
104
15
        CommandError::Command(format!(
105
15
            "malformed transaction page: {}",
106
15
            nomiscript::format_value(reply)
107
15
        ))
108
15
    };
109
1096
    let rows = plist_field_raw(reply, ":rows").ok_or_else(malformed)?;
110
1083
    let rows = match rows {
111
163
        Value::Nil => Vec::new(),
112
920
        other => nomiscript::list_to_vec(&other).ok_or_else(malformed)?,
113
    };
114
    Ok(Page {
115
1082
        rows: rows
116
1082
            .iter()
117
1082
            .map(row_of)
118
1082
            .collect::<Option<_>>()
119
1082
            .ok_or_else(malformed)?,
120
1081
        has_more: matches!(plist_field_raw(reply, ":has-more"), Some(Value::T)),
121
1081
        total: match plist_field_raw(reply, ":total") {
122
1077
            Some(Value::Number(n)) => u64::try_from(n.value().to_integer()).ok(),
123
4
            _ => None,
124
        },
125
    })
126
1096
}
127

            
128
3415
fn row_of(row: &Value) -> Option<TransactionRow> {
129
    Some(TransactionRow {
130
3415
        id: plist_field(row, ":id")?,
131
3415
        date: plist_field(row, ":date-text")?,
132
3414
        note: plist_field(row, ":note")?,
133
3414
        amount: plist_field(row, ":amount")?,
134
    })
135
3415
}
136

            
137
/// One line per row.
138
#[must_use]
139
4
pub fn render_page(page: &Page) -> Vec<String> {
140
4
    page.rows
141
4
        .iter()
142
3
        .map(|row| {
143
3
            let note = note_line(&row.note);
144
3
            format!("{}  {note}  {}  {}", row.date, row.amount, row.id)
145
3
        })
146
        .collect()
147
4
}
148

            
149
/// The stderr footer of a listing that starts at row `offset`; `None` when
150
/// there is nothing to say.
151
#[must_use]
152
5
pub fn paging_note(page: &Page, offset: u64) -> Option<String> {
153
5
    let more = page.has_more.then_some("more… (raise --offset)");
154
5
    let range = page.total.filter(|_| !page.rows.is_empty()).map(|total| {
155
2
        let first = offset.saturating_add(1);
156
2
        let last = offset.saturating_add(page.rows.len() as u64);
157
2
        format!("rows {first}–{last} of {total}")
158
2
    });
159
5
    match (range, more) {
160
1
        (Some(range), Some(more)) => Some(format!("{range}; {more}")),
161
4
        (range, more) => range.or_else(|| more.map(str::to_string)),
162
    }
163
5
}
164

            
165
/// The first line of `note`, ending in an ellipsis when more lines follow.
166
6
pub(crate) fn note_line(note: &str) -> String {
167
6
    match note.split_once('\n') {
168
2
        Some((first, _)) => format!("{first} …"),
169
4
        None => note.to_string(),
170
    }
171
6
}
172

            
173
#[cfg(test)]
174
pub(crate) mod tests;