Lanna Desk is the legal side of buildfor.life (B4L), and the client link, its agreements, the demo agreement and the messages now name Lanna Desk: "Lanna Desk looks after your visa ...", "Send to Lanna Desk", "Lanna Desk keeps the signed copy". B4L stays where it is the company itself: the employer in the Non-B pack and its BOI application. README and PLAN say the same. Checks: fmt, clippy, 109 unit and 57 integration tests.
1310 lines
40 KiB
Rust
1310 lines
40 KiB
Rust
//! The client's pages at `/c/<token>`: the one part of the app open
|
|
//! without a login. The client fills in their personal details, the
|
|
//! passport (with the photo reader), the address in Thailand and contact,
|
|
//! uploads scans, and presses Send. Each part is saved on its own, straight
|
|
//! into the person's record, and logged with the actor `link <id>`; staff
|
|
//! check it on the person's page. The pages show nothing about anyone else
|
|
//! and nothing of the record but what the client fills in here.
|
|
|
|
use std::sync::Arc;
|
|
|
|
use axum::Form;
|
|
use axum::extract::multipart::MultipartError;
|
|
use axum::extract::{Multipart, Path, Query, State};
|
|
use axum::http::StatusCode;
|
|
use axum::response::{IntoResponse, Redirect, Response};
|
|
use chrono::Utc;
|
|
use minijinja::{Value, context};
|
|
use serde::{Deserialize, Serialize};
|
|
use tracing::warn;
|
|
|
|
use super::documents::{self as webdocs, FILE_LIMIT, MAX_FILES, Refused};
|
|
use super::links::{CLIENT_KINDS, client_kinds};
|
|
use super::people::{read_zone, select_lists, zone_note};
|
|
use super::{AppState, Res, render, with_reader};
|
|
use crate::agreements::{self, Signing};
|
|
use crate::audit::{self, Action, Entity, Entry};
|
|
use crate::documents::{self, LINKS, Meta, Owner};
|
|
use crate::forms::{Errors, Fields, err, get};
|
|
use crate::links::{self, Link, State as LinkState};
|
|
use crate::mrz::Mrz;
|
|
use crate::people::{
|
|
self, AddressForm, AddressInput, PassportForm, PassportInput, Person, PersonForm, PersonInput,
|
|
};
|
|
use crate::session::{self, User};
|
|
use crate::{dates, embedded};
|
|
|
|
/// The link of a page, and the person it is for.
|
|
struct Client {
|
|
link: Link,
|
|
person: Person,
|
|
/// `/c/<token>`
|
|
base: String,
|
|
}
|
|
|
|
impl Client {
|
|
/// The one the link acts as, for the upload's checks and the audit log.
|
|
fn user(&self) -> User {
|
|
User {
|
|
login: self.link.actor(),
|
|
name: "Client".into(),
|
|
local: false,
|
|
csrf: self.link.csrf.clone(),
|
|
}
|
|
}
|
|
|
|
fn id(&self) -> i64 {
|
|
self.person.id
|
|
}
|
|
}
|
|
|
|
/// A page of the client's own frame.
|
|
fn client_page(
|
|
st: &AppState,
|
|
c: &Client,
|
|
name: &str,
|
|
title: &str,
|
|
status: StatusCode,
|
|
ctx: Value,
|
|
) -> Response {
|
|
let full = context! {
|
|
title,
|
|
v => embedded::STATIC_HASH,
|
|
csrf => &c.link.csrf,
|
|
base => &c.base,
|
|
until => links::day(c.link.expires_at),
|
|
first_name => &c.person.first_name,
|
|
..ctx
|
|
};
|
|
render(st, name, full, status)
|
|
}
|
|
|
|
/// A link that cannot be used (any more), and why.
|
|
fn closed_page(st: &AppState, link: Option<&Link>) -> Response {
|
|
let now = Utc::now();
|
|
let (status, title, text) = match link.map(|l| (l.state(now), l)) {
|
|
None => (
|
|
StatusCode::NOT_FOUND,
|
|
"This link does not work",
|
|
"There is no link at this address. Check that you opened the whole link, or ask Lanna Desk \
|
|
for a new one."
|
|
.to_string(),
|
|
),
|
|
Some((LinkState::Sent, l)) => (
|
|
StatusCode::GONE,
|
|
"Thank you",
|
|
format!(
|
|
"You sent your details on {}. Lanna Desk checks them and gets in touch. To change \
|
|
something now, ask Lanna Desk for a new link.",
|
|
l.sent_at.map(links::day).unwrap_or_default()
|
|
),
|
|
),
|
|
Some((LinkState::Expired, l)) => (
|
|
StatusCode::GONE,
|
|
"This link has expired",
|
|
format!(
|
|
"It worked until {}. Ask Lanna Desk for a new one; what you saved through it is kept.",
|
|
links::day(l.expires_at)
|
|
),
|
|
),
|
|
Some(_) => (
|
|
StatusCode::GONE,
|
|
"This link is closed",
|
|
"Lanna Desk closed it. Ask for a new one if you still need to send something; what you \
|
|
saved through it is kept."
|
|
.to_string(),
|
|
),
|
|
};
|
|
render(
|
|
st,
|
|
"client_closed.html",
|
|
context! { title, text, v => embedded::STATIC_HASH },
|
|
status,
|
|
)
|
|
}
|
|
|
|
/// The open link with this token and its person, or the page that says
|
|
/// why there is none.
|
|
async fn open(st: &AppState, token: &str) -> anyhow::Result<Result<Client, Response>> {
|
|
let Some(link) = links::by_token(&st.db, token).await? else {
|
|
return Ok(Err(closed_page(st, None)));
|
|
};
|
|
if !link.usable(Utc::now()) {
|
|
return Ok(Err(closed_page(st, Some(&link))));
|
|
}
|
|
let Some(person) = people::get_person(&st.db, link.person_id).await? else {
|
|
return Ok(Err(closed_page(st, None)));
|
|
};
|
|
links::touch(&st.db, link.id).await?;
|
|
Ok(Ok(Client {
|
|
link,
|
|
person,
|
|
base: format!("/c/{token}"),
|
|
}))
|
|
}
|
|
|
|
/// A form of the link must carry the link's own token.
|
|
fn token_ok(c: &Client, f: &Fields) -> bool {
|
|
session::same_token(&get(f, "csrf"), &c.link.csrf)
|
|
}
|
|
|
|
fn stale(st: &AppState) -> Response {
|
|
render(
|
|
st,
|
|
"client_closed.html",
|
|
context! {
|
|
title => "The page was too old",
|
|
text => "Go back, reload the page and send it again.",
|
|
v => embedded::STATIC_HASH,
|
|
},
|
|
StatusCode::FORBIDDEN,
|
|
)
|
|
}
|
|
|
|
fn log<'a>(
|
|
c: &Client,
|
|
actor: &'a str,
|
|
action: Action,
|
|
entity: Entity,
|
|
id: Option<i64>,
|
|
fields: &'a [String],
|
|
) -> Entry<'a> {
|
|
Entry {
|
|
actor,
|
|
action,
|
|
entity,
|
|
entity_id: id,
|
|
person_id: Some(c.id()),
|
|
company_id: None,
|
|
fields,
|
|
}
|
|
}
|
|
|
|
async fn viewed(st: &AppState, c: &Client, entity: Entity, id: i64) -> anyhow::Result<()> {
|
|
let actor = c.link.actor();
|
|
audit::record(&st.db, &log(c, &actor, Action::View, entity, Some(id), &[])).await
|
|
}
|
|
|
|
fn status_for(errors: &Errors) -> StatusCode {
|
|
if errors.is_empty() {
|
|
StatusCode::OK
|
|
} else {
|
|
StatusCode::UNPROCESSABLE_ENTITY
|
|
}
|
|
}
|
|
|
|
macro_rules! open_or_return {
|
|
($st:expr, $token:expr) => {
|
|
match open(&$st, &$token).await? {
|
|
Ok(c) => c,
|
|
Err(resp) => return Ok(resp),
|
|
}
|
|
};
|
|
}
|
|
|
|
/// The first active agreement the client has not signed in its current
|
|
/// version: the client reads and signs it before anything else.
|
|
async fn unsigned(st: &AppState, c: &Client) -> anyhow::Result<Option<i64>> {
|
|
Ok(agreements::for_person(&st.db, c.id())
|
|
.await?
|
|
.into_iter()
|
|
.find(|d| d.signed.is_none())
|
|
.map(|d| d.agreement.id))
|
|
}
|
|
|
|
/// Opens the link like `open_or_return!`, and sends a client who still has
|
|
/// an agreement to sign there first; what they posted is not taken.
|
|
macro_rules! signed_or_return {
|
|
($st:expr, $token:expr) => {{
|
|
let c = open_or_return!($st, $token);
|
|
if let Some(id) = unsigned(&$st, &c).await? {
|
|
return Ok(Redirect::to(&format!("{}/agree/{id}", c.base)).into_response());
|
|
}
|
|
c
|
|
}};
|
|
}
|
|
|
|
// ------------------------------------------------------------- overview
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct Part {
|
|
slug: String,
|
|
title: String,
|
|
what: String,
|
|
done: bool,
|
|
status: String,
|
|
/// Opens only once the agreements are signed.
|
|
locked: bool,
|
|
}
|
|
|
|
fn part(slug: &str, title: &str, what: &str, done: bool, status: String) -> Part {
|
|
Part {
|
|
slug: slug.to_string(),
|
|
title: title.to_string(),
|
|
what: what.to_string(),
|
|
done,
|
|
status,
|
|
locked: false,
|
|
}
|
|
}
|
|
|
|
async fn parts(st: &AppState, c: &Client) -> anyhow::Result<Vec<Part>> {
|
|
let p = &c.person;
|
|
let about = !p.surname.is_empty()
|
|
&& !p.first_name.is_empty()
|
|
&& !p.sex.is_empty()
|
|
&& p.date_of_birth.is_some()
|
|
&& !p.nationality.is_empty();
|
|
let passports = people::passports(&st.db, c.id()).await?;
|
|
let current = people::addresses(&st.db, c.id())
|
|
.await?
|
|
.into_iter()
|
|
.any(|a| a.moved_out_on.is_none());
|
|
let contact = !p.phone.is_empty() || !p.email.is_empty();
|
|
let actor = c.link.actor();
|
|
let docs = documents::list(&st.db, Owner::Person(c.id())).await?;
|
|
let mine = docs.iter().filter(|d| d.uploaded_by == actor).count();
|
|
let has = |k: &str| docs.iter().any(|d| d.kind == k);
|
|
let papers = has("passport-photo-page") && has("photo");
|
|
let state = |done: bool, yes: &str, no: &str| if done { yes } else { no }.to_string();
|
|
// the agreements first: they say what Lanna Desk does with the rest
|
|
let mut out: Vec<Part> = agreements::for_person(&st.db, c.id())
|
|
.await?
|
|
.into_iter()
|
|
.map(|d| {
|
|
let done = d.signed.is_some();
|
|
let what = if d.earlier.is_some() && !done {
|
|
"Its text has changed since you signed it: read it and sign again."
|
|
} else {
|
|
"Read it and sign it on the screen."
|
|
};
|
|
part(
|
|
&format!("agree/{}", d.agreement.id),
|
|
&d.agreement.title,
|
|
what,
|
|
done,
|
|
state(done, "Signed", "To sign"),
|
|
)
|
|
})
|
|
.collect();
|
|
let locked = out.iter().any(|p| !p.done);
|
|
let first = out.len();
|
|
out.extend([
|
|
part(
|
|
"about",
|
|
"About you",
|
|
"Your name as in the passport, date and place of birth, nationality, occupation.",
|
|
about,
|
|
state(about, "Filled in", "To fill in"),
|
|
),
|
|
part(
|
|
"passport",
|
|
"Passport",
|
|
"A photo of the passport's photo page fills it in, or type the two lines at its bottom.",
|
|
!passports.is_empty(),
|
|
state(!passports.is_empty(), "Recorded", "To fill in"),
|
|
),
|
|
part(
|
|
"address",
|
|
"Address in Thailand",
|
|
"Where you live now, and your landlord or house owner.",
|
|
current,
|
|
state(current, "Recorded", "To fill in"),
|
|
),
|
|
part(
|
|
"contact",
|
|
"Contact",
|
|
"Your phone number and email address.",
|
|
contact,
|
|
state(contact, "Filled in", "To fill in"),
|
|
),
|
|
part(
|
|
"documents",
|
|
"Documents",
|
|
"Scans or photos: the passport's photo page, a passport photo, the TDAC and others.",
|
|
papers,
|
|
match mine {
|
|
0 if papers => "Recorded".into(),
|
|
0 => "To upload".into(),
|
|
1 => "1 file uploaded".into(),
|
|
n => format!("{n} files uploaded"),
|
|
},
|
|
),
|
|
]);
|
|
if locked {
|
|
for p in &mut out[first..] {
|
|
p.locked = true;
|
|
p.status = "After signing".into();
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub struct SavedQuery {
|
|
saved: Option<String>,
|
|
}
|
|
|
|
pub async fn overview(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
Query(q): Query<SavedQuery>,
|
|
) -> Res {
|
|
let c = open_or_return!(st, token);
|
|
let parts = parts(&st, &c).await?;
|
|
let saved = q
|
|
.saved
|
|
.as_deref()
|
|
.and_then(|s| parts.iter().find(|p| p.slug == s))
|
|
.map(|p| p.title.clone());
|
|
let missing: Vec<&str> = parts
|
|
.iter()
|
|
.filter(|p| !p.done)
|
|
.map(|p| p.title.as_str())
|
|
.collect();
|
|
let locked = parts.iter().any(|p| p.locked);
|
|
let actor = c.link.actor();
|
|
audit::record(
|
|
&st.db,
|
|
&log(&c, &actor, Action::View, Entity::Link, Some(c.link.id), &[]),
|
|
)
|
|
.await?;
|
|
Ok(client_page(
|
|
&st,
|
|
&c,
|
|
"client.html",
|
|
"Your details",
|
|
StatusCode::OK,
|
|
context! { parts, saved, missing, locked },
|
|
))
|
|
}
|
|
|
|
// --------------------------------------------------------------- about
|
|
|
|
/// The fields of the About part; the rest of the record stays as it is.
|
|
const ABOUT: &[&str] = &[
|
|
"surname",
|
|
"first_name",
|
|
"middle_name",
|
|
"title",
|
|
"sex",
|
|
"date_of_birth",
|
|
"place_of_birth",
|
|
"nationality",
|
|
"occupation",
|
|
];
|
|
const CONTACT: &[&str] = &["phone", "email"];
|
|
|
|
/// The record's fields with the posted ones of a part over them.
|
|
fn person_form(p: &Person, f: &Fields, keys: &[&str]) -> PersonForm {
|
|
let posted = PersonForm::from_fields(f);
|
|
let mut pf = PersonForm::from_person(p);
|
|
for k in keys {
|
|
match *k {
|
|
"surname" => pf.surname = posted.surname.clone(),
|
|
"first_name" => pf.first_name = posted.first_name.clone(),
|
|
"middle_name" => pf.middle_name = posted.middle_name.clone(),
|
|
"title" => pf.title = posted.title.clone(),
|
|
"sex" => pf.sex = posted.sex.clone(),
|
|
"date_of_birth" => pf.date_of_birth = posted.date_of_birth.clone(),
|
|
"place_of_birth" => pf.place_of_birth = posted.place_of_birth.clone(),
|
|
"nationality" => pf.nationality = posted.nationality.clone(),
|
|
"occupation" => pf.occupation = posted.occupation.clone(),
|
|
"phone" => pf.phone = posted.phone.clone(),
|
|
"email" => pf.email = posted.email.clone(),
|
|
_ => {}
|
|
}
|
|
}
|
|
pf
|
|
}
|
|
|
|
/// Saves a person's fields changed by the client; true when it validated.
|
|
async fn save_person(
|
|
st: &AppState,
|
|
c: &Client,
|
|
pf: &PersonForm,
|
|
) -> anyhow::Result<Result<(), Errors>> {
|
|
let employer: Vec<i64> = c.person.employer_id.into_iter().collect();
|
|
let input = match pf.validate(dates::today(), &employer) {
|
|
Ok(i) => i,
|
|
Err(e) => return Ok(Err(e)),
|
|
};
|
|
let mut tx = st.db.begin().await?;
|
|
let Some(old) = people::get_person_in(&mut tx, c.id()).await? else {
|
|
return Ok(Ok(()));
|
|
};
|
|
let changed = input.changed_from(&PersonInput::from(&old));
|
|
if !changed.is_empty() {
|
|
people::update_person(&mut tx, c.id(), &input).await?;
|
|
let actor = c.link.actor();
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(
|
|
c,
|
|
&actor,
|
|
Action::Update,
|
|
Entity::Person,
|
|
Some(c.id()),
|
|
&changed,
|
|
),
|
|
)
|
|
.await?;
|
|
}
|
|
tx.commit().await?;
|
|
Ok(Ok(()))
|
|
}
|
|
|
|
fn person_part(st: &AppState, c: &Client, part: &str, f: &PersonForm, errors: &Errors) -> Response {
|
|
let (name, title) = match part {
|
|
"contact" => ("client_contact.html", "Contact"),
|
|
_ => ("client_about.html", "About you"),
|
|
};
|
|
client_page(
|
|
st,
|
|
c,
|
|
name,
|
|
title,
|
|
status_for(errors),
|
|
context! { f, errors, ..select_lists() },
|
|
)
|
|
}
|
|
|
|
async fn person_get(st: Arc<AppState>, token: String, part: &str) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
viewed(&st, &c, Entity::Person, c.id()).await?;
|
|
let f = PersonForm::from_person(&c.person);
|
|
Ok(person_part(&st, &c, part, &f, &Errors::new()))
|
|
}
|
|
|
|
async fn person_post(st: Arc<AppState>, token: String, part: &str, f: Fields) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
if !token_ok(&c, &f) {
|
|
return Ok(stale(&st));
|
|
}
|
|
let keys = if part == "contact" { CONTACT } else { ABOUT };
|
|
let pf = person_form(&c.person, &f, keys);
|
|
match save_person(&st, &c, &pf).await? {
|
|
Ok(()) => Ok(Redirect::to(&format!("{}?saved={part}", c.base)).into_response()),
|
|
Err(errors) => Ok(person_part(&st, &c, part, &pf, &errors)),
|
|
}
|
|
}
|
|
|
|
pub async fn about(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
|
person_get(st, token, "about").await
|
|
}
|
|
|
|
pub async fn about_save(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
person_post(st, token, "about", f).await
|
|
}
|
|
|
|
pub async fn contact(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
|
person_get(st, token, "contact").await
|
|
}
|
|
|
|
pub async fn contact_save(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
person_post(st, token, "contact", f).await
|
|
}
|
|
|
|
// ------------------------------------------------------------ passport
|
|
|
|
fn passport_page(
|
|
st: &AppState,
|
|
c: &Client,
|
|
pf: &PassportForm,
|
|
errors: &Errors,
|
|
mrz_note: Option<String>,
|
|
) -> Response {
|
|
with_reader(client_page(
|
|
st,
|
|
c,
|
|
"client_passport.html",
|
|
"Passport",
|
|
status_for(errors),
|
|
context! { pf, errors, mrz_note, ..select_lists() },
|
|
))
|
|
}
|
|
|
|
/// The passport the page shows: the one this link added, else the current
|
|
/// one.
|
|
async fn shown_passport(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Passport>> {
|
|
let all = people::passports(&st.db, c.id()).await?;
|
|
let made = links::made(&st.db, c.link.id, "passport").await?;
|
|
Ok(match made.and_then(|id| all.iter().find(|p| p.id == id)) {
|
|
Some(p) => Some(p.clone()),
|
|
None => all.into_iter().next(),
|
|
})
|
|
}
|
|
|
|
pub async fn passport(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
let pf = match shown_passport(&st, &c).await? {
|
|
Some(p) => {
|
|
viewed(&st, &c, Entity::Passport, p.id).await?;
|
|
PassportForm::from_passport(&p)
|
|
}
|
|
None => PassportForm {
|
|
issuing_country: c.person.nationality.clone(),
|
|
..Default::default()
|
|
},
|
|
};
|
|
Ok(passport_page(&st, &c, &pf, &Errors::new(), None))
|
|
}
|
|
|
|
/// The zone fills in the personal details the record does not have yet.
|
|
async fn fill_person(st: &AppState, c: &Client, m: &Mrz) -> anyhow::Result<()> {
|
|
let mut pf = PersonForm::from_person(&c.person);
|
|
pf.take_mrz(m, false);
|
|
// a zone with odd fields leaves the record as it is
|
|
let _ = save_person(st, c, &pf).await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn passport_save(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
if !token_ok(&c, &f) {
|
|
return Ok(stale(&st));
|
|
}
|
|
let today = dates::today();
|
|
let mut pf = PassportForm::from_fields(&f);
|
|
let mut errors = Errors::new();
|
|
let zone = read_zone(&mut pf.mrz, today, &mut errors);
|
|
let photo = get(&f, "mrz_source") == "photo";
|
|
|
|
if get(&f, "action") == "read-mrz" {
|
|
let mut note = None;
|
|
match &zone {
|
|
Some(m) => {
|
|
pf.take_mrz(m, true);
|
|
note = zone_note(m, photo, &mut errors);
|
|
}
|
|
None if pf.mrz.is_empty() => err(
|
|
&mut errors,
|
|
"mrz",
|
|
"Type the two lines first, or take a photo.",
|
|
),
|
|
None => {}
|
|
}
|
|
return Ok(passport_page(&st, &c, &pf, &errors, note));
|
|
}
|
|
|
|
if let Some(m) = &zone {
|
|
pf.take_mrz(m, false);
|
|
}
|
|
let input = match pf.validate(zone.as_ref()) {
|
|
Ok(i) if errors.is_empty() => i,
|
|
Ok(_) => return Ok(passport_page(&st, &c, &pf, &errors, None)),
|
|
Err(e) => {
|
|
for (k, v) in e {
|
|
err(&mut errors, &k, v);
|
|
}
|
|
return Ok(passport_page(&st, &c, &pf, &errors, None));
|
|
}
|
|
};
|
|
// the same passport again, else the one this link added (a corrected
|
|
// number), else a new one
|
|
let all = people::passports(&st.db, c.id()).await?;
|
|
let made = links::made(&st.db, c.link.id, "passport").await?;
|
|
let target = all
|
|
.iter()
|
|
.find(|p| p.issuing_country == input.issuing_country && p.number == input.number)
|
|
.or_else(|| made.and_then(|id| all.iter().find(|p| p.id == id)))
|
|
.cloned();
|
|
let actor = c.link.actor();
|
|
let mut tx = st.db.begin().await?;
|
|
if people::passport_taken(&mut tx, &input, target.as_ref().map(|p| p.id)).await? {
|
|
err(
|
|
&mut errors,
|
|
"number",
|
|
"This passport cannot be saved here. If it is yours, tell Lanna Desk.",
|
|
);
|
|
return Ok(passport_page(&st, &c, &pf, &errors, None));
|
|
}
|
|
match target {
|
|
Some(old) => {
|
|
let changed = input.changed_from(&PassportInput::from(&old));
|
|
if !changed.is_empty() {
|
|
people::update_passport(&mut tx, old.id, &input).await?;
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(
|
|
&c,
|
|
&actor,
|
|
Action::Update,
|
|
Entity::Passport,
|
|
Some(old.id),
|
|
&changed,
|
|
),
|
|
)
|
|
.await?;
|
|
}
|
|
}
|
|
None => {
|
|
let id = people::create_passport(&mut tx, c.id(), &input).await?;
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(&c, &actor, Action::Create, Entity::Passport, Some(id), &[]),
|
|
)
|
|
.await?;
|
|
}
|
|
}
|
|
tx.commit().await?;
|
|
if let Some(m) = &zone {
|
|
fill_person(&st, &c, m).await?;
|
|
}
|
|
Ok(Redirect::to(&format!("{}?saved=passport", c.base)).into_response())
|
|
}
|
|
|
|
// ------------------------------------------------------------- address
|
|
|
|
fn address_page(st: &AppState, c: &Client, af: &AddressForm, errors: &Errors) -> Response {
|
|
client_page(
|
|
st,
|
|
c,
|
|
"client_address.html",
|
|
"Address in Thailand",
|
|
status_for(errors),
|
|
context! { af, errors, ..select_lists() },
|
|
)
|
|
}
|
|
|
|
/// The address the page shows and saves to: the one this link added, if
|
|
/// it is still there.
|
|
async fn made_address(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Address>> {
|
|
Ok(match links::made(&st.db, c.link.id, "address").await? {
|
|
Some(id) => people::address(&st.db, c.id(), id).await?,
|
|
None => None,
|
|
})
|
|
}
|
|
|
|
async fn current_address(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Address>> {
|
|
Ok(people::addresses(&st.db, c.id())
|
|
.await?
|
|
.into_iter()
|
|
.find(|a| a.moved_out_on.is_none()))
|
|
}
|
|
|
|
pub async fn address(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
let shown = match made_address(&st, &c).await? {
|
|
Some(a) => Some(a),
|
|
None => current_address(&st, &c).await?,
|
|
};
|
|
let af = match &shown {
|
|
Some(a) => {
|
|
viewed(&st, &c, Entity::Address, a.id).await?;
|
|
AddressForm::from_address(a)
|
|
}
|
|
None => AddressForm {
|
|
province: "Chiang Mai".into(),
|
|
..Default::default()
|
|
},
|
|
};
|
|
Ok(address_page(&st, &c, &af, &Errors::new()))
|
|
}
|
|
|
|
/// Saves the client's address: the one this link added is changed; an
|
|
/// address like the current one changes nothing; any other is added as a
|
|
/// new one, so the current address and its TM.30 receipt stay as they are
|
|
/// until staff check it.
|
|
pub async fn address_save(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
if !token_ok(&c, &f) {
|
|
return Ok(stale(&st));
|
|
}
|
|
let made = made_address(&st, &c).await?;
|
|
let current = current_address(&st, &c).await?;
|
|
let posted = AddressForm::from_fields(&f);
|
|
// the parts staff fill in come from the address saved to
|
|
let base = made
|
|
.as_ref()
|
|
.map(AddressForm::from_address)
|
|
.unwrap_or_default();
|
|
let af = AddressForm {
|
|
moved_out_on: base.moved_out_on,
|
|
tm30_reported_on: base.tm30_reported_on,
|
|
tm30_receipt_no: base.tm30_receipt_no,
|
|
..posted
|
|
};
|
|
let input = match af.validate(dates::today()) {
|
|
Ok(i) => i,
|
|
Err(errors) => return Ok(address_page(&st, &c, &af, &errors)),
|
|
};
|
|
let actor = c.link.actor();
|
|
let mut tx = st.db.begin().await?;
|
|
match (&made, ¤t) {
|
|
(Some(old), _) => {
|
|
let changed = input.changed_from(&AddressInput::from(old));
|
|
if !changed.is_empty() {
|
|
people::update_address(&mut tx, old.id, &input).await?;
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(
|
|
&c,
|
|
&actor,
|
|
Action::Update,
|
|
Entity::Address,
|
|
Some(old.id),
|
|
&changed,
|
|
),
|
|
)
|
|
.await?;
|
|
}
|
|
}
|
|
(None, Some(cur)) if same_place(&input, &AddressInput::from(cur)) => {}
|
|
_ => {
|
|
let id = people::create_address(&mut tx, c.id(), &input).await?;
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(&c, &actor, Action::Create, Entity::Address, Some(id), &[]),
|
|
)
|
|
.await?;
|
|
}
|
|
}
|
|
tx.commit().await?;
|
|
Ok(Redirect::to(&format!("{}?saved=address", c.base)).into_response())
|
|
}
|
|
|
|
/// The same address and house master, whatever staff recorded about TM.30.
|
|
fn same_place(a: &AddressInput, b: &AddressInput) -> bool {
|
|
let strip = |x: &AddressInput| AddressInput {
|
|
moved_out_on: None,
|
|
tm30_reported_on: None,
|
|
tm30_receipt_no: String::new(),
|
|
..x.clone()
|
|
};
|
|
strip(a) == strip(b)
|
|
}
|
|
|
|
// ----------------------------------------------------------- documents
|
|
|
|
#[derive(Debug, Default, Serialize)]
|
|
struct UploadValues {
|
|
kind: String,
|
|
note: String,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct Uploaded {
|
|
label: String,
|
|
file_name: String,
|
|
size: String,
|
|
at: String,
|
|
}
|
|
|
|
async fn documents_page(
|
|
st: &AppState,
|
|
c: &Client,
|
|
v: &UploadValues,
|
|
errors: &Errors,
|
|
status: StatusCode,
|
|
) -> anyhow::Result<Response> {
|
|
let actor = c.link.actor();
|
|
let owner = Owner::Person(c.id());
|
|
let uploaded: Vec<Uploaded> = documents::list(&st.db, owner)
|
|
.await?
|
|
.iter()
|
|
.filter(|d| d.uploaded_by == actor)
|
|
.map(|d| Uploaded {
|
|
label: documents::kind_label(owner, &d.kind),
|
|
file_name: d.file_name.clone(),
|
|
size: webdocs::size_label(d.size_bytes.into()),
|
|
at: dates::fmt_datetime(d.uploaded_at),
|
|
})
|
|
.collect();
|
|
Ok(client_page(
|
|
st,
|
|
c,
|
|
"client_documents.html",
|
|
"Documents",
|
|
status,
|
|
context! {
|
|
uploaded, v, errors,
|
|
kinds => client_kinds(),
|
|
files_on => st.files.is_some(),
|
|
file_limit => FILE_LIMIT,
|
|
file_limit_mb => FILE_LIMIT / (1024 * 1024),
|
|
max_files => MAX_FILES,
|
|
},
|
|
))
|
|
}
|
|
|
|
pub async fn documents_get(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
let actor = c.link.actor();
|
|
audit::record(
|
|
&st.db,
|
|
&log(&c, &actor, Action::View, Entity::Link, Some(c.link.id), &[]),
|
|
)
|
|
.await?;
|
|
Ok(documents_page(
|
|
&st,
|
|
&c,
|
|
&UploadValues::default(),
|
|
&Errors::new(),
|
|
StatusCode::OK,
|
|
)
|
|
.await?)
|
|
}
|
|
|
|
/// The record a client's document of this kind belongs to: the person's
|
|
/// newest one of that kind of record, if there is one.
|
|
async fn record_for(
|
|
st: &AppState,
|
|
person: i64,
|
|
kind: &str,
|
|
) -> anyhow::Result<Option<(&'static documents::Link, i64)>> {
|
|
let Some(slug) = documents::kind(Owner::Person(person), kind).and_then(|k| k.record) else {
|
|
return Ok(None);
|
|
};
|
|
let Some(link) = LINKS.iter().find(|l| l.slug == slug) else {
|
|
return Ok(None);
|
|
};
|
|
let order = if slug == "passports" {
|
|
"expires_on DESC, id DESC"
|
|
} else {
|
|
"id DESC"
|
|
};
|
|
let id: Option<i64> = sqlx::query_scalar(&format!(
|
|
"SELECT id FROM {} WHERE person_id = $1 ORDER BY {order} LIMIT 1",
|
|
link.table
|
|
))
|
|
.bind(person)
|
|
.fetch_optional(&st.db)
|
|
.await?;
|
|
Ok(id.map(|id| (link, id)))
|
|
}
|
|
|
|
fn upload_refused(st: &AppState, e: Option<&MultipartError>) -> Response {
|
|
let text = match e {
|
|
Some(e) if e.status() == StatusCode::PAYLOAD_TOO_LARGE => format!(
|
|
"Upload up to {MAX_FILES} files of up to {} MB each at once. Go back and send fewer \
|
|
files.",
|
|
FILE_LIMIT / (1024 * 1024)
|
|
),
|
|
Some(e) => {
|
|
warn!("a client's upload could not be read: {}", e.body_text());
|
|
"The files did not arrive whole. Go back and send them again.".to_string()
|
|
}
|
|
None => format!("Upload up to {MAX_FILES} files at once. Go back and send fewer files."),
|
|
};
|
|
render(
|
|
st,
|
|
"client_closed.html",
|
|
context! { title => "The upload did not work", text, v => embedded::STATIC_HASH },
|
|
StatusCode::BAD_REQUEST,
|
|
)
|
|
}
|
|
|
|
pub async fn documents_upload(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
mp: Multipart,
|
|
) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
let user = c.user();
|
|
let up = match webdocs::read_upload(&user, mp).await {
|
|
Ok(Ok(up)) => up,
|
|
Ok(Err(Refused::Token)) => return Ok(stale(&st)),
|
|
Ok(Err(Refused::TooMany)) => return Ok(upload_refused(&st, None)),
|
|
Err(e) => return Ok(upload_refused(&st, Some(&e))),
|
|
};
|
|
let v = UploadValues {
|
|
kind: up.values.kind.clone(),
|
|
note: up.values.note.clone(),
|
|
};
|
|
let owner = Owner::Person(c.id());
|
|
let mut errors = Errors::new();
|
|
let Some(store) = st.files.clone() else {
|
|
err(
|
|
&mut errors,
|
|
"file",
|
|
"Uploads are switched off on this server.",
|
|
);
|
|
return Ok(documents_page(&st, &c, &v, &errors, StatusCode::SERVICE_UNAVAILABLE).await?);
|
|
};
|
|
if !CLIENT_KINDS.contains(&v.kind.as_str()) {
|
|
err(&mut errors, "kind", "Choose what the files are.");
|
|
}
|
|
if v.note.chars().count() > 500 {
|
|
err(&mut errors, "note", "Keep the note under 500 characters.");
|
|
}
|
|
let checked = webdocs::check_files(&st, owner, up, &mut errors).await?;
|
|
if !errors.is_empty() {
|
|
return Ok(documents_page(&st, &c, &v, &errors, StatusCode::UNPROCESSABLE_ENTITY).await?);
|
|
}
|
|
let meta = Meta {
|
|
kind: v.kind.clone(),
|
|
link: record_for(&st, c.id(), &v.kind).await?,
|
|
dated_on: None,
|
|
note: v.note.clone(),
|
|
};
|
|
webdocs::save(&st, &user, &store, owner, &meta, checked).await?;
|
|
Ok(Redirect::to(&format!("{}/documents#uploaded", c.base)).into_response())
|
|
}
|
|
|
|
// ---------------------------------------------------------------- send
|
|
|
|
pub async fn send(
|
|
State(st): State<Arc<AppState>>,
|
|
Path(token): Path<String>,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
let c = signed_or_return!(st, token);
|
|
if !token_ok(&c, &f) {
|
|
return Ok(stale(&st));
|
|
}
|
|
let actor = c.link.actor();
|
|
let mut tx = st.db.begin().await?;
|
|
if links::close(&mut tx, c.link.id, "client", true).await? {
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(&c, &actor, Action::Send, Entity::Link, Some(c.link.id), &[]),
|
|
)
|
|
.await?;
|
|
}
|
|
tx.commit().await?;
|
|
let link = links::get(&st.db, c.id(), c.link.id).await?;
|
|
// the thanks: the page a sent link shows from now on
|
|
let mut resp = closed_page(&st, link.as_ref());
|
|
*resp.status_mut() = StatusCode::OK;
|
|
Ok(resp)
|
|
}
|
|
|
|
// ------------------------------------------------------------ agreements
|
|
|
|
/// The largest drawn signature taken, as a PNG.
|
|
const DRAWING_LIMIT: usize = 400 * 1024;
|
|
|
|
#[derive(Debug, Default, Serialize)]
|
|
struct SignForm {
|
|
name: String,
|
|
accept: bool,
|
|
}
|
|
|
|
/// The name as the client would sign it: given names, then the surname.
|
|
fn full_name(p: &Person) -> String {
|
|
[
|
|
p.first_name.as_str(),
|
|
p.middle_name.as_str(),
|
|
p.surname.as_str(),
|
|
]
|
|
.iter()
|
|
.filter(|s| !s.is_empty())
|
|
.copied()
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
}
|
|
|
|
async fn agreement_page(
|
|
st: &AppState,
|
|
c: &Client,
|
|
id: i64,
|
|
f: &SignForm,
|
|
errors: &Errors,
|
|
status: StatusCode,
|
|
) -> anyhow::Result<Option<Response>> {
|
|
let Some(due) = agreements::for_person(&st.db, c.id())
|
|
.await?
|
|
.into_iter()
|
|
.find(|d| d.agreement.id == id)
|
|
else {
|
|
return Ok(None);
|
|
};
|
|
let signed = due
|
|
.signed
|
|
.as_ref()
|
|
.map(|s| dates::fmt_datetime(s.signed_at));
|
|
Ok(Some(client_page(
|
|
st,
|
|
c,
|
|
"client_agree.html",
|
|
&due.agreement.title,
|
|
status,
|
|
context! {
|
|
title => &due.agreement.title,
|
|
agreement_id => id,
|
|
version => due.current.version,
|
|
version_id => due.current.id,
|
|
published => links::day(due.current.published_at),
|
|
blocks => agreements::blocks(&due.current.body),
|
|
again => due.earlier.is_some() && due.signed.is_none(),
|
|
signed, f, errors,
|
|
},
|
|
)))
|
|
}
|
|
|
|
pub async fn agreement(
|
|
State(st): State<Arc<AppState>>,
|
|
Path((token, id)): Path<(String, i64)>,
|
|
) -> Res {
|
|
let c = open_or_return!(st, token);
|
|
let f = SignForm {
|
|
name: full_name(&c.person),
|
|
accept: false,
|
|
};
|
|
match agreement_page(&st, &c, id, &f, &Errors::new(), StatusCode::OK).await? {
|
|
Some(resp) => {
|
|
let actor = c.link.actor();
|
|
audit::record(
|
|
&st.db,
|
|
&log(&c, &actor, Action::View, Entity::Agreement, Some(id), &[]),
|
|
)
|
|
.await?;
|
|
Ok(resp)
|
|
}
|
|
None => Ok(closed_page(&st, None)),
|
|
}
|
|
}
|
|
|
|
/// The drawn signature from the form: a PNG as a `data:` address, if any.
|
|
fn drawing(f: &Fields) -> Result<Option<Vec<u8>>, &'static str> {
|
|
use base64::Engine;
|
|
let raw = f.get("drawing").map(|s| s.trim()).unwrap_or_default();
|
|
if raw.is_empty() {
|
|
return Ok(None);
|
|
}
|
|
let Some(b64) = raw.strip_prefix("data:image/png;base64,") else {
|
|
return Err("The drawn signature did not arrive as a picture. Clear it and sign again.");
|
|
};
|
|
let bytes = base64::engine::general_purpose::STANDARD
|
|
.decode(b64)
|
|
.map_err(|_| "The drawn signature did not arrive whole. Clear it and sign again.")?;
|
|
if bytes.len() > DRAWING_LIMIT || crate::files::sniff(&bytes) != Some("image/png") {
|
|
return Err("The drawn signature did not arrive whole. Clear it and sign again.");
|
|
}
|
|
Ok(Some(bytes))
|
|
}
|
|
|
|
/// The client's address as the proxy in front of the app forwarded it.
|
|
fn client_ip(headers: &axum::http::HeaderMap) -> String {
|
|
headers
|
|
.get("x-forwarded-for")
|
|
.and_then(|v| v.to_str().ok())
|
|
.and_then(|v| v.split(',').next())
|
|
.map(|v| v.trim().chars().take(64).collect())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// Signs the current version: the signature, its PDF as the person's
|
|
/// document and both in the audit log, in one transaction.
|
|
pub async fn sign(
|
|
State(st): State<Arc<AppState>>,
|
|
Path((token, id)): Path<(String, i64)>,
|
|
headers: axum::http::HeaderMap,
|
|
Form(f): Form<Fields>,
|
|
) -> Res {
|
|
let c = open_or_return!(st, token);
|
|
if !token_ok(&c, &f) {
|
|
return Ok(stale(&st));
|
|
}
|
|
let Some(due) = agreements::for_person(&st.db, c.id())
|
|
.await?
|
|
.into_iter()
|
|
.find(|d| d.agreement.id == id)
|
|
else {
|
|
return Ok(closed_page(&st, None));
|
|
};
|
|
let back = format!("{}?saved=agree/{id}", c.base);
|
|
if due.signed.is_some() {
|
|
return Ok(Redirect::to(&back).into_response());
|
|
}
|
|
let form = SignForm {
|
|
name: get(&f, "name"),
|
|
accept: get(&f, "accept") == "yes",
|
|
};
|
|
let mut errors = Errors::new();
|
|
if get(&f, "version") != due.current.id.to_string() {
|
|
err(
|
|
&mut errors,
|
|
"accept",
|
|
"Lanna Desk changed the text while you read it. Read this version and sign again.",
|
|
);
|
|
}
|
|
if form.name.is_empty() {
|
|
err(
|
|
&mut errors,
|
|
"name",
|
|
"Type your full name as your signature.",
|
|
);
|
|
} else if form.name.chars().count() > 200 {
|
|
err(&mut errors, "name", "Type your name only.");
|
|
}
|
|
if !form.accept {
|
|
err(
|
|
&mut errors,
|
|
"accept",
|
|
"Tick the box to accept the agreement.",
|
|
);
|
|
}
|
|
let drawn = match drawing(&f) {
|
|
Ok(d) => d,
|
|
Err(msg) => {
|
|
err(&mut errors, "drawing", msg);
|
|
None
|
|
}
|
|
};
|
|
let Some(store) = st.files.clone() else {
|
|
err(
|
|
&mut errors,
|
|
"accept",
|
|
"Signing is switched off on this server: it keeps no documents.",
|
|
);
|
|
return Ok(
|
|
agreement_page(&st, &c, id, &form, &errors, StatusCode::SERVICE_UNAVAILABLE)
|
|
.await?
|
|
.unwrap_or_else(|| closed_page(&st, None)),
|
|
);
|
|
};
|
|
if !errors.is_empty() {
|
|
return Ok(agreement_page(
|
|
&st,
|
|
&c,
|
|
id,
|
|
&form,
|
|
&errors,
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
)
|
|
.await?
|
|
.unwrap_or_else(|| closed_page(&st, None)));
|
|
}
|
|
|
|
let ip = client_ip(&headers);
|
|
let user_agent: String = headers
|
|
.get(axum::http::header::USER_AGENT)
|
|
.and_then(|v| v.to_str().ok())
|
|
.unwrap_or_default()
|
|
.chars()
|
|
.take(300)
|
|
.collect();
|
|
let actor = c.link.actor();
|
|
let mut tx = st.db.begin().await?;
|
|
let Some(sig) = agreements::sign(
|
|
&mut tx,
|
|
&Signing {
|
|
person: c.id(),
|
|
version: due.current.id,
|
|
link: Some(c.link.id),
|
|
name: &form.name,
|
|
drawn: drawn.is_some(),
|
|
ip: &ip,
|
|
user_agent: &user_agent,
|
|
},
|
|
)
|
|
.await?
|
|
else {
|
|
// signed a moment ago, in another tab
|
|
return Ok(Redirect::to(&back).into_response());
|
|
};
|
|
|
|
// the signed copy
|
|
let passport = people::passports(&st.db, c.id()).await?.into_iter().next();
|
|
let mut record = c.person.display_name();
|
|
if let Some(d) = c.person.date_of_birth {
|
|
record.push_str(&format!(", born {}", dates::fmt_date(d)));
|
|
}
|
|
if let Some(p) = &passport {
|
|
record.push_str(&format!(", passport {} ({})", p.number, p.issuing_country));
|
|
}
|
|
let at = format!("{} (Chiang Mai time)", dates::fmt_datetime(sig.signed_at));
|
|
let through = format!("client link {} at {}", c.link.id, st.cfg.public_url);
|
|
let published = links::day(due.current.published_at);
|
|
let pdf = agreements::pdf::render(
|
|
&agreements::pdf::Signed {
|
|
title: &due.agreement.title,
|
|
version: due.current.version,
|
|
published: &published,
|
|
sha256: &due.current.sha256,
|
|
name: &form.name,
|
|
record: &record,
|
|
at: &at,
|
|
through: &through,
|
|
ip: &ip,
|
|
user_agent: &user_agent,
|
|
drawing: drawn.as_deref(),
|
|
},
|
|
&agreements::blocks(&due.current.body),
|
|
)?;
|
|
let sha = crate::files::sha256_hex(&pdf);
|
|
let meta = Meta {
|
|
kind: "agreement".into(),
|
|
link: None,
|
|
dated_on: Some(sig.signed_at.with_timezone(&dates::bangkok()).date_naive()),
|
|
note: format!("{}, version {}", due.agreement.title, due.current.version),
|
|
};
|
|
let file_name = format!(
|
|
"{} - {} v{}.pdf",
|
|
c.person.display_name(),
|
|
due.agreement.title,
|
|
due.current.version
|
|
);
|
|
let file = documents::NewFile {
|
|
name: &documents::clean_name(&file_name),
|
|
content_type: "application/pdf",
|
|
size: i32::try_from(pdf.len())?,
|
|
sha256: &sha,
|
|
};
|
|
let doc = documents::insert(&mut tx, Owner::Person(c.id()), &meta, &file, &actor).await?;
|
|
store.put(doc, pdf).await?;
|
|
let saved: anyhow::Result<()> = async {
|
|
agreements::set_document(&mut tx, sig.id, doc).await?;
|
|
let fields: Vec<String> = ["signed_name", "accepted"]
|
|
.iter()
|
|
.chain(drawn.is_some().then_some(&"drawing"))
|
|
.map(|s| s.to_string())
|
|
.collect();
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(
|
|
&c,
|
|
&actor,
|
|
Action::Create,
|
|
Entity::Signature,
|
|
Some(sig.id),
|
|
&fields,
|
|
),
|
|
)
|
|
.await?;
|
|
let doc_fields = meta.set_fields();
|
|
audit::record(
|
|
&mut *tx,
|
|
&log(
|
|
&c,
|
|
&actor,
|
|
Action::Create,
|
|
Entity::Document,
|
|
Some(doc),
|
|
&doc_fields,
|
|
),
|
|
)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
.await;
|
|
if let Err(e) = match saved {
|
|
Ok(()) => tx.commit().await.map_err(anyhow::Error::from),
|
|
Err(e) => Err(e),
|
|
} {
|
|
if let Err(r) = store.remove(doc).await {
|
|
tracing::error!("removing the file of the failed signature {doc}: {r:#}");
|
|
}
|
|
return Err(e.into());
|
|
}
|
|
Ok(Redirect::to(&back).into_response())
|
|
}
|