Phase 6: the Non-B extension pack, checked and printed as one PDF
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 31s

The pack for an extension of stay based on work, item by item in the
officer's order, each with its state at the date of the application:
generated, has blanks, uploaded, missing, out of date, no date, or not
needed for this person.

- src/pack/mod.rs: the rules as a pure function of the records and the
  documents, a unit test per rule. Copies belong to their record (the
  current passport, the last arrival and its TDAC, the re-entry permit it
  came back on, every extension since the passport was issued, the last
  90-day report, the current address, the work permit); the company
  certificate and BOJ.5 count six months from their certification, the
  balance sheet 17 months from its year's end, PND.1, SPS 1-10 and PP.30
  the last three months, PND.91 the latest year; two photos of the office.
  Sources in docs/PLAN.md (thailand.go.th 006_008, Immigration Division 1).
- A Pack tab: the six parts, each item's files and form, and what fixes it
  (the upload with the kind and record chosen, through the new ?kind= on
  the Documents tab and on a company's page; a document's date; a record).
  The application's fields are the Forms tab's, and both tabs carry them.
- /people/{id}/pack.pdf (src/pack/pdf.rs): a cover sheet with the contents
  page by page and what to sign and bring, the five forms, then every copy:
  uploaded PDFs as they are (a PDF 2.0 upload makes the pack 2.0), images
  fitted on A4 and turned as their EXIF orientation says, a page in place of
  a file that cannot be read; bookmarks per item. krilla gains its
  raster-images feature. The audit logs the forms' codes and a view or
  download of each document that went in.
- A company's page shows its part of every employee's pack.
- The extension deadline links to the pack; at 390 px the six tabs fit, as
  "Visa and stay" reads "Stay" on phones.
- Demo data shows every state.
- The Forms tab showed "Back about" and "Purpose" empty: the template read
  app.back and app.purpose, which serialize as "return" and "for".

