1
//! The create pages over a shared mutation form.
2

            
3
use std::collections::BTreeMap;
4

            
5
use axum::response::Response;
6
use forms::{FieldError, Form, FormValues};
7
use uuid::Uuid;
8

            
9
use super::attempt::{Attempt, attempt};
10
use super::references;
11
use crate::form_invalid::form_invalid;
12
use crate::form_render::{References, render_form};
13
use crate::response::WebError;
14

            
15
/// A create form and the path it posts to.
16
pub struct Create {
17
    pub form: &'static Form,
18
    pub action: &'static str,
19
}
20

            
21
/// A submit's answer: the stored entity with its notice, or the response
22
/// that replaces the form.
23
pub enum Created {
24
    Saved { id: Uuid, notice: Option<String> },
25
    Invalid(Response),
26
}
27

            
28
impl Create {
29
18
    fn render(
30
18
        &self,
31
18
        values: &FormValues,
32
18
        errors: &[FieldError],
33
18
        references: &References,
34
18
    ) -> Result<String, WebError> {
35
18
        render_form(self.form, values, errors, self.action, references)
36
            .map_err(|e| WebError::internal("Create form render failed", e))
37
18
    }
38

            
39
    /// The empty form.
40
10
    pub async fn blank(&self, user_id: Uuid) -> Result<String, WebError> {
41
10
        let references = references(self.form, user_id, BTreeMap::new()).await?;
42
10
        self.render(&FormValues::default(), &[], &references)
43
10
    }
44

            
45
24
    pub async fn submit(
46
24
        &self,
47
24
        user_id: Uuid,
48
24
        pairs: Vec<(String, String)>,
49
24
    ) -> Result<Created, WebError> {
50
24
        Ok(match attempt(self.form, user_id, pairs).await? {
51
14
            Attempt::Saved { id, notice } => Created::Saved { id, notice },
52
8
            Attempt::Rejected(rejected) => Created::Invalid(form_invalid(
53
8
                self.form,
54
8
                self.render(&rejected.values, &rejected.errors, &rejected.references)?,
55
            )),
56
        })
57
24
    }
58
}