Phase 6: the Non-B extension pack, checked and printed as one PDF
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 31s

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.
This commit is contained in:
grabowski committed 2026-11-20 16:04:13 +07:00
1 parent 990d5c88a4
commit fc8c1b6a44
26 files changed
+3367 -59

No files matched your search

+358
View File
@@ -0,0 +1,358 @@
//! A person's Pack tab: the extension pack for work, item by item with its
//! state and what to do about it, and the whole pack as one PDF to print.
//! The application's own values (the date, the office, the reason ...) come
//! from the tab's fields as on the Forms tab and travel in the links, so
//! nothing of them is stored.
use std::collections::HashMap;
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 chrono::{NaiveDate, Utc};
use minijinja::context;
use serde::Serialize;
use tracing::error;
use super::documents::{FILE_CSP, disposition};
use super::papers::PdfQuery;
use super::people::load_person;
use super::{AppState, Res, message, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::documents::Document;
use crate::forms::Errors;
use crate::pack::pdf::{Cover, Loaded};
use crate::pack::{self, Item, PARTS, Summary};
use crate::papers::values::{self, Application};
use crate::papers::{self, Values};
use crate::session::User;
use crate::{countries, dates, files};
/// The most the documents of one pack may weigh together.
const PACK_LIMIT: i64 = 200 * 1024 * 1024;
/// One application, assessed: what the tab and the PDF show.
struct Assessed {
facts: values::Facts,
app: Application,
errors: Errors,
values: Values,
on: NaiveDate,
pack: pack::Facts,
items: Vec<Item>,
}
impl Assessed {
/// The documents of the person and of the employer, by id.
fn docs(&self) -> HashMap<i64, &Document> {
self.pack
.person_docs
.iter()
.chain(&self.pack.company_docs)
.map(|d| (d.id, d))
.collect()
}
}
async fn assess(st: &AppState, id: i64, app: Application) -> anyhow::Result<Option<Assessed>> {
let Some(facts) = values::load(&st.db, id).await? else {
return Ok(None);
};
let today = dates::today();
let app = app.with_defaults(&facts, today);
let errors = app.check();
let v = values::values(&facts, &app, today);
let on = dates::parse_form_date(&app.date).unwrap_or(today);
let blanks = papers::EXTENSION
.iter()
.map(|&p| (p, values::missing(p, &v, &facts)))
.collect();
let pack = pack::load(&st.db, &facts, blanks).await?;
let items = pack::assess(&pack, on);
Ok(Some(Assessed {
facts,
app,
errors,
values: v,
on,
pack,
items,
}))
}
#[derive(Debug, Serialize)]
struct FileLink {
label: String,
href: String,
}
#[derive(Debug, Serialize)]
struct ItemView<'a> {
#[serde(flatten)]
item: &'a Item,
/// A form's PDF.
open: String,
/// The documents that go in, each opening its file.
files: Vec<FileLink>,
}
#[derive(Debug, Serialize)]
struct Part<'a> {
n: usize,
title: &'static str,
items: Vec<ItemView<'a>>,
}
/// An item as the tab shows it: with the links to its form or its files.
fn item_view<'a>(item: &'a Item, docs: &HashMap<i64, &Document>, id: i64, q: &str) -> ItemView<'a> {
ItemView {
item,
open: item
.paper
.map(|p| format!("/people/{id}/forms/{}.pdf?{q}", p.slug()))
.unwrap_or_default(),
files: item
.docs
.iter()
.filter_map(|d| docs.get(d))
.map(|d| FileLink {
label: d
.dated_on
.map(dates::fmt_date)
.unwrap_or_else(|| "View".to_string()),
href: format!("{}/{}/file", d.owner().base(), d.id),
})
.collect(),
}
}
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(a)) = (load_person(&st, id).await?, assess(&st, id, app).await?) else {
return Ok(not_found_page(&st));
};
let q = a.app.query();
let docs = a.docs();
let parts: Vec<Part> = PARTS
.iter()
.enumerate()
.map(|(i, title)| Part {
n: i + 1,
title,
items: a
.items
.iter()
.filter(|it| it.part == i + 1)
.map(|it| item_view(it, &docs, id, &q))
.collect(),
})
.collect();
let summary = Summary::of(&a.items);
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let status = if a.errors.is_empty() {
StatusCode::OK
} else {
StatusCode::UNPROCESSABLE_ENTITY
};
let title = format!("Pack: {}", p.name);
let complete = summary.complete();
Ok(page(
&st,
&user,
"pack.html",
&title,
"people",
status,
context! {
p,
tab => "pack",
app => &a.app,
appq => &q,
errors => &a.errors,
parts,
summary,
complete,
on => dates::fmt_date(a.on),
pdf_href => format!("/people/{id}/pack.pdf?{q}"),
},
))
}
/// The pack as one PDF, opened in the browser or (`?download=1`) saved.
pub async fn pdf(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Query(q): Query<PdfQuery>,
) -> Res {
let Some(a) = assess(&st, id, q.app).await? else {
return Ok(not_found_page(&st));
};
if !a.errors.is_empty() {
// the tab shows what is wrong with the fields
return Ok(Redirect::to(&format!("/people/{id}/pack?{}", a.app.query())).into_response());
}
let docs = a.docs();
let wanted: Vec<&Document> = a
.items
.iter()
.flat_map(|i| &i.docs)
.filter_map(|d| docs.get(d).copied())
.collect();
let total: i64 = wanted.iter().map(|d| i64::from(d.size_bytes)).sum();
if total > PACK_LIMIT {
return Ok(message(
&st,
StatusCode::PAYLOAD_TOO_LARGE,
"The pack is too large for one file",
&format!(
"Its documents weigh {} MB together, more than the {} MB one PDF takes. Open the \
large scans one by one from the Documents tab.",
total / (1024 * 1024),
PACK_LIMIT / (1024 * 1024)
),
(&format!("/people/{id}/pack"), "Back to the pack"),
));
}
let mut loaded = HashMap::new();
let mut read: Vec<&Document> = Vec::new();
for d in &wanted {
let bytes = match &st.files {
None => Err("documents are switched off on this server".to_string()),
Some(store) => match store.get(d.id).await {
Ok(b) if files::sha256_hex(&b) == d.sha256 => {
read.push(d);
Ok(b)
}
Ok(_) => {
error!(
"document {}: the file does not match the checksum of its upload",
d.id
);
Err("it does not match its upload".to_string())
}
Err(e) => {
error!("document {}: {e:#}", d.id);
Err("it is missing or damaged on the server".to_string())
}
},
};
loaded.insert(
d.id,
Loaded {
name: d.file_name.clone(),
content_type: d.content_type.clone(),
bytes,
},
);
}
let person = &a.facts.person;
let whose = person.display_name();
let mut lines = Vec::new();
if let Some(pp) = &a.facts.passport {
let country = countries::name(&pp.issuing_country).unwrap_or(&pp.issuing_country);
lines.push(format!("Passport {}, {country}", pp.number));
}
if let Some(c) = &a.pack.company {
lines.push(format!("Employer: {}", c.name));
}
lines.push(format!(
"For {} on {}, asking for {} days",
a.app.at,
dates::fmt_date(a.on),
a.app.days
));
let cover = Cover {
title: format!("Extension pack: {whose}"),
person: whose.clone(),
lines,
made: format!(
"Put together by visa.buildfor.life for {} on {}.",
user.login,
dates::fmt_datetime(Utc::now())
),
};
let items = a.items.clone();
let v = a.values.clone();
let bytes = tokio::task::spawn_blocking(move || pack::pdf::render(&cover, &items, &v, loaded))
.await??;
// the forms and every document that went in, never their contents
let download = q.download.is_some();
let action = if download {
Action::Download
} else {
Action::View
};
let codes: Vec<String> = a
.items
.iter()
.filter_map(|i| i.paper)
.map(|p| p.code().to_string())
.collect();
let file = ["file".to_string()];
let mut tx = st.db.begin().await?;
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action,
entity: Entity::Form,
entity_id: None,
person_id: Some(id),
company_id: None,
fields: &codes,
},
)
.await?;
for d in read {
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action,
entity: Entity::Document,
entity_id: Some(d.id),
person_id: Some(id),
company_id: d.company_id,
fields: &file,
},
)
.await?;
}
tx.commit().await?;
let name = format!(
"{} - Extension pack - {}.pdf",
whose.replace(',', ""),
a.app.date
);
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)
}