//! Deadlines from a person's records: the next 90-day report and its //! windows, the window for the next extension of stay, a decision to collect, //! overstay, the passport's and the work permit's expiry, TM.30, re-entry //! permits and the TDAC. The rules and their sources are in docs/PLAN.md //! ("Deadline rules"). `assess` is a pure function of the records and the //! day, so the tests below pin each rule. A date from a receipt or a stamp //! wins over a calculated one, and a calculated date is marked an estimate. use std::collections::HashMap; use anyhow::Result; use chrono::{Datelike, NaiveDate, TimeDelta, Weekday}; use serde::Serialize; use sqlx::PgPool; use crate::dates; use crate::records; /// The TDAC replaced the paper arrival card (TM.6) for arrivals from this day. fn tdac_start() -> NaiveDate { NaiveDate::from_ymd_opt(2025, 5, 1).expect("a valid date") } #[derive(Clone, Debug, Default)] pub struct Facts { pub passports: Vec, pub visas: Vec, /// In the order of arrival. pub arrivals: Vec, /// In the order of application. pub extensions: Vec, pub reports: Vec, /// The valid-until dates of re-entry permits. pub reentry_permits: Vec, /// The valid-until dates of work permits. pub work_permits: Vec, /// The current address in Thailand. pub address: Option, } #[derive(Clone, Debug)] pub struct PassportFact { pub issued_on: Option, pub expires_on: NaiveDate, } #[derive(Clone, Debug)] pub struct VisaFact { pub category: String, pub valid_until: NaiveDate, } #[derive(Clone, Debug)] pub struct ArrivalFact { pub arrived_on: NaiveDate, pub permitted_until: NaiveDate, pub departed_on: Option, pub admission: String, /// The category of the visa used, if one is linked. pub visa_category: Option, pub tdac_no: String, } #[derive(Clone, Debug)] pub struct ExtensionFact { pub applied_on: NaiveDate, pub basis: String, pub decision: String, pub permitted_until: Option, pub office: String, } #[derive(Clone, Debug)] pub struct ReportFact { pub reported_on: NaiveDate, pub next_due_on: Option, } #[derive(Clone, Debug)] pub struct AddressFact { pub moved_in_on: Option, pub tm30_reported_on: Option, } #[derive(Clone, Debug, Serialize)] pub struct Deadline { /// report, extension, decision, overstay, leave, passport, work-permit, /// tm30, address, reentry, tdac or visa pub key: &'static str, pub title: String, pub due: Option, /// "Nov 17, 2026" pub due_text: String, /// "in 12 days", "3 days ago" pub when: String, /// bad, warn, ok or info pub level: &'static str, /// The chip's text, which says what the color means. pub label: String, pub note: String, /// Calculated, not read from a receipt or a stamp. pub estimate: bool, } /// Where the person stands today. #[derive(Clone, Debug, Default, Serialize)] pub struct Stay { /// in, abroad or unknown pub state: &'static str, pub since: String, pub permitted_until: String, pub remaining: String, pub basis: String, pub left_on: String, pub overstay: bool, } #[derive(Clone, Debug, Default, Serialize)] pub struct Assessment { pub stay: Stay, /// The most urgent first. pub items: Vec, } impl Assessment { /// The most urgent item with a date. pub fn next(&self) -> Option<&Deadline> { self.items.iter().find(|d| d.due.is_some()) } } fn days(n: i64) -> TimeDelta { TimeDelta::days(n) } fn fmt(d: NaiveDate) -> String { dates::fmt_date(d) } fn item( key: &'static str, title: &str, due: Option, level: &'static str, label: impl Into, note: impl Into, today: NaiveDate, ) -> Deadline { Deadline { key, title: title.to_string(), due, due_text: due.map(fmt).unwrap_or_default(), when: due.map(|d| dates::relative(today, d)).unwrap_or_default(), level, label: label.into(), note: note.into(), estimate: false, } } /// bad, warn, ok, info pub fn rank(level: &str) -> u8 { match level { "bad" => 0, "warn" => 1, "ok" => 2, _ => 3, } } /// The last weekday on or before `d`: immigration offices close on weekends. pub fn last_working_day(d: NaiveDate) -> NaiveDate { match d.weekday() { Weekday::Sat => d - days(1), Weekday::Sun => d - days(2), _ => d, } } fn weekday_name(d: NaiveDate) -> &'static str { match d.weekday() { Weekday::Sat => "Saturday", Weekday::Sun => "Sunday", _ => "weekday", } } pub fn assess(f: &Facts, today: NaiveDate) -> Assessment { let mut items = Vec::new(); let mut stay = Stay { state: "unknown", ..Stay::default() }; passport(f, today, &mut items); work_permit(f, today, &mut items); // the latest arrival; for two on one day, the one recorded last match f.arrivals.iter().max_by_key(|a| a.arrived_on) { None => visas(f, today, &mut items), Some(a) => match a.departed_on { Some(left) => { stay.state = "abroad"; stay.left_on = fmt(left); visas(f, today, &mut items); } None => in_thailand(f, a, today, &mut stay, &mut items), }, } items.sort_by(|x, y| { rank(x.level).cmp(&rank(y.level)).then( x.due .unwrap_or(NaiveDate::MAX) .cmp(&y.due.unwrap_or(NaiveDate::MAX)), ) }); Assessment { stay, items } } fn admission_text(a: &ArrivalFact) -> String { match a.admission.as_str() { "visa" => match &a.visa_category { Some(c) => format!("{} visa", records::visa_category_short(c)), None => "a visa".into(), }, "exempt" => "visa exemption".into(), "voa" => "visa on arrival".into(), "reentry" => "re-entry permit".into(), other => other.into(), } } /// "marriage to a Thai national": the reason, lower case at the start only. fn basis_text(b: &str) -> String { let l = records::label(records::BASES, b).unwrap_or(b); let mut c = l.chars(); match c.next() { Some(first) => first.to_lowercase().chain(c).collect(), None => String::new(), } } fn in_thailand( f: &Facts, a: &ArrivalFact, today: NaiveDate, stay: &mut Stay, items: &mut Vec, ) { let since = a.arrived_on; let mut permitted = a.permitted_until; let mut basis = admission_text(a); if a.admission == "reentry" && let Some(e) = f .extensions .iter() .filter(|e| e.applied_on < since && e.decision == "approved") .max_by_key(|e| e.applied_on) { basis = format!( "extension of stay for {}, kept by a re-entry permit", basis_text(&e.basis) ); } let mut pending: Option<&ExtensionFact> = None; let mut refused: Option<&ExtensionFact> = None; // an extension of stay, also one carried over by a re-entry permit let mut extended = a.admission == "reentry"; let mut exts: Vec<&ExtensionFact> = f .extensions .iter() .filter(|e| e.applied_on >= since) .collect(); exts.sort_by_key(|e| e.applied_on); for &e in &exts { if let Some(d) = e.permitted_until { permitted = d; } pending = None; refused = None; match e.decision.as_str() { "approved" => { extended = true; basis = format!("extension of stay for {}", basis_text(&e.basis)); } "consideration" => { extended = true; pending = Some(e); basis = format!( "extension of stay for {}, under consideration", basis_text(&e.basis) ); } "refused" => { refused = Some(e); basis = "extension of stay refused".into(); } _ => {} } } let overstay = today > permitted; *stay = Stay { state: "in", since: fmt(since), permitted_until: fmt(permitted), remaining: dates::relative(today, permitted), basis, left_on: String::new(), overstay, }; if overstay { let n = (today - permitted).num_days(); let fine = (n * 500).min(20_000); items.push(item( "overstay", "Overstay", Some(permitted), "bad", "Overstay", format!( "The permission to stay ended on {}. Overstay costs 500 THB a day, at most 20,000 THB; {n} days so far make {} THB. Go to the immigration office at once.", fmt(permitted), records::thousands(fine) ), today, )); } else if let Some(e) = refused { items.push(item( "leave", "Leave Thailand", Some(permitted), "bad", "Refused", format!( "The extension applied for on {} was refused. The stamp allows the stay until {}.", fmt(e.applied_on), fmt(permitted) ), today, )); } else if let Some(e) = pending { let level = if (permitted - today).num_days() <= 7 { "warn" } else { "ok" }; let office = if e.office.is_empty() { "the immigration office" } else { e.office.as_str() }; items.push(item( "decision", "Decision on the extension", Some(permitted), level, format!("Return {}", dates::relative(today, permitted)), format!( "Return to {office} on {} for the decision on the application of {}.", fmt(permitted), fmt(e.applied_on) ), today, )); } else { extension_window(permitted, today, items); } if !overstay && refused.is_none() { report(f, since, &exts, permitted, today, items); } tm30(f, since, today, items); if !overstay && extended && !f.reentry_permits.iter().any(|d| *d >= today) { items.push(item( "reentry", "Re-entry permit", None, "info", "None valid", "Leaving Thailand without a re-entry permit (TM.8) ends the permission to stay. A single permit costs 1,000 THB, a multiple one 3,800 THB.", today, )); } if a.arrived_on >= tdac_start() && a.tdac_no.is_empty() { items.push(item( "tdac", "TDAC of the arrival", None, "info", "Not recorded", format!( "The arrival on {} has no TDAC number; the extension pack includes the TDAC.", fmt(a.arrived_on) ), today, )); } } /// TM.7 is accepted from 30 days before the permission ends (Chiang Mai); /// the last day to apply is the last working day. fn extension_window(permitted: NaiveDate, today: NaiveDate, items: &mut Vec) { let opens = permitted - days(30); let last = last_working_day(permitted); let (level, label) = if today >= opens { if (last - today).num_days() <= 7 { ("bad", "Apply now".to_string()) } else { ("warn", "Window open".to_string()) } } else { ("ok", format!("Opens {}", dates::relative(today, opens))) }; let mut note = format!( "Chiang Mai Immigration accepts the application (TM.7) from {} to {}.", fmt(opens), fmt(last) ); if last != permitted { note.push_str(&format!( " The permission ends on {}, a {}, when the office is closed.", fmt(permitted), weekday_name(permitted) )); } items.push(item( "extension", "Extension of stay", Some(last), level, label, note, today, )); } /// The arrival is day 1, so the first report is due on day 90 (arrival plus /// 89 days). A report or an extension of stay starts the count again; the /// date on a receipt wins. Accepted in person from 15 days before to 7 days /// after the due date, online from 15 to 7 days before. fn report( f: &Facts, since: NaiveDate, exts: &[&ExtensionFact], permitted: NaiveDate, today: NaiveDate, items: &mut Vec, ) { let mut base = since; let mut next: Option = None; let mut source = "arrival"; for r in f.reports.iter().filter(|r| r.reported_on >= since) { if r.reported_on >= base { base = r.reported_on; next = r.next_due_on; source = "report"; } } for e in exts.iter().filter(|e| e.decision != "refused") { if e.applied_on > base { base = e.applied_on; next = None; source = "extension"; } } let (due, estimate) = match (next, source) { (Some(d), _) => (d, false), (None, "arrival") => (since + days(89), true), (None, _) => (base + days(90), true), }; // The stay ends first: the person leaves, or the extension that keeps // them here counts as the report. if due > permitted { return; } let online_from = due - days(15); let online_until = due - days(7); let late_after = due + days(7); let new_passport = f .passports .iter() .any(|p| p.issued_on.is_some_and(|d| d > base)); let online_ok = source != "extension" && !new_passport; let (level, label, mut note) = if today > late_after { ( "bad", "Late".to_string(), format!( "Due on {}. Report in person and pay the 2,000 THB fine; being caught without a report costs up to 5,000 THB.", fmt(due) ), ) } else if today > due { ( "bad", "Overdue".to_string(), format!( "Due on {}. In person it is accepted until {} without a fine.", fmt(due), fmt(late_after) ), ) } else if today >= online_from { let how = if online_ok && today <= online_until { format!( "Online until {}, in person until {}.", fmt(online_until), fmt(late_after) ) } else { format!( "In person or by an authorized person until {}.", fmt(late_after) ) }; ("warn", "Window open".to_string(), how) } else { let how = if online_ok { format!( "Accepted from {}: online until {}, in person until {}.", fmt(online_from), fmt(online_until), fmt(late_after) ) } else { format!( "Accepted in person from {} to {}.", fmt(online_from), fmt(late_after) ) }; ( "ok", format!("Opens {}", dates::relative(today, online_from)), how, ) }; if !online_ok { note.push_str(if source == "extension" { " The first report after an extension of stay is made in person." } else { " After a new passport the next report is made in person." }); } if estimate { note.push_str(match source { "arrival" => " Calculated as the arrival plus 89 days; the date on the receipt wins.", "report" => { " Calculated as the last report plus 90 days; the date on the receipt wins." } _ => " Calculated as the extension plus 90 days; the date on the receipt wins.", }); } let mut d = item( "report", "90-day report", Some(due), level, label, note, today, ); d.estimate = estimate; items.push(d); } /// The house master files TM.30 within 24 hours of each arrival at the /// address, also after a trip abroad. fn tm30(f: &Facts, since: NaiveDate, today: NaiveDate, items: &mut Vec) { let Some(ad) = &f.address else { items.push(item( "address", "Address in Thailand", None, "warn", "Missing", "No current address is recorded. TM.7 and TM.47 ask for it, with the TM.30 receipt.", today, )); return; }; let from = ad.moved_in_on.map_or(since, |m| m.max(since)); if ad.tm30_reported_on.is_some_and(|r| r >= from) { return; } let note = match ad.tm30_reported_on { None => "No TM.30 receipt is recorded for the current address. The house master files TM.30 within 24 hours of the arrival.".to_string(), Some(r) => format!( "The TM.30 on record is from {}, before {} on {}. The house master files TM.30 again within 24 hours.", fmt(r), if from == since { "the arrival" } else { "moving in" }, fmt(from) ), }; items.push(item( "tm30", "TM.30 for the address", Some(from + days(1)), "warn", "Not reported", note, today, )); } fn passport(f: &Facts, today: NaiveDate, items: &mut Vec) { let Some(p) = f.passports.iter().max_by_key(|p| p.expires_on) else { items.push(item( "passport", "Passport", None, "warn", "Missing", "No passport is recorded.", today, )); return; }; let s = dates::passport_status(p.expires_on, today); let (label, note) = match s.level { "ok" => ("Valid", "Valid for more than a year."), "warn" => ( "Under 12 months", "An extension of stay never runs past the passport's expiry. Renew the passport before the next extension.", ), _ if p.expires_on < today => ("Expired", "The passport has expired."), _ => ( "Under 6 months", "An extension of stay never runs past the passport's expiry. Renew the passport now.", ), }; items.push(item( "passport", "Passport expiry", Some(p.expires_on), s.level, label, note, today, )); } fn work_permit(f: &Facts, today: NaiveDate, items: &mut Vec) { let Some(&until) = f.work_permits.iter().max() else { return; }; // a permit of a job that ended long ago is history if until < today - days(365) { return; } let (level, label) = if until < today { ("bad", "Expired".to_string()) } else if until <= today + days(60) { ("warn", format!("Expires {}", dates::relative(today, until))) } else { ("ok", "Valid".to_string()) }; items.push(item( "work-permit", "Work permit expiry", Some(until), level, label, "The employer renews the work permit, together with the extension of stay.", today, )); } /// For someone abroad: the visas still valid for entry. fn visas(f: &Facts, today: NaiveDate, items: &mut Vec) { for v in f.visas.iter().filter(|v| v.valid_until >= today) { let (level, label) = if v.valid_until <= today + days(30) { ("warn", "Ends soon") } else { ("ok", "Valid") }; items.push(item( "visa", "Visa valid for entry", Some(v.valid_until), level, label, format!( "The {} visa must be used to enter Thailand by {}.", records::visa_category_short(&v.category), fmt(v.valid_until) ), today, )); } } // ------------------------------------------------------------- loading /// The facts of these people, with a few queries for all of them. pub async fn load(db: &PgPool, people: &[i64]) -> Result> { let mut map: HashMap = people.iter().map(|id| (*id, Facts::default())).collect(); let rows: Vec<(i64, Option, NaiveDate)> = sqlx::query_as( "SELECT person_id, issued_on, expires_on FROM passports WHERE person_id = ANY($1)", ) .bind(people) .fetch_all(db) .await?; for (p, issued_on, expires_on) in rows { if let Some(f) = map.get_mut(&p) { f.passports.push(PassportFact { issued_on, expires_on, }); } } let rows: Vec<(i64, String, NaiveDate)> = sqlx::query_as( "SELECT person_id, category, valid_until FROM visas WHERE person_id = ANY($1) \ ORDER BY valid_until, id", ) .bind(people) .fetch_all(db) .await?; for (p, category, valid_until) in rows { if let Some(f) = map.get_mut(&p) { f.visas.push(VisaFact { category, valid_until, }); } } type ArrivalRow = ( i64, NaiveDate, NaiveDate, Option, String, Option, String, ); let rows: Vec = sqlx::query_as( "SELECT a.person_id, a.arrived_on, a.permitted_until, a.departed_on, a.admission, \ v.category, a.tdac_no \ FROM arrivals a LEFT JOIN visas v ON v.id = a.visa_id \ WHERE a.person_id = ANY($1) ORDER BY a.arrived_on, a.id", ) .bind(people) .fetch_all(db) .await?; for (p, arrived_on, permitted_until, departed_on, admission, visa_category, tdac_no) in rows { if let Some(f) = map.get_mut(&p) { f.arrivals.push(ArrivalFact { arrived_on, permitted_until, departed_on, admission, visa_category, tdac_no, }); } } type ExtensionRow = (i64, NaiveDate, String, String, Option, String); let rows: Vec = sqlx::query_as( "SELECT person_id, applied_on, basis, decision, permitted_until, office \ FROM extensions WHERE person_id = ANY($1) ORDER BY applied_on, id", ) .bind(people) .fetch_all(db) .await?; for (p, applied_on, basis, decision, permitted_until, office) in rows { if let Some(f) = map.get_mut(&p) { f.extensions.push(ExtensionFact { applied_on, basis, decision, permitted_until, office, }); } } let rows: Vec<(i64, NaiveDate, Option)> = sqlx::query_as( "SELECT person_id, reported_on, next_due_on FROM ninety_day_reports \ WHERE person_id = ANY($1) ORDER BY reported_on, id", ) .bind(people) .fetch_all(db) .await?; for (p, reported_on, next_due_on) in rows { if let Some(f) = map.get_mut(&p) { f.reports.push(ReportFact { reported_on, next_due_on, }); } } let rows: Vec<(i64, NaiveDate)> = sqlx::query_as( "SELECT person_id, valid_until FROM reentry_permits WHERE person_id = ANY($1)", ) .bind(people) .fetch_all(db) .await?; for (p, until) in rows { if let Some(f) = map.get_mut(&p) { f.reentry_permits.push(until); } } let rows: Vec<(i64, NaiveDate)> = sqlx::query_as("SELECT person_id, valid_until FROM work_permits WHERE person_id = ANY($1)") .bind(people) .fetch_all(db) .await?; for (p, until) in rows { if let Some(f) = map.get_mut(&p) { f.work_permits.push(until); } } let rows: Vec<(i64, Option, Option)> = sqlx::query_as( "SELECT DISTINCT ON (person_id) person_id, moved_in_on, tm30_reported_on \ FROM addresses WHERE person_id = ANY($1) AND moved_out_on IS NULL \ ORDER BY person_id, moved_in_on DESC NULLS LAST, id DESC", ) .bind(people) .fetch_all(db) .await?; for (p, moved_in_on, tm30_reported_on) in rows { if let Some(f) = map.get_mut(&p) { f.address = Some(AddressFact { moved_in_on, tm30_reported_on, }); } } Ok(map) } pub async fn for_people( db: &PgPool, people: &[i64], today: NaiveDate, ) -> Result> { Ok(load(db, people) .await? .into_iter() .map(|(id, f)| (id, assess(&f, today))) .collect()) } pub async fn for_person(db: &PgPool, person: i64, today: NaiveDate) -> Result { Ok(for_people(db, &[person], today) .await? .remove(&person) .unwrap_or_default()) } #[cfg(test)] mod tests { use super::*; fn d(s: &str) -> NaiveDate { dates::parse_date(s).unwrap() } fn arrival(on: &str, until: &str) -> ArrivalFact { ArrivalFact { arrived_on: d(on), permitted_until: d(until), departed_on: None, admission: "visa".into(), visa_category: Some("non-b".into()), tdac_no: "T1".into(), } } fn base() -> Facts { Facts { passports: vec![PassportFact { issued_on: Some(d("2021-01-01")), expires_on: d("2031-01-01"), }], address: Some(AddressFact { moved_in_on: Some(d("2025-01-01")), tm30_reported_on: Some(d("2028-01-01")), }), ..Facts::default() } } fn find(a: &Assessment, key: &str) -> Option { a.items.iter().find(|x| x.key == key).cloned() } #[test] fn the_first_report_is_day_90_counting_the_arrival() { let mut f = base(); f.arrivals.push(arrival("2026-09-01", "2027-08-31")); let r = find(&assess(&f, d("2026-09-10")), "report").unwrap(); assert_eq!(r.due, Some(d("2026-11-29"))); assert!(r.estimate); assert_eq!((r.level, r.label.as_str()), ("ok", "Opens in 2 months")); let r = find(&assess(&f, d("2026-11-14")), "report").unwrap(); assert_eq!((r.level, r.label.as_str()), ("warn", "Window open")); assert!( r.note .starts_with("Online until Nov 22, 2026, in person until Dec 6, 2026."), "{}", r.note ); let r = find(&assess(&f, d("2026-11-25")), "report").unwrap(); assert!( r.note .starts_with("In person or by an authorized person until Dec 6, 2026.") ); let r = find(&assess(&f, d("2026-12-01")), "report").unwrap(); assert_eq!((r.level, r.label.as_str()), ("bad", "Overdue")); let r = find(&assess(&f, d("2026-12-07")), "report").unwrap(); assert_eq!(r.label, "Late"); assert!(r.note.contains("2,000 THB")); } #[test] fn the_receipt_wins_and_each_report_restarts_the_count() { let mut f = base(); f.arrivals.push(arrival("2026-01-10", "2027-01-09")); f.reports.push(ReportFact { reported_on: d("2026-04-05"), next_due_on: Some(d("2026-07-08")), }); let r = find(&assess(&f, d("2026-06-01")), "report").unwrap(); assert_eq!(r.due, Some(d("2026-07-08"))); assert!(!r.estimate && !r.note.contains("Calculated")); f.reports.push(ReportFact { reported_on: d("2026-07-01"), next_due_on: None, }); let r = find(&assess(&f, d("2026-08-01")), "report").unwrap(); assert_eq!(r.due, Some(d("2026-09-29"))); assert!(r.estimate && r.note.contains("last report plus 90 days")); } #[test] fn leaving_ends_the_count_and_the_next_arrival_starts_it_again() { let mut f = base(); let mut first = arrival("2026-01-10", "2027-01-09"); first.departed_on = Some(d("2026-03-01")); f.arrivals.push(first); let a = assess(&f, d("2026-03-05")); assert_eq!( (a.stay.state, a.stay.left_on.as_str()), ("abroad", "Mar 1, 2026") ); assert!(find(&a, "report").is_none() && find(&a, "extension").is_none()); let mut back = arrival("2026-03-20", "2027-01-09"); back.admission = "reentry".into(); f.arrivals.push(back); let a = assess(&f, d("2026-03-25")); assert_eq!(a.stay.state, "in"); assert_eq!(a.stay.basis, "re-entry permit"); assert_eq!(find(&a, "report").unwrap().due, Some(d("2026-06-17"))); assert_eq!(find(&a, "reentry").unwrap().level, "info"); f.reentry_permits.push(d("2027-01-09")); assert!(find(&assess(&f, d("2026-03-25")), "reentry").is_none()); } #[test] fn the_extension_window_opens_30_days_before_and_skips_the_weekend() { let mut f = base(); // permitted until Sunday, Jan 31, 2027 f.arrivals.push(arrival("2026-12-01", "2027-01-31")); let e = find(&assess(&f, d("2026-12-01")), "extension").unwrap(); assert_eq!(e.due, Some(d("2027-01-29"))); assert_eq!((e.level, e.label.as_str()), ("ok", "Opens in 31 days")); assert!( e.note.contains("from Jan 1, 2027 to Jan 29, 2027"), "{}", e.note ); assert!(e.note.contains("a Sunday")); let e = find(&assess(&f, d("2027-01-05")), "extension").unwrap(); assert_eq!((e.level, e.label.as_str()), ("warn", "Window open")); let e = find(&assess(&f, d("2027-01-25")), "extension").unwrap(); assert_eq!((e.level, e.label.as_str()), ("bad", "Apply now")); } #[test] fn no_report_when_the_stay_ends_first() { let mut f = base(); let mut a = arrival("2026-09-01", "2026-10-30"); a.admission = "exempt".into(); a.visa_category = None; f.arrivals.push(a); let r = assess(&f, d("2026-09-20")); assert!(find(&r, "report").is_none()); assert_eq!(r.stay.basis, "visa exemption"); assert_eq!(find(&r, "extension").unwrap().label, "Opens in 10 days"); assert!( find(&r, "reentry").is_none(), "no extension, nothing to protect" ); } #[test] fn overstay_counts_the_fine() { let mut f = base(); f.arrivals.push(arrival("2026-09-01", "2026-10-30")); let a = assess(&f, d("2026-11-03")); let o = find(&a, "overstay").unwrap(); assert!( o.note.contains("4 days so far make 2,000 THB"), "{}", o.note ); assert!(a.stay.overstay); assert_eq!(a.items[0].key, "overstay"); assert!(find(&a, "extension").is_none() && find(&a, "report").is_none()); let a = assess(&f, d("2027-03-01")); assert!( find(&a, "overstay") .unwrap() .note .contains("make 20,000 THB") ); } #[test] fn an_extension_moves_the_stay_and_counts_as_a_report() { let mut f = base(); f.arrivals.push(arrival("2026-03-01", "2026-05-29")); f.extensions.push(ExtensionFact { applied_on: d("2026-05-20"), basis: "work".into(), decision: "consideration".into(), permitted_until: Some(d("2026-06-19")), office: "Chiang Mai Immigration Office".into(), }); let a = assess(&f, d("2026-06-10")); let dec = find(&a, "decision").unwrap(); assert_eq!(dec.due, Some(d("2026-06-19"))); assert!( dec.note .contains("Return to Chiang Mai Immigration Office on Jun 19, 2026") ); assert!(find(&a, "extension").is_none()); f.extensions.push(ExtensionFact { applied_on: d("2026-05-20"), basis: "work".into(), decision: "approved".into(), permitted_until: Some(d("2027-05-29")), office: String::new(), }); let a = assess(&f, d("2026-06-10")); assert!(find(&a, "decision").is_none()); assert_eq!(a.stay.permitted_until, "May 29, 2027"); assert_eq!(a.stay.basis, "extension of stay for work"); let r = find(&a, "report").unwrap(); assert_eq!(r.due, Some(d("2026-08-18"))); assert!( r.note .contains("after an extension of stay is made in person") ); assert!(find(&a, "reentry").is_some()); } #[test] fn a_refusal_means_leaving() { let mut f = base(); f.arrivals.push(arrival("2026-03-01", "2026-05-29")); f.extensions.push(ExtensionFact { applied_on: d("2026-05-20"), basis: "work".into(), decision: "refused".into(), permitted_until: Some(d("2026-05-27")), office: String::new(), }); let a = assess(&f, d("2026-05-21")); let l = find(&a, "leave").unwrap(); assert_eq!((l.level, l.due), ("bad", Some(d("2026-05-27")))); assert!(find(&a, "report").is_none() && find(&a, "extension").is_none()); } #[test] fn tm30_after_each_arrival() { let mut f = base(); f.address = Some(AddressFact { moved_in_on: Some(d("2025-01-01")), tm30_reported_on: Some(d("2025-01-02")), }); f.arrivals.push(arrival("2026-09-01", "2027-08-31")); let t = find(&assess(&f, d("2026-09-10")), "tm30").unwrap(); assert_eq!(t.due, Some(d("2026-09-02"))); assert!( t.note.contains("before the arrival on Sep 1, 2026"), "{}", t.note ); f.address = None; assert_eq!( find(&assess(&f, d("2026-09-10")), "address").unwrap().level, "warn" ); } #[test] fn a_new_passport_means_the_next_report_in_person() { let mut f = base(); f.arrivals.push(arrival("2026-09-01", "2027-08-31")); f.passports.push(PassportFact { issued_on: Some(d("2026-10-01")), expires_on: d("2036-09-30"), }); let r = find(&assess(&f, d("2026-11-15")), "report").unwrap(); assert!(r.note.starts_with("In person"), "{}", r.note); assert!(r.note.contains("After a new passport")); } #[test] fn passport_work_permit_and_visa_dates() { let mut f = base(); f.passports = vec![PassportFact { issued_on: None, expires_on: d("2027-03-01"), }]; f.work_permits = vec![d("2026-12-01")]; f.visas.push(VisaFact { category: "non-b".into(), valid_until: d("2026-12-10"), }); let a = assess(&f, d("2026-11-17")); assert_eq!(a.stay.state, "unknown"); let p = find(&a, "passport").unwrap(); assert_eq!((p.level, p.label.as_str()), ("bad", "Under 6 months")); assert_eq!(a.items[0].key, "passport"); assert_eq!(find(&a, "work-permit").unwrap().level, "warn"); let v = find(&a, "visa").unwrap(); assert_eq!(v.level, "warn"); assert!(v.note.contains("Non-Immigrant B visa must be used")); // an old job's permit is history f.work_permits = vec![d("2024-01-01")]; assert!(find(&assess(&f, d("2026-11-17")), "work-permit").is_none()); } #[test] fn a_missing_tdac_is_noted() { let mut f = base(); let mut a = arrival("2026-09-01", "2027-08-31"); a.tdac_no = String::new(); f.arrivals.push(a); assert_eq!( find(&assess(&f, d("2026-09-10")), "tdac").unwrap().level, "info" ); f.arrivals[0].arrived_on = d("2025-04-01"); assert!(find(&assess(&f, d("2026-09-10")), "tdac").is_none()); } #[test] fn working_days() { assert_eq!(last_working_day(d("2027-01-31")), d("2027-01-29")); assert_eq!(last_working_day(d("2027-01-30")), d("2027-01-29")); assert_eq!(last_working_day(d("2027-01-29")), d("2027-01-29")); } }