Phase 2: companies, stay records, deadlines
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 22s

Companies become records of their own, and the stay in Thailand is
recorded in full; from these records the app works out each person's
deadlines (docs/PLAN.md, phase 2).

- Companies: list, page, form, archive; Thai name, the 13-digit
  registration number with its check digit verified, address and the
  director who signs. The employer is chosen from them on the person form
  and on work permits; a company's page adds people to it; the people
  list and the Deadlines page filter by employer. Migration 0002 turns
  the free-text employers into companies.
- Stay records, each one `Kind` in src/records.rs with one form, one set
  of routes and the same audit entries: arrivals and departures with the
  TDAC, extensions of stay (approved, under consideration, refused),
  90-day reports with the receipt's next date, visas, re-entry permits and
  work permits. Passports, visas and companies are chosen from the
  person's own records; the server checks the choice.
- The deadline engine (src/deadlines.rs, a pure function with a unit
  test per rule): the 90-day report from day 1 of each arrival, reset by
  a report or an extension, with the in-person and online windows and the
  in-person rule after a new passport or an extension; the extension
  window from 30 days before to the last working day; the decision to
  collect; overstay with its fine; TM.30 after each arrival; passport and
  work permit expiry; re-entry permits; visas still to be used.
- The Deadlines page at /, the person's status and deadlines on the
  Overview and the new "Visa and stay" tab, the person's Activity tab,
  and the next deadline in the people list.
- The online 90-day window ends 7 days before the due date (the plan
  said 8; the Immigration Bureau's TM.47 manual says 7).
- 69 tests: 45 unit tests and 24 integration tests.
This commit is contained in:
grabowski committed 2026-11-17 18:20:14 +07:00
1 parent 2e009700a9
commit 83bc481952
37 files changed
+5515 -142

No files matched your search

+353
View File
@@ -0,0 +1,353 @@
//! 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,
})
}
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?;
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,
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),
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))
}