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> { + let Some(person) = people::get_person(db, id).await? else { + return Ok(None); + }; + let passport = people::passports(db, id) + .await? + .into_iter() + .max_by_key(|p| (p.expires_on, p.id)); + let address = people::addresses(db, id) + .await? + .into_iter() + .filter(|a| a.moved_out_on.is_none()) + .max_by_key(|a| (a.moved_in_on, a.id)); + let arrival = records::list(db, &records::ARRIVALS, id) + .await? + .into_iter() + .max_by_key(|r| (r.date("arrived_on"), r.id)); + let mut visas = records::list(db, &records::VISAS, id).await?; + let used = arrival.as_ref().map(|a| a.get("visa_id").to_string()); + let visa = match visas.iter().position(|v| Some(v.id.to_string()) == used) { + Some(i) => Some(visas.swap_remove(i)), + None => visas + .into_iter() + .max_by_key(|v| (v.date("issued_on"), v.id)), + }; + let extensions = records::list(db, &records::EXTENSIONS, id).await?; + let since = arrival.as_ref().and_then(|a| a.date("arrived_on")); + let permitted_until = arrival + .iter() + .filter_map(|a| a.date("permitted_until")) + .chain( + extensions + .iter() + .filter(|e| e.get("decision") != "refused") + .filter(|e| match (since, e.date("applied_on")) { + (Some(s), Some(d)) => d >= s, + _ => true, + }) + .filter_map(|e| e.date("permitted_until")), + ) + .max(); + let approved = extensions + .iter() + .filter(|e| e.get("decision") == "approved") + .count(); + let work_permit = records::list(db, &records::WORK_PERMITS, id) + .await? + .into_iter() + .max_by_key(|r| (r.date("valid_until"), r.id)); + let company_id = work_permit + .as_ref() + .and_then(|w| w.get("company_id").parse::().ok()) + .or(person.employer_id); + let (company, certificate_on) = match company_id { + Some(c) => ( + records::get(db, &records::COMPANIES, None, c).await?, + documents::list(db, Owner::Company(c)) + .await? + .into_iter() + .filter(|d| d.kind == "company-certificate") + .filter_map(|d| d.dated_on) + .max(), + ), + None => (None, None), + }; + Ok(Some(Facts { + person, + passport, + address, + arrival, + visa, + permitted_until, + extensions: approved, + work_permit, + company, + certificate_on, + })) +} + +/// What this application says, as the Forms tab's fields hold it (query +/// parameters, so that the links to the PDFs carry them). +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +#[serde(default)] +pub struct Application { + /// The date on the forms, YYYY-MM-DD. + pub date: String, + /// "Written at": the office the forms go to. + pub at: String, + pub reason: String, + /// The reason in a few words, for the narrow lines of STM.2 and STM.11. + pub short: String, + /// The days asked for on TM.7. + pub days: String, + /// Which yearly extension this is (STM.11). + pub nth: String, + /// TM.8: single or multiple. + pub entries: String, + /// TM.8: where to, by what, what for, leaving and coming back. + pub to: String, + pub by: String, + #[serde(rename = "for")] + pub purpose: String, + pub leave: String, + #[serde(rename = "return")] + pub back: String, +} + +pub const OFFICE: &str = "Chiang Mai Immigration"; + +impl Application { + /// The empty fields take their defaults from the records. + pub fn with_defaults(mut self, f: &Facts, today: NaiveDate) -> Application { + let set = |v: &mut String, d: String| { + if v.trim().is_empty() { + *v = d; + } else { + *v = v.trim().to_string(); + } + }; + set(&mut self.date, today.to_string()); + set(&mut self.at, OFFICE.to_string()); + set(&mut self.reason, default_reason(f)); + let short = match &f.company { + Some(c) => format!("Working at {}", c.get("name")), + None => self.reason.clone(), + }; + set(&mut self.short, short); + let tourist = f.visa.as_ref().is_some_and(|v| v.get("category") == "tr") + || f.arrival + .as_ref() + .is_some_and(|a| a.get("admission") == "exempt"); + set( + &mut self.days, + if tourist { "30" } else { "365" }.to_string(), + ); + set(&mut self.nth, (f.extensions + 1).to_string()); + set(&mut self.entries, "single".to_string()); + set(&mut self.to, String::new()); + set(&mut self.by, "Air".to_string()); + set(&mut self.purpose, "Tourism".to_string()); + set(&mut self.leave, String::new()); + set(&mut self.back, String::new()); + self + } + + /// The fields' problems, by field name. + pub fn check(&self) -> Errors { + let mut e = Errors::new(); + for (name, value) in [ + ("date", &self.date), + ("leave", &self.leave), + ("return", &self.back), + ] { + if !value.is_empty() + && let Err(msg) = dates::parse_form_date(value) + { + err(&mut e, name, msg); + } + } + if !matches!(self.days.parse::(), Ok(1..=999)) { + err(&mut e, "days", "Enter the number of days, such as 365."); + } + if !matches!(self.nth.parse::(), Ok(1..=99)) { + err(&mut e, "nth", "Enter a number, such as 1 for the first."); + } + if !matches!(self.entries.as_str(), "single" | "multiple") { + err(&mut e, "entries", "Choose single or multiple."); + } + if let (Some(a), Some(b)) = ( + dates::parse_date(&self.leave), + dates::parse_date(&self.back), + ) && b < a + { + err(&mut e, "return", "The return comes after the departure."); + } + for (name, value, limit) in [ + ("at", &self.at, 80), + ("reason", &self.reason, 300), + ("short", &self.short, 80), + ("to", &self.to, 120), + ("by", &self.by, 60), + ("for", &self.purpose, 120), + ] { + if value.chars().count() > limit { + err(&mut e, name, format!("Keep this under {limit} characters.")); + } + } + e + } + + /// The query string that carries the application to the PDFs. + pub fn query(&self) -> String { + serde_urlencoded::to_string(self).unwrap_or_default() + } +} + +fn default_reason(f: &Facts) -> String { + let Some(c) = &f.company else { + return String::new(); + }; + let position = f + .work_permit + .as_ref() + .map(|w| w.get("position")) + .filter(|p| !p.is_empty()) + .unwrap_or(&f.person.occupation); + if position.is_empty() { + format!("To continue working for {}", c.get("name")) + } else { + format!("To continue working for {} as {}", c.get("name"), position) + } +} + +const MONTHS: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; + +fn full_date(d: NaiveDate) -> String { + format!("{} {} {}", d.day(), MONTHS[d.month0() as usize], d.year()) +} + +/// For a narrow blank: "9 Oct 2026". +fn short_date(d: NaiveDate) -> String { + format!( + "{} {} {}", + d.day(), + &MONTHS[d.month0() as usize][..3], + d.year() + ) +} + +/// A date in the three blanks day, month and year. +fn put_date(v: &mut Values, prefix: &'static str, d: Option) { + let (day, month, year) = match prefix { + "date" => ("date_day", "date_month", "date_year"), + "birth" => ("birth_day", "birth_month", "birth_year"), + "passport_issue" => ( + "passport_issue_day", + "passport_issue_month", + "passport_issue_year", + ), + "passport_expiry" => ( + "passport_expiry_day", + "passport_expiry_month", + "passport_expiry_year", + ), + "visa_issue" => ("visa_issue_day", "visa_issue_month", "visa_issue_year"), + "arrival" => ("arrival_day", "arrival_month", "arrival_year"), + "permitted" => ("permitted_day", "permitted_month", "permitted_year"), + "leave" => ("leave_day", "leave_month", "leave_year"), + "return" => ("return_day", "return_month", "return_year"), + _ => unreachable!("no date blanks called {prefix}"), + }; + let (a, b, c) = match d { + Some(d) => ( + d.day().to_string(), + MONTHS[d.month0() as usize].to_string(), + d.year().to_string(), + ), + None => Default::default(), + }; + v.insert(day, a); + v.insert(month, b); + v.insert(year, c); +} + +fn age(born: NaiveDate, on: NaiveDate) -> i32 { + let mut years = on.year() - born.year(); + if (on.month(), on.day()) < (born.month(), born.day()) { + years -= 1; + } + years +} + +fn money(raw: &str) -> String { + raw.parse::() + .map(records::thousands) + .unwrap_or_default() +} + +/// The house number with the moo: "88/8 MOO 3". +fn house(no: &str, moo: &str) -> String { + match (no.trim(), moo.trim()) { + (n, "") => n.to_string(), + ("", m) => format!("Moo {m}"), + (n, m) => format!("{n} Moo {m}"), + } +} + +/// Soi and road: "Soi 5, Nimmanhaemin Road". +fn street(soi: &str, road: &str) -> String { + let soi = soi.trim(); + let soi = if soi.is_empty() || soi.to_lowercase().starts_with("soi") { + soi.to_string() + } else { + format!("Soi {soi}") + }; + match (soi.as_str(), road.trim()) { + (s, "") => s.to_string(), + ("", r) => r.to_string(), + (s, r) => format!("{s}, {r}"), + } +} + +/// "Non-Immigrant B (work, business)" becomes "Non-Immigrant B". +fn visa_type(f: &Facts) -> String { + if let Some(v) = &f.visa { + let label = records::label(records::VISA_CATEGORIES, v.get("category")).unwrap_or(""); + return label.split(" (").next().unwrap_or(label).to_string(); + } + match f.arrival.as_ref().map(|a| a.get("admission")) { + Some("exempt") => "Visa exemption".to_string(), + Some("voa") => "Visa on arrival".to_string(), + _ => String::new(), + } +} + +/// The box for the kind of visa (TM.8's last visa, TM.47). +fn visa_kind(f: &Facts) -> &'static str { + let category = f.visa.as_ref().map(|v| v.get("category")).unwrap_or(""); + match category { + "non-b" | "non-o" | "o-a" | "non-ed" => "non-immigrant", + "tr" => "tourist", + "" => match f.arrival.as_ref().map(|a| a.get("admission")) { + Some("exempt") | Some("voa") => "tourist", + _ => "", + }, + _ => "other", + } +} + +/// Every value the forms take. Keys without a value hold "". +pub fn values(f: &Facts, a: &Application, today: NaiveDate) -> Values { + let mut v = Values::new(); + let p = &f.person; + let on = dates::parse_date(&a.date).unwrap_or(today); + v.insert("written_at", a.at.clone()); + v.insert("date", full_date(on)); + put_date(&mut v, "date", Some(on)); + + v.insert("title", p.title.clone()); + v.insert("family_name", p.surname.clone()); + v.insert("first_name", p.first_name.clone()); + v.insert("middle_name", p.middle_name.clone()); + let full = [&p.first_name, &p.middle_name, &p.surname] + .iter() + .filter(|s| !s.is_empty()) + .map(|s| s.as_str()) + .collect::>() + .join(" "); + v.insert("full_name", full); + v.insert( + "age", + p.date_of_birth + .map(|b| age(b, on).to_string()) + .unwrap_or_default(), + ); + put_date(&mut v, "birth", p.date_of_birth); + v.insert("birth_place", p.place_of_birth.clone()); + v.insert("birth_country", String::new()); + v.insert( + "nationality", + countries::name(&p.nationality) + .unwrap_or(&p.nationality) + .to_string(), + ); + let position = f + .work_permit + .as_ref() + .map(|w| w.get("position").to_string()) + .unwrap_or_default(); + v.insert( + "occupation", + if p.occupation.is_empty() { + position.clone() + } else { + p.occupation.clone() + }, + ); + v.insert("phone", p.phone.clone()); + + let pp = f.passport.as_ref(); + v.insert( + "passport_no", + pp.map(|x| x.number.clone()).unwrap_or_default(), + ); + v.insert( + "passport_country", + pp.and_then(|x| countries::name(&x.issuing_country)) + .unwrap_or("") + .to_string(), + ); + v.insert( + "passport_issued_at", + pp.map(|x| x.issued_at.clone()).unwrap_or_default(), + ); + put_date(&mut v, "passport_issue", pp.and_then(|x| x.issued_on)); + put_date(&mut v, "passport_expiry", pp.map(|x| x.expires_on)); + + v.insert("visa_type", visa_type(f)); + v.insert("visa_kind", visa_kind(f).to_string()); + let visa = f.visa.as_ref(); + v.insert( + "visa_issued_at", + visa.map(|x| x.get("issued_at").to_string()) + .unwrap_or_default(), + ); + put_date(&mut v, "visa_issue", visa.and_then(|x| x.date("issued_on"))); + + let arr = f.arrival.as_ref(); + let get = |k: &str| arr.map(|x| x.get(k).to_string()).unwrap_or_default(); + v.insert("arrived_by", get("flight")); + v.insert("arrived_from", get("came_from")); + v.insert("arrival_port", get("port")); + v.insert("tdac_no", get("tdac_no")); + put_date(&mut v, "arrival", arr.and_then(|x| x.date("arrived_on"))); + put_date(&mut v, "permitted", f.permitted_until); + + let ad = f.address.as_ref(); + v.insert( + "address", + ad.map(|x| people::address_line(&AddressInput::from(x))) + .unwrap_or_default(), + ); + v.insert( + "house_no", + ad.map(|x| house(&x.house_no, &x.moo)).unwrap_or_default(), + ); + v.insert( + "road", + ad.map(|x| street(&x.soi, &x.road)).unwrap_or_default(), + ); + for (key, field) in [("subdistrict", 0), ("district", 1), ("province", 2)] { + let value = ad + .map(|x| [&x.subdistrict, &x.district, &x.province][field].clone()) + .unwrap_or_default(); + v.insert(key, value); + } + + v.insert("reason", a.reason.clone()); + v.insert("reason_short", a.short.clone()); + v.insert("days", a.days.clone()); + v.insert("extension_nth", a.nth.clone()); + v.insert("extension_years", "1".to_string()); + v.insert("applying_for", "extension".to_string()); + v.insert("entries", a.entries.clone()); + v.insert("trip_to", a.to.clone()); + v.insert("trip_by", a.by.clone()); + v.insert("trip_for", a.purpose.clone()); + put_date(&mut v, "leave", dates::parse_date(&a.leave)); + put_date(&mut v, "return", dates::parse_date(&a.back)); + + let wp = f.work_permit.as_ref(); + v.insert("position", position); + v.insert( + "salary", + wp.map(|w| money(w.get("monthly_salary_thb"))) + .unwrap_or_default(), + ); + for (key, field) in [ + ("contract_from", "contract_from"), + ("contract_until", "contract_until"), + ] { + v.insert( + key, + wp.and_then(|w| w.date(field)) + .map(full_date) + .unwrap_or_default(), + ); + } + + let c = f.company.as_ref(); + let cget = |k: &str| c.map(|x| x.get(k).to_string()).unwrap_or_default(); + v.insert("company_name", cget("name")); + // the employer writes STM.1, at the company + v.insert("company_written_at", cget("name")); + v.insert( + "company_name_th", + c.map(|x| { + if x.get("name_th").is_empty() { + x.get("name") + } else { + x.get("name_th") + } + .to_string() + }) + .unwrap_or_default(), + ); + v.insert("company_registered_at", cget("province")); + v.insert( + "company_house_no", + c.map(|x| house(x.get("house_no"), x.get("moo"))) + .unwrap_or_default(), + ); + v.insert( + "company_road", + c.map(|x| street(x.get("soi"), x.get("road"))) + .unwrap_or_default(), + ); + v.insert("company_subdistrict", cget("subdistrict")); + v.insert("company_district", cget("district")); + v.insert("company_province", cget("province")); + v.insert("company_signatory", cget("signatory")); + v.insert("company_business", cget("business")); + v.insert( + "company_certificate_date", + f.certificate_on.map(full_date).unwrap_or_default(), + ); + v.insert( + "company_certificate_short", + f.certificate_on.map(short_date).unwrap_or_default(), + ); + v.insert("company_capital", money(&cget("capital_thb"))); + v.insert("company_paid_up", money(&cget("paid_up_thb"))); + v.insert("figures_year", cget("figures_year")); + v.insert("revenue", money(&cget("revenue_thb"))); + v.insert("equity", money(&cget("equity_thb"))); + v.insert("foreign_costs", money(&cget("foreign_costs_thb"))); + v.insert("thai_staff", cget("thai_staff")); + v.insert("foreign_staff", cget("foreign_staff")); + v.insert("coordinator", cget("coordinator")); + v.insert("coordinator_phone", cget("coordinator_phone")); + + // capitals, as on a form filled in by hand; the marks' values stay + for (key, value) in v.iter_mut() { + if !matches!(*key, "title" | "visa_kind" | "entries" | "applying_for") { + *value = value.to_uppercase(); + } + } + v +} + +/// Something a form needs that the records do not have, and where to add it. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Missing { + pub what: &'static str, + pub href: String, +} + +/// Values a form may leave empty: there is nothing to write for many people. +const OPTIONAL: &[&str] = &[ + "middle_name", + "birth_country", + "title", + "road", + "company_road", + "visa_issued_at", + "visa_issue", + "visa_kind", + "company_name_th", +]; + +/// What a value is called in the list of missing things, and where it is +/// added. +fn about(key: &str, f: &Facts) -> (&'static str, String) { + let id = f.person.id; + let person = format!("/people/{id}/edit"); + let stay = format!("/people/{id}/stay"); + let company = match &f.company { + Some(c) => format!("/companies/{}/edit", c.id), + None => person.clone(), + }; + let key = if key == "figures_year" { + key + } else { + key.trim_end_matches("_day") + .trim_end_matches("_month") + .trim_end_matches("_year") + }; + match key { + "family_name" | "first_name" | "full_name" => ("The name", person), + "age" | "birth" => ("The date of birth", person), + "birth_place" => ("The place of birth", person), + "nationality" => ("The nationality", person), + "occupation" => ("The occupation", person), + "phone" => ("The person's phone number", person), + "passport_no" | "passport_country" | "passport_expiry" => { + ("A passport", format!("/people/{id}#passports")) + } + "passport_issued_at" => ( + "Where the passport was issued", + format!("/people/{id}#passports"), + ), + "passport_issue" => ( + "The passport's date of issue", + format!("/people/{id}#passports"), + ), + "visa_type" => ("The visa or the last arrival", stay), + "arrived_by" => ("The flight of the last arrival", format!("{stay}#arrivals")), + "arrived_from" => ( + "Where the last arrival came from", + format!("{stay}#arrivals"), + ), + "arrival_port" => ("The port of the last arrival", format!("{stay}#arrivals")), + "arrival" => ("The last arrival", format!("{stay}#arrivals")), + "tdac_no" => ( + "The TDAC number of the last arrival", + format!("{stay}#arrivals"), + ), + "permitted" => ("The permitted-until date", format!("{stay}#arrivals")), + "address" | "house_no" | "subdistrict" | "district" | "province" => { + ("An address in Thailand", format!("/people/{id}#addresses")) + } + "position" => ( + "The position on the work permit", + format!("{stay}#work-permits"), + ), + "salary" => ( + "The monthly salary on the work permit", + format!("{stay}#work-permits"), + ), + "contract_from" | "contract_until" => ( + "The contract's dates on the work permit", + format!("{stay}#work-permits"), + ), + "company_name" | "company_written_at" => ("The employer", person), + "company_registered_at" + | "company_house_no" + | "company_subdistrict" + | "company_district" + | "company_province" => ("The employer's address", company), + "company_signatory" => ("The employer's authorized director", company), + "company_business" => ("The employer's type of business", company), + "company_capital" | "company_paid_up" => ("The employer's capital", company), + "figures_year" | "revenue" | "equity" | "foreign_costs" => { + ("The employer's figures for STM.1", company) + } + "thai_staff" | "foreign_staff" => ("The employer's number of staff", company), + "coordinator" | "coordinator_phone" => ("The employer's coordinator", company), + "company_certificate_date" | "company_certificate_short" => ( + "The employer's company certificate, uploaded with its date", + match &f.company { + Some(c) => format!("/companies/{}#documents", c.id), + None => person, + }, + ), + "reason" | "reason_short" => ("The reason for the extension", "#application".to_string()), + "trip_to" | "trip_by" | "trip_for" | "leave" | "return" => { + ("The trip", "#application".to_string()) + } + _ => ("Another value", "#application".to_string()), + } +} + +/// What `paper` needs that `v` lacks, each thing once. +pub fn missing(paper: Paper, v: &Values, f: &Facts) -> Vec { + let mut out: Vec = Vec::new(); + for key in paper.keys() { + let base = key + .trim_end_matches("_day") + .trim_end_matches("_month") + .trim_end_matches("_year"); + if OPTIONAL.contains(&key) || OPTIONAL.contains(&base) { + continue; + } + if v.get(key).is_some_and(|x| !x.trim().is_empty()) { + continue; + } + let (what, href) = about(key, f); + if !out.iter().any(|m| m.what == what) { + out.push(Missing { what, href }); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(s: &str) -> NaiveDate { + dates::parse_date(s).unwrap() + } + + #[test] + fn ages_and_dates() { + assert_eq!(age(d("1984-08-12"), d("2026-08-11")), 41); + assert_eq!(age(d("1984-08-12"), d("2026-08-12")), 42); + assert_eq!(full_date(d("2026-11-18")), "18 November 2026"); + let mut v = Values::new(); + put_date(&mut v, "leave", Some(d("2027-01-05"))); + assert_eq!(v["leave_day"], "5"); + assert_eq!(v["leave_month"], "January"); + assert_eq!(v["leave_year"], "2027"); + } + + #[test] + fn addresses_in_the_forms_blanks() { + assert_eq!(house("88/8", "3"), "88/8 Moo 3"); + assert_eq!(house("", "3"), "Moo 3"); + assert_eq!( + street("Soi 5", "Nimmanhaemin Road"), + "Soi 5, Nimmanhaemin Road" + ); + assert_eq!(street("", "Superhighway Road"), "Superhighway Road"); + assert_eq!(street("7", "Huay Kaew Road"), "Soi 7, Huay Kaew Road"); + assert_eq!(short_date(d("2026-10-09")), "9 Oct 2026"); + assert_eq!(money("2000000"), "2,000,000"); + assert_eq!(money(""), ""); + } + + #[test] + fn the_application_is_checked() { + let mut a = Application { + date: "2026-11-18".into(), + days: "365".into(), + nth: "2".into(), + entries: "single".into(), + leave: "2027-01-05".into(), + back: "2027-01-02".into(), + ..Default::default() + }; + let e = a.check(); + assert!(e.contains_key("return"), "{e:?}"); + a.back = "2027-01-20".into(); + assert!(a.check().is_empty(), "{:?}", a.check()); + a.days = "a year".into(); + a.entries = "many".into(); + a.date = "202611-18".into(); + let e = a.check(); + assert!( + e.contains_key("days") && e.contains_key("entries") && e.contains_key("date"), + "{e:?}" + ); + let q = Application { + purpose: "Visiting family".into(), + back: "2027-01-20".into(), + ..Default::default() + } + .query(); + assert!( + q.contains("for=Visiting+family") && q.contains("return=2027-01-20"), + "{q}" + ); + } +} diff --git a/src/records.rs b/src/records.rs index acf0391..6a16f95 100644 --- a/src/records.rs +++ b/src/records.rs @@ -42,6 +42,12 @@ pub enum Input { Company, /// A GPS position, kept as "18.796500, 99.008200" (`gps`). Gps, + /// Whole baht of any size, also below zero (a company's equity). + Amount, + /// A number of people. + Count, + /// A year, the Western one; a Thai year (B.E.) is turned into it. + Year, } #[derive(Debug)] @@ -56,6 +62,8 @@ pub struct Field { /// A `` with suggestions: "ports", "offices" or "provinces". pub suggest: &'static str, pub wide: bool, + /// A heading the form shows before this field. + pub section: &'static str, } const fn field(name: &'static str, label: &'static str, input: Input) -> Field { @@ -67,6 +75,7 @@ const fn field(name: &'static str, label: &'static str, input: Input) -> Field { hint: "", suggest: "", wide: false, + section: "", } } @@ -83,6 +92,9 @@ impl Field { const fn wide(self) -> Field { Field { wide: true, ..self } } + const fn section(self, section: &'static str) -> Field { + Field { section, ..self } + } } /// The later date may not come before the earlier one; the message goes to @@ -252,6 +264,8 @@ const ARRIVAL_FIELDS: &[Field] = &[ .hint("The date in the arrival stamp."), field("passport_id", "Passport", Input::Passport), field("flight", "Flight or vehicle", Input::Code).hint("Such as TG110."), + field("came_from", "Came from", Input::Text) + .hint("Where the flight or the journey started, such as Frankfurt; TM.7 asks for it."), field("tdac_no", "TDAC number", Input::Code).hint( "The Thailand Digital Arrival Card, filed online within the three days before arrival.", ), @@ -400,6 +414,10 @@ const WORK_PERMIT_FIELDS: &[Field] = &[ field("position", "Position", Input::Text), field("issued_on", "Issued on", Input::Date), field("valid_until", "Valid until", Input::Date).req("Enter the date the permit ends."), + field("monthly_salary_thb", "Monthly salary in THB", Input::Money) + .hint("As in the employment contract; the employer's certificate (STM.1) states it."), + field("contract_from", "Contract from", Input::Date), + field("contract_until", "Contract until", Input::Date), field("notes", "Notes", Input::Area).wide(), ]; @@ -413,12 +431,20 @@ pub static WORK_PERMITS: Kind = Kind { fields: WORK_PERMIT_FIELDS, headline: &["company_id", "number"], order: "valid_until DESC, id DESC", - date_order: &[DateOrder { - earlier: "issued_on", - later: "valid_until", - target: "valid_until", - message: "The permit cannot end before it was issued.", - }], + date_order: &[ + DateOrder { + earlier: "issued_on", + later: "valid_until", + target: "valid_until", + message: "The permit cannot end before it was issued.", + }, + DateOrder { + earlier: "contract_from", + later: "contract_until", + target: "contract_until", + message: "The contract cannot end before it starts.", + }, + ], check: no_check, status: work_permit_status, per_person: true, @@ -451,6 +477,23 @@ const COMPANY_FIELDS: &[Field] = &[ field("signatory", "Authorized director", Input::Text) .hint("Signs for the company on STM.1 and on the employer's part of TM.7."), field("signatory_position", "Director's position", Input::Text), + field("capital_thb", "Registered capital in THB", Input::Amount) + .section("For the employer's certificate (STM.1)"), + field("paid_up_thb", "Paid-up capital in THB", Input::Amount), + field("figures_year", "Year of the latest financial statements", Input::Year) + .hint("Such as 2025. A Thai year, such as 2568, is turned into the Western one."), + field("revenue_thb", "Total revenue in that year, in THB", Input::Amount) + .hint("As in the profit and loss statement."), + field("equity_thb", "Owners' equity in THB", Input::Amount) + .hint("As in the balance sheet of that year."), + field("foreign_costs_thb", "Foreign staff's pay next year, in THB", Input::Amount) + .hint("Salaries, wages and every benefit of all foreign employees in the next fiscal year."), + field("thai_staff", "Permanent Thai employees", Input::Count), + field("foreign_staff", "Foreign employees", Input::Count), + field("coordinator", "Coordinator for immigration", Input::Text) + .section("For the consent form (STM.11)") + .hint("The person at the company whom the officers may call about an application."), + field("coordinator_phone", "Coordinator's phone", Input::Text), field("notes", "Notes", Input::Area).wide(), ]; @@ -520,6 +563,26 @@ fn company_check(v: &Values, e: &mut Errors) { if !email.is_empty() && !crate::people::looks_like_email(email) { err(e, "email", "This does not look like an email address."); } + let amount = |k: &str| val(v, k).parse::().ok(); + for k in [ + "capital_thb", + "paid_up_thb", + "revenue_thb", + "foreign_costs_thb", + ] { + if amount(k).is_some_and(|n| n < 0) { + err(e, k, "Enter an amount of zero or more."); + } + } + if let (Some(capital), Some(paid)) = (amount("capital_thb"), amount("paid_up_thb")) + && paid > capital + { + err( + e, + "paid_up_thb", + "The paid-up capital is at most the registered capital.", + ); + } } /// The check digit of a Thai 13-digit number (juristic persons and @@ -649,7 +712,13 @@ pub fn read(kind: &Kind, f: &Fields) -> Values { let v = match fl.input { Input::Code => compact_upper(raw), Input::Digits => raw.trim().replace([' ', '-'], ""), - Input::Money => raw.trim().replace([',', ' '], ""), + Input::Money | Input::Count => raw.trim().replace([',', ' '], ""), + Input::Amount => raw.trim().replace([',', ' ', '\u{0e3f}'], ""), + Input::Year => match raw.trim().parse::() { + // the Thai year: 2568 is 2025 + Ok(y) if (2443..=2643).contains(&y) => (y - 543).to_string(), + _ => raw.trim().to_string(), + }, Input::Area => raw.trim().replace("\r\n", "\n"), Input::Gps => gps::parse(raw).map_or_else(|| raw.trim().to_string(), |p| p.text()), _ => raw.trim().to_string(), @@ -708,6 +777,18 @@ pub fn validate(kind: &Kind, v: &Values, opts: &Options) -> Errors { err(&mut e, fl.name, msg); } } + Input::Amount => match value.parse::() { + Ok(n) if n.abs() <= 10_000_000_000_000 => {} + _ => err(&mut e, fl.name, "Enter whole baht, such as 2,000,000."), + }, + Input::Count => match value.parse::() { + Ok(n) if (0..=1_000_000).contains(&n) => {} + _ => err(&mut e, fl.name, "Enter a number of people, such as 12."), + }, + Input::Year => match value.parse::() { + Ok(n) if (1900..=2100).contains(&n) => {} + _ => err(&mut e, fl.name, "Enter the year, such as 2025."), + }, Input::Text | Input::Code | Input::Area => {} } } @@ -761,7 +842,13 @@ fn columns(kind: &Kind) -> String { .iter() .map(|f| match f.input { Input::Date => format!("COALESCE(to_char({0}, 'YYYY-MM-DD'), '') AS {0}", f.name), - Input::Money | Input::Passport | Input::Visa | Input::Company => { + Input::Money + | Input::Amount + | Input::Count + | Input::Year + | Input::Passport + | Input::Visa + | Input::Company => { format!("COALESCE({0}::text, '') AS {0}", f.name) } _ => f.name.to_string(), @@ -841,9 +928,12 @@ fn bind_value(qb: &mut QueryBuilder<'_, Postgres>, f: &Field, v: &Values) { Input::Date => { qb.push_bind(dates::parse_date(&s)); } - Input::Money => { + Input::Money | Input::Count | Input::Year => { qb.push_bind(s.parse::().ok()); } + Input::Amount => { + qb.push_bind(s.parse::().ok()); + } Input::Passport | Input::Visa | Input::Company => { qb.push_bind(s.parse::().ok()); } @@ -935,6 +1025,7 @@ pub struct FormField { pub required: bool, pub suggest: &'static str, pub wide: bool, + pub section: &'static str, } pub fn form_fields(kind: &Kind, opts: &Options) -> Vec { @@ -950,7 +1041,8 @@ pub fn form_fields(kind: &Kind, opts: &Options) -> Vec { let (k, options) = match fl.input { Input::Date => ("date", vec![]), Input::Area => ("area", vec![]), - Input::Money => ("number", vec![]), + Input::Money | Input::Count | Input::Year => ("number", vec![]), + Input::Amount => ("text", vec![]), Input::Choice(list) => ( "select", list.iter() @@ -972,6 +1064,7 @@ pub fn form_fields(kind: &Kind, opts: &Options) -> Vec { required, suggest: fl.suggest, wide: fl.wide || fl.input == Input::Area, + section: fl.section, } }) .collect() @@ -1023,7 +1116,7 @@ pub fn shown_value(fl: &Field, raw: &str, opts: &Options) -> Part { .map(dates::fmt_date) .unwrap_or_else(|| raw.to_string()), Input::Choice(list) => label(list, raw).unwrap_or(raw).to_string(), - Input::Money => raw + Input::Money | Input::Amount => raw .parse::() .map(|n| format!("{} THB", thousands(n))) .unwrap_or_else(|_| raw.to_string()), diff --git a/src/seed.rs b/src/seed.rs index 6dd1594..0d2a2c9 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -173,6 +173,16 @@ fn companies() -> Vec { "email" => "office@demo-engineering.example", "signatory" => "Malee Jaidee", "signatory_position" => "Managing director", + "capital_thb" => "5000000", + "paid_up_thb" => "5000000", + "figures_year" => "2025", + "revenue_thb" => "48500000", + "equity_thb" => "9800000", + "foreign_costs_thb" => "2400000", + "thai_staff" => "24", + "foreign_staff" => "2", + "coordinator" => "Wanida Meechai", + "coordinator_phone" => "+66 53 000 002", "notes" => MARKER, }, vals! { @@ -236,7 +246,8 @@ fn demos(today: NaiveDate) -> Vec { vals! { "arrived_on" => plus(-394), "port" => CNX, "admission" => "visa", "visa_id" => "@visa", "permitted_until" => plus(-305), "passport_id" => "@passport", - "flight" => "TG110", "tdac_no" => "DEMO0001", "tdac_submitted_on" => plus(-396), + "flight" => "TG110", "came_from" => "Frankfurt", "tdac_no" => "DEMO0001", + "tdac_submitted_on" => plus(-396), "departed_on" => plus(-90), "departure_port" => CNX, }, ), @@ -274,6 +285,7 @@ fn demos(today: NaiveDate) -> Vec { vals! { "arrived_on" => plus(-79), "port" => CNX, "admission" => "reentry", "permitted_until" => plus(60), "passport_id" => "@passport", "flight" => "TG111", + "came_from" => "Singapore", "tdac_no" => "DEMO0002", "tdac_submitted_on" => plus(-81), }, ), @@ -282,7 +294,8 @@ fn demos(today: NaiveDate) -> Vec { vals! { "company_id" => "@employer", "number" => "WP-DEMO-0001", "position" => "Electrical engineer", "issued_on" => plus(-300), - "valid_until" => plus(60), + "valid_until" => plus(60), "monthly_salary_thb" => "95000", + "contract_from" => plus(-400), "contract_until" => plus(330), }, ), ]; @@ -322,6 +335,7 @@ fn demos(today: NaiveDate) -> Vec { vals! { "arrived_on" => plus(-40), "port" => CNX, "admission" => "exempt", "permitted_until" => plus(20), "passport_id" => "@passport", "flight" => "TG102", + "came_from" => "Bangkok", "tdac_no" => "DEMO0003", "tdac_submitted_on" => plus(-42), }, )]; @@ -382,7 +396,7 @@ fn demos(today: NaiveDate) -> Vec { &records::WORK_PERMITS, vals! { "company_id" => "@employer", "number" => "WP-DEMO-0003", "position" => "Accountant", - "issued_on" => plus(-320), "valid_until" => plus(45), + "issued_on" => plus(-320), "valid_until" => plus(45), "monthly_salary_thb" => "62000", }, ), ]; diff --git a/src/web/documents.rs b/src/web/documents.rs index 5470a04..8d257a1 100644 --- a/src/web/documents.rs +++ b/src/web/documents.rs @@ -40,7 +40,7 @@ const NOTE_LIMIT: usize = 500; /// The file responses' own policy: nothing runs; the browser's image or PDF /// viewer shows the file and may style its own page. -const FILE_CSP: &str = "default-src 'none'; img-src 'self'; object-src 'self'; \ +pub(crate) const FILE_CSP: &str = "default-src 'none'; img-src 'self'; object-src 'self'; \ style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; \ form-action 'none'"; @@ -781,7 +781,7 @@ fn download_name(whose: &str, d: &Document) -> String { } /// `inline` or `attachment` with the name in both forms (RFC 6266). -fn disposition(how: &str, name: &str) -> HeaderValue { +pub(crate) fn disposition(how: &str, name: &str) -> HeaderValue { let ascii: String = name .chars() .map(|c| { diff --git a/src/web/mod.rs b/src/web/mod.rs index 98b2b44..d309355 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -5,6 +5,7 @@ pub mod auth; pub mod companies; pub mod dashboard; pub mod documents; +pub mod papers; pub mod people; pub mod records; @@ -240,6 +241,10 @@ pub fn router(st: Arc) -> Router { // about one document, its change and its deletion. A person's documents // have their own tab; a company's are on its page. r = r.route("/people/{id}/documents", get(documents::person_tab)); + // The filled-in forms: the tab, and a form's PDF (or the extension's). + r = r + .route("/people/{id}/forms", get(papers::tab)) + .route("/people/{id}/forms/{file}", get(papers::pdf)); type OwnerOf = fn(i64) -> Owner; let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)]; for (prefix, owner) in owners { diff --git a/src/web/papers.rs b/src/web/papers.rs new file mode 100644 index 0000000..5b28716 --- /dev/null +++ b/src/web/papers.rs @@ -0,0 +1,177 @@ +//! A person's Forms tab: the Immigration Bureau's forms filled in from the +//! records, what each still lacks with a link to where it is added, and the +//! PDFs (one form, or the five of an extension in one file). What only this +//! application says comes from the tab's fields as query parameters, so a +//! link to a PDF carries it and nothing is stored. + +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 minijinja::context; +use serde::{Deserialize, Serialize}; + +use super::documents::{FILE_CSP, disposition}; +use super::people::load_person; +use super::{AppState, Res, not_found_page, page}; +use crate::audit::{self, Action, Entity, Entry}; +use crate::dates; +use crate::papers::values::{self, Application, Missing}; +use crate::papers::{self, Paper}; +use crate::session::User; + +#[derive(Debug, Serialize)] +struct FormView { + slug: &'static str, + code: &'static str, + title: &'static str, + when: &'static str, + missing: Vec, + href: String, +} + +pub async fn tab( + State(st): State>, + Extension(user): Extension, + Path(id): Path, + Query(app): Query, +) -> Res { + let (Some((_, p)), Some(facts)) = + (load_person(&st, id).await?, values::load(&st.db, id).await?) + else { + return Ok(not_found_page(&st)); + }; + let today = dates::today(); + let app = app.with_defaults(&facts, today); + let errors = app.check(); + let v = values::values(&facts, &app, today); + let q = app.query(); + let forms: Vec = papers::ALL + .iter() + .map(|&paper| FormView { + slug: paper.slug(), + code: paper.code(), + title: paper.title(), + when: paper.when(), + missing: values::missing(paper, &v, &facts), + href: format!("/people/{id}/forms/{}.pdf?{q}", paper.slug()), + }) + .collect(); + audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?; + let title = format!("Forms: {}", p.name); + let status = if errors.is_empty() { + StatusCode::OK + } else { + StatusCode::UNPROCESSABLE_ENTITY + }; + let extension_codes = papers::EXTENSION + .iter() + .map(|p| p.code()) + .collect::>() + .join(", "); + Ok(page( + &st, + &user, + "papers.html", + &title, + "people", + status, + context! { + p, + tab => "forms", + app, + errors, + forms, + extension_href => format!("/people/{id}/forms/extension.pdf?{q}"), + extension_codes, + }, + )) +} + +#[derive(Debug, Deserialize)] +pub struct PdfQuery { + #[serde(flatten)] + app: Application, + download: Option, +} + +/// One form (`tm7.pdf`) or the forms of an extension (`extension.pdf`), +/// opened in the browser or (`?download=1`) saved. +pub async fn pdf( + State(st): State>, + Extension(user): Extension, + Path((id, file)): Path<(i64, String)>, + Query(q): Query, +) -> Res { + let chosen: Vec = match file.strip_suffix(".pdf") { + Some("extension") => papers::EXTENSION.to_vec(), + Some(slug) => match Paper::from_slug(slug) { + Some(p) => vec![p], + None => return Ok(not_found_page(&st)), + }, + None => return Ok(not_found_page(&st)), + }; + let Some(facts) = values::load(&st.db, id).await? else { + return Ok(not_found_page(&st)); + }; + let today = dates::today(); + let app = q.app.with_defaults(&facts, today); + if !app.check().is_empty() { + // the tab shows what is wrong with the fields + return Ok(Redirect::to(&format!("/people/{id}/forms?{}", app.query())).into_response()); + } + let v = values::values(&facts, &app, today); + let label = if chosen.len() == 1 { + chosen[0].code().to_string() + } else { + "Extension forms".to_string() + }; + let whose = facts.person.display_name().replace(',', ""); + let name = format!("{whose} - {label} - {}.pdf", app.date); + let codes: Vec = chosen.iter().map(|p| p.code().to_string()).collect(); + let title = format!("{label}: {whose}"); + let bytes = tokio::task::spawn_blocking(move || papers::render(&chosen, &v, &title)).await??; + + let download = q.download.is_some(); + audit::record( + &st.db, + &Entry { + actor: &user.login, + action: if download { + Action::Download + } else { + Action::View + }, + entity: Entity::Form, + entity_id: None, + person_id: Some(id), + company_id: None, + fields: &codes, + }, + ) + .await?; + let how = if download { "attachment" } else { "inline" }; + let mut resp = Response::new(Body::from(bytes)); + let h = resp.headers_mut(); + h.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/pdf"), + ); + h.insert(header::CONTENT_DISPOSITION, disposition(how, &name)); + h.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, no-store"), + ); + h.insert( + header::CONTENT_SECURITY_POLICY, + HeaderValue::from_static(FILE_CSP), + ); + h.insert( + "cross-origin-resource-policy", + HeaderValue::from_static("same-origin"), + ); + Ok(resp) +} diff --git a/static/app.css b/static/app.css index 5c03cb2..b0bef9c 100644 --- a/static/app.css +++ b/static/app.css @@ -717,14 +717,14 @@ textarea.mrz { color: var(--hd); border-bottom-color: var(--accent); } -/* four tabs fit a phone */ +/* five tabs fit a phone */ @media (max-width: 560px) { .tabs { gap: 0; } .tabs a { - padding: 8px 9px; - font-size: 14px; + padding: 8px 7px; + font-size: 13.5px; } } @@ -997,6 +997,79 @@ textarea.mrz { } } +/* ---- a heading inside a form, over the whole row */ +.fsec { + grid-column: 1 / -1; + margin: 18px 0 4px; + font-size: 14.5px; + font-weight: 750; + color: var(--hd); +} +.grid > .fsec:first-child { + margin-top: 0; +} + +/* ---- the Forms tab: each form with its links and what it still lacks */ +.paper { + padding: 12px 0; + border-top: 1px solid var(--line); +} +.paper:first-of-type { + border-top: 0; + padding-top: 4px; +} +.paper-head { + display: grid; + grid-template-columns: 62px minmax(0, 1fr) auto; + gap: 8px 12px; + align-items: start; +} +.paper-code { + padding: 2px 0; + border-radius: 6px; + background: var(--accent-s); + color: var(--hd); + font-size: 13px; + font-weight: 800; + text-align: center; + white-space: nowrap; +} +.paper-go { + display: flex; + gap: 6px; +} +.paper-missing { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 12px; + margin: 8px 0 0 74px; + font-size: 13.5px; +} +.appform .grid + .fsec { + margin-top: 20px; +} +/* the forms get the wider column */ +.cols.papers { + grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); +} +@media (max-width: 1060px) { + .cols.papers { + grid-template-columns: minmax(0, 1fr); + } +} +@media (max-width: 560px) { + .paper-head { + grid-template-columns: 58px minmax(0, 1fr); + } + .paper-go { + grid-column: 2; + } + .paper-missing { + margin-left: 70px; + } +} + /* the list runs to the card's edges */ .tblwrap.bleed { margin: 0 -20px -18px; diff --git a/templates/_person_head.html b/templates/_person_head.html index 3d44e84..4193f5d 100644 --- a/templates/_person_head.html +++ b/templates/_person_head.html @@ -19,9 +19,10 @@ {%- if p.employer %}·{{ p.employer }}{% endif %}

