Phase 7: the client link
Staff make a link for a person (or "+ New client": a record with only the name they know, and its link); the client fills in their own record from their phone without a login, and presses Send. - Links (src/links.rs, migrations/0006): the table keeps the SHA-256 of the token only, as sessions do; the link is shown once, to copy, to email (mailto with the person's address) or as a QR code (qrcode crate, inline SVG). It is open 14 days, until Send, or until staff close it; a new link closes the earlier one. States open, opened, sent, closed, expired. - The client's pages at /c/<token> (src/web/client.rs, client_*.html in a frame of their own, phone first): About you, Passport (the photo reader; a zone fills in the personal details still empty), Address in Thailand, Contact, Documents, Send. Each part is saved on its own, straight into the record. Forms carry the link's own token plus the same-site check. A passport with the same number is changed; an address unlike the current one is added beside it, so the current one and its TM.30 receipt stay; a second save changes what the link added. Uploads (passport page, photo, visa, arrival stamp, TDAC, work permit, other) go through the same checks and encrypted store as staff uploads, tied to the person's newest record of their kind. - Audit: the client's views and changes carry the actor `link <id>`; actions send and close and entity link are new. The person's page shows the newest links, when they were opened and sent, and each record the client changed, with the fields, to check. - Demo data: Erika sent her link an hour ago (phone and email changed), Jane opened hers. - documents::read_upload returns why it refused, so the client's pages answer in their own words. Checks: fmt, clippy; 101 unit and 54 integration tests (tests/client.rs: the link shown once and kept as a hash, a new client, the whole client flow with the login on, forged, closed, expired and made-up links); layout check light/dark desk/phone on the client pages, the person page and the new client form: no problems; the camera reader on the client's passport page with a fake camera filled the form and Send closed the link.
This commit is contained in:
1 parent
a6ebdfc89c
commit
43ed75d81b
32 files changed
+2706
-40
No files matched your search
@@ -0,0 +1,917 @@
|
||||
//! 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::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 B4L \
|
||||
for a new one."
|
||||
.to_string(),
|
||||
),
|
||||
Some((LinkState::Sent, l)) => (
|
||||
StatusCode::GONE,
|
||||
"Thank you",
|
||||
format!(
|
||||
"You sent your details on {}. B4L checks them and gets in touch. To change \
|
||||
something now, ask B4L 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 B4L for a new one; what you saved through it is kept.",
|
||||
links::day(l.expires_at)
|
||||
),
|
||||
),
|
||||
Some(_) => (
|
||||
StatusCode::GONE,
|
||||
"This link is closed",
|
||||
"B4L closed it. Ask them 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),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- overview
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Part {
|
||||
slug: &'static str,
|
||||
title: &'static str,
|
||||
what: &'static str,
|
||||
done: bool,
|
||||
status: String,
|
||||
}
|
||||
|
||||
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();
|
||||
Ok(vec![
|
||||
Part {
|
||||
slug: "about",
|
||||
title: "About you",
|
||||
what: "Your name as in the passport, date and place of birth, nationality, occupation.",
|
||||
done: about,
|
||||
status: state(about, "Filled in", "To fill in"),
|
||||
},
|
||||
Part {
|
||||
slug: "passport",
|
||||
title: "Passport",
|
||||
what: "A photo of the passport's photo page fills it in, or type the two lines at its bottom.",
|
||||
done: !passports.is_empty(),
|
||||
status: state(!passports.is_empty(), "Recorded", "To fill in"),
|
||||
},
|
||||
Part {
|
||||
slug: "address",
|
||||
title: "Address in Thailand",
|
||||
what: "Where you live now, and your landlord or house owner.",
|
||||
done: current,
|
||||
status: state(current, "Recorded", "To fill in"),
|
||||
},
|
||||
Part {
|
||||
slug: "contact",
|
||||
title: "Contact",
|
||||
what: "Your phone number and email address.",
|
||||
done: contact,
|
||||
status: state(contact, "Filled in", "To fill in"),
|
||||
},
|
||||
Part {
|
||||
slug: "documents",
|
||||
title: "Documents",
|
||||
what: "Scans or photos: the passport's photo page, a passport photo, the TDAC and others.",
|
||||
done: papers,
|
||||
status: match mine {
|
||||
0 if papers => "Recorded".into(),
|
||||
0 => "To upload".into(),
|
||||
1 => "1 file uploaded".into(),
|
||||
n => format!("{n} files uploaded"),
|
||||
},
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
#[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);
|
||||
let missing: Vec<&str> = parts.iter().filter(|p| !p.done).map(|p| p.title).collect();
|
||||
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 },
|
||||
))
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- 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 = open_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 = open_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 = open_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 = open_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 B4L.",
|
||||
);
|
||||
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 = open_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 = open_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 = open_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 = open_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 = open_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)
|
||||
}
|
||||
+22
-13
@@ -446,8 +446,8 @@ fn broken_upload(st: &AppState, e: &MultipartError) -> Response {
|
||||
|
||||
/// An upload as it arrived, before any check.
|
||||
#[derive(Default)]
|
||||
struct Upload {
|
||||
values: Values,
|
||||
pub(crate) struct Upload {
|
||||
pub(crate) values: Values,
|
||||
files: Vec<(String, Vec<u8>)>,
|
||||
/// files over the limit, by name
|
||||
too_big: Vec<String>,
|
||||
@@ -474,13 +474,21 @@ async fn read_field(
|
||||
Ok((!over).then_some(out))
|
||||
}
|
||||
|
||||
/// Why an upload was refused before its files were checked.
|
||||
pub(crate) enum Refused {
|
||||
/// No form token, or not the session's (or the client link's).
|
||||
Token,
|
||||
/// More than `MAX_FILES` files.
|
||||
TooMany,
|
||||
}
|
||||
|
||||
/// The form token must come first (the page puts it there), so a forged
|
||||
/// form is refused before any file is read.
|
||||
async fn read_upload(
|
||||
st: &AppState,
|
||||
/// form is refused before any file is read. `user` is the session's, or
|
||||
/// the one a client link acts as (`web::client`).
|
||||
pub(crate) async fn read_upload(
|
||||
user: &User,
|
||||
mut mp: Multipart,
|
||||
) -> Result<Result<Upload, Response>, MultipartError> {
|
||||
) -> Result<Result<Upload, Refused>, MultipartError> {
|
||||
let token = match mp.next_field().await? {
|
||||
Some(mut f) if f.name() == Some("csrf") => read_field(&mut f, FIELD_LIMIT)
|
||||
.await?
|
||||
@@ -492,7 +500,7 @@ async fn read_upload(
|
||||
"refused an upload without a valid token from {}",
|
||||
user.login
|
||||
);
|
||||
return Ok(Err(super::expired(st)));
|
||||
return Ok(Err(Refused::Token));
|
||||
}
|
||||
let mut up = Upload::default();
|
||||
let mut count = 0;
|
||||
@@ -530,7 +538,7 @@ async fn read_upload(
|
||||
}
|
||||
}
|
||||
if count > MAX_FILES {
|
||||
return Ok(Err(too_large(st)));
|
||||
return Ok(Err(Refused::TooMany));
|
||||
}
|
||||
Ok(Ok(up))
|
||||
}
|
||||
@@ -587,7 +595,7 @@ async fn check_meta(st: &AppState, owner: Owner, v: &Values) -> anyhow::Result<(
|
||||
))
|
||||
}
|
||||
|
||||
struct Checked {
|
||||
pub(crate) struct Checked {
|
||||
name: String,
|
||||
bytes: Vec<u8>,
|
||||
content_type: &'static str,
|
||||
@@ -596,7 +604,7 @@ struct Checked {
|
||||
|
||||
/// The files, checked: a type the app takes (by the file's first bytes),
|
||||
/// not empty, not too large, not uploaded before for this person or company.
|
||||
async fn check_files(
|
||||
pub(crate) async fn check_files(
|
||||
st: &AppState,
|
||||
owner: Owner,
|
||||
up: Upload,
|
||||
@@ -651,7 +659,7 @@ async fn check_files(
|
||||
/// Saves the checked files as documents: the rows, the encrypted files and
|
||||
/// the audit entries in one transaction. Files written before a failure are
|
||||
/// removed again. Returns the first new id.
|
||||
async fn save(
|
||||
pub(crate) async fn save(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
store: &Store,
|
||||
@@ -728,9 +736,10 @@ pub async fn upload(st: Arc<AppState>, user: User, owner: Owner, mp: Multipart)
|
||||
None
|
||||
}
|
||||
};
|
||||
let up = match read_upload(&st, &user, mp).await {
|
||||
let up = match read_upload(&user, mp).await {
|
||||
Ok(Ok(up)) => up,
|
||||
Ok(Err(resp)) => return Ok(resp),
|
||||
Ok(Err(Refused::Token)) => return Ok(super::expired(&st)),
|
||||
Ok(Err(Refused::TooMany)) => return Ok(too_large(&st)),
|
||||
Err(e) => return Ok(broken_upload(&st, &e)),
|
||||
};
|
||||
let Some(store) = st.files.clone() else {
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! The client link on the staff's side: the card on a person's page, making
|
||||
//! a link (also with a new, nearly empty record: "+ New client"), the page
|
||||
//! that shows the link once, and closing a link.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use axum::{Extension, Form};
|
||||
use chrono::Utc;
|
||||
use minijinja::context;
|
||||
use qrcode::QrCode;
|
||||
use qrcode::render::svg;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::people::{PersonView, load_person};
|
||||
use super::{AppState, Res, not_found_page, page, percent_encode};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::forms::{Errors, Fields, err, get};
|
||||
use crate::links::{self, Link};
|
||||
use crate::people::{self, PersonInput};
|
||||
use crate::session::User;
|
||||
use crate::{dates, documents};
|
||||
|
||||
/// A link as the person's page shows it.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct LinkView {
|
||||
pub id: i64,
|
||||
pub state: &'static str,
|
||||
pub level: &'static str,
|
||||
pub usable: bool,
|
||||
pub made: String,
|
||||
pub by: String,
|
||||
pub until: String,
|
||||
pub opened: String,
|
||||
pub sent: String,
|
||||
pub closed: String,
|
||||
pub changes: Vec<ChangeView>,
|
||||
}
|
||||
|
||||
/// One record the client added or changed through a link.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ChangeView {
|
||||
pub label: String,
|
||||
pub href: String,
|
||||
pub fields: String,
|
||||
}
|
||||
|
||||
fn change_view(person: i64, c: &links::Change) -> ChangeView {
|
||||
let made = c.action == "create";
|
||||
let (label, href) = match (c.entity.as_str(), c.entity_id) {
|
||||
("person", _) => (
|
||||
"Personal details".to_string(),
|
||||
format!("/people/{person}#details"),
|
||||
),
|
||||
("passport", _) => (
|
||||
if made { "New passport" } else { "Passport" }.to_string(),
|
||||
format!("/people/{person}#passports"),
|
||||
),
|
||||
("address", _) => (
|
||||
if made { "New address" } else { "Address" }.to_string(),
|
||||
format!("/people/{person}#addresses"),
|
||||
),
|
||||
("document", Some(id)) => (
|
||||
"Document".to_string(),
|
||||
format!("/people/{person}/documents#doc-{id}"),
|
||||
),
|
||||
(other, _) => (other.to_string(), format!("/people/{person}/activity")),
|
||||
};
|
||||
// a new document's fields say only what was set; its kind is enough
|
||||
let fields = if c.entity == "document" {
|
||||
String::new()
|
||||
} else {
|
||||
c.fields.join(", ").replace('_', " ")
|
||||
};
|
||||
ChangeView {
|
||||
label,
|
||||
href,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
async fn link_view(st: &AppState, l: &Link) -> anyhow::Result<LinkView> {
|
||||
let now = Utc::now();
|
||||
let state = l.state(now);
|
||||
let changes = links::changes(&st.db, l.id)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|c| change_view(l.person_id, c))
|
||||
.collect();
|
||||
Ok(LinkView {
|
||||
id: l.id,
|
||||
state: state.label(),
|
||||
level: state.level(),
|
||||
usable: l.usable(now),
|
||||
made: dates::fmt_datetime(l.created_at),
|
||||
by: l.created_by.clone(),
|
||||
until: links::day(l.expires_at),
|
||||
opened: l.first_used_at.map(dates::fmt_datetime).unwrap_or_default(),
|
||||
sent: l.sent_at.map(dates::fmt_datetime).unwrap_or_default(),
|
||||
closed: match (l.sent_at, l.closed_at) {
|
||||
(None, Some(t)) => format!("{} by {}", dates::fmt_datetime(t), l.closed_by),
|
||||
_ => String::new(),
|
||||
},
|
||||
changes,
|
||||
})
|
||||
}
|
||||
|
||||
/// The person page's card: the newest links, each with what the client
|
||||
/// changed through it.
|
||||
pub async fn card(st: &AppState, person: i64) -> anyhow::Result<Vec<LinkView>> {
|
||||
let mut out = Vec::new();
|
||||
for l in links::for_person(&st.db, person).await?.iter().take(3) {
|
||||
out.push(link_view(st, l).await?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn log<'a>(user: &'a User, action: Action, link: i64, person: i64) -> Entry<'a> {
|
||||
Entry {
|
||||
actor: &user.login,
|
||||
action,
|
||||
entity: Entity::Link,
|
||||
entity_id: Some(link),
|
||||
person_id: Some(person),
|
||||
company_id: None,
|
||||
fields: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// The link as a QR code, an SVG for the page (no script, no style).
|
||||
fn qr_svg(url: &str) -> String {
|
||||
match QrCode::new(url.as_bytes()) {
|
||||
Ok(code) => {
|
||||
let svg = code
|
||||
.render::<svg::Color>()
|
||||
.min_dimensions(220, 220)
|
||||
.dark_color(svg::Color("#071323"))
|
||||
.light_color(svg::Color("#ffffff"))
|
||||
.build();
|
||||
// the page holds it inline: without the XML declaration
|
||||
match svg.find("<svg") {
|
||||
Some(i) => svg[i..].to_string(),
|
||||
None => svg,
|
||||
}
|
||||
}
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The page right after a link is made: the only time the link is shown.
|
||||
fn made_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
p: &PersonView,
|
||||
link: &Link,
|
||||
token: &str,
|
||||
email: &str,
|
||||
) -> Response {
|
||||
let url = format!("{}/c/{token}", st.cfg.public_url);
|
||||
let mail = if email.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
let body = format!(
|
||||
"Hello,\n\nplease fill in your details for your visa and stay in Thailand here:\n\n{url}\n\n\
|
||||
The link works until {}. Each part is saved on its own; press Send when you are done.\n",
|
||||
links::day(link.expires_at)
|
||||
);
|
||||
format!(
|
||||
"mailto:{email}?subject={}&body={}",
|
||||
percent_encode("Your details for B4L"),
|
||||
percent_encode(&body)
|
||||
)
|
||||
};
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"link_made.html",
|
||||
&format!("Link for {}", p.name),
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! {
|
||||
p, tab => "overview", url, qr => qr_svg(&url), mail,
|
||||
until => links::day(link.expires_at),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some((p, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
let (link, token) = links::create(&mut tx, id, &user.login).await?;
|
||||
audit::record(&mut *tx, &log(&user, Action::Create, link.id, id)).await?;
|
||||
tx.commit().await?;
|
||||
Ok(made_page(&st, &user, &view, &link, &token, &p.email))
|
||||
}
|
||||
|
||||
pub async fn close(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, lid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
if links::get(&st.db, id, lid).await?.is_none() {
|
||||
return Ok(not_found_page(&st));
|
||||
}
|
||||
let mut tx = st.db.begin().await?;
|
||||
if links::close(&mut tx, lid, &user.login, false).await? {
|
||||
audit::record(&mut *tx, &log(&user, Action::Close, lid, id)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}#client-link")).into_response())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ new client
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
struct NewClient {
|
||||
surname: String,
|
||||
first_name: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
fn new_client_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
f: &NewClient,
|
||||
errors: &Errors,
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"new_client.html",
|
||||
"New client",
|
||||
"people",
|
||||
status,
|
||||
context! { f, errors },
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn new_client_form(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
) -> Res {
|
||||
Ok(new_client_page(
|
||||
&st,
|
||||
&user,
|
||||
&NewClient::default(),
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
/// A new record with only the name staff know, and its link: the client
|
||||
/// fills in the rest.
|
||||
pub async fn new_client(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let nc = NewClient {
|
||||
surname: get(&f, "surname"),
|
||||
first_name: get(&f, "first_name"),
|
||||
email: get(&f, "email"),
|
||||
};
|
||||
let mut errors = Errors::new();
|
||||
if nc.surname.is_empty() && nc.first_name.is_empty() {
|
||||
err(
|
||||
&mut errors,
|
||||
"surname",
|
||||
"Enter a name to find the record by; the client corrects it.",
|
||||
);
|
||||
}
|
||||
if !nc.email.is_empty() && !people::looks_like_email(&nc.email) {
|
||||
err(
|
||||
&mut errors,
|
||||
"email",
|
||||
"This does not look like an email address.",
|
||||
);
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
return Ok(new_client_page(
|
||||
&st,
|
||||
&user,
|
||||
&nc,
|
||||
&errors,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
let input = PersonInput {
|
||||
surname: nc.surname.clone(),
|
||||
first_name: nc.first_name.clone(),
|
||||
middle_name: String::new(),
|
||||
title: String::new(),
|
||||
sex: String::new(),
|
||||
date_of_birth: None,
|
||||
place_of_birth: String::new(),
|
||||
nationality: String::new(),
|
||||
occupation: String::new(),
|
||||
employer: None,
|
||||
phone: String::new(),
|
||||
email: nc.email.clone(),
|
||||
notes: String::new(),
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
let id = people::create_person(&mut tx, &input).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&Entry {
|
||||
actor: &user.login,
|
||||
action: Action::Create,
|
||||
entity: Entity::Person,
|
||||
entity_id: Some(id),
|
||||
person_id: Some(id),
|
||||
company_id: None,
|
||||
fields: &[],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let (link, token) = links::create(&mut tx, id, &user.login).await?;
|
||||
audit::record(&mut *tx, &log(&user, Action::Create, link.id, id)).await?;
|
||||
tx.commit().await?;
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
Ok(made_page(&st, &user, &view, &link, &token, &nc.email))
|
||||
}
|
||||
|
||||
/// The kinds of document a client uploads, in the order they are asked for.
|
||||
pub const CLIENT_KINDS: &[&str] = &[
|
||||
"passport-photo-page",
|
||||
"photo",
|
||||
"visa",
|
||||
"arrival-stamp",
|
||||
"tdac",
|
||||
"work-permit",
|
||||
"other",
|
||||
];
|
||||
|
||||
/// The kinds for the client's selection, with the app's labels.
|
||||
pub fn client_kinds() -> Vec<(&'static str, String)> {
|
||||
CLIENT_KINDS
|
||||
.iter()
|
||||
.map(|k| (*k, documents::kind_label(documents::Owner::Person(0), k)))
|
||||
.collect()
|
||||
}
|
||||
+39
-2
@@ -2,9 +2,11 @@
|
||||
|
||||
pub mod activity;
|
||||
pub mod auth;
|
||||
pub mod client;
|
||||
pub mod companies;
|
||||
pub mod dashboard;
|
||||
pub mod documents;
|
||||
pub mod links;
|
||||
pub mod pack;
|
||||
pub mod papers;
|
||||
pub mod people;
|
||||
@@ -133,6 +135,12 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
.route("/", get(dashboard::page_handler))
|
||||
.route("/people", get(p::list).post(p::create))
|
||||
.route("/people/new", get(p::new_form))
|
||||
.route(
|
||||
"/people/new-client",
|
||||
get(links::new_client_form).post(links::new_client),
|
||||
)
|
||||
.route("/people/{id}/links", post(links::create))
|
||||
.route("/people/{id}/links/{lid}/close", post(links::close))
|
||||
.route("/people/{id}", get(p::show).post(p::update))
|
||||
.route("/people/{id}/edit", get(p::edit_form))
|
||||
.route("/people/{id}/archive", post(p::archive))
|
||||
@@ -307,6 +315,32 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
),
|
||||
);
|
||||
}
|
||||
// The client's pages: open without a login, each checks its link.
|
||||
r = r
|
||||
.route("/c/{token}", get(client::overview))
|
||||
.route(
|
||||
"/c/{token}/about",
|
||||
get(client::about).post(client::about_save),
|
||||
)
|
||||
.route(
|
||||
"/c/{token}/contact",
|
||||
get(client::contact).post(client::contact_save),
|
||||
)
|
||||
.route(
|
||||
"/c/{token}/passport",
|
||||
get(client::passport).post(client::passport_save),
|
||||
)
|
||||
.route(
|
||||
"/c/{token}/address",
|
||||
get(client::address).post(client::address_save),
|
||||
)
|
||||
.route(
|
||||
"/c/{token}/documents",
|
||||
get(client::documents_get)
|
||||
.post(client::documents_upload)
|
||||
.layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)),
|
||||
)
|
||||
.route("/c/{token}/send", post(client::send));
|
||||
r.route("/activity", get(activity::page))
|
||||
.route("/login", get(auth::login))
|
||||
.route("/auth/callback", get(auth::callback))
|
||||
@@ -327,12 +361,14 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
.with_state(st)
|
||||
}
|
||||
|
||||
/// Paths open without a session.
|
||||
/// Paths open without a session: the client's pages (`/c/<token>`, which
|
||||
/// check their link themselves) among them.
|
||||
fn is_public(path: &str) -> bool {
|
||||
matches!(
|
||||
path,
|
||||
"/healthz" | "/version" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico"
|
||||
) || path.starts_with("/static/")
|
||||
|| path.starts_with("/c/")
|
||||
}
|
||||
|
||||
/// Lets a request through with its user, or sends the browser to the login.
|
||||
@@ -394,7 +430,8 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
|
||||
);
|
||||
}
|
||||
let Some(user) = req.extensions().get::<User>().cloned() else {
|
||||
// public paths take no forms
|
||||
// public paths take no forms but the client's, which check the
|
||||
// link's own token (`web::client`)
|
||||
return next.run(req).await;
|
||||
};
|
||||
let multipart = req
|
||||
|
||||
+5
-3
@@ -162,7 +162,7 @@ pub async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Perso
|
||||
Ok(Some((p, view)))
|
||||
}
|
||||
|
||||
fn select_lists() -> minijinja::Value {
|
||||
pub(crate) fn select_lists() -> minijinja::Value {
|
||||
context! {
|
||||
titles => TITLES,
|
||||
sexes => SEXES,
|
||||
@@ -203,7 +203,7 @@ fn log<'a>(
|
||||
/// (`mrz::from_ocr`: lines in any order, look-alike characters) replaces
|
||||
/// it, if that one matches or the text was no zone at all. A text that
|
||||
/// holds no zone becomes a field error.
|
||||
fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||
pub(crate) fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -229,7 +229,7 @@ fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option
|
||||
|
||||
/// `photo`: the lines came from the photo reader (the form's
|
||||
/// `mrz_source`), whose names have no check digit to catch a misread.
|
||||
fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option<String> {
|
||||
pub(crate) fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option<String> {
|
||||
match (m.all_ok(), photo) {
|
||||
(true, false) => {
|
||||
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
||||
@@ -358,6 +358,7 @@ pub async fn show(
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
let recent = audit::recent(&st.db, Some(id), 6).await?;
|
||||
let docs = super::documents::chips(&st, id).await?;
|
||||
let client_links = super::links::card(&st, id).await?;
|
||||
let title = view.name.clone();
|
||||
Ok(page(
|
||||
&st,
|
||||
@@ -373,6 +374,7 @@ pub async fn show(
|
||||
addresses,
|
||||
docs,
|
||||
recent,
|
||||
client_links,
|
||||
stay => assessment.stay,
|
||||
deadlines => assessment.items,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user