//! Agreements the client signs through their link (task 7.6): the //! processing of their data by Lanna Desk 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\nLanna Desk 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("Lanna Desk 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"); } }