Lines
88.37 %
Functions
77.27 %
Branches
100 %
//! `commodity-edit` submit: syntax, ownership, then the one `EditCommodity`
//! command under the commodity's locks.
use forms::{COMMODITY_EDIT, FormValues};
use server::command::commodity_edit::EditCommodity;
use server::command::commodity_tag::IDENTITY_TAGS;
use server::command::{CmdError, CmdResult, FinanceEntity};
use server::commodity_state::STALE_COMMODITY;
use server::user::User;
use uuid::Uuid;
use super::Failure;
use super::edit_tags::edited_tags;
use super::transaction_rows::{error_at, joined, single_line};
use crate::host_failure::cmd_failure;
const CTX: &str = "submit-form";
/// Validate `commodity-edit` values and apply the symbol, the name and the
/// tag replacement.
pub(super) async fn edit_commodity(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
let errors = values.check(&COMMODITY_EDIT);
if !errors.is_empty() {
return Err(errors.into());
}
let text = |key| values.text(key).unwrap_or_default().trim();
let lines: Vec<_> = IDENTITY_TAGS
.into_iter()
.filter_map(|key| single_line(key, text(key)).err())
.collect();
let named = if lines.is_empty() { Ok(()) } else { Err(lines) };
let (_, tags) = joined(named, edited_tags(values, &IDENTITY_TAGS, "a commodity"))?;
let commodity_id = owned_commodity(user_id, text("id")).await?;
let edited = EditCommodity::new()
.user_id(user_id)
.commodity_id(commodity_id)
.symbol(text("symbol").to_string())
.name(text("name").to_string())
.tags(tags)
.revision(text("revision").to_string())
.run()
.await;
match edited {
Ok(Some(CmdResult::Entity(FinanceEntity::Commodity(commodity)))) => Ok(commodity.id),
Ok(other) => Err(Failure::Internal(wasmtime::Error::msg(format!(
"{CTX}: unexpected edit result {other:?}"
)))),
Err(err) => Err(edit_failure(err)),
/// The stale revision is a field error; the rest as elsewhere.
fn edit_failure(err: CmdError) -> Failure {
match err {
CmdError::Args(message) if message == STALE_COMMODITY => {
error_at("revision".to_string(), message).into()
other => Failure::from_command(CTX, other),
/// The id of a commodity that is the user's, else a field error at `id`.
async fn owned_commodity(user_id: Uuid, text: &str) -> Result<Uuid, Failure> {
let unknown = || error_at("id".to_string(), "unknown commodity");
let id = Uuid::parse_str(text).map_err(|_| unknown())?;
let stored = User { id: user_id }
.commodity_snapshot(id)
.await
.map_err(|err| cmd_failure(CTX, err.into()))?;
stored.map(|_| id).ok_or_else(|| unknown().into())