diff --git a/AGENTS.md b/AGENTS.md index ff229f2..a270e81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,8 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | `.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 `) | | `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/agreements/` | agreements in versions whose text never changes, signatures, and the signed copy as a PDF (`pdf.rs`) | +| `src/web/agreements.rs` | the Agreements section and the person page's card; the client signs in `web/client.rs` | | `src/web/client.rs` | the client's pages at `/c/`, 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` | | `src/web/` | routes, the login gate, pages | diff --git a/README.md b/README.md index 985cf62..6af1c89 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,13 @@ Data Protection Act (PDPA) asks. 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. +- Agreements the client signs on the link: staff paste the lawyers' text + under Agreements and publish it as a version that never changes. Every + client link asks for each active agreement first; the client ticks that + they accept, types their name and signs with a finger. The signed copy is + a PDF with the exact text, the signature, the time and where it was + signed from, kept with the person's documents. A changed text is a new + version, which clients sign again. - 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, passports and addresses; "Visa and stay" with arrivals and departures, diff --git a/docs/PLAN.md b/docs/PLAN.md index cfb7e39..3d8db2f 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -7,8 +7,9 @@ > PR #150); the documents move once that PR is deployed. Phase 6, the Non-B > extension pack, and phase 7, the client link, were built on November 20, > 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.** +> installs by itself. Task 7.6, the agreements the client signs, followed the +> same day; B4L's real text goes in under Agreements once the lawyers send +> it. **Resume here: phase 8, reminders.** visa.buildfor.life keeps the immigration records of the foreigners that B4L looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -44,7 +45,7 @@ The first round of questions was answered on November 17, 2026. | Client input (Nov 20) | goes straight into the person's record, logged as coming from the link; staff check it | | Link lifetime (Nov 20) | 14 days, or until the client presses Send or staff close the link | | Passport photo (Nov 20) | read in the browser with Tesseract.js and an MRZ model served by the app; the photo never leaves the device, only the lines it finds are sent, and the server checks them like typed ones | -| Client agreement (later) | a box on the client link where the client signs the agreement with B4L to keep and work with their data; its text comes from B4L | +| Client agreements (Nov 20) | built into the app rather than run as a separate signing service (DocuSeal was weighed: its embedding, single sign-on and branding are paid, and it would be a second store of client identities): any number of agreements in versions whose text never changes, each signed on the client link with the typed name and a drawing; the data processing agreement first, legal services and consultations later. The texts come from B4L's lawyers | Kanidm keeps persons, groups and OAuth2 clients in one namespace, so the client cannot be called `visa` like the group. It is `visa-web`, as @@ -230,7 +231,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 | | 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 | -| 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 | +| 7 | The client link: a client fills in their own record on a phone, the MRZ read from a photo, and signs B4L's agreements | built Nov 20, 2026 | | 8 | Reminders by Matrix room message and by email | | | later | Thai user interface, agency cases and fees, other visa categories' packs | | @@ -492,14 +493,25 @@ Planned on November 20, 2026, from Alex's answers (decisions table). 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 - 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 - signature, the agreement's version and the time). +- [x] 7.6 Agreements, built on November 20, 2026 (`src/agreements/`, + `src/web/agreements.rs`, `migrations/0007`). Staff add an agreement + under Agreements by pasting legal's text (an empty line between + paragraphs, `# ` a heading, `- ` a list item) and publish it as + version 1; a published text never changes (the table refuses it), a + changed one is the next version. Every active agreement is the first + step of every client link, in its current version: the client reads + it, ticks that they accept, types their name and signs with a finger. + The signed copy is a PDF (Sarabun, so Thai prints) with the text, the + name, the drawing, the time, the link, the client's address and + browser and the text's SHA-256, kept as the person's encrypted + document of kind `agreement`. A new version is signed again at the + next link; the person's page says who has signed which version. An + agreement switched off is no longer asked for. ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay through the BOI's One Start One Stop center, which changes phase 6's pack. -2. The agreement's text for the client link (task 7.6) comes from B4L; a - lawyer may want to check it. +2. The agreements' texts come from B4L's lawyers. Whether a client must + sign before entering any data, and whether a typed name and a drawing are + enough for each kind of agreement, is theirs to say. diff --git a/migrations/0007_agreements.sql b/migrations/0007_agreements.sql new file mode 100644 index 0000000..a64d9c5 --- /dev/null +++ b/migrations/0007_agreements.sql @@ -0,0 +1,71 @@ +-- visa.buildfor.life, task 7.6: agreements the client signs through their +-- link (docs/PLAN.md "Phase 7"). +-- +-- An agreement (the processing of the client's data, later legal services +-- or a consultation) has versions; a version's text never changes once it +-- is published, so a signature always names the exact words signed. A new +-- text is a new version, which every client signs again at their next +-- link. The signed PDF is a document of the person (kind `agreement`). + +CREATE TABLE agreements ( + id BIGSERIAL PRIMARY KEY, + title TEXT NOT NULL CHECK (title <> ''), + -- every client link asks for it while it is active + active BOOLEAN NOT NULL DEFAULT true, + created_by TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE agreement_versions ( + id BIGSERIAL PRIMARY KEY, + agreement_id BIGINT NOT NULL REFERENCES agreements (id), + version INTEGER NOT NULL CHECK (version > 0), + -- the text as legal wrote it: paragraphs separated by an empty line, + -- "# " before a heading, "- " before a list item + body TEXT NOT NULL CHECK (body <> ''), + -- of the body, as UTF-8; printed on every signed copy + sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + published_by TEXT NOT NULL, + published_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (agreement_id, version) +); + +CREATE FUNCTION agreement_versions_unchanged() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'a published agreement text never changes: publish a new version'; +END +$$; + +CREATE TRIGGER agreement_versions_no_change +BEFORE UPDATE OR DELETE ON agreement_versions +FOR EACH ROW EXECUTE FUNCTION agreement_versions_unchanged(); + +CREATE TABLE signatures ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT NOT NULL REFERENCES people (id), + version_id BIGINT NOT NULL REFERENCES agreement_versions (id), + -- the link it was signed through + link_id BIGINT REFERENCES client_links (id), + -- the name the client typed as their signature + signed_name TEXT NOT NULL CHECK (signed_name <> ''), + -- whether they also drew one (it is in the PDF only) + drawn BOOLEAN NOT NULL DEFAULT false, + signed_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- the client's address as the proxy forwarded it, and their browser + ip TEXT NOT NULL DEFAULT '', + user_agent TEXT NOT NULL DEFAULT '', + -- the signed copy + document_id BIGINT REFERENCES documents (id), + UNIQUE (person_id, version_id) +); +CREATE INDEX signatures_person ON signatures (person_id); + +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', + 'agreement', 'signature' + ) +); diff --git a/src/agreements/mod.rs b/src/agreements/mod.rs new file mode 100644 index 0000000..9510bf4 --- /dev/null +++ b/src/agreements/mod.rs @@ -0,0 +1,385 @@ +//! Agreements the client signs through their link (task 7.6): the +//! processing of their data by B4L first, later legal services or a +//! consultation. An agreement has versions; a published text never changes +//! (the table refuses it), so a signature names the exact words signed, by +//! version and SHA-256. A new text is a new version, which each client signs +//! again at their next link. The signed copy is a PDF (`pdf.rs`) kept as +//! the person's document of kind `agreement`. + +pub mod pdf; + +use anyhow::{Result, bail}; +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sqlx::{PgConnection, PgPool}; + +use crate::files; + +/// The longest text taken, in characters. +pub const BODY_LIMIT: usize = 60_000; + +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Agreement { + pub id: i64, + pub title: String, + pub active: bool, + pub created_by: String, + pub created_at: DateTime, +} + +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Version { + pub id: i64, + pub agreement_id: i64, + pub version: i32, + pub body: String, + pub sha256: String, + pub published_by: String, + pub published_at: DateTime, +} + +/// A part of an agreement's text. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", content = "text", rename_all = "lowercase")] +pub enum Block { + Heading(String), + Para(String), + Item(String), +} + +/// The text as legal wrote it, in blocks: an empty line ends a paragraph, +/// "# " starts a heading, "- " a list item. Lines of a paragraph join with +/// a space. +pub fn blocks(body: &str) -> Vec { + let mut out = Vec::new(); + let mut para: Vec<&str> = Vec::new(); + fn flush(para: &mut Vec<&str>, out: &mut Vec) { + if !para.is_empty() { + out.push(Block::Para(para.join(" "))); + para.clear(); + } + } + for raw in body.lines() { + let line = raw.trim(); + if line.is_empty() { + flush(&mut para, &mut out); + } else if let Some(h) = line.strip_prefix("# ") { + flush(&mut para, &mut out); + out.push(Block::Heading(h.trim().to_string())); + } else if let Some(i) = line.strip_prefix("- ") { + flush(&mut para, &mut out); + out.push(Block::Item(i.trim().to_string())); + } else { + para.push(line); + } + } + flush(&mut para, &mut out); + out +} + +/// The body as kept: line ends as `\n`, no space at line ends, no empty +/// lines at either end. Its SHA-256 is what a signature names. +pub fn normalize(body: &str) -> String { + body.replace("\r\n", "\n") + .replace('\r', "\n") + .lines() + .map(str::trim_end) + .collect::>() + .join("\n") + .trim_matches('\n') + .to_string() +} + +/// Checks a title and a text before they are published. +pub fn check(title: &str, body: &str) -> Vec<(&'static str, String)> { + let mut e = Vec::new(); + if title.trim().is_empty() { + e.push(("title", "Give the agreement a title.".to_string())); + } + if body.trim().is_empty() { + e.push(("body", "Paste the agreement's text.".to_string())); + } else if body.chars().count() > BODY_LIMIT { + e.push(( + "body", + format!("The text is longer than {BODY_LIMIT} characters."), + )); + } + e +} + +/// A new agreement with its first version. +pub async fn create( + conn: &mut PgConnection, + title: &str, + body: &str, + by: &str, +) -> Result<(i64, Version)> { + let id: i64 = sqlx::query_scalar( + "INSERT INTO agreements (title, created_by) VALUES ($1, $2) RETURNING id", + ) + .bind(title.trim()) + .bind(by) + .fetch_one(&mut *conn) + .await?; + let v = publish(conn, id, body, by).await?; + Ok((id, v)) +} + +/// Publishes a new version of the agreement's text, numbered after the +/// last one. +pub async fn publish( + conn: &mut PgConnection, + agreement: i64, + body: &str, + by: &str, +) -> Result { + let body = normalize(body); + if body.is_empty() { + bail!("an empty agreement text"); + } + let sha = files::sha256_hex(body.as_bytes()); + Ok(sqlx::query_as( + "INSERT INTO agreement_versions (agreement_id, version, body, sha256, published_by) \ + VALUES ($1, (SELECT COALESCE(max(version), 0) + 1 FROM agreement_versions \ + WHERE agreement_id = $1), $2, $3, $4) \ + RETURNING *", + ) + .bind(agreement) + .bind(&body) + .bind(&sha) + .bind(by) + .fetch_one(conn) + .await?) +} + +pub async fn set_active(conn: &mut PgConnection, id: i64, active: bool) -> Result { + let done = sqlx::query("UPDATE agreements SET active = $2 WHERE id = $1 AND active <> $2") + .bind(id) + .bind(active) + .execute(conn) + .await?; + Ok(done.rows_affected() == 1) +} + +pub async fn get(db: &PgPool, id: i64) -> Result> { + Ok(sqlx::query_as("SELECT * FROM agreements WHERE id = $1") + .bind(id) + .fetch_optional(db) + .await?) +} + +/// The agreement's versions, the newest (the current one) first. +pub async fn versions(db: &PgPool, agreement: i64) -> Result> { + Ok(sqlx::query_as( + "SELECT * FROM agreement_versions WHERE agreement_id = $1 ORDER BY version DESC", + ) + .bind(agreement) + .fetch_all(db) + .await?) +} + +pub async fn version(db: &PgPool, id: i64) -> Result> { + Ok( + sqlx::query_as("SELECT * FROM agreement_versions WHERE id = $1") + .bind(id) + .fetch_optional(db) + .await?, + ) +} + +/// One row of the Agreements page. +#[derive(Debug, sqlx::FromRow)] +pub struct Listed { + pub id: i64, + pub title: String, + pub active: bool, + pub version: i32, + pub published_at: DateTime, + /// Signatures of the current version. + pub signed: i64, +} + +pub async fn list(db: &PgPool) -> Result> { + Ok(sqlx::query_as( + "SELECT a.id, a.title, a.active, v.version, v.published_at, \ + (SELECT count(*) FROM signatures s WHERE s.version_id = v.id) AS signed \ + FROM agreements a \ + JOIN LATERAL (SELECT * FROM agreement_versions WHERE agreement_id = a.id \ + ORDER BY version DESC LIMIT 1) v ON true \ + ORDER BY a.active DESC, a.id", + ) + .fetch_all(db) + .await?) +} + +/// An active agreement and where the person stands with it. +#[derive(Clone, Debug)] +pub struct Due { + pub agreement: Agreement, + pub current: Version, + /// The person's signature of the current version, if any. + pub signed: Option, + /// The newest older version they signed, if any. + pub earlier: Option, +} + +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Signature { + pub id: i64, + pub person_id: i64, + pub version_id: i64, + pub link_id: Option, + pub signed_name: String, + pub drawn: bool, + pub signed_at: DateTime, + pub ip: String, + pub user_agent: String, + pub document_id: Option, +} + +/// Every active agreement with the person's signatures of it. +pub async fn for_person(db: &PgPool, person: i64) -> Result> { + let active: Vec = + sqlx::query_as("SELECT * FROM agreements WHERE active ORDER BY id") + .fetch_all(db) + .await?; + let sigs: Vec<(Signature, i64, i32)> = { + let rows: Vec = sqlx::query_as( + "SELECT s.*, v.agreement_id, v.version FROM signatures s \ + JOIN agreement_versions v ON v.id = s.version_id WHERE s.person_id = $1", + ) + .bind(person) + .fetch_all(db) + .await?; + rows.into_iter() + .map(|r| (r.sig, r.agreement_id, r.version)) + .collect() + }; + let mut out = Vec::new(); + for a in active { + let Some(current) = versions(db, a.id).await?.into_iter().next() else { + continue; + }; + let signed = sigs + .iter() + .find(|(s, _, _)| s.version_id == current.id) + .map(|(s, _, _)| s.clone()); + let earlier = sigs + .iter() + .filter(|(_, ag, v)| *ag == a.id && *v < current.version) + .map(|(_, _, v)| *v) + .max(); + out.push(Due { + agreement: a, + current, + signed, + earlier, + }); + } + Ok(out) +} + +#[derive(sqlx::FromRow)] +struct SigRow { + #[sqlx(flatten)] + sig: Signature, + agreement_id: i64, + version: i32, +} + +/// A signature as the person's page lists it, of any agreement, active or +/// not, newest first. +#[derive(Debug, sqlx::FromRow)] +pub struct Signed { + pub title: String, + pub version: i32, + pub current: i32, + pub signed_at: DateTime, + pub signed_name: String, + pub link_id: Option, + pub document_id: Option, +} + +pub async fn signed_by(db: &PgPool, person: i64) -> Result> { + Ok(sqlx::query_as( + "SELECT a.title, v.version, \ + (SELECT max(version) FROM agreement_versions WHERE agreement_id = a.id) AS current, \ + s.signed_at, s.signed_name, s.link_id, s.document_id \ + FROM signatures s JOIN agreement_versions v ON v.id = s.version_id \ + JOIN agreements a ON a.id = v.agreement_id \ + WHERE s.person_id = $1 ORDER BY s.signed_at DESC", + ) + .bind(person) + .fetch_all(db) + .await?) +} + +/// What a signature records besides the version. +pub struct Signing<'a> { + pub person: i64, + pub version: i64, + pub link: Option, + pub name: &'a str, + pub drawn: bool, + pub ip: &'a str, + pub user_agent: &'a str, +} + +/// Records a signature; None when this version is signed already. +pub async fn sign(conn: &mut PgConnection, s: &Signing<'_>) -> Result> { + Ok(sqlx::query_as( + "INSERT INTO signatures (person_id, version_id, link_id, signed_name, drawn, ip, \ + user_agent) VALUES ($1, $2, $3, $4, $5, $6, $7) \ + ON CONFLICT (person_id, version_id) DO NOTHING RETURNING *", + ) + .bind(s.person) + .bind(s.version) + .bind(s.link) + .bind(s.name) + .bind(s.drawn) + .bind(s.ip) + .bind(s.user_agent) + .fetch_optional(conn) + .await?) +} + +pub async fn set_document(conn: &mut PgConnection, signature: i64, document: i64) -> Result<()> { + sqlx::query("UPDATE signatures SET document_id = $2 WHERE id = $1") + .bind(signature) + .bind(document) + .execute(conn) + .await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn text_in_blocks() { + let body = + "# 1. Purpose\r\nB4L processes\nyour data.\n\n- name\n- passport\n\nEnd. \n\n\n"; + assert_eq!( + blocks(body), + vec![ + Block::Heading("1. Purpose".into()), + Block::Para("B4L processes your data.".into()), + Block::Item("name".into()), + Block::Item("passport".into()), + Block::Para("End.".into()), + ] + ); + let n = normalize(body); + assert!(!n.contains('\r') && !n.ends_with('\n') && !n.contains("End. ")); + assert_eq!(normalize(&n), n); + } + + #[test] + fn titles_and_texts_are_checked() { + assert_eq!(check("", "x").len(), 1); + assert_eq!(check("T", " ").len(), 1); + assert!(check("T", "x").is_empty()); + assert_eq!(check("T", &"x".repeat(BODY_LIMIT + 1))[0].0, "body"); + } +} diff --git a/src/agreements/pdf.rs b/src/agreements/pdf.rs new file mode 100644 index 0000000..cd34b1e --- /dev/null +++ b/src/agreements/pdf.rs @@ -0,0 +1,387 @@ +//! The signed copy of an agreement as a PDF: the title and version, the +//! text as published, and a last part that says who signed, when, through +//! which link and from where, with the drawn signature and the SHA-256 of +//! the text. Sarabun writes it, so Thai text prints too. + +use anyhow::{Result, anyhow}; +use krilla::color::rgb; +use krilla::geom::{PathBuilder, Point, Size, Transform}; +use krilla::image::Image; +use krilla::metadata::Metadata; +use krilla::num::NormalizedF32; +use krilla::page::PageSettings; +use krilla::paint::{Fill, LineCap, Stroke}; +use krilla::surface::Surface; +use krilla::text::TextDirection; +use krilla::{Data, Document}; + +use super::Block; +use crate::papers::{Pen, width}; + +/// A4 portrait, in points. +const W: f32 = 595.0; +const H: f32 = 842.0; +const MARGIN: f32 = 56.0; +const BOTTOM: f32 = H - 60.0; + +const NAVY: (u8, u8, u8) = (7, 19, 35); +const INK: (u8, u8, u8) = (34, 38, 46); +const GREY: (u8, u8, u8) = (104, 112, 124); +const GOLD: (u8, u8, u8) = (245, 192, 0); + +/// Who signed, and the facts the signature page records. +pub struct Signed<'a> { + pub title: &'a str, + pub version: i32, + /// "Nov 20, 2026" + pub published: &'a str, + pub sha256: &'a str, + /// The name typed as the signature. + pub name: &'a str, + /// The record: "MUSTERMANN, Erika, born Aug 12, 1984, passport C01X00T47 (Germany)" + pub record: &'a str, + /// "Nov 20, 2026, 14:05 (Chiang Mai time)" + pub at: &'a str, + /// "client link 12 at https://visa.buildfor.life" + pub through: &'a str, + pub ip: &'a str, + pub user_agent: &'a str, + /// The drawn signature, a PNG. + pub drawing: Option<&'a [u8]>, +} + +enum Op { + Text { + x: f32, + y: f32, + size: f32, + color: (u8, u8, u8), + text: String, + }, + Rule { + y: f32, + }, + Image { + x: f32, + y: f32, + w: f32, + h: f32, + }, +} + +/// Pages of drawing operations, with the place to write next. +struct Layout<'p> { + pen: &'p Pen<'p>, + pages: Vec>, + y: f32, +} + +impl Layout<'_> { + fn room(&mut self, needed: f32) { + if self.y + needed > BOTTOM { + self.pages.push(Vec::new()); + self.y = 72.0; + } + } + + fn op(&mut self, op: Op) { + self.pages.last_mut().expect("a page").push(op); + } + + /// Text wrapped to the width at `x`, line by line. + fn text(&mut self, x: f32, text: &str, size: f32, lead: f32, color: (u8, u8, u8)) { + for line in wrap(self.pen, text, size, W - MARGIN - x) { + self.room(lead); + self.y += lead; + self.op(Op::Text { + x, + y: self.y, + size, + color, + text: line, + }); + } + } +} + +/// Thai vowels and tone marks written above or below the letter before +/// them: a line never starts with one. +fn combining(c: char) -> bool { + matches!(c, '\u{0E31}' | '\u{0E34}'..='\u{0E3A}' | '\u{0E47}'..='\u{0E4E}') +} + +/// `text` in lines that fit `room`; a word wider than a line (Thai has no +/// spaces between words) is cut where it must be. +fn wrap(pen: &Pen<'_>, text: &str, size: f32, room: f32) -> Vec { + let mut lines = Vec::new(); + let mut line = String::new(); + for word in text.split_whitespace() { + let tried = if line.is_empty() { + word.to_string() + } else { + format!("{line} {word}") + }; + if width(&pen.face, &tried, size) <= room { + line = tried; + continue; + } + if !line.is_empty() { + lines.push(std::mem::take(&mut line)); + } + if width(&pen.face, word, size) <= room { + line = word.to_string(); + continue; + } + let mut piece = String::new(); + for c in word.chars() { + let mut next = piece.clone(); + next.push(c); + if !piece.is_empty() && !combining(c) && width(&pen.face, &next, size) > room { + lines.push(std::mem::take(&mut piece)); + piece.push(c); + } else { + piece = next; + } + } + line = piece; + } + if !line.is_empty() { + lines.push(line); + } + lines +} + +fn fill(c: (u8, u8, u8)) -> Fill { + Fill { + paint: rgb::Color::new(c.0, c.1, c.2).into(), + opacity: NormalizedF32::ONE, + rule: Default::default(), + } +} + +/// The signed copy. `blocks` is the version's text. +pub fn render(s: &Signed<'_>, blocks: &[Block]) -> Result> { + let pen = Pen::sarabun()?; + let image = match s.drawing { + Some(png) => Some( + Image::from_png(Data::from(png.to_vec()), true) + .map_err(|e| anyhow!("the drawn signature: {e}"))?, + ), + None => None, + }; + let mut l = Layout { + pen: &pen, + pages: vec![Vec::new()], + y: 40.0, + }; + l.text(MARGIN, s.title, 18.0, 30.0, NAVY); + l.text( + MARGIN, + &format!("Version {}, published {}", s.version, s.published), + 9.5, + 16.0, + GREY, + ); + l.y += 10.0; + l.op(Op::Rule { y: l.y }); + l.y += 6.0; + for b in blocks { + match b { + Block::Heading(t) => { + l.room(40.0); + l.y += 8.0; + l.text(MARGIN, t, 12.5, 19.0, NAVY); + } + Block::Para(t) => { + l.y += 5.0; + l.text(MARGIN, t, 10.5, 15.0, INK); + } + Block::Item(t) => { + l.room(15.0); + l.y += 2.0; + let top = l.y; + l.text(MARGIN + 14.0, t, 10.5, 15.0, INK); + // the bullet on the item's first line + let first = top + 15.0; + if let Some(page) = l.pages.last_mut() + && first <= l.y + { + page.push(Op::Text { + x: MARGIN + 2.0, + y: first, + size: 10.5, + color: INK, + text: "•".into(), + }); + } + } + } + } + + // the signature, kept together on one page + let drawing_h = if image.is_some() { 90.0 } else { 0.0 }; + l.y += 18.0; + l.room(230.0 + drawing_h); + l.op(Op::Rule { y: l.y }); + l.y += 4.0; + l.text(MARGIN, "Signed", 13.0, 22.0, NAVY); + let rows: [(&str, &str); 3] = [ + ("Signed by", s.name), + ("Record", s.record), + ("Signed on", s.at), + ]; + for (k, v) in rows { + l.text(MARGIN, &format!("{k}: {v}"), 10.5, 16.0, INK); + } + if let Some(img) = &image { + let (pw, ph) = img.size(); + let (pw, ph) = (pw.max(1) as f32, ph.max(1) as f32); + let scale = (220.0 / pw).min(80.0 / ph); + let (w, h) = (pw * scale, ph * scale); + l.y += 8.0; + l.op(Op::Image { + x: MARGIN, + y: l.y, + w, + h, + }); + l.y += h + 4.0; + l.op(Op::Rule { y: l.y }); + } + l.y += 6.0; + let small = [ + format!("Through {}", s.through), + format!( + "From the address {}", + if s.ip.is_empty() { "not known" } else { s.ip } + ), + format!("Browser: {}", s.user_agent), + format!("Text: version {}, SHA-256 {}", s.version, s.sha256), + ]; + for line in &small { + l.text(MARGIN, line, 8.5, 12.5, GREY); + } + + let total = l.pages.len(); + let mut doc = Document::new(); + doc.set_metadata( + Metadata::new() + .title(format!("{}, version {}", s.title, s.version)) + .creator("visa.buildfor.life".to_string()), + ); + for (i, ops) in l.pages.iter().enumerate() { + let mut page = doc.start_page_with(PageSettings::from_wh(W, H).expect("A4")); + let mut surface = page.surface(); + for op in ops { + draw(&mut surface, &pen, op, image.as_ref()); + } + draw( + &mut surface, + &pen, + &Op::Text { + x: MARGIN, + y: H - 30.0, + size: 8.0, + color: GREY, + text: format!( + "{}, version {} · signed by {} · page {} of {total}", + s.title, + s.version, + s.name, + i + 1 + ), + }, + None, + ); + surface.finish(); + page.finish(); + } + doc.finish() + .map_err(|e| anyhow!("writing the agreement: {e:?}")) +} + +fn draw(s: &mut Surface<'_>, pen: &Pen<'_>, op: &Op, image: Option<&Image>) { + match op { + Op::Text { + x, + y, + size, + color, + text, + } => { + s.set_fill(Some(fill(*color))); + s.draw_text( + Point::from_xy(*x, *y), + pen.font.clone(), + *size, + text, + false, + TextDirection::Auto, + ); + } + Op::Rule { y } => { + let mut pb = PathBuilder::new(); + pb.move_to(MARGIN, *y); + pb.line_to(W - MARGIN, *y); + if let Some(path) = pb.finish() { + s.set_fill(None); + s.set_stroke(Some(Stroke { + paint: rgb::Color::new(GOLD.0, GOLD.1, GOLD.2).into(), + width: 1.2, + line_cap: LineCap::Butt, + opacity: NormalizedF32::ONE, + ..Default::default() + })); + s.draw_path(&path); + s.set_stroke(None); + } + } + Op::Image { x, y, w, h } => { + let (Some(img), Some(size)) = (image, Size::from_wh(*w, *h)) else { + return; + }; + s.push_transform(&Transform::from_translate(*x, *y)); + s.draw_image(img.clone(), size); + s.pop(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn long_thai_words_are_cut_and_marks_stay_with_their_letter() { + let pen = Pen::sarabun().unwrap(); + let thai = "ข้อมูลส่วนบุคคลของท่านจะถูกเก็บรักษาไว้อย่างปลอดภัยตามพระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล"; + let lines = wrap(&pen, thai, 10.5, 120.0); + assert!(lines.len() > 2, "{lines:?}"); + assert_eq!(lines.concat(), thai); + for l in &lines { + assert!(!l.chars().next().is_some_and(combining), "{l:?}"); + assert!(width(&pen.face, l, 10.5) <= 125.0, "{l:?}"); + } + } + + #[test] + fn a_signed_copy_renders() { + let blocks = + super::super::blocks("# Purpose\nB4L processes your data.\n\n- name\n- passport"); + let s = Signed { + title: "Processing of your data", + version: 1, + published: "Nov 20, 2026", + sha256: &"a".repeat(64), + name: "Erika Mustermann", + record: "MUSTERMANN, Erika", + at: "Nov 20, 2026, 14:05", + through: "client link 1", + ip: "203.0.113.7", + user_agent: "Test", + drawing: None, + }; + let pdf = render(&s, &blocks).unwrap(); + assert!(pdf.starts_with(b"%PDF-")); + } +} diff --git a/src/audit.rs b/src/audit.rs index 1c2f49e..197d9a4 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -63,6 +63,10 @@ pub enum Entity { Form, /// A client link (`links.rs`). Link, + /// An agreement's text, published (`agreements`). + Agreement, + /// A client's signature of an agreement. + Signature, } impl Entity { @@ -82,6 +86,8 @@ impl Entity { Entity::Document => "document", Entity::Form => "form", Entity::Link => "link", + Entity::Agreement => "agreement", + Entity::Signature => "signature", } } } diff --git a/src/documents.rs b/src/documents.rs index e14f96a..b923bda 100644 --- a/src/documents.rs +++ b/src/documents.rs @@ -90,6 +90,8 @@ pub const PERSON_KINDS: &[Kind] = &[ k("tm30-receipt", "TM.30 receipt", Some("addresses")), k("work-permit", "Work permit", Some("work-permits")), k("pnd91", "Income tax return (PND.91)", None), + // made by the app when the client signs through their link + k("agreement", "Signed agreement", None), k("other", "Other", None), ]; diff --git a/src/lib.rs b/src/lib.rs index fe52b2a..e392704 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ //! visa.buildfor.life: immigration records, deadlines and extension packs //! for foreigners in Thailand (docs/PLAN.md). +pub mod agreements; pub mod audit; pub mod companies; pub mod config; diff --git a/src/seed.rs b/src/seed.rs index fcb1be4..3c1f2c7 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -7,6 +7,7 @@ use anyhow::Result; use chrono::{Datelike, NaiveDate, TimeDelta}; use sqlx::PgPool; +use crate::agreements; use crate::audit::{self, Action, Entity, Entry}; use crate::dates; use crate::documents::{self, Meta, NewFile, Owner}; @@ -635,10 +636,37 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result { } } demo_links(&mut tx, &person_ids).await?; + let (_, v) = agreements::create(&mut tx, DEMO_AGREEMENT.0, DEMO_AGREEMENT.1, "seed").await?; + audit::record( + &mut *tx, + &seeded(Action::Create, Entity::Agreement, v.id, None), + ) + .await?; tx.commit().await?; Ok(true) } +/// An invented agreement, so the client link shows the step to sign; B4L's +/// real text comes from its lawyers. +const DEMO_AGREEMENT: (&str, &str) = ( + "How B4L processes your personal data (demo)", + "# This text is invented for development\n\ + It shows how an agreement looks on the client's link. B4L's real text \ + comes from its lawyers and is added under Agreements.\n\ + \n\ + # 1. What B4L keeps\n\ + - your name, date of birth and nationality\n\ + - your passport, visas and stamps\n\ + - your address in Thailand and how to reach you\n\ + \n\ + # 2. What for\n\ + B4L keeps these to look after your visa and your stay in Thailand: \ + the deadlines, the forms and the documents Immigration asks for.\n\ + \n\ + # 3. ข้อความภาษาไทย\n\ + ข้อความนี้แสดงว่าภาษาไทยพิมพ์ได้ในสำเนาที่ลงนาม", +); + /// Client links to see on the person's page: the first demo person sent /// theirs an hour ago, with a new phone number and email address; the /// second opened theirs and has not sent it yet. Their tokens are thrown diff --git a/src/web/agreements.rs b/src/web/agreements.rs new file mode 100644 index 0000000..5b50068 --- /dev/null +++ b/src/web/agreements.rs @@ -0,0 +1,392 @@ +//! The Agreements section for staff: the agreements clients sign through +//! their link, each with its versions. A published text never changes; a +//! new text is a new version, which every client signs again at their next +//! link. An agreement switched off is no longer asked for. + +use std::sync::Arc; + +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::response::{IntoResponse, Redirect, Response}; +use axum::{Extension, Form}; +use minijinja::context; +use serde::Serialize; + +use super::{AppState, Res, not_found_page, page}; +use crate::agreements::{self, Block, Version}; +use crate::audit::{self, Action, Entity, Entry}; +use crate::dates; +use crate::forms::{Errors, Fields, err}; +use crate::links; +use crate::session::User; + +#[derive(Debug, Serialize)] +struct Row { + id: i64, + title: String, + active: bool, + version: i32, + published: String, + signed: i64, +} + +#[derive(Debug, Serialize)] +struct VersionView { + id: i64, + version: i32, + published: String, + by: String, + sha256: String, + signed: i64, +} + +async fn version_view(st: &AppState, v: &Version) -> anyhow::Result { + let signed: i64 = sqlx::query_scalar("SELECT count(*) FROM signatures WHERE version_id = $1") + .bind(v.id) + .fetch_one(&st.db) + .await?; + Ok(VersionView { + id: v.id, + version: v.version, + published: dates::fmt_datetime(v.published_at), + by: v.published_by.clone(), + sha256: v.sha256.clone(), + signed, + }) +} + +fn log<'a>( + user: &'a User, + action: Action, + entity: Entity, + id: i64, + fields: &'a [String], +) -> Entry<'a> { + Entry { + actor: &user.login, + action, + entity, + entity_id: Some(id), + person_id: None, + company_id: None, + fields, + } +} + +pub async fn list(State(st): State>, Extension(user): Extension) -> Res { + let rows: Vec = agreements::list(&st.db) + .await? + .into_iter() + .map(|r| Row { + id: r.id, + title: r.title, + active: r.active, + version: r.version, + published: links::day(r.published_at), + signed: r.signed, + }) + .collect(); + Ok(page( + &st, + &user, + "agreements.html", + "Agreements", + "agreements", + StatusCode::OK, + context! { rows }, + )) +} + +#[derive(Debug, Default, Serialize)] +struct Draft { + title: String, + body: String, +} + +fn new_page( + st: &AppState, + user: &User, + d: &Draft, + errors: &Errors, + status: StatusCode, +) -> Response { + page( + st, + user, + "agreement_form.html", + "New agreement", + "agreements", + status, + context! { d, errors, preview => agreements::blocks(&d.body) }, + ) +} + +pub async fn new_form(State(st): State>, Extension(user): Extension) -> Res { + Ok(new_page( + &st, + &user, + &Draft::default(), + &Errors::new(), + StatusCode::OK, + )) +} + +fn text_of(f: &Fields, key: &str) -> String { + f.get(key).cloned().unwrap_or_default() +} + +/// A new agreement and its first version; "Preview" shows the text as +/// clients will read it, without publishing. +pub async fn create( + State(st): State>, + Extension(user): Extension, + Form(f): Form, +) -> Res { + let d = Draft { + title: text_of(&f, "title").trim().to_string(), + body: agreements::normalize(&text_of(&f, "body")), + }; + let mut errors = Errors::new(); + for (k, v) in agreements::check(&d.title, &d.body) { + err(&mut errors, k, v); + } + if !errors.is_empty() || f.get("action").map(String::as_str) == Some("preview") { + let status = if errors.is_empty() { + StatusCode::OK + } else { + StatusCode::UNPROCESSABLE_ENTITY + }; + return Ok(new_page(&st, &user, &d, &errors, status)); + } + let mut tx = st.db.begin().await?; + let (id, v) = agreements::create(&mut tx, &d.title, &d.body, &user.login).await?; + audit::record( + &mut *tx, + &log(&user, Action::Create, Entity::Agreement, v.id, &[]), + ) + .await?; + tx.commit().await?; + Ok(Redirect::to(&format!("/agreements/{id}")).into_response()) +} + +/// The agreement's page with version `shown` (the current one if None); +/// `draft` is a new text sent for a preview or refused. +async fn show_page( + st: &AppState, + user: &User, + id: i64, + shown: Option, + draft: Option<&str>, + errors: &Errors, + status: StatusCode, +) -> Res { + let Some(a) = agreements::get(&st.db, id).await? else { + return Ok(not_found_page(st)); + }; + let all = agreements::versions(&st.db, id).await?; + let Some(current) = all.first() else { + return Ok(not_found_page(st)); + }; + let v = match shown { + Some(n) => match all.iter().find(|v| v.version == n) { + Some(v) => v, + None => return Ok(not_found_page(st)), + }, + None => current, + }; + let mut versions = Vec::new(); + for x in &all { + versions.push(version_view(st, x).await?); + } + let blocks: Vec = agreements::blocks(&v.body); + let draft_given = draft.is_some(); + let draft = draft.unwrap_or(¤t.body).to_string(); + Ok(page( + st, + user, + "agreement.html", + &a.title, + "agreements", + status, + context! { + a, versions, blocks, draft, errors, + shown => v.version, + current => current.version, + is_preview => draft_given, + preview => agreements::blocks(&draft), + }, + )) +} + +pub async fn show( + State(st): State>, + Extension(user): Extension, + Path(id): Path, +) -> Res { + show_page(&st, &user, id, None, None, &Errors::new(), StatusCode::OK).await +} + +pub async fn show_version( + State(st): State>, + Extension(user): Extension, + Path((id, n)): Path<(i64, i32)>, +) -> Res { + show_page( + &st, + &user, + id, + Some(n), + None, + &Errors::new(), + StatusCode::OK, + ) + .await +} + +/// A new version of the text; the same text again is refused. +pub async fn publish( + State(st): State>, + Extension(user): Extension, + Path(id): Path, + Form(f): Form, +) -> Res { + let Some(a) = agreements::get(&st.db, id).await? else { + return Ok(not_found_page(&st)); + }; + let body = agreements::normalize(&text_of(&f, "body")); + let mut errors = Errors::new(); + for (k, v) in agreements::check(&a.title, &body) { + err(&mut errors, k, v); + } + let current = agreements::versions(&st.db, id).await?; + if current.first().is_some_and(|c| c.body == body) { + err( + &mut errors, + "body", + "This is the current text: change it to publish a new version.", + ); + } + if !errors.is_empty() || f.get("action").map(String::as_str) == Some("preview") { + let status = if errors.is_empty() { + StatusCode::OK + } else { + StatusCode::UNPROCESSABLE_ENTITY + }; + return show_page(&st, &user, id, None, Some(&body), &errors, status).await; + } + let mut tx = st.db.begin().await?; + let v = agreements::publish(&mut tx, id, &body, &user.login).await?; + audit::record( + &mut *tx, + &log(&user, Action::Create, Entity::Agreement, v.id, &[]), + ) + .await?; + tx.commit().await?; + Ok(Redirect::to(&format!("/agreements/{id}")).into_response()) +} + +/// Switches an agreement off (no longer asked for) or on again. +pub async fn set_active( + State(st): State>, + Extension(user): Extension, + Path(id): Path, + Form(f): Form, +) -> Res { + if agreements::get(&st.db, id).await?.is_none() { + return Ok(not_found_page(&st)); + } + let active = f.get("active").map(String::as_str) == Some("1"); + let mut tx = st.db.begin().await?; + if agreements::set_active(&mut tx, id, active).await? { + let fields = ["active".to_string()]; + audit::record( + &mut *tx, + &log(&user, Action::Update, Entity::Agreement, id, &fields), + ) + .await?; + } + tx.commit().await?; + Ok(Redirect::to(&format!("/agreements/{id}")).into_response()) +} + +/// The person page's card: each active agreement and where the person +/// stands, and the signed copies of any agreement. +#[derive(Debug, Serialize)] +pub struct PersonAgreement { + pub title: String, + pub id: i64, + pub state: &'static str, + pub level: &'static str, + pub note: String, +} + +#[derive(Debug, Serialize)] +pub struct SignedView { + pub title: String, + pub version: i32, + pub old: bool, + pub at: String, + pub name: String, + pub through: String, + pub href: String, +} + +pub async fn card( + st: &AppState, + person: i64, +) -> anyhow::Result<(Vec, Vec)> { + let dues = agreements::for_person(&st.db, person) + .await? + .into_iter() + .map(|d| { + let (state, level, note) = match (&d.signed, d.earlier) { + (Some(s), _) => ( + "signed", + "ok", + format!( + "version {} on {}", + d.current.version, + dates::fmt_datetime(s.signed_at) + ), + ), + (None, Some(v)) => ( + "to sign again", + "warn", + format!( + "signed version {v}; version {} is current, the next client link asks for it", + d.current.version + ), + ), + (None, None) => ( + "not signed", + "warn", + "the next client link asks for it".to_string(), + ), + }; + PersonAgreement { + title: d.agreement.title, + id: d.agreement.id, + state, + level, + note, + } + }) + .collect(); + let signed = agreements::signed_by(&st.db, person) + .await? + .into_iter() + .map(|s| SignedView { + old: s.version < s.current, + title: s.title, + version: s.version, + at: dates::fmt_datetime(s.signed_at), + name: s.signed_name, + through: s.link_id.map(links::actor).unwrap_or_default(), + href: s + .document_id + .map(|d| format!("/people/{person}/documents/{d}/file")) + .unwrap_or_default(), + }) + .collect(); + Ok((dues, signed)) +} diff --git a/src/web/client.rs b/src/web/client.rs index ca9938f..59225d7 100644 --- a/src/web/client.rs +++ b/src/web/client.rs @@ -22,6 +22,7 @@ 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::agreements::{self, Signing}; use crate::audit::{self, Action, Entity, Entry}; use crate::documents::{self, LINKS, Meta, Owner}; use crate::forms::{Errors, Fields, err, get}; @@ -205,13 +206,23 @@ macro_rules! open_or_return { #[derive(Debug, Serialize)] struct Part { - slug: &'static str, - title: &'static str, - what: &'static str, + slug: String, + title: String, + what: String, done: bool, status: String, } +fn part(slug: &str, title: &str, what: &str, done: bool, status: String) -> Part { + Part { + slug: slug.to_string(), + title: title.to_string(), + what: what.to_string(), + done, + status, + } +} + async fn parts(st: &AppState, c: &Client) -> anyhow::Result> { let p = &c.person; let about = !p.surname.is_empty() @@ -231,48 +242,69 @@ async fn parts(st: &AppState, c: &Client) -> anyhow::Result> { 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 { + // the agreements first: they say what B4L does with the rest + let mut out: Vec = agreements::for_person(&st.db, c.id()) + .await? + .into_iter() + .map(|d| { + let done = d.signed.is_some(); + let what = if d.earlier.is_some() && !done { + "Its text has changed since you signed it: read it and sign again." + } else { + "Read it and sign it on the screen." + }; + part( + &format!("agree/{}", d.agreement.id), + &d.agreement.title, + what, + done, + state(done, "Signed", "To sign"), + ) + }) + .collect(); + out.extend([ + part( + "about", + "About you", + "Your name as in the passport, date and place of birth, nationality, occupation.", + about, + state(about, "Filled in", "To fill in"), + ), + part( + "passport", + "Passport", + "A photo of the passport's photo page fills it in, or type the two lines at its bottom.", + !passports.is_empty(), + state(!passports.is_empty(), "Recorded", "To fill in"), + ), + part( + "address", + "Address in Thailand", + "Where you live now, and your landlord or house owner.", + current, + state(current, "Recorded", "To fill in"), + ), + part( + "contact", + "Contact", + "Your phone number and email address.", + contact, + state(contact, "Filled in", "To fill in"), + ), + part( + "documents", + "Documents", + "Scans or photos: the passport's photo page, a passport photo, the TDAC and others.", + papers, + match mine { 0 if papers => "Recorded".into(), 0 => "To upload".into(), 1 => "1 file uploaded".into(), n => format!("{n} files uploaded"), }, - }, - ]) + ), + ]); + Ok(out) } #[derive(Deserialize)] @@ -291,8 +323,12 @@ pub async fn overview( .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(); + .map(|p| p.title.clone()); + let missing: Vec<&str> = parts + .iter() + .filter(|p| !p.done) + .map(|p| p.title.as_str()) + .collect(); let actor = c.link.actor(); audit::record( &st.db, @@ -915,3 +951,325 @@ pub async fn send( *resp.status_mut() = StatusCode::OK; Ok(resp) } + +// ------------------------------------------------------------ agreements + +/// The largest drawn signature taken, as a PNG. +const DRAWING_LIMIT: usize = 400 * 1024; + +#[derive(Debug, Default, Serialize)] +struct SignForm { + name: String, + accept: bool, +} + +/// The name as the client would sign it: given names, then the surname. +fn full_name(p: &Person) -> String { + [ + p.first_name.as_str(), + p.middle_name.as_str(), + p.surname.as_str(), + ] + .iter() + .filter(|s| !s.is_empty()) + .copied() + .collect::>() + .join(" ") +} + +async fn agreement_page( + st: &AppState, + c: &Client, + id: i64, + f: &SignForm, + errors: &Errors, + status: StatusCode, +) -> anyhow::Result> { + let Some(due) = agreements::for_person(&st.db, c.id()) + .await? + .into_iter() + .find(|d| d.agreement.id == id) + else { + return Ok(None); + }; + let signed = due + .signed + .as_ref() + .map(|s| dates::fmt_datetime(s.signed_at)); + Ok(Some(client_page( + st, + c, + "client_agree.html", + &due.agreement.title, + status, + context! { + title => &due.agreement.title, + agreement_id => id, + version => due.current.version, + version_id => due.current.id, + published => links::day(due.current.published_at), + blocks => agreements::blocks(&due.current.body), + again => due.earlier.is_some() && due.signed.is_none(), + signed, f, errors, + }, + ))) +} + +pub async fn agreement( + State(st): State>, + Path((token, id)): Path<(String, i64)>, +) -> Res { + let c = open_or_return!(st, token); + let f = SignForm { + name: full_name(&c.person), + accept: false, + }; + match agreement_page(&st, &c, id, &f, &Errors::new(), StatusCode::OK).await? { + Some(resp) => { + let actor = c.link.actor(); + audit::record( + &st.db, + &log(&c, &actor, Action::View, Entity::Agreement, Some(id), &[]), + ) + .await?; + Ok(resp) + } + None => Ok(closed_page(&st, None)), + } +} + +/// The drawn signature from the form: a PNG as a `data:` address, if any. +fn drawing(f: &Fields) -> Result>, &'static str> { + use base64::Engine; + let raw = f.get("drawing").map(|s| s.trim()).unwrap_or_default(); + if raw.is_empty() { + return Ok(None); + } + let Some(b64) = raw.strip_prefix("data:image/png;base64,") else { + return Err("The drawn signature did not arrive as a picture. Clear it and sign again."); + }; + let bytes = base64::engine::general_purpose::STANDARD + .decode(b64) + .map_err(|_| "The drawn signature did not arrive whole. Clear it and sign again.")?; + if bytes.len() > DRAWING_LIMIT || crate::files::sniff(&bytes) != Some("image/png") { + return Err("The drawn signature did not arrive whole. Clear it and sign again."); + } + Ok(Some(bytes)) +} + +/// The client's address as the proxy in front of the app forwarded it. +fn client_ip(headers: &axum::http::HeaderMap) -> String { + headers + .get("x-forwarded-for") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.split(',').next()) + .map(|v| v.trim().chars().take(64).collect()) + .unwrap_or_default() +} + +/// Signs the current version: the signature, its PDF as the person's +/// document and both in the audit log, in one transaction. +pub async fn sign( + State(st): State>, + Path((token, id)): Path<(String, i64)>, + headers: axum::http::HeaderMap, + Form(f): Form, +) -> Res { + let c = open_or_return!(st, token); + if !token_ok(&c, &f) { + return Ok(stale(&st)); + } + let Some(due) = agreements::for_person(&st.db, c.id()) + .await? + .into_iter() + .find(|d| d.agreement.id == id) + else { + return Ok(closed_page(&st, None)); + }; + let back = format!("{}?saved=agree/{id}", c.base); + if due.signed.is_some() { + return Ok(Redirect::to(&back).into_response()); + } + let form = SignForm { + name: get(&f, "name"), + accept: get(&f, "accept") == "yes", + }; + let mut errors = Errors::new(); + if get(&f, "version") != due.current.id.to_string() { + err( + &mut errors, + "accept", + "B4L changed the text while you read it. Read this version and sign again.", + ); + } + if form.name.is_empty() { + err( + &mut errors, + "name", + "Type your full name as your signature.", + ); + } else if form.name.chars().count() > 200 { + err(&mut errors, "name", "Type your name only."); + } + if !form.accept { + err( + &mut errors, + "accept", + "Tick the box to accept the agreement.", + ); + } + let drawn = match drawing(&f) { + Ok(d) => d, + Err(msg) => { + err(&mut errors, "drawing", msg); + None + } + }; + let Some(store) = st.files.clone() else { + err( + &mut errors, + "accept", + "Signing is switched off on this server: it keeps no documents.", + ); + return Ok( + agreement_page(&st, &c, id, &form, &errors, StatusCode::SERVICE_UNAVAILABLE) + .await? + .unwrap_or_else(|| closed_page(&st, None)), + ); + }; + if !errors.is_empty() { + return Ok(agreement_page( + &st, + &c, + id, + &form, + &errors, + StatusCode::UNPROCESSABLE_ENTITY, + ) + .await? + .unwrap_or_else(|| closed_page(&st, None))); + } + + let ip = client_ip(&headers); + let user_agent: String = headers + .get(axum::http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .chars() + .take(300) + .collect(); + let actor = c.link.actor(); + let mut tx = st.db.begin().await?; + let Some(sig) = agreements::sign( + &mut tx, + &Signing { + person: c.id(), + version: due.current.id, + link: Some(c.link.id), + name: &form.name, + drawn: drawn.is_some(), + ip: &ip, + user_agent: &user_agent, + }, + ) + .await? + else { + // signed a moment ago, in another tab + return Ok(Redirect::to(&back).into_response()); + }; + + // the signed copy + let passport = people::passports(&st.db, c.id()).await?.into_iter().next(); + let mut record = c.person.display_name(); + if let Some(d) = c.person.date_of_birth { + record.push_str(&format!(", born {}", dates::fmt_date(d))); + } + if let Some(p) = &passport { + record.push_str(&format!(", passport {} ({})", p.number, p.issuing_country)); + } + let at = format!("{} (Chiang Mai time)", dates::fmt_datetime(sig.signed_at)); + let through = format!("client link {} at {}", c.link.id, st.cfg.public_url); + let published = links::day(due.current.published_at); + let pdf = agreements::pdf::render( + &agreements::pdf::Signed { + title: &due.agreement.title, + version: due.current.version, + published: &published, + sha256: &due.current.sha256, + name: &form.name, + record: &record, + at: &at, + through: &through, + ip: &ip, + user_agent: &user_agent, + drawing: drawn.as_deref(), + }, + &agreements::blocks(&due.current.body), + )?; + let sha = crate::files::sha256_hex(&pdf); + let meta = Meta { + kind: "agreement".into(), + link: None, + dated_on: Some(sig.signed_at.with_timezone(&dates::bangkok()).date_naive()), + note: format!("{}, version {}", due.agreement.title, due.current.version), + }; + let file_name = format!( + "{} - {} v{}.pdf", + c.person.display_name(), + due.agreement.title, + due.current.version + ); + let file = documents::NewFile { + name: &documents::clean_name(&file_name), + content_type: "application/pdf", + size: i32::try_from(pdf.len())?, + sha256: &sha, + }; + let doc = documents::insert(&mut tx, Owner::Person(c.id()), &meta, &file, &actor).await?; + store.put(doc, pdf).await?; + let saved: anyhow::Result<()> = async { + agreements::set_document(&mut tx, sig.id, doc).await?; + let fields: Vec = ["signed_name", "accepted"] + .iter() + .chain(drawn.is_some().then_some(&"drawing")) + .map(|s| s.to_string()) + .collect(); + audit::record( + &mut *tx, + &log( + &c, + &actor, + Action::Create, + Entity::Signature, + Some(sig.id), + &fields, + ), + ) + .await?; + let doc_fields = meta.set_fields(); + audit::record( + &mut *tx, + &log( + &c, + &actor, + Action::Create, + Entity::Document, + Some(doc), + &doc_fields, + ), + ) + .await?; + Ok(()) + } + .await; + if let Err(e) = match saved { + Ok(()) => tx.commit().await.map_err(anyhow::Error::from), + Err(e) => Err(e), + } { + if let Err(r) = store.remove(doc).await { + tracing::error!("removing the file of the failed signature {doc}: {r:#}"); + } + return Err(e.into()); + } + Ok(Redirect::to(&back).into_response()) +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 69c9c8d..f3fd93e 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -1,6 +1,7 @@ //! The web side: state, routes, the login gate, form checks, rendering. pub mod activity; +pub mod agreements; pub mod auth; pub mod client; pub mod companies; @@ -341,6 +342,23 @@ pub fn router(st: Arc) -> Router { .layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)), ) .route("/c/{token}/send", post(client::send)); + r = r + .route( + "/agreements", + get(agreements::list).post(agreements::create), + ) + .route("/agreements/new", get(agreements::new_form)) + .route("/agreements/{id}", get(agreements::show)) + .route("/agreements/{id}/versions", post(agreements::publish)) + .route( + "/agreements/{id}/versions/{n}", + get(agreements::show_version), + ) + .route("/agreements/{id}/active", post(agreements::set_active)) + .route( + "/c/{token}/agree/{id}", + get(client::agreement).post(client::sign), + ); r.route("/activity", get(activity::page)) .route("/login", get(auth::login)) .route("/auth/callback", get(auth::callback)) @@ -406,8 +424,9 @@ async fn gate(State(st): State>, mut req: Request, next: Next) -> Redirect::to(&login).into_response() } -/// The largest form body read; uploads (phase 4) get their own limit. -const FORM_LIMIT: usize = 256 * 1024; +/// The largest form body read; uploads (phase 4) get their own limit. An +/// agreement's text in Thai takes nine bytes a character once encoded. +const FORM_LIMIT: usize = 1024 * 1024; /// Every request that changes something must come from this site and carry /// the session's form token (`csrf` in the form, or `X-CSRF-Token`). diff --git a/src/web/people.rs b/src/web/people.rs index bdc2080..7ad4174 100644 --- a/src/web/people.rs +++ b/src/web/people.rs @@ -359,6 +359,7 @@ pub async fn show( let recent = audit::recent(&st.db, Some(id), 6).await?; let docs = super::documents::chips(&st, id).await?; let client_links = super::links::card(&st, id).await?; + let (agreements, signed_agreements) = super::agreements::card(&st, id).await?; let title = view.name.clone(); Ok(page( &st, @@ -375,6 +376,8 @@ pub async fn show( docs, recent, client_links, + agreements, + signed_agreements, stay => assessment.stay, deadlines => assessment.items, }, diff --git a/static/app.css b/static/app.css index f26b9c4..247bec8 100644 --- a/static/app.css +++ b/static/app.css @@ -1237,13 +1237,24 @@ textarea.mrz { border-right: 0; border-bottom: 1px solid var(--line); } + /* one row that scrolls sideways when the sections do not fit, so it + keeps its height and place on every page */ .nav { flex-direction: row; - flex-wrap: wrap; + flex-wrap: nowrap; + flex: 1 1 auto; + min-width: 0; + overflow-x: auto; + scrollbar-width: none; + } + .nav::-webkit-scrollbar { + display: none; } .nav a { - padding: 6px 9px; + padding: 6px 8px; font-size: 14px; + white-space: nowrap; + flex: 0 0 auto; } .who { margin: 0 0 0 auto; @@ -1501,3 +1512,83 @@ textarea.mrz { .cmain .upload .drop { margin-bottom: 4px; } + +/* ---- agreements: the text as clients read it, the signature pad */ +.agtext h3 { + margin: 16px 0 6px; + font-size: 16px; + color: var(--hd); +} +.agtext h3:first-child { + margin-top: 0; +} +.agtext p, +.agtext li { + line-height: 1.55; +} +.agtext p { + margin: 0 0 10px; +} +.agtext ul { + margin: 0 0 10px; + padding-left: 22px; +} +.agcard { + max-height: 60vh; + overflow-y: auto; +} +.agcols { + grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); +} +@media (max-width: 1060px) { + .agcols { + grid-template-columns: minmax(0, 1fr); + } +} +.agrow { + flex-wrap: wrap; + margin-bottom: 8px; +} +label.check { + display: flex; + gap: 10px; + align-items: flex-start; + font-weight: 600; +} +label.check input { + width: auto; + margin-top: 3px; + flex: 0 0 auto; +} +.sigpad { + display: block; + width: 100%; + height: 170px; + border: 1px dashed var(--stroke); + border-radius: 8px; + background: #ffffff; + touch-action: none; + cursor: crosshair; +} +.sigbar { + display: flex; + gap: 12px; + align-items: center; + margin-top: 6px; +} +#sign-form h2 { + margin-top: 0; +} +#sign-form .field { + margin-bottom: 14px; +} +/* a version's SHA-256 breaks anywhere rather than widening the page */ +#versions .mono { + overflow-wrap: anywhere; +} +@media (max-width: 420px) { + .nav a { + padding: 6px 6px; + font-size: 13px; + } +} diff --git a/static/app.js b/static/app.js index 9216e02..dda5b04 100644 --- a/static/app.js +++ b/static/app.js @@ -18,6 +18,15 @@ } }); + // ---- on phones the sections scroll sideways: the current one in view + document.addEventListener("DOMContentLoaded", function () { + var nav = document.querySelector(".nav"); + var on = nav && nav.querySelector("a.on"); + if (on && nav.scrollWidth > nav.clientWidth) { + nav.scrollLeft = Math.max(0, on.offsetLeft - nav.offsetLeft - 24); + } + }); + // ---- 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) { diff --git a/static/signature.js b/static/signature.js new file mode 100644 index 0000000..2ba3cb2 --- /dev/null +++ b/static/signature.js @@ -0,0 +1,92 @@ +// The signature pad of an agreement on the client's link: drawn with a +// finger, a pen or the mouse, sent as a PNG in the hidden field `drawing`. +// Without JavaScript the pad stays hidden and the typed name signs alone. +(function () { + "use strict"; + + function setup(form) { + var wrap = form.querySelector("[data-sign-wrap]"); + var pad = form.querySelector("[data-sign-pad]"); + var out = form.querySelector("[data-sign-out]"); + var msg = form.querySelector("[data-sign-msg]"); + if (!wrap || !pad || !out || !pad.getContext) return; + wrap.hidden = false; + var ctx = pad.getContext("2d"); + var drawn = false; + var last = null; + + // the canvas in device pixels; a resize clears it, as the strokes no + // longer fit + function size() { + var r = pad.getBoundingClientRect(); + var dpr = Math.min(window.devicePixelRatio || 1, 3); + pad.width = Math.max(1, Math.round(r.width * dpr)); + pad.height = Math.max(1, Math.round(r.height * dpr)); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.lineWidth = 2.4; + ctx.strokeStyle = "#071323"; + drawn = false; + out.value = ""; + } + function at(ev) { + var r = pad.getBoundingClientRect(); + return { x: ev.clientX - r.left, y: ev.clientY - r.top }; + } + pad.addEventListener("pointerdown", function (ev) { + ev.preventDefault(); + pad.setPointerCapture(ev.pointerId); + last = at(ev); + ctx.beginPath(); + ctx.arc(last.x, last.y, 1.1, 0, 2 * Math.PI); + ctx.fillStyle = "#071323"; + ctx.fill(); + drawn = true; + if (msg) msg.hidden = true; + }); + pad.addEventListener("pointermove", function (ev) { + if (!last) return; + ev.preventDefault(); + var p = at(ev); + ctx.beginPath(); + ctx.moveTo(last.x, last.y); + ctx.lineTo(p.x, p.y); + ctx.stroke(); + last = p; + }); + function end() { + last = null; + } + pad.addEventListener("pointerup", end); + pad.addEventListener("pointercancel", end); + form.querySelector("[data-sign-clear]").addEventListener("click", function () { + ctx.clearRect(0, 0, pad.width, pad.height); + drawn = false; + out.value = ""; + }); + form.addEventListener("submit", function (ev) { + if (!drawn) { + ev.preventDefault(); + if (msg) msg.hidden = false; + pad.scrollIntoView({ block: "center" }); + return; + } + out.value = pad.toDataURL("image/png"); + }); + var width = 0; + window.addEventListener("resize", function () { + var w = pad.getBoundingClientRect().width; + if (Math.abs(w - width) > 2) { + width = w; + size(); + } + }); + width = pad.getBoundingClientRect().width; + size(); + } + + document.addEventListener("DOMContentLoaded", function () { + document.querySelectorAll("form[data-sign-form]").forEach(setup); + }); +})(); diff --git a/templates/_agreement_text.html b/templates/_agreement_text.html new file mode 100644 index 0000000..626d87c --- /dev/null +++ b/templates/_agreement_text.html @@ -0,0 +1,15 @@ +{#- An agreement's text, in its blocks: headings, paragraphs and list + items, as `agreements::blocks` reads them. -#} +{% macro text(blocks) -%} +
+ {%- set ns = namespace(open=false) %} + {%- for b in blocks %} + {%- if b.kind == "item" and not ns.open %}
    {% set ns.open = true %}{% endif %} + {%- if b.kind != "item" and ns.open %}
{% set ns.open = false %}{% endif %} + {%- if b.kind == "heading" %}

