Files
visa/src/web/papers.rs
T
grabowski fc8c1b6a44
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 31s
Phase 6: the Non-B extension pack, checked and printed as one PDF
The pack for an extension of stay based on work, item by item in the
officer's order, each with its state at the date of the application:
generated, has blanks, uploaded, missing, out of date, no date, or not
needed for this person.

- src/pack/mod.rs: the rules as a pure function of the records and the
  documents, a unit test per rule. Copies belong to their record (the
  current passport, the last arrival and its TDAC, the re-entry permit it
  came back on, every extension since the passport was issued, the last
  90-day report, the current address, the work permit); the company
  certificate and BOJ.5 count six months from their certification, the
  balance sheet 17 months from its year's end, PND.1, SPS 1-10 and PP.30
  the last three months, PND.91 the latest year; two photos of the office.
  Sources in docs/PLAN.md (thailand.go.th 006_008, Immigration Division 1).
- A Pack tab: the six parts, each item's files and form, and what fixes it
  (the upload with the kind and record chosen, through the new ?kind= on
  the Documents tab and on a company's page; a document's date; a record).
  The application's fields are the Forms tab's, and both tabs carry them.
- /people/{id}/pack.pdf (src/pack/pdf.rs): a cover sheet with the contents
  page by page and what to sign and bring, the five forms, then every copy:
  uploaded PDFs as they are (a PDF 2.0 upload makes the pack 2.0), images
  fitted on A4 and turned as their EXIF orientation says, a page in place of
  a file that cannot be read; bookmarks per item. krilla gains its
  raster-images feature. The audit logs the forms' codes and a view or
  download of each document that went in.
- A company's page shows its part of every employee's pack.
- The extension deadline links to the pack; at 390 px the six tabs fit, as
  "Visa and stay" reads "Stay" on phones.
- Demo data shows every state.
- The Forms tab showed "Back about" and "Purpose" empty: the template read
  app.back and app.purpose, which serialize as "return" and "for".

docs/PLAN.md: phase 6 done, open question 2 settled (the office is the
application's), phase 7 planned from Alex's answers: the client link, the
MRZ from a phone photo, later the signed agreement; reminders move to 8.

Checks: cargo fmt, clippy -D warnings, 97 unit and 47 integration tests;
layout_check 0 problems (pack, company, forms, dashboard, person; light,
dark, desk, phone); the tabs measured at 390 and 360 px; the pack PDF
rendered and looked at, an EXIF-turned JPEG upright.
2026-11-20 16:04:13 +07:00

179 lines
5.4 KiB
Rust

//! 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<Missing>,
href: String,
}
pub async fn tab(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Query(app): Query<Application>,
) -> 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<FormView> = 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::<Vec<_>>()
.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<String>,
}
/// 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<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, file)): Path<(i64, String)>,
Query(q): Query<PdfQuery>,
) -> Res {
let chosen: Vec<Paper> = 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<String> = 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)
}