Agreements the client signs on the link (task 7.6)
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 1m0s
CI / release (push) Skipped

Built into the app rather than a separate signing service: any number of
agreements (the processing of the client's data first, legal services
and consultations later), each in versions whose text never changes.

- Staff (Agreements in the sidebar, src/web/agreements.rs): paste the
  lawyers' text (empty line = paragraph, "# " heading, "- " list item),
  preview it as the client reads it, publish version 1; a changed text is
  the next version, the same text again is refused, and the database
  refuses any change to a published one (migrations/0007, trigger).
  Switch an agreement off and links stop asking for it.
- Client: every active agreement is the first step of every link. The
  client reads it, ticks that they accept, types their name and signs
  with a finger or the mouse (static/signature.js; a PNG of the pad). A
  text changed while they read it is refused. A new version is asked for
  again at the next link.
- The signed copy (src/agreements/pdf.rs, Sarabun so Thai prints, long
  Thai words cut without parting marks from their letter): the text, the
  name, the record, the time, the drawing, the link, the forwarded
  address, the browser and the text's SHA-256; kept as the person's
  encrypted document of kind "agreement", all in one transaction with the
  signature and the audit rows (actor link N).
- The person's page shows each agreement's state (signed, not signed, to
  sign again) and every signed copy.
- Phones: the section row now scrolls sideways instead of wrapping, so it
  keeps one height with five sections and Sign out.
- Demo data: an invented agreement with a Thai paragraph.

Checks: fmt, clippy; 105 unit and 56 integration tests (tests/agreements.rs:
versions that never change, signing with a drawing, address and browser
recorded, the PDF, signing again after a change, a stale version refused,
switched off); layout check light/dark desk/phone on the agreement pages,
the client's agreement page, the person page and the people list: no
problems; a drawn signature in Edge at 390x844 signed and printed.
This commit is contained in:
grabowski committed 2026-11-20 20:18:59 +07:00
1 parent 43ed75d81b
commit d0e13dffd2
28 files changed
+2469 -57

No files matched your search

+385
View File
@@ -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<Utc>,
}
#[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<Utc>,
}
/// 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<Block> {
let mut out = Vec::new();
let mut para: Vec<&str> = Vec::new();
fn flush(para: &mut Vec<&str>, out: &mut Vec<Block>) {
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::<Vec<_>>()
.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<Version> {
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<bool> {
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<Option<Agreement>> {
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<Vec<Version>> {
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<Option<Version>> {
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<Utc>,
/// Signatures of the current version.
pub signed: i64,
}
pub async fn list(db: &PgPool) -> Result<Vec<Listed>> {
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<Signature>,
/// The newest older version they signed, if any.
pub earlier: Option<i32>,
}
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
pub struct Signature {
pub id: i64,
pub person_id: i64,
pub version_id: i64,
pub link_id: Option<i64>,
pub signed_name: String,
pub drawn: bool,
pub signed_at: DateTime<Utc>,
pub ip: String,
pub user_agent: String,
pub document_id: Option<i64>,
}
/// Every active agreement with the person's signatures of it.
pub async fn for_person(db: &PgPool, person: i64) -> Result<Vec<Due>> {
let active: Vec<Agreement> =
sqlx::query_as("SELECT * FROM agreements WHERE active ORDER BY id")
.fetch_all(db)
.await?;
let sigs: Vec<(Signature, i64, i32)> = {
let rows: Vec<SigRow> = 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<Utc>,
pub signed_name: String,
pub link_id: Option<i64>,
pub document_id: Option<i64>,
}
pub async fn signed_by(db: &PgPool, person: i64) -> Result<Vec<Signed>> {
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<i64>,
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<Option<Signature>> {
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");
}
}