diff --git a/AGENTS.md b/AGENTS.md index a116c05..9058f2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,13 @@ visa.buildfor.life holds passport data of real people. Read this file and - **No inline script or style.** The Content Security Policy refuses them; `tests/pages.rs` checks the templates. - **Migrations** are never edited once they are on `main`; add a new file. +- **A new kind of record** for a stay is a migration and one `Kind` in + `src/records.rs`; the routes, the form, the Stay tab and the audit entries + follow from it. A reference to another record is a selection (`Input:: + Passport`, `Visa`, `Company`) whose choices are checked on the server. +- **Deadline rules** live in `src/deadlines.rs` with a unit test each, and in + docs/PLAN.md ("Deadline rules") with their sources. A date from a receipt + or a stamp wins over a calculated one. - **Dates** are shown as "Nov 17, 2026" in Chiang Mai time (`src/dates.rs`); countries are ISO 3166-1 alpha-3 codes as in the passport's zone (`src/countries.rs`, generated by `scripts/gen_countries.py`). @@ -49,6 +56,9 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | `src/session.rs` | sessions in PostgreSQL, keyed by the SHA-256 of the cookie | | `src/audit.rs` | the activity log | | `src/people.rs` | people, passports, addresses: validation and SQL | +| `src/records.rs` | the stay records and companies, one `Kind` each: fields, checks, SQL, display | +| `src/deadlines.rs` | the deadline rules as a pure function (`assess`), and loading their facts | +| `src/companies.rs` | what only companies need: list, archive, selections, employees | | `src/mrz.rs` | reading the passport's machine-readable zone (ICAO 9303, TD3) | | `src/web/` | routes, the login gate, pages | | `templates/` | minijinja templates, compiled in by `build.rs` | diff --git a/README.md b/README.md index 768d968..cc9bf09 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ # visa.buildfor.life visa.buildfor.life keeps the immigration records of the foreigners that B4L -looks after in Thailand: their passports, addresses and TM.30 receipts, and -from phase 2 their visas, arrivals with the TDAC, extensions of stay, -re-entry permits, 90-day reports and work permits. From those records it will -work out every deadline and prepare the documents for the next extension of -stay at Chiang Mai Immigration with the forms filled in. +looks after in Thailand: their passports, addresses and TM.30 receipts, +visas, arrivals with the TDAC, extensions of stay, re-entry permits, 90-day +reports and work permits, and the companies that employ them. From those +records it works out every deadline, and from phase 5 it prepares the +documents for the next extension of stay at Chiang Mai Immigration with the +forms filled in. B4L's own staff use it first. The data model treats everyone as a client of an agency whose staff see all records, so it can grow into the internal tool @@ -17,10 +18,22 @@ view and change of a person's record goes into an append-only activity log that names the fields changed but never their values, as Thailand's Personal Data Protection Act (PDPA) asks. -## What works now (phase 1) +## What works now (phases 1 and 2) -- A list of people with a filter, and a page per person with personal - details, passports and addresses in Thailand. +- The Deadlines page: every person's coming deadlines, the most urgent + first, with a filter by employer. It covers the 90-day report with its + windows online and in person, the window for the next extension of stay, + a decision to collect, overstay, TM.30 after each arrival, the passport's + and the work permit's expiry, and visas still to be used. +- A list of people with a filter and each person's next deadline, and a + page per person with three tabs: the overview with personal details, + passports and addresses; "Visa and stay" with arrivals and departures, + extensions, 90-day reports, visas, re-entry permits and work permits; and + the person's activity. +- Companies with their Thai name, registration number (the check digit is + verified), address and signing director. A person's employer and the + employer on a work permit are chosen from them, and a company's page adds + people to it. - New people and passports from the passport's machine-readable zone: paste the two lines at the bottom of the photo page and the form fills itself in. The check digits catch typing errors. diff --git a/docs/PLAN.md b/docs/PLAN.md index 495eb44..f9294b8 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # visa.buildfor.life: plan -> Phase 1 built on November 17, 2026. **Resume here: phase 2, task 2.1.** +> Phases 1 and 2 built on November 17, 2026. **Resume here: phase 3, task 3.1.** visa.buildfor.life keeps the immigration records of the foreigners that B4L looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -28,6 +28,7 @@ The first round of questions was answered on November 17, 2026. | First extension pack | Non-B with a work permit, employer B4L, at Chiang Mai Immigration | | Reminders | the dashboard first; later a Matrix room message and an email to the person concerned | | Repository | private `B4L/visa`; the fleet then needs a read token for its flake input | +| Employers | companies are records of their own under Companies; a person's employer and a work permit's employer are chosen from them, and a company's page adds people to it | Kanidm keeps persons, groups and OAuth2 clients in one namespace, so the client cannot be called `visa` like the group. It is `visa-web`, as @@ -67,17 +68,18 @@ made of. | Table | Holds | Phase | | -------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----- | -| `people` | names as in the passport, title, sex, birth date and place, nationality, occupation, employer, phone, email, notes; archiving | 1 | +| `people` | names as in the passport, title, sex, birth date and place, nationality, occupation, employer (a company), phone, email, notes; archiving | 1 | | `passports` | number, issuing state, issue and expiry dates, issuing authority, the MRZ as read; the current one has the latest expiry | 1 | | `addresses` | the address in Thailand in the order Thai forms use, moving dates, the house master and the TM.30 receipt | 1 | | `sessions` | signed-in sessions | 1 | | `audit_log` | who viewed or changed which record, append-only | 1 | +| `companies` | name in English and Thai, the 13-digit registration number with its check digit, address, the director who signs; archiving | 2 | | `visas` | visa category (Non-B, Non-O, DTV and others), number, place and date of issue, validity, entries | 2 | -| `entries` | arrival date, port, flight, visa used, permitted-until date, TDAC number; departure date when the person left | 2 | +| `arrivals` | arrival date, port, flight, visa used, permitted-until date, TDAC number; departure date when the person left | 2 | | `extensions` | extensions of stay: approval date, new permitted-until date, reason, office, receipt | 2 | | `reentry_permits` | TM.8 permits, single or multiple, valid until | 2 | | `ninety_day_reports` | the report date, the way it was filed, the receipt and the next due date printed on it | 2 | -| `work_permits` | number, employer, position, validity | 2 | +| `work_permits` | number, employer (a company), position, validity | 2 | | `documents` | encrypted uploads tied to a person and a record | 4 | ## Deadline rules @@ -91,14 +93,19 @@ shows a calculated date as an estimate until a receipt confirms it. receipt names the next date. Leaving Thailand ends the count; after the next arrival it starts again from day 1. A report in person, or by someone the person authorizes, is accepted from 15 days before to 7 days after the - due date. Online it is accepted from 15 days before to 8 days before, and - never after a new passport until one report was made in person. A late - report costs 2,000 THB; being caught without one, up to 5,000 THB. The - Immigration Bureau treats a first extension of stay as the first report. + due date. Online it is accepted from 15 days before to 7 days before. The + first report after a new passport, and the first after an extension of + stay, is made in person. A late report costs 2,000 THB; being caught + without one, up to 5,000 THB. An extension of stay starts the count again, + so when the permission to stay ends before the next report is due, the app + shows no report: the person either leaves or extends. - **Extension of stay (TM.7).** The application must be made before the permitted-until date. Chiang Mai accepts it from 30 days before (some categories 45); the app opens the window 30 days before and counts down to - the last working day. An overstay costs 500 THB a day. + the last working day, the Friday when the permission ends on a weekend. + An overstay costs 500 THB a day, at most 20,000 THB. A first application + for work is often stamped "under consideration" for 30 days; the app then + shows the day to return for the decision. - **Passport.** An extension never runs past the passport's expiry, so the app warns 12 months before expiry and marks a passport with less than six months left. @@ -148,8 +155,8 @@ dark at desktop and phone width, a commit and a push. | Phase | Content | Status | | ----- | --------------------------------------------------------------------------------------------------------------- | ---------------------------- | | 1 | App, Kanidm login, people, passports with MRZ reading, addresses in Thailand, audit log, demo data, CI | built Nov 17, 2026 | -| 2 | Stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | **next** | -| 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | | +| 2 | Companies; stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | built Nov 17, 2026 | +| 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | **next** | | 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo), viewing and download, all audited | | | 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment, TM.47, TM.8 and STM.1 as PDF | | | 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | | @@ -175,16 +182,25 @@ dark at desktop and phone width, a commit and a push. ### Phase 2: stays and deadlines -- [ ] 2.1 Visas and arrivals: arrival date, port, flight, visa used, +- [x] 2.1 Visas and arrivals: arrival date, port, flight, visa used, permitted-until date, TDAC number and date; departures. -- [ ] 2.2 Extensions of stay and re-entry permits. -- [ ] 2.3 90-day reports with the next due date from the receipt. -- [ ] 2.4 Work permits. -- [ ] 2.5 The deadline engine as pure functions with unit tests for every +- [x] 2.2 Extensions of stay and re-entry permits. +- [x] 2.3 90-day reports with the next due date from the receipt. +- [x] 2.4 Work permits. +- [x] 2.5 The deadline engine as pure functions with unit tests for every rule above (arrival plus 89 days, the windows, a trip resetting the count, the extension window, passport and work permit expiry). -- [ ] 2.6 Dashboard at `/`: every person's next deadlines sorted by urgency; - a timeline on the person page. +- [x] 2.6 Dashboard at `/`: every person's deadlines sorted by urgency, with + a company filter; the person's status and deadlines on the Overview + and the "Visa and stay" tab; the next deadline in the people list. +- [x] 2.7 Companies: list, page, form, archive; the employer chosen from + them on the person form and on work permits; people added to a + company from its page; the people list filtered by employer. + +The six kinds of stay record and companies share one description each +(`Kind` in `src/records.rs`): one form template, one set of routes and the +same audit entries serve them all. A new kind of record is a migration and +one `Kind`. ### Phase 3: on cnx01 diff --git a/migrations/0002_companies_and_stays.sql b/migrations/0002_companies_and_stays.sql new file mode 100644 index 0000000..f3e10d5 --- /dev/null +++ b/migrations/0002_companies_and_stays.sql @@ -0,0 +1,168 @@ +-- visa.buildfor.life, phase 2: companies (the employers, later also the +-- agency's corporate clients) and the records a stay in Thailand is made of: +-- visas, arrivals with the TDAC, extensions of stay, re-entry permits, +-- 90-day reports and work permits (docs/PLAN.md "Data model"). +-- +-- As in 0001: optional text is NOT NULL DEFAULT '', unknown dates are NULL. + +CREATE TABLE companies ( + id BIGSERIAL PRIMARY KEY, + name TEXT NOT NULL, + name_th TEXT NOT NULL DEFAULT '', + -- the 13-digit juristic person number, which is also the tax ID + registration_no TEXT NOT NULL DEFAULT '', + business TEXT NOT NULL DEFAULT '', + -- the registered address, in the order Thai forms use + house_no TEXT NOT NULL DEFAULT '', + moo TEXT NOT NULL DEFAULT '', + building TEXT NOT NULL DEFAULT '', + soi TEXT NOT NULL DEFAULT '', + road TEXT NOT NULL DEFAULT '', + subdistrict TEXT NOT NULL DEFAULT '', + district TEXT NOT NULL DEFAULT '', + province TEXT NOT NULL DEFAULT '', + postal_code TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + -- the director who signs for the company (STM.1, the employer's part of TM.7) + signatory TEXT NOT NULL DEFAULT '', + signatory_position TEXT NOT NULL DEFAULT '', + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + archived_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX companies_registration_no ON companies (registration_no) + WHERE registration_no <> ''; + +-- The employer was free text; it becomes a company, chosen from a list. +ALTER TABLE people ADD COLUMN employer_id BIGINT REFERENCES companies (id); +INSERT INTO companies (name) + SELECT DISTINCT employer FROM people WHERE employer <> ''; +UPDATE people p SET employer_id = c.id + FROM companies c WHERE p.employer <> '' AND c.name = p.employer; +ALTER TABLE people DROP COLUMN employer; +CREATE INDEX people_employer ON people (employer_id); + +CREATE TABLE visas ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + category TEXT NOT NULL, + entries TEXT NOT NULL DEFAULT '', + number TEXT NOT NULL DEFAULT '', + passport_id BIGINT REFERENCES passports (id) ON DELETE SET NULL, + issued_at TEXT NOT NULL DEFAULT '', + issued_on DATE, + -- the last day to enter Thailand with the visa + valid_until DATE NOT NULL, + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (issued_on IS NULL OR issued_on <= valid_until) +); +CREATE INDEX visas_person ON visas (person_id); + +CREATE TABLE arrivals ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + arrived_on DATE NOT NULL, + port TEXT NOT NULL DEFAULT '', + -- visa, exempt, voa (visa on arrival) or reentry (with a re-entry permit) + admission TEXT NOT NULL, + visa_id BIGINT REFERENCES visas (id) ON DELETE SET NULL, + -- the date in the arrival stamp + permitted_until DATE NOT NULL, + passport_id BIGINT REFERENCES passports (id) ON DELETE SET NULL, + flight TEXT NOT NULL DEFAULT '', + -- the Thailand Digital Arrival Card, which replaced the TM.6 card in 2025 + tdac_no TEXT NOT NULL DEFAULT '', + tdac_submitted_on DATE, + departed_on DATE, + departure_port TEXT NOT NULL DEFAULT '', + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (permitted_until >= arrived_on), + CHECK (departed_on IS NULL OR departed_on >= arrived_on), + CHECK (tdac_submitted_on IS NULL OR tdac_submitted_on <= arrived_on) +); +CREATE INDEX arrivals_person ON arrivals (person_id, arrived_on); + +CREATE TABLE extensions ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + applied_on DATE NOT NULL, + -- work, marriage, family, retirement, education, tourism or other + basis TEXT NOT NULL, + -- approved, consideration (the 30-day stamp while it is decided) or refused + decision TEXT NOT NULL, + -- the date in the stamp: the new end of the stay, the day to come back + -- for the decision, or the day to leave after a refusal + permitted_until DATE, + office TEXT NOT NULL DEFAULT '', + receipt_no TEXT NOT NULL DEFAULT '', + fee_thb INTEGER, + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (permitted_until IS NULL OR permitted_until >= applied_on) +); +CREATE INDEX extensions_person ON extensions (person_id, applied_on); + +CREATE TABLE reentry_permits ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + -- single or multiple + kind TEXT NOT NULL, + number TEXT NOT NULL DEFAULT '', + issued_on DATE NOT NULL, + valid_until DATE NOT NULL, + office TEXT NOT NULL DEFAULT '', + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (issued_on <= valid_until) +); +CREATE INDEX reentry_permits_person ON reentry_permits (person_id); + +CREATE TABLE ninety_day_reports ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + reported_on DATE NOT NULL, + -- in-person, agent, online or mail + method TEXT NOT NULL, + receipt_no TEXT NOT NULL DEFAULT '', + -- the date printed on the receipt + next_due_on DATE, + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (next_due_on IS NULL OR next_due_on >= reported_on) +); +CREATE INDEX ninety_day_reports_person ON ninety_day_reports (person_id, reported_on); + +CREATE TABLE work_permits ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + company_id BIGINT REFERENCES companies (id), + number TEXT NOT NULL DEFAULT '', + position TEXT NOT NULL DEFAULT '', + issued_on DATE, + valid_until DATE NOT NULL, + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (issued_on IS NULL OR issued_on <= valid_until) +); +CREATE INDEX work_permits_person ON work_permits (person_id); +CREATE INDEX work_permits_company ON work_permits (company_id); + +-- The audit log names the new records too. Changing a constraint is no +-- update of a row, so the append-only trigger lets it through. +ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check; +ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK ( + entity IN ( + 'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival', + 'extension', 'reentry-permit', 'report', 'work-permit' + ) +); diff --git a/src/audit.rs b/src/audit.rs index 8c3a69f..55d6aa4 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -42,6 +42,13 @@ pub enum Entity { Passport, Address, Session, + Company, + Visa, + Arrival, + Extension, + ReentryPermit, + Report, + WorkPermit, } impl Entity { @@ -51,6 +58,13 @@ impl Entity { Entity::Passport => "passport", Entity::Address => "address", Entity::Session => "session", + Entity::Company => "company", + Entity::Visa => "visa", + Entity::Arrival => "arrival", + Entity::Extension => "extension", + Entity::ReentryPermit => "reentry-permit", + Entity::Report => "report", + Entity::WorkPermit => "work-permit", } } } @@ -112,6 +126,7 @@ struct Row { person_id: Option, fields: Vec, person_name: Option, + company_name: Option, } #[derive(Debug, Serialize)] @@ -123,17 +138,30 @@ pub struct Item { pub what: String, pub person_id: Option, pub person_name: Option, + pub company_id: Option, + pub company_name: Option, pub fields: String, } +/// The record's kind as people say it. +fn noun(entity: &str) -> &str { + match entity { + "reentry-permit" => "re-entry permit", + "work-permit" => "work permit", + "report" => "90-day report", + other => other, + } +} + /// The newest entries first, for one person or for everyone. pub async fn recent(db: &PgPool, person: Option, limit: i64) -> Result> { let rows: Vec = sqlx::query_as( "SELECT a.id, a.at, a.actor, a.action, a.entity, a.entity_id, a.person_id, a.fields, \ CASE WHEN p.id IS NULL THEN NULL \ ELSE upper(p.surname) || ', ' || trim(p.first_name || ' ' || p.middle_name) \ - END AS person_name \ + END AS person_name, c.name AS company_name \ FROM audit_log a LEFT JOIN people p ON p.id = a.person_id \ + LEFT JOIN companies c ON a.entity = 'company' AND c.id = a.entity_id \ WHERE ($1::bigint IS NULL OR a.person_id = $1) \ ORDER BY a.id DESC LIMIT $2", ) @@ -146,9 +174,11 @@ pub async fn recent(db: &PgPool, person: Option, limit: i64) -> Result String::new(), - (e, Some(id)) => format!("{e} {id}"), - (e, None) => e.to_string(), + ("company", _) => String::new(), + (e, Some(id)) => format!("{} {id}", noun(e)), + (e, None) => noun(e).to_string(), }; + let company_id = (r.entity == "company").then_some(r.entity_id).flatten(); Item { id: r.id, at: dates::fmt_datetime(r.at), @@ -157,6 +187,8 @@ pub async fn recent(db: &PgPool, person: Option, limit: i64) -> Result Result> { + let rows: Vec<(i64, String, String, String, String, i64)> = sqlx::query_as( + "SELECT c.id, c.name, c.name_th, c.registration_no, c.province, \ + (SELECT count(*) FROM people p \ + WHERE p.employer_id = c.id AND p.archived_at IS NULL) \ + FROM companies c WHERE (c.archived_at IS NOT NULL) = $1 \ + ORDER BY lower(c.name), c.id", + ) + .bind(archived) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, name, name_th, registration_no, province, people)| { + let q = format!("{name} {name_th} {registration_no} {province}").to_lowercase(); + ListItem { + id, + name, + name_th, + registration_no, + province, + people, + q, + } + }) + .collect()) +} + +/// Companies in the list and in the archive. +pub async fn counts(db: &PgPool) -> Result<(i64, i64)> { + Ok(sqlx::query_as( + "SELECT count(*) FILTER (WHERE archived_at IS NULL), \ + count(*) FILTER (WHERE archived_at IS NOT NULL) FROM companies", + ) + .fetch_one(db) + .await?) +} + +/// The companies to choose from: the active ones, and `keep` (a company +/// already chosen, even when archived since). (id, name) pairs. +pub async fn choices(db: &PgPool, keep: Option) -> Result> { + let rows: Vec<(i64, String)> = sqlx::query_as( + "SELECT id, name FROM companies WHERE archived_at IS NULL OR id = $1 \ + ORDER BY lower(name), id", + ) + .bind(keep) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, name)| (id.to_string(), name)) + .collect()) +} + +/// Every company, archived ones too, to name them in existing records. +pub async fn names(db: &PgPool) -> Result> { + let rows: Vec<(i64, String)> = + sqlx::query_as("SELECT id, name FROM companies ORDER BY lower(name), id") + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, name)| (id.to_string(), name)) + .collect()) +} + +pub async fn name(db: &PgPool, id: i64) -> Result> { + Ok( + sqlx::query_scalar("SELECT name FROM companies WHERE id = $1") + .bind(id) + .fetch_optional(db) + .await?, + ) +} + +/// None when there is no such company; Some(None) while it is active. +pub async fn archived_at(db: &PgPool, id: i64) -> Result>>> { + Ok( + sqlx::query_scalar("SELECT archived_at FROM companies WHERE id = $1") + .bind(id) + .fetch_optional(db) + .await?, + ) +} + +/// Archives or restores; false when nothing changed. +pub async fn set_archived(conn: &mut PgConnection, id: i64, archived: bool) -> Result { + let sql = if archived { + "UPDATE companies SET archived_at = now(), updated_at = now() \ + WHERE id = $1 AND archived_at IS NULL" + } else { + "UPDATE companies SET archived_at = NULL, updated_at = now() \ + WHERE id = $1 AND archived_at IS NOT NULL" + }; + let done = sqlx::query(sql).bind(id).execute(conn).await?; + Ok(done.rows_affected() == 1) +} + +/// Another company has this registration number. +pub async fn registration_taken(db: &PgPool, number: &str, except: Option) -> Result { + if number.is_empty() { + return Ok(false); + } + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM companies WHERE registration_no = $1 \ + AND ($2::bigint IS NULL OR id <> $2))", + ) + .bind(number) + .bind(except) + .fetch_one(db) + .await?) +} + +/// Someone the company employs, with the work permit for it. +#[derive(Debug, Serialize)] +pub struct Employee { + pub id: i64, + pub name: String, + pub nationality: String, + pub permit: Status, +} + +pub async fn employees(db: &PgPool, company: i64, today: NaiveDate) -> Result> { + type Row = (i64, String, String, String, String, Option); + let rows: Vec = sqlx::query_as( + "SELECT p.id, p.surname, p.first_name, p.middle_name, p.nationality, \ + (SELECT max(w.valid_until) FROM work_permits w \ + WHERE w.person_id = p.id AND w.company_id = $1) \ + FROM people p WHERE p.employer_id = $1 AND p.archived_at IS NULL \ + ORDER BY lower(p.surname), lower(p.first_name), p.id", + ) + .bind(company) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, surname, first, middle, nationality, permit)| { + let permit = match permit { + None => Status { + level: "warn", + label: "No work permit recorded".into(), + }, + Some(d) if d < today => Status { + level: "bad", + label: format!("Work permit expired {}", dates::fmt_date(d)), + }, + Some(d) if d <= today + TimeDelta::days(60) => Status { + level: "warn", + label: format!("Work permit expires {}", dates::relative(today, d)), + }, + Some(d) => Status { + level: "ok", + label: format!("Work permit until {}", dates::fmt_date(d)), + }, + }; + Employee { + id, + name: full_name(&surname, &first, &middle), + nationality: countries::name(&nationality) + .unwrap_or(&nationality) + .to_string(), + permit, + } + }) + .collect()) +} + +fn full_name(surname: &str, first: &str, middle: &str) -> String { + let given = if middle.is_empty() { + first.to_string() + } else { + format!("{first} {middle}") + }; + format!("{}, {given}", surname.to_uppercase()) +} + +/// People who could be added as employees: everyone in the list whom the +/// company does not employ yet, with their current employer. +pub async fn candidates(db: &PgPool, company: i64) -> Result> { + type Row = (i64, String, String, String, Option); + let rows: Vec = sqlx::query_as( + "SELECT p.id, p.surname, p.first_name, p.middle_name, c.name \ + FROM people p LEFT JOIN companies c ON c.id = p.employer_id \ + WHERE p.archived_at IS NULL AND p.employer_id IS DISTINCT FROM $1 \ + ORDER BY lower(p.surname), lower(p.first_name), p.id", + ) + .bind(company) + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, surname, first, middle, employer)| { + let mut label = full_name(&surname, &first, &middle); + if let Some(e) = employer { + label = format!("{label} (now with {e})"); + } + (id.to_string(), label) + }) + .collect()) +} + +/// Makes the company the person's employer; false when it already was or +/// the person is archived. +pub async fn hire(conn: &mut PgConnection, company: i64, person: i64) -> Result { + let done = sqlx::query( + "UPDATE people SET employer_id = $2, updated_at = now() \ + WHERE id = $1 AND archived_at IS NULL AND employer_id IS DISTINCT FROM $2", + ) + .bind(person) + .bind(company) + .execute(conn) + .await?; + Ok(done.rows_affected() == 1) +} + +/// Ends the employment in the records; false when the company was not the +/// person's employer. +pub async fn release(conn: &mut PgConnection, company: i64, person: i64) -> Result { + let done = sqlx::query( + "UPDATE people SET employer_id = NULL, updated_at = now() \ + WHERE id = $1 AND employer_id = $2", + ) + .bind(person) + .bind(company) + .execute(conn) + .await?; + Ok(done.rows_affected() == 1) +} + +/// A company as its page shows it. +#[derive(Debug, Serialize)] +pub struct View { + pub id: i64, + pub name: String, + pub name_th: String, + pub registration_no: String, + pub business: String, + pub address: String, + pub phone: String, + pub email: String, + pub signatory: String, + pub signatory_position: String, + pub notes: String, + pub archived: bool, + pub archived_on: String, +} + +pub fn view(r: &Record, archived_at: Option>) -> View { + let address = people::address_line(&AddressInput { + house_no: r.get("house_no").into(), + moo: r.get("moo").into(), + building: r.get("building").into(), + soi: r.get("soi").into(), + road: r.get("road").into(), + subdistrict: r.get("subdistrict").into(), + district: r.get("district").into(), + province: r.get("province").into(), + postal_code: r.get("postal_code").into(), + moved_in_on: None, + moved_out_on: None, + house_master: String::new(), + house_master_phone: String::new(), + tm30_reported_on: None, + tm30_receipt_no: String::new(), + }); + View { + id: r.id, + name: r.get("name").into(), + name_th: r.get("name_th").into(), + registration_no: r.get("registration_no").into(), + business: r.get("business").into(), + address, + phone: r.get("phone").into(), + email: r.get("email").into(), + signatory: r.get("signatory").into(), + signatory_position: r.get("signatory_position").into(), + notes: r.get("notes").into(), + archived: archived_at.is_some(), + archived_on: archived_at + .map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive())) + .unwrap_or_default(), + } +} diff --git a/src/deadlines.rs b/src/deadlines.rs new file mode 100644 index 0000000..c66df71 --- /dev/null +++ b/src/deadlines.rs @@ -0,0 +1,1166 @@ +//! 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")); + } +} diff --git a/src/lib.rs b/src/lib.rs index 47d5015..a589d96 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,15 +2,18 @@ //! for foreigners in Thailand (docs/PLAN.md). pub mod audit; +pub mod companies; pub mod config; pub mod countries; pub mod dates; pub mod db; +pub mod deadlines; pub mod embedded; pub mod forms; pub mod mrz; pub mod oidc; pub mod people; +pub mod records; pub mod seed; pub mod session; pub mod web; diff --git a/src/people.rs b/src/people.rs index b75d52b..ee7c504 100644 --- a/src/people.rs +++ b/src/people.rs @@ -46,7 +46,7 @@ pub struct Person { pub place_of_birth: String, pub nationality: String, pub occupation: String, - pub employer: String, + pub employer_id: Option, pub phone: String, pub email: String, pub notes: String, @@ -86,6 +86,7 @@ pub struct PersonForm { pub place_of_birth: String, pub nationality: String, pub occupation: String, + /// The employer's company id, from the selection. pub employer: String, pub phone: String, pub email: String, @@ -104,7 +105,8 @@ pub struct PersonInput { pub place_of_birth: String, pub nationality: String, pub occupation: String, - pub employer: String, + /// The employer's company. + pub employer: Option, pub phone: String, pub email: String, pub notes: String, @@ -130,7 +132,7 @@ impl From<&Person> for PersonInput { place_of_birth: p.place_of_birth.clone(), nationality: p.nationality.clone(), occupation: p.occupation.clone(), - employer: p.employer.clone(), + employer: p.employer_id, phone: p.phone.clone(), email: p.email.clone(), notes: p.notes.clone(), @@ -171,7 +173,7 @@ impl PersonForm { place_of_birth: p.place_of_birth.clone(), nationality: p.nationality.clone(), occupation: p.occupation.clone(), - employer: p.employer.clone(), + employer: p.employer_id.map(|c| c.to_string()).unwrap_or_default(), phone: p.phone.clone(), email: p.email.clone(), notes: p.notes.clone(), @@ -199,8 +201,17 @@ impl PersonForm { } } - pub fn validate(&self, today: NaiveDate) -> Result { + /// `companies`: the ids the employer may be chosen from. + pub fn validate(&self, today: NaiveDate, companies: &[i64]) -> Result { let mut e = Errors::new(); + let employer = match self.employer.parse::() { + _ if self.employer.is_empty() => None, + Ok(c) if companies.contains(&c) => Some(c), + _ => { + err(&mut e, "employer", "Choose a company from the list."); + None + } + }; if self.surname.is_empty() { err( &mut e, @@ -248,7 +259,7 @@ impl PersonForm { place_of_birth: self.place_of_birth.clone(), nationality: self.nationality.clone(), occupation: self.occupation.clone(), - employer: self.employer.clone(), + employer, phone: self.phone.clone(), email: self.email.clone(), notes: self.notes.clone(), @@ -256,7 +267,7 @@ impl PersonForm { } } -fn looks_like_email(s: &str) -> bool { +pub fn looks_like_email(s: &str) -> bool { match s.split_once('@') { Some((user, host)) => { !user.is_empty() && host.contains('.') && !host.starts_with('.') && !s.contains(' ') @@ -295,7 +306,7 @@ pub async fn get_person_in(conn: &mut PgConnection, id: i64) -> Result Result { let id: i64 = sqlx::query_scalar( "INSERT INTO people (surname, first_name, middle_name, title, sex, date_of_birth, \ - place_of_birth, nationality, occupation, employer, phone, email, notes) \ + place_of_birth, nationality, occupation, employer_id, phone, email, notes) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id", ) .bind(&p.surname) @@ -307,7 +318,7 @@ pub async fn create_person(conn: &mut PgConnection, p: &PersonInput) -> Result sqlx::query( "UPDATE people SET surname = $2, first_name = $3, middle_name = $4, title = $5, \ sex = $6, date_of_birth = $7, place_of_birth = $8, nationality = $9, \ - occupation = $10, employer = $11, phone = $12, email = $13, notes = $14, \ + occupation = $10, employer_id = $11, phone = $12, email = $13, notes = $14, \ updated_at = now() WHERE id = $1", ) .bind(id) @@ -333,7 +344,7 @@ pub async fn update_person(conn: &mut PgConnection, id: i64, p: &PersonInput) -> .bind(&p.place_of_birth) .bind(&p.nationality) .bind(&p.occupation) - .bind(&p.employer) + .bind(p.employer) .bind(&p.phone) .bind(&p.email) .bind(&p.notes) @@ -363,7 +374,8 @@ struct ListRow { middle_name: String, nationality: String, date_of_birth: Option, - employer: String, + employer_id: Option, + employer: Option, passport_number: Option, passport_expires: Option, province: Option, @@ -376,30 +388,42 @@ pub struct ListItem { pub name: String, pub nationality: String, pub age: Option, + pub employer_id: Option, pub employer: String, pub passport_number: String, pub passport_expires: String, pub passport_status: Option, pub province: String, + /// The most urgent deadline; the page fills it in. + pub next: Option, /// Lower-case text the filter box searches. pub q: String, } -pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result> { +/// The people in the list or in the archive; with `company`, only those it +/// employs. +pub async fn list( + db: &PgPool, + archived: bool, + company: Option, + today: NaiveDate, +) -> Result> { let rows: Vec = sqlx::query_as( "SELECT p.id, p.surname, p.first_name, p.middle_name, p.nationality, p.date_of_birth, \ - p.employer, pp.number AS passport_number, pp.expires_on AS passport_expires, \ - a.province \ + p.employer_id, c.name AS employer, pp.number AS passport_number, \ + pp.expires_on AS passport_expires, a.province \ FROM people p \ + LEFT JOIN companies c ON c.id = p.employer_id \ LEFT JOIN LATERAL (SELECT number, expires_on FROM passports \ WHERE person_id = p.id ORDER BY expires_on DESC, id DESC LIMIT 1) pp ON true \ LEFT JOIN LATERAL (SELECT province FROM addresses \ WHERE person_id = p.id AND moved_out_on IS NULL \ ORDER BY moved_in_on DESC NULLS LAST, id DESC LIMIT 1) a ON true \ - WHERE (p.archived_at IS NOT NULL) = $1 \ + WHERE (p.archived_at IS NOT NULL) = $1 AND ($2::bigint IS NULL OR p.employer_id = $2) \ ORDER BY lower(p.surname), lower(p.first_name), p.id", ) .bind(archived) + .bind(company) .fetch_all(db) .await?; Ok(rows @@ -415,9 +439,10 @@ pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result Result>(), vec!["date_of_birth", "email", "title"] @@ -1095,9 +1122,11 @@ mod tests { ("first_name", "Erika"), ("date_of_birth", "1984-08-12"), ("nationality", "DEU"), + ("employer", "3"), ])) - .validate(today) + .validate(today, &[3]) .unwrap(); + assert_eq!(ok.employer, Some(3)); assert_eq!(ok.date_of_birth, Some(d("1984-08-12"))); let mut other = ok.clone(); other.email = "erika@example.com".into(); diff --git a/src/records.rs b/src/records.rs new file mode 100644 index 0000000..3df18c8 --- /dev/null +++ b/src/records.rs @@ -0,0 +1,1251 @@ +//! 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::{Datelike, 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}; + +/// 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; + +#[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, +} + +#[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 `` with suggestions: "ports", "offices" or "provinces". + pub suggest: &'static str, + pub wide: bool, +} + +const fn field(name: &'static str, label: &'static str, input: Input) -> Field { + Field { + name, + label, + input, + missing: "", + hint: "", + suggest: "", + wide: false, + } +} + +impl Field { + const fn req(self, missing: &'static str) -> Field { + Field { missing, ..self } + } + const fn hint(self, hint: &'static str) -> Field { + Field { hint, ..self } + } + const fn suggest(self, suggest: &'static str) -> Field { + Field { suggest, ..self } + } + const fn wide(self) -> Field { + Field { wide: true, ..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}/. + 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, + /// 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("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("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.", + }], + 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("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("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 + +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 { + dates::parse_date(val(v, k)) +} + +fn no_check(_: &Values, _: &mut Errors) {} + +fn no_status(_: &Values, _: NaiveDate) -> Option { + 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."); + } +} + +/// 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 = 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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)>, +} + +impl Options { + fn list(&self, input: Input) -> &[(String, String)] { + match input { + Input::Passport => &self.passports, + Input::Visa => &self.visas, + Input::Company => &self.companies, + _ => &[], + } + } + + 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 => raw.trim().replace([',', ' '], ""), + Input::Area => raw.trim().replace("\r\n", "\n"), + _ => 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 => match dates::parse_date(value) { + Some(d) if (1900..=2100).contains(&d.year()) => {} + _ => err(&mut e, fl.name, "Enter a date such as 2026-11-17."), + }, + Input::Choice(list) => { + if label(list, value).is_none() { + err(&mut e, fl.name, "Choose from the list."); + } + } + Input::Money => match value.parse::() { + 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 => { + if opts.label_of(fl.input, value).is_none() { + err(&mut e, fl.name, "Choose from the list."); + } + } + 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 { + 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 { + 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::Passport | Input::Visa | Input::Company => { + format!("COALESCE({0}::text, '') AS {0}", f.name) + } + _ => f.name.to_string(), + }) + .collect::>() + .join(", ") +} + +fn record_from(kind: &Kind, row: &PgRow) -> Result { + let mut values = Values::new(); + for f in kind.fields { + values.insert(f.name.to_string(), row.try_get::(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> { + 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, id: i64) -> Result> { + 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, + id: i64, +) -> Result> { + 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 => { + qb.push_bind(s.parse::().ok()); + } + Input::Passport | Input::Visa | Input::Company => { + qb.push_bind(s.parse::().ok()); + } + _ => { + qb.push_bind(s); + } + } +} + +pub async fn create( + conn: &mut PgConnection, + kind: &Kind, + person: Option, + v: &Values, +) -> Result { + let names: Vec<&str> = kind.fields.iter().map(|f| f.name).collect(); + let mut qb = QueryBuilder::::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, + id: i64, + v: &Values, +) -> Result { + let mut qb = QueryBuilder::::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 { + 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 fn form_fields(kind: &Kind, opts: &Options) -> Vec { + 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 => ("number", vec![]), + Input::Choice(list) => ( + "select", + list.iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect(), + ), + Input::Passport | Input::Visa | Input::Company => { + ("select", opts.list(fl.input).to_vec()) + } + Input::Text | Input::Code | Input::Digits => ("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, + } + }) + .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, + pub status: Option, + /// History: no longer in force. + pub old: bool, + pub items: Vec, +} + +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 => raw + .parse::() + .map(|n| format!("{} THB", thousands(n))) + .unwrap_or_else(|_| raw.to_string()), + Input::Passport | Input::Visa | Input::Company => opts + .label_of(fl.input, raw) + .map(str::to_string) + .unwrap_or_else(|| format!("record {raw}")), + _ => raw.to_string(), + }; + let href = if fl.input == Input::Company { + format!("/companies/{raw}") + } else { + 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())], + visas: vec![], + companies: vec![], + }; + 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"); + } +} diff --git a/src/seed.rs b/src/seed.rs index 8a8d146..8bde291 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -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, passports: Vec, addresses: Vec, + 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 { + 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 { - 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 { "Berlin", "DEU", "Electrical engineer", - employer, 1, ); let erika_pp = passport( @@ -164,6 +219,73 @@ fn demos(today: NaiveDate) -> Vec { "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 { "Portland, Oregon", "USA", "Product designer", - employer, 2, ); let jane_old = passport( @@ -193,6 +314,16 @@ fn demos(today: NaiveDate) -> Vec { "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 { "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 { "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 { vec![ Demo { person: erika, + employer: Some(0), passports: vec![erika_pp], addresses: vec![ address( @@ -237,9 +444,9 @@ fn demos(today: NaiveDate) -> Vec { "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 { "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 { "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 { "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) -> 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 { 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 { 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 = None; + for (kind, mut values) in demo.stays { + for v in values.values_mut() { + let id_of = |x: Option| 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?; diff --git a/src/web/companies.rs b/src/web/companies.rs new file mode 100644 index 0000000..5e20969 --- /dev/null +++ b/src/web/companies.rs @@ -0,0 +1,319 @@ +//! Pages for companies: the list, a company with the people it employs, the +//! form, archiving, and adding or removing employees. + +use std::sync::Arc; + +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Redirect, Response}; +use axum::{Extension, Form}; +use minijinja::context; +use serde::Deserialize; + +use super::records::datalists; +use super::{AppState, Res, not_found_page, page}; +use crate::audit::{self, Action, Entity, Entry}; +use crate::companies; +use crate::dates; +use crate::forms::{Errors, Fields, err, get}; +use crate::records::{self, COMPANIES, Options, Values}; +use crate::session::User; + +#[derive(Deserialize)] +pub struct ListQuery { + #[serde(default)] + archived: Option, +} + +pub async fn list( + State(st): State>, + Extension(user): Extension, + Query(q): Query, +) -> Res { + let archived = q.archived.as_deref() == Some("1"); + let rows = companies::list(&st.db, archived).await?; + let (n_active, n_archived) = companies::counts(&st.db).await?; + Ok(page( + &st, + &user, + "companies.html", + if archived { + "Archived companies" + } else { + "Companies" + }, + "companies", + StatusCode::OK, + context! { companies => rows, archived, n_active, n_archived }, + )) +} + +fn company_entry<'a>(user: &'a User, action: Action, id: i64, fields: &'a [String]) -> Entry<'a> { + Entry { + actor: &user.login, + action, + entity: Entity::Company, + entity_id: Some(id), + person_id: None, + fields, + } +} + +fn form_page( + st: &AppState, + user: &User, + company: Option<(i64, &str)>, + values: &Values, + errors: &Errors, + status: StatusCode, +) -> Response { + let (heading, mode, action, cancel) = match company { + Some((id, name)) => ( + format!("Edit {name}"), + "edit", + format!("/companies/{id}"), + format!("/companies/{id}"), + ), + None => ( + "New company".to_string(), + "new", + "/companies".to_string(), + "/companies".to_string(), + ), + }; + page( + st, + user, + "record_form.html", + &heading, + "companies", + status, + context! { + heading, + one => "company", + lead => COMPANIES.lead, + mode, + action, + fields => records::form_fields(&COMPANIES, &Options::default()), + values, + errors, + cancel, + ..datalists() + }, + ) +} + +pub async fn new_form(State(st): State>, Extension(user): Extension) -> Res { + Ok(form_page( + &st, + &user, + None, + &Values::new(), + &Errors::new(), + StatusCode::OK, + )) +} + +async fn checked(st: &AppState, f: &Fields, id: Option) -> anyhow::Result<(Values, Errors)> { + let values = records::read(&COMPANIES, f); + let mut errors = records::validate(&COMPANIES, &values, &Options::default()); + let reg = values + .get("registration_no") + .map(String::as_str) + .unwrap_or(""); + if !errors.contains_key("registration_no") + && companies::registration_taken(&st.db, reg, id).await? + { + err( + &mut errors, + "registration_no", + "Another company has this registration number.", + ); + } + Ok((values, errors)) +} + +pub async fn create( + State(st): State>, + Extension(user): Extension, + Form(f): Form, +) -> Res { + let (values, errors) = checked(&st, &f, None).await?; + if !errors.is_empty() { + return Ok(form_page( + &st, + &user, + None, + &values, + &errors, + StatusCode::UNPROCESSABLE_ENTITY, + )); + } + let mut tx = st.db.begin().await?; + let id = records::create(&mut tx, &COMPANIES, None, &values).await?; + audit::record(&mut *tx, &company_entry(&user, Action::Create, id, &[])).await?; + tx.commit().await?; + Ok(Redirect::to(&format!("/companies/{id}")).into_response()) +} + +pub async fn show( + State(st): State>, + Extension(user): Extension, + Path(id): Path, +) -> Res { + let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else { + return Ok(not_found_page(&st)); + }; + let archived_at = companies::archived_at(&st.db, id).await?.flatten(); + let c = companies::view(&r, archived_at); + let employees = companies::employees(&st.db, id, dates::today()).await?; + let candidates = companies::candidates(&st.db, id).await?; + let title = c.name.clone(); + Ok(page( + &st, + &user, + "company.html", + &title, + "companies", + StatusCode::OK, + context! { c, employees, candidates }, + )) +} + +pub async fn edit_form( + State(st): State>, + Extension(user): Extension, + Path(id): Path, +) -> Res { + let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else { + return Ok(not_found_page(&st)); + }; + Ok(form_page( + &st, + &user, + Some((id, r.get("name"))), + &r.values, + &Errors::new(), + StatusCode::OK, + )) +} + +pub async fn update( + State(st): State>, + Extension(user): Extension, + Path(id): Path, + Form(f): Form, +) -> Res { + let mut tx = st.db.begin().await?; + let Some(old) = records::get_for_update(&mut tx, &COMPANIES, None, id).await? else { + return Ok(not_found_page(&st)); + }; + let (values, errors) = checked(&st, &f, Some(id)).await?; + if !errors.is_empty() { + return Ok(form_page( + &st, + &user, + Some((id, old.get("name"))), + &values, + &errors, + StatusCode::UNPROCESSABLE_ENTITY, + )); + } + let changed = records::changed(&COMPANIES, &old.values, &values); + if !changed.is_empty() { + records::update(&mut tx, &COMPANIES, None, id, &values).await?; + audit::record( + &mut *tx, + &company_entry(&user, Action::Update, id, &changed), + ) + .await?; + } + tx.commit().await?; + Ok(Redirect::to(&format!("/companies/{id}")).into_response()) +} + +async fn set_archived(st: &AppState, user: &User, id: i64, archived: bool) -> Res { + if companies::archived_at(&st.db, id).await?.is_none() { + return Ok(not_found_page(st)); + } + let mut tx = st.db.begin().await?; + if companies::set_archived(&mut tx, id, archived).await? { + let action = if archived { + Action::Archive + } else { + Action::Restore + }; + audit::record(&mut *tx, &company_entry(user, action, id, &[])).await?; + } + tx.commit().await?; + Ok(Redirect::to(&format!("/companies/{id}")).into_response()) +} + +pub async fn archive( + State(st): State>, + Extension(user): Extension, + Path(id): Path, +) -> Res { + set_archived(&st, &user, id, true).await +} + +pub async fn restore( + State(st): State>, + Extension(user): Extension, + Path(id): Path, +) -> Res { + set_archived(&st, &user, id, false).await +} + +fn employer_changed<'a>(user: &'a User, person: i64, fields: &'a [String]) -> Entry<'a> { + Entry { + actor: &user.login, + action: Action::Update, + entity: Entity::Person, + entity_id: Some(person), + person_id: Some(person), + fields, + } +} + +/// Adds the person chosen in the selection as an employee. +pub async fn hire( + State(st): State>, + Extension(user): Extension, + Path(id): Path, + Form(f): Form, +) -> Res { + if companies::archived_at(&st.db, id).await?.is_none() { + return Ok(not_found_page(&st)); + } + let chosen = get(&f, "person"); + let allowed = companies::candidates(&st.db, id).await?; + let Some(person) = allowed + .iter() + .find(|(pid, _)| *pid == chosen) + .and_then(|(pid, _)| pid.parse::().ok()) + else { + return Ok(Redirect::to(&format!("/companies/{id}#people")).into_response()); + }; + let mut tx = st.db.begin().await?; + if companies::hire(&mut tx, id, person).await? { + let fields = ["employer".to_string()]; + audit::record(&mut *tx, &employer_changed(&user, person, &fields)).await?; + } + tx.commit().await?; + Ok(Redirect::to(&format!("/companies/{id}#people")).into_response()) +} + +pub async fn release( + State(st): State>, + Extension(user): Extension, + Path((id, person)): Path<(i64, i64)>, +) -> Res { + let mut tx = st.db.begin().await?; + if companies::release(&mut tx, id, person).await? { + let fields = ["employer".to_string()]; + audit::record(&mut *tx, &employer_changed(&user, person, &fields)).await?; + } + tx.commit().await?; + Ok(Redirect::to(&format!("/companies/{id}#people")).into_response()) +} diff --git a/src/web/dashboard.rs b/src/web/dashboard.rs new file mode 100644 index 0000000..fdc0480 --- /dev/null +++ b/src/web/dashboard.rs @@ -0,0 +1,113 @@ +//! The Deadlines page at /: every person's coming deadlines, the most +//! urgent first. + +use std::sync::Arc; + +use axum::Extension; +use axum::extract::{Query, State}; +use axum::http::StatusCode; +use chrono::TimeDelta; +use minijinja::context; +use serde::{Deserialize, Serialize}; + +use super::{AppState, Res, page}; +use crate::companies; +use crate::dates; +use crate::deadlines::{self, Deadline}; +use crate::session::User; + +#[derive(Deserialize)] +pub struct DashQuery { + /// "1": also what lies beyond the next 90 days. + #[serde(default)] + all: Option, + /// A company's id: only the people it employs. + #[serde(default)] + company: Option, +} + +#[derive(Debug, Serialize)] +struct Row { + person_id: i64, + person: String, + employer: String, + d: Deadline, + q: String, +} + +/// How far ahead the page looks unless asked for everything; anything +/// overdue or close (bad, warn) shows regardless. +const HORIZON_DAYS: i64 = 90; + +pub async fn page_handler( + State(st): State>, + Extension(user): Extension, + Query(q): Query, +) -> Res { + let today = dates::today(); + let all = q.all.as_deref() == Some("1"); + let company: Option = q.company.as_deref().and_then(|c| c.parse().ok()); + let people: Vec<(i64, String, String, String, Option)> = sqlx::query_as( + "SELECT p.id, p.surname, p.first_name, p.middle_name, c.name \ + FROM people p LEFT JOIN companies c ON c.id = p.employer_id \ + WHERE p.archived_at IS NULL AND ($1::bigint IS NULL OR p.employer_id = $1)", + ) + .bind(company) + .fetch_all(&st.db) + .await?; + let ids: Vec = people.iter().map(|p| p.0).collect(); + let mut found = deadlines::for_people(&st.db, &ids, today).await?; + let horizon = today + TimeDelta::days(HORIZON_DAYS); + let mut rows = Vec::new(); + for (id, surname, first, middle, employer) in &people { + let Some(a) = found.remove(id) else { continue }; + let given = if middle.is_empty() { + first.clone() + } else { + format!("{first} {middle}") + }; + let person = format!("{}, {given}", surname.to_uppercase()); + let employer = employer.clone().unwrap_or_default(); + for d in a.items { + let Some(due) = d.due else { continue }; + let urgent = matches!(d.level, "bad" | "warn"); + if !all && !urgent && due > horizon { + continue; + } + let q = format!("{person} {employer} {} {}", d.title, d.label).to_lowercase(); + rows.push(Row { + person_id: *id, + person: person.clone(), + employer: employer.clone(), + d, + q, + }); + } + } + rows.sort_by(|x, y| { + deadlines::rank(x.d.level) + .cmp(&deadlines::rank(y.d.level)) + .then(x.d.due.cmp(&y.d.due)) + .then(x.person.cmp(&y.person)) + }); + let overdue = rows.iter().filter(|r| r.d.level == "bad").count(); + let soon = rows.iter().filter(|r| r.d.level == "warn").count(); + Ok(page( + &st, + &user, + "dashboard.html", + "Deadlines", + "deadlines", + StatusCode::OK, + context! { + rows, + overdue, + soon, + all, + n_people => people.len(), + horizon_days => HORIZON_DAYS, + companies => companies::choices(&st.db, company).await?, + company => company.map(|c| c.to_string()).unwrap_or_default(), + }, + )) +} diff --git a/src/web/mod.rs b/src/web/mod.rs index bf723ed..50e8100 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -2,23 +2,27 @@ pub mod activity; pub mod auth; +pub mod companies; +pub mod dashboard; pub mod people; +pub mod records; use std::sync::{Arc, RwLock}; use std::time::Duration; -use axum::Router; use axum::body::Body; use axum::extract::{Path, Request, State}; use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header}; use axum::middleware::{self, Next}; use axum::response::{Html, IntoResponse, Redirect, Response}; use axum::routing::{get, post}; +use axum::{Extension, Form, Router}; use minijinja::{Environment, Value, context}; use sqlx::PgPool; use tracing::{error, info, warn}; use crate::config::{Auth, Config}; +use crate::forms::Fields; use crate::session::{self, Flows, SESSION_COOKIE, User}; use crate::{VERSION, countries, dates, embedded, oidc}; @@ -113,9 +117,10 @@ pub fn spawn_background(st: Arc) { } pub fn router(st: Arc) -> Router { + use companies as c; use people as p; - Router::new() - .route("/", get(|| async { Redirect::to("/people") })) + let mut r = Router::new() + .route("/", get(dashboard::page_handler)) .route("/people", get(p::list).post(p::create)) .route("/people/new", get(p::new_form)) .route("/people/{id}", get(p::show).post(p::update)) @@ -138,7 +143,89 @@ pub fn router(st: Arc) -> Router { "/people/{id}/addresses/{aid}/delete", post(p::address_delete), ) - .route("/activity", get(activity::page)) + .route( + "/people/{id}/stay", + get( + |State(st): State>, + Extension(user): Extension, + Path(id): Path| records::stay(st, user, id), + ), + ) + .route( + "/people/{id}/activity", + get( + |State(st): State>, + Extension(user): Extension, + Path(id): Path| records::person_activity(st, user, id), + ), + ) + .route("/companies", get(c::list).post(c::create)) + .route("/companies/new", get(c::new_form)) + .route("/companies/{id}", get(c::show).post(c::update)) + .route("/companies/{id}/edit", get(c::edit_form)) + .route("/companies/{id}/archive", post(c::archive)) + .route("/companies/{id}/restore", post(c::restore)) + .route("/companies/{id}/employees", post(c::hire)) + .route("/companies/{id}/employees/{pid}/remove", post(c::release)); + // Every kind of stay record: /people/{id}/, .../new, + // .../{rid}, .../{rid}/edit and .../{rid}/delete. + for kind in crate::records::STAY { + let base = format!("/people/{{id}}/{}", kind.slug); + r = r + .route( + &base, + post( + move |State(st): State>, + Extension(user): Extension, + Path(id): Path, + Form(f): Form| { + records::create(kind, st, user, id, f) + }, + ), + ) + .route( + &format!("{base}/new"), + get( + move |State(st): State>, + Extension(user): Extension, + Path(id): Path| { + records::new_form(kind, st, user, id) + }, + ), + ) + .route( + &format!("{base}/{{rid}}"), + post( + move |State(st): State>, + Extension(user): Extension, + Path((id, rid)): Path<(i64, i64)>, + Form(f): Form| { + records::update(kind, st, user, id, rid, f) + }, + ), + ) + .route( + &format!("{base}/{{rid}}/edit"), + get( + move |State(st): State>, + Extension(user): Extension, + Path((id, rid)): Path<(i64, i64)>| { + records::edit_form(kind, st, user, id, rid) + }, + ), + ) + .route( + &format!("{base}/{{rid}}/delete"), + post( + move |State(st): State>, + Extension(user): Extension, + Path((id, rid)): Path<(i64, i64)>| { + records::delete(kind, st, user, id, rid) + }, + ), + ); + } + r.route("/activity", get(activity::page)) .route("/login", get(auth::login)) .route("/auth/callback", get(auth::callback)) .route("/logout", post(auth::logout)) diff --git a/src/web/people.rs b/src/web/people.rs index 7b13c29..fdc512c 100644 --- a/src/web/people.rs +++ b/src/web/people.rs @@ -21,6 +21,7 @@ use crate::people::{ PersonInput, SEXES, TITLES, }; use crate::session::User; +use crate::{companies, deadlines}; // ----------------------------------------------------------------- views @@ -38,7 +39,9 @@ pub struct PersonView { pub nationality: String, pub nationality_name: String, pub occupation: String, + /// The employer's name. pub employer: String, + pub employer_id: Option, pub phone: String, pub email: String, pub notes: String, @@ -48,7 +51,12 @@ pub struct PersonView { pub updated: String, } -fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> PersonView { +fn person_view( + p: &Person, + current_passport: Option<&str>, + employer: Option, + today: NaiveDate, +) -> PersonView { PersonView { id: p.id, name: p.display_name(), @@ -64,7 +72,8 @@ fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> .unwrap_or(&p.nationality) .to_string(), occupation: p.occupation.clone(), - employer: p.employer.clone(), + employer: employer.unwrap_or_default(), + employer_id: p.employer_id, phone: p.phone.clone(), email: p.email.clone(), notes: p.notes.clone(), @@ -133,14 +142,23 @@ fn address_view(a: &Address) -> AddressView { } } -/// The person with the number of their current passport, for the header -/// every page of the person shares. -async fn load_person(st: &AppState, id: i64) -> anyhow::Result> { +/// The person with the number of their current passport and the name of +/// their employer, for the head every page of the person shares. +pub async fn load_person(st: &AppState, id: i64) -> anyhow::Result> { let Some(p) = people::get_person(&st.db, id).await? else { return Ok(None); }; let pps = people::passports(&st.db, id).await?; - let view = person_view(&p, pps.first().map(|x| x.number.as_str()), dates::today()); + let employer = match p.employer_id { + Some(c) => companies::name(&st.db, c).await?, + None => None, + }; + let view = person_view( + &p, + pps.first().map(|x| x.number.as_str()), + employer, + dates::today(), + ); Ok(Some((p, view))) } @@ -217,6 +235,9 @@ fn zone_note(m: &Mrz, errors: &mut Errors) -> Option { pub struct ListQuery { #[serde(default)] archived: Option, + /// A company's id: only the people it employs. + #[serde(default)] + company: Option, } pub async fn list( @@ -224,21 +245,42 @@ pub async fn list( Extension(user): Extension, Query(q): Query, ) -> Res { + let today = dates::today(); let archived = q.archived.as_deref() == Some("1"); - let rows = people::list(&st.db, archived, dates::today()).await?; + let company: Option = q.company.as_deref().and_then(|c| c.parse().ok()); + let mut rows = people::list(&st.db, archived, company, today).await?; + let ids: Vec = rows.iter().map(|r| r.id).collect(); + let mut found = deadlines::for_people(&st.db, &ids, today).await?; + for r in &mut rows { + r.next = found.remove(&r.id).and_then(|a| a.next().cloned()); + } let (n_active, n_archived) = people::counts(&st.db).await?; + let company_name = match company { + Some(c) => companies::name(&st.db, c).await?, + None => None, + }; + let heading = match (&company_name, archived) { + (Some(n), _) => format!("People at {n}"), + (None, true) => "Archived people".to_string(), + (None, false) => "People".to_string(), + }; Ok(page( &st, &user, "people.html", - if archived { - "Archived people" - } else { - "People" - }, + &heading, "people", StatusCode::OK, - context! { people => rows, archived, n_active, n_archived }, + context! { + people => rows, + archived, + n_active, + n_archived, + heading, + companies => companies::choices(&st.db, company).await?, + company => company.map(|c| c.to_string()).unwrap_or_default(), + company_name, + }, )) } @@ -277,6 +319,7 @@ pub async fn show( .iter() .map(address_view) .collect(); + let assessment = deadlines::for_person(&st.db, id, today).await?; audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?; let recent = audit::recent(&st.db, Some(id), 6).await?; let title = view.name.clone(); @@ -287,7 +330,15 @@ pub async fn show( &title, "people", StatusCode::OK, - context! { p => view, passports, addresses, recent }, + context! { + p => view, + tab => "overview", + passports, + addresses, + recent, + stay => assessment.stay, + deadlines => assessment.items, + }, )) } @@ -300,6 +351,7 @@ fn person_form_page( pf: &PassportForm, errors: &Errors, mrz_note: Option, + companies: &[(String, String)], status: StatusCode, ) -> Response { let (title, mode, action) = match p { @@ -317,11 +369,26 @@ fn person_form_page( &title, "people", status, - context! { p, f, pf, errors, mrz_note, mode, action, ..select_lists() }, + context! { + p, tab => "overview", f, pf, errors, mrz_note, mode, action, companies, + ..select_lists() + }, ) } +/// The companies the employer is chosen from (the active ones and the one +/// already chosen), and their ids for the check. +async fn employer_choices( + st: &AppState, + current: Option, +) -> anyhow::Result<(Vec<(String, String)>, Vec)> { + let list = companies::choices(&st.db, current).await?; + let ids = list.iter().filter_map(|(id, _)| id.parse().ok()).collect(); + Ok((list, ids)) +} + pub async fn new_form(State(st): State>, Extension(user): Extension) -> Res { + let (companies, _) = employer_choices(&st, None).await?; Ok(person_form_page( &st, &user, @@ -330,6 +397,7 @@ pub async fn new_form(State(st): State>, Extension(user): Extensio &PassportForm::default(), &Errors::new(), None, + &companies, StatusCode::OK, )) } @@ -340,6 +408,7 @@ pub async fn create( Form(f): Form, ) -> Res { let today = dates::today(); + let (companies, company_ids) = employer_choices(&st, None).await?; let mut pf = PersonForm::from_fields(&f); let mut ppf = PassportForm::from_fields(&f); let mut errors = Errors::new(); @@ -360,7 +429,7 @@ pub async fn create( } let status = status_for(&errors); return Ok(person_form_page( - &st, &user, None, &pf, &ppf, &errors, note, status, + &st, &user, None, &pf, &ppf, &errors, note, &companies, status, )); } @@ -368,7 +437,7 @@ pub async fn create( pf.take_mrz(m, false); ppf.take_mrz(m, false); } - let person = pf.validate(today); + let person = pf.validate(today, &company_ids); let passport = (!ppf.is_blank()).then(|| ppf.validate(zone.as_ref())); for e in [ person.as_ref().err(), @@ -390,6 +459,7 @@ pub async fn create( &ppf, &errors, None, + &companies, StatusCode::UNPROCESSABLE_ENTITY, )); }; @@ -412,6 +482,7 @@ pub async fn create( &ppf, &errors, None, + &companies, StatusCode::UNPROCESSABLE_ENTITY, )); } @@ -441,6 +512,7 @@ pub async fn edit_form( let Some((p, view)) = load_person(&st, id).await? else { return Ok(not_found_page(&st)); }; + let (companies, _) = employer_choices(&st, p.employer_id).await?; audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?; Ok(person_form_page( &st, @@ -450,6 +522,7 @@ pub async fn edit_form( &PassportForm::default(), &Errors::new(), None, + &companies, StatusCode::OK, )) } @@ -460,11 +533,12 @@ pub async fn update( Path(id): Path, Form(f): Form, ) -> Res { - let Some((_, view)) = load_person(&st, id).await? else { + let Some((p, view)) = load_person(&st, id).await? else { return Ok(not_found_page(&st)); }; + let (companies, company_ids) = employer_choices(&st, p.employer_id).await?; let pf = PersonForm::from_fields(&f); - let input = match pf.validate(dates::today()) { + let input = match pf.validate(dates::today(), &company_ids) { Ok(i) => i, Err(errors) => { return Ok(person_form_page( @@ -475,6 +549,7 @@ pub async fn update( &PassportForm::default(), &errors, None, + &companies, StatusCode::UNPROCESSABLE_ENTITY, )); } @@ -569,7 +644,7 @@ fn passport_form_page( &format!("{title}: {}", p.name), "people", status, - context! { p, pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() }, + context! { p, tab => "overview", pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() }, ) } @@ -824,7 +899,7 @@ fn address_form_page( &format!("{heading}: {}", p.name), "people", status, - context! { p, af, errors, mode, action, heading, ..select_lists() }, + context! { p, tab => "overview", af, errors, mode, action, heading, ..select_lists() }, ) } diff --git a/src/web/records.rs b/src/web/records.rs new file mode 100644 index 0000000..9828587 --- /dev/null +++ b/src/web/records.rs @@ -0,0 +1,353 @@ +//! Pages for the records of a stay: the person's "Visa and stay" tab, one +//! form for every kind (`records::Kind`), and the person's Activity tab. + +use std::sync::Arc; + +use axum::http::StatusCode; +use axum::response::{IntoResponse, Redirect, Response}; +use minijinja::context; +use sqlx::PgPool; + +use super::people::{PersonView, load_person}; +use super::{AppState, Res, not_found_page, page}; +use crate::audit::{self, Action, Entity, Entry}; +use crate::countries; +use crate::dates; +use crate::deadlines; +use crate::forms::{Errors, Fields}; +use crate::records::{self, Kind, Options, Values}; +use crate::session::User; +use crate::{companies, people}; + +/// Suggestions for the text fields with a ``. +pub fn datalists() -> minijinja::Value { + context! { + ports => records::PORTS, + offices => records::OFFICES, + provinces => countries::PROVINCES, + } +} + +/// The choices of a person's forms. `all_companies` names archived companies +/// too (to show records); otherwise only active ones and `keep_company`. +pub async fn options( + db: &PgPool, + person: i64, + all_companies: bool, + keep_company: Option, +) -> anyhow::Result { + let passports = people::passports(db, person) + .await? + .iter() + .map(|p| { + let country = countries::name(&p.issuing_country).unwrap_or(&p.issuing_country); + (p.id.to_string(), format!("{} ({country})", p.number)) + }) + .collect(); + let visas = records::list(db, &records::VISAS, person) + .await? + .iter() + .map(|r| (r.id.to_string(), records::visa_choice(r))) + .collect(); + let companies = if all_companies { + companies::names(db).await? + } else { + companies::choices(db, keep_company).await? + }; + Ok(Options { + passports, + visas, + companies, + }) +} + +fn company_of(v: &Values) -> Option { + v.get("company_id").and_then(|c| c.parse().ok()) +} + +pub async fn stay(st: Arc, user: User, id: i64) -> Res { + let Some((_, view)) = load_person(&st, id).await? else { + return Ok(not_found_page(&st)); + }; + let today = dates::today(); + let opts = options(&st.db, id, true, None).await?; + let mut sections = Vec::new(); + for kind in records::STAY { + let shown: Vec = records::list(&st.db, kind, id) + .await? + .iter() + .map(|r| records::show(kind, r, &opts, today)) + .collect(); + sections.push(context! { + slug => kind.slug, + title => kind.title, + one => kind.one, + records => shown, + }); + } + let assessment = deadlines::for_person(&st.db, id, today).await?; + audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?; + let title = format!("Visa and stay: {}", view.name); + Ok(page( + &st, + &user, + "stay.html", + &title, + "people", + StatusCode::OK, + context! { + p => view, + tab => "stay", + sections, + stay => assessment.stay, + deadlines => assessment.items, + }, + )) +} + +pub async fn person_activity(st: Arc, user: User, id: i64) -> Res { + let Some((_, view)) = load_person(&st, id).await? else { + return Ok(not_found_page(&st)); + }; + let items = audit::recent(&st.db, Some(id), 300).await?; + audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?; + let title = format!("Activity: {}", view.name); + Ok(page( + &st, + &user, + "person_activity.html", + &title, + "people", + StatusCode::OK, + context! { p => view, tab => "activity", items }, + )) +} + +#[allow(clippy::too_many_arguments)] +fn form_page( + st: &AppState, + user: &User, + kind: &Kind, + p: &PersonView, + record: Option, + values: &Values, + errors: &Errors, + opts: &Options, + status: StatusCode, +) -> Response { + let base = format!("/people/{}/{}", p.id, kind.slug); + let (heading, mode, action) = match record { + Some(r) => ( + format!("Edit the {}", kind.one), + "edit", + format!("{base}/{r}"), + ), + None => (format!("New {}", kind.one), "new", base), + }; + let title = format!("{heading}: {}", p.name); + page( + st, + user, + "record_form.html", + &title, + "people", + status, + context! { + p, + tab => "stay", + heading, + one => kind.one, + lead => kind.lead, + mode, + action, + fields => records::form_fields(kind, opts), + values, + errors, + cancel => format!("/people/{}/stay#{}", p.id, kind.slug), + ..datalists() + }, + ) +} + +/// Sensible first values: the current passport, the employer, Chiang Mai. +fn defaults(kind: &Kind, view: &PersonView, opts: &Options) -> Values { + let mut v = Values::new(); + let first_passport = opts.passports.first().map(|(id, _)| id.clone()); + match kind.slug { + "arrivals" => { + if let Some(pp) = first_passport { + v.insert("passport_id".into(), pp); + } + } + "visas" => { + if let Some(pp) = first_passport { + v.insert("passport_id".into(), pp); + } + } + "extensions" => { + v.insert("office".into(), "Chiang Mai Immigration Office".into()); + v.insert("fee_thb".into(), "1900".into()); + } + "reentry-permits" => { + v.insert("office".into(), "Chiang Mai Immigration Office".into()); + } + "work-permits" => { + if let Some(c) = view.employer_id { + v.insert("company_id".into(), c.to_string()); + } + v.insert("position".into(), String::new()); + } + _ => {} + } + v +} + +pub async fn new_form(kind: &'static Kind, st: Arc, user: User, id: i64) -> Res { + let Some((_, view)) = load_person(&st, id).await? else { + return Ok(not_found_page(&st)); + }; + let opts = options(&st.db, id, false, view.employer_id).await?; + let values = defaults(kind, &view, &opts); + Ok(form_page( + &st, + &user, + kind, + &view, + None, + &values, + &Errors::new(), + &opts, + StatusCode::OK, + )) +} + +fn entry<'a>( + user: &'a User, + action: Action, + kind: &Kind, + record: i64, + person: i64, + fields: &'a [String], +) -> Entry<'a> { + Entry { + actor: &user.login, + action, + entity: kind.entity, + entity_id: Some(record), + person_id: Some(person), + fields, + } +} + +fn back(kind: &Kind, person: i64) -> Response { + Redirect::to(&format!("/people/{person}/stay#{}", kind.slug)).into_response() +} + +pub async fn create(kind: &'static Kind, st: Arc, user: User, id: i64, f: Fields) -> Res { + let Some((_, view)) = load_person(&st, id).await? else { + return Ok(not_found_page(&st)); + }; + let values = records::read(kind, &f); + let opts = options(&st.db, id, false, None).await?; + let errors = records::validate(kind, &values, &opts); + if !errors.is_empty() { + return Ok(form_page( + &st, + &user, + kind, + &view, + None, + &values, + &errors, + &opts, + StatusCode::UNPROCESSABLE_ENTITY, + )); + } + let mut tx = st.db.begin().await?; + let rid = records::create(&mut tx, kind, Some(id), &values).await?; + audit::record(&mut *tx, &entry(&user, Action::Create, kind, rid, id, &[])).await?; + tx.commit().await?; + Ok(back(kind, id)) +} + +pub async fn edit_form( + kind: &'static Kind, + st: Arc, + user: User, + id: i64, + rid: i64, +) -> Res { + let Some((_, view)) = load_person(&st, id).await? else { + return Ok(not_found_page(&st)); + }; + let Some(r) = records::get(&st.db, kind, Some(id), rid).await? else { + return Ok(not_found_page(&st)); + }; + let opts = options(&st.db, id, false, company_of(&r.values)).await?; + audit::viewed(&st.db, &user.login, kind.entity, rid, id).await?; + Ok(form_page( + &st, + &user, + kind, + &view, + Some(rid), + &r.values, + &Errors::new(), + &opts, + StatusCode::OK, + )) +} + +pub async fn update( + kind: &'static Kind, + st: Arc, + user: User, + id: i64, + rid: i64, + f: Fields, +) -> Res { + let Some((_, view)) = load_person(&st, id).await? else { + return Ok(not_found_page(&st)); + }; + let mut tx = st.db.begin().await?; + let Some(old) = records::get_for_update(&mut tx, kind, Some(id), rid).await? else { + return Ok(not_found_page(&st)); + }; + let values = records::read(kind, &f); + let opts = options(&st.db, id, false, company_of(&old.values)).await?; + let errors = records::validate(kind, &values, &opts); + if !errors.is_empty() { + return Ok(form_page( + &st, + &user, + kind, + &view, + Some(rid), + &values, + &errors, + &opts, + StatusCode::UNPROCESSABLE_ENTITY, + )); + } + let changed = records::changed(kind, &old.values, &values); + if !changed.is_empty() { + records::update(&mut tx, kind, Some(id), rid, &values).await?; + audit::record( + &mut *tx, + &entry(&user, Action::Update, kind, rid, id, &changed), + ) + .await?; + } + tx.commit().await?; + Ok(back(kind, id)) +} + +pub async fn delete(kind: &'static Kind, st: Arc, user: User, id: i64, rid: i64) -> Res { + let mut tx = st.db.begin().await?; + if !records::delete(&mut tx, kind, id, rid).await? { + return Ok(not_found_page(&st)); + } + audit::record(&mut *tx, &entry(&user, Action::Delete, kind, rid, id, &[])).await?; + tx.commit().await?; + Ok(back(kind, id)) +} diff --git a/static/app.css b/static/app.css index 0ffa256..48f78b8 100644 --- a/static/app.css +++ b/static/app.css @@ -401,6 +401,7 @@ main { .chip { display: inline-block; + white-space: nowrap; padding: 1px 9px; border-radius: 999px; font-size: 12.5px; @@ -666,6 +667,135 @@ textarea.mrz { border-top: 1px solid var(--line); } +/* ---- tabs of a person */ +.phead.tabbed { + border-bottom: 0; + padding-bottom: 0; +} +.tabs { + display: flex; + gap: 2px; + margin-top: 12px; + border-bottom: 1px solid var(--line); + overflow-x: auto; +} +.tabs a { + padding: 8px 14px; + color: var(--mute); + font-weight: 600; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + white-space: nowrap; +} +.tabs a:hover { + color: var(--hd); + text-decoration: none; +} +.tabs a.on { + color: var(--hd); + border-bottom-color: var(--accent); +} + +/* ---- status and deadlines */ +.stayline { + margin: 0 0 10px; +} +.stayline.bad { + color: var(--bad); + font-weight: 600; +} +.dl { + list-style: none; + margin: 0; + padding: 0; +} +.dl li { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 2px 12px; + padding: 10px 0; + border-top: 1px solid var(--line); +} +.dl li:first-child { + border-top: 0; +} +.dl-what { + display: flex; + flex-wrap: wrap; + gap: 2px 10px; + align-items: baseline; +} +.dl-when { + color: var(--mute); + font-size: 13px; +} +.dl li > .chip { + align-self: start; + justify-self: end; +} +.dl-note { + grid-column: 1 / -1; + margin: 0; + font-size: 13.5px; + color: var(--mute); +} +.summary { + display: flex; + gap: 10px; + align-items: center; + flex-wrap: wrap; + margin-bottom: 12px; +} +.sel { + display: inline-flex; + align-items: center; + gap: 8px; +} +.sel select { + width: auto; + min-width: 170px; + max-width: 100%; +} +.nowrap { + white-space: nowrap; +} +.tbl .note { + min-width: 260px; + max-width: 440px; +} +.linkbtn { + background: none; + border: 0; + padding: 0; + color: var(--link); + font: inherit; + font-size: 13px; + cursor: pointer; +} +.linkbtn:hover { + text-decoration: underline; +} +.hire { + margin-top: 14px; + padding-top: 12px; + border-top: 1px solid var(--line); +} +.hire label { + display: block; + font-size: 13px; + font-weight: 650; + color: var(--hd); + margin-bottom: 4px; +} +.hire-row { + display: flex; + gap: 8px; +} +.hire-row select { + flex: 1; + min-width: 0; +} + /* ---- a page outside the frame */ .solo { max-width: 560px; @@ -695,6 +825,11 @@ textarea.mrz { } .nav { flex-direction: row; + flex-wrap: wrap; + } + .nav a { + padding: 6px 9px; + font-size: 14px; } .who { margin: 0 0 0 auto; diff --git a/static/app.js b/static/app.js index ddcb584..fc6f3b4 100644 --- a/static/app.js +++ b/static/app.js @@ -24,6 +24,14 @@ if (msg && !window.confirm(msg)) ev.preventDefault(); }); + // ---- a selection with data-autosubmit filters the page at once + document.addEventListener("change", function (ev) { + var t = ev.target; + if (t && t.hasAttribute && t.hasAttribute("data-autosubmit") && t.form) { + t.form.submit(); + } + }); + // ---- filter: rows carry data-q (lower case); "/" focuses the box function applyFilter() { var box = document.getElementById("q"); diff --git a/templates/_deadlines.html b/templates/_deadlines.html new file mode 100644 index 0000000..c39298a --- /dev/null +++ b/templates/_deadlines.html @@ -0,0 +1,22 @@ +{#- Where the person stands and what is due, the most urgent first. -#} +
+

