Files
visa/src/audit.rs
T
grabowski 83bc481952
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 22s
Phase 2: companies, stay records, deadlines
Companies become records of their own, and the stay in Thailand is
recorded in full; from these records the app works out each person's
deadlines (docs/PLAN.md, phase 2).

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

197 lines
5.3 KiB
Rust

//! The audit log (PDPA): who viewed or changed which record. It holds the
//! names of changed fields, never their values, and the table refuses
//! updates and deletes (migrations/0001_init.sql).
use anyhow::Result;
use chrono::{DateTime, Utc};
use serde::Serialize;
use sqlx::{Executor, PgPool, Postgres};
use crate::dates;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
View,
Create,
Update,
Delete,
Archive,
Restore,
SignIn,
SignOut,
}
impl Action {
pub fn as_str(self) -> &'static str {
match self {
Action::View => "view",
Action::Create => "create",
Action::Update => "update",
Action::Delete => "delete",
Action::Archive => "archive",
Action::Restore => "restore",
Action::SignIn => "sign-in",
Action::SignOut => "sign-out",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Entity {
Person,
Passport,
Address,
Session,
Company,
Visa,
Arrival,
Extension,
ReentryPermit,
Report,
WorkPermit,
}
impl Entity {
pub fn as_str(self) -> &'static str {
match self {
Entity::Person => "person",
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",
}
}
}
pub struct Entry<'a> {
pub actor: &'a str,
pub action: Action,
pub entity: Entity,
pub entity_id: Option<i64>,
pub person_id: Option<i64>,
pub fields: &'a [String],
}
/// Writes one entry; pass the transaction (`&mut *tx`) when the change it
/// records is in one, so both commit or roll back together.
pub async fn record<'e, E>(ex: E, e: &Entry<'_>) -> Result<()>
where
E: Executor<'e, Database = Postgres>,
{
sqlx::query(
"INSERT INTO audit_log (actor, action, entity, entity_id, person_id, fields) \
VALUES ($1, $2, $3, $4, $5, $6)",
)
.bind(e.actor)
.bind(e.action.as_str())
.bind(e.entity.as_str())
.bind(e.entity_id)
.bind(e.person_id)
.bind(e.fields)
.execute(ex)
.await?;
Ok(())
}
/// A view of a person's record.
pub async fn viewed(db: &PgPool, actor: &str, entity: Entity, id: i64, person: i64) -> Result<()> {
record(
db,
&Entry {
actor,
action: Action::View,
entity,
entity_id: Some(id),
person_id: Some(person),
fields: &[],
},
)
.await
}
#[derive(Debug, sqlx::FromRow)]
struct Row {
id: i64,
at: DateTime<Utc>,
actor: String,
action: String,
entity: String,
entity_id: Option<i64>,
person_id: Option<i64>,
fields: Vec<String>,
person_name: Option<String>,
company_name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct Item {
pub id: i64,
pub at: String,
pub actor: String,
pub action: String,
pub what: String,
pub person_id: Option<i64>,
pub person_name: Option<String>,
pub company_id: Option<i64>,
pub company_name: Option<String>,
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<i64>, limit: i64) -> Result<Vec<Item>> {
let rows: Vec<Row> = 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, 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",
)
.bind(person)
.bind(limit)
.fetch_all(db)
.await?;
Ok(rows
.into_iter()
.map(|r| {
let what = match (r.entity.as_str(), r.entity_id) {
("session", _) => String::new(),
("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),
actor: r.actor,
action: r.action,
what,
person_id: r.person_id,
person_name: r.person_name,
company_id,
company_name: r.company_name,
fields: r.fields.join(", ").replace('_', " "),
}
})
.collect())
}