From fc8c1b6a44bff45f697f1264a2d3e82ab6109680 Mon Sep 17 00:00:00 2001 From: grabowski Date: Fri, 20 Nov 2026 16:04:13 +0700 Subject: [PATCH] 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. --- AGENTS.md | 2 + Cargo.lock | 89 ++- Cargo.toml | 4 +- README.md | 19 +- docs/PLAN.md | 130 +++- src/lib.rs | 1 + src/pack/mod.rs | 1444 +++++++++++++++++++++++++++++++++++ src/pack/pdf.rs | 796 +++++++++++++++++++ src/papers/mod.rs | 62 +- src/seed.rs | 104 ++- src/web/companies.rs | 29 +- src/web/documents.rs | 8 + src/web/mod.rs | 5 + src/web/pack.rs | 358 +++++++++ src/web/papers.rs | 5 +- static/app.css | 75 +- templates/_deadlines.html | 2 +- templates/_person_head.html | 7 +- templates/company.html | 17 + templates/dashboard.html | 2 +- templates/pack.html | 68 ++ templates/papers.html | 6 +- tests/main.rs | 1 + tests/pack.rs | 183 +++++ tests/pages.rs | 4 + tests/papers.rs | 5 + 26 files changed, 3367 insertions(+), 59 deletions(-) create mode 100644 src/pack/mod.rs create mode 100644 src/pack/pdf.rs create mode 100644 src/web/pack.rs create mode 100644 templates/pack.html create mode 100644 tests/pack.rs diff --git a/AGENTS.md b/AGENTS.md index b426cbd..a4c8e79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,6 +74,8 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | `src/files.rs` | the encrypted document store (a bucket or a directory): sealing, opening, the mirror for backups, checking a file's type | | `src/s3.rs` | a small S3 client with SigV4 signing, for the bucket in Garage | | `src/documents.rs` | documents of people and companies: kinds, records, SQL, `files-check`, `files-migrate` | +| `src/papers/` | the Immigration Bureau's forms filled in (`layout.rs` is generated by `scripts/gen_layout.py`) | +| `src/pack/` | the extension pack: its rules as a pure function (`assess`), and the pack as one PDF (`pdf.rs`) | | `src/web/` | routes, the login gate, pages | | `templates/` | minijinja templates, compiled in by `build.rs` | | `static/` | CSS and JavaScript, compiled in; the URL carries a content hash | diff --git a/Cargo.lock b/Cargo.lock index 852998e..84c811b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -183,6 +183,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -234,6 +240,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "const-oid" version = "0.9.6" @@ -447,6 +459,15 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "fearless_simd" version = "0.4.1" @@ -472,7 +493,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.9.1", "zlib-rs", ] @@ -628,6 +649,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -977,6 +1008,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c" + [[package]] name = "indexmap" version = "2.14.2" @@ -1020,9 +1067,13 @@ dependencies = [ "bumpalo", "flate2", "float-cmp", + "gif", "hayro-write", + "image-webp", + "imagesize", "indexmap", "pdf-writer", + "png", "rustc-hash", "rustybuzz", "siphasher", @@ -1032,6 +1083,7 @@ dependencies = [ "tiny-skia-path", "xmp-writer", "yoke", + "zune-jpeg", ] [[package]] @@ -1160,6 +1212,16 @@ dependencies = [ "serde", ] +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1356,6 +1418,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "polycool" version = "0.4.0" @@ -1392,6 +1467,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quinn" version = "0.11.12" @@ -2635,6 +2716,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "whoami" version = "1.6.1" diff --git a/Cargo.toml b/Cargo.toml index 2bde280..d3ea280 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,9 @@ axum = { version = "0.8", features = ["multipart"] } base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] } form_urlencoded = "1" -krilla = { version = "0.8", default-features = false, features = ["pdf", "simple-text"] } +# pdf: the blank forms and uploaded PDFs go in as they are; raster-images: +# uploaded scans and photos in the extension pack. +krilla = { version = "0.8", default-features = false, features = ["pdf", "raster-images", "simple-text"] } minijinja = "2" # The login service's certificate is checked against the system's CA bundle # (native roots), so a NixOS VM test can bring its own CA. diff --git a/README.md b/README.md index 1b4f873..09aadb7 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ looks after in Thailand: their passports, addresses and TM.30 receipts, visas, arrivals with the TDAC, extensions of stay, re-entry permits, 90-day reports and work permits, and the companies that employ them. From those records it works out every deadline and fills in the Immigration Bureau's -forms. From phase 6 it prepares the whole pack for the next extension of stay -at Chiang Mai Immigration. +forms, and it prepares the whole pack for the next extension of stay at +Chiang Mai Immigration. B4L's own staff use it first. The data model treats everyone as a client of an agency whose staff see all records, so it can grow into the internal tool @@ -18,7 +18,7 @@ view and change of a person's record goes into an append-only activity log that names the fields changed but never their values, as Thailand's Personal Data Protection Act (PDPA) asks. -## What works now (phases 1 to 5) +## What works now (phases 1 to 6) - The Deadlines page: every person's coming deadlines, the most urgent first, with a filter by employer. It covers the 90-day report with its @@ -26,10 +26,11 @@ Data Protection Act (PDPA) asks. a decision to collect, overstay, TM.30 after each arrival, the passport's and the work permit's expiry, and visas still to be used. - A list of people with a filter and each person's next deadline, and a - page per person with five tabs: the overview with personal details, + page per person with six tabs: the overview with personal details, passports and addresses; "Visa and stay" with arrivals and departures, extensions, 90-day reports, visas, re-entry permits and work permits; the - person's documents; the forms; and the person's activity. + person's documents; the forms; the extension pack; and the person's + activity. - Documents: scans and photos of the passport pages, the TDAC, receipts and the photo, dropped on a dashed strip, several at a time, and filed under the record they belong to. A company keeps its own documents for the @@ -42,6 +43,14 @@ Data Protection Act (PDPA) asks. 90-day report and TM.8 for a re-entry permit. Each opens as a PDF or downloads, and the five of an extension come in one file. The Forms tab says what would stay blank and links to where it is added. +- The extension pack for work (Non-B): every item Chiang Mai Immigration + asks for, in the officer's order, each marked as generated, uploaded, + missing, out of date or not needed, with a link to what fixes it. The + employer's certificates count for six months, its monthly returns for the + last three months. "Print the pack" gives one PDF: a cover sheet with the + contents page by page and what to sign and bring, the five forms, then + every copy, scans as they are and photos fitted on A4 and turned upright. + A company's page shows its part of every employee's pack. - Companies with their Thai name, registration number (the check digit is verified), address and signing director. A person's employer and the employer on a work permit are chosen from them, and a company's page adds diff --git a/docs/PLAN.md b/docs/PLAN.md index f986dc0..cbf19e5 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -4,8 +4,9 @@ > 2026, all live at https://visa.buildfor.life. On November 19, 2026 the move > of the documents from a directory on cnx01 into a bucket of cnx01's Garage > was built (task 4.8) and checked in the fleet (task 4.9, cnx-network-clan -> PR #150); the documents move once that PR is deployed. **Resume here: phase -> 6, the Non-B extension pack.** +> PR #150); the documents move once that PR is deployed. Phase 6, the Non-B +> extension pack, was built on November 20, 2026. **Resume here: phase 7, the +> client link.** visa.buildfor.life keeps the immigration records of the foreigners that B4L looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -35,6 +36,11 @@ The first round of questions was answered on November 17, 2026. | Reminders | the dashboard first; later a Matrix room message and an email to the person concerned | | Repository | public `B4L/visa` since Nov 17, 2026: it holds code and invented demo data only, so the fleet fetches it like proplan | | Employers | companies are records of their own under Companies; a person's employer and a work permit's employer are chosen from them, and a company's page adds people to it | +| Which office (Nov 20) | part of each application: the field "Office" on the Pack and Forms tabs, Chiang Mai Immigration unless changed, so the pack's cover sheet names whichever office it goes to | +| Client link (Nov 20) | staff make a link for a person, often a new and empty record; the client fills in personal details, the passport (with the MRZ reader, also from a photo taken on the phone), the address in Thailand and contact, and uploads scans (passport pages, photo, TDAC) | +| Client input (Nov 20) | goes straight into the person's record, logged as coming from the link; staff check it | +| Link lifetime (Nov 20) | 14 days, or until the client presses Send or staff close the link | +| Client agreement (later) | a box on the client link where the client signs the agreement with B4L to keep and work with their data; its text comes from B4L | Kanidm keeps persons, groups and OAuth2 clients in one namespace, so the client cannot be called `visa` like the group. It is `visa-web`, as @@ -146,7 +152,8 @@ downloads (bangkok.immigration.go.th/en/downloads_en); thailand.go.th, For an extension of stay based on work, Chiang Mai Immigration asks for the following. The pack lists each item with its state (generated, uploaded, -missing or out of date) and prints them in this order. +missing, out of date, or not needed for this person) and prints them in this +order. 1. TM.7 with a 4 x 6 cm photo, the acknowledgment of overstay penalties and STM.2, all filled in from the records. @@ -166,6 +173,46 @@ The company documents are shared by every employee's pack, so they are kept once per company with their own expiry (a certification older than six months counts as out of date). +How the app judges each item, at the date of the application (`src/pack/`, +a unit test per rule): + +- **Forms** are generated from the records; one with blank lines is marked + "Has blanks" with links to what fills them. +- **Copies of records** (the passport's photo page, the visa, the last + arrival's stamp and TDAC, the re-entry permit when the last arrival used + one, the stamp of every extension approved since the passport was issued, + the last 90-day receipt, the TM.30 receipt of the current address, the work + permit): a document of the kind tied to that record, else one tied to no + record. A copy tied only to another record (an earlier passport or + arrival) is out of date. Arrivals before May 1, 2025 had no TDAC. +- **The photo** was taken within the six months before (the date on it, else + the day it was added). It is glued to TM.7, so it is brought along rather than printed. +- **The company certificate and BOJ.5** were certified by the registrar + within the six months before; the page says until when each counts. +- **The balance sheet with PND.50** is the latest year's: dated at the end of + the year it covers, it counts for 17 months, since the next year's are + filed within five months of its end. +- **PND.1, SPS 1-10 and PP.30** cover the last three months: the newest is + dated within the two months before, and every one of the last four months + goes into the pack, oldest first. +- **The applicant's PND.91** of the latest year is dated within the 15 months + before; someone whose first work permit was issued this year has none yet. +- **A map** is any; **photos of the office** are two or more (outside, with + the number and the name of the company; inside, with the staff at work). +- A document whose date matters but is not recorded goes into the pack, and + the page asks for its date. + +The PDF starts with a cover sheet: the contents with the page of each item, +what is still missing, and what to do before handing it in (print two sets, +the signatures, the company's seal on every page of the employer's +documents, the photo, the fee of 1,900 THB and the originals to bring). + +Sources: thailand.go.th, "Business visa extension for foreigners working in +Thailand" (guide-book-detail/006_008); Immigration Division 1, "List of +documents required to support an application by a foreigner for extension of +a Non-Immigrant Visa Category B" (counter M); Ministry of Foreign Affairs, +Non-Immigrant Visa B (a photo taken within the past six months). + ## Phases Each phase ends with the tests, clippy, formatting, screenshots in light and @@ -178,9 +225,10 @@ dark at desktop and phone width, a commit and a push. | 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | live Nov 17, 2026 | | 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) in a bucket of cnx01's Garage (first on the dataset `zroot/visa`) with a key var, viewing and download, all audited; the office's GPS position and photo | live Nov 18, 2026; Garage built Nov 19, 2026 | | 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment (STM.9), STM.11, STM.1, TM.47 and TM.8 as PDF | built Nov 18, 2026 | -| 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | | -| 7 | Reminders by Matrix room message and by email | | -| later | Thai user interface, agency cases and fees, a view for clients, other visa categories' packs | | +| 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | built Nov 20, 2026 | +| 7 | The client link: a client fills in their own record on a phone, the MRZ read from a photo; later the signed agreement | planned Nov 20, 2026 | +| 8 | Reminders by Matrix room message and by email | | +| later | Thai user interface, agency cases and fees, other visa categories' packs | | ### Phase 1: app, login, people @@ -352,10 +400,74 @@ one `Kind`. dependencies' build stays the same; a build in a checkout asks git. Live with the release after `a2cedcd`. +### Phase 6: the Non-B extension pack + +- [x] 6.1 The rules (`src/pack/mod.rs`): every item of the pack in the + officer's order with its state at the date of the application, as a + pure function of the records and the documents, with a unit test per + rule ("The Non-B extension pack" above). +- [x] 6.2 A Pack tab on each person: the six parts with each item's state, + what it holds (the form, the files with their dates), and what fixes + it: the upload with the kind and the record chosen (`?for=` and the new + `?kind=` on the Documents tab and on a company's page), a document's + date, or a record to add. The application's fields are those of the + Forms tab, and the two tabs carry them to each other. +- [x] 6.3 One PDF to print (`/people/{id}/pack.pdf`, `src/pack/pdf.rs`): the + cover sheet, the five forms, then every copy in the pack's order. An + uploaded PDF goes in page by page as it is (a PDF 2.0 file makes the + pack 2.0), an image is fitted on an A4 page of its own orientation and + turned as its EXIF tag says, and a file that cannot be read gets a page + that says so. Bookmarks lead to each item. Opening or saving it logs the + forms' codes and a view or download of every document that went in. +- [x] 6.4 A company's page shows its part of every employee's pack, with + until when each certification counts and what to upload. +- [x] 6.5 The extension's deadline (Deadlines page, a person's deadlines) + links to the pack when the person has an employer. The tabs fit a 390 + px phone: "Visa and stay" reads "Stay" there. +- [x] 6.6 Demo data: copies of Erika's visa, arrival stamp, extension stamp, + re-entry permit and work permit, and the employer's balance sheet, + three months of PND.1, an undated SPS 1-10 and a map, so every state + shows (the BOJ.5 is out of date, PP.30 missing, one office photo). +- [x] 6.7 Settled: which office (decisions table). + +### Phase 7: the client link + +Planned on November 20, 2026, from Alex's answers (decisions table). + +- [ ] 7.1 Links: staff make a link on a person's page, and "+ New client" in + the people list makes an empty record with its link. The app keeps only + the SHA-256 of the link's token, as with sessions: it shows the link + once, to copy or as a QR code to show on a phone, and a new link closes + the person's earlier one. The person's page lists the links with their + state (open, used, sent, closed, expired), and staff close one. +- [ ] 7.2 The client's pages at `/c/`, the one part of the app open + without a login: about you, the passport, the address in Thailand, + contact, the documents, and Send. Plain English, phone first, each part + saved on its own; the link's own form token and the same-site check; + nothing about anyone else. After Send, or 14 days, or once staff close + it, the link shows only that it is closed. +- [ ] 7.3 The passport from a photo: on a phone the camera takes the MRZ + (``); the + two lines it reads go into the MRZ field, whose check digits then fill + in the form. The same on the staff's new person and new passport forms. + To settle when building it: reading in the browser (the photo stays on + the phone; Tesseract.js with a model trained for the MRZ, served by the + app, needs `'wasm-unsafe-eval'` in the policy) or on the server. +- [ ] 7.4 Uploads from the client into the encrypted store: the passport's + photo page, the photo, the TDAC and other scans, each tied to its record + where there is one. +- [ ] 7.5 Audit: every view and change through a link is logged with the + actor `link ` and the names of the fields; making, using, sending + and closing a link too. The person's page says when the client sent the + form and links to what changed. +- [ ] 7.6 Later: the agreement. A box where the client signs, drawn on the + screen, the agreement with B4L to keep and work with their data; the + signed agreement is kept as an encrypted document (a PDF with the + signature, the agreement's version and the time). + ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay through the BOI's One Start One Stop center, which changes phase 6's pack. -2. Which Chiang Mai office handles B4L's cases (the main office at 71 Moo 3 - Airport Road or the branch at Central Chiangmai) only matters for the - cover sheet; to be settled in phase 6. +2. The agreement's text for the client link (task 7.6) comes from B4L; a + lawyer may want to check it. diff --git a/src/lib.rs b/src/lib.rs index 40bf496..4de8b22 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/pack/mod.rs b/src/pack/mod.rs new file mode 100644 index 0000000..3608f7a --- /dev/null +++ b/src/pack/mod.rs @@ -0,0 +1,1444 @@ +//! 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, +} + +/// 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, + /// The passport that runs longest. + pub passport: Option, + /// The visa of the last arrival, else the latest visa. + pub visa: Option, + /// The last arrival. + pub arrival: Option, + /// The last arrival was on a re-entry permit ... + pub on_reentry: bool, + /// ... this one, if it is recorded. + pub reentry: Option, + /// Extensions of stay approved since the passport was issued, oldest + /// first: their stamps are in it. + pub extensions: Vec, + /// The last 90-day report. + pub report: Option, + /// The address the person lives at now. + pub address: Option, + /// The work permit that runs longest. + pub work_permit: Option, + /// When the person's first work permit was issued. + pub working_since: Option, + pub person_docs: Vec, + pub company_docs: Vec, + /// What each form of the extension leaves blank. + pub blanks: Vec<(Paper, Vec)>, +} + +/// 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, + /// The documents that go into the PDF, in the order they print. + pub docs: Vec, + /// What to do about it, and where. + pub fix: Option, + /// For a form: what stays blank, each with where it is added. + pub blanks: Vec, + /// 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) -> 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) -> Item { + self.level = level; + self.label = label; + self.note = note.into(); + self + } + + fn uploaded(self, note: impl Into, docs: Vec) -> Item { + let mut it = self.set("ok", UPLOADED, note); + it.docs = docs; + it + } + + fn missing(self, note: impl Into, fix: Fix) -> Item { + let mut it = self.set("bad", MISSING, note); + it.fix = Some(fix); + it + } + + fn old(self, note: impl Into, 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) -> 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, +} + +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) -> 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) -> 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 = f.extensions.iter().map(|e| e.name.clone()).collect(); + if let Some(first) = lacking.first() { + let missing: Vec = 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 = 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 = 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 { + 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)); + } + } + } + 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 { + 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)>, +) -> Result { + let id = v.person.id; + let day = |d: Option| 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 = 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, + }; + 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" + ); + } +} diff --git a/src/pack/pdf.rs b/src/pack/pdf.rs new file mode 100644 index 0000000..3d72192 --- /dev/null +++ b/src/pack/pdf.rs @@ -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, 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, + /// 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 { + 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) -> 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, +) -> Result> { + let pen = Pen::sarabun()?; + let mut plan: Vec<(usize, Vec)> = Vec::new(); + for (i, item) in items.iter().enumerate() { + let mut pieces: Vec = 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 = plan + .iter() + .map(|(_, pieces)| pieces.iter().map(Piece::pages).sum::>()) + .collect::>()?; + 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)], + spans: &Spans, + sheet: &[Vec], + version: PdfVersion, +) -> Result, 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 { + 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> { + /// Moves down by `step` (to a new page at the bottom) and draws there. + fn put(pages: &mut Vec>, 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![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 { + 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 { + 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 { + 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 { + 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 { + let mut tiff: Vec = Vec::new(); + let p16 = + |v: u16, t: &mut Vec| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() }); + let p32 = + |v: u32, t: &mut Vec| 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::>().join(" ") + ); + assert!(lines.iter().all(|l| width(&pen.face, l, 9.5) <= 300.0)); + } +} diff --git a/src/papers/mod.rs b/src/papers/mod.rs index ac9c622..4f9def6 100644 --- a/src/papers/mod.rs +++ b/src/papers/mod.rs @@ -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> { + 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::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 { + 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> { - 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> { .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:?}")) } diff --git a/src/seed.rs b/src/seed.rs index 41b54d2..ca8eb16 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -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(); diff --git a/src/web/companies.rs b/src/web/companies.rs index 784d29f..a81743d 100644 --- a/src/web/companies.rs +++ b/src/web/companies.rs @@ -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, +} + pub async fn show( State(st): State>, Extension(user): Extension, Path(id): Path, + Query(q): Query, ) -> 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 }, )) } diff --git a/src/web/documents.rs b/src/web/documents.rs index f74ec90..bec4727 100644 --- a/src/web/documents.rs +++ b/src/web/documents.rs @@ -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, + /// A kind to add, as the Pack tab asks for it: `photo`. + pub kind: Option, } 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) diff --git a/src/web/mod.rs b/src/web/mod.rs index e105652..4a6c41a 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -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) -> 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 { diff --git a/src/web/pack.rs b/src/web/pack.rs new file mode 100644 index 0000000..9875089 --- /dev/null +++ b/src/web/pack.rs @@ -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, +} + +impl Assessed { + /// The documents of the person and of the employer, by id. + fn docs(&self) -> HashMap { + 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> { + 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, +} + +#[derive(Debug, Serialize)] +struct Part<'a> { + n: usize, + title: &'static str, + items: Vec>, +} + +/// 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, 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>, + Extension(user): Extension, + Path(id): Path, + Query(app): Query, +) -> 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 = 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>, + Extension(user): Extension, + Path(id): Path, + Query(q): Query, +) -> 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 = 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) +} diff --git a/src/web/papers.rs b/src/web/papers.rs index 5b28716..5f8117a 100644 --- a/src/web/papers.rs +++ b/src/web/papers.rs @@ -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, + pub app: Application, + pub download: Option, } /// One form (`tm7.pdf`) or the forms of an extension (`extension.pdf`), diff --git a/static/app.css b/static/app.css index b0bef9c..f7fa72c 100644 --- a/static/app.css +++ b/static/app.css @@ -717,15 +717,30 @@ textarea.mrz { color: var(--hd); border-bottom-color: var(--accent); } -/* five tabs fit a phone */ +.tabs .tab-short { + display: none; +} +/* six tabs fit a phone: "Visa and stay" becomes "Stay" */ @media (max-width: 560px) { .tabs { gap: 0; } .tabs a { - padding: 8px 7px; + padding: 8px 6px; font-size: 13.5px; } + .tabs .tab-long { + display: none; + } + .tabs .tab-short { + display: inline; + } +} +@media (max-width: 380px) { + .tabs a { + padding: 8px 5px; + font-size: 13px; + } } /* ---- status and deadlines */ @@ -1070,6 +1085,62 @@ textarea.mrz { } } +/* ---- the Pack tab and a company's part of the packs: a checklist */ +.checklist { + list-style: none; + margin: 0; + padding: 0; +} +.ci { + display: grid; + grid-template-columns: 96px minmax(0, 1fr); + gap: 4px 12px; + align-items: start; + padding: 10px 0; + border-top: 1px solid var(--line); +} +.ci:first-child { + border-top: 0; + padding-top: 2px; +} +.ci > .chip { + justify-self: start; + margin-top: 1px; +} +.ci-what { + font-weight: 650; + color: var(--hd); +} +.ci-what .paper-code { + display: inline-block; + padding: 0 7px; + margin-right: 2px; +} +.ci-note { + margin: 2px 0 0; + font-size: 13.5px; + color: var(--mute); +} +.ci-blanks { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 2px 12px; + margin: 4px 0 0; + font-size: 13.5px; +} +.ci .rowactions { + margin-top: 4px; +} +.ci:target { + background: var(--accent-s); +} +@media (max-width: 560px) { + .ci { + grid-template-columns: minmax(0, 1fr); + } +} + /* the list runs to the card's edges */ .tblwrap.bleed { margin: 0 -20px -18px; diff --git a/templates/_deadlines.html b/templates/_deadlines.html index c39298a..f673d51 100644 --- a/templates/_deadlines.html +++ b/templates/_deadlines.html @@ -14,7 +14,7 @@
  • {{ d.title }}{% if d.due_text %}{{ d.due_text }}, {{ d.when }}{% if d.estimate %} (estimate){% endif %}{% endif %}
    {{ d.label }} -

    {{ d.note }}

    +

    {{ d.note }}{% if d.key == "extension" and p.employer %} Prepare the pack{% endif %}

  • {% endfor %} diff --git a/templates/_person_head.html b/templates/_person_head.html index 4193f5d..25f565c 100644 --- a/templates/_person_head.html +++ b/templates/_person_head.html @@ -19,10 +19,11 @@ {%- if p.employer %}·{{ p.employer }}{% endif %}

    diff --git a/templates/company.html b/templates/company.html index 9e5d362..37ea202 100644 --- a/templates/company.html +++ b/templates/company.html @@ -118,6 +118,23 @@ +
    +

    For the extension packs

    as each employee's pack sees them today
    +
      + {%- for i in pack %} +
    • + {{ i.label }} +
      +
      {{ i.what }}
      +

      {{ i.note }}

      + {%- if i.fix %} + + {%- endif %} +
      +
    • + {%- endfor %} +
    +

    Company documents

    for the extension packs of the people employed here
    {{ dm.upload(upload, csrf, person=false) }} diff --git a/templates/dashboard.html b/templates/dashboard.html index a33c22b..cd228f4 100644 --- a/templates/dashboard.html +++ b/templates/dashboard.html @@ -35,7 +35,7 @@ {{ r.person }}{% if r.employer %}
    {{ r.employer }}
    {% endif %} {{ r.d.title }} {{ r.d.label }} - {{ r.d.note }} + {{ r.d.note }}{% if r.d.key == "extension" and r.employer %} Prepare the pack{% endif %} {% endfor %} diff --git a/templates/pack.html b/templates/pack.html new file mode 100644 index 0000000..1577c87 --- /dev/null +++ b/templates/pack.html @@ -0,0 +1,68 @@ +{% extends "base.html" %} +{% import "_fields.html" as fm %} +{% block main %} +{% include "_person_head.html" %} +
    +
    +

    Extension pack, work (Non-B)

    +
    + {{ summary.ready }} ready + {%- if summary.check %}{{ summary.check }} to check{% endif %} + {%- if summary.lacking %}{{ summary.lacking }} missing or out of date{% endif %} + {%- if summary.not_needed %}{{ summary.not_needed }} not needed{% endif %} +
    +

    For {{ app.at }} on {{ on }}. {% if complete %}Everything is there. Print the pack twice: the office takes two sets.{% else %}The PDF holds what is there, and its cover sheet lists the rest. Once nothing is missing, print it twice: the office takes two sets.{% endif %}

    + {%- for part in parts %} +

    {{ part.n }}. {{ part.title }}

    +
      + {%- for i in part.items %} +
    • + {{ i.label }} +
      +
      {% if i.code %}{{ i.code }} {% endif %}{{ i.what }}
      + {%- if i.note %} +

      {{ i.note }}

      + {%- endif %} + {%- if i.blanks %} +

      Still blank:{% for m in i.blanks %}{{ m.what }}{% endfor %}

      + {%- endif %} + {%- if i.open or i.files or i.fix %} +
      + {%- if i.open %}Open the form{% endif %} + {%- for f in i.files %}{{ f.label }}{% endfor %} + {%- if i.fix %}{{ i.fix.text }}{% endif %} +
      + {%- endif %} +
      +
    • + {%- endfor %} +
    + {%- endfor %} +
    +
    +

    This application

    +
    + {%- if errors %} +
    Correct what is marked; the pack opens once these values are right.
    + {%- endif %} +

    The same values fill the forms on the Forms tab. They are not stored: the links carry them.

    +
    + {{ fm.text("date", "Date at the office", app.date, err=errors.date, type="date", req=true, hint="The date on the forms; the documents must count on that day.") }} + {{ fm.text("at", "Office", app.at, err=errors.at, hint="The office the pack goes to.") }} + {{ fm.text("reason", "Reason for the extension", app.reason, err=errors.reason, hint="As TM.7 and the Thai half of STM.2 state it.", cls="wide") }} + {{ fm.text("short", "The reason in a few words", app.short, err=errors.short, hint="For the narrow lines of STM.2 and STM.11.", cls="wide") }} + {{ fm.text("days", "Days asked for", app.days, err=errors.days, type="number", hint="365 for a year of work.") }} + {{ fm.text("nth", "Which yearly extension", app.nth, err=errors.nth, type="number", hint="STM.11 asks: 1 for the first.") }} +
    + {#- the trip stays as it was, for TM.8 on the Forms tab #} + + + + + + +
    +
    +
    +
    +{% endblock %} diff --git a/templates/papers.html b/templates/papers.html index 511db67..dfa5850 100644 --- a/templates/papers.html +++ b/templates/papers.html @@ -5,7 +5,7 @@

    Forms

    The extension's five forms
    -

    Filled in from the records on the Immigration Bureau's own forms, as of 2025. {{ extension_codes }} go with every extension of stay, in this order.

    +

    Filled in from the records on the Immigration Bureau's own forms, as of 2025. {{ extension_codes }} go with every extension of stay, in this order. The Pack tab puts them in one PDF with the copies and the employer's documents.

    {%- for f in forms %}
    @@ -41,9 +41,9 @@ {{ fm.select("entries", "Re-entry permit", app.entries, [("single", "Single entry"), ("multiple", "Multiple entries")], err=errors.entries, blank="Choose") }} {{ fm.text("to", "Travelling to", app.to, err=errors.to, ph="Germany") }} {{ fm.text("leave", "Leaving on", app.leave, err=errors.leave, type="date") }} - {{ fm.text("return", "Back about", app.back, err=errors["return"], type="date") }} + {{ fm.text("return", "Back about", app["return"], err=errors["return"], type="date") }} {{ fm.text("by", "Travelling by", app.by, err=errors.by) }} - {{ fm.text("for", "Purpose", app.purpose, err=errors["for"]) }} + {{ fm.text("for", "Purpose", app["for"], err=errors["for"]) }}
    diff --git a/tests/main.rs b/tests/main.rs index 90b5b6d..649e0f1 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -9,6 +9,7 @@ mod companies; mod deadlines; mod documents; mod garage; +mod pack; mod pages; mod papers; mod people; diff --git a/tests/pack.rs b/tests/pack.rs new file mode 100644 index 0000000..70a5130 --- /dev/null +++ b/tests/pack.rs @@ -0,0 +1,183 @@ +//! The Pack tab: the extension pack's checklist with each item's state, the +//! employer's part on the company's page, and the whole pack as one PDF with +//! its audit entries. + +use axum::http::StatusCode; +use sqlx::PgPool; + +use crate::common::{App, local}; + +async fn seeded(pool: &PgPool) -> (App, i64, i64) { + let today = visa::dates::today(); + visa::seed::demo(pool, today).await.unwrap(); + let app = local(pool.clone()); + let store = app.st.files.as_ref().unwrap(); + visa::seed::demo_documents(pool, store, today) + .await + .unwrap(); + let erika: i64 = sqlx::query_scalar("SELECT id FROM people WHERE surname = 'Mustermann'") + .fetch_one(pool) + .await + .unwrap(); + let company: i64 = + sqlx::query_scalar("SELECT id FROM companies WHERE name = 'Demo Engineering Co., Ltd.'") + .fetch_one(pool) + .await + .unwrap(); + (app, erika, company) +} + +/// The item `key` of the tab, up to the next one. +fn item<'a>(page: &'a str, key: &str) -> &'a str { + let at = page + .find(&format!("id=\"item-{key}\"")) + .unwrap_or_else(|| panic!("no item {key}")); + let rest = &page[at..]; + let end = rest[1..] + .find("
  • Vec<(f32, f32)> { + krilla::pdf::Pdf::new(pdf.to_vec()) + .unwrap() + .pages() + .iter() + .map(|p| p.render_dimensions()) + .collect() +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_tab_shows_each_item_with_its_state(pool: PgPool) { + let (app, id, company) = seeded(&pool).await; + let r = app.get(&format!("/people/{id}/pack")).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let t = r.text(); + assert!(t.contains("Extension pack, work (Non-B)"), "{t}"); + assert!(t.contains("aria-current=\"page\">Pack"), "{t}"); + // the forms come from the records; the copies from the documents + assert!(item(&t, "tm7").contains("Generated")); + assert!(item(&t, "tm7").contains(&format!("/people/{id}/forms/tm7.pdf?date="))); + for key in [ + "passport", + "visa", + "arrival", + "reentry", + "extensions", + "tdac", + "work-permit", + ] { + assert!( + item(&t, key).contains("Uploaded"), + "{key}: {}", + item(&t, key) + ); + } + // the employer's documents, each judged by its date + assert!(item(&t, "company-certificate").contains("counts until")); + assert!(item(&t, "shareholders").contains("Out of date")); + assert!(item(&t, "pnd1").contains("3 files")); + assert!(item(&t, "sps1-10").contains("No date")); + assert!(item(&t, "office-photo").contains("1 of 2")); + let pp30 = item(&t, "pp30"); + assert!(pp30.contains("Missing"), "{pp30}"); + assert!( + pp30.contains(&format!("/companies/{company}?kind=pp30#upload")), + "{pp30}" + ); + assert!(t.contains(&format!("/people/{id}/pack.pdf?date="))); + // the Forms tab and the Pack tab carry the application to each other + let r = app.get(&format!("/people/{id}/pack?days=180")).await; + assert!(r.text().contains(&format!("/people/{id}/forms?date="))); + assert!(r.text().contains("days=180")); + // a wrong value is marked, and its PDF goes back to the tab + let r = app.get(&format!("/people/{id}/pack?date=202611-20")).await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + let r = app.get(&format!("/people/{id}/pack.pdf?days=many")).await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert!(r.location().starts_with(&format!("/people/{id}/pack?"))); + assert_eq!( + app.get("/people/999999/pack").await.status, + StatusCode::NOT_FOUND + ); + + // the fixes open the upload with the kind chosen + let r = app.get(&format!("/people/{id}/documents?kind=pnd91")).await; + assert!(r.text().contains("