Lanna Desk's larger work is contracts, general ones and artists', for clients who are Thai or foreign, people or organizations, with several lawyers in the team. The back office gets a Legal section (phase 9 in docs/PLAN.md): - Lawyers: license number, contact, the login of one who uses the app (then "My contracts"), in the team or left. - Clients, as record cards: person or organization, names in English and Thai, stage name or brand, a Thai ID number (checked), a passport or a registration number, the lawyer in charge. - Contracts: code LD-<year>-<n>, the general kinds and the artist kinds (recording, management, publishing, performance, license, merchandise), other party, status, lawyer, dates and value; a contract in force shows its notice day and its end ahead. Filters: general or artists, a lawyer, mine, those over. - Versions: a text kept here, a file (PDF or scan, encrypted as the client's document) or both. They never change: the database refuses UPDATE and DELETE, a version's file cannot be deleted and no document's checksum can change. Any version reads against the one before as a line diff. - Paper copies: the id <code>-P<n> to write on the paper or print as a 90 x 50 mm label with a QR code; where it lies, its state and holder, each move journaled; found again by its id. - The journal: every change in words, in the change's transaction, each entry chained to the one before by SHA-256. The database refuses to change, delete or truncate it; /journal checks the chain and every version's text and fingerprints against its entry, shows the last hash and exports CSV. The sidebar groups its sections: Legal, Visas and stays, Office. Demo data (seed-demo) adds three lawyers, six clients and seven contracts with versions, papers and moves. Documents take a third owner, the client (migration 0009). Checks: fmt, clippy, 115 unit and 62 integration tests (new: versions and the journal, the database refusing changes, a change around the app breaking the chain, paper ids and moves, the demo checking whole); screenshots of the new pages in light, dark and on a phone.
1370 lines
46 KiB
Rust
1370 lines
46 KiB
Rust
//! Records that make up a person's stay in Thailand, and the companies that
|
|
//! employ people. Each kind is described once (`Kind`): its table, its
|
|
//! fields with their checks, and how a record reads on the page. One set of
|
|
//! functions reads the forms, checks them, stores and shows the records, so
|
|
//! visas, arrivals, extensions of stay, re-entry permits, 90-day reports,
|
|
//! work permits and companies behave alike, in the audit log too.
|
|
|
|
use std::collections::BTreeMap;
|
|
|
|
use anyhow::Result;
|
|
use chrono::{NaiveDate, TimeDelta};
|
|
use serde::Serialize;
|
|
use sqlx::postgres::PgRow;
|
|
use sqlx::{PgConnection, PgPool, Postgres, QueryBuilder, Row};
|
|
|
|
use crate::audit::Entity;
|
|
use crate::dates::{self, Status};
|
|
use crate::forms::{Errors, Fields, compact_upper, err};
|
|
use crate::gps;
|
|
|
|
/// A record's values as text by field name: what the form shows and the
|
|
/// checks read. Dates are `YYYY-MM-DD`; references are ids.
|
|
pub type Values = BTreeMap<String, String>;
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum Input {
|
|
Text,
|
|
/// Upper case without spaces: numbers on stamps, receipts and permits.
|
|
Code,
|
|
/// Digits only (spaces and dashes are dropped): registration numbers.
|
|
Digits,
|
|
Area,
|
|
Date,
|
|
Choice(&'static [(&'static str, &'static str)]),
|
|
/// Whole baht.
|
|
Money,
|
|
/// One of the person's passports.
|
|
Passport,
|
|
/// One of the person's visas.
|
|
Visa,
|
|
/// One of the companies.
|
|
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,
|
|
/// One of the lawyers.
|
|
Lawyer,
|
|
/// One of the clients of the legal practice.
|
|
Client,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Field {
|
|
/// The column, and the form field.
|
|
pub name: &'static str,
|
|
pub label: &'static str,
|
|
pub input: Input,
|
|
/// The message when it is left empty; empty for an optional field.
|
|
pub missing: &'static str,
|
|
pub hint: &'static str,
|
|
/// 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,
|
|
}
|
|
|
|
pub(crate) const fn field(name: &'static str, label: &'static str, input: Input) -> Field {
|
|
Field {
|
|
name,
|
|
label,
|
|
input,
|
|
missing: "",
|
|
hint: "",
|
|
suggest: "",
|
|
wide: false,
|
|
section: "",
|
|
}
|
|
}
|
|
|
|
impl Field {
|
|
pub(crate) const fn req(self, missing: &'static str) -> Field {
|
|
Field { missing, ..self }
|
|
}
|
|
pub(crate) const fn hint(self, hint: &'static str) -> Field {
|
|
Field { hint, ..self }
|
|
}
|
|
pub(crate) const fn suggest(self, suggest: &'static str) -> Field {
|
|
Field { suggest, ..self }
|
|
}
|
|
pub(crate) const fn wide(self) -> Field {
|
|
Field { wide: true, ..self }
|
|
}
|
|
pub(crate) 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
|
|
/// `target`.
|
|
#[derive(Debug)]
|
|
pub struct DateOrder {
|
|
pub earlier: &'static str,
|
|
pub later: &'static str,
|
|
pub target: &'static str,
|
|
pub message: &'static str,
|
|
}
|
|
|
|
pub struct Kind {
|
|
/// The URL segment: /people/{id}/<slug>.
|
|
pub slug: &'static str,
|
|
pub table: &'static str,
|
|
pub entity: Entity,
|
|
/// "visa", as in "New visa" and "Edit the visa".
|
|
pub one: &'static str,
|
|
/// The section's heading.
|
|
pub title: &'static str,
|
|
/// The explanation above the form.
|
|
pub lead: &'static str,
|
|
pub fields: &'static [Field],
|
|
/// Fields whose values make the record's first line.
|
|
pub headline: &'static [&'static str],
|
|
/// SQL ORDER BY of the list.
|
|
pub order: &'static str,
|
|
pub date_order: &'static [DateOrder],
|
|
/// Checks beyond the fields' own.
|
|
pub check: fn(&Values, &mut Errors),
|
|
/// A chip for a record that still matters; None marks it as history.
|
|
pub status: fn(&Values, NaiveDate) -> Option<Status>,
|
|
/// Records belong to a person (all but companies).
|
|
pub per_person: bool,
|
|
}
|
|
|
|
impl Kind {
|
|
pub fn field(&self, name: &str) -> Option<&'static Field> {
|
|
self.fields.iter().find(|f| f.name == name)
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------- the lists
|
|
|
|
pub const VISA_CATEGORIES: &[(&str, &str)] = &[
|
|
("non-b", "Non-Immigrant B (work, business)"),
|
|
("non-o", "Non-Immigrant O (family, retirement, other)"),
|
|
("o-a", "Non-Immigrant O-A (long stay)"),
|
|
("non-ed", "Non-Immigrant ED (education)"),
|
|
("dtv", "Destination Thailand Visa (DTV)"),
|
|
("ltr", "Long-Term Resident (LTR)"),
|
|
("smart", "SMART visa"),
|
|
("tr", "Tourist visa (TR)"),
|
|
("other", "Other"),
|
|
];
|
|
pub const ENTRIES: &[(&str, &str)] =
|
|
&[("single", "Single entry"), ("multiple", "Multiple entries")];
|
|
pub const ADMISSIONS: &[(&str, &str)] = &[
|
|
("visa", "A visa"),
|
|
("exempt", "Visa exemption"),
|
|
("voa", "Visa on arrival"),
|
|
("reentry", "A re-entry permit"),
|
|
];
|
|
pub const BASES: &[(&str, &str)] = &[
|
|
("work", "Work"),
|
|
("marriage", "Marriage to a Thai national"),
|
|
("family", "Family of a foreigner with a permission to stay"),
|
|
("retirement", "Retirement"),
|
|
("education", "Education"),
|
|
("tourism", "Tourism"),
|
|
("other", "Other"),
|
|
];
|
|
pub const DECISIONS: &[(&str, &str)] = &[
|
|
("approved", "Approved"),
|
|
("consideration", "Under consideration"),
|
|
("refused", "Refused"),
|
|
];
|
|
pub const REENTRY_KINDS: &[(&str, &str)] = &[("single", "Single"), ("multiple", "Multiple")];
|
|
pub const REPORT_METHODS: &[(&str, &str)] = &[
|
|
("in-person", "In person"),
|
|
("agent", "By an authorized person"),
|
|
("online", "Online"),
|
|
("mail", "By registered mail"),
|
|
];
|
|
|
|
/// Suggestions for the ports of entry and departure.
|
|
pub const PORTS: &[&str] = &[
|
|
"Chiang Mai International Airport",
|
|
"Suvarnabhumi Airport",
|
|
"Don Mueang International Airport",
|
|
"Phuket International Airport",
|
|
"Chiang Rai International Airport",
|
|
"Mae Sai border checkpoint",
|
|
"Chiang Khong border checkpoint",
|
|
"Nong Khai border checkpoint",
|
|
"Sadao border checkpoint",
|
|
];
|
|
/// Suggestions for the immigration office.
|
|
pub const OFFICES: &[&str] = &[
|
|
"Chiang Mai Immigration Office",
|
|
"Lamphun Immigration Office",
|
|
"Chiang Rai Immigration Office",
|
|
"Bangkok Immigration Division 1",
|
|
"One Start One Stop Investment Center",
|
|
];
|
|
|
|
pub fn label(list: &'static [(&'static str, &'static str)], key: &str) -> Option<&'static str> {
|
|
list.iter().find(|(k, _)| *k == key).map(|(_, l)| *l)
|
|
}
|
|
|
|
/// "Non-Immigrant B": the category without the explanation in brackets.
|
|
pub fn visa_category_short(key: &str) -> String {
|
|
let l = label(VISA_CATEGORIES, key).unwrap_or(key);
|
|
match l.split_once(" (") {
|
|
Some((_, short)) if key == "dtv" || key == "ltr" => short.trim_end_matches(')').to_string(),
|
|
Some((head, _)) => head.to_string(),
|
|
None => l.to_string(),
|
|
}
|
|
}
|
|
|
|
// --------------------------------------------------------------- the kinds
|
|
|
|
const VISA_FIELDS: &[Field] = &[
|
|
field("category", "Category", Input::Choice(VISA_CATEGORIES))
|
|
.req("Choose the visa's category."),
|
|
field("entries", "Entries", Input::Choice(ENTRIES)),
|
|
field("number", "Visa number", Input::Code).hint("As printed on the visa or the e-Visa."),
|
|
field("passport_id", "In passport", Input::Passport),
|
|
field("issued_at", "Issued at", Input::Text).hint("The embassy or consulate, or e-Visa."),
|
|
field("issued_on", "Date of issue", Input::Date),
|
|
field("valid_until", "Enter before", Input::Date)
|
|
.req("Enter the last day to enter Thailand with this visa.")
|
|
.hint("The last day to enter Thailand with this visa."),
|
|
field("notes", "Notes", Input::Area).wide(),
|
|
];
|
|
|
|
pub static VISAS: Kind = Kind {
|
|
slug: "visas",
|
|
table: "visas",
|
|
entity: Entity::Visa,
|
|
one: "visa",
|
|
title: "Visas",
|
|
lead: "A visa issued by an embassy, a consulate or online (e-Visa). Visa exemption and visa on arrival need no visa record; the arrival says how the person was admitted.",
|
|
fields: VISA_FIELDS,
|
|
headline: &["category", "number"],
|
|
order: "valid_until DESC, id DESC",
|
|
date_order: &[DateOrder {
|
|
earlier: "issued_on",
|
|
later: "valid_until",
|
|
target: "valid_until",
|
|
message: "The visa cannot end before it was issued.",
|
|
}],
|
|
check: no_check,
|
|
status: visa_status,
|
|
per_person: true,
|
|
};
|
|
|
|
const ARRIVAL_FIELDS: &[Field] = &[
|
|
field("arrived_on", "Arrival date", Input::Date).req("Enter the arrival date."),
|
|
field("port", "Port of entry", Input::Text).suggest("ports"),
|
|
field("admission", "Admitted with", Input::Choice(ADMISSIONS))
|
|
.req("Choose how the person was admitted."),
|
|
field("visa_id", "Visa", Input::Visa).hint("The visa used for this entry, if any."),
|
|
field("permitted_until", "Permitted to stay until", Input::Date)
|
|
.req("Enter the date in the arrival stamp.")
|
|
.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.",
|
|
),
|
|
field("tdac_submitted_on", "TDAC filed on", Input::Date),
|
|
field("departed_on", "Departure date", Input::Date)
|
|
.hint("Empty while the person is in Thailand."),
|
|
field("departure_port", "Port of departure", Input::Text).suggest("ports"),
|
|
field("notes", "Notes", Input::Area).wide(),
|
|
];
|
|
|
|
pub static ARRIVALS: Kind = Kind {
|
|
slug: "arrivals",
|
|
table: "arrivals",
|
|
entity: Entity::Arrival,
|
|
one: "arrival",
|
|
title: "Arrivals and departures",
|
|
lead: "Each entry into Thailand, from the arrival stamp, with the TDAC filed for it. The departure date closes the stay; the 90-day count starts again at the next arrival.",
|
|
fields: ARRIVAL_FIELDS,
|
|
headline: &["arrived_on", "port"],
|
|
order: "arrived_on DESC, id DESC",
|
|
date_order: &[
|
|
DateOrder {
|
|
earlier: "arrived_on",
|
|
later: "permitted_until",
|
|
target: "permitted_until",
|
|
message: "The permitted stay cannot end before the arrival.",
|
|
},
|
|
DateOrder {
|
|
earlier: "arrived_on",
|
|
later: "departed_on",
|
|
target: "departed_on",
|
|
message: "The departure cannot come before the arrival.",
|
|
},
|
|
DateOrder {
|
|
earlier: "tdac_submitted_on",
|
|
later: "arrived_on",
|
|
target: "tdac_submitted_on",
|
|
message: "The TDAC is filed before the arrival.",
|
|
},
|
|
],
|
|
check: no_check,
|
|
status: arrival_status,
|
|
per_person: true,
|
|
};
|
|
|
|
const EXTENSION_FIELDS: &[Field] = &[
|
|
field("applied_on", "Applied on", Input::Date).req("Enter the date of the application."),
|
|
field("basis", "Reason", Input::Choice(BASES)).req("Choose the reason for the extension."),
|
|
field("decision", "Decision", Input::Choice(DECISIONS)).req("Choose the decision."),
|
|
field("permitted_until", "Permitted to stay until", Input::Date).hint(
|
|
"The date in the stamp: the new end of the stay, or the day to return for the decision.",
|
|
),
|
|
field("office", "Immigration office", Input::Text).suggest("offices"),
|
|
field("receipt_no", "Receipt number", Input::Code),
|
|
field("fee_thb", "Fee in THB", Input::Money).hint("1,900 THB for an extension of stay."),
|
|
field("notes", "Notes", Input::Area).wide(),
|
|
];
|
|
|
|
pub static EXTENSIONS: Kind = Kind {
|
|
slug: "extensions",
|
|
table: "extensions",
|
|
entity: Entity::Extension,
|
|
one: "extension of stay",
|
|
title: "Extensions of stay",
|
|
lead: "An application on form TM.7 and its outcome. A first application for work is often stamped \"under consideration\" for 30 days; record that, and the approval as a second record when it comes.",
|
|
fields: EXTENSION_FIELDS,
|
|
headline: &["applied_on", "decision"],
|
|
order: "applied_on DESC, id DESC",
|
|
date_order: &[DateOrder {
|
|
earlier: "applied_on",
|
|
later: "permitted_until",
|
|
target: "permitted_until",
|
|
message: "The stamp's date cannot come before the application.",
|
|
}],
|
|
check: extension_check,
|
|
status: extension_status,
|
|
per_person: true,
|
|
};
|
|
|
|
const REPORT_FIELDS: &[Field] = &[
|
|
field("reported_on", "Reported on", Input::Date).req("Enter the date of the report."),
|
|
field("method", "How", Input::Choice(REPORT_METHODS)).req("Choose how it was reported."),
|
|
field("receipt_no", "Receipt number", Input::Code),
|
|
field("next_due_on", "Next report due", Input::Date).hint("The date printed on the receipt."),
|
|
field("notes", "Notes", Input::Area).wide(),
|
|
];
|
|
|
|
pub static REPORTS: Kind = Kind {
|
|
slug: "reports",
|
|
table: "ninety_day_reports",
|
|
entity: Entity::Report,
|
|
one: "90-day report",
|
|
title: "90-day reports",
|
|
lead: "The notification of residence on form TM.47. The receipt names the date of the next report; that date wins over any calculation.",
|
|
fields: REPORT_FIELDS,
|
|
headline: &["reported_on", "method"],
|
|
order: "reported_on DESC, id DESC",
|
|
date_order: &[DateOrder {
|
|
earlier: "reported_on",
|
|
later: "next_due_on",
|
|
target: "next_due_on",
|
|
message: "The next report cannot be due before this one was made.",
|
|
}],
|
|
check: no_check,
|
|
status: report_status,
|
|
per_person: true,
|
|
};
|
|
|
|
const REENTRY_FIELDS: &[Field] = &[
|
|
field("kind", "Kind", Input::Choice(REENTRY_KINDS)).req("Choose single or multiple."),
|
|
field("number", "Permit number", Input::Code),
|
|
field("issued_on", "Issued on", Input::Date).req("Enter the date of issue."),
|
|
field("valid_until", "Valid until", Input::Date)
|
|
.req("Enter the date the permit ends.")
|
|
.hint("The end of the permission to stay it protects."),
|
|
field("office", "Issued by", Input::Text).suggest("offices"),
|
|
field("notes", "Notes", Input::Area).wide(),
|
|
];
|
|
|
|
pub static REENTRY_PERMITS: Kind = Kind {
|
|
slug: "reentry-permits",
|
|
table: "reentry_permits",
|
|
entity: Entity::ReentryPermit,
|
|
one: "re-entry permit",
|
|
title: "Re-entry permits",
|
|
lead: "A re-entry permit (TM.8) keeps the permission to stay when the person travels abroad. Leaving without one ends it.",
|
|
fields: REENTRY_FIELDS,
|
|
headline: &["kind", "valid_until"],
|
|
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.",
|
|
}],
|
|
check: no_check,
|
|
status: until_status,
|
|
per_person: true,
|
|
};
|
|
|
|
const WORK_PERMIT_FIELDS: &[Field] = &[
|
|
field("company_id", "Employer", Input::Company)
|
|
.req("Choose the employer.")
|
|
.hint("Companies are kept under Companies."),
|
|
field("number", "Work permit number", Input::Code),
|
|
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(),
|
|
];
|
|
|
|
pub static WORK_PERMITS: Kind = Kind {
|
|
slug: "work-permits",
|
|
table: "work_permits",
|
|
entity: Entity::WorkPermit,
|
|
one: "work permit",
|
|
title: "Work permits",
|
|
lead: "The work permit names the employer and the position. It is renewed together with the extension of stay.",
|
|
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.",
|
|
},
|
|
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,
|
|
};
|
|
|
|
const COMPANY_FIELDS: &[Field] = &[
|
|
field("name", "Name in English", Input::Text)
|
|
.req("Enter the company's name as registered.")
|
|
.wide(),
|
|
field("name_th", "Name in Thai", Input::Text).wide(),
|
|
field("registration_no", "Registration number", Input::Digits)
|
|
.hint("The 13-digit juristic person number, which is also the tax ID."),
|
|
field("business", "Type of business", Input::Text),
|
|
field("house_no", "House number", Input::Text),
|
|
field("moo", "Moo (village number)", Input::Text),
|
|
field("building", "Village, building or office", Input::Text).wide(),
|
|
field("soi", "Soi", Input::Text),
|
|
field("road", "Road", Input::Text),
|
|
field("subdistrict", "Subdistrict (tambon)", Input::Text),
|
|
field("district", "District (amphoe)", Input::Text),
|
|
field("province", "Province", Input::Text).suggest("provinces"),
|
|
field("postal_code", "Postal code", Input::Digits),
|
|
field("office_gps", "GPS position of the office", Input::Gps)
|
|
.hint(
|
|
"As Google Maps copies it: right-click the office on the map and click the numbers. A link to the place works too.",
|
|
)
|
|
.wide(),
|
|
field("phone", "Phone", Input::Text),
|
|
field("email", "Email", Input::Text),
|
|
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(),
|
|
];
|
|
|
|
pub static COMPANIES: Kind = Kind {
|
|
slug: "companies",
|
|
table: "companies",
|
|
entity: Entity::Company,
|
|
one: "company",
|
|
title: "Companies",
|
|
lead: "As in the company certificate. The registered address and the director go onto the employer's forms.",
|
|
fields: COMPANY_FIELDS,
|
|
headline: &["name"],
|
|
order: "lower(name), id",
|
|
date_order: &[],
|
|
check: company_check,
|
|
status: no_status,
|
|
per_person: false,
|
|
};
|
|
|
|
/// The record kinds of a stay, in the order of the person's Stay tab.
|
|
pub static STAY: [&Kind; 6] = [
|
|
&ARRIVALS,
|
|
&EXTENSIONS,
|
|
&REPORTS,
|
|
&VISAS,
|
|
&REENTRY_PERMITS,
|
|
&WORK_PERMITS,
|
|
];
|
|
|
|
// ----------------------------------------------------- checks and chips
|
|
|
|
pub(crate) fn val<'a>(v: &'a Values, k: &str) -> &'a str {
|
|
v.get(k).map(String::as_str).unwrap_or("")
|
|
}
|
|
|
|
fn date(v: &Values, k: &str) -> Option<NaiveDate> {
|
|
dates::parse_date(val(v, k))
|
|
}
|
|
|
|
pub(crate) fn no_check(_: &Values, _: &mut Errors) {}
|
|
|
|
pub(crate) fn no_status(_: &Values, _: NaiveDate) -> Option<Status> {
|
|
None
|
|
}
|
|
|
|
fn extension_check(v: &Values, e: &mut Errors) {
|
|
let decision = val(v, "decision");
|
|
if !decision.is_empty() && decision != "refused" && val(v, "permitted_until").is_empty() {
|
|
err(e, "permitted_until", "Enter the date in the stamp.");
|
|
}
|
|
}
|
|
|
|
fn company_check(v: &Values, e: &mut Errors) {
|
|
let reg = val(v, "registration_no");
|
|
if !reg.is_empty() && !thai_id_valid(reg) {
|
|
err(
|
|
e,
|
|
"registration_no",
|
|
"A registration number has 13 digits and ends in a check digit, which does not match here. Check the number for a typo.",
|
|
);
|
|
}
|
|
let postal = val(v, "postal_code");
|
|
if !postal.is_empty() && postal.len() != 5 {
|
|
err(e, "postal_code", "A Thai postal code has five digits.");
|
|
}
|
|
let email = val(v, "email");
|
|
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
|
|
/// citizens): weights 13 down to 2 on the first twelve digits.
|
|
pub fn thai_id_valid(s: &str) -> bool {
|
|
let d: Vec<u32> = s.chars().filter_map(|c| c.to_digit(10)).collect();
|
|
if d.len() != 13 || s.chars().count() != 13 {
|
|
return false;
|
|
}
|
|
let sum: u32 = d[..12].iter().zip((2..=13).rev()).map(|(x, w)| x * w).sum();
|
|
(11 - sum % 11) % 10 == d[12]
|
|
}
|
|
|
|
fn visa_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
let until = date(v, "valid_until")?;
|
|
(until >= today).then(|| Status {
|
|
level: "ok",
|
|
label: format!("Valid for entry until {}", dates::fmt_date(until)),
|
|
})
|
|
}
|
|
|
|
fn arrival_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
if !val(v, "departed_on").is_empty() {
|
|
return None;
|
|
}
|
|
let until = date(v, "permitted_until")?;
|
|
Some(if until >= today {
|
|
Status {
|
|
level: "ok",
|
|
label: "In Thailand".into(),
|
|
}
|
|
} else {
|
|
Status {
|
|
level: "bad",
|
|
label: format!("Stamp ended {}", dates::fmt_date(until)),
|
|
}
|
|
})
|
|
}
|
|
|
|
fn extension_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
match val(v, "decision") {
|
|
"consideration" => Some(Status {
|
|
level: "warn",
|
|
label: "Under consideration".into(),
|
|
}),
|
|
"refused" => Some(Status {
|
|
level: "bad",
|
|
label: "Refused".into(),
|
|
}),
|
|
_ => date(v, "permitted_until")
|
|
.filter(|d| *d >= today)
|
|
.map(|d| Status {
|
|
level: "ok",
|
|
label: format!("Permitted until {}", dates::fmt_date(d)),
|
|
}),
|
|
}
|
|
}
|
|
|
|
fn report_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
let next = date(v, "next_due_on")?;
|
|
(next >= today).then(|| Status {
|
|
level: "ok",
|
|
label: format!("Next due {}", dates::fmt_date(next)),
|
|
})
|
|
}
|
|
|
|
fn until_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
let until = date(v, "valid_until")?;
|
|
(until >= today).then(|| Status {
|
|
level: "ok",
|
|
label: format!("Valid until {}", dates::fmt_date(until)),
|
|
})
|
|
}
|
|
|
|
fn work_permit_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
let until = date(v, "valid_until")?;
|
|
if until < today {
|
|
None
|
|
} else if until <= today + TimeDelta::days(60) {
|
|
Some(Status {
|
|
level: "warn",
|
|
label: format!("Expires {}", dates::relative(today, until)),
|
|
})
|
|
} else {
|
|
Some(Status {
|
|
level: "ok",
|
|
label: format!("Valid until {}", dates::fmt_date(until)),
|
|
})
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------- reading forms
|
|
|
|
/// The choices for the reference fields: the person's passports and visas,
|
|
/// and the companies. Each is (id, label).
|
|
#[derive(Clone, Debug, Default, Serialize)]
|
|
pub struct Options {
|
|
pub passports: Vec<(String, String)>,
|
|
pub visas: Vec<(String, String)>,
|
|
pub companies: Vec<(String, String)>,
|
|
pub lawyers: Vec<(String, String)>,
|
|
pub clients: Vec<(String, String)>,
|
|
}
|
|
|
|
impl Options {
|
|
fn list(&self, input: Input) -> &[(String, String)] {
|
|
match input {
|
|
Input::Passport => &self.passports,
|
|
Input::Visa => &self.visas,
|
|
Input::Company => &self.companies,
|
|
Input::Lawyer => &self.lawyers,
|
|
Input::Client => &self.clients,
|
|
_ => &[],
|
|
}
|
|
}
|
|
|
|
fn label_of(&self, input: Input, id: &str) -> Option<&str> {
|
|
self.list(input)
|
|
.iter()
|
|
.find(|(k, _)| k == id)
|
|
.map(|(_, l)| l.as_str())
|
|
}
|
|
}
|
|
|
|
/// The form's values, trimmed and brought into the stored form.
|
|
pub fn read(kind: &Kind, f: &Fields) -> Values {
|
|
kind.fields
|
|
.iter()
|
|
.map(|fl| {
|
|
let raw = f.get(fl.name).map(String::as_str).unwrap_or("");
|
|
let v = match fl.input {
|
|
Input::Code => compact_upper(raw),
|
|
Input::Digits => 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(),
|
|
};
|
|
(fl.name.to_string(), v)
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
pub fn validate(kind: &Kind, v: &Values, opts: &Options) -> Errors {
|
|
let mut e = Errors::new();
|
|
for fl in kind.fields {
|
|
let value = val(v, fl.name);
|
|
if value.is_empty() {
|
|
if !fl.missing.is_empty() {
|
|
err(&mut e, fl.name, fl.missing);
|
|
}
|
|
continue;
|
|
}
|
|
let limit = if fl.input == Input::Area { 4000 } else { 300 };
|
|
if value.chars().count() > limit {
|
|
err(
|
|
&mut e,
|
|
fl.name,
|
|
format!("This is longer than {limit} characters."),
|
|
);
|
|
continue;
|
|
}
|
|
match fl.input {
|
|
Input::Date => {
|
|
if let Err(msg) = dates::parse_form_date(value) {
|
|
err(&mut e, fl.name, msg);
|
|
}
|
|
}
|
|
Input::Choice(list) => {
|
|
if label(list, value).is_none() {
|
|
err(&mut e, fl.name, "Choose from the list.");
|
|
}
|
|
}
|
|
Input::Money => match value.parse::<i32>() {
|
|
Ok(n) if (0..=1_000_000).contains(&n) => {}
|
|
_ => err(&mut e, fl.name, "Enter whole baht, such as 1900."),
|
|
},
|
|
Input::Digits => {
|
|
if !value.chars().all(|c| c.is_ascii_digit()) {
|
|
err(&mut e, fl.name, "Enter digits only.");
|
|
}
|
|
}
|
|
Input::Passport | Input::Visa | Input::Company | Input::Lawyer | Input::Client => {
|
|
if opts.label_of(fl.input, value).is_none() {
|
|
err(&mut e, fl.name, "Choose from the list.");
|
|
}
|
|
}
|
|
Input::Gps => {
|
|
if let Some(msg) = gps::problem(value) {
|
|
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 => {}
|
|
}
|
|
}
|
|
for o in kind.date_order {
|
|
if let (Some(a), Some(b)) = (date(v, o.earlier), date(v, o.later))
|
|
&& b < a
|
|
{
|
|
err(&mut e, o.target, o.message);
|
|
}
|
|
}
|
|
(kind.check)(v, &mut e);
|
|
e
|
|
}
|
|
|
|
/// The audit log's name for a field: `company_id` is "company".
|
|
pub fn audit_name(name: &str) -> String {
|
|
name.strip_suffix("_id").unwrap_or(name).to_string()
|
|
}
|
|
|
|
/// The names of the fields whose values differ, in the form's order.
|
|
pub fn changed(kind: &Kind, old: &Values, new: &Values) -> Vec<String> {
|
|
kind.fields
|
|
.iter()
|
|
.filter(|f| val(old, f.name) != val(new, f.name))
|
|
.map(|f| audit_name(f.name))
|
|
.collect()
|
|
}
|
|
|
|
// ---------------------------------------------------------------- SQL
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub struct Record {
|
|
pub id: i64,
|
|
pub values: Values,
|
|
}
|
|
|
|
impl Record {
|
|
pub fn get(&self, name: &str) -> &str {
|
|
val(&self.values, name)
|
|
}
|
|
|
|
pub fn date(&self, name: &str) -> Option<NaiveDate> {
|
|
date(&self.values, name)
|
|
}
|
|
}
|
|
|
|
/// Every column as text: dates as YYYY-MM-DD, numbers and ids as digits,
|
|
/// NULL as ''.
|
|
fn columns(kind: &Kind) -> String {
|
|
kind.fields
|
|
.iter()
|
|
.map(|f| match f.input {
|
|
Input::Date => format!("COALESCE(to_char({0}, 'YYYY-MM-DD'), '') AS {0}", f.name),
|
|
Input::Money
|
|
| Input::Amount
|
|
| Input::Count
|
|
| Input::Year
|
|
| Input::Passport
|
|
| Input::Visa
|
|
| Input::Company
|
|
| Input::Lawyer
|
|
| Input::Client => {
|
|
format!("COALESCE({0}::text, '') AS {0}", f.name)
|
|
}
|
|
_ => f.name.to_string(),
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join(", ")
|
|
}
|
|
|
|
fn record_from(kind: &Kind, row: &PgRow) -> Result<Record> {
|
|
let mut values = Values::new();
|
|
for f in kind.fields {
|
|
values.insert(f.name.to_string(), row.try_get::<String, _>(f.name)?);
|
|
}
|
|
Ok(Record {
|
|
id: row.try_get("id")?,
|
|
values,
|
|
})
|
|
}
|
|
|
|
fn select_one(kind: &Kind, lock: bool) -> String {
|
|
let mut sql = format!(
|
|
"SELECT id, {} FROM {} WHERE id = $1",
|
|
columns(kind),
|
|
kind.table
|
|
);
|
|
if kind.per_person {
|
|
sql.push_str(" AND person_id = $2");
|
|
}
|
|
if lock {
|
|
sql.push_str(" FOR UPDATE");
|
|
}
|
|
sql
|
|
}
|
|
|
|
/// A person's records of one kind, in the kind's order.
|
|
pub async fn list(db: &PgPool, kind: &Kind, person: i64) -> Result<Vec<Record>> {
|
|
let sql = format!(
|
|
"SELECT id, {} FROM {} WHERE person_id = $1 ORDER BY {}",
|
|
columns(kind),
|
|
kind.table,
|
|
kind.order
|
|
);
|
|
let rows = sqlx::query(&sql).bind(person).fetch_all(db).await?;
|
|
rows.iter().map(|r| record_from(kind, r)).collect()
|
|
}
|
|
|
|
/// One record; `person` is ignored for kinds that belong to nobody.
|
|
pub async fn get(db: &PgPool, kind: &Kind, person: Option<i64>, id: i64) -> Result<Option<Record>> {
|
|
let sql = select_one(kind, false);
|
|
let mut q = sqlx::query(&sql).bind(id);
|
|
if kind.per_person {
|
|
q = q.bind(person.unwrap_or(-1));
|
|
}
|
|
let row = q.fetch_optional(db).await?;
|
|
row.map(|r| record_from(kind, &r)).transpose()
|
|
}
|
|
|
|
/// One record, locked until the transaction ends.
|
|
pub async fn get_for_update(
|
|
conn: &mut PgConnection,
|
|
kind: &Kind,
|
|
person: Option<i64>,
|
|
id: i64,
|
|
) -> Result<Option<Record>> {
|
|
let sql = select_one(kind, true);
|
|
let mut q = sqlx::query(&sql).bind(id);
|
|
if kind.per_person {
|
|
q = q.bind(person.unwrap_or(-1));
|
|
}
|
|
let row = q.fetch_optional(&mut *conn).await?;
|
|
row.map(|r| record_from(kind, &r)).transpose()
|
|
}
|
|
|
|
fn bind_value(qb: &mut QueryBuilder<'_, Postgres>, f: &Field, v: &Values) {
|
|
let s = val(v, f.name).to_string();
|
|
match f.input {
|
|
Input::Date => {
|
|
qb.push_bind(dates::parse_date(&s));
|
|
}
|
|
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 | Input::Lawyer | Input::Client => {
|
|
qb.push_bind(s.parse::<i64>().ok());
|
|
}
|
|
_ => {
|
|
qb.push_bind(s);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub async fn create(
|
|
conn: &mut PgConnection,
|
|
kind: &Kind,
|
|
person: Option<i64>,
|
|
v: &Values,
|
|
) -> Result<i64> {
|
|
let names: Vec<&str> = kind.fields.iter().map(|f| f.name).collect();
|
|
let mut qb = QueryBuilder::<Postgres>::new(format!("INSERT INTO {} (", kind.table));
|
|
if kind.per_person {
|
|
qb.push("person_id, ");
|
|
}
|
|
qb.push(names.join(", "));
|
|
qb.push(") VALUES (");
|
|
if kind.per_person {
|
|
qb.push_bind(person.unwrap_or(-1));
|
|
qb.push(", ");
|
|
}
|
|
for (i, f) in kind.fields.iter().enumerate() {
|
|
if i > 0 {
|
|
qb.push(", ");
|
|
}
|
|
bind_value(&mut qb, f, v);
|
|
}
|
|
qb.push(") RETURNING id");
|
|
let id: i64 = qb.build_query_scalar().fetch_one(&mut *conn).await?;
|
|
Ok(id)
|
|
}
|
|
|
|
/// False when there is no such record (of this person).
|
|
pub async fn update(
|
|
conn: &mut PgConnection,
|
|
kind: &Kind,
|
|
person: Option<i64>,
|
|
id: i64,
|
|
v: &Values,
|
|
) -> Result<bool> {
|
|
let mut qb = QueryBuilder::<Postgres>::new(format!("UPDATE {} SET ", kind.table));
|
|
for f in kind.fields {
|
|
qb.push(f.name);
|
|
qb.push(" = ");
|
|
bind_value(&mut qb, f, v);
|
|
qb.push(", ");
|
|
}
|
|
qb.push("updated_at = now() WHERE id = ");
|
|
qb.push_bind(id);
|
|
if kind.per_person {
|
|
qb.push(" AND person_id = ");
|
|
qb.push_bind(person.unwrap_or(-1));
|
|
}
|
|
let done = qb.build().execute(&mut *conn).await?;
|
|
Ok(done.rows_affected() == 1)
|
|
}
|
|
|
|
/// False when there is no such record of this person.
|
|
pub async fn delete(conn: &mut PgConnection, kind: &Kind, person: i64, id: i64) -> Result<bool> {
|
|
let sql = format!(
|
|
"DELETE FROM {} WHERE id = $1 AND person_id = $2",
|
|
kind.table
|
|
);
|
|
let done = sqlx::query(&sql)
|
|
.bind(id)
|
|
.bind(person)
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
Ok(done.rows_affected() == 1)
|
|
}
|
|
|
|
// ---------------------------------------------------------------- pages
|
|
|
|
/// A field as the form template draws it.
|
|
#[derive(Debug, Serialize)]
|
|
pub struct FormField {
|
|
pub name: &'static str,
|
|
pub label: &'static str,
|
|
/// text, date, number, select or area
|
|
pub kind: &'static str,
|
|
pub options: Vec<(String, String)>,
|
|
pub blank: &'static str,
|
|
pub hint: &'static str,
|
|
pub required: bool,
|
|
pub suggest: &'static str,
|
|
pub wide: bool,
|
|
pub section: &'static str,
|
|
}
|
|
|
|
pub fn form_fields(kind: &Kind, opts: &Options) -> Vec<FormField> {
|
|
kind.fields
|
|
.iter()
|
|
.map(|fl| {
|
|
let required = !fl.missing.is_empty();
|
|
let blank = if required {
|
|
"Choose one"
|
|
} else {
|
|
"Not recorded"
|
|
};
|
|
let (k, options) = match fl.input {
|
|
Input::Date => ("date", vec![]),
|
|
Input::Area => ("area", vec![]),
|
|
Input::Money | Input::Count | Input::Year => ("number", vec![]),
|
|
Input::Amount => ("text", vec![]),
|
|
Input::Choice(list) => (
|
|
"select",
|
|
list.iter()
|
|
.map(|(a, b)| (a.to_string(), b.to_string()))
|
|
.collect(),
|
|
),
|
|
Input::Passport | Input::Visa | Input::Company | Input::Lawyer | Input::Client => {
|
|
("select", opts.list(fl.input).to_vec())
|
|
}
|
|
Input::Text | Input::Code | Input::Digits | Input::Gps => ("text", vec![]),
|
|
};
|
|
FormField {
|
|
name: fl.name,
|
|
label: fl.label,
|
|
kind: k,
|
|
options,
|
|
blank,
|
|
hint: fl.hint,
|
|
required,
|
|
suggest: fl.suggest,
|
|
wide: fl.wide || fl.input == Input::Area,
|
|
section: fl.section,
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct Part {
|
|
pub text: String,
|
|
/// A link, for a company.
|
|
pub href: String,
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct Item {
|
|
pub label: &'static str,
|
|
pub value: String,
|
|
pub href: String,
|
|
pub pre: bool,
|
|
pub mono: bool,
|
|
}
|
|
|
|
/// A record as its list shows it.
|
|
#[derive(Debug, Serialize)]
|
|
pub struct Shown {
|
|
pub id: i64,
|
|
pub headline: Vec<Part>,
|
|
pub status: Option<Status>,
|
|
/// History: no longer in force.
|
|
pub old: bool,
|
|
pub items: Vec<Item>,
|
|
}
|
|
|
|
pub fn thousands(n: i64) -> String {
|
|
let s = n.abs().to_string();
|
|
let mut out = String::new();
|
|
for (i, c) in s.chars().enumerate() {
|
|
if i > 0 && (s.len() - i).is_multiple_of(3) {
|
|
out.push(',');
|
|
}
|
|
out.push(c);
|
|
}
|
|
if n < 0 { format!("-{out}") } else { out }
|
|
}
|
|
|
|
/// A value as people read it, and a link where it names a company.
|
|
pub fn shown_value(fl: &Field, raw: &str, opts: &Options) -> Part {
|
|
let text = match fl.input {
|
|
Input::Date => dates::parse_date(raw)
|
|
.map(dates::fmt_date)
|
|
.unwrap_or_else(|| raw.to_string()),
|
|
Input::Choice(list) => label(list, raw).unwrap_or(raw).to_string(),
|
|
Input::Money | Input::Amount => raw
|
|
.parse::<i64>()
|
|
.map(|n| format!("{} THB", thousands(n)))
|
|
.unwrap_or_else(|_| raw.to_string()),
|
|
Input::Passport | Input::Visa | Input::Company | Input::Lawyer | Input::Client => opts
|
|
.label_of(fl.input, raw)
|
|
.map(str::to_string)
|
|
.unwrap_or_else(|| format!("record {raw}")),
|
|
_ => raw.to_string(),
|
|
};
|
|
let href = match fl.input {
|
|
Input::Company => format!("/companies/{raw}"),
|
|
Input::Client => format!("/clients/{raw}"),
|
|
Input::Lawyer => format!("/lawyers/{raw}"),
|
|
_ => String::new(),
|
|
};
|
|
Part { text, href }
|
|
}
|
|
|
|
pub fn show(kind: &Kind, r: &Record, opts: &Options, today: NaiveDate) -> Shown {
|
|
let headline = kind
|
|
.headline
|
|
.iter()
|
|
.filter_map(|n| {
|
|
let fl = kind.field(n)?;
|
|
let raw = r.get(n);
|
|
(!raw.is_empty()).then(|| shown_value(fl, raw, opts))
|
|
})
|
|
.collect();
|
|
let items = kind
|
|
.fields
|
|
.iter()
|
|
.filter(|fl| !kind.headline.contains(&fl.name) && !r.get(fl.name).is_empty())
|
|
.map(|fl| {
|
|
let p = shown_value(fl, r.get(fl.name), opts);
|
|
Item {
|
|
label: fl.label,
|
|
value: p.text,
|
|
href: p.href,
|
|
pre: fl.input == Input::Area,
|
|
mono: matches!(fl.input, Input::Code | Input::Digits),
|
|
}
|
|
})
|
|
.collect();
|
|
let status = (kind.status)(&r.values, today);
|
|
Shown {
|
|
id: r.id,
|
|
headline,
|
|
old: status.is_none(),
|
|
status,
|
|
items,
|
|
}
|
|
}
|
|
|
|
/// "Non-Immigrant B, V0000101": a visa in a selection list.
|
|
pub fn visa_choice(r: &Record) -> String {
|
|
let mut s = visa_category_short(r.get("category"));
|
|
if !r.get("number").is_empty() {
|
|
s = format!("{s}, {}", r.get("number"));
|
|
}
|
|
if let Some(d) = r.date("valid_until") {
|
|
s = format!("{s}, enter before {}", dates::fmt_date(d));
|
|
}
|
|
s
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn fields(pairs: &[(&str, &str)]) -> Fields {
|
|
pairs
|
|
.iter()
|
|
.map(|(k, v)| (k.to_string(), v.to_string()))
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn thai_check_digits() {
|
|
// published tax IDs of two listed companies, and the demo numbers
|
|
assert!(thai_id_valid("0107536000102"));
|
|
assert!(thai_id_valid("0107544000108"));
|
|
assert!(thai_id_valid("0999999000004"));
|
|
assert!(thai_id_valid("0999999000012"));
|
|
assert!(!thai_id_valid("0107536000103"));
|
|
assert!(!thai_id_valid("010753600010"));
|
|
assert!(!thai_id_valid("01075360001021"));
|
|
}
|
|
|
|
#[test]
|
|
fn every_kind_has_sound_fields() {
|
|
for kind in STAY.iter().copied().chain([&COMPANIES]) {
|
|
let mut seen = std::collections::HashSet::new();
|
|
for f in kind.fields {
|
|
assert!(seen.insert(f.name), "{}: {} twice", kind.slug, f.name);
|
|
assert!(
|
|
f.name.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
|
|
"{}: {} is no plain column name",
|
|
kind.slug,
|
|
f.name
|
|
);
|
|
}
|
|
for h in kind.headline {
|
|
assert!(kind.field(h).is_some(), "{}: headline {h}", kind.slug);
|
|
}
|
|
for o in kind.date_order {
|
|
for n in [o.earlier, o.later, o.target] {
|
|
assert_eq!(
|
|
kind.field(n).map(|f| f.input),
|
|
Some(Input::Date),
|
|
"{}: {n}",
|
|
kind.slug
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn reads_and_checks_an_arrival() {
|
|
let opts = Options {
|
|
passports: vec![("7".into(), "C01X00T47 (Germany)".into())],
|
|
..Options::default()
|
|
};
|
|
let v = read(
|
|
&ARRIVALS,
|
|
&fields(&[
|
|
("arrived_on", "2026-09-01"),
|
|
("admission", "exempt"),
|
|
("permitted_until", "2026-08-30"),
|
|
("passport_id", "8"),
|
|
("flight", " tg 110 "),
|
|
("tdac_no", "ab 12"),
|
|
("tdac_submitted_on", "2026-09-02"),
|
|
]),
|
|
);
|
|
assert_eq!(v["flight"], "TG110");
|
|
assert_eq!(v["tdac_no"], "AB12");
|
|
let e = validate(&ARRIVALS, &v, &opts);
|
|
assert!(e["permitted_until"].contains("before the arrival"));
|
|
assert!(e["tdac_submitted_on"].contains("before the arrival"));
|
|
assert_eq!(e["passport_id"], "Choose from the list.");
|
|
assert!(!e.contains_key("arrived_on"));
|
|
|
|
let empty = validate(&ARRIVALS, &read(&ARRIVALS, &Fields::new()), &opts);
|
|
assert_eq!(empty["arrived_on"], "Enter the arrival date.");
|
|
assert_eq!(empty["admission"], "Choose how the person was admitted.");
|
|
}
|
|
|
|
#[test]
|
|
fn extension_needs_the_stamp_unless_refused() {
|
|
let o = Options::default();
|
|
let mut v = read(
|
|
&EXTENSIONS,
|
|
&fields(&[
|
|
("applied_on", "2026-10-01"),
|
|
("basis", "work"),
|
|
("decision", "approved"),
|
|
("fee_thb", "1,900"),
|
|
]),
|
|
);
|
|
assert_eq!(v["fee_thb"], "1900");
|
|
assert!(validate(&EXTENSIONS, &v, &o).contains_key("permitted_until"));
|
|
v.insert("decision".into(), "refused".into());
|
|
assert!(validate(&EXTENSIONS, &v, &o).is_empty());
|
|
v.insert("fee_thb".into(), "lots".into());
|
|
assert!(validate(&EXTENSIONS, &v, &o).contains_key("fee_thb"));
|
|
}
|
|
|
|
#[test]
|
|
fn companies_check_numbers() {
|
|
let o = Options::default();
|
|
let v = read(
|
|
&COMPANIES,
|
|
&fields(&[
|
|
("name", "Demo Co., Ltd."),
|
|
("registration_no", "0-9999-99000-00-5"),
|
|
("postal_code", "5020"),
|
|
("email", "nope"),
|
|
]),
|
|
);
|
|
assert_eq!(v["registration_no"], "0999999000005");
|
|
let e = validate(&COMPANIES, &v, &o);
|
|
assert!(e["registration_no"].contains("check digit"));
|
|
assert!(e.contains_key("postal_code") && e.contains_key("email"));
|
|
}
|
|
|
|
#[test]
|
|
fn changed_names_fields_without_values() {
|
|
let old = read(
|
|
&WORK_PERMITS,
|
|
&fields(&[("company_id", "1"), ("number", "A1")]),
|
|
);
|
|
let new = read(
|
|
&WORK_PERMITS,
|
|
&fields(&[("company_id", "2"), ("number", "A1")]),
|
|
);
|
|
assert_eq!(changed(&WORK_PERMITS, &old, &new), vec!["company"]);
|
|
assert!(changed(&WORK_PERMITS, &old, &old).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn shows_values_as_people_read_them() {
|
|
let opts = Options {
|
|
companies: vec![("3".into(), "Demo Engineering Co., Ltd.".into())],
|
|
..Options::default()
|
|
};
|
|
let r = Record {
|
|
id: 1,
|
|
values: read(
|
|
&WORK_PERMITS,
|
|
&fields(&[
|
|
("company_id", "3"),
|
|
("number", "wp 1"),
|
|
("valid_until", "2027-01-31"),
|
|
]),
|
|
),
|
|
};
|
|
let s = show(
|
|
&WORK_PERMITS,
|
|
&r,
|
|
&opts,
|
|
dates::parse_date("2026-12-15").unwrap(),
|
|
);
|
|
assert_eq!(s.headline[0].text, "Demo Engineering Co., Ltd.");
|
|
assert_eq!(s.headline[0].href, "/companies/3");
|
|
assert_eq!(s.headline[1].text, "WP1");
|
|
assert_eq!(s.items[0].value, "Jan 31, 2027");
|
|
assert_eq!(s.status.unwrap().level, "warn");
|
|
assert_eq!(thousands(1900), "1,900");
|
|
assert_eq!(thousands(20000), "20,000");
|
|
assert_eq!(thousands(950), "950");
|
|
}
|
|
|
|
#[test]
|
|
fn visa_labels() {
|
|
assert_eq!(visa_category_short("non-b"), "Non-Immigrant B");
|
|
assert_eq!(visa_category_short("dtv"), "DTV");
|
|
assert_eq!(visa_category_short("smart"), "SMART visa");
|
|
}
|
|
}
|