Files
visa/src/pack/mod.rs
T
grabowski 1f526f17f9
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 43s
CI / release (push) Skipped
Pack print: A4 upright pages, small pictures at their size, card sides on one sheet
Every page of the pack is now A4 upright, so it prints as one stack. A
PDF page or a whole-page picture that lies wider than tall is turned
onto the page (a small one that fits as it is stays as it is), and a
PDF page is only made smaller, never larger.

A picture never prints larger than its resolution allows (the JFIF or
PNG dpi, else 150 dpi), nor larger than its kind's box: passport pages,
visas and stamps 180 x 128 mm, cards 130 x 90 mm, and a phone's
screenshot (the TDAC, or any picture about twice as tall as wide)
150 x 75 mm. These print at the top of the page.

Cards: a new kind "ID card", and the work permit, take two pictures in
one upload as front and back (migration 0008 documents.back_of). The
Documents tab marks them front/back, lists them together and offers
"Print both sides" (.../documents/{id}/sides.pdf); the pack prints both
on one sheet. The client link takes ID cards too. The demo seeds a TDAC
screenshot and an ID card's two sides.

Checks: fmt, clippy, 108 unit and 57 integration tests (print sizes,
dpi reading, the back following its front, the paired upload, its
audit and the sides PDF); the demo pack's pages checked as images.
The Documents tab's actions stack on a phone, so none is cut off.
2026-11-21 18:30:43 +07:00

1486 lines
49 KiB
Rust

