Every page of the pack is now A4 upright, so it prints as one stack. A
PDF page or a whole-page picture that lies wider than tall is turned
onto the page (a small one that fits as it is stays as it is), and a
PDF page is only made smaller, never larger.
A picture never prints larger than its resolution allows (the JFIF or
PNG dpi, else 150 dpi), nor larger than its kind's box: passport pages,
visas and stamps 180 x 128 mm, cards 130 x 90 mm, and a phone's
screenshot (the TDAC, or any picture about twice as tall as wide)
150 x 75 mm. These print at the top of the page.
Cards: a new kind "ID card", and the work permit, take two pictures in
one upload as front and back (migration 0008 documents.back_of). The
Documents tab marks them front/back, lists them together and offers
"Print both sides" (.../documents/{id}/sides.pdf); the pack prints both
on one sheet. The client link takes ID cards too. The demo seeds a TDAC
screenshot and an ID card's two sides.
Checks: fmt, clippy, 108 unit and 57 integration tests (print sizes,
dpi reading, the back following its front, the paired upload, its
audit and the sides PDF); the demo pack's pages checked as images.
The Documents tab's actions stack on a phone, so none is cut off.
355 lines
10 KiB
Rust
355 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",
|
|
"id-card",
|
|
"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()
|
|
}
|