Status and deadlines

{% if tab != "stay" %}Visa and stay{% endif %}
+ {% if stay.state == "in" %} +

In Thailand since {{ stay.since }}, permitted to stay until {{ stay.permitted_until }} ({{ stay.remaining }}). Basis: {{ stay.basis }}.

+ {% elif stay.state == "abroad" %} +

Left Thailand on {{ stay.left_on }}; no stay is running.

+ {% else %} +

No arrival is recorded yet. Add the latest arrival under Visa and stay to see the deadlines of the stay.

+ {% endif %} + {% if deadlines %} +
    + {% for d in deadlines %} +
  • +
    {{ d.title }}{% if d.due_text %}{{ d.due_text }}, {{ d.when }}{% if d.estimate %} (estimate){% endif %}{% endif %}
    + {{ d.label }} +

    {{ d.note }}

    +
  • + {% endfor %} +
+ {% endif %} +
diff --git a/templates/_fields.html b/templates/_fields.html index 8a7b138..f357524 100644 --- a/templates/_fields.html +++ b/templates/_fields.html @@ -14,10 +14,10 @@ {%- endmacro %} -{% macro select(name, label, value, options, err="", hint="", blank="Not recorded", cls="") -%} +{% macro select(name, label, value, options, err="", hint="", blank="Not recorded", cls="", req=false) -%}
- - {%- for o in options %} diff --git a/templates/_person_head.html b/templates/_person_head.html index 6b9410a..edb27eb 100644 --- a/templates/_person_head.html +++ b/templates/_person_head.html @@ -1,5 +1,6 @@ -{#- The head of every page about one person: the same place on each. -#} -
+{#- The head of every page about one person, with its tabs: the same + place on each. -#} +

{{ p.name }}

@@ -15,9 +16,14 @@ {%- if p.nationality_name %}{{ p.nationality_name }}{% else %}Nationality not recorded{% endif %} {%- if p.age is not none %}·{{ p.age }} years{% endif %} {%- if p.current_passport %}·passport {{ p.current_passport }}{% endif %} - {%- if p.employer %}·{{ p.employer }}{% endif %} + {%- if p.employer %}·{{ p.employer }}{% endif %}

+
{% if p.archived %} -
Archived on {{ p.archived_on }}. Archived people are left out of the list; Restore brings the record back.
+
Archived on {{ p.archived_on }}. Archived people are left out of the list and the deadlines; Restore brings the record back.
{% endif %} diff --git a/templates/activity.html b/templates/activity.html index 4fdc441..23dc44e 100644 --- a/templates/activity.html +++ b/templates/activity.html @@ -16,7 +16,7 @@ {{ e.at }} {{ e.actor }} {{ e.action }} - {% if e.person_id %}{{ e.person_name or ("person " ~ e.person_id) }} {{ e.what }}{% else %}{{ e.what }}{% endif %} + {% if e.person_id %}{{ e.person_name or ("person " ~ e.person_id) }} {{ e.what }}{% elif e.company_id %}{{ e.company_name or ("company " ~ e.company_id) }} company{% else %}{{ e.what }}{% endif %} {{ e.fields }} {% endfor %} diff --git a/templates/base.html b/templates/base.html index 8a04343..6bb3a65 100644 --- a/templates/base.html +++ b/templates/base.html @@ -12,7 +12,7 @@
- + {% include "_mark.html" %} Visabuildfor.life @@ -21,7 +21,9 @@