//! The shared draft of a contract (phase 13): open for tracked edits by our //! team and every other party until all agree, then locked as a contract //! version. One side edits at a time: the editor holds a lease that each //! save renews and that ends by itself after `LEASE_SECS`, so a closed tab //! never keeps the draft. Every change is a row in `draft_saves`; taking a //! change in or dropping it, resolving a highlight, agreeing and locking //! are journal entries too. Any change voids the agreements given so far, //! since they are tied to the revision they were given at. use anyhow::{Result, bail}; use chrono::{DateTime, Utc}; use serde::Serialize; use sqlx::{PgConnection, PgPool}; use crate::files::sha256_hex; use crate::reviews::{self, Piece, US}; use crate::{journal, legal}; /// How long an editor keeps the draft without a save or a sign of life. pub const LEASE_SECS: i32 = 45; #[derive(Clone, Debug, sqlx::FromRow, Serialize)] pub struct Draft { pub contract_id: i64, pub base_version_id: i64, pub pieces: serde_json::Value, pub revision: i32, pub state: String, pub editor: Option, pub editor_name: Option, pub editor_until: Option>, pub opened_by: String, pub opened_at: DateTime, pub changed_at: DateTime, pub locked_at: Option>, pub locked_version_id: Option, } impl Draft { pub fn pieces(&self) -> Vec { reviews::from_json(&self.pieces) } pub fn open(&self) -> bool { self.state == "open" } /// Who edits now, if anyone: their key and name. pub fn editing(&self) -> Option<(&str, &str)> { match (&self.editor, &self.editor_until) { (Some(k), Some(until)) if *until > Utc::now() => { Some((k.as_str(), self.editor_name.as_deref().unwrap_or("Someone"))) } _ => None, } } } /// Who acts on a draft: a side, the key of this editor (`us:` or /// `party:`) and the name others see. #[derive(Clone, Debug)] pub struct Actor { pub side: String, pub key: String, pub name: String, /// the staff login; empty for a party pub login: String, } impl Actor { pub fn staff(login: &str, name: &str) -> Actor { Actor { side: US.to_string(), key: format!("us:{login}"), name: format!("{name} (Lanna Desk)"), login: login.to_string(), } } pub fn party(id: i64, party: &str) -> Actor { Actor { side: reviews::party_side(id), key: reviews::party_side(id), name: party.to_string(), login: String::new(), } } } /// Why a change to the draft did not happen. #[derive(Debug, PartialEq, Eq)] pub enum Refused { /// someone else edits now Busy(String), /// the page showed an older revision Stale, /// the draft is locked Locked, /// the change itself is wrong Wrong(&'static str), } impl Refused { pub fn message(&self) -> String { match self { Refused::Busy(name) => format!("{name} is editing the draft right now."), Refused::Stale => { "The draft changed in the meantime. It has been reloaded; try again.".into() } Refused::Locked => "The draft is locked: all sides agreed to it.".into(), Refused::Wrong(m) => (*m).to_string(), } } } pub type Outcome = Result>; pub async fn get(db: &PgPool, contract: i64) -> Result> { Ok( sqlx::query_as("SELECT * FROM contract_drafts WHERE contract_id = $1") .bind(contract) .fetch_optional(db) .await?, ) } async fn for_update(conn: &mut PgConnection, contract: i64) -> Result> { Ok( sqlx::query_as("SELECT * FROM contract_drafts WHERE contract_id = $1 FOR UPDATE") .bind(contract) .fetch_optional(&mut *conn) .await?, ) } fn pieces_sha(pieces: &[Piece]) -> String { sha256_hex(reviews::to_json(pieces).to_string().as_bytes()) } async fn saved( conn: &mut PgConnection, contract: i64, revision: i32, who: &Actor, kind: &str, pieces: &[Piece], ) -> Result<()> { let actor = if who.login.is_empty() { who.name.clone() } else { who.login.clone() }; sqlx::query( "INSERT INTO draft_saves (contract_id, revision, side, actor, kind, sha256) \ VALUES ($1, $2, $3, $4, $5, $6)", ) .bind(contract) .bind(revision) .bind(&who.side) .bind(actor) .bind(kind) .bind(pieces_sha(pieces)) .execute(&mut *conn) .await?; Ok(()) } /// Opens the draft from a version with a text. A locked draft can start /// over from a newer version (an amendment); an open one cannot. pub async fn open( conn: &mut PgConnection, head: &legal::Head, version: &legal::Version, by: &Actor, ) -> Result { if version.body.is_empty() { bail!("a draft needs a version with a text"); } let pieces = reviews::unmarked(&version.body); let json = reviews::to_json(&pieces); let d: Option = sqlx::query_as( "INSERT INTO contract_drafts (contract_id, base_version_id, pieces, opened_by) \ VALUES ($1, $2, $3, $4) \ ON CONFLICT (contract_id) DO UPDATE SET base_version_id = $2, pieces = $3, \ opened_by = $4, opened_at = now(), changed_at = now(), state = 'open', \ revision = contract_drafts.revision + 1, editor = NULL, editor_name = NULL, \ editor_until = NULL, locked_at = NULL, locked_version_id = NULL \ WHERE contract_drafts.state = 'locked' RETURNING *", ) .bind(head.id) .bind(version.id) .bind(&json) .bind(&by.login) .fetch_optional(&mut *conn) .await?; let Some(d) = d else { bail!("the contract has an open draft already"); }; saved(conn, head.id, d.revision, by, "opened", &pieces).await?; journal::append( conn, &journal::New { actor: &by.login, client: Some(head.client_id), contract: Some(head.id), event: "draft opened", detail: format!( "A shared draft opened from version {}. Text SHA-256 {}.", version.version, version.body_sha256.as_deref().unwrap_or("none") ), }, ) .await?; Ok(d) } /// Takes the draft for editing, or renews the lease of whoever has it. pub async fn take(conn: &mut PgConnection, contract: i64, who: &Actor) -> Outcome { let d: Option = sqlx::query_as( "UPDATE contract_drafts SET editor = $2, editor_name = $3, \ editor_until = now() + make_interval(secs => $4) \ WHERE contract_id = $1 AND state = 'open' \ AND (editor IS NULL OR editor_until < now() OR editor = $2) RETURNING *", ) .bind(contract) .bind(&who.key) .bind(&who.name) .bind(LEASE_SECS) .fetch_optional(&mut *conn) .await?; if let Some(d) = d { return Ok(Ok(d)); } let now: Option = sqlx::query_as("SELECT * FROM contract_drafts WHERE contract_id = $1") .bind(contract) .fetch_optional(&mut *conn) .await?; Ok(Err(match now { Some(d) if !d.open() => Refused::Locked, Some(d) => Refused::Busy(d.editing().map_or("Someone".into(), |(_, n)| n.to_string())), None => Refused::Wrong("There is no shared draft."), })) } /// Gives the draft up, if this editor has it. pub async fn release(conn: &mut PgConnection, contract: i64, who: &Actor) -> Result<()> { sqlx::query( "UPDATE contract_drafts SET editor = NULL, editor_name = NULL, editor_until = NULL \ WHERE contract_id = $1 AND editor = $2", ) .bind(contract) .bind(&who.key) .execute(&mut *conn) .await?; Ok(()) } /// The draft for a change at `revision`: open, at that revision, and /// either nobody's or this editor's. async fn ready( conn: &mut PgConnection, contract: i64, who: &Actor, revision: i32, must_hold: bool, ) -> Result> { let Some(d) = for_update(conn, contract).await? else { return Ok(Err(Refused::Wrong("There is no shared draft."))); }; if !d.open() { return Ok(Err(Refused::Locked)); } match d.editing() { Some((k, name)) if k != who.key => return Ok(Err(Refused::Busy(name.to_string()))), None if must_hold => { return Ok(Err(Refused::Wrong( "Your editing time ran out. Press Edit to go on.", ))); } _ => {} } if d.revision != revision { return Ok(Err(Refused::Stale)); } Ok(Ok(d)) } async fn store( conn: &mut PgConnection, contract: i64, pieces: &[Piece], renew_for: Option<&Actor>, ) -> Result { let rev: i32 = sqlx::query_scalar( "UPDATE contract_drafts SET pieces = $2, revision = revision + 1, changed_at = now(), \ editor_until = CASE WHEN editor = $3 THEN now() + make_interval(secs => $4) \ ELSE editor_until END \ WHERE contract_id = $1 RETURNING revision", ) .bind(contract) .bind(reviews::to_json(pieces)) .bind(renew_for.map(|a| a.key.as_str())) .bind(LEASE_SECS) .fetch_one(&mut *conn) .await?; Ok(rev) } /// Saves the editor's tracked edits; returns the new revision, or the old /// one when nothing changed (the lease is renewed either way). pub async fn save( conn: &mut PgConnection, contract: i64, who: &Actor, revision: i32, new: &[Piece], ) -> Outcome { let d = match ready(conn, contract, who, revision, true).await? { Ok(d) => d, Err(r) => return Ok(Err(r)), }; let old = d.pieces(); if let Err(m) = reviews::check_save(&old, new, &who.side) { return Ok(Err(Refused::Wrong(m))); } if old == new { take(conn, contract, who).await?.ok(); return Ok(Ok(d.revision)); } let rev = store(conn, contract, new, Some(who)).await?; saved(conn, contract, rev, who, "edit", new).await?; Ok(Ok(rev)) } /// At most `n` characters of a text, on one line, for the journal. fn short(text: &str, n: usize) -> String { let one: String = text .chars() .map(|c| if c == '\n' { ' ' } else { c }) .collect(); let one = one.trim(); if one.chars().count() > n { format!("{}…", one.chars().take(n).collect::()) } else { one.to_string() } } /// The name of a side: Lanna Desk or a party's. pub async fn side_name(db: impl sqlx::PgExecutor<'_>, side: &str) -> Result { match reviews::party_of(side) { Some(id) => Ok(sqlx::query_scalar::<_, String>( "SELECT name FROM contract_parties WHERE id = $1", ) .bind(id) .fetch_optional(db) .await? .unwrap_or_else(|| "a former party".into())), None => Ok("Lanna Desk".into()), } } /// Takes change `n` in or drops it. Only another side takes a change in; /// its own side may withdraw it. pub async fn settle( conn: &mut PgConnection, head: &legal::Head, who: &Actor, revision: i32, n: usize, accept: bool, ) -> Outcome { let d = match ready(conn, head.id, who, revision, false).await? { Ok(d) => d, Err(r) => return Ok(Err(r)), }; let Some((new, change)) = reviews::settle(&d.pieces(), n, accept) else { return Ok(Err(Refused::Stale)); }; if accept && change.side == who.side { return Ok(Err(Refused::Wrong( "The other side takes your own changes in; you can withdraw them.", ))); } let rev = store(conn, head.id, &new, None).await?; saved( conn, head.id, rev, who, if accept { "accept" } else { "reject" }, &new, ) .await?; let by = side_name(&mut *conn, &change.side).await?; let what = match (change.removed.is_empty(), change.added.is_empty()) { (false, false) => format!( "\"{}\" becomes \"{}\"", short(&change.removed, 120), short(&change.added, 120) ), (false, true) => format!("\"{}\" taken out", short(&change.removed, 120)), _ => format!("\"{}\" added", short(&change.added, 120)), }; let verb = match (accept, change.side == who.side) { (true, _) => "accepted", (false, true) => "withdrew", (false, false) => "rejected", }; journal::append( conn, &journal::New { actor: &actor_of(who), client: Some(head.client_id), contract: Some(head.id), event: if accept { "change accepted" } else { "change rejected" }, detail: format!( "{} {verb} a change by {by} (draft revision {rev}): {what}.", who.name ), }, ) .await?; Ok(Ok(rev)) } fn actor_of(who: &Actor) -> String { if who.login.is_empty() { who.key.clone() } else { who.login.clone() } } /// Resolves highlight `k`: the text stays, the highlight goes. pub async fn resolve( conn: &mut PgConnection, head: &legal::Head, who: &Actor, revision: i32, k: usize, ) -> Outcome { let d = match ready(conn, head.id, who, revision, false).await? { Ok(d) => d, Err(r) => return Ok(Err(r)), }; let Some((new, h)) = reviews::resolve(&d.pieces(), k) else { return Ok(Err(Refused::Stale)); }; let rev = store(conn, head.id, &new, None).await?; saved(conn, head.id, rev, who, "resolve", &new).await?; let by = side_name(&mut *conn, &h.side).await?; journal::append( conn, &journal::New { actor: &actor_of(who), client: Some(head.client_id), contract: Some(head.id), event: "highlight resolved", detail: format!( "{} resolved a highlight by {by} on \"{}\"{}.", who.name, short(&h.text, 120), if h.comment.is_empty() { String::new() } else { format!(" (\"{}\")", short(&h.comment, 200)) } ), }, ) .await?; Ok(Ok(rev)) } /// The sides that must agree: Lanna Desk and every party still on the /// contract. pub async fn required(db: impl sqlx::PgExecutor<'_>, contract: i64) -> Result> { let parties: Vec = sqlx::query_scalar( "SELECT id FROM contract_parties WHERE contract_id = $1 AND removed_at IS NULL ORDER BY id", ) .bind(contract) .fetch_all(db) .await?; let mut out = vec![US.to_string()]; out.extend(parties.into_iter().map(reviews::party_side)); Ok(out) } #[derive(Clone, Debug, sqlx::FromRow, Serialize)] pub struct Agreement { pub side: String, pub actor: String, pub at: DateTime, } /// The agreements given at a revision. pub async fn agreements( db: impl sqlx::PgExecutor<'_>, contract: i64, revision: i32, ) -> Result> { Ok(sqlx::query_as( "SELECT side, actor, at FROM draft_agreements WHERE contract_id = $1 AND revision = $2 \ ORDER BY id", ) .bind(contract) .bind(revision) .fetch_all(db) .await?) } /// What an agreement did. #[derive(Debug, PartialEq, Eq)] pub enum Agreed { /// noted; other sides still have to agree Waiting, /// the last side agreed: the text is now this contract version Locked(i32), } /// Records a side's agreement to the text at `revision`. Open changes /// must be settled first. When every side has agreed, the text becomes a /// contract version and the draft locks. pub async fn agree( conn: &mut PgConnection, head: &legal::Head, who: &Actor, person: &str, revision: i32, ip: &str, user_agent: &str, ) -> Outcome { let d = match ready(conn, head.id, who, revision, false).await? { Ok(d) => d, Err(r) => return Ok(Err(r)), }; let pieces = d.pieces(); if !reviews::changes(&pieces).is_empty() { return Ok(Err(Refused::Wrong( "Accept or reject every open change first: the text to agree to is what stands.", ))); } // a highlight is an open question if !reviews::highlights(&pieces).is_empty() { return Ok(Err(Refused::Wrong( "Resolve every highlight first: each is a question still open.", ))); } let text = reviews::base(&pieces); let sha = sha256_hex(text.as_bytes()); let fresh = sqlx::query( "INSERT INTO draft_agreements (contract_id, revision, side, actor, text_sha256, ip, \ user_agent) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT DO NOTHING", ) .bind(head.id) .bind(revision) .bind(&who.side) .bind(person) .bind(&sha) .bind(ip) .bind(user_agent) .execute(&mut *conn) .await? .rows_affected() > 0; if fresh { journal::append( conn, &journal::New { actor: &actor_of(who), client: Some(head.client_id), contract: Some(head.id), event: "text agreed", detail: format!( "{} ({person}) agreed to the draft at revision {revision}. Text SHA-256 {sha}.", who.name ), }, ) .await?; } let need = required(&mut *conn, head.id).await?; let have = agreements(&mut *conn, head.id, revision).await?; if !need.iter().all(|s| have.iter().any(|a| &a.side == s)) { return Ok(Ok(Agreed::Waiting)); } // every side agreed: the text is set in stone let names: Vec = have.iter().map(|a| a.actor.clone()).collect::>(); let v = legal::add_version( conn, head, "Agreed by all sides in the shared draft, locked", &text, None, &actor_of(who), ) .await?; sqlx::query( "UPDATE contract_drafts SET state = 'locked', locked_at = now(), locked_version_id = $2, \ editor = NULL, editor_name = NULL, editor_until = NULL WHERE contract_id = $1", ) .bind(head.id) .bind(v.id) .execute(&mut *conn) .await?; journal::append( conn, &journal::New { actor: &actor_of(who), client: Some(head.client_id), contract: Some(head.id), event: "draft locked", detail: format!( "Every side agreed ({}); the draft is locked as version {}. Text SHA-256 {sha}.", names.join(", "), v.version ), }, ) .await?; Ok(Ok(Agreed::Locked(v.version))) }