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.
This commit is contained in:
1 parent
990d5c88a4
commit
fc8c1b6a44
26 files changed
+3367
-59
No files matched your search
+19
-10
@@ -160,20 +160,26 @@ pub async fn create(
|
||||
Ok(Redirect::to(&format!("/companies/{id}")).into_response())
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ShowQuery {
|
||||
/// A kind of document to add, as an employee's pack asks for it.
|
||||
pub kind: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn show(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Query(q): Query<ShowQuery>,
|
||||
) -> Res {
|
||||
company_page(
|
||||
&st,
|
||||
&user,
|
||||
id,
|
||||
&documents::Values::default(),
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
)
|
||||
.await
|
||||
let mut values = documents::Values::default();
|
||||
if let Some(k) = q
|
||||
.kind
|
||||
.filter(|k| crate::documents::kind(Owner::Company(id), k).is_some())
|
||||
{
|
||||
values.kind = k;
|
||||
}
|
||||
company_page(&st, &user, id, &values, &Errors::new(), StatusCode::OK).await
|
||||
}
|
||||
|
||||
/// The company's page, with its documents and their upload form (and the
|
||||
@@ -196,6 +202,9 @@ pub async fn company_page(
|
||||
let owner = Owner::Company(id);
|
||||
let docs = documents::views(st, owner, &HashMap::new()).await?;
|
||||
let office = documents::office_context(st, &docs, values, errors);
|
||||
// the employer's part of every employee's pack, as of today
|
||||
let raw = crate::documents::list(&st.db, owner).await?;
|
||||
let pack = crate::pack::employer_items(id, &raw, dates::today());
|
||||
// a refused office photo shows its errors on the office card only
|
||||
let upload = if values.from_office() {
|
||||
documents::upload_context(
|
||||
@@ -216,7 +225,7 @@ pub async fn company_page(
|
||||
&title,
|
||||
"companies",
|
||||
status,
|
||||
context! { c, employees, candidates, docs, upload, office },
|
||||
context! { c, employees, candidates, docs, upload, office, pack },
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -333,6 +333,8 @@ pub struct TabQuery {
|
||||
/// A record to add a document to, as on its page: `arrivals:7`.
|
||||
#[serde(rename = "for")]
|
||||
pub for_record: Option<String>,
|
||||
/// A kind to add, as the Pack tab asks for it: `photo`.
|
||||
pub kind: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn person_tab(
|
||||
@@ -346,6 +348,12 @@ pub async fn person_tab(
|
||||
};
|
||||
let choices = choices(&st, id).await?;
|
||||
let mut values = Values::default();
|
||||
if let Some(k) = q
|
||||
.kind
|
||||
.filter(|k| documents::kind(Owner::Person(id), k).is_some())
|
||||
{
|
||||
values.kind = k;
|
||||
}
|
||||
if let Some(v) = q.for_record.filter(|v| choices.names.contains_key(v)) {
|
||||
if let Some((link, _)) = documents::parse_link(&v) {
|
||||
values.kind = documents::kind_for_link(link.slug)
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod auth;
|
||||
pub mod companies;
|
||||
pub mod dashboard;
|
||||
pub mod documents;
|
||||
pub mod pack;
|
||||
pub mod papers;
|
||||
pub mod people;
|
||||
pub mod records;
|
||||
@@ -242,6 +243,10 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
r = r
|
||||
.route("/people/{id}/forms", get(papers::tab))
|
||||
.route("/people/{id}/forms/{file}", get(papers::pdf));
|
||||
// The extension pack: its checklist, and all of it as one PDF.
|
||||
r = r
|
||||
.route("/people/{id}/pack", get(pack::tab))
|
||||
.route("/people/{id}/pack.pdf", get(pack::pdf));
|
||||
type OwnerOf = fn(i64) -> Owner;
|
||||
let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)];
|
||||
for (prefix, owner) in owners {
|
||||
|
||||
+358
@@ -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)
|
||||
}
|
||||
+3
-2
@@ -87,6 +87,7 @@ pub async fn tab(
|
||||
forms,
|
||||
extension_href => format!("/people/{id}/forms/extension.pdf?{q}"),
|
||||
extension_codes,
|
||||
appq => &q,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -94,8 +95,8 @@ pub async fn tab(
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct PdfQuery {
|
||||
#[serde(flatten)]
|
||||
app: Application,
|
||||
download: Option<String>,
|
||||
pub app: Application,
|
||||
pub download: Option<String>,
|
||||
}
|
||||
|
||||
/// One form (`tm7.pdf`) or the forms of an extension (`extension.pdf`),
|
||||
|
||||
Reference in new issue
Block a user