The back office now looks like lannadesk.com: - Light theme as a printed letterhead (warm paper, navy ink, thin gold rules, a gold line across the top), and the default; the dark theme is the same navy and gold and stays a click away. - Trirong for headings and names, Sarabun for text: the website's fonts, self-hosted in static/fonts/ (latin and Thai subsets, OFL), since the CSP allows fonts from this origin only. - The header reads "Lanna Desk, back office"; primary buttons are navy on paper and gold on navy; corners are squarer. People are record cards, like the example record on the website: a monogram, the name in Trirong, nationality and province, the most urgent deadline's chip, the stay today, the next four dated deadlines with how far away they are, the passport and the employer. The filter works on the cards; "Table" shows the table as before (?view=table), and the switch keeps the employer and archive filters. Checks: fmt, clippy, 109 unit and 57 integration tests (the cards show the stay, the next dates and the monogram; the table view and the switch keep their filters); screenshots of People (light, dark, phone), a person, the deadlines and a client link.
1124 lines
32 KiB
Rust
1124 lines
32 KiB
Rust
//! 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<i32>,
|
|
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<i64>,
|
|
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<String>,
|
|
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<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 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 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)))
|
|
}
|
|
|
|
pub(crate) 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.
|
|
pub(crate) fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
|
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.
|
|
pub(crate) fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option<String> {
|
|
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<String>,
|
|
/// A company's id: only the people it employs.
|
|
#[serde(default)]
|
|
company: Option<String>,
|
|
/// "table" for the table; the record cards otherwise.
|
|
#[serde(default)]
|
|
view: Option<String>,
|
|
}
|
|
|
|
pub async fn list(
|
|
State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Query(q): Query<ListQuery>,
|
|
) -> Res {
|
|
let today = dates::today();
|
|
let archived = q.archived.as_deref() == Some("1");
|
|
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 {
|
|
if let Some(a) = found.remove(&r.id) {
|
|
r.next = a.next().cloned();
|
|
r.upcoming = a
|
|
.items
|
|
.iter()
|
|
.filter(|d| d.due.is_some())
|
|
.take(4)
|
|
.cloned()
|
|
.collect();
|
|
r.stay = Some(a.stay);
|
|
}
|
|
}
|
|
let table = q.view.as_deref() == Some("table");
|
|
// the other view keeps the filters
|
|
let mut keep: Vec<String> = Vec::new();
|
|
if archived {
|
|
keep.push("archived=1".into());
|
|
}
|
|
if let Some(c) = company {
|
|
keep.push(format!("company={c}"));
|
|
}
|
|
let with = |extra: Option<&str>| {
|
|
let all: Vec<&str> = keep.iter().map(String::as_str).chain(extra).collect();
|
|
if all.is_empty() {
|
|
"/people".to_string()
|
|
} else {
|
|
format!("/people?{}", all.join("&"))
|
|
}
|
|
};
|
|
let (cards_href, table_href) = (with(None), with(Some("view=table")));
|
|
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,
|
|
table,
|
|
cards_href,
|
|
table_href,
|
|
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<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();
|
|
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 client_links = super::links::card(&st, id).await?;
|
|
let (agreements, signed_agreements) = super::agreements::card(&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,
|
|
client_links,
|
|
agreements,
|
|
signed_agreements,
|
|
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<String>,
|
|
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<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,
|
|
None,
|
|
&PersonForm::default(),
|
|
&PassportForm::default(),
|
|
&Errors::new(),
|
|
None,
|
|
&companies,
|
|
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 (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<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,
|
|
&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<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));
|
|
};
|
|
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<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>,
|
|
Form(f): Form<Fields>,
|
|
) -> 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<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)),
|
|
};
|
|
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<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(&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<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, tab => "overview", 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())
|
|
}
|