diff --git a/templates/company.html b/templates/company.html index be17286..9e5d362 100644 --- a/templates/company.html +++ b/templates/company.html @@ -36,6 +36,16 @@
Authorized director
{% if c.signatory %}{{ c.signatory }}{% if c.signatory_position %}, {{ c.signatory_position }}{% endif %}{% else %}not recorded{% endif %}
{% if c.notes %}
Notes
{{ c.notes }}
{% endif %} +

For the forms

+ {%- if c.figures %} +
+ {%- for f in c.figures %} +
{{ f[0] }}
{{ f[1] }}
+ {%- endfor %} +
+ {%- else %} +

The employer's certificate (STM.1) states the capital, the latest revenue and equity, and the staff; STM.11 names a coordinator. Add them.

+ {%- endif %}

People employed

{% if employees %}In the people list{% endif %}
diff --git a/templates/papers.html b/templates/papers.html new file mode 100644 index 0000000..511db67 --- /dev/null +++ b/templates/papers.html @@ -0,0 +1,52 @@ +{% extends "base.html" %} +{% import "_fields.html" as fm %} +{% block main %} +{% include "_person_head.html" %} +
+
+

Forms

The extension's five forms
+

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

+ {%- for f in forms %} +
+
+ {{ f.code }} +
{{ f.title }}
{{ f.when }}
+ +
+ {%- if f.missing %} +

