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.
This commit is contained in:
1 parent
2e009700a9
commit
83bc481952
37 files changed
+5514
-141
No files matched your search
@@ -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` |
|
||||
|
||||
@@ -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.
|
||||
|
||||
+34
-18
@@ -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
|
||||
|
||||
|
||||
@@ -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'
|
||||
)
|
||||
);
|
||||
+35
-3
@@ -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<i64>,
|
||||
fields: Vec<String>,
|
||||
person_name: Option<String>,
|
||||
company_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -123,17 +138,30 @@ pub struct Item {
|
||||
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 \
|
||||
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<i64>, limit: i64) -> Result<Vec<
|
||||
.map(|r| {
|
||||
let what = match (r.entity.as_str(), r.entity_id) {
|
||||
("session", _) => 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<i64>, limit: i64) -> Result<Vec<
|
||||
what,
|
||||
person_id: r.person_id,
|
||||
person_name: r.person_name,
|
||||
company_id,
|
||||
company_name: r.company_name,
|
||||
fields: r.fields.join(", ").replace('_', " "),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
//! Companies: the employers of the people in the records, later also the
|
||||
//! agency's corporate clients. Their fields and checks are
|
||||
//! `records::COMPANIES`; this module holds what only companies need: the
|
||||
//! list, archiving, the choices for the selections, and the people they
|
||||
//! employ.
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::{DateTime, NaiveDate, TimeDelta, Utc};
|
||||
use serde::Serialize;
|
||||
use sqlx::{PgConnection, PgPool};
|
||||
|
||||
use crate::countries;
|
||||
use crate::dates::{self, Status};
|
||||
use crate::people::{self, AddressInput};
|
||||
use crate::records::Record;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ListItem {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub name_th: String,
|
||||
pub registration_no: String,
|
||||
pub province: String,
|
||||
/// People it employs (not archived).
|
||||
pub people: i64,
|
||||
/// Lower-case text the filter box searches.
|
||||
pub q: String,
|
||||
}
|
||||
|
||||
pub async fn list(db: &PgPool, archived: bool) -> Result<Vec<ListItem>> {
|
||||
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<i64>) -> Result<Vec<(String, String)>> {
|
||||
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<Vec<(String, String)>> {
|
||||
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<Option<String>> {
|
||||
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<Option<Option<DateTime<Utc>>>> {
|
||||
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<bool> {
|
||||
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<i64>) -> Result<bool> {
|
||||
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<Vec<Employee>> {
|
||||
type Row = (i64, String, String, String, String, Option<NaiveDate>);
|
||||
let rows: Vec<Row> = 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<Vec<(String, String)>> {
|
||||
type Row = (i64, String, String, String, Option<String>);
|
||||
let rows: Vec<Row> = 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<bool> {
|
||||
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<bool> {
|
||||
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<DateTime<Utc>>) -> 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(),
|
||||
}
|
||||
}
|
||||
+1166
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
|
||||
+50
-21
@@ -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<i64>,
|
||||
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<i64>,
|
||||
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<PersonInput, Errors> {
|
||||
/// `companies`: the ids the employer may be chosen from.
|
||||
pub fn validate(&self, today: NaiveDate, companies: &[i64]) -> Result<PersonInput, Errors> {
|
||||
let mut e = Errors::new();
|
||||
let employer = match self.employer.parse::<i64>() {
|
||||
_ 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<Option<Pe
|
||||
pub async fn create_person(conn: &mut PgConnection, p: &PersonInput) -> Result<i64> {
|
||||
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<i
|
||||
.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)
|
||||
@@ -320,7 +331,7 @@ pub async fn update_person(conn: &mut PgConnection, id: i64, p: &PersonInput) ->
|
||||
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<NaiveDate>,
|
||||
employer: String,
|
||||
employer_id: Option<i64>,
|
||||
employer: Option<String>,
|
||||
passport_number: Option<String>,
|
||||
passport_expires: Option<NaiveDate>,
|
||||
province: Option<String>,
|
||||
@@ -376,30 +388,42 @@ pub struct ListItem {
|
||||
pub name: String,
|
||||
pub nationality: String,
|
||||
pub age: Option<i32>,
|
||||
pub employer_id: Option<i64>,
|
||||
pub employer: String,
|
||||
pub passport_number: String,
|
||||
pub passport_expires: String,
|
||||
pub passport_status: Option<dates::Status>,
|
||||
pub province: String,
|
||||
/// The most urgent deadline; the page fills it in.
|
||||
pub next: Option<crate::deadlines::Deadline>,
|
||||
/// Lower-case text the filter box searches.
|
||||
pub q: String,
|
||||
}
|
||||
|
||||
pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result<Vec<ListItem>> {
|
||||
/// 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<i64>,
|
||||
today: NaiveDate,
|
||||
) -> Result<Vec<ListItem>> {
|
||||
let rows: Vec<ListRow> = 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<Vec<L
|
||||
.to_string();
|
||||
let passport_number = r.passport_number.unwrap_or_default();
|
||||
let province = r.province.unwrap_or_default();
|
||||
let employer = r.employer.unwrap_or_default();
|
||||
let q = format!(
|
||||
"{name} {nationality} {} {passport_number} {} {province}",
|
||||
r.nationality, r.employer
|
||||
"{name} {nationality} {} {passport_number} {employer} {province}",
|
||||
r.nationality
|
||||
)
|
||||
.to_lowercase();
|
||||
ListItem {
|
||||
@@ -427,9 +452,11 @@ pub async fn list(db: &PgPool, archived: bool, today: NaiveDate) -> Result<Vec<L
|
||||
passport_status: r.passport_expires.map(|d| dates::passport_status(d, today)),
|
||||
name,
|
||||
nationality,
|
||||
employer: r.employer,
|
||||
employer_id: r.employer_id,
|
||||
employer,
|
||||
passport_number,
|
||||
province,
|
||||
next: None,
|
||||
q,
|
||||
}
|
||||
})
|
||||
@@ -1085,7 +1112,7 @@ mod tests {
|
||||
]));
|
||||
assert_eq!(f.surname, "Mustermann");
|
||||
assert_eq!(f.nationality, "DEU");
|
||||
let e = f.validate(today).unwrap_err();
|
||||
let e = f.validate(today, &[]).unwrap_err();
|
||||
assert_eq!(
|
||||
e.keys().map(String::as_str).collect::<Vec<_>>(),
|
||||
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();
|
||||
|
||||
+1251
File diff suppressed because it is too large.
Load diff
+317
-43
@@ -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<usize>,
|
||||
passports: Vec<PassportInput>,
|
||||
addresses: Vec<AddressInput>,
|
||||
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)
|
||||
};
|
||||
let mrz = if with_mrz {
|
||||
mrz::compose(&mrz::Compose {
|
||||
issuing_state: if p.nationality == "DEU" {
|
||||
// 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: 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<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",
|
||||
"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<Demo> {
|
||||
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<Demo> {
|
||||
"Berlin",
|
||||
"DEU",
|
||||
"Electrical engineer",
|
||||
employer,
|
||||
1,
|
||||
);
|
||||
let erika_pp = passport(
|
||||
@@ -164,6 +219,73 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"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<Demo> {
|
||||
"Portland, Oregon",
|
||||
"USA",
|
||||
"Product designer",
|
||||
employer,
|
||||
2,
|
||||
);
|
||||
let jane_old = passport(
|
||||
@@ -193,6 +314,16 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"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<Demo> {
|
||||
"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<Demo> {
|
||||
"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<Demo> {
|
||||
vec![
|
||||
Demo {
|
||||
person: erika,
|
||||
employer: Some(0),
|
||||
passports: vec![erika_pp],
|
||||
addresses: vec![
|
||||
address(
|
||||
@@ -237,9 +444,9 @@ fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||
"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<Demo> {
|
||||
"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<Demo> {
|
||||
"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<Demo> {
|
||||
"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<i64>) -> 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<bool> {
|
||||
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<bool> {
|
||||
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<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, &log(Action::Archive, Entity::Person, id, id)).await?;
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&seeded(Action::Archive, Entity::Person, id, Some(id)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
tx.commit().await?;
|
||||
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<ListQuery>,
|
||||
) -> 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<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
|
||||
Ok(form_page(
|
||||
&st,
|
||||
&user,
|
||||
None,
|
||||
&Values::new(),
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
|
||||
async fn checked(st: &AppState, f: &Fields, id: Option<i64>) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
set_archived(&st, &user, id, true).await
|
||||
}
|
||||
|
||||
pub async fn restore(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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::<i64>().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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
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())
|
||||
}
|
||||
@@ -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<String>,
|
||||
/// A company's id: only the people it employs.
|
||||
#[serde(default)]
|
||||
company: Option<String>,
|
||||
}
|
||||
|
||||
#[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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<DashQuery>,
|
||||
) -> Res {
|
||||
let today = dates::today();
|
||||
let all = q.all.as_deref() == Some("1");
|
||||
let company: Option<i64> = q.company.as_deref().and_then(|c| c.parse().ok());
|
||||
let people: Vec<(i64, String, String, String, Option<String>)> = 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<i64> = 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(),
|
||||
},
|
||||
))
|
||||
}
|
||||
+91
-4
@@ -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<AppState>) {
|
||||
}
|
||||
|
||||
pub fn router(st: Arc<AppState>) -> 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<AppState>) -> Router {
|
||||
"/people/{id}/addresses/{aid}/delete",
|
||||
post(p::address_delete),
|
||||
)
|
||||
.route("/activity", get(activity::page))
|
||||
.route(
|
||||
"/people/{id}/stay",
|
||||
get(
|
||||
|State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>| records::stay(st, user, id),
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/people/{id}/activity",
|
||||
get(
|
||||
|State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>| 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}/<slug>, .../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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>| {
|
||||
records::create(kind, st, user, id, f)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/new"),
|
||||
get(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>| {
|
||||
records::new_form(kind, st, user, id)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{rid}}"),
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>,
|
||||
Form(f): Form<Fields>| {
|
||||
records::update(kind, st, user, id, rid, f)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{rid}}/edit"),
|
||||
get(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>| {
|
||||
records::edit_form(kind, st, user, id, rid)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{rid}}/delete"),
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
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))
|
||||
|
||||
+96
-21
@@ -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<i64>,
|
||||
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<String>,
|
||||
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<Option<(Person, PersonView)>> {
|
||||
/// 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<Option<(Person, PersonView)>> {
|
||||
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<String> {
|
||||
pub struct ListQuery {
|
||||
#[serde(default)]
|
||||
archived: Option<String>,
|
||||
/// A company's id: only the people it employs.
|
||||
#[serde(default)]
|
||||
company: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
@@ -224,21 +245,42 @@ pub async fn list(
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<ListQuery>,
|
||||
) -> 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<i64> = q.company.as_deref().and_then(|c| c.parse().ok());
|
||||
let mut rows = people::list(&st.db, archived, company, today).await?;
|
||||
let ids: Vec<i64> = 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<String>,
|
||||
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<i64>,
|
||||
) -> anyhow::Result<(Vec<(String, String)>, Vec<i64>)> {
|
||||
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<Arc<AppState>>, Extension(user): Extension<User>) -> 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<Arc<AppState>>, Extension(user): Extensio
|
||||
&PassportForm::default(),
|
||||
&Errors::new(),
|
||||
None,
|
||||
&companies,
|
||||
StatusCode::OK,
|
||||
))
|
||||
}
|
||||
@@ -340,6 +408,7 @@ pub async fn create(
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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() },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 `<datalist>`.
|
||||
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<i64>,
|
||||
) -> anyhow::Result<Options> {
|
||||
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<i64> {
|
||||
v.get("company_id").and_then(|c| c.parse().ok())
|
||||
}
|
||||
|
||||
pub async fn stay(st: Arc<AppState>, 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::Shown> = 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<AppState>, 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<i64>,
|
||||
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<AppState>, 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<AppState>, 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<AppState>,
|
||||
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<AppState>,
|
||||
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<AppState>, 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))
|
||||
}
|
||||
+135
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{#- Where the person stands and what is due, the most urgent first. -#}
|
||||
<section class="card span2" id="deadlines">
|
||||
<header><h2>Status and deadlines</h2>{% if tab != "stay" %}<a class="btn sm ghost" href="/people/{{ p.id }}/stay">Visa and stay</a>{% endif %}</header>
|
||||
{% if stay.state == "in" %}
|
||||
<p class="stayline{% if stay.overstay %} bad{% endif %}">In Thailand since <b>{{ stay.since }}</b>, permitted to stay until <b>{{ stay.permitted_until }}</b> ({{ stay.remaining }}). Basis: {{ stay.basis }}.</p>
|
||||
{% elif stay.state == "abroad" %}
|
||||
<p class="stayline">Left Thailand on <b>{{ stay.left_on }}</b>; no stay is running.</p>
|
||||
{% else %}
|
||||
<p class="stayline muted">No arrival is recorded yet. Add the latest arrival under <a href="/people/{{ p.id }}/stay#arrivals">Visa and stay</a> to see the deadlines of the stay.</p>
|
||||
{% endif %}
|
||||
{% if deadlines %}
|
||||
<ul class="dl">
|
||||
{% for d in deadlines %}
|
||||
<li>
|
||||
<div class="dl-what"><b>{{ d.title }}</b>{% if d.due_text %}<span class="dl-when">{{ d.due_text }}, {{ d.when }}{% if d.estimate %} (estimate){% endif %}</span>{% endif %}</div>
|
||||
<span class="chip {{ d.level }}">{{ d.label }}</span>
|
||||
<p class="dl-note">{{ d.note }}</p>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</section>
|
||||
@@ -14,10 +14,10 @@
|
||||
</div>
|
||||
{%- 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) -%}
|
||||
<div class="field{% if err %} has-err{% endif %}{% if cls %} {{ cls }}{% endif %}">
|
||||
<label for="f-{{ name }}">{{ label }}</label>
|
||||
<select id="f-{{ name }}" name="{{ name }}"{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% endif %}>
|
||||
<label for="f-{{ name }}">{{ label }}{% if req %} <span class="req" aria-hidden="true">*</span>{% endif %}</label>
|
||||
<select id="f-{{ name }}" name="{{ name }}"{% if req %} required{% endif %}{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% endif %}>
|
||||
<option value="">{{ blank }}</option>
|
||||
{%- for o in options %}
|
||||
<option value="{{ o[0] }}"{% if o[0] == value %} selected{% endif %}>{{ o[1] }}</option>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{#- The head of every page about one person: the same place on each. -#}
|
||||
<div class="phead">
|
||||
{#- The head of every page about one person, with its tabs: the same
|
||||
place on each. -#}
|
||||
<div class="phead tabbed">
|
||||
<div class="crumbs"><a href="/people">People</a></div>
|
||||
<div class="pagehead">
|
||||
<h1><a href="/people/{{ p.id }}">{{ p.name }}</a></h1>
|
||||
@@ -15,9 +16,14 @@
|
||||
{%- if p.nationality_name %}{{ p.nationality_name }}{% else %}Nationality not recorded{% endif %}
|
||||
{%- if p.age is not none %}<span class="sep">·</span>{{ p.age }} years{% endif %}
|
||||
{%- if p.current_passport %}<span class="sep">·</span>passport <span class="mono">{{ p.current_passport }}</span>{% endif %}
|
||||
{%- if p.employer %}<span class="sep">·</span>{{ p.employer }}{% endif %}
|
||||
{%- if p.employer %}<span class="sep">·</span><a href="/companies/{{ p.employer_id }}">{{ p.employer }}</a>{% endif %}
|
||||
</p>
|
||||
<nav class="tabs" aria-label="About {{ p.name }}">
|
||||
<a href="/people/{{ p.id }}"{% if tab != "stay" and tab != "activity" %} class="on" aria-current="page"{% endif %}>Overview</a>
|
||||
<a href="/people/{{ p.id }}/stay"{% if tab == "stay" %} class="on" aria-current="page"{% endif %}>Visa and stay</a>
|
||||
<a href="/people/{{ p.id }}/activity"{% if tab == "activity" %} class="on" aria-current="page"{% endif %}>Activity</a>
|
||||
</nav>
|
||||
</div>
|
||||
{% if p.archived %}
|
||||
<div class="notice warn">Archived on {{ p.archived_on }}. Archived people are left out of the list; Restore brings the record back.</div>
|
||||
<div class="notice warn">Archived on {{ p.archived_on }}. Archived people are left out of the list and the deadlines; Restore brings the record back.</div>
|
||||
{% endif %}
|
||||
@@ -16,7 +16,7 @@
|
||||
<td class="mono">{{ e.at }}</td>
|
||||
<td>{{ e.actor }}</td>
|
||||
<td>{{ e.action }}</td>
|
||||
<td>{% if e.person_id %}<a href="/people/{{ e.person_id }}">{{ e.person_name or ("person " ~ e.person_id) }}</a> <span class="muted">{{ e.what }}</span>{% else %}<span class="muted">{{ e.what }}</span>{% endif %}</td>
|
||||
<td>{% if e.person_id %}<a href="/people/{{ e.person_id }}">{{ e.person_name or ("person " ~ e.person_id) }}</a> <span class="muted">{{ e.what }}</span>{% elif e.company_id %}<a href="/companies/{{ e.company_id }}">{{ e.company_name or ("company " ~ e.company_id) }}</a> <span class="muted">company</span>{% else %}<span class="muted">{{ e.what }}</span>{% endif %}</td>
|
||||
<td class="hs muted">{{ e.fields }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
+3
-1
@@ -12,7 +12,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<a class="brand" href="/people" aria-label="visa.buildfor.life, the people">
|
||||
<a class="brand" href="/" aria-label="visa.buildfor.life, the deadlines">
|
||||
{% include "_mark.html" %}
|
||||
<span class="nm">Visa</span><span class="sub">buildfor.life</span>
|
||||
</a>
|
||||
@@ -21,7 +21,9 @@
|
||||
<div class="app">
|
||||
<aside class="side">
|
||||
<nav class="nav" aria-label="Sections">
|
||||
<a href="/"{% if nav == "deadlines" %} class="on" aria-current="page"{% endif %}>Deadlines</a>
|
||||
<a href="/people"{% if nav == "people" %} class="on" aria-current="page"{% endif %}>People</a>
|
||||
<a href="/companies"{% if nav == "companies" %} class="on" aria-current="page"{% endif %}>Companies</a>
|
||||
<a href="/activity"{% if nav == "activity" %} class="on" aria-current="page"{% endif %}>Activity</a>
|
||||
</nav>
|
||||
<div class="who">
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="pagehead">
|
||||
<h1>{% if archived %}Archived companies{% else %}Companies{% endif %}</h1>
|
||||
<div class="actions"><a class="btn pri" href="/companies/new" id="new-company">+ New company</a></div>
|
||||
</div>
|
||||
{% if companies or n_archived %}
|
||||
<div class="toolbar">
|
||||
{% if companies %}<input type="search" id="q" class="filter" placeholder="Filter by name, number or province ( / )" aria-label="Filter the list" autocomplete="off">{% endif %}
|
||||
{% if archived %}<a href="/companies">Back to the {{ n_active }} in the list</a>{% elif n_archived %}<a href="/companies?archived=1">Archived ({{ n_archived }})</a>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if companies %}
|
||||
<div class="card flush">
|
||||
<div class="tblwrap">
|
||||
<table class="tbl" id="companies">
|
||||
<thead><tr><th>Company</th><th>Registration number</th><th class="hs">Province</th><th>People</th></tr></thead>
|
||||
<tbody>
|
||||
{% for c in companies %}
|
||||
<tr data-q="{{ c.q }}">
|
||||
<td><a class="strong" href="/companies/{{ c.id }}">{{ c.name }}</a>{% if c.name_th %}<div class="sub">{{ c.name_th }}</div>{% endif %}</td>
|
||||
<td class="mono">{{ c.registration_no }}</td>
|
||||
<td class="hs">{{ c.province }}</td>
|
||||
<td>{% if c.people %}<a href="/people?company={{ c.id }}">{{ c.people }}</a>{% else %}<span class="muted">0</span>{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="filter-empty" data-filter-empty hidden>No company matches the filter.</p>
|
||||
</div>
|
||||
{% elif archived %}
|
||||
<div class="card"><p class="empty-inline">No company is archived.</p></div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<h2>No companies yet</h2>
|
||||
<p>Add the employers with <b>+ New company</b>. A person's employer and the employer on a work permit are then chosen from this list.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,70 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/companies">Companies</a></div>
|
||||
<div class="pagehead">
|
||||
<h1>{{ c.name }}</h1>
|
||||
<div class="actions">
|
||||
<a class="btn sm" href="/companies/{{ c.id }}/edit">Edit</a>
|
||||
{% if c.archived %}
|
||||
<form method="post" action="/companies/{{ c.id }}/restore" class="inline-form"><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm">Restore</button></form>
|
||||
{% else %}
|
||||
<form method="post" action="/companies/{{ c.id }}/archive" class="inline-form" data-confirm="Archive {{ c.name }}? It is no longer offered as an employer; existing records keep it."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm ghost">Archive</button></form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<p class="meta">
|
||||
{%- if c.name_th %}{{ c.name_th }}{% endif %}
|
||||
{%- if c.registration_no %}{% if c.name_th %}<span class="sep">·</span>{% endif %}registration <span class="mono">{{ c.registration_no }}</span>{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
{% if c.archived %}
|
||||
<div class="notice warn">Archived on {{ c.archived_on }}. It is no longer offered as an employer; Restore brings it back.</div>
|
||||
{% endif %}
|
||||
<div class="cols">
|
||||
<section class="card" id="details">
|
||||
<header><h2>Company details</h2></header>
|
||||
<dl class="kv">
|
||||
<dt>Name in English</dt><dd>{{ c.name }}</dd>
|
||||
<dt>Name in Thai</dt><dd>{% if c.name_th %}{{ c.name_th }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Registration number</dt><dd>{% if c.registration_no %}<span class="mono">{{ c.registration_no }}</span>{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Type of business</dt><dd>{% if c.business %}{{ c.business }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Address</dt><dd>{% if c.address %}{{ c.address }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Phone</dt><dd>{% if c.phone %}{{ c.phone }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Email</dt><dd>{% if c.email %}{{ c.email }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Authorized director</dt><dd>{% if c.signatory %}{{ c.signatory }}{% if c.signatory_position %}, {{ c.signatory_position }}{% endif %}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
{% if c.notes %}<dt>Notes</dt><dd class="pre">{{ c.notes }}</dd>{% endif %}
|
||||
</dl>
|
||||
</section>
|
||||
<section class="card" id="people">
|
||||
<header><h2>People employed</h2>{% if employees %}<a class="btn sm ghost" href="/people?company={{ c.id }}">In the people list</a>{% endif %}</header>
|
||||
{% for e in employees %}
|
||||
<div class="item">
|
||||
<div class="row"><a class="strong" href="/people/{{ e.id }}">{{ e.name }}</a><span class="muted">{{ e.nationality }}</span></div>
|
||||
<div class="row">
|
||||
<span class="chip {{ e.permit.level }}">{{ e.permit.label }}</span>
|
||||
<form method="post" action="/companies/{{ c.id }}/employees/{{ e.id }}/remove" class="inline-form" data-confirm="Remove {{ e.name }} from the people employed here? The person's record stays."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="linkbtn">Remove</button></form>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty-inline">No one is recorded as employed here yet.</p>
|
||||
{% endfor %}
|
||||
{% if candidates and not c.archived %}
|
||||
<form method="post" action="/companies/{{ c.id }}/employees" class="hire" id="hire-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<label for="f-person">Add a person</label>
|
||||
<div class="hire-row">
|
||||
<select id="f-person" name="person" required>
|
||||
<option value="">Choose a person</option>
|
||||
{%- for o in candidates %}
|
||||
<option value="{{ o[0] }}">{{ o[1] }}</option>
|
||||
{%- endfor %}
|
||||
</select>
|
||||
<button type="submit" class="btn sm">Add</button>
|
||||
</div>
|
||||
<p class="hint">This makes the company the person's employer. Someone new is first added under People.</p>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,54 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="pagehead">
|
||||
<h1>Deadlines</h1>
|
||||
<div class="actions"><a class="btn" href="/people">People</a></div>
|
||||
</div>
|
||||
<div class="summary">
|
||||
<span class="chip {% if overdue %}bad{% else %}ok{% endif %}">{{ overdue }} overdue or urgent</span>
|
||||
<span class="chip {% if soon %}warn{% else %}ok{% endif %}">{{ soon }} need attention</span>
|
||||
<span class="muted small">For {{ n_people }} {% if n_people == 1 %}person{% else %}people{% endif %}{% if not all %}: the next {{ horizon_days }} days, and anything urgent{% endif %}.</span>
|
||||
</div>
|
||||
<form method="get" action="/" class="toolbar" id="dash-filter">
|
||||
{% if rows %}<input type="search" id="q" class="filter" placeholder="Filter by name, company or deadline ( / )" aria-label="Filter the list" autocomplete="off">{% endif %}
|
||||
{% if companies %}
|
||||
<label class="sel"><span class="small muted">Employer</span>
|
||||
<select name="company" data-autosubmit>
|
||||
<option value="">Any</option>
|
||||
{%- for c in companies %}
|
||||
<option value="{{ c[0] }}"{% if c[0] == company %} selected{% endif %}>{{ c[1] }}</option>
|
||||
{%- endfor %}
|
||||
</select></label>
|
||||
<noscript><button type="submit" class="btn sm">Show</button></noscript>
|
||||
{% endif %}
|
||||
{% if all %}<input type="hidden" name="all" value="1"><a href="/{% if company %}?company={{ company }}{% endif %}">Only the next {{ horizon_days }} days</a>{% else %}<a href="/?all=1{% if company %}&company={{ company }}{% endif %}">Show everything</a>{% endif %}
|
||||
</form>
|
||||
{% if rows %}
|
||||
<div class="card flush">
|
||||
<div class="tblwrap">
|
||||
<table class="tbl" id="deadline-list">
|
||||
<thead><tr><th>Due</th><th>Person</th><th>Deadline</th><th>Status</th><th class="hs">What to do</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr data-q="{{ r.q }}">
|
||||
<td class="nowrap">{{ r.d.due_text }}<div class="sub">{{ r.d.when }}{% if r.d.estimate %}, estimate{% endif %}</div></td>
|
||||
<td class="nowrap"><a class="strong" href="/people/{{ r.person_id }}">{{ r.person }}</a>{% if r.employer %}<div class="sub">{{ r.employer }}</div>{% endif %}</td>
|
||||
<td class="nowrap">{{ r.d.title }}</td>
|
||||
<td><span class="chip {{ r.d.level }}">{{ r.d.label }}</span></td>
|
||||
<td class="hs small note">{{ r.d.note }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="filter-empty" data-filter-empty hidden>No deadline matches the filter.</p>
|
||||
</div>
|
||||
{% elif n_people %}
|
||||
<div class="card"><p class="empty-inline">Nothing is due{% if not all %} in the next {{ horizon_days }} days{% endif %}.</p></div>
|
||||
{% else %}
|
||||
<div class="card">
|
||||
<h2>No people yet</h2>
|
||||
<p>The deadlines appear here once people and their arrivals are recorded. Start under <a href="/people">People</a>.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
+21
-8
@@ -1,31 +1,42 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="pagehead">
|
||||
<h1>{% if archived %}Archived people{% else %}People{% endif %}</h1>
|
||||
<h1>{{ heading }}</h1>
|
||||
<div class="actions"><a class="btn pri" href="/people/new" id="new-person">+ New person</a></div>
|
||||
</div>
|
||||
{% if people or n_archived %}
|
||||
<div class="toolbar">
|
||||
{% if people or n_archived or company %}
|
||||
<form method="get" action="/people" class="toolbar" id="people-filter">
|
||||
{% if people %}<input type="search" id="q" class="filter" placeholder="Filter by name, passport, nationality or employer ( / )" aria-label="Filter the list" autocomplete="off">{% endif %}
|
||||
{% if archived %}<a href="/people">Back to the {{ n_active }} in the list</a>{% elif n_archived %}<a href="/people?archived=1">Archived ({{ n_archived }})</a>{% endif %}
|
||||
</div>
|
||||
{% if companies %}
|
||||
<label class="sel"><span class="small muted">Employer</span>
|
||||
<select name="company" data-autosubmit>
|
||||
<option value="">Any</option>
|
||||
{%- for c in companies %}
|
||||
<option value="{{ c[0] }}"{% if c[0] == company %} selected{% endif %}>{{ c[1] }}</option>
|
||||
{%- endfor %}
|
||||
</select></label>
|
||||
<noscript><button type="submit" class="btn sm">Show</button></noscript>
|
||||
{% endif %}
|
||||
{% if archived %}<input type="hidden" name="archived" value="1"><a href="/people">Back to the {{ n_active }} in the list</a>{% elif n_archived and not company %}<a href="/people?archived=1">Archived ({{ n_archived }})</a>{% endif %}
|
||||
</form>
|
||||
{% endif %}
|
||||
{% if people %}
|
||||
<div class="card flush">
|
||||
<div class="tblwrap">
|
||||
<table class="tbl" id="people">
|
||||
<thead>
|
||||
<tr><th>Name</th><th class="hs">Nationality</th><th>Passport</th><th>Valid until</th><th class="hs">Lives in</th><th class="hs">Employer</th></tr>
|
||||
<tr><th>Name</th><th>Next deadline</th><th>Passport</th><th>Valid until</th><th class="hs">Nationality</th><th class="hs">Employer</th><th class="hs">Lives in</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in people %}
|
||||
<tr data-q="{{ r.q }}">
|
||||
<td><a class="strong" href="/people/{{ r.id }}">{{ r.name }}</a>{% if r.age is not none %}<div class="sub">{{ r.age }} years</div>{% endif %}</td>
|
||||
<td class="hs">{{ r.nationality }}</td>
|
||||
<td>{% if r.next %}<span class="chip {{ r.next.level }}">{{ r.next.label }}</span><div class="sub">{{ r.next.title }}, {{ r.next.due_text }}</div>{% else %}<span class="muted">none</span>{% endif %}</td>
|
||||
<td>{% if r.passport_number %}<span class="mono">{{ r.passport_number }}</span>{% else %}<span class="muted">none recorded</span>{% endif %}</td>
|
||||
<td>{% if r.passport_status %}{{ r.passport_expires }}<div><span class="chip {{ r.passport_status.level }}">{{ r.passport_status.label }}</span></div>{% endif %}</td>
|
||||
<td class="hs">{{ r.nationality }}</td>
|
||||
<td class="hs">{% if r.employer %}<a href="/companies/{{ r.employer_id }}">{{ r.employer }}</a>{% endif %}</td>
|
||||
<td class="hs">{{ r.province }}</td>
|
||||
<td class="hs">{{ r.employer }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -33,6 +44,8 @@
|
||||
</div>
|
||||
<p class="filter-empty" data-filter-empty hidden>No one in the list matches the filter.</p>
|
||||
</div>
|
||||
{% elif company %}
|
||||
<div class="card"><p class="empty-inline">No one in the list works for {{ company_name or "this company" }}. <a href="/people">Everyone</a></p></div>
|
||||
{% elif archived %}
|
||||
<div class="card"><p class="empty-inline">No one is archived.</p></div>
|
||||
{% else %}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
{% block main %}
|
||||
{% include "_person_head.html" %}
|
||||
<div class="cols">
|
||||
{% include "_deadlines.html" %}
|
||||
<section class="card" id="details">
|
||||
<header><h2>Personal details</h2><a class="btn sm" href="/people/{{ p.id }}/edit">Edit</a></header>
|
||||
<dl class="kv">
|
||||
@@ -13,7 +14,7 @@
|
||||
<dt>Place of birth</dt><dd>{% if p.place_of_birth %}{{ p.place_of_birth }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Nationality</dt><dd>{% if p.nationality %}{{ p.nationality_name }} <span class="muted mono">{{ p.nationality }}</span>{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Occupation</dt><dd>{% if p.occupation %}{{ p.occupation }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Employer</dt><dd>{% if p.employer %}{{ p.employer }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Employer</dt><dd>{% if p.employer %}<a href="/companies/{{ p.employer_id }}">{{ p.employer }}</a>{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Phone</dt><dd>{% if p.phone %}{{ p.phone }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
<dt>Email</dt><dd>{% if p.email %}{{ p.email }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||
{% if p.notes %}<dt>Notes</dt><dd class="pre">{{ p.notes }}</dd>{% endif %}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
{% include "_person_head.html" %}
|
||||
<p class="muted">Every view and change of this person's record, newest first: who, when and which fields changed, never their values. The log cannot be edited.</p>
|
||||
{% if items %}
|
||||
<div class="card flush">
|
||||
<div class="tblwrap">
|
||||
<table class="tbl" id="activity">
|
||||
<thead><tr><th>When</th><th>Who</th><th>Did</th><th>Record</th><th class="hs">Fields</th></tr></thead>
|
||||
<tbody>
|
||||
{% for e in items %}
|
||||
<tr><td class="mono">{{ e.at }}</td><td>{{ e.actor }}</td><td>{{ e.action }}</td><td class="muted">{{ e.what }}</td><td class="hs muted">{{ e.fields }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card"><p class="empty-inline">Nothing has happened yet.</p></div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -33,7 +33,7 @@
|
||||
{{ fm.text("place_of_birth", "Place of birth", f.place_of_birth, err=errors.place_of_birth) }}
|
||||
{{ fm.select("nationality", "Nationality", f.nationality, countries, err=errors.nationality) }}
|
||||
{{ fm.text("occupation", "Occupation", f.occupation, err=errors.occupation) }}
|
||||
{{ fm.text("employer", "Employer", f.employer, err=errors.employer, hint="The company named in the work permit.") }}
|
||||
{{ fm.select("employer", "Employer", f.employer, companies, err=errors.employer, blank="Not employed", hint="The company named in the work permit. Companies are kept under Companies.") }}
|
||||
{{ fm.text("phone", "Phone", f.phone, err=errors.phone, type="tel") }}
|
||||
{{ fm.text("email", "Email", f.email, err=errors.email, type="email") }}
|
||||
{{ fm.area("notes", "Notes", f.notes, err=errors.notes, rows=3, fcls="wide") }}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_fields.html" as fm %}
|
||||
{% block main %}
|
||||
{% if p %}
|
||||
{% include "_person_head.html" %}
|
||||
{% else %}
|
||||
<div class="crumbs"><a href="/companies">Companies</a></div>
|
||||
<div class="pagehead"><h1>{{ heading }}</h1></div>
|
||||
{% endif %}
|
||||
<form method="post" action="{{ action }}" class="form" id="record-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<section class="card">
|
||||
{% if p %}<header><h2>{{ heading }}</h2></header>{% endif %}
|
||||
{% if lead %}<p class="hint lead">{{ lead }}</p>{% endif %}
|
||||
<div class="grid">
|
||||
{%- for fl in fields %}
|
||||
{%- if fl.kind == "area" %}
|
||||
{{ fm.area(fl.name, fl.label, values[fl.name], err=errors[fl.name], hint=fl.hint, rows=3, fcls="wide") }}
|
||||
{%- elif fl.kind == "select" %}
|
||||
{{ fm.select(fl.name, fl.label, values[fl.name], fl.options, err=errors[fl.name], hint=fl.hint, blank=fl.blank, cls=("wide" if fl.wide else ""), req=fl.required) }}
|
||||
{%- else %}
|
||||
{{ fm.text(fl.name, fl.label, values[fl.name], err=errors[fl.name], hint=fl.hint, req=fl.required, type=fl.kind, list=fl.suggest, cls=("wide" if fl.wide else "")) }}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
</div>
|
||||
</section>
|
||||
<div class="formactions">
|
||||
<button type="submit" class="btn pri" id="save">{% if mode == "new" %}Add the {{ one }}{% else %}Save{% endif %}</button>
|
||||
<a class="btn ghost" href="{{ cancel }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
<datalist id="ports">{% for x in ports %}<option value="{{ x }}"></option>{% endfor %}</datalist>
|
||||
<datalist id="offices">{% for x in offices %}<option value="{{ x }}"></option>{% endfor %}</datalist>
|
||||
<datalist id="provinces">{% for x in provinces %}<option value="{{ x }}"></option>{% endfor %}</datalist>
|
||||
{% if mode == "edit" and p %}
|
||||
<form method="post" action="{{ action }}/delete" class="dangerzone" data-confirm="Delete this {{ one }} from the record?">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<button type="submit" class="btn sm danger">Delete this {{ one }}</button>
|
||||
<span class="muted small">For a record entered by mistake. The activity log keeps a note that it existed.</span>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,30 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
{% include "_person_head.html" %}
|
||||
<div class="cols">
|
||||
{% include "_deadlines.html" %}
|
||||
{% for s in sections %}
|
||||
<section class="card" id="{{ s.slug }}">
|
||||
<header><h2>{{ s.title }}</h2><a class="btn sm" href="/people/{{ p.id }}/{{ s.slug }}/new">+ New {{ s.one }}</a></header>
|
||||
{% for r in s.records %}
|
||||
<div class="item{% if r.old %} old{% endif %}">
|
||||
<div class="row">
|
||||
{%- for h in r.headline %}{% if not loop.first %}<span class="muted">·</span>{% endif %}{% if h.href %}<a class="strong" href="{{ h.href }}">{{ h.text }}</a>{% else %}<span class="strong">{{ h.text }}</span>{% endif %}{% endfor %}
|
||||
{%- if r.status %}<span class="chip {{ r.status.level }}">{{ r.status.label }}</span>{% endif %}
|
||||
</div>
|
||||
{% if r.items %}
|
||||
<dl class="kv">
|
||||
{%- for it in r.items %}
|
||||
<dt>{{ it.label }}</dt><dd{% if it.pre %} class="pre"{% elif it.mono %} class="mono"{% endif %}>{% if it.href %}<a href="{{ it.href }}">{{ it.value }}</a>{% else %}{{ it.value }}{% endif %}</dd>
|
||||
{%- endfor %}
|
||||
</dl>
|
||||
{% endif %}
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/{{ s.slug }}/{{ r.id }}/edit">Edit</a></div>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty-inline">No {{ s.one }} recorded yet.</p>
|
||||
{% endfor %}
|
||||
</section>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Companies and the selections that use them: the employer on the person
|
||||
//! form, employees added from the company page, the company filter.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::common::{id_from, local};
|
||||
|
||||
fn company_from(location: &str) -> i64 {
|
||||
location
|
||||
.trim_start_matches("/companies/")
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("no company id in {location:?}"))
|
||||
}
|
||||
|
||||
async fn audit_fields(pool: &PgPool, entity: &str, id: i64, action: &str) -> Vec<Vec<String>> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT fields FROM audit_log WHERE entity = $1 AND entity_id = $2 AND action = $3 \
|
||||
ORDER BY id",
|
||||
)
|
||||
.bind(entity)
|
||||
.bind(id)
|
||||
.bind(action)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn companies_are_checked_and_edited(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let r = app
|
||||
.post(
|
||||
"/companies",
|
||||
&[
|
||||
("name", "Test Works Co., Ltd."),
|
||||
("registration_no", "0999999000005"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(r.text().contains("check digit"), "{}", r.text());
|
||||
assert!(
|
||||
r.body.contains("value=\"Test Works Co., Ltd.\""),
|
||||
"typed values stay"
|
||||
);
|
||||
|
||||
let fields = [
|
||||
("name", "Test Works Co., Ltd."),
|
||||
("registration_no", "0-9999-99000-00-4"),
|
||||
("district", "Mueang Chiang Mai"),
|
||||
("province", "Chiang Mai"),
|
||||
("postal_code", "50000"),
|
||||
("signatory", "Malee Jaidee"),
|
||||
];
|
||||
let r = app.post("/companies", &fields).await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let id = company_from(r.location());
|
||||
let page = app.get(&format!("/companies/{id}")).await.text();
|
||||
assert!(page.contains("0999999000004"));
|
||||
assert!(
|
||||
page.contains("Mueang Chiang Mai, Chiang Mai 50000"),
|
||||
"{page}"
|
||||
);
|
||||
assert!(
|
||||
app.get("/companies")
|
||||
.await
|
||||
.text()
|
||||
.contains("Test Works Co., Ltd.")
|
||||
);
|
||||
|
||||
// the same number twice
|
||||
let r = app
|
||||
.post(
|
||||
"/companies",
|
||||
&[
|
||||
("name", "Other Co., Ltd."),
|
||||
("registration_no", "0999999000004"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(
|
||||
r.text()
|
||||
.contains("Another company has this registration number")
|
||||
);
|
||||
|
||||
let mut changed = fields.to_vec();
|
||||
changed.push(("phone", "+66 53 000 000"));
|
||||
let r = app.post(&format!("/companies/{id}"), &changed).await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
audit_fields(&pool, "company", id, "update").await,
|
||||
vec![vec!["phone"]]
|
||||
);
|
||||
// nothing changed: no entry
|
||||
app.post(&format!("/companies/{id}"), &changed).await;
|
||||
assert_eq!(audit_fields(&pool, "company", id, "update").await.len(), 1);
|
||||
let log = app.get("/activity").await.text();
|
||||
assert!(
|
||||
log.contains("Test Works Co., Ltd."),
|
||||
"the log links the company"
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_employer_is_chosen_from_the_companies(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let r = app
|
||||
.post("/companies", &[("name", "Test Works Co., Ltd.")])
|
||||
.await;
|
||||
let c = company_from(r.location());
|
||||
let cs = c.to_string();
|
||||
|
||||
let form = app.get("/people/new").await.body;
|
||||
assert!(form.contains(&format!(
|
||||
"<option value=\"{c}\">Test Works Co., Ltd.</option>"
|
||||
)));
|
||||
|
||||
let r = app
|
||||
.post(
|
||||
"/people",
|
||||
&[
|
||||
("surname", "Doe"),
|
||||
("first_name", "Jane"),
|
||||
("employer", &cs),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let jane = id_from(r.location());
|
||||
let page = app.get(&format!("/people/{jane}")).await.body;
|
||||
assert!(page.contains(&format!(
|
||||
"<a href=\"/companies/{c}\">Test Works Co., Ltd.</a>"
|
||||
)));
|
||||
|
||||
// an id that is no company
|
||||
let r = app
|
||||
.post(
|
||||
"/people",
|
||||
&[
|
||||
("surname", "Roe"),
|
||||
("first_name", "Rita"),
|
||||
("employer", "999999"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(r.text().contains("Choose a company from the list."));
|
||||
|
||||
// someone else, added from the company's page
|
||||
let r = app
|
||||
.post("/people", &[("surname", "Novak"), ("first_name", "Tomas")])
|
||||
.await;
|
||||
let tomas = id_from(r.location());
|
||||
let page = app.get(&format!("/companies/{c}")).await.text();
|
||||
assert!(page.contains("DOE, Jane Marie") || page.contains("DOE, Jane"));
|
||||
assert!(page.contains(&format!("<option value=\"{tomas}\">NOVAK, Tomas</option>")));
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/companies/{c}/employees"),
|
||||
&[("person", &tomas.to_string())],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
let employer: Option<i64> = sqlx::query_scalar("SELECT employer_id FROM people WHERE id = $1")
|
||||
.bind(tomas)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(employer, Some(c));
|
||||
assert_eq!(
|
||||
audit_fields(&pool, "person", tomas, "update").await,
|
||||
vec![vec!["employer"]]
|
||||
);
|
||||
|
||||
// the company filter on the people list
|
||||
let list = app.get(&format!("/people?company={c}")).await.text();
|
||||
assert!(list.contains("People at Test Works Co., Ltd."));
|
||||
assert!(list.contains("NOVAK, Tomas") && list.contains("DOE, Jane"));
|
||||
|
||||
let r = app
|
||||
.post(&format!("/companies/{c}/employees/{tomas}/remove"), &[])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
let list = app.get(&format!("/people?company={c}")).await.text();
|
||||
assert!(!list.contains("NOVAK, Tomas"));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn an_archived_company_is_no_longer_offered(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let r = app
|
||||
.post("/companies", &[("name", "Old Works Co., Ltd.")])
|
||||
.await;
|
||||
let c = company_from(r.location());
|
||||
let cs = c.to_string();
|
||||
let r = app
|
||||
.post(
|
||||
"/people",
|
||||
&[
|
||||
("surname", "Doe"),
|
||||
("first_name", "Jane"),
|
||||
("employer", &cs),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let jane = id_from(r.location());
|
||||
|
||||
app.post(&format!("/companies/{c}/archive"), &[]).await;
|
||||
assert!(
|
||||
app.get("/companies?archived=1")
|
||||
.await
|
||||
.text()
|
||||
.contains("Old Works")
|
||||
);
|
||||
assert!(
|
||||
!app.get("/people/new")
|
||||
.await
|
||||
.body
|
||||
.contains(&format!("value=\"{c}\""))
|
||||
);
|
||||
// a new person cannot choose it any more
|
||||
let r = app
|
||||
.post(
|
||||
"/people",
|
||||
&[
|
||||
("surname", "Roe"),
|
||||
("first_name", "Rita"),
|
||||
("employer", &cs),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
// the person who works there keeps it, and can be saved unchanged
|
||||
let edit = app.get(&format!("/people/{jane}/edit")).await.body;
|
||||
assert!(edit.contains(&format!(
|
||||
"<option value=\"{c}\" selected>Old Works Co., Ltd.</option>"
|
||||
)));
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{jane}"),
|
||||
&[
|
||||
("surname", "Doe"),
|
||||
("first_name", "Jane"),
|
||||
("employer", &cs),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
|
||||
app.post(&format!("/companies/{c}/restore"), &[]).await;
|
||||
assert!(
|
||||
app.get("/people/new")
|
||||
.await
|
||||
.body
|
||||
.contains(&format!("value=\"{c}\""))
|
||||
);
|
||||
let actions: Vec<String> =
|
||||
sqlx::query_scalar("SELECT action FROM audit_log WHERE entity = 'company' ORDER BY id")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(actions, vec!["create", "archive", "restore"]);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! The deadlines of the demo people, on the Deadlines page, the people list
|
||||
//! and the person's pages.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::common::local;
|
||||
|
||||
async fn person(pool: &PgPool, surname: &str) -> i64 {
|
||||
sqlx::query_scalar("SELECT id FROM people WHERE surname = $1")
|
||||
.bind(surname)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_demo_people_show_every_kind_of_deadline(pool: PgPool) {
|
||||
visa::seed::demo(&pool, visa::dates::today()).await.unwrap();
|
||||
let app = local(pool.clone());
|
||||
|
||||
let r = app.get("/").await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
let page = r.text();
|
||||
for expect in [
|
||||
// Tomas: the report was due 11 days ago, a week of grace is over
|
||||
"Late",
|
||||
// Jane: 60 days of visa exemption, 20 left
|
||||
"Extension of stay",
|
||||
"Under 6 months",
|
||||
"TM.30 for the address",
|
||||
// Erika: back from a trip 79 days ago
|
||||
"Window open",
|
||||
"Work permit expiry",
|
||||
// Sofia: still abroad with her visa
|
||||
"Visa valid for entry",
|
||||
] {
|
||||
assert!(page.contains(expect), "the dashboard lacks {expect:?}");
|
||||
}
|
||||
assert!(
|
||||
!page.contains("SAMPLE"),
|
||||
"archived people have no deadlines"
|
||||
);
|
||||
// the most urgent first: Tomas's late report
|
||||
let late = page.find("Late").unwrap();
|
||||
let open = page.find("Window open").unwrap();
|
||||
assert!(late < open);
|
||||
|
||||
let tomas = person(&pool, "Novak").await;
|
||||
let p = app.get(&format!("/people/{tomas}")).await.text();
|
||||
assert!(
|
||||
p.contains("Basis: extension of stay for marriage to a Thai national."),
|
||||
"{p}"
|
||||
);
|
||||
assert!(p.contains("Report in person and pay the 2,000 THB fine"));
|
||||
let erika = person(&pool, "Mustermann").await;
|
||||
let s = app.get(&format!("/people/{erika}/stay")).await.text();
|
||||
assert!(
|
||||
s.contains("Basis: extension of stay for work, kept by a re-entry permit."),
|
||||
"{s}"
|
||||
);
|
||||
assert!(s.contains("Online until"), "Erika may still report online");
|
||||
assert!(
|
||||
s.contains("Demo Engineering Co., Ltd."),
|
||||
"the work permit names the employer"
|
||||
);
|
||||
|
||||
// the people list shows each person's next deadline
|
||||
let list = app.get("/people").await.text();
|
||||
assert!(list.contains("90-day report,"));
|
||||
// the company filter on the dashboard
|
||||
let company: i64 =
|
||||
sqlx::query_scalar("SELECT id FROM companies WHERE name = 'Demo Accounting Partnership'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let only = app.get(&format!("/?company={company}")).await.text();
|
||||
assert!(only.contains("NOVAK, Tomas") && !only.contains("MUSTERMANN"));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn a_new_arrival_brings_its_deadlines(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let r = app
|
||||
.post("/people", &[("surname", "Doe"), ("first_name", "Jane")])
|
||||
.await;
|
||||
let id = crate::common::id_from(r.location());
|
||||
let page = app.get(&format!("/people/{id}")).await.text();
|
||||
assert!(page.contains("No arrival is recorded yet."));
|
||||
|
||||
let today = visa::dates::today();
|
||||
let arrived = (today - chrono::TimeDelta::days(30)).to_string();
|
||||
let until = (today + chrono::TimeDelta::days(150)).to_string();
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{id}/arrivals"),
|
||||
&[
|
||||
("arrived_on", arrived.as_str()),
|
||||
("admission", "visa"),
|
||||
("permitted_until", until.as_str()),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
|
||||
let page = app.get(&format!("/people/{id}")).await.text();
|
||||
assert!(page.contains("In Thailand since"));
|
||||
assert!(page.contains("90-day report"));
|
||||
assert!(page.contains("Calculated as the arrival plus 89 days"));
|
||||
assert!(page.contains("No current address is recorded."));
|
||||
let due = visa::dates::fmt_date(today + chrono::TimeDelta::days(59));
|
||||
assert!(page.contains(&due), "the report is due on day 90: {due}");
|
||||
}
|
||||
@@ -4,8 +4,11 @@
|
||||
|
||||
mod auth;
|
||||
mod common;
|
||||
mod companies;
|
||||
mod deadlines;
|
||||
mod pages;
|
||||
mod people;
|
||||
mod records;
|
||||
|
||||
#[test]
|
||||
fn every_test_file_is_a_module() {
|
||||
|
||||
+70
-4
@@ -31,7 +31,69 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let pages = [
|
||||
let company: i64 =
|
||||
sqlx::query_scalar("SELECT id FROM companies WHERE name = 'Demo Engineering Co., Ltd.'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let arrival: i64 = sqlx::query_scalar(
|
||||
"SELECT id FROM arrivals WHERE person_id = $1 ORDER BY arrived_on DESC LIMIT 1",
|
||||
)
|
||||
.bind(erika)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let permit: i64 = sqlx::query_scalar("SELECT id FROM work_permits WHERE person_id = $1")
|
||||
.bind(erika)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut pages = vec![
|
||||
("/".to_string(), "90-day report".to_string()),
|
||||
("/?all=1".to_string(), "Only the next 90 days".to_string()),
|
||||
(
|
||||
format!("/?company={company}"),
|
||||
"MUSTERMANN, Erika".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/people/{erika}/stay"),
|
||||
"Arrivals and departures".to_string(),
|
||||
),
|
||||
(format!("/people/{erika}/activity"), "seed".to_string()),
|
||||
(
|
||||
format!("/people/{erika}/arrivals/{arrival}/edit"),
|
||||
"Edit the arrival".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/people/{erika}/work-permits/{permit}/edit"),
|
||||
"WP-DEMO-0001".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/people?company={company}"),
|
||||
"People at Demo Engineering Co., Ltd.".to_string(),
|
||||
),
|
||||
(
|
||||
"/companies".to_string(),
|
||||
"Demo Accounting Partnership".to_string(),
|
||||
),
|
||||
("/companies/new".to_string(), "New company".to_string()),
|
||||
(
|
||||
format!("/companies/{company}"),
|
||||
"People employed".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/companies/{company}/edit"),
|
||||
"0999999000004".to_string(),
|
||||
),
|
||||
];
|
||||
for kind in visa::records::STAY {
|
||||
pages.push((
|
||||
format!("/people/{erika}/{}/new", kind.slug),
|
||||
format!("New {}", kind.one),
|
||||
));
|
||||
}
|
||||
let older = [
|
||||
("/people".to_string(), "MUSTERMANN, Erika"),
|
||||
("/people?archived=1".to_string(), "SAMPLE, Oliver"),
|
||||
("/people/new".to_string(), "Read the passport"),
|
||||
@@ -53,10 +115,14 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
||||
("/activity".to_string(), "seed"),
|
||||
(format!("/activity?person={erika}"), "MUSTERMANN, Erika"),
|
||||
];
|
||||
pages.extend(older.into_iter().map(|(p, e)| (p, e.to_string())));
|
||||
for (path, expect) in &pages {
|
||||
let r = app.get(path).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{path}: {}", r.body);
|
||||
assert!(r.text().contains(expect), "{path} lacks {expect:?}");
|
||||
assert!(
|
||||
r.text().contains(expect.as_str()),
|
||||
"{path} lacks {expect:?}"
|
||||
);
|
||||
assert_unique_ids(&r.body, path);
|
||||
assert_eq!(r.headers["cache-control"], "no-store", "{path}");
|
||||
}
|
||||
@@ -103,8 +169,8 @@ async fn open_paths_headers_and_not_found(pool: PgPool) {
|
||||
);
|
||||
|
||||
let r = app.get("/").await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(r.location(), "/people");
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert!(r.text().contains("No people yet"));
|
||||
|
||||
let r = app.get("/people/999999").await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! The records of a stay through their forms: every kind is added, edited
|
||||
//! and deleted, with the audit log; references stay within the person.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::common::{id_from, local};
|
||||
|
||||
async fn last_created(pool: &PgPool, person: i64) -> (i64, String) {
|
||||
sqlx::query_as(
|
||||
"SELECT entity_id, entity FROM audit_log WHERE person_id = $1 AND action = 'create' \
|
||||
ORDER BY id DESC LIMIT 1",
|
||||
)
|
||||
.bind(person)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A kind's slug and audit entity, the fields of a new record, and a field
|
||||
/// to change: its name, the value typed and the value shown.
|
||||
type Case<'a> = (
|
||||
&'a str,
|
||||
&'a str,
|
||||
Vec<(&'a str, &'a str)>,
|
||||
(&'a str, &'a str, &'a str),
|
||||
);
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn every_kind_is_added_edited_and_deleted(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let r = app
|
||||
.post("/companies", &[("name", "Test Works Co., Ltd.")])
|
||||
.await;
|
||||
let company = r.location().trim_start_matches("/companies/").to_string();
|
||||
let r = app
|
||||
.post("/people", &[("surname", "Doe"), ("first_name", "Jane")])
|
||||
.await;
|
||||
let id = id_from(r.location());
|
||||
|
||||
// (slug, entity, the fields of a new record, a field to change)
|
||||
let cases: Vec<Case> = vec![
|
||||
(
|
||||
"visas",
|
||||
"visa",
|
||||
vec![("category", "non-b"), ("valid_until", "2027-01-01")],
|
||||
("number", "v 123", "V123"),
|
||||
),
|
||||
(
|
||||
"arrivals",
|
||||
"arrival",
|
||||
vec![
|
||||
("arrived_on", "2026-09-01"),
|
||||
("admission", "exempt"),
|
||||
("permitted_until", "2026-10-30"),
|
||||
],
|
||||
("tdac_no", "tdac 77", "TDAC77"),
|
||||
),
|
||||
(
|
||||
"extensions",
|
||||
"extension",
|
||||
vec![
|
||||
("applied_on", "2026-10-20"),
|
||||
("basis", "tourism"),
|
||||
("decision", "approved"),
|
||||
("permitted_until", "2026-11-29"),
|
||||
],
|
||||
("fee_thb", "1,900", "1,900 THB"),
|
||||
),
|
||||
(
|
||||
"reports",
|
||||
"report",
|
||||
vec![("reported_on", "2026-09-10"), ("method", "online")],
|
||||
("next_due_on", "2026-12-09", "Dec 9, 2026"),
|
||||
),
|
||||
(
|
||||
"reentry-permits",
|
||||
"reentry-permit",
|
||||
vec![
|
||||
("kind", "single"),
|
||||
("issued_on", "2026-09-10"),
|
||||
("valid_until", "2026-10-30"),
|
||||
],
|
||||
(
|
||||
"office",
|
||||
"Chiang Mai Immigration Office",
|
||||
"Chiang Mai Immigration Office",
|
||||
),
|
||||
),
|
||||
(
|
||||
"work-permits",
|
||||
"work-permit",
|
||||
vec![
|
||||
("company_id", company.as_str()),
|
||||
("valid_until", "2027-09-01"),
|
||||
],
|
||||
("position", "Designer", "Designer"),
|
||||
),
|
||||
];
|
||||
for (slug, entity, fields, (field, value, shown)) in cases {
|
||||
let r = app.post(&format!("/people/{id}/{slug}"), &fields).await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{slug}: {}", r.text());
|
||||
assert_eq!(r.location(), format!("/people/{id}/stay#{slug}"));
|
||||
let (rid, e) = last_created(&pool, id).await;
|
||||
assert_eq!(e, entity);
|
||||
|
||||
let edit = app.get(&format!("/people/{id}/{slug}/{rid}/edit")).await;
|
||||
assert_eq!(edit.status, StatusCode::OK, "{slug}");
|
||||
let mut changed = fields.clone();
|
||||
changed.push((field, value));
|
||||
let r = app
|
||||
.post(&format!("/people/{id}/{slug}/{rid}"), &changed)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{slug}: {}", r.text());
|
||||
let logged: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT fields FROM audit_log WHERE entity = $1 AND entity_id = $2 \
|
||||
AND action = 'update'",
|
||||
)
|
||||
.bind(entity)
|
||||
.bind(rid)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(logged, vec![field.to_string()], "{slug}");
|
||||
let page = app.get(&format!("/people/{id}/stay")).await.text();
|
||||
assert!(page.contains(shown), "{slug}: {shown} not shown");
|
||||
|
||||
// another person's path finds nothing
|
||||
assert_eq!(
|
||||
app.get(&format!("/people/{}/{slug}/{rid}/edit", id + 1000))
|
||||
.await
|
||||
.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
let r = app
|
||||
.post(&format!("/people/{id}/{slug}/{rid}/delete"), &[])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{slug}");
|
||||
}
|
||||
let page = app.get(&format!("/people/{id}/stay")).await.text();
|
||||
assert!(page.contains("No arrival recorded yet."));
|
||||
let deleted: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_log WHERE action = 'delete'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(deleted, 6);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn forms_say_what_is_missing_or_wrong(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let r = app
|
||||
.post("/people", &[("surname", "Doe"), ("first_name", "Jane")])
|
||||
.await;
|
||||
let id = id_from(r.location());
|
||||
let r = app.post(&format!("/people/{id}/arrivals"), &[]).await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let t = r.text();
|
||||
assert!(
|
||||
t.contains("Enter the arrival date.") && t.contains("Enter the date in the arrival stamp.")
|
||||
);
|
||||
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{id}/arrivals"),
|
||||
&[
|
||||
("arrived_on", "2026-09-01"),
|
||||
("admission", "visa"),
|
||||
("permitted_until", "2026-08-01"),
|
||||
("departed_on", "2026-08-15"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let t = r.text();
|
||||
assert!(t.contains("The permitted stay cannot end before the arrival."));
|
||||
assert!(t.contains("The departure cannot come before the arrival."));
|
||||
assert!(r.body.contains("value=\"2026-09-01\""), "typed values stay");
|
||||
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{id}/extensions"),
|
||||
&[
|
||||
("applied_on", "2026-10-20"),
|
||||
("basis", "work"),
|
||||
("decision", "consideration"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(r.text().contains("Enter the date in the stamp."));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn passports_and_visas_are_chosen_from_the_persons_own(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let mut people = Vec::new();
|
||||
for (surname, number) in [("Doe", "Z00000042"), ("Roe", "Z00000043")] {
|
||||
let r = app
|
||||
.post("/people", &[("surname", surname), ("first_name", "Test")])
|
||||
.await;
|
||||
let id = id_from(r.location());
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{id}/passports"),
|
||||
&[
|
||||
("number", number),
|
||||
("issuing_country", "USA"),
|
||||
("expires_on", "2031-01-01"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
|
||||
let pp: i64 = sqlx::query_scalar("SELECT id FROM passports WHERE number = $1")
|
||||
.bind(number)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
people.push((id, pp));
|
||||
}
|
||||
let (doe, doe_pp) = people[0];
|
||||
let (_, roe_pp) = people[1];
|
||||
|
||||
// the new arrival's form offers Doe's passport, already chosen
|
||||
let form = app.get(&format!("/people/{doe}/arrivals/new")).await.body;
|
||||
assert!(form.contains(&format!(
|
||||
"<option value=\"{doe_pp}\" selected>Z00000042 (United States)</option>"
|
||||
)));
|
||||
assert!(!form.contains("Z00000043"));
|
||||
|
||||
let arrival = |pp: i64| {
|
||||
vec![
|
||||
("arrived_on", "2026-09-01".to_string()),
|
||||
("admission", "exempt".to_string()),
|
||||
("permitted_until", "2026-10-30".to_string()),
|
||||
("passport_id", pp.to_string()),
|
||||
]
|
||||
};
|
||||
let other = arrival(roe_pp);
|
||||
let other: Vec<(&str, &str)> = other.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
let r = app.post(&format!("/people/{doe}/arrivals"), &other).await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(r.text().contains("Choose from the list."));
|
||||
|
||||
let own = arrival(doe_pp);
|
||||
let own: Vec<(&str, &str)> = own.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
let r = app.post(&format!("/people/{doe}/arrivals"), &own).await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
|
||||
|
||||
// deleting the passport leaves the arrival without one
|
||||
let r = app
|
||||
.post(&format!("/people/{doe}/passports/{doe_pp}/delete"), &[])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
let left: Option<i64> =
|
||||
sqlx::query_scalar("SELECT passport_id FROM arrivals WHERE person_id = $1")
|
||||
.bind(doe)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(left, None);
|
||||
}
|
||||
Reference in new issue
Block a user