{{ b.text }}

+ {%- elif b.kind == "item" %}
  • {{ b.text }}
  • + {%- else %}

    {{ b.text }}

    {% endif %} + {%- endfor %} + {%- if ns.open %}{% endif %} +
    +{%- endmacro %} diff --git a/templates/agreement.html b/templates/agreement.html new file mode 100644 index 0000000..2dc4185 --- /dev/null +++ b/templates/agreement.html @@ -0,0 +1,51 @@ +{% extends "base.html" %} +{% import "_fields.html" as fm %} +{% import "_agreement_text.html" as ag %} +{% block main %} + +
    +

    {{ a.title }}

    +
    +
    + + + +
    +
    +
    +

    {% if a.active %}asked for Every client link asks for version {{ current }}.{% else %}switched off Client links do not ask for it.{% endif %}

    +
    +
    +

    Version {{ shown }}{% if shown != current %} earlier{% endif %}

    + {{ ag.text(blocks) }} +
    +
    +

    Versions

    + {% for v in versions %} +
    +
    Version {{ v.version }}{% if v.version == current %}current{% endif %}{{ v.signed }} signed
    +
    published {{ v.published }} by {{ v.by }}
    +
    {{ v.sha256 }}
    +
    + {% endfor %} +
    +
    +
    + +
    +

    A new version

    +

    Change the text below and publish it as version {{ current + 1 }}. Clients who signed an earlier version sign again at their next link. A published text can never be changed.

    + {{ fm.area("body", "Text", draft, err=errors.body, rows=16, fcls="wide") }} +
    + + +
    +
    +
    +{% if is_preview %} +
    +

    The new text as the client reads it

    + {{ ag.text(preview) }} +
    +{% endif %} +{% endblock %} diff --git a/templates/agreement_form.html b/templates/agreement_form.html new file mode 100644 index 0000000..2a1385e --- /dev/null +++ b/templates/agreement_form.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% import "_fields.html" as fm %} +{% import "_agreement_text.html" as ag %} +{% block main %} + +

    New agreement

    +
    + +
    +
    + {{ fm.text("title", "Title", d.title, err=errors.title, req=true, cls="wide", hint="As the client sees it, for example: How B4L processes your personal data.") }} + {{ fm.area("body", "Text", d.body, err=errors.body, rows=18, fcls="wide", hint="Paste it as legal wrote it. An empty line starts a new paragraph, # and a space a heading, - and a space a list item.") }} +
    +
    +
    + + + Cancel +
    +

    A published text can never be changed, only followed by a new version.

    +
    +{% if d.body %} +
    +

    As the client reads it

    + {{ ag.text(preview) }} +
    +{% endif %} +{% endblock %} diff --git a/templates/agreements.html b/templates/agreements.html new file mode 100644 index 0000000..6eeaeeb --- /dev/null +++ b/templates/agreements.html @@ -0,0 +1,27 @@ +{% extends "base.html" %} +{% block main %} +
    +

    Agreements

    + +
    +

    What clients sign through their link: every active agreement is asked for, in its current version. A published text never changes; a new version is signed again at the client's next link.

    +{% if rows %} +
    + + + + {% for r in rows %} + + + + + + + {% endfor %} + +
    AgreementCurrent versionSignedState
    {{ r.title }}{{ r.version }}, {{ r.published }}{{ r.signed }}{% if r.active %}asked for{% else %}switched off{% endif %}
    +
    +{% else %} +

    No agreement yet. Once one is added, every client link asks the client to read and sign it.

    +{% endif %} +{% endblock %} diff --git a/templates/base.html b/templates/base.html index bd1ee08..206211e 100644 --- a/templates/base.html +++ b/templates/base.html @@ -24,6 +24,7 @@ Deadlines People Companies + Agreements Activity
    diff --git a/templates/client.html b/templates/client.html index 2481a70..55fd0ae 100644 --- a/templates/client.html +++ b/templates/client.html @@ -6,7 +6,7 @@
      {% for p in parts %}
    1. - + {{ p.title }}{{ p.what }} {{ p.status }} diff --git a/templates/client_agree.html b/templates/client_agree.html new file mode 100644 index 0000000..d844283 --- /dev/null +++ b/templates/client_agree.html @@ -0,0 +1,43 @@ +{% extends "client_base.html" %} +{% import "_agreement_text.html" as ag %} +{% block main %} + +

      {{ title }}

      +

      Version {{ version }}, {{ published }}

      +{% if again %}
      The text has changed since you last signed it. Read this version and sign it again.
      {% endif %} +
      + {{ ag.text(blocks) }} +
      +{% if signed %} +
      You signed this version on {{ signed }}. B4L keeps the signed copy.
      +

      Back

      +{% else %} +
      + + +

      Sign

      +
      + + {% if errors.accept %}

      {{ errors.accept }}

      {% endif %} +
      +
      + + + {% if errors.name %}

      {{ errors.name }}

      {% endif %} +
      + +
      + + Back +
      +

      Signing records your name, the time, this link, your internet address and your browser with the exact text. B4L keeps the signed copy as a PDF.

      +
      + +{% endif %} +{% endblock %} diff --git a/templates/person.html b/templates/person.html index 939263e..1b8d388 100644 --- a/templates/person.html +++ b/templates/person.html @@ -87,6 +87,22 @@ {% endfor %} + {% if agreements or signed_agreements %} +
      +

      Agreements

      + {% for g in agreements %} +
      {{ g.title }}{{ g.state }}{{ g.note }}
      + {% endfor %} + {% if signed_agreements %} +
        + {% for s in signed_agreements %} +
      • {{ s.at }}{% if s.href %}{{ s.title }}, version {{ s.version }}{% else %}{{ s.title }}, version {{ s.version }}{% endif %} signed as {{ s.name }}{% if s.through %} ({{ s.through }}){% endif %}{% if s.old %} earlier version{% endif %}
      • + {% endfor %} +
      + {% endif %} +
      + {% endif %} +

      Recent activity

      All of it
        diff --git a/tests/agreements.rs b/tests/agreements.rs new file mode 100644 index 0000000..5e37a56 --- /dev/null +++ b/tests/agreements.rs @@ -0,0 +1,359 @@ +//! Agreements (task 7.6): staff publish texts in versions that never +//! change; the client link asks for every active one, the client signs with +//! their name and a drawing, the signed copy is a PDF among the person's +//! documents, and a new version is signed again. + +use axum::http::StatusCode; +use sqlx::PgPool; + +use crate::common::{App, Resp, assert_unique_ids, local}; + +/// A 1 x 1 PNG, as the signature pad would send it. +const DRAWING: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="; + +const TEXT: &str = "# 1. What B4L keeps\nYour name and passport.\n\n- name\n- passport"; + +async fn client_post( + app: &App, + uri: &str, + csrf: &str, + form: &[(&str, &str)], + headers: &[(&str, &str)], +) -> Resp { + let mut pairs = form.to_vec(); + pairs.push(("csrf", csrf)); + let mut h = vec![("sec-fetch-site", "same-origin")]; + h.extend_from_slice(headers); + app.post_raw(uri, &pairs, &h).await +} + +/// A person, an open link for them, and the link's form token. +async fn client(pool: &PgPool) -> (i64, i64, String, String) { + let mut conn = pool.acquire().await.unwrap(); + let person: i64 = sqlx::query_scalar( + "INSERT INTO people (surname, first_name, date_of_birth) \ + VALUES ('Becker', 'Hans', '1990-02-03') RETURNING id", + ) + .fetch_one(&mut *conn) + .await + .unwrap(); + let (link, token) = visa::links::create(&mut conn, person, "grabowski") + .await + .unwrap(); + (person, link.id, token, link.csrf) +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn staff_publish_versions_that_never_change(pool: PgPool) { + let app = local(pool.clone()); + let r = app.get("/agreements").await; + assert_eq!(r.status, StatusCode::OK); + assert!(r.text().contains("No agreement yet")); + + // a preview publishes nothing + let r = app + .post( + "/agreements", + &[ + ("title", "Your data"), + ("body", TEXT), + ("action", "preview"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::OK); + assert!( + r.text().contains("

        1. What B4L keeps

        "), + "{}", + r.body + ); + assert!(r.text().contains("
      • passport
      • ")); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM agreements") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(n, 0); + let r = app + .post("/agreements", &[("title", ""), ("body", "")]) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + + let r = app + .post( + "/agreements", + &[ + ("title", "Your data"), + ("body", TEXT), + ("action", "publish"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + let page = r.location().to_string(); + let r = app.get(&page).await; + assert_eq!(r.status, StatusCode::OK); + assert_unique_ids(&r.body, &page); + assert!(r.text().contains("Publish version 2")); + + // the same text again is no new version; a changed one is + let r = app + .post( + &format!("{page}/versions"), + &[("body", TEXT), ("action", "publish")], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + let r = app + .post( + &format!("{page}/versions"), + &[ + ("body", &format!("{TEXT}\n- address")), + ("action", "publish"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + let r = app.get(&format!("{page}/versions/1")).await; + assert_eq!(r.status, StatusCode::OK); + assert!(!r.text().contains("
      • address
      • ")); + assert_eq!( + app.get(&format!("{page}/versions/9")).await.status, + StatusCode::NOT_FOUND + ); + + // the database refuses to change a published text + let changed = sqlx::query("UPDATE agreement_versions SET body = 'other'") + .execute(&pool) + .await; + assert!(changed.is_err()); + let deleted = sqlx::query("DELETE FROM agreement_versions") + .execute(&pool) + .await; + assert!(deleted.is_err()); + + let list = app.get("/agreements").await.text(); + assert!( + list.contains("Your data") && list.contains("asked for"), + "{list}" + ); + let r = app + .post(&format!("{page}/active"), &[("active", "0")]) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert!(app.get("/agreements").await.text().contains("switched off")); + let actions: Vec<(String, String)> = sqlx::query_as( + "SELECT action, entity FROM audit_log WHERE entity = 'agreement' ORDER BY id", + ) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(actions.len(), 3, "{actions:?}"); +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_client_signs_and_signs_again_after_a_change(pool: PgPool) { + let app = local(pool.clone()); + app.post( + "/agreements", + &[ + ("title", "Your data"), + ("body", TEXT), + ("action", "publish"), + ], + ) + .await; + let agreement: i64 = sqlx::query_scalar("SELECT id FROM agreements") + .fetch_one(&pool) + .await + .unwrap(); + let v1: i64 = sqlx::query_scalar("SELECT id FROM agreement_versions") + .fetch_one(&pool) + .await + .unwrap(); + let (person, link, token, csrf) = client(&pool).await; + let base = format!("/c/{token}"); + let uri = format!("{base}/agree/{agreement}"); + + // the link asks for it first + let o = app.get(&base).await.text(); + let first = o.find("Your data").unwrap(); + assert!(first < o.find("About you").unwrap(), "{o}"); + assert!(o.contains("To sign")); + let r = app.get(&uri).await; + assert_eq!(r.status, StatusCode::OK); + assert_unique_ids(&r.body, &uri); + let t = r.text(); + assert!(t.contains("

        1. What B4L keeps

        ")); + assert!(t.contains("value=\"Hans Becker\""), "{t}"); + assert!(t.contains("/static/signature.js")); + + // without the box ticked, or with a broken drawing + let r = client_post( + &app, + &uri, + &csrf, + &[("name", "Hans Becker"), ("version", &v1.to_string())], + &[], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!(r.text().contains("Tick the box")); + let r = client_post( + &app, + &uri, + &csrf, + &[ + ("name", "Hans Becker"), + ("accept", "yes"), + ("version", &v1.to_string()), + ("drawing", "data:image/png;base64,AAAA"), + ], + &[], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + // without the link's token + let r = client_post( + &app, + &uri, + "wrong", + &[("name", "x"), ("accept", "yes")], + &[], + ) + .await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + + let r = client_post( + &app, + &uri, + &csrf, + &[ + ("name", "Hans Peter Becker"), + ("accept", "yes"), + ("version", &v1.to_string()), + ("drawing", DRAWING), + ], + &[ + ("x-forwarded-for", "203.0.113.7, 10.0.0.1"), + ("user-agent", "TestPhone/1.0"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + assert_eq!(r.location(), format!("{base}?saved=agree/{agreement}")); + + let (name, drawn, ip, ua, doc): (String, bool, String, String, Option) = sqlx::query_as( + "SELECT signed_name, drawn, ip, user_agent, document_id FROM signatures \ + WHERE person_id = $1", + ) + .bind(person) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(name, "Hans Peter Becker"); + assert!(drawn); + assert_eq!(ip, "203.0.113.7"); + assert_eq!(ua, "TestPhone/1.0"); + let doc = doc.expect("a signed copy"); + let (kind, by, note): (String, String, String) = + sqlx::query_as("SELECT kind, uploaded_by, note FROM documents WHERE id = $1") + .bind(doc) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(kind, "agreement"); + assert_eq!(by, format!("link {link}")); + assert_eq!(note, "Your data, version 1"); + let file = app + .get(&format!("/people/{person}/documents/{doc}/file")) + .await; + assert_eq!(file.status, StatusCode::OK); + assert!(file.bytes.starts_with(b"%PDF-")); + + // signed: the page says so, a second post changes nothing + assert!( + app.get(&uri) + .await + .text() + .contains("You signed this version on") + ); + assert!(app.get(&base).await.text().contains(">Signed")); + let again = client_post( + &app, + &uri, + &csrf, + &[ + ("name", "X"), + ("accept", "yes"), + ("version", &v1.to_string()), + ], + &[], + ) + .await; + assert_eq!(again.status, StatusCode::SEE_OTHER); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM signatures") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(n, 1); + let person_page = app.get(&format!("/people/{person}")).await.text(); + assert!( + person_page.contains("signed as Hans Peter Becker"), + "{person_page}" + ); + let logged: Vec<(String, String)> = sqlx::query_as( + "SELECT action, entity FROM audit_log WHERE actor = $1 AND action = 'create' ORDER BY id", + ) + .bind(format!("link {link}")) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!( + logged, + [ + ("create".to_string(), "signature".to_string()), + ("create".to_string(), "document".to_string()) + ] + ); + + // a new version: signed again, and a post of the old one is refused + app.post( + &format!("/agreements/{agreement}/versions"), + &[("body", "Changed text."), ("action", "publish")], + ) + .await; + let o = app.get(&base).await.text(); + assert!( + o.contains("Its text has changed since you signed it"), + "{o}" + ); + assert!( + app.get(&format!("/people/{person}")) + .await + .text() + .contains("to sign again") + ); + let r = client_post( + &app, + &uri, + &csrf, + &[ + ("name", "Hans Becker"), + ("accept", "yes"), + ("version", &v1.to_string()), + ], + &[], + ) + .await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!(r.text().contains("changed the text while you read it")); + + // switched off: no longer asked for + app.post( + &format!("/agreements/{agreement}/active"), + &[("active", "0")], + ) + .await; + assert!(!app.get(&base).await.text().contains("Your data")); + assert_eq!(app.get(&uri).await.status, StatusCode::NOT_FOUND); +} diff --git a/tests/main.rs b/tests/main.rs index ba336cd..5b64c08 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -2,6 +2,7 @@ //! The database tests need `DATABASE_URL` (a PostgreSQL role that may create //! databases); each `#[sqlx::test]` gets its own database. +mod agreements; mod auth; mod bucket; mod client; diff --git a/tests/pages.rs b/tests/pages.rs index e7b38cf..c698980 100644 --- a/tests/pages.rs +++ b/tests/pages.rs @@ -158,6 +158,12 @@ async fn every_page_renders_with_demo_data(pool: PgPool) { "/people/new-client".to_string(), "Make the record and its link", ), + ( + "/agreements".to_string(), + "How B4L processes your personal data (demo)", + ), + ("/agreements/new".to_string(), "Publish version 1"), + ("/agreements/1".to_string(), "ข้อความภาษาไทย"), (format!("/people/{erika}"), "Baan Suan Demo"), (format!("/people/{erika}/edit"), "Personal details"), (format!("/people/{erika}/passports/new"), "New passport"),