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

358 lines
10 KiB
Rust

//! Pages for the records of a stay: the person's "Visa and stay" tab, one
//! form for every kind (`records::Kind`), and the person's Activity tab.
use std::sync::Arc;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response};
use minijinja::context;
use sqlx::PgPool;
use super::people::{PersonView, load_person};
use super::{AppState, Res, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::countries;
use crate::dates;
use crate::deadlines;
use crate::forms::{Errors, Fields};
use crate::records::{self, Kind, Options, Values};
use crate::session::User;
use crate::{companies, people};
/// Suggestions for the text fields with a `<datalist>`.
pub fn datalists() -> minijinja::Value {
context! {
ports => records::PORTS,
offices => records::OFFICES,
provinces => countries::PROVINCES,
}
}
/// The choices of a person's forms. `all_companies` names archived companies
/// too (to show records); otherwise only active ones and `keep_company`.
pub async fn options(
db: &PgPool,
person: i64,
all_companies: bool,
keep_company: Option<i64>,
) -> anyhow::Result<Options> {
let passports = people::passports(db, person)
.await?
.iter()
.map(|p| {
let country = countries::name(&p.issuing_country).unwrap_or(&p.issuing_country);
(p.id.to_string(), format!("{} ({country})", p.number))
})
.collect();
let visas = records::list(db, &records::VISAS, person)
.await?
.iter()
.map(|r| (r.id.to_string(), records::visa_choice(r)))
.collect();
let companies = if all_companies {
companies::names(db).await?
} else {
companies::choices(db, keep_company).await?
};
Ok(Options {
passports,
visas,
companies,
..Options::default()
})
}
fn company_of(v: &Values) -> Option<i64> {
v.get("company_id").and_then(|c| c.parse().ok())
}
pub async fn stay(st: Arc<AppState>, user: User, id: i64) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let today = dates::today();
let opts = options(&st.db, id, true, None).await?;
let mut sections = Vec::new();
for kind in records::STAY {
let shown: Vec<records::Shown> = records::list(&st.db, kind, id)
.await?
.iter()
.map(|r| records::show(kind, r, &opts, today))
.collect();
sections.push(context! {
slug => kind.slug,
title => kind.title,
one => kind.one,
records => shown,
});
}
let assessment = deadlines::for_person(&st.db, id, today).await?;
let docs = super::documents::chips(&st, id).await?;
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let title = format!("Visa and stay: {}", view.name);
Ok(page(
&st,
&user,
"stay.html",
&title,
"people",
StatusCode::OK,
context! {
p => view,
tab => "stay",
sections,
docs,
stay => assessment.stay,
deadlines => assessment.items,
},
))
}
pub async fn person_activity(st: Arc<AppState>, user: User, id: i64) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let items = audit::recent(&st.db, Some(id), 300).await?;
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let title = format!("Activity: {}", view.name);
Ok(page(
&st,
&user,
"person_activity.html",
&title,
"people",
StatusCode::OK,
context! { p => view, tab => "activity", items },
))
}
#[allow(clippy::too_many_arguments)]
fn form_page(
st: &AppState,
user: &User,
kind: &Kind,
p: &PersonView,
record: Option<i64>,
values: &Values,
errors: &Errors,
opts: &Options,
status: StatusCode,
) -> Response {
let base = format!("/people/{}/{}", p.id, kind.slug);
let (heading, mode, action) = match record {
Some(r) => (
format!("Edit the {}", kind.one),
"edit",
format!("{base}/{r}"),
),
None => (format!("New {}", kind.one), "new", base),
};
let title = format!("{heading}: {}", p.name);
page(
st,
user,
"record_form.html",
&title,
"people",
status,
context! {
p,
tab => "stay",
heading,
one => kind.one,
lead => kind.lead,
mode,
action,
fields => records::form_fields(kind, opts),
values,
errors,
cancel => format!("/people/{}/stay#{}", p.id, kind.slug),
..datalists()
},
)
}
/// Sensible first values: the current passport, the employer, Chiang Mai.
fn defaults(kind: &Kind, view: &PersonView, opts: &Options) -> Values {
let mut v = Values::new();
let first_passport = opts.passports.first().map(|(id, _)| id.clone());
match kind.slug {
"arrivals" => {
if let Some(pp) = first_passport {
v.insert("passport_id".into(), pp);
}
}
"visas" => {
if let Some(pp) = first_passport {
v.insert("passport_id".into(), pp);
}
}
"extensions" => {
v.insert("office".into(), "Chiang Mai Immigration Office".into());
v.insert("fee_thb".into(), "1900".into());
}
"reentry-permits" => {
v.insert("office".into(), "Chiang Mai Immigration Office".into());
}
"work-permits" => {
if let Some(c) = view.employer_id {
v.insert("company_id".into(), c.to_string());
}
v.insert("position".into(), String::new());
}
_ => {}
}
v
}
pub async fn new_form(kind: &'static Kind, st: Arc<AppState>, user: User, id: i64) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let opts = options(&st.db, id, false, view.employer_id).await?;
let values = defaults(kind, &view, &opts);
Ok(form_page(
&st,
&user,
kind,
&view,
None,
&values,
&Errors::new(),
&opts,
StatusCode::OK,
))
}
fn entry<'a>(
user: &'a User,
action: Action,
kind: &Kind,
record: i64,
person: i64,
fields: &'a [String],
) -> Entry<'a> {
Entry {
actor: &user.login,
action,
entity: kind.entity,
entity_id: Some(record),
person_id: Some(person),
company_id: None,
fields,
}
}
fn back(kind: &Kind, person: i64) -> Response {
Redirect::to(&format!("/people/{person}/stay#{}", kind.slug)).into_response()
}
pub async fn create(kind: &'static Kind, st: Arc<AppState>, user: User, id: i64, f: Fields) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let values = records::read(kind, &f);
let opts = options(&st.db, id, false, None).await?;
let errors = records::validate(kind, &values, &opts);
if !errors.is_empty() {
return Ok(form_page(
&st,
&user,
kind,
&view,
None,
&values,
&errors,
&opts,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
let mut tx = st.db.begin().await?;
let rid = records::create(&mut tx, kind, Some(id), &values).await?;
audit::record(&mut *tx, &entry(&user, Action::Create, kind, rid, id, &[])).await?;
tx.commit().await?;
Ok(back(kind, id))
}
pub async fn edit_form(
kind: &'static Kind,
st: Arc<AppState>,
user: User,
id: i64,
rid: i64,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let Some(r) = records::get(&st.db, kind, Some(id), rid).await? else {
return Ok(not_found_page(&st));
};
let opts = options(&st.db, id, false, company_of(&r.values)).await?;
audit::viewed(&st.db, &user.login, kind.entity, rid, id).await?;
Ok(form_page(
&st,
&user,
kind,
&view,
Some(rid),
&r.values,
&Errors::new(),
&opts,
StatusCode::OK,
))
}
pub async fn update(
kind: &'static Kind,
st: Arc<AppState>,
user: User,
id: i64,
rid: i64,
f: Fields,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let mut tx = st.db.begin().await?;
let Some(old) = records::get_for_update(&mut tx, kind, Some(id), rid).await? else {
return Ok(not_found_page(&st));
};
let values = records::read(kind, &f);
let opts = options(&st.db, id, false, company_of(&old.values)).await?;
let errors = records::validate(kind, &values, &opts);
if !errors.is_empty() {
return Ok(form_page(
&st,
&user,
kind,
&view,
Some(rid),
&values,
&errors,
&opts,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
let changed = records::changed(kind, &old.values, &values);
if !changed.is_empty() {
records::update(&mut tx, kind, Some(id), rid, &values).await?;
audit::record(
&mut *tx,
&entry(&user, Action::Update, kind, rid, id, &changed),
)
.await?;
}
tx.commit().await?;
Ok(back(kind, id))
}
pub async fn delete(kind: &'static Kind, st: Arc<AppState>, user: User, id: i64, rid: i64) -> Res {
let mut tx = st.db.begin().await?;
if !records::delete(&mut tx, kind, id, rid).await? {
return Ok(not_found_page(&st));
}
audit::record(&mut *tx, &entry(&user, Action::Delete, kind, rid, id, &[])).await?;
tx.commit().await?;
Ok(back(kind, id))
}