Phase 2: companies, stay records, deadlines
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 22s

Companies become records of their own, and the stay in Thailand is
recorded in full; from these records the app works out each person's
deadlines (docs/PLAN.md, phase 2).

- Companies: list, page, form, archive; Thai name, the 13-digit
  registration number with its check digit verified, address and the
  director who signs. The employer is chosen from them on the person form
  and on work permits; a company's page adds people to it; the people
  list and the Deadlines page filter by employer. Migration 0002 turns
  the free-text employers into companies.
- Stay records, each one `Kind` in src/records.rs with one form, one set
  of routes and the same audit entries: arrivals and departures with the
  TDAC, extensions of stay (approved, under consideration, refused),
  90-day reports with the receipt's next date, visas, re-entry permits and
  work permits. Passports, visas and companies are chosen from the
  person's own records; the server checks the choice.
- The deadline engine (src/deadlines.rs, a pure function with a unit
  test per rule): the 90-day report from day 1 of each arrival, reset by
  a report or an extension, with the in-person and online windows and the
  in-person rule after a new passport or an extension; the extension
  window from 30 days before to the last working day; the decision to
  collect; overstay with its fine; TM.30 after each arrival; passport and
  work permit expiry; re-entry permits; visas still to be used.
- The Deadlines page at /, the person's status and deadlines on the
  Overview and the new "Visa and stay" tab, the person's Activity tab,
  and the next deadline in the people list.
