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
@@ -15,6 +15,7 @@ pub mod forms;
|
||||
pub mod gps;
|
||||
pub mod mrz;
|
||||
pub mod oidc;
|
||||
pub mod pack;
|
||||
pub mod papers;
|
||||
pub mod people;
|
||||
pub mod records;
|
||||
|
||||
+1444
File diff suppressed because it is too large.
Load diff
+796
@@ -0,0 +1,796 @@
|
||||
//! The pack as one PDF to print: a cover sheet with the contents page by
|
||||
//! page and what to do before handing it in, then the forms filled in from
|
||||
//! the records, then every copy in the pack's order. A PDF's pages go in as
|
||||
//! they are; an image is fitted on an A4 page, turned as the camera's EXIF
|
||||
//! tag says. A file that cannot be read gets a page that says so, and the
|
||||
//! pack still prints.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use krilla::color::rgb;
|
||||
use krilla::configure::{ConfigurationBuilder, PdfVersion};
|
||||
use krilla::destination::XyzDestination;
|
||||
use krilla::error::KrillaError;
|
||||
use krilla::geom::{PathBuilder, Point, Size, Transform};
|
||||
use krilla::image::Image;
|
||||
use krilla::metadata::Metadata;
|
||||
use krilla::num::NormalizedF32;
|
||||
use krilla::outline::{Outline, OutlineNode};
|
||||
use krilla::page::PageSettings;
|
||||
use krilla::paint::{Fill, LineCap, Stroke};
|
||||
use krilla::pdf::{Pdf, PdfDocument, PdfError};
|
||||
use krilla::surface::Surface;
|
||||
use krilla::text::TextDirection;
|
||||
use krilla::{Data, Document, SerializeSettings};
|
||||
|
||||
use super::{Item, PARTS};
|
||||
use crate::papers::{self, Paper, Pen, Values, width};
|
||||
|
||||
/// A file of the pack as the store gave it.
|
||||
pub struct Loaded {
|
||||
/// Its name as uploaded.
|
||||
pub name: String,
|
||||
pub content_type: String,
|
||||
/// The file, or why it could not be read.
|
||||
pub bytes: Result<Vec<u8>, String>,
|
||||
}
|
||||
|
||||
/// What the cover sheet says about the application.
|
||||
pub struct Cover {
|
||||
/// The PDF's title.
|
||||
pub title: String,
|
||||
/// "MUSTERMANN, Erika"
|
||||
pub person: String,
|
||||
/// The passport, the employer, the office and the date.
|
||||
pub lines: Vec<String>,
|
||||
/// Who put it together, and when.
|
||||
pub made: String,
|
||||
}
|
||||
|
||||
/// What the person and the employer do before the pack goes in.
|
||||
const BEFORE: [&str; 5] = [
|
||||
"Print the pack twice: the office takes two sets.",
|
||||
"The person signs TM.7, STM.2, STM.9 and STM.11, and signs every copy of the passport as a \
|
||||
true copy.",
|
||||
"Every page of the employer's documents carries the company's seal and the signature of the \
|
||||
director named in the company certificate; the director also signs STM.1.",
|
||||
"Glue the 4 x 6 cm photo to TM.7.",
|
||||
"Bring the passport, the work permit, the fee of 1,900 THB, and the originals of the company \
|
||||
certificate, BOJ.5, the balance sheet with PND.50, PND.1, PND.91 and SPS 1-10.",
|
||||
];
|
||||
|
||||
/// A4 portrait, in points.
|
||||
const W: f32 = 595.0;
|
||||
const H: f32 = 842.0;
|
||||
const MARGIN: f32 = 48.0;
|
||||
|
||||
const NAVY: (u8, u8, u8) = (7, 19, 35);
|
||||
const INK: (u8, u8, u8) = (34, 38, 46);
|
||||
const GREY: (u8, u8, u8) = (104, 112, 124);
|
||||
const RED: (u8, u8, u8) = (176, 32, 32);
|
||||
const AMBER: (u8, u8, u8) = (150, 98, 0);
|
||||
const GOLD: (u8, u8, u8) = (245, 192, 0);
|
||||
|
||||
/// What one document or form puts into the PDF.
|
||||
enum Piece {
|
||||
Form(Paper),
|
||||
/// An uploaded PDF and the size of each of its pages.
|
||||
Pdf(PdfDocument, Vec<(f32, f32)>),
|
||||
/// An image and its EXIF orientation.
|
||||
Image(Image, u16),
|
||||
/// A page that says what could not be added, and why.
|
||||
Note(String),
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
fn pages(&self) -> Result<usize> {
|
||||
Ok(match self {
|
||||
Piece::Form(p) => papers::page_count(*p)?,
|
||||
Piece::Pdf(_, sizes) => sizes.len(),
|
||||
Piece::Image(..) | Piece::Note(_) => 1,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What goes into the PDF for one document.
|
||||
fn piece(what: &str, file: Option<Loaded>) -> Piece {
|
||||
let later = "Open it from the Documents tab and print it from there.";
|
||||
let Some(file) = file else {
|
||||
return Piece::Note(format!("{what}: the file was not found. {later}"));
|
||||
};
|
||||
let name = file.name;
|
||||
let bytes = match file.bytes {
|
||||
Ok(b) => b,
|
||||
Err(why) => {
|
||||
return Piece::Note(format!("{what}: {name} could not be read ({why}). {later}"));
|
||||
}
|
||||
};
|
||||
if file.content_type == "application/pdf" {
|
||||
return match Pdf::new(bytes) {
|
||||
Ok(pdf) => {
|
||||
let sizes: Vec<(f32, f32)> =
|
||||
pdf.pages().iter().map(|p| p.render_dimensions()).collect();
|
||||
if sizes.is_empty() {
|
||||
Piece::Note(format!("{what}: {name} has no pages."))
|
||||
} else {
|
||||
Piece::Pdf(PdfDocument::new(Arc::new(pdf)), sizes)
|
||||
}
|
||||
}
|
||||
Err(e) => Piece::Note(format!(
|
||||
"{what}: {name} is a PDF the app cannot read ({e:?}). {later}"
|
||||
)),
|
||||
};
|
||||
}
|
||||
let orientation = if file.content_type == "image/jpeg" {
|
||||
exif_orientation(&bytes)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let data: Data = bytes.into();
|
||||
let image = match file.content_type.as_str() {
|
||||
"image/jpeg" => Image::from_jpeg(data, true),
|
||||
"image/png" => Image::from_png(data, true),
|
||||
"image/webp" => Image::from_webp(data, true),
|
||||
other => Err(format!("{other} is not an image type the app takes")),
|
||||
};
|
||||
match image {
|
||||
Ok(i) => Piece::Image(i, orientation),
|
||||
Err(e) => Piece::Note(format!(
|
||||
"{what}: {name} is an image the app cannot read ({e}). {later}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pages of each item that prints: the item's index in `items`, its
|
||||
/// first and last page (counted from 1).
|
||||
type Spans = Vec<(usize, usize, usize)>;
|
||||
|
||||
/// The pack as one PDF: the cover sheet, then the items that print. `files`
|
||||
/// holds the documents' files by id.
|
||||
pub fn render(
|
||||
cover: &Cover,
|
||||
items: &[Item],
|
||||
v: &Values,
|
||||
mut files: HashMap<i64, Loaded>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let pen = Pen::sarabun()?;
|
||||
let mut plan: Vec<(usize, Vec<Piece>)> = Vec::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
let mut pieces: Vec<Piece> = item.paper.into_iter().map(Piece::Form).collect();
|
||||
for id in &item.docs {
|
||||
pieces.push(piece(&item.what, files.remove(id)));
|
||||
}
|
||||
if !pieces.is_empty() {
|
||||
plan.push((i, pieces));
|
||||
}
|
||||
}
|
||||
// the cover's own length decides where the rest begins
|
||||
let counts: Vec<usize> = plan
|
||||
.iter()
|
||||
.map(|(_, pieces)| pieces.iter().map(Piece::pages).sum::<Result<usize>>())
|
||||
.collect::<Result<_>>()?;
|
||||
let spans_after = |cover_pages: usize| -> Spans {
|
||||
let mut next = cover_pages + 1;
|
||||
plan.iter()
|
||||
.zip(&counts)
|
||||
.map(|((i, _), n)| {
|
||||
let span = (*i, next, next + n - 1);
|
||||
next += n;
|
||||
span
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let guess = cover_sheet(&pen, cover, items, &spans_after(1)).len();
|
||||
let spans = spans_after(guess);
|
||||
let sheet = cover_sheet(&pen, cover, items, &spans);
|
||||
let built = match build(
|
||||
&pen,
|
||||
cover,
|
||||
items,
|
||||
v,
|
||||
&plan,
|
||||
&spans,
|
||||
&sheet,
|
||||
PdfVersion::Pdf17,
|
||||
)? {
|
||||
// an uploaded PDF of version 2.0 needs a pack of 2.0
|
||||
Err(KrillaError::Pdf(_, PdfError::VersionMismatch(_), _)) => build(
|
||||
&pen,
|
||||
cover,
|
||||
items,
|
||||
v,
|
||||
&plan,
|
||||
&spans,
|
||||
&sheet,
|
||||
PdfVersion::Pdf20,
|
||||
)?,
|
||||
other => other,
|
||||
};
|
||||
built.map_err(|e| anyhow!("writing the pack: {e:?}"))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build(
|
||||
pen: &Pen<'_>,
|
||||
cover: &Cover,
|
||||
items: &[Item],
|
||||
v: &Values,
|
||||
plan: &[(usize, Vec<Piece>)],
|
||||
spans: &Spans,
|
||||
sheet: &[Vec<Draw>],
|
||||
version: PdfVersion,
|
||||
) -> Result<Result<Vec<u8>, KrillaError>> {
|
||||
let configuration = ConfigurationBuilder::new()
|
||||
.with_version(version)
|
||||
.finish()
|
||||
.map_err(|e| anyhow!("the PDF's version: {e:?}"))?;
|
||||
let mut doc = Document::new_with(SerializeSettings {
|
||||
configuration,
|
||||
..Default::default()
|
||||
});
|
||||
doc.set_metadata(
|
||||
Metadata::new()
|
||||
.title(cover.title.clone())
|
||||
.creator("visa.buildfor.life".to_string()),
|
||||
);
|
||||
let top = |page: usize| XyzDestination::new(page, Point::from_xy(0.0, 0.0));
|
||||
let mut outline = Outline::new();
|
||||
outline.push_child(OutlineNode::new("Contents".to_string(), top(0)));
|
||||
for draws in sheet {
|
||||
let mut page = doc.start_page_with(a4(false));
|
||||
let mut s = page.surface();
|
||||
for d in draws {
|
||||
d.draw(&mut s, pen);
|
||||
}
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
for ((i, pieces), (_, first, _)) in plan.iter().zip(spans) {
|
||||
outline.push_child(OutlineNode::new(heading(&items[*i]), top(first - 1)));
|
||||
for piece in pieces {
|
||||
match piece {
|
||||
Piece::Form(p) => papers::add_form(&mut doc, pen, *p, v)?,
|
||||
Piece::Pdf(pdf, sizes) => {
|
||||
for (k, &(w, h)) in sizes.iter().enumerate() {
|
||||
let (Some(settings), Some(size)) =
|
||||
(PageSettings::from_wh(w, h), Size::from_wh(w, h))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let mut page = doc.start_page_with(settings);
|
||||
let mut s = page.surface();
|
||||
s.draw_pdf_page(pdf, size, k);
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
}
|
||||
Piece::Image(image, orientation) => image_page(&mut doc, image, *orientation),
|
||||
Piece::Note(text) => note_page(&mut doc, pen, text),
|
||||
}
|
||||
}
|
||||
}
|
||||
doc.set_outline(outline);
|
||||
Ok(doc.finish())
|
||||
}
|
||||
|
||||
fn a4(landscape: bool) -> PageSettings {
|
||||
let (w, h) = if landscape { (H, W) } else { (W, H) };
|
||||
PageSettings::from_wh(w, h).expect("A4 is a valid page size")
|
||||
}
|
||||
|
||||
/// "TM.7 Application for extension of temporary stay", or what a copy is.
|
||||
fn heading(item: &Item) -> String {
|
||||
if item.code.is_empty() {
|
||||
item.what.clone()
|
||||
} else {
|
||||
format!("{} {}", item.code, item.what)
|
||||
}
|
||||
}
|
||||
|
||||
/// Something drawn on the cover sheet.
|
||||
enum Draw {
|
||||
Text {
|
||||
x: f32,
|
||||
y: f32,
|
||||
size: f32,
|
||||
color: (u8, u8, u8),
|
||||
text: String,
|
||||
},
|
||||
Rule {
|
||||
y: f32,
|
||||
},
|
||||
}
|
||||
|
||||
impl Draw {
|
||||
fn draw(&self, s: &mut Surface<'_>, pen: &Pen<'_>) {
|
||||
match self {
|
||||
Draw::Text {
|
||||
x,
|
||||
y,
|
||||
size,
|
||||
color,
|
||||
text,
|
||||
} => {
|
||||
s.set_fill(Some(fill(*color)));
|
||||
s.draw_text(
|
||||
Point::from_xy(*x, *y),
|
||||
pen.font.clone(),
|
||||
*size,
|
||||
text,
|
||||
false,
|
||||
TextDirection::Auto,
|
||||
);
|
||||
}
|
||||
Draw::Rule { y } => {
|
||||
let mut pb = PathBuilder::new();
|
||||
pb.move_to(MARGIN, *y);
|
||||
pb.line_to(W - MARGIN, *y);
|
||||
if let Some(path) = pb.finish() {
|
||||
s.set_fill(None);
|
||||
s.set_stroke(Some(Stroke {
|
||||
paint: color(GOLD).into(),
|
||||
width: 1.6,
|
||||
line_cap: LineCap::Butt,
|
||||
opacity: NormalizedF32::ONE,
|
||||
..Default::default()
|
||||
}));
|
||||
s.draw_path(&path);
|
||||
s.set_stroke(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn color((r, g, b): (u8, u8, u8)) -> rgb::Color {
|
||||
rgb::Color::new(r, g, b)
|
||||
}
|
||||
|
||||
fn fill(c: (u8, u8, u8)) -> Fill {
|
||||
Fill {
|
||||
paint: color(c).into(),
|
||||
opacity: NormalizedF32::ONE,
|
||||
rule: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` at a size that fits `room`, at least 7.5 points, cut short with
|
||||
/// an ellipsis if even that is too wide.
|
||||
fn clip(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> (String, f32) {
|
||||
let w = width(&pen.face, text, size);
|
||||
if w <= room {
|
||||
return (text.to_string(), size);
|
||||
}
|
||||
let smaller = (size * room / w).max(7.5);
|
||||
if width(&pen.face, text, smaller) <= room {
|
||||
return (text.to_string(), smaller);
|
||||
}
|
||||
let mut cut: String = text.to_string();
|
||||
while !cut.is_empty() && width(&pen.face, &format!("{cut}…"), smaller) > room {
|
||||
cut.pop();
|
||||
}
|
||||
(format!("{}…", cut.trim_end()), smaller)
|
||||
}
|
||||
|
||||
/// `text` broken into lines that fit `room`.
|
||||
fn wrap(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
let mut line = String::new();
|
||||
for word in text.split_whitespace() {
|
||||
let tried = if line.is_empty() {
|
||||
word.to_string()
|
||||
} else {
|
||||
format!("{line} {word}")
|
||||
};
|
||||
if width(&pen.face, &tried, size) > room && !line.is_empty() {
|
||||
lines.push(std::mem::take(&mut line));
|
||||
line = word.to_string();
|
||||
} else {
|
||||
line = tried;
|
||||
}
|
||||
}
|
||||
if !line.is_empty() {
|
||||
lines.push(line);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The cover sheet, page by page: the application, the contents with their
|
||||
/// pages, what is still missing, and what to do before handing it in.
|
||||
fn cover_sheet(pen: &Pen<'_>, cover: &Cover, items: &[Item], spans: &Spans) -> Vec<Vec<Draw>> {
|
||||
/// Moves down by `step` (to a new page at the bottom) and draws there.
|
||||
fn put(pages: &mut Vec<Vec<Draw>>, y: &mut f32, step: f32, d: Draw) {
|
||||
*y += step;
|
||||
if *y > H - 56.0 {
|
||||
pages.push(Vec::new());
|
||||
*y = 72.0;
|
||||
}
|
||||
let d = match d {
|
||||
Draw::Text {
|
||||
x,
|
||||
size,
|
||||
color,
|
||||
text,
|
||||
..
|
||||
} => Draw::Text {
|
||||
x,
|
||||
y: *y,
|
||||
size,
|
||||
color,
|
||||
text,
|
||||
},
|
||||
Draw::Rule { .. } => Draw::Rule { y: *y },
|
||||
};
|
||||
if let Some(p) = pages.last_mut() {
|
||||
p.push(d);
|
||||
}
|
||||
}
|
||||
fn text(x: f32, size: f32, color: (u8, u8, u8), text: String) -> Draw {
|
||||
Draw::Text {
|
||||
x,
|
||||
y: 0.0,
|
||||
size,
|
||||
color,
|
||||
text,
|
||||
}
|
||||
}
|
||||
let mut pages: Vec<Vec<Draw>> = vec![Vec::new()];
|
||||
let mut y = 72.0;
|
||||
let right = W - MARGIN;
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
0.0,
|
||||
text(
|
||||
MARGIN,
|
||||
17.0,
|
||||
NAVY,
|
||||
"Extension of stay for work (Non-B)".into(),
|
||||
),
|
||||
);
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
24.0,
|
||||
text(MARGIN, 13.0, INK, cover.person.clone()),
|
||||
);
|
||||
for line in &cover.lines {
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
16.0,
|
||||
text(MARGIN, 10.0, GREY, line.clone()),
|
||||
);
|
||||
}
|
||||
put(&mut pages, &mut y, 14.0, Draw::Rule { y: 0.0 });
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
26.0,
|
||||
text(MARGIN, 12.0, NAVY, "Contents".into()),
|
||||
);
|
||||
let mut part = 0;
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if item.level == "info" {
|
||||
continue;
|
||||
}
|
||||
if item.part != part {
|
||||
part = item.part;
|
||||
let title = format!("{part} {}", PARTS[part - 1]);
|
||||
put(&mut pages, &mut y, 19.0, text(MARGIN, 10.5, NAVY, title));
|
||||
}
|
||||
let pages_of = spans.iter().find(|(k, ..)| *k == i);
|
||||
let (place, color) = match pages_of {
|
||||
Some((_, a, b)) if a == b => (format!("page {a}"), INK),
|
||||
Some((_, a, b)) => (format!("pages {a}-{b}"), INK),
|
||||
None if item.bring && item.level == "ok" => ("bring it".to_string(), INK),
|
||||
None => (item.label.to_lowercase(), RED),
|
||||
};
|
||||
// the state of an item that prints but needs a look
|
||||
let state = match (pages_of.is_some(), item.level) {
|
||||
(true, "warn") => Some((item.label.to_string(), AMBER)),
|
||||
(true, "bad") => Some((item.label.to_string(), RED)),
|
||||
_ => None,
|
||||
};
|
||||
let x = MARGIN + 20.0;
|
||||
let room = right - 128.0 - x;
|
||||
let (title, size) = clip(pen, &heading(item), 9.5, room);
|
||||
put(&mut pages, &mut y, 14.5, text(x, size, INK, title));
|
||||
let pw = width(&pen.face, &place, 9.5);
|
||||
put(&mut pages, &mut y, 0.0, text(right - pw, 9.5, color, place));
|
||||
if let Some((label, c)) = state {
|
||||
put(&mut pages, &mut y, 0.0, text(right - 122.0, 8.5, c, label));
|
||||
}
|
||||
}
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
30.0,
|
||||
text(MARGIN, 12.0, NAVY, "Before handing it in".into()),
|
||||
);
|
||||
let room = W - 2.0 * MARGIN - 14.0;
|
||||
for point in BEFORE {
|
||||
let mut first = true;
|
||||
for line in wrap(pen, point, 9.5, room) {
|
||||
let step = if first { 17.0 } else { 12.5 };
|
||||
if first {
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
step,
|
||||
text(MARGIN, 9.5, GOLD_DARK, "•".into()),
|
||||
);
|
||||
put(&mut pages, &mut y, 0.0, text(MARGIN + 14.0, 9.5, INK, line));
|
||||
} else {
|
||||
put(
|
||||
&mut pages,
|
||||
&mut y,
|
||||
step,
|
||||
text(MARGIN + 14.0, 9.5, INK, line),
|
||||
);
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
// the footer sits at the bottom of the last page
|
||||
if y > H - 48.0 {
|
||||
pages.push(Vec::new());
|
||||
}
|
||||
if let Some(last) = pages.last_mut() {
|
||||
last.push(Draw::Text {
|
||||
x: MARGIN,
|
||||
y: H - 30.0,
|
||||
size: 8.0,
|
||||
color: GREY,
|
||||
text: cover.made.clone(),
|
||||
});
|
||||
}
|
||||
pages
|
||||
}
|
||||
|
||||
/// The bullets' color: the app's gold, darker for paper.
|
||||
const GOLD_DARK: (u8, u8, u8) = (196, 150, 0);
|
||||
|
||||
/// An image on an A4 page of its own orientation, as large as the margins
|
||||
/// allow, turned upright as its EXIF orientation says.
|
||||
fn image_page(doc: &mut Document, image: &Image, orientation: u16) {
|
||||
let (pw, ph) = image.size();
|
||||
let (w, h) = (pw.max(1) as f32, ph.max(1) as f32);
|
||||
let (dw, dh) = if orientation >= 5 { (h, w) } else { (w, h) };
|
||||
let landscape = dw > dh;
|
||||
let (page_w, page_h) = if landscape { (H, W) } else { (W, H) };
|
||||
let scale = ((page_w - 2.0 * MARGIN) / dw).min((page_h - 2.0 * MARGIN) / dh);
|
||||
let (x0, y0) = ((page_w - dw * scale) / 2.0, (page_h - dh * scale) / 2.0);
|
||||
let Some(size) = Size::from_wh(w, h) else {
|
||||
return;
|
||||
};
|
||||
let [sx, ky, kx, sy, tx, ty] = upright(orientation, w, h);
|
||||
let mut page = doc.start_page_with(a4(landscape));
|
||||
let mut s = page.surface();
|
||||
s.push_transform(&Transform::from_row(scale, 0.0, 0.0, scale, x0, y0));
|
||||
s.push_transform(&Transform::from_row(sx, ky, kx, sy, tx, ty));
|
||||
s.draw_image(image.clone(), size);
|
||||
s.pop();
|
||||
s.pop();
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
|
||||
/// The matrix `[sx, ky, kx, sy, tx, ty]` (x' = sx x + kx y + tx,
|
||||
/// y' = ky x + sy y + ty) that shows an image of `w` x `h` pixels upright,
|
||||
/// for its EXIF orientation (1 to 8), in a box of the turned size.
|
||||
fn upright(orientation: u16, w: f32, h: f32) -> [f32; 6] {
|
||||
match orientation {
|
||||
2 => [-1.0, 0.0, 0.0, 1.0, w, 0.0],
|
||||
3 => [-1.0, 0.0, 0.0, -1.0, w, h],
|
||||
4 => [1.0, 0.0, 0.0, -1.0, 0.0, h],
|
||||
5 => [0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
|
||||
6 => [0.0, 1.0, -1.0, 0.0, h, 0.0],
|
||||
7 => [0.0, -1.0, -1.0, 0.0, h, w],
|
||||
8 => [0.0, -1.0, 1.0, 0.0, 0.0, w],
|
||||
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// A page in place of a file that could not be added.
|
||||
fn note_page(doc: &mut Document, pen: &Pen<'_>, note: &str) {
|
||||
let mut page = doc.start_page_with(a4(false));
|
||||
let mut s = page.surface();
|
||||
let mut draws = vec![Draw::Text {
|
||||
x: MARGIN,
|
||||
y: 96.0,
|
||||
size: 15.0,
|
||||
color: RED,
|
||||
text: "This file could not be added".into(),
|
||||
}];
|
||||
let mut y = 128.0;
|
||||
for line in wrap(pen, note, 11.0, W - 2.0 * MARGIN) {
|
||||
draws.push(Draw::Text {
|
||||
x: MARGIN,
|
||||
y,
|
||||
size: 11.0,
|
||||
color: INK,
|
||||
text: line,
|
||||
});
|
||||
y += 16.0;
|
||||
}
|
||||
for d in &draws {
|
||||
d.draw(&mut s, pen);
|
||||
}
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
|
||||
/// The orientation (1 to 8) that the EXIF block of a JPEG gives; 1 when it
|
||||
/// has none. Phones store a photo as the sensor saw it and say in this tag
|
||||
/// how to turn it; browsers follow it, and so does the pack.
|
||||
pub fn exif_orientation(jpeg: &[u8]) -> u16 {
|
||||
fn at16(b: &[u8], i: usize, le: bool) -> Option<u16> {
|
||||
let x: [u8; 2] = b.get(i..i + 2)?.try_into().ok()?;
|
||||
Some(if le {
|
||||
u16::from_le_bytes(x)
|
||||
} else {
|
||||
u16::from_be_bytes(x)
|
||||
})
|
||||
}
|
||||
fn at32(b: &[u8], i: usize, le: bool) -> Option<u32> {
|
||||
let x: [u8; 4] = b.get(i..i + 4)?.try_into().ok()?;
|
||||
Some(if le {
|
||||
u32::from_le_bytes(x)
|
||||
} else {
|
||||
u32::from_be_bytes(x)
|
||||
})
|
||||
}
|
||||
/// The tag 0x0112 in the first image directory of a TIFF block.
|
||||
fn in_tiff(t: &[u8]) -> Option<u16> {
|
||||
let le = match t.get(0..2)? {
|
||||
b"II" => true,
|
||||
b"MM" => false,
|
||||
_ => return None,
|
||||
};
|
||||
if at16(t, 2, le)? != 42 {
|
||||
return None;
|
||||
}
|
||||
let dir = at32(t, 4, le)? as usize;
|
||||
let n = at16(t, dir, le)? as usize;
|
||||
(0..n)
|
||||
.map(|k| dir + 2 + k * 12)
|
||||
.find(|&e| at16(t, e, le) == Some(0x0112))
|
||||
.and_then(|e| at16(t, e + 8, le))
|
||||
.filter(|v| (1..=8).contains(v))
|
||||
}
|
||||
fn find(jpeg: &[u8]) -> Option<u16> {
|
||||
if !jpeg.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut i = 2;
|
||||
loop {
|
||||
if *jpeg.get(i)? != 0xFF {
|
||||
return None;
|
||||
}
|
||||
let marker = *jpeg.get(i + 1)?;
|
||||
match marker {
|
||||
// fill bytes
|
||||
0xFF => i += 1,
|
||||
// markers without a length
|
||||
0x01 | 0xD0..=0xD8 => i += 2,
|
||||
// the image data begins: no EXIF before it
|
||||
0xD9 | 0xDA => return None,
|
||||
_ => {
|
||||
let len = at16(jpeg, i + 2, false)? as usize;
|
||||
let body = jpeg.get(i + 4..i + 2 + len)?;
|
||||
if marker == 0xE1
|
||||
&& let Some(tiff) = body.strip_prefix(b"Exif\0\0")
|
||||
{
|
||||
return in_tiff(tiff);
|
||||
}
|
||||
i += 2 + len;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
find(jpeg).unwrap_or(1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A JPEG's head with an EXIF block that says `orientation`.
|
||||
fn jpeg_with(orientation: u16, le: bool) -> Vec<u8> {
|
||||
let mut tiff: Vec<u8> = Vec::new();
|
||||
let p16 =
|
||||
|v: u16, t: &mut Vec<u8>| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() });
|
||||
let p32 =
|
||||
|v: u32, t: &mut Vec<u8>| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() });
|
||||
tiff.extend(if le { b"II" } else { b"MM" });
|
||||
p16(42, &mut tiff);
|
||||
p32(8, &mut tiff);
|
||||
p16(2, &mut tiff);
|
||||
// another tag first, then the orientation (type SHORT, count 1)
|
||||
for (tag, value) in [(0x010F_u16, 0_u16), (0x0112, orientation)] {
|
||||
p16(tag, &mut tiff);
|
||||
p16(3, &mut tiff);
|
||||
p32(1, &mut tiff);
|
||||
p16(value, &mut tiff);
|
||||
p16(0, &mut tiff);
|
||||
}
|
||||
let mut app1 = b"Exif\0\0".to_vec();
|
||||
app1.extend(tiff);
|
||||
let mut out = vec![0xFF, 0xD8];
|
||||
// a JFIF block before it
|
||||
out.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]);
|
||||
out.extend([0xFF, 0xE1]);
|
||||
out.extend(((app1.len() + 2) as u16).to_be_bytes());
|
||||
out.extend(app1);
|
||||
out.extend([0xFF, 0xDA, 0x00, 0x02]);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exif_orientation_is_read_in_either_byte_order() {
|
||||
assert_eq!(exif_orientation(&jpeg_with(6, true)), 6);
|
||||
assert_eq!(exif_orientation(&jpeg_with(8, false)), 8);
|
||||
assert_eq!(
|
||||
exif_orientation(&jpeg_with(9, false)),
|
||||
1,
|
||||
"not an orientation"
|
||||
);
|
||||
assert_eq!(exif_orientation(&[0xFF, 0xD8, 0xFF, 0xDA]), 1);
|
||||
let cut = jpeg_with(6, true);
|
||||
assert_eq!(exif_orientation(&cut[..cut.len() / 2]), 1);
|
||||
assert_eq!(exif_orientation(b"not a jpeg"), 1);
|
||||
}
|
||||
|
||||
/// Where the matrix of `upright` puts a point.
|
||||
fn map(m: [f32; 6], (x, y): (f32, f32)) -> (f32, f32) {
|
||||
let [sx, ky, kx, sy, tx, ty] = m;
|
||||
(sx * x + kx * y + tx, ky * x + sy * y + ty)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_maps_the_corners_onto_the_turned_box() {
|
||||
let (w, h) = (40.0_f32, 30.0_f32);
|
||||
for o in 1..=8u16 {
|
||||
let m = upright(o, w, h);
|
||||
let (bw, bh) = if o >= 5 { (h, w) } else { (w, h) };
|
||||
let mut corners: Vec<(f32, f32)> = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]
|
||||
.into_iter()
|
||||
.map(|p| map(m, p))
|
||||
.collect();
|
||||
corners.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
assert_eq!(
|
||||
corners,
|
||||
[(0.0, 0.0), (0.0, bh), (bw, 0.0), (bw, bh)],
|
||||
"orientation {o}"
|
||||
);
|
||||
}
|
||||
// 6, turned a quarter clockwise: the image's top left corner goes
|
||||
// to the top right, its top row becomes the right edge
|
||||
assert_eq!(map(upright(6, w, h), (0.0, 0.0)), (h, 0.0));
|
||||
assert_eq!(map(upright(6, w, h), (w, 0.0)), (h, w));
|
||||
// 8, a quarter the other way: the top row becomes the left edge
|
||||
assert_eq!(map(upright(8, w, h), (0.0, 0.0)), (0.0, w));
|
||||
assert_eq!(map(upright(1, w, h), (w, h)), (w, h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_titles_shrink_or_are_cut_and_notes_wrap() {
|
||||
let pen = Pen::sarabun().unwrap();
|
||||
let (t, size) = clip(&pen, "Short", 9.5, 200.0);
|
||||
assert_eq!((t.as_str(), size), ("Short", 9.5));
|
||||
let long = "List of shareholders (BOJ.5), certified within six months, ".repeat(3);
|
||||
let (t, size) = clip(&pen, &long, 9.5, 200.0);
|
||||
assert!(t.ends_with('…') && size == 7.5, "{t} {size}");
|
||||
assert!(width(&pen.face, &t, size) <= 200.0);
|
||||
let lines = wrap(&pen, BEFORE[4], 9.5, 300.0);
|
||||
assert!(lines.len() > 1);
|
||||
assert_eq!(
|
||||
lines.join(" "),
|
||||
BEFORE[4].split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
);
|
||||
assert!(lines.iter().all(|l| width(&pen.face, l, 9.5) <= 300.0));
|
||||
}
|
||||
}
|
||||
+42
-20
@@ -230,7 +230,7 @@ const MIN_SIZE: f32 = 6.0;
|
||||
const LIFT: f32 = 1.6;
|
||||
|
||||
/// The width of `text` at `size` points, as shaped.
|
||||
fn width(face: &rustybuzz::Face<'_>, text: &str, size: f32) -> f32 {
|
||||
pub(crate) fn width(face: &rustybuzz::Face<'_>, text: &str, size: f32) -> f32 {
|
||||
let mut buf = rustybuzz::UnicodeBuffer::new();
|
||||
buf.push_str(text);
|
||||
buf.guess_segment_properties();
|
||||
@@ -267,9 +267,18 @@ fn first_line<'a>(face: &rustybuzz::Face<'_>, text: &'a str, room: f32) -> (&'a
|
||||
(&text[..end], text[end..].trim_start())
|
||||
}
|
||||
|
||||
struct Pen<'a> {
|
||||
font: Font,
|
||||
face: rustybuzz::Face<'a>,
|
||||
/// Sarabun, for writing on the forms and the pack's cover sheet.
|
||||
pub(crate) struct Pen<'a> {
|
||||
pub(crate) font: Font,
|
||||
pub(crate) face: rustybuzz::Face<'a>,
|
||||
}
|
||||
|
||||
impl Pen<'static> {
|
||||
pub(crate) fn sarabun() -> Result<Pen<'static>> {
|
||||
let font = Font::new(FONT.into(), 0).context("the font Sarabun")?;
|
||||
let face = rustybuzz::Face::from_slice(FONT, 0).context("the font Sarabun")?;
|
||||
Ok(Pen { font, face })
|
||||
}
|
||||
}
|
||||
|
||||
impl Pen<'_> {
|
||||
@@ -418,11 +427,36 @@ fn fill_page(s: &mut Surface<'_>, pen: &Pen<'_>, layout: &Layout, page: usize, v
|
||||
}
|
||||
}
|
||||
|
||||
/// The blank form as the Bureau publishes it, read.
|
||||
fn blank_pdf(paper: Paper) -> Result<Pdf> {
|
||||
Pdf::new(Arc::new(paper.blank())).map_err(|e| anyhow!("the blank form {}: {e:?}", paper.code()))
|
||||
}
|
||||
|
||||
/// How many pages the form has.
|
||||
pub fn page_count(paper: Paper) -> Result<usize> {
|
||||
Ok(blank_pdf(paper)?.pages().len())
|
||||
}
|
||||
|
||||
/// Adds the pages of `paper` to `doc`, filled in with `v`.
|
||||
pub(crate) fn add_form(doc: &mut Document, pen: &Pen<'_>, paper: Paper, v: &Values) -> Result<()> {
|
||||
let pdf = blank_pdf(paper)?;
|
||||
let pages: Vec<(f32, f32)> = pdf.pages().iter().map(|p| p.render_dimensions()).collect();
|
||||
let blank = PdfDocument::new(Arc::new(pdf));
|
||||
for (i, (w, h)) in pages.into_iter().enumerate() {
|
||||
let settings = PageSettings::from_wh(w, h).context("a page size")?;
|
||||
let mut page = doc.start_page_with(settings);
|
||||
let mut s = page.surface();
|
||||
s.draw_pdf_page(&blank, Size::from_wh(w, h).context("a page size")?, i);
|
||||
fill_page(&mut s, pen, paper.layout(), i + 1, v);
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The forms filled in with `v`, one after the other in one PDF.
|
||||
pub fn render(papers: &[Paper], v: &Values, title: &str) -> Result<Vec<u8>> {
|
||||
let font = Font::new(FONT.into(), 0).context("the font Sarabun")?;
|
||||
let face = rustybuzz::Face::from_slice(FONT, 0).context("the font Sarabun")?;
|
||||
let pen = Pen { font, face };
|
||||
let pen = Pen::sarabun()?;
|
||||
let mut doc = Document::new();
|
||||
doc.set_metadata(
|
||||
Metadata::new()
|
||||
@@ -430,19 +464,7 @@ pub fn render(papers: &[Paper], v: &Values, title: &str) -> Result<Vec<u8>> {
|
||||
.creator("visa.buildfor.life".to_string()),
|
||||
);
|
||||
for &paper in papers {
|
||||
let pdf = Pdf::new(Arc::new(paper.blank()))
|
||||
.map_err(|e| anyhow!("the blank form {}: {e:?}", paper.code()))?;
|
||||
let pages: Vec<(f32, f32)> = pdf.pages().iter().map(|p| p.render_dimensions()).collect();
|
||||
let blank = PdfDocument::new(Arc::new(pdf));
|
||||
for (i, (w, h)) in pages.into_iter().enumerate() {
|
||||
let settings = PageSettings::from_wh(w, h).context("a page size")?;
|
||||
let mut page = doc.start_page_with(settings);
|
||||
let mut s = page.surface();
|
||||
s.draw_pdf_page(&blank, Size::from_wh(w, h).context("a page size")?, i);
|
||||
fill_page(&mut s, &pen, paper.layout(), i + 1, v);
|
||||
s.finish();
|
||||
page.finish();
|
||||
}
|
||||
add_form(&mut doc, &pen, paper, v)?;
|
||||
}
|
||||
doc.finish().map_err(|e| anyhow!("writing the PDF: {e:?}"))
|
||||
}
|
||||
|
||||
+103
-1
@@ -4,7 +4,7 @@
|
||||
//! relative to the day it runs, so every kind of deadline shows.
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::{NaiveDate, TimeDelta};
|
||||
use chrono::{Datelike, NaiveDate, TimeDelta};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
@@ -738,6 +738,59 @@ pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Res
|
||||
"photo 4x6.png".into(),
|
||||
demo_png(Picture::Portrait),
|
||||
));
|
||||
// the copies of the passport's pages and the work permit that
|
||||
// the extension pack asks for
|
||||
let copies = [
|
||||
("visas", "issued_on", "visa", "Visa", "visa.pdf"),
|
||||
(
|
||||
"arrivals",
|
||||
"arrived_on",
|
||||
"arrival-stamp",
|
||||
"Arrival stamp",
|
||||
"arrival stamp.pdf",
|
||||
),
|
||||
(
|
||||
"extensions",
|
||||
"applied_on",
|
||||
"extension-stamp",
|
||||
"Extension of stay",
|
||||
"extension stamp.pdf",
|
||||
),
|
||||
(
|
||||
"reentry_permits",
|
||||
"issued_on",
|
||||
"reentry-permit",
|
||||
"Re-entry permit",
|
||||
"re-entry permit.pdf",
|
||||
),
|
||||
(
|
||||
"work_permits",
|
||||
"valid_until",
|
||||
"work-permit",
|
||||
"Work permit",
|
||||
"work permit.pdf",
|
||||
),
|
||||
];
|
||||
for (table, order, kind, title, file) in copies {
|
||||
let link = match table {
|
||||
"reentry_permits" => "reentry-permits",
|
||||
"work_permits" => "work-permits",
|
||||
other => other,
|
||||
};
|
||||
if let Some(r) = one(latest(table, order)).await? {
|
||||
plan.push((
|
||||
owner,
|
||||
kind,
|
||||
Some(format!("{link}:{r}")),
|
||||
None,
|
||||
file.into(),
|
||||
demo_pdf(
|
||||
&format!("{title} (copy of the passport page)"),
|
||||
&[format!("Holder: {whose}")],
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(a) = one(latest("addresses", "moved_in_on")).await? {
|
||||
plan.push((
|
||||
owner,
|
||||
@@ -800,6 +853,55 @@ pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Res
|
||||
"office outside.png".into(),
|
||||
demo_png(Picture::Office),
|
||||
));
|
||||
// the latest year's statements, dated at the year's end
|
||||
let year_end = NaiveDate::from_ymd_opt(today.year() - 1, 12, 31);
|
||||
plan.push((
|
||||
owner,
|
||||
"balance-sheet",
|
||||
None,
|
||||
year_end,
|
||||
"balance sheet and PND50.pdf".into(),
|
||||
demo_pdf(
|
||||
"Balance sheet with PND.50",
|
||||
&[
|
||||
format!("Company: {name}"),
|
||||
"Financial statements of the year".into(),
|
||||
],
|
||||
),
|
||||
));
|
||||
// three months of withholding tax; social security without its date
|
||||
for days in [75, 45, 14] {
|
||||
plan.push((
|
||||
owner,
|
||||
"pnd1",
|
||||
None,
|
||||
Some(today - TimeDelta::days(days)),
|
||||
format!("PND1 {days}.pdf"),
|
||||
demo_pdf(
|
||||
"Withholding tax (PND.1) with its receipt",
|
||||
&[format!("Company: {name}"), format!("Filed {days} days ago")],
|
||||
),
|
||||
));
|
||||
}
|
||||
plan.push((
|
||||
owner,
|
||||
"sps1-10",
|
||||
None,
|
||||
None,
|
||||
"SPS 1-10.pdf".into(),
|
||||
demo_pdf(
|
||||
"Social security (SPS 1-10), three months",
|
||||
&[format!("Company: {name}")],
|
||||
),
|
||||
));
|
||||
plan.push((
|
||||
owner,
|
||||
"map",
|
||||
None,
|
||||
None,
|
||||
"map.pdf".into(),
|
||||
demo_pdf("Map to the office", &[format!("Company: {name}")]),
|
||||
));
|
||||
}
|
||||
let mut tx = db.begin().await?;
|
||||
let mut written = Vec::new();
|
||||
|
||||
+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