Phase 1: app, Kanidm login, people, passports, addresses, audit log
visa.buildfor.life keeps the immigration records of the foreigners B4L looks after. This first phase is the base the deadlines and extension packs build on (docs/PLAN.md, phases 2 to 7). - One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its templates, static files and migrations compiled in. - Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256), client visa-web, group visa; sessions in PostgreSQL keyed by the SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback development only. - Same-site check and form token on every POST; a CSP without inline script or style; security headers. - People: list with filter, page, create, edit, archive, restore. - Passports from the machine-readable zone with check digits (ICAO 9303 TD3); expiry warnings at 12 and 6 months. - Addresses in Thailand in the order Thai forms use, with the house master and the TM.30 receipt. - Append-only audit log of every view and change, with the names of the changed fields but never their values (PDPA); the Activity page. - Invented demo people (visa seed-demo, refused when login is on). - 40 tests: unit tests, pages with demo data, the forms, the audit log and the whole login against a fake OpenID provider. - CI: gitleaks over the history, fmt, clippy and the tests against PostgreSQL 18; the pre-commit secret scan.
This commit is contained in:
commit
2e009700a9
56 files changed
+11193
No files matched your search
@@ -0,0 +1,970 @@
|
||||
//! Pages for people, their passports and their addresses.
|
||||
|
||||
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 chrono::NaiveDate;
|
||||
use minijinja::context;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{AppState, Res, not_found_page, page};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::countries;
|
||||
use crate::dates::{self, Status};
|
||||
use crate::forms::{Errors, Fields, err, get};
|
||||
use crate::mrz::{self, Mrz};
|
||||
use crate::people::{
|
||||
self, Address, AddressForm, AddressInput, PassportForm, PassportInput, Person, PersonForm,
|
||||
PersonInput, SEXES, TITLES,
|
||||
};
|
||||
use crate::session::User;
|
||||
|
||||
// ----------------------------------------------------------------- views
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct PersonView {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub surname: String,
|
||||
pub given: String,
|
||||
pub title: String,
|
||||
pub sex: String,
|
||||
pub dob: String,
|
||||
pub age: Option<i32>,
|
||||
pub place_of_birth: String,
|
||||
pub nationality: String,
|
||||
pub nationality_name: String,
|
||||
pub occupation: String,
|
||||
pub employer: String,
|
||||
pub phone: String,
|
||||
pub email: String,
|
||||
pub notes: String,
|
||||
pub archived: bool,
|
||||
pub archived_on: String,
|
||||
pub current_passport: String,
|
||||
pub updated: String,
|
||||
}
|
||||
|
||||
fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> PersonView {
|
||||
PersonView {
|
||||
id: p.id,
|
||||
name: p.display_name(),
|
||||
surname: p.surname.to_uppercase(),
|
||||
given: p.given_names(),
|
||||
title: p.title.clone(),
|
||||
sex: people::sex_label(&p.sex).to_string(),
|
||||
dob: p.date_of_birth.map(dates::fmt_date).unwrap_or_default(),
|
||||
age: p.date_of_birth.map(|d| dates::age(d, today)),
|
||||
place_of_birth: p.place_of_birth.clone(),
|
||||
nationality: p.nationality.clone(),
|
||||
nationality_name: countries::name(&p.nationality)
|
||||
.unwrap_or(&p.nationality)
|
||||
.to_string(),
|
||||
occupation: p.occupation.clone(),
|
||||
employer: p.employer.clone(),
|
||||
phone: p.phone.clone(),
|
||||
email: p.email.clone(),
|
||||
notes: p.notes.clone(),
|
||||
archived: p.archived_at.is_some(),
|
||||
archived_on: p
|
||||
.archived_at
|
||||
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
|
||||
.unwrap_or_default(),
|
||||
current_passport: current_passport.unwrap_or_default().to_string(),
|
||||
updated: dates::fmt_datetime(p.updated_at),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PassportView {
|
||||
id: i64,
|
||||
number: String,
|
||||
country: String,
|
||||
country_name: String,
|
||||
issued_on: String,
|
||||
expires_on: String,
|
||||
issued_at: String,
|
||||
current: bool,
|
||||
status: Option<Status>,
|
||||
has_mrz: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct AddressView {
|
||||
id: i64,
|
||||
line: String,
|
||||
current: bool,
|
||||
moved_in_on: String,
|
||||
moved_out_on: String,
|
||||
house_master: String,
|
||||
house_master_phone: String,
|
||||
tm30_reported_on: String,
|
||||
tm30_receipt_no: String,
|
||||
tm30: Option<Status>,
|
||||
}
|
||||
|
||||
fn address_view(a: &Address) -> AddressView {
|
||||
let current = a.moved_out_on.is_none();
|
||||
let tm30 = current.then(|| match a.tm30_reported_on {
|
||||
Some(d) => Status {
|
||||
level: "ok",
|
||||
label: format!("TM.30 reported {}", dates::fmt_date(d)),
|
||||
},
|
||||
None => Status {
|
||||
level: "warn",
|
||||
label: "No TM.30 receipt recorded".into(),
|
||||
},
|
||||
});
|
||||
let fmt = |d: Option<NaiveDate>| d.map(dates::fmt_date).unwrap_or_default();
|
||||
AddressView {
|
||||
id: a.id,
|
||||
line: people::address_line(&AddressInput::from(a)),
|
||||
current,
|
||||
moved_in_on: fmt(a.moved_in_on),
|
||||
moved_out_on: fmt(a.moved_out_on),
|
||||
house_master: a.house_master.clone(),
|
||||
house_master_phone: a.house_master_phone.clone(),
|
||||
tm30_reported_on: fmt(a.tm30_reported_on),
|
||||
tm30_receipt_no: a.tm30_receipt_no.clone(),
|
||||
tm30,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)>> {
|
||||
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());
|
||||
Ok(Some((p, view)))
|
||||
}
|
||||
|
||||
fn select_lists() -> minijinja::Value {
|
||||
context! {
|
||||
titles => TITLES,
|
||||
sexes => SEXES,
|
||||
countries => countries::options(),
|
||||
provinces => countries::PROVINCES,
|
||||
}
|
||||
}
|
||||
|
||||
fn status_for(errors: &Errors) -> StatusCode {
|
||||
if errors.is_empty() {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
}
|
||||
}
|
||||
|
||||
fn log<'a>(
|
||||
user: &'a User,
|
||||
action: Action,
|
||||
entity: Entity,
|
||||
id: i64,
|
||||
person: i64,
|
||||
fields: &'a [String],
|
||||
) -> Entry<'a> {
|
||||
Entry {
|
||||
actor: &user.login,
|
||||
action,
|
||||
entity,
|
||||
entity_id: Some(id),
|
||||
person_id: Some(person),
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the zone typed into a form; a text that is no zone becomes a
|
||||
/// field error.
|
||||
fn read_zone(text: &str, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
match mrz::parse(text, today) {
|
||||
Ok(m) => Some(m),
|
||||
Err(msg) => {
|
||||
err(errors, "mrz", msg);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn zone_note(m: &Mrz, errors: &mut Errors) -> Option<String> {
|
||||
if m.all_ok() {
|
||||
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
||||
} else {
|
||||
err(
|
||||
errors,
|
||||
"mrz",
|
||||
format!(
|
||||
"Filled in, but the check digits do not match for: {}. Compare the lines with \
|
||||
the passport.",
|
||||
m.failed().join(", ")
|
||||
),
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the list
|
||||
|
||||
#[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 = people::list(&st.db, archived, dates::today()).await?;
|
||||
let (n_active, n_archived) = people::counts(&st.db).await?;
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"people.html",
|
||||
if archived {
|
||||
"Archived people"
|
||||
} else {
|
||||
"People"
|
||||
},
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! { people => rows, archived, n_active, n_archived },
|
||||
))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- one person
|
||||
|
||||
pub async fn show(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let today = dates::today();
|
||||
let passports: Vec<PassportView> = people::passports(&st.db, id)
|
||||
.await?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| PassportView {
|
||||
id: p.id,
|
||||
number: p.number.clone(),
|
||||
country: p.issuing_country.clone(),
|
||||
country_name: countries::name(&p.issuing_country)
|
||||
.unwrap_or(&p.issuing_country)
|
||||
.to_string(),
|
||||
issued_on: p.issued_on.map(dates::fmt_date).unwrap_or_default(),
|
||||
expires_on: dates::fmt_date(p.expires_on),
|
||||
issued_at: p.issued_at.clone(),
|
||||
current: i == 0,
|
||||
status: (i == 0).then(|| dates::passport_status(p.expires_on, today)),
|
||||
has_mrz: !p.mrz.is_empty(),
|
||||
})
|
||||
.collect();
|
||||
let addresses: Vec<AddressView> = people::addresses(&st.db, id)
|
||||
.await?
|
||||
.iter()
|
||||
.map(address_view)
|
||||
.collect();
|
||||
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();
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"person.html",
|
||||
&title,
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! { p => view, passports, addresses, recent },
|
||||
))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn person_form_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
p: Option<&PersonView>,
|
||||
f: &PersonForm,
|
||||
pf: &PassportForm,
|
||||
errors: &Errors,
|
||||
mrz_note: Option<String>,
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
let (title, mode, action) = match p {
|
||||
Some(p) => (
|
||||
format!("Edit {}", p.name),
|
||||
"edit",
|
||||
format!("/people/{}", p.id),
|
||||
),
|
||||
None => ("New person".to_string(), "new", "/people".to_string()),
|
||||
};
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"person_form.html",
|
||||
&title,
|
||||
"people",
|
||||
status,
|
||||
context! { p, f, pf, errors, mrz_note, mode, action, ..select_lists() },
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
|
||||
Ok(person_form_page(
|
||||
&st,
|
||||
&user,
|
||||
None,
|
||||
&PersonForm::default(),
|
||||
&PassportForm::default(),
|
||||
&Errors::new(),
|
||||
None,
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let today = dates::today();
|
||||
let mut pf = PersonForm::from_fields(&f);
|
||||
let mut ppf = PassportForm::from_fields(&f);
|
||||
let mut errors = Errors::new();
|
||||
let zone = read_zone(&ppf.mrz, today, &mut errors);
|
||||
|
||||
if get(&f, "action") == "read-mrz" {
|
||||
let mut note = None;
|
||||
match &zone {
|
||||
Some(m) => {
|
||||
pf.take_mrz(m, true);
|
||||
ppf.take_mrz(m, true);
|
||||
note = zone_note(m, &mut errors);
|
||||
}
|
||||
None if ppf.mrz.is_empty() => {
|
||||
err(&mut errors, "mrz", "Paste the two lines first.");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let status = status_for(&errors);
|
||||
return Ok(person_form_page(
|
||||
&st, &user, None, &pf, &ppf, &errors, note, status,
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(m) = &zone {
|
||||
pf.take_mrz(m, false);
|
||||
ppf.take_mrz(m, false);
|
||||
}
|
||||
let person = pf.validate(today);
|
||||
let passport = (!ppf.is_blank()).then(|| ppf.validate(zone.as_ref()));
|
||||
for e in [
|
||||
person.as_ref().err(),
|
||||
passport.as_ref().and_then(|p| p.as_ref().err()),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
for (k, v) in e {
|
||||
err(&mut errors, k, v.clone());
|
||||
}
|
||||
}
|
||||
let (Ok(person), true) = (person, errors.is_empty()) else {
|
||||
return Ok(person_form_page(
|
||||
&st,
|
||||
&user,
|
||||
None,
|
||||
&pf,
|
||||
&ppf,
|
||||
&errors,
|
||||
None,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
};
|
||||
let passport: Option<PassportInput> = passport.and_then(Result::ok);
|
||||
|
||||
let mut tx = st.db.begin().await?;
|
||||
if let Some(pp) = &passport
|
||||
&& people::passport_taken(&mut tx, pp, None).await?
|
||||
{
|
||||
err(
|
||||
&mut errors,
|
||||
"number",
|
||||
"A passport with this number from this country is already recorded.",
|
||||
);
|
||||
return Ok(person_form_page(
|
||||
&st,
|
||||
&user,
|
||||
None,
|
||||
&pf,
|
||||
&ppf,
|
||||
&errors,
|
||||
None,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
let id = people::create_person(&mut tx, &person).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(&user, Action::Create, Entity::Person, id, id, &[]),
|
||||
)
|
||||
.await?;
|
||||
if let Some(pp) = &passport {
|
||||
let pid = people::create_passport(&mut tx, id, pp).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(&user, Action::Create, Entity::Passport, pid, id, &[]),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}")).into_response())
|
||||
}
|
||||
|
||||
pub async fn edit_form(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some((p, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
Ok(person_form_page(
|
||||
&st,
|
||||
&user,
|
||||
Some(&view),
|
||||
&PersonForm::from_person(&p),
|
||||
&PassportForm::default(),
|
||||
&Errors::new(),
|
||||
None,
|
||||
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 Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let pf = PersonForm::from_fields(&f);
|
||||
let input = match pf.validate(dates::today()) {
|
||||
Ok(i) => i,
|
||||
Err(errors) => {
|
||||
return Ok(person_form_page(
|
||||
&st,
|
||||
&user,
|
||||
Some(&view),
|
||||
&pf,
|
||||
&PassportForm::default(),
|
||||
&errors,
|
||||
None,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
let Some(old) = people::get_person_in(&mut tx, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let changed = input.changed_from(&PersonInput::from(&old));
|
||||
if !changed.is_empty() {
|
||||
people::update_person(&mut tx, id, &input).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(&user, Action::Update, Entity::Person, id, id, &changed),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}")).into_response())
|
||||
}
|
||||
|
||||
async fn set_archived(st: &AppState, user: &User, id: i64, archived: bool) -> Res {
|
||||
let mut tx = st.db.begin().await?;
|
||||
if people::get_person_in(&mut tx, id).await?.is_none() {
|
||||
return Ok(not_found_page(st));
|
||||
}
|
||||
if people::set_archived(&mut tx, id, archived).await? {
|
||||
let action = if archived {
|
||||
Action::Archive
|
||||
} else {
|
||||
Action::Restore
|
||||
};
|
||||
audit::record(&mut *tx, &log(user, action, Entity::Person, id, id, &[])).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{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
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ passports
|
||||
|
||||
/// What reading the zone found: the check digits matched, or the names
|
||||
/// differ from the record's.
|
||||
#[derive(Default)]
|
||||
struct Notes {
|
||||
mrz_note: Option<String>,
|
||||
name_hint: Option<String>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn passport_form_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
p: &PersonView,
|
||||
passport_id: Option<i64>,
|
||||
pf: &PassportForm,
|
||||
errors: &Errors,
|
||||
notes: Notes,
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
let Notes {
|
||||
mrz_note,
|
||||
name_hint,
|
||||
} = notes;
|
||||
let (title, mode, action) = match passport_id {
|
||||
Some(pid) => (
|
||||
"Edit passport",
|
||||
"edit",
|
||||
format!("/people/{}/passports/{pid}", p.id),
|
||||
),
|
||||
None => ("New passport", "new", format!("/people/{}/passports", p.id)),
|
||||
};
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"passport_form.html",
|
||||
&format!("{title}: {}", p.name),
|
||||
"people",
|
||||
status,
|
||||
context! { p, pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn passport_new(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some((p, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
// a new passport is usually from the same country as the last one
|
||||
let pf = PassportForm {
|
||||
issuing_country: p.nationality.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(passport_form_page(
|
||||
&st,
|
||||
&user,
|
||||
&view,
|
||||
None,
|
||||
&pf,
|
||||
&Errors::new(),
|
||||
Notes::default(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
/// The names in the zone against the record's, as a hint (transliteration
|
||||
/// and long names make them differ legitimately).
|
||||
fn name_hint(m: &Mrz, p: &Person) -> Option<String> {
|
||||
let record = format!("{} {}", p.surname, p.given_names()).to_uppercase();
|
||||
let zone = format!("{} {}", m.surname, m.given_names);
|
||||
(record.split_whitespace().collect::<Vec<_>>() != zone.split_whitespace().collect::<Vec<_>>())
|
||||
.then(|| {
|
||||
format!(
|
||||
"The zone names {}, {}; the record says {}. Check that this is the right person.",
|
||||
m.surname,
|
||||
m.given_names,
|
||||
p.display_name()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn passport_save(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
id: i64,
|
||||
passport_id: Option<i64>,
|
||||
f: &Fields,
|
||||
) -> Res {
|
||||
let Some((person, view)) = load_person(st, id).await? else {
|
||||
return Ok(not_found_page(st));
|
||||
};
|
||||
if let Some(pid) = passport_id
|
||||
&& people::passport(&st.db, id, pid).await?.is_none()
|
||||
{
|
||||
return Ok(not_found_page(st));
|
||||
}
|
||||
let today = dates::today();
|
||||
let mut pf = PassportForm::from_fields(f);
|
||||
let mut errors = Errors::new();
|
||||
let zone = read_zone(&pf.mrz, today, &mut errors);
|
||||
let mut notes = Notes::default();
|
||||
|
||||
if get(f, "action") == "read-mrz" {
|
||||
match &zone {
|
||||
Some(m) => {
|
||||
pf.take_mrz(m, true);
|
||||
notes.mrz_note = zone_note(m, &mut errors);
|
||||
notes.name_hint = name_hint(m, &person);
|
||||
}
|
||||
None if pf.mrz.is_empty() => err(&mut errors, "mrz", "Paste the two lines first."),
|
||||
None => {}
|
||||
}
|
||||
let status = status_for(&errors);
|
||||
return Ok(passport_form_page(
|
||||
st,
|
||||
user,
|
||||
&view,
|
||||
passport_id,
|
||||
&pf,
|
||||
&errors,
|
||||
notes,
|
||||
status,
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(m) = &zone {
|
||||
pf.take_mrz(m, false);
|
||||
}
|
||||
let input = match pf.validate(zone.as_ref()) {
|
||||
Ok(i) if errors.is_empty() => i,
|
||||
Ok(_) => {
|
||||
return Ok(passport_form_page(
|
||||
st,
|
||||
user,
|
||||
&view,
|
||||
passport_id,
|
||||
&pf,
|
||||
&errors,
|
||||
notes,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
Err(e) => {
|
||||
for (k, v) in e {
|
||||
err(&mut errors, &k, v);
|
||||
}
|
||||
return Ok(passport_form_page(
|
||||
st,
|
||||
user,
|
||||
&view,
|
||||
passport_id,
|
||||
&pf,
|
||||
&errors,
|
||||
notes,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
if people::passport_taken(&mut tx, &input, passport_id).await? {
|
||||
err(
|
||||
&mut errors,
|
||||
"number",
|
||||
"A passport with this number from this country is already recorded.",
|
||||
);
|
||||
return Ok(passport_form_page(
|
||||
st,
|
||||
user,
|
||||
&view,
|
||||
passport_id,
|
||||
&pf,
|
||||
&errors,
|
||||
notes,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
match passport_id {
|
||||
None => {
|
||||
let pid = people::create_passport(&mut tx, id, &input).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(user, Action::Create, Entity::Passport, pid, id, &[]),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Some(pid) => {
|
||||
let old = people::passport(&st.db, id, pid)
|
||||
.await?
|
||||
.map(|p| PassportInput::from(&p));
|
||||
let changed = old.map(|o| input.changed_from(&o)).unwrap_or_default();
|
||||
if !changed.is_empty() {
|
||||
people::update_passport(&mut tx, pid, &input).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(user, Action::Update, Entity::Passport, pid, id, &changed),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}#passports")).into_response())
|
||||
}
|
||||
|
||||
pub async fn passport_create(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
passport_save(&st, &user, id, None, &f).await
|
||||
}
|
||||
|
||||
pub async fn passport_edit(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, pid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let Some(pp) = people::passport(&st.db, id, pid).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
audit::viewed(&st.db, &user.login, Entity::Passport, pid, id).await?;
|
||||
Ok(passport_form_page(
|
||||
&st,
|
||||
&user,
|
||||
&view,
|
||||
Some(pid),
|
||||
&PassportForm::from_passport(&pp),
|
||||
&Errors::new(),
|
||||
Notes::default(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn passport_update(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, pid)): Path<(i64, i64)>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
passport_save(&st, &user, id, Some(pid), &f).await
|
||||
}
|
||||
|
||||
pub async fn passport_delete(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, pid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let mut tx = st.db.begin().await?;
|
||||
if !people::delete_passport(&mut tx, id, pid).await? {
|
||||
return Ok(not_found_page(&st));
|
||||
}
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(&user, Action::Delete, Entity::Passport, pid, id, &[]),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}#passports")).into_response())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ addresses
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn address_form_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
p: &PersonView,
|
||||
address_id: Option<i64>,
|
||||
af: &AddressForm,
|
||||
errors: &Errors,
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
let (heading, mode, action) = match address_id {
|
||||
Some(aid) => (
|
||||
"Edit address",
|
||||
"edit",
|
||||
format!("/people/{}/addresses/{aid}", p.id),
|
||||
),
|
||||
None => ("New address", "new", format!("/people/{}/addresses", p.id)),
|
||||
};
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"address_form.html",
|
||||
&format!("{heading}: {}", p.name),
|
||||
"people",
|
||||
status,
|
||||
context! { p, af, errors, mode, action, heading, ..select_lists() },
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn address_new(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let af = AddressForm {
|
||||
province: "Chiang Mai".into(),
|
||||
moved_in_on: dates::today().to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
Ok(address_form_page(
|
||||
&st,
|
||||
&user,
|
||||
&view,
|
||||
None,
|
||||
&af,
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
async fn address_save(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
id: i64,
|
||||
address_id: Option<i64>,
|
||||
f: &Fields,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(st, id).await? else {
|
||||
return Ok(not_found_page(st));
|
||||
};
|
||||
let old = match address_id {
|
||||
Some(aid) => match people::address(&st.db, id, aid).await? {
|
||||
Some(a) => Some(AddressInput::from(&a)),
|
||||
None => return Ok(not_found_page(st)),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let af = AddressForm::from_fields(f);
|
||||
let input = match af.validate(dates::today()) {
|
||||
Ok(i) => i,
|
||||
Err(errors) => {
|
||||
return Ok(address_form_page(
|
||||
st,
|
||||
user,
|
||||
&view,
|
||||
address_id,
|
||||
&af,
|
||||
&errors,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
match (address_id, old) {
|
||||
(Some(aid), Some(old)) => {
|
||||
let changed = input.changed_from(&old);
|
||||
if !changed.is_empty() {
|
||||
people::update_address(&mut tx, aid, &input).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(user, Action::Update, Entity::Address, aid, id, &changed),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let aid = people::create_address(&mut tx, id, &input).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(user, Action::Create, Entity::Address, aid, id, &[]),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}#addresses")).into_response())
|
||||
}
|
||||
|
||||
pub async fn address_create(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
address_save(&st, &user, id, None, &f).await
|
||||
}
|
||||
|
||||
pub async fn address_edit(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, aid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let Some(a) = people::address(&st.db, id, aid).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
audit::viewed(&st.db, &user.login, Entity::Address, aid, id).await?;
|
||||
Ok(address_form_page(
|
||||
&st,
|
||||
&user,
|
||||
&view,
|
||||
Some(aid),
|
||||
&AddressForm::from_address(&a),
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn address_update(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, aid)): Path<(i64, i64)>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
address_save(&st, &user, id, Some(aid), &f).await
|
||||
}
|
||||
|
||||
pub async fn address_delete(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, aid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let mut tx = st.db.begin().await?;
|
||||
if !people::delete_address(&mut tx, id, aid).await? {
|
||||
return Ok(not_found_page(&st));
|
||||
}
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&log(&user, Action::Delete, Entity::Address, aid, id, &[]),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/people/{id}#addresses")).into_response())
|
||||
}
|
||||
Reference in new issue
Block a user