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

+319
View File
@@ -0,0 +1,319 @@
//! Pages for companies: the list, a company with the people it employs, the
//! form, archiving, and adding or removing employees.
use std::sync::Arc;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Extension, Form};
use minijinja::context;
use serde::Deserialize;
use super::records::datalists;
use super::{AppState, Res, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::companies;
use crate::dates;
use crate::forms::{Errors, Fields, err, get};
use crate::records::{self, COMPANIES, Options, Values};
use crate::session::User;
#[derive(Deserialize)]
pub struct ListQuery {
#[serde(default)]
archived: Option<String>,
}
pub async fn list(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<ListQuery>,
) -> Res {
let archived = q.archived.as_deref() == Some("1");
let rows = companies::list(&st.db, archived).await?;
let (n_active, n_archived) = companies::counts(&st.db).await?;
Ok(page(
&st,
&user,
"companies.html",
if archived {
"Archived companies"
} else {
"Companies"
},
"companies",
StatusCode::OK,
context! { companies => rows, archived, n_active, n_archived },
))
}
fn company_entry<'a>(user: &'a User, action: Action, id: i64, fields: &'a [String]) -> Entry<'a> {
Entry {
actor: &user.login,
action,
entity: Entity::Company,
entity_id: Some(id),
person_id: None,
fields,
}
}
fn form_page(
st: &AppState,
user: &User,
company: Option<(i64, &str)>,
values: &Values,
errors: &Errors,
status: StatusCode,
) -> Response {
let (heading, mode, action, cancel) = match company {
Some((id, name)) => (
format!("Edit {name}"),
"edit",
format!("/companies/{id}"),
format!("/companies/{id}"),
),
None => (
"New company".to_string(),
"new",
"/companies".to_string(),
"/companies".to_string(),
),
};
page(
st,
user,
"record_form.html",
&heading,
"companies",
status,
context! {
heading,
one => "company",
lead => COMPANIES.lead,
mode,
action,
fields => records::form_fields(&COMPANIES, &Options::default()),
values,
errors,
cancel,
..datalists()
},
)
}
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
Ok(form_page(
&st,
&user,
None,
&Values::new(),
&Errors::new(),
StatusCode::OK,
))
}
async fn checked(st: &AppState, f: &Fields, id: Option<i64>) -> anyhow::Result<(Values, Errors)> {
let values = records::read(&COMPANIES, f);
let mut errors = records::validate(&COMPANIES, &values, &Options::default());
let reg = values
.get("registration_no")
.map(String::as_str)
.unwrap_or("");
if !errors.contains_key("registration_no")
&& companies::registration_taken(&st.db, reg, id).await?
{
err(
&mut errors,
"registration_no",
"Another company has this registration number.",
);
}
Ok((values, errors))
}
pub async fn create(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Form(f): Form<Fields>,
) -> Res {
let (values, errors) = checked(&st, &f, None).await?;
if !errors.is_empty() {
return Ok(form_page(
&st,
&user,
None,
&values,
&errors,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
let mut tx = st.db.begin().await?;
let id = records::create(&mut tx, &COMPANIES, None, &values).await?;
audit::record(&mut *tx, &company_entry(&user, Action::Create, id, &[])).await?;
tx.commit().await?;
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
}
pub async fn show(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else {
return Ok(not_found_page(&st));
};
let archived_at = companies::archived_at(&st.db, id).await?.flatten();
let c = companies::view(&r, archived_at);
let employees = companies::employees(&st.db, id, dates::today()).await?;
let candidates = companies::candidates(&st.db, id).await?;
let title = c.name.clone();
Ok(page(
&st,
&user,
"company.html",
&title,
"companies",
StatusCode::OK,
context! { c, employees, candidates },
))
}
pub async fn edit_form(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else {
return Ok(not_found_page(&st));
};
Ok(form_page(
&st,
&user,
Some((id, r.get("name"))),
&r.values,
&Errors::new(),
StatusCode::OK,
))
}
pub async fn update(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
let mut tx = st.db.begin().await?;
let Some(old) = records::get_for_update(&mut tx, &COMPANIES, None, id).await? else {
return Ok(not_found_page(&st));
};
let (values, errors) = checked(&st, &f, Some(id)).await?;
if !errors.is_empty() {
return Ok(form_page(
&st,
&user,
Some((id, old.get("name"))),
&values,
&errors,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
let changed = records::changed(&COMPANIES, &old.values, &values);
if !changed.is_empty() {
records::update(&mut tx, &COMPANIES, None, id, &values).await?;
audit::record(
&mut *tx,
&company_entry(&user, Action::Update, id, &changed),
)
.await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
}
async fn set_archived(st: &AppState, user: &User, id: i64, archived: bool) -> Res {
if companies::archived_at(&st.db, id).await?.is_none() {
return Ok(not_found_page(st));
}
let mut tx = st.db.begin().await?;
if companies::set_archived(&mut tx, id, archived).await? {
let action = if archived {
Action::Archive
} else {
Action::Restore
};
audit::record(&mut *tx, &company_entry(user, action, id, &[])).await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
}
pub async fn archive(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
set_archived(&st, &user, id, true).await
}
pub async fn restore(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
set_archived(&st, &user, id, false).await
}
fn employer_changed<'a>(user: &'a User, person: i64, fields: &'a [String]) -> Entry<'a> {
Entry {
actor: &user.login,
action: Action::Update,
entity: Entity::Person,
entity_id: Some(person),
person_id: Some(person),
fields,
}
}
/// Adds the person chosen in the selection as an employee.
pub async fn hire(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
if companies::archived_at(&st.db, id).await?.is_none() {
return Ok(not_found_page(&st));
}
let chosen = get(&f, "person");
let allowed = companies::candidates(&st.db, id).await?;
let Some(person) = allowed
.iter()
.find(|(pid, _)| *pid == chosen)
.and_then(|(pid, _)| pid.parse::<i64>().ok())
else {
return Ok(Redirect::to(&format!("/companies/{id}#people")).into_response());
};
let mut tx = st.db.begin().await?;
if companies::hire(&mut tx, id, person).await? {
let fields = ["employer".to_string()];
audit::record(&mut *tx, &employer_changed(&user, person, &fields)).await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/companies/{id}#people")).into_response())
}
pub async fn release(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, person)): Path<(i64, i64)>,
) -> Res {
let mut tx = st.db.begin().await?;
if companies::release(&mut tx, id, person).await? {
let fields = ["employer".to_string()];
audit::record(&mut *tx, &employer_changed(&user, person, &fields)).await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/companies/{id}#people")).into_response())
}
+113
View File
@@ -0,0 +1,113 @@
//! The Deadlines page at /: every person's coming deadlines, the most
//! urgent first.
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Query, State};
use axum::http::StatusCode;
use chrono::TimeDelta;
use minijinja::context;
use serde::{Deserialize, Serialize};
use super::{AppState, Res, page};
use crate::companies;
use crate::dates;
use crate::deadlines::{self, Deadline};
use crate::session::User;
#[derive(Deserialize)]
pub struct DashQuery {
/// "1": also what lies beyond the next 90 days.
#[serde(default)]
all: Option<String>,
/// A company's id: only the people it employs.
#[serde(default)]
company: Option<String>,
}
#[derive(Debug, Serialize)]
struct Row {
person_id: i64,
person: String,
employer: String,
d: Deadline,
q: String,
}
/// How far ahead the page looks unless asked for everything; anything
/// overdue or close (bad, warn) shows regardless.
const HORIZON_DAYS: i64 = 90;
pub async fn page_handler(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<DashQuery>,
) -> Res {
let today = dates::today();
let all = q.all.as_deref() == Some("1");
let company: Option<i64> = q.company.as_deref().and_then(|c| c.parse().ok());
let people: Vec<(i64, String, String, String, Option<String>)> = sqlx::query_as(
"SELECT p.id, p.surname, p.first_name, p.middle_name, c.name \
FROM people p LEFT JOIN companies c ON c.id = p.employer_id \
WHERE p.archived_at IS NULL AND ($1::bigint IS NULL OR p.employer_id = $1)",
)
.bind(company)
.fetch_all(&st.db)
.await?;
let ids: Vec<i64> = people.iter().map(|p| p.0).collect();
let mut found = deadlines::for_people(&st.db, &ids, today).await?;
let horizon = today + TimeDelta::days(HORIZON_DAYS);
let mut rows = Vec::new();
for (id, surname, first, middle, employer) in &people {
let Some(a) = found.remove(id) else { continue };
let given = if middle.is_empty() {
first.clone()
} else {
format!("{first} {middle}")
};
let person = format!("{}, {given}", surname.to_uppercase());
let employer = employer.clone().unwrap_or_default();
for d in a.items {
let Some(due) = d.due else { continue };
let urgent = matches!(d.level, "bad" | "warn");
if !all && !urgent && due > horizon {
continue;
}
let q = format!("{person} {employer} {} {}", d.title, d.label).to_lowercase();
rows.push(Row {
person_id: *id,
person: person.clone(),
employer: employer.clone(),
d,
q,
});
}
}
rows.sort_by(|x, y| {
deadlines::rank(x.d.level)
.cmp(&deadlines::rank(y.d.level))
.then(x.d.due.cmp(&y.d.due))
.then(x.person.cmp(&y.person))
});
let overdue = rows.iter().filter(|r| r.d.level == "bad").count();
let soon = rows.iter().filter(|r| r.d.level == "warn").count();
Ok(page(
&st,
&user,
"dashboard.html",
"Deadlines",
"deadlines",
StatusCode::OK,
context! {
rows,
overdue,
soon,
all,
n_people => people.len(),
horizon_days => HORIZON_DAYS,
companies => companies::choices(&st.db, company).await?,
company => company.map(|c| c.to_string()).unwrap_or_default(),
},
))
}
+91 -4
View File
@@ -2,23 +2,27 @@
pub mod activity;
pub mod auth;
pub mod companies;
pub mod dashboard;
pub mod people;
pub mod records;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use axum::Router;
use axum::body::Body;
use axum::extract::{Path, Request, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use axum::{Extension, Form, Router};
use minijinja::{Environment, Value, context};
use sqlx::PgPool;
use tracing::{error, info, warn};
use crate::config::{Auth, Config};
use crate::forms::Fields;
use crate::session::{self, Flows, SESSION_COOKIE, User};
use crate::{VERSION, countries, dates, embedded, oidc};
@@ -113,9 +117,10 @@ pub fn spawn_background(st: Arc<AppState>) {
}
pub fn router(st: Arc<AppState>) -> Router {
use companies as c;
use people as p;
Router::new()
.route("/", get(|| async { Redirect::to("/people") }))
let mut r = Router::new()
.route("/", get(dashboard::page_handler))
.route("/people", get(p::list).post(p::create))
.route("/people/new", get(p::new_form))
.route("/people/{id}", get(p::show).post(p::update))
@@ -138,7 +143,89 @@ pub fn router(st: Arc<AppState>) -> Router {
"/people/{id}/addresses/{aid}/delete",
post(p::address_delete),
)
.route("/activity", get(activity::page))
.route(
"/people/{id}/stay",
get(
|State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>| records::stay(st, user, id),
),
)
.route(
"/people/{id}/activity",
get(
|State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>| records::person_activity(st, user, id),
),
)
.route("/companies", get(c::list).post(c::create))
.route("/companies/new", get(c::new_form))
.route("/companies/{id}", get(c::show).post(c::update))
.route("/companies/{id}/edit", get(c::edit_form))
.route("/companies/{id}/archive", post(c::archive))
.route("/companies/{id}/restore", post(c::restore))
.route("/companies/{id}/employees", post(c::hire))
.route("/companies/{id}/employees/{pid}/remove", post(c::release));
// Every kind of stay record: /people/{id}/<slug>, .../new,
// .../{rid}, .../{rid}/edit and .../{rid}/delete.
for kind in crate::records::STAY {
let base = format!("/people/{{id}}/{}", kind.slug);
r = r
.route(
&base,
post(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>| {
records::create(kind, st, user, id, f)
},
),
)
.route(
&format!("{base}/new"),
get(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>| {
records::new_form(kind, st, user, id)
},
),
)
.route(
&format!("{base}/{{rid}}"),
post(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, rid)): Path<(i64, i64)>,
Form(f): Form<Fields>| {
records::update(kind, st, user, id, rid, f)
},
),
)
.route(
&format!("{base}/{{rid}}/edit"),
get(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, rid)): Path<(i64, i64)>| {
records::edit_form(kind, st, user, id, rid)
},
),
)
.route(
&format!("{base}/{{rid}}/delete"),
post(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, rid)): Path<(i64, i64)>| {
records::delete(kind, st, user, id, rid)
},
),
);
}
r.route("/activity", get(activity::page))
.route("/login", get(auth::login))
.route("/auth/callback", get(auth::callback))
.route("/logout", post(auth::logout))
+96 -21
View File
@@ -21,6 +21,7 @@ use crate::people::{
PersonInput, SEXES, TITLES,
};
use crate::session::User;
use crate::{companies, deadlines};
// ----------------------------------------------------------------- views
@@ -38,7 +39,9 @@ pub struct PersonView {
pub nationality: String,
pub nationality_name: String,
pub occupation: String,
/// The employer's name.
pub employer: String,
pub employer_id: Option<i64>,
pub phone: String,
pub email: String,
pub notes: String,
@@ -48,7 +51,12 @@ pub struct PersonView {
pub updated: String,
}
fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> PersonView {
fn person_view(
p: &Person,
current_passport: Option<&str>,
employer: Option<String>,
today: NaiveDate,
) -> PersonView {
PersonView {
id: p.id,
name: p.display_name(),
@@ -64,7 +72,8 @@ fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) ->
.unwrap_or(&p.nationality)
.to_string(),
occupation: p.occupation.clone(),
employer: p.employer.clone(),
employer: employer.unwrap_or_default(),
employer_id: p.employer_id,
phone: p.phone.clone(),
email: p.email.clone(),
notes: p.notes.clone(),
@@ -133,14 +142,23 @@ fn address_view(a: &Address) -> AddressView {
}
}
/// The person with the number of their current passport, for the header
/// every page of the person shares.
async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Person, PersonView)>> {
/// The person with the number of their current passport and the name of
/// their employer, for the head every page of the person shares.
pub async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Person, PersonView)>> {
let Some(p) = people::get_person(&st.db, id).await? else {
return Ok(None);
};
let pps = people::passports(&st.db, id).await?;
let view = person_view(&p, pps.first().map(|x| x.number.as_str()), dates::today());
let employer = match p.employer_id {
Some(c) => companies::name(&st.db, c).await?,
None => None,
};
let view = person_view(
&p,
pps.first().map(|x| x.number.as_str()),
employer,
dates::today(),
);
Ok(Some((p, view)))
}
@@ -217,6 +235,9 @@ fn zone_note(m: &Mrz, errors: &mut Errors) -> Option<String> {
pub struct ListQuery {
#[serde(default)]
archived: Option<String>,
/// A company's id: only the people it employs.
#[serde(default)]
company: Option<String>,
}
pub async fn list(
@@ -224,21 +245,42 @@ pub async fn list(
Extension(user): Extension<User>,
Query(q): Query<ListQuery>,
) -> Res {
let today = dates::today();
let archived = q.archived.as_deref() == Some("1");
let rows = people::list(&st.db, archived, dates::today()).await?;
let company: Option<i64> = q.company.as_deref().and_then(|c| c.parse().ok());
let mut rows = people::list(&st.db, archived, company, today).await?;
let ids: Vec<i64> = rows.iter().map(|r| r.id).collect();
let mut found = deadlines::for_people(&st.db, &ids, today).await?;
for r in &mut rows {
r.next = found.remove(&r.id).and_then(|a| a.next().cloned());
}
let (n_active, n_archived) = people::counts(&st.db).await?;
let company_name = match company {
Some(c) => companies::name(&st.db, c).await?,
None => None,
};
let heading = match (&company_name, archived) {
(Some(n), _) => format!("People at {n}"),
(None, true) => "Archived people".to_string(),
(None, false) => "People".to_string(),
};
Ok(page(
&st,
&user,
"people.html",
if archived {
"Archived people"
} else {
"People"
},
&heading,
"people",
StatusCode::OK,
context! { people => rows, archived, n_active, n_archived },
context! {
people => rows,
archived,
n_active,
n_archived,
heading,
companies => companies::choices(&st.db, company).await?,
company => company.map(|c| c.to_string()).unwrap_or_default(),
company_name,
},
))
}
@@ -277,6 +319,7 @@ pub async fn show(
.iter()
.map(address_view)
.collect();
let assessment = deadlines::for_person(&st.db, id, today).await?;
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let recent = audit::recent(&st.db, Some(id), 6).await?;
let title = view.name.clone();
@@ -287,7 +330,15 @@ pub async fn show(
&title,
"people",
StatusCode::OK,
context! { p => view, passports, addresses, recent },
context! {
p => view,
tab => "overview",
passports,
addresses,
recent,
stay => assessment.stay,
deadlines => assessment.items,
},
))
}
@@ -300,6 +351,7 @@ fn person_form_page(
pf: &PassportForm,
errors: &Errors,
mrz_note: Option<String>,
companies: &[(String, String)],
status: StatusCode,
) -> Response {
let (title, mode, action) = match p {
@@ -317,11 +369,26 @@ fn person_form_page(
&title,
"people",
status,
context! { p, f, pf, errors, mrz_note, mode, action, ..select_lists() },
context! {
p, tab => "overview", f, pf, errors, mrz_note, mode, action, companies,
..select_lists()
},
)
}
/// The companies the employer is chosen from (the active ones and the one
/// already chosen), and their ids for the check.
async fn employer_choices(
st: &AppState,
current: Option<i64>,
) -> anyhow::Result<(Vec<(String, String)>, Vec<i64>)> {
let list = companies::choices(&st.db, current).await?;
let ids = list.iter().filter_map(|(id, _)| id.parse().ok()).collect();
Ok((list, ids))
}
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
let (companies, _) = employer_choices(&st, None).await?;
Ok(person_form_page(
&st,
&user,
@@ -330,6 +397,7 @@ pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extensio
&PassportForm::default(),
&Errors::new(),
None,
&companies,
StatusCode::OK,
))
}
@@ -340,6 +408,7 @@ pub async fn create(
Form(f): Form<Fields>,
) -> Res {
let today = dates::today();
let (companies, company_ids) = employer_choices(&st, None).await?;
let mut pf = PersonForm::from_fields(&f);
let mut ppf = PassportForm::from_fields(&f);
let mut errors = Errors::new();
@@ -360,7 +429,7 @@ pub async fn create(
}
let status = status_for(&errors);
return Ok(person_form_page(
&st, &user, None, &pf, &ppf, &errors, note, status,
&st, &user, None, &pf, &ppf, &errors, note, &companies, status,
));
}
@@ -368,7 +437,7 @@ pub async fn create(
pf.take_mrz(m, false);
ppf.take_mrz(m, false);
}
let person = pf.validate(today);
let person = pf.validate(today, &company_ids);
let passport = (!ppf.is_blank()).then(|| ppf.validate(zone.as_ref()));
for e in [
person.as_ref().err(),
@@ -390,6 +459,7 @@ pub async fn create(
&ppf,
&errors,
None,
&companies,
StatusCode::UNPROCESSABLE_ENTITY,
));
};
@@ -412,6 +482,7 @@ pub async fn create(
&ppf,
&errors,
None,
&companies,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
@@ -441,6 +512,7 @@ pub async fn edit_form(
let Some((p, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let (companies, _) = employer_choices(&st, p.employer_id).await?;
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
Ok(person_form_page(
&st,
@@ -450,6 +522,7 @@ pub async fn edit_form(
&PassportForm::default(),
&Errors::new(),
None,
&companies,
StatusCode::OK,
))
}
@@ -460,11 +533,12 @@ pub async fn update(
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
let Some((p, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let (companies, company_ids) = employer_choices(&st, p.employer_id).await?;
let pf = PersonForm::from_fields(&f);
let input = match pf.validate(dates::today()) {
let input = match pf.validate(dates::today(), &company_ids) {
Ok(i) => i,
Err(errors) => {
return Ok(person_form_page(
@@ -475,6 +549,7 @@ pub async fn update(
&PassportForm::default(),
&errors,
None,
&companies,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
@@ -569,7 +644,7 @@ fn passport_form_page(
&format!("{title}: {}", p.name),
"people",
status,
context! { p, pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
context! { p, tab => "overview", pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
)
}
@@ -824,7 +899,7 @@ fn address_form_page(
&format!("{heading}: {}", p.name),
"people",
status,
context! { p, af, errors, mode, action, heading, ..select_lists() },
context! { p, tab => "overview", af, errors, mode, action, heading, ..select_lists() },
)
}
+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))
}