1
//! The load and submit steps shared by the edit pages over a stored entity.
2

            
3
use std::collections::BTreeMap;
4

            
5
use askama::Template;
6
use axum::response::{IntoResponse, Response};
7
use forms::{FieldError, Form, FormValues};
8
use rpc::forms::{Failure, FormAction, count_result, load_noticed};
9
use uuid::Uuid;
10

            
11
use super::attempt::{Attempt, attempt};
12
use super::{failure_error, references};
13
use crate::form_invalid::form_invalid;
14
use crate::form_render::{References, render_form_reloading};
15
use crate::response::WebError;
16

            
17
/// A submit's answer: the stored entity with its notice, or the response
18
/// that replaces the form.
19
pub enum Edited {
20
    Saved { id: Uuid, notice: Option<String> },
21
    Invalid(Response),
22
}
23

            
24
/// An edit form and the page that serves it.
25
pub struct Edit {
26
    pub form: &'static Form,
27
    /// The capitalised name of the edited entity, as the error pages say it.
28
    pub noun: &'static str,
29
    pub action: &'static str,
30
    /// The page that loads the entity; `{id}` is the entity's id.
31
    pub page: &'static str,
32
    /// What to do about a stored entity the form refuses, if anything works.
33
    pub remedy: &'static str,
34
}
35

            
36
/// A load's answer: the rendered form, or why the entity cannot be a form.
37
pub enum Loaded {
38
    Form {
39
        form: String,
40
        notice: Option<String>,
41
    },
42
    Refused(String),
43
}
44

            
45
#[derive(Template)]
46
#[template(path = "forms/revision.html")]
47
struct FreshRevision<'a> {
48
    form: &'a str,
49
    revision: &'a str,
