Phase 2: companies, stay records, deadlines
Companies become records of their own, and the stay in Thailand is recorded in full; from these records the app works out each person's deadlines (docs/PLAN.md, phase 2). - Companies: list, page, form, archive; Thai name, the 13-digit registration number with its check digit verified, address and the director who signs. The employer is chosen from them on the person form and on work permits; a company's page adds people to it; the people list and the Deadlines page filter by employer. Migration 0002 turns the free-text employers into companies. - Stay records, each one `Kind` in src/records.rs with one form, one set of routes and the same audit entries: arrivals and departures with the TDAC, extensions of stay (approved, under consideration, refused), 90-day reports with the receipt's next date, visas, re-entry permits and work permits. Passports, visas and companies are chosen from the person's own records; the server checks the choice. - The deadline engine (src/deadlines.rs, a pure function with a unit test per rule): the 90-day report from day 1 of each arrival, reset by a report or an extension, with the in-person and online windows and the in-person rule after a new passport or an extension; the extension window from 30 days before to the last working day; the decision to collect; overstay with its fine; TM.30 after each arrival; passport and work permit expiry; re-entry permits; visas still to be used. - The Deadlines page at /, the person's status and deadlines on the Overview and the new "Visa and stay" tab, the person's Activity tab, and the next deadline in the people list. - The online 90-day window ends 7 days before the due date (the plan said 8; the Immigration Bureau's TM.47 manual says 7). - 69 tests: 45 unit tests and 24 integration tests.
This commit is contained in:
1 parent
2e009700a9
commit
83bc481952
37 files changed
+5515
-142
No files matched your search
+35
-3
@@ -42,6 +42,13 @@ pub enum Entity {
|
||||
Passport,
|
||||
Address,
|
||||
Session,
|
||||
Company,
|
||||
Visa,
|
||||
Arrival,
|
||||
Extension,
|
||||
ReentryPermit,
|
||||
Report,
|
||||
WorkPermit,
|
||||
}
|
||||
|
||||
impl Entity {
|
||||
@@ -51,6 +58,13 @@ impl Entity {
|
||||
Entity::Passport => "passport",
|
||||
Entity::Address => "address",
|
||||
Entity::Session => "session",
|
||||
Entity::Company => "company",
|
||||
Entity::Visa => "visa",
|
||||
Entity::Arrival => "arrival",
|
||||
Entity::Extension => "extension",
|
||||
Entity::ReentryPermit => "reentry-permit",
|
||||
Entity::Report => "report",
|
||||
Entity::WorkPermit => "work-permit",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,6 +126,7 @@ struct Row {
|
||||
person_id: Option<i64>,
|
||||
fields: Vec<String>,
|
||||
person_name: Option<String>,
|
||||
company_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -123,17 +138,30 @@ pub struct Item {
|
||||
pub what: String,
|
||||
pub person_id: Option<i64>,
|
||||
pub person_name: Option<String>,
|
||||
pub company_id: Option<i64>,
|
||||
pub company_name: Option<String>,
|
||||
pub fields: String,
|
||||
}
|
||||
|
||||
/// The record's kind as people say it.
|
||||
fn noun(entity: &str) -> &str {
|
||||
match entity {
|
||||
"reentry-permit" => "re-entry permit",
|
||||
"work-permit" => "work permit",
|
||||
"report" => "90-day report",
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest entries first, for one person or for everyone.
|
||||
pub async fn recent(db: &PgPool, person: Option<i64>, limit: i64) -> Result<Vec<Item>> {
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT a.id, a.at, a.actor, a.action, a.entity, a.entity_id, a.person_id, a.fields, \
|
||||
CASE WHEN p.id IS NULL THEN NULL \
|
||||
ELSE upper(p.surname) || ', ' || trim(p.first_name || ' ' || p.middle_name) \
|
||||
END AS person_name \
|
||||
END AS person_name, c.name AS company_name \
|
||||
FROM audit_log a LEFT JOIN people p ON p.id = a.person_id \
|
||||
LEFT JOIN companies c ON a.entity = 'company' AND c.id = a.entity_id \
|
||||
WHERE ($1::bigint IS NULL OR a.person_id = $1) \
|
||||
ORDER BY a.id DESC LIMIT $2",
|
||||
)
|
||||
@@ -146,9 +174,11 @@ pub async fn recent(db: &PgPool, person: Option<i64>, limit: i64) -> Result<Vec<
|
||||
.map(|r| {
|
||||
let what = match (r.entity.as_str(), r.entity_id) {
|
||||
("session", _) => String::new(),
|
||||
(e, Some(id)) => format!("{e} {id}"),
|
||||
(e, None) => e.to_string(),
|
||||
("company", _) => String::new(),
|
||||
(e, Some(id)) => format!("{} {id}", noun(e)),
|
||||
(e, None) => noun(e).to_string(),
|
||||
};
|
||||
let company_id = (r.entity == "company").then_some(r.entity_id).flatten();
|
||||
Item {
|
||||
id: r.id,
|
||||
at: dates::fmt_datetime(r.at),
|
||||
@@ -157,6 +187,8 @@ pub async fn recent(db: &PgPool, person: Option<i64>, limit: i64) -> Result<Vec<
|
||||
what,
|
||||
person_id: r.person_id,
|
||||
person_name: r.person_name,
|
||||
company_id,
|
||||
company_name: r.company_name,
|
||||
fields: r.fields.join(", ").replace('_', " "),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
//! Companies: the employers of the people in the records, later also the
|
||||
//! agency's corporate clients. Their fields and checks are
|
||||
//! `records::COMPANIES`; this module holds what only companies need: the
|
||||
//! list, archiving, the choices for the selections, and the people they
|
||||
//! employ.
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::{DateTime, NaiveDate, TimeDelta, Utc};
|
||||
use serde::Serialize;
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
|
||||
use crate::countries;
|
||||
use crate::dates::{self, Status};
|
||||
use crate::people::{self, AddressInput};
|
||||
use crate::records::Record;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ListItem {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub name_th: String,
|
||||
pub registration_no: String,
|
||||
pub province: String,
|
||||
/// People it employs (not archived).
|
||||
pub people: i64,
|
||||
/// Lower-case text the filter box searches.
|
||||
pub q: String,
|
||||
}
|
||||
|
||||
pub async fn list(db: &PgPool, archived: bool) -> Result<Vec<ListItem>> {
|
||||
let rows: Vec<(i64, String, String, String, String, i64)> = sqlx::query_as(
|
||||
"SELECT c.id, c.name, c.name_th, c.registration_no, c.province, \
|
||||
(SELECT count(*) FROM people p \
|
||||
WHERE p.employer_id = c.id AND p.archived_at IS NULL) \
|
||||
FROM companies c WHERE (c.archived_at IS NOT NULL) = $1 \
|
||||
ORDER BY lower(c.name), c.id",
|
||||
)
|
||||
.bind(archived)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, name, name_th, registration_no, province, people)| {
|
||||
let q = format!("{name} {name_th} {registration_no} {province}").to_lowercase();
|
||||
ListItem {
|
||||
id,
|
||||
name,
|
||||
name_th,
|
||||
registration_no,
|
||||
province,
|
||||
people,
|
||||
q,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Companies 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 companies",
|
||||
)
|
||||
.fetch_one(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// The companies to choose from: the active ones, and `keep` (a company
|
||||
/// already chosen, even when archived since). (id, name) pairs.
|
||||
pub async fn choices(db: &PgPool, keep: Option<i64>) -> Result<Vec<(String, String)>> {
|
||||
let rows: Vec<(i64, String)> = sqlx::query_as(
|
||||
"SELECT id, name FROM companies WHERE archived_at IS NULL OR id = $1 \
|
||||
ORDER BY lower(name), id",
|
||||
)
|
||||
.bind(keep)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, name)| (id.to_string(), name))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Every company, archived ones too, to name them in existing records.
|
||||
pub async fn names(db: &PgPool) -> Result<Vec<(String, String)>> {
|
||||
let rows: Vec<(i64, String)> =
|
||||
sqlx::query_as("SELECT id, name FROM companies ORDER BY lower(name), id")
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, name)| (id.to_string(), name))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn name(db: &PgPool, id: i64) -> Result<Option<String>> {
|
||||
Ok(
|
||||
sqlx::query_scalar("SELECT name FROM companies WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
|
||||
/// None when there is no such company; Some(None) while it is active.
|
||||
pub async fn archived_at(db: &PgPool, id: i64) -> Result<Option<Option<DateTime<Utc>>>> {
|
||||
Ok(
|
||||
sqlx::query_scalar("SELECT archived_at FROM companies WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
|
||||
/// 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 companies SET archived_at = now(), updated_at = now() \
|
||||
WHERE id = $1 AND archived_at IS NULL"
|
||||
} else {
|
||||
"UPDATE companies 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)
|
||||
}
|
||||
|
||||
/// Another company has this registration number.
|
||||
pub async fn registration_taken(db: &PgPool, number: &str, except: Option<i64>) -> Result<bool> {
|
||||
if number.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(sqlx::query_scalar(
|
||||
"SELECT EXISTS (SELECT 1 FROM companies WHERE registration_no = $1 \
|
||||
AND ($2::bigint IS NULL OR id <> $2))",
|
||||
)
|
||||
.bind(number)
|
||||
.bind(except)
|
||||
.fetch_one(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// Someone the company employs, with the work permit for it.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Employee {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub nationality: String,
|
||||
pub permit: Status,
|
||||
}
|
||||
|
||||
pub async fn employees(db: &PgPool, company: i64, today: NaiveDate) -> Result<Vec<Employee>> {
|
||||
type Row = (i64, String, String, String, String, Option<NaiveDate>);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT p.id, p.surname, p.first_name, p.middle_name, p.nationality, \
|
||||
(SELECT max(w.valid_until) FROM work_permits w \
|
||||
WHERE w.person_id = p.id AND w.company_id = $1) \
|
||||
FROM people p WHERE p.employer_id = $1 AND p.archived_at IS NULL \
|
||||
ORDER BY lower(p.surname), lower(p.first_name), p.id",
|
||||
)
|
||||
.bind(company)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, surname, first, middle, nationality, permit)| {
|
||||
let permit = match permit {
|
||||
None => Status {
|
||||
level: "warn",
|
||||
label: "No work permit recorded".into(),
|
||||
},
|
||||
Some(d) if d < today => Status {
|
||||
level: "bad",
|
||||
label: format!("Work permit expired {}", dates::fmt_date(d)),
|
||||
},
|
||||
Some(d) if d <= today + TimeDelta::days(60) => Status {
|
||||
level: "warn",
|
||||
label: format!("Work permit expires {}", dates::relative(today, d)),
|
||||
},
|
||||
Some(d) => Status {
|
||||
level: "ok",
|
||||
label: format!("Work permit until {}", dates::fmt_date(d)),
|
||||
},
|
||||
};
|
||||
Employee {
|
||||
id,
|
||||
name: full_name(&surname, &first, &middle),
|
||||
nationality: countries::name(&nationality)
|
||||
.unwrap_or(&nationality)
|
||||
.to_string(),
|
||||
permit,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn full_name(surname: &str, first: &str, middle: &str) -> String {
|
||||
let given = if middle.is_empty() {
|
||||
first.to_string()
|
||||
} else {
|
||||
format!("{first} {middle}")
|
||||
};
|
||||
format!("{}, {given}", surname.to_uppercase())
|
||||
}
|
||||
|
||||
/// People who could be added as employees: everyone in the list whom the
|
||||
/// company does not employ yet, with their current employer.
|
||||
pub async fn candidates(db: &PgPool, company: i64) -> Result<Vec<(String, String)>> {
|
||||
type Row = (i64, String, String, String, Option<String>);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT p.id, p.surname, p.first_name, p.middle_name, c.name \
|
||||
FROM people p LEFT JOIN companies c ON c.id = p.employer_id \
|
||||
WHERE p.archived_at IS NULL AND p.employer_id IS DISTINCT FROM $1 \
|
||||
ORDER BY lower(p.surname), lower(p.first_name), p.id",
|
||||
)
|
||||
.bind(company)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, surname, first, middle, employer)| {
|
||||
let mut label = full_name(&surname, &first, &middle);
|
||||
if let Some(e) = employer {
|
||||
label = format!("{label} (now with {e})");
|
||||
}
|
||||
(id.to_string(), label)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Makes the company the person's employer; false when it already was or
|
||||
/// the person is archived.
|
||||
pub async fn hire(conn: &mut PgConnection, company: i64, person: i64) -> Result<bool> {
|
||||
let done = sqlx::query(
|
||||
"UPDATE people SET employer_id = $2, updated_at = now() \
|
||||
WHERE id = $1 AND archived_at IS NULL AND employer_id IS DISTINCT FROM $2",
|
||||
)
|
||||
.bind(person)
|
||||
.bind(company)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(done.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// Ends the employment in the records; false when the company was not the
|
||||
/// person's employer.
|
||||
pub async fn release(conn: &mut PgConnection, company: i64, person: i64) -> Result<bool> {
|
||||
let done = sqlx::query(
|
||||
"UPDATE people SET employer_id = NULL, updated_at = now() \
|
||||
WHERE id = $1 AND employer_id = $2",
|
||||
)
|
||||
.bind(person)
|
||||
.bind(company)
|
||||
.execute(conn)
|
||||
.await?;
|
||||
Ok(done.rows_affected() == 1)
|
||||
}
|
||||
|
||||
/// A company as its page shows it.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct View {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub name_th: String,
|
||||
pub registration_no: String,
|
||||
pub business: String,
|
||||
pub address: String,
|
||||
pub phone: String,
|
||||
pub email: String,
|
||||
pub signatory: String,
|
||||
pub signatory_position: String,
|
||||
pub notes: String,
|
||||
pub archived: bool,
|
||||
pub archived_on: String,
|
||||
}
|
||||
|
||||
pub fn view(r: &Record, archived_at: Option<DateTime<Utc>>) -> View {
|
||||
let address = people::address_line(&AddressInput {
|
||||
house_no: r.get("house_no").into(),
|
||||
moo: r.get("moo").into(),
|
||||
building: r.get("building").into(),
|
||||
soi: r.get("soi").into(),
|
||||
road: r.get("road").into(),
|
||||
subdistrict: r.get("subdistrict").into(),
|
||||
district: r.get("district").into(),
|
||||
province: r.get("province").into(),
|
||||
postal_code: r.get("postal_code").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(),
|
||||
});
|
||||
View {
|
||||
id: r.id,
|
||||
name: r.get("name").into(),
|
||||
name_th: r.get("name_th").into(),
|
||||
registration_no: r.get("registration_no").into(),
|
||||
business: r.get("business").into(),
|
||||
address,
|
||||
phone: r.get("phone").into(),
|
||||
email: r.get("email").into(),
|
||||
signatory: r.get("signatory").into(),
|
||||
signatory_position: r.get("signatory_position").into(),
|
||||
notes: r.get("notes").into(),
|
||||
archived: archived_at.is_some(),
|
||||
archived_on: archived_at
|
||||
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
+1166
File diff suppressed because it is too large.
Load diff
@@ -2,15 +2,18 @@
|
||||
//! for foreigners in Thailand (docs/PLAN.md).
|
||||
|
||||
pub mod audit;
|
||||
pub mod companies;
|
||||
pub mod config;
|
||||
pub mod countries;
|
||||
pub mod dates;
|
||||
pub mod db;
|
||||
pub mod deadlines;
|
||||
pub mod embedded;
|
||||
pub mod forms;
|
||||
pub mod mrz;
|
||||
pub mod oidc;
|
||||
pub mod people;
|
||||
pub mod records;
|
||||
pub mod seed;
|
||||
pub mod session;
|
||||
pub mod web;
|
||||
|
||||
+50
-21
@@ -46,7 +46,7 @@ pub struct Person {
|
||||
pub place_of_birth: String,
|
||||
pub nationality: String,
|
||||
pub occupation: String,
|
||||
pub employer: String,
|
||||
pub employer_id: Option<i64>,
|
||||
pub phone: String,
|
||||
pub email: String,
|
||||
pub notes: String,
|
||||
@@ -86,6 +86,7 @@ pub struct PersonForm {
|
||||
pub place_of_birth: String,
|
||||
pub nationality: String,
|
||||
pub occupation: String,
|
||||
/// The employer's company id, from the selection.
|
||||
pub employer: String,
|
||||
pub phone: String,
|
||||
pub email: String,
|
||||
@@ -104,7 +105,8 @@ pub struct PersonInput {
|
||||
pub place_of_birth: String,
|
||||
pub nationality: String,
|
||||
pub occupation: String,
|
||||
pub employer: String,
|
||||
/// The employer's company.
|
||||
pub employer: Option<i64>,
|
||||
pub phone: String,
|
||||
pub email: String,
|
||||
pub notes: String,
|
||||
@@ -130,7 +132,7 @@ impl From<&Person> for PersonInput {
|
||||
place_of_birth: p.place_of_birth.clone(),
|
||||
nationality: p.nationality.clone(),
|
||||
occupation: p.occupation.clone(),
|
||||
employer: p.employer.clone(),
|
||||
employer: p.employer_id,
|
||||
phone: p.phone.clone(),
|
||||
email: p.email.clone(),
|
||||
notes: p.notes.clone(),
|
||||
@@ -171,7 +173,7 @@ impl PersonForm {
|
||||
place_of_birth: p.place_of_birth.clone(),
|
||||
nationality: p.nationality.clone(),
|
||||
occupation: p.occupation.clone(),
|
||||
employer: p.employer.clone(),
|
||||
employer: p.employer_id.map(|c| c.to_string()).unwrap_or_default(),
|
||||
phone: p.phone.clone(),
|
||||
email: p.email.clone(),
|
||||
notes: p.notes.clone(),
|
||||
@@ -199,8 +201,17 @@ impl PersonForm {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self, today: NaiveDate) -> Result<PersonInput, Errors> {
|
||||
/// `companies`: the ids the employer may be chosen from.
|
||||
pub fn validate(&self, today: NaiveDate, companies: &[i64]) -> Result<PersonInput, Errors> {
|
||||
let mut e = Errors::new();
|
||||
let employer = match self.employer.parse::<i64>() {
|
||||
_ if self.employer.is_empty() => None,
|
||||
Ok(c) if companies.contains(&c) => Some(c),
|
||||
_ => {
|
||||
err(&mut e, "employer", "Choose a company from the list.");
|
||||
None
|
||||
}
|
||||
};
|
||||
if self.surname.is_empty() {
|
||||
err(
|
||||
&mut e,
|
||||
@@ -248,7 +259,7 @@ impl PersonForm {
|
||||
place_of_birth: self.place_of_birth.clone(),
|
||||
nationality: self.nationality.clone(),
|
||||
occupation: self.occupation.clone(),
|
||||
employer: self.employer.clone(),
|
||||
employer,
|
||||
phone: self.phone.clone(),
|
||||
email: self.email.clone(),
|
||||
notes: self.notes.clone(),
|
||||
@@ -256,7 +267,7 @@ impl PersonForm {
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_like_email(s: &str) -> bool {
|
||||
pub fn looks_like_email(s: &str) -> bool {
|
||||
match s.split_once('@') {
|
||||
Some((user, host)) => {
|
||||
!user.is_empty() && host.contains('.') && !host.starts_with('.') && !s.contains(' ')
|
||||
@@ -295,7 +306,7 @@ pub async fn get_person_in(conn: &mut PgConnection, id: i64) -> Result<Option<Pe
|
||||
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) \
|
||||
place_of_birth, nationality, occupation, employer_id, phone, email, notes) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id",
|
||||
)
|
||||
.bind(&p.surname)
|
||||
@@ -307,7 +318,7 @@ pub async fn create_person(conn: &mut PgConnection, p: &PersonInput) -> Result<i
|
||||
.bind(&p.place_of_birth)
|
||||
.bind(&p.nationality)
|
||||
.bind(&p.occupation)
|
||||
.bind(&p.employer)
|
||||
.bind(p.employer)
|
||||
.bind(&p.phone)
|
||||
.bind(&p.email)
|
||||
.bind(&p.notes)
|
||||
@@ -320,7 +331,7 @@ pub async fn update_person(conn: &mut PgConnection, id: i64, p: &PersonInput) ->
|
||||
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, \
|
||||
occupation = $10, employer_id = $11, phone = $12, email = $13, notes = $14, \
|
||||
updated_at = now() WHERE id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
@@ -333,7 +344,7 @@ pub async fn update_person(conn: &mut PgConnection, id: i64, p: &PersonInput) ->
|
||||
.bind(&p.place_of_birth)
|
||||
.bind(&p.nationality)
|
||||
.bind(&p.occupation)
|
||||
.bind(&p.employer)
|
||||
.bind(p.employer)
|
||||
.bind(&p.phone)
|
||||
.bind(&p.email)
|
||||
.bind(&p.notes)
|
||||
@@ -363,7 +374,8 @@ struct ListRow {
|
||||
middle_name: String,
|
||||
nationality: String,
|
||||
date_of_birth: Option<NaiveDate>,
|
||||
employer: String,
|
||||
employer_id: Option<i64>,
|
||||
employer: Option<String>,
|
||||
passport_number: Option<String>,
|
||||
passport_expires: Option<NaiveDate>,
|
||||
province: Option<String>,
|
||||
@@ -376,30 +388,42 @@ pub struct ListItem {
|
||||
pub name: String,
|
||||
pub nationality: String,
|
||||
pub age: Option<i32>,
|
||||
pub employer_id: Option<i64>,
|
||||
pub employer: String,
|
||||
pub passport_number: String,
|
||||
pub passport_expires: String,
|
||||
pub passport_status: Option<dates::Status>,
|
||||
pub province: String,
|
||||
/// The most urgent deadline; the page fills it in.
|
||||
pub next: Option<crate::deadlines::Deadline>,
|
||||
/// Lower-case text the filter box searches.
|
||||
pub q: String,
|
||||
}
|
||||
|
||||
pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result<Vec<ListItem>> {
|
||||
/// The people in the list or in the archive; with `company`, only those it
|
||||
/// employs.
|
||||
pub async fn list(
|
||||
db: &PgPool,
|
||||
archived: bool,
|
||||
company: Option<i64>,
|
||||
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 \
|
||||
p.employer_id, c.name AS employer, pp.number AS passport_number, \
|
||||
pp.expires_on AS passport_expires, a.province \
|
||||
FROM people p \
|
||||
LEFT JOIN companies c ON c.id = p.employer_id \
|
||||
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 \
|
||||
WHERE (p.archived_at IS NOT NULL) = $1 AND ($2::bigint IS NULL OR p.employer_id = $2) \
|
||||
ORDER BY lower(p.surname), lower(p.first_name), p.id",
|
||||
)
|
||||
.bind(archived)
|
||||
.bind(company)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
@@ -415,9 +439,10 @@ pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result<Vec<L
|
||||
.to_string();
|
||||
let passport_number = r.passport_number.unwrap_or_default();
|
||||
let province = r.province.unwrap_or_default();
|
||||
let employer = r.employer.unwrap_or_default();
|
||||
let q = format!(
|
||||
"{name} {nationality} {} {passport_number} {} {province}",
|
||||
r.nationality, r.employer
|
||||
"{name} {nationality} {} {passport_number} {employer} {province}",
|
||||
r.nationality
|
||||
)
|
||||
.to_lowercase();
|
||||
ListItem {
|
||||
@@ -427,9 +452,11 @@ pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result<Vec<L
|
||||
passport_status: r.passport_expires.map(|d| dates::passport_status(d, today)),
|
||||
name,
|
||||
nationality,
|
||||
employer: r.employer,
|
||||
employer_id: r.employer_id,
|
||||
employer,
|
||||
passport_number,
|
||||
province,
|
||||
next: None,
|
||||
q,
|
||||
}
|
||||
})
|
||||
@@ -1085,7 +1112,7 @@ mod tests {
|
||||
]));
|
||||
assert_eq!(f.surname, "Mustermann");
|
||||
assert_eq!(f.nationality, "DEU");
|
||||
let e = f.validate(today).unwrap_err();
|
||||
let e = f.validate(today, &[]).unwrap_err();
|
||||
assert_eq!(
|
||||
e.keys().map(String::as_str).collect::<Vec<_>>(),
|
||||
vec!["date_of_birth", "email", "title"]
|
||||
@@ -1095,9 +1122,11 @@ mod tests {
|
||||
("first_name", "Erika"),
|
||||
("date_of_birth", "1984-08-12"),
|
||||
("nationality", "DEU"),
|
||||
("employer", "3"),
|
||||
]))
|
||||
.validate(today)
|
||||
.validate(today, &[3])
|
||||
.unwrap();
|
||||
assert_eq!(ok.employer, Some(3));
|
||||
assert_eq!(ok.date_of_birth, Some(d("1984-08-12")));
|
||||
let mut other = ok.clone();
|
||||
other.email = "erika@example.com".into();
|
||||
|
||||
+1251
File diff suppressed because it is too large.
Load diff
+318
-44
@@ -1,15 +1,17 @@
|
||||
//! Demo data for development: invented people only (specimen names, numbers
|
||||
//! that belong to nobody). `visa seed-demo` refuses to run when the login is
|
||||
//! on, so it never writes into production.
|
||||
//! Demo data for development: invented people and companies only (specimen
|
||||
//! names, numbers that belong to nobody). `visa seed-demo` refuses to run
|
||||
//! when the login is on, so it never writes into production. The dates are
|
||||
//! relative to the day it runs, so every kind of deadline shows.
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::NaiveDate;
|
||||
use chrono::{NaiveDate, TimeDelta};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::dates;
|
||||
use crate::mrz;
|
||||
use crate::people::{self, AddressInput, PassportInput, PersonInput};
|
||||
use crate::records::{self, Kind, Values};
|
||||
|
||||
pub const MARKER: &str = "Demo record, invented for development.";
|
||||
|
||||
@@ -17,10 +19,23 @@ fn d(s: &str) -> NaiveDate {
|
||||
dates::parse_date(s).expect("demo dates are valid")
|
||||
}
|
||||
|
||||
/// A record's values; `"@passport"`, `"@visa"` and `"@employer"` stand for
|
||||
/// the person's current passport, the visa recorded last and the employer.
|
||||
macro_rules! vals {
|
||||
($($k:literal => $v:expr),* $(,)?) => {{
|
||||
let mut m = Values::new();
|
||||
$( m.insert($k.to_string(), $v.to_string()); )*
|
||||
m
|
||||
}};
|
||||
}
|
||||
|
||||
struct Demo {
|
||||
person: PersonInput,
|
||||
/// An index into `companies()`.
|
||||
employer: Option<usize>,
|
||||
passports: Vec<PassportInput>,
|
||||
addresses: Vec<AddressInput>,
|
||||
stays: Vec<(&'static Kind, Values)>,
|
||||
archived: bool,
|
||||
}
|
||||
|
||||
@@ -35,7 +50,6 @@ fn person(
|
||||
place: &str,
|
||||
nationality: &str,
|
||||
occupation: &str,
|
||||
employer: &str,
|
||||
n: u32,
|
||||
) -> PersonInput {
|
||||
PersonInput {
|
||||
@@ -48,7 +62,7 @@ fn person(
|
||||
place_of_birth: place.into(),
|
||||
nationality: nationality.into(),
|
||||
occupation: occupation.into(),
|
||||
employer: employer.into(),
|
||||
employer: None,
|
||||
phone: format!("+66 80 000 000{n}"),
|
||||
email: format!(
|
||||
"{}.{}@example.com",
|
||||
@@ -72,21 +86,19 @@ fn passport(
|
||||
} else {
|
||||
format!("{} {}", p.first_name, p.middle_name)
|
||||
};
|
||||
// Germany's code in the zone is D
|
||||
let state = if p.nationality == "DEU" {
|
||||
"D"
|
||||
} else {
|
||||
p.nationality.as_str()
|
||||
};
|
||||
let mrz = if with_mrz {
|
||||
mrz::compose(&mrz::Compose {
|
||||
issuing_state: if p.nationality == "DEU" {
|
||||
"D"
|
||||
} else {
|
||||
p.nationality.as_str()
|
||||
},
|
||||
issuing_state: state,
|
||||
surname: &p.surname,
|
||||
given_names: &given,
|
||||
number,
|
||||
nationality: if p.nationality == "DEU" {
|
||||
"D"
|
||||
} else {
|
||||
p.nationality.as_str()
|
||||
},
|
||||
nationality: state,
|
||||
date_of_birth: p.date_of_birth.expect("demo people have birth dates"),
|
||||
sex: &p.sex,
|
||||
expiry_date: d(expires),
|
||||
@@ -138,11 +150,55 @@ fn address(
|
||||
}
|
||||
}
|
||||
|
||||
/// Two invented companies; their registration numbers carry valid check
|
||||
/// digits but no real company has them (province code 99 does not exist).
|
||||
fn companies() -> Vec<Values> {
|
||||
vec![
|
||||
vals! {
|
||||
"name" => "Demo Engineering Co., Ltd.",
|
||||
"name_th" => "บริษัท เดโม เอ็นจิเนียริ่ง จำกัด",
|
||||
"registration_no" => "0999999000004",
|
||||
"business" => "Engineering services",
|
||||
"house_no" => "88/8",
|
||||
"building" => "Demo Tower, fifth floor",
|
||||
"road" => "Superhighway Road",
|
||||
"subdistrict" => "Wat Ket",
|
||||
"district" => "Mueang Chiang Mai",
|
||||
"province" => "Chiang Mai",
|
||||
"postal_code" => "50000",
|
||||
"phone" => "+66 53 000 000",
|
||||
"email" => "office@demo-engineering.example",
|
||||
"signatory" => "Malee Jaidee",
|
||||
"signatory_position" => "Managing director",
|
||||
"notes" => MARKER,
|
||||
},
|
||||
vals! {
|
||||
"name" => "Demo Accounting Partnership",
|
||||
"name_th" => "ห้างหุ้นส่วนจำกัด เดโม แอคเคาน์ติ้ง",
|
||||
"registration_no" => "0999999000012",
|
||||
"business" => "Accounting",
|
||||
"house_no" => "55",
|
||||
"moo" => "2",
|
||||
"subdistrict" => "Ban Klang",
|
||||
"district" => "Mueang Lamphun",
|
||||
"province" => "Lamphun",
|
||||
"postal_code" => "51000",
|
||||
"phone" => "+66 53 000 001",
|
||||
"signatory" => "Prasert Jaidee",
|
||||
"signatory_position" => "Managing partner",
|
||||
"notes" => MARKER,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Dates relative to `today`, so the warnings show whenever the seed runs.
|
||||
fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
let plus = |days: i64| (today + chrono::TimeDelta::days(days)).to_string();
|
||||
let employer = "Demo Engineering Co., Ltd.";
|
||||
let plus = |days: i64| (today + TimeDelta::days(days)).to_string();
|
||||
const CNX: &str = "Chiang Mai International Airport";
|
||||
const OFFICE: &str = "Chiang Mai Immigration Office";
|
||||
|
||||
// Non-B with a work permit, back from a trip on a re-entry permit: the
|
||||
// 90-day report is due in ten days, the extension window opens in 30.
|
||||
let erika = person(
|
||||
"Mustermann",
|
||||
"Erika",
|
||||
@@ -153,7 +209,6 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Berlin",
|
||||
"DEU",
|
||||
"Electrical engineer",
|
||||
employer,
|
||||
1,
|
||||
);
|
||||
let erika_pp = passport(
|
||||
@@ -164,6 +219,73 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Stadt Koeln",
|
||||
true,
|
||||
);
|
||||
let erika_stays = vec![
|
||||
(
|
||||
&records::VISAS,
|
||||
vals! {
|
||||
"category" => "non-b", "entries" => "single", "number" => "V0000101",
|
||||
"passport_id" => "@passport", "issued_at" => "Royal Thai Embassy, Berlin",
|
||||
"issued_on" => plus(-440), "valid_until" => plus(-350),
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::ARRIVALS,
|
||||
vals! {
|
||||
"arrived_on" => plus(-394), "port" => CNX, "admission" => "visa",
|
||||
"visa_id" => "@visa", "permitted_until" => plus(-305), "passport_id" => "@passport",
|
||||
"flight" => "TG110", "tdac_no" => "DEMO0001", "tdac_submitted_on" => plus(-396),
|
||||
"departed_on" => plus(-90), "departure_port" => CNX,
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::EXTENSIONS,
|
||||
vals! {
|
||||
"applied_on" => plus(-310), "basis" => "work", "decision" => "approved",
|
||||
"permitted_until" => plus(60), "office" => OFFICE, "receipt_no" => "DEMO-R-0101",
|
||||
"fee_thb" => "1900",
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::REPORTS,
|
||||
vals! {
|
||||
"reported_on" => plus(-222), "method" => "in-person",
|
||||
"receipt_no" => "DEMO-90-0001", "next_due_on" => plus(-132),
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::REPORTS,
|
||||
vals! {
|
||||
"reported_on" => plus(-135), "method" => "online",
|
||||
"receipt_no" => "DEMO-90-0002", "next_due_on" => plus(-45),
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::REENTRY_PERMITS,
|
||||
vals! {
|
||||
"kind" => "multiple", "number" => "DEMO-RE-0001", "issued_on" => plus(-300),
|
||||
"valid_until" => plus(60), "office" => OFFICE,
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::ARRIVALS,
|
||||
vals! {
|
||||
"arrived_on" => plus(-79), "port" => CNX, "admission" => "reentry",
|
||||
"permitted_until" => plus(60), "passport_id" => "@passport", "flight" => "TG111",
|
||||
"tdac_no" => "DEMO0002", "tdac_submitted_on" => plus(-81),
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::WORK_PERMITS,
|
||||
vals! {
|
||||
"company_id" => "@employer", "number" => "WP-DEMO-0001",
|
||||
"position" => "Electrical engineer", "issued_on" => plus(-300),
|
||||
"valid_until" => plus(60),
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
// Visa exemption for 60 days, starting at the company: the extension
|
||||
// window is open, the passport has under six months, no TM.30 yet.
|
||||
let jane = person(
|
||||
"Doe",
|
||||
"Jane",
|
||||
@@ -174,7 +296,6 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Portland, Oregon",
|
||||
"USA",
|
||||
"Product designer",
|
||||
employer,
|
||||
2,
|
||||
);
|
||||
let jane_old = passport(
|
||||
@@ -193,6 +314,16 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"U.S. Department of State",
|
||||
true,
|
||||
);
|
||||
let jane_stays = vec![(
|
||||
&records::ARRIVALS,
|
||||
vals! {
|
||||
"arrived_on" => plus(-40), "port" => CNX, "admission" => "exempt",
|
||||
"permitted_until" => plus(20), "passport_id" => "@passport", "flight" => "TG102",
|
||||
"tdac_no" => "DEMO0003", "tdac_submitted_on" => plus(-42),
|
||||
},
|
||||
)];
|
||||
|
||||
// Married to a Thai national, extended twice: the 90-day report is late.
|
||||
let tomas = person(
|
||||
"Novak",
|
||||
"Tomas",
|
||||
@@ -203,10 +334,86 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Brno",
|
||||
"CZE",
|
||||
"Accountant",
|
||||
"Demo Accounting Partnership",
|
||||
3,
|
||||
);
|
||||
let tomas_pp = passport(&tomas, "40000001", "2018-01-15", &plus(300), "Brno", true);
|
||||
let tomas_stays = vec![
|
||||
(
|
||||
&records::VISAS,
|
||||
vals! {
|
||||
"category" => "non-o", "entries" => "single", "number" => "V0000303",
|
||||
"passport_id" => "@passport", "issued_at" => "Royal Thai Embassy, Prague",
|
||||
"issued_on" => plus(-800), "valid_until" => plus(-710),
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::ARRIVALS,
|
||||
vals! {
|
||||
"arrived_on" => plus(-760), "port" => "Suvarnabhumi Airport", "admission" => "visa",
|
||||
"visa_id" => "@visa", "permitted_until" => plus(-671), "passport_id" => "@passport",
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::EXTENSIONS,
|
||||
vals! {
|
||||
"applied_on" => plus(-680), "basis" => "marriage", "decision" => "approved",
|
||||
"permitted_until" => plus(-306), "office" => OFFICE, "fee_thb" => "1900",
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::EXTENSIONS,
|
||||
vals! {
|
||||
"applied_on" => plus(-320), "basis" => "marriage", "decision" => "approved",
|
||||
"permitted_until" => plus(45), "office" => OFFICE, "receipt_no" => "DEMO-R-0303",
|
||||
"fee_thb" => "1900",
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::REPORTS,
|
||||
vals! {
|
||||
"reported_on" => plus(-101), "method" => "agent",
|
||||
"receipt_no" => "DEMO-90-0303", "next_due_on" => plus(-11),
|
||||
},
|
||||
),
|
||||
(
|
||||
&records::WORK_PERMITS,
|
||||
vals! {
|
||||
"company_id" => "@employer", "number" => "WP-DEMO-0003", "position" => "Accountant",
|
||||
"issued_on" => plus(-320), "valid_until" => plus(45),
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
// Hired, still abroad: the visa has to be used within 70 days.
|
||||
let sofia = person(
|
||||
"Ejemplo",
|
||||
"Sofia",
|
||||
"",
|
||||
"Ms",
|
||||
"F",
|
||||
"1993-04-21",
|
||||
"Valencia",
|
||||
"ESP",
|
||||
"Project engineer",
|
||||
5,
|
||||
);
|
||||
let sofia_pp = passport(
|
||||
&sofia,
|
||||
"XDE000505",
|
||||
"2023-06-01",
|
||||
"2033-05-31",
|
||||
"Valencia",
|
||||
true,
|
||||
);
|
||||
let sofia_stays = vec![(
|
||||
&records::VISAS,
|
||||
vals! {
|
||||
"category" => "non-b", "entries" => "single", "number" => "V0000505",
|
||||
"passport_id" => "@passport", "issued_at" => "e-Visa",
|
||||
"issued_on" => plus(-20), "valid_until" => plus(70),
|
||||
},
|
||||
)];
|
||||
|
||||
let old = person(
|
||||
"Sample",
|
||||
"Oliver",
|
||||
@@ -217,7 +424,6 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Leeds",
|
||||
"GBR",
|
||||
"Retired",
|
||||
"",
|
||||
4,
|
||||
);
|
||||
let old_pp = passport(&old, "100000001", "2014-01-10", "2024-01-10", "HMPO", false);
|
||||
@@ -225,6 +431,7 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
vec![
|
||||
Demo {
|
||||
person: erika,
|
||||
employer: Some(0),
|
||||
passports: vec![erika_pp],
|
||||
addresses: vec![
|
||||
address(
|
||||
@@ -237,9 +444,9 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Mueang Chiang Mai",
|
||||
"Chiang Mai",
|
||||
"50200",
|
||||
"2025-06-01",
|
||||
Some("2026-02-28"),
|
||||
Some(("2025-06-02", "TM30-DEMO-0007")),
|
||||
&plus(-900),
|
||||
Some(&plus(-500)),
|
||||
Some((&plus(-899), "TM30-DEMO-0007")),
|
||||
),
|
||||
address(
|
||||
"99/9",
|
||||
@@ -251,15 +458,17 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Mueang Chiang Mai",
|
||||
"Chiang Mai",
|
||||
"50300",
|
||||
"2026-03-01",
|
||||
&plus(-500),
|
||||
None,
|
||||
Some(("2026-03-02", "TM30-DEMO-0012")),
|
||||
Some((&plus(-78), "TM30-DEMO-0012")),
|
||||
),
|
||||
],
|
||||
stays: erika_stays,
|
||||
archived: false,
|
||||
},
|
||||
Demo {
|
||||
person: jane,
|
||||
employer: Some(0),
|
||||
passports: vec![jane_old, jane_pp],
|
||||
addresses: vec![address(
|
||||
"1/23",
|
||||
@@ -271,14 +480,16 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Mueang Chiang Mai",
|
||||
"Chiang Mai",
|
||||
"50300",
|
||||
"2026-09-15",
|
||||
&plus(-38),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
stays: jane_stays,
|
||||
archived: false,
|
||||
},
|
||||
Demo {
|
||||
person: tomas,
|
||||
employer: Some(1),
|
||||
passports: vec![tomas_pp],
|
||||
addresses: vec![address(
|
||||
"55",
|
||||
@@ -290,22 +501,45 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"Mueang Lamphun",
|
||||
"Lamphun",
|
||||
"51000",
|
||||
"2024-11-01",
|
||||
&plus(-700),
|
||||
None,
|
||||
Some(("2024-11-01", "TM30-DEMO-0003")),
|
||||
Some((&plus(-700), "TM30-DEMO-0003")),
|
||||
)],
|
||||
stays: tomas_stays,
|
||||
archived: false,
|
||||
},
|
||||
Demo {
|
||||
person: sofia,
|
||||
employer: Some(0),
|
||||
passports: vec![sofia_pp],
|
||||
addresses: vec![],
|
||||
stays: sofia_stays,
|
||||
archived: false,
|
||||
},
|
||||
Demo {
|
||||
person: old,
|
||||
employer: None,
|
||||
passports: vec![old_pp],
|
||||
addresses: vec![],
|
||||
stays: vec![],
|
||||
archived: true,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Adds the demo people unless they are there already; true when it did.
|
||||
fn seeded(action: Action, entity: Entity, id: i64, person: Option<i64>) -> Entry<'static> {
|
||||
Entry {
|
||||
actor: "seed",
|
||||
action,
|
||||
entity,
|
||||
entity_id: Some(id),
|
||||
person_id: person,
|
||||
fields: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the demo companies and people unless they are there already; true
|
||||
/// when it did.
|
||||
pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
||||
let present: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM people WHERE notes = $1)")
|
||||
.bind(MARKER)
|
||||
@@ -315,28 +549,68 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut tx = db.begin().await?;
|
||||
let log = |action, entity, id, person| Entry {
|
||||
actor: "seed",
|
||||
action,
|
||||
entity,
|
||||
entity_id: Some(id),
|
||||
person_id: Some(person),
|
||||
fields: &[],
|
||||
};
|
||||
for demo in demos(today) {
|
||||
let mut company_ids = Vec::new();
|
||||
for c in companies() {
|
||||
let id = records::create(&mut tx, &records::COMPANIES, None, &c).await?;
|
||||
audit::record(&mut *tx, &seeded(Action::Create, Entity::Company, id, None)).await?;
|
||||
company_ids.push(id);
|
||||
}
|
||||
for mut demo in demos(today) {
|
||||
demo.person.employer = demo.employer.map(|i| company_ids[i]);
|
||||
let id = people::create_person(&mut tx, &demo.person).await?;
|
||||
audit::record(&mut *tx, &log(Action::Create, Entity::Person, id, id)).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&seeded(Action::Create, Entity::Person, id, Some(id)),
|
||||
)
|
||||
.await?;
|
||||
let mut current: Option<(NaiveDate, i64)> = None;
|
||||
for p in &demo.passports {
|
||||
let pid = people::create_passport(&mut tx, id, p).await?;
|
||||
audit::record(&mut *tx, &log(Action::Create, Entity::Passport, pid, id)).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&seeded(Action::Create, Entity::Passport, pid, Some(id)),
|
||||
)
|
||||
.await?;
|
||||
if current.is_none_or(|(e, _)| p.expires_on > e) {
|
||||
current = Some((p.expires_on, pid));
|
||||
}
|
||||
}
|
||||
for a in &demo.addresses {
|
||||
let aid = people::create_address(&mut tx, id, a).await?;
|
||||
audit::record(&mut *tx, &log(Action::Create, Entity::Address, aid, id)).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&seeded(Action::Create, Entity::Address, aid, Some(id)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
let mut last_visa: Option<i64> = None;
|
||||
for (kind, mut values) in demo.stays {
|
||||
for v in values.values_mut() {
|
||||
let id_of = |x: Option<i64>| x.map(|i| i.to_string()).unwrap_or_default();
|
||||
match v.as_str() {
|
||||
"@passport" => *v = id_of(current.map(|c| c.1)),
|
||||
"@visa" => *v = id_of(last_visa),
|
||||
"@employer" => *v = id_of(demo.person.employer),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let rid = records::create(&mut tx, kind, Some(id), &values).await?;
|
||||
if kind.slug == records::VISAS.slug {
|
||||
last_visa = Some(rid);
|
||||
}
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&seeded(Action::Create, kind.entity, rid, Some(id)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if demo.archived {
|
||||
people::set_archived(&mut tx, id, true).await?;
|
||||
audit::record(&mut *tx, &log(Action::Archive, Entity::Person, id, id)).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&seeded(Action::Archive, Entity::Person, id, Some(id)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Pages for companies: the list, a company with the people it employs, the
|
||||
//! form, archiving, and adding or removing employees.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use axum::{Extension, Form};
|
||||
use minijinja::context;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::records::datalists;
|
||||
use super::{AppState, Res, not_found_page, page};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::companies;
|
||||
use crate::dates;
|
||||
use crate::forms::{Errors, Fields, err, get};
|
||||
use crate::records::{self, COMPANIES, Options, Values};
|
||||
use crate::session::User;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ListQuery {
|
||||
#[serde(default)]
|
||||
archived: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<ListQuery>,
|
||||
) -> Res {
|
||||
let archived = q.archived.as_deref() == Some("1");
|
||||
let rows = companies::list(&st.db, archived).await?;
|
||||
let (n_active, n_archived) = companies::counts(&st.db).await?;
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"companies.html",
|
||||
if archived {
|
||||
"Archived companies"
|
||||
} else {
|
||||
"Companies"
|
||||
},
|
||||
"companies",
|
||||
StatusCode::OK,
|
||||
context! { companies => rows, archived, n_active, n_archived },
|
||||
))
|
||||
}
|
||||
|
||||
fn company_entry<'a>(user: &'a User, action: Action, id: i64, fields: &'a [String]) -> Entry<'a> {
|
||||
Entry {
|
||||
actor: &user.login,
|
||||
action,
|
||||
entity: Entity::Company,
|
||||
entity_id: Some(id),
|
||||
person_id: None,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
fn form_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
company: Option<(i64, &str)>,
|
||||
values: &Values,
|
||||
errors: &Errors,
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
let (heading, mode, action, cancel) = match company {
|
||||
Some((id, name)) => (
|
||||
format!("Edit {name}"),
|
||||
"edit",
|
||||
format!("/companies/{id}"),
|
||||
format!("/companies/{id}"),
|
||||
),
|
||||
None => (
|
||||
"New company".to_string(),
|
||||
"new",
|
||||
"/companies".to_string(),
|
||||
"/companies".to_string(),
|
||||
),
|
||||
};
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"record_form.html",
|
||||
&heading,
|
||||
"companies",
|
||||
status,
|
||||
context! {
|
||||
heading,
|
||||
one => "company",
|
||||
lead => COMPANIES.lead,
|
||||
mode,
|
||||
action,
|
||||
fields => records::form_fields(&COMPANIES, &Options::default()),
|
||||
values,
|
||||
errors,
|
||||
cancel,
|
||||
..datalists()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
|
||||
Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
None,
|
||||
&Values::new(),
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
async fn checked(st: &AppState, f: &Fields, id: Option<i64>) -> anyhow::Result<(Values, Errors)> {
|
||||
let values = records::read(&COMPANIES, f);
|
||||
let mut errors = records::validate(&COMPANIES, &values, &Options::default());
|
||||
let reg = values
|
||||
.get("registration_no")
|
||||
.map(String::as_str)
|
||||
.unwrap_or("");
|
||||
if !errors.contains_key("registration_no")
|
||||
&& companies::registration_taken(&st.db, reg, id).await?
|
||||
{
|
||||
err(
|
||||
&mut errors,
|
||||
"registration_no",
|
||||
"Another company has this registration number.",
|
||||
);
|
||||
}
|
||||
Ok((values, errors))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let (values, errors) = checked(&st, &f, None).await?;
|
||||
if !errors.is_empty() {
|
||||
return Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
None,
|
||||
&values,
|
||||
&errors,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
let mut tx = st.db.begin().await?;
|
||||
let id = records::create(&mut tx, &COMPANIES, None, &values).await?;
|
||||
audit::record(&mut *tx, &company_entry(&user, Action::Create, id, &[])).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
|
||||
}
|
||||
|
||||
pub async fn show(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let archived_at = companies::archived_at(&st.db, id).await?.flatten();
|
||||
let c = companies::view(&r, archived_at);
|
||||
let employees = companies::employees(&st.db, id, dates::today()).await?;
|
||||
let candidates = companies::candidates(&st.db, id).await?;
|
||||
let title = c.name.clone();
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"company.html",
|
||||
&title,
|
||||
"companies",
|
||||
StatusCode::OK,
|
||||
context! { c, employees, candidates },
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn edit_form(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
Some((id, r.get("name"))),
|
||||
&r.values,
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let mut tx = st.db.begin().await?;
|
||||
let Some(old) = records::get_for_update(&mut tx, &COMPANIES, None, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let (values, errors) = checked(&st, &f, Some(id)).await?;
|
||||
if !errors.is_empty() {
|
||||
return Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
Some((id, old.get("name"))),
|
||||
&values,
|
||||
&errors,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
let changed = records::changed(&COMPANIES, &old.values, &values);
|
||||
if !changed.is_empty() {
|
||||
records::update(&mut tx, &COMPANIES, None, id, &values).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&company_entry(&user, Action::Update, id, &changed),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
|
||||
}
|
||||
|
||||
async fn set_archived(st: &AppState, user: &User, id: i64, archived: bool) -> Res {
|
||||
if companies::archived_at(&st.db, id).await?.is_none() {
|
||||
return Ok(not_found_page(st));
|
||||
}
|
||||
let mut tx = st.db.begin().await?;
|
||||
if companies::set_archived(&mut tx, id, archived).await? {
|
||||
let action = if archived {
|
||||
Action::Archive
|
||||
} else {
|
||||
Action::Restore
|
||||
};
|
||||
audit::record(&mut *tx, &company_entry(user, action, id, &[])).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
|
||||
}
|
||||
|
||||
pub async fn archive(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
set_archived(&st, &user, id, true).await
|
||||
}
|
||||
|
||||
pub async fn restore(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
set_archived(&st, &user, id, false).await
|
||||
}
|
||||
|
||||
fn employer_changed<'a>(user: &'a User, person: i64, fields: &'a [String]) -> Entry<'a> {
|
||||
Entry {
|
||||
actor: &user.login,
|
||||
action: Action::Update,
|
||||
entity: Entity::Person,
|
||||
entity_id: Some(person),
|
||||
person_id: Some(person),
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the person chosen in the selection as an employee.
|
||||
pub async fn hire(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
if companies::archived_at(&st.db, id).await?.is_none() {
|
||||
return Ok(not_found_page(&st));
|
||||
}
|
||||
let chosen = get(&f, "person");
|
||||
let allowed = companies::candidates(&st.db, id).await?;
|
||||
let Some(person) = allowed
|
||||
.iter()
|
||||
.find(|(pid, _)| *pid == chosen)
|
||||
.and_then(|(pid, _)| pid.parse::<i64>().ok())
|
||||
else {
|
||||
return Ok(Redirect::to(&format!("/companies/{id}#people")).into_response());
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
if companies::hire(&mut tx, id, person).await? {
|
||||
let fields = ["employer".to_string()];
|
||||
audit::record(&mut *tx, &employer_changed(&user, person, &fields)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/companies/{id}#people")).into_response())
|
||||
}
|
||||
|
||||
pub async fn release(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, person)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let mut tx = st.db.begin().await?;
|
||||
if companies::release(&mut tx, id, person).await? {
|
||||
let fields = ["employer".to_string()];
|
||||
audit::record(&mut *tx, &employer_changed(&user, person, &fields)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/companies/{id}#people")).into_response())
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//! The Deadlines page at /: every person's coming deadlines, the most
|
||||
//! urgent first.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Extension;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use chrono::TimeDelta;
|
||||
use minijinja::context;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{AppState, Res, page};
|
||||
use crate::companies;
|
||||
use crate::dates;
|
||||
use crate::deadlines::{self, Deadline};
|
||||
use crate::session::User;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DashQuery {
|
||||
/// "1": also what lies beyond the next 90 days.
|
||||
#[serde(default)]
|
||||
all: Option<String>,
|
||||
/// A company's id: only the people it employs.
|
||||
#[serde(default)]
|
||||
company: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Row {
|
||||
person_id: i64,
|
||||
person: String,
|
||||
employer: String,
|
||||
d: Deadline,
|
||||
q: String,
|
||||
}
|
||||
|
||||
/// How far ahead the page looks unless asked for everything; anything
|
||||
/// overdue or close (bad, warn) shows regardless.
|
||||
const HORIZON_DAYS: i64 = 90;
|
||||
|
||||
pub async fn page_handler(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<DashQuery>,
|
||||
) -> Res {
|
||||
let today = dates::today();
|
||||
let all = q.all.as_deref() == Some("1");
|
||||
let company: Option<i64> = q.company.as_deref().and_then(|c| c.parse().ok());
|
||||
let people: Vec<(i64, String, String, String, Option<String>)> = sqlx::query_as(
|
||||
"SELECT p.id, p.surname, p.first_name, p.middle_name, c.name \
|
||||
FROM people p LEFT JOIN companies c ON c.id = p.employer_id \
|
||||
WHERE p.archived_at IS NULL AND ($1::bigint IS NULL OR p.employer_id = $1)",
|
||||
)
|
||||
.bind(company)
|
||||
.fetch_all(&st.db)
|
||||
.await?;
|
||||
let ids: Vec<i64> = people.iter().map(|p| p.0).collect();
|
||||
let mut found = deadlines::for_people(&st.db, &ids, today).await?;
|
||||
let horizon = today + TimeDelta::days(HORIZON_DAYS);
|
||||
let mut rows = Vec::new();
|
||||
for (id, surname, first, middle, employer) in &people {
|
||||
let Some(a) = found.remove(id) else { continue };
|
||||
let given = if middle.is_empty() {
|
||||
first.clone()
|
||||
} else {
|
||||
format!("{first} {middle}")
|
||||
};
|
||||
let person = format!("{}, {given}", surname.to_uppercase());
|
||||
let employer = employer.clone().unwrap_or_default();
|
||||
for d in a.items {
|
||||
let Some(due) = d.due else { continue };
|
||||
let urgent = matches!(d.level, "bad" | "warn");
|
||||
if !all && !urgent && due > horizon {
|
||||
continue;
|
||||
}
|
||||
let q = format!("{person} {employer} {} {}", d.title, d.label).to_lowercase();
|
||||
rows.push(Row {
|
||||
person_id: *id,
|
||||
person: person.clone(),
|
||||
employer: employer.clone(),
|
||||
d,
|
||||
q,
|
||||
});
|
||||
}
|
||||
}
|
||||
rows.sort_by(|x, y| {
|
||||
deadlines::rank(x.d.level)
|
||||
.cmp(&deadlines::rank(y.d.level))
|
||||
.then(x.d.due.cmp(&y.d.due))
|
||||
.then(x.person.cmp(&y.person))
|
||||
});
|
||||
let overdue = rows.iter().filter(|r| r.d.level == "bad").count();
|
||||
let soon = rows.iter().filter(|r| r.d.level == "warn").count();
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"dashboard.html",
|
||||
"Deadlines",
|
||||
"deadlines",
|
||||
StatusCode::OK,
|
||||
context! {
|
||||
rows,
|
||||
overdue,
|
||||
soon,
|
||||
all,
|
||||
n_people => people.len(),
|
||||
horizon_days => HORIZON_DAYS,
|
||||
companies => companies::choices(&st.db, company).await?,
|
||||
company => company.map(|c| c.to_string()).unwrap_or_default(),
|
||||
},
|
||||
))
|
||||
}
|
||||
+91
-4
@@ -2,23 +2,27 @@
|
||||
|
||||
pub mod activity;
|
||||
pub mod auth;
|
||||
pub mod companies;
|
||||
pub mod dashboard;
|
||||
pub mod people;
|
||||
pub mod records;
|
||||
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Path, Request, State};
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Extension, Form, Router};
|
||||
use minijinja::{Environment, Value, context};
|
||||
use sqlx::PgPool;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use crate::config::{Auth, Config};
|
||||
use crate::forms::Fields;
|
||||
use crate::session::{self, Flows, SESSION_COOKIE, User};
|
||||
use crate::{VERSION, countries, dates, embedded, oidc};
|
||||
|
||||
@@ -113,9 +117,10 @@ pub fn spawn_background(st: Arc<AppState>) {
|
||||
}
|
||||
|
||||
pub fn router(st: Arc<AppState>) -> Router {
|
||||
use companies as c;
|
||||
use people as p;
|
||||
Router::new()
|
||||
.route("/", get(|| async { Redirect::to("/people") }))
|
||||
let mut r = Router::new()
|
||||
.route("/", get(dashboard::page_handler))
|
||||
.route("/people", get(p::list).post(p::create))
|
||||
.route("/people/new", get(p::new_form))
|
||||
.route("/people/{id}", get(p::show).post(p::update))
|
||||
@@ -138,7 +143,89 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
"/people/{id}/addresses/{aid}/delete",
|
||||
post(p::address_delete),
|
||||
)
|
||||
.route("/activity", get(activity::page))
|
||||
.route(
|
||||
"/people/{id}/stay",
|
||||
get(
|
||||
|State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>| records::stay(st, user, id),
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/people/{id}/activity",
|
||||
get(
|
||||
|State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>| records::person_activity(st, user, id),
|
||||
),
|
||||
)
|
||||
.route("/companies", get(c::list).post(c::create))
|
||||
.route("/companies/new", get(c::new_form))
|
||||
.route("/companies/{id}", get(c::show).post(c::update))
|
||||
.route("/companies/{id}/edit", get(c::edit_form))
|
||||
.route("/companies/{id}/archive", post(c::archive))
|
||||
.route("/companies/{id}/restore", post(c::restore))
|
||||
.route("/companies/{id}/employees", post(c::hire))
|
||||
.route("/companies/{id}/employees/{pid}/remove", post(c::release));
|
||||
// Every kind of stay record: /people/{id}/<slug>, .../new,
|
||||
// .../{rid}, .../{rid}/edit and .../{rid}/delete.
|
||||
for kind in crate::records::STAY {
|
||||
let base = format!("/people/{{id}}/{}", kind.slug);
|
||||
r = r
|
||||
.route(
|
||||
&base,
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>| {
|
||||
records::create(kind, st, user, id, f)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/new"),
|
||||
get(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>| {
|
||||
records::new_form(kind, st, user, id)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{rid}}"),
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>,
|
||||
Form(f): Form<Fields>| {
|
||||
records::update(kind, st, user, id, rid, f)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{rid}}/edit"),
|
||||
get(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>| {
|
||||
records::edit_form(kind, st, user, id, rid)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{rid}}/delete"),
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>| {
|
||||
records::delete(kind, st, user, id, rid)
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
r.route("/activity", get(activity::page))
|
||||
.route("/login", get(auth::login))
|
||||
.route("/auth/callback", get(auth::callback))
|
||||
.route("/logout", post(auth::logout))
|
||||
|
||||
+96
-21
@@ -21,6 +21,7 @@ use crate::people::{
|
||||
PersonInput, SEXES, TITLES,
|
||||
};
|
||||
use crate::session::User;
|
||||
use crate::{companies, deadlines};
|
||||
|
||||
// ----------------------------------------------------------------- views
|
||||
|
||||
@@ -38,7 +39,9 @@ pub struct PersonView {
|
||||
pub nationality: String,
|
||||
pub nationality_name: String,
|
||||
pub occupation: String,
|
||||
/// The employer's name.
|
||||
pub employer: String,
|
||||
pub employer_id: Option<i64>,
|
||||
pub phone: String,
|
||||
pub email: String,
|
||||
pub notes: String,
|
||||
@@ -48,7 +51,12 @@ pub struct PersonView {
|
||||
pub updated: String,
|
||||
}
|
||||
|
||||
fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> PersonView {
|
||||
fn person_view(
|
||||
p: &Person,
|
||||
current_passport: Option<&str>,
|
||||
employer: Option<String>,
|
||||
today: NaiveDate,
|
||||
) -> PersonView {
|
||||
PersonView {
|
||||
id: p.id,
|
||||
name: p.display_name(),
|
||||
@@ -64,7 +72,8 @@ fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) ->
|
||||
.unwrap_or(&p.nationality)
|
||||
.to_string(),
|
||||
occupation: p.occupation.clone(),
|
||||
employer: p.employer.clone(),
|
||||
employer: employer.unwrap_or_default(),
|
||||
employer_id: p.employer_id,
|
||||
phone: p.phone.clone(),
|
||||
email: p.email.clone(),
|
||||
notes: p.notes.clone(),
|
||||
@@ -133,14 +142,23 @@ fn address_view(a: &Address) -> AddressView {
|
||||
}
|
||||
}
|
||||
|
||||
/// The person with the number of their current passport, for the header
|
||||
/// every page of the person shares.
|
||||
async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Person, PersonView)>> {
|
||||
/// The person with the number of their current passport and the name of
|
||||
/// their employer, for the head every page of the person shares.
|
||||
pub async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Person, PersonView)>> {
|
||||
let Some(p) = people::get_person(&st.db, id).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let pps = people::passports(&st.db, id).await?;
|
||||
let view = person_view(&p, pps.first().map(|x| x.number.as_str()), dates::today());
|
||||
let employer = match p.employer_id {
|
||||
Some(c) => companies::name(&st.db, c).await?,
|
||||
None => None,
|
||||
};
|
||||
let view = person_view(
|
||||
&p,
|
||||
pps.first().map(|x| x.number.as_str()),
|
||||
employer,
|
||||
dates::today(),
|
||||
);
|
||||
Ok(Some((p, view)))
|
||||
}
|
||||
|
||||
@@ -217,6 +235,9 @@ fn zone_note(m: &Mrz, errors: &mut Errors) -> Option<String> {
|
||||
pub struct ListQuery {
|
||||
#[serde(default)]
|
||||
archived: Option<String>,
|
||||
/// A company's id: only the people it employs.
|
||||
#[serde(default)]
|
||||
company: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
@@ -224,21 +245,42 @@ pub async fn list(
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<ListQuery>,
|
||||
) -> Res {
|
||||
let today = dates::today();
|
||||
let archived = q.archived.as_deref() == Some("1");
|
||||
let rows = people::list(&st.db, archived, dates::today()).await?;
|
||||
let company: Option<i64> = q.company.as_deref().and_then(|c| c.parse().ok());
|
||||
let mut rows = people::list(&st.db, archived, company, today).await?;
|
||||
let ids: Vec<i64> = rows.iter().map(|r| r.id).collect();
|
||||
let mut found = deadlines::for_people(&st.db, &ids, today).await?;
|
||||
for r in &mut rows {
|
||||
r.next = found.remove(&r.id).and_then(|a| a.next().cloned());
|
||||
}
|
||||
let (n_active, n_archived) = people::counts(&st.db).await?;
|
||||
let company_name = match company {
|
||||
Some(c) => companies::name(&st.db, c).await?,
|
||||
None => None,
|
||||
};
|
||||
let heading = match (&company_name, archived) {
|
||||
(Some(n), _) => format!("People at {n}"),
|
||||
(None, true) => "Archived people".to_string(),
|
||||
(None, false) => "People".to_string(),
|
||||
};
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"people.html",
|
||||
if archived {
|
||||
"Archived people"
|
||||
} else {
|
||||
"People"
|
||||
},
|
||||
&heading,
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! { people => rows, archived, n_active, n_archived },
|
||||
context! {
|
||||
people => rows,
|
||||
archived,
|
||||
n_active,
|
||||
n_archived,
|
||||
heading,
|
||||
companies => companies::choices(&st.db, company).await?,
|
||||
company => company.map(|c| c.to_string()).unwrap_or_default(),
|
||||
company_name,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
@@ -277,6 +319,7 @@ pub async fn show(
|
||||
.iter()
|
||||
.map(address_view)
|
||||
.collect();
|
||||
let assessment = deadlines::for_person(&st.db, id, today).await?;
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
let recent = audit::recent(&st.db, Some(id), 6).await?;
|
||||
let title = view.name.clone();
|
||||
@@ -287,7 +330,15 @@ pub async fn show(
|
||||
&title,
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! { p => view, passports, addresses, recent },
|
||||
context! {
|
||||
p => view,
|
||||
tab => "overview",
|
||||
passports,
|
||||
addresses,
|
||||
recent,
|
||||
stay => assessment.stay,
|
||||
deadlines => assessment.items,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
@@ -300,6 +351,7 @@ fn person_form_page(
|
||||
pf: &PassportForm,
|
||||
errors: &Errors,
|
||||
mrz_note: Option<String>,
|
||||
companies: &[(String, String)],
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
let (title, mode, action) = match p {
|
||||
@@ -317,11 +369,26 @@ fn person_form_page(
|
||||
&title,
|
||||
"people",
|
||||
status,
|
||||
context! { p, f, pf, errors, mrz_note, mode, action, ..select_lists() },
|
||||
context! {
|
||||
p, tab => "overview", f, pf, errors, mrz_note, mode, action, companies,
|
||||
..select_lists()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// The companies the employer is chosen from (the active ones and the one
|
||||
/// already chosen), and their ids for the check.
|
||||
async fn employer_choices(
|
||||
st: &AppState,
|
||||
current: Option<i64>,
|
||||
) -> anyhow::Result<(Vec<(String, String)>, Vec<i64>)> {
|
||||
let list = companies::choices(&st.db, current).await?;
|
||||
let ids = list.iter().filter_map(|(id, _)| id.parse().ok()).collect();
|
||||
Ok((list, ids))
|
||||
}
|
||||
|
||||
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
|
||||
let (companies, _) = employer_choices(&st, None).await?;
|
||||
Ok(person_form_page(
|
||||
&st,
|
||||
&user,
|
||||
@@ -330,6 +397,7 @@ pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extensio
|
||||
&PassportForm::default(),
|
||||
&Errors::new(),
|
||||
None,
|
||||
&companies,
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
@@ -340,6 +408,7 @@ pub async fn create(
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let today = dates::today();
|
||||
let (companies, company_ids) = employer_choices(&st, None).await?;
|
||||
let mut pf = PersonForm::from_fields(&f);
|
||||
let mut ppf = PassportForm::from_fields(&f);
|
||||
let mut errors = Errors::new();
|
||||
@@ -360,7 +429,7 @@ pub async fn create(
|
||||
}
|
||||
let status = status_for(&errors);
|
||||
return Ok(person_form_page(
|
||||
&st, &user, None, &pf, &ppf, &errors, note, status,
|
||||
&st, &user, None, &pf, &ppf, &errors, note, &companies, status,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -368,7 +437,7 @@ pub async fn create(
|
||||
pf.take_mrz(m, false);
|
||||
ppf.take_mrz(m, false);
|
||||
}
|
||||
let person = pf.validate(today);
|
||||
let person = pf.validate(today, &company_ids);
|
||||
let passport = (!ppf.is_blank()).then(|| ppf.validate(zone.as_ref()));
|
||||
for e in [
|
||||
person.as_ref().err(),
|
||||
@@ -390,6 +459,7 @@ pub async fn create(
|
||||
&ppf,
|
||||
&errors,
|
||||
None,
|
||||
&companies,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
};
|
||||
@@ -412,6 +482,7 @@ pub async fn create(
|
||||
&ppf,
|
||||
&errors,
|
||||
None,
|
||||
&companies,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
@@ -441,6 +512,7 @@ pub async fn edit_form(
|
||||
let Some((p, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let (companies, _) = employer_choices(&st, p.employer_id).await?;
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
Ok(person_form_page(
|
||||
&st,
|
||||
@@ -450,6 +522,7 @@ pub async fn edit_form(
|
||||
&PassportForm::default(),
|
||||
&Errors::new(),
|
||||
None,
|
||||
&companies,
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
@@ -460,11 +533,12 @@ pub async fn update(
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
let Some((p, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let (companies, company_ids) = employer_choices(&st, p.employer_id).await?;
|
||||
let pf = PersonForm::from_fields(&f);
|
||||
let input = match pf.validate(dates::today()) {
|
||||
let input = match pf.validate(dates::today(), &company_ids) {
|
||||
Ok(i) => i,
|
||||
Err(errors) => {
|
||||
return Ok(person_form_page(
|
||||
@@ -475,6 +549,7 @@ pub async fn update(
|
||||
&PassportForm::default(),
|
||||
&errors,
|
||||
None,
|
||||
&companies,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
@@ -569,7 +644,7 @@ fn passport_form_page(
|
||||
&format!("{title}: {}", p.name),
|
||||
"people",
|
||||
status,
|
||||
context! { p, pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
|
||||
context! { p, tab => "overview", pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -824,7 +899,7 @@ fn address_form_page(
|
||||
&format!("{heading}: {}", p.name),
|
||||
"people",
|
||||
status,
|
||||
context! { p, af, errors, mode, action, heading, ..select_lists() },
|
||||
context! { p, tab => "overview", af, errors, mode, action, heading, ..select_lists() },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Pages for the records of a stay: the person's "Visa and stay" tab, one
|
||||
//! form for every kind (`records::Kind`), and the person's Activity tab.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use minijinja::context;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use super::people::{PersonView, load_person};
|
||||
use super::{AppState, Res, not_found_page, page};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::countries;
|
||||
use crate::dates;
|
||||
use crate::deadlines;
|
||||
use crate::forms::{Errors, Fields};
|
||||
use crate::records::{self, Kind, Options, Values};
|
||||
use crate::session::User;
|
||||
use crate::{companies, people};
|
||||
|
||||
/// Suggestions for the text fields with a `<datalist>`.
|
||||
pub fn datalists() -> minijinja::Value {
|
||||
context! {
|
||||
ports => records::PORTS,
|
||||
offices => records::OFFICES,
|
||||
provinces => countries::PROVINCES,
|
||||
}
|
||||
}
|
||||
|
||||
/// The choices of a person's forms. `all_companies` names archived companies
|
||||
/// too (to show records); otherwise only active ones and `keep_company`.
|
||||
pub async fn options(
|
||||
db: &PgPool,
|
||||
person: i64,
|
||||
all_companies: bool,
|
||||
keep_company: Option<i64>,
|
||||
) -> anyhow::Result<Options> {
|
||||
let passports = people::passports(db, person)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let country = countries::name(&p.issuing_country).unwrap_or(&p.issuing_country);
|
||||
(p.id.to_string(), format!("{} ({country})", p.number))
|
||||
})
|
||||
.collect();
|
||||
let visas = records::list(db, &records::VISAS, person)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|r| (r.id.to_string(), records::visa_choice(r)))
|
||||
.collect();
|
||||
let companies = if all_companies {
|
||||
companies::names(db).await?
|
||||
} else {
|
||||
companies::choices(db, keep_company).await?
|
||||
};
|
||||
Ok(Options {
|
||||
passports,
|
||||
visas,
|
||||
companies,
|
||||
})
|
||||
}
|
||||
|
||||
fn company_of(v: &Values) -> Option<i64> {
|
||||
v.get("company_id").and_then(|c| c.parse().ok())
|
||||
}
|
||||
|
||||
pub async fn stay(st: Arc<AppState>, user: User, id: i64) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let today = dates::today();
|
||||
let opts = options(&st.db, id, true, None).await?;
|
||||
let mut sections = Vec::new();
|
||||
for kind in records::STAY {
|
||||
let shown: Vec<records::Shown> = records::list(&st.db, kind, id)
|
||||
.await?
|
||||
.iter()
|
||||
.map(|r| records::show(kind, r, &opts, today))
|
||||
.collect();
|
||||
sections.push(context! {
|
||||
slug => kind.slug,
|
||||
title => kind.title,
|
||||
one => kind.one,
|
||||
records => shown,
|
||||
});
|
||||
}
|
||||
let assessment = deadlines::for_person(&st.db, id, today).await?;
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
let title = format!("Visa and stay: {}", view.name);
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"stay.html",
|
||||
&title,
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! {
|
||||
p => view,
|
||||
tab => "stay",
|
||||
sections,
|
||||
stay => assessment.stay,
|
||||
deadlines => assessment.items,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn person_activity(st: Arc<AppState>, user: User, id: i64) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let items = audit::recent(&st.db, Some(id), 300).await?;
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
let title = format!("Activity: {}", view.name);
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"person_activity.html",
|
||||
&title,
|
||||
"people",
|
||||
StatusCode::OK,
|
||||
context! { p => view, tab => "activity", items },
|
||||
))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn form_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
kind: &Kind,
|
||||
p: &PersonView,
|
||||
record: Option<i64>,
|
||||
values: &Values,
|
||||
errors: &Errors,
|
||||
opts: &Options,
|
||||
status: StatusCode,
|
||||
) -> Response {
|
||||
let base = format!("/people/{}/{}", p.id, kind.slug);
|
||||
let (heading, mode, action) = match record {
|
||||
Some(r) => (
|
||||
format!("Edit the {}", kind.one),
|
||||
"edit",
|
||||
format!("{base}/{r}"),
|
||||
),
|
||||
None => (format!("New {}", kind.one), "new", base),
|
||||
};
|
||||
let title = format!("{heading}: {}", p.name);
|
||||
page(
|
||||
st,
|
||||
user,
|
||||
"record_form.html",
|
||||
&title,
|
||||
"people",
|
||||
status,
|
||||
context! {
|
||||
p,
|
||||
tab => "stay",
|
||||
heading,
|
||||
one => kind.one,
|
||||
lead => kind.lead,
|
||||
mode,
|
||||
action,
|
||||
fields => records::form_fields(kind, opts),
|
||||
values,
|
||||
errors,
|
||||
cancel => format!("/people/{}/stay#{}", p.id, kind.slug),
|
||||
..datalists()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Sensible first values: the current passport, the employer, Chiang Mai.
|
||||
fn defaults(kind: &Kind, view: &PersonView, opts: &Options) -> Values {
|
||||
let mut v = Values::new();
|
||||
let first_passport = opts.passports.first().map(|(id, _)| id.clone());
|
||||
match kind.slug {
|
||||
"arrivals" => {
|
||||
if let Some(pp) = first_passport {
|
||||
v.insert("passport_id".into(), pp);
|
||||
}
|
||||
}
|
||||
"visas" => {
|
||||
if let Some(pp) = first_passport {
|
||||
v.insert("passport_id".into(), pp);
|
||||
}
|
||||
}
|
||||
"extensions" => {
|
||||
v.insert("office".into(), "Chiang Mai Immigration Office".into());
|
||||
v.insert("fee_thb".into(), "1900".into());
|
||||
}
|
||||
"reentry-permits" => {
|
||||
v.insert("office".into(), "Chiang Mai Immigration Office".into());
|
||||
}
|
||||
"work-permits" => {
|
||||
if let Some(c) = view.employer_id {
|
||||
v.insert("company_id".into(), c.to_string());
|
||||
}
|
||||
v.insert("position".into(), String::new());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub async fn new_form(kind: &'static Kind, st: Arc<AppState>, user: User, id: i64) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let opts = options(&st.db, id, false, view.employer_id).await?;
|
||||
let values = defaults(kind, &view, &opts);
|
||||
Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
kind,
|
||||
&view,
|
||||
None,
|
||||
&values,
|
||||
&Errors::new(),
|
||||
&opts,
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
fn entry<'a>(
|
||||
user: &'a User,
|
||||
action: Action,
|
||||
kind: &Kind,
|
||||
record: i64,
|
||||
person: i64,
|
||||
fields: &'a [String],
|
||||
) -> Entry<'a> {
|
||||
Entry {
|
||||
actor: &user.login,
|
||||
action,
|
||||
entity: kind.entity,
|
||||
entity_id: Some(record),
|
||||
person_id: Some(person),
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
fn back(kind: &Kind, person: i64) -> Response {
|
||||
Redirect::to(&format!("/people/{person}/stay#{}", kind.slug)).into_response()
|
||||
}
|
||||
|
||||
pub async fn create(kind: &'static Kind, st: Arc<AppState>, user: User, id: i64, f: Fields) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let values = records::read(kind, &f);
|
||||
let opts = options(&st.db, id, false, None).await?;
|
||||
let errors = records::validate(kind, &values, &opts);
|
||||
if !errors.is_empty() {
|
||||
return Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
kind,
|
||||
&view,
|
||||
None,
|
||||
&values,
|
||||
&errors,
|
||||
&opts,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
let mut tx = st.db.begin().await?;
|
||||
let rid = records::create(&mut tx, kind, Some(id), &values).await?;
|
||||
audit::record(&mut *tx, &entry(&user, Action::Create, kind, rid, id, &[])).await?;
|
||||
tx.commit().await?;
|
||||
Ok(back(kind, id))
|
||||
}
|
||||
|
||||
pub async fn edit_form(
|
||||
kind: &'static Kind,
|
||||
st: Arc<AppState>,
|
||||
user: User,
|
||||
id: i64,
|
||||
rid: i64,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let Some(r) = records::get(&st.db, kind, Some(id), rid).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let opts = options(&st.db, id, false, company_of(&r.values)).await?;
|
||||
audit::viewed(&st.db, &user.login, kind.entity, rid, id).await?;
|
||||
Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
kind,
|
||||
&view,
|
||||
Some(rid),
|
||||
&r.values,
|
||||
&Errors::new(),
|
||||
&opts,
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
kind: &'static Kind,
|
||||
st: Arc<AppState>,
|
||||
user: User,
|
||||
id: i64,
|
||||
rid: i64,
|
||||
f: Fields,
|
||||
) -> Res {
|
||||
let Some((_, view)) = load_person(&st, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let mut tx = st.db.begin().await?;
|
||||
let Some(old) = records::get_for_update(&mut tx, kind, Some(id), rid).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let values = records::read(kind, &f);
|
||||
let opts = options(&st.db, id, false, company_of(&old.values)).await?;
|
||||
let errors = records::validate(kind, &values, &opts);
|
||||
if !errors.is_empty() {
|
||||
return Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
kind,
|
||||
&view,
|
||||
Some(rid),
|
||||
&values,
|
||||
&errors,
|
||||
&opts,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
));
|
||||
}
|
||||
let changed = records::changed(kind, &old.values, &values);
|
||||
if !changed.is_empty() {
|
||||
records::update(&mut tx, kind, Some(id), rid, &values).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&entry(&user, Action::Update, kind, rid, id, &changed),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(back(kind, id))
|
||||
}
|
||||
|
||||
pub async fn delete(kind: &'static Kind, st: Arc<AppState>, user: User, id: i64, rid: i64) -> Res {
|
||||
let mut tx = st.db.begin().await?;
|
||||
if !records::delete(&mut tx, kind, id, rid).await? {
|
||||
return Ok(not_found_page(&st));
|
||||
}
|
||||
audit::record(&mut *tx, &entry(&user, Action::Delete, kind, rid, id, &[])).await?;
|
||||
tx.commit().await?;
|
||||
Ok(back(kind, id))
|
||||
}
|
||||
Reference in new issue
Block a user