Files
visa/src/documents.rs
T
grabowski d0e13dffd2
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 1m0s
CI / release (push) Skipped
Agreements the client signs on the link (task 7.6)
Built into the app rather than a separate signing service: any number of
agreements (the processing of the client's data first, legal services
and consultations later), each in versions whose text never changes.

- Staff (Agreements in the sidebar, src/web/agreements.rs): paste the
  lawyers' text (empty line = paragraph, "# " heading, "- " list item),
  preview it as the client reads it, publish version 1; a changed text is
  the next version, the same text again is refused, and the database
  refuses any change to a published one (migrations/0007, trigger).
  Switch an agreement off and links stop asking for it.
- Client: every active agreement is the first step of every link. The
  client reads it, ticks that they accept, types their name and signs
  with a finger or the mouse (static/signature.js; a PNG of the pad). A
  text changed while they read it is refused. A new version is asked for
  again at the next link.
- The signed copy (src/agreements/pdf.rs, Sarabun so Thai prints, long
  Thai words cut without parting marks from their letter): the text, the
  name, the record, the time, the drawing, the link, the forwarded
  address, the browser and the text's SHA-256; kept as the person's
  encrypted document of kind "agreement", all in one transaction with the
  signature and the audit rows (actor link N).
- The person's page shows each agreement's state (signed, not signed, to
  sign again) and every signed copy.
- Phones: the section row now scrolls sideways instead of wrapping, so it
  keeps one height with five sections and Sign out.
- Demo data: an invented agreement with a Thai paragraph.

Checks: fmt, clippy; 105 unit and 56 integration tests (tests/agreements.rs:
versions that never change, signing with a drawing, address and browser
recorded, the PDF, signing again after a change, a stale version refused,
switched off); layout check light/dark desk/phone on the agreement pages,
the client's agreement page, the person page and the people list: no
problems; a drawn signature in Edge at 390x844 signed and printed.
2026-11-20 20:18:59 +07:00

702 lines
21 KiB
Rust