50
}
51

            
52
impl Edit {
53
58
    fn render(
54
58
        &self,
55
58
        values: &FormValues,
56
58
        errors: &[FieldError],
57
58
        references: &References,
58
58
    ) -> Result<String, WebError> {
59
58
        let id = values.text("id").unwrap_or_default().trim();
60
58
        let reload = self.page.replace("{id}", id);
61
58
        render_form_reloading(self.form, values, errors, self.action, references, &reload)
62
            .map_err(|e| WebError::internal("Edit form render failed", e))
63
58
    }
64

            
65
11
    fn lowercase_noun(&self) -> String {
66
11
        self.noun.to_lowercase()
67
11
    }
68

            
69
6
    fn refusal(&self, reason: &str) -> String {
70
6
        let remedy = match self.remedy.is_empty() {
71
5
            true => String::new(),
72
1
            false => format!("; {}", self.remedy),
73
        };
74
6
        format!(
75
6
            "This {} cannot be edited as a form: {reason}{remedy}",
76
6
            self.lowercase_noun()
77
        )
78
6
    }
79

            
80
    /// `from_pairs` reads every posted line break as LF, so a loaded CR would be lost.
81
48
    fn browser_safe(&self, values: FormValues) -> Result<FormValues, String> {
82
48
        match values
83
48
            .to_pairs(self.form)
84
48
            .iter()
85
576
            .any(|(_, value)| value.contains('\r'))
86
        {
87
4
            true => Err(format!(
88
4
                "This {} holds a carriage return in a field or a tag description, \
89
4
                 which a browser cannot keep; edit it in the CLI or Emacs",
90
4
                self.lowercase_noun()
91
4
            )),
92
44
            false => Ok(values),
93
        }
94
48
    }
95

            
96
    /// The form loaded for `id` and rendered for posting, or the refusal.
97
67
    pub async fn load(&self, user_id: Uuid, id: &str) -> Result<Loaded, WebError> {
98
67
        let loaded = count_result(
99
67
            self.form.name,
100
67
            FormAction::Load,
101
67
            load_noticed(user_id, self.form, id).await,
102
        );
103
67
        let (values, notice) = match loaded {
104
48
            Ok(loaded) => loaded,
105
6
            Err(Failure::Refused(reason)) => return Ok(Loaded::Refused(self.refusal(&reason))),
106
13
            Err(failure) => return Err(failure_error("Form load failed", failure)),
107
        };
108
48
        let values = match self.browser_safe(values) {
109
44
            Ok(values) => values,
110
4
            Err(message) => return Ok(Loaded::Refused(message)),
111
        };
112
44
        let references = references(self.form, user_id, BTreeMap::new()).await?;
113
44
        let form = self.render(&values, &[], &references)?;
114
44
        Ok(Loaded::Form { form, notice })
115
67
    }
116

            
117
    /// [`Edit::load`] for a page of its own: a refusal is its 422 page.
118
56
    pub async fn loaded_noticed(
119
56
        &self,
120
56
        user_id: Uuid,
121
56
        id: &str,
122
56
    ) -> Result<(String, Option<String>), WebError> {
123
56
        match self.load(user_id, id).await? {
124
34
            Loaded::Form { form, notice } => Ok((form, notice)),
125
9
            Loaded::Refused(message) => Err(WebError::unprocessable(message)),
126
        }
127
56
    }
128

            
129
    /// [`Edit::loaded_noticed`] without the notice.
130
48
    pub async fn loaded_form(&self, user_id: Uuid, id: &str) -> Result<String, WebError> {
131
48
        Ok(self.loaded_noticed(user_id, id).await?.0)
132
48
    }
133

            
134
    /// The saved `message` for the result box, with the entity's fresh
135
    /// revision swapped into the form so the next save is not stale.
136
19
    pub async fn saved_response(
137
19
        &self,
138
19
        user_id: Uuid,
139
19
        id: Uuid,
140
19
        message: String,
141
19
    ) -> Result<Response, WebError> {
142
19
        let stored = rpc::forms::load(user_id, self.form, &id.to_string()).await;
143
19
        let Some(revision) = stored
144
19
            .ok()
145
19
            .and_then(|v| v.text("revision").map(str::to_string))
146
        else {
147
            return super::message::reply(&message);
148
        };
149
19
        let form = format!("nf-{}", self.form.name);
150
19
        let swap = FreshRevision {
151
19
            form: &form,
152
19
            revision: &revision,
153
19
        }
154
19
        .render()
155
        .map_err(|e| WebError::internal("Revision render failed", e))?;
156
19
        Ok(format!("{}{swap}", super::message::escaped(&message)?).into_response())
157
19
    }
158

            
159
    /// The hidden `id` cannot be corrected on the page, so an error at it is
160
    /// the typed page of a bad or unknown entity, not a re-rendered form.
161
16
    fn id_error(&self, values: &FormValues, errors: &[FieldError]) -> Option<WebError> {
162
16
        errors.iter().find(|error| error.field == "id")?;
163
2
        let id = values.text("id").unwrap_or_default();
164
2
        Some(match Uuid::parse_str(id.trim()) {
165
1
            Ok(_) => WebError::not_found(format!("{} not found", self.noun)),
166
1
            Err(_) => WebError::bad_request(format!("Invalid {} ID format", self.lowercase_noun())),
167
        })
168
16
    }
169

            
170
    /// Submit the posted `pairs`; field errors come back as the 422 re-render.
171
42
    pub async fn submit(
172
42
        &self,
173
42
        user_id: Uuid,
174
42
        pairs: Vec<(String, String)>,
175
42
    ) -> Result<Edited, WebError> {
176
42
        match attempt(self.form, user_id, pairs).await? {
177
22
            Attempt::Saved { id, notice } => Ok(Edited::Saved { id, notice }),
178
            Attempt::Rejected(rejected) => {
179
16
                if let Some(error) = self.id_error(&rejected.values, &rejected.errors) {
180
2
                    return Err(error);
181
14
                }
182
14
                let html = self.render(&rejected.values, &rejected.errors, &rejected.references)?;
183
14
                Ok(Edited::Invalid(form_invalid(self.form, html)))
184
            }
185
        }
186
42
    }
187
}