Lines
97.03 %
Functions
27.38 %
Branches
100 %
//! The create page over the shared forms: `TRANSACTION_CREATE` rendered by
//! `form_render` and submitted through `rpc::forms::submit`.
use std::collections::BTreeMap;
use askama::Template;
use axum::{
Extension, Form,
extract::Query,
response::{IntoResponse, Response},
};
use forms::{FieldError, FormValues, Row, Source, TRANSACTION_CREATE};
use rpc::forms::{Failure, FormAction, FormOption, count_result};
use serde::Deserialize;
use uuid::Uuid;
use crate::form_invalid::form_invalid;
use crate::form_render::{References, render_form};
use crate::pages::{
HtmlTemplate,
forms::{failure_error, message, references, request::Request},
use crate::{jwt_auth::JWTAuthMiddleware, response::WebError};
pub const SUBMIT_PATH: &str = "/api/transaction/new/submit";
#[derive(Deserialize)]
pub struct NewParams {
template: Option<String>,
from_account: Option<String>,
}
#[derive(Template)]
#[template(path = "pages/transaction/new.html")]
struct NewPage {
form: String,
/// The message of a successful create, shown in the form's result box.
#[must_use]
pub fn created_message(id: Uuid) -> String {
format!("{}: {id}", t!("New transaction created with ID"))
fn render(
values: &FormValues,
errors: &[FieldError],
references: &References,
) -> Result<String, WebError> {
render_form(&TRANSACTION_CREATE, values, errors, SUBMIT_PATH, references)
.map_err(|e| WebError::internal("Create form render failed", e))
fn template_error(failure: Failure) -> WebError {
match failure {
Failure::Refused(reason) => {
WebError::unprocessable(format!("The template cannot be shown as a form: {reason}"))
other => failure_error("Template load failed", other),
/// The plain create page: one empty split row.
pub fn blank_values() -> FormValues {
first_row(Row::new())
fn first_row(row: Row) -> FormValues {
let mut values = FormValues::default();
values.push_row("splits", row);
values
/// The values of a create page and the cells a fill wrote into them.
struct Seed {
values: FormValues,
filled: BTreeMap<String, bool>,
impl From<FormValues> for Seed {
fn from(values: FormValues) -> Self {
Self {
values,
filled: BTreeMap::new(),
/// The first row of a pick of `option`: its only commodity fills the
/// from-commodity, which fills the to-commodity in turn, each marked filled.
fn picked_row(option: &FormOption) -> (Row, BTreeMap<String, bool>) {
let mut row = Row::from([("from".to_string(), option.id.to_string())]);
let mut filled = BTreeMap::new();
for cell in ["from-commodity", "to-commodity"] {
if let Some(commodity) = option.commodity {
row.insert(cell.to_string(), commodity.to_string());
filled.insert(format!("splits.0.{cell}"), false);
(row, filled)
/// The first row starts as a pick of the account `id` when it is one of the
/// user's own; anything else seeds the blank page.
async fn from_account(user_id: Uuid, id: Option<&str>) -> Result<Seed, WebError> {
let Some(wanted) = id.and_then(|id| Uuid::parse_str(id.trim()).ok()) else {
return Ok(blank_values().into());
let options = rpc::forms::options(user_id, Source::Accounts)
.await
.map_err(|f| failure_error("Account options failed", f))?;
Ok(match options.iter().find(|option| option.id == wanted) {
Some(option) => {
let (row, filled) = picked_row(option);
Seed {
values: first_row(row),
filled,
None => blank_values().into(),
})
/// A template wins over `from_account`; a create without a date starts now.
async fn seed(user_id: Uuid, params: NewParams) -> Result<Seed, WebError> {
let mut seed = match params {
NewParams {
template: Some(template),
..
} => count_result(
TRANSACTION_CREATE.name,
FormAction::Load,
rpc::forms::load(user_id, &TRANSACTION_CREATE, &template).await,
)
.map(Seed::from)
.map_err(template_error)?,
from_account: id, ..
} => from_account(user_id, id.as_deref()).await?,
if seed.values.text("date").is_none_or(str::is_empty) {
seed.values.set("date", &forms::now_instant());
Ok(seed)
pub async fn transaction_new_page(
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
Query(params): Query<NewParams>,
) -> Result<impl IntoResponse, WebError> {
let Seed { values, filled } = seed(jwt_auth.user.id, params).await?;
let mut references = references(&TRANSACTION_CREATE, jwt_auth.user.id, BTreeMap::new()).await?;
references.filled = filled;
let form = render(&values, &[], &references)?;
Ok(HtmlTemplate(NewPage { form }))
pub async fn transaction_new_submit(
Form(pairs): Form<Vec<(String, String)>>,
) -> Result<Response, WebError> {
let request = Request::read(
&TRANSACTION_CREATE,
FormAction::Submit,
jwt_auth.user.id,
pairs,
.await?;
let submitted = request
.settle(async |values| {
rpc::forms::submit(jwt_auth.user.id, &TRANSACTION_CREATE, values).await
.await;
match submitted {
Ok(submitted) => message::reply(&created_message(submitted.id)),
Err(Failure::Invalid(errors)) => Ok(form_invalid(
render(&request.values, &errors, &request.references)?,
)),
Err(failure) => Err(failure_error("Transaction create failed", failure)),