Files
visa/src/web/links.rs
T
grabowski 16e4cdc73d
CI / secret scan (push) Successful in 7s
CI / fmt, clippy, tests (push) Successful in 45s
CI / release (push) Skipped
The legal practice: clients, lawyers, contracts, papers, the journal
Lanna Desk's larger work is contracts, general ones and artists', for
clients who are Thai or foreign, people or organizations, with several
lawyers in the team. The back office gets a Legal section (phase 9 in
docs/PLAN.md):

- Lawyers: license number, contact, the login of one who uses the app
  (then "My contracts"), in the team or left.
- Clients, as record cards: person or organization, names in English and
  Thai, stage name or brand, a Thai ID number (checked), a passport or a
  registration number, the lawyer in charge.
- Contracts: code LD-<year>-<n>, the general kinds and the artist kinds
  (recording, management, publishing, performance, license,
  merchandise), other party, status, lawyer, dates and value; a contract
  in force shows its notice day and its end ahead. Filters: general or
  artists, a lawyer, mine, those over.
- Versions: a text kept here, a file (PDF or scan, encrypted as the
  client's document) or both. They never change: the database refuses
  UPDATE and DELETE, a version's file cannot be deleted and no document's
  checksum can change. Any version reads against the one before as a
  line diff.
- Paper copies: the id <code>-P<n> to write on the paper or print as a
  90 x 50 mm label with a QR code; where it lies, its state and holder,
  each move journaled; found again by its id.
- The journal: every change in words, in the change's transaction, each
  entry chained to the one before by SHA-256. The database refuses to
  change, delete or truncate it; /journal checks the chain and every
  version's text and fingerprints against its entry, shows the last hash
  and exports CSV.

The sidebar groups its sections: Legal, Visas and stays, Office. Demo data
(seed-demo) adds three lawyers, six clients and seven contracts with
versions, papers and moves. Documents take a third owner, the client
(migration 0009).

Checks: fmt, clippy, 115 unit and 62 integration tests (new: versions and
the journal, the database refusing changes, a change around the app
breaking the chain, paper ids and moves, the demo checking whole);
screenshots of the new pages in light, dark and on a phone.
2026-11-21 23:20:20 +07:00

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).
pub(crate) 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 Lanna Desk"),
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()
}