Skip to main content

cli_core/
transaction.rs

1//! Transaction commands over the client-form natives.
2
3use forms::{Form, FormValues, TRANSACTION_CREATE, TRANSACTION_QUERY, escape_str, write_payload};
4use nomiscript::Value;
5use rpc::Session;
6
7use crate::CommandError;
8use crate::eval::{
9    RenderMode, Rendered, build_delete_transaction_form, eval_form, next_id, plist_field,
10    plist_field_raw, render_error_to_command,
11};
12use crate::forms::map_references;
13use crate::render::{WireValue, parse_wire};
14
15mod edit;
16mod from_template;
17mod show;
18mod split_tags;
19
20pub use edit::{apply, apply_form, edit, parse_loaded_for};
21pub use from_template::create_from_template;
22pub use show::{detail_form, render_detail, render_detail_reply, show};
23pub use split_tags::{check_split_tags, link_split_tags};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub 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)]
35pub 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]
43pub fn submit_call(form: &Form, values: &FormValues) -> String {
44    format!(
45        "(submit-form {} {})",
46        escape_str(form.name),
47        escape_str(&write_payload(form, values))
48    )
49}
50
51pub(crate) async fn eval_text(session: &mut Session, call: &str) -> Result<String, CommandError> {
52    match eval_form(session, call, RenderMode::Scalar).await? {
53        Rendered::Lines(lines) => lines
54            .into_iter()
55            .next()
56            .ok_or_else(|| CommandError::Command("empty reply".to_string())),
57        _ => Err(CommandError::Command("unexpected reply".to_string())),
58    }
59}
60
61/// The reply value of evaluating `call`, without rendering it.
62pub(crate) async fn eval_value(session: &mut Session, call: &str) -> Result<Value, CommandError> {
63    let frame = format!("(:id {} :form {call})", next_id());
64    let WireValue::Value(value) =
65        parse_wire(&session.handle_form(&frame).await).map_err(render_error_to_command)?;
66    Ok(value)
67}
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.
75pub async fn create(session: &mut Session, values: &FormValues) -> Result<String, CommandError> {
76    let linked = link_split_tags(values)?;
77    let mapped = map_references(session, &TRANSACTION_CREATE, &linked).await?;
78    eval_text(session, &submit_call(&TRANSACTION_CREATE, &mapped)).await
79}
80
81/// # Errors
82/// [`CommandError::FormInvalid`] for rejected filters, or the server error.
83pub async fn query(session: &mut Session, values: &FormValues) -> Result<Page, CommandError> {
84    let mapped = map_references(session, &TRANSACTION_QUERY, values).await?;
85    parse_page(&eval_value(session, &submit_call(&TRANSACTION_QUERY, &mapped)).await?)
86}
87
88/// # Errors
89/// The server error, or a command error when nothing was deleted.
90pub async fn delete(session: &mut Session, id: &str) -> Result<(), CommandError> {
91    let form = build_delete_transaction_form(id);
92    match eval_form(session, &form, RenderMode::BoolSuccess).await? {
93        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}
99
100/// # Errors
101/// [`CommandError::Command`] when `reply` is not a `transaction-query` reply.
102pub fn parse_page(reply: &Value) -> Result<Page, CommandError> {
103    let malformed = || {
104        CommandError::Command(format!(
105            "malformed transaction page: {}",
106            nomiscript::format_value(reply)
107        ))
108    };
109    let rows = plist_field_raw(reply, ":rows").ok_or_else(malformed)?;
110    let rows = match rows {
111        Value::Nil => Vec::new(),
112        other => nomiscript::list_to_vec(&other).ok_or_else(malformed)?,
113    };
114    Ok(Page {
115        rows: rows
116            .iter()
117            .map(row_of)
118            .collect::<Option<_>>()
119            .ok_or_else(malformed)?,
120        has_more: matches!(plist_field_raw(reply, ":has-more"), Some(Value::T)),
121        total: match plist_field_raw(reply, ":total") {
122            Some(Value::Number(n)) => u64::try_from(n.value().to_integer()).ok(),
123            _ => None,
124        },
125    })
126}
127
128fn row_of(row: &Value) -> Option<TransactionRow> {
129    Some(TransactionRow {
130        id: plist_field(row, ":id")?,
131        date: plist_field(row, ":date-text")?,
132        note: plist_field(row, ":note")?,
133        amount: plist_field(row, ":amount")?,
134    })
135}
136
137/// One line per row.
138#[must_use]
139pub fn render_page(page: &Page) -> Vec<String> {
140    page.rows
141        .iter()
142        .map(|row| {
143            let note = note_line(&row.note);
144            format!("{}  {note}  {}  {}", row.date, row.amount, row.id)
145        })
146        .collect()
147}
148
149/// The stderr footer of a listing that starts at row `offset`; `None` when
150/// there is nothing to say.
151#[must_use]
152pub fn paging_note(page: &Page, offset: u64) -> Option<String> {
153    let more = page.has_more.then_some("more… (raise --offset)");
154    let range = page.total.filter(|_| !page.rows.is_empty()).map(|total| {
155        let first = offset.saturating_add(1);
156        let last = offset.saturating_add(page.rows.len() as u64);
157        format!("rows {first}–{last} of {total}")
158    });
159    match (range, more) {
160        (Some(range), Some(more)) => Some(format!("{range}; {more}")),
161        (range, more) => range.or_else(|| more.map(str::to_string)),
162    }
163}
164
165/// The first line of `note`, ending in an ellipsis when more lines follow.
166pub(crate) fn note_line(note: &str) -> String {
167    match note.split_once('\n') {
168        Some((first, _)) => format!("{first} …"),
169        None => note.to_string(),
170    }
171}
172
173#[cfg(test)]
174pub(crate) mod tests;