Files
visa/src/web/documents.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

1230 lines
38 KiB
Rust

//! Documents in the pages: a person's Documents tab and the documents on a
//! company's page, the upload (several files at once), opening and
//! downloading a file, changing what is known about a document, and
//! deleting it. Each of these is an entry in the audit log; opening a file
//! is a view of the document, saving it to disk a download.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use axum::Extension;
use axum::body::Body;
use axum::extract::multipart::{Field, MultipartError};
use axum::extract::{Multipart, Path, Query, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use minijinja::context;
use serde::{Deserialize, Serialize};
use tracing::{error, warn};
use crate::audit::{self, Action, Entity, Entry};
use crate::documents::{self, Document, LINKS, Meta, NewFile, Owner};
use crate::files::{self, Store};
use crate::forms::{self, Errors, Fields};
use crate::people::{self, AddressInput};
use crate::session::{self, User};
use crate::{companies, countries, dates, records};
use super::people::{PersonView, load_person};
use super::records::options;
use super::{AppState, HOME, Res, message, not_found_page, page};
/// The largest file taken.
pub const FILE_LIMIT: usize = 20 * 1024 * 1024;
/// The most files in one upload.
pub const MAX_FILES: usize = 10;
/// The largest upload, all its files and fields together.
pub const UPLOAD_LIMIT: usize = 64 * 1024 * 1024;
const FIELD_LIMIT: usize = 4 * 1024;
const NOTE_LIMIT: usize = 500;
/// The file responses' own policy: nothing runs; the browser's image or PDF
/// viewer shows the file and may style its own page.
pub(crate) const FILE_CSP: &str = "default-src 'none'; img-src 'self'; object-src 'self'; \
style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; \
form-action 'none'";
/// What the upload and change forms hold.
#[derive(Clone, Debug, Default, Serialize)]
pub struct Values {
pub kind: String,
pub link: String,
pub dated_on: String,
pub note: String,
/// Where an upload came from: "office" for the office card of a
/// company's page, which it returns to.
pub back: String,
}
impl Values {
fn of(d: &Document) -> Values {
Values {
kind: d.kind.clone(),
link: documents::link_value(d.link()),
dated_on: d.dated_on.map(|d| d.to_string()).unwrap_or_default(),
note: d.note.clone(),
back: String::new(),
}
}
fn from_fields(f: &Fields) -> Values {
Values {
kind: forms::get(f, "kind"),
link: forms::get(f, "link"),
dated_on: forms::get(f, "dated_on"),
note: forms::get(f, "note"),
back: String::new(),
}
}
/// The upload came from the office card of a company's page.
pub fn from_office(&self) -> bool {
self.back == "office"
}
}
/// A document as the pages show it.
#[derive(Debug, Serialize)]
pub struct DocView {
pub id: i64,
pub kind: String,
pub kind_label: String,
pub link_label: String,
pub link_href: String,
pub dated_on: String,
pub note: String,
pub file_name: String,
pub type_label: &'static str,
pub size: String,
pub image: bool,
pub uploaded: String,
pub uploaded_by: String,
pub updated: String,
pub sha256: String,
pub href: String,
pub edit: String,
/// A card's side: "front", "back" or empty.
pub side: &'static str,
}
/// A document next to its record (Overview, Visa and stay).
#[derive(Debug, Serialize)]
pub struct Chip {
pub label: String,
pub href: String,
}
#[derive(Debug, Serialize)]
pub struct Group {
pub title: &'static str,
pub options: Vec<(String, String)>,
}
/// The records of a person a document may belong to, for the selection,
/// and each one's name and page for the list.
#[derive(Debug, Default)]
pub struct Choices {
pub groups: Vec<Group>,
pub names: HashMap<String, (String, String)>,
}
pub async fn choices(st: &AppState, person: i64) -> anyhow::Result<Choices> {
let today = dates::today();
let opts = options(&st.db, person, true, None).await?;
let mut out = Choices::default();
for link in LINKS {
let mut items: Vec<(String, String, String)> = Vec::new();
match link.slug {
"passports" => {
for p in people::passports(&st.db, person).await? {
let country = countries::name(&p.issuing_country).unwrap_or(&p.issuing_country);
items.push((
format!("passports:{}", p.id),
format!(
"{} ({country}), valid to {}",
p.number,
dates::fmt_date(p.expires_on)
),
format!("/people/{person}#passports"),
));
}
}
"addresses" => {
for a in people::addresses(&st.db, person).await? {
items.push((
format!("addresses:{}", a.id),
people::address_line(&AddressInput::from(&a)),
format!("/people/{person}#addresses"),
));
}
}
slug => {
let Some(kind) = records::STAY.iter().find(|k| k.slug == slug) else {
continue;
};
for r in records::list(&st.db, kind, person).await? {
let shown = records::show(kind, &r, &opts, today);
let name: Vec<&str> = shown.headline.iter().map(|p| p.text.as_str()).collect();
items.push((
format!("{slug}:{}", r.id),
name.join(" · "),
format!("/people/{person}/stay#{slug}"),
));
}
}
}
if items.is_empty() {
continue;
}
let mut options = Vec::new();
for (value, name, href) in items {
options.push((value.clone(), name.clone()));
out.names
.insert(value, (format!("{}: {name}", singular(link.slug)), href));
}
out.groups.push(Group {
title: link.title,
options,
});
}
Ok(out)
}
fn singular(link: &str) -> &'static str {
match link {
"passports" => "Passport",
"visas" => "Visa",
"arrivals" => "Arrival",
"extensions" => "Extension",
"reentry-permits" => "Re-entry permit",
"reports" => "90-day report",
"addresses" => "Address",
"work-permits" => "Work permit",
_ => "Record",
}
}
pub fn size_label(n: i64) -> String {
if n < 1024 {
format!("{n} bytes")
} else if n < 1024 * 1024 {
format!("{} KB", (n + 512) / 1024)
} else {
format!("{:.1} MB", n as f64 / (1024.0 * 1024.0))
}
}
fn view(d: &Document, names: &HashMap<String, (String, String)>) -> DocView {
let owner = d.owner();
let (link_label, link_href) = names
.get(&documents::link_value(d.link()))
.cloned()
.unwrap_or_default();
DocView {
id: d.id,
kind: d.kind.clone(),
kind_label: documents::kind_label(owner, &d.kind),
link_label,
link_href,
dated_on: d.dated_on.map(dates::fmt_date).unwrap_or_default(),
note: d.note.clone(),
file_name: d.file_name.clone(),
type_label: files::type_label(&d.content_type),
size: size_label(d.size_bytes.into()),
image: files::is_image(&d.content_type),
uploaded: dates::fmt_datetime(d.uploaded_at),
uploaded_by: d.uploaded_by.clone(),
updated: if d.updated_at > d.uploaded_at + chrono::Duration::seconds(1) {
dates::fmt_datetime(d.updated_at)
} else {
String::new()
},
sha256: d.sha256.clone(),
href: format!("{}/{}/file", owner.base(), d.id),
edit: format!("{}/{}/edit", owner.base(), d.id),
side: if d.back_of.is_some() { "back" } else { "" },
}
}
pub async fn views(
st: &AppState,
owner: Owner,
names: &HashMap<String, (String, String)>,
) -> anyhow::Result<Vec<DocView>> {
let docs = documents::list(&st.db, owner).await?;
let fronts: HashSet<i64> = docs.iter().filter_map(|d| d.back_of).collect();
Ok(docs
.iter()
.map(|d| {
let mut v = view(d, names);
if fronts.contains(&d.id) {
v.side = "front";
}
v
})
.collect())
}
/// A person's documents by the record they belong to (`arrivals:7`).
pub async fn chips(st: &AppState, person: i64) -> anyhow::Result<HashMap<String, Vec<Chip>>> {
let owner = Owner::Person(person);
let mut out: HashMap<String, Vec<Chip>> = HashMap::new();
for d in documents::list(&st.db, owner).await? {
if let Some(link) = d.link() {
out.entry(documents::link_value(Some(link)))
.or_default()
.push(Chip {
label: documents::kind_label(owner, &d.kind),
href: format!("{}/{}/file", owner.base(), d.id),
});
}
}
Ok(out)
}
/// The kinds for the selection.
fn kinds(owner: Owner) -> Vec<(&'static str, &'static str)> {
owner.kinds().iter().map(|k| (k.slug, k.label)).collect()
}
/// The office card of a company's page: the newest photo of the office that
/// is an image, how many more there are, and the strip that adds one (with
/// its errors when an upload from it was refused).
pub fn office_context(
st: &AppState,
docs: &[DocView],
values: &Values,
errors: &Errors,
) -> minijinja::Value {
let all = docs.iter().filter(|d| d.kind == "office-photo").count();
let photo = docs
.iter()
.filter(|d| d.kind == "office-photo" && d.image)
.max_by_key(|d| d.id);
let errors = if values.from_office() {
errors.clone()
} else {
Errors::new()
};
context! {
files_on => st.files.is_some(),
photo,
// the other photos of the office, PDFs among them
more => all - usize::from(photo.is_some()),
errors,
file_limit_mb => FILE_LIMIT / (1024 * 1024),
file_limit => FILE_LIMIT,
}
}
/// The upload part of a page: on the Documents tab and the company's page.
pub fn upload_context(
st: &AppState,
owner: Owner,
values: &Values,
errors: &Errors,
groups: &[Group],
) -> minijinja::Value {
context! {
files_on => st.files.is_some(),
action => owner.base(),
kinds => kinds(owner),
groups,
values,
errors,
file_limit_mb => FILE_LIMIT / (1024 * 1024),
file_limit => FILE_LIMIT,
max_files => MAX_FILES,
}
}
#[derive(Debug, Deserialize)]
pub struct TabQuery {
/// A record to add a document to, as on its page: `arrivals:7`.
#[serde(rename = "for")]
pub for_record: Option<String>,
/// A kind to add, as the Pack tab asks for it: `photo`.
pub kind: Option<String>,
}
pub async fn person_tab(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Query(q): Query<TabQuery>,
) -> Res {
let Some((_, p)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let choices = choices(&st, id).await?;
let mut values = Values::default();
if let Some(k) = q
.kind
.filter(|k| documents::kind(Owner::Person(id), k).is_some())
{
values.kind = k;
}
if let Some(v) = q.for_record.filter(|v| choices.names.contains_key(v)) {
if let Some((link, _)) = documents::parse_link(&v) {
values.kind = documents::kind_for_link(link.slug)
.map(|k| k.slug.to_string())
.unwrap_or_default();
}
values.link = v;
}
person_tab_page(
&st,
&user,
&p,
&choices,
&values,
&Errors::new(),
StatusCode::OK,
)
.await
}
async fn person_tab_page(
st: &AppState,
user: &User,
p: &PersonView,
choices: &Choices,
values: &Values,
errors: &Errors,
status: StatusCode,
) -> Res {
let owner = Owner::Person(p.id);
let docs = views(st, owner, &choices.names).await?;
audit::viewed(&st.db, &user.login, Entity::Person, p.id, p.id).await?;
let title = format!("Documents: {}", p.name);
Ok(page(
st,
user,
"documents.html",
&title,
"people",
status,
context! {
p,
tab => "documents",
docs,
upload => upload_context(st, owner, values, errors, &choices.groups),
},
))
}
/// A card's front and back on one A4 page as a PDF, to print.
pub async fn sides(st: Arc<AppState>, user: User, owner: Owner, id: i64) -> Res {
let (Some(front), Some(name)) = (
documents::get(&st.db, owner, id).await?,
whose(&st, owner).await?,
) else {
return Ok(not_found_page(&st));
};
let Some(back) = documents::list(&st.db, owner)
.await?
.into_iter()
.find(|d| d.back_of == Some(id))
else {
return Ok(not_found_page(&st));
};
let Some(store) = st.files.clone() else {
return Ok(files_off(&st));
};
let mut loaded = Vec::new();
for d in [&front, &back] {
let bytes = match store.get(d.id).await {
Ok(b) if files::sha256_hex(&b) == d.sha256 => b,
Ok(_) | Err(_) => {
error!("document {}: missing or not as uploaded", d.id);
return Ok(unreadable(&st, owner));
}
};
loaded.push(crate::pack::pdf::Loaded {
name: d.file_name.clone(),
content_type: d.content_type.clone(),
kind: d.kind.clone(),
back_of: d.back_of,
bytes: Ok(bytes),
});
}
let (b, f) = (loaded.pop(), loaded.pop());
let (Some(f), Some(b)) = (f, b) else {
return Ok(not_found_page(&st));
};
let pdf = tokio::task::spawn_blocking(move || crate::pack::pdf::sides(f, b)).await??;
let fields = ["file".to_string()];
for d in [&front, &back] {
audit::record(
&st.db,
&Entry {
actor: &user.login,
action: Action::View,
entity: Entity::Document,
entity_id: Some(d.id),
person_id: owner.person(),
company_id: owner.company(),
fields: &fields,
},
)
.await?;
}
let file_name = format!(
"{name} - {} - both sides.pdf",
documents::kind_label(owner, &front.kind)
);
let mut resp = Response::new(Body::from(pdf));
let h = resp.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/pdf"),
);
h.insert(
header::CONTENT_DISPOSITION,
disposition("inline", &file_name),
);
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"),
);
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(FILE_CSP),
);
Ok(resp)
}
/// Documents are off: no files directory and key (local development).
fn files_off(st: &AppState) -> Response {
message(
st,
StatusCode::SERVICE_UNAVAILABLE,
"Documents are switched off",
"This server has no files directory and file key (VISA_FILES_DIR, VISA_FILES_KEY_FILE), \
so it neither takes nor shows documents.",
(HOME, "Open the app"),
)
}
fn too_large(st: &AppState) -> Response {
message(
st,
StatusCode::PAYLOAD_TOO_LARGE,
"The upload is too large",
&format!(
"One upload takes up to {MAX_FILES} files of up to {} MB each, {} MB in all. Send the \
files in smaller groups.",
FILE_LIMIT / (1024 * 1024),
UPLOAD_LIMIT / (1024 * 1024)
),
(HOME, "Open the app"),
)
}
fn broken_upload(st: &AppState, e: &MultipartError) -> Response {
if e.status() == StatusCode::PAYLOAD_TOO_LARGE {
return too_large(st);
}
warn!("an upload could not be read: {}", e.body_text());
message(
st,
StatusCode::BAD_REQUEST,
"The upload was cut short",
"The files did not arrive whole. Go back and send them again.",
(HOME, "Open the app"),
)
}
/// An upload as it arrived, before any check.
#[derive(Default)]
pub(crate) struct Upload {
pub(crate) values: Values,
files: Vec<(String, Vec<u8>)>,
/// files over the limit, by name
too_big: Vec<String>,
/// no file chosen, or an empty one, by name
empty: Vec<String>,
}
/// Reads at most `limit` bytes of a field; the rest is read and dropped.
/// `None` when the field was longer.
pub(crate) async fn read_field(
field: &mut Field<'_>,
limit: usize,
) -> Result<Option<Vec<u8>>, MultipartError> {
let mut out = Vec::new();
let mut over = false;
while let Some(chunk) = field.chunk().await? {
if over || out.len() + chunk.len() > limit {
over = true;
out = Vec::new();
continue;
}
out.extend_from_slice(&chunk);
}
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. `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, Refused>, MultipartError> {
let token = match mp.next_field().await? {
Some(mut f) if f.name() == Some("csrf") => read_field(&mut f, FIELD_LIMIT)
.await?
.map(|b| String::from_utf8_lossy(&b).into_owned()),
_ => None,
};
if !token.is_some_and(|t| session::same_token(&t, &user.csrf)) {
warn!(
"refused an upload without a valid token from {}",
user.login
);
return Ok(Err(Refused::Token));
}
let mut up = Upload::default();
let mut count = 0;
while let Some(mut field) = mp.next_field().await? {
let name = field.name().unwrap_or_default().to_string();
if name == "file" {
let raw_name = field.file_name().unwrap_or_default().to_string();
let file_name = documents::clean_name(&raw_name);
match read_field(&mut field, FILE_LIMIT).await? {
// no file chosen: browsers send an empty part without a name
Some(b) if b.is_empty() && raw_name.is_empty() => {}
Some(b) if b.is_empty() => up.empty.push(file_name),
Some(b) => {
count += 1;
if count > MAX_FILES {
continue;
}
up.files.push((file_name, b));
}
None => up.too_big.push(file_name),
}
continue;
}
let text = read_field(&mut field, FIELD_LIMIT)
.await?
.map(|b| String::from_utf8_lossy(&b).trim().to_string())
.unwrap_or_default();
match name.as_str() {
"kind" => up.values.kind = text,
"link" => up.values.link = text,
"dated_on" => up.values.dated_on = text,
"note" => up.values.note = text,
"back" => up.values.back = text,
_ => {}
}
}
if count > MAX_FILES {
return Ok(Err(Refused::TooMany));
}
Ok(Ok(up))
}
/// What the forms say about a document, checked: the kind is one of the
/// owner's, the record one of the person's, the date a date.
async fn check_meta(st: &AppState, owner: Owner, v: &Values) -> anyhow::Result<(Meta, Errors)> {
let mut errors = Errors::new();
let kind = v.kind.trim();
if documents::kind(owner, kind).is_none() {
forms::err(&mut errors, "kind", "Choose what the document is.");
}
let mut link = None;
if let Owner::Person(person) = owner
&& !v.link.trim().is_empty()
{
match documents::parse_link(v.link.trim()) {
Some((l, id)) if documents::link_is_theirs(&st.db, person, l, id).await? => {
link = Some((l, id));
}
_ => forms::err(
&mut errors,
"link",
"Choose one of this person's records, or none.",
),
}
}
let dated_on = match v.dated_on.trim() {
"" => None,
s => match dates::parse_form_date(s) {
Ok(d) => Some(d),
Err(msg) => {
forms::err(&mut errors, "dated_on", msg);
None
}
},
};
let note = v.note.trim().to_string();
if note.chars().count() > NOTE_LIMIT {
forms::err(
&mut errors,
"note",
format!("Keep the note under {NOTE_LIMIT} characters."),
);
}
Ok((
Meta {
kind: kind.to_string(),
link,
dated_on,
note,
},
errors,
))
}
pub(crate) struct Checked {
name: String,
bytes: Vec<u8>,
content_type: &'static str,
sha256: String,
}
/// 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.
pub(crate) async fn check_files(
st: &AppState,
owner: Owner,
up: Upload,
errors: &mut Errors,
) -> anyhow::Result<Vec<Checked>> {
let mut problems: Vec<String> = Vec::new();
if up.files.is_empty() && up.too_big.is_empty() && up.empty.is_empty() {
problems.push("Choose a file to upload.".into());
}
for n in &up.too_big {
problems.push(format!(
"{n} is larger than {} MB.",
FILE_LIMIT / (1024 * 1024)
));
}
for n in &up.empty {
problems.push(format!("{n} is empty."));
}
let mut seen = HashSet::new();
let mut out = Vec::new();
for (name, bytes) in up.files {
let Some(content_type) = files::sniff(&bytes) else {
problems.push(format!("{name} is not a PDF, JPEG, PNG or WebP file."));
continue;
};
let sha256 = files::sha256_hex(&bytes);
if !seen.insert(sha256.clone()) {
problems.push(format!("{name} is in this upload twice."));
continue;
}
if let Some(d) = documents::same_file(&st.db, owner, &sha256).await? {
problems.push(format!(
"{name} is here already: {}, added {}.",
documents::kind_label(owner, &d.kind),
dates::fmt_datetime(d.uploaded_at)
));
continue;
}
out.push(Checked {
name,
bytes,
content_type,
sha256,
});
}
if !problems.is_empty() {
forms::err(errors, "file", problems.join(" "));
}
Ok(out)
}
/// 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.
pub(crate) async fn save(
st: &AppState,
user: &User,
store: &Store,
owner: Owner,
meta: &Meta,
checked: Vec<Checked>,
) -> anyhow::Result<i64> {
let fields = meta.set_fields();
// a card's two sides in one upload: the second picture is the back
let pair = documents::is_card(&meta.kind)
&& checked.len() == 2
&& checked.iter().all(|c| files::is_image(c.content_type));
let mut back_fields = fields.clone();
back_fields.push("back_of".into());
let mut tx = st.db.begin().await?;
let mut written: Vec<i64> = Vec::new();
let result: anyhow::Result<()> = async {
for f in checked {
let file = NewFile {
name: &f.name,
content_type: f.content_type,
size: i32::try_from(f.bytes.len())?,
sha256: &f.sha256,
};
let id = documents::insert(&mut tx, owner, meta, &file, &user.login).await?;
store.put(id, f.bytes).await?;
let back = match written.first() {
Some(&front) if pair => {
documents::set_back(&mut tx, id, front).await?;
true
}
_ => false,
};
written.push(id);
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action: Action::Create,
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: if back { &back_fields } else { &fields },
},
)
.await?;
}
Ok(())
}
.await;
let result = match result {
Ok(()) => tx.commit().await.map_err(anyhow::Error::from),
Err(e) => Err(e),
};
if let Err(e) = result {
for id in &written {
if let Err(r) = store.remove(*id).await {
error!("removing the file of the failed upload {id}: {r:#}");
}
}
return Err(e);
}
Ok(written.first().copied().unwrap_or_default())
}
/// Where a document's list is, with its anchor.
fn list_page(owner: Owner) -> String {
match owner {
Owner::Person(id) => format!("/people/{id}/documents"),
Owner::Company(id) => format!("/companies/{id}"),
Owner::Client(id) => format!("/clients/{id}"),
}
}
/// The upload of one or more files with what they are.
pub async fn upload(st: Arc<AppState>, user: User, owner: Owner, mp: Multipart) -> Res {
// the owner first: a missing one needs no upload read
let person = match owner {
Owner::Person(id) => match load_person(&st, id).await? {
Some((_, p)) => Some(p),
None => return Ok(not_found_page(&st)),
},
Owner::Company(id) => {
if companies::name(&st.db, id).await?.is_none() {
return Ok(not_found_page(&st));
}
None
}
// a client's files come in as contract versions (`web::legal`)
Owner::Client(_) => return Ok(not_found_page(&st)),
};
let up = match read_upload(&user, mp).await {
Ok(Ok(up)) => up,
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 {
return Ok(files_off(&st));
};
let values = up.values.clone();
let (meta, mut errors) = check_meta(&st, owner, &values).await?;
let checked = check_files(&st, owner, up, &mut errors).await?;
if !errors.is_empty() {
let status = StatusCode::UNPROCESSABLE_ENTITY;
return match (owner, person) {
(Owner::Person(id), Some(p)) => {
let choices = choices(&st, id).await?;
person_tab_page(&st, &user, &p, &choices, &values, &errors, status).await
}
(_, _) => {
let id = owner.company().unwrap_or_default();
super::companies::company_page(&st, &user, id, &values, &errors, status).await
}
};
}
let first = save(&st, &user, &store, owner, &meta, checked).await?;
let to = match owner {
Owner::Company(id) if values.from_office() => format!("/companies/{id}#office"),
_ => format!("{}#doc-{first}", list_page(owner)),
};
Ok(Redirect::to(&to).into_response())
}
#[derive(Debug, Deserialize)]
pub struct FileQuery {
pub download: Option<String>,
}
/// The name a downloaded file gets: whose it is, what, and its date.
fn download_name(whose: &str, d: &Document) -> String {
let date = d
.dated_on
.unwrap_or_else(|| d.uploaded_at.with_timezone(&dates::bangkok()).date_naive());
let raw = format!(
"{whose} - {} - {date}.{}",
documents::kind_label(d.owner(), &d.kind),
files::extension(&d.content_type)
);
raw.chars()
.map(|c| {
if c.is_control() || "/\\:*?\"<>|".contains(c) {
'-'
} else {
c
}
})
.collect()
}
/// `inline` or `attachment` with the name in both forms (RFC 6266).
pub(crate) fn disposition(how: &str, name: &str) -> HeaderValue {
let ascii: String = name
.chars()
.map(|c| {
if c.is_ascii_graphic() || c == ' ' {
c
} else {
'_'
}
})
.filter(|c| *c != '"' && *c != '\\')
.collect();
let value = format!(
"{how}; filename=\"{ascii}\"; filename*=UTF-8''{}",
// `/` is no attr-char (RFC 8187); the names have none, but still
super::percent_encode(name).replace('/', "%2F")
);
HeaderValue::from_str(&value).unwrap_or_else(|_| HeaderValue::from_static("attachment"))
}
async fn whose(st: &AppState, owner: Owner) -> anyhow::Result<Option<String>> {
Ok(match owner {
Owner::Person(id) => people::get_person(&st.db, id)
.await?
.map(|p| p.display_name().replace(',', "")),
Owner::Company(id) => companies::name(&st.db, id).await?,
Owner::Client(id) => {
sqlx::query_scalar("SELECT name FROM clients WHERE id = $1")
.bind(id)
.fetch_optional(&st.db)
.await?
}
})
}
/// A document's file, opened in the browser or (`?download=1`) saved.
pub async fn file(st: Arc<AppState>, user: User, owner: Owner, id: i64, q: FileQuery) -> Res {
let download = q.download.is_some();
let (Some(d), Some(name)) = (
documents::get(&st.db, owner, id).await?,
whose(&st, owner).await?,
) else {
return Ok(not_found_page(&st));
};
let Some(store) = st.files.clone() else {
return Ok(files_off(&st));
};
let bytes = match store.get(id).await {
Ok(b) if files::sha256_hex(&b) == d.sha256 => b,
Ok(_) => {
error!("document {id}: the file does not match the checksum of its upload");
return Ok(unreadable(&st, owner));
}
Err(e) => {
error!("document {id}: {e:#}");
return Ok(unreadable(&st, owner));
}
};
let fields = ["file".to_string()];
audit::record(
&st.db,
&Entry {
actor: &user.login,
action: if download {
Action::Download
} else {
Action::View
},
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: &fields,
},
)
.await?;
let how = if download { "attachment" } else { "inline" };
let mut resp = Response::new(Body::from(bytes));
let h = resp.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_str(&d.content_type)?,
);
h.insert(
header::CONTENT_DISPOSITION,
disposition(how, &download_name(&name, &d)),
);
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"),
);
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(FILE_CSP),
);
h.insert(
"cross-origin-resource-policy",
HeaderValue::from_static("same-origin"),
);
Ok(resp)
}
fn unreadable(st: &AppState, owner: Owner) -> Response {
message(
st,
StatusCode::INTERNAL_SERVER_ERROR,
"The file cannot be opened",
"The file of this document is missing or damaged on the server. The server log has the \
details; `visa files-check` checks every file.",
(&list_page(owner), "Back to the documents"),
)
}
/// The page about one document: what it is, its file, the change form.
#[allow(clippy::too_many_arguments)]
async fn form_page(
st: &AppState,
user: &User,
owner: Owner,
d: &Document,
values: &Values,
errors: &Errors,
status: StatusCode,
) -> Res {
let (p, company, groups, names) = match owner {
Owner::Person(id) => {
let Some((_, p)) = load_person(st, id).await? else {
return Ok(not_found_page(st));
};
let c = choices(st, id).await?;
(Some(p), None, c.groups, c.names)
}
Owner::Company(id) => {
let Some(name) = companies::name(&st.db, id).await? else {
return Ok(not_found_page(st));
};
(
None,
Some(context! { id, name }),
Vec::new(),
HashMap::new(),
)
}
// a contract version's file is not edited
Owner::Client(_) => return Ok(not_found_page(st)),
};
let doc = view(d, &names);
let title = format!(
"{}: {}",
doc.kind_label,
whose(st, owner).await?.unwrap_or_default()
);
Ok(page(
st,
user,
"document_form.html",
&title,
if p.is_some() { "people" } else { "companies" },
status,
context! {
p,
company,
tab => "documents",
doc,
action => format!("{}/{}", owner.base(), d.id),
cancel => format!("{}#doc-{}", list_page(owner), d.id),
kinds => kinds(owner),
groups,
values,
errors,
},
))
}
pub async fn edit_form(st: Arc<AppState>, user: User, owner: Owner, id: i64) -> Res {
let Some(d) = documents::get(&st.db, owner, id).await? else {
return Ok(not_found_page(&st));
};
if let Some(person) = owner.person() {
audit::viewed(&st.db, &user.login, Entity::Document, id, person).await?;
}
form_page(
&st,
&user,
owner,
&d,
&Values::of(&d),
&Errors::new(),
StatusCode::OK,
)
.await
}
pub async fn update(st: Arc<AppState>, user: User, owner: Owner, id: i64, f: Fields) -> Res {
let Some(d) = documents::get(&st.db, owner, id).await? else {
return Ok(not_found_page(&st));
};
let values = Values::from_fields(&f);
let (meta, errors) = check_meta(&st, owner, &values).await?;
if !errors.is_empty() {
return form_page(
&st,
&user,
owner,
&d,
&values,
&errors,
StatusCode::UNPROCESSABLE_ENTITY,
)
.await;
}
let changed = Meta::of(&d).changed(&meta);
if !changed.is_empty() {
let mut tx = st.db.begin().await?;
documents::update(&mut tx, owner, id, &meta).await?;
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action: Action::Update,
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: &changed,
},
)
.await?;
tx.commit().await?;
}
Ok(Redirect::to(&format!("{}#doc-{id}", list_page(owner))).into_response())
}
/// Deletes the document and its file; the audit log keeps that it existed.
pub async fn delete(st: Arc<AppState>, user: User, owner: Owner, id: i64) -> Res {
let Some(store) = st.files.clone() else {
return Ok(files_off(&st));
};
let mut tx = st.db.begin().await?;
if !documents::delete(&mut tx, owner, id).await? {
return Ok(not_found_page(&st));
}
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action: Action::Delete,
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: &[],
},
)
.await?;
tx.commit().await?;
if let Err(e) = store.remove(id).await {
error!("document {id} is deleted, but not its file: {e:#}");
}
Ok(Redirect::to(&list_page(owner)).into_response())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_read_like_a_file_manager() {
assert_eq!(size_label(900), "900 bytes");
assert_eq!(size_label(1500), "1 KB");
assert_eq!(size_label(340 * 1024), "340 KB");
assert_eq!(size_label(1_300_000), "1.2 MB");
}
#[test]
fn the_file_name_says_whose_what_and_when() {
let at = chrono::DateTime::parse_from_rfc3339("2026-11-18T20:00:00Z")
.unwrap()
.to_utc();
let d = Document {
id: 1,
person_id: Some(1),
company_id: None,
kind: "photo".into(),
passport_id: None,
address_id: None,
visa_id: None,
arrival_id: None,
extension_id: None,
report_id: None,
reentry_permit_id: None,
work_permit_id: None,
dated_on: None,
note: String::new(),
file_name: "IMG_2041.JPG".into(),
content_type: "image/jpeg".into(),
size_bytes: 10,
sha256: "0".repeat(64),
uploaded_by: "local".into(),
uploaded_at: at,
updated_at: at,
back_of: None,
};
// 20:00 UTC is the next day in Chiang Mai
assert_eq!(
download_name("MUSTERMANN Erika", &d),
"MUSTERMANN Erika - Photo, 4 x 6 cm - 2026-11-19.jpg"
);
assert_eq!(
download_name("A/B: C", &d).split(" - ").next(),
Some("A-B- C")
);
let h = disposition("inline", "Müller - TDAC.pdf");
let s = h.to_str().unwrap();
assert!(
s.starts_with("inline; filename=\"M_ller - TDAC.pdf\""),
"{s}"
);
assert!(
s.contains("filename*=UTF-8''M%C3%BCller%20-%20TDAC.pdf"),
"{s}"
);
}
}