Files
visa/src/web/links.rs
T
grabowski 43ed75d81b
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 59s
CI / release (push) Skipped
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.
2026-11-20 19:48:34 +07:00

354 lines
10 KiB
Rust

//! 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()
}