//! The extension pack for work (Non-B): what an immigration office asks for
//! with an extension of stay based on work, item by item in the order the
//! officer reads it, each with its state at the date of the application.
//! The forms are filled in from the records (`papers`); everything else is a
//! document of the person or of the employer, judged by its kind, the record
//! it belongs to and the date on it.
//!
//! `assess` is a pure function of `Facts`, with a unit test per rule; `load`
//! reads the facts. The rules and their sources are in docs/PLAN.md ("The
//! Non-B extension pack").
pub mod pdf;
use anyhow::Result;
use chrono::{DateTime, Datelike, Months, NaiveDate, Utc};
use serde::Serialize;
use sqlx::PgPool;
use crate::dates;
use crate::documents::{self, Document, Owner};
use crate::papers::Paper;
use crate::papers::values::{self, Missing};
use crate::people::{self, AddressInput};
use crate::records::{self, Record};
/// The parts of the pack, in the officer's order.
pub const PARTS: [&str; 6] = [
"The forms",
"The employer's certificate",
"Copies of the passport",
"Receipts",
"The work permit",
"The employer's documents",
];
/// A record a copy belongs to: its id, what the page calls it, and its
/// date (an arrival's, a report's, a passport's issue).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Rec {
pub id: i64,
pub name: String,
pub on: Option<NaiveDate>,
}
/// What the rules read.
#[derive(Clone, Debug, Default)]
pub struct Facts {
pub person: i64,
/// The employer: the work permit's, else the person's.
pub company: Option<Rec>,
/// The passport that runs longest.
pub passport: Option<Rec>,
/// The visa of the last arrival, else the latest visa.
pub visa: Option<Rec>,
/// The last arrival.
pub arrival: Option<Rec>,
/// The last arrival was on a re-entry permit ...
pub on_reentry: bool,
/// ... this one, if it is recorded.
pub reentry: Option<Rec>,
/// Extensions of stay approved since the passport was issued, oldest
/// first: their stamps are in it.
pub extensions: Vec<Rec>,
/// The last 90-day report.
pub report: Option<Rec>,
/// The address the person lives at now.
pub address: Option<Rec>,
/// The work permit that runs longest.
pub work_permit: Option<Rec>,
/// When the person's first work permit was issued.
pub working_since: Option<NaiveDate>,
pub person_docs: Vec<Document>,
pub company_docs: Vec<Document>,
/// What each form of the extension leaves blank.
pub blanks: Vec<(Paper, Vec<Missing>)>,
}
/// One item of the pack.
#[derive(Clone, Debug, Serialize)]
pub struct Item {
/// 1 to 6: the part of the pack (`PARTS`).
pub part: usize,
/// The item's anchor on the page, such as `passport` or `pnd1`.
pub key: &'static str,
/// A form's code, such as TM.7; empty for a copy.
pub code: &'static str,
pub what: String,
/// ok, warn, bad, or info for an item this application does not need
pub level: &'static str,
/// The chip's text: Generated, Uploaded, Missing, Out of date ...
pub label: &'static str,
pub note: String,
/// The form, for an item the app fills in.
#[serde(skip)]
pub paper: Option<Paper>,
/// The documents that go into the PDF, in the order they print.
pub docs: Vec<i64>,
/// What to do about it, and where.
pub fix: Option<Fix>,
/// For a form: what stays blank, each with where it is added.
pub blanks: Vec<Missing>,
/// Brought along rather than printed: the photo.
pub bring: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Fix {
pub text: &'static str,
pub href: String,
}
const GENERATED: &str = "Generated";
const BLANKS: &str = "Has blanks";
const UPLOADED: &str = "Uploaded";
const MISSING: &str = "Missing";
const OLD: &str = "Out of date";
const UNDATED: &str = "No date";
const NOT_NEEDED: &str = "Not needed";
impl Item {
fn new(part: usize, key: &'static str, what: impl Into<String>) -> Item {
Item {
part,
key,
code: "",
what: what.into(),
level: "bad",
label: MISSING,
note: String::new(),
paper: None,
docs: Vec::new(),
fix: None,
blanks: Vec::new(),
bring: false,
}
}
fn set(mut self, level: &'static str, label: &'static str, note: impl Into<String>) -> Item {
self.level = level;
self.label = label;
self.note = note.into();
self
}
fn uploaded(self, note: impl Into<String>, docs: Vec<i64>) -> Item {
let mut it = self.set("ok", UPLOADED, note);
it.docs = docs;
it
}
fn missing(self, note: impl Into<String>, fix: Fix) -> Item {
let mut it = self.set("bad", MISSING, note);
it.fix = Some(fix);
it
}
fn old(self, note: impl Into<String>, fix: Fix) -> Item {
let mut it = self.set("bad", OLD, note);
it.fix = Some(fix);
it
}
/// A document whose age matters, without the date on it: it goes into
/// the PDF, and the page asks for its date.
fn undated(self, d: &Document) -> Item {
let mut it = self.set(
"warn",
UNDATED,
"The date on it is not recorded, so the app cannot tell whether it is recent enough.",
);
it.docs = vec![d.id];
it.fix = Some(Fix {
text: "Add its date",
href: format!("{}/{}/edit", d.owner().base(), d.id),
});
it
}
fn not_needed(self, note: impl Into<String>) -> Item {
self.set("info", NOT_NEEDED, note)
}
/// Whether it puts pages into the PDF.
pub fn printed(&self) -> bool {
self.paper.is_some() || !self.docs.is_empty()
}
}
/// Where things are added: the person's pages and the employer's.
struct Links {
person: i64,
company: Option<i64>,
}
impl Links {
/// The person's upload, with the kind and the record chosen.
fn upload(&self, text: &'static str, kind: &str, record: Option<(&str, i64)>) -> Fix {
let href = match record {
Some((link, id)) => format!("/people/{}/documents?for={link}:{id}#upload", self.person),
None => format!("/people/{}/documents?kind={kind}#upload", self.person),
};
Fix { text, href }
}
/// The employer's upload, on the company's page.
fn company_upload(&self, text: &'static str, kind: &str) -> Fix {
Fix {
text,
href: format!(
"/companies/{}?kind={kind}#upload",
self.company.unwrap_or_default()
),
}
}
/// A new record of the person (`passports`, `arrivals` ...).
fn add(&self, text: &'static str, slug: &str) -> Fix {
Fix {
text,
href: format!("/people/{}/{slug}/new", self.person),
}
}
}
fn fmt(d: NaiveDate) -> String {
dates::fmt_date(d)
}
/// The day of an upload in Chiang Mai.
fn local_day(t: DateTime<Utc>) -> NaiveDate {
t.with_timezone(&dates::bangkok()).date_naive()
}
fn months_before(on: NaiveDate, n: u32) -> NaiveDate {
on.checked_sub_months(Months::new(n))
.unwrap_or(NaiveDate::MIN)
}
fn months_after(on: NaiveDate, n: u32) -> NaiveDate {
on.checked_add_months(Months::new(n))
.unwrap_or(NaiveDate::MAX)
}
/// The documents, the latest date on them first; undated ones last.
fn newest_first<'a>(docs: impl Iterator<Item = &'a Document>) -> Vec<&'a Document> {
let mut v: Vec<&Document> = docs.collect();
v.sort_by_key(|d| std::cmp::Reverse((d.dated_on, d.uploaded_at, d.id)));
v
}
/// "Dated Oct 11, 2026." or "Added Nov 2, 2026."
fn dated_note(d: &Document) -> String {
match d.dated_on {
Some(on) => format!("Dated {}.", fmt(on)),
None => format!("Added {}.", fmt(local_day(d.uploaded_at))),
}
}
/// "A", "A and B", "A, B and C".
fn and_list(items: &[String]) -> String {
match items {
[] => String::new(),
[one] => one.clone(),
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
}
}
/// A copy that belongs to a record: one of `kind` tied to it, else one tied
/// to no record. Copies tied only to other records (an earlier passport, an
/// earlier arrival) are out of date.
fn copy(
f: &Facts,
links: &Links,
it: Item,
kind: &str,
link: &str,
rec: &Rec,
other: String,
) -> Item {
let of_kind = newest_first(f.person_docs.iter().filter(|d| d.kind == kind));
let tied = of_kind.iter().find(|d| {
d.link()
.is_some_and(|(l, id)| l.slug == link && id == rec.id)
});
let loose = of_kind.iter().find(|d| d.link().is_none());
match tied.or(loose) {
Some(d) => it.uploaded(dated_note(d), vec![d.id]),
None if !of_kind.is_empty() => it.old(
other,
links.upload("Upload the right one", kind, Some((link, rec.id))),
),
None => it.missing(
"No copy yet.",
links.upload("Upload it", kind, Some((link, rec.id))),
),
}
}
/// A form of the pack, generated from the records.
fn form(f: &Facts, part: usize, paper: Paper) -> Item {
let mut it = Item::new(part, paper.slug(), paper.title());
it.code = paper.code();
it.paper = Some(paper);
let signs = match paper {
Paper::Stm1 => "The director signs it and adds the company's seal.",
_ => "The person signs it.",
};
let blanks = f
.blanks
.iter()
.find(|(p, _)| *p == paper)
.map(|(_, b)| b.clone())
.unwrap_or_default();
if blanks.is_empty() {
it.set(
"ok",
GENERATED,
format!("Filled in from the records. {signs}"),
)
} else {
it.blanks = blanks;
it.set(
"warn",
BLANKS,
format!("Filled in from the records, but some lines stay blank. {signs}"),
)
}
}
/// The photo glued to TM.7: taken within the six months before the
/// application (the date on it, else the day it was added). It is brought
/// along, not printed.
fn photo(f: &Facts, links: &Links, on: NaiveDate) -> Item {
let mut it = Item::new(1, "photo", "Photo, 4 x 6 cm, for TM.7");
it.bring = true;
let taken = |d: &Document| d.dated_on.unwrap_or_else(|| local_day(d.uploaded_at));
let newest = f
.person_docs
.iter()
.filter(|d| d.kind == "photo")
.max_by_key(|d| (taken(d), d.id));
let Some(d) = newest else {
return it.missing(
"No photo yet. A printed one is glued to TM.7.",
links.upload("Upload it", "photo", None),
);
};
let day = taken(d);
if day >= months_before(on, 6) {
it.set(
"ok",
UPLOADED,
format!("Taken {}. Bring a print of it to glue to TM.7.", fmt(day)),
)
} else {
it.old(
format!(
"The newest photo is from {}, more than six months before {}.",
fmt(day),
fmt(on)
),
links.upload("Upload a newer one", "photo", None),
)
}
}
fn passport(f: &Facts, links: &Links) -> Item {
let it = Item::new(3, "passport", "Passport photo page");
match &f.passport {
None => it.missing(
"No passport is recorded.",
links.add("Add the passport", "passports"),
),
Some(p) => copy(
f,
links,
it,
"passport-photo-page",
"passports",
p,
format!(
"The copy here is of another passport; the current one is {}.",
p.name
),
),
}
}
fn visa(f: &Facts, links: &Links) -> Item {
let it = Item::new(3, "visa", "Visa");
match &f.visa {
None => it.missing(
"No visa is recorded. An extension for work continues a Non-B visa.",
links.add("Add the visa", "visas"),
),
Some(v) => copy(
f,
links,
it,
"visa",
"visas",
v,
format!(
"The copy here is of another visa; the one in use is {}.",
v.name
),
),
}
}
fn arrival(f: &Facts, links: &Links) -> Item {
let it = Item::new(3, "arrival", "Stamp of the last arrival");
match &f.arrival {
None => it.missing(
"No arrival is recorded.",
links.add("Add the arrival", "arrivals"),
),
Some(a) => copy(
f,
links,
it,
"arrival-stamp",
"arrivals",
a,
format!(
"The copy here is of an earlier arrival; the last was on {}.",
a.name
),
),
}
}
/// The re-entry permit, when the last arrival came back on one.
fn reentry(f: &Facts, links: &Links) -> Item {
let it = Item::new(3, "reentry", "Re-entry permit");
if !f.on_reentry {
return it.not_needed("The last arrival was not on a re-entry permit.");
}
match &f.reentry {
None => it.missing(
"The last arrival was on a re-entry permit that is not recorded.",
links.add("Add the permit", "reentry-permits"),
),
Some(r) => copy(
f,
links,
it,
"reentry-permit",
"reentry-permits",
r,
"The copy here is of another re-entry permit.".to_string(),
),
}
}
/// The stamp of every extension approved since the passport was issued.
fn extension_stamps(f: &Facts, links: &Links) -> Item {
let mut it = Item::new(3, "extensions", "Stamps of earlier extensions");
if f.extensions.is_empty() {
return it.not_needed("No extension of stay was approved since the passport was issued.");
}
let stamps = newest_first(f.person_docs.iter().filter(|d| d.kind == "extension-stamp"));
let mut loose: Vec<&Document> = stamps
.iter()
.filter(|d| d.link().is_none())
.copied()
.collect();
let mut docs = Vec::new();
let mut lacking: Vec<&Rec> = Vec::new();
for e in &f.extensions {
let tied = stamps.iter().find(|d| {
d.link()
.is_some_and(|(l, id)| l.slug == "extensions" && id == e.id)
});
match tied.copied().or_else(|| loose.pop()) {
Some(d) => docs.push(d.id),
None => lacking.push(e),
}
}
let names: Vec<String> = f.extensions.iter().map(|e| e.name.clone()).collect();
if let Some(first) = lacking.first() {
let missing: Vec<String> = lacking.iter().map(|e| e.name.clone()).collect();
it.docs = docs;
return it.missing(
format!(
"No copy of the stamp of the extension applied for on {}.",
and_list(&missing)
),
links.upload(
"Upload it",
"extension-stamp",
Some(("extensions", first.id)),
),
);
}
it.uploaded(
format!("The extensions applied for on {}.", and_list(&names)),
docs,
)
}
/// The TDAC of the last arrival; arrivals before May 1, 2025 had none.
fn tdac(f: &Facts, links: &Links) -> Item {
let it = Item::new(3, "tdac", "TDAC of the last arrival");
let Some(a) = &f.arrival else {
return it.missing(
"No arrival is recorded.",
links.add("Add the arrival", "arrivals"),
);
};
let began = NaiveDate::from_ymd_opt(2025, 5, 1).unwrap_or(NaiveDate::MIN);
if a.on.is_some_and(|d| d < began) {
return it.not_needed(format!(
"The last arrival, on {}, came before the TDAC began on May 1, 2025.",
a.name
));
}
copy(
f,
links,
it,
"tdac",
"arrivals",
a,
format!(
"The TDAC here is of an earlier arrival; the last was on {}.",
a.name
),
)
}
fn report(f: &Facts, links: &Links) -> Item {
let it = Item::new(4, "report", "Receipt of the last 90-day report");
match &f.report {
None => it.not_needed("No 90-day report is recorded yet."),
Some(r) => copy(
f,
links,
it,
"ninety-day-receipt",
"reports",
r,
format!(
"The receipt here is of an earlier report; the last was made on {}.",
r.name
),
),
}
}
fn tm30(f: &Facts, links: &Links) -> Item {
let it = Item::new(4, "tm30", "TM.30 receipt of the current address");
match &f.address {
None => it.missing(
"No current address is recorded.",
links.add("Add the address", "addresses"),
),
Some(a) => copy(
f,
links,
it,
"tm30-receipt",
"addresses",
a,
"The receipt here is of an earlier address.".to_string(),
),
}
}
fn work_permit(f: &Facts, links: &Links) -> Item {
let it = Item::new(5, "work-permit", "Work permit");
match &f.work_permit {
None => it.missing(
"No work permit is recorded.",
links.add("Add the work permit", "work-permits"),
),
Some(w) => copy(
f,
links,
it,
"work-permit",
"work-permits",
w,
format!(
"The copy here is of another work permit; the current one is {}.",
w.name
),
),
}
}
/// How long a document of the employer counts.
#[derive(Clone, Copy, Debug)]
enum Rule {
/// Certified by the registrar within the six months before.
Certified,
/// The latest year's statements, dated at the end of the year they
/// cover: the next year's are filed within five months of its end, so
/// they count for 17 months.
LatestYear,
/// Monthly returns of the last three months: the newest is dated within
/// the two months before, and those of the last four months print.
Monthly,
/// The newest one, whatever its date.
Newest,
/// Two or more: outside and inside.
Photos,
}
/// The employer's documents in the pack's order; the applicant's PND.91
/// goes between the VAT returns and the map.
const EMPLOYER: [(&str, &str, Rule); 8] = [
(
"company-certificate",
"Company certificate, certified within six months",
Rule::Certified,
),
(
"shareholders",
"List of shareholders (BOJ.5), certified within six months",
Rule::Certified,
),
(
"balance-sheet",
"Balance sheet with PND.50, of the latest year",
Rule::LatestYear,
),
(
"pnd1",
"Withholding tax (PND.1), the last three months",
Rule::Monthly,
),
(
"sps1-10",
"Social security (SPS 1-10), the last three months",
Rule::Monthly,
),
(
"pp30",
"VAT return (PP.30), the last three months",
Rule::Monthly,
),
("map", "Map to the office", Rule::Newest),
(
"office-photo",
"Photos of the office, outside and inside",
Rule::Photos,
),
];
/// A document that counts for `months` after the date on it: the newest
/// dated one if it still counts, else an undated one (its date is asked
/// for), else the newest dated one is out of date.
fn dated(
it: Item,
docs: &[&Document],
months: u32,
word: &str,
on: NaiveDate,
upload: Fix,
newer: Fix,
) -> Item {
let dated = docs.iter().find(|d| d.dated_on.is_some());
let undated = docs.iter().find(|d| d.dated_on.is_none());
match (dated, undated) {
(Some(d), _) if d.dated_on.is_some_and(|x| x >= months_before(on, months)) => {
let x = d.dated_on.unwrap_or(on);
it.uploaded(
format!(
"{word} {}; it counts until {}.",
fmt(x),
fmt(months_after(x, months))
),
vec![d.id],
)
}
(_, Some(d)) => it.undated(d),
(Some(d), None) => it.old(
format!(
"{word} {}, more than {} before {}.",
fmt(d.dated_on.unwrap_or(on)),
match months {
6 => "six months".to_string(),
n => format!("{n} months"),
},
fmt(on)
),
newer,
),
(None, None) => it.missing("No copy yet.", upload),
}
}
/// One of the employer's documents, for the pack of `on`.
fn employer_item(
links: &Links,
docs: &[Document],
(kind, what, rule): (&'static str, &'static str, Rule),
on: NaiveDate,
) -> Item {
let it = Item::new(6, kind, what);
let all = newest_first(docs.iter().filter(|d| d.kind == kind));
let upload = links.company_upload("Upload it", kind);
let newer = links.company_upload("Upload a newer one", kind);
match rule {
Rule::Certified => dated(it, &all, 6, "Certified", on, upload, newer),
Rule::LatestYear => dated(it, &all, 17, "Dated", on, upload, newer),
Rule::Newest => match all.first() {
Some(d) => it.uploaded(dated_note(d), vec![d.id]),
None => it.missing("No copy yet.", upload),
},
Rule::Photos => {
let ids: Vec<i64> = all.iter().rev().map(|d| d.id).collect();
match ids.len() {
0 => it.missing(
"No photo yet: one outside, with the number and the name of the company, \
and one inside, with the staff at work.",
upload,
),
1 => {
let mut it = it.set(
"warn",
"1 of 2",
"One photo. The office asks for one outside, with the number and the \
name of the company, and one inside, with the staff at work.",
);
it.docs = ids;
it.fix = Some(links.company_upload("Add the other", kind));
it
}
n => it.uploaded(format!("{n} photos."), ids),
}
}
Rule::Monthly => {
let window = months_before(on, 4);
let mut picked: Vec<&Document> = all
.iter()
.filter(|d| d.dated_on.is_none_or(|x| x >= window))
.copied()
.collect();
// the months in order, undated ones after them
picked.sort_by_key(|d| (d.dated_on.is_none(), d.dated_on, d.id));
let newest = all.iter().filter_map(|d| d.dated_on).max();
let undated = all.iter().find(|d| d.dated_on.is_none());
match (newest, undated) {
(Some(x), _) if x >= months_before(on, 2) => {
let days: Vec<NaiveDate> = picked.iter().filter_map(|d| d.dated_on).collect();
let note = match (days.first(), days.last()) {
(Some(a), Some(b)) if days.len() > 1 => {
format!("{} files, dated {} to {}.", days.len(), fmt(*a), fmt(*b))
}
_ => format!("Dated {}.", fmt(x)),
};
it.uploaded(note, picked.iter().map(|d| d.id).collect())
}
(_, Some(d)) => {
let mut it = it.undated(d);
it.docs = picked.iter().map(|d| d.id).collect();
it
}
(Some(x), None) => it.old(
format!(
"The newest is dated {}; the office asks for the last three months.",
fmt(x)
),
newer,
),
(None, None) => it.missing("No copy yet.", upload),
}
}
}
}
/// The applicant's income tax return of the latest year (PND.91, filed by
/// the end of March): dated within the 15 months before. Someone whose
/// first work permit came this year has none yet.
fn pnd91(f: &Facts, links: &Links, on: NaiveDate) -> Item {
let it = Item::new(
6,
"pnd91",
"The applicant's income tax return (PND.91), of the latest year",
);
if let Some(since) = f.working_since
&& since.year() >= on.year()
{
return it.not_needed(format!(
"The first work permit was issued in {}, so there is no return for an earlier year yet.",
since.year()
));
}
let all = newest_first(f.person_docs.iter().filter(|d| d.kind == "pnd91"));
dated(
it,
&all,
15,
"Dated",
on,
links.upload("Upload it", "pnd91", None),
links.upload("Upload a newer one", "pnd91", None),
)
}
/// The pack's items for an application on `on`, in the officer's order.
pub fn assess(f: &Facts, on: NaiveDate) -> Vec<Item> {
let links = Links {
person: f.person,
company: f.company.as_ref().map(|c| c.id),
};
let mut out = vec![
form(f, 1, Paper::Tm7),
photo(f, &links, on),
form(f, 1, Paper::Stm2),
form(f, 1, Paper::Stm9),
form(f, 1, Paper::Stm11),
form(f, 2, Paper::Stm1),
passport(f, &links),
visa(f, &links),
arrival(f, &links),
reentry(f, &links),
extension_stamps(f, &links),
tdac(f, &links),
report(f, &links),
tm30(f, &links),
work_permit(f, &links),
];
match &f.company {
None => {
out.push(
Item::new(6, "employer", "The employer's documents").missing(
"No employer is recorded. Choose the employer on the person's page, or record \
the work permit with it.",
Fix {
text: "Choose the employer",
href: format!("/people/{}/edit", f.person),
},
),
);
out.push(pnd91(f, &links, on));
}
Some(_) => {
for (i, entry) in EMPLOYER.into_iter().enumerate() {
if i == 6 {
out.push(pnd91(f, &links, on));
}
out.push(employer_item(&links, &f.company_docs, entry, on));
}
}
}
let all: Vec<&Document> = f.person_docs.iter().chain(&f.company_docs).collect();
for it in &mut out {
it.docs = with_backs(&it.docs, &all);
}
out
}
/// A card's two sides print together: a back chosen stands for its front,
/// and each front is followed by its back.
fn with_backs(ids: &[i64], docs: &[&Document]) -> Vec<i64> {
let mut out: Vec<i64> = Vec::new();
for id in ids {
let front = docs
.iter()
.find(|d| d.id == *id)
.and_then(|d| d.back_of)
.filter(|f| docs.iter().any(|d| d.id == *f))
.unwrap_or(*id);
if out.contains(&front) {
continue;
}
out.push(front);
if let Some(back) = docs.iter().find(|d| d.back_of == Some(front)) {
out.push(back.id);
}
}
out
}
/// The employer's documents as every employee's pack sees them on `on`, for
/// the company's page.
pub fn employer_items(company: i64, docs: &[Document], on: NaiveDate) -> Vec<Item> {
let links = Links {
person: 0,
company: Some(company),
};
EMPLOYER
.into_iter()
.map(|entry| employer_item(&links, docs, entry, on))
.collect()
}
/// How far the pack is.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Summary {
/// Generated or uploaded, nothing to do.
pub ready: usize,
/// There, but with something to look at: blanks, no date, one photo.
pub check: usize,
/// Missing or out of date.
pub lacking: usize,
pub not_needed: usize,
}
impl Summary {
pub fn of(items: &[Item]) -> Summary {
let count = |level: &str| items.iter().filter(|i| i.level == level).count();
Summary {
ready: count("ok"),
check: count("warn"),
lacking: count("bad"),
not_needed: count("info"),
}
}
pub fn complete(&self) -> bool {
self.check == 0 && self.lacking == 0
}
}
/// "Non-Immigrant B V0000101".
fn visa_name(v: &Record) -> String {
let category = records::visa_category_short(v.get("category"));
match v.get("number") {
"" => category,
n => format!("{category} {n}"),
}
}
/// Reads what the rules need for the person of `v`; `blanks` are what the
/// forms leave blank for this application.
pub async fn load(
db: &PgPool,
v: &values::Facts,
blanks: Vec<(Paper, Vec<Missing>)>,
) -> Result<Facts> {
let id = v.person.id;
let day = |d: Option<NaiveDate>| d.map(fmt).unwrap_or_default();
let passport = v.passport.as_ref().map(|p| Rec {
id: p.id,
name: p.number.clone(),
on: p.issued_on,
});
let visa = v.visa.as_ref().map(|x| Rec {
id: x.id,
name: visa_name(x),
on: x.date("issued_on"),
});
let arrival = v.arrival.as_ref().map(|a| Rec {
id: a.id,
name: day(a.date("arrived_on")),
on: a.date("arrived_on"),
});
let on_reentry = v
.arrival
.as_ref()
.is_some_and(|a| a.get("admission") == "reentry");
let reentry = match (on_reentry, arrival.as_ref().and_then(|a| a.on)) {
(true, Some(arrived)) => records::list(db, &records::REENTRY_PERMITS, id)
.await?
.into_iter()
.filter(|r| r.date("issued_on").is_none_or(|i| i <= arrived))
.max_by_key(|r| (r.date("issued_on"), r.id))
.map(|r| Rec {
id: r.id,
name: r.get("number").to_string(),
on: r.date("issued_on"),
}),
_ => None,
};
let issued = passport.as_ref().and_then(|p| p.on);
let mut extensions: Vec<Rec> = records::list(db, &records::EXTENSIONS, id)
.await?
.into_iter()
.filter(|e| e.get("decision") == "approved")
.filter(|e| match (issued, e.date("applied_on")) {
(Some(i), Some(a)) => a >= i,
_ => true,
})
.map(|e| Rec {
id: e.id,
name: day(e.date("applied_on")),
on: e.date("applied_on"),
})
.collect();
extensions.sort_by_key(|e| (e.on, e.id));
let report = records::list(db, &records::REPORTS, id)
.await?
.into_iter()
.max_by_key(|r| (r.date("reported_on"), r.id))
.map(|r| Rec {
id: r.id,
name: day(r.date("reported_on")),
on: r.date("reported_on"),
});
let address = v.address.as_ref().map(|a| Rec {
id: a.id,
name: people::address_line(&AddressInput::from(a)),
on: a.moved_in_on,
});
let work_permit = v.work_permit.as_ref().map(|w| Rec {
id: w.id,
name: w.get("number").to_string(),
on: w.date("issued_on"),
});
let working_since = records::list(db, &records::WORK_PERMITS, id)
.await?
.iter()
.filter_map(|w| w.date("issued_on"))
.min();
let company = v.company.as_ref().map(|c| Rec {
id: c.id,
name: c.get("name").to_string(),
on: None,
});
let company_docs = match &company {
Some(c) => documents::list(db, Owner::Company(c.id)).await?,
None => Vec::new(),
};
Ok(Facts {
person: id,
company,
passport,
visa,
arrival,
on_reentry,
reentry,
extensions,
report,
address,
work_permit,
working_since,
person_docs: documents::list(db, Owner::Person(id)).await?,
company_docs,
blanks,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn d(s: &str) -> NaiveDate {
dates::parse_date(s).unwrap()
}
const ON: &str = "2026-11-20";
/// A document of the person (or, with `company`, of the company 9).
fn doc(id: i64, kind: &str, link: Option<(&str, i64)>, dated: Option<&str>) -> Document {
let at = DateTime::parse_from_rfc3339("2026-11-02T03:00:00Z")
.unwrap()
.to_utc();
let mut x = Document {
id,
person_id: Some(1),
company_id: None,
kind: kind.into(),
passport_id: None,
address_id: None,
visa_id: None,
arrival_id: None,
extension_id: None,
report_id: None,
reentry_permit_id: None,
work_permit_id: None,
dated_on: dated.map(d),
note: String::new(),
file_name: format!("{kind}.pdf"),
content_type: "application/pdf".into(),
size_bytes: 100,
sha256: "0".repeat(64),
uploaded_by: "test".into(),
uploaded_at: at,
updated_at: at,
back_of: None,
};
match link {
Some(("passports", r)) => x.passport_id = Some(r),
Some(("visas", r)) => x.visa_id = Some(r),
Some(("arrivals", r)) => x.arrival_id = Some(r),
Some(("extensions", r)) => x.extension_id = Some(r),
Some(("reports", r)) => x.report_id = Some(r),
Some(("reentry-permits", r)) => x.reentry_permit_id = Some(r),
Some(("addresses", r)) => x.address_id = Some(r),
Some(("work-permits", r)) => x.work_permit_id = Some(r),
_ => {}
}
x
}
fn company_doc(id: i64, kind: &str, dated: Option<&str>) -> Document {
Document {
person_id: None,
company_id: Some(9),
..doc(id, kind, None, dated)
}
}
fn rec(id: i64, name: &str, on: Option<&str>) -> Rec {
Rec {
id,
name: name.into(),
on: on.map(d),
}
}
/// Erika's records, with no documents yet.
fn facts() -> Facts {
Facts {
person: 1,
company: Some(rec(9, "Demo Engineering Co., Ltd.", None)),
passport: Some(rec(11, "C01X00T47", Some("2021-08-02"))),
visa: Some(rec(21, "Non-Immigrant B V0000101", Some("2025-09-06"))),
arrival: Some(rec(31, "Sep 2, 2026", Some("2026-09-02"))),
on_reentry: true,
reentry: Some(rec(41, "DEMO-RE-0001", Some("2026-01-24"))),
extensions: vec![rec(51, "Jan 14, 2026", Some("2026-01-14"))],
report: Some(rec(61, "Jul 8, 2026", Some("2026-07-08"))),
address: Some(rec(71, "99/9 Moo 4, Chang Phueak", None)),
work_permit: Some(rec(81, "WP-DEMO-0001", Some("2026-01-24"))),
working_since: Some(d("2025-10-01")),
..Facts::default()
}
}
fn find<'a>(items: &'a [Item], key: &str) -> &'a Item {
items.iter().find(|i| i.key == key).unwrap()
}
#[test]
fn the_pack_follows_the_officer_s_order() {
let items = assess(&facts(), d(ON));
let keys: Vec<&str> = items.iter().map(|i| i.key).collect();
assert_eq!(
keys,
[
"tm7",
"photo",
"stm2",
"stm9",
"stm11",
"stm1",
"passport",
"visa",
"arrival",
"reentry",
"extensions",
"tdac",
"report",
"tm30",
"work-permit",
"company-certificate",
"shareholders",
"balance-sheet",
"pnd1",
"sps1-10",
"pp30",
"pnd91",
"map",
"office-photo",
]
);
assert!(items.windows(2).all(|w| w[0].part <= w[1].part));
assert_eq!(find(&items, "stm1").part, 2);
// without an employer, one item asks for it
let f = Facts {
company: None,
..facts()
};
let items = assess(&f, d(ON));
let employer = find(&items, "employer");
assert_eq!((employer.level, employer.part), ("bad", 6));
assert_eq!(employer.fix.as_ref().unwrap().href, "/people/1/edit");
assert!(items.iter().all(|i| i.key != "pnd1"));
}
#[test]
fn forms_are_generated_or_have_blanks() {
let mut f = facts();
f.blanks = vec![
(Paper::Tm7, vec![]),
(
Paper::Stm1,
vec![Missing {
what: "The employer's capital",
href: "/companies/9/edit".into(),
}],
),
];
let items = assess(&f, d(ON));
let tm7 = find(&items, "tm7");
assert_eq!((tm7.level, tm7.label, tm7.code), ("ok", GENERATED, "TM.7"));
assert!(tm7.printed() && tm7.note.contains("The person signs it."));
let stm1 = find(&items, "stm1");
assert_eq!((stm1.level, stm1.label), ("warn", BLANKS));
assert_eq!(stm1.blanks.len(), 1);
assert!(stm1.note.contains("company's seal"), "{}", stm1.note);
}
#[test]
fn the_photo_is_at_most_six_months_old_and_brought_along() {
let mut f = facts();
let it = photo(
&f,
&Links {
person: 1,
company: None,
},
d(ON),
);
assert_eq!(it.label, MISSING);
assert_eq!(
it.fix.unwrap().href,
"/people/1/documents?kind=photo#upload"
);
f.person_docs = vec![doc(5, "photo", None, Some("2026-05-21"))];
let items = assess(&f, d(ON));
let it = find(&items, "photo");
assert_eq!((it.level, it.bring), ("ok", true));
assert!(
it.docs.is_empty() && !it.printed(),
"the photo is not printed"
);
// one day more than six months
f.person_docs = vec![doc(5, "photo", None, Some("2026-05-19"))];
assert_eq!(find(&assess(&f, d(ON)), "photo").label, OLD);
// an undated photo counts from the day it was added (Nov 2, 2026)
f.person_docs = vec![doc(5, "photo", None, None)];
let it = find(&assess(&f, d(ON)), "photo").clone();
assert_eq!(it.level, "ok");
assert!(it.note.contains("Nov 2, 2026"), "{}", it.note);
}
#[test]
fn a_copy_belongs_to_its_record_or_to_none() {
let mut f = facts();
let it = find(&assess(&f, d(ON)), "passport").clone();
assert_eq!(it.label, MISSING);
assert_eq!(
it.fix.unwrap().href,
"/people/1/documents?for=passports:11#upload"
);
// a copy of an earlier passport is out of date
f.person_docs = vec![doc(5, "passport-photo-page", Some(("passports", 10)), None)];
let it = find(&assess(&f, d(ON)), "passport").clone();
assert_eq!(it.label, OLD);
assert!(it.note.contains("C01X00T47"), "{}", it.note);
// one tied to no record counts; one tied to the passport wins
f.person_docs
.push(doc(6, "passport-photo-page", None, Some("2026-10-01")));
assert_eq!(find(&assess(&f, d(ON)), "passport").docs, [6]);
f.person_docs
.push(doc(7, "passport-photo-page", Some(("passports", 11)), None));
let it = find(&assess(&f, d(ON)), "passport").clone();
assert_eq!((it.label, it.docs.as_slice()), (UPLOADED, [7].as_slice()));
// no passport recorded: the fix adds one
f.passport = None;
let it = find(&assess(&f, d(ON)), "passport").clone();
assert_eq!(it.fix.unwrap().href, "/people/1/passports/new");
}
#[test]
fn the_reentry_permit_only_after_a_trip() {
let mut f = facts();
f.person_docs = vec![doc(
5,
"reentry-permit",
Some(("reentry-permits", 41)),
None,
)];
assert_eq!(find(&assess(&f, d(ON)), "reentry").label, UPLOADED);
f.reentry = None;
let it = find(&assess(&f, d(ON)), "reentry").clone();
assert_eq!(it.label, MISSING);
assert_eq!(it.fix.unwrap().href, "/people/1/reentry-permits/new");
f.on_reentry = false;
let it = find(&assess(&f, d(ON)), "reentry").clone();
assert_eq!((it.level, it.label), ("info", NOT_NEEDED));
assert!(!it.printed());
}
#[test]
fn every_extension_since_the_passport_has_its_stamp() {
let mut f = facts();
f.extensions
.insert(0, rec(50, "Jan 15, 2025", Some("2025-01-15")));
f.person_docs = vec![doc(5, "extension-stamp", Some(("extensions", 51)), None)];
let it = find(&assess(&f, d(ON)), "extensions").clone();
assert_eq!(it.label, MISSING);
assert!(it.note.contains("Jan 15, 2025"), "{}", it.note);
assert_eq!(it.docs, [5], "the stamp there still prints");
assert_eq!(
it.fix.unwrap().href,
"/people/1/documents?for=extensions:50#upload"
);
// a stamp tied to no record covers the other
f.person_docs.push(doc(6, "extension-stamp", None, None));
let it = find(&assess(&f, d(ON)), "extensions").clone();
assert_eq!(
(it.label, it.docs.as_slice()),
(UPLOADED, [6, 5].as_slice())
);
assert!(
it.note.contains("Jan 15, 2025 and Jan 14, 2026"),
"{}",
it.note
);
f.extensions.clear();
assert_eq!(find(&assess(&f, d(ON)), "extensions").label, NOT_NEEDED);
}
#[test]
fn the_tdac_belongs_to_the_last_arrival_since_may_2025() {
let mut f = facts();
f.person_docs = vec![doc(5, "tdac", Some(("arrivals", 30)), None)];
let it = find(&assess(&f, d(ON)), "tdac").clone();
assert_eq!(it.label, OLD);
assert!(it.note.contains("Sep 2, 2026"), "{}", it.note);
f.person_docs
.push(doc(6, "tdac", Some(("arrivals", 31)), None));
assert_eq!(find(&assess(&f, d(ON)), "tdac").docs, [6]);
f.arrival = Some(rec(31, "Apr 30, 2025", Some("2025-04-30")));
assert_eq!(find(&assess(&f, d(ON)), "tdac").label, NOT_NEEDED);
}
#[test]
fn the_last_report_s_receipt_and_the_address_s_tm30() {
let mut f = facts();
f.person_docs = vec![
doc(5, "ninety-day-receipt", Some(("reports", 61)), None),
doc(6, "tm30-receipt", Some(("addresses", 70)), None),
];
let items = assess(&f, d(ON));
assert_eq!(find(&items, "report").label, UPLOADED);
assert_eq!(find(&items, "tm30").label, OLD, "an earlier address's");
f.report = None;
f.address = None;
let items = assess(&f, d(ON));
assert_eq!(find(&items, "report").label, NOT_NEEDED);
assert_eq!(
find(&items, "tm30").fix.as_ref().unwrap().href,
"/people/1/addresses/new"
);
}
#[test]
fn certificates_count_for_six_months_from_their_certification() {
let mut f = facts();
let it = find(&assess(&f, d(ON)), "company-certificate").clone();
assert_eq!(it.label, MISSING);
assert_eq!(
it.fix.unwrap().href,
"/companies/9?kind=company-certificate#upload"
);
f.company_docs = vec![company_doc(5, "company-certificate", Some("2026-05-20"))];
let it = find(&assess(&f, d(ON)), "company-certificate").clone();
assert_eq!((it.label, it.docs.as_slice()), (UPLOADED, [5].as_slice()));
assert!(it.note.contains("counts until Nov 20, 2026"), "{}", it.note);
f.company_docs = vec![company_doc(5, "company-certificate", Some("2026-05-19"))];
let it = find(&assess(&f, d(ON)), "company-certificate").clone();
assert_eq!(it.label, OLD);
assert!(it.docs.is_empty(), "an old one does not print");
// an undated one prints and asks for its date
f.company_docs
.push(company_doc(6, "company-certificate", None));
let it = find(&assess(&f, d(ON)), "company-certificate").clone();
assert_eq!((it.level, it.label), ("warn", UNDATED));
assert_eq!(it.docs, [6]);
assert_eq!(it.fix.unwrap().href, "/companies/9/documents/6/edit");
}
#[test]
fn the_balance_sheet_of_the_latest_year() {
let mut f = facts();
f.company_docs = vec![company_doc(5, "balance-sheet", Some("2025-06-30"))];
assert_eq!(find(&assess(&f, d(ON)), "balance-sheet").label, UPLOADED);
f.company_docs = vec![company_doc(5, "balance-sheet", Some("2025-06-19"))];
assert_eq!(find(&assess(&f, d(ON)), "balance-sheet").label, OLD);
}
#[test]
fn three_months_of_monthly_returns() {
let mut f = facts();
f.company_docs = vec![
company_doc(5, "pnd1", Some("2026-06-07")),
company_doc(6, "pnd1", Some("2026-10-07")),
company_doc(7, "pnd1", Some("2026-08-07")),
company_doc(8, "pnd1", Some("2026-09-07")),
];
let it = find(&assess(&f, d(ON)), "pnd1").clone();
assert_eq!(it.label, UPLOADED);
assert_eq!(it.docs, [7, 8, 6], "the last four months, oldest first");
assert!(
it.note
.contains("3 files, dated Aug 7, 2026 to Oct 7, 2026"),
"{}",
it.note
);
// the newest is more than two months old
f.company_docs = vec![company_doc(5, "sps1-10", Some("2026-09-19"))];
let it = find(&assess(&f, d(ON)), "sps1-10").clone();
assert_eq!(it.label, OLD);
assert!(it.note.contains("Sep 19, 2026"), "{}", it.note);
// undated returns print and ask for their dates
f.company_docs.push(company_doc(6, "sps1-10", None));
let it = find(&assess(&f, d(ON)), "sps1-10").clone();
assert_eq!((it.label, it.docs.as_slice()), (UNDATED, [5, 6].as_slice()));
assert_eq!(find(&assess(&f, d(ON)), "pp30").label, MISSING);
}
#[test]
fn the_office_in_two_photos_and_a_map() {
let mut f = facts();
f.company_docs = vec![
company_doc(5, "office-photo", None),
company_doc(6, "map", None),
];
let items = assess(&f, d(ON));
let photos = find(&items, "office-photo");
assert_eq!((photos.level, photos.label), ("warn", "1 of 2"));
assert_eq!(find(&items, "map").label, UPLOADED);
f.company_docs.push(company_doc(7, "office-photo", None));
let it = find(&assess(&f, d(ON)), "office-photo").clone();
assert_eq!(
(it.label, it.docs.as_slice()),
(UPLOADED, [5, 7].as_slice())
);
}
#[test]
fn the_applicant_s_tax_return_unless_work_began_this_year() {
let mut f = facts();
let it = find(&assess(&f, d(ON)), "pnd91").clone();
assert_eq!(it.label, MISSING);
assert_eq!(
it.fix.unwrap().href,
"/people/1/documents?kind=pnd91#upload"
);
f.person_docs = vec![doc(5, "pnd91", None, Some("2025-08-20"))];
assert_eq!(find(&assess(&f, d(ON)), "pnd91").label, UPLOADED);
f.person_docs = vec![doc(5, "pnd91", None, Some("2025-08-19"))];
assert_eq!(find(&assess(&f, d(ON)), "pnd91").label, OLD);
f.working_since = Some(d("2026-01-24"));
assert_eq!(find(&assess(&f, d(ON)), "pnd91").label, NOT_NEEDED);
}
#[test]
fn the_summary_counts_what_is_left() {
let mut f = facts();
f.on_reentry = false;
f.extensions.clear();
f.report = None;
f.working_since = Some(d("2026-01-24"));
let items = assess(&f, d(ON));
let s = Summary::of(&items);
assert_eq!(s.ready, 5, "the forms");
assert_eq!(s.not_needed, 4);
assert_eq!(s.ready + s.check + s.lacking + s.not_needed, items.len());
assert!(!s.complete());
let company = employer_items(9, &[company_doc(5, "map", None)], d(ON));
assert_eq!(company.len(), 8);
assert_eq!(find(&company, "map").label, UPLOADED);
assert_eq!(
find(&company, "pp30").fix.as_ref().unwrap().href,
"/companies/9?kind=pp30#upload"
);
assert_eq!(
and_list(&["a".into(), "b".into(), "c".into()]),
"a, b and c"
);
}
#[test]
fn a_cards_back_prints_after_its_front() {
let mut f = facts();
let mut front = doc(5, "work-permit", Some(("work-permits", 81)), None);
front.content_type = "image/jpeg".into();
// the back has the higher id, so it is the newest: it stands for
// the front, which prints first
let mut back = doc(6, "work-permit", Some(("work-permits", 81)), None);
back.back_of = Some(5);
f.person_docs = vec![front, back];
let it = find(&assess(&f, d(ON)), "work-permit").clone();
assert_eq!(it.docs, [5, 6], "{it:?}");
}
}