Phase 5: the Immigration Bureau's forms, filled in from the records
A Forms tab on each person fills in 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. The Bureau's blank pages (forms/, with their sources and checksums) go unchanged into a new PDF, and the values are written on the dotted lines in Sarabun; boxes are ticked and the title circled where a form asks. scripts/gen_layout.py measures the blanks into src/papers/layout.rs. The tab says what would stay blank and links to where it is added. What only the application says (the date, the office, the reason, the days, a trip) is carried in the links and never stored. The extension's five forms also come in one PDF. Opening or downloading a form is audited as entity "form" with the forms' codes, never their values. Migration 0005 adds what STM.1 and STM.11 ask of the company (capital, revenue, equity, staff, a coordinator), a work permit's salary and contract dates, and where an arrival came from. The Nix package now takes forms/.
This commit is contained in:
1 parent
2a6e972b68
commit
a2cedcdd7e
40 files changed
+3404
-35
No files matched your search
@@ -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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+34
-1
@@ -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::<i64>() {
|
||||
Ok(n) if *baht => format!("{} THB", records::thousands(n)),
|
||||
_ => raw.to_string(),
|
||||
};
|
||||
(*label, value)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn view(r: &Record, archived_at: Option<DateTime<Utc>>) -> 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<DateTime<Utc>>) -> 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()))
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
];
|
||||
@@ -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<Paper> {
|
||||
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<f32> = 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<Vec<u8>> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<Passport>,
|
||||
/// The address the person has not moved out of, the latest moved into.
|
||||
pub address: Option<Address>,
|
||||
pub arrival: Option<Record>,
|
||||
/// The visa of the last arrival, or the latest visa.
|
||||
pub visa: Option<Record>,
|
||||
/// The end of the permission to stay: the last arrival's stamp or a
|
||||
/// later extension's.
|
||||
pub permitted_until: Option<NaiveDate>,
|
||||
/// Extensions approved so far.
|
||||
pub extensions: usize,
|
||||
pub work_permit: Option<Record>,
|
||||
/// The employer on the work permit, else the person's employer.
|
||||
pub company: Option<Record>,
|
||||
/// The date of the newest company certificate among its documents.
|
||||
pub certificate_on: Option<NaiveDate>,
|
||||
}
|
||||
|
||||
pub async fn load(db: &PgPool, id: i64) -> Result<Option<Facts>> {
|
||||
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::<i64>().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::<u32>(), Ok(1..=999)) {
|
||||
err(&mut e, "days", "Enter the number of days, such as 365.");
|
||||
}
|
||||
if !matches!(self.nth.parse::<u32>(), 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<NaiveDate>) {
|
||||
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::<i64>()
|
||||
.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::<Vec<_>>()
|
||||
.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<Missing> {
|
||||
let mut out: Vec<Missing> = 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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+104
-11
@@ -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 `<datalist>` 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::<i64>().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::<i32>() {
|
||||
// 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::<i64>() {
|
||||
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::<i32>() {
|
||||
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::<i32>() {
|
||||
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::<i32>().ok());
|
||||
}
|
||||
Input::Amount => {
|
||||
qb.push_bind(s.parse::<i64>().ok());
|
||||
}
|
||||
Input::Passport | Input::Visa | Input::Company => {
|
||||
qb.push_bind(s.parse::<i64>().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<FormField> {
|
||||
@@ -950,7 +1041,8 @@ pub fn form_fields(kind: &Kind, opts: &Options) -> Vec<FormField> {
|
||||
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<FormField> {
|
||||
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::<i64>()
|
||||
.map(|n| format!("{} THB", thousands(n)))
|
||||
.unwrap_or_else(|_| raw.to_string()),
|
||||
|
||||
+17
-3
@@ -173,6 +173,16 @@ fn companies() -> Vec<Values> {
|
||||
"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<Demo> {
|
||||
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<Demo> {
|
||||
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<Demo> {
|
||||
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<Demo> {
|
||||
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<Demo> {
|
||||
&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",
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -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<AppState>) -> 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 {
|
||||
|
||||
@@ -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<Missing>,
|
||||
href: String,
|
||||
}
|
||||
|
||||
pub async fn tab(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Query(app): Query<Application>,
|
||||
) -> Res {
|
||||
let (Some((_, p)), Some(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<FormView> = 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::<Vec<_>>()
|
||||
.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<String>,
|
||||
}
|
||||
|
||||
/// 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, file)): Path<(i64, String)>,
|
||||
Query(q): Query<PdfQuery>,
|
||||
) -> Res {
|
||||
let chosen: Vec<Paper> = 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<String> = 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)
|
||||
}
|
||||
Reference in new issue
Block a user