- The online 90-day window ends 7 days before the due date (the plan
  said 8; the Immigration Bureau's TM.47 manual says 7).
- 69 tests: 45 unit tests and 24 integration tests.
This commit is contained in:
grabowski committed 2026-11-17 18:20:14 +07:00
1 parent 2e009700a9
commit 83bc481952
37 files changed
+5515 -142

No files matched your search

+318 -44
View File
@@ -1,15 +1,17 @@
//! Demo data for development: invented people only (specimen names, numbers
//! that belong to nobody). `visa seed-demo` refuses to run when the login is
//! on, so it never writes into production.
//! Demo data for development: invented people and companies only (specimen
//! names, numbers that belong to nobody). `visa seed-demo` refuses to run
//! when the login is on, so it never writes into production. The dates are
//! relative to the day it runs, so every kind of deadline shows.
use anyhow::Result;
use chrono::NaiveDate;
use chrono::{NaiveDate, TimeDelta};
use sqlx::PgPool;
use crate::audit::{self, Action, Entity, Entry};
use crate::dates;
use crate::mrz;
use crate::people::{self, AddressInput, PassportInput, PersonInput};
use crate::records::{self, Kind, Values};
pub const MARKER: &str = "Demo record, invented for development.";
@@ -17,10 +19,23 @@ fn d(s: &str) -> NaiveDate {
dates::parse_date(s).expect("demo dates are valid")
}
/// A record's values; `"@passport"`, `"@visa"` and `"@employer"` stand for
/// the person's current passport, the visa recorded last and the employer.
macro_rules! vals {
($($k:literal => $v:expr),* $(,)?) => {{
let mut m = Values::new();
$( m.insert($k.to_string(), $v.to_string()); )*
m
}};
}
struct Demo {
person: PersonInput,
/// An index into `companies()`.
employer: Option<usize>,
passports: Vec<PassportInput>,
addresses: Vec<AddressInput>,
stays: Vec<(&'static Kind, Values)>,
archived: bool,
}
@@ -35,7 +50,6 @@ fn person(
place: &str,
nationality: &str,
occupation: &str,
employer: &str,
n: u32,
) -> PersonInput {
PersonInput {
@@ -48,7 +62,7 @@ fn person(
place_of_birth: place.into(),
nationality: nationality.into(),
occupation: occupation.into(),
employer: employer.into(),
employer: None,
phone: format!("+66 80 000 000{n}"),
email: format!(
"{}.{}@example.com",
@@ -72,21 +86,19 @@ fn passport(
} else {
format!("{} {}", p.first_name, p.middle_name)
};
// Germany's code in the zone is D
let state = if p.nationality == "DEU" {
"D"
} else {
p.nationality.as_str()
};
let mrz = if with_mrz {
mrz::compose(&mrz::Compose {
issuing_state: if p.nationality == "DEU" {
"D"
} else {
p.nationality.as_str()
},
issuing_state: state,
surname: &p.surname,
given_names: &given,
number,
nationality: if p.nationality == "DEU" {
"D"
} else {
p.nationality.as_str()
},
nationality: state,
date_of_birth: p.date_of_birth.expect("demo people have birth dates"),
sex: &p.sex,
expiry_date: d(expires),
@@ -138,11 +150,55 @@ fn address(
}
}
/// Two invented companies; their registration numbers carry valid check
/// digits but no real company has them (province code 99 does not exist).
fn companies() -> Vec<Values> {
vec![
vals! {
"name" => "Demo Engineering Co., Ltd.",
"name_th" => "บริษัท เดโม เอ็นจิเนียริ่ง จำกัด",
"registration_no" => "0999999000004",
"business" => "Engineering services",
"house_no" => "88/8",
"building" => "Demo Tower, fifth floor",
"road" => "Superhighway Road",
"subdistrict" => "Wat Ket",
"district" => "Mueang Chiang Mai",
"province" => "Chiang Mai",
"postal_code" => "50000",
"phone" => "+66 53 000 000",
"email" => "office@demo-engineering.example",
"signatory" => "Malee Jaidee",
"signatory_position" => "Managing director",
"notes" => MARKER,
},
vals! {
"name" => "Demo Accounting Partnership",
"name_th" => "ห้างหุ้นส่วนจำกัด เดโม แอคเคาน์ติ้ง",
"registration_no" => "0999999000012",
"business" => "Accounting",
"house_no" => "55",
"moo" => "2",
"subdistrict" => "Ban Klang",
"district" => "Mueang Lamphun",
"province" => "Lamphun",
"postal_code" => "51000",
"phone" => "+66 53 000 001",
"signatory" => "Prasert Jaidee",
"signatory_position" => "Managing partner",
"notes" => MARKER,
},
]
}
/// Dates relative to `today`, so the warnings show whenever the seed runs.
fn demos(today: NaiveDate) -> Vec<Demo> {
let plus = |days: i64| (today + chrono::TimeDelta::days(days)).to_string();
let employer = "Demo Engineering Co., Ltd.";
let plus = |days: i64| (today + TimeDelta::days(days)).to_string();
const CNX: &str = "Chiang Mai International Airport";
const OFFICE: &str = "Chiang Mai Immigration Office";
// Non-B with a work permit, back from a trip on a re-entry permit: the
// 90-day report is due in ten days, the extension window opens in 30.
let erika = person(
"Mustermann",
"Erika",
@@ -153,7 +209,6 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Berlin",
"DEU",
"Electrical engineer",
employer,
1,
);
let erika_pp = passport(
@@ -164,6 +219,73 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Stadt Koeln",
true,
);
let erika_stays = vec![
(
&records::VISAS,
vals! {
"category" => "non-b", "entries" => "single", "number" => "V0000101",
"passport_id" => "@passport", "issued_at" => "Royal Thai Embassy, Berlin",
"issued_on" => plus(-440), "valid_until" => plus(-350),
},
),
(
&records::ARRIVALS,
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),
"departed_on" => plus(-90), "departure_port" => CNX,
},
),
(
&records::EXTENSIONS,
vals! {
"applied_on" => plus(-310), "basis" => "work", "decision" => "approved",
"permitted_until" => plus(60), "office" => OFFICE, "receipt_no" => "DEMO-R-0101",
"fee_thb" => "1900",
},
),
(
&records::REPORTS,
vals! {
"reported_on" => plus(-222), "method" => "in-person",
"receipt_no" => "DEMO-90-0001", "next_due_on" => plus(-132),
},
),
(
&records::REPORTS,
vals! {
"reported_on" => plus(-135), "method" => "online",
"receipt_no" => "DEMO-90-0002", "next_due_on" => plus(-45),
},
),
(
&records::REENTRY_PERMITS,
vals! {
"kind" => "multiple", "number" => "DEMO-RE-0001", "issued_on" => plus(-300),
"valid_until" => plus(60), "office" => OFFICE,
},
),
(
&records::ARRIVALS,
vals! {
"arrived_on" => plus(-79), "port" => CNX, "admission" => "reentry",
"permitted_until" => plus(60), "passport_id" => "@passport", "flight" => "TG111",
"tdac_no" => "DEMO0002", "tdac_submitted_on" => plus(-81),
},
),
(
&records::WORK_PERMITS,
vals! {
"company_id" => "@employer", "number" => "WP-DEMO-0001",
"position" => "Electrical engineer", "issued_on" => plus(-300),
"valid_until" => plus(60),
},
),
];
// Visa exemption for 60 days, starting at the company: the extension
// window is open, the passport has under six months, no TM.30 yet.
let jane = person(
"Doe",
"Jane",
@@ -174,7 +296,6 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Portland, Oregon",
"USA",
"Product designer",
employer,
2,
);
let jane_old = passport(
@@ -193,6 +314,16 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"U.S. Department of State",
true,
);
let jane_stays = vec![(
&records::ARRIVALS,
vals! {
"arrived_on" => plus(-40), "port" => CNX, "admission" => "exempt",
"permitted_until" => plus(20), "passport_id" => "@passport", "flight" => "TG102",
"tdac_no" => "DEMO0003", "tdac_submitted_on" => plus(-42),
},
)];
// Married to a Thai national, extended twice: the 90-day report is late.
let tomas = person(
"Novak",
"Tomas",
@@ -203,10 +334,86 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Brno",
"CZE",
"Accountant",
"Demo Accounting Partnership",
3,
);
let tomas_pp = passport(&tomas, "40000001", "2018-01-15", &plus(300), "Brno", true);
let tomas_stays = vec![
(
&records::VISAS,
vals! {
"category" => "non-o", "entries" => "single", "number" => "V0000303",
"passport_id" => "@passport", "issued_at" => "Royal Thai Embassy, Prague",
"issued_on" => plus(-800), "valid_until" => plus(-710),
},
),
(
&records::ARRIVALS,
vals! {
"arrived_on" => plus(-760), "port" => "Suvarnabhumi Airport", "admission" => "visa",
"visa_id" => "@visa", "permitted_until" => plus(-671), "passport_id" => "@passport",
},
),
(
&records::EXTENSIONS,
vals! {
"applied_on" => plus(-680), "basis" => "marriage", "decision" => "approved",
"permitted_until" => plus(-306), "office" => OFFICE, "fee_thb" => "1900",
},
),
(
&records::EXTENSIONS,
vals! {
"applied_on" => plus(-320), "basis" => "marriage", "decision" => "approved",
"permitted_until" => plus(45), "office" => OFFICE, "receipt_no" => "DEMO-R-0303",
"fee_thb" => "1900",
},
),
(
&records::REPORTS,
vals! {
"reported_on" => plus(-101), "method" => "agent",
"receipt_no" => "DEMO-90-0303", "next_due_on" => plus(-11),
},
),
(
&records::WORK_PERMITS,
vals! {
"company_id" => "@employer", "number" => "WP-DEMO-0003", "position" => "Accountant",
"issued_on" => plus(-320), "valid_until" => plus(45),
},
),
];
// Hired, still abroad: the visa has to be used within 70 days.
let sofia = person(
"Ejemplo",
"Sofia",
"",
"Ms",
"F",
"1993-04-21",
"Valencia",
"ESP",
"Project engineer",
5,
);
let sofia_pp = passport(
&sofia,
"XDE000505",
"2023-06-01",
"2033-05-31",
"Valencia",
true,
);
let sofia_stays = vec![(
&records::VISAS,
vals! {
"category" => "non-b", "entries" => "single", "number" => "V0000505",
"passport_id" => "@passport", "issued_at" => "e-Visa",
"issued_on" => plus(-20), "valid_until" => plus(70),
},
)];
let old = person(
"Sample",
"Oliver",
@@ -217,7 +424,6 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Leeds",
"GBR",
"Retired",
"",
4,
);
let old_pp = passport(&old, "100000001", "2014-01-10", "2024-01-10", "HMPO", false);
@@ -225,6 +431,7 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
vec![
Demo {
person: erika,
employer: Some(0),
passports: vec![erika_pp],
addresses: vec![
address(
@@ -237,9 +444,9 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Mueang Chiang Mai",
"Chiang Mai",
"50200",
"2025-06-01",
Some("2026-02-28"),
Some(("2025-06-02", "TM30-DEMO-0007")),
&plus(-900),
Some(&plus(-500)),
Some((&plus(-899), "TM30-DEMO-0007")),
),
address(
"99/9",
@@ -251,15 +458,17 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Mueang Chiang Mai",
"Chiang Mai",
"50300",
"2026-03-01",
&plus(-500),
None,
Some(("2026-03-02", "TM30-DEMO-0012")),
Some((&plus(-78), "TM30-DEMO-0012")),
),
],
stays: erika_stays,
archived: false,
},
Demo {
person: jane,
employer: Some(0),
passports: vec![jane_old, jane_pp],
addresses: vec![address(
"1/23",
@@ -271,14 +480,16 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Mueang Chiang Mai",
"Chiang Mai",
"50300",
"2026-09-15",
&plus(-38),
None,
None,
)],
stays: jane_stays,
archived: false,
},
Demo {
person: tomas,
employer: Some(1),
passports: vec![tomas_pp],
addresses: vec![address(
"55",
@@ -290,22 +501,45 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
"Mueang Lamphun",
"Lamphun",
"51000",
"2024-11-01",
&plus(-700),
None,
Some(("2024-11-01", "TM30-DEMO-0003")),
Some((&plus(-700), "TM30-DEMO-0003")),
)],
stays: tomas_stays,
archived: false,
},
Demo {
person: sofia,
employer: Some(0),
passports: vec![sofia_pp],
addresses: vec![],
stays: sofia_stays,
archived: false,
},
Demo {
person: old,
employer: None,
passports: vec![old_pp],
addresses: vec![],
stays: vec![],
archived: true,
},
]
}
/// Adds the demo people unless they are there already; true when it did.
fn seeded(action: Action, entity: Entity, id: i64, person: Option<i64>) -> Entry<'static> {
Entry {
actor: "seed",
action,
entity,
entity_id: Some(id),
person_id: person,
fields: &[],
}
}
/// Adds the demo companies and people unless they are there already; true
/// when it did.
pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
let present: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM people WHERE notes = $1)")
.bind(MARKER)
@@ -315,28 +549,68 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
return Ok(false);
}
let mut tx = db.begin().await?;
let log = |action, entity, id, person| Entry {
actor: "seed",
action,
entity,
entity_id: Some(id),
person_id: Some(person),
fields: &[],
};
for demo in demos(today) {
let mut company_ids = Vec::new();
for c in companies() {
let id = records::create(&mut tx, &records::COMPANIES, None, &c).await?;
audit::record(&mut *tx, &seeded(Action::Create, Entity::Company, id, None)).await?;
company_ids.push(id);
}
for mut demo in demos(today) {
demo.person.employer = demo.employer.map(|i| company_ids[i]);
let id = people::create_person(&mut tx, &demo.person).await?;
audit::record(&mut *tx, &log(Action::Create, Entity::Person, id, id)).await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Person, id, Some(id)),
)
.await?;
let mut current: Option<(NaiveDate, i64)> = None;
for p in &demo.passports {
let pid = people::create_passport(&mut tx, id, p).await?;
audit::record(&mut *tx, &log(Action::Create, Entity::Passport, pid, id)).await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Passport, pid, Some(id)),
)
.await?;
if current.is_none_or(|(e, _)| p.expires_on > e) {
current = Some((p.expires_on, pid));
}
}
for a in &demo.addresses {
let aid = people::create_address(&mut tx, id, a).await?;
audit::record(&mut *tx, &log(Action::Create, Entity::Address, aid, id)).await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Address, aid, Some(id)),
)
.await?;
}
let mut last_visa: Option<i64> = None;
for (kind, mut values) in demo.stays {
for v in values.values_mut() {
let id_of = |x: Option<i64>| x.map(|i| i.to_string()).unwrap_or_default();
match v.as_str() {
"@passport" => *v = id_of(current.map(|c| c.1)),
"@visa" => *v = id_of(last_visa),
"@employer" => *v = id_of(demo.person.employer),
_ => {}
}
}
let rid = records::create(&mut tx, kind, Some(id), &values).await?;
if kind.slug == records::VISAS.slug {
last_visa = Some(rid);
}
audit::record(
&mut *tx,
&seeded(Action::Create, kind.entity, rid, Some(id)),
)
.await?;
}
if demo.archived {
people::set_archived(&mut tx, id, true).await?;
audit::record(&mut *tx, &log(Action::Archive, Entity::Person, id, id)).await?;
audit::record(
&mut *tx,
&seeded(Action::Archive, Entity::Person, id, Some(id)),
)
.await?;
}
}
tx.commit().await?;