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

756 lines
23 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),
/// A client of the legal practice: the files of their contracts.
Client(i64),
}
impl Owner {
pub fn person(self) -> Option<i64> {
match self {
Owner::Person(id) => Some(id),
_ => None,
}
}
pub fn company(self) -> Option<i64> {
match self {
Owner::Company(id) => Some(id),
_ => None,
}
}
pub fn client(self) -> Option<i64> {
match self {
Owner::Client(id) => Some(id),
_ => 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"),
Owner::Client(id) => format!("/clients/{id}/documents"),
}
}
pub fn kinds(self) -> &'static [Kind] {
match self {
Owner::Person(_) => PERSON_KINDS,
Owner::Company(_) => COMPANY_KINDS,
Owner::Client(_) => CLIENT_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("id-card", "ID card (pink card or other)", None),
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),
];
/// A client's documents: the files of their contracts' versions.
pub const CLIENT_KINDS: &[Kind] = &[
k("contract", "Contract version", None),
k("other", "Other", None),
];
/// The kinds that are cards with two sides: uploaded as two pictures at
/// once, the first is the front and the second the back, and the pack
/// prints both on one A4 sheet.
pub const CARD_KINDS: &[&str] = &["id-card", "work-permit"];
pub fn is_card(kind: &str) -> bool {
CARD_KINDS.contains(&kind)
}
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>,
/// The front this document is the back of (a card's two sides).
pub back_of: Option<i64>,
}
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)
};
// a card's back sorts as its front, right after it
let front = |d: &Document| d.back_of.unwrap_or(d.id);
let fronts: std::collections::HashMap<i64, Option<NaiveDate>> =
docs.iter().map(|d| (d.id, d.dated_on)).collect();
let dated = |d: &Document| match d.back_of {
Some(f) => fronts.get(&f).copied().unwrap_or(d.dated_on),
None => d.dated_on,
};
docs.sort_by(|a, b| {
rank(a)
.cmp(&rank(b))
.then(dated(b).cmp(&dated(a)))
.then(front(b).cmp(&front(a)))
.then(a.back_of.is_some().cmp(&b.back_of.is_some()))
});
docs
}
/// Makes `back` the back side of `front`.
pub async fn set_back(tx: &mut Transaction<'_, Postgres>, back: i64, front: i64) -> Result<()> {
sqlx::query("UPDATE documents SET back_of = $2 WHERE id = $1")
.bind(back)
.bind(front)
.execute(&mut **tx)
.await?;
Ok(())
}
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 AND client_id IS NOT DISTINCT FROM $3",
)
.bind(owner.person())
.bind(owner.company())
.bind(owner.client())
.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 AND client_id IS NOT DISTINCT FROM $4",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.bind(owner.client())
.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 \
AND client_id IS NOT DISTINCT FROM $4 ORDER BY id LIMIT 1",
)
.bind(sha256)
.bind(owner.person())
.bind(owner.company())
.bind(owner.client())
.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(
conn: &mut sqlx::PgConnection,
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, client_id) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, \
$19) 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)
.bind(owner.client())
.fetch_one(conn)
.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 AND client_id IS NOT DISTINCT FROM $15",
)
.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)
.bind(owner.client())
.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 AND client_id IS NOT DISTINCT FROM $4",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.bind(owner.client())
.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");
}
}