Phase 7: the client link
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 59s
CI / release (push) Skipped

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:
grabowski committed 2026-11-20 19:48:34 +07:00
1 parent a6ebdfc89c
commit 43ed75d81b
32 files changed
+2706 -40

No files matched your search

+10
View File
@@ -21,6 +21,10 @@ pub enum Action {
SignOut,
/// A document's file saved to the browser's disk (opening it is a view).
Download,
/// The client sent what they filled in through their link.
Send,
/// Staff closed a client's link.
Close,
}
impl Action {
@@ -35,6 +39,8 @@ impl Action {
Action::SignIn => "sign-in",
Action::SignOut => "sign-out",
Action::Download => "download",
Action::Send => "send",
Action::Close => "close",
}
}
}
@@ -55,6 +61,8 @@ pub enum Entity {
Document,
/// A filled-in form, opened or downloaded; `fields` names the forms.
Form,
/// A client link (`links.rs`).
Link,
}
impl Entity {
@@ -73,6 +81,7 @@ impl Entity {
Entity::WorkPermit => "work-permit",
Entity::Document => "document",
Entity::Form => "form",
Entity::Link => "link",
}
}
}
@@ -162,6 +171,7 @@ fn noun(entity: &str) -> &str {
"reentry-permit" => "re-entry permit",
"work-permit" => "work permit",
"report" => "90-day report",
"link" => "client link",
other => other,
}
}
+1
View File
@@ -13,6 +13,7 @@ pub mod embedded;
pub mod files;
pub mod forms;
pub mod gps;
pub mod links;
pub mod mrz;
pub mod oidc;
pub mod pack;
+308
View File
@@ -0,0 +1,308 @@
//! The client link (phase 7): staff make a link for a person, and the
//! client fills in their details through it without a login. The table
//! keeps the SHA-256 of the link's token, never the token, as `sessions`
//! does; the token is shown once, when the link is made. A link is open
//! for `LIFETIME`, until the client presses Send, or until staff close it;
//! a new link closes the person's earlier one. Everything the client does
//! through it is in the audit log with the actor `link <id>`.
use std::time::Duration;
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::Serialize;
use sqlx::{PgConnection, PgPool};
use crate::dates;
use crate::oidc::random_token;
/// How long a link stays open.
pub const LIFETIME: Duration = Duration::from_secs(14 * 24 * 3600);
#[derive(Clone, Debug, sqlx::FromRow)]
pub struct Link {
pub id: i64,
pub person_id: i64,
pub csrf: String,
pub created_by: String,
pub created_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
pub first_used_at: Option<DateTime<Utc>>,
pub last_used_at: Option<DateTime<Utc>>,
pub sent_at: Option<DateTime<Utc>>,
pub closed_at: Option<DateTime<Utc>>,
pub closed_by: String,
}
/// Where a link stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
/// Made, not opened yet.
Open,
/// Opened by the client at least once.
Used,
/// The client pressed Send; closed.
Sent,
/// Closed by staff, or by a newer link.
Closed,
Expired,
}
impl State {
pub fn label(self) -> &'static str {
match self {
State::Open => "open",
State::Used => "opened",
State::Sent => "sent",
State::Closed => "closed",
State::Expired => "expired",
}
}
/// The chip's color.
pub fn level(self) -> &'static str {
match self {
State::Open | State::Used => "warn",
State::Sent => "ok",
State::Closed | State::Expired => "plain",
}
}
}
impl Link {
pub fn state(&self, now: DateTime<Utc>) -> State {
match (self.sent_at, self.closed_at) {
(Some(_), _) => State::Sent,
(None, Some(_)) => State::Closed,
_ if self.expires_at <= now => State::Expired,
_ if self.first_used_at.is_some() => State::Used,
_ => State::Open,
}
}
/// The client may still use it.
pub fn usable(&self, now: DateTime<Utc>) -> bool {
matches!(self.state(now), State::Open | State::Used)
}
/// The audit log's actor for what the client does through it.
pub fn actor(&self) -> String {
actor(self.id)
}
}
pub fn actor(id: i64) -> String {
format!("link {id}")
}
fn hash(token: &str) -> Vec<u8> {
ring::digest::digest(&ring::digest::SHA256, token.as_bytes())
.as_ref()
.to_vec()
}
/// Makes a link for the person and closes their earlier open ones (by
/// `by`, a staff login). Returns the link and its token, which nothing
/// keeps: the page that made it shows it once.
pub async fn create(conn: &mut PgConnection, person: i64, by: &str) -> Result<(Link, String)> {
sqlx::query(
"UPDATE client_links SET closed_at = now(), closed_by = $2 \
WHERE person_id = $1 AND closed_at IS NULL AND expires_at > now()",
)
.bind(person)
.bind(by)
.execute(&mut *conn)
.await?;
let token = random_token();
let ttl = chrono::TimeDelta::seconds(LIFETIME.as_secs() as i64);
let link: Link = sqlx::query_as(
"INSERT INTO client_links (person_id, token_hash, csrf, created_by, expires_at) \
VALUES ($1, $2, $3, $4, now() + $5) \
RETURNING id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \
last_used_at, sent_at, closed_at, closed_by",
)
.bind(person)
.bind(hash(&token))
.bind(random_token())
.bind(by)
.bind(ttl)
.fetch_one(&mut *conn)
.await?;
Ok((link, token))
}
const COLUMNS: &str = "id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \
last_used_at, sent_at, closed_at, closed_by";
/// The link with this token, whatever its state.
pub async fn by_token(db: &PgPool, token: &str) -> Result<Option<Link>> {
// a token is 43 characters of base64url; anything else is no token
if token.len() != 43
|| !token
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return Ok(None);
}
Ok(sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM client_links WHERE token_hash = $1"
))
.bind(hash(token))
.fetch_optional(db)
.await?)
}
pub async fn get(db: &PgPool, person: i64, id: i64) -> Result<Option<Link>> {
Ok(sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM client_links WHERE person_id = $1 AND id = $2"
))
.bind(person)
.bind(id)
.fetch_optional(db)
.await?)
}
/// The person's links, newest first.
pub async fn for_person(db: &PgPool, person: i64) -> Result<Vec<Link>> {
Ok(sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM client_links WHERE person_id = $1 ORDER BY id DESC"
))
.bind(person)
.fetch_all(db)
.await?)
}
/// Notes that the client opened a page of the link.
pub async fn touch(db: &PgPool, id: i64) -> Result<()> {
sqlx::query(
"UPDATE client_links SET first_used_at = COALESCE(first_used_at, now()), \
last_used_at = now() WHERE id = $1",
)
.bind(id)
.execute(db)
.await?;
Ok(())
}
/// Closes an open link; `sent`: the client sent it. False when it was no
/// longer open.
pub async fn close(conn: &mut PgConnection, id: i64, by: &str, sent: bool) -> Result<bool> {
let done = sqlx::query(
"UPDATE client_links SET closed_at = now(), closed_by = $2, \
sent_at = CASE WHEN $3 THEN now() END \
WHERE id = $1 AND closed_at IS NULL AND expires_at > now()",
)
.bind(id)
.bind(by)
.bind(sent)
.execute(conn)
.await?;
Ok(done.rows_affected() == 1)
}
/// What the client changed through a link, from the audit log: one entry
/// per record, with the names of the fields (never their values).
#[derive(Clone, Debug, Serialize)]
pub struct Change {
pub entity: String,
pub entity_id: Option<i64>,
pub action: String,
pub fields: Vec<String>,
}
pub async fn changes(db: &PgPool, id: i64) -> Result<Vec<Change>> {
let rows: Vec<(String, Option<i64>, String, Vec<String>)> = sqlx::query_as(
"SELECT entity, entity_id, action, fields FROM audit_log \
WHERE actor = $1 AND action IN ('create', 'update') ORDER BY id",
)
.bind(actor(id))
.fetch_all(db)
.await?;
let mut out: Vec<Change> = Vec::new();
for (entity, entity_id, action, fields) in rows {
match out
.iter_mut()
.find(|c| c.entity == entity && c.entity_id == entity_id)
{
Some(c) => {
for f in fields {
if !c.fields.contains(&f) {
c.fields.push(f);
}
}
}
None => out.push(Change {
entity,
entity_id,
action,
fields,
}),
}
}
Ok(out)
}
/// The record of `entity` the link made last, if any: the client's own
/// address or passport, which a second save changes instead of adding
/// another.
pub async fn made(db: &PgPool, id: i64, entity: &str) -> Result<Option<i64>> {
Ok(sqlx::query_scalar(
"SELECT entity_id FROM audit_log WHERE actor = $1 AND action = 'create' \
AND entity = $2 ORDER BY id DESC LIMIT 1",
)
.bind(actor(id))
.bind(entity)
.fetch_optional(db)
.await?
.flatten())
}
/// "Dec 4, 2026" in Chiang Mai time.
pub fn day(t: DateTime<Utc>) -> String {
dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive())
}
#[cfg(test)]
mod tests {
use super::*;
fn link(now: DateTime<Utc>) -> Link {
Link {
id: 7,
person_id: 1,
csrf: String::new(),
created_by: "grabowski".into(),
created_at: now,
expires_at: now + chrono::TimeDelta::days(14),
first_used_at: None,
last_used_at: None,
sent_at: None,
closed_at: None,
closed_by: String::new(),
}
}
#[test]
fn states() {
let now = Utc::now();
let mut l = link(now);
assert_eq!(l.state(now), State::Open);
l.first_used_at = Some(now);
assert_eq!(l.state(now), State::Used);
assert!(l.usable(now));
assert_eq!(l.state(now + chrono::TimeDelta::days(15)), State::Expired);
l.closed_at = Some(now);
assert_eq!(l.state(now), State::Closed);
assert!(!l.usable(now));
l.sent_at = Some(now);
assert_eq!(l.state(now), State::Sent);
assert_eq!(l.actor(), "link 7");
}
#[test]
fn only_tokens_are_looked_up() {
assert_eq!(random_token().len(), 43);
assert_eq!(hash("x").len(), 32);
}
}
+64
View File
@@ -11,6 +11,7 @@ use crate::audit::{self, Action, Entity, Entry};
use crate::dates;
use crate::documents::{self, Meta, NewFile, Owner};
use crate::files::{self, Store};
use crate::links;
use crate::mrz;
use crate::people::{self, AddressInput, PassportInput, PersonInput};
use crate::records::{self, Kind, Values};
@@ -568,6 +569,7 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
}
let mut tx = db.begin().await?;
let mut company_ids = Vec::new();
let mut person_ids = Vec::new();
for c in companies() {
let id = records::create(&mut tx, &records::COMPANIES, None, &c).await?;
audit::record(&mut *tx, &seeded(Action::Create, Entity::Company, id, None)).await?;
@@ -576,6 +578,7 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
for mut demo in demos(today) {
demo.person.employer = demo.employer.map(|i| company_ids[i]);
let id = people::create_person(&mut tx, &demo.person).await?;
person_ids.push(id);
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Person, id, Some(id)),
@@ -631,10 +634,71 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
.await?;
}
}
demo_links(&mut tx, &person_ids).await?;
tx.commit().await?;
Ok(true)
}
/// Client links to see on the person's page: the first demo person sent
/// theirs an hour ago, with a new phone number and email address; the
/// second opened theirs and has not sent it yet. Their tokens are thrown
/// away: to try the client's pages, make a new link.
async fn demo_links(tx: &mut sqlx::PgConnection, people: &[i64]) -> Result<()> {
if let Some(&id) = people.first() {
let (link, _) = links::create(tx, id, "seed").await?;
sqlx::query(
"UPDATE client_links SET created_at = now() - interval '1 day', \
first_used_at = now() - interval '2 hours', last_used_at = now() - interval '1 hour', \
sent_at = now() - interval '1 hour', closed_at = now() - interval '1 hour', \
closed_by = 'client' WHERE id = $1",
)
.bind(link.id)
.execute(&mut *tx)
.await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Link, link.id, Some(id)),
)
.await?;
let actor = link.actor();
let fields = ["phone".to_string(), "email".to_string()];
for (action, entity, eid, fields) in [
(Action::Update, Entity::Person, id, &fields[..]),
(Action::Send, Entity::Link, link.id, &[][..]),
] {
audit::record(
&mut *tx,
&Entry {
actor: &actor,
action,
entity,
entity_id: Some(eid),
person_id: Some(id),
company_id: None,
fields,
},
)
.await?;
}
}
if let Some(&id) = people.get(1) {
let (link, _) = links::create(tx, id, "seed").await?;
sqlx::query(
"UPDATE client_links SET first_used_at = now() - interval '3 hours', \
last_used_at = now() - interval '3 hours' WHERE id = $1",
)
.bind(link.id)
.execute(&mut *tx)
.await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Link, link.id, Some(id)),
)
.await?;
}
Ok(())
}
/// A demo document to add: whose, its kind, its record, its date, the
/// file's name and the file.
type Planned = (
+917
View File
@@ -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, &current) {
(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
View File
@@ -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 {
+353
View File
@@ -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
View File
@@ -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
View File
@@ -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,
},