//! 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)) }