docs/PLAN.md: phase 6 done, open question 2 settled (the office is the
application's), phase 7 planned from Alex's answers: the client link, the
MRZ from a phone photo, later the signed agreement; reminders move to 8.

Checks: cargo fmt, clippy -D warnings, 97 unit and 47 integration tests;
layout_check 0 problems (pack, company, forms, dashboard, person; light,
dark, desk, phone); the tabs measured at 390 and 360 px; the pack PDF
rendered and looked at, an EXIF-turned JPEG upright.
This commit is contained in:
grabowski committed 2026-11-20 16:04:13 +07:00
1 parent 990d5c88a4
commit fc8c1b6a44
26 files changed
+3366 -58

No files matched your search

+2
View File
@@ -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/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/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/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 | | `src/web/` | routes, the login gate, pages |
| `templates/` | minijinja templates, compiled in by `build.rs` | | `templates/` | minijinja templates, compiled in by `build.rs` |
| `static/` | CSS and JavaScript, compiled in; the URL carries a content hash | | `static/` | CSS and JavaScript, compiled in; the URL carries a content hash |
Generated
+88 -1
View File
@@ -183,6 +183,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]] [[package]]
name = "bytes" name = "bytes"
version = "1.12.1" version = "1.12.1"
@@ -234,6 +240,12 @@ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]] [[package]]
name = "const-oid" name = "const-oid"
version = "0.9.6" version = "0.9.6"
@@ -447,6 +459,15 @@ dependencies = [
"pin-project-lite", "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]] [[package]]
name = "fearless_simd" name = "fearless_simd"
version = "0.4.1" version = "0.4.1"
@@ -472,7 +493,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [ dependencies = [
"crc32fast", "crc32fast",
"miniz_oxide", "miniz_oxide 0.9.1",
"zlib-rs", "zlib-rs",
] ]
@@ -628,6 +649,16 @@ dependencies = [
"wasm-bindgen", "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]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.15.5" version = "0.15.5"
@@ -977,6 +1008,22 @@ dependencies = [
"icu_properties", "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]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.14.2" version = "2.14.2"
@@ -1020,9 +1067,13 @@ dependencies = [
"bumpalo", "bumpalo",
"flate2", "flate2",
"float-cmp", "float-cmp",
"gif",
"hayro-write", "hayro-write",
"image-webp",
"imagesize",
"indexmap", "indexmap",
"pdf-writer", "pdf-writer",
"png",
"rustc-hash", "rustc-hash",
"rustybuzz", "rustybuzz",
"siphasher", "siphasher",
@@ -1032,6 +1083,7 @@ dependencies = [
"tiny-skia-path", "tiny-skia-path",
"xmp-writer", "xmp-writer",
"yoke", "yoke",
"zune-jpeg",
] ]
[[package]] [[package]]
@@ -1160,6 +1212,16 @@ dependencies = [
"serde", "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]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.9.1" version = "0.9.1"
@@ -1356,6 +1418,19 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" 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]] [[package]]
name = "polycool" name = "polycool"
version = "0.4.0" version = "0.4.0"
@@ -1392,6 +1467,12 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]] [[package]]
name = "quinn" name = "quinn"
version = "0.11.12" version = "0.11.12"
@@ -2635,6 +2716,12 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "weezl"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]] [[package]]
name = "whoami" name = "whoami"
version = "1.6.1" version = "1.6.1"
+3 -1
View File
@@ -27,7 +27,9 @@ axum = { version = "0.8", features = ["multipart"] }
base64 = "0.22" base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] } chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
form_urlencoded = "1" 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" minijinja = "2"
# The login service's certificate is checked against the system's CA bundle # 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. # (native roots), so a NixOS VM test can bring its own CA.
+14 -5
View File
@@ -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 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 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 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 forms, and it prepares the whole pack for the next extension of stay at
at Chiang Mai Immigration. Chiang Mai Immigration.
B4L's own staff use it first. The data model treats everyone as a client of 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 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 that names the fields changed but never their values, as Thailand's Personal
Data Protection Act (PDPA) asks. 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 - 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 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 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. 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 - 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, passports and addresses; "Visa and stay" with arrivals and departures,
extensions, 90-day reports, visas, re-entry permits and work permits; the 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 - 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 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 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 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 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. 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 - Companies with their Thai name, registration number (the check digit is
verified), address and signing director. A person's employer and the 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 employer on a work permit are chosen from them, and a company's page adds
+121 -9
View File
@@ -4,8 +4,9 @@
> 2026, all live at https://visa.buildfor.life. On November 19, 2026 the move > 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 > 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 > 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 > PR #150); the documents move once that PR is deployed. Phase 6, the Non-B
> 6, the Non-B extension pack.** > 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 visa.buildfor.life keeps the immigration records of the foreigners that B4L
looks after: their passports, addresses in Thailand, arrivals with the Thailand 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 | | 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 | | 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 | | 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 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 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 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, 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 1. TM.7 with a 4 x 6 cm photo, the acknowledgment of overstay penalties and
STM.2, all filled in from the records. 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 once per company with their own expiry (a certification older than six months
counts as out of date). 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 ## Phases
Each phase ends with the tests, clippy, formatting, screenshots in light and 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 | | 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 | | 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 | | 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 | | | 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | built Nov 20, 2026 |
| 7 | Reminders by Matrix room message and by email | | | 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 |
| later | Thai user interface, agency cases and fees, a view for clients, other visa categories' packs | | | 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 ### Phase 1: app, login, people
@@ -352,10 +400,74 @@ one `Kind`.
dependencies' build stays the same; a build in a checkout asks git. dependencies' build stays the same; a build in a checkout asks git.
Live with the release after `a2cedcd`. 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/<token>`, 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
(`<input type="file" accept="image/*" capture="environment">`); 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 <id>` 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 ## Open questions
1. B4L's BOI application: once B4L is promoted, its staff extend their stay 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. 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 2. The agreement's text for the client link (task 7.6) comes from B4L; a
Airport Road or the branch at Central Chiangmai) only matters for the lawyer may want to check it.
cover sheet; to be settled in phase 6.
+1
View File
@@ -15,6 +15,7 @@ pub mod forms;
pub mod gps; pub mod gps;
pub mod mrz; pub mod mrz;
pub mod oidc; pub mod oidc;
pub mod pack;
pub mod papers; pub mod papers;
pub mod people; pub mod people;
pub mod records; pub mod records;
+1444
View File
File diff suppressed because it is too large. Load diff
+796
View File
@@ -0,0 +1,796 @@
//! The pack as one PDF to print: a cover sheet with the contents page by
//! page and what to do before handing it in, then the forms filled in from
//! the records, then every copy in the pack's order. A PDF's pages go in as
//! they are; an image is fitted on an A4 page, turned as the camera's EXIF
//! tag says. A file that cannot be read gets a page that says so, and the
//! pack still prints.
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::{Result, anyhow};
use krilla::color::rgb;
use krilla::configure::{ConfigurationBuilder, PdfVersion};
use krilla::destination::XyzDestination;
use krilla::error::KrillaError;
use krilla::geom::{PathBuilder, Point, Size, Transform};
use krilla::image::Image;
use krilla::metadata::Metadata;
use krilla::num::NormalizedF32;
use krilla::outline::{Outline, OutlineNode};
use krilla::page::PageSettings;
use krilla::paint::{Fill, LineCap, Stroke};
use krilla::pdf::{Pdf, PdfDocument, PdfError};
use krilla::surface::Surface;
use krilla::text::TextDirection;
use krilla::{Data, Document, SerializeSettings};
use super::{Item, PARTS};
use crate::papers::{self, Paper, Pen, Values, width};
/// A file of the pack as the store gave it.
pub struct Loaded {
/// Its name as uploaded.
pub name: String,
pub content_type: String,
/// The file, or why it could not be read.
pub bytes: Result<Vec<u8>, String>,
}
/// What the cover sheet says about the application.
pub struct Cover {
/// The PDF's title.
pub title: String,
/// "MUSTERMANN, Erika"
pub person: String,
/// The passport, the employer, the office and the date.
pub lines: Vec<String>,
/// Who put it together, and when.
pub made: String,
}
/// What the person and the employer do before the pack goes in.
const BEFORE: [&str; 5] = [
"Print the pack twice: the office takes two sets.",
"The person signs TM.7, STM.2, STM.9 and STM.11, and signs every copy of the passport as a \
true copy.",
"Every page of the employer's documents carries the company's seal and the signature of the \
director named in the company certificate; the director also signs STM.1.",
"Glue the 4 x 6 cm photo to TM.7.",
"Bring the passport, the work permit, the fee of 1,900 THB, and the originals of the company \
certificate, BOJ.5, the balance sheet with PND.50, PND.1, PND.91 and SPS 1-10.",
];
/// A4 portrait, in points.
const W: f32 = 595.0;
const H: f32 = 842.0;
const MARGIN: f32 = 48.0;
const NAVY: (u8, u8, u8) = (7, 19, 35);
const INK: (u8, u8, u8) = (34, 38, 46);
const GREY: (u8, u8, u8) = (104, 112, 124);
const RED: (u8, u8, u8) = (176, 32, 32);
const AMBER: (u8, u8, u8) = (150, 98, 0);
const GOLD: (u8, u8, u8) = (245, 192, 0);
/// What one document or form puts into the PDF.
enum Piece {
Form(Paper),
/// An uploaded PDF and the size of each of its pages.
Pdf(PdfDocument, Vec<(f32, f32)>),
/// An image and its EXIF orientation.
Image(Image, u16),
/// A page that says what could not be added, and why.
Note(String),
}
impl Piece {
fn pages(&self) -> Result<usize> {
Ok(match self {
Piece::Form(p) => papers::page_count(*p)?,
Piece::Pdf(_, sizes) => sizes.len(),
Piece::Image(..) | Piece::Note(_) => 1,
})
}
}
/// What goes into the PDF for one document.
fn piece(what: &str, file: Option<Loaded>) -> Piece {
let later = "Open it from the Documents tab and print it from there.";
let Some(file) = file else {
return Piece::Note(format!("{what}: the file was not found. {later}"));
};
let name = file.name;
let bytes = match file.bytes {
Ok(b) => b,
Err(why) => {
return Piece::Note(format!("{what}: {name} could not be read ({why}). {later}"));
}
};
if file.content_type == "application/pdf" {
return match Pdf::new(bytes) {
Ok(pdf) => {
let sizes: Vec<(f32, f32)> =
pdf.pages().iter().map(|p| p.render_dimensions()).collect();
if sizes.is_empty() {
Piece::Note(format!("{what}: {name} has no pages."))
} else {
Piece::Pdf(PdfDocument::new(Arc::new(pdf)), sizes)
}
}
Err(e) => Piece::Note(format!(
"{what}: {name} is a PDF the app cannot read ({e:?}). {later}"
)),
};
}
let orientation = if file.content_type == "image/jpeg" {
exif_orientation(&bytes)
} else {
1
};
let data: Data = bytes.into();
let image = match file.content_type.as_str() {
"image/jpeg" => Image::from_jpeg(data, true),
"image/png" => Image::from_png(data, true),
"image/webp" => Image::from_webp(data, true),
other => Err(format!("{other} is not an image type the app takes")),
};
match image {
Ok(i) => Piece::Image(i, orientation),
Err(e) => Piece::Note(format!(
"{what}: {name} is an image the app cannot read ({e}). {later}"
)),
}
}
/// The pages of each item that prints: the item's index in `items`, its
/// first and last page (counted from 1).
type Spans = Vec<(usize, usize, usize)>;
/// The pack as one PDF: the cover sheet, then the items that print. `files`
/// holds the documents' files by id.
pub fn render(
cover: &Cover,
items: &[Item],
v: &Values,
mut files: HashMap<i64, Loaded>,
) -> Result<Vec<u8>> {
let pen = Pen::sarabun()?;
let mut plan: Vec<(usize, Vec<Piece>)> = Vec::new();
for (i, item) in items.iter().enumerate() {
let mut pieces: Vec<Piece> = item.paper.into_iter().map(Piece::Form).collect();
for id in &item.docs {
pieces.push(piece(&item.what, files.remove(id)));
}
if !pieces.is_empty() {
plan.push((i, pieces));
}
}
// the cover's own length decides where the rest begins
let counts: Vec<usize> = plan
.iter()
.map(|(_, pieces)| pieces.iter().map(Piece::pages).sum::<Result<usize>>())
.collect::<Result<_>>()?;
let spans_after = |cover_pages: usize| -> Spans {
let mut next = cover_pages + 1;
plan.iter()
.zip(&counts)
.map(|((i, _), n)| {
let span = (*i, next, next + n - 1);
next += n;
span
})
.collect()
};
let guess = cover_sheet(&pen, cover, items, &spans_after(1)).len();
let spans = spans_after(guess);
let sheet = cover_sheet(&pen, cover, items, &spans);
let built = match build(
&pen,
cover,
items,
v,
&plan,
&spans,
&sheet,
PdfVersion::Pdf17,
)? {
// an uploaded PDF of version 2.0 needs a pack of 2.0
Err(KrillaError::Pdf(_, PdfError::VersionMismatch(_), _)) => build(
&pen,
cover,
items,
v,
&plan,
&spans,
&sheet,
PdfVersion::Pdf20,
)?,
other => other,
};
built.map_err(|e| anyhow!("writing the pack: {e:?}"))
}
#[allow(clippy::too_many_arguments)]
fn build(
pen: &Pen<'_>,
cover: &Cover,
items: &[Item],
v: &Values,
plan: &[(usize, Vec<Piece>)],
spans: &Spans,
sheet: &[Vec<Draw>],
version: PdfVersion,
) -> Result<Result<Vec<u8>, KrillaError>> {
let configuration = ConfigurationBuilder::new()
.with_version(version)
.finish()
.map_err(|e| anyhow!("the PDF's version: {e:?}"))?;
let mut doc = Document::new_with(SerializeSettings {
configuration,
..Default::default()
});
doc.set_metadata(
Metadata::new()
.title(cover.title.clone())
.creator("visa.buildfor.life".to_string()),
);
let top = |page: usize| XyzDestination::new(page, Point::from_xy(0.0, 0.0));
let mut outline = Outline::new();
outline.push_child(OutlineNode::new("Contents".to_string(), top(0)));
for draws in sheet {
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
for d in draws {
d.draw(&mut s, pen);
}
s.finish();
page.finish();
}
for ((i, pieces), (_, first, _)) in plan.iter().zip(spans) {
outline.push_child(OutlineNode::new(heading(&items[*i]), top(first - 1)));
for piece in pieces {
match piece {
Piece::Form(p) => papers::add_form(&mut doc, pen, *p, v)?,
Piece::Pdf(pdf, sizes) => {
for (k, &(w, h)) in sizes.iter().enumerate() {
let (Some(settings), Some(size)) =
(PageSettings::from_wh(w, h), Size::from_wh(w, h))
else {
continue;
};
let mut page = doc.start_page_with(settings);
let mut s = page.surface();
s.draw_pdf_page(pdf, size, k);
s.finish();
page.finish();
}
}
Piece::Image(image, orientation) => image_page(&mut doc, image, *orientation),
Piece::Note(text) => note_page(&mut doc, pen, text),
}
}
}
doc.set_outline(outline);
Ok(doc.finish())
}
fn a4(landscape: bool) -> PageSettings {
let (w, h) = if landscape { (H, W) } else { (W, H) };
PageSettings::from_wh(w, h).expect("A4 is a valid page size")
}
/// "TM.7 Application for extension of temporary stay", or what a copy is.
fn heading(item: &Item) -> String {
if item.code.is_empty() {
item.what.clone()
} else {
format!("{} {}", item.code, item.what)
}
}
/// Something drawn on the cover sheet.
enum Draw {
Text {
x: f32,
y: f32,
size: f32,
color: (u8, u8, u8),
text: String,
},
Rule {
y: f32,
},
}
impl Draw {
fn draw(&self, s: &mut Surface<'_>, pen: &Pen<'_>) {
match self {
Draw::Text {
x,
y,
size,
color,
text,
} => {
s.set_fill(Some(fill(*color)));
s.draw_text(
Point::from_xy(*x, *y),
pen.font.clone(),
*size,
text,
false,
TextDirection::Auto,
);
}
Draw::Rule { y } => {
let mut pb = PathBuilder::new();
pb.move_to(MARGIN, *y);
pb.line_to(W - MARGIN, *y);
if let Some(path) = pb.finish() {
s.set_fill(None);
s.set_stroke(Some(Stroke {
paint: color(GOLD).into(),
width: 1.6,
line_cap: LineCap::Butt,
opacity: NormalizedF32::ONE,
..Default::default()
}));
s.draw_path(&path);
s.set_stroke(None);
}
}
}
}
}
fn color((r, g, b): (u8, u8, u8)) -> rgb::Color {
rgb::Color::new(r, g, b)
}
fn fill(c: (u8, u8, u8)) -> Fill {
Fill {
paint: color(c).into(),
opacity: NormalizedF32::ONE,
rule: Default::default(),
}
}
/// `text` at a size that fits `room`, at least 7.5 points, cut short with
/// an ellipsis if even that is too wide.
fn clip(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> (String, f32) {
let w = width(&pen.face, text, size);
if w <= room {
return (text.to_string(), size);
}
let smaller = (size * room / w).max(7.5);
if width(&pen.face, text, smaller) <= room {
return (text.to_string(), smaller);
}
let mut cut: String = text.to_string();
while !cut.is_empty() && width(&pen.face, &format!("{cut}…"), smaller) > room {
cut.pop();
}
(format!("{}…", cut.trim_end()), smaller)
}
/// `text` broken into lines that fit `room`.
fn wrap(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> Vec<String> {
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split_whitespace() {
let tried = if line.is_empty() {
word.to_string()
} else {
format!("{line} {word}")
};
if width(&pen.face, &tried, size) > room && !line.is_empty() {
lines.push(std::mem::take(&mut line));
line = word.to_string();
} else {
line = tried;
}
}
if !line.is_empty() {
lines.push(line);
}
lines
}
/// The cover sheet, page by page: the application, the contents with their
/// pages, what is still missing, and what to do before handing it in.
fn cover_sheet(pen: &Pen<'_>, cover: &Cover, items: &[Item], spans: &Spans) -> Vec<Vec<Draw>> {
/// Moves down by `step` (to a new page at the bottom) and draws there.
fn put(pages: &mut Vec<Vec<Draw>>, y: &mut f32, step: f32, d: Draw) {
*y += step;
if *y > H - 56.0 {
pages.push(Vec::new());
*y = 72.0;
}
let d = match d {
Draw::Text {
x,
size,
color,
text,
..
} => Draw::Text {
x,
y: *y,
size,
color,
text,
},
Draw::Rule { .. } => Draw::Rule { y: *y },
};
if let Some(p) = pages.last_mut() {
p.push(d);
}
}
fn text(x: f32, size: f32, color: (u8, u8, u8), text: String) -> Draw {
Draw::Text {
x,
y: 0.0,
size,
color,
text,
}
}
let mut pages: Vec<Vec<Draw>> = vec![Vec::new()];
let mut y = 72.0;
let right = W - MARGIN;
put(
&mut pages,
&mut y,
0.0,
text(
MARGIN,
17.0,
NAVY,
"Extension of stay for work (Non-B)".into(),
),
);
put(
&mut pages,
&mut y,
24.0,
text(MARGIN, 13.0, INK, cover.person.clone()),
);
for line in &cover.lines {
put(
&mut pages,
&mut y,
16.0,
text(MARGIN, 10.0, GREY, line.clone()),
);
}
put(&mut pages, &mut y, 14.0, Draw::Rule { y: 0.0 });
put(
&mut pages,
&mut y,
26.0,
text(MARGIN, 12.0, NAVY, "Contents".into()),
);
let mut part = 0;
for (i, item) in items.iter().enumerate() {
if item.level == "info" {
continue;
}
if item.part != part {
part = item.part;
let title = format!("{part} {}", PARTS[part - 1]);
put(&mut pages, &mut y, 19.0, text(MARGIN, 10.5, NAVY, title));
}
let pages_of = spans.iter().find(|(k, ..)| *k == i);
let (place, color) = match pages_of {
Some((_, a, b)) if a == b => (format!("page {a}"), INK),
Some((_, a, b)) => (format!("pages {a}-{b}"), INK),
None if item.bring && item.level == "ok" => ("bring it".to_string(), INK),
None => (item.label.to_lowercase(), RED),
};
// the state of an item that prints but needs a look
let state = match (pages_of.is_some(), item.level) {
(true, "warn") => Some((item.label.to_string(), AMBER)),
(true, "bad") => Some((item.label.to_string(), RED)),
_ => None,
};
let x = MARGIN + 20.0;
let room = right - 128.0 - x;
let (title, size) = clip(pen, &heading(item), 9.5, room);
put(&mut pages, &mut y, 14.5, text(x, size, INK, title));
let pw = width(&pen.face, &place, 9.5);
put(&mut pages, &mut y, 0.0, text(right - pw, 9.5, color, place));
if let Some((label, c)) = state {
put(&mut pages, &mut y, 0.0, text(right - 122.0, 8.5, c, label));
}
}
put(
&mut pages,
&mut y,
30.0,
text(MARGIN, 12.0, NAVY, "Before handing it in".into()),
);
let room = W - 2.0 * MARGIN - 14.0;
for point in BEFORE {
let mut first = true;
for line in wrap(pen, point, 9.5, room) {
let step = if first { 17.0 } else { 12.5 };
if first {
put(
&mut pages,
&mut y,
step,
text(MARGIN, 9.5, GOLD_DARK, "•".into()),
);
put(&mut pages, &mut y, 0.0, text(MARGIN + 14.0, 9.5, INK, line));
} else {
put(
&mut pages,
&mut y,
step,
text(MARGIN + 14.0, 9.5, INK, line),
);
}
first = false;
}
}
// the footer sits at the bottom of the last page
if y > H - 48.0 {
pages.push(Vec::new());
}
if let Some(last) = pages.last_mut() {
last.push(Draw::Text {
x: MARGIN,
y: H - 30.0,
size: 8.0,
color: GREY,
text: cover.made.clone(),
});
}
pages
}
/// The bullets' color: the app's gold, darker for paper.
const GOLD_DARK: (u8, u8, u8) = (196, 150, 0);
/// An image on an A4 page of its own orientation, as large as the margins
/// allow, turned upright as its EXIF orientation says.
fn image_page(doc: &mut Document, image: &Image, orientation: u16) {
let (pw, ph) = image.size();
let (w, h) = (pw.max(1) as f32, ph.max(1) as f32);
let (dw, dh) = if orientation >= 5 { (h, w) } else { (w, h) };
let landscape = dw > dh;
let (page_w, page_h) = if landscape { (H, W) } else { (W, H) };
let scale = ((page_w - 2.0 * MARGIN) / dw).min((page_h - 2.0 * MARGIN) / dh);
let (x0, y0) = ((page_w - dw * scale) / 2.0, (page_h - dh * scale) / 2.0);
let Some(size) = Size::from_wh(w, h) else {
return;
};
let [sx, ky, kx, sy, tx, ty] = upright(orientation, w, h);
let mut page = doc.start_page_with(a4(landscape));
let mut s = page.surface();
s.push_transform(&Transform::from_row(scale, 0.0, 0.0, scale, x0, y0));
s.push_transform(&Transform::from_row(sx, ky, kx, sy, tx, ty));
s.draw_image(image.clone(), size);
s.pop();
s.pop();
s.finish();
page.finish();
}
/// The matrix `[sx, ky, kx, sy, tx, ty]` (x' = sx x + kx y + tx,
/// y' = ky x + sy y + ty) that shows an image of `w` x `h` pixels upright,
/// for its EXIF orientation (1 to 8), in a box of the turned size.
fn upright(orientation: u16, w: f32, h: f32) -> [f32; 6] {
match orientation {
2 => [-1.0, 0.0, 0.0, 1.0, w, 0.0],
3 => [-1.0, 0.0, 0.0, -1.0, w, h],
4 => [1.0, 0.0, 0.0, -1.0, 0.0, h],
5 => [0.0, 1.0, 1.0, 0.0, 0.0, 0.0],
6 => [0.0, 1.0, -1.0, 0.0, h, 0.0],
7 => [0.0, -1.0, -1.0, 0.0, h, w],
8 => [0.0, -1.0, 1.0, 0.0, 0.0, w],
_ => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
}
}
/// A page in place of a file that could not be added.
fn note_page(doc: &mut Document, pen: &Pen<'_>, note: &str) {
let mut page = doc.start_page_with(a4(false));
let mut s = page.surface();
let mut draws = vec![Draw::Text {
x: MARGIN,
y: 96.0,
size: 15.0,
color: RED,
text: "This file could not be added".into(),
}];
let mut y = 128.0;
for line in wrap(pen, note, 11.0, W - 2.0 * MARGIN) {
draws.push(Draw::Text {
x: MARGIN,
y,
size: 11.0,
color: INK,
text: line,
});
y += 16.0;
}
for d in &draws {
d.draw(&mut s, pen);
}
s.finish();
page.finish();
}
/// The orientation (1 to 8) that the EXIF block of a JPEG gives; 1 when it
/// has none. Phones store a photo as the sensor saw it and say in this tag
/// how to turn it; browsers follow it, and so does the pack.
pub fn exif_orientation(jpeg: &[u8]) -> u16 {
fn at16(b: &[u8], i: usize, le: bool) -> Option<u16> {
let x: [u8; 2] = b.get(i..i + 2)?.try_into().ok()?;
Some(if le {
u16::from_le_bytes(x)
} else {
u16::from_be_bytes(x)
})
}
fn at32(b: &[u8], i: usize, le: bool) -> Option<u32> {
let x: [u8; 4] = b.get(i..i + 4)?.try_into().ok()?;
Some(if le {
u32::from_le_bytes(x)
} else {
u32::from_be_bytes(x)
})
}
/// The tag 0x0112 in the first image directory of a TIFF block.
fn in_tiff(t: &[u8]) -> Option<u16> {
let le = match t.get(0..2)? {
b"II" => true,
b"MM" => false,
_ => return None,
};
if at16(t, 2, le)? != 42 {
return None;
}
let dir = at32(t, 4, le)? as usize;
let n = at16(t, dir, le)? as usize;
(0..n)
.map(|k| dir + 2 + k * 12)
.find(|&e| at16(t, e, le) == Some(0x0112))
.and_then(|e| at16(t, e + 8, le))
.filter(|v| (1..=8).contains(v))
}
fn find(jpeg: &[u8]) -> Option<u16> {
if !jpeg.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut i = 2;
loop {
if *jpeg.get(i)? != 0xFF {
return None;
}
let marker = *jpeg.get(i + 1)?;
match marker {
// fill bytes
0xFF => i += 1,
// markers without a length
0x01 | 0xD0..=0xD8 => i += 2,
// the image data begins: no EXIF before it
0xD9 | 0xDA => return None,
_ => {
let len = at16(jpeg, i + 2, false)? as usize;
let body = jpeg.get(i + 4..i + 2 + len)?;
if marker == 0xE1
&& let Some(tiff) = body.strip_prefix(b"Exif\0\0")
{
return in_tiff(tiff);
}
i += 2 + len;
}
}
}
}
find(jpeg).unwrap_or(1)
}
#[cfg(test)]
mod tests {
use super::*;
/// A JPEG's head with an EXIF block that says `orientation`.
fn jpeg_with(orientation: u16, le: bool) -> Vec<u8> {
let mut tiff: Vec<u8> = Vec::new();
let p16 =
|v: u16, t: &mut Vec<u8>| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() });
let p32 =
|v: u32, t: &mut Vec<u8>| t.extend(if le { v.to_le_bytes() } else { v.to_be_bytes() });
tiff.extend(if le { b"II" } else { b"MM" });
p16(42, &mut tiff);
p32(8, &mut tiff);
p16(2, &mut tiff);
// another tag first, then the orientation (type SHORT, count 1)
for (tag, value) in [(0x010F_u16, 0_u16), (0x0112, orientation)] {
p16(tag, &mut tiff);
p16(3, &mut tiff);
p32(1, &mut tiff);
p16(value, &mut tiff);
p16(0, &mut tiff);
}
let mut app1 = b"Exif\0\0".to_vec();
app1.extend(tiff);
let mut out = vec![0xFF, 0xD8];
// a JFIF block before it
out.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]);
out.extend([0xFF, 0xE1]);
out.extend(((app1.len() + 2) as u16).to_be_bytes());
out.extend(app1);
out.extend([0xFF, 0xDA, 0x00, 0x02]);
out
}
#[test]
fn the_exif_orientation_is_read_in_either_byte_order() {
assert_eq!(exif_orientation(&jpeg_with(6, true)), 6);
assert_eq!(exif_orientation(&jpeg_with(8, false)), 8);
assert_eq!(
exif_orientation(&jpeg_with(9, false)),
1,
"not an orientation"
);
assert_eq!(exif_orientation(&[0xFF, 0xD8, 0xFF, 0xDA]), 1);
let cut = jpeg_with(6, true);
assert_eq!(exif_orientation(&cut[..cut.len() / 2]), 1);
assert_eq!(exif_orientation(b"not a jpeg"), 1);
}
/// Where the matrix of `upright` puts a point.
fn map(m: [f32; 6], (x, y): (f32, f32)) -> (f32, f32) {
let [sx, ky, kx, sy, tx, ty] = m;
(sx * x + kx * y + tx, ky * x + sy * y + ty)
}
#[test]
fn turning_maps_the_corners_onto_the_turned_box() {
let (w, h) = (40.0_f32, 30.0_f32);
for o in 1..=8u16 {
let m = upright(o, w, h);
let (bw, bh) = if o >= 5 { (h, w) } else { (w, h) };
let mut corners: Vec<(f32, f32)> = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]
.into_iter()
.map(|p| map(m, p))
.collect();
corners.sort_by(|a, b| a.partial_cmp(b).unwrap());
assert_eq!(
corners,
[(0.0, 0.0), (0.0, bh), (bw, 0.0), (bw, bh)],
"orientation {o}"
);
}
// 6, turned a quarter clockwise: the image's top left corner goes
// to the top right, its top row becomes the right edge
assert_eq!(map(upright(6, w, h), (0.0, 0.0)), (h, 0.0));
assert_eq!(map(upright(6, w, h), (w, 0.0)), (h, w));
// 8, a quarter the other way: the top row becomes the left edge
assert_eq!(map(upright(8, w, h), (0.0, 0.0)), (0.0, w));
assert_eq!(map(upright(1, w, h), (w, h)), (w, h));
}
#[test]
fn long_titles_shrink_or_are_cut_and_notes_wrap() {
let pen = Pen::sarabun().unwrap();
let (t, size) = clip(&pen, "Short", 9.5, 200.0);
assert_eq!((t.as_str(), size), ("Short", 9.5));
let long = "List of shareholders (BOJ.5), certified within six months, ".repeat(3);
let (t, size) = clip(&pen, &long, 9.5, 200.0);
assert!(t.ends_with('…') && size == 7.5, "{t} {size}");
assert!(width(&pen.face, &t, size) <= 200.0);
let lines = wrap(&pen, BEFORE[4], 9.5, 300.0);
assert!(lines.len() > 1);
assert_eq!(
lines.join(" "),
BEFORE[4].split_whitespace().collect::<Vec<_>>().join(" ")
);
assert!(lines.iter().all(|l| width(&pen.face, l, 9.5) <= 300.0));
}
}
+41 -19
View File
@@ -230,7 +230,7 @@ const MIN_SIZE: f32 = 6.0;
const LIFT: f32 = 1.6; const LIFT: f32 = 1.6;
/// The width of `text` at `size` points, as shaped. /// 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(); let mut buf = rustybuzz::UnicodeBuffer::new();
buf.push_str(text); buf.push_str(text);
buf.guess_segment_properties(); 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()) (&text[..end], text[end..].trim_start())
} }
struct Pen<'a> { /// Sarabun, for writing on the forms and the pack's cover sheet.
font: Font, pub(crate) struct Pen<'a> {
face: rustybuzz::Face<'a>, pub(crate) font: Font,
pub(crate) face: rustybuzz::Face<'a>,
}
impl Pen<'static> {
pub(crate) fn sarabun() -> Result<Pen<'static>> {
let font = Font::new(FONT.into(), 0).context("the font Sarabun")?;
let face = rustybuzz::Face::from_slice(FONT, 0).context("the font Sarabun")?;
Ok(Pen { font, face })
}
} }
impl Pen<'_> { impl Pen<'_> {
@@ -418,20 +427,19 @@ fn fill_page(s: &mut Surface<'_>, pen: &Pen<'_>, layout: &Layout, page: usize, v
} }
} }
/// The forms filled in with `v`, one after the other in one PDF. /// The blank form as the Bureau publishes it, read.
pub fn render(papers: &[Paper], v: &Values, title: &str) -> Result<Vec<u8>> { fn blank_pdf(paper: Paper) -> Result<Pdf> {
let font = Font::new(FONT.into(), 0).context("the font Sarabun")?; Pdf::new(Arc::new(paper.blank())).map_err(|e| anyhow!("the blank form {}: {e:?}", paper.code()))
let face = rustybuzz::Face::from_slice(FONT, 0).context("the font Sarabun")?; }
let pen = Pen { font, face };
let mut doc = Document::new(); /// How many pages the form has.
doc.set_metadata( pub fn page_count(paper: Paper) -> Result<usize> {
Metadata::new() Ok(blank_pdf(paper)?.pages().len())
.title(title.to_string()) }
.creator("visa.buildfor.life".to_string()),
); /// Adds the pages of `paper` to `doc`, filled in with `v`.
for &paper in papers { pub(crate) fn add_form(doc: &mut Document, pen: &Pen<'_>, paper: Paper, v: &Values) -> Result<()> {
let pdf = Pdf::new(Arc::new(paper.blank())) let pdf = blank_pdf(paper)?;
.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 pages: Vec<(f32, f32)> = pdf.pages().iter().map(|p| p.render_dimensions()).collect();
let blank = PdfDocument::new(Arc::new(pdf)); let blank = PdfDocument::new(Arc::new(pdf));
for (i, (w, h)) in pages.into_iter().enumerate() { for (i, (w, h)) in pages.into_iter().enumerate() {
@@ -439,10 +447,24 @@ pub fn render(papers: &[Paper], v: &Values, title: &str) -> Result<Vec<u8>> {
let mut page = doc.start_page_with(settings); let mut page = doc.start_page_with(settings);
let mut s = page.surface(); let mut s = page.surface();
s.draw_pdf_page(&blank, Size::from_wh(w, h).context("a page size")?, i); 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); fill_page(&mut s, pen, paper.layout(), i + 1, v);
s.finish(); s.finish();
page.finish(); page.finish();
} }
Ok(())
}
/// The forms filled in with `v`, one after the other in one PDF.
pub fn render(papers: &[Paper], v: &Values, title: &str) -> Result<Vec<u8>> {
let pen = Pen::sarabun()?;
let mut doc = Document::new();
doc.set_metadata(
Metadata::new()
.title(title.to_string())
.creator("visa.buildfor.life".to_string()),
);
for &paper in papers {
add_form(&mut doc, &pen, paper, v)?;
} }
doc.finish().map_err(|e| anyhow!("writing the PDF: {e:?}")) doc.finish().map_err(|e| anyhow!("writing the PDF: {e:?}"))
} }
+103 -1
View File
@@ -4,7 +4,7 @@
//! relative to the day it runs, so every kind of deadline shows. //! relative to the day it runs, so every kind of deadline shows.
use anyhow::Result; use anyhow::Result;
use chrono::{NaiveDate, TimeDelta}; use chrono::{Datelike, NaiveDate, TimeDelta};
use sqlx::PgPool; use sqlx::PgPool;
use crate::audit::{self, Action, Entity, Entry}; 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(), "photo 4x6.png".into(),
demo_png(Picture::Portrait), 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? { if let Some(a) = one(latest("addresses", "moved_in_on")).await? {
plan.push(( plan.push((
owner, owner,
@@ -800,6 +853,55 @@ pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Res
"office outside.png".into(), "office outside.png".into(),
demo_png(Picture::Office), 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 tx = db.begin().await?;
let mut written = Vec::new(); let mut written = Vec::new();
+19 -10
View File
@@ -160,20 +160,26 @@ pub async fn create(
Ok(Redirect::to(&format!("/companies/{id}")).into_response()) Ok(Redirect::to(&format!("/companies/{id}")).into_response())
} }
#[derive(Debug, Deserialize)]
pub struct ShowQuery {
/// A kind of document to add, as an employee's pack asks for it.
pub kind: Option<String>,
}
pub async fn show( pub async fn show(
State(st): State<Arc<AppState>>, State(st): State<Arc<AppState>>,
Extension(user): Extension<User>, Extension(user): Extension<User>,
Path(id): Path<i64>, Path(id): Path<i64>,
Query(q): Query<ShowQuery>,
) -> Res { ) -> Res {
company_page( let mut values = documents::Values::default();
&st, if let Some(k) = q
&user, .kind
id, .filter(|k| crate::documents::kind(Owner::Company(id), k).is_some())
&documents::Values::default(), {
&Errors::new(), values.kind = k;
StatusCode::OK, }
) company_page(&st, &user, id, &values, &Errors::new(), StatusCode::OK).await
.await
} }
/// The company's page, with its documents and their upload form (and the /// 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 owner = Owner::Company(id);
let docs = documents::views(st, owner, &HashMap::new()).await?; let docs = documents::views(st, owner, &HashMap::new()).await?;
let office = documents::office_context(st, &docs, values, errors); 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 // a refused office photo shows its errors on the office card only
let upload = if values.from_office() { let upload = if values.from_office() {
documents::upload_context( documents::upload_context(
@@ -216,7 +225,7 @@ pub async fn company_page(
&title, &title,
"companies", "companies",
status, status,
context! { c, employees, candidates, docs, upload, office }, context! { c, employees, candidates, docs, upload, office, pack },
)) ))
} }
+8
View File
@@ -333,6 +333,8 @@ pub struct TabQuery {
/// A record to add a document to, as on its page: `arrivals:7`. /// A record to add a document to, as on its page: `arrivals:7`.
#[serde(rename = "for")] #[serde(rename = "for")]
pub for_record: Option<String>, pub for_record: Option<String>,
/// A kind to add, as the Pack tab asks for it: `photo`.
pub kind: Option<String>,
} }
pub async fn person_tab( pub async fn person_tab(
@@ -346,6 +348,12 @@ pub async fn person_tab(
}; };
let choices = choices(&st, id).await?; let choices = choices(&st, id).await?;
let mut values = Values::default(); 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(v) = q.for_record.filter(|v| choices.names.contains_key(v)) {
if let Some((link, _)) = documents::parse_link(&v) { if let Some((link, _)) = documents::parse_link(&v) {
values.kind = documents::kind_for_link(link.slug) values.kind = documents::kind_for_link(link.slug)
+5
View File
@@ -5,6 +5,7 @@ pub mod auth;
pub mod companies; pub mod companies;
pub mod dashboard; pub mod dashboard;
pub mod documents; pub mod documents;
pub mod pack;
pub mod papers; pub mod papers;
pub mod people; pub mod people;
pub mod records; pub mod records;
@@ -242,6 +243,10 @@ pub fn router(st: Arc<AppState>) -> Router {
r = r r = r
.route("/people/{id}/forms", get(papers::tab)) .route("/people/{id}/forms", get(papers::tab))
.route("/people/{id}/forms/{file}", get(papers::pdf)); .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; type OwnerOf = fn(i64) -> Owner;
let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)]; let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)];
for (prefix, owner) in owners { for (prefix, owner) in owners {
+358
View File
@@ -0,0 +1,358 @@
//! A person's Pack tab: the extension pack for work, item by item with its
//! state and what to do about it, and the whole pack as one PDF to print.
//! The application's own values (the date, the office, the reason ...) come
//! from the tab's fields as on the Forms tab and travel in the links, so
//! nothing of them is stored.
use std::collections::HashMap;
use std::sync::Arc;
use axum::Extension;
use axum::body::Body;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use chrono::{NaiveDate, Utc};
use minijinja::context;
use serde::Serialize;
use tracing::error;
use super::documents::{FILE_CSP, disposition};
use super::papers::PdfQuery;
use super::people::load_person;
use super::{AppState, Res, message, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::documents::Document;
use crate::forms::Errors;
use crate::pack::pdf::{Cover, Loaded};
use crate::pack::{self, Item, PARTS, Summary};
use crate::papers::values::{self, Application};
use crate::papers::{self, Values};
use crate::session::User;
use crate::{countries, dates, files};
/// The most the documents of one pack may weigh together.
const PACK_LIMIT: i64 = 200 * 1024 * 1024;
/// One application, assessed: what the tab and the PDF show.
struct Assessed {
facts: values::Facts,
app: Application,
errors: Errors,
values: Values,
on: NaiveDate,
pack: pack::Facts,
items: Vec<Item>,
}
impl Assessed {
/// The documents of the person and of the employer, by id.
fn docs(&self) -> HashMap<i64, &Document> {
self.pack
.person_docs
.iter()
.chain(&self.pack.company_docs)
.map(|d| (d.id, d))
.collect()
}
}
async fn assess(st: &AppState, id: i64, app: Application) -> anyhow::Result<Option<Assessed>> {
let Some(facts) = values::load(&st.db, id).await? else {
return Ok(None);
};
let today = dates::today();
let app = app.with_defaults(&facts, today);
let errors = app.check();
let v = values::values(&facts, &app, today);
let on = dates::parse_form_date(&app.date).unwrap_or(today);
let blanks = papers::EXTENSION
.iter()
.map(|&p| (p, values::missing(p, &v, &facts)))
.collect();
let pack = pack::load(&st.db, &facts, blanks).await?;
let items = pack::assess(&pack, on);
Ok(Some(Assessed {
facts,
app,
errors,
values: v,
on,
pack,
items,
}))
}
#[derive(Debug, Serialize)]
struct FileLink {
label: String,
href: String,
}
#[derive(Debug, Serialize)]
struct ItemView<'a> {
#[serde(flatten)]
item: &'a Item,
/// A form's PDF.
open: String,
/// The documents that go in, each opening its file.
files: Vec<FileLink>,
}
#[derive(Debug, Serialize)]
struct Part<'a> {
n: usize,
title: &'static str,
items: Vec<ItemView<'a>>,
}
/// An item as the tab shows it: with the links to its form or its files.
fn item_view<'a>(item: &'a Item, docs: &HashMap<i64, &Document>, id: i64, q: &str) -> ItemView<'a> {
ItemView {
item,
open: item
.paper
.map(|p| format!("/people/{id}/forms/{}.pdf?{q}", p.slug()))
.unwrap_or_default(),
files: item
.docs
.iter()
.filter_map(|d| docs.get(d))
.map(|d| FileLink {
label: d
.dated_on
.map(dates::fmt_date)
.unwrap_or_else(|| "View".to_string()),
href: format!("{}/{}/file", d.owner().base(), d.id),
})
.collect(),
}
}
pub async fn tab(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Query(app): Query<Application>,
) -> Res {
let (Some((_, p)), Some(a)) = (load_person(&st, id).await?, assess(&st, id, app).await?) else {
return Ok(not_found_page(&st));
};
let q = a.app.query();
let docs = a.docs();
let parts: Vec<Part> = PARTS
.iter()
.enumerate()
.map(|(i, title)| Part {
n: i + 1,
title,
items: a
.items
.iter()
.filter(|it| it.part == i + 1)
.map(|it| item_view(it, &docs, id, &q))
.collect(),
})
.collect();
let summary = Summary::of(&a.items);
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let status = if a.errors.is_empty() {
StatusCode::OK
} else {
StatusCode::UNPROCESSABLE_ENTITY
};
let title = format!("Pack: {}", p.name);
let complete = summary.complete();
Ok(page(
&st,
&user,
"pack.html",
&title,
"people",
status,
context! {
p,
tab => "pack",
app => &a.app,
appq => &q,
errors => &a.errors,
parts,
summary,
complete,
on => dates::fmt_date(a.on),
pdf_href => format!("/people/{id}/pack.pdf?{q}"),
},
))
}
/// The pack as one PDF, opened in the browser or (`?download=1`) saved.
pub async fn pdf(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Query(q): Query<PdfQuery>,
) -> Res {
let Some(a) = assess(&st, id, q.app).await? else {
return Ok(not_found_page(&st));
};
if !a.errors.is_empty() {
// the tab shows what is wrong with the fields
return Ok(Redirect::to(&format!("/people/{id}/pack?{}", a.app.query())).into_response());
}
let docs = a.docs();
let wanted: Vec<&Document> = a
.items
.iter()
.flat_map(|i| &i.docs)
.filter_map(|d| docs.get(d).copied())
.collect();
let total: i64 = wanted.iter().map(|d| i64::from(d.size_bytes)).sum();
if total > PACK_LIMIT {
return Ok(message(
&st,
StatusCode::PAYLOAD_TOO_LARGE,
"The pack is too large for one file",
&format!(
"Its documents weigh {} MB together, more than the {} MB one PDF takes. Open the \
large scans one by one from the Documents tab.",
total / (1024 * 1024),
PACK_LIMIT / (1024 * 1024)
),
(&format!("/people/{id}/pack"), "Back to the pack"),
));
}
let mut loaded = HashMap::new();
let mut read: Vec<&Document> = Vec::new();
for d in &wanted {
let bytes = match &st.files {
None => Err("documents are switched off on this server".to_string()),
Some(store) => match store.get(d.id).await {
Ok(b) if files::sha256_hex(&b) == d.sha256 => {
read.push(d);
Ok(b)
}
Ok(_) => {
error!(
"document {}: the file does not match the checksum of its upload",
d.id
);
Err("it does not match its upload".to_string())
}
Err(e) => {
error!("document {}: {e:#}", d.id);
Err("it is missing or damaged on the server".to_string())
}
},
};
loaded.insert(
d.id,
Loaded {
name: d.file_name.clone(),
content_type: d.content_type.clone(),
bytes,
},
);
}
let person = &a.facts.person;
let whose = person.display_name();
let mut lines = Vec::new();
if let Some(pp) = &a.facts.passport {
let country = countries::name(&pp.issuing_country).unwrap_or(&pp.issuing_country);
lines.push(format!("Passport {}, {country}", pp.number));
}
if let Some(c) = &a.pack.company {
lines.push(format!("Employer: {}", c.name));
}
lines.push(format!(
"For {} on {}, asking for {} days",
a.app.at,
dates::fmt_date(a.on),
a.app.days
));
let cover = Cover {
title: format!("Extension pack: {whose}"),
person: whose.clone(),
lines,
made: format!(
"Put together by visa.buildfor.life for {} on {}.",
user.login,
dates::fmt_datetime(Utc::now())
),
};
let items = a.items.clone();
let v = a.values.clone();
let bytes = tokio::task::spawn_blocking(move || pack::pdf::render(&cover, &items, &v, loaded))
.await??;
// the forms and every document that went in, never their contents
let download = q.download.is_some();
let action = if download {
Action::Download
} else {
Action::View
};
let codes: Vec<String> = a
.items
.iter()
.filter_map(|i| i.paper)
.map(|p| p.code().to_string())
.collect();
let file = ["file".to_string()];
let mut tx = st.db.begin().await?;
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action,
entity: Entity::Form,
entity_id: None,
person_id: Some(id),
company_id: None,
fields: &codes,
},
)
.await?;
for d in read {
audit::record(
&mut *tx,
&Entry {
actor: &user.login,
action,
entity: Entity::Document,
entity_id: Some(d.id),
person_id: Some(id),
company_id: d.company_id,
fields: &file,
},
)
.await?;
}
tx.commit().await?;
let name = format!(
"{} - Extension pack - {}.pdf",
whose.replace(',', ""),
a.app.date
);
let how = if download { "attachment" } else { "inline" };
let mut resp = Response::new(Body::from(bytes));
let h = resp.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/pdf"),
);
h.insert(header::CONTENT_DISPOSITION, disposition(how, &name));
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"),
);
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(FILE_CSP),
);
h.insert(
"cross-origin-resource-policy",
HeaderValue::from_static("same-origin"),
);
Ok(resp)
}
+3 -2
View File
@@ -87,6 +87,7 @@ pub async fn tab(
forms, forms,
extension_href => format!("/people/{id}/forms/extension.pdf?{q}"), extension_href => format!("/people/{id}/forms/extension.pdf?{q}"),
extension_codes, extension_codes,
appq => &q,
}, },
)) ))
} }
@@ -94,8 +95,8 @@ pub async fn tab(
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
pub struct PdfQuery { pub struct PdfQuery {
#[serde(flatten)] #[serde(flatten)]
app: Application, pub app: Application,
download: Option<String>, pub download: Option<String>,
} }
/// One form (`tm7.pdf`) or the forms of an extension (`extension.pdf`), /// One form (`tm7.pdf`) or the forms of an extension (`extension.pdf`),
+73 -2
View File
@@ -717,15 +717,30 @@ textarea.mrz {
color: var(--hd); color: var(--hd);
border-bottom-color: var(--accent); 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) { @media (max-width: 560px) {
.tabs { .tabs {
gap: 0; gap: 0;
} }
.tabs a { .tabs a {
padding: 8px 7px; padding: 8px 6px;
font-size: 13.5px; 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 */ /* ---- 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 */ /* the list runs to the card's edges */
.tblwrap.bleed { .tblwrap.bleed {
margin: 0 -20px -18px; margin: 0 -20px -18px;
+1 -1
View File
@@ -14,7 +14,7 @@
<li> <li>
<div class="dl-what"><b>{{ d.title }}</b>{% if d.due_text %}<span class="dl-when">{{ d.due_text }}, {{ d.when }}{% if d.estimate %} (estimate){% endif %}</span>{% endif %}</div> <div class="dl-what"><b>{{ d.title }}</b>{% if d.due_text %}<span class="dl-when">{{ d.due_text }}, {{ d.when }}{% if d.estimate %} (estimate){% endif %}</span>{% endif %}</div>
<span class="chip {{ d.level }}">{{ d.label }}</span> <span class="chip {{ d.level }}">{{ d.label }}</span>
<p class="dl-note">{{ d.note }}</p> <p class="dl-note">{{ d.note }}{% if d.key == "extension" and p.employer %} <a href="/people/{{ p.id }}/pack">Prepare the pack</a>{% endif %}</p>
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
+4 -3
View File
@@ -19,10 +19,11 @@
{%- if p.employer %}<span class="sep">·</span><a href="/companies/{{ p.employer_id }}">{{ p.employer }}</a>{% endif %} {%- if p.employer %}<span class="sep">·</span><a href="/companies/{{ p.employer_id }}">{{ p.employer }}</a>{% endif %}
</p> </p>
<nav class="tabs" aria-label="About {{ p.name }}"> <nav class="tabs" aria-label="About {{ p.name }}">
<a href="/people/{{ p.id }}"{% if tab not in ["stay", "documents", "forms", "activity"] %} class="on" aria-current="page"{% endif %}>Overview</a> <a href="/people/{{ p.id }}"{% if tab not in ["stay", "documents", "forms", "pack", "activity"] %} class="on" aria-current="page"{% endif %}>Overview</a>
<a href="/people/{{ p.id }}/stay"{% if tab == "stay" %} class="on" aria-current="page"{% endif %}>Visa and stay</a> <a href="/people/{{ p.id }}/stay"{% if tab == "stay" %} class="on" aria-current="page"{% endif %}><span class="tab-long">Visa and stay</span><span class="tab-short">Stay</span></a>
<a href="/people/{{ p.id }}/documents"{% if tab == "documents" %} class="on" aria-current="page"{% endif %}>Documents</a> <a href="/people/{{ p.id }}/documents"{% if tab == "documents" %} class="on" aria-current="page"{% endif %}>Documents</a>
<a href="/people/{{ p.id }}/forms"{% if tab == "forms" %} class="on" aria-current="page"{% endif %}>Forms</a> <a href="/people/{{ p.id }}/forms{% if appq %}?{{ appq }}{% endif %}"{% if tab == "forms" %} class="on" aria-current="page"{% endif %}>Forms</a>
<a href="/people/{{ p.id }}/pack{% if appq %}?{{ appq }}{% endif %}"{% if tab == "pack" %} class="on" aria-current="page"{% endif %}>Pack</a>
<a href="/people/{{ p.id }}/activity"{% if tab == "activity" %} class="on" aria-current="page"{% endif %}>Activity</a> <a href="/people/{{ p.id }}/activity"{% if tab == "activity" %} class="on" aria-current="page"{% endif %}>Activity</a>
</nav> </nav>
</div> </div>
+17
View File
@@ -118,6 +118,23 @@
</div> </div>
</div> </div>
</section> </section>
<section class="card span2" id="pack">
<header><h2>For the extension packs</h2><span class="muted small">as each employee's pack sees them today</span></header>
<ul class="checklist">
{%- for i in pack %}
<li class="ci" id="item-{{ i.key }}">
<span class="chip {{ i.level }}">{{ i.label }}</span>
<div class="ci-body">
<div class="ci-what">{{ i.what }}</div>
<p class="ci-note">{{ i.note }}</p>
{%- if i.fix %}
<div class="rowactions"><a href="{{ i.fix.href }}">{{ i.fix.text }}</a></div>
{%- endif %}
</div>
</li>
{%- endfor %}
</ul>
</section>
<section class="card span2" id="documents"> <section class="card span2" id="documents">
<header><h2>Company documents</h2><span class="muted small">for the extension packs of the people employed here</span></header> <header><h2>Company documents</h2><span class="muted small">for the extension packs of the people employed here</span></header>
{{ dm.upload(upload, csrf, person=false) }} {{ dm.upload(upload, csrf, person=false) }}
+1 -1
View File
@@ -35,7 +35,7 @@
<td class="nowrap"><a class="strong" href="/people/{{ r.person_id }}">{{ r.person }}</a>{% if r.employer %}<div class="sub">{{ r.employer }}</div>{% endif %}</td> <td class="nowrap"><a class="strong" href="/people/{{ r.person_id }}">{{ r.person }}</a>{% if r.employer %}<div class="sub">{{ r.employer }}</div>{% endif %}</td>
<td class="nowrap">{{ r.d.title }}</td> <td class="nowrap">{{ r.d.title }}</td>
<td><span class="chip {{ r.d.level }}">{{ r.d.label }}</span></td> <td><span class="chip {{ r.d.level }}">{{ r.d.label }}</span></td>
<td class="hs small note">{{ r.d.note }}</td> <td class="hs small note">{{ r.d.note }}{% if r.d.key == "extension" and r.employer %} <a href="/people/{{ r.person_id }}/pack">Prepare the pack</a>{% endif %}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
+68
View File
@@ -0,0 +1,68 @@
{% extends "base.html" %}
{% import "_fields.html" as fm %}
{% block main %}
{% include "_person_head.html" %}
<div class="cols papers">
<section class="card" id="pack">
<header><h2>Extension pack, work (Non-B)</h2><div class="paper-go"><a class="btn sm pri" href="{{ pdf_href }}" target="_blank" rel="noopener">Print the pack</a><a class="btn sm ghost" href="{{ pdf_href }}&amp;download=1">Download</a></div></header>
<div class="summary">
<span class="chip ok">{{ summary.ready }} ready</span>
{%- if summary.check %}<span class="chip warn">{{ summary.check }} to check</span>{% endif %}
{%- if summary.lacking %}<span class="chip bad">{{ summary.lacking }} missing or out of date</span>{% endif %}
{%- if summary.not_needed %}<span class="chip">{{ summary.not_needed }} not needed</span>{% endif %}
</div>
<p class="hint lead">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 %}</p>
{%- for part in parts %}
<h3 class="fsec">{{ part.n }}. {{ part.title }}</h3>
<ul class="checklist">
{%- for i in part.items %}
<li class="ci" id="item-{{ i.key }}">
<span class="chip {{ i.level }}">{{ i.label }}</span>
<div class="ci-body">
<div class="ci-what">{% if i.code %}<span class="paper-code">{{ i.code }}</span> {% endif %}{{ i.what }}</div>
{%- if i.note %}
<p class="ci-note">{{ i.note }}</p>
{%- endif %}
{%- if i.blanks %}
<p class="ci-blanks"><span class="muted">Still blank:</span>{% for m in i.blanks %}<a href="{{ m.href }}">{{ m.what }}</a>{% endfor %}</p>
{%- endif %}
{%- if i.open or i.files or i.fix %}
<div class="rowactions">
{%- if i.open %}<a href="{{ i.open }}" target="_blank" rel="noopener">Open the form</a>{% endif %}
{%- for f in i.files %}<a class="doclink" href="{{ f.href }}" target="_blank" rel="noopener">{{ f.label }}</a>{% endfor %}
{%- if i.fix %}<a href="{{ i.fix.href }}">{{ i.fix.text }}</a>{% endif %}
</div>
{%- endif %}
</div>
</li>
{%- endfor %}
</ul>
{%- endfor %}
</section>
<section class="card" id="application">
<header><h2>This application</h2></header>
<form method="get" action="/people/{{ p.id }}/pack" class="form appform">
{%- if errors %}
<div class="notice warn">Correct what is marked; the pack opens once these values are right.</div>
{%- endif %}
<p class="hint lead">The same values fill the forms on the Forms tab. They are not stored: the links carry them.</p>
<div class="grid">
{{ 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.") }}
</div>
{#- the trip stays as it was, for TM.8 on the Forms tab #}
<input type="hidden" name="entries" value="{{ app.entries }}">
<input type="hidden" name="to" value="{{ app.to }}">
<input type="hidden" name="leave" value="{{ app.leave }}">
<input type="hidden" name="return" value="{{ app["return"] }}">
<input type="hidden" name="by" value="{{ app.by }}">
<input type="hidden" name="for" value="{{ app["for"] }}">
<div class="formactions"><button type="submit" class="btn pri">Use these</button></div>
</form>
</section>
</div>
{% endblock %}
+3 -3
View File
@@ -5,7 +5,7 @@
<div class="cols papers"> <div class="cols papers">
<section class="card" id="forms"> <section class="card" id="forms">
<header><h2>Forms</h2><a class="btn sm pri" href="{{ extension_href }}" target="_blank" rel="noopener">The extension's five forms</a></header> <header><h2>Forms</h2><a class="btn sm pri" href="{{ extension_href }}" target="_blank" rel="noopener">The extension's five forms</a></header>
<p class="hint lead">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.</p> <p class="hint lead">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 <a href="/people/{{ p.id }}/pack?{{ appq }}">Pack</a> tab puts them in one PDF with the copies and the employer's documents.</p>
{%- for f in forms %} {%- for f in forms %}
<div class="paper" id="form-{{ f.slug }}"> <div class="paper" id="form-{{ f.slug }}">
<div class="paper-head"> <div class="paper-head">
@@ -41,9 +41,9 @@
{{ fm.select("entries", "Re-entry permit", app.entries, [("single", "Single entry"), ("multiple", "Multiple entries")], err=errors.entries, blank="Choose") }} {{ 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("to", "Travelling to", app.to, err=errors.to, ph="Germany") }}
{{ fm.text("leave", "Leaving on", app.leave, err=errors.leave, type="date") }} {{ 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("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"]) }}
</div> </div>
<div class="formactions"><button type="submit" class="btn pri">Use these</button></div> <div class="formactions"><button type="submit" class="btn pri">Use these</button></div>
</form> </form>
+1
View File
@@ -9,6 +9,7 @@ mod companies;
mod deadlines; mod deadlines;
mod documents; mod documents;
mod garage; mod garage;
mod pack;
mod pages; mod pages;
mod papers; mod papers;
mod people; mod people;
+183
View File
@@ -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("<li class=\"ci\"")
.map_or(rest.len(), |e| e + 1);
&rest[..end]
}
fn pages(pdf: &[u8]) -> 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</a>"), "{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("<option value=\"pnd91\" selected>"));
let r = app.get(&format!("/companies/{company}?kind=pp30")).await;
let t = r.text();
assert!(t.contains("<option value=\"pp30\" selected>"), "{t}");
// the company's page shows its part of every pack
assert!(t.contains("For the extension packs"));
assert!(item(&t, "shareholders").contains("Out of date"));
// the deadline of the extension leads to the pack
let t = app.get(&format!("/people/{id}")).await.text();
assert!(
t.contains(&format!("href=\"/people/{id}/pack\">Prepare the pack")),
"{t}"
);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_pdf_is_the_cover_the_forms_and_the_copies_and_it_is_audited(pool: PgPool) {
let (app, id, company) = seeded(&pool).await;
let r = app.get(&format!("/people/{id}/pack.pdf")).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(r.header("content-type"), "application/pdf");
assert_eq!(r.header("cache-control"), "private, no-store");
assert!(
r.header("content-disposition")
.contains("MUSTERMANN Erika - Extension pack - "),
"{}",
r.header("content-disposition")
);
let sizes = pages(&r.bytes);
// the cover, six pages of forms, nine copies of Erika's and eight of the
// employer's (the old BOJ.5 stays out)
assert_eq!(sizes.len(), 1 + 6 + 9 + 8, "{sizes:?}");
// the passport's photo page, a picture wider than high, lies on its side
assert!(
sizes
.iter()
.any(|(w, h)| (w - 842.0).abs() < 1.0 && (h - 595.0).abs() < 1.0)
);
let rows: Vec<(String, String, Option<i64>, Option<i64>)> = sqlx::query_as(
"SELECT action, entity, person_id, company_id FROM audit_log \
WHERE entity IN ('form', 'document') AND actor <> 'seed' ORDER BY id",
)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(rows.len(), 1 + 17, "{rows:?}");
assert!(rows.iter().all(|r| r.0 == "view" && r.2 == Some(id)));
let of_company = rows.iter().filter(|r| r.3 == Some(company)).count();
assert_eq!(of_company, 8);
let codes: Vec<String> =
sqlx::query_scalar("SELECT unnest(fields) FROM audit_log WHERE entity = 'form'")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(codes, ["TM.7", "STM.2", "STM.9", "STM.11", "STM.1"]);
// a file that cannot be read gets a page of its own, and no audit row
let tdac: i64 =
sqlx::query_scalar("SELECT id FROM documents WHERE person_id = $1 AND kind = 'tdac'")
.bind(id)
.fetch_one(&pool)
.await
.unwrap();
app.st.files.as_ref().unwrap().remove(tdac).await.unwrap();
let r = app.get(&format!("/people/{id}/pack.pdf?download=1")).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert!(r.header("content-disposition").starts_with("attachment;"));
assert_eq!(pages(&r.bytes).len(), 24);
let downloads: i64 = sqlx::query_scalar(
"SELECT count(*) FROM audit_log WHERE action = 'download' AND entity = 'document'",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(downloads, 16);
}
+4
View File
@@ -139,6 +139,10 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
format!("/people/{erika}/forms"), format!("/people/{erika}/forms"),
"This application".to_string(), "This application".to_string(),
), ),
(
format!("/people/{erika}/pack"),
"Extension pack, work (Non-B)".to_string(),
),
]; ];
for kind in visa::records::STAY { for kind in visa::records::STAY {
pages.push(( pages.push((
+5
View File
@@ -137,6 +137,11 @@ async fn the_forms_tab_lists_the_forms_and_what_they_lack(pool: PgPool) {
.await; .await;
assert_eq!(r.status, StatusCode::OK); assert_eq!(r.status, StatusCode::OK);
let t = r.text(); let t = r.text();
// the fields keep what was entered (they serialize as "return" and "for")
assert!(
t.contains("name=\"return\" type=\"date\" value=\"2027-01-20\""),
"{t}"
);
let tm8 = &t[t.find("id=\"form-tm8\"").unwrap()..]; let tm8 = &t[t.find("id=\"form-tm8\"").unwrap()..];
assert!(tm8.contains("Complete"), "{tm8}"); assert!(tm8.contains("Complete"), "{tm8}");
assert!(tm8.contains("to=Germany"), "{tm8}"); assert!(tm8.contains("to=Germany"), "{tm8}");