Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43ed75d81b | ||
|
|
a6ebdfc89c |
No files matched your search
@@ -81,6 +81,9 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running.
|
|||||||
| `src/papers/` | the Immigration Bureau's forms filled in (`layout.rs` is generated by `scripts/gen_layout.py`) |
|
| `src/papers/` | the Immigration Bureau's forms filled in (`layout.rs` is generated by `scripts/gen_layout.py`) |
|
||||||
| `src/pack/` | the extension pack: its rules as a pure function (`assess`), and the pack as one PDF (`pdf.rs`) |
|
| `src/pack/` | the extension pack: its rules as a pure function (`assess`), and the pack as one PDF (`pdf.rs`) |
|
||||||
| `.gitea/scripts/` | CI: toolchain, gitleaks, and the release (`release.py` + `test_release.py`, `build-release.sh`, `sign-release.sh`; key `release/allowed-signers`) |
|
| `.gitea/scripts/` | CI: toolchain, gitleaks, and the release (`release.py` + `test_release.py`, `build-release.sh`, `sign-release.sh`; key `release/allowed-signers`) |
|
||||||
|
| `src/links.rs` | the client link: made, looked up by the SHA-256 of its token, its state, closed, and what the client changed (from the audit log, actor `link <id>`) |
|
||||||
|
| `src/web/links.rs` | the staff's side: the person page's card, making a link (also "+ New client"), the page that shows it once with its QR code, closing it |
|
||||||
|
| `src/web/client.rs` | the client's pages at `/c/<token>`, open without a login: each checks its link and the link's own form token |
|
||||||
| `static/mrz-photo.js` | the passport photo reader in the browser (camera view, Tesseract.js from `static/vendor/tesseract/`, see its README.txt); the server's half is `mrz::from_ocr` |
|
| `static/mrz-photo.js` | the passport photo reader in the browser (camera view, Tesseract.js from `static/vendor/tesseract/`, see its README.txt); the server's half is `mrz::from_ocr` |
|
||||||
| `src/web/` | routes, the login gate, pages |
|
| `src/web/` | routes, the login gate, pages |
|
||||||
| `templates/` | minijinja templates, compiled in by `build.rs` |
|
| `templates/` | minijinja templates, compiled in by `build.rs` |
|
||||||
|
|||||||
Generated
+7
@@ -1467,6 +1467,12 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "qrcode"
|
||||||
|
version = "0.14.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quick-error"
|
name = "quick-error"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
@@ -2607,6 +2613,7 @@ dependencies = [
|
|||||||
"http-body-util",
|
"http-body-util",
|
||||||
"krilla",
|
"krilla",
|
||||||
"minijinja",
|
"minijinja",
|
||||||
|
"qrcode",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"ring",
|
"ring",
|
||||||
"rustybuzz",
|
"rustybuzz",
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ form_urlencoded = "1"
|
|||||||
# uploaded scans and photos in the extension pack.
|
# uploaded scans and photos in the extension pack.
|
||||||
krilla = { version = "0.8", default-features = false, features = ["pdf", "raster-images", "simple-text"] }
|
krilla = { version = "0.8", default-features = false, features = ["pdf", "raster-images", "simple-text"] }
|
||||||
minijinja = "2"
|
minijinja = "2"
|
||||||
|
# The client link as a QR code to show on a phone (an inline SVG).
|
||||||
|
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
|
||||||
# The login service's certificate is checked against the system's CA bundle
|
# The login service's certificate is checked against the system's CA bundle
|
||||||
# (native roots), so a NixOS VM test can bring its own CA.
|
# (native roots), so a NixOS VM test can bring its own CA.
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "json"] }
|
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "json"] }
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ 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
|
that names the fields changed but never their values, as Thailand's Personal
|
||||||
Data Protection Act (PDPA) asks.
|
Data Protection Act (PDPA) asks.
|
||||||
|
|
||||||
## What works now (phases 1 to 6)
|
## What works now (phases 1 to 7)
|
||||||
|
|
||||||
- The Deadlines page: every person's coming deadlines, the most urgent
|
- 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
|
first, with a filter by employer. It covers the 90-day report with its
|
||||||
@@ -28,9 +28,19 @@ Data Protection Act (PDPA) asks.
|
|||||||
- The passport's zone from a photo: on the new person and new passport
|
- The passport's zone from a photo: on the new person and new passport
|
||||||
forms, "Take a photo" opens a camera view with a frame for the photo page
|
forms, "Take a photo" opens a camera view with a frame for the photo page
|
||||||
and a band for the two lines, says when there is glare or too little
|
and a band for the two lines, says when there is glare or too little
|
||||||
light, and takes the photo once the lines look readable; "Choose a
|
light, and takes the photo once the lines have looked readable and held
|
||||||
|
still for 2.5 seconds; "Choose a
|
||||||
picture" reads any image. The reading happens in the browser, so the
|
picture" reads any image. The reading happens in the browser, so the
|
||||||
photo stays on the device, and the check digits catch a misread.
|
photo stays on the device, and the check digits catch a misread.
|
||||||
|
- The client link: on a person's page, or with "+ New client" for a new
|
||||||
|
record, staff make a link to give the client by email, chat or as a QR
|
||||||
|
code. Without a login, from their phone, the client fills in their
|
||||||
|
personal details, the passport (from a photo of the photo page), the
|
||||||
|
address in Thailand and contact, uploads scans, and presses Send. Each
|
||||||
|
part goes straight into the record, logged as the link's; the person's
|
||||||
|
page shows what the client changed, for staff to check. The app keeps
|
||||||
|
only a hash of the link, which works for 14 days, until Send, or until
|
||||||
|
staff close it.
|
||||||
- A list of people with a filter and each person's next deadline, and a
|
- A list of people with a filter and each person's next deadline, and a
|
||||||
page per person with six tabs: the overview with personal details,
|
page per person with six tabs: the overview with personal details,
|
||||||
passports and addresses; "Visa and stay" with arrivals and departures,
|
passports and addresses; "Visa and stay" with arrivals and departures,
|
||||||
|
|||||||
+37
-22
@@ -5,8 +5,10 @@
|
|||||||
> of the documents from a directory on cnx01 into a bucket of cnx01's Garage
|
> of the documents from a directory on cnx01 into a bucket of cnx01's Garage
|
||||||
> was built (task 4.8) and checked in the fleet (task 4.9, cnx-network-clan
|
> was built (task 4.8) and checked in the fleet (task 4.9, cnx-network-clan
|
||||||
> PR #150); the documents move once that PR is deployed. Phase 6, the Non-B
|
> PR #150); the documents move once that PR is deployed. Phase 6, the Non-B
|
||||||
> extension pack, was built on November 20, 2026. **Resume here: phase 7, the
|
> extension pack, and phase 7, the client link, were built on November 20,
|
||||||
> client link.**
|
> 2026, the same day every push to main became a signed release that cnx01
|
||||||
|
> installs by itself. **Resume here: phase 8, reminders; task 7.6, the
|
||||||
|
> client's signed agreement, waits for B4L's text.**
|
||||||
|
|
||||||
visa.buildfor.life keeps the immigration records of the foreigners that B4L
|
visa.buildfor.life keeps the immigration records of the foreigners that B4L
|
||||||
looks after: their passports, addresses in Thailand, arrivals with the Thailand
|
looks after: their passports, addresses in Thailand, arrivals with the Thailand
|
||||||
@@ -228,7 +230,7 @@ dark at desktop and phone width, a commit and a push.
|
|||||||
| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) in a bucket of cnx01's Garage (first on the dataset `zroot/visa`) with a key var, viewing and download, all audited; the office's GPS position and photo | live Nov 18, 2026; Garage built Nov 19, 2026 |
|
| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) in a bucket of cnx01's Garage (first on the dataset `zroot/visa`) with a key var, viewing and download, all audited; the office's GPS position and photo | live Nov 18, 2026; Garage built Nov 19, 2026 |
|
||||||
| 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment (STM.9), STM.11, STM.1, TM.47 and TM.8 as PDF | built Nov 18, 2026 |
|
| 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment (STM.9), STM.11, STM.1, TM.47 and TM.8 as PDF | built Nov 18, 2026 |
|
||||||
| 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | built Nov 20, 2026 |
|
| 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | built Nov 20, 2026 |
|
||||||
| 7 | The client link: a client fills in their own record on a phone, the MRZ read from a photo; later the signed agreement | planned Nov 20, 2026 |
|
| 7 | The client link: a client fills in their own record on a phone, the MRZ read from a photo; later the signed agreement | built Nov 20, 2026; 7.6 waits for the text |
|
||||||
| 8 | Reminders by Matrix room message and by email | |
|
| 8 | Reminders by Matrix room message and by email | |
|
||||||
| later | Thai user interface, agency cases and fees, other visa categories' packs | |
|
| later | Thai user interface, agency cases and fees, other visa categories' packs | |
|
||||||
|
|
||||||
@@ -436,26 +438,36 @@ one `Kind`.
|
|||||||
|
|
||||||
Planned on November 20, 2026, from Alex's answers (decisions table).
|
Planned on November 20, 2026, from Alex's answers (decisions table).
|
||||||
|
|
||||||
- [ ] 7.1 Links: staff make a link on a person's page, and "+ New client" in
|
- [x] 7.1 Links: staff make a link on a person's page, and "+ New client" in
|
||||||
the people list makes an empty record with its link. The app keeps only
|
the people list makes a record with only the name staff know (and an
|
||||||
the SHA-256 of the link's token, as with sessions: it shows the link
|
email address, if any) with its link. The app keeps only the SHA-256 of
|
||||||
once, to copy or as a QR code to show on a phone, and a new link closes
|
the link's token, as with sessions: it shows the link once, to copy, to
|
||||||
the person's earlier one. The person's page lists the links with their
|
email or as a QR code to show on a phone, and a new link closes the
|
||||||
state (open, used, sent, closed, expired), and staff close one.
|
person's earlier one. The person's page lists the newest three links
|
||||||
- [ ] 7.2 The client's pages at `/c/<token>`, the one part of the app open
|
with their state (open, opened, sent, closed, expired), and staff close
|
||||||
|
one (`src/links.rs`, `src/web/links.rs`, `migrations/0006`).
|
||||||
|
- [x] 7.2 The client's pages at `/c/<token>`, the one part of the app open
|
||||||
without a login: about you, the passport, the address in Thailand,
|
without a login: about you, the passport, the address in Thailand,
|
||||||
contact, the documents, and Send. Plain English, phone first, each part
|
contact, the documents, and Send. Plain English, phone first, each part
|
||||||
saved on its own; the link's own form token and the same-site check;
|
saved on its own; the link's own form token and the same-site check;
|
||||||
nothing about anyone else. After Send, or 14 days, or once staff close
|
nothing about anyone else (`src/web/client.rs`, `templates/client*.html`
|
||||||
it, the link shows only that it is closed.
|
in a frame of their own). The parts show what the record holds, so the
|
||||||
|
client corrects rather than retypes. A passport from a zone fills in
|
||||||
|
the personal details still empty. A passport with the same number is
|
||||||
|
changed; an address unlike the current one is added beside it, so the
|
||||||
|
current one and its TM.30 receipt stay until staff check; a second
|
||||||
|
save changes what the link added. After Send, or 14 days, or once staff
|
||||||
|
close it, the link shows only that it is closed.
|
||||||
- [x] 7.3 The passport from a photo, built ahead on November 20, 2026 on
|
- [x] 7.3 The passport from a photo, built ahead on November 20, 2026 on
|
||||||
the staff's new person and new passport forms (the client's pages
|
the staff's new person and new passport forms (the client's pages
|
||||||
reuse `templates/_mrz_photo.html`). "Take a photo" opens a camera view:
|
reuse `templates/_mrz_photo.html`). "Take a photo" opens a camera view:
|
||||||
a frame of the photo page's shape and a band for the two lines, with
|
a frame of the photo page's shape and a band for the two lines, with
|
||||||
a hint that says when it is too dark, when there is glare on the
|
a hint that says when it is too dark, when there is glare on the
|
||||||
lines, when no lines are in the band or the picture is not sharp, and
|
lines, when no lines are in the band, the picture is not sharp or
|
||||||
that takes the photo by itself once the band has looked readable for
|
still moves, and that takes the photo by itself once the band has
|
||||||
a second. "Choose a picture" reads any image (EXIF orientation, the
|
looked readable and stood still for 2.5 seconds (never in the first
|
||||||
|
1.5 seconds; a second was too quick on a phone, Nov 20), counting
|
||||||
|
down in the hint; "Take the photo" takes it at once. "Choose a picture" reads any image (EXIF orientation, the
|
||||||
four quarter turns, a tilt either way). Reading happens in the browser
|
four quarter turns, a tilt either way). Reading happens in the browser
|
||||||
(`static/mrz-photo.js`): Tesseract.js 7 with Doubango's MRZ model, all
|
(`static/mrz-photo.js`): Tesseract.js 7 with Doubango's MRZ model, all
|
||||||
served by the app (`static/vendor/tesseract/README.txt`, about 6 MB,
|
served by the app (`static/vendor/tesseract/README.txt`, about 6 MB,
|
||||||
@@ -470,13 +482,16 @@ Planned on November 20, 2026, from Alex's answers (decisions table).
|
|||||||
specimen pages: every readable zone read, except under a hard shadow
|
specimen pages: every readable zone read, except under a hard shadow
|
||||||
across the lines; the specimens that failed have their zone blanked
|
across the lines; the specimens that failed have their zone blanked
|
||||||
out.
|
out.
|
||||||
- [ ] 7.4 Uploads from the client into the encrypted store: the passport's
|
- [x] 7.4 Uploads from the client into the encrypted store: the passport's
|
||||||
photo page, the photo, the TDAC and other scans, each tied to its record
|
photo page, the photo, the visa, the arrival stamp, the TDAC, the work
|
||||||
where there is one.
|
permit and other scans, each tied to the person's newest record of its
|
||||||
- [ ] 7.5 Audit: every view and change through a link is logged with the
|
kind where there is one. The client sees the names of what they
|
||||||
actor `link <id>` and the names of the fields; making, using, sending
|
uploaded through the link, never the files.
|
||||||
and closing a link too. The person's page says when the client sent the
|
- [x] 7.5 Audit: every view and change through a link is logged with the
|
||||||
form and links to what changed.
|
actor `link <id>` and the names of the fields; making, sending and
|
||||||
|
closing a link too (actions `send` and `close`, entity `link`). The
|
||||||
|
person's page says when the client opened and sent the form and links
|
||||||
|
to each record changed, with the fields.
|
||||||
- [ ] 7.6 Later: the agreement. A box where the client signs, drawn on the
|
- [ ] 7.6 Later: the agreement. A box where the client signs, drawn on the
|
||||||
screen, the agreement with B4L to keep and work with their data; the
|
screen, the agreement with B4L to keep and work with their data; the
|
||||||
signed agreement is kept as an encrypted document (a PDF with the
|
signed agreement is kept as an encrypted document (a PDF with the
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- visa.buildfor.life, phase 7: the client link (docs/PLAN.md "Phase 7").
|
||||||
|
--
|
||||||
|
-- Staff make a link for a person; the client fills in their details through
|
||||||
|
-- it without a login. The table keeps the SHA-256 of the link's token, never
|
||||||
|
-- the token, as `sessions` does: a dump of it opens no link. A link is open
|
||||||
|
-- until it expires, the client presses Send, or staff close it; a new link
|
||||||
|
-- closes the person's earlier one.
|
||||||
|
|
||||||
|
CREATE TABLE client_links (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
person_id BIGINT NOT NULL REFERENCES people (id),
|
||||||
|
token_hash BYTEA NOT NULL UNIQUE,
|
||||||
|
-- the link's own form token
|
||||||
|
csrf TEXT NOT NULL,
|
||||||
|
created_by TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
first_used_at TIMESTAMPTZ,
|
||||||
|
last_used_at TIMESTAMPTZ,
|
||||||
|
sent_at TIMESTAMPTZ,
|
||||||
|
closed_at TIMESTAMPTZ,
|
||||||
|
-- who closed it: a staff login, or 'client' when the client sent it
|
||||||
|
closed_by TEXT NOT NULL DEFAULT '',
|
||||||
|
CHECK (expires_at > created_at),
|
||||||
|
CHECK (sent_at IS NULL OR closed_at IS NOT NULL)
|
||||||
|
);
|
||||||
|
CREATE INDEX client_links_person ON client_links (person_id, id);
|
||||||
|
|
||||||
|
-- The link in the audit log: made, sent and closed; the client's views and
|
||||||
|
-- changes carry the actor `link <id>`.
|
||||||
|
ALTER TABLE audit_log DROP CONSTRAINT audit_log_action_check;
|
||||||
|
ALTER TABLE audit_log ADD CONSTRAINT audit_log_action_check CHECK (
|
||||||
|
action IN (
|
||||||
|
'view', 'create', 'update', 'delete', 'archive', 'restore', 'sign-in', 'sign-out',
|
||||||
|
'download', 'send', 'close'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
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', 'document', 'form', 'link'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
CREATE INDEX audit_log_actor ON audit_log (actor, id);
|
||||||
@@ -21,6 +21,10 @@ pub enum Action {
|
|||||||
SignOut,
|
SignOut,
|
||||||
/// A document's file saved to the browser's disk (opening it is a view).
|
/// A document's file saved to the browser's disk (opening it is a view).
|
||||||
Download,
|
Download,
|
||||||
|
/// The client sent what they filled in through their link.
|
||||||
|
Send,
|
||||||
|
/// Staff closed a client's link.
|
||||||
|
Close,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Action {
|
impl Action {
|
||||||
@@ -35,6 +39,8 @@ impl Action {
|
|||||||
Action::SignIn => "sign-in",
|
Action::SignIn => "sign-in",
|
||||||
Action::SignOut => "sign-out",
|
Action::SignOut => "sign-out",
|
||||||
Action::Download => "download",
|
Action::Download => "download",
|
||||||
|
Action::Send => "send",
|
||||||
|
Action::Close => "close",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -55,6 +61,8 @@ pub enum Entity {
|
|||||||
Document,
|
Document,
|
||||||
/// A filled-in form, opened or downloaded; `fields` names the forms.
|
/// A filled-in form, opened or downloaded; `fields` names the forms.
|
||||||
Form,
|
Form,
|
||||||
|
/// A client link (`links.rs`).
|
||||||
|
Link,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Entity {
|
impl Entity {
|
||||||
@@ -73,6 +81,7 @@ impl Entity {
|
|||||||
Entity::WorkPermit => "work-permit",
|
Entity::WorkPermit => "work-permit",
|
||||||
Entity::Document => "document",
|
Entity::Document => "document",
|
||||||
Entity::Form => "form",
|
Entity::Form => "form",
|
||||||
|
Entity::Link => "link",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -162,6 +171,7 @@ fn noun(entity: &str) -> &str {
|
|||||||
"reentry-permit" => "re-entry permit",
|
"reentry-permit" => "re-entry permit",
|
||||||
"work-permit" => "work permit",
|
"work-permit" => "work permit",
|
||||||
"report" => "90-day report",
|
"report" => "90-day report",
|
||||||
|
"link" => "client link",
|
||||||
other => other,
|
other => other,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ pub mod embedded;
|
|||||||
pub mod files;
|
pub mod files;
|
||||||
pub mod forms;
|
pub mod forms;
|
||||||
pub mod gps;
|
pub mod gps;
|
||||||
|
pub mod links;
|
||||||
pub mod mrz;
|
pub mod mrz;
|
||||||
pub mod oidc;
|
pub mod oidc;
|
||||||
pub mod pack;
|
pub mod pack;
|
||||||
|
|||||||
+308
@@ -0,0 +1,308 @@
|
|||||||
|
//! The client link (phase 7): staff make a link for a person, and the
|
||||||
|
//! client fills in their details through it without a login. The table
|
||||||
|
//! keeps the SHA-256 of the link's token, never the token, as `sessions`
|
||||||
|
//! does; the token is shown once, when the link is made. A link is open
|
||||||
|
//! for `LIFETIME`, until the client presses Send, or until staff close it;
|
||||||
|
//! a new link closes the person's earlier one. Everything the client does
|
||||||
|
//! through it is in the audit log with the actor `link <id>`.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::{PgConnection, PgPool};
|
||||||
|
|
||||||
|
use crate::dates;
|
||||||
|
use crate::oidc::random_token;
|
||||||
|
|
||||||
|
/// How long a link stays open.
|
||||||
|
pub const LIFETIME: Duration = Duration::from_secs(14 * 24 * 3600);
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct Link {
|
||||||
|
pub id: i64,
|
||||||
|
pub person_id: i64,
|
||||||
|
pub csrf: String,
|
||||||
|
pub created_by: String,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub expires_at: DateTime<Utc>,
|
||||||
|
pub first_used_at: Option<DateTime<Utc>>,
|
||||||
|
pub last_used_at: Option<DateTime<Utc>>,
|
||||||
|
pub sent_at: Option<DateTime<Utc>>,
|
||||||
|
pub closed_at: Option<DateTime<Utc>>,
|
||||||
|
pub closed_by: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a link stands.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum State {
|
||||||
|
/// Made, not opened yet.
|
||||||
|
Open,
|
||||||
|
/// Opened by the client at least once.
|
||||||
|
Used,
|
||||||
|
/// The client pressed Send; closed.
|
||||||
|
Sent,
|
||||||
|
/// Closed by staff, or by a newer link.
|
||||||
|
Closed,
|
||||||
|
Expired,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
State::Open => "open",
|
||||||
|
State::Used => "opened",
|
||||||
|
State::Sent => "sent",
|
||||||
|
State::Closed => "closed",
|
||||||
|
State::Expired => "expired",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The chip's color.
|
||||||
|
pub fn level(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
State::Open | State::Used => "warn",
|
||||||
|
State::Sent => "ok",
|
||||||
|
State::Closed | State::Expired => "plain",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Link {
|
||||||
|
pub fn state(&self, now: DateTime<Utc>) -> State {
|
||||||
|
match (self.sent_at, self.closed_at) {
|
||||||
|
(Some(_), _) => State::Sent,
|
||||||
|
(None, Some(_)) => State::Closed,
|
||||||
|
_ if self.expires_at <= now => State::Expired,
|
||||||
|
_ if self.first_used_at.is_some() => State::Used,
|
||||||
|
_ => State::Open,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client may still use it.
|
||||||
|
pub fn usable(&self, now: DateTime<Utc>) -> bool {
|
||||||
|
matches!(self.state(now), State::Open | State::Used)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audit log's actor for what the client does through it.
|
||||||
|
pub fn actor(&self) -> String {
|
||||||
|
actor(self.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn actor(id: i64) -> String {
|
||||||
|
format!("link {id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hash(token: &str) -> Vec<u8> {
|
||||||
|
ring::digest::digest(&ring::digest::SHA256, token.as_bytes())
|
||||||
|
.as_ref()
|
||||||
|
.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes a link for the person and closes their earlier open ones (by
|
||||||
|
/// `by`, a staff login). Returns the link and its token, which nothing
|
||||||
|
/// keeps: the page that made it shows it once.
|
||||||
|
pub async fn create(conn: &mut PgConnection, person: i64, by: &str) -> Result<(Link, String)> {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE client_links SET closed_at = now(), closed_by = $2 \
|
||||||
|
WHERE person_id = $1 AND closed_at IS NULL AND expires_at > now()",
|
||||||
|
)
|
||||||
|
.bind(person)
|
||||||
|
.bind(by)
|
||||||
|
.execute(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
let token = random_token();
|
||||||
|
let ttl = chrono::TimeDelta::seconds(LIFETIME.as_secs() as i64);
|
||||||
|
let link: Link = sqlx::query_as(
|
||||||
|
"INSERT INTO client_links (person_id, token_hash, csrf, created_by, expires_at) \
|
||||||
|
VALUES ($1, $2, $3, $4, now() + $5) \
|
||||||
|
RETURNING id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \
|
||||||
|
last_used_at, sent_at, closed_at, closed_by",
|
||||||
|
)
|
||||||
|
.bind(person)
|
||||||
|
.bind(hash(&token))
|
||||||
|
.bind(random_token())
|
||||||
|
.bind(by)
|
||||||
|
.bind(ttl)
|
||||||
|
.fetch_one(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
Ok((link, token))
|
||||||
|
}
|
||||||
|
|
||||||
|
const COLUMNS: &str = "id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \
|
||||||
|
last_used_at, sent_at, closed_at, closed_by";
|
||||||
|
|
||||||
|
/// The link with this token, whatever its state.
|
||||||
|
pub async fn by_token(db: &PgPool, token: &str) -> Result<Option<Link>> {
|
||||||
|
// a token is 43 characters of base64url; anything else is no token
|
||||||
|
if token.len() != 43
|
||||||
|
|| !token
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
{
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(sqlx::query_as(&format!(
|
||||||
|
"SELECT {COLUMNS} FROM client_links WHERE token_hash = $1"
|
||||||
|
))
|
||||||
|
.bind(hash(token))
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(db: &PgPool, person: i64, id: i64) -> Result<Option<Link>> {
|
||||||
|
Ok(sqlx::query_as(&format!(
|
||||||
|
"SELECT {COLUMNS} FROM client_links WHERE person_id = $1 AND id = $2"
|
||||||
|
))
|
||||||
|
.bind(person)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The person's links, newest first.
|
||||||
|
pub async fn for_person(db: &PgPool, person: i64) -> Result<Vec<Link>> {
|
||||||
|
Ok(sqlx::query_as(&format!(
|
||||||
|
"SELECT {COLUMNS} FROM client_links WHERE person_id = $1 ORDER BY id DESC"
|
||||||
|
))
|
||||||
|
.bind(person)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notes that the client opened a page of the link.
|
||||||
|
pub async fn touch(db: &PgPool, id: i64) -> Result<()> {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE client_links SET first_used_at = COALESCE(first_used_at, now()), \
|
||||||
|
last_used_at = now() WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes an open link; `sent`: the client sent it. False when it was no
|
||||||
|
/// longer open.
|
||||||
|
pub async fn close(conn: &mut PgConnection, id: i64, by: &str, sent: bool) -> Result<bool> {
|
||||||
|
let done = sqlx::query(
|
||||||
|
"UPDATE client_links SET closed_at = now(), closed_by = $2, \
|
||||||
|
sent_at = CASE WHEN $3 THEN now() END \
|
||||||
|
WHERE id = $1 AND closed_at IS NULL AND expires_at > now()",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(by)
|
||||||
|
.bind(sent)
|
||||||
|
.execute(conn)
|
||||||
|
.await?;
|
||||||
|
Ok(done.rows_affected() == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the client changed through a link, from the audit log: one entry
|
||||||
|
/// per record, with the names of the fields (never their values).
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct Change {
|
||||||
|
pub entity: String,
|
||||||
|
pub entity_id: Option<i64>,
|
||||||
|
pub action: String,
|
||||||
|
pub fields: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn changes(db: &PgPool, id: i64) -> Result<Vec<Change>> {
|
||||||
|
let rows: Vec<(String, Option<i64>, String, Vec<String>)> = sqlx::query_as(
|
||||||
|
"SELECT entity, entity_id, action, fields FROM audit_log \
|
||||||
|
WHERE actor = $1 AND action IN ('create', 'update') ORDER BY id",
|
||||||
|
)
|
||||||
|
.bind(actor(id))
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut out: Vec<Change> = Vec::new();
|
||||||
|
for (entity, entity_id, action, fields) in rows {
|
||||||
|
match out
|
||||||
|
.iter_mut()
|
||||||
|
.find(|c| c.entity == entity && c.entity_id == entity_id)
|
||||||
|
{
|
||||||
|
Some(c) => {
|
||||||
|
for f in fields {
|
||||||
|
if !c.fields.contains(&f) {
|
||||||
|
c.fields.push(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => out.push(Change {
|
||||||
|
entity,
|
||||||
|
entity_id,
|
||||||
|
action,
|
||||||
|
fields,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The record of `entity` the link made last, if any: the client's own
|
||||||
|
/// address or passport, which a second save changes instead of adding
|
||||||
|
/// another.
|
||||||
|
pub async fn made(db: &PgPool, id: i64, entity: &str) -> Result<Option<i64>> {
|
||||||
|
Ok(sqlx::query_scalar(
|
||||||
|
"SELECT entity_id FROM audit_log WHERE actor = $1 AND action = 'create' \
|
||||||
|
AND entity = $2 ORDER BY id DESC LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(actor(id))
|
||||||
|
.bind(entity)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?
|
||||||
|
.flatten())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Dec 4, 2026" in Chiang Mai time.
|
||||||
|
pub fn day(t: DateTime<Utc>) -> String {
|
||||||
|
dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn link(now: DateTime<Utc>) -> Link {
|
||||||
|
Link {
|
||||||
|
id: 7,
|
||||||
|
person_id: 1,
|
||||||
|
csrf: String::new(),
|
||||||
|
created_by: "grabowski".into(),
|
||||||
|
created_at: now,
|
||||||
|
expires_at: now + chrono::TimeDelta::days(14),
|
||||||
|
first_used_at: None,
|
||||||
|
last_used_at: None,
|
||||||
|
sent_at: None,
|
||||||
|
closed_at: None,
|
||||||
|
closed_by: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn states() {
|
||||||
|
let now = Utc::now();
|
||||||
|
let mut l = link(now);
|
||||||
|
assert_eq!(l.state(now), State::Open);
|
||||||
|
l.first_used_at = Some(now);
|
||||||
|
assert_eq!(l.state(now), State::Used);
|
||||||
|
assert!(l.usable(now));
|
||||||
|
assert_eq!(l.state(now + chrono::TimeDelta::days(15)), State::Expired);
|
||||||
|
l.closed_at = Some(now);
|
||||||
|
assert_eq!(l.state(now), State::Closed);
|
||||||
|
assert!(!l.usable(now));
|
||||||
|
l.sent_at = Some(now);
|
||||||
|
assert_eq!(l.state(now), State::Sent);
|
||||||
|
assert_eq!(l.actor(), "link 7");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_tokens_are_looked_up() {
|
||||||
|
assert_eq!(random_token().len(), 43);
|
||||||
|
assert_eq!(hash("x").len(), 32);
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
@@ -11,6 +11,7 @@ use crate::audit::{self, Action, Entity, Entry};
|
|||||||
use crate::dates;
|
use crate::dates;
|
||||||
use crate::documents::{self, Meta, NewFile, Owner};
|
use crate::documents::{self, Meta, NewFile, Owner};
|
||||||
use crate::files::{self, Store};
|
use crate::files::{self, Store};
|
||||||
|
use crate::links;
|
||||||
use crate::mrz;
|
use crate::mrz;
|
||||||
use crate::people::{self, AddressInput, PassportInput, PersonInput};
|
use crate::people::{self, AddressInput, PassportInput, PersonInput};
|
||||||
use crate::records::{self, Kind, Values};
|
use crate::records::{self, Kind, Values};
|
||||||
@@ -568,6 +569,7 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
|||||||
}
|
}
|
||||||
let mut tx = db.begin().await?;
|
let mut tx = db.begin().await?;
|
||||||
let mut company_ids = Vec::new();
|
let mut company_ids = Vec::new();
|
||||||
|
let mut person_ids = Vec::new();
|
||||||
for c in companies() {
|
for c in companies() {
|
||||||
let id = records::create(&mut tx, &records::COMPANIES, None, &c).await?;
|
let id = records::create(&mut tx, &records::COMPANIES, None, &c).await?;
|
||||||
audit::record(&mut *tx, &seeded(Action::Create, Entity::Company, id, None)).await?;
|
audit::record(&mut *tx, &seeded(Action::Create, Entity::Company, id, None)).await?;
|
||||||
@@ -576,6 +578,7 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
|||||||
for mut demo in demos(today) {
|
for mut demo in demos(today) {
|
||||||
demo.person.employer = demo.employer.map(|i| company_ids[i]);
|
demo.person.employer = demo.employer.map(|i| company_ids[i]);
|
||||||
let id = people::create_person(&mut tx, &demo.person).await?;
|
let id = people::create_person(&mut tx, &demo.person).await?;
|
||||||
|
person_ids.push(id);
|
||||||
audit::record(
|
audit::record(
|
||||||
&mut *tx,
|
&mut *tx,
|
||||||
&seeded(Action::Create, Entity::Person, id, Some(id)),
|
&seeded(Action::Create, Entity::Person, id, Some(id)),
|
||||||
@@ -631,10 +634,71 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
|||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
demo_links(&mut tx, &person_ids).await?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Client links to see on the person's page: the first demo person sent
|
||||||
|
/// theirs an hour ago, with a new phone number and email address; the
|
||||||
|
/// second opened theirs and has not sent it yet. Their tokens are thrown
|
||||||
|
/// away: to try the client's pages, make a new link.
|
||||||
|
async fn demo_links(tx: &mut sqlx::PgConnection, people: &[i64]) -> Result<()> {
|
||||||
|
if let Some(&id) = people.first() {
|
||||||
|
let (link, _) = links::create(tx, id, "seed").await?;
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE client_links SET created_at = now() - interval '1 day', \
|
||||||
|
first_used_at = now() - interval '2 hours', last_used_at = now() - interval '1 hour', \
|
||||||
|
sent_at = now() - interval '1 hour', closed_at = now() - interval '1 hour', \
|
||||||
|
closed_by = 'client' WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(link.id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&seeded(Action::Create, Entity::Link, link.id, Some(id)),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let actor = link.actor();
|
||||||
|
let fields = ["phone".to_string(), "email".to_string()];
|
||||||
|
for (action, entity, eid, fields) in [
|
||||||
|
(Action::Update, Entity::Person, id, &fields[..]),
|
||||||
|
(Action::Send, Entity::Link, link.id, &[][..]),
|
||||||
|
] {
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&Entry {
|
||||||
|
actor: &actor,
|
||||||
|
action,
|
||||||
|
entity,
|
||||||
|
entity_id: Some(eid),
|
||||||
|
person_id: Some(id),
|
||||||
|
company_id: None,
|
||||||
|
fields,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(&id) = people.get(1) {
|
||||||
|
let (link, _) = links::create(tx, id, "seed").await?;
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE client_links SET first_used_at = now() - interval '3 hours', \
|
||||||
|
last_used_at = now() - interval '3 hours' WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(link.id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&seeded(Action::Create, Entity::Link, link.id, Some(id)),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// A demo document to add: whose, its kind, its record, its date, the
|
/// A demo document to add: whose, its kind, its record, its date, the
|
||||||
/// file's name and the file.
|
/// file's name and the file.
|
||||||
type Planned = (
|
type Planned = (
|
||||||
|
|||||||
@@ -0,0 +1,917 @@
|
|||||||
|
//! The client's pages at `/c/<token>`: the one part of the app open
|
||||||
|
//! without a login. The client fills in their personal details, the
|
||||||
|
//! passport (with the photo reader), the address in Thailand and contact,
|
||||||
|
//! uploads scans, and presses Send. Each part is saved on its own, straight
|
||||||
|
//! into the person's record, and logged with the actor `link <id>`; staff
|
||||||
|
//! check it on the person's page. The pages show nothing about anyone else
|
||||||
|
//! and nothing of the record but what the client fills in here.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Form;
|
||||||
|
use axum::extract::multipart::MultipartError;
|
||||||
|
use axum::extract::{Multipart, Path, Query, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Redirect, Response};
|
||||||
|
use chrono::Utc;
|
||||||
|
use minijinja::{Value, context};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
|
use super::documents::{self as webdocs, FILE_LIMIT, MAX_FILES, Refused};
|
||||||
|
use super::links::{CLIENT_KINDS, client_kinds};
|
||||||
|
use super::people::{read_zone, select_lists, zone_note};
|
||||||
|
use super::{AppState, Res, render, with_reader};
|
||||||
|
use crate::audit::{self, Action, Entity, Entry};
|
||||||
|
use crate::documents::{self, LINKS, Meta, Owner};
|
||||||
|
use crate::forms::{Errors, Fields, err, get};
|
||||||
|
use crate::links::{self, Link, State as LinkState};
|
||||||
|
use crate::mrz::Mrz;
|
||||||
|
use crate::people::{
|
||||||
|
self, AddressForm, AddressInput, PassportForm, PassportInput, Person, PersonForm, PersonInput,
|
||||||
|
};
|
||||||
|
use crate::session::{self, User};
|
||||||
|
use crate::{dates, embedded};
|
||||||
|
|
||||||
|
/// The link of a page, and the person it is for.
|
||||||
|
struct Client {
|
||||||
|
link: Link,
|
||||||
|
person: Person,
|
||||||
|
/// `/c/<token>`
|
||||||
|
base: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
/// The one the link acts as, for the upload's checks and the audit log.
|
||||||
|
fn user(&self) -> User {
|
||||||
|
User {
|
||||||
|
login: self.link.actor(),
|
||||||
|
name: "Client".into(),
|
||||||
|
local: false,
|
||||||
|
csrf: self.link.csrf.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(&self) -> i64 {
|
||||||
|
self.person.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page of the client's own frame.
|
||||||
|
fn client_page(
|
||||||
|
st: &AppState,
|
||||||
|
c: &Client,
|
||||||
|
name: &str,
|
||||||
|
title: &str,
|
||||||
|
status: StatusCode,
|
||||||
|
ctx: Value,
|
||||||
|
) -> Response {
|
||||||
|
let full = context! {
|
||||||
|
title,
|
||||||
|
v => embedded::STATIC_HASH,
|
||||||
|
csrf => &c.link.csrf,
|
||||||
|
base => &c.base,
|
||||||
|
until => links::day(c.link.expires_at),
|
||||||
|
first_name => &c.person.first_name,
|
||||||
|
..ctx
|
||||||
|
};
|
||||||
|
render(st, name, full, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A link that cannot be used (any more), and why.
|
||||||
|
fn closed_page(st: &AppState, link: Option<&Link>) -> Response {
|
||||||
|
let now = Utc::now();
|
||||||
|
let (status, title, text) = match link.map(|l| (l.state(now), l)) {
|
||||||
|
None => (
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"This link does not work",
|
||||||
|
"There is no link at this address. Check that you opened the whole link, or ask B4L \
|
||||||
|
for a new one."
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
Some((LinkState::Sent, l)) => (
|
||||||
|
StatusCode::GONE,
|
||||||
|
"Thank you",
|
||||||
|
format!(
|
||||||
|
"You sent your details on {}. B4L checks them and gets in touch. To change \
|
||||||
|
something now, ask B4L for a new link.",
|
||||||
|
l.sent_at.map(links::day).unwrap_or_default()
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Some((LinkState::Expired, l)) => (
|
||||||
|
StatusCode::GONE,
|
||||||
|
"This link has expired",
|
||||||
|
format!(
|
||||||
|
"It worked until {}. Ask B4L for a new one; what you saved through it is kept.",
|
||||||
|
links::day(l.expires_at)
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Some(_) => (
|
||||||
|
StatusCode::GONE,
|
||||||
|
"This link is closed",
|
||||||
|
"B4L closed it. Ask them for a new one if you still need to send something; what you \
|
||||||
|
saved through it is kept."
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
render(
|
||||||
|
st,
|
||||||
|
"client_closed.html",
|
||||||
|
context! { title, text, v => embedded::STATIC_HASH },
|
||||||
|
status,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The open link with this token and its person, or the page that says
|
||||||
|
/// why there is none.
|
||||||
|
async fn open(st: &AppState, token: &str) -> anyhow::Result<Result<Client, Response>> {
|
||||||
|
let Some(link) = links::by_token(&st.db, token).await? else {
|
||||||
|
return Ok(Err(closed_page(st, None)));
|
||||||
|
};
|
||||||
|
if !link.usable(Utc::now()) {
|
||||||
|
return Ok(Err(closed_page(st, Some(&link))));
|
||||||
|
}
|
||||||
|
let Some(person) = people::get_person(&st.db, link.person_id).await? else {
|
||||||
|
return Ok(Err(closed_page(st, None)));
|
||||||
|
};
|
||||||
|
links::touch(&st.db, link.id).await?;
|
||||||
|
Ok(Ok(Client {
|
||||||
|
link,
|
||||||
|
person,
|
||||||
|
base: format!("/c/{token}"),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A form of the link must carry the link's own token.
|
||||||
|
fn token_ok(c: &Client, f: &Fields) -> bool {
|
||||||
|
session::same_token(&get(f, "csrf"), &c.link.csrf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stale(st: &AppState) -> Response {
|
||||||
|
render(
|
||||||
|
st,
|
||||||
|
"client_closed.html",
|
||||||
|
context! {
|
||||||
|
title => "The page was too old",
|
||||||
|
text => "Go back, reload the page and send it again.",
|
||||||
|
v => embedded::STATIC_HASH,
|
||||||
|
},
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log<'a>(
|
||||||
|
c: &Client,
|
||||||
|
actor: &'a str,
|
||||||
|
action: Action,
|
||||||
|
entity: Entity,
|
||||||
|
id: Option<i64>,
|
||||||
|
fields: &'a [String],
|
||||||
|
) -> Entry<'a> {
|
||||||
|
Entry {
|
||||||
|
actor,
|
||||||
|
action,
|
||||||
|
entity,
|
||||||
|
entity_id: id,
|
||||||
|
person_id: Some(c.id()),
|
||||||
|
company_id: None,
|
||||||
|
fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn viewed(st: &AppState, c: &Client, entity: Entity, id: i64) -> anyhow::Result<()> {
|
||||||
|
let actor = c.link.actor();
|
||||||
|
audit::record(&st.db, &log(c, &actor, Action::View, entity, Some(id), &[])).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_for(errors: &Errors) -> StatusCode {
|
||||||
|
if errors.is_empty() {
|
||||||
|
StatusCode::OK
|
||||||
|
} else {
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! open_or_return {
|
||||||
|
($st:expr, $token:expr) => {
|
||||||
|
match open(&$st, &$token).await? {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(resp) => return Ok(resp),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- overview
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
struct Part {
|
||||||
|
slug: &'static str,
|
||||||
|
title: &'static str,
|
||||||
|
what: &'static str,
|
||||||
|
done: bool,
|
||||||
|
status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn parts(st: &AppState, c: &Client) -> anyhow::Result<Vec<Part>> {
|
||||||
|
let p = &c.person;
|
||||||
|
let about = !p.surname.is_empty()
|
||||||
|
&& !p.first_name.is_empty()
|
||||||
|
&& !p.sex.is_empty()
|
||||||
|
&& p.date_of_birth.is_some()
|
||||||
|
&& !p.nationality.is_empty();
|
||||||
|
let passports = people::passports(&st.db, c.id()).await?;
|
||||||
|
let current = people::addresses(&st.db, c.id())
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.any(|a| a.moved_out_on.is_none());
|
||||||
|
let contact = !p.phone.is_empty() || !p.email.is_empty();
|
||||||
|
let actor = c.link.actor();
|
||||||
|
let docs = documents::list(&st.db, Owner::Person(c.id())).await?;
|
||||||
|
let mine = docs.iter().filter(|d| d.uploaded_by == actor).count();
|
||||||
|
let has = |k: &str| docs.iter().any(|d| d.kind == k);
|
||||||
|
let papers = has("passport-photo-page") && has("photo");
|
||||||
|
let state = |done: bool, yes: &str, no: &str| if done { yes } else { no }.to_string();
|
||||||
|
Ok(vec![
|
||||||
|
Part {
|
||||||
|
slug: "about",
|
||||||
|
title: "About you",
|
||||||
|
what: "Your name as in the passport, date and place of birth, nationality, occupation.",
|
||||||
|
done: about,
|
||||||
|
status: state(about, "Filled in", "To fill in"),
|
||||||
|
},
|
||||||
|
Part {
|
||||||
|
slug: "passport",
|
||||||
|
title: "Passport",
|
||||||
|
what: "A photo of the passport's photo page fills it in, or type the two lines at its bottom.",
|
||||||
|
done: !passports.is_empty(),
|
||||||
|
status: state(!passports.is_empty(), "Recorded", "To fill in"),
|
||||||
|
},
|
||||||
|
Part {
|
||||||
|
slug: "address",
|
||||||
|
title: "Address in Thailand",
|
||||||
|
what: "Where you live now, and your landlord or house owner.",
|
||||||
|
done: current,
|
||||||
|
status: state(current, "Recorded", "To fill in"),
|
||||||
|
},
|
||||||
|
Part {
|
||||||
|
slug: "contact",
|
||||||
|
title: "Contact",
|
||||||
|
what: "Your phone number and email address.",
|
||||||
|
done: contact,
|
||||||
|
status: state(contact, "Filled in", "To fill in"),
|
||||||
|
},
|
||||||
|
Part {
|
||||||
|
slug: "documents",
|
||||||
|
title: "Documents",
|
||||||
|
what: "Scans or photos: the passport's photo page, a passport photo, the TDAC and others.",
|
||||||
|
done: papers,
|
||||||
|
status: match mine {
|
||||||
|
0 if papers => "Recorded".into(),
|
||||||
|
0 => "To upload".into(),
|
||||||
|
1 => "1 file uploaded".into(),
|
||||||
|
n => format!("{n} files uploaded"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct SavedQuery {
|
||||||
|
saved: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn overview(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
Query(q): Query<SavedQuery>,
|
||||||
|
) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
let parts = parts(&st, &c).await?;
|
||||||
|
let saved = q
|
||||||
|
.saved
|
||||||
|
.as_deref()
|
||||||
|
.and_then(|s| parts.iter().find(|p| p.slug == s))
|
||||||
|
.map(|p| p.title);
|
||||||
|
let missing: Vec<&str> = parts.iter().filter(|p| !p.done).map(|p| p.title).collect();
|
||||||
|
let actor = c.link.actor();
|
||||||
|
audit::record(
|
||||||
|
&st.db,
|
||||||
|
&log(&c, &actor, Action::View, Entity::Link, Some(c.link.id), &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(client_page(
|
||||||
|
&st,
|
||||||
|
&c,
|
||||||
|
"client.html",
|
||||||
|
"Your details",
|
||||||
|
StatusCode::OK,
|
||||||
|
context! { parts, saved, missing },
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
// --------------------------------------------------------------- about
|
||||||
|
|
||||||
|
/// The fields of the About part; the rest of the record stays as it is.
|
||||||
|
const ABOUT: &[&str] = &[
|
||||||
|
"surname",
|
||||||
|
"first_name",
|
||||||
|
"middle_name",
|
||||||
|
"title",
|
||||||
|
"sex",
|
||||||
|
"date_of_birth",
|
||||||
|
"place_of_birth",
|
||||||
|
"nationality",
|
||||||
|
"occupation",
|
||||||
|
];
|
||||||
|
const CONTACT: &[&str] = &["phone", "email"];
|
||||||
|
|
||||||
|
/// The record's fields with the posted ones of a part over them.
|
||||||
|
fn person_form(p: &Person, f: &Fields, keys: &[&str]) -> PersonForm {
|
||||||
|
let posted = PersonForm::from_fields(f);
|
||||||
|
let mut pf = PersonForm::from_person(p);
|
||||||
|
for k in keys {
|
||||||
|
match *k {
|
||||||
|
"surname" => pf.surname = posted.surname.clone(),
|
||||||
|
"first_name" => pf.first_name = posted.first_name.clone(),
|
||||||
|
"middle_name" => pf.middle_name = posted.middle_name.clone(),
|
||||||
|
"title" => pf.title = posted.title.clone(),
|
||||||
|
"sex" => pf.sex = posted.sex.clone(),
|
||||||
|
"date_of_birth" => pf.date_of_birth = posted.date_of_birth.clone(),
|
||||||
|
"place_of_birth" => pf.place_of_birth = posted.place_of_birth.clone(),
|
||||||
|
"nationality" => pf.nationality = posted.nationality.clone(),
|
||||||
|
"occupation" => pf.occupation = posted.occupation.clone(),
|
||||||
|
"phone" => pf.phone = posted.phone.clone(),
|
||||||
|
"email" => pf.email = posted.email.clone(),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pf
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves a person's fields changed by the client; true when it validated.
|
||||||
|
async fn save_person(
|
||||||
|
st: &AppState,
|
||||||
|
c: &Client,
|
||||||
|
pf: &PersonForm,
|
||||||
|
) -> anyhow::Result<Result<(), Errors>> {
|
||||||
|
let employer: Vec<i64> = c.person.employer_id.into_iter().collect();
|
||||||
|
let input = match pf.validate(dates::today(), &employer) {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(e) => return Ok(Err(e)),
|
||||||
|
};
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
let Some(old) = people::get_person_in(&mut tx, c.id()).await? else {
|
||||||
|
return Ok(Ok(()));
|
||||||
|
};
|
||||||
|
let changed = input.changed_from(&PersonInput::from(&old));
|
||||||
|
if !changed.is_empty() {
|
||||||
|
people::update_person(&mut tx, c.id(), &input).await?;
|
||||||
|
let actor = c.link.actor();
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(
|
||||||
|
c,
|
||||||
|
&actor,
|
||||||
|
Action::Update,
|
||||||
|
Entity::Person,
|
||||||
|
Some(c.id()),
|
||||||
|
&changed,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn person_part(st: &AppState, c: &Client, part: &str, f: &PersonForm, errors: &Errors) -> Response {
|
||||||
|
let (name, title) = match part {
|
||||||
|
"contact" => ("client_contact.html", "Contact"),
|
||||||
|
_ => ("client_about.html", "About you"),
|
||||||
|
};
|
||||||
|
client_page(
|
||||||
|
st,
|
||||||
|
c,
|
||||||
|
name,
|
||||||
|
title,
|
||||||
|
status_for(errors),
|
||||||
|
context! { f, errors, ..select_lists() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn person_get(st: Arc<AppState>, token: String, part: &str) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
viewed(&st, &c, Entity::Person, c.id()).await?;
|
||||||
|
let f = PersonForm::from_person(&c.person);
|
||||||
|
Ok(person_part(&st, &c, part, &f, &Errors::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn person_post(st: Arc<AppState>, token: String, part: &str, f: Fields) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
if !token_ok(&c, &f) {
|
||||||
|
return Ok(stale(&st));
|
||||||
|
}
|
||||||
|
let keys = if part == "contact" { CONTACT } else { ABOUT };
|
||||||
|
let pf = person_form(&c.person, &f, keys);
|
||||||
|
match save_person(&st, &c, &pf).await? {
|
||||||
|
Ok(()) => Ok(Redirect::to(&format!("{}?saved={part}", c.base)).into_response()),
|
||||||
|
Err(errors) => Ok(person_part(&st, &c, part, &pf, &errors)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn about(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
||||||
|
person_get(st, token, "about").await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn about_save(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
person_post(st, token, "about", f).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn contact(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
||||||
|
person_get(st, token, "contact").await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn contact_save(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
person_post(st, token, "contact", f).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ passport
|
||||||
|
|
||||||
|
fn passport_page(
|
||||||
|
st: &AppState,
|
||||||
|
c: &Client,
|
||||||
|
pf: &PassportForm,
|
||||||
|
errors: &Errors,
|
||||||
|
mrz_note: Option<String>,
|
||||||
|
) -> Response {
|
||||||
|
with_reader(client_page(
|
||||||
|
st,
|
||||||
|
c,
|
||||||
|
"client_passport.html",
|
||||||
|
"Passport",
|
||||||
|
status_for(errors),
|
||||||
|
context! { pf, errors, mrz_note, ..select_lists() },
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The passport the page shows: the one this link added, else the current
|
||||||
|
/// one.
|
||||||
|
async fn shown_passport(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Passport>> {
|
||||||
|
let all = people::passports(&st.db, c.id()).await?;
|
||||||
|
let made = links::made(&st.db, c.link.id, "passport").await?;
|
||||||
|
Ok(match made.and_then(|id| all.iter().find(|p| p.id == id)) {
|
||||||
|
Some(p) => Some(p.clone()),
|
||||||
|
None => all.into_iter().next(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
let pf = match shown_passport(&st, &c).await? {
|
||||||
|
Some(p) => {
|
||||||
|
viewed(&st, &c, Entity::Passport, p.id).await?;
|
||||||
|
PassportForm::from_passport(&p)
|
||||||
|
}
|
||||||
|
None => PassportForm {
|
||||||
|
issuing_country: c.person.nationality.clone(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
};
|
||||||
|
Ok(passport_page(&st, &c, &pf, &Errors::new(), None))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The zone fills in the personal details the record does not have yet.
|
||||||
|
async fn fill_person(st: &AppState, c: &Client, m: &Mrz) -> anyhow::Result<()> {
|
||||||
|
let mut pf = PersonForm::from_person(&c.person);
|
||||||
|
pf.take_mrz(m, false);
|
||||||
|
// a zone with odd fields leaves the record as it is
|
||||||
|
let _ = save_person(st, c, &pf).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport_save(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
if !token_ok(&c, &f) {
|
||||||
|
return Ok(stale(&st));
|
||||||
|
}
|
||||||
|
let today = dates::today();
|
||||||
|
let mut pf = PassportForm::from_fields(&f);
|
||||||
|
let mut errors = Errors::new();
|
||||||
|
let zone = read_zone(&mut pf.mrz, today, &mut errors);
|
||||||
|
let photo = get(&f, "mrz_source") == "photo";
|
||||||
|
|
||||||
|
if get(&f, "action") == "read-mrz" {
|
||||||
|
let mut note = None;
|
||||||
|
match &zone {
|
||||||
|
Some(m) => {
|
||||||
|
pf.take_mrz(m, true);
|
||||||
|
note = zone_note(m, photo, &mut errors);
|
||||||
|
}
|
||||||
|
None if pf.mrz.is_empty() => err(
|
||||||
|
&mut errors,
|
||||||
|
"mrz",
|
||||||
|
"Type the two lines first, or take a photo.",
|
||||||
|
),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
return Ok(passport_page(&st, &c, &pf, &errors, note));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(m) = &zone {
|
||||||
|
pf.take_mrz(m, false);
|
||||||
|
}
|
||||||
|
let input = match pf.validate(zone.as_ref()) {
|
||||||
|
Ok(i) if errors.is_empty() => i,
|
||||||
|
Ok(_) => return Ok(passport_page(&st, &c, &pf, &errors, None)),
|
||||||
|
Err(e) => {
|
||||||
|
for (k, v) in e {
|
||||||
|
err(&mut errors, &k, v);
|
||||||
|
}
|
||||||
|
return Ok(passport_page(&st, &c, &pf, &errors, None));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// the same passport again, else the one this link added (a corrected
|
||||||
|
// number), else a new one
|
||||||
|
let all = people::passports(&st.db, c.id()).await?;
|
||||||
|
let made = links::made(&st.db, c.link.id, "passport").await?;
|
||||||
|
let target = all
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.issuing_country == input.issuing_country && p.number == input.number)
|
||||||
|
.or_else(|| made.and_then(|id| all.iter().find(|p| p.id == id)))
|
||||||
|
.cloned();
|
||||||
|
let actor = c.link.actor();
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if people::passport_taken(&mut tx, &input, target.as_ref().map(|p| p.id)).await? {
|
||||||
|
err(
|
||||||
|
&mut errors,
|
||||||
|
"number",
|
||||||
|
"This passport cannot be saved here. If it is yours, tell B4L.",
|
||||||
|
);
|
||||||
|
return Ok(passport_page(&st, &c, &pf, &errors, None));
|
||||||
|
}
|
||||||
|
match target {
|
||||||
|
Some(old) => {
|
||||||
|
let changed = input.changed_from(&PassportInput::from(&old));
|
||||||
|
if !changed.is_empty() {
|
||||||
|
people::update_passport(&mut tx, old.id, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(
|
||||||
|
&c,
|
||||||
|
&actor,
|
||||||
|
Action::Update,
|
||||||
|
Entity::Passport,
|
||||||
|
Some(old.id),
|
||||||
|
&changed,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let id = people::create_passport(&mut tx, c.id(), &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&c, &actor, Action::Create, Entity::Passport, Some(id), &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
if let Some(m) = &zone {
|
||||||
|
fill_person(&st, &c, m).await?;
|
||||||
|
}
|
||||||
|
Ok(Redirect::to(&format!("{}?saved=passport", c.base)).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- address
|
||||||
|
|
||||||
|
fn address_page(st: &AppState, c: &Client, af: &AddressForm, errors: &Errors) -> Response {
|
||||||
|
client_page(
|
||||||
|
st,
|
||||||
|
c,
|
||||||
|
"client_address.html",
|
||||||
|
"Address in Thailand",
|
||||||
|
status_for(errors),
|
||||||
|
context! { af, errors, ..select_lists() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The address the page shows and saves to: the one this link added, if
|
||||||
|
/// it is still there.
|
||||||
|
async fn made_address(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Address>> {
|
||||||
|
Ok(match links::made(&st.db, c.link.id, "address").await? {
|
||||||
|
Some(id) => people::address(&st.db, c.id(), id).await?,
|
||||||
|
None => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn current_address(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Address>> {
|
||||||
|
Ok(people::addresses(&st.db, c.id())
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.find(|a| a.moved_out_on.is_none()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn address(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
let shown = match made_address(&st, &c).await? {
|
||||||
|
Some(a) => Some(a),
|
||||||
|
None => current_address(&st, &c).await?,
|
||||||
|
};
|
||||||
|
let af = match &shown {
|
||||||
|
Some(a) => {
|
||||||
|
viewed(&st, &c, Entity::Address, a.id).await?;
|
||||||
|
AddressForm::from_address(a)
|
||||||
|
}
|
||||||
|
None => AddressForm {
|
||||||
|
province: "Chiang Mai".into(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
};
|
||||||
|
Ok(address_page(&st, &c, &af, &Errors::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves the client's address: the one this link added is changed; an
|
||||||
|
/// address like the current one changes nothing; any other is added as a
|
||||||
|
/// new one, so the current address and its TM.30 receipt stay as they are
|
||||||
|
/// until staff check it.
|
||||||
|
pub async fn address_save(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
if !token_ok(&c, &f) {
|
||||||
|
return Ok(stale(&st));
|
||||||
|
}
|
||||||
|
let made = made_address(&st, &c).await?;
|
||||||
|
let current = current_address(&st, &c).await?;
|
||||||
|
let posted = AddressForm::from_fields(&f);
|
||||||
|
// the parts staff fill in come from the address saved to
|
||||||
|
let base = made
|
||||||
|
.as_ref()
|
||||||
|
.map(AddressForm::from_address)
|
||||||
|
.unwrap_or_default();
|
||||||
|
let af = AddressForm {
|
||||||
|
moved_out_on: base.moved_out_on,
|
||||||
|
tm30_reported_on: base.tm30_reported_on,
|
||||||
|
tm30_receipt_no: base.tm30_receipt_no,
|
||||||
|
..posted
|
||||||
|
};
|
||||||
|
let input = match af.validate(dates::today()) {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(errors) => return Ok(address_page(&st, &c, &af, &errors)),
|
||||||
|
};
|
||||||
|
let actor = c.link.actor();
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
match (&made, ¤t) {
|
||||||
|
(Some(old), _) => {
|
||||||
|
let changed = input.changed_from(&AddressInput::from(old));
|
||||||
|
if !changed.is_empty() {
|
||||||
|
people::update_address(&mut tx, old.id, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(
|
||||||
|
&c,
|
||||||
|
&actor,
|
||||||
|
Action::Update,
|
||||||
|
Entity::Address,
|
||||||
|
Some(old.id),
|
||||||
|
&changed,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(None, Some(cur)) if same_place(&input, &AddressInput::from(cur)) => {}
|
||||||
|
_ => {
|
||||||
|
let id = people::create_address(&mut tx, c.id(), &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&c, &actor, Action::Create, Entity::Address, Some(id), &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("{}?saved=address", c.base)).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same address and house master, whatever staff recorded about TM.30.
|
||||||
|
fn same_place(a: &AddressInput, b: &AddressInput) -> bool {
|
||||||
|
let strip = |x: &AddressInput| AddressInput {
|
||||||
|
moved_out_on: None,
|
||||||
|
tm30_reported_on: None,
|
||||||
|
tm30_receipt_no: String::new(),
|
||||||
|
..x.clone()
|
||||||
|
};
|
||||||
|
strip(a) == strip(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------- documents
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize)]
|
||||||
|
struct UploadValues {
|
||||||
|
kind: String,
|
||||||
|
note: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
struct Uploaded {
|
||||||
|
label: String,
|
||||||
|
file_name: String,
|
||||||
|
size: String,
|
||||||
|
at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn documents_page(
|
||||||
|
st: &AppState,
|
||||||
|
c: &Client,
|
||||||
|
v: &UploadValues,
|
||||||
|
errors: &Errors,
|
||||||
|
status: StatusCode,
|
||||||
|
) -> anyhow::Result<Response> {
|
||||||
|
let actor = c.link.actor();
|
||||||
|
let owner = Owner::Person(c.id());
|
||||||
|
let uploaded: Vec<Uploaded> = documents::list(&st.db, owner)
|
||||||
|
.await?
|
||||||
|
.iter()
|
||||||
|
.filter(|d| d.uploaded_by == actor)
|
||||||
|
.map(|d| Uploaded {
|
||||||
|
label: documents::kind_label(owner, &d.kind),
|
||||||
|
file_name: d.file_name.clone(),
|
||||||
|
size: webdocs::size_label(d.size_bytes.into()),
|
||||||
|
at: dates::fmt_datetime(d.uploaded_at),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(client_page(
|
||||||
|
st,
|
||||||
|
c,
|
||||||
|
"client_documents.html",
|
||||||
|
"Documents",
|
||||||
|
status,
|
||||||
|
context! {
|
||||||
|
uploaded, v, errors,
|
||||||
|
kinds => client_kinds(),
|
||||||
|
files_on => st.files.is_some(),
|
||||||
|
file_limit => FILE_LIMIT,
|
||||||
|
file_limit_mb => FILE_LIMIT / (1024 * 1024),
|
||||||
|
max_files => MAX_FILES,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn documents_get(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
let actor = c.link.actor();
|
||||||
|
audit::record(
|
||||||
|
&st.db,
|
||||||
|
&log(&c, &actor, Action::View, Entity::Link, Some(c.link.id), &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(documents_page(
|
||||||
|
&st,
|
||||||
|
&c,
|
||||||
|
&UploadValues::default(),
|
||||||
|
&Errors::new(),
|
||||||
|
StatusCode::OK,
|
||||||
|
)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The record a client's document of this kind belongs to: the person's
|
||||||
|
/// newest one of that kind of record, if there is one.
|
||||||
|
async fn record_for(
|
||||||
|
st: &AppState,
|
||||||
|
person: i64,
|
||||||
|
kind: &str,
|
||||||
|
) -> anyhow::Result<Option<(&'static documents::Link, i64)>> {
|
||||||
|
let Some(slug) = documents::kind(Owner::Person(person), kind).and_then(|k| k.record) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let Some(link) = LINKS.iter().find(|l| l.slug == slug) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let order = if slug == "passports" {
|
||||||
|
"expires_on DESC, id DESC"
|
||||||
|
} else {
|
||||||
|
"id DESC"
|
||||||
|
};
|
||||||
|
let id: Option<i64> = sqlx::query_scalar(&format!(
|
||||||
|
"SELECT id FROM {} WHERE person_id = $1 ORDER BY {order} LIMIT 1",
|
||||||
|
link.table
|
||||||
|
))
|
||||||
|
.bind(person)
|
||||||
|
.fetch_optional(&st.db)
|
||||||
|
.await?;
|
||||||
|
Ok(id.map(|id| (link, id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upload_refused(st: &AppState, e: Option<&MultipartError>) -> Response {
|
||||||
|
let text = match e {
|
||||||
|
Some(e) if e.status() == StatusCode::PAYLOAD_TOO_LARGE => format!(
|
||||||
|
"Upload up to {MAX_FILES} files of up to {} MB each at once. Go back and send fewer \
|
||||||
|
files.",
|
||||||
|
FILE_LIMIT / (1024 * 1024)
|
||||||
|
),
|
||||||
|
Some(e) => {
|
||||||
|
warn!("a client's upload could not be read: {}", e.body_text());
|
||||||
|
"The files did not arrive whole. Go back and send them again.".to_string()
|
||||||
|
}
|
||||||
|
None => format!("Upload up to {MAX_FILES} files at once. Go back and send fewer files."),
|
||||||
|
};
|
||||||
|
render(
|
||||||
|
st,
|
||||||
|
"client_closed.html",
|
||||||
|
context! { title => "The upload did not work", text, v => embedded::STATIC_HASH },
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn documents_upload(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
mp: Multipart,
|
||||||
|
) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
let user = c.user();
|
||||||
|
let up = match webdocs::read_upload(&user, mp).await {
|
||||||
|
Ok(Ok(up)) => up,
|
||||||
|
Ok(Err(Refused::Token)) => return Ok(stale(&st)),
|
||||||
|
Ok(Err(Refused::TooMany)) => return Ok(upload_refused(&st, None)),
|
||||||
|
Err(e) => return Ok(upload_refused(&st, Some(&e))),
|
||||||
|
};
|
||||||
|
let v = UploadValues {
|
||||||
|
kind: up.values.kind.clone(),
|
||||||
|
note: up.values.note.clone(),
|
||||||
|
};
|
||||||
|
let owner = Owner::Person(c.id());
|
||||||
|
let mut errors = Errors::new();
|
||||||
|
let Some(store) = st.files.clone() else {
|
||||||
|
err(
|
||||||
|
&mut errors,
|
||||||
|
"file",
|
||||||
|
"Uploads are switched off on this server.",
|
||||||
|
);
|
||||||
|
return Ok(documents_page(&st, &c, &v, &errors, StatusCode::SERVICE_UNAVAILABLE).await?);
|
||||||
|
};
|
||||||
|
if !CLIENT_KINDS.contains(&v.kind.as_str()) {
|
||||||
|
err(&mut errors, "kind", "Choose what the files are.");
|
||||||
|
}
|
||||||
|
if v.note.chars().count() > 500 {
|
||||||
|
err(&mut errors, "note", "Keep the note under 500 characters.");
|
||||||
|
}
|
||||||
|
let checked = webdocs::check_files(&st, owner, up, &mut errors).await?;
|
||||||
|
if !errors.is_empty() {
|
||||||
|
return Ok(documents_page(&st, &c, &v, &errors, StatusCode::UNPROCESSABLE_ENTITY).await?);
|
||||||
|
}
|
||||||
|
let meta = Meta {
|
||||||
|
kind: v.kind.clone(),
|
||||||
|
link: record_for(&st, c.id(), &v.kind).await?,
|
||||||
|
dated_on: None,
|
||||||
|
note: v.note.clone(),
|
||||||
|
};
|
||||||
|
webdocs::save(&st, &user, &store, owner, &meta, checked).await?;
|
||||||
|
Ok(Redirect::to(&format!("{}/documents#uploaded", c.base)).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- send
|
||||||
|
|
||||||
|
pub async fn send(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Path(token): Path<String>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
let c = open_or_return!(st, token);
|
||||||
|
if !token_ok(&c, &f) {
|
||||||
|
return Ok(stale(&st));
|
||||||
|
}
|
||||||
|
let actor = c.link.actor();
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if links::close(&mut tx, c.link.id, "client", true).await? {
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&c, &actor, Action::Send, Entity::Link, Some(c.link.id), &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
let link = links::get(&st.db, c.id(), c.link.id).await?;
|
||||||
|
// the thanks: the page a sent link shows from now on
|
||||||
|
let mut resp = closed_page(&st, link.as_ref());
|
||||||
|
*resp.status_mut() = StatusCode::OK;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
+22
-13
@@ -446,8 +446,8 @@ fn broken_upload(st: &AppState, e: &MultipartError) -> Response {
|
|||||||
|
|
||||||
/// An upload as it arrived, before any check.
|
/// An upload as it arrived, before any check.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Upload {
|
pub(crate) struct Upload {
|
||||||
values: Values,
|
pub(crate) values: Values,
|
||||||
files: Vec<(String, Vec<u8>)>,
|
files: Vec<(String, Vec<u8>)>,
|
||||||
/// files over the limit, by name
|
/// files over the limit, by name
|
||||||
too_big: Vec<String>,
|
too_big: Vec<String>,
|
||||||
@@ -474,13 +474,21 @@ async fn read_field(
|
|||||||
Ok((!over).then_some(out))
|
Ok((!over).then_some(out))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Why an upload was refused before its files were checked.
|
||||||
|
pub(crate) enum Refused {
|
||||||
|
/// No form token, or not the session's (or the client link's).
|
||||||
|
Token,
|
||||||
|
/// More than `MAX_FILES` files.
|
||||||
|
TooMany,
|
||||||
|
}
|
||||||
|
|
||||||
/// The form token must come first (the page puts it there), so a forged
|
/// The form token must come first (the page puts it there), so a forged
|
||||||
/// form is refused before any file is read.
|
/// form is refused before any file is read. `user` is the session's, or
|
||||||
async fn read_upload(
|
/// the one a client link acts as (`web::client`).
|
||||||
st: &AppState,
|
pub(crate) async fn read_upload(
|
||||||
user: &User,
|
user: &User,
|
||||||
mut mp: Multipart,
|
mut mp: Multipart,
|
||||||
) -> Result<Result<Upload, Response>, MultipartError> {
|
) -> Result<Result<Upload, Refused>, MultipartError> {
|
||||||
let token = match mp.next_field().await? {
|
let token = match mp.next_field().await? {
|
||||||
Some(mut f) if f.name() == Some("csrf") => read_field(&mut f, FIELD_LIMIT)
|
Some(mut f) if f.name() == Some("csrf") => read_field(&mut f, FIELD_LIMIT)
|
||||||
.await?
|
.await?
|
||||||
@@ -492,7 +500,7 @@ async fn read_upload(
|
|||||||
"refused an upload without a valid token from {}",
|
"refused an upload without a valid token from {}",
|
||||||
user.login
|
user.login
|
||||||
);
|
);
|
||||||
return Ok(Err(super::expired(st)));
|
return Ok(Err(Refused::Token));
|
||||||
}
|
}
|
||||||
let mut up = Upload::default();
|
let mut up = Upload::default();
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
@@ -530,7 +538,7 @@ async fn read_upload(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if count > MAX_FILES {
|
if count > MAX_FILES {
|
||||||
return Ok(Err(too_large(st)));
|
return Ok(Err(Refused::TooMany));
|
||||||
}
|
}
|
||||||
Ok(Ok(up))
|
Ok(Ok(up))
|
||||||
}
|
}
|
||||||
@@ -587,7 +595,7 @@ async fn check_meta(st: &AppState, owner: Owner, v: &Values) -> anyhow::Result<(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Checked {
|
pub(crate) struct Checked {
|
||||||
name: String,
|
name: String,
|
||||||
bytes: Vec<u8>,
|
bytes: Vec<u8>,
|
||||||
content_type: &'static str,
|
content_type: &'static str,
|
||||||
@@ -596,7 +604,7 @@ struct Checked {
|
|||||||
|
|
||||||
/// The files, checked: a type the app takes (by the file's first bytes),
|
/// The files, checked: a type the app takes (by the file's first bytes),
|
||||||
/// not empty, not too large, not uploaded before for this person or company.
|
/// not empty, not too large, not uploaded before for this person or company.
|
||||||
async fn check_files(
|
pub(crate) async fn check_files(
|
||||||
st: &AppState,
|
st: &AppState,
|
||||||
owner: Owner,
|
owner: Owner,
|
||||||
up: Upload,
|
up: Upload,
|
||||||
@@ -651,7 +659,7 @@ async fn check_files(
|
|||||||
/// Saves the checked files as documents: the rows, the encrypted files and
|
/// Saves the checked files as documents: the rows, the encrypted files and
|
||||||
/// the audit entries in one transaction. Files written before a failure are
|
/// the audit entries in one transaction. Files written before a failure are
|
||||||
/// removed again. Returns the first new id.
|
/// removed again. Returns the first new id.
|
||||||
async fn save(
|
pub(crate) async fn save(
|
||||||
st: &AppState,
|
st: &AppState,
|
||||||
user: &User,
|
user: &User,
|
||||||
store: &Store,
|
store: &Store,
|
||||||
@@ -728,9 +736,10 @@ pub async fn upload(st: Arc<AppState>, user: User, owner: Owner, mp: Multipart)
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let up = match read_upload(&st, &user, mp).await {
|
let up = match read_upload(&user, mp).await {
|
||||||
Ok(Ok(up)) => up,
|
Ok(Ok(up)) => up,
|
||||||
Ok(Err(resp)) => return Ok(resp),
|
Ok(Err(Refused::Token)) => return Ok(super::expired(&st)),
|
||||||
|
Ok(Err(Refused::TooMany)) => return Ok(too_large(&st)),
|
||||||
Err(e) => return Ok(broken_upload(&st, &e)),
|
Err(e) => return Ok(broken_upload(&st, &e)),
|
||||||
};
|
};
|
||||||
let Some(store) = st.files.clone() else {
|
let Some(store) = st.files.clone() else {
|
||||||
|
|||||||
@@ -0,0 +1,353 @@
|
|||||||
|
//! The client link on the staff's side: the card on a person's page, making
|
||||||
|
//! a link (also with a new, nearly empty record: "+ New client"), the page
|
||||||
|
//! that shows the link once, and closing a link.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Redirect, Response};
|
||||||
|
use axum::{Extension, Form};
|
||||||
|
use chrono::Utc;
|
||||||
|
use minijinja::context;
|
||||||
|
use qrcode::QrCode;
|
||||||
|
use qrcode::render::svg;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use super::people::{PersonView, load_person};
|
||||||
|
use super::{AppState, Res, not_found_page, page, percent_encode};
|
||||||
|
use crate::audit::{self, Action, Entity, Entry};
|
||||||
|
use crate::forms::{Errors, Fields, err, get};
|
||||||
|
use crate::links::{self, Link};
|
||||||
|
use crate::people::{self, PersonInput};
|
||||||
|
use crate::session::User;
|
||||||
|
use crate::{dates, documents};
|
||||||
|
|
||||||
|
/// A link as the person's page shows it.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct LinkView {
|
||||||
|
pub id: i64,
|
||||||
|
pub state: &'static str,
|
||||||
|
pub level: &'static str,
|
||||||
|
pub usable: bool,
|
||||||
|
pub made: String,
|
||||||
|
pub by: String,
|
||||||
|
pub until: String,
|
||||||
|
pub opened: String,
|
||||||
|
pub sent: String,
|
||||||
|
pub closed: String,
|
||||||
|
pub changes: Vec<ChangeView>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One record the client added or changed through a link.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct ChangeView {
|
||||||
|
pub label: String,
|
||||||
|
pub href: String,
|
||||||
|
pub fields: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn change_view(person: i64, c: &links::Change) -> ChangeView {
|
||||||
|
let made = c.action == "create";
|
||||||
|
let (label, href) = match (c.entity.as_str(), c.entity_id) {
|
||||||
|
("person", _) => (
|
||||||
|
"Personal details".to_string(),
|
||||||
|
format!("/people/{person}#details"),
|
||||||
|
),
|
||||||
|
("passport", _) => (
|
||||||
|
if made { "New passport" } else { "Passport" }.to_string(),
|
||||||
|
format!("/people/{person}#passports"),
|
||||||
|
),
|
||||||
|
("address", _) => (
|
||||||
|
if made { "New address" } else { "Address" }.to_string(),
|
||||||
|
format!("/people/{person}#addresses"),
|
||||||
|
),
|
||||||
|
("document", Some(id)) => (
|
||||||
|
"Document".to_string(),
|
||||||
|
format!("/people/{person}/documents#doc-{id}"),
|
||||||
|
),
|
||||||
|
(other, _) => (other.to_string(), format!("/people/{person}/activity")),
|
||||||
|
};
|
||||||
|
// a new document's fields say only what was set; its kind is enough
|
||||||
|
let fields = if c.entity == "document" {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
c.fields.join(", ").replace('_', " ")
|
||||||
|
};
|
||||||
|
ChangeView {
|
||||||
|
label,
|
||||||
|
href,
|
||||||
|
fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn link_view(st: &AppState, l: &Link) -> anyhow::Result<LinkView> {
|
||||||
|
let now = Utc::now();
|
||||||
|
let state = l.state(now);
|
||||||
|
let changes = links::changes(&st.db, l.id)
|
||||||
|
.await?
|
||||||
|
.iter()
|
||||||
|
.map(|c| change_view(l.person_id, c))
|
||||||
|
.collect();
|
||||||
|
Ok(LinkView {
|
||||||
|
id: l.id,
|
||||||
|
state: state.label(),
|
||||||
|
level: state.level(),
|
||||||
|
usable: l.usable(now),
|
||||||
|
made: dates::fmt_datetime(l.created_at),
|
||||||
|
by: l.created_by.clone(),
|
||||||
|
until: links::day(l.expires_at),
|
||||||
|
opened: l.first_used_at.map(dates::fmt_datetime).unwrap_or_default(),
|
||||||
|
sent: l.sent_at.map(dates::fmt_datetime).unwrap_or_default(),
|
||||||
|
closed: match (l.sent_at, l.closed_at) {
|
||||||
|
(None, Some(t)) => format!("{} by {}", dates::fmt_datetime(t), l.closed_by),
|
||||||
|
_ => String::new(),
|
||||||
|
},
|
||||||
|
changes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The person page's card: the newest links, each with what the client
|
||||||
|
/// changed through it.
|
||||||
|
pub async fn card(st: &AppState, person: i64) -> anyhow::Result<Vec<LinkView>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for l in links::for_person(&st.db, person).await?.iter().take(3) {
|
||||||
|
out.push(link_view(st, l).await?);
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log<'a>(user: &'a User, action: Action, link: i64, person: i64) -> Entry<'a> {
|
||||||
|
Entry {
|
||||||
|
actor: &user.login,
|
||||||
|
action,
|
||||||
|
entity: Entity::Link,
|
||||||
|
entity_id: Some(link),
|
||||||
|
person_id: Some(person),
|
||||||
|
company_id: None,
|
||||||
|
fields: &[],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The link as a QR code, an SVG for the page (no script, no style).
|
||||||
|
fn qr_svg(url: &str) -> String {
|
||||||
|
match QrCode::new(url.as_bytes()) {
|
||||||
|
Ok(code) => {
|
||||||
|
let svg = code
|
||||||
|
.render::<svg::Color>()
|
||||||
|
.min_dimensions(220, 220)
|
||||||
|
.dark_color(svg::Color("#071323"))
|
||||||
|
.light_color(svg::Color("#ffffff"))
|
||||||
|
.build();
|
||||||
|
// the page holds it inline: without the XML declaration
|
||||||
|
match svg.find("<svg") {
|
||||||
|
Some(i) => svg[i..].to_string(),
|
||||||
|
None => svg,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(_) => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The page right after a link is made: the only time the link is shown.
|
||||||
|
fn made_page(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
p: &PersonView,
|
||||||
|
link: &Link,
|
||||||
|
token: &str,
|
||||||
|
email: &str,
|
||||||
|
) -> Response {
|
||||||
|
let url = format!("{}/c/{token}", st.cfg.public_url);
|
||||||
|
let mail = if email.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
let body = format!(
|
||||||
|
"Hello,\n\nplease fill in your details for your visa and stay in Thailand here:\n\n{url}\n\n\
|
||||||
|
The link works until {}. Each part is saved on its own; press Send when you are done.\n",
|
||||||
|
links::day(link.expires_at)
|
||||||
|
);
|
||||||
|
format!(
|
||||||
|
"mailto:{email}?subject={}&body={}",
|
||||||
|
percent_encode("Your details for B4L"),
|
||||||
|
percent_encode(&body)
|
||||||
|
)
|
||||||
|
};
|
||||||
|
page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
"link_made.html",
|
||||||
|
&format!("Link for {}", p.name),
|
||||||
|
"people",
|
||||||
|
StatusCode::OK,
|
||||||
|
context! {
|
||||||
|
p, tab => "overview", url, qr => qr_svg(&url), mail,
|
||||||
|
until => links::day(link.expires_at),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((p, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
let (link, token) = links::create(&mut tx, id, &user.login).await?;
|
||||||
|
audit::record(&mut *tx, &log(&user, Action::Create, link.id, id)).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(made_page(&st, &user, &view, &link, &token, &p.email))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn close(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, lid)): Path<(i64, i64)>,
|
||||||
|
) -> Res {
|
||||||
|
if links::get(&st.db, id, lid).await?.is_none() {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
}
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if links::close(&mut tx, lid, &user.login, false).await? {
|
||||||
|
audit::record(&mut *tx, &log(&user, Action::Close, lid, id)).await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}#client-link")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ new client
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Serialize)]
|
||||||
|
struct NewClient {
|
||||||
|
surname: String,
|
||||||
|
first_name: String,
|
||||||
|
email: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_client_page(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
f: &NewClient,
|
||||||
|
errors: &Errors,
|
||||||
|
status: StatusCode,
|
||||||
|
) -> Response {
|
||||||
|
page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
"new_client.html",
|
||||||
|
"New client",
|
||||||
|
"people",
|
||||||
|
status,
|
||||||
|
context! { f, errors },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn new_client_form(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
) -> Res {
|
||||||
|
Ok(new_client_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
&NewClient::default(),
|
||||||
|
&Errors::new(),
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new record with only the name staff know, and its link: the client
|
||||||
|
/// fills in the rest.
|
||||||
|
pub async fn new_client(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
let nc = NewClient {
|
||||||
|
surname: get(&f, "surname"),
|
||||||
|
first_name: get(&f, "first_name"),
|
||||||
|
email: get(&f, "email"),
|
||||||
|
};
|
||||||
|
let mut errors = Errors::new();
|
||||||
|
if nc.surname.is_empty() && nc.first_name.is_empty() {
|
||||||
|
err(
|
||||||
|
&mut errors,
|
||||||
|
"surname",
|
||||||
|
"Enter a name to find the record by; the client corrects it.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !nc.email.is_empty() && !people::looks_like_email(&nc.email) {
|
||||||
|
err(
|
||||||
|
&mut errors,
|
||||||
|
"email",
|
||||||
|
"This does not look like an email address.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !errors.is_empty() {
|
||||||
|
return Ok(new_client_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
&nc,
|
||||||
|
&errors,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let input = PersonInput {
|
||||||
|
surname: nc.surname.clone(),
|
||||||
|
first_name: nc.first_name.clone(),
|
||||||
|
middle_name: String::new(),
|
||||||
|
title: String::new(),
|
||||||
|
sex: String::new(),
|
||||||
|
date_of_birth: None,
|
||||||
|
place_of_birth: String::new(),
|
||||||
|
nationality: String::new(),
|
||||||
|
occupation: String::new(),
|
||||||
|
employer: None,
|
||||||
|
phone: String::new(),
|
||||||
|
email: nc.email.clone(),
|
||||||
|
notes: String::new(),
|
||||||
|
};
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
let id = people::create_person(&mut tx, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&Entry {
|
||||||
|
actor: &user.login,
|
||||||
|
action: Action::Create,
|
||||||
|
entity: Entity::Person,
|
||||||
|
entity_id: Some(id),
|
||||||
|
person_id: Some(id),
|
||||||
|
company_id: None,
|
||||||
|
fields: &[],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (link, token) = links::create(&mut tx, id, &user.login).await?;
|
||||||
|
audit::record(&mut *tx, &log(&user, Action::Create, link.id, id)).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
let Some((_, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
Ok(made_page(&st, &user, &view, &link, &token, &nc.email))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The kinds of document a client uploads, in the order they are asked for.
|
||||||
|
pub const CLIENT_KINDS: &[&str] = &[
|
||||||
|
"passport-photo-page",
|
||||||
|
"photo",
|
||||||
|
"visa",
|
||||||
|
"arrival-stamp",
|
||||||
|
"tdac",
|
||||||
|
"work-permit",
|
||||||
|
"other",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The kinds for the client's selection, with the app's labels.
|
||||||
|
pub fn client_kinds() -> Vec<(&'static str, String)> {
|
||||||
|
CLIENT_KINDS
|
||||||
|
.iter()
|
||||||
|
.map(|k| (*k, documents::kind_label(documents::Owner::Person(0), k)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
+39
-2
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
pub mod activity;
|
pub mod activity;
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
|
pub mod client;
|
||||||
pub mod companies;
|
pub mod companies;
|
||||||
pub mod dashboard;
|
pub mod dashboard;
|
||||||
pub mod documents;
|
pub mod documents;
|
||||||
|
pub mod links;
|
||||||
pub mod pack;
|
pub mod pack;
|
||||||
pub mod papers;
|
pub mod papers;
|
||||||
pub mod people;
|
pub mod people;
|
||||||
@@ -133,6 +135,12 @@ pub fn router(st: Arc<AppState>) -> Router {
|
|||||||
.route("/", get(dashboard::page_handler))
|
.route("/", get(dashboard::page_handler))
|
||||||
.route("/people", get(p::list).post(p::create))
|
.route("/people", get(p::list).post(p::create))
|
||||||
.route("/people/new", get(p::new_form))
|
.route("/people/new", get(p::new_form))
|
||||||
|
.route(
|
||||||
|
"/people/new-client",
|
||||||
|
get(links::new_client_form).post(links::new_client),
|
||||||
|
)
|
||||||
|
.route("/people/{id}/links", post(links::create))
|
||||||
|
.route("/people/{id}/links/{lid}/close", post(links::close))
|
||||||
.route("/people/{id}", get(p::show).post(p::update))
|
.route("/people/{id}", get(p::show).post(p::update))
|
||||||
.route("/people/{id}/edit", get(p::edit_form))
|
.route("/people/{id}/edit", get(p::edit_form))
|
||||||
.route("/people/{id}/archive", post(p::archive))
|
.route("/people/{id}/archive", post(p::archive))
|
||||||
@@ -307,6 +315,32 @@ pub fn router(st: Arc<AppState>) -> Router {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// The client's pages: open without a login, each checks its link.
|
||||||
|
r = r
|
||||||
|
.route("/c/{token}", get(client::overview))
|
||||||
|
.route(
|
||||||
|
"/c/{token}/about",
|
||||||
|
get(client::about).post(client::about_save),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/c/{token}/contact",
|
||||||
|
get(client::contact).post(client::contact_save),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/c/{token}/passport",
|
||||||
|
get(client::passport).post(client::passport_save),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/c/{token}/address",
|
||||||
|
get(client::address).post(client::address_save),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/c/{token}/documents",
|
||||||
|
get(client::documents_get)
|
||||||
|
.post(client::documents_upload)
|
||||||
|
.layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)),
|
||||||
|
)
|
||||||
|
.route("/c/{token}/send", post(client::send));
|
||||||
r.route("/activity", get(activity::page))
|
r.route("/activity", get(activity::page))
|
||||||
.route("/login", get(auth::login))
|
.route("/login", get(auth::login))
|
||||||
.route("/auth/callback", get(auth::callback))
|
.route("/auth/callback", get(auth::callback))
|
||||||
@@ -327,12 +361,14 @@ pub fn router(st: Arc<AppState>) -> Router {
|
|||||||
.with_state(st)
|
.with_state(st)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Paths open without a session.
|
/// Paths open without a session: the client's pages (`/c/<token>`, which
|
||||||
|
/// check their link themselves) among them.
|
||||||
fn is_public(path: &str) -> bool {
|
fn is_public(path: &str) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
path,
|
path,
|
||||||
"/healthz" | "/version" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico"
|
"/healthz" | "/version" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico"
|
||||||
) || path.starts_with("/static/")
|
) || path.starts_with("/static/")
|
||||||
|
|| path.starts_with("/c/")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lets a request through with its user, or sends the browser to the login.
|
/// Lets a request through with its user, or sends the browser to the login.
|
||||||
@@ -394,7 +430,8 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
let Some(user) = req.extensions().get::<User>().cloned() else {
|
let Some(user) = req.extensions().get::<User>().cloned() else {
|
||||||
// public paths take no forms
|
// public paths take no forms but the client's, which check the
|
||||||
|
// link's own token (`web::client`)
|
||||||
return next.run(req).await;
|
return next.run(req).await;
|
||||||
};
|
};
|
||||||
let multipart = req
|
let multipart = req
|
||||||
|
|||||||
+5
-3
@@ -162,7 +162,7 @@ pub async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Perso
|
|||||||
Ok(Some((p, view)))
|
Ok(Some((p, view)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn select_lists() -> minijinja::Value {
|
pub(crate) fn select_lists() -> minijinja::Value {
|
||||||
context! {
|
context! {
|
||||||
titles => TITLES,
|
titles => TITLES,
|
||||||
sexes => SEXES,
|
sexes => SEXES,
|
||||||
@@ -203,7 +203,7 @@ fn log<'a>(
|
|||||||
/// (`mrz::from_ocr`: lines in any order, look-alike characters) replaces
|
/// (`mrz::from_ocr`: lines in any order, look-alike characters) replaces
|
||||||
/// it, if that one matches or the text was no zone at all. A text that
|
/// it, if that one matches or the text was no zone at all. A text that
|
||||||
/// holds no zone becomes a field error.
|
/// holds no zone becomes a field error.
|
||||||
fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
pub(crate) fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||||
if text.is_empty() {
|
if text.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -229,7 +229,7 @@ fn read_zone(text: &mut String, today: NaiveDate, errors: &mut Errors) -> Option
|
|||||||
|
|
||||||
/// `photo`: the lines came from the photo reader (the form's
|
/// `photo`: the lines came from the photo reader (the form's
|
||||||
/// `mrz_source`), whose names have no check digit to catch a misread.
|
/// `mrz_source`), whose names have no check digit to catch a misread.
|
||||||
fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option<String> {
|
pub(crate) fn zone_note(m: &Mrz, photo: bool, errors: &mut Errors) -> Option<String> {
|
||||||
match (m.all_ok(), photo) {
|
match (m.all_ok(), photo) {
|
||||||
(true, false) => {
|
(true, false) => {
|
||||||
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
||||||
@@ -358,6 +358,7 @@ pub async fn show(
|
|||||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||||
let recent = audit::recent(&st.db, Some(id), 6).await?;
|
let recent = audit::recent(&st.db, Some(id), 6).await?;
|
||||||
let docs = super::documents::chips(&st, id).await?;
|
let docs = super::documents::chips(&st, id).await?;
|
||||||
|
let client_links = super::links::card(&st, id).await?;
|
||||||
let title = view.name.clone();
|
let title = view.name.clone();
|
||||||
Ok(page(
|
Ok(page(
|
||||||
&st,
|
&st,
|
||||||
@@ -373,6 +374,7 @@ pub async fn show(
|
|||||||
addresses,
|
addresses,
|
||||||
docs,
|
docs,
|
||||||
recent,
|
recent,
|
||||||
|
client_links,
|
||||||
stay => assessment.stay,
|
stay => assessment.stay,
|
||||||
deadlines => assessment.items,
|
deadlines => assessment.items,
|
||||||
},
|
},
|
||||||
|
|||||||
+112
@@ -1389,3 +1389,115 @@ textarea.mrz {
|
|||||||
gap: 12px;
|
gap: 12px;
|
||||||
padding: 16px 16px max(16px, env(safe-area-inset-bottom));
|
padding: 16px 16px max(16px, env(safe-area-inset-bottom));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- the client link: the card on a person's page and the page that
|
||||||
|
shows a new link once */
|
||||||
|
.chip.plain {
|
||||||
|
background: var(--panel2);
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
.changes {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
}
|
||||||
|
.linkrow {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
.linkrow input {
|
||||||
|
flex: 1 1 280px;
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.qr {
|
||||||
|
width: 240px;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
margin: 4px 0 14px;
|
||||||
|
background: #ffffff;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
.qr svg {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- the client's pages (/c/<token>): one column, phone first */
|
||||||
|
.cmain {
|
||||||
|
max-width: 680px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px 16px 40px;
|
||||||
|
}
|
||||||
|
.cmain .card {
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.chead {
|
||||||
|
margin: 4px 0 8px;
|
||||||
|
}
|
||||||
|
.lead2 {
|
||||||
|
margin: 0 0 16px;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
.parts {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 16px;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.part {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 32px minmax(0, 1fr) auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px 12px;
|
||||||
|
padding: 14px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--panel);
|
||||||
|
color: var(--fg);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.part:hover {
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
.pmark {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
font-weight: 700;
|
||||||
|
background: var(--panel2);
|
||||||
|
color: var(--hd);
|
||||||
|
}
|
||||||
|
.part.done .pmark {
|
||||||
|
background: var(--ok-s);
|
||||||
|
color: var(--ok);
|
||||||
|
}
|
||||||
|
.pbody {
|
||||||
|
display: grid;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
/* on phones the state goes under the text */
|
||||||
|
@media (max-width: 520px) {
|
||||||
|
.part {
|
||||||
|
grid-template-columns: 32px minmax(0, 1fr);
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.part .chip {
|
||||||
|
grid-column: 2;
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.sendcard h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.cmain .upload .field {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.cmain .upload .drop {
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
@@ -18,6 +18,32 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---- a button with data-copy="#input" copies that input's text (the
|
||||||
|
// client link); a field with data-select-all selects itself when focused
|
||||||
|
document.addEventListener("click", function (ev) {
|
||||||
|
var b = ev.target.closest && ev.target.closest("[data-copy]");
|
||||||
|
if (!b) return;
|
||||||
|
var input = document.querySelector(b.getAttribute("data-copy"));
|
||||||
|
if (!input) return;
|
||||||
|
input.select();
|
||||||
|
var done = function () {
|
||||||
|
b.textContent = "Copied";
|
||||||
|
};
|
||||||
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
|
navigator.clipboard.writeText(input.value).then(done, function () {
|
||||||
|
document.execCommand("copy");
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
document.execCommand("copy");
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener("focusin", function (ev) {
|
||||||
|
var t = ev.target;
|
||||||
|
if (t && t.hasAttribute && t.hasAttribute("data-select-all")) t.select();
|
||||||
|
});
|
||||||
|
|
||||||
// ---- forms with data-confirm ask first (archive, delete)
|
// ---- forms with data-confirm ask first (archive, delete)
|
||||||
document.addEventListener("submit", function (ev) {
|
document.addEventListener("submit", function (ev) {
|
||||||
var f = ev.target;
|
var f = ev.target;
|
||||||
|
|||||||
+45
-9
@@ -481,6 +481,16 @@
|
|||||||
// the variance of the band's Laplacian below which it is not sharp yet,
|
// the variance of the band's Laplacian below which it is not sharp yet,
|
||||||
// measured on the band scaled to 320 pixels across
|
// measured on the band scaled to 320 pixels across
|
||||||
var SHARP = 150;
|
var SHARP = 150;
|
||||||
|
// The photo takes itself only once the band has looked readable and the
|
||||||
|
// picture has stood still for HOLD checks in a row (one every 250 ms, so
|
||||||
|
// 2.5 s), and never in the first START ms, while the passport is still
|
||||||
|
// being put into the frame. A second was too quick on a phone: it took
|
||||||
|
// the photo while the hand still moved.
|
||||||
|
var HOLD = 10;
|
||||||
|
var START = 1500;
|
||||||
|
// the mean change of a band pixel from one check to the next (0 to 255)
|
||||||
|
// above which the picture still moves
|
||||||
|
var STILL = 6;
|
||||||
|
|
||||||
// What is wrong with the band in the picture, or "" when it looks
|
// What is wrong with the band in the picture, or "" when it looks
|
||||||
// readable: too dark, glare, no lines in it, or not sharp.
|
// readable: too dark, glare, no lines in it, or not sharp.
|
||||||
@@ -512,18 +522,28 @@
|
|||||||
}
|
}
|
||||||
var sharp = n ? s2 / n - (s1 / n) * (s1 / n) : 0;
|
var sharp = n ? s2 / n - (s1 / n) * (s1 / n) : 0;
|
||||||
var m = { mean: Math.round(mean), glare: bright / g.length, ink: ink / g.length, sharp: Math.round(sharp) };
|
var m = { mean: Math.round(mean), glare: bright / g.length, ink: ink / g.length, sharp: Math.round(sharp) };
|
||||||
if (mean < 50) return { why: "Too dark: find more light.", m: m };
|
if (mean < 50) return { why: "Too dark: find more light.", m: m, g: g };
|
||||||
if (m.glare > 0.02) {
|
if (m.glare > 0.02) {
|
||||||
return {
|
return {
|
||||||
why: "Glare on the two lines: tilt the passport a little, or turn away from the lamp.",
|
why: "Glare on the two lines: tilt the passport a little, or turn away from the lamp.",
|
||||||
m: m,
|
m: m,
|
||||||
|
g: g,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (m.ink < 0.04) {
|
if (m.ink < 0.04) {
|
||||||
return { why: "Put the two lines at the bottom of the photo page into the yellow band.", m: m };
|
return { why: "Put the two lines at the bottom of the photo page into the yellow band.", m: m, g: g };
|
||||||
}
|
}
|
||||||
if (sharp < SHARP) return { why: "Hold still: the lines are not sharp yet.", m: m };
|
if (sharp < SHARP) return { why: "Hold still: the lines are not sharp yet.", m: m, g: g };
|
||||||
return { why: "", m: m };
|
return { why: "", m: m, g: g };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The mean change of a pixel between two looks at the band; Infinity
|
||||||
|
// when there is no earlier look of the same size.
|
||||||
|
function moved(a, b) {
|
||||||
|
if (!a || !b || a.length !== b.length) return Infinity;
|
||||||
|
var sum = 0;
|
||||||
|
for (var i = 0; i < a.length; i++) sum += Math.abs(a[i] - b[i]);
|
||||||
|
return sum / a.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
function el(tag, cls, text) {
|
function el(tag, cls, text) {
|
||||||
@@ -621,6 +641,8 @@
|
|||||||
|
|
||||||
var timer = 0;
|
var timer = 0;
|
||||||
var good = 0;
|
var good = 0;
|
||||||
|
var last = null;
|
||||||
|
var opened = Date.now();
|
||||||
var done = false;
|
var done = false;
|
||||||
var small = canvas(320, 80);
|
var small = canvas(320, 80);
|
||||||
var sctx = small.getContext("2d", { willReadFrequently: true });
|
var sctx = small.getContext("2d", { willReadFrequently: true });
|
||||||
@@ -658,12 +680,26 @@
|
|||||||
small.height = Math.max(8, Math.round((bh * 320) / bw));
|
small.height = Math.max(8, Math.round((bh * 320) / bw));
|
||||||
sctx.drawImage(video, bx, by, bw, bh, 0, 0, 320, small.height);
|
sctx.drawImage(video, bx, by, bw, bh, 0, 0, 320, small.height);
|
||||||
var j = judge(sctx, 320, small.height);
|
var j = judge(sctx, 320, small.height);
|
||||||
hint.textContent = j.why || "Good. Hold still...";
|
var change = moved(last, j.g);
|
||||||
root.classList.toggle("good", !j.why);
|
last = j.g;
|
||||||
|
j.m.moved = Math.round(change * 10) / 10;
|
||||||
|
// the first look has nothing to compare with: not still yet, but
|
||||||
|
// nothing to say about it either
|
||||||
|
var why = j.why || (change > STILL && change !== Infinity ? "Hold still: the picture still moves." : "");
|
||||||
|
var early = Date.now() - opened < START;
|
||||||
|
good = why || early || change > STILL ? 0 : good + 1;
|
||||||
|
if (why) {
|
||||||
|
hint.textContent = why;
|
||||||
|
} else if (early) {
|
||||||
|
hint.textContent = "Good. Hold still...";
|
||||||
|
} else {
|
||||||
|
var left = Math.max(1, Math.ceil(((HOLD - good) * 250) / 1000));
|
||||||
|
hint.textContent = "Good. Hold still: the photo is taken in " + left + " s, or press Take the photo.";
|
||||||
|
}
|
||||||
|
root.classList.toggle("good", !why);
|
||||||
root.setAttribute("data-measure", JSON.stringify(j.m));
|
root.setAttribute("data-measure", JSON.stringify(j.m));
|
||||||
good = j.why ? 0 : good + 1;
|
// a readable band that stands still for HOLD checks takes the photo
|
||||||
// a steady, readable band for about a second takes the photo
|
if (good >= HOLD) {
|
||||||
if (good >= 4) {
|
|
||||||
take();
|
take();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% block main %}
|
||||||
|
<h1 class="chead">{% if first_name %}Hello {{ first_name }}{% else %}Hello{% endif %}</h1>
|
||||||
|
<p class="lead2">B4L looks after your visa and your stay in Thailand. Fill in the parts below. Each part is saved on its own, so you can stop and come back to this link. When everything is in, press Send.</p>
|
||||||
|
{% if saved %}<div class="notice ok" role="status">Saved: {{ saved }}.</div>{% endif %}
|
||||||
|
<ol class="parts">
|
||||||
|
{% for p in parts %}
|
||||||
|
<li>
|
||||||
|
<a class="part{% if p.done %} done{% endif %}" href="{{ base }}/{{ p.slug }}" id="part-{{ p.slug }}">
|
||||||
|
<span class="pmark" aria-hidden="true">{% if p.done %}✓{% else %}{{ loop.index }}{% endif %}</span>
|
||||||
|
<span class="pbody"><b>{{ p.title }}</b><span class="muted small">{{ p.what }}</span></span>
|
||||||
|
<span class="chip {% if p.done %}ok{% else %}warn{% endif %}">{{ p.status }}</span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ol>
|
||||||
|
<form method="post" action="{{ base }}/send" class="card sendcard" id="send"{% if missing %} data-confirm="Still to do: {{ missing|join(", ") }}. Send anyway? The link closes once it is sent."{% else %} data-confirm="Send your details to B4L? The link closes once it is sent."{% endif %}>
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<h2>Send</h2>
|
||||||
|
<p class="muted">{% if missing %}Still to do: {{ missing|join(", ") }}. You can send now and give the rest to B4L later.{% else %}Everything is in. Send it, and B4L checks it.{% endif %} After Send the link closes.</p>
|
||||||
|
<button type="submit" class="btn pri" id="send-btn">Send to B4L</button>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="crumbs"><a href="{{ base }}">Your details</a></div>
|
||||||
|
<h1 class="chead">About you</h1>
|
||||||
|
<form method="post" action="{{ base }}/about" class="form" id="about-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<section class="card">
|
||||||
|
<p class="hint lead">Write your names exactly as the passport prints them.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("surname", "Surname", f.surname, err=errors.surname, req=true, auto="family-name") }}
|
||||||
|
{{ fm.text("first_name", "First name", f.first_name, err=errors.first_name, req=true, auto="given-name") }}
|
||||||
|
{{ fm.text("middle_name", "Middle names", f.middle_name, err=errors.middle_name, auto="additional-name") }}
|
||||||
|
{{ fm.select("title", "Title", f.title, titles, err=errors.title, blank="Choose") }}
|
||||||
|
{{ fm.select("sex", "Sex", f.sex, sexes, err=errors.sex, blank="Choose") }}
|
||||||
|
{{ fm.text("date_of_birth", "Date of birth", f.date_of_birth, err=errors.date_of_birth, type="date", auto="bday") }}
|
||||||
|
{{ fm.text("place_of_birth", "Place of birth", f.place_of_birth, err=errors.place_of_birth, hint="As in the passport.") }}
|
||||||
|
{{ fm.select("nationality", "Nationality", f.nationality, countries, err=errors.nationality, blank="Choose a country") }}
|
||||||
|
{{ fm.text("occupation", "Occupation", f.occupation, err=errors.occupation, cls="wide") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" class="btn pri" id="save">Save</button>
|
||||||
|
<a class="btn ghost" href="{{ base }}">Back</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="crumbs"><a href="{{ base }}">Your details</a></div>
|
||||||
|
<h1 class="chead">Address in Thailand</h1>
|
||||||
|
<form method="post" action="{{ base }}/address" class="form" id="address-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<section class="card">
|
||||||
|
<p class="hint lead">Where you live now, in the order Thai forms use. Leave out what your address does not have.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("house_no", "House number", af.house_no, err=errors.house_no, ph="99/9") }}
|
||||||
|
{{ fm.text("moo", "Moo (village number)", af.moo, err=errors.moo) }}
|
||||||
|
{{ fm.text("building", "Village, building or condominium", af.building, err=errors.building, hint="With the room number, if any.", cls="wide") }}
|
||||||
|
{{ fm.text("soi", "Soi", af.soi, err=errors.soi) }}
|
||||||
|
{{ fm.text("road", "Road", af.road, err=errors.road) }}
|
||||||
|
{{ fm.text("subdistrict", "Subdistrict (tambon)", af.subdistrict, err=errors.subdistrict) }}
|
||||||
|
{{ fm.text("district", "District (amphoe)", af.district, err=errors.district, req=true) }}
|
||||||
|
{{ fm.text("province", "Province", af.province, err=errors.province, req=true, list="provinces") }}
|
||||||
|
{{ fm.text("postal_code", "Postal code", af.postal_code, err=errors.postal_code, auto="postal-code") }}
|
||||||
|
{{ fm.text("moved_in_on", "Moved in on", af.moved_in_on, err=errors.moved_in_on, type="date") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>House owner or landlord</h2></header>
|
||||||
|
<p class="hint lead">They report your address to Immigration (form TM.30) after you move in and after every trip abroad.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("house_master", "Name", af.house_master, err=errors.house_master) }}
|
||||||
|
{{ fm.text("house_master_phone", "Phone", af.house_master_phone, err=errors.house_master_phone, type="tel") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" class="btn pri" id="save">Save</button>
|
||||||
|
<a class="btn ghost" href="{{ base }}">Back</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<datalist id="provinces">{% for pv in provinces %}<option value="{{ pv }}"></option>{% endfor %}</datalist>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="robots" content="noindex,nofollow">
|
||||||
|
<meta name="referrer" content="no-referrer">
|
||||||
|
<title>{{ title }} · B4L</title>
|
||||||
|
<script src="/static/theme-init.js?v={{ v }}"></script>
|
||||||
|
<link rel="icon" href="/static/favicon.svg?v={{ v }}" type="image/svg+xml">
|
||||||
|
<link rel="stylesheet" href="/static/app.css?v={{ v }}">
|
||||||
|
<script src="/static/app.js?v={{ v }}" defer></script>
|
||||||
|
</head>
|
||||||
|
<body class="client">
|
||||||
|
{#- The client's own frame: no sections, no sign-in, nothing of the
|
||||||
|
staff's app. Every page of the link links back to its start. #}
|
||||||
|
<header class="top">
|
||||||
|
{% if base %}<a class="brand" href="{{ base }}" aria-label="Your details, the start">{% else %}<span class="brand">{% endif %}
|
||||||
|
{% include "_mark.html" %}
|
||||||
|
<span class="nm">Visa</span><span class="sub">B4L</span>
|
||||||
|
{% if base %}</a>{% else %}</span>{% endif %}
|
||||||
|
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
||||||
|
</header>
|
||||||
|
<main class="cmain" id="main">
|
||||||
|
{% block main %}{% endblock %}
|
||||||
|
{% if until %}<footer class="ft">This link works until {{ until }}. What you save here goes to B4L, who look after your visa and stay in Thailand; nobody else sees it.</footer>{% endif %}
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="card">
|
||||||
|
<h1>{{ title }}</h1>
|
||||||
|
<p>{{ text }}</p>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="crumbs"><a href="{{ base }}">Your details</a></div>
|
||||||
|
<h1 class="chead">Contact</h1>
|
||||||
|
<form method="post" action="{{ base }}/contact" class="form" id="contact-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<section class="card">
|
||||||
|
<p class="hint lead">B4L uses them to reach you about your visa and your deadlines.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("phone", "Phone", f.phone, err=errors.phone, type="tel", auto="tel", hint="With the country code if it is not a Thai number.") }}
|
||||||
|
{{ fm.text("email", "Email", f.email, err=errors.email, type="email", auto="email") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" class="btn pri" id="save">Save</button>
|
||||||
|
<a class="btn ghost" href="{{ base }}">Back</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="crumbs"><a href="{{ base }}">Your details</a></div>
|
||||||
|
<h1 class="chead">Documents</h1>
|
||||||
|
<p class="lead2">Scans or photos of your papers: the passport's photo page, a passport photo (4 x 6 cm), your visa, the arrival stamp, the TDAC, the work permit. Upload one kind at a time.</p>
|
||||||
|
{% if files_on %}
|
||||||
|
<form method="post" action="{{ base }}/documents" enctype="multipart/form-data" class="upload card" id="upload">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
{%- if errors %}
|
||||||
|
<div class="notice warn">Nothing was uploaded. Correct what is marked and choose the files again.</div>
|
||||||
|
{%- endif %}
|
||||||
|
{{ fm.select("kind", "What the files are", v.kind, kinds, err=errors.kind, blank="Choose", req=true) }}
|
||||||
|
<div class="drop{% if errors.file %} has-err{% endif %}" data-max="{{ file_limit }}">
|
||||||
|
<input type="file" id="f-file" name="file" multiple required accept="application/pdf,image/jpeg,image/png,image/webp" aria-describedby="h-file{% if errors.file %} e-file{% endif %}">
|
||||||
|
<span class="drop-icon" aria-hidden="true">+</span>
|
||||||
|
<label for="f-file"><b>Choose files</b> or take a photo</label>
|
||||||
|
<span class="drop-names" data-drop-names></span>
|
||||||
|
<span class="hint" id="h-file">PDF, JPEG, PNG or WebP, up to {{ file_limit_mb }} MB each, {{ max_files }} at once</span>
|
||||||
|
</div>
|
||||||
|
{%- if errors.file %}
|
||||||
|
<p class="err" id="e-file">{{ errors.file }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
{{ fm.text("note", "Note", v.note, err=errors.note, ph="page 2") }}
|
||||||
|
<div class="formactions"><button type="submit" class="btn pri" id="upload-btn">Upload</button><a class="btn ghost" href="{{ base }}">Back</a></div>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<div class="notice warn">Uploads are switched off on this server. Give your papers to B4L instead.</div>
|
||||||
|
{% endif %}
|
||||||
|
<section class="card" id="uploaded">
|
||||||
|
<header><h2>Uploaded through this link</h2></header>
|
||||||
|
{% for d in uploaded %}
|
||||||
|
<div class="item"><div class="row"><b>{{ d.label }}</b><span class="muted small">{{ d.at }}</span></div><div class="muted small fname">{{ d.file_name }}, {{ d.size }}</div></div>
|
||||||
|
{% else %}
|
||||||
|
<p class="empty-inline">Nothing yet.</p>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
{% extends "client_base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="crumbs"><a href="{{ base }}">Your details</a></div>
|
||||||
|
<h1 class="chead">Passport</h1>
|
||||||
|
<form method="post" action="{{ base }}/passport" class="form" id="passport-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<button type="submit" name="action" value="save" class="default-submit" tabindex="-1" aria-hidden="true">Save</button>
|
||||||
|
<section class="card" id="mrz-card">
|
||||||
|
<header><h2>Read the passport</h2></header>
|
||||||
|
<p class="hint lead">Take a photo of the passport's photo page: the two lines of letters and <<< at its bottom fill in the form. The photo stays on your phone; only the two lines are sent. You can also type the lines and press Read.</p>
|
||||||
|
{{ fm.area("mrz", "The two lines at the bottom of the photo page", pf.mrz, err=errors.mrz, rows=2, cls="mrz") }}
|
||||||
|
<div class="formactions">
|
||||||
|
{% include "_mrz_photo.html" %}
|
||||||
|
<button type="submit" name="action" value="read-mrz" class="btn" id="read-mrz" formnovalidate>Read</button>
|
||||||
|
{% if mrz_note %}<p class="okline" role="status">{{ mrz_note }}</p>{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>Passport</h2></header>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("number", "Passport number", pf.number, err=errors.number, req=true) }}
|
||||||
|
{{ fm.select("issuing_country", "Issued by", pf.issuing_country, countries, err=errors.issuing_country, blank="Choose a country") }}
|
||||||
|
{{ fm.text("issued_on", "Date of issue", pf.issued_on, err=errors.issued_on, type="date") }}
|
||||||
|
{{ fm.text("expires_on", "Date of expiry", pf.expires_on, err=errors.expires_on, type="date", req=true) }}
|
||||||
|
{{ fm.text("issued_at", "Authority or place of issue", pf.issued_at, err=errors.issued_at, hint="As printed in the passport.", cls="wide") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" name="action" value="save" class="btn pri" id="save">Save</button>
|
||||||
|
<a class="btn ghost" href="{{ base }}">Back</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block main %}
|
||||||
|
{% include "_person_head.html" %}
|
||||||
|
<section class="card linkcard" id="link-made">
|
||||||
|
<header><h2>The client's link</h2></header>
|
||||||
|
<p>Give this link to {{ p.name }}: by email or chat, or let them scan the code with their phone. It works until {{ until }}, or until they press Send.</p>
|
||||||
|
<div class="linkrow">
|
||||||
|
<input type="text" readonly value="{{ url }}" id="link-url" aria-label="The link" data-select-all>
|
||||||
|
<button type="button" class="btn" data-copy="#link-url">Copy</button>
|
||||||
|
{% if mail %}<a class="btn" href="{{ mail }}">Email it</a>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if qr %}<div class="qr" aria-label="The link as a QR code">{{ qr|safe }}</div>{% endif %}
|
||||||
|
<p class="notice warn">The link is shown only now: the app keeps only a fingerprint of it. Copy it before you leave this page; otherwise make a new one, which closes this one.</p>
|
||||||
|
<div class="formactions"><a class="btn pri" href="/people/{{ p.id }}#client-link">Done</a></div>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="crumbs"><a href="/people">People</a></div>
|
||||||
|
<div class="pagehead"><h1>New client</h1></div>
|
||||||
|
<form method="post" action="/people/new-client" class="form" id="new-client-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<section class="card">
|
||||||
|
<p class="hint lead">A new record with the name you know, and a link for the client: they fill in the rest themselves, with the passport from a photo. The link works for 14 days, or until they press Send.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("surname", "Surname", f.surname, err=errors.surname) }}
|
||||||
|
{{ fm.text("first_name", "First name", f.first_name, err=errors.first_name) }}
|
||||||
|
{{ fm.text("email", "Email", f.email, err=errors.email, type="email", hint="Optional: the next page then offers an email with the link.") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" class="btn pri" id="save">Make the record and its link</button>
|
||||||
|
<a class="btn ghost" href="/people">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
{% block main %}
|
{% block main %}
|
||||||
<div class="pagehead">
|
<div class="pagehead">
|
||||||
<h1>{{ heading }}</h1>
|
<h1>{{ heading }}</h1>
|
||||||
<div class="actions"><a class="btn pri" href="/people/new" id="new-person">+ New person</a></div>
|
<div class="actions"><a class="btn" href="/people/new-client" id="new-client">+ New client</a><a class="btn pri" href="/people/new" id="new-person">+ New person</a></div>
|
||||||
</div>
|
</div>
|
||||||
{% if people or n_archived or company %}
|
{% if people or n_archived or company %}
|
||||||
<form method="get" action="/people" class="toolbar" id="people-filter">
|
<form method="get" action="/people" class="toolbar" id="people-filter">
|
||||||
|
|||||||
@@ -63,6 +63,30 @@
|
|||||||
{% endfor %}
|
{% endfor %}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="card" id="client-link">
|
||||||
|
<header><h2>Client link</h2>
|
||||||
|
<form method="post" action="/people/{{ p.id }}/links" class="inline-form"{% if client_links and client_links[0].usable %} data-confirm="Make a new link? The open one stops working."{% endif %}><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm" id="make-link">{% if client_links %}New link{% else %}Make a link{% endif %}</button></form>
|
||||||
|
</header>
|
||||||
|
{% for l in client_links %}
|
||||||
|
<div class="item{% if not loop.first %} old{% endif %}">
|
||||||
|
<div class="row">
|
||||||
|
<span class="chip {{ l.level }}">{{ l.state }}</span>
|
||||||
|
<span class="muted small">made {{ l.made }} by {{ l.by }}{% if l.usable %}, works until {{ l.until }}{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
<dl class="kv">
|
||||||
|
{% if l.opened %}<dt>Opened</dt><dd>{{ l.opened }}</dd>{% endif %}
|
||||||
|
{% if l.sent %}<dt>Sent</dt><dd>{{ l.sent }}</dd>{% endif %}
|
||||||
|
{% if l.closed %}<dt>Closed</dt><dd>{{ l.closed }}</dd>{% endif %}
|
||||||
|
{% if l.changes %}<dt>Changed</dt><dd><ul class="changes">{% for c in l.changes %}<li><a href="{{ c.href }}">{{ c.label }}</a>{% if c.fields %} <span class="muted">({{ c.fields }})</span>{% endif %}</li>{% endfor %}</ul></dd>{% endif %}
|
||||||
|
</dl>
|
||||||
|
{% if l.changes %}<p class="hint">The client's entries went straight into the record: check them against the papers.</p>{% endif %}
|
||||||
|
{% if l.usable %}<div class="rowactions"><form method="post" action="/people/{{ p.id }}/links/{{ l.id }}/close" class="inline-form" data-confirm="Close this link? The client can no longer use it."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="linkbtn">Close the link</button></form></div>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p class="empty-inline">A link lets the client fill in their own details, passport, address and scans from their phone, without a login. It works for 14 days, or until they press Send.</p>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="card" id="recent">
|
<section class="card" id="recent">
|
||||||
<header><h2>Recent activity</h2><a class="btn sm ghost" href="/activity?person={{ p.id }}">All of it</a></header>
|
<header><h2>Recent activity</h2><a class="btn sm ghost" href="/activity?person={{ p.id }}">All of it</a></header>
|
||||||
<ul class="log">
|
<ul class="log">
|
||||||
|
|||||||
+466
@@ -0,0 +1,466 @@
|
|||||||
|
//! The client link (phase 7): a link shown once and kept as a hash, the
|
||||||
|
//! client's pages open without a login and only through an open link, each
|
||||||
|
//! part saved straight into the record and logged as the link's, uploads
|
||||||
|
//! tied to their record, Send, and links that are closed, expired or made
|
||||||
|
//! up.
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use visa::config::Auth;
|
||||||
|
|
||||||
|
use crate::common::{App, Part, assert_unique_ids, erika_mrz, local, oidc_config, pdf, with_auth};
|
||||||
|
|
||||||
|
/// The token in the page that shows a new link.
|
||||||
|
fn token_in(html: &str) -> String {
|
||||||
|
let i = html.find("/c/").expect("no link on the page");
|
||||||
|
html[i + 3..]
|
||||||
|
.chars()
|
||||||
|
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A form of the client's page: the link's own token, from this site.
|
||||||
|
async fn send_form(app: &App, uri: &str, csrf: &str, form: &[(&str, &str)]) -> crate::common::Resp {
|
||||||
|
let mut pairs = form.to_vec();
|
||||||
|
pairs.push(("csrf", csrf));
|
||||||
|
app.post_raw(uri, &pairs, &[("sec-fetch-site", "same-origin")])
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn csrf_of(pool: &PgPool, link: i64) -> String {
|
||||||
|
sqlx::query_scalar("SELECT csrf FROM client_links WHERE id = $1")
|
||||||
|
.bind(link)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A person with only a name, and a link for them made as staff make it.
|
||||||
|
async fn person_with_link(pool: &PgPool) -> (i64, i64, String) {
|
||||||
|
let mut conn = pool.acquire().await.unwrap();
|
||||||
|
let person: i64 = sqlx::query_scalar(
|
||||||
|
"INSERT INTO people (surname, first_name) VALUES ('Becker', 'Hans') RETURNING id",
|
||||||
|
)
|
||||||
|
.fetch_one(&mut *conn)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (link, token) = visa::links::create(&mut conn, person, "grabowski")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
(person, link.id, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn audit_rows(pool: &PgPool, actor: &str) -> Vec<(String, String, Vec<String>)> {
|
||||||
|
sqlx::query_as("SELECT action, entity, fields FROM audit_log WHERE actor = $1 ORDER BY id")
|
||||||
|
.bind(actor)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn a_link_is_shown_once_and_kept_as_a_hash(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
"/people",
|
||||||
|
&[
|
||||||
|
("surname", "Becker"),
|
||||||
|
("first_name", "Hans"),
|
||||||
|
("email", "hans@example.com"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let person = crate::common::id_from(r.location());
|
||||||
|
|
||||||
|
let r = app.post(&format!("/people/{person}/links"), &[]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
let t = r.text();
|
||||||
|
assert!(t.contains("The link is shown only now"), "{t}");
|
||||||
|
assert!(t.contains("<svg"), "no QR code: {t}");
|
||||||
|
assert!(t.contains("mailto:hans@example.com?subject="), "{t}");
|
||||||
|
assert_unique_ids(&r.body, "link made");
|
||||||
|
let token = token_in(&t);
|
||||||
|
assert_eq!(token.len(), 43);
|
||||||
|
|
||||||
|
// the table holds the token's SHA-256 only
|
||||||
|
let (hash, by): (Vec<u8>, String) =
|
||||||
|
sqlx::query_as("SELECT token_hash, created_by FROM client_links WHERE person_id = $1")
|
||||||
|
.bind(person)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let want = ring::digest::digest(&ring::digest::SHA256, token.as_bytes());
|
||||||
|
assert_eq!(hash, want.as_ref());
|
||||||
|
assert_eq!(by, "local");
|
||||||
|
let dump: String = sqlx::query_scalar("SELECT string_agg(t::text, ' ') FROM client_links t")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(!dump.contains(&token));
|
||||||
|
|
||||||
|
// the person's page lists it; the client opens it
|
||||||
|
let page = app.get(&format!("/people/{person}")).await.text();
|
||||||
|
assert!(page.contains("id=\"client-link\""), "{page}");
|
||||||
|
assert!(page.contains(">open</span>"), "{page}");
|
||||||
|
assert_eq!(app.get(&format!("/c/{token}")).await.status, StatusCode::OK);
|
||||||
|
let page = app.get(&format!("/people/{person}")).await.text();
|
||||||
|
assert!(page.contains(">opened</span>"), "{page}");
|
||||||
|
|
||||||
|
// a new link closes the old one
|
||||||
|
let r = app.post(&format!("/people/{person}/links"), &[]).await;
|
||||||
|
let newer = token_in(&r.text());
|
||||||
|
let old = app.get(&format!("/c/{token}")).await;
|
||||||
|
assert_eq!(old.status, StatusCode::GONE);
|
||||||
|
assert!(old.text().contains("This link is closed"));
|
||||||
|
assert_eq!(app.get(&format!("/c/{newer}")).await.status, StatusCode::OK);
|
||||||
|
|
||||||
|
// staff close it
|
||||||
|
let lid: i64 = sqlx::query_scalar(
|
||||||
|
"SELECT id FROM client_links WHERE person_id = $1 ORDER BY id DESC LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(person)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let r = app
|
||||||
|
.post(&format!("/people/{person}/links/{lid}/close"), &[])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
assert_eq!(
|
||||||
|
app.get(&format!("/c/{newer}")).await.status,
|
||||||
|
StatusCode::GONE
|
||||||
|
);
|
||||||
|
let made: Vec<String> = sqlx::query_scalar(
|
||||||
|
"SELECT action FROM audit_log WHERE entity = 'link' AND actor = 'local' ORDER BY id",
|
||||||
|
)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(made, ["create", "create", "close"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn a_new_client_is_a_name_and_a_link(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let form = app.get("/people/new-client").await;
|
||||||
|
assert_eq!(form.status, StatusCode::OK);
|
||||||
|
let r = app.post("/people/new-client", &[]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(r.text().contains("Enter a name to find the record by"));
|
||||||
|
let r = app
|
||||||
|
.post("/people/new-client", &[("first_name", "Mai")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
let token = token_in(&r.text());
|
||||||
|
let name: String = sqlx::query_scalar("SELECT first_name FROM people")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(name, "Mai");
|
||||||
|
let c = app.get(&format!("/c/{token}")).await.text();
|
||||||
|
assert!(c.contains("Hello Mai"), "{c}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn the_client_fills_in_everything_without_a_login(pool: PgPool) {
|
||||||
|
// with the login on: the staff's pages need it, the client's do not
|
||||||
|
let app = with_auth(pool.clone(), Auth::Oidc(oidc_config("https://idp.test")));
|
||||||
|
let (person, link, token) = person_with_link(&pool).await;
|
||||||
|
let csrf = csrf_of(&pool, link).await;
|
||||||
|
let base = format!("/c/{token}");
|
||||||
|
assert!(
|
||||||
|
app.get(&format!("/people/{person}"))
|
||||||
|
.await
|
||||||
|
.location()
|
||||||
|
.starts_with("/login")
|
||||||
|
);
|
||||||
|
|
||||||
|
let r = app.get(&base).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK);
|
||||||
|
let t = r.text();
|
||||||
|
assert!(t.contains("Hello Hans"), "{t}");
|
||||||
|
assert!(
|
||||||
|
!t.contains("Sign out") && !t.contains("/activity"),
|
||||||
|
"staff frame on {t}"
|
||||||
|
);
|
||||||
|
assert_eq!(r.header("referrer-policy"), "same-origin");
|
||||||
|
for part in ["about", "contact", "passport", "address", "documents"] {
|
||||||
|
let r = app.get(&format!("{base}/{part}")).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{part}: {}", r.body);
|
||||||
|
assert_unique_ids(&r.body, part);
|
||||||
|
}
|
||||||
|
// the photo reader's page allows the camera and WebAssembly
|
||||||
|
let r = app.get(&format!("{base}/passport")).await;
|
||||||
|
assert!(r.header("permissions-policy").contains("camera=(self)"));
|
||||||
|
assert!(r.text().contains("data-mrz-camera"));
|
||||||
|
|
||||||
|
// about you: straight into the record, logged as the link's
|
||||||
|
let r = send_form(
|
||||||
|
&app,
|
||||||
|
&format!("{base}/about"),
|
||||||
|
&csrf,
|
||||||
|
&[
|
||||||
|
("surname", "Becker"),
|
||||||
|
("first_name", "Hans"),
|
||||||
|
("middle_name", "Peter"),
|
||||||
|
("sex", "M"),
|
||||||
|
("date_of_birth", "1990-02-03"),
|
||||||
|
("nationality", "DEU"),
|
||||||
|
("occupation", "Engineer"),
|
||||||
|
// not a field of the part: ignored
|
||||||
|
("notes", "from the client"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
assert_eq!(r.location(), format!("{base}?saved=about"));
|
||||||
|
let (middle, notes): (String, String) =
|
||||||
|
sqlx::query_as("SELECT middle_name, notes FROM people WHERE id = $1")
|
||||||
|
.bind(person)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!((middle.as_str(), notes.as_str()), ("Peter", ""));
|
||||||
|
assert!(
|
||||||
|
app.get(&format!("{base}?saved=about"))
|
||||||
|
.await
|
||||||
|
.text()
|
||||||
|
.contains("Saved: About you.")
|
||||||
|
);
|
||||||
|
|
||||||
|
// a wrong date is marked, nothing saved
|
||||||
|
let r = send_form(
|
||||||
|
&app,
|
||||||
|
&format!("{base}/about"),
|
||||||
|
&csrf,
|
||||||
|
&[
|
||||||
|
("surname", "Becker"),
|
||||||
|
("first_name", "Hans"),
|
||||||
|
("date_of_birth", "2090-01-01"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
|
||||||
|
// contact
|
||||||
|
let r = send_form(
|
||||||
|
&app,
|
||||||
|
&format!("{base}/contact"),
|
||||||
|
&csrf,
|
||||||
|
&[("phone", "+66 81 000 0000"), ("email", "hans@example.com")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
|
||||||
|
// the passport from its zone; Read first fills the form in
|
||||||
|
let zone = erika_mrz();
|
||||||
|
let r = send_form(
|
||||||
|
&app,
|
||||||
|
&format!("{base}/passport"),
|
||||||
|
&csrf,
|
||||||
|
&[("mrz", &zone), ("action", "read-mrz")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
assert!(r.text().contains("value=\"C01X00T47\""));
|
||||||
|
let r = send_form(
|
||||||
|
&app,
|
||||||
|
&format!("{base}/passport"),
|
||||||
|
&csrf,
|
||||||
|
&[("mrz", &zone), ("action", "save")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
// the same passport again changes it, adds none
|
||||||
|
let r = send_form(
|
||||||
|
&app,
|
||||||
|
&format!("{base}/passport"),
|
||||||
|
&csrf,
|
||||||
|
&[
|
||||||
|
("mrz", &zone),
|
||||||
|
("issued_at", "Stadt Köln"),
|
||||||
|
("action", "save"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
let passports: Vec<(i64, String)> =
|
||||||
|
sqlx::query_as("SELECT id, issued_at FROM passports WHERE person_id = $1")
|
||||||
|
.bind(person)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(passports.len(), 1);
|
||||||
|
assert_eq!(passports[0].1, "Stadt Köln");
|
||||||
|
|
||||||
|
// the address: added once, then changed in place
|
||||||
|
let addr = [
|
||||||
|
("house_no", "12/3"),
|
||||||
|
("district", "Mueang Chiang Mai"),
|
||||||
|
("province", "Chiang Mai"),
|
||||||
|
("postal_code", "50200"),
|
||||||
|
("house_master", "Khun Somchai"),
|
||||||
|
// staff's fields: ignored
|
||||||
|
("tm30_receipt_no", "FAKE"),
|
||||||
|
];
|
||||||
|
let r = send_form(&app, &format!("{base}/address"), &csrf, &addr).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let mut moved = addr.to_vec();
|
||||||
|
moved[0] = ("house_no", "12/4");
|
||||||
|
send_form(&app, &format!("{base}/address"), &csrf, &moved).await;
|
||||||
|
let addresses: Vec<(String, String)> =
|
||||||
|
sqlx::query_as("SELECT house_no, tm30_receipt_no FROM addresses WHERE person_id = $1")
|
||||||
|
.bind(person)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(addresses, [("12/4".to_string(), String::new())]);
|
||||||
|
|
||||||
|
// a scan of the photo page belongs to the passport
|
||||||
|
let scan = pdf("photo page");
|
||||||
|
let parts = [
|
||||||
|
Part::field("csrf", csrf.as_bytes()),
|
||||||
|
Part::field("kind", b"passport-photo-page"),
|
||||||
|
Part::file("page.pdf", &scan),
|
||||||
|
];
|
||||||
|
let r = app
|
||||||
|
.upload_raw(
|
||||||
|
&format!("{base}/documents"),
|
||||||
|
&parts,
|
||||||
|
&[("sec-fetch-site", "same-origin")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let (by, pp): (String, Option<i64>) =
|
||||||
|
sqlx::query_as("SELECT uploaded_by, passport_id FROM documents WHERE person_id = $1")
|
||||||
|
.bind(person)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(by, format!("link {link}"));
|
||||||
|
assert_eq!(pp, Some(passports[0].0));
|
||||||
|
let docs = app.get(&format!("{base}/documents")).await.text();
|
||||||
|
assert!(
|
||||||
|
docs.contains("Passport photo page") && docs.contains("page.pdf"),
|
||||||
|
"{docs}"
|
||||||
|
);
|
||||||
|
// a kind staff keep to themselves is refused
|
||||||
|
let parts = [
|
||||||
|
Part::field("csrf", csrf.as_bytes()),
|
||||||
|
Part::field("kind", b"tm30-receipt"),
|
||||||
|
Part::file("x.pdf", &scan),
|
||||||
|
];
|
||||||
|
let r = app
|
||||||
|
.upload_raw(
|
||||||
|
&format!("{base}/documents"),
|
||||||
|
&parts,
|
||||||
|
&[("sec-fetch-site", "same-origin")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
|
||||||
|
// every change carries the link as the actor, with field names only
|
||||||
|
let rows = audit_rows(&pool, &format!("link {link}")).await;
|
||||||
|
let changes: Vec<(String, String)> = rows
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.0 != "view")
|
||||||
|
.map(|r| (r.0.clone(), r.1.clone()))
|
||||||
|
.collect();
|
||||||
|
let want: Vec<(String, String)> = [
|
||||||
|
("update", "person"),
|
||||||
|
("update", "person"),
|
||||||
|
("create", "passport"),
|
||||||
|
("update", "passport"),
|
||||||
|
("create", "address"),
|
||||||
|
("update", "address"),
|
||||||
|
("create", "document"),
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.map(|(a, e)| (a.to_string(), e.to_string()))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(changes, want);
|
||||||
|
assert!(rows.iter().any(|r| r.0 == "view"));
|
||||||
|
let first = rows.iter().find(|r| r.0 == "update").unwrap();
|
||||||
|
assert!(first.2.contains(&"middle_name".to_string()), "{rows:?}");
|
||||||
|
assert!(!first.2.contains(&"notes".to_string()), "{rows:?}");
|
||||||
|
let changes = visa::links::changes(&pool, link).await.unwrap();
|
||||||
|
assert_eq!(changes.len(), 4, "{changes:?}");
|
||||||
|
|
||||||
|
// Send closes the link and thanks
|
||||||
|
let r = send_form(&app, &format!("{base}/send"), &csrf, &[]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK);
|
||||||
|
assert!(r.text().contains("Thank you"));
|
||||||
|
let after = app.get(&base).await;
|
||||||
|
assert_eq!(after.status, StatusCode::GONE);
|
||||||
|
assert!(after.text().contains("You sent your details on"));
|
||||||
|
let (sent, by): (bool, String) =
|
||||||
|
sqlx::query_as("SELECT sent_at IS NOT NULL, closed_by FROM client_links WHERE id = $1")
|
||||||
|
.bind(link)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(sent);
|
||||||
|
assert_eq!(by, "client");
|
||||||
|
// and takes nothing more
|
||||||
|
let r = send_form(&app, &format!("{base}/contact"), &csrf, &[("phone", "1")]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::GONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn forged_closed_and_made_up_links_are_refused(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let (_, link, token) = person_with_link(&pool).await;
|
||||||
|
let base = format!("/c/{token}");
|
||||||
|
|
||||||
|
// without the link's token, or with the local session's
|
||||||
|
let r = app
|
||||||
|
.post_raw(
|
||||||
|
&format!("{base}/contact"),
|
||||||
|
&[("phone", "1")],
|
||||||
|
&[("sec-fetch-site", "same-origin")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||||
|
let r = app
|
||||||
|
.post(&format!("{base}/contact"), &[("phone", "1")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||||
|
// from another site
|
||||||
|
let csrf = csrf_of(&pool, link).await;
|
||||||
|
let r = app
|
||||||
|
.post_raw(
|
||||||
|
&format!("{base}/contact"),
|
||||||
|
&[("phone", "1"), ("csrf", &csrf)],
|
||||||
|
&[("sec-fetch-site", "cross-site")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||||
|
let phone: String = sqlx::query_scalar("SELECT phone FROM people")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(phone, "");
|
||||||
|
|
||||||
|
// made up, malformed
|
||||||
|
for bad in ["/c/xyz", "/c/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"] {
|
||||||
|
let r = app.get(bad).await;
|
||||||
|
assert_eq!(r.status, StatusCode::NOT_FOUND, "{bad}");
|
||||||
|
assert!(r.text().contains("This link does not work"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// expired
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE client_links SET created_at = now() - interval '15 days', \
|
||||||
|
expires_at = now() - interval '1 day' WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(link)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let r = app.get(&base).await;
|
||||||
|
assert_eq!(r.status, StatusCode::GONE);
|
||||||
|
assert!(r.text().contains("This link has expired"));
|
||||||
|
let page = app.get("/people/1").await.text();
|
||||||
|
assert!(page.contains(">expired</span>"), "{page}");
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
mod auth;
|
mod auth;
|
||||||
mod bucket;
|
mod bucket;
|
||||||
|
mod client;
|
||||||
mod common;
|
mod common;
|
||||||
mod companies;
|
mod companies;
|
||||||
mod deadlines;
|
mod deadlines;
|
||||||
|
|||||||
@@ -154,6 +154,10 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
|||||||
("/people".to_string(), "MUSTERMANN, Erika"),
|
("/people".to_string(), "MUSTERMANN, Erika"),
|
||||||
("/people?archived=1".to_string(), "SAMPLE, Oliver"),
|
("/people?archived=1".to_string(), "SAMPLE, Oliver"),
|
||||||
("/people/new".to_string(), "Read the passport"),
|
("/people/new".to_string(), "Read the passport"),
|
||||||
|
(
|
||||||
|
"/people/new-client".to_string(),
|
||||||
|
"Make the record and its link",
|
||||||
|
),
|
||||||
(format!("/people/{erika}"), "Baan Suan Demo"),
|
(format!("/people/{erika}"), "Baan Suan Demo"),
|
||||||
(format!("/people/{erika}/edit"), "Personal details"),
|
(format!("/people/{erika}/edit"), "Personal details"),
|
||||||
(format!("/people/{erika}/passports/new"), "New passport"),
|
(format!("/people/{erika}/passports/new"), "New passport"),
|
||||||
|
|||||||
Reference in new issue
Block a user