Files
visa/src/seed.rs
T
grabowski 16e4cdc73d
CI / secret scan (push) Successful in 7s
CI / fmt, clippy, tests (push) Successful in 45s
CI / release (push) Skipped
The legal practice: clients, lawyers, contracts, papers, the journal
Lanna Desk's larger work is contracts, general ones and artists', for
clients who are Thai or foreign, people or organizations, with several
lawyers in the team. The back office gets a Legal section (phase 9 in
docs/PLAN.md):

- Lawyers: license number, contact, the login of one who uses the app
  (then "My contracts"), in the team or left.
- Clients, as record cards: person or organization, names in English and
  Thai, stage name or brand, a Thai ID number (checked), a passport or a
  registration number, the lawyer in charge.
- Contracts: code LD-<year>-<n>, the general kinds and the artist kinds
  (recording, management, publishing, performance, license,
  merchandise), other party, status, lawyer, dates and value; a contract
  in force shows its notice day and its end ahead. Filters: general or
  artists, a lawyer, mine, those over.
- Versions: a text kept here, a file (PDF or scan, encrypted as the
  client's document) or both. They never change: the database refuses
  UPDATE and DELETE, a version's file cannot be deleted and no document's
  checksum can change. Any version reads against the one before as a
  line diff.
- Paper copies: the id <code>-P<n> to write on the paper or print as a
  90 x 50 mm label with a QR code; where it lies, its state and holder,
  each move journaled; found again by its id.
- The journal: every change in words, in the change's transaction, each
  entry chained to the one before by SHA-256. The database refuses to
  change, delete or truncate it; /journal checks the chain and every
  version's text and fingerprints against its entry, shows the last hash
  and exports CSV.

The sidebar groups its sections: Legal, Visas and stays, Office. Demo data
(seed-demo) adds three lawyers, six clients and seven contracts with
versions, papers and moves. Documents take a third owner, the client
(migration 0009).

Checks: fmt, clippy, 115 unit and 62 integration tests (new: versions and
the journal, the database refusing changes, a change around the app
breaking the chain, paper ids and moves, the demo checking whole);
screenshots of the new pages in light, dark and on a phone.
2026-11-21 23:20:20 +07:00

1341 lines
43 KiB
Rust

//! 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. `legal`
//! adds the legal practice's demo clients and contracts.
pub mod legal;
use anyhow::Result;
use chrono::{Datelike, NaiveDate, TimeDelta};
use sqlx::PgPool;
use crate::agreements;
use crate::audit::{self, Action, Entity, Entry};
use crate::dates;
use crate::documents::{self, Meta, NewFile, Owner};
use crate::files::{self, Store};
use crate::links;
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.";
fn d(s: &str) -> NaiveDate {
dates::parse_date(s).expect("demo dates are valid")
}
/// A record's values; `"@passport"`, `"@visa"` and `"@employer"` stand for
/// the person's current passport, the visa recorded last and the employer.
macro_rules! vals {
($($k:literal => $v:expr),* $(,)?) => {{
let mut m = Values::new();
$( m.insert($k.to_string(), $v.to_string()); )*
m
}};
}
struct Demo {
person: PersonInput,
/// An index into `companies()`.
employer: Option<usize>,
passports: Vec<PassportInput>,
addresses: Vec<AddressInput>,
stays: Vec<(&'static Kind, Values)>,
archived: bool,
}
#[allow(clippy::too_many_arguments)]
fn person(
surname: &str,
first: &str,
middle: &str,
title: &str,
sex: &str,
born: &str,
place: &str,
nationality: &str,
occupation: &str,
n: u32,
) -> PersonInput {
PersonInput {
surname: surname.into(),
first_name: first.into(),
middle_name: middle.into(),
title: title.into(),
sex: sex.into(),
date_of_birth: Some(d(born)),
place_of_birth: place.into(),
nationality: nationality.into(),
occupation: occupation.into(),
employer: None,
phone: format!("+66 80 000 000{n}"),
email: format!(
"{}.{}@example.com",
first.to_lowercase(),
surname.to_lowercase()
),
notes: MARKER.into(),
}
}
fn passport(
p: &PersonInput,
number: &str,
issued: &str,
expires: &str,
at: &str,
with_mrz: bool,
) -> PassportInput {
let given = if p.middle_name.is_empty() {
p.first_name.clone()
} 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: state,
surname: &p.surname,
given_names: &given,
number,
nationality: state,
date_of_birth: p.date_of_birth.expect("demo people have birth dates"),
sex: &p.sex,
expiry_date: d(expires),
})
} else {
String::new()
};
PassportInput {
number: number.into(),
issuing_country: p.nationality.clone(),
issued_on: Some(d(issued)),
expires_on: d(expires),
issued_at: at.into(),
mrz,
}
}
#[allow(clippy::too_many_arguments)]
fn address(
house_no: &str,
moo: &str,
building: &str,
soi: &str,
road: &str,
subdistrict: &str,
district: &str,
province: &str,
postal: &str,
moved_in: &str,
moved_out: Option<&str>,
tm30: Option<(&str, &str)>,
) -> AddressInput {
AddressInput {
house_no: house_no.into(),
moo: moo.into(),
building: building.into(),
soi: soi.into(),
road: road.into(),
subdistrict: subdistrict.into(),
district: district.into(),
province: province.into(),
postal_code: postal.into(),
moved_in_on: Some(d(moved_in)),
moved_out_on: moved_out.map(d),
house_master: "Somchai Jaidee".into(),
house_master_phone: "+66 80 000 0099".into(),
tm30_reported_on: tm30.map(|(date, _)| d(date)),
tm30_receipt_no: tm30.map(|(_, no)| no.to_string()).unwrap_or_default(),
}
}
/// Two invented companies; their registration numbers carry valid check
/// digits but no real company has them (province code 99 does not exist).
fn companies() -> Vec<Values> {
vec![
vals! {
"name" => "Demo Engineering Co., Ltd.",
"name_th" => "บริษัท เดโม เอ็นจิเนียริ่ง จำกัด",
"registration_no" => "0999999000004",
"business" => "Engineering services",
"house_no" => "88/8",
"building" => "Demo Tower, fifth floor",
"road" => "Superhighway Road",
"subdistrict" => "Wat Ket",
"district" => "Mueang Chiang Mai",
"province" => "Chiang Mai",
"postal_code" => "50000",
"office_gps" => "18.796500, 99.008200",
"phone" => "+66 53 000 000",
"email" => "office@demo-engineering.example",
"signatory" => "Malee Jaidee",
"signatory_position" => "Managing director",
"capital_thb" => "5000000",
"paid_up_thb" => "5000000",
"figures_year" => "2025",
"revenue_thb" => "48500000",
"equity_thb" => "9800000",
"foreign_costs_thb" => "2400000",
"thai_staff" => "24",
"foreign_staff" => "2",
"coordinator" => "Wanida Meechai",
"coordinator_phone" => "+66 53 000 002",
"notes" => MARKER,
},
vals! {
"name" => "Demo Accounting Partnership",
"name_th" => "ห้างหุ้นส่วนจำกัด เดโม แอคเคาน์ติ้ง",
"registration_no" => "0999999000012",
"business" => "Accounting",
"house_no" => "55",
"moo" => "2",
"subdistrict" => "Ban Klang",
"district" => "Mueang Lamphun",
"province" => "Lamphun",
"postal_code" => "51000",
"phone" => "+66 53 000 001",
"signatory" => "Prasert Jaidee",
"signatory_position" => "Managing partner",
"notes" => MARKER,
},
]
}
/// Dates relative to `today`, so the warnings show whenever the seed runs.
fn demos(today: NaiveDate) -> Vec<Demo> {
let plus = |days: i64| (today + 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",
"",
"Ms",
"F",
"1984-08-12",
"Berlin",
"DEU",
"Electrical engineer",
1,
);
let erika_pp = passport(
&erika,
"C01X00T47",
"2021-08-02",
"2031-08-01",
"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", "came_from" => "Frankfurt", "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",
"came_from" => "Singapore",
"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), "monthly_salary_thb" => "95000",
"contract_from" => plus(-400), "contract_until" => plus(330),
},
),
];
// 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",
"Marie",
"Ms",
"F",
"1990-02-14",
"Portland, Oregon",
"USA",
"Product designer",
2,
);
let jane_old = passport(
&jane,
"Z00000017",
"2012-03-01",
"2022-02-28",
"U.S. Department of State",
false,
);
let jane_pp = passport(
&jane,
"Z00000042",
"2017-03-01",
&plus(95),
"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",
"came_from" => "Bangkok",
"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",
"",
"Mr",
"M",
"1979-11-03",
"Brno",
"CZE",
"Accountant",
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), "monthly_salary_thb" => "62000",
},
),
];
// 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",
"",
"Mr",
"M",
"1961-05-30",
"Leeds",
"GBR",
"Retired",
4,
);
let old_pp = passport(&old, "100000001", "2014-01-10", "2024-01-10", "HMPO", false);
vec![
Demo {
person: erika,
employer: Some(0),
passports: vec![erika_pp],
addresses: vec![
address(
"12",
"",
"Nimman Demo Residence",
"9",
"Nimmanhaemin Road",
"Suthep",
"Mueang Chiang Mai",
"Chiang Mai",
"50200",
&plus(-900),
Some(&plus(-500)),
Some((&plus(-899), "TM30-DEMO-0007")),
),
address(
"99/9",
"4",
"Baan Suan Demo",
"7",
"Huay Kaew Road",
"Chang Phueak",
"Mueang Chiang Mai",
"Chiang Mai",
"50300",
&plus(-500),
None,
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",
"",
"Demo Condominium, room 512",
"",
"Chotana Road",
"Chang Phueak",
"Mueang Chiang Mai",
"Chiang Mai",
"50300",
&plus(-38),
None,
None,
)],
stays: jane_stays,
archived: false,
},
Demo {
person: tomas,
employer: Some(1),
passports: vec![tomas_pp],
addresses: vec![address(
"55",
"2",
"",
"",
"",
"Ban Klang",
"Mueang Lamphun",
"Lamphun",
"51000",
&plus(-700),
None,
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,
},
]
}
fn seeded(action: Action, entity: Entity, id: i64, person: Option<i64>) -> Entry<'static> {
Entry {
actor: "seed",
action,
entity,
entity_id: Some(id),
person_id: person,
company_id: None,
fields: &[],
}
}
/// Adds the demo companies and people unless they are there already; true
/// when it did.
pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
let present: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM people WHERE notes = $1)")
.bind(MARKER)
.fetch_one(db)
.await?;
if present {
return Ok(false);
}
let mut tx = db.begin().await?;
let mut company_ids = Vec::new();
let mut person_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?;
person_ids.push(id);
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,
&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,
&seeded(Action::Create, Entity::Address, aid, Some(id)),
)
.await?;
}
let mut last_visa: Option<i64> = None;
for (kind, mut values) in demo.stays {
for v in values.values_mut() {
let id_of = |x: Option<i64>| x.map(|i| i.to_string()).unwrap_or_default();
match v.as_str() {
"@passport" => *v = id_of(current.map(|c| c.1)),
"@visa" => *v = id_of(last_visa),
"@employer" => *v = id_of(demo.person.employer),
_ => {}
}
}
let rid = records::create(&mut tx, kind, Some(id), &values).await?;
if kind.slug == records::VISAS.slug {
last_visa = Some(rid);
}
audit::record(
&mut *tx,
&seeded(Action::Create, kind.entity, rid, Some(id)),
)
.await?;
}
if demo.archived {
people::set_archived(&mut tx, id, true).await?;
audit::record(
&mut *tx,
&seeded(Action::Archive, Entity::Person, id, Some(id)),
)
.await?;
}
}
demo_links(&mut tx, &person_ids).await?;
let (_, v) = agreements::create(&mut tx, DEMO_AGREEMENT.0, DEMO_AGREEMENT.1, "seed").await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Agreement, v.id, None),
)
.await?;
tx.commit().await?;
Ok(true)
}
/// An invented agreement, so the client link shows the step to sign; Lanna Desk's
/// real text comes from its lawyers.
const DEMO_AGREEMENT: (&str, &str) = (
"How Lanna Desk processes your personal data (demo)",
"# This text is invented for development\n\
It shows how an agreement looks on the client's link. Lanna Desk's real text \
comes from its lawyers and is added under Agreements.\n\
\n\
# 1. What Lanna Desk keeps\n\
- your name, date of birth and nationality\n\
- your passport, visas and stamps\n\
- your address in Thailand and how to reach you\n\
\n\
# 2. What for\n\
Lanna Desk keeps these to look after your visa and your stay in Thailand: \
the deadlines, the forms and the documents Immigration asks for.\n\
\n\
# 3. ข้อความภาษาไทย\n\
ข้อความนี้แสดงว่าภาษาไทยพิมพ์ได้ในสำเนาที่ลงนาม",
);
/// Client links to see on the person's page: the first demo person sent
/// theirs an hour ago, with a new phone number and email address; the
/// second opened theirs and has not sent it yet. Their tokens are thrown
/// away: to try the client's pages, make a new link.
async fn demo_links(tx: &mut sqlx::PgConnection, people: &[i64]) -> Result<()> {
if let Some(&id) = people.first() {
let (link, _) = links::create(tx, id, "seed").await?;
sqlx::query(
"UPDATE client_links SET created_at = now() - interval '1 day', \
first_used_at = now() - interval '2 hours', last_used_at = now() - interval '1 hour', \
sent_at = now() - interval '1 hour', closed_at = now() - interval '1 hour', \
closed_by = 'client' WHERE id = $1",
)
.bind(link.id)
.execute(&mut *tx)
.await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Link, link.id, Some(id)),
)
.await?;
let actor = link.actor();
let fields = ["phone".to_string(), "email".to_string()];
for (action, entity, eid, fields) in [
(Action::Update, Entity::Person, id, &fields[..]),
(Action::Send, Entity::Link, link.id, &[][..]),
] {
audit::record(
&mut *tx,
&Entry {
actor: &actor,
action,
entity,
entity_id: Some(eid),
person_id: Some(id),
company_id: None,
fields,
},
)
.await?;
}
}
if let Some(&id) = people.get(1) {
let (link, _) = links::create(tx, id, "seed").await?;
sqlx::query(
"UPDATE client_links SET first_used_at = now() - interval '3 hours', \
last_used_at = now() - interval '3 hours' WHERE id = $1",
)
.bind(link.id)
.execute(&mut *tx)
.await?;
audit::record(
&mut *tx,
&seeded(Action::Create, Entity::Link, link.id, Some(id)),
)
.await?;
}
Ok(())
}
/// A demo document to add: whose, its kind, its record, its date, the
/// file's name and the file.
type Planned = (
Owner,
&'static str,
Option<String>,
Option<NaiveDate>,
String,
Vec<u8>,
);
/// A demo document's picture.
#[derive(Clone, Copy)]
enum Picture {
PassportPage,
Portrait,
Office,
/// A phone's screenshot, as a TDAC is often kept.
Screenshot,
CardFront,
CardBack,
}
/// Adds invented documents to the demo people and companies, unless the
/// seed added documents before: scans as PDF (text pages that say they are
/// demos) and pictures as PNG (shapes, no one's likeness). Returns how many.
pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Result<usize> {
let present: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM documents WHERE uploaded_by = 'seed')")
.fetch_one(db)
.await?;
if present {
return Ok(0);
}
let people: Vec<(i64, String, String)> = sqlx::query_as(
"SELECT id, upper(surname), first_name FROM people \
WHERE notes = $1 AND archived_at IS NULL ORDER BY id",
)
.bind(MARKER)
.fetch_all(db)
.await?;
let latest = |table: &'static str, order: &'static str| {
format!(
"SELECT id FROM {table} WHERE person_id = $1 ORDER BY {order} DESC, id DESC LIMIT 1"
)
};
let mut plan: Vec<Planned> = Vec::new();
for (n, (id, surname, given)) in people.iter().enumerate() {
let whose = format!("{surname}, {given}");
let one = |sql: String| {
let id = *id;
async move {
sqlx::query_scalar::<_, i64>(&sql)
.bind(id)
.fetch_optional(db)
.await
}
};
let owner = Owner::Person(*id);
if let Some(pp) = one(latest("passports", "expires_on")).await? {
plan.push((
owner,
"passport-photo-page",
Some(format!("passports:{pp}")),
None,
"passport-photo-page.png".into(),
demo_png(Picture::PassportPage),
));
}
if let Some(a) = one(latest("arrivals", "arrived_on")).await? {
plan.push((
owner,
"tdac",
Some(format!("arrivals:{a}")),
None,
// the first person keeps it as a phone's screenshot
if n == 0 {
"TDAC screenshot.png".into()
} else {
"TDAC.pdf".into()
},
if n == 0 {
demo_png(Picture::Screenshot)
} else {
demo_pdf(
"Thailand Digital Arrival Card",
&[
format!("Traveller: {whose}"),
"Arrival card number: TDAC-DEMO".into(),
],
)
},
));
}
if let Some(r) = one(latest("ninety_day_reports", "reported_on")).await? {
plan.push((
owner,
"ninety-day-receipt",
Some(format!("reports:{r}")),
None,
"TM47 receipt.pdf".into(),
demo_pdf(
"Receipt of notification of staying over 90 days",
&[format!("Name: {whose}"), "Form TM.47, filed online".into()],
),
));
}
if n == 0 {
plan.push((
owner,
"photo",
None,
Some(today - TimeDelta::days(20)),
"photo 4x6.png".into(),
demo_png(Picture::Portrait),
));
// an ID card's two sides: they print on one page
for (file, picture) in [
("ID card front.png", Picture::CardFront),
("ID card back.png", Picture::CardBack),
] {
plan.push((owner, "id-card", None, None, file.into(), demo_png(picture)));
}
// the copies of the passport's pages and the work permit that
// the extension pack asks for
let copies = [
("visas", "issued_on", "visa", "Visa", "visa.pdf"),
(
"arrivals",
"arrived_on",
"arrival-stamp",
"Arrival stamp",
"arrival stamp.pdf",
),
(
"extensions",
"applied_on",
"extension-stamp",
"Extension of stay",
"extension stamp.pdf",
),
(
"reentry_permits",
"issued_on",
"reentry-permit",
"Re-entry permit",
"re-entry permit.pdf",
),
(
"work_permits",
"valid_until",
"work-permit",
"Work permit",
"work permit.pdf",
),
];
for (table, order, kind, title, file) in copies {
let link = match table {
"reentry_permits" => "reentry-permits",
"work_permits" => "work-permits",
other => other,
};
if let Some(r) = one(latest(table, order)).await? {
plan.push((
owner,
kind,
Some(format!("{link}:{r}")),
None,
file.into(),
demo_pdf(
&format!("{title} (copy of the passport page)"),
&[format!("Holder: {whose}")],
),
));
}
}
if let Some(a) = one(latest("addresses", "moved_in_on")).await? {
plan.push((
owner,
"tm30-receipt",
Some(format!("addresses:{a}")),
None,
"TM30 receipt.pdf".into(),
demo_pdf(
"Receipt of notification of residence (TM.30)",
&[
format!("Foreigner: {whose}"),
"Notified by the house master".into(),
],
),
));
}
}
}
let companies: Vec<(i64, String)> =
sqlx::query_as("SELECT id, name FROM companies WHERE notes = $1 ORDER BY id LIMIT 1")
.bind(MARKER)
.fetch_all(db)
.await?;
for (id, name) in companies {
let owner = Owner::Company(id);
plan.push((
owner,
"company-certificate",
None,
Some(today - TimeDelta::days(40)),
"company certificate.pdf".into(),
demo_pdf(
"Company certificate (certified copy)",
&[
format!("Company: {name}"),
"Certified by the registrar".into(),
],
),
));
// older than six months: out of date for the pack (phase 6)
plan.push((
owner,
"shareholders",
None,
Some(today - TimeDelta::days(240)),
"BOJ5.pdf".into(),
demo_pdf(
"List of shareholders (BOJ.5)",
&[
format!("Company: {name}"),
"Shareholders as of the last meeting".into(),
],
),
));
plan.push((
owner,
"office-photo",
None,
None,
"office outside.png".into(),
demo_png(Picture::Office),
));
// the latest year's statements, dated at the year's end
let year_end = NaiveDate::from_ymd_opt(today.year() - 1, 12, 31);
plan.push((
owner,
"balance-sheet",
None,
year_end,
"balance sheet and PND50.pdf".into(),
demo_pdf(
"Balance sheet with PND.50",
&[
format!("Company: {name}"),
"Financial statements of the year".into(),
],
),
));
// three months of withholding tax; social security without its date
for days in [75, 45, 14] {
plan.push((
owner,
"pnd1",
None,
Some(today - TimeDelta::days(days)),
format!("PND1 {days}.pdf"),
demo_pdf(
"Withholding tax (PND.1) with its receipt",
&[format!("Company: {name}"), format!("Filed {days} days ago")],
),
));
}
plan.push((
owner,
"sps1-10",
None,
None,
"SPS 1-10.pdf".into(),
demo_pdf(
"Social security (SPS 1-10), three months",
&[format!("Company: {name}")],
),
));
plan.push((
owner,
"map",
None,
None,
"map.pdf".into(),
demo_pdf("Map to the office", &[format!("Company: {name}")]),
));
}
let mut tx = db.begin().await?;
let mut written = Vec::new();
for (owner, kind, link, dated_on, name, bytes) in &plan {
let meta = Meta {
kind: (*kind).to_string(),
link: link.as_deref().and_then(documents::parse_link),
dated_on: *dated_on,
note: "Demo file".into(),
};
let sha256 = files::sha256_hex(bytes);
let file = NewFile {
name,
content_type: files::sniff(bytes).expect("demo files have a known type"),
size: i32::try_from(bytes.len())?,
sha256: &sha256,
};
let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?;
store.put(id, bytes.clone()).await?;
if name.ends_with(" back.png")
&& let Some(&front) = written.last()
{
documents::set_back(&mut tx, id, front).await?;
}
written.push(id);
audit::record(
&mut *tx,
&Entry {
actor: "seed",
action: Action::Create,
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: &[],
},
)
.await?;
}
tx.commit().await?;
Ok(written.len())
}
/// A one-page PDF in the app's colours: a title, a few lines and the demo
/// marker. ASCII text in Helvetica, so it needs no embedded font.
pub fn demo_pdf(title: &str, lines: &[String]) -> Vec<u8> {
let esc = |s: &str| {
s.chars()
.filter(char::is_ascii)
.collect::<String>()
.replace('\\', "\\\\")
.replace('(', "\\(")
.replace(')', "\\)")
};
let mut content =
String::from("0.027 0.075 0.137 rg 0 762 595 80 re f\n0.961 0.753 0 rg 0 756 595 6 re f\n");
content.push_str(&format!(
"BT /F1 18 Tf 1 1 1 rg 48 792 Td ({}) Tj ET\n",
esc(title)
));
let mut y = 700;
for line in lines {
content.push_str(&format!(
"BT /F1 12 Tf 0.1 0.1 0.1 rg 48 {y} Td ({}) Tj ET\n",
esc(line)
));
y -= 22;
}
content.push_str(&format!(
"BT /F1 26 Tf 0.85 0.2 0.2 rg 48 520 Td (SPECIMEN) Tj ET\n\
BT /F1 10 Tf 0.4 0.4 0.4 rg 48 60 Td ({}) Tj ET\n",
esc(MARKER)
));
let objects = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] \
/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>"
.to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"
.to_string(),
format!(
"<< /Length {} >>\nstream\n{content}endstream",
content.len()
),
];
let mut out = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
);
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
out
}
/// A picture made of shapes, as a PNG with a palette.
/// A plain PNG of `w` x `h` pixels, for tests of how pictures print.
pub fn plain_png(w: usize, h: usize) -> Vec<u8> {
png(w, h, &vec![0u8; w * h])
}
fn demo_png(picture: Picture) -> Vec<u8> {
let (w, h) = match picture {
Picture::PassportPage => (600usize, 420usize),
Picture::Portrait => (240, 360),
Picture::Office => (480, 320),
Picture::Screenshot => (390, 844),
Picture::CardFront | Picture::CardBack => (428, 270),
};
let mut px = vec![0u8; w * h];
let mut fill = |x0: usize, y0: usize, x1: usize, y1: usize, c: u8| {
for y in y0.min(h)..y1.min(h) {
for x in x0.min(w)..x1.min(w) {
px[y * w + x] = c;
}
}
};
let head = |cx: f64, cy: f64, r: f64, x: usize, y: usize| {
let (dx, dy) = (x as f64 - cx, (y as f64 - cy) * 0.85);
dx * dx + dy * dy <= r * r
};
match picture {
Picture::PassportPage => {
fill(0, 0, w, 56, 1);
fill(0, 56, w, 62, 2);
fill(30, 92, 170, 282, 4);
for (i, len) in [220usize, 160, 250, 140, 200, 120].iter().enumerate() {
let y = 100 + i * 30;
fill(200, y, 200 + len, y + 12, 6);
}
fill(0, 320, w, h, 5);
for row in 0..2 {
for cell in 0..44 {
let (x, y) = (24 + cell * 12, 338 + row * 34);
fill(x, y, x + 9, y + 18, 6);
}
}
}
Picture::Portrait => {
fill(0, 0, w, h, 4);
fill(40, 270, 200, h, 1);
}
Picture::Screenshot => {
fill(0, 0, w, h, 5);
fill(0, 0, w, 44, 4);
fill(0, 44, w, 140, 1);
fill(24, 72, 240, 96, 2);
for i in 0..9 {
let y = 180 + i * 56;
fill(24, y, 140, y + 12, 3);
fill(24, y + 20, 24 + 120 + (i * 37) % 200, y + 34, 6);
}
fill(110, 700, 280, 790, 6);
}
Picture::CardFront => {
fill(0, 0, w, h, 4);
fill(0, 0, w, 40, 1);
fill(20, 60, 120, 200, 3);
for (i, len) in [200usize, 150, 230, 120].iter().enumerate() {
let y = 70 + i * 34;
fill(140, y, 140 + len, y + 12, 6);
}
fill(0, 240, w, 248, 2);
}
Picture::CardBack => {
fill(0, 0, w, h, 4);
fill(0, 30, w, 70, 1);
for i in 0..5 {
let y = 100 + i * 26;
fill(24, y, 24 + 300 - i * 30, y + 10, 6);
}
}
Picture::Office => {
fill(0, 0, w, 200, 7);
fill(0, 260, w, h, 3);
fill(90, 70, 390, 260, 0);
fill(90, 62, 390, 72, 1);
for col in 0..5 {
for row in 0..3 {
let (x, y) = (112 + col * 56, 92 + row * 52);
fill(x, y, x + 32, y + 30, 1);
}
}
fill(212, 200, 268, 260, 2);
}
}
if let Picture::Portrait = picture {
for y in 0..h {
for x in 0..w {
if head(120.0, 150.0, 62.0, x, y) {
px[y * w + x] = 3;
}
}
}
}
if let Picture::PassportPage = picture {
for y in 92..282 {
for x in 30..170 {
if head(100.0, 160.0, 40.0, x, y) {
px[y * w + x] = 3;
}
}
}
for y in 230..282 {
for x in 50..150 {
px[y * w + x] = 3;
}
}
}
png(w, h, &px)
}
/// A PNG of `w` x `h` pixels in the demo palette, stored without
/// compression.
fn png(w: usize, h: usize, px: &[u8]) -> Vec<u8> {
const PALETTE: [[u8; 3]; 8] = [
[0xf3, 0xef, 0xe2], // paper
[0x07, 0x13, 0x23], // navy
[0xf5, 0xc0, 0x00], // gold
[0x9b, 0xa8, 0xba], // grey
[0xd8, 0xdd, 0xe5], // light grey
[0xff, 0xff, 0xff], // white
[0x3a, 0x45, 0x56], // ink
[0xa9, 0xc8, 0xe8], // sky
];
// the image data: each row with filter 0, in stored deflate blocks
let mut raw = Vec::with_capacity(h * (w + 1));
for row in px.chunks(w) {
raw.push(0);
raw.extend_from_slice(row);
}
let mut z = vec![0x78, 0x01];
let blocks: Vec<&[u8]> = raw.chunks(65_535).collect();
for (i, b) in blocks.iter().enumerate() {
z.push(u8::from(i + 1 == blocks.len()));
let len = b.len() as u16;
z.extend_from_slice(&len.to_le_bytes());
z.extend_from_slice(&(!len).to_le_bytes());
z.extend_from_slice(b);
}
z.extend_from_slice(&adler32(&raw).to_be_bytes());
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&(w as u32).to_be_bytes());
ihdr.extend_from_slice(&(h as u32).to_be_bytes());
ihdr.extend_from_slice(&[8, 3, 0, 0, 0]);
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
chunk(&mut out, b"IHDR", &ihdr);
chunk(&mut out, b"PLTE", &PALETTE.concat());
chunk(&mut out, b"IDAT", &z);
chunk(&mut out, b"IEND", &[]);
out
}
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc = 0xFFFF_FFFFu32;
for &b in kind.iter().chain(data) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
out.extend_from_slice(&(!crc).to_be_bytes());
}
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &x in data {
a = (a + u32::from(x)) % 65_521;
b = (b + a) % 65_521;
}
(b << 16) | a
}
#[cfg(test)]
mod demo_file_tests {
use super::*;
#[test]
fn demo_files_are_what_they_say() {
let pdf = demo_pdf("Title (demo)", &["Line".to_string()]);
assert_eq!(files::sniff(&pdf), Some("application/pdf"));
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains(MARKER));
assert!(text.contains("Title \\(demo\\)"));
// the cross-reference table points at the objects
let xref: usize = text
.rsplit("startxref\n")
.next()
.and_then(|t| t.lines().next())
.and_then(|n| n.parse().ok())
.unwrap();
assert!(text[xref..].starts_with("xref"));
for p in [Picture::PassportPage, Picture::Portrait, Picture::Office] {
let png = demo_png(p);
assert_eq!(files::sniff(&png), Some("image/png"));
assert!(png.ends_with(&[0xAE, 0x42, 0x60, 0x82]), "IEND's CRC");
}
assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398);
}
}