//! A person's Forms tab: the Immigration Bureau's forms filled in from the //! records, what each still lacks with a link to where it is added, and the //! PDFs (one form, or the five of an extension in one file). What only this //! application says comes from the tab's fields as query parameters, so a //! link to a PDF carries it and nothing is stored. use std::sync::Arc; use axum::Extension; use axum::body::Body; use axum::extract::{Path, Query, State}; use axum::http::{HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Redirect, Response}; use minijinja::context; use serde::{Deserialize, Serialize}; use super::documents::{FILE_CSP, disposition}; use super::people::load_person; use super::{AppState, Res, not_found_page, page}; use crate::audit::{self, Action, Entity, Entry}; use crate::dates; use crate::papers::values::{self, Application, Missing}; use crate::papers::{self, Paper}; use crate::session::User; #[derive(Debug, Serialize)] struct FormView { slug: &'static str, code: &'static str, title: &'static str, when: &'static str, missing: Vec, href: String, } pub async fn tab( State(st): State>, Extension(user): Extension, Path(id): Path, Query(app): Query, ) -> Res { let (Some((_, p)), Some(facts)) = (load_person(&st, id).await?, values::load(&st.db, id).await?) else { return Ok(not_found_page(&st)); }; let today = dates::today(); let app = app.with_defaults(&facts, today); let errors = app.check(); let v = values::values(&facts, &app, today); let q = app.query(); let forms: Vec = papers::ALL .iter() .map(|&paper| FormView { slug: paper.slug(), code: paper.code(), title: paper.title(), when: paper.when(), missing: values::missing(paper, &v, &facts), href: format!("/people/{id}/forms/{}.pdf?{q}", paper.slug()), }) .collect(); audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?; let title = format!("Forms: {}", p.name); let status = if errors.is_empty() { StatusCode::OK } else { StatusCode::UNPROCESSABLE_ENTITY }; let extension_codes = papers::EXTENSION .iter() .map(|p| p.code()) .collect::>() .join(", "); Ok(page( &st, &user, "papers.html", &title, "people", status, context! { p, tab => "forms", app, errors, forms, extension_href => format!("/people/{id}/forms/extension.pdf?{q}"), extension_codes, appq => &q, }, )) } #[derive(Debug, Deserialize)] pub struct PdfQuery { #[serde(flatten)] pub app: Application, pub download: Option, } /// One form (`tm7.pdf`) or the forms of an extension (`extension.pdf`), /// opened in the browser or (`?download=1`) saved. pub async fn pdf( State(st): State>, Extension(user): Extension, Path((id, file)): Path<(i64, String)>, Query(q): Query, ) -> Res { let chosen: Vec = match file.strip_suffix(".pdf") { Some("extension") => papers::EXTENSION.to_vec(), Some(slug) => match Paper::from_slug(slug) { Some(p) => vec![p], None => return Ok(not_found_page(&st)), }, None => return Ok(not_found_page(&st)), }; let Some(facts) = values::load(&st.db, id).await? else { return Ok(not_found_page(&st)); }; let today = dates::today(); let app = q.app.with_defaults(&facts, today); if !app.check().is_empty() { // the tab shows what is wrong with the fields return Ok(Redirect::to(&format!("/people/{id}/forms?{}", app.query())).into_response()); } let v = values::values(&facts, &app, today); let label = if chosen.len() == 1 { chosen[0].code().to_string() } else { "Extension forms".to_string() }; let whose = facts.person.display_name().replace(',', ""); let name = format!("{whose} - {label} - {}.pdf", app.date); let codes: Vec = chosen.iter().map(|p| p.code().to_string()).collect(); let title = format!("{label}: {whose}"); let bytes = tokio::task::spawn_blocking(move || papers::render(&chosen, &v, &title)).await??; let download = q.download.is_some(); audit::record( &st.db, &Entry { actor: &user.login, action: if download { Action::Download } else { Action::View }, entity: Entity::Form, entity_id: None, person_id: Some(id), company_id: None, fields: &codes, }, ) .await?; let how = if download { "attachment" } else { "inline" }; let mut resp = Response::new(Body::from(bytes)); let h = resp.headers_mut(); h.insert( header::CONTENT_TYPE, HeaderValue::from_static("application/pdf"), ); h.insert(header::CONTENT_DISPOSITION, disposition(how, &name)); h.insert( header::CACHE_CONTROL, HeaderValue::from_static("private, no-store"), ); h.insert( header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(FILE_CSP), ); h.insert( "cross-origin-resource-policy", HeaderValue::from_static("same-origin"), ); Ok(resp) }