Still blank{% for m in f.missing %}{{ m.what }}{% endfor %}

+ {%- else %} +

Complete

+ {%- endif %} +
+ {%- endfor %} +
+
+

This application

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

What the records cannot say. The forms take these values once you click Use these.

+
+ {{ fm.text("date", "Date on the forms", app.date, err=errors.date, type="date", req=true) }} + {{ fm.text("at", "Written at", app.at, err=errors.at, hint="The office the forms go 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, 30 for a tourist.") }} + {{ fm.text("nth", "Which yearly extension", app.nth, err=errors.nth, type="number", hint="STM.11 asks: 1 for the first.") }} +
+

A trip abroad, for TM.8

+
+ {{ fm.select("entries", "Re-entry permit", app.entries, [("single", "Single entry"), ("multiple", "Multiple entries")], err=errors.entries, blank="Choose") }} + {{ fm.text("to", "Travelling to", app.to, err=errors.to, ph="Germany") }} + {{ fm.text("leave", "Leaving on", app.leave, err=errors.leave, type="date") }} + {{ fm.text("return", "Back about", app.back, err=errors["return"], type="date") }} + {{ fm.text("by", "Travelling by", app.by, err=errors.by) }} + {{ fm.text("for", "Purpose", app.purpose, err=errors["for"]) }} +
+
+
+
+
+{% endblock %} diff --git a/templates/record_form.html b/templates/record_form.html index 029acfa..db8033d 100644 --- a/templates/record_form.html +++ b/templates/record_form.html @@ -14,6 +14,9 @@ {% if lead %}

