//! The legal practice's pages (phase 9): lawyers, clients, contracts with //! their versions and paper copies, and the journal. Every change is //! written to the journal in the same transaction, and to the audit log as //! the rest of the app's changes are. use std::sync::Arc; use axum::body::Body; use axum::extract::{Multipart, Path, Query, State}; use axum::http::{HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Redirect, Response}; use axum::{Extension, Form}; use minijinja::context; use serde::{Deserialize, Serialize}; use super::documents::{FILE_LIMIT, FileQuery, read_field}; use super::{AppState, Res, message, not_found_page, page}; use crate::agreements; use crate::audit::{self, Action, Entity, Entry}; use crate::conflicts::{self, For, Hit, Probe}; use crate::dates; use crate::documents::{self, Meta, NewFile, Owner}; use crate::files; use crate::forms::{Errors, Fields, err}; use crate::journal::{self, New}; use crate::legal::{self, CLIENTS, CONTRACTS, Filter}; use crate::records::{self, Kind, Options, Values}; use crate::session::{self, User}; fn audit_entry<'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, } } /// The section a kind's pages sit in, and the list it goes back to. fn section(kind: &Kind) -> (&'static str, &'static str, &'static str) { match kind.slug { "lawyers" => ("lawyers", "/lawyers", "Lawyers"), "clients" => ("clients", "/clients", "Clients"), _ => ("contracts", "/contracts", "Contracts"), } } #[allow(clippy::too_many_arguments)] fn form_page( st: &AppState, user: &User, kind: &'static Kind, id: Option, values: &Values, opts: &Options, errors: &Errors, status: StatusCode, check: &Check, ) -> Response { let (nav, list, crumb) = section(kind); let (heading, mode, action, cancel) = match id { Some(id) => ( format!("Edit the {}", kind.one), "edit", format!("{list}/{id}"), format!("{list}/{id}"), ), None => ( format!("New {}", kind.one), "new", list.to_string(), list.to_string(), ), }; page( st, user, "record_form.html", &heading, nav, status, context! { heading, one => kind.one, lead => kind.lead, mode, action, fields => records::form_fields(kind, opts), values, errors, cancel, crumb, crumb_href => list, check, }, ) } /// The conflict check as a form shows it: the matches, whether a lawyer /// must clear them before the save goes through, and what they wrote. #[derive(Debug, Default, Serialize)] struct Check { hits: Vec, ask: bool, note: String, } /// The fields of a client the conflict check reads. const CLIENT_CHECKED: &[&str] = &[ "name", "name_th", "known_as", "thai_id", "passport_no", "registration_no", ]; fn client_probe(v: &Values) -> Probe { let g = |n: &str| records::val(v, n).to_string(); Probe { names: vec![g("name"), g("name_th"), g("known_as")], numbers: vec![g("thai_id"), g("passport_no"), g("registration_no")], } } /// What a lawyer wrote when clearing matches, kept short. fn cleared_note(f: &Fields) -> String { crate::forms::get(f, "cleared_note") .trim() .chars() .take(500) .collect() } /// Runs the check; Err holds the form's check when matches wait to be /// cleared, Ok the check's words for the journal. async fn run_check( st: &AppState, probe: &Probe, who: For, f: &Fields, ) -> anyhow::Result> { let hits = conflicts::check(&st.db, probe, who).await?; let note = cleared_note(f); if conflicts::needs_clearing(&hits) && crate::forms::get(f, "cleared") != "1" { return Ok(Err(Check { hits, ask: true, note, })); } Ok(Ok(conflicts::summary(&hits, ¬e))) } #[derive(Debug, Deserialize)] pub struct NewQuery { #[serde(default)] client: Option, } pub async fn new_form(kind: &'static Kind, st: Arc, user: User, q: NewQuery) -> Res { let opts = legal::options(&st.db).await?; let mut v = Values::new(); match kind.slug { "contracts" => { v.insert("status".into(), "draft".into()); if let Some(c) = q.client { v.insert("client_id".into(), c.to_string()); // the client's lawyer, to begin with let lawyer: Option> = sqlx::query_scalar("SELECT lawyer_id FROM clients WHERE id = $1") .bind(c) .fetch_optional(&st.db) .await?; if let Some(Some(l)) = lawyer { v.insert("lawyer_id".into(), l.to_string()); } } } "clients" => { v.insert("status".into(), "active".into()); v.insert("kind".into(), "person".into()); // a lawyer who signs in looks after the clients they add if let Some(l) = legal::lawyer_of_login(&st.db, &user.login).await? { v.insert("lawyer_id".into(), l.to_string()); } } _ => { v.insert("status".into(), "active".into()); } } Ok(form_page( &st, &user, kind, None, &v, &opts, &Errors::new(), StatusCode::OK, &Check::default(), )) } /// The ids a record's journal entry is about. fn about(kind: &Kind, id: i64, v: &Values) -> (Option, Option) { match kind.slug { "clients" => (Some(id), None), "contracts" => (records::val(v, "client_id").parse().ok(), Some(id)), _ => (None, None), } } pub async fn create(kind: &'static Kind, st: Arc, user: User, f: Fields) -> Res { let opts = legal::options(&st.db).await?; let values = records::read(kind, &f); let errors = records::validate(kind, &values, &opts); if !errors.is_empty() { let status = StatusCode::UNPROCESSABLE_ENTITY; return Ok(form_page( &st, &user, kind, None, &values, &opts, &errors, status, &Check::default(), )); } // a new client is checked against everyone on record first let mut checked = String::new(); if kind.slug == "clients" { match run_check(&st, &client_probe(&values), For::Client(None), &f).await? { Ok(said) => checked = said, Err(check) => { return Ok(form_page( &st, &user, kind, None, &values, &opts, &errors, StatusCode::CONFLICT, &check, )); } } } let mut tx = st.db.begin().await?; let (id, detail) = if kind.slug == "contracts" { let (id, code) = legal::create_contract(&mut tx, &values, &user.login).await?; ( id, format!("{code}. {}", legal::detail_of(kind, &values, &opts)), ) } else { let id = records::create(&mut tx, kind, None, &values).await?; (id, legal::detail_of(kind, &values, &opts)) }; let detail = if checked.is_empty() { detail } else { format!("{detail}. {checked}") }; let (client, contract) = about(kind, id, &values); journal::append( &mut tx, &New { actor: &user.login, client, contract, event: &format!("{} added", kind.one), detail, }, ) .await?; let fields: Vec = kind .fields .iter() .filter(|fl| !records::val(&values, fl.name).is_empty()) .map(|fl| records::audit_name(fl.name)) .collect(); audit::record( &mut *tx, &audit_entry(&user, Action::Create, kind.entity, id, &fields), ) .await?; tx.commit().await?; let (_, list, _) = section(kind); Ok(Redirect::to(&format!("{list}/{id}")).into_response()) } pub async fn edit_form(kind: &'static Kind, st: Arc, user: User, id: i64) -> Res { let Some(r) = records::get(&st.db, kind, None, id).await? else { return Ok(not_found_page(&st)); }; let opts = legal::options(&st.db).await?; Ok(form_page( &st, &user, kind, Some(id), &r.values, &opts, &Errors::new(), StatusCode::OK, &Check::default(), )) } pub async fn update(kind: &'static Kind, st: Arc, user: User, id: i64, f: Fields) -> Res { let opts = legal::options(&st.db).await?; let values = records::read(kind, &f); let errors = records::validate(kind, &values, &opts); let Some(before) = records::get(&st.db, kind, None, id).await? else { return Ok(not_found_page(&st)); }; if !errors.is_empty() { let status = StatusCode::UNPROCESSABLE_ENTITY; return Ok(form_page( &st, &user, kind, Some(id), &values, &opts, &errors, status, &Check::default(), )); } // a client with a new name or number is checked again let mut checked = String::new(); if kind.slug == "clients" && CLIENT_CHECKED .iter() .any(|n| records::val(&before.values, n) != records::val(&values, n)) { match run_check(&st, &client_probe(&values), For::Client(Some(id)), &f).await? { Ok(said) => checked = said, Err(check) => { return Ok(form_page( &st, &user, kind, Some(id), &values, &opts, &errors, StatusCode::CONFLICT, &check, )); } } } let (_, list, _) = section(kind); let mut tx = st.db.begin().await?; let Some(old) = records::get_for_update(&mut tx, kind, None, id).await? else { return Ok(not_found_page(&st)); }; let said = legal::changes_of(kind, &old.values, &values, &opts); if !said.is_empty() { records::update(&mut tx, kind, None, id, &values).await?; let (client, contract) = about(kind, id, &values); let detail = if kind.slug == "contracts" { let code: String = sqlx::query_scalar("SELECT code FROM contracts WHERE id = $1") .bind(id) .fetch_one(&mut *tx) .await?; format!("{code}. {said}") } else if checked.is_empty() { said } else { format!("{said}. {checked}") }; journal::append( &mut tx, &New { actor: &user.login, client, contract, event: &format!("{} changed", kind.one), detail, }, ) .await?; let fields = records::changed(kind, &old.values, &values); audit::record( &mut *tx, &audit_entry(&user, Action::Update, kind.entity, id, &fields), ) .await?; } tx.commit().await?; Ok(Redirect::to(&format!("{list}/{id}")).into_response()) } // ------------------------------------------------------------- lawyers #[derive(Debug, Serialize, sqlx::FromRow)] struct LawyerRow { id: i64, name: String, name_th: String, license_no: String, email: String, phone: String, login: String, status: String, clients: i64, open: i64, } pub async fn lawyers(State(st): State>, Extension(user): Extension) -> Res { let rows: Vec = sqlx::query_as( "SELECT l.id, l.name, l.name_th, l.license_no, l.email, l.phone, l.login, l.status, \ (SELECT count(*) FROM clients c WHERE c.lawyer_id = l.id AND c.status = 'active') AS clients, \ (SELECT count(*) FROM contracts k WHERE k.lawyer_id = l.id \ AND k.status NOT IN ('ended', 'terminated', 'dropped')) AS open \ FROM lawyers l ORDER BY l.status, lower(l.name), l.id", ) .fetch_all(&st.db) .await?; Ok(page( &st, &user, "lawyers.html", "Lawyers", "lawyers", StatusCode::OK, context! { rows }, )) } /// A lawyer's page is their contracts. pub async fn lawyer(Path(id): Path) -> Response { Redirect::to(&format!("/contracts?lawyer={id}")).into_response() } // ------------------------------------------------------------- clients #[derive(Debug, Deserialize)] pub struct ClientsQuery { #[serde(default)] former: Option, } #[derive(Debug, Serialize)] struct ClientCard { #[serde(flatten)] row: legal::ClientRow, initials: String, last: String, q: String, } fn initials(name: &str) -> String { let words: Vec<&str> = name .split(|c: char| c.is_whitespace() || c == ',') .filter(|w| w.chars().next().is_some_and(char::is_alphanumeric)) // "Co., Ltd." says nothing about who it is .filter(|w| { let w = w.trim_end_matches('.').to_lowercase(); !matches!( w.as_str(), "co" | "ltd" | "limited" | "inc" | "llc" | "plc" | "gmbh" ) }) .collect(); let pick: Vec<&str> = match words.as_slice() { [] => vec![], [one] => vec![one], [first, .., last] => vec![first, last], }; pick.iter() .filter_map(|w| w.chars().next()) .flat_map(char::to_uppercase) .collect() } pub async fn clients( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let former = q.former.as_deref() == Some("1"); let cards: Vec = legal::list_clients(&st.db, former) .await? .into_iter() .map(|r| ClientCard { initials: initials(&r.name), last: r.last.map(dates::fmt_datetime).unwrap_or_default(), q: [&r.name, &r.name_th, &r.known_as, &r.nationality, &r.email] .iter() .map(|s| s.to_lowercase()) .collect::>() .join(" "), row: r, }) .collect(); let n_former: i64 = sqlx::query_scalar("SELECT count(*) FROM clients WHERE status = 'former'") .fetch_one(&st.db) .await?; let title = if former { "Former clients" } else { "Clients" }; Ok(page( &st, &user, "clients.html", title, "clients", StatusCode::OK, context! { cards, former, n_former }, )) } #[derive(Debug, Serialize)] struct ContractRow { #[serde(flatten)] c: legal::Listed, kind_label: &'static str, artist: bool, status_label: &'static str, chip: Option, ends: String, q: String, } async fn contract_rows(st: &AppState, f: &Filter) -> anyhow::Result> { let today = dates::today(); Ok(legal::list_contracts(&st.db, f) .await? .into_iter() .map(|c| { let mut v = Values::new(); v.insert("status".into(), c.status.clone()); for (k, d) in [("ends_on", c.ends_on), ("notice_by", c.notice_by)] { if let Some(d) = d { v.insert(k.into(), d.format("%Y-%m-%d").to_string()); } } ContractRow { kind_label: records::label(legal::CONTRACT_KINDS, &c.kind).unwrap_or("Other"), artist: legal::is_artist(&c.kind), status_label: records::label(legal::CONTRACT_STATUSES, &c.status).unwrap_or(""), chip: (CONTRACTS.status)(&v, today), ends: c.ends_on.map(dates::fmt_date).unwrap_or_default(), q: [&c.code, &c.title, &c.client, &c.counterparty] .iter() .map(|s| s.to_lowercase()) .collect::>() .join(" "), c, } }) .collect()) } #[derive(Debug, Serialize)] pub(crate) struct JournalView { seq: i64, at: String, actor: String, event: String, detail: String, hash: String, short: String, contract_id: Option, } pub(crate) fn journal_views(entries: Vec) -> Vec { entries .into_iter() .map(|e| JournalView { seq: e.seq, at: dates::fmt_datetime(e.at), actor: e.actor, event: e.event, detail: e.detail, short: e.hash[..12].to_string(), hash: e.hash, contract_id: e.contract_id, }) .collect() } pub async fn client_page( State(st): State>, Extension(user): Extension, Path(id): Path, ) -> Res { let Some(r) = records::get(&st.db, &CLIENTS, None, id).await? else { return Ok(not_found_page(&st)); }; let opts = legal::options(&st.db).await?; let shown = records::show(&CLIENTS, &r, &opts, dates::today()); let f = Filter { client: Some(id), all: true, ..Filter::default() }; let contracts = contract_rows(&st, &f).await?; let entries = journal_views(journal::list(&st.db, Some(id), None, 30).await?); let originals = super::originals::card(&st, crate::originals::Owner::Client(id)).await?; let name = r.get("name").to_string(); audit::record( &st.db, &audit_entry(&user, Action::View, Entity::Client, id, &[]), ) .await?; Ok(page( &st, &user, "legal_client.html", &name, "clients", StatusCode::OK, context! { id, name, shown, contracts, entries, originals, initials => initials(&name), name_th => r.get("name_th"), known_as => r.get("known_as"), kind => r.get("kind"), former => r.get("status") == "former", }, )) } // ----------------------------------------------------------- contracts #[derive(Debug, Deserialize)] pub struct ContractsQuery { #[serde(default)] lawyer: Option, #[serde(default)] group: Option, #[serde(default)] all: Option, #[serde(default)] mine: Option, } pub async fn contracts( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let me = legal::lawyer_of_login(&st.db, &user.login).await?; let lawyer = if q.mine.is_some() { me.or(Some(-1)) } else { q.lawyer }; let group = q.group.filter(|g| g == "artist" || g == "general"); let f = Filter { lawyer, group: group.clone(), all: q.all.as_deref() == Some("1"), ..Filter::default() }; let rows = contract_rows(&st, &f).await?; let lawyer_name: Option = match lawyer { Some(l) => { sqlx::query_scalar("SELECT name FROM lawyers WHERE id = $1") .bind(l) .fetch_optional(&st.db) .await? } None => None, }; // the filters as links that keep each other let href = |group: Option<&str>, all: bool| { let mut p: Vec = Vec::new(); if let Some(l) = lawyer.filter(|_| q.mine.is_none()) { p.push(format!("lawyer={l}")); } if q.mine.is_some() { p.push("mine=1".into()); } if let Some(g) = group { p.push(format!("group={g}")); } if all { p.push("all=1".into()); } if p.is_empty() { "/contracts".to_string() } else { format!("/contracts?{}", p.join("&")) } }; let all = f.all; let g = group.as_deref(); let tabs = vec![ (href(None, all), "All kinds", g.is_none()), (href(Some("general"), all), "General", g == Some("general")), (href(Some("artist"), all), "Artists", g == Some("artist")), ]; let over_href = href(g, !all); Ok(page( &st, &user, "contracts.html", "Contracts", "contracts", StatusCode::OK, context! { rows, tabs, all, over_href, lawyer_name, mine => q.mine.is_some(), me => me.is_some(), }, )) } #[derive(Debug, Serialize)] struct VersionView { version: i32, note: String, by: String, at: String, body_sha: String, file_sha: String, has_text: bool, file: String, file_name: String, chars: usize, } #[derive(Debug, Serialize)] struct PaperView { id: i64, code: String, what: String, version: Option, location: String, state: String, state_label: &'static str, holder: String, moved: String, gone: bool, } #[derive(Debug, Default, Deserialize)] pub struct ContractQuery { /// The version shown; the newest otherwise. #[serde(default)] v: Option, /// Compare the shown version with the one before. #[serde(default)] compare: Option, } /// What the contract page's forms show again after a post: the version /// form's, and the party form's with its conflict check. #[derive(Default)] struct Shown { errors: Errors, note: String, body: String, status: StatusCode, party: legal::NewParty, party_errors: Errors, check: Check, } #[derive(Debug, Serialize)] struct PartyView { id: i64, name: String, name_th: String, id_no: String, role: String, by: String, added: String, removed: Option, removed_by: Option, } async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, form: Shown) -> Res { let (Some(head), Some(r)) = ( legal::head(&st.db, id).await?, records::get(&st.db, &CONTRACTS, None, id).await?, ) else { return Ok(not_found_page(st)); }; let opts = legal::options(&st.db).await?; let shown = records::show(&CONTRACTS, &r, &opts, dates::today()); let all = legal::versions(&st.db, id).await?; let mut versions = Vec::new(); for v in &all { let (file, file_name) = match v.document_id { Some(d) => { let name: String = sqlx::query_scalar("SELECT file_name FROM documents WHERE id = $1") .bind(d) .fetch_one(&st.db) .await?; (format!("/contracts/{id}/versions/{}/file", v.version), name) } None => (String::new(), String::new()), }; versions.push(VersionView { version: v.version, note: v.note.clone(), by: v.added_by.clone(), at: dates::fmt_datetime(v.added_at), body_sha: v.body_sha256.clone().unwrap_or_default(), file_sha: v.file_sha256.clone().unwrap_or_default(), has_text: !v.body.is_empty(), chars: v.body.chars().count(), file, file_name, }); } // the version to read: asked for, else the newest with a text let current = match q.v { Some(n) => match all.iter().find(|v| v.version == n) { Some(v) => Some(v), None => return Ok(not_found_page(st)), }, None => all.iter().find(|v| !v.body.is_empty()), }; let before = current.and_then(|c| { all.iter() .filter(|v| v.version < c.version && !v.body.is_empty()) .max_by_key(|v| v.version) }); let compare = q.compare.is_some() && before.is_some(); let diff = match (compare, current, before) { (true, Some(c), Some(b)) => legal::diff(&b.body, &c.body), _ => None, }; let papers: Vec = legal::papers(&st.db, id) .await? .into_iter() .map(|p| PaperView { id: p.id, version: p .version_id .and_then(|vid| all.iter().find(|v| v.id == vid)) .map(|v| v.version), state_label: legal::paper_state(&p.state), gone: matches!(p.state.as_str(), "handed-over" | "destroyed"), moved: dates::fmt_datetime(p.moved_at), code: p.code, what: p.what, location: p.location, state: p.state, holder: p.holder, }) .collect(); let parties: Vec = legal::parties(&st.db, id) .await? .into_iter() .map(|p| PartyView { id: p.id, added: dates::fmt_datetime(p.added_at), removed: p.removed_at.map(dates::fmt_datetime), removed_by: p.removed_by, by: p.added_by, name: p.name, name_th: p.name_th, id_no: p.id_no, role: p.role, }) .collect(); let live_parties = parties.iter().filter(|p| p.removed.is_none()).count(); let review_parties: Vec<(String, String)> = parties .iter() .filter(|p| p.removed.is_none()) .map(|p| (p.id.to_string(), p.name.clone())) .collect(); let text_versions: Vec<(String, String)> = all .iter() .filter(|v| !v.body.is_empty()) .map(|v| { ( v.version.to_string(), format!("Version {}: {}", v.version, v.note), ) }) .collect(); let reviews = super::reviews::card(st, id).await?; let entries = journal_views(journal::list(&st.db, None, Some(id), 50).await?); let client_name: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1") .bind(head.client_id) .fetch_one(&st.db) .await?; let kind = r.get("kind"); audit::record( &st.db, &audit_entry(user, Action::View, Entity::Contract, id, &[]), ) .await?; Ok(page( st, user, "contract.html", &format!("{} {}", head.code, head.title), "contracts", form.status, context! { id, shown, versions, papers, entries, client_name, diff, compare, parties, live_parties, review_parties, text_versions, reviews, party => form.party, party_errors => form.party_errors, check => form.check, roles => legal::PARTY_ROLES, opened => dates::fmt_datetime(head.created_at), head, kind_label => records::label(legal::CONTRACT_KINDS, kind).unwrap_or("Other"), artist => legal::is_artist(kind), reading => current.map(|v| v.version), reading_note => current.map(|v| v.note.clone()), reading_sha => current.and_then(|v| v.body_sha256.clone()), blocks => current.map(|v| agreements::blocks(&v.body)).unwrap_or_default(), before => before.map(|v| v.version), next_version => all.first().map_or(1, |v| v.version + 1), draft_body => if form.body.is_empty() { all.iter().find(|v| !v.body.is_empty()).map(|v| v.body.clone()).unwrap_or_default() } else { form.body }, draft_note => form.note, errors => form.errors, states => legal::PAPER_STATES, whats => legal::PAPER_WHATS, locations => legal::locations(&st.db).await?, body_limit => legal::BODY_LIMIT, file_mb => FILE_LIMIT / (1024 * 1024), uploads => st.files.is_some(), }, )) } /// The contract page with the version form filled: the next version's /// start, from the other side's changes (`web::reviews::take`). pub(crate) async fn contract_with_draft( st: &AppState, user: &User, id: i64, note: String, body: String, ) -> Res { let form = Shown { note, body, status: StatusCode::OK, ..Shown::default() }; contract_view(st, user, id, &ContractQuery::default(), form).await } pub async fn contract_page( State(st): State>, Extension(user): Extension, Path(id): Path, Query(q): Query, ) -> Res { contract_view(&st, &user, id, &q, Shown::default()).await } /// The fields of the version form, as they arrived. #[derive(Default)] struct VersionForm { note: String, body: String, file: Option<(String, Vec)>, too_big: bool, } /// The longest text field, in bytes: the body in Thai takes three a /// character. const BODY_BYTES: usize = legal::BODY_LIMIT * 4; async fn read_version_form( user: &User, mut mp: Multipart, ) -> Result, axum::extract::multipart::MultipartError> { let token = match mp.next_field().await? { Some(mut f) if f.name() == Some("csrf") => read_field(&mut f, 4096) .await? .map(|b| String::from_utf8_lossy(&b).into_owned()), _ => None, }; if !token.is_some_and(|t| session::same_token(&t, &user.csrf)) { return Ok(None); } let mut out = VersionForm::default(); while let Some(mut field) = mp.next_field().await? { match field.name().unwrap_or_default() { "file" => { let name = documents::clean_name(field.file_name().unwrap_or_default()); match read_field(&mut field, FILE_LIMIT).await? { Some(b) if b.is_empty() => {} Some(b) => out.file = Some((name, b)), None => out.too_big = true, } } "note" => { if let Some(b) = read_field(&mut field, 4096).await? { out.note = String::from_utf8_lossy(&b).trim().to_string(); } } "body" => match read_field(&mut field, BODY_BYTES).await? { Some(b) => out.body = String::from_utf8_lossy(&b).into_owned(), None => out.too_big = true, }, _ => {} } } Ok(Some(out)) } /// A new version: a text, a file or both. The text as it stands on the /// page is the last version's, so a version with only a new file keeps no /// copy of an unchanged text. pub async fn add_version( State(st): State>, Extension(user): Extension, Path(id): Path, mp: Multipart, ) -> Res { let Some(head) = legal::head(&st.db, id).await? else { return Ok(not_found_page(&st)); }; let form = match read_version_form(&user, mp).await { Ok(Some(f)) => f, Ok(None) => return Ok(super::expired(&st)), Err(e) => { return Ok(message( &st, StatusCode::BAD_REQUEST, "The upload was cut short", &format!( "The version did not arrive whole ({}). Go back and send it again.", e.body_text() ), (&format!("/contracts/{id}"), "Back to the contract"), )); } }; let all = legal::versions(&st.db, id).await?; let last_text = all .iter() .find(|v| !v.body.is_empty()) .map(|v| v.body.as_str()); let body = agreements::normalize(&form.body); // an unchanged text is not kept again let new_text = if Some(body.as_str()) == last_text { "" } else { body.as_str() }; let mut errors = Errors::new(); if form.note.is_empty() { err( &mut errors, "note", "Say what this version is, such as: the label's changes of Nov 21.", ); } if st.cfg.demo() && form.file.is_some() { err( &mut errors, "file", "Uploads are off in the demo. Paste the text instead; it is kept as the version.", ); } if form.too_big { err( &mut errors, "file", format!( "The file is larger than {} MB, or the text longer than {} characters.", FILE_LIMIT / (1024 * 1024), legal::BODY_LIMIT ), ); } if body.chars().count() > legal::BODY_LIMIT { err( &mut errors, "body", format!("The text is longer than {} characters.", legal::BODY_LIMIT), ); } let mut file = None; if let Some((name, bytes)) = form.file { match files::sniff(&bytes) { None => err( &mut errors, "file", format!("{name} is not a PDF, JPEG, PNG or WebP file."), ), Some(ct) => { let sha = files::sha256_hex(&bytes); if let Some(d) = documents::same_file(&st.db, Owner::Client(head.client_id), &sha).await? { err( &mut errors, "file", format!( "{name} is this client's already, added {}.", dates::fmt_datetime(d.uploaded_at) ), ); } else { file = Some((name, bytes, ct, sha)); } } } } if new_text.is_empty() && file.is_none() && !form.too_big { err( &mut errors, "body", "Change the text or choose a file: a version needs something new.", ); } if file.is_some() && st.files.is_none() { err( &mut errors, "file", "This server keeps no files: add the text only.", ); } if !errors.is_empty() { let shown = Shown { errors, note: form.note, body: form.body, status: StatusCode::UNPROCESSABLE_ENTITY, ..Shown::default() }; let q = ContractQuery::default(); return contract_view(&st, &user, id, &q, shown).await; } let owner = Owner::Client(head.client_id); let mut tx = st.db.begin().await?; let mut written = None; let result: anyhow::Result = async { let vf = match &file { Some((name, bytes, ct, sha)) => { let meta = Meta { kind: "contract".into(), note: format!("{}: {}", head.code, form.note), ..Meta::default() }; let nf = NewFile { name, content_type: ct, size: i32::try_from(bytes.len())?, sha256: sha, }; let doc = documents::insert(&mut tx, owner, &meta, &nf, &user.login).await?; if let Some(store) = &st.files { store.put(doc, bytes.clone()).await?; written = Some(doc); } let fields = meta.set_fields(); audit::record( &mut *tx, &audit_entry(&user, Action::Create, Entity::Document, doc, &fields), ) .await?; Some((doc, sha.clone(), name.clone())) } None => None, }; let vfile = vf.as_ref().map(|(doc, sha, name)| legal::VersionFile { document: *doc, sha256: sha, name, }); let v = legal::add_version( &mut tx, &head, &form.note, new_text, vfile.as_ref(), &user.login, ) .await?; audit::record( &mut *tx, &audit_entry(&user, Action::Create, Entity::ContractVersion, v.id, &[]), ) .await?; Ok(v) } .await; match result { Ok(v) => { tx.commit().await?; Ok(Redirect::to(&format!("/contracts/{id}?v={}#versions", v.version)).into_response()) } Err(e) => { if let (Some(doc), Some(store)) = (written, &st.files) { let _ = store.remove(doc).await; } Err(e.into()) } } } /// A version's file, through the documents' handler: checked against its /// checksum and written to the audit log. pub async fn version_file( State(st): State>, Extension(user): Extension, Path((id, n)): Path<(i64, i32)>, Query(q): Query, ) -> Res { let found: Option<(i64, Option)> = sqlx::query_as( "SELECT c.client_id, v.document_id FROM contract_versions v \ JOIN contracts c ON c.id = v.contract_id WHERE v.contract_id = $1 AND v.version = $2", ) .bind(id) .bind(n) .fetch_optional(&st.db) .await?; let Some((client, Some(doc))) = found else { return Ok(not_found_page(&st)); }; super::documents::file(st, user, Owner::Client(client), doc, q).await } // -------------------------------------------------------- paper copies // ------------------------------------------------------------- parties fn party_of(f: &Fields) -> legal::NewParty { let g = |n: &str| crate::forms::get(f, n).trim().to_string(); legal::NewParty { name: g("party_name"), name_th: g("party_name_th"), id_no: g("party_id_no"), role: g("party_role"), } } /// Adds another party to a contract, after the conflict check: matches /// that need a decision show on the form until a lawyer clears them. pub async fn add_party( State(st): State>, Extension(user): Extension, Path(id): Path, Form(f): Form, ) -> Res { let Some(head) = legal::head(&st.db, id).await? else { return Ok(not_found_page(&st)); }; let party = party_of(&f); let mut errors = Errors::new(); if party.name.is_empty() { err(&mut errors, "party_name", "Enter the other party's name."); } for (k, v) in [ ("party_name", &party.name), ("party_name_th", &party.name_th), ("party_id_no", &party.id_no), ("party_role", &party.role), ] { if v.len() > 300 { err(&mut errors, k, "At most 300 characters."); } } let q = ContractQuery::default(); if !errors.is_empty() { let form = Shown { status: StatusCode::UNPROCESSABLE_ENTITY, party, party_errors: errors, ..Shown::default() }; return contract_view(&st, &user, id, &q, form).await; } let probe = Probe { names: vec![party.name.clone(), party.name_th.clone()], numbers: vec![party.id_no.clone()], }; let who = For::Party { contract: id, client: head.client_id, }; let checked = match run_check(&st, &probe, who, &f).await? { Ok(said) => said, Err(check) => { let form = Shown { status: StatusCode::CONFLICT, party, check, ..Shown::default() }; return contract_view(&st, &user, id, &q, form).await; } }; let mut tx = st.db.begin().await?; let p = legal::add_party(&mut tx, &head, &party, &checked, &user.login).await?; audit::record( &mut *tx, &audit_entry(&user, Action::Create, Entity::ContractParty, p.id, &[]), ) .await?; tx.commit().await?; Ok(Redirect::to(&format!("/contracts/{id}#party-{}", p.id)).into_response()) } /// Takes a party off a contract; it stays on record, marked removed. pub async fn remove_party( State(st): State>, Extension(user): Extension, Path((id, pid)): Path<(i64, i64)>, ) -> Res { let Some(head) = legal::head(&st.db, id).await? else { return Ok(not_found_page(&st)); }; let mut tx = st.db.begin().await?; if !legal::remove_party(&mut tx, &head, pid, &user.login).await? { return Ok(not_found_page(&st)); } audit::record( &mut *tx, &audit_entry(&user, Action::Delete, Entity::ContractParty, pid, &[]), ) .await?; tx.commit().await?; Ok(Redirect::to(&format!("/contracts/{id}#parties")).into_response()) } #[derive(Debug, Deserialize)] pub struct ConflictQuery { #[serde(default)] name: String, #[serde(default)] number: String, } /// The conflict check on its own, before a first meeting: nothing is /// saved, so nothing goes into the journal. pub async fn conflicts_page( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let (name, number) = (q.name.trim(), q.number.trim()); let probe = Probe { names: vec![name.to_string()], numbers: vec![number.to_string()], }; let asked = !probe.is_empty(); let hits = if asked { conflicts::check(&st.db, &probe, For::Search).await? } else { Vec::new() }; Ok(page( &st, &user, "conflicts.html", "Conflict check", "clients", StatusCode::OK, context! { name, number, asked, check => Check { hits, ask: false, note: String::new() }, }, )) } pub async fn add_paper( State(st): State>, Extension(user): Extension, Path(id): Path, Form(f): Form, ) -> Res { let Some(head) = legal::head(&st.db, id).await? else { return Ok(not_found_page(&st)); }; let what = crate::forms::get(&f, "what"); let location = crate::forms::get(&f, "location"); let all = legal::versions(&st.db, id).await?; let version = match crate::forms::get(&f, "version").trim().parse::() { Ok(n) => all.iter().find(|v| v.version == n), Err(_) => None, }; if what.trim().is_empty() || location.trim().is_empty() || what.len() > 300 || location.len() > 300 { return Ok(message( &st, StatusCode::UNPROCESSABLE_ENTITY, "Say what the paper is and where it lies", "A paper copy needs both: what it is (such as Signed original) and where it is filed.", (&format!("/contracts/{id}#papers"), "Back to the contract"), )); } let mut tx = st.db.begin().await?; let p = legal::add_paper(&mut tx, &head, version, &what, &location, &user.login).await?; audit::record( &mut *tx, &audit_entry(&user, Action::Create, Entity::PaperCopy, p.id, &[]), ) .await?; tx.commit().await?; Ok(Redirect::to(&format!("/contracts/{id}#paper-{}", p.id)).into_response()) } pub async fn move_paper( State(st): State>, Extension(user): Extension, Path(pid): Path, Form(f): Form, ) -> Res { let Some(p) = legal::paper(&st.db, pid).await? else { return Ok(not_found_page(&st)); }; let Some(head) = legal::head(&st.db, p.contract_id).await? else { return Ok(not_found_page(&st)); }; let location = crate::forms::get(&f, "location"); let state = crate::forms::get(&f, "state"); let holder = crate::forms::get(&f, "holder"); let note = crate::forms::get(&f, "note"); if location.trim().is_empty() || records::label(legal::PAPER_STATES, &state).is_none() || [&location, &holder, ¬e].iter().any(|s| s.len() > 300) { return Ok(message( &st, StatusCode::UNPROCESSABLE_ENTITY, "Say where the paper is", "A move needs the place where the paper is now, and its state from the list.", ( &format!("/contracts/{}#paper-{pid}", p.contract_id), "Back to the contract", ), )); } let mut tx = st.db.begin().await?; let m = legal::Move { location: &location, state: &state, holder: &holder, note: ¬e, }; if legal::move_paper(&mut tx, &head, &p, &m, &user.login).await? { let fields = ["location".to_string()]; audit::record( &mut *tx, &audit_entry(&user, Action::Update, Entity::PaperCopy, pid, &fields), ) .await?; } tx.commit().await?; Ok(Redirect::to(&format!("/contracts/{}#paper-{pid}", p.contract_id)).into_response()) } #[derive(Debug, Deserialize)] pub struct PaperQuery { #[serde(default)] code: Option, } /// Finds a paper by the id on it: the box on the Contracts page. pub async fn find_paper( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let code = q.code.unwrap_or_default(); found_paper(&st, &user, &code).await } /// `/papers/LD-2026-0007-P1`, the address in a label's QR code. pub async fn paper_by_code( State(st): State>, Extension(user): Extension, Path(code): Path, ) -> Res { found_paper(&st, &user, &code).await } async fn found_paper(st: &AppState, _user: &User, code: &str) -> Res { match legal::paper_by_code(&st.db, code).await? { Some(p) => Ok( Redirect::to(&format!("/contracts/{}#paper-{}", p.contract_id, p.id)).into_response(), ), None => Ok(message( st, StatusCode::NOT_FOUND, "No paper with this id", &format!( "No paper copy has the id {}. The id is on the paper's label, such as LD-2026-0007-P1.", code.trim() ), ("/contracts", "Back to the contracts"), )), } } /// The label to stick on a paper or its folder: the id large, a QR code to /// its page, the contract and version with its fingerprint, and where it /// belongs. pub async fn paper_label( State(st): State>, Extension(user): Extension, Path(pid): Path, ) -> Res { let Some(p) = legal::paper(&st.db, pid).await? else { return Ok(not_found_page(&st)); }; let Some(head) = legal::head(&st.db, p.contract_id).await? else { return Ok(not_found_page(&st)); }; let client: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1") .bind(head.client_id) .fetch_one(&st.db) .await?; let version: Option<(i32, Option, Option)> = match p.version_id { Some(v) => { sqlx::query_as( "SELECT version, body_sha256, file_sha256 FROM contract_versions WHERE id = $1", ) .bind(v) .fetch_optional(&st.db) .await? } None => None, }; let url = format!("{}/papers/{}", st.cfg.public_url, p.code); let qr = super::links::qr_svg(&url); let fingerprint = version .as_ref() .and_then(|(_, b, f)| f.clone().or(b.clone())) .map(|h| h[..16].to_string()) .unwrap_or_default(); Ok(page( &st, &user, "paper_label.html", &format!("Label {}", p.code), "contracts", StatusCode::OK, context! { p, head, client, qr, url, fingerprint, paper_version => version.map(|v| v.0), }, )) } // ------------------------------------------------------------- journal #[derive(Debug, Deserialize)] pub struct AnchorQuery { #[serde(default)] seq: String, #[serde(default)] hash: String, } /// Compares an anchor someone kept (a mail of the daily anchor, a note) /// with the journal as it is now. pub async fn anchor_check( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let asked = !q.seq.trim().is_empty() || !q.hash.trim().is_empty(); let mut error = String::new(); let mut result = None; if asked { match q.seq.trim().parse::() { Ok(seq) if seq > 0 && crate::anchor::is_hash(&q.hash) => { result = Some(crate::anchor::compare(&st.db, seq, &q.hash).await?); } _ => { error = "Enter the entry's number and its hash of 64 characters, as the anchor mail gives them.".into(); } } } let check = journal::verify(&st.db).await?; let status = if error.is_empty() { StatusCode::OK } else { StatusCode::UNPROCESSABLE_ENTITY }; Ok(page( &st, &user, "anchor_check.html", "Check an anchor", "journal", status, context! { seq => q.seq.trim(), hash => q.hash.trim(), error, result, whole => check.whole(), count => check.entries, }, )) } #[derive(Debug, Deserialize)] pub struct JournalQuery { #[serde(default)] contract: Option, #[serde(default)] client: Option, } pub async fn journal_page( State(st): State>, Extension(user): Extension, Query(q): Query, ) -> Res { let check = journal::verify(&st.db).await?; let entries = journal_views(journal::list(&st.db, q.client, q.contract, 500).await?); Ok(page( &st, &user, "journal.html", "Journal", "journal", StatusCode::OK, context! { entries, whole => check.whole(), problems => check.problems, count => check.entries, head => check.head, head_at => check.head_at.map(dates::fmt_datetime), filtered => q.client.is_some() || q.contract.is_some(), }, )) } /// The whole journal as CSV, for a copy kept outside this server. pub async fn journal_csv(State(st): State>, Extension(user): Extension) -> Res { let entries = journal::all(&st.db).await?; let fields = ["journal".to_string()]; audit::record( &st.db, &Entry { actor: &user.login, action: Action::Download, entity: Entity::Contract, entity_id: None, person_id: None, company_id: None, fields: &fields, }, ) .await?; let name = format!( "lanna-desk-journal-{}.csv", dates::today().format("%Y-%m-%d") ); let mut resp = Response::new(Body::from(journal::csv(&entries))); let h = resp.headers_mut(); h.insert( header::CONTENT_TYPE, HeaderValue::from_static("text/csv; charset=utf-8"), ); h.insert( header::CONTENT_DISPOSITION, super::documents::disposition("attachment", &name), ); Ok(resp) } #[cfg(test)] mod tests { use super::*; #[test] fn initials_take_the_first_and_last_word() { assert_eq!(initials("Demo Records Co., Ltd."), "DR"); assert_eq!(initials("Somchai Jaidee"), "SJ"); assert_eq!(initials("Lanna"), "L"); assert_eq!(initials("สมชาย ใจดี"), "สใ"); assert_eq!(initials(""), ""); } }