//! 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, with_reader}; 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; use crate::{companies, deadlines}; // ----------------------------------------------------------------- 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, pub place_of_birth: String, pub nationality: String, pub nationality_name: String, pub occupation: String, /// The employer's name. pub employer: String, pub employer_id: Option, 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>, employer: Option, 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: employer.unwrap_or_default(), employer_id: p.employer_id, 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, 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, } 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| 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 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> { let Some(p) = people::get_person(&st.db, id).await? else { return Ok(None); }; let pps = people::passports(&st.db, id).await?; 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))) } 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), company_id: None, fields, } } /// Reads the zone typed into a form or read from a photo. When the text is /// no zone whose check digits all match, the zone in it as OCR read it /// (`mrz::from_ocr`: lines in any order, look-alike characters) replaces /// it, if that one matches or the text was no zone at all. A text that /// holds no zone becomes a field error. fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option { if text.is_empty() { return None; } let typed = mrz::parse(text, today); if typed.as_ref().is_ok_and(Mrz::all_ok) { return typed.ok(); } if let Some(found) = mrz::from_ocr(text) && let Ok(m) = mrz::parse(&found, today) && (m.all_ok() || typed.is_err()) { *text = found; return Some(m); } match typed { Ok(m) => Some(m), Err(msg) => { err(errors, "mrz", msg); None } } } /// `photo`: the lines came from the photo reader (the form's /// `mrz_source`), whose names have no check digit to catch a misread. fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option { match (m.all_ok(), photo) { (true, false) => { Some("Filled in from the machine-readable zone; every check digit matches.".into()) } (true, true) => Some( "Read from the photo; every check digit matches. The names have no check digit: \ compare them with the passport." .into(), ), (false, _) => { let what = if photo { "Read from the photo" } else { "Filled in" }; err( errors, "mrz", format!( "{what}, but the check digits do not match for: {}. Compare the lines \ with the passport and correct them{}.", m.failed().join(", "), if photo { ", or take the photo again" } else { "" } ), ); None } } } // ------------------------------------------------------------ the list #[derive(Deserialize)] pub struct ListQuery { #[serde(default)] archived: Option, /// A company's id: only the people it employs. #[serde(default)] company: Option, } pub async fn list( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let today = dates::today(); let archived = q.archived.as_deref() == Some("1"); let company: Option = q.company.as_deref().and_then(|c| c.parse().ok()); let mut rows = people::list(&st.db, archived, company, today).await?; let ids: Vec = 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", &heading, "people", StatusCode::OK, 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, }, )) } // ------------------------------------------------------- one person pub async fn show( State(st): State>, Extension(user): Extension, Path(id): Path, ) -> Res { let Some((_, view)) = load_person(&st, id).await? else { return Ok(not_found_page(&st)); }; let today = dates::today(); let passports: Vec = 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 = people::addresses(&st.db, id) .await? .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 docs = super::documents::chips(&st, id).await?; let title = view.name.clone(); Ok(page( &st, &user, "person.html", &title, "people", StatusCode::OK, context! { p => view, tab => "overview", passports, addresses, docs, recent, stay => assessment.stay, deadlines => assessment.items, }, )) } #[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, companies: &[(String, 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()), }; with_reader(page( st, user, "person_form.html", &title, "people", status, 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, ) -> anyhow::Result<(Vec<(String, String)>, Vec)> { 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>, Extension(user): Extension) -> Res { let (companies, _) = employer_choices(&st, None).await?; Ok(person_form_page( &st, &user, None, &PersonForm::default(), &PassportForm::default(), &Errors::new(), None, &companies, StatusCode::OK, )) } pub async fn create( State(st): State>, Extension(user): Extension, Form(f): Form, ) -> 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(); let zone = read_zone(&mut ppf.mrz, today, &mut errors); let photo = get(&f, "mrz_source") == "photo"; 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, photo, &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, &companies, status, )); } if let Some(m) = &zone { pf.take_mrz(m, false); ppf.take_mrz(m, false); } 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(), 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, &companies, StatusCode::UNPROCESSABLE_ENTITY, )); }; let passport: Option = 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, &companies, 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>, Extension(user): Extension, Path(id): Path, ) -> Res { 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, &user, Some(&view), &PersonForm::from_person(&p), &PassportForm::default(), &Errors::new(), None, &companies, StatusCode::OK, )) } pub async fn update( State(st): State>, Extension(user): Extension, Path(id): Path, Form(f): Form, ) -> Res { 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(), &company_ids) { Ok(i) => i, Err(errors) => { return Ok(person_form_page( &st, &user, Some(&view), &pf, &PassportForm::default(), &errors, None, &companies, 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>, Extension(user): Extension, Path(id): Path, ) -> Res { set_archived(&st, &user, id, true).await } pub async fn restore( State(st): State>, Extension(user): Extension, Path(id): Path, ) -> 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, name_hint: Option, } #[allow(clippy::too_many_arguments)] fn passport_form_page( st: &AppState, user: &User, p: &PersonView, passport_id: Option, 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)), }; with_reader(page( st, user, "passport_form.html", &format!("{title}: {}", p.name), "people", status, context! { p, tab => "overview", pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() }, )) } pub async fn passport_new( State(st): State>, Extension(user): Extension, Path(id): Path, ) -> 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 { let record = format!("{} {}", p.surname, p.given_names()).to_uppercase(); let zone = format!("{} {}", m.surname, m.given_names); (record.split_whitespace().collect::>() != zone.split_whitespace().collect::>()) .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, 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(&mut pf.mrz, today, &mut errors); let photo = get(f, "mrz_source") == "photo"; 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, photo, &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>, Extension(user): Extension, Path(id): Path, Form(f): Form, ) -> Res { passport_save(&st, &user, id, None, &f).await } pub async fn passport_edit( State(st): State>, Extension(user): Extension, 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>, Extension(user): Extension, Path((id, pid)): Path<(i64, i64)>, Form(f): Form, ) -> Res { passport_save(&st, &user, id, Some(pid), &f).await } pub async fn passport_delete( State(st): State>, Extension(user): Extension, 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, 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, tab => "overview", af, errors, mode, action, heading, ..select_lists() }, ) } pub async fn address_new( State(st): State>, Extension(user): Extension, Path(id): Path, ) -> 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, 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>, Extension(user): Extension, Path(id): Path, Form(f): Form, ) -> Res { address_save(&st, &user, id, None, &f).await } pub async fn address_edit( State(st): State>, Extension(user): Extension, 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>, Extension(user): Extension, Path((id, aid)): Path<(i64, i64)>, Form(f): Form, ) -> Res { address_save(&st, &user, id, Some(aid), &f).await } pub async fn address_delete( State(st): State>, Extension(user): Extension, 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()) }