The header (staff pages, messages and the client link), page titles, footer, messages, the pack's cover line and the PDFs' creator now say Lanna Desk (lannadesk.com) instead of visa.buildfor.life. The company named in the client's texts and agreements stays B4L. Nothing depends on the name the app is reached under: VISA_PUBLIC_URL comes from the fleet, which moves it to https://lannadesk.com and redirects visa.buildfor.life there with the path, so links already sent keep working. README, AGENTS, PLAN and the release notes name the new address. Checks: fmt, clippy, 108 unit and 57 integration tests; the header at 360 and 390 px and on a desktop.
361 lines
10 KiB
Rust
361 lines
10 KiB
Rust
//! 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(),
|
|
kind: d.kind.clone(),
|
|
back_of: d.back_of,
|
|
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 Lanna Desk (lannadesk.com) 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)
|
|
}
|