//! Documents: scans and photos of a person's papers, and the company
//! documents the extension packs need. A row holds what is known about a
//! file; the file itself lies encrypted in the store (`files.rs`), on the
//! server a bucket of the fleet's Garage. A
//! person's document may belong to one of their records (a passport, an
//! arrival, a 90-day report ...), and then shows next to that record too.
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use anyhow::{Context, Result, bail, ensure};
use chrono::{DateTime, NaiveDate, Utc};
use sqlx::{PgPool, Postgres, Transaction};
use crate::files::{self, Store};
use crate::s3::Put;
/// Whose document it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Owner {
Person(i64),
Company(i64),
}
impl Owner {
pub fn person(self) -> Option<i64> {
match self {
Owner::Person(id) => Some(id),
Owner::Company(_) => None,
}
}
pub fn company(self) -> Option<i64> {
match self {
Owner::Company(id) => Some(id),
Owner::Person(_) => None,
}
}
/// The address of its documents' pages.
pub fn base(self) -> String {
match self {
Owner::Person(id) => format!("/people/{id}/documents"),
Owner::Company(id) => format!("/companies/{id}/documents"),
}
}
pub fn kinds(self) -> &'static [Kind] {
match self {
Owner::Person(_) => PERSON_KINDS,
Owner::Company(_) => COMPANY_KINDS,
}
}
}
/// A kind of document; `record` is the kind of record it usually belongs to.
#[derive(Debug)]
pub struct Kind {
pub slug: &'static str,
pub label: &'static str,
pub record: Option<&'static str>,
}
const fn k(slug: &'static str, label: &'static str, record: Option<&'static str>) -> Kind {
Kind {
slug,
label,
record,
}
}
/// In the order of the Non-B pack (docs/PLAN.md).
pub const PERSON_KINDS: &[Kind] = &[
k("photo", "Photo, 4 x 6 cm", None),
k(
"passport-photo-page",
"Passport photo page",
Some("passports"),
),
k("visa", "Visa", Some("visas")),
k("arrival-stamp", "Arrival stamp", Some("arrivals")),
k("tdac", "TDAC", Some("arrivals")),
k("extension-stamp", "Extension stamp", Some("extensions")),
k("reentry-permit", "Re-entry permit", Some("reentry-permits")),
k(
"ninety-day-receipt",
"90-day report receipt",
Some("reports"),
),
k("tm30-receipt", "TM.30 receipt", Some("addresses")),
k("work-permit", "Work permit", Some("work-permits")),
k("pnd91", "Income tax return (PND.91)", None),
// made by the app when the client signs through their link
k("agreement", "Signed agreement", None),
k("other", "Other", None),
];
/// The company documents of the Non-B pack, in its order.
pub const COMPANY_KINDS: &[Kind] = &[
k("company-certificate", "Company certificate", None),
k("shareholders", "List of shareholders (BOJ.5)", None),
k("balance-sheet", "Balance sheet with PND.50", None),
k("pnd1", "Withholding tax (PND.1)", None),
k("sps1-10", "Social security (SPS 1-10)", None),
k("pp30", "VAT return (PP.30)", None),
k("map", "Map to the office", None),
k("office-photo", "Photo of the office", None),
k("other", "Other", None),
];
pub fn kind(owner: Owner, slug: &str) -> Option<&'static Kind> {
owner.kinds().iter().find(|k| k.slug == slug)
}
pub fn kind_label(owner: Owner, slug: &str) -> String {
kind(owner, slug).map_or_else(|| slug.to_string(), |k| k.label.to_string())
}
/// The first kind that belongs to a kind of record: what a document added
/// from that record is.
pub fn kind_for_link(link: &str) -> Option<&'static Kind> {
PERSON_KINDS.iter().find(|k| k.record == Some(link))
}
/// A kind of record a person's document may belong to; `slug` is the one of
/// its pages (`/people/{id}/arrivals/...`).
#[derive(Debug)]
pub struct Link {
pub slug: &'static str,
pub column: &'static str,
pub table: &'static str,
pub title: &'static str,
}
const fn l(
slug: &'static str,
column: &'static str,
table: &'static str,
title: &'static str,
) -> Link {
Link {
slug,
column,
table,
title,
}
}
pub const LINKS: &[Link] = &[
l("passports", "passport_id", "passports", "Passports"),
l("visas", "visa_id", "visas", "Visas"),
l("arrivals", "arrival_id", "arrivals", "Arrivals"),
l(
"extensions",
"extension_id",
"extensions",
"Extensions of stay",
),
l(
"reentry-permits",
"reentry_permit_id",
"reentry_permits",
"Re-entry permits",
),
l(
"reports",
"report_id",
"ninety_day_reports",
"90-day reports",
),
l(
"addresses",
"address_id",
"addresses",
"Addresses in Thailand",
),
l(
"work-permits",
"work_permit_id",
"work_permits",
"Work permits",
),
];
/// `arrivals:7`, as the forms send it.
pub fn parse_link(value: &str) -> Option<(&'static Link, i64)> {
let (slug, id) = value.split_once(':')?;
let link = LINKS.iter().find(|l| l.slug == slug)?;
let id: i64 = id.parse().ok().filter(|&n| n > 0)?;
Some((link, id))
}
pub fn link_value(link: Option<(&Link, i64)>) -> String {
link.map(|(l, id)| format!("{}:{id}", l.slug))
.unwrap_or_default()
}
#[derive(Clone, Debug, sqlx::FromRow)]
pub struct Document {
pub id: i64,
pub person_id: Option<i64>,
pub company_id: Option<i64>,
pub kind: String,
pub passport_id: Option<i64>,
pub address_id: Option<i64>,
pub visa_id: Option<i64>,
pub arrival_id: Option<i64>,
pub extension_id: Option<i64>,
pub report_id: Option<i64>,
pub reentry_permit_id: Option<i64>,
pub work_permit_id: Option<i64>,
pub dated_on: Option<NaiveDate>,
pub note: String,
pub file_name: String,
pub content_type: String,
pub size_bytes: i32,
pub sha256: String,
pub uploaded_by: String,
pub uploaded_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Document {
pub fn owner(&self) -> Owner {
match (self.person_id, self.company_id) {
(Some(p), _) => Owner::Person(p),
(None, Some(c)) => Owner::Company(c),
// the table's check rules this out
(None, None) => Owner::Person(0),
}
}
/// The record it belongs to, if any.
pub fn link(&self) -> Option<(&'static Link, i64)> {
let ids = [
self.passport_id,
self.visa_id,
self.arrival_id,
self.extension_id,
self.reentry_permit_id,
self.report_id,
self.address_id,
self.work_permit_id,
];
LINKS
.iter()
.zip(ids)
.find_map(|(l, id)| id.map(|id| (l, id)))
}
}
/// What the forms set about a document.
#[derive(Clone, Debug, Default)]
pub struct Meta {
pub kind: String,
pub link: Option<(&'static Link, i64)>,
pub dated_on: Option<NaiveDate>,
pub note: String,
}
impl Meta {
pub fn of(d: &Document) -> Meta {
Meta {
kind: d.kind.clone(),
link: d.link(),
dated_on: d.dated_on,
note: d.note.clone(),
}
}
/// The id for each link column, in the order of `LINKS`.
fn link_ids(&self) -> [Option<i64>; 8] {
let mut ids = [None; 8];
if let Some((link, id)) = self.link
&& let Some(i) = LINKS.iter().position(|l| l.slug == link.slug)
{
ids[i] = Some(id);
}
ids
}
/// The names of the fields a new document sets, for the audit log.
pub fn set_fields(&self) -> Vec<String> {
let mut out = vec!["kind".to_string(), "file".to_string()];
if let Some((link, _)) = self.link {
out.push(link.column.to_string());
}
if self.dated_on.is_some() {
out.push("dated_on".into());
}
if !self.note.is_empty() {
out.push("note".into());
}
out
}
/// The names of the fields a change touches.
pub fn changed(&self, new: &Meta) -> Vec<String> {
let mut out = BTreeSet::new();
if self.kind != new.kind {
out.insert("kind".to_string());
}
let (a, b) = (self.link_ids(), new.link_ids());
for (i, link) in LINKS.iter().enumerate() {
if a[i] != b[i] {
out.insert(link.column.to_string());
}
}
if self.dated_on != new.dated_on {
out.insert("dated_on".into());
}
if self.note != new.note {
out.insert("note".into());
}
out.into_iter().collect()
}
}
/// The file of a new document, as checked.
pub struct NewFile<'a> {
pub name: &'a str,
pub content_type: &'static str,
pub size: i32,
pub sha256: &'a str,
}
/// The newest first within each kind, the kinds in the pack's order.
fn sorted(owner: Owner, mut docs: Vec<Document>) -> Vec<Document> {
let rank = |d: &Document| {
owner
.kinds()
.iter()
.position(|k| k.slug == d.kind)
.unwrap_or(usize::MAX)
};
docs.sort_by(|a, b| {
rank(a)
.cmp(&rank(b))
.then(b.dated_on.cmp(&a.dated_on))
.then(b.id.cmp(&a.id))
});
docs
}
pub async fn list(db: &PgPool, owner: Owner) -> Result<Vec<Document>> {
let docs: Vec<Document> = sqlx::query_as(
"SELECT * FROM documents \
WHERE person_id IS NOT DISTINCT FROM $1 AND company_id IS NOT DISTINCT FROM $2",
)
.bind(owner.person())
.bind(owner.company())
.fetch_all(db)
.await?;
Ok(sorted(owner, docs))
}
pub async fn get(db: &PgPool, owner: Owner, id: i64) -> Result<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents WHERE id = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.fetch_optional(db)
.await?)
}
/// The same file uploaded before for the same person or company.
pub async fn same_file(db: &PgPool, owner: Owner, sha256: &str) -> Result<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents WHERE sha256 = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3 \
ORDER BY id LIMIT 1",
)
.bind(sha256)
.bind(owner.person())
.bind(owner.company())
.fetch_optional(db)
.await?)
}
/// Whether the record is one of this person's.
pub async fn link_is_theirs(db: &PgPool, person: i64, link: &Link, id: i64) -> Result<bool> {
// the table name comes from LINKS, never from the form
let sql = format!(
"SELECT EXISTS (SELECT 1 FROM {} WHERE id = $1 AND person_id = $2)",
link.table
);
Ok(sqlx::query_scalar(&sql)
.bind(id)
.bind(person)
.fetch_one(db)
.await?)
}
pub async fn insert(
tx: &mut Transaction<'_, Postgres>,
owner: Owner,
meta: &Meta,
file: &NewFile<'_>,
by: &str,
) -> Result<i64> {
let ids = meta.link_ids();
let id = sqlx::query_scalar(
"INSERT INTO documents (person_id, company_id, kind, passport_id, visa_id, \
arrival_id, extension_id, reentry_permit_id, report_id, address_id, work_permit_id, \
dated_on, note, file_name, content_type, size_bytes, sha256, uploaded_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
RETURNING id",
)
.bind(owner.person())
.bind(owner.company())
.bind(&meta.kind)
.bind(ids[0])
.bind(ids[1])
.bind(ids[2])
.bind(ids[3])
.bind(ids[4])
.bind(ids[5])
.bind(ids[6])
.bind(ids[7])
.bind(meta.dated_on)
.bind(&meta.note)
.bind(file.name)
.bind(file.content_type)
.bind(file.size)
.bind(file.sha256)
.bind(by)
.fetch_one(&mut **tx)
.await?;
Ok(id)
}
pub async fn update(
tx: &mut Transaction<'_, Postgres>,
owner: Owner,
id: i64,
meta: &Meta,
) -> Result<()> {
let ids = meta.link_ids();
sqlx::query(
"UPDATE documents SET kind = $4, passport_id = $5, visa_id = $6, arrival_id = $7, \
extension_id = $8, reentry_permit_id = $9, report_id = $10, address_id = $11, \
work_permit_id = $12, dated_on = $13, note = $14, updated_at = now() \
WHERE id = $1 AND person_id IS NOT DISTINCT FROM $2 \
AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.bind(&meta.kind)
.bind(ids[0])
.bind(ids[1])
.bind(ids[2])
.bind(ids[3])
.bind(ids[4])
.bind(ids[5])
.bind(ids[6])
.bind(ids[7])
.bind(meta.dated_on)
.bind(&meta.note)
.execute(&mut **tx)
.await?;
Ok(())
}
pub async fn delete(tx: &mut Transaction<'_, Postgres>, owner: Owner, id: i64) -> Result<bool> {
let n = sqlx::query(
"DELETE FROM documents WHERE id = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.execute(&mut **tx)
.await?
.rows_affected();
Ok(n == 1)
}
/// The name a browser sent, without any path, control characters or
/// excess length.
pub fn clean_name(raw: &str) -> String {
let base = raw.rsplit(['/', '\\']).next().unwrap_or_default();
let name: String = base.chars().filter(|c| !c.is_control()).take(150).collect();
let name = name.trim();
if name.is_empty() {
"file".into()
} else {
name.to_string()
}
}
/// What `visa files-check` found.
#[derive(Debug, Default)]
pub struct Check {
pub documents: usize,
pub problems: Vec<String>,
}
/// Reads every document's file back, decrypts it and compares it with the
/// size and checksum recorded at the upload; lists files that belong to no
/// document.
pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
let rows = uploads(db).await?;
let entries = store.entries().await?;
let mut out = Check {
documents: rows.len(),
..Check::default()
};
for (id, (size, sha)) in &rows {
match store.get(*id).await {
Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {}
Ok(_) => out.problems.push(format!(
"document {id}: the file does not match the size and checksum of its upload"
)),
Err(e) => out.problems.push(format!("document {id}: {e:#}")),
}
}
for (id, _) in entries
.files
.iter()
.filter(|(id, _)| !rows.contains_key(id))
{
out.problems.push(format!(
"{}: a file without its document",
files::file_name(*id)
));
}
for name in entries.other {
out.problems
.push(format!("{name}: not a file of the store"));
}
Ok(out)
}
/// Every document's size and SHA-256 as recorded at its upload.
async fn uploads(db: &PgPool) -> Result<BTreeMap<i64, (i32, String)>> {
let rows: Vec<(i64, i32, String)> =
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id")
.fetch_all(db)
.await?;
Ok(rows
.into_iter()
.map(|(id, size, sha)| (id, (size, sha)))
.collect())
}
/// What `visa files-migrate` did.
#[derive(Debug, Default)]
pub struct Moved {
/// Files copied into the store.
pub copied: usize,
/// Files the store had already, with the same bytes.
pub there: usize,
/// Files in the directory that belong to no document, left there.
pub strays: Vec<String>,
/// Documents whose file is neither in the directory nor in the store.
pub missing: Vec<i64>,
}
/// Copies the documents' files from a files directory (where they lay
/// before the bucket, or a mirror the backups hold) into the store, as they
/// are: still encrypted. Each file is opened with the key and compared with
/// the size and checksum of its upload before it is copied, and read back
/// from the store and compared again after. A file the store has already
/// with the same bytes is counted and skipped, so the copy can run again; a
/// file the store has with other bytes, or one that does not open, stops it
/// with an error. Files of no document stay in the directory, listed.
pub async fn migrate(db: &PgPool, from: &Path, to: &Store) -> Result<Moved> {
if let Some(d) = to.dir() {
ensure!(
!files::same_dir(d, from),
"{} is the store itself: files-migrate copies from another directory",
from.display()
);
}
ensure!(from.is_dir(), "{} is not a directory", from.display());
let src = Store::in_dir(from.to_path_buf(), to.file_key().clone())?;
let rows = uploads(db).await?;
let present = src.entries().await?;
let in_dir: BTreeSet<i64> = present.files.iter().map(|(id, _)| *id).collect();
let mut out = Moved::default();
for (id, (size, sha)) in &rows {
let matches =
|bytes: &[u8]| bytes.len() == *size as usize && files::sha256_hex(bytes) == *sha;
if !in_dir.contains(id) {
if to.get_sealed(*id).await?.is_some() {
out.there += 1;
} else {
out.missing.push(*id);
}
continue;
}
let plain = src
.get(*id)
.await
.with_context(|| format!("document {id}: its file in the directory"))?;
if !matches(&plain) {
bail!(
"document {id}: the file in {} does not match the size and checksum of its upload",
from.display()
);
}
let sealed = src
.get_sealed(*id)
.await?
.with_context(|| format!("document {id}: its file went missing"))?;
match to
.put_sealed(*id, sealed)
.await
.with_context(|| format!("document {id}: copying its file"))?
{
Put::Written => out.copied += 1,
Put::Same => out.there += 1,
}
let back = to
.get(*id)
.await
.with_context(|| format!("document {id}: reading the copy back"))?;
if !matches(&back) {
bail!(
"document {id}: the copy in {} does not match its upload",
to.describe()
);
}
}
out.strays = present
.files
.iter()
.filter(|(id, _)| !rows.contains_key(id))
.map(|(id, _)| files::file_name(*id))
.chain(present.other)
.collect();
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_read_back_and_kinds_know_their_record() {
let (link, id) = parse_link("arrivals:7").unwrap();
assert_eq!((link.column, id), ("arrival_id", 7));
for bad in [
"",
"arrivals",
"arrivals:",
"arrivals:0",
"arrivals:-3",
"people:1",
"x:1",
] {
assert!(parse_link(bad).is_none(), "{bad:?}");
}
assert_eq!(link_value(Some((link, 7))), "arrivals:7");
assert_eq!(kind_for_link("arrivals").unwrap().slug, "arrival-stamp");
assert_eq!(kind_for_link("addresses").unwrap().slug, "tm30-receipt");
// every kind's record is a link, every link has a kind
for k in PERSON_KINDS {
if let Some(r) = k.record {
assert!(LINKS.iter().any(|l| l.slug == r), "{}", k.slug);
}
}
for l in LINKS {
assert!(kind_for_link(l.slug).is_some(), "{}", l.slug);
}
}
#[test]
fn the_audit_names_the_changed_fields_only() {
let (link, _) = parse_link("passports:1").unwrap();
let a = Meta {
kind: "passport-photo-page".into(),
link: Some((link, 1)),
dated_on: None,
note: String::new(),
};
assert_eq!(a.set_fields(), ["kind", "file", "passport_id"]);
assert!(a.changed(&a.clone()).is_empty());
let b = Meta {
link: parse_link("arrivals:4"),
note: "page 2".into(),
..a.clone()
};
assert_eq!(a.changed(&b), ["arrival_id", "note", "passport_id"]);
}
#[test]
fn names_lose_their_path_and_control_characters() {
assert_eq!(clean_name("C:\\Users\\x\\Scan 1.pdf"), "Scan 1.pdf");
assert_eq!(clean_name("/tmp/a/b.jpg"), "b.jpg");
assert_eq!(clean_name("pass\nport\u{7}.png"), "passport.png");
assert_eq!(clean_name(" "), "file");
assert_eq!(clean_name("../"), "file");
assert_eq!(clean_name(&"a".repeat(400)).len(), 150);
assert_eq!(clean_name("หนังสือเดินทาง.pdf"), "หนังสือเดินทาง.pdf");
}
}