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.
1214 lines
38 KiB
Rust
1214 lines
38 KiB
Rust
//! People, their passports and their addresses in Thailand: forms,
|
|
//! validation and SQL. Handlers in `web::people` turn these into pages.
|
|
|
|
use anyhow::Result;
|
|
use chrono::{DateTime, NaiveDate, Utc};
|
|
use serde::Serialize;
|
|
use sqlx::{PgConnection, PgPool};
|
|
|
|
use crate::countries;
|
|
use crate::dates;
|
|
use crate::forms::{Errors, Fields, compact_upper, err, get};
|
|
use crate::mrz::Mrz;
|
|
|
|
pub const TITLES: &[(&str, &str)] = &[("Mr", "Mr"), ("Mrs", "Mrs"), ("Ms", "Ms"), ("Miss", "Miss")];
|
|
pub const SEXES: &[(&str, &str)] = &[("F", "Female"), ("M", "Male"), ("X", "Unspecified")];
|
|
|
|
pub fn sex_label(code: &str) -> &'static str {
|
|
SEXES
|
|
.iter()
|
|
.find(|(c, _)| *c == code)
|
|
.map(|(_, l)| *l)
|
|
.unwrap_or("")
|
|
}
|
|
|
|
/// Compares two records field by field and lists the names that differ
|
|
/// (for the audit log, which keeps names and never values).
|
|
macro_rules! changed_fields {
|
|
($new:expr, $old:expr; $($f:ident),* $(,)?) => {{
|
|
let mut v: Vec<String> = Vec::new();
|
|
$( if $new.$f != $old.$f { v.push(stringify!($f).to_string()); } )*
|
|
v
|
|
}};
|
|
}
|
|
|
|
// ---------------------------------------------------------------- people
|
|
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Person {
|
|
pub id: i64,
|
|
pub surname: String,
|
|
pub first_name: String,
|
|
pub middle_name: String,
|
|
pub title: String,
|
|
pub sex: String,
|
|
pub date_of_birth: Option<NaiveDate>,
|
|
pub place_of_birth: String,
|
|
pub nationality: String,
|
|
pub occupation: String,
|
|
pub employer: String,
|
|
pub phone: String,
|
|
pub email: String,
|
|
pub notes: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub updated_at: DateTime<Utc>,
|
|
pub archived_at: Option<DateTime<Utc>>,
|
|
}
|
|
|
|
impl Person {
|
|
pub fn given_names(&self) -> String {
|
|
join_names(&self.first_name, &self.middle_name)
|
|
}
|
|
|
|
/// "MUSTERMANN, Erika": the surname as passports print it.
|
|
pub fn display_name(&self) -> String {
|
|
format!("{}, {}", self.surname.to_uppercase(), self.given_names())
|
|
}
|
|
}
|
|
|
|
fn join_names(first: &str, middle: &str) -> String {
|
|
if middle.is_empty() {
|
|
first.to_string()
|
|
} else {
|
|
format!("{first} {middle}")
|
|
}
|
|
}
|
|
|
|
/// A person's fields as typed in the form.
|
|
#[derive(Clone, Debug, Default, Serialize)]
|
|
pub struct PersonForm {
|
|
pub surname: String,
|
|
pub first_name: String,
|
|
pub middle_name: String,
|
|
pub title: String,
|
|
pub sex: String,
|
|
pub date_of_birth: String,
|
|
pub place_of_birth: String,
|
|
pub nationality: String,
|
|
pub occupation: String,
|
|
pub employer: String,
|
|
pub phone: String,
|
|
pub email: String,
|
|
pub notes: String,
|
|
}
|
|
|
|
/// A person's fields, checked.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct PersonInput {
|
|
pub surname: String,
|
|
pub first_name: String,
|
|
pub middle_name: String,
|
|
pub title: String,
|
|
pub sex: String,
|
|
pub date_of_birth: Option<NaiveDate>,
|
|
pub place_of_birth: String,
|
|
pub nationality: String,
|
|
pub occupation: String,
|
|
pub employer: String,
|
|
pub phone: String,
|
|
pub email: String,
|
|
pub notes: String,
|
|
}
|
|
|
|
impl PersonInput {
|
|
pub fn changed_from(&self, old: &PersonInput) -> Vec<String> {
|
|
changed_fields!(self, old; surname, first_name, middle_name, title, sex,
|
|
date_of_birth, place_of_birth, nationality, occupation, employer, phone,
|
|
email, notes)
|
|
}
|
|
}
|
|
|
|
impl From<&Person> for PersonInput {
|
|
fn from(p: &Person) -> Self {
|
|
PersonInput {
|
|
surname: p.surname.clone(),
|
|
first_name: p.first_name.clone(),
|
|
middle_name: p.middle_name.clone(),
|
|
title: p.title.clone(),
|
|
sex: p.sex.clone(),
|
|
date_of_birth: p.date_of_birth,
|
|
place_of_birth: p.place_of_birth.clone(),
|
|
nationality: p.nationality.clone(),
|
|
occupation: p.occupation.clone(),
|
|
employer: p.employer.clone(),
|
|
phone: p.phone.clone(),
|
|
email: p.email.clone(),
|
|
notes: p.notes.clone(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl PersonForm {
|
|
pub fn from_fields(f: &Fields) -> Self {
|
|
PersonForm {
|
|
surname: get(f, "surname"),
|
|
first_name: get(f, "first_name"),
|
|
middle_name: get(f, "middle_name"),
|
|
title: get(f, "title"),
|
|
sex: get(f, "sex"),
|
|
date_of_birth: get(f, "date_of_birth"),
|
|
place_of_birth: get(f, "place_of_birth"),
|
|
nationality: compact_upper(&get(f, "nationality")),
|
|
occupation: get(f, "occupation"),
|
|
employer: get(f, "employer"),
|
|
phone: get(f, "phone"),
|
|
email: get(f, "email"),
|
|
notes: f
|
|
.get("notes")
|
|
.map(|s| s.trim().to_string())
|
|
.unwrap_or_default(),
|
|
}
|
|
}
|
|
|
|
pub fn from_person(p: &Person) -> Self {
|
|
PersonForm {
|
|
surname: p.surname.clone(),
|
|
first_name: p.first_name.clone(),
|
|
middle_name: p.middle_name.clone(),
|
|
title: p.title.clone(),
|
|
sex: p.sex.clone(),
|
|
date_of_birth: p.date_of_birth.map(|d| d.to_string()).unwrap_or_default(),
|
|
place_of_birth: p.place_of_birth.clone(),
|
|
nationality: p.nationality.clone(),
|
|
occupation: p.occupation.clone(),
|
|
employer: p.employer.clone(),
|
|
phone: p.phone.clone(),
|
|
email: p.email.clone(),
|
|
notes: p.notes.clone(),
|
|
}
|
|
}
|
|
|
|
/// Takes what the zone holds; `overwrite` false only fills empty fields.
|
|
pub fn take_mrz(&mut self, m: &Mrz, overwrite: bool) {
|
|
let (first, middle) = m.first_and_middle();
|
|
let set = |field: &mut String, value: String| {
|
|
if !value.is_empty() && (overwrite || field.is_empty()) {
|
|
*field = value;
|
|
}
|
|
};
|
|
set(&mut self.surname, m.surname.clone());
|
|
set(&mut self.first_name, first);
|
|
set(&mut self.middle_name, middle);
|
|
set(&mut self.sex, m.sex.clone());
|
|
set(
|
|
&mut self.date_of_birth,
|
|
m.date_of_birth.map(|d| d.to_string()).unwrap_or_default(),
|
|
);
|
|
if countries::is_known(&m.nationality) {
|
|
set(&mut self.nationality, m.nationality.clone());
|
|
}
|
|
}
|
|
|
|
pub fn validate(&self, today: NaiveDate) -> Result<PersonInput, Errors> {
|
|
let mut e = Errors::new();
|
|
if self.surname.is_empty() {
|
|
err(
|
|
&mut e,
|
|
"surname",
|
|
"Enter the surname as printed in the passport.",
|
|
);
|
|
}
|
|
if self.first_name.is_empty() {
|
|
err(
|
|
&mut e,
|
|
"first_name",
|
|
"Enter the first name as printed in the passport.",
|
|
);
|
|
}
|
|
if !self.title.is_empty() && !TITLES.iter().any(|(t, _)| *t == self.title) {
|
|
err(&mut e, "title", "Choose a title from the list.");
|
|
}
|
|
if !self.sex.is_empty() && !SEXES.iter().any(|(s, _)| *s == self.sex) {
|
|
err(&mut e, "sex", "Choose from the list.");
|
|
}
|
|
let date_of_birth = optional_date(&self.date_of_birth, "date_of_birth", &mut e);
|
|
if date_of_birth.is_some_and(|d| d > today) {
|
|
err(
|
|
&mut e,
|
|
"date_of_birth",
|
|
"The date of birth lies in the future.",
|
|
);
|
|
}
|
|
if !self.nationality.is_empty() && !countries::is_known(&self.nationality) {
|
|
err(&mut e, "nationality", "Choose a country from the list.");
|
|
}
|
|
if !self.email.is_empty() && !looks_like_email(&self.email) {
|
|
err(&mut e, "email", "This does not look like an email address.");
|
|
}
|
|
if !e.is_empty() {
|
|
return Err(e);
|
|
}
|
|
Ok(PersonInput {
|
|
surname: self.surname.clone(),
|
|
first_name: self.first_name.clone(),
|
|
middle_name: self.middle_name.clone(),
|
|
title: self.title.clone(),
|
|
sex: self.sex.clone(),
|
|
date_of_birth,
|
|
place_of_birth: self.place_of_birth.clone(),
|
|
nationality: self.nationality.clone(),
|
|
occupation: self.occupation.clone(),
|
|
employer: self.employer.clone(),
|
|
phone: self.phone.clone(),
|
|
email: self.email.clone(),
|
|
notes: self.notes.clone(),
|
|
})
|
|
}
|
|
}
|
|
|
|
fn looks_like_email(s: &str) -> bool {
|
|
match s.split_once('@') {
|
|
Some((user, host)) => {
|
|
!user.is_empty() && host.contains('.') && !host.starts_with('.') && !s.contains(' ')
|
|
}
|
|
None => false,
|
|
}
|
|
}
|
|
|
|
fn optional_date(value: &str, field: &str, e: &mut Errors) -> Option<NaiveDate> {
|
|
if value.is_empty() {
|
|
return None;
|
|
}
|
|
let d = dates::parse_date(value);
|
|
if d.is_none() {
|
|
err(e, field, "Enter a date (year-month-day).");
|
|
}
|
|
d
|
|
}
|
|
|
|
pub async fn get_person(db: &PgPool, id: i64) -> Result<Option<Person>> {
|
|
Ok(sqlx::query_as("SELECT * FROM people WHERE id = $1")
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn get_person_in(conn: &mut PgConnection, id: i64) -> Result<Option<Person>> {
|
|
Ok(
|
|
sqlx::query_as("SELECT * FROM people WHERE id = $1 FOR UPDATE")
|
|
.bind(id)
|
|
.fetch_optional(conn)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
pub async fn create_person(conn: &mut PgConnection, p: &PersonInput) -> Result<i64> {
|
|
let id: i64 = sqlx::query_scalar(
|
|
"INSERT INTO people (surname, first_name, middle_name, title, sex, date_of_birth, \
|
|
place_of_birth, nationality, occupation, employer, phone, email, notes) \
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id",
|
|
)
|
|
.bind(&p.surname)
|
|
.bind(&p.first_name)
|
|
.bind(&p.middle_name)
|
|
.bind(&p.title)
|
|
.bind(&p.sex)
|
|
.bind(p.date_of_birth)
|
|
.bind(&p.place_of_birth)
|
|
.bind(&p.nationality)
|
|
.bind(&p.occupation)
|
|
.bind(&p.employer)
|
|
.bind(&p.phone)
|
|
.bind(&p.email)
|
|
.bind(&p.notes)
|
|
.fetch_one(conn)
|
|
.await?;
|
|
Ok(id)
|
|
}
|
|
|
|
pub async fn update_person(conn: &mut PgConnection, id: i64, p: &PersonInput) -> Result<()> {
|
|
sqlx::query(
|
|
"UPDATE people SET surname = $2, first_name = $3, middle_name = $4, title = $5, \
|
|
sex = $6, date_of_birth = $7, place_of_birth = $8, nationality = $9, \
|
|
occupation = $10, employer = $11, phone = $12, email = $13, notes = $14, \
|
|
updated_at = now() WHERE id = $1",
|
|
)
|
|
.bind(id)
|
|
.bind(&p.surname)
|
|
.bind(&p.first_name)
|
|
.bind(&p.middle_name)
|
|
.bind(&p.title)
|
|
.bind(&p.sex)
|
|
.bind(p.date_of_birth)
|
|
.bind(&p.place_of_birth)
|
|
.bind(&p.nationality)
|
|
.bind(&p.occupation)
|
|
.bind(&p.employer)
|
|
.bind(&p.phone)
|
|
.bind(&p.email)
|
|
.bind(&p.notes)
|
|
.execute(conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Archives or restores; false when nothing changed.
|
|
pub async fn set_archived(conn: &mut PgConnection, id: i64, archived: bool) -> Result<bool> {
|
|
let sql = if archived {
|
|
"UPDATE people SET archived_at = now(), updated_at = now() \
|
|
WHERE id = $1 AND archived_at IS NULL"
|
|
} else {
|
|
"UPDATE people SET archived_at = NULL, updated_at = now() \
|
|
WHERE id = $1 AND archived_at IS NOT NULL"
|
|
};
|
|
let done = sqlx::query(sql).bind(id).execute(conn).await?;
|
|
Ok(done.rows_affected() == 1)
|
|
}
|
|
|
|
#[derive(Debug, sqlx::FromRow)]
|
|
struct ListRow {
|
|
id: i64,
|
|
surname: String,
|
|
first_name: String,
|
|
middle_name: String,
|
|
nationality: String,
|
|
date_of_birth: Option<NaiveDate>,
|
|
employer: String,
|
|
passport_number: Option<String>,
|
|
passport_expires: Option<NaiveDate>,
|
|
province: Option<String>,
|
|
}
|
|
|
|
/// One row of the people list, ready to show.
|
|
#[derive(Debug, Serialize)]
|
|
pub struct ListItem {
|
|
pub id: i64,
|
|
pub name: String,
|
|
pub nationality: String,
|
|
pub age: Option<i32>,
|
|
pub employer: String,
|
|
pub passport_number: String,
|
|
pub passport_expires: String,
|
|
pub passport_status: Option<dates::Status>,
|
|
pub province: String,
|
|
/// Lower-case text the filter box searches.
|
|
pub q: String,
|
|
}
|
|
|
|
pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result<Vec<ListItem>> {
|
|
let rows: Vec<ListRow> = sqlx::query_as(
|
|
"SELECT p.id, p.surname, p.first_name, p.middle_name, p.nationality, p.date_of_birth, \
|
|
p.employer, pp.number AS passport_number, pp.expires_on AS passport_expires, \
|
|
a.province \
|
|
FROM people p \
|
|
LEFT JOIN LATERAL (SELECT number, expires_on FROM passports \
|
|
WHERE person_id = p.id ORDER BY expires_on DESC, id DESC LIMIT 1) pp ON true \
|
|
LEFT JOIN LATERAL (SELECT province FROM addresses \
|
|
WHERE person_id = p.id AND moved_out_on IS NULL \
|
|
ORDER BY moved_in_on DESC NULLS LAST, id DESC LIMIT 1) a ON true \
|
|
WHERE (p.archived_at IS NOT NULL) = $1 \
|
|
ORDER BY lower(p.surname), lower(p.first_name), p.id",
|
|
)
|
|
.bind(archived)
|
|
.fetch_all(db)
|
|
.await?;
|
|
Ok(rows
|
|
.into_iter()
|
|
.map(|r| {
|
|
let name = format!(
|
|
"{}, {}",
|
|
r.surname.to_uppercase(),
|
|
join_names(&r.first_name, &r.middle_name)
|
|
);
|
|
let nationality = countries::name(&r.nationality)
|
|
.unwrap_or(&r.nationality)
|
|
.to_string();
|
|
let passport_number = r.passport_number.unwrap_or_default();
|
|
let province = r.province.unwrap_or_default();
|
|
let q = format!(
|
|
"{name} {nationality} {} {passport_number} {} {province}",
|
|
r.nationality, r.employer
|
|
)
|
|
.to_lowercase();
|
|
ListItem {
|
|
id: r.id,
|
|
age: r.date_of_birth.map(|d| dates::age(d, today)),
|
|
passport_expires: r.passport_expires.map(dates::fmt_date).unwrap_or_default(),
|
|
passport_status: r.passport_expires.map(|d| dates::passport_status(d, today)),
|
|
name,
|
|
nationality,
|
|
employer: r.employer,
|
|
passport_number,
|
|
province,
|
|
q,
|
|
}
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
/// People in the list and in the archive.
|
|
pub async fn counts(db: &PgPool) -> Result<(i64, i64)> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT count(*) FILTER (WHERE archived_at IS NULL), \
|
|
count(*) FILTER (WHERE archived_at IS NOT NULL) FROM people",
|
|
)
|
|
.fetch_one(db)
|
|
.await?)
|
|
}
|
|
|
|
// ------------------------------------------------------------- passports
|
|
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Passport {
|
|
pub id: i64,
|
|
pub person_id: i64,
|
|
pub number: String,
|
|
pub issuing_country: String,
|
|
pub issued_on: Option<NaiveDate>,
|
|
pub expires_on: NaiveDate,
|
|
pub issued_at: String,
|
|
pub mrz: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub updated_at: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, Serialize)]
|
|
pub struct PassportForm {
|
|
pub number: String,
|
|
pub issuing_country: String,
|
|
pub issued_on: String,
|
|
pub expires_on: String,
|
|
pub issued_at: String,
|
|
pub mrz: String,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct PassportInput {
|
|
pub number: String,
|
|
pub issuing_country: String,
|
|
pub issued_on: Option<NaiveDate>,
|
|
pub expires_on: NaiveDate,
|
|
pub issued_at: String,
|
|
pub mrz: String,
|
|
}
|
|
|
|
impl PassportInput {
|
|
pub fn changed_from(&self, old: &PassportInput) -> Vec<String> {
|
|
changed_fields!(self, old; number, issuing_country, issued_on, expires_on, issued_at, mrz)
|
|
}
|
|
}
|
|
|
|
impl From<&Passport> for PassportInput {
|
|
fn from(p: &Passport) -> Self {
|
|
PassportInput {
|
|
number: p.number.clone(),
|
|
issuing_country: p.issuing_country.clone(),
|
|
issued_on: p.issued_on,
|
|
expires_on: p.expires_on,
|
|
issued_at: p.issued_at.clone(),
|
|
mrz: p.mrz.clone(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl PassportForm {
|
|
pub fn from_fields(f: &Fields) -> Self {
|
|
PassportForm {
|
|
number: compact_upper(&get(f, "number")),
|
|
issuing_country: compact_upper(&get(f, "issuing_country")),
|
|
issued_on: get(f, "issued_on"),
|
|
expires_on: get(f, "expires_on"),
|
|
issued_at: get(f, "issued_at"),
|
|
mrz: get(f, "mrz"),
|
|
}
|
|
}
|
|
|
|
pub fn from_passport(p: &Passport) -> Self {
|
|
PassportForm {
|
|
number: p.number.clone(),
|
|
issuing_country: p.issuing_country.clone(),
|
|
issued_on: p.issued_on.map(|d| d.to_string()).unwrap_or_default(),
|
|
expires_on: p.expires_on.to_string(),
|
|
issued_at: p.issued_at.clone(),
|
|
mrz: p.mrz.clone(),
|
|
}
|
|
}
|
|
|
|
/// Nothing typed: the passport part of the new person form is optional.
|
|
pub fn is_blank(&self) -> bool {
|
|
self.number.is_empty()
|
|
&& self.issuing_country.is_empty()
|
|
&& self.issued_on.is_empty()
|
|
&& self.expires_on.is_empty()
|
|
&& self.issued_at.is_empty()
|
|
&& self.mrz.is_empty()
|
|
}
|
|
|
|
pub fn take_mrz(&mut self, m: &Mrz, overwrite: bool) {
|
|
let set = |field: &mut String, value: String| {
|
|
if !value.is_empty() && (overwrite || field.is_empty()) {
|
|
*field = value;
|
|
}
|
|
};
|
|
set(&mut self.number, m.number.clone());
|
|
if countries::is_known(&m.issuing_state) {
|
|
set(&mut self.issuing_country, m.issuing_state.clone());
|
|
}
|
|
set(
|
|
&mut self.expires_on,
|
|
m.expiry_date.map(|d| d.to_string()).unwrap_or_default(),
|
|
);
|
|
self.mrz = m.text.clone();
|
|
}
|
|
|
|
/// Checks the fields; `mrz` is the zone read from `self.mrz`, if any,
|
|
/// which must agree with the number and the expiry date.
|
|
pub fn validate(&self, mrz: Option<&Mrz>) -> Result<PassportInput, Errors> {
|
|
let mut e = Errors::new();
|
|
if self.number.is_empty() {
|
|
err(&mut e, "number", "Enter the passport number.");
|
|
} else if self.number.len() > 20 || !self.number.chars().all(|c| c.is_ascii_alphanumeric())
|
|
{
|
|
err(
|
|
&mut e,
|
|
"number",
|
|
"A passport number has only letters and digits.",
|
|
);
|
|
}
|
|
if self.issuing_country.is_empty() {
|
|
err(
|
|
&mut e,
|
|
"issuing_country",
|
|
"Choose the country that issued the passport.",
|
|
);
|
|
} else if !countries::is_known(&self.issuing_country) {
|
|
err(&mut e, "issuing_country", "Choose a country from the list.");
|
|
}
|
|
let issued_on = optional_date(&self.issued_on, "issued_on", &mut e);
|
|
let expires_on = if self.expires_on.is_empty() {
|
|
err(&mut e, "expires_on", "Enter the expiry date.");
|
|
None
|
|
} else {
|
|
optional_date(&self.expires_on, "expires_on", &mut e)
|
|
};
|
|
if let (Some(i), Some(x)) = (issued_on, expires_on)
|
|
&& i >= x
|
|
{
|
|
err(
|
|
&mut e,
|
|
"issued_on",
|
|
"The issue date must lie before the expiry date.",
|
|
);
|
|
}
|
|
if let Some(m) = mrz {
|
|
if !m.all_ok() {
|
|
err(
|
|
&mut e,
|
|
"mrz",
|
|
format!(
|
|
"The check digits do not match for: {}. Compare the lines with the passport.",
|
|
m.failed().join(", ")
|
|
),
|
|
);
|
|
}
|
|
if !self.number.is_empty() && m.number != self.number {
|
|
err(
|
|
&mut e,
|
|
"number",
|
|
format!("The machine-readable zone says {}.", m.number),
|
|
);
|
|
}
|
|
if let (Some(x), Some(mx)) = (expires_on, m.expiry_date)
|
|
&& x != mx
|
|
{
|
|
err(
|
|
&mut e,
|
|
"expires_on",
|
|
format!("The machine-readable zone says {}.", dates::fmt_date(mx)),
|
|
);
|
|
}
|
|
}
|
|
let Some(expires_on) = expires_on else {
|
|
return Err(e);
|
|
};
|
|
if !e.is_empty() {
|
|
return Err(e);
|
|
}
|
|
Ok(PassportInput {
|
|
number: self.number.clone(),
|
|
issuing_country: self.issuing_country.clone(),
|
|
issued_on,
|
|
expires_on,
|
|
issued_at: self.issued_at.clone(),
|
|
mrz: mrz.map(|m| m.text.clone()).unwrap_or_default(),
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Newest first; the first one is the current passport.
|
|
pub async fn passports(db: &PgPool, person: i64) -> Result<Vec<Passport>> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT * FROM passports WHERE person_id = $1 ORDER BY expires_on DESC, id DESC",
|
|
)
|
|
.bind(person)
|
|
.fetch_all(db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn passport(db: &PgPool, person: i64, id: i64) -> Result<Option<Passport>> {
|
|
Ok(
|
|
sqlx::query_as("SELECT * FROM passports WHERE person_id = $1 AND id = $2")
|
|
.bind(person)
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
/// Another passport with this number from this country, if one exists.
|
|
pub async fn passport_taken(
|
|
conn: &mut PgConnection,
|
|
p: &PassportInput,
|
|
except: Option<i64>,
|
|
) -> Result<bool> {
|
|
let n: i64 = sqlx::query_scalar(
|
|
"SELECT count(*) FROM passports WHERE issuing_country = $1 AND number = $2 \
|
|
AND ($3::bigint IS NULL OR id <> $3)",
|
|
)
|
|
.bind(&p.issuing_country)
|
|
.bind(&p.number)
|
|
.bind(except)
|
|
.fetch_one(conn)
|
|
.await?;
|
|
Ok(n > 0)
|
|
}
|
|
|
|
pub async fn create_passport(
|
|
conn: &mut PgConnection,
|
|
person: i64,
|
|
p: &PassportInput,
|
|
) -> Result<i64> {
|
|
let id: i64 = sqlx::query_scalar(
|
|
"INSERT INTO passports (person_id, number, issuing_country, issued_on, expires_on, \
|
|
issued_at, mrz) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id",
|
|
)
|
|
.bind(person)
|
|
.bind(&p.number)
|
|
.bind(&p.issuing_country)
|
|
.bind(p.issued_on)
|
|
.bind(p.expires_on)
|
|
.bind(&p.issued_at)
|
|
.bind(&p.mrz)
|
|
.fetch_one(conn)
|
|
.await?;
|
|
Ok(id)
|
|
}
|
|
|
|
pub async fn update_passport(conn: &mut PgConnection, id: i64, p: &PassportInput) -> Result<()> {
|
|
sqlx::query(
|
|
"UPDATE passports SET number = $2, issuing_country = $3, issued_on = $4, \
|
|
expires_on = $5, issued_at = $6, mrz = $7, updated_at = now() WHERE id = $1",
|
|
)
|
|
.bind(id)
|
|
.bind(&p.number)
|
|
.bind(&p.issuing_country)
|
|
.bind(p.issued_on)
|
|
.bind(p.expires_on)
|
|
.bind(&p.issued_at)
|
|
.bind(&p.mrz)
|
|
.execute(conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn delete_passport(conn: &mut PgConnection, person: i64, id: i64) -> Result<bool> {
|
|
let done = sqlx::query("DELETE FROM passports WHERE person_id = $1 AND id = $2")
|
|
.bind(person)
|
|
.bind(id)
|
|
.execute(conn)
|
|
.await?;
|
|
Ok(done.rows_affected() == 1)
|
|
}
|
|
|
|
// ------------------------------------------------------------- addresses
|
|
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Address {
|
|
pub id: i64,
|
|
pub person_id: i64,
|
|
pub house_no: String,
|
|
pub moo: String,
|
|
pub building: String,
|
|
pub soi: String,
|
|
pub road: String,
|
|
pub subdistrict: String,
|
|
pub district: String,
|
|
pub province: String,
|
|
pub postal_code: String,
|
|
pub moved_in_on: Option<NaiveDate>,
|
|
pub moved_out_on: Option<NaiveDate>,
|
|
pub house_master: String,
|
|
pub house_master_phone: String,
|
|
pub tm30_reported_on: Option<NaiveDate>,
|
|
pub tm30_receipt_no: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub updated_at: DateTime<Utc>,
|
|
}
|
|
|
|
/// The address in one line, in the order Thai forms use: house number,
|
|
/// moo, building, soi, road, subdistrict, district, province, postal code.
|
|
pub fn address_line(a: &AddressInput) -> String {
|
|
let mut parts: Vec<String> = Vec::new();
|
|
let mut first = a.house_no.clone();
|
|
if !a.moo.is_empty() {
|
|
let moo = prefixed("Moo", &a.moo);
|
|
first = if first.is_empty() {
|
|
moo
|
|
} else {
|
|
format!("{first} {moo}")
|
|
};
|
|
}
|
|
for p in [
|
|
first,
|
|
a.building.clone(),
|
|
if a.soi.is_empty() {
|
|
String::new()
|
|
} else {
|
|
prefixed("Soi", &a.soi)
|
|
},
|
|
a.road.clone(),
|
|
a.subdistrict.clone(),
|
|
a.district.clone(),
|
|
] {
|
|
if !p.is_empty() {
|
|
parts.push(p);
|
|
}
|
|
}
|
|
let last = [a.province.as_str(), a.postal_code.as_str()]
|
|
.iter()
|
|
.filter(|s| !s.is_empty())
|
|
.copied()
|
|
.collect::<Vec<_>>()
|
|
.join(" ");
|
|
if !last.is_empty() {
|
|
parts.push(last);
|
|
}
|
|
parts.join(", ")
|
|
}
|
|
|
|
/// "Soi 7" from "7", but "Soi Sukhumvit 7" stays as typed.
|
|
fn prefixed(word: &str, value: &str) -> String {
|
|
if value.to_lowercase().starts_with(&word.to_lowercase()) {
|
|
value.to_string()
|
|
} else {
|
|
format!("{word} {value}")
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, Serialize)]
|
|
pub struct AddressForm {
|
|
pub house_no: String,
|
|
pub moo: String,
|
|
pub building: String,
|
|
pub soi: String,
|
|
pub road: String,
|
|
pub subdistrict: String,
|
|
pub district: String,
|
|
pub province: String,
|
|
pub postal_code: String,
|
|
pub moved_in_on: String,
|
|
pub moved_out_on: String,
|
|
pub house_master: String,
|
|
pub house_master_phone: String,
|
|
pub tm30_reported_on: String,
|
|
pub tm30_receipt_no: String,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct AddressInput {
|
|
pub house_no: String,
|
|
pub moo: String,
|
|
pub building: String,
|
|
pub soi: String,
|
|
pub road: String,
|
|
pub subdistrict: String,
|
|
pub district: String,
|
|
pub province: String,
|
|
pub postal_code: String,
|
|
pub moved_in_on: Option<NaiveDate>,
|
|
pub moved_out_on: Option<NaiveDate>,
|
|
pub house_master: String,
|
|
pub house_master_phone: String,
|
|
pub tm30_reported_on: Option<NaiveDate>,
|
|
pub tm30_receipt_no: String,
|
|
}
|
|
|
|
impl AddressInput {
|
|
pub fn changed_from(&self, old: &AddressInput) -> Vec<String> {
|
|
changed_fields!(self, old; house_no, moo, building, soi, road, subdistrict,
|
|
district, province, postal_code, moved_in_on, moved_out_on, house_master,
|
|
house_master_phone, tm30_reported_on, tm30_receipt_no)
|
|
}
|
|
}
|
|
|
|
impl From<&Address> for AddressInput {
|
|
fn from(a: &Address) -> Self {
|
|
AddressInput {
|
|
house_no: a.house_no.clone(),
|
|
moo: a.moo.clone(),
|
|
building: a.building.clone(),
|
|
soi: a.soi.clone(),
|
|
road: a.road.clone(),
|
|
subdistrict: a.subdistrict.clone(),
|
|
district: a.district.clone(),
|
|
province: a.province.clone(),
|
|
postal_code: a.postal_code.clone(),
|
|
moved_in_on: a.moved_in_on,
|
|
moved_out_on: a.moved_out_on,
|
|
house_master: a.house_master.clone(),
|
|
house_master_phone: a.house_master_phone.clone(),
|
|
tm30_reported_on: a.tm30_reported_on,
|
|
tm30_receipt_no: a.tm30_receipt_no.clone(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl AddressForm {
|
|
pub fn from_fields(f: &Fields) -> Self {
|
|
AddressForm {
|
|
house_no: get(f, "house_no"),
|
|
moo: get(f, "moo"),
|
|
building: get(f, "building"),
|
|
soi: get(f, "soi"),
|
|
road: get(f, "road"),
|
|
subdistrict: get(f, "subdistrict"),
|
|
district: get(f, "district"),
|
|
province: get(f, "province"),
|
|
postal_code: get(f, "postal_code"),
|
|
moved_in_on: get(f, "moved_in_on"),
|
|
moved_out_on: get(f, "moved_out_on"),
|
|
house_master: get(f, "house_master"),
|
|
house_master_phone: get(f, "house_master_phone"),
|
|
tm30_reported_on: get(f, "tm30_reported_on"),
|
|
tm30_receipt_no: get(f, "tm30_receipt_no"),
|
|
}
|
|
}
|
|
|
|
pub fn from_address(a: &Address) -> Self {
|
|
let d = |v: Option<NaiveDate>| v.map(|d| d.to_string()).unwrap_or_default();
|
|
AddressForm {
|
|
house_no: a.house_no.clone(),
|
|
moo: a.moo.clone(),
|
|
building: a.building.clone(),
|
|
soi: a.soi.clone(),
|
|
road: a.road.clone(),
|
|
subdistrict: a.subdistrict.clone(),
|
|
district: a.district.clone(),
|
|
province: a.province.clone(),
|
|
postal_code: a.postal_code.clone(),
|
|
moved_in_on: d(a.moved_in_on),
|
|
moved_out_on: d(a.moved_out_on),
|
|
house_master: a.house_master.clone(),
|
|
house_master_phone: a.house_master_phone.clone(),
|
|
tm30_reported_on: d(a.tm30_reported_on),
|
|
tm30_receipt_no: a.tm30_receipt_no.clone(),
|
|
}
|
|
}
|
|
|
|
pub fn validate(&self, today: NaiveDate) -> Result<AddressInput, Errors> {
|
|
let mut e = Errors::new();
|
|
if self.house_no.is_empty() && self.building.is_empty() {
|
|
err(
|
|
&mut e,
|
|
"house_no",
|
|
"Enter the house number (or the building below).",
|
|
);
|
|
}
|
|
if self.district.is_empty() {
|
|
err(&mut e, "district", "Enter the district (amphoe).");
|
|
}
|
|
if self.province.is_empty() {
|
|
err(&mut e, "province", "Enter the province.");
|
|
}
|
|
if !self.postal_code.is_empty()
|
|
&& !(self.postal_code.len() == 5
|
|
&& self.postal_code.chars().all(|c| c.is_ascii_digit()))
|
|
{
|
|
err(&mut e, "postal_code", "A Thai postal code has five digits.");
|
|
}
|
|
let moved_in_on = optional_date(&self.moved_in_on, "moved_in_on", &mut e);
|
|
let moved_out_on = optional_date(&self.moved_out_on, "moved_out_on", &mut e);
|
|
if let (Some(i), Some(o)) = (moved_in_on, moved_out_on)
|
|
&& o < i
|
|
{
|
|
err(
|
|
&mut e,
|
|
"moved_out_on",
|
|
"The move-out date lies before the move-in date.",
|
|
);
|
|
}
|
|
let tm30_reported_on = optional_date(&self.tm30_reported_on, "tm30_reported_on", &mut e);
|
|
if tm30_reported_on.is_some_and(|d| d > today) {
|
|
err(
|
|
&mut e,
|
|
"tm30_reported_on",
|
|
"The report date lies in the future.",
|
|
);
|
|
}
|
|
if !e.is_empty() {
|
|
return Err(e);
|
|
}
|
|
Ok(AddressInput {
|
|
house_no: self.house_no.clone(),
|
|
moo: self.moo.clone(),
|
|
building: self.building.clone(),
|
|
soi: self.soi.clone(),
|
|
road: self.road.clone(),
|
|
subdistrict: self.subdistrict.clone(),
|
|
district: self.district.clone(),
|
|
province: self.province.clone(),
|
|
postal_code: self.postal_code.clone(),
|
|
moved_in_on,
|
|
moved_out_on,
|
|
house_master: self.house_master.clone(),
|
|
house_master_phone: self.house_master_phone.clone(),
|
|
tm30_reported_on,
|
|
tm30_receipt_no: self.tm30_receipt_no.clone(),
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Current addresses first (no move-out date), then by move-in date.
|
|
pub async fn addresses(db: &PgPool, person: i64) -> Result<Vec<Address>> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT * FROM addresses WHERE person_id = $1 \
|
|
ORDER BY (moved_out_on IS NULL) DESC, moved_in_on DESC NULLS LAST, id DESC",
|
|
)
|
|
.bind(person)
|
|
.fetch_all(db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn address(db: &PgPool, person: i64, id: i64) -> Result<Option<Address>> {
|
|
Ok(
|
|
sqlx::query_as("SELECT * FROM addresses WHERE person_id = $1 AND id = $2")
|
|
.bind(person)
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
pub async fn create_address(conn: &mut PgConnection, person: i64, a: &AddressInput) -> Result<i64> {
|
|
let id: i64 = sqlx::query_scalar(
|
|
"INSERT INTO addresses (person_id, house_no, moo, building, soi, road, subdistrict, \
|
|
district, province, postal_code, moved_in_on, moved_out_on, house_master, \
|
|
house_master_phone, tm30_reported_on, tm30_receipt_no) \
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) \
|
|
RETURNING id",
|
|
)
|
|
.bind(person)
|
|
.bind(&a.house_no)
|
|
.bind(&a.moo)
|
|
.bind(&a.building)
|
|
.bind(&a.soi)
|
|
.bind(&a.road)
|
|
.bind(&a.subdistrict)
|
|
.bind(&a.district)
|
|
.bind(&a.province)
|
|
.bind(&a.postal_code)
|
|
.bind(a.moved_in_on)
|
|
.bind(a.moved_out_on)
|
|
.bind(&a.house_master)
|
|
.bind(&a.house_master_phone)
|
|
.bind(a.tm30_reported_on)
|
|
.bind(&a.tm30_receipt_no)
|
|
.fetch_one(conn)
|
|
.await?;
|
|
Ok(id)
|
|
}
|
|
|
|
pub async fn update_address(conn: &mut PgConnection, id: i64, a: &AddressInput) -> Result<()> {
|
|
sqlx::query(
|
|
"UPDATE addresses SET house_no = $2, moo = $3, building = $4, soi = $5, road = $6, \
|
|
subdistrict = $7, district = $8, province = $9, postal_code = $10, \
|
|
moved_in_on = $11, moved_out_on = $12, house_master = $13, \
|
|
house_master_phone = $14, tm30_reported_on = $15, tm30_receipt_no = $16, \
|
|
updated_at = now() WHERE id = $1",
|
|
)
|
|
.bind(id)
|
|
.bind(&a.house_no)
|
|
.bind(&a.moo)
|
|
.bind(&a.building)
|
|
.bind(&a.soi)
|
|
.bind(&a.road)
|
|
.bind(&a.subdistrict)
|
|
.bind(&a.district)
|
|
.bind(&a.province)
|
|
.bind(&a.postal_code)
|
|
.bind(a.moved_in_on)
|
|
.bind(a.moved_out_on)
|
|
.bind(&a.house_master)
|
|
.bind(&a.house_master_phone)
|
|
.bind(a.tm30_reported_on)
|
|
.bind(&a.tm30_receipt_no)
|
|
.execute(conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn delete_address(conn: &mut PgConnection, person: i64, id: i64) -> Result<bool> {
|
|
let done = sqlx::query("DELETE FROM addresses WHERE person_id = $1 AND id = $2")
|
|
.bind(person)
|
|
.bind(id)
|
|
.execute(conn)
|
|
.await?;
|
|
Ok(done.rows_affected() == 1)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::mrz;
|
|
|
|
fn d(s: &str) -> NaiveDate {
|
|
dates::parse_date(s).unwrap()
|
|
}
|
|
|
|
fn fields(pairs: &[(&str, &str)]) -> Fields {
|
|
pairs
|
|
.iter()
|
|
.map(|(k, v)| (k.to_string(), v.to_string()))
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn person_validation() {
|
|
let today = d("2026-11-17");
|
|
let f = PersonForm::from_fields(&fields(&[
|
|
("surname", " Mustermann "),
|
|
("first_name", "Erika"),
|
|
("date_of_birth", "2030-01-01"),
|
|
("nationality", "deu"),
|
|
("email", "erika@"),
|
|
("title", "Dr"),
|
|
]));
|
|
assert_eq!(f.surname, "Mustermann");
|
|
assert_eq!(f.nationality, "DEU");
|
|
let e = f.validate(today).unwrap_err();
|
|
assert_eq!(
|
|
e.keys().map(String::as_str).collect::<Vec<_>>(),
|
|
vec!["date_of_birth", "email", "title"]
|
|
);
|
|
let ok = PersonForm::from_fields(&fields(&[
|
|
("surname", "Mustermann"),
|
|
("first_name", "Erika"),
|
|
("date_of_birth", "1984-08-12"),
|
|
("nationality", "DEU"),
|
|
]))
|
|
.validate(today)
|
|
.unwrap();
|
|
assert_eq!(ok.date_of_birth, Some(d("1984-08-12")));
|
|
let mut other = ok.clone();
|
|
other.email = "erika@example.com".into();
|
|
other.first_name = "Erica".into();
|
|
assert_eq!(other.changed_from(&ok), vec!["first_name", "email"]);
|
|
}
|
|
|
|
#[test]
|
|
fn mrz_fills_person_and_passport() {
|
|
let today = d("2026-11-17");
|
|
let text = mrz::compose(&mrz::Compose {
|
|
issuing_state: "D",
|
|
surname: "MUSTERMANN",
|
|
given_names: "ERIKA ANNA",
|
|
number: "C01X00T47",
|
|
nationality: "D",
|
|
date_of_birth: d("1984-08-12"),
|
|
sex: "F",
|
|
expiry_date: d("2031-08-01"),
|
|
});
|
|
let m = mrz::parse(&text, today).unwrap();
|
|
let mut pf = PersonForm {
|
|
surname: "Typed".into(),
|
|
..Default::default()
|
|
};
|
|
pf.take_mrz(&m, false);
|
|
assert_eq!(pf.surname, "Typed", "blank-only fill keeps typed values");
|
|
assert_eq!(pf.first_name, "ERIKA");
|
|
assert_eq!(pf.middle_name, "ANNA");
|
|
assert_eq!(pf.nationality, "DEU");
|
|
pf.take_mrz(&m, true);
|
|
assert_eq!(pf.surname, "MUSTERMANN");
|
|
|
|
let mut pp = PassportForm::default();
|
|
pp.take_mrz(&m, true);
|
|
assert_eq!(pp.number, "C01X00T47");
|
|
assert_eq!(pp.issuing_country, "DEU");
|
|
assert_eq!(pp.expires_on, "2031-08-01");
|
|
let input = pp.validate(Some(&m)).unwrap();
|
|
assert_eq!(input.mrz, m.text);
|
|
|
|
// a number typed differently from the zone is refused
|
|
pp.number = "C01X00T48".into();
|
|
let e = pp.validate(Some(&m)).unwrap_err();
|
|
assert!(e["number"].contains("C01X00T47"), "{e:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn passport_and_address_validation() {
|
|
let e = PassportForm {
|
|
issued_on: "2031-01-01".into(),
|
|
expires_on: "2030-01-01".into(),
|
|
issuing_country: "XYZ".into(),
|
|
number: "AB 12".into(),
|
|
..Default::default()
|
|
}
|
|
.validate(None)
|
|
.unwrap_err();
|
|
assert!(e.contains_key("issued_on"));
|
|
assert!(e.contains_key("issuing_country"));
|
|
assert!(e.contains_key("number"));
|
|
|
|
let today = d("2026-11-17");
|
|
let e = AddressForm {
|
|
postal_code: "5020".into(),
|
|
moved_in_on: "2026-05-01".into(),
|
|
moved_out_on: "2026-04-01".into(),
|
|
..Default::default()
|
|
}
|
|
.validate(today)
|
|
.unwrap_err();
|
|
for k in [
|
|
"house_no",
|
|
"district",
|
|
"province",
|
|
"postal_code",
|
|
"moved_out_on",
|
|
] {
|
|
assert!(e.contains_key(k), "{k} in {e:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn address_lines_in_thai_order() {
|
|
let a = AddressInput {
|
|
house_no: "99/9".into(),
|
|
moo: "4".into(),
|
|
building: "Baan Suan Demo".into(),
|
|
soi: "7".into(),
|
|
road: "Huay Kaew Road".into(),
|
|
subdistrict: "Suthep".into(),
|
|
district: "Mueang Chiang Mai".into(),
|
|
province: "Chiang Mai".into(),
|
|
postal_code: "50200".into(),
|
|
moved_in_on: None,
|
|
moved_out_on: None,
|
|
house_master: String::new(),
|
|
house_master_phone: String::new(),
|
|
tm30_reported_on: None,
|
|
tm30_receipt_no: String::new(),
|
|
};
|
|
assert_eq!(
|
|
address_line(&a),
|
|
"99/9 Moo 4, Baan Suan Demo, Soi 7, Huay Kaew Road, Suthep, Mueang Chiang Mai, Chiang Mai 50200"
|
|
);
|
|
let b = AddressInput {
|
|
moo: String::new(),
|
|
soi: "Soi Sukhumvit 7".into(),
|
|
..a
|
|
};
|
|
assert!(address_line(&b).starts_with("99/9, Baan Suan Demo, Soi Sukhumvit 7,"));
|
|
}
|
|
}
|