diff --git a/.gitattributes b/.gitattributes
index 775d1d4..01f645b 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -7,6 +7,7 @@ migrations/*.sql text eol=lf
.gitea/scripts/* text eol=lf
*.png binary
*.pdf binary
+*.ttf binary
# Nix reads flake.lock as JSON either way; keep both LF like the fleet.
*.nix text eol=lf
flake.lock text eol=lf
diff --git a/.gitignore b/.gitignore
index ab63ffc..9f12630 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,5 @@
/result
# local development: the documents and their key
/.dev/
+# Python's caches, from scripts/
+__pycache__/
diff --git a/Cargo.lock b/Cargo.lock
index ecfb46f..852998e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -23,6 +29,18 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
[[package]]
name = "atoi"
version = "2.0.0"
@@ -139,6 +157,26 @@ version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+]
+
[[package]]
name = "byteorder"
version = "1.5.0"
@@ -224,6 +262,15 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
+[[package]]
+name = "core_maths"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
+dependencies = [
+ "libm",
+]
+
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -257,6 +304,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
+[[package]]
+name = "crc32fast"
+version = "1.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "crossbeam-queue"
version = "0.3.14"
@@ -372,6 +428,15 @@ dependencies = [
"windows-sys 0.48.0",
]
+[[package]]
+name = "euclid"
+version = "0.22.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "event-listener"
version = "5.4.2"
@@ -382,12 +447,44 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "fearless_simd"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
+
+[[package]]
+name = "fearless_simd"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "629c9d6b6f30b5604089e0980f4d924a013aacb1654a6cdf5d3d852224f68651"
+
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
+[[package]]
+name = "flate2"
+version = "1.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "float-cmp"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "flume"
version = "0.11.1"
@@ -405,6 +502,15 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+[[package]]
+name = "font-types"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -548,6 +654,57 @@ dependencies = [
"hashbrown 0.15.5",
]
+[[package]]
+name = "hayro-ccitt"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2866f0d976e76497480b853d5e258dab6e4b89ecfe991124e08f15dfa8fd03ad"
+
+[[package]]
+name = "hayro-jbig2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "000e025850f4592ddcaee85640db70704151f2bafd43b6f431aa5b6a2c6a35a9"
+dependencies = [
+ "fearless_simd 1.2.0",
+ "hayro-ccitt",
+]
+
+[[package]]
+name = "hayro-jpeg2000"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"
+dependencies = [
+ "fearless_simd 0.4.1",
+]
+
+[[package]]
+name = "hayro-syntax"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27"
+dependencies = [
+ "flate2",
+ "hayro-jbig2",
+ "hayro-jpeg2000",
+ "memchr",
+ "rustc-hash",
+ "smallvec",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "hayro-write"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0b3db92c4917aad24ff30d61413a9a7509ae88b27aee1ae34eff881e1d2723a"
+dependencies = [
+ "flate2",
+ "hayro-syntax",
+ "pdf-writer",
+]
+
[[package]]
name = "heck"
version = "0.5.0"
@@ -853,6 +1010,42 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "krilla"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
+dependencies = [
+ "base64 0.22.1",
+ "bumpalo",
+ "flate2",
+ "float-cmp",
+ "hayro-write",
+ "indexmap",
+ "pdf-writer",
+ "rustc-hash",
+ "rustybuzz",
+ "siphasher",
+ "skrifa",
+ "smallvec",
+ "subsetter",
+ "tiny-skia-path",
+ "xmp-writer",
+ "yoke",
+]
+
+[[package]]
+name = "kurbo"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "polycool",
+ "smallvec",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.1"
@@ -967,6 +1160,16 @@ dependencies = [
"serde",
]
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
[[package]]
name = "mio"
version = "1.2.5"
@@ -1087,6 +1290,18 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "pdf-writer"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
+dependencies = [
+ "bitflags",
+ "itoa",
+ "memchr",
+ "ryu",
+]
+
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
@@ -1141,6 +1356,15 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+[[package]]
+name = "polycool"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "potential_utf"
version = "0.1.6"
@@ -1295,6 +1519,16 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "read-fonts"
+version = "0.39.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
+dependencies = [
+ "bytemuck",
+ "font-types",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -1444,6 +1678,24 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "rustybuzz"
+version = "0.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
+dependencies = [
+ "bitflags",
+ "bytemuck",
+ "core_maths",
+ "log",
+ "smallvec",
+ "ttf-parser",
+ "unicode-bidi-mirroring",
+ "unicode-ccc",
+ "unicode-properties",
+ "unicode-script",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -1611,12 +1863,34 @@ dependencies = [
"rand_core 0.6.4",
]
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
+[[package]]
+name = "siphasher"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
+
+[[package]]
+name = "skrifa"
+version = "0.42.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
+dependencies = [
+ "bytemuck",
+ "read-fonts",
+]
+
[[package]]
name = "slab"
version = "0.4.12"
@@ -1859,6 +2133,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+[[package]]
+name = "strict-num"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+
[[package]]
name = "stringprep"
version = "0.1.5"
@@ -1870,6 +2150,18 @@ dependencies = [
"unicode-properties",
]
+[[package]]
+name = "subsetter"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
+dependencies = [
+ "kurbo",
+ "rustc-hash",
+ "skrifa",
+ "write-fonts",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -1947,6 +2239,17 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "tiny-skia-path"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"
+dependencies = [
+ "arrayref",
+ "bytemuck",
+ "strict-num",
+]
+
[[package]]
name = "tinystr"
version = "0.8.5"
@@ -2106,6 +2409,15 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "ttf-parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+dependencies = [
+ "core_maths",
+]
+
[[package]]
name = "typenum"
version = "1.20.1"
@@ -2118,6 +2430,18 @@ version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+[[package]]
+name = "unicode-bidi-mirroring"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"
+
+[[package]]
+name = "unicode-ccc"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e"
+
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -2139,6 +2463,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833"
+[[package]]
+name = "unicode-script"
+version = "0.5.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf"
+
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -2194,11 +2524,14 @@ dependencies = [
"chrono",
"form_urlencoded",
"http-body-util",
+ "krilla",
"minijinja",
"reqwest",
"ring",
+ "rustybuzz",
"serde",
"serde_json",
+ "serde_urlencoded",
"sqlx",
"tokio",
"tower",
@@ -2519,12 +2852,31 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "write-fonts"
+version = "0.48.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
+dependencies = [
+ "font-types",
+ "indexmap",
+ "kurbo",
+ "log",
+ "read-fonts",
+]
+
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+[[package]]
+name = "xmp-writer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
+
[[package]]
name = "yoke"
version = "0.8.4"
@@ -2628,8 +2980,29 @@ dependencies = [
"syn 3.0.10",
]
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
diff --git a/Cargo.toml b/Cargo.toml
index d5f5aec..2bde280 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,6 +27,7 @@ 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"] }
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.
@@ -34,8 +35,10 @@ reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-
# ID token signatures (ES256 from Kanidm, RS256 accepted), PKCE, random tokens
# and the session hashes, as in proplan and the fleet overview.
ring = "0.17"
+rustybuzz = "0.20"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+serde_urlencoded = "0.7"
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "postgres", "chrono", "migrate", "macros"] }
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] }
tracing = "0.1"
diff --git a/README.md b/README.md
index 8f62f8a..3771fb0 100644
--- a/README.md
+++ b/README.md
@@ -4,9 +4,9 @@ visa.buildfor.life keeps the immigration records of the foreigners that B4L
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 from phase 5 it prepares the
-documents for the next extension of stay at Chiang Mai Immigration with the
-forms filled in.
+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.
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 4)
+## What works now (phases 1 to 5)
- 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,19 +26,26 @@ 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 four tabs: the overview with personal details,
+ page per person with five 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; and the person's activity.
+ person's documents; the forms; 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
extension packs. The files are encrypted on the server, open in the
browser's viewer, and every upload, view and download is in the log.
+- Forms, filled in from the records on the Immigration Bureau's own pages:
+ TM.7, STM.2, STM.9, STM.11 and STM.1 for an extension of stay, TM.47 for a
+ 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.
- 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
- people to it. The page's Office card shows the office's GPS position,
+ people to it. It also holds what the employer's certificate (STM.1)
+ states: the capital, the latest revenue and equity, and the staff. The
+ page's Office card shows the office's GPS position,
with links to OpenStreetMap and Google Maps, and the newest photo of the
office; the position may be pasted as Google Maps copies it or as a link
to the place.
diff --git a/docs/PLAN.md b/docs/PLAN.md
index 661e644..f907371 100644
--- a/docs/PLAN.md
+++ b/docs/PLAN.md
@@ -1,9 +1,10 @@
# visa.buildfor.life: plan
-> Phases 1 to 3 built on November 17, 2026, and phase 4's app side on
-> November 18, 2026; the app is live at https://visa.buildfor.life. **Resume
-> here: phase 5, the filled-in forms.** Task 4.6, the fleet side of the
-> documents, waits in cnx-network-clan PR #126.
+> Phases 1 to 3 built on November 17, 2026, phase 4's app side and phase 5
+> on November 18, 2026. The live app at https://visa.buildfor.life has phases
+> 1 to 3 until cnx-network-clan PR #126 (task 4.6) is deployed and the fleet's
+> `visa` input is updated to the newest commit. **Resume here: phase 6, the
+> Non-B extension pack.**
visa.buildfor.life keeps the immigration records of the foreigners that B4L
looks after: their passports, addresses in Thailand, arrivals with the Thailand
@@ -170,7 +171,7 @@ dark at desktop and phone width, a commit and a push.
| 2 | Companies; stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | built 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) on the dataset `zroot/visa` with a key var, viewing and download, all audited; the office's GPS position and photo | app built Nov 18, 2026; fleet in PR #126 |
-| 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment, TM.47, TM.8 and STM.1 as PDF | |
+| 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 | |
@@ -275,6 +276,43 @@ one `Kind`.
The photos are documents of the kind "Photo of the office", so they
are encrypted and audited like every other file.
+### Phase 5: filled-in forms
+
+- [x] 5.1 The blank forms as the Immigration Bureau publishes them, in
+ `forms/` with their sources and checksums in `forms/README.md`: TM.7,
+ STM.2, STM.9 (the acknowledgment of the penalties for overstay),
+ STM.11, STM.1, TM.47 and TM.8. Each page goes unchanged into a new PDF
+ and the values are written on its dotted lines in Sarabun, the font of
+ the forms; a box is ticked and the person's title circled where the
+ form asks for that. Signatures, the photo and the officers' parts stay
+ blank.
+- [x] 5.2 Where each value goes: `scripts/gen_layout.py` finds the dotted
+ lines in the blank PDFs and writes `src/papers/layout.rs`. TM.47 has no
+ dotted lines, so its blanks are measured from the lines drawn on it. A
+ new version of a form needs the script run again and every page checked.
+- [x] 5.3 The values (`src/papers/values.rs`) come from the person, the
+ passport that runs longest, the current address, the last arrival with
+ its visa and permission to stay, the work permit and the employer, and
+ the date of the company certificate from the company's documents. They
+ are written in capitals with the Western year, as the passport has
+ them. What only the application says (the date, the office, the reason,
+ the days asked for, which yearly extension it is, a trip for TM.8) is
+ on the tab, with defaults from the records, and travels in the links as
+ query parameters, so none of it is stored.
+- [x] 5.4 A Forms tab on each person: every form with what it is for, Open
+ and Download, and what would stay blank, each with a link to where it
+ is added. "The extension's five forms" gives TM.7, STM.2, STM.9, STM.11
+ and STM.1 in one PDF, in the order the officer reads them.
+- [x] 5.5 New fields for the forms (`migrations/0005_forms.sql`): a
+ company's registered and paid-up capital, the year of its latest
+ financial statements with the revenue and the owners' equity, the
+ foreign staff's pay for the next year, its Thai and foreign staff, and
+ a coordinator for immigration; a work permit's monthly salary and
+ contract dates; where an arrival came from. A Thai year such as 2568 is
+ taken as 2025.
+- [x] 5.6 Audit: opening or downloading a form is logged as `form` with the
+ codes of the forms, never their values.
+
## Open questions
1. B4L's BOI application: once B4L is promoted, its staff extend their stay
diff --git a/flake.nix b/flake.nix
index b2f9ef2..e324a3a 100644
--- a/flake.nix
+++ b/flake.nix
@@ -19,8 +19,8 @@
];
forAll = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
- # The server: one binary with its templates, static files and
- # migrations compiled in (build.rs, sqlx::migrate!). The tests need
+ # The server: one binary with its templates, static files, migrations
+ # and blank forms compiled in (build.rs, sqlx::migrate!, include_bytes!). The tests need
# PostgreSQL, so the package build runs none; CI and the fleet's VM
# test (checks.visa in cnx-network-clan) cover them.
package =
@@ -38,6 +38,8 @@
./templates
./static
./migrations
+ # the blank forms and their font, compiled in (src/papers)
+ ./forms
# Cargo.toml names tests/main.rs as a target
./tests
];
diff --git a/forms/README.md b/forms/README.md
new file mode 100644
index 0000000..ea8074d
--- /dev/null
+++ b/forms/README.md
@@ -0,0 +1,47 @@
+# The blank forms
+
+The Immigration Bureau's forms that the app fills in (`src/papers`), kept
+unchanged as the Bureau publishes them. The app lays each page into a new PDF
+and writes the values on its dotted lines, so a filled-in form looks like one
+filled in by hand, only legible.
+
+They come from the downloads of Immigration Division 1 at
+https://bangkok.immigration.go.th/en/downloads_en/, fetched on November 18,
+2026. The STM forms are the versions of 2025. The forms are the Bureau's own,
+for every immigration office; Chiang Mai Immigration's website offers no
+downloads of its own.
+
+| Form | File | What it is | SHA-256 |
+| ---- | ---- | ---------- | ------- |
+| [TM.7](https://bangkok.immigration.go.th/wp-content/uploads/2021/06/14%E0%B8%84%E0%B8%B3%E0%B8%82%E0%B8%AD%E0%B8%AD%E0%B8%99%E0%B8%B8%E0%B8%8D%E0%B8%B2%E0%B8%95%E0%B9%80%E0%B8%9E%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%AD%E0%B8%A2%E0%B8%B9%E0%B9%88%E0%B9%83%E0%B8%99%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B8%AD%E0%B8%B2%E0%B8%93%E0%B8%B2%E0%B8%88%E0%B8%B1%E0%B8%81%E0%B8%A3%E0%B9%80%E0%B8%9B%E0%B9%87%E0%B8%99%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%8A%E0%B8%B1%E0%B9%88%E0%B8%A7%E0%B8%84%E0%B8%A3%E0%B8%B2%E0%B8%A7%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B9%84%E0%B8%9B-%E0%B8%95%E0%B8%A1.7.pdf) | `tm7.pdf` | Application for extension of temporary stay | `93bcd4b4fda4a9e88329e313112a6bd6d17a8f604f16392734f72a647fc8b62d` |
+| [STM.2](https://bangkok.immigration.go.th/wp-content/uploads/STM-2-FORM-2025.pdf) | `stm2.pdf` | Acknowledgment of the conditions of a temporary stay | `0675fcd31ad6ee5ad50ca38f0ba115a82378e81faa7cab1aea22dbfb5335c35e` |
+| [STM.9](https://bangkok.immigration.go.th/wp-content/uploads/STM-9-FORM-2025.pdf) | `stm9.pdf` | Acknowledgment of the penalties for overstay | `c9939371a18e4b8cd74b2a8bc88377ac39f53d9a8049dc28b832917e300eccb6` |
+| [STM.11](https://bangkok.immigration.go.th/wp-content/uploads/STM-11-FORM-2025.pdf) | `stm11.pdf` | Consent to the checking of the application | `41b86da3094ec86837512f0d3b84871dd75ffed8c70fcd415a33d26704d74612` |
+| [STM.1](https://bangkok.immigration.go.th/wp-content/uploads/STM-1-FORM-2025.pdf) | `stm1.pdf` | Certificate of employment, from the employer | `591484049f81d8c3c86bc118413b85521fa8935e2d00a7b85c48747e3d790cf1` |
+| [TM.47](https://bangkok.immigration.go.th/wp-content/uploads/Form-TM-47.pdf) | `tm47.pdf` | Notification of staying longer than 90 days | `2208dc2aa65f82dc8e2129759d6eb2e8bf1185b271c4e02c3803a527dd5ccbac` |
+| [TM.8](https://bangkok.immigration.go.th/wp-content/uploads/2021/06/15%E0%B8%84%E0%B8%B3%E0%B8%82%E0%B8%AD%E0%B8%AD%E0%B8%99%E0%B8%B8%E0%B8%8D%E0%B8%B2%E0%B8%95%E0%B9%80%E0%B8%9E%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%A5%E0%B8%B1%E0%B8%9A%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B8%A1%E0%B8%B2%E0%B9%83%E0%B8%99%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B8%AD%E0%B8%B2%E0%B8%93%E0%B8%B2%E0%B8%88%E0%B8%B1%E0%B8%81%E0%B8%A3%E0%B8%AD%E0%B8%B5%E0%B8%81-%E0%B8%95%E0%B8%A1.8.pdf) | `tm8.pdf` | Application for a re-entry permit | `2bcd666622f0aa99e16e4bcbac8d3eec8c06566d620e3a3d7d9799aaab41920a` |
+
+## Where the values go
+
+`scripts/gen_layout.py` finds the dotted lines and the boxes in these PDFs and
+writes `src/papers/layout.rs`, which says where each value goes. TM.47 has no
+dotted lines, so its blanks are measured from the lines drawn on it.
+`scripts/form_blanks.py` lists a form's dotted lines with their labels, which
+helps when a form changes:
+
+```sh
+uv run --with pymupdf python scripts/form_blanks.py forms/tm7.pdf
+uv run --with pymupdf python scripts/gen_layout.py
+```
+
+`gen_layout.py` formats its output with rustfmt, so a rerun on the same forms
+gives the same file. When the Bureau publishes a new version of a form,
+replace the file, run `gen_layout.py` again, update the table above, and check every page of the
+filled-in form against the blank before the change goes live.
+
+## The font
+
+The values are written in Sarabun Regular (`fonts/Sarabun-Regular.ttf`), the
+font the forms themselves use, by Cadson Demak, under the SIL Open Font
+License 1.1 (`fonts/OFL.txt`), from
+https://github.com/google/fonts/tree/main/ofl/sarabun.
diff --git a/forms/fonts/OFL.txt b/forms/fonts/OFL.txt
new file mode 100644
index 0000000..a7d3a12
--- /dev/null
+++ b/forms/fonts/OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2018 The Sarabun Project Authors (https://github.com/cadsondemak/Sarabun)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/forms/fonts/Sarabun-Regular.ttf b/forms/fonts/Sarabun-Regular.ttf
new file mode 100644
index 0000000..161c9ac
Binary files /dev/null and b/forms/fonts/Sarabun-Regular.ttf differ
diff --git a/forms/stm1.pdf b/forms/stm1.pdf
new file mode 100644
index 0000000..3d0c5c4
Binary files /dev/null and b/forms/stm1.pdf differ
diff --git a/forms/stm11.pdf b/forms/stm11.pdf
new file mode 100644
index 0000000..ee087cd
Binary files /dev/null and b/forms/stm11.pdf differ
diff --git a/forms/stm2.pdf b/forms/stm2.pdf
new file mode 100644
index 0000000..10291bc
Binary files /dev/null and b/forms/stm2.pdf differ
diff --git a/forms/stm9.pdf b/forms/stm9.pdf
new file mode 100644
index 0000000..c7790ae
Binary files /dev/null and b/forms/stm9.pdf differ
diff --git a/forms/tm47.pdf b/forms/tm47.pdf
new file mode 100644
index 0000000..f92838e
Binary files /dev/null and b/forms/tm47.pdf differ
diff --git a/forms/tm7.pdf b/forms/tm7.pdf
new file mode 100644
index 0000000..bb71765
Binary files /dev/null and b/forms/tm7.pdf differ
diff --git a/forms/tm8.pdf b/forms/tm8.pdf
new file mode 100644
index 0000000..baf0713
Binary files /dev/null and b/forms/tm8.pdf differ
diff --git a/migrations/0005_forms.sql b/migrations/0005_forms.sql
new file mode 100644
index 0000000..0097fe6
--- /dev/null
+++ b/migrations/0005_forms.sql
@@ -0,0 +1,31 @@
+-- Phase 5, the filled-in forms: what STM.1 (the employer's certificate)
+-- asks of the company and of the employment, the coordinator STM.11 names,
+-- where an arrival came from (TM.7), and the audit entity "form" for a
+-- filled-in form opened or downloaded. Amounts are whole baht.
+
+ALTER TABLE companies
+ ADD COLUMN capital_thb BIGINT CHECK (capital_thb >= 0),
+ ADD COLUMN paid_up_thb BIGINT CHECK (paid_up_thb >= 0),
+ ADD COLUMN figures_year INTEGER CHECK (figures_year BETWEEN 1900 AND 2100),
+ ADD COLUMN revenue_thb BIGINT CHECK (revenue_thb >= 0),
+ ADD COLUMN equity_thb BIGINT,
+ ADD COLUMN foreign_costs_thb BIGINT CHECK (foreign_costs_thb >= 0),
+ ADD COLUMN thai_staff INTEGER CHECK (thai_staff >= 0),
+ ADD COLUMN foreign_staff INTEGER CHECK (foreign_staff >= 0),
+ ADD COLUMN coordinator TEXT NOT NULL DEFAULT '',
+ ADD COLUMN coordinator_phone TEXT NOT NULL DEFAULT '';
+
+ALTER TABLE work_permits
+ ADD COLUMN monthly_salary_thb INTEGER CHECK (monthly_salary_thb >= 0),
+ ADD COLUMN contract_from DATE,
+ ADD COLUMN contract_until DATE;
+
+ALTER TABLE arrivals ADD COLUMN came_from TEXT NOT NULL DEFAULT '';
+
+ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check;
+ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK (
+ entity IN (
+ 'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival',
+ 'extension', 'reentry-permit', 'report', 'work-permit', 'document', 'form'
+ )
+);
diff --git a/scripts/form_blanks.py b/scripts/form_blanks.py
new file mode 100644
index 0000000..3940eb8
--- /dev/null
+++ b/scripts/form_blanks.py
@@ -0,0 +1,49 @@
+"""List the blanks of an official form: the runs of dots (or the ellipsis
+character) that the applicant writes on, with their page, position and the
+label before them. Positions are PDF points from the top left of the page,
+the system krilla draws in, so a value starts at x0 on the baseline.
+
+ uv run --with pymupdf python scripts/form_blanks.py forms/tm7.pdf
+
+Used to measure a form's blanks for src/forms/layout.rs when a form is new
+or the Immigration Bureau publishes a new version of it.
+"""
+
+import sys
+
+import pymupdf
+
+DOTS = {".", "\u2026", "\u00b7"}
+
+
+def blanks(path):
+ doc = pymupdf.open(path)
+ for pno, page in enumerate(doc):
+ raw = page.get_text("rawdict")
+ for block in raw["blocks"]:
+ for line in block.get("lines", []):
+ chars = [c for span in line["spans"] for c in span["chars"]]
+ origin_y = None
+ i = 0
+ while i < len(chars):
+ if chars[i]["c"] in DOTS:
+ j = i
+ while j < len(chars) and chars[j]["c"] in DOTS:
+ j += 1
+ if j - i >= 4:
+ label = "".join(c["c"] for c in chars[max(0, i - 28) : i])
+ x0 = chars[i]["bbox"][0]
+ x1 = chars[j - 1]["bbox"][2]
+ origin_y = chars[i]["origin"][1]
+ yield pno + 1, round(x0, 1), round(x1, 1), round(origin_y, 1), label.strip()
+ i = j
+ else:
+ i += 1
+
+
+if __name__ == "__main__":
+ for path in sys.argv[1:]:
+ print(f"== {path}")
+ rows = sorted(blanks(path), key=lambda r: (r[0], r[3], r[1]))
+ for n, (page, x0, x1, y, label) in enumerate(rows, 1):
+ print(f"{n:3} p{page} x {x0:6.1f}..{x1:6.1f} (w {x1 - x0:5.1f}) y {y:6.1f} after {label!r}")
diff --git a/scripts/gen_layout.py b/scripts/gen_layout.py
new file mode 100644
index 0000000..ca28e27
--- /dev/null
+++ b/scripts/gen_layout.py
@@ -0,0 +1,298 @@
+# Generates src/papers/layout.rs from the official forms in forms/: every
+# blank (measured by scripts/form_blanks.py, or for TM.47 from the gaps
+# between its labels), the boxes to tick and the titles to circle, each with
+# the key of the value that goes there.
+import importlib.util
+import pathlib
+import subprocess
+import sys
+
+import pymupdf
+
+# the repository, from scripts/
+REPO = pathlib.Path(__file__).resolve().parent.parent
+spec = importlib.util.spec_from_file_location("fb", REPO / "scripts" / "form_blanks.py")
+fb = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(fb)
+
+# blank number (as form_blanks.py prints it) -> key; SKIP lists the blanks
+# left empty on purpose (signatures, lines for the officer). A key used on
+# several blanks repeats its value (the Thai and the English half of a form);
+# "key+" continues the text of the blank before it on the next line.
+MAP = {
+ "tm7": {
+ 1: "written_at", 2: "date_day", 3: "date_month", 4: "date_year",
+ 5: "family_name", 6: "first_name",
+ 7: "middle_name", 8: "age", 9: "birth_day", 10: "birth_month", 11: "birth_year",
+ 12: "birth_place", 13: "nationality",
+ 14: "passport_no", 15: "passport_issue_day",
+ 16: "passport_issue_month", 17: "passport_issue_year", 18: "passport_issued_at", 19: "passport_expiry_day",
+ 20: "passport_expiry_month", 21: "passport_expiry_year", 22: "visa_type",
+ 23: "arrived_by", 24: "arrived_from",
+ 25: "arrival_port", 26: "arrival_day", 27: "arrival_month", 28: "arrival_year",
+ 29: "tdac_no",
+ 30: "days", 31: "days",
+ 32: "reason", 33: "reason+", 34: "reason+", 35: "reason+",
+ 37: "address", 38: "full_name",
+ 39: "house_no", 40: "road", 41: "subdistrict",
+ 42: "district", 43: "province",
+ },
+ "tm8": {
+ 1: "written_at", 2: "date_day", 3: "date_month", 4: "date_year",
+ 5: "family_name", 6: "first_name",
+ 7: "middle_name", 8: "nationality", 9: "age", 10: "birth_day",
+ 11: "birth_month", 12: "birth_year", 13: "birth_place", 14: "birth_country",
+ 15: "occupation", 16: "house_no", 17: "road",
+ 18: "subdistrict", 19: "district", 20: "province",
+ 21: "trip_to",
+ 22: "leave_day", 23: "leave_month", 24: "leave_year",
+ 25: "trip_by", 26: "trip_for",
+ 28: "return_day", 29: "return_month", 30: "return_year",
+ 31: "passport_country", 32: "passport_issued_at", 33: "passport_no", 34: "passport_issue_day",
+ 35: "passport_issue_month", 36: "passport_issue_year", 37: "passport_expiry_day", 38: "passport_expiry_month", 39: "passport_expiry_year",
+ 40: "visa_issued_at", 41: "visa_issue_day", 42: "visa_issue_month", 43: "visa_issue_year",
+ 44: "arrival_day", 45: "arrival_month", 46: "arrival_year",
+ 47: "permitted_day", 48: "permitted_month", 49: "permitted_year",
+ },
+ "stm2": {
+ 1: "date", 2: "full_name", 3: "age", 4: "nationality", 5: "reason",
+ 7: "date", 8: "full_name", 9: "age", 10: "nationality", 11: "reason_short",
+ },
+ "stm9": {
+ 1: "written_at", 2: "date_day", 3: "date_month", 4: "date_year",
+ 5: "family_name", 6: "first_name",
+ 7: "middle_name", 8: "age", 9: "nationality", 10: "passport_no",
+ },
+ "stm11": {
+ 1: "date_day", 2: "date_month", 3: "date_year",
+ 4: "full_name", 5: "age",
+ 6: "nationality", 7: "passport_no", 8: "phone",
+ 9: "extension_nth",
+ 10: "reason_short", 11: "position",
+ 12: "company_name",
+ 13: "coordinator", 14: "coordinator_phone",
+ 16: "date", 17: "full_name", 18: "age",
+ 19: "nationality", 20: "passport_no", 21: "phone",
+ 22: "extension_years",
+ 23: "reason_short", 24: "position",
+ 25: "company_name",
+ 26: "coordinator", 27: "coordinator_phone",
+ },
+ "stm1": {
+ 1: "company_written_at", 2: "date",
+ 3: "company_name_th",
+ 4: "company_registered_at", 5: "company_house_no", 6: "company_road",
+ 7: "company_subdistrict", 8: "company_district", 9: "company_province", 10: "company_signatory",
+ 11: "company_registered_at",
+ 12: "company_name",
+ 13: "company_certificate_short", 14: "full_name", 15: "age", 16: "nationality",
+ 17: "position", 18: "salary",
+ 19: "contract_from", 20: "contract_until",
+ 21: "company_business",
+ 22: "company_capital",
+ 23: "company_paid_up",
+ 24: "figures_year", 25: "revenue",
+ 26: "foreign_costs",
+ 27: "figures_year", 28: "equity",
+ 29: "thai_staff", 30: "foreign_staff",
+ 31: "company_signatory",
+ },
+}
+SKIP = {
+ "tm7": {36, 44}, # the applicant's and the writer's signatures
+ "tm8": {27, 50}, # the end of "and shall return" (the date follows), the signature
+ "stm2": {6, 12},
+ "stm9": {11},
+ "stm11": {15, 28},
+ "stm1": set(),
+}
+
+# TM.47 draws its dotted lines dot by dot: its blanks run from a label's end
+# to the next label (or the right margin at 521), on the Thai baselines.
+TM47 = [
+ # key, baseline, from x, to x
+ ("written_at", 131.2, 356.0, 521.0),
+ ("date_day", 164.1, 318.6, 340.6),
+ ("date_month", 164.1, 368.2, 448.6),
+ ("date_year", 164.1, 470.5, 521.0),
+ ("full_name", 230.1, 165.8, 521.0),
+ ("nationality", 263.1, 106.9, 233.0),
+ ("arrival_day", 297.8, None, None), # measured below
+ ("arrival_month", 297.8, None, None),
+ ("arrival_year", 297.8, 292.7, 322.6),
+ ("arrived_by", 297.8, 373.8, 521.0),
+ ("passport_no", 330.8, 156.0, 286.6),
+ ("tdac_no", 330.8, 367.6, 521.0),
+ ("house_no", 363.8, 382.2, 521.0),
+ ("road", 396.8, 115.6, 223.5),
+ ("subdistrict", 396.8, 252.6, 376.6),
+ ("district", 396.8, 407.3, 521.0),
+ ("province", 429.9, 104.6, 223.5),
+ ("phone", 429.9, 265.2, 377.0),
+]
+
+# boxes: form -> [(key, value, page, x0, x1, y0, y1)]
+TICKS = {
+ "tm8": [
+ ("entries", "single", 1, 115.2, 133.2, 484.2, 510.8),
+ ("entries", "multiple", 1, 259.9, 277.9, 484.4, 510.8),
+ ("visa_kind", "non-immigrant", 2, 115.9, 133.9, 119.4, 146.4),
+ ("visa_kind", "tourist", 2, 294.8, 312.8, 118.4, 146.4),
+ ("visa_kind", "transit", 2, 439.9, 457.9, 117.5, 146.4),
+ ("visa_kind", "other", 2, 115.9, 133.9, 154.3, 181.3),
+ ],
+ "stm11": [
+ ("applying_for", "extension", 1, 109.8, 126.3, 240.0, 253.7),
+ ("applying_for", "extension", 1, 84.8, 101.3, 581.8, 595.5),
+ ],
+ "tm47": [
+ ("visa_kind", "tourist", 1, 325.1, 332.4, 257.6, 264.8),
+ ("visa_kind", "non-immigrant", 1, 325.1, 332.4, 270.2, 277.4),
+ ],
+}
+
+# the printed titles to circle: (form, page, English line's words with their
+# key value, the Thai span)
+TITLE_WORDS = {
+ "tm7": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 275.0, 295.0, "นาย/นาง/นางสาว", 255.0, 278.0),
+ "tm8": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 286.0, 305.0, "นาย/นาง/นางสาว", 266.0, 289.0),
+ "stm2": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 497.0, 519.0, "นาย/นาง/นางสาว", 130.0, 155.0),
+ "stm9": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Ms": "Ms."}, 300.0, 322.0, "นาย/นาง/นางสาว", 280.0, 304.0),
+ "stm11": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 499.0, 520.0, "นาย/นาง/นางสาว", 155.0, 178.0),
+ "stm1": (1, {"Mr": "Mr.", "Mrs": "Mrs.", "Miss": "Miss"}, 366.0, 386.0, "นาย,นาง,นางสาว", 350.0, 372.0),
+}
+THAI_TITLES = [("Mr", "นาย"), ("Mrs", "นาง"), ("Miss", "นางสาว")]
+
+
+def rings(form, doc):
+ page_no, words, ey0, ey1, thai, ty0, ty1 = TITLE_WORDS[form]
+ page = doc[page_no - 1]
+ out = []
+ mr = [r for r in page.search_for("Mr.") if ey0 <= r.y0 <= ey1]
+ assert len(mr) == 1, (form, mr)
+ for value, word in words.items():
+ # "Miss" also matches inside "Commissioner" and "permission": the
+ # title is a short word on the line of "Mr."
+ hits = [
+ r
+ for r in page.search_for(word)
+ if abs(r.y0 - mr[0].y0) < 2 and r.width < 25
+ ]
+ assert len(hits) == 1, (form, word, hits)
+ r = hits[0]
+ out.append(("title", value, page_no, r.x0, r.x1, r.y0, r.y1))
+ # the Thai titles: the characters of the span "นาย/นาง/นางสาว"
+ raw = page.get_text("rawdict")
+ for block in raw["blocks"]:
+ for line in block.get("lines", []):
+ chars = [c for s in line["spans"] for c in s["chars"]]
+ text = "".join(c["c"] for c in chars)
+ i = text.find(thai)
+ if i < 0 or not (ty0 <= chars[i]["bbox"][1] <= ty1):
+ continue
+ sep = thai[3]
+ parts = thai.split(sep)
+ pos = i
+ for (value, _), part in zip(THAI_TITLES, parts):
+ cs = chars[pos : pos + len(part)]
+ x0 = min(c["bbox"][0] for c in cs)
+ x1 = max(c["bbox"][2] for c in cs)
+ y0 = min(c["bbox"][1] for c in cs)
+ y1 = max(c["bbox"][3] for c in cs)
+ out.append(("title", value, page_no, x0, x1, y0, y1))
+ pos += len(part) + 1
+ return out
+ raise SystemExit(f"{form}: no Thai title span {thai!r}")
+
+
+def tm47_entered(doc):
+ """The day and month blanks of 'เดินทางเข้ามาเมื่อวันที่ ... เดือน ...'."""
+ page = doc[0]
+ raw = page.get_text("rawdict")
+ for block in raw["blocks"]:
+ for line in block.get("lines", []):
+ chars = [c for s in line["spans"] for c in s["chars"]]
+ text = "".join(c["c"] for c in chars)
+ if text.startswith("เดินทางเข้ามาเมื่อวันที่"):
+ day_from = chars[len("เดินทางเข้ามาเมื่อวันที่") - 1]["bbox"][2] + 1.5
+ j = text.index("เดือน")
+ day_to = chars[j]["bbox"][0] - 1.5
+ month_from = chars[j + len("เดือน") - 1]["bbox"][2] + 1.5
+ return (day_from, day_to), (month_from, 268.6)
+ raise SystemExit("tm47: no entry line")
+
+
+def rust_blanks(form):
+ path = REPO / "forms" / f"{form}.pdf"
+ if form == "tm47":
+ doc = pymupdf.open(path)
+ (d0, d1), (m0, m1) = tm47_entered(doc)
+ out = []
+ for key, y, x0, x1 in TM47:
+ if key == "arrival_day":
+ x0, x1 = d0, d1
+ elif key == "arrival_month":
+ x0, x1 = m0, m1
+ out.append((1, x0, y, x1 - x0, key))
+ return out
+ rows = sorted(fb.blanks(str(path)), key=lambda r: (r[0], r[3], r[1]))
+ mapping, skip = MAP[form], SKIP[form]
+ numbers = set(range(1, len(rows) + 1))
+ assert set(mapping) | skip == numbers, (form, sorted(numbers - set(mapping) - skip), sorted(set(mapping) - numbers))
+ assert not set(mapping) & skip, form
+ out = []
+ for n, (page, x0, x1, y, _label) in enumerate(rows, 1):
+ if n in mapping:
+ out.append((page, x0, y, x1 - x0, mapping[n]))
+ return out
+
+
+FORMS = ["tm7", "stm2", "stm9", "stm11", "stm1", "tm47", "tm8"]
+
+
+def main():
+ lines = [
+ "//! Where the values go on the official forms: generated by",
+ "//! scripts/gen_layout.py from the blank forms in forms/ (positions in PDF",
+ "//! points from the top left of the page, the baseline of each blank's",
+ "//! dotted line). Do not edit by hand; measure again when the Immigration",
+ "//! Bureau publishes a new version of a form.",
+ "",
+ "use super::{Blank, Layout, Mark, b, m};",
+ "",
+ ]
+ for form in FORMS:
+ doc = pymupdf.open(REPO / "forms" / f"{form}.pdf")
+ blanks = rust_blanks(form)
+ marks = [("tick",) + t for t in TICKS.get(form, [])]
+ if form in TITLE_WORDS:
+ marks += [("ring",) + r for r in rings(form, doc)]
+ name = form.upper()
+ lines.append(f"pub const {name}: Layout = Layout {{")
+ lines.append(f" blanks: &{name}_BLANKS,")
+ lines.append(f" marks: &{name}_MARKS,")
+ lines.append("};")
+ lines.append("")
+ lines.append(f"const {name}_BLANKS: [Blank; {len(blanks)}] = [")
+ for page, x, y, w, key in blanks:
+ lines.append(f" b({page}, {x:.1f}, {y:.1f}, {w:.1f}, \"{key}\"),")
+ lines.append("];")
+ lines.append("")
+ lines.append(f"const {name}_MARKS: [Mark; {len(marks)}] = [")
+ for kind, key, value, page, x0, x1, y0, y1 in marks:
+ ring = "true" if kind == "ring" else "false"
+ lines.append(
+ f" m({page}, {x0:.1f}, {y0:.1f}, {x1 - x0:.1f}, {y1 - y0:.1f}, \"{key}\", \"{value}\", {ring}),"
+ )
+ lines.append("];")
+ lines.append("")
+ out = REPO / "src" / "papers" / "layout.rs"
+ out.parent.mkdir(exist_ok=True)
+ out.write_text("\n".join(lines), encoding="utf-8", newline="\n")
+ # formatted as cargo fmt would, so a rerun gives the committed file
+ subprocess.run(["rustfmt", "--edition", "2024", str(out)], check=True)
+ print("wrote", out, sum(1 for l in lines if l.startswith(" b(")), "blanks", sum(1 for l in lines if l.startswith(" m(")), "marks")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/audit.rs b/src/audit.rs
index 5dedec5..a26869f 100644
--- a/src/audit.rs
+++ b/src/audit.rs
@@ -53,6 +53,8 @@ pub enum Entity {
Report,
WorkPermit,
Document,
+ /// A filled-in form, opened or downloaded; `fields` names the forms.
+ Form,
}
impl Entity {
@@ -70,6 +72,7 @@ impl Entity {
Entity::Report => "report",
Entity::WorkPermit => "work-permit",
Entity::Document => "document",
+ Entity::Form => "form",
}
}
}
diff --git a/src/companies.rs b/src/companies.rs
index aee508f..5dbd735 100644
--- a/src/companies.rs
+++ b/src/companies.rs
@@ -13,7 +13,7 @@ use crate::countries;
use crate::dates::{self, Status};
use crate::gps;
use crate::people::{self, AddressInput};
-use crate::records::Record;
+use crate::records::{self, Record};
#[derive(Debug, Serialize)]
pub struct ListItem {
@@ -275,10 +275,42 @@ pub struct View {
pub signatory: String,
pub signatory_position: String,
pub notes: String,
+ /// What the forms take from the company (STM.1, STM.11), recorded ones
+ /// only, as label and value.
+ pub figures: Vec<(&'static str, String)>,
pub archived: bool,
pub archived_on: String,
}
+/// The company's values for the forms, in the order of its form.
+const FIGURES: &[(&str, &str, bool)] = &[
+ ("capital_thb", "Registered capital", true),
+ ("paid_up_thb", "Paid-up capital", true),
+ ("figures_year", "Year of the figures", false),
+ ("revenue_thb", "Revenue in that year", true),
+ ("equity_thb", "Owners' equity", true),
+ ("foreign_costs_thb", "Foreign staff's pay next year", true),
+ ("thai_staff", "Permanent Thai employees", false),
+ ("foreign_staff", "Foreign employees", false),
+ ("coordinator", "Coordinator for immigration", false),
+ ("coordinator_phone", "Coordinator's phone", false),
+];
+
+fn figures(r: &Record) -> Vec<(&'static str, String)> {
+ FIGURES
+ .iter()
+ .filter(|(k, _, _)| !r.get(k).is_empty())
+ .map(|(k, label, baht)| {
+ let raw = r.get(k);
+ let value = match raw.parse::() {
+ Ok(n) if *baht => format!("{} THB", records::thousands(n)),
+ _ => raw.to_string(),
+ };
+ (*label, value)
+ })
+ .collect()
+}
+
pub fn view(r: &Record, archived_at: Option>) -> View {
let address = people::address_line(&AddressInput {
house_no: r.get("house_no").into(),
@@ -313,6 +345,7 @@ pub fn view(r: &Record, archived_at: Option>) -> View {
signatory: r.get("signatory").into(),
signatory_position: r.get("signatory_position").into(),
notes: r.get("notes").into(),
+ figures: figures(r),
archived: archived_at.is_some(),
archived_on: archived_at
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
diff --git a/src/lib.rs b/src/lib.rs
index 75d3577..086482c 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 papers;
pub mod people;
pub mod records;
pub mod seed;
diff --git a/src/papers/layout.rs b/src/papers/layout.rs
new file mode 100644
index 0000000..5da5d40
--- /dev/null
+++ b/src/papers/layout.rs
@@ -0,0 +1,351 @@
+//! Where the values go on the official forms: generated by
+//! scripts/gen_layout.py from the blank forms in forms/ (positions in PDF
+//! points from the top left of the page, the baseline of each blank's
+//! dotted line). Do not edit by hand; measure again when the Immigration
+//! Bureau publishes a new version of a form.
+
+use super::{Blank, Layout, Mark, b, m};
+
+pub const TM7: Layout = Layout {
+ blanks: &TM7_BLANKS,
+ marks: &TM7_MARKS,
+};
+
+const TM7_BLANKS: [Blank; 42] = [
+ b(1, 419.0, 140.7, 125.4, "written_at"),
+ b(1, 328.5, 184.3, 38.7, "date_day"),
+ b(1, 386.7, 184.3, 86.3, "date_month"),
+ b(1, 491.6, 184.3, 52.9, "date_year"),
+ b(1, 236.9, 271.0, 149.9, "family_name"),
+ b(1, 408.0, 271.0, 147.5, "first_name"),
+ b(1, 95.7, 305.2, 163.7, "middle_name"),
+ b(1, 274.9, 305.2, 34.5, "age"),
+ b(1, 362.0, 305.2, 41.5, "birth_day"),
+ b(1, 423.2, 305.2, 76.1, "birth_month"),
+ b(1, 518.1, 305.2, 36.9, "birth_year"),
+ b(1, 111.7, 339.5, 293.4, "birth_place"),
+ b(1, 433.0, 339.5, 122.2, "nationality"),
+ b(1, 288.0, 373.7, 154.6, "passport_no"),
+ b(1, 468.8, 373.7, 78.5, "passport_issue_day"),
+ b(1, 90.6, 407.9, 94.5, "passport_issue_month"),
+ b(1, 203.9, 407.9, 39.1, "passport_issue_year"),
+ b(1, 274.7, 407.9, 131.7, "passport_issued_at"),
+ b(1, 470.9, 407.9, 78.3, "passport_expiry_day"),
+ b(1, 90.6, 442.1, 94.5, "passport_expiry_month"),
+ b(1, 203.9, 442.1, 39.1, "passport_expiry_year"),
+ b(1, 302.8, 442.1, 251.8, "visa_type"),
+ b(1, 149.9, 476.5, 156.8, "arrived_by"),
+ b(1, 321.8, 476.5, 231.1, "arrived_from"),
+ b(1, 124.0, 510.7, 186.8, "arrival_port"),
+ b(1, 327.7, 510.7, 43.8, "arrival_day"),
+ b(1, 391.1, 510.7, 92.3, "arrival_month"),
+ b(1, 502.2, 510.7, 53.1, "arrival_year"),
+ b(1, 245.8, 544.9, 159.1, "tdac_no"),
+ b(1, 417.2, 579.1, 124.4, "days"),
+ b(1, 423.2, 596.9, 46.2, "days"),
+ b(1, 134.3, 614.6, 420.6, "reason"),
+ b(1, 70.9, 648.8, 480.6, "reason+"),
+ b(1, 70.9, 665.9, 480.6, "reason+"),
+ b(1, 70.9, 682.9, 480.6, "reason+"),
+ b(2, 163.5, 89.7, 388.1, "address"),
+ b(2, 210.8, 127.7, 304.5, "full_name"),
+ b(2, 117.5, 165.6, 106.1, "house_no"),
+ b(2, 240.6, 165.6, 104.0, "road"),
+ b(2, 389.1, 165.6, 166.0, "subdistrict"),
+ b(2, 112.5, 203.5, 193.7, "district"),
+ b(2, 332.0, 203.5, 221.4, "province"),
+];
+
+const TM7_MARKS: [Mark; 6] = [
+ m(1, 138.0, 275.6, 13.0, 15.4, "title", "Mr", true),
+ m(1, 153.3, 275.6, 16.9, 15.4, "title", "Mrs", true),
+ m(1, 172.4, 275.6, 17.6, 15.4, "title", "Miss", true),
+ m(1, 138.0, 259.1, 15.6, 15.4, "title", "Mr", true),
+ m(1, 157.5, 259.1, 14.5, 15.4, "title", "Mrs", true),
+ m(1, 175.6, 259.1, 28.9, 15.4, "title", "Miss", true),
+];
+
+pub const STM2: Layout = Layout {
+ blanks: &STM2_BLANKS,
+ marks: &STM2_MARKS,
+};
+
+const STM2_BLANKS: [Blank; 10] = [
+ b(1, 424.0, 115.2, 128.8, "date"),
+ b(1, 202.9, 145.6, 350.2, "full_name"),
+ b(1, 58.6, 160.8, 57.6, "age"),
+ b(1, 154.4, 160.8, 187.2, "nationality"),
+ b(1, 57.8, 176.0, 496.1, "reason"),
+ b(1, 438.5, 480.0, 114.3, "date"),
+ b(1, 155.0, 510.4, 126.2, "full_name"),
+ b(1, 297.4, 510.4, 63.1, "age"),
+ b(1, 436.7, 510.4, 116.5, "nationality"),
+ b(1, 390.8, 525.6, 162.5, "reason_short"),
+];
+
+const STM2_MARKS: [Mark; 6] = [
+ m(1, 93.2, 497.9, 13.9, 18.9, "title", "Mr", true),
+ m(1, 111.2, 497.9, 18.1, 18.9, "title", "Mrs", true),
+ m(1, 133.3, 497.9, 18.8, 18.9, "title", "Miss", true),
+ m(1, 132.1, 133.1, 16.6, 18.9, "title", "Mr", true),
+ m(1, 152.8, 133.1, 15.4, 18.9, "title", "Mrs", true),
+ m(1, 172.1, 133.1, 30.8, 18.9, "title", "Miss", true),
+];
+
+pub const STM9: Layout = Layout {
+ blanks: &STM9_BLANKS,
+ marks: &STM9_MARKS,
+};
+
+const STM9_BLANKS: [Blank; 10] = [
+ b(1, 398.3, 220.9, 154.8, "written_at"),
+ b(1, 377.0, 257.9, 28.5, "date_day"),
+ b(1, 424.8, 257.9, 74.6, "date_month"),
+ b(1, 517.6, 257.9, 35.1, "date_year"),
+ b(1, 222.0, 294.9, 143.5, "family_name"),
+ b(1, 387.6, 294.9, 165.1, "first_name"),
+ b(1, 69.1, 331.9, 82.6, "middle_name"),
+ b(1, 167.9, 331.9, 43.7, "age"),
+ b(1, 253.7, 331.9, 99.7, "nationality"),
+ b(1, 433.7, 331.9, 119.1, "passport_no"),
+];
+
+const STM9_MARKS: [Mark; 6] = [
+ m(1, 94.2, 300.9, 13.9, 18.9, "title", "Mr", true),
+ m(1, 113.8, 300.9, 18.1, 18.9, "title", "Mrs", true),
+ m(1, 137.6, 300.9, 14.9, 18.9, "title", "Ms", true),
+ m(1, 118.3, 282.4, 16.5, 18.9, "title", "Mr", true),
+ m(1, 138.7, 282.4, 15.3, 18.9, "title", "Mrs", true),
+ m(1, 158.0, 282.4, 30.6, 18.9, "title", "Miss", true),
+];
+
+pub const STM11: Layout = Layout {
+ blanks: &STM11_BLANKS,
+ marks: &STM11_MARKS,
+};
+
+const STM11_BLANKS: [Blank; 26] = [
+ b(1, 395.3, 137.0, 27.0, "date_day"),
+ b(1, 445.9, 137.0, 51.7, "date_month"),
+ b(1, 517.9, 137.0, 35.9, "date_year"),
+ b(1, 197.4, 170.0, 270.0, "full_name"),
+ b(1, 482.4, 170.0, 65.3, "age"),
+ b(1, 72.5, 186.5, 105.8, "nationality"),
+ b(1, 272.1, 186.5, 127.0, "passport_no"),
+ b(1, 441.1, 186.5, 112.9, "phone"),
+ b(1, 344.5, 252.5, 51.0, "extension_nth"),
+ b(1, 69.2, 269.0, 300.7, "reason_short"),
+ b(1, 410.7, 269.0, 143.4, "position"),
+ b(1, 138.5, 285.5, 414.7, "company_name"),
+ b(1, 109.3, 302.0, 237.4, "coordinator"),
+ b(1, 390.0, 302.0, 164.7, "coordinator_phone"),
+ b(1, 439.6, 478.9, 114.2, "date"),
+ b(1, 150.3, 511.9, 298.6, "full_name"),
+ b(1, 465.2, 511.9, 65.5, "age"),
+ b(1, 91.7, 528.4, 102.0, "nationality"),
+ b(1, 245.8, 528.4, 160.3, "passport_no"),
+ b(1, 468.8, 528.4, 85.0, "phone"),
+ b(1, 393.1, 594.4, 72.9, "extension_years"),
+ b(1, 75.3, 610.9, 290.1, "reason_short"),
+ b(1, 400.1, 610.9, 153.4, "position"),
+ b(1, 170.8, 627.4, 383.3, "company_name"),
+ b(1, 125.6, 643.9, 238.2, "coordinator"),
+ b(1, 427.6, 643.9, 123.9, "coordinator_phone"),
+];
+
+const STM11_MARKS: [Mark; 8] = [
+ m(
+ 1,
+ 109.8,
+ 240.0,
+ 16.5,
+ 13.7,
+ "applying_for",
+ "extension",
+ false,
+ ),
+ m(
+ 1,
+ 84.8,
+ 581.8,
+ 16.5,
+ 13.7,
+ "applying_for",
+ "extension",
+ false,
+ ),
+ m(1, 91.4, 499.3, 13.9, 18.9, "title", "Mr", true),
+ m(1, 109.3, 499.3, 18.1, 18.9, "title", "Mrs", true),
+ m(1, 131.5, 499.3, 18.8, 18.9, "title", "Miss", true),
+ m(1, 130.5, 157.5, 15.8, 18.9, "title", "Mr", true),
+ m(1, 150.0, 157.5, 14.6, 18.9, "title", "Mrs", true),
+ m(1, 168.3, 157.5, 29.2, 18.9, "title", "Miss", true),
+];
+
+pub const STM1: Layout = Layout {
+ blanks: &STM1_BLANKS,
+ marks: &STM1_MARKS,
+};
+
+const STM1_BLANKS: [Blank; 31] = [
+ b(1, 427.2, 112.2, 125.3, "company_written_at"),
+ b(1, 418.9, 140.2, 133.9, "date"),
+ b(1, 184.8, 238.2, 259.9, "company_name_th"),
+ b(1, 42.5, 266.2, 136.0, "company_registered_at"),
+ b(1, 266.3, 266.2, 172.2, "company_house_no"),
+ b(1, 455.5, 266.2, 97.5, "company_road"),
+ b(1, 86.3, 294.2, 74.7, "company_subdistrict"),
+ b(1, 201.8, 294.2, 99.5, "company_district"),
+ b(1, 326.6, 294.2, 70.2, "company_province"),
+ b(1, 410.8, 294.2, 142.5, "company_signatory"),
+ b(1, 387.3, 322.2, 165.5, "company_registered_at"),
+ b(1, 407.6, 336.2, 145.2, "company_name"),
+ b(1, 67.4, 364.2, 59.8, "company_certificate_short"),
+ b(1, 292.9, 364.2, 143.0, "full_name"),
+ b(1, 450.3, 364.2, 25.6, "age"),
+ b(1, 512.1, 364.2, 40.6, "nationality"),
+ b(1, 117.3, 392.2, 163.3, "position"),
+ b(1, 337.9, 392.2, 68.0, "salary"),
+ b(1, 105.2, 434.2, 106.6, "contract_from"),
+ b(1, 237.8, 434.2, 102.1, "contract_until"),
+ b(1, 268.8, 462.2, 215.5, "company_business"),
+ b(1, 256.5, 476.2, 167.9, "company_capital"),
+ b(1, 272.8, 490.2, 151.9, "company_paid_up"),
+ b(1, 145.1, 504.2, 56.7, "figures_year"),
+ b(1, 360.4, 504.2, 147.4, "revenue"),
+ b(1, 133.5, 546.2, 129.3, "foreign_costs"),
+ b(1, 145.1, 588.2, 56.7, "figures_year"),
+ b(1, 375.3, 588.2, 88.5, "equity"),
+ b(1, 228.3, 616.2, 56.7, "thai_staff"),
+ b(1, 406.4, 616.2, 56.7, "foreign_staff"),
+ b(1, 299.0, 738.2, 127.0, "company_signatory"),
+];
+
+const STM1_MARKS: [Mark; 6] = [
+ m(1, 281.8, 366.5, 13.0, 17.6, "title", "Mr", true),
+ m(1, 304.6, 366.5, 16.9, 17.6, "title", "Mrs", true),
+ m(1, 331.3, 366.5, 17.6, 17.6, "title", "Miss", true),
+ m(1, 230.0, 352.5, 14.9, 17.6, "title", "Mr", true),
+ m(1, 247.0, 352.5, 13.8, 17.6, "title", "Mrs", true),
+ m(1, 262.8, 352.5, 27.6, 17.6, "title", "Miss", true),
+];
+
+pub const TM47: Layout = Layout {
+ blanks: &TM47_BLANKS,
+ marks: &TM47_MARKS,
+};
+
+const TM47_BLANKS: [Blank; 18] = [
+ b(1, 356.0, 131.2, 165.0, "written_at"),
+ b(1, 318.6, 164.1, 22.0, "date_day"),
+ b(1, 368.2, 164.1, 80.4, "date_month"),
+ b(1, 470.5, 164.1, 50.5, "date_year"),
+ b(1, 165.8, 230.1, 355.2, "full_name"),
+ b(1, 106.9, 263.1, 126.1, "nationality"),
+ b(1, 155.9, 297.8, 22.6, "arrival_day"),
+ b(1, 201.5, 297.8, 67.1, "arrival_month"),
+ b(1, 292.7, 297.8, 29.9, "arrival_year"),
+ b(1, 373.8, 297.8, 147.2, "arrived_by"),
+ b(1, 156.0, 330.8, 130.6, "passport_no"),
+ b(1, 367.6, 330.8, 153.4, "tdac_no"),
+ b(1, 382.2, 363.8, 138.8, "house_no"),
+ b(1, 115.6, 396.8, 107.9, "road"),
+ b(1, 252.6, 396.8, 124.0, "subdistrict"),
+ b(1, 407.3, 396.8, 113.7, "district"),
+ b(1, 104.6, 429.9, 118.9, "province"),
+ b(1, 265.2, 429.9, 111.8, "phone"),
+];
+
+const TM47_MARKS: [Mark; 2] = [
+ m(1, 325.1, 257.6, 7.3, 7.2, "visa_kind", "tourist", false),
+ m(
+ 1,
+ 325.1,
+ 270.2,
+ 7.3,
+ 7.2,
+ "visa_kind",
+ "non-immigrant",
+ false,
+ ),
+];
+
+pub const TM8: Layout = Layout {
+ blanks: &TM8_BLANKS,
+ marks: &TM8_MARKS,
+};
+
+const TM8_BLANKS: [Blank; 48] = [
+ b(1, 406.0, 148.9, 141.0, "written_at"),
+ b(1, 328.5, 193.0, 39.1, "date_day"),
+ b(1, 387.3, 193.0, 87.7, "date_month"),
+ b(1, 493.8, 193.0, 53.1, "date_year"),
+ b(1, 236.9, 282.0, 149.9, "family_name"),
+ b(1, 408.0, 282.0, 147.5, "first_name"),
+ b(1, 95.7, 316.2, 163.9, "middle_name"),
+ b(1, 287.6, 316.2, 78.4, "nationality"),
+ b(1, 381.2, 316.2, 34.5, "age"),
+ b(1, 471.3, 316.2, 85.3, "birth_day"),
+ b(1, 90.6, 350.4, 74.8, "birth_month"),
+ b(1, 184.8, 350.4, 36.3, "birth_year"),
+ b(1, 270.9, 350.4, 151.9, "birth_place"),
+ b(1, 452.7, 350.4, 103.9, "birth_country"),
+ b(1, 92.3, 384.6, 136.1, "occupation"),
+ b(1, 303.2, 384.6, 106.5, "house_no"),
+ b(1, 426.9, 384.6, 126.9, "road"),
+ b(1, 115.3, 419.0, 133.7, "subdistrict"),
+ b(1, 290.5, 419.0, 104.5, "district"),
+ b(1, 420.3, 419.0, 134.0, "province"),
+ b(1, 269.9, 532.0, 281.5, "trip_to"),
+ b(1, 196.5, 566.2, 74.9, "leave_day"),
+ b(1, 291.0, 566.2, 154.2, "leave_month"),
+ b(1, 463.9, 566.2, 85.3, "leave_year"),
+ b(1, 99.5, 598.2, 147.9, "trip_by"),
+ b(1, 271.2, 598.2, 138.7, "trip_for"),
+ b(1, 186.3, 632.9, 90.0, "return_day"),
+ b(1, 296.1, 632.9, 150.1, "return_month"),
+ b(1, 465.0, 632.9, 85.4, "return_year"),
+ b(1, 100.9, 706.2, 108.4, "passport_country"),
+ b(1, 241.0, 706.2, 94.7, "passport_issued_at"),
+ b(1, 355.3, 706.2, 83.0, "passport_no"),
+ b(1, 464.5, 706.2, 85.3, "passport_issue_day"),
+ b(1, 90.6, 740.4, 115.3, "passport_issue_month"),
+ b(1, 224.7, 740.4, 41.5, "passport_issue_year"),
+ b(1, 330.5, 740.4, 41.6, "passport_expiry_day"),
+ b(1, 391.8, 740.4, 73.7, "passport_expiry_month"),
+ b(1, 484.3, 740.4, 69.2, "passport_expiry_year"),
+ b(2, 102.5, 202.3, 154.6, "visa_issued_at"),
+ b(2, 273.9, 202.3, 71.6, "visa_issue_day"),
+ b(2, 365.2, 202.3, 94.6, "visa_issue_month"),
+ b(2, 481.5, 202.3, 71.6, "visa_issue_year"),
+ b(2, 243.2, 240.4, 69.2, "arrival_day"),
+ b(2, 332.2, 240.4, 115.3, "arrival_month"),
+ b(2, 466.3, 240.4, 87.7, "arrival_year"),
+ b(2, 204.5, 277.0, 52.3, "permitted_day"),
+ b(2, 276.4, 277.0, 74.9, "permitted_month"),
+ b(2, 370.8, 277.0, 56.7, "permitted_year"),
+];
+
+const TM8_MARKS: [Mark; 12] = [
+ m(1, 115.2, 484.2, 18.0, 26.6, "entries", "single", false),
+ m(1, 259.9, 484.4, 18.0, 26.4, "entries", "multiple", false),
+ m(
+ 2,
+ 115.9,
+ 119.4,
+ 18.0,
+ 27.0,
+ "visa_kind",
+ "non-immigrant",
+ false,
+ ),
+ m(2, 294.8, 118.4, 18.0, 28.0, "visa_kind", "tourist", false),
+ m(2, 439.9, 117.5, 18.0, 28.9, "visa_kind", "transit", false),
+ m(2, 115.9, 154.3, 18.0, 27.0, "visa_kind", "other", false),
+ m(1, 138.0, 286.6, 13.0, 15.4, "title", "Mr", true),
+ m(1, 153.3, 286.6, 16.9, 15.4, "title", "Mrs", true),
+ m(1, 172.4, 286.6, 17.6, 15.4, "title", "Miss", true),
+ m(1, 138.0, 270.1, 15.6, 15.4, "title", "Mr", true),
+ m(1, 157.5, 270.1, 14.5, 15.4, "title", "Mrs", true),
+ m(1, 175.6, 270.1, 28.9, 15.4, "title", "Miss", true),
+];
diff --git a/src/papers/mod.rs b/src/papers/mod.rs
new file mode 100644
index 0000000..ac9c622
--- /dev/null
+++ b/src/papers/mod.rs
@@ -0,0 +1,522 @@
+//! The Immigration Bureau's forms, filled in from the records. Each page of
+//! the blank form (forms/, as the Bureau publishes it) is laid unchanged into
+//! a new PDF, and the values are written on its dotted lines in Sarabun, the
+//! font of the forms themselves; a box is ticked or the person's title is
+//! circled where the form asks for that.
+
+pub mod layout;
+pub mod values;
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use anyhow::{Context, Result, anyhow};
+use krilla::Document;
+use krilla::color::rgb;
+use krilla::geom::{PathBuilder, Point, Size};
+use krilla::metadata::Metadata;
+use krilla::num::NormalizedF32;
+use krilla::page::PageSettings;
+use krilla::paint::{Fill, LineCap, Stroke};
+use krilla::pdf::{Pdf, PdfDocument};
+use krilla::surface::Surface;
+use krilla::text::{Font, TextDirection};
+use serde::Serialize;
+
+/// The values by key (`layout.rs` names the keys), as they go on the form.
+pub type Values = HashMap<&'static str, String>;
+
+/// A blank: the value of `key` is written from `x` on the baseline `y`
+/// (points from the page's top left), within `w`.
+#[derive(Debug)]
+pub struct Blank {
+ pub page: usize,
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub key: &'static str,
+}
+
+/// A box that is ticked, or a printed word that is circled (`ring`), when
+/// the value of `key` is `is`.
+#[derive(Debug)]
+pub struct Mark {
+ pub page: usize,
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ pub key: &'static str,
+ pub is: &'static str,
+ pub ring: bool,
+}
+
+#[derive(Debug)]
+pub struct Layout {
+ pub blanks: &'static [Blank],
+ pub marks: &'static [Mark],
+}
+
+const fn b(page: usize, x: f32, y: f32, w: f32, key: &'static str) -> Blank {
+ Blank { page, x, y, w, key }
+}
+
+#[allow(clippy::too_many_arguments)]
+const fn m(
+ page: usize,
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ key: &'static str,
+ is: &'static str,
+ ring: bool,
+) -> Mark {
+ Mark {
+ page,
+ x,
+ y,
+ w,
+ h,
+ key,
+ is,
+ ring,
+ }
+}
+
+/// A form of the Immigration Bureau.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
+pub enum Paper {
+ Tm7,
+ Stm2,
+ Stm9,
+ Stm11,
+ Stm1,
+ Tm47,
+ Tm8,
+}
+
+/// Every form, in the order the Forms tab lists them.
+pub const ALL: [Paper; 7] = [
+ Paper::Tm7,
+ Paper::Stm2,
+ Paper::Stm9,
+ Paper::Stm11,
+ Paper::Stm1,
+ Paper::Tm47,
+ Paper::Tm8,
+];
+
+/// The forms of an extension of stay, in the order the officer reads them.
+pub const EXTENSION: [Paper; 5] = [
+ Paper::Tm7,
+ Paper::Stm2,
+ Paper::Stm9,
+ Paper::Stm11,
+ Paper::Stm1,
+];
+
+/// Where the blank forms come from: Immigration Division 1's downloads, the
+/// versions of 2025 for the STM forms (forms/README.md).
+const SOURCE: &str = "https://bangkok.immigration.go.th/en/downloads_en/";
+
+impl Paper {
+ pub fn slug(self) -> &'static str {
+ match self {
+ Paper::Tm7 => "tm7",
+ Paper::Stm2 => "stm2",
+ Paper::Stm9 => "stm9",
+ Paper::Stm11 => "stm11",
+ Paper::Stm1 => "stm1",
+ Paper::Tm47 => "tm47",
+ Paper::Tm8 => "tm8",
+ }
+ }
+
+ pub fn from_slug(s: &str) -> Option {
+ ALL.into_iter().find(|p| p.slug() == s)
+ }
+
+ pub fn code(self) -> &'static str {
+ match self {
+ Paper::Tm7 => "TM.7",
+ Paper::Stm2 => "STM.2",
+ Paper::Stm9 => "STM.9",
+ Paper::Stm11 => "STM.11",
+ Paper::Stm1 => "STM.1",
+ Paper::Tm47 => "TM.47",
+ Paper::Tm8 => "TM.8",
+ }
+ }
+
+ pub fn title(self) -> &'static str {
+ match self {
+ Paper::Tm7 => "Application for extension of temporary stay",
+ Paper::Stm2 => "Acknowledgment of the conditions of a temporary stay",
+ Paper::Stm9 => "Acknowledgment of the penalties for overstay",
+ Paper::Stm11 => "Consent to the checking of the application",
+ Paper::Stm1 => "Certificate of employment, from the employer",
+ Paper::Tm47 => "Notification of staying longer than 90 days",
+ Paper::Tm8 => "Application for a re-entry permit",
+ }
+ }
+
+ pub fn when(self) -> &'static str {
+ match self {
+ Paper::Tm7 | Paper::Stm2 | Paper::Stm9 | Paper::Stm11 => {
+ "With every extension of stay; signed by the person."
+ }
+ Paper::Stm1 => {
+ "With an extension for work; signed by the director, with the company's seal."
+ }
+ Paper::Tm47 => "For a 90-day report in person or by someone the person authorizes.",
+ Paper::Tm8 => "Before a trip abroad, so that the extension of stay is kept.",
+ }
+ }
+
+ pub fn source(self) -> &'static str {
+ SOURCE
+ }
+
+ fn blank(self) -> &'static [u8] {
+ match self {
+ Paper::Tm7 => include_bytes!("../../forms/tm7.pdf"),
+ Paper::Stm2 => include_bytes!("../../forms/stm2.pdf"),
+ Paper::Stm9 => include_bytes!("../../forms/stm9.pdf"),
+ Paper::Stm11 => include_bytes!("../../forms/stm11.pdf"),
+ Paper::Stm1 => include_bytes!("../../forms/stm1.pdf"),
+ Paper::Tm47 => include_bytes!("../../forms/tm47.pdf"),
+ Paper::Tm8 => include_bytes!("../../forms/tm8.pdf"),
+ }
+ }
+
+ pub fn layout(self) -> &'static Layout {
+ match self {
+ Paper::Tm7 => &layout::TM7,
+ Paper::Stm2 => &layout::STM2,
+ Paper::Stm9 => &layout::STM9,
+ Paper::Stm11 => &layout::STM11,
+ Paper::Stm1 => &layout::STM1,
+ Paper::Tm47 => &layout::TM47,
+ Paper::Tm8 => &layout::TM8,
+ }
+ }
+
+ /// The keys the form uses, each once, in the order of its blanks.
+ pub fn keys(self) -> Vec<&'static str> {
+ let l = self.layout();
+ let mut out: Vec<&'static str> = Vec::new();
+ let keys = l
+ .blanks
+ .iter()
+ .map(|b| b.key.trim_end_matches('+'))
+ .chain(l.marks.iter().map(|m| m.key));
+ for k in keys {
+ if !out.contains(&k) {
+ out.push(k);
+ }
+ }
+ out
+ }
+}
+
+/// Sarabun (SIL Open Font License, forms/fonts/OFL.txt): Thai and Latin.
+static FONT: &[u8] = include_bytes!("../../forms/fonts/Sarabun-Regular.ttf");
+
+/// The size of the values, and the least they shrink to in a short blank.
+const SIZE: f32 = 10.5;
+const MIN_SIZE: f32 = 6.0;
+/// Values sit this far above the dotted line, as handwriting would.
+const LIFT: f32 = 1.6;
+
+/// The width of `text` at `size` points, as shaped.
+fn width(face: &rustybuzz::Face<'_>, text: &str, size: f32) -> f32 {
+ let mut buf = rustybuzz::UnicodeBuffer::new();
+ buf.push_str(text);
+ buf.guess_segment_properties();
+ let shaped = rustybuzz::shape(face, &[], buf);
+ let units: i32 = shaped.glyph_positions().iter().map(|p| p.x_advance).sum();
+ units as f32 * size / f32::from(face.units_per_em() as u16)
+}
+
+/// The size at which `text` fits into `room`, never under MIN_SIZE.
+fn fitting(face: &rustybuzz::Face<'_>, text: &str, room: f32) -> f32 {
+ let w = width(face, text, SIZE);
+ if w <= room {
+ SIZE
+ } else {
+ (SIZE * room / w).max(MIN_SIZE)
+ }
+}
+
+/// Splits `text` into a first line that fits `room` at full size and the
+/// rest.
+fn first_line<'a>(face: &rustybuzz::Face<'_>, text: &'a str, room: f32) -> (&'a str, &'a str) {
+ let mut end = 0;
+ for (i, c) in text.char_indices() {
+ if c == ' ' {
+ if width(face, &text[..i], SIZE) > room {
+ break;
+ }
+ end = i;
+ }
+ }
+ if end == 0 || width(face, text, SIZE) <= room {
+ return (text, "");
+ }
+ (&text[..end], text[end..].trim_start())
+}
+
+struct Pen<'a> {
+ font: Font,
+ face: rustybuzz::Face<'a>,
+}
+
+impl Pen<'_> {
+ fn write(&self, s: &mut Surface<'_>, blank: &Blank, text: &str) {
+ if text.is_empty() {
+ return;
+ }
+ let room = blank.w - 4.0;
+ let size = fitting(&self.face, text, room);
+ let w = width(&self.face, text, size);
+ // a short blank (a day, an age) gets its value in the middle
+ let x = if blank.w < 70.0 {
+ blank.x + ((blank.w - w) / 2.0).max(0.0)
+ } else {
+ blank.x + 3.0
+ };
+ s.draw_text(
+ Point::from_xy(x, blank.y - LIFT),
+ self.font.clone(),
+ size,
+ text,
+ false,
+ TextDirection::Auto,
+ );
+ }
+}
+
+fn ink() -> rgb::Color {
+ rgb::Color::new(0, 0, 0)
+}
+
+fn stroke(width: f32) -> Stroke {
+ Stroke {
+ paint: ink().into(),
+ width,
+ line_cap: LineCap::Round,
+ opacity: NormalizedF32::ONE,
+ ..Default::default()
+ }
+}
+
+/// An X in a box.
+fn tick(s: &mut Surface<'_>, mk: &Mark) {
+ let inset = mk.w.min(mk.h) * 0.22;
+ let (x0, y0) = (mk.x + inset, mk.y + inset);
+ let (x1, y1) = (mk.x + mk.w - inset, mk.y + mk.h - inset);
+ // a square X in a tall box
+ let side = (x1 - x0).min(y1 - y0);
+ let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
+ let h = side / 2.0;
+ let mut pb = PathBuilder::new();
+ pb.move_to(cx - h, cy - h);
+ pb.line_to(cx + h, cy + h);
+ pb.move_to(cx + h, cy - h);
+ pb.line_to(cx - h, cy + h);
+ if let Some(path) = pb.finish() {
+ s.set_fill(None);
+ s.set_stroke(Some(stroke(1.3)));
+ s.draw_path(&path);
+ s.set_stroke(None);
+ }
+}
+
+/// An ellipse around a printed word.
+fn ring(s: &mut Surface<'_>, mk: &Mark) {
+ let (rx, ry) = (mk.w / 2.0 + 2.5, mk.h / 2.0 - 1.0);
+ let (cx, cy) = (mk.x + mk.w / 2.0, mk.y + mk.h / 2.0 + 0.5);
+ // four cubic arcs
+ const K: f32 = 0.552_284_8;
+ let mut pb = PathBuilder::new();
+ pb.move_to(cx + rx, cy);
+ pb.cubic_to(cx + rx, cy + K * ry, cx + K * rx, cy + ry, cx, cy + ry);
+ pb.cubic_to(cx - K * rx, cy + ry, cx - rx, cy + K * ry, cx - rx, cy);
+ pb.cubic_to(cx - rx, cy - K * ry, cx - K * rx, cy - ry, cx, cy - ry);
+ pb.cubic_to(cx + K * rx, cy - ry, cx + rx, cy - K * ry, cx + rx, cy);
+ pb.close();
+ if let Some(path) = pb.finish() {
+ s.set_fill(None);
+ s.set_stroke(Some(stroke(0.8)));
+ s.draw_path(&path);
+ s.set_stroke(None);
+ }
+}
+
+/// The title to circle on a line that offers `offered`: the person's own,
+/// or Miss for Ms and Ms for Miss where the line has only the other.
+fn title_on_line<'a>(title: &str, offered: &[&'a Mark]) -> Option<&'a Mark> {
+ let alt = match title {
+ "Ms" => "Miss",
+ "Miss" => "Ms",
+ _ => "",
+ };
+ offered
+ .iter()
+ .find(|mk| mk.is == title)
+ .or_else(|| offered.iter().find(|mk| mk.is == alt))
+ .copied()
+}
+
+fn fill_page(s: &mut Surface<'_>, pen: &Pen<'_>, layout: &Layout, page: usize, v: &Values) {
+ s.set_fill(Some(Fill {
+ paint: ink().into(),
+ opacity: NormalizedF32::ONE,
+ rule: Default::default(),
+ }));
+ // what is left of a flowing value for its next line
+ let mut rest = String::new();
+ let blanks: Vec<&Blank> = layout.blanks.iter().filter(|b| b.page == page).collect();
+ for (i, blank) in blanks.iter().enumerate() {
+ let continued = blank.key.ends_with('+');
+ let text = if continued {
+ std::mem::take(&mut rest)
+ } else {
+ v.get(blank.key).cloned().unwrap_or_default()
+ };
+ let flows_on = blanks
+ .get(i + 1)
+ .is_some_and(|next| next.key.ends_with('+'));
+ if flows_on {
+ let (line, more) = first_line(&pen.face, &text, blank.w - 6.0);
+ pen.write(s, blank, line);
+ rest = more.to_string();
+ } else {
+ pen.write(s, blank, &text);
+ }
+ }
+ let marks: Vec<&Mark> = layout.marks.iter().filter(|mk| mk.page == page).collect();
+ for mk in marks.iter().filter(|mk| !mk.ring) {
+ if v.get(mk.key).is_some_and(|x| x == mk.is) {
+ tick(s, mk);
+ }
+ }
+ // titles: one ring on each line that offers them
+ let title = v.get("title").map(String::as_str).unwrap_or("");
+ let mut lines: Vec = marks.iter().filter(|mk| mk.ring).map(|mk| mk.y).collect();
+ lines.dedup_by(|a, b| (*a - *b).abs() < 1.0);
+ for y in lines {
+ let offered: Vec<&Mark> = marks
+ .iter()
+ .filter(|mk| mk.ring && (mk.y - y).abs() < 1.0)
+ .copied()
+ .collect();
+ if let Some(mk) = title_on_line(title, &offered) {
+ ring(s, mk);
+ }
+ }
+}
+
+/// 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 mut doc = Document::new();
+ doc.set_metadata(
+ Metadata::new()
+ .title(title.to_string())
+ .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();
+ }
+ }
+ doc.finish().map_err(|e| anyhow!("writing the PDF: {e:?}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn face() -> rustybuzz::Face<'static> {
+ rustybuzz::Face::from_slice(FONT, 0).unwrap()
+ }
+
+ #[test]
+ fn every_form_has_its_blanks_and_keys() {
+ for p in ALL {
+ assert_eq!(Paper::from_slug(p.slug()), Some(p));
+ assert!(!p.layout().blanks.is_empty(), "{}", p.code());
+ assert!(p.blank().starts_with(b"%PDF-"), "{}", p.code());
+ for b in p.layout().blanks {
+ assert!(b.w > 10.0 && b.x > 30.0 && b.x + b.w < 570.0, "{b:?}");
+ assert!(b.y > 50.0 && b.y < 830.0, "{b:?}");
+ }
+ }
+ assert!(Paper::Tm7.keys().contains(&"reason"));
+ assert!(!Paper::Tm7.keys().contains(&"reason+"));
+ }
+
+ #[test]
+ fn a_long_value_shrinks_and_a_reason_flows() {
+ let f = face();
+ assert_eq!(fitting(&f, "18", 30.0), SIZE);
+ let long = "DEMO ENGINEERING COMPANY LIMITED, FIFTH FLOOR, DEMO TOWER";
+ let size = fitting(&f, long, 120.0);
+ assert!((MIN_SIZE..SIZE).contains(&size), "{size}");
+ let (line, rest) = first_line(&f, long, 150.0);
+ assert!(width(&f, line, SIZE) <= 150.0, "{line}");
+ assert_eq!(format!("{line} {rest}"), long);
+ assert_eq!(first_line(&f, "SHORT", 150.0), ("SHORT", ""));
+ }
+
+ #[test]
+ fn thai_is_shaped_with_its_marks() {
+ let f = face();
+ // the tone mark and the vowel above take no room of their own
+ assert!(width(&f, "นี้", SIZE) < width(&f, "นนน", SIZE));
+ }
+
+ #[test]
+ fn the_title_or_its_neighbour_is_circled() {
+ let mr = m(1, 0.0, 0.0, 1.0, 1.0, "title", "Mr", true);
+ let miss = m(1, 0.0, 0.0, 1.0, 1.0, "title", "Miss", true);
+ let ms = m(1, 0.0, 0.0, 1.0, 1.0, "title", "Ms", true);
+ assert_eq!(
+ title_on_line("Ms", &[&mr, &miss]).map(|x| x.is),
+ Some("Miss")
+ );
+ assert_eq!(title_on_line("Miss", &[&mr, &ms]).map(|x| x.is), Some("Ms"));
+ assert_eq!(title_on_line("Ms", &[&mr, &ms]).map(|x| x.is), Some("Ms"));
+ assert!(title_on_line("", &[&mr, &miss]).is_none());
+ }
+
+ #[test]
+ fn a_filled_form_is_a_pdf_with_the_form_s_pages() {
+ let mut v = Values::new();
+ v.insert("family_name", "MUSTERMANN".into());
+ v.insert("title", "Ms".into());
+ v.insert("entries", "multiple".into());
+ v.insert(
+ "reason",
+ "TO CONTINUE WORKING FOR DEMO ENGINEERING CO., LTD. AS ELECTRICAL ENGINEER, AS IN THE WORK PERMIT AND THE EMPLOYER'S CERTIFICATE".into(),
+ );
+ let pdf = render(&[Paper::Tm7, Paper::Tm8], &v, "TM.7 and TM.8").unwrap();
+ assert!(pdf.starts_with(b"%PDF-"));
+ let parsed = Pdf::new(pdf).unwrap();
+ assert_eq!(parsed.pages().len(), 4);
+ }
+}
diff --git a/src/papers/values.rs b/src/papers/values.rs
new file mode 100644
index 0000000..b3831e0
--- /dev/null
+++ b/src/papers/values.rs
@@ -0,0 +1,791 @@
+//! The values on the forms. Most come from the records: the person, the
+//! current passport and address, the last arrival with its visa, the
+//! permission to stay, the work permit and the employer. What only this
+//! application says (the date on the forms, the reason, a planned trip) comes
+//! from the Forms tab, with defaults from the records.
+//!
+//! The forms are filled in in capitals, with the Western year, as the
+//! passport and the stamps have it; the TM.6 line takes the TDAC number.
+
+use anyhow::Result;
+use chrono::{Datelike, NaiveDate};
+use serde::{Deserialize, Serialize};
+use sqlx::PgPool;
+
+use super::{Paper, Values};
+use crate::countries;
+use crate::dates;
+use crate::documents::{self, Owner};
+use crate::forms::{Errors, err};
+use crate::people::{self, Address, AddressInput, Passport, Person};
+use crate::records::{self, Record};
+
+/// What the records say for the forms.
+pub struct Facts {
+ pub person: Person,
+ /// The passport that runs longest.
+ pub passport: Option,
+ /// The address the person has not moved out of, the latest moved into.
+ pub address: Option,
+ pub arrival: Option,
+ /// The visa of the last arrival, or the latest visa.
+ pub visa: Option,
+ /// The end of the permission to stay: the last arrival's stamp or a
+ /// later extension's.
+ pub permitted_until: Option,
+ /// Extensions approved so far.
+ pub extensions: usize,
+ pub work_permit: Option,
+ /// The employer on the work permit, else the person's employer.
+ pub company: Option,
+ /// The date of the newest company certificate among its documents.
+ pub certificate_on: Option,
+}
+
+pub async fn load(db: &PgPool, id: i64) -> Result