{{ lead }}

{% endif %}
{%- for fl in fields %} + {%- if fl.section %} +

{{ fl.section }}

+ {%- endif %} {%- if fl.kind == "area" %} {{ fm.area(fl.name, fl.label, values[fl.name], err=errors[fl.name], hint=fl.hint, rows=3, fcls="wide") }} {%- elif fl.kind == "select" %} diff --git a/tests/companies.rs b/tests/companies.rs index dbefe6a..5e33c42 100644 --- a/tests/companies.rs +++ b/tests/companies.rs @@ -336,3 +336,74 @@ async fn the_office_position_is_read_from_what_people_paste(pool: PgPool) { let page = app.get(&format!("/companies/{id}")).await.text(); assert!(page.contains("Add the GPS position"), "{page}"); } + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_employer_s_figures_are_checked(pool: PgPool) { + let app = local(pool.clone()); + let name = ("name", "Test Works Co., Ltd."); + let r = app + .post( + "/companies", + &[ + name, + ("capital_thb", "1,000,000"), + ("paid_up_thb", "2,000,000"), + ("revenue_thb", "-5"), + ("thai_staff", "many"), + ("figures_year", "1800"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + let t = r.text(); + for msg in [ + "The paid-up capital is at most the registered capital.", + "Enter an amount of zero or more.", + "Enter a number of people, such as 12.", + "Enter the year, such as 2025.", + ] { + assert!(t.contains(msg), "{msg}: {t}"); + } + // the section headings of the form + assert!(t.contains("For the employer's certificate (STM.1)")); + + // a Thai year becomes the Western one; a loss leaves the equity below zero + let r = app + .post( + "/companies", + &[ + name, + ("capital_thb", "2,000,000"), + ("paid_up_thb", "2000000"), + ("figures_year", "2568"), + ("equity_thb", "-150,000"), + ("thai_staff", "4"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + let id = company_from(r.location()); + let row: (Option, Option, Option, Option) = sqlx::query_as( + "SELECT capital_thb, figures_year, equity_thb, thai_staff FROM companies WHERE id = $1", + ) + .bind(id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(row, (Some(2_000_000), Some(2025), Some(-150_000), Some(4))); + + // the company's page lists them for the forms + let t = app.get(&format!("/companies/{id}")).await.text(); + for shown in ["For the forms", "2,000,000 THB", "-150,000 THB", "2025"] { + assert!(t.contains(shown), "{shown}: {t}"); + } + assert!(!t.contains("Add them"), "{t}"); + // a company without them is asked for them + let r = app.post("/companies", &[("name", "Plain Co., Ltd.")]).await; + let plain = company_from(r.location()); + let t = app.get(&format!("/companies/{plain}")).await.text(); + assert!( + t.contains(&format!("/companies/{plain}/edit#f-capital_thb")), + "{t}" + ); +} diff --git a/tests/main.rs b/tests/main.rs index 07244c7..5c3fb0f 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -8,6 +8,7 @@ mod companies; mod deadlines; mod documents; mod pages; +mod papers; mod people; mod records; diff --git a/tests/pages.rs b/tests/pages.rs index f95ceed..b5848b6 100644 --- a/tests/pages.rs +++ b/tests/pages.rs @@ -135,6 +135,10 @@ async fn every_page_renders_with_demo_data(pool: PgPool) { format!("/companies/{company}/documents/{company_doc}/edit"), "About the document".to_string(), ), + ( + format!("/people/{erika}/forms"), + "This application".to_string(), + ), ]; for kind in visa::records::STAY { pages.push(( diff --git a/tests/papers.rs b/tests/papers.rs new file mode 100644 index 0000000..a59b53d --- /dev/null +++ b/tests/papers.rs @@ -0,0 +1,220 @@ +//! The Forms tab: the Immigration Bureau's forms filled in from the records, +//! what each still lacks, the PDFs and their audit entries. + +use axum::http::StatusCode; +use sqlx::PgPool; +use visa::papers::values::{self, Application}; + +use crate::common::local; + +async fn erika(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT id FROM people WHERE surname = 'Mustermann'") + .fetch_one(pool) + .await + .unwrap() +} + +fn pages(pdf: &[u8]) -> usize { + krilla::pdf::Pdf::new(pdf.to_vec()).unwrap().pages().len() +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_values_come_from_the_records(pool: PgPool) { + let today = visa::dates::today(); + visa::seed::demo(&pool, today).await.unwrap(); + let id = erika(&pool).await; + let facts = values::load(&pool, id).await.unwrap().unwrap(); + let app = Application::default().with_defaults(&facts, today); + assert_eq!( + app.reason, + "To continue working for Demo Engineering Co., Ltd. as Electrical engineer" + ); + assert_eq!((app.days.as_str(), app.entries.as_str()), ("365", "single")); + let v = values::values(&facts, &app, today); + let plus = |days: i64| today + chrono::TimeDelta::days(days); + let expect = [ + ("family_name", "MUSTERMANN".to_string()), + ("first_name", "ERIKA".to_string()), + ("full_name", "ERIKA MUSTERMANN".to_string()), + ("title", "Ms".to_string()), + ("nationality", "GERMANY".to_string()), + ("birth_place", "BERLIN".to_string()), + ("birth_month", "AUGUST".to_string()), + ("passport_no", "C01X00T47".to_string()), + ("passport_issued_at", "STADT KOELN".to_string()), + ("passport_expiry_year", "2031".to_string()), + ("visa_type", "NON-IMMIGRANT B".to_string()), + ("visa_kind", "non-immigrant".to_string()), + ("visa_issued_at", "ROYAL THAI EMBASSY, BERLIN".to_string()), + // the last arrival: back from a trip on the re-entry permit + ("arrived_by", "TG111".to_string()), + ("arrived_from", "SINGAPORE".to_string()), + ( + "arrival_port", + "CHIANG MAI INTERNATIONAL AIRPORT".to_string(), + ), + ( + "permitted_day", + chrono::Datelike::day(&plus(60)).to_string(), + ), + ("position", "ELECTRICAL ENGINEER".to_string()), + ("salary", "95,000".to_string()), + ("company_name", "DEMO ENGINEERING CO., LTD.".to_string()), + ("company_capital", "5,000,000".to_string()), + ("revenue", "48,500,000".to_string()), + ("figures_year", "2025".to_string()), + ("thai_staff", "24".to_string()), + ("coordinator", "WANIDA MEECHAI".to_string()), + ("days", "365".to_string()), + ( + "reason_short", + "WORKING AT DEMO ENGINEERING CO., LTD.".to_string(), + ), + ( + "company_written_at", + "DEMO ENGINEERING CO., LTD.".to_string(), + ), + ("road", "SOI 7, HUAY KAEW ROAD".to_string()), + ("extension_nth", "2".to_string()), + ]; + for (key, want) in expect { + assert_eq!(v.get(key), Some(&want), "{key}"); + } + // nothing is missing for an extension but the employer's certificate + // date, which only the company's documents give + for paper in visa::papers::EXTENSION { + let lacks: Vec<&str> = values::missing(paper, &v, &facts) + .iter() + .map(|m| m.what) + .collect(); + if paper == visa::papers::Paper::Stm1 { + assert_eq!( + lacks, + ["The employer's company certificate, uploaded with its date"], + "{}", + paper.code() + ); + } else { + assert!(lacks.is_empty(), "{}: {lacks:?}", paper.code()); + } + } +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_forms_tab_lists_the_forms_and_what_they_lack(pool: PgPool) { + let today = visa::dates::today(); + visa::seed::demo(&pool, today).await.unwrap(); + let app = local(pool.clone()); + let id = erika(&pool).await; + let r = app.get(&format!("/people/{id}/forms")).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let t = r.text(); + for code in ["TM.7", "STM.2", "STM.9", "STM.11", "STM.1", "TM.47", "TM.8"] { + assert!(t.contains(code), "{code}"); + } + assert!(t.contains( + "value=\"To continue working for Demo Engineering Co., Ltd. as Electrical engineer\"" + )); + assert!( + t.contains(&format!("/people/{id}/forms/tm7.pdf?date={today}")), + "{t}" + ); + // the trip is still blank on TM.8, and the certificate's date on STM.1 + let tm8 = &t[t.find("id=\"form-tm8\"").unwrap()..]; + assert!(tm8.contains("The trip"), "{tm8}"); + let stm1 = &t[t.find("id=\"form-stm1\"").unwrap()..t.find("id=\"form-tm47\"").unwrap()]; + assert!(stm1.contains("company certificate"), "{stm1}"); + assert!( + stm1.contains("#documents"), + "the link goes to the company's documents" + ); + + // with the trip, TM.8 is complete and its link carries the trip + let r = app + .get(&format!( + "/people/{id}/forms?to=Germany&leave=2027-01-05&return=2027-01-20&entries=multiple" + )) + .await; + assert_eq!(r.status, StatusCode::OK); + let t = r.text(); + let tm8 = &t[t.find("id=\"form-tm8\"").unwrap()..]; + assert!(tm8.contains("Complete"), "{tm8}"); + assert!(tm8.contains("to=Germany"), "{tm8}"); + + // wrong values are marked on the tab; a PDF with them goes back there + let r = app + .get(&format!("/people/{id}/forms?date=202611-18&days=many")) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!( + r.text().contains("Enter the number of days"), + "{}", + r.text() + ); + let r = app + .get(&format!("/people/{id}/forms/tm7.pdf?days=many")) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert!(r.location().starts_with(&format!("/people/{id}/forms?"))); +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn a_form_is_the_official_pages_filled_in_and_audited(pool: PgPool) { + let today = visa::dates::today(); + visa::seed::demo(&pool, today).await.unwrap(); + let app = local(pool.clone()); + let id = erika(&pool).await; + + let r = app.get(&format!("/people/{id}/forms/tm7.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").starts_with("inline;")); + assert!( + r.header("content-disposition") + .contains(&format!("MUSTERMANN Erika - TM.7 - {today}.pdf")), + "{}", + r.header("content-disposition") + ); + assert_eq!(pages(&r.bytes), 2, "TM.7 has two pages"); + + let r = app + .get(&format!("/people/{id}/forms/extension.pdf?download=1")) + .await; + assert_eq!(r.status, StatusCode::OK); + assert!(r.header("content-disposition").starts_with("attachment;")); + assert_eq!(pages(&r.bytes), 6, "TM.7, STM.2, STM.9, STM.11 and STM.1"); + let r = app.get(&format!("/people/{id}/forms/tm8.pdf")).await; + assert_eq!(pages(&r.bytes), 2); + + // what was opened and saved, by whom; the form's values are not logged + let rows: Vec<(String, Vec)> = sqlx::query_as( + "SELECT action, fields FROM audit_log WHERE entity = 'form' AND person_id = $1 ORDER BY id", + ) + .bind(id) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!( + rows, + [ + ("view".to_string(), vec!["TM.7".to_string()]), + ( + "download".to_string(), + ["TM.7", "STM.2", "STM.9", "STM.11", "STM.1"] + .map(String::from) + .to_vec() + ), + ("view".to_string(), vec!["TM.8".to_string()]), + ] + ); + let t = app.get(&format!("/activity?person={id}")).await.text(); + assert!(t.contains("TM.7, STM.2, STM.9, STM.11, STM.1"), "{t}"); + + for bad in ["tm99.pdf", "tm7", "extension.txt"] { + let r = app.get(&format!("/people/{id}/forms/{bad}")).await; + assert_eq!(r.status, StatusCode::NOT_FOUND, "{bad}"); + } + let r = app.get("/people/999999/forms/tm7.pdf").await; + assert_eq!(r.status, StatusCode::NOT_FOUND); +}