Lines
96.85 %
Functions
85 %
Branches
100 %
//! Template commands over the template forms and `form-options "templates"`.
use forms::{FormValues, TEMPLATE_CREATE, TEMPLATE_EDIT, TEMPLATE_TEST, escape_str};
use nomiscript::{Value, list_to_vec};
use rpc::Session;
use crate::CommandError;
use crate::eval::{plist_field, plist_field_raw};
use crate::flat::{Reply, edit as edit_form, load_values, submit};
use crate::forms::{FormOption, parse_option_list};
use crate::transaction::{eval_text, eval_value, submit_call};
pub(crate) async fn options(
session: &mut Session,
source: &str,
) -> Result<Vec<FormOption>, CommandError> {
let call = format!("(form-options {})", escape_str(source));
Ok(parse_option_list(&eval_text(session, &call).await?))
}
/// One line per stored template: its id and name.
///
/// # Errors
/// The server error.
pub async fn list(session: &mut Session) -> Result<Vec<String>, CommandError> {
let templates = options(session, "templates").await?;
Ok(templates
.iter()
.map(|template| format!("{} {}", template.id, template.label))
.collect())
fn stored_id(reply: Reply) -> Result<String, CommandError> {
match reply {
Reply::Entity(id) => Ok(id),
other => Err(CommandError::Command(format!(
"unexpected template reply: {other:?}"
))),
fn values_of(name: Option<&str>, source: Option<&str>) -> FormValues {
let mut values = FormValues::default();
name.into_iter().for_each(|name| values.set("name", name));
source
.into_iter()
.for_each(|source| values.set("source", source));
values
/// Store a new template and return its id.
/// [`CommandError::FormInvalid`] for a source that does not compile, or the server error.
pub async fn create(
name: Option<&str>,
) -> Result<String, CommandError> {
let values = values_of(name, Some(source));
stored_id(submit(session, &TEMPLATE_CREATE, &values).await?.reply)
/// Replace the given fields of template `id`, keeping the rest as stored.
/// The server's refusal of the load, [`CommandError::FormInvalid`] for a
/// source that does not compile or a stale revision.
pub async fn edit(
id: &str,
source: Option<&str>,
let values = values_of(name, source);
stored_id(edit_form(session, &TEMPLATE_EDIT, id, &values).await?.reply)
/// The stored source of template `id`.
/// The server's refusal of the load.
pub async fn stored_source(session: &mut Session, id: &str) -> Result<String, CommandError> {
let loaded = load_values(session, &TEMPLATE_EDIT, id).await?;
Ok(loaded.text("source").unwrap_or_default().to_string())
/// The read-only printout of `source` rendered against the user's data.
/// [`CommandError::FormInvalid`] with the server's message at `source`
/// when it does not compile or render.
pub async fn test(session: &mut Session, source: &str) -> Result<Vec<String>, CommandError> {
let values = values_of(None, Some(source));
let draft = eval_value(session, &submit_call(&TEMPLATE_TEST, &values)).await?;
let accounts = options(session, "accounts").await?;
let commodities = options(session, "commodities").await?;
render_draft(&draft, &accounts, &commodities)
fn label_of(options: &[FormOption], id: &str) -> String {
options
.find(|option| option.id == id)
.map_or_else(|| id.to_string(), |option| option.label.clone())
fn items(value: Option<Value>) -> Vec<Value> {
value.as_ref().and_then(list_to_vec).unwrap_or_default()
fn tag_text(tag: &Value) -> Option<String> {
Some(format!(
"{}={}",
plist_field(tag, ":name")?,
plist_field(tag, ":value")?
))
fn tags_text(tags: Option<Value>) -> Vec<String> {
items(tags).iter().filter_map(tag_text).collect()
fn split_line(
split: &Value,
accounts: &[FormOption],
commodities: &[FormOption],
) -> Option<String> {
let account = label_of(accounts, &plist_field(split, ":account")?);
let commodity = label_of(commodities, &plist_field(split, ":commodity")?);
let amount = plist_field(split, ":amount")?;
let tags = tags_text(plist_field_raw(split, ":tags")).join(", ");
let line = format!("split: {account} {amount} {commodity}");
Some(match tags.is_empty() {
true => line,
false => format!("{line} [{tags}]"),
})
fn optional_line(label: &str, value: Option<Value>) -> Option<String> {
match value? {
Value::String(text) => Some(format!("{label}: {text}")),
_ => None,
fn prefillable_line(draft: &Value) -> String {
match (
plist_field_raw(draft, ":prefillable"),
plist_field_raw(draft, ":reason"),
) {
(Some(Value::T), _) => "prefillable: yes".to_string(),
(_, Some(Value::String(reason))) => format!("prefillable: no: {reason}"),
_ => "prefillable: no".to_string(),
/// The lines of a `template-test` draft, accounts and commodities by label.
/// [`CommandError::Command`] when `draft` is not a draft plist.
pub fn render_draft(
draft: &Value,
) -> Result<Vec<String>, CommandError> {
let malformed = || {
CommandError::Command(format!(
"malformed template draft: {}",
nomiscript::format_value(draft)
};
let splits = items(plist_field_raw(draft, ":splits"))
.map(|split| split_line(split, accounts, commodities))
.collect::<Option<Vec<_>>>()
.ok_or_else(malformed)?;
let tags = tags_text(plist_field_raw(draft, ":tags"));
let mut lines = Vec::new();
lines.extend(optional_line("note", plist_field_raw(draft, ":note")));
lines.extend(optional_line("date", plist_field_raw(draft, ":date")));
lines.extend(splits);
if !tags.is_empty() {
lines.push(format!("tags: {}", tags.join(", ")));
lines.push(prefillable_line(draft));
Ok(lines)
#[cfg(test)]
mod tests;