Lines
98.46 %
Functions
52.27 %
Branches
100 %
//! The template test over the `template-test` query form: the draft a source
//! renders to, shown read-only beside the page it is tested from.
use std::collections::BTreeMap;
use askama::Template;
use axum::{
Extension, Form,
http::{HeaderName, HeaderValue, StatusCode},
response::{Html, IntoResponse, Response},
};
use forms::{FieldError, Source, TEMPLATE_TEST};
use rpc::forms::{Failure, FormAction, TemplateDraft};
use rpc::{DraftSplit, DraftTag};
use crate::form_render::References;
use crate::pages::{
HtmlTemplate,
forms::{failure_error, references, request::Request},
use crate::{jwt_auth::JWTAuthMiddleware, response::WebError};
pub const TEST_PATH: &str = "/api/template/test";
/// The element of the template pages the test answer is swapped into.
const RESULT_TARGET: &str = "#template-test-result";
struct SplitView {
account: String,
commodity: String,
amount: String,
tags: Vec<String>,
}
#[derive(Template)]
#[template(path = "components/template/draft.html")]
struct DraftView {
note: Option<String>,
date: Option<String>,
splits: Vec<SplitView>,
reason: Option<String>,
#[template(path = "components/template/test_invalid.html")]
struct InvalidView {
errors: Vec<FieldError>,
fn label(references: &References, source: Source, id: &str) -> String {
references
.label_of(source, id)
.unwrap_or_else(|| id.to_string())
fn split_view(split: &DraftSplit, references: &References) -> SplitView {
SplitView {
account: label(references, Source::Accounts, &split.account_id),
commodity: label(references, Source::Commodities, &split.commodity_id),
amount: amount::wire_rational(num_rational::Rational64::new_raw(
split.value_num,
split.value_denom,
)),
tags: split.tags.iter().map(tag_text).collect(),
fn tag_text(tag: &DraftTag) -> String {
format!("{}={}", tag.name, tag.value)
fn view(tested: TemplateDraft, references: &References) -> DraftView {
let draft = tested.draft;
DraftView {
splits: draft
.splits
.iter()
.map(|split| split_view(split, references))
.collect(),
tags: draft.tags.iter().map(tag_text).collect(),
note: draft.note,
date: draft.date,
reason: tested.refusal,
/// The 422 answer for a source that does not compile or render: it replaces
/// the test result, as a form re-render replaces its form.
fn invalid(errors: Vec<FieldError>) -> Result<Response, WebError> {
let html = InvalidView { errors }
.render()
.map_err(|e| WebError::internal("Template test render failed", e))?;
Ok((
StatusCode::UNPROCESSABLE_ENTITY,
[
(
HeaderName::from_static("hx-retarget"),
HeaderValue::from_static(RESULT_TARGET),
),
HeaderName::from_static("hx-reswap"),
HeaderValue::from_static("innerHTML"),
],
Html(html),
)
.into_response())
pub async fn template_test(
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
Form(pairs): Form<Vec<(String, String)>>,
) -> Result<Response, WebError> {
let user_id = jwt_auth.user.id;
let request = Request::read(&TEMPLATE_TEST, FormAction::Query, user_id, pairs).await?;
let answered = request
.settle(async |values| rpc::forms::test_template(user_id, values).await)
.await;
match answered {
Ok(tested) => {
let references = references(&TEMPLATE_TEST, user_id, BTreeMap::new()).await?;
Ok(HtmlTemplate(view(tested, &references)).into_response())
Err(Failure::Invalid(errors)) => invalid(errors),
Err(failure) => Err(failure_error("Template test failed", failure)),
#[cfg(test)]
#[path = "draft_tests.rs"]
mod tests;