//! 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 ``. 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, ) -> anyhow::Result { 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, ..Options::default() }) } fn company_of(v: &Values) -> Option { v.get("company_id").and_then(|c| c.parse().ok()) } pub async fn stay(st: Arc, 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::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?; let docs = super::documents::chips(&st, id).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, docs, stay => assessment.stay, deadlines => assessment.items, }, )) } pub async fn person_activity(st: Arc, 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, 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, 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), company_id: None, 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, 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, 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, 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, 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)) }