Lines
100 %
Functions
95 %
Branches
//! `transaction-edit` submit: syntax, ownership, resolution and domain
//! stages, then the shared logical update path.
use forms::{FieldError, FormValues, Row, TRANSACTION_EDIT, address};
use uuid::Uuid;
use super::Failure;
use super::hidden::Hidden;
use super::transaction_rows::{error_at, joined, lower_rows, post_date};
use super::transaction_split_tags::split_tags;
use super::transaction_stored::is_owned;
use super::transaction_tags::required_tags;
use crate::lowering::{Header, update_lowered};
use crate::resolve::Directory;
const CTX: &str = "submit-form";
/// Validate `transaction-edit` values and replace the transaction's splits
/// and tags.
pub(super) async fn edit_transaction(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
let errors = values.check(&TRANSACTION_EDIT);
if !errors.is_empty() {
return Err(errors.into());
}
let rows = values.rows("splits").unwrap_or_default();
let tags = joined(required_tags(values), split_tags(values, rows, true));
let (hidden, (tags, row_tags)) = joined(parse_hidden(rows), tags)?;
let post_date = post_date(values)?;
let transaction_id = owned_transaction(user_id, values.text("id").unwrap_or_default()).await?;
let directory = Directory::load(CTX, user_id).await?;
let lowered = lower_rows(&directory, rows, &hidden, &row_tags)?;
let header = Header {
note: values.text("note").map(blank_to_empty),
post_date: Some(post_date),
tags: Some(tags),
};
let revision = values.text("revision").map(str::trim);
update_lowered(CTX, user_id, transaction_id, header, lowered, revision).await
/// A whitespace-only note clears like an empty one.
fn blank_to_empty(note: &str) -> String {
match note.trim().is_empty() {
true => String::new(),
false => note.to_string(),
/// Parse every row's hidden data, collecting the errors of all of them.
fn parse_hidden(rows: &[Row]) -> Result<Vec<Option<Hidden>>, Vec<FieldError>> {
let mut hidden = Vec::with_capacity(rows.len());
let mut errors = Vec::new();
for (index, row) in rows.iter().enumerate() {
match row
.get("hidden")
.map(|text| text.trim())
.filter(|text| !text.is_empty())
{
None => hidden.push(None),
Some(text) => match Hidden::parse(text) {
Ok(parsed) => hidden.push(Some(parsed)),
Err(message) => errors.push(error_at(address::row("splits", index), message)),
},
match errors.is_empty() {
true => Ok(hidden),
false => Err(errors),
/// The id of a transaction that is the user's, else a field error at `id`.
/// Staleness is checked first by the update itself, under the transaction's
/// row lock, then the same refusals as at load.
async fn owned_transaction(user_id: Uuid, text: &str) -> Result<Uuid, Failure> {
let unknown = || error_at("id".to_string(), "unknown transaction");
let id = Uuid::parse_str(text.trim()).map_err(|_| unknown())?;
match is_owned(user_id, id).await? {
true => Ok(id),
false => Err(unknown().into()),