The other side reviews a draft (phase 13, step 1)
CI / secret scan (push) Successful in 5s
CI / fmt, clippy, tests (push) Successful in 49s
CI / release (push) Skipped

A lawyer sends a contract version to one of its parties with a link. On
it the other side marks the text up in an editor that keeps every change
visible, as tracked changes do: deleting our text crosses it out in red,
typing is marked as added in green, and the highlighter marks a passage
in yellow with a comment. Restore and Undo take marks back. They send it
back once a round; each later version comes on the same link.

- Migration 0014: review_links (token kept as a SHA-256, one open link a
  party) and review_rounds (the reply written once: their pieces, text,
  SHA-256, name, message; a trigger refuses any other change and every
  delete). Journal entries "sent for review", "review returned" (with the
  fingerprint of their text) and "review link closed"; audit entity
  "review".
- The reply is a list of pieces (same, ins, del, mark). The server checks
  that the pieces without the added ones are exactly the version sent, so
  nothing changes unseen (reviews::check).
- Our review page: their message, the changes numbered with the words
  around them and a box each, the highlights with comments, a git-style
  diff (line numbers, - and + lines, the changed words marked, three lines
  of context per hunk) and their markup. "Take the ticked changes" opens
  the contract page with the version form filled with our text plus those
  changes.
- static/review-editor.js: edits work on the pieces and redraw, so our
  text cannot vanish; keyboard compositions and edits the browser will not
  cancel are compared with the text and taken as edits.
- Property tests (any markup is accepted and taken back exactly; markup
  that changes our text unseen is refused), the fuzz text target runs
  reviews::check, integration tests, and the demo has the label's review
  of the recording agreement.
- PLAN: phase 13.
This commit is contained in:
grabowski committed 2026-11-23 15:31:43 +07:00
1 parent ff716eb9d3
commit a4155548b8
24 files changed
+3004 -6

No files matched your search

+1 -1
View File
@@ -1093,7 +1093,7 @@ fn drawing(f: &Fields) -> Result<Option<Vec<u8>>, &'static str> {
}
/// The client's address as the proxy in front of the app forwarded it.
fn client_ip(headers: &axum::http::HeaderMap) -> String {
pub(crate) fn client_ip(headers: &axum::http::HeaderMap) -> String {
headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
+35 -1
View File
@@ -876,6 +876,22 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f
})
.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)
@@ -896,7 +912,7 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f
form.status,
context! {
id, shown, versions, papers, entries, client_name, diff, compare,
parties, live_parties,
parties, live_parties, review_parties, text_versions, reviews,
party => form.party,
party_errors => form.party_errors,
check => form.check,
@@ -928,6 +944,24 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f
))
}
/// 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<Arc<AppState>>,
Extension(user): Extension<User>,
+22
View File
@@ -15,6 +15,7 @@ pub mod pack;
pub mod papers;
pub mod people;
pub mod records;
pub mod reviews;
use std::sync::{Arc, RwLock};
use std::time::Duration;
@@ -334,6 +335,15 @@ pub fn router(st: Arc<AppState>) -> Router {
),
);
}
// The other side's review page: open without a login, it checks its
// link. The marked-up text of a long Thai contract urlencodes to a few
// megabytes.
r = r.route(
"/r/{token}",
get(reviews::party_show)
.post(reviews::party_reply)
.layer(DefaultBodyLimit::max(REVIEW_LIMIT)),
);
// The client's pages: open without a login, each checks its link.
r = r
.route("/c/{token}", get(client::overview))
@@ -443,6 +453,13 @@ pub fn router(st: Arc<AppState>) -> Router {
post(l::remove_party),
)
.route("/conflicts", get(l::conflicts_page))
.route("/contracts/{id}/reviews", post(reviews::send))
.route("/contracts/{id}/reviews/{rid}", get(reviews::show))
.route("/contracts/{id}/reviews/{rid}/take", post(reviews::take))
.route(
"/contracts/{id}/review-links/{lid}/close",
post(reviews::close),
)
.route("/originals", get(originals::list).post(originals::create))
.route("/originals/new", get(originals::new))
.route("/originals/{code}", get(originals::show))
@@ -494,8 +511,13 @@ fn is_public(path: &str) -> bool {
| "/favicon.ico"
) || path.starts_with("/static/")
|| path.starts_with("/c/")
|| path.starts_with("/r/")
}
/// The largest reply from the review page: the pieces of a text of
/// `legal::BODY_LIMIT` characters, urlencoded.
const REVIEW_LIMIT: usize = 8 * 1024 * 1024;
/// Lets a request through with its user, or sends the browser to the login.
async fn gate(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
if is_public(req.uri().path()) {
+543
View File
@@ -0,0 +1,543 @@
//! The review pages (phase 13, `crate::reviews`). Staff: the card on the
//! contract page, sending a version to a party, reading what came back
//! (their markup, the git view, the changes to tick) and taking the ticked
//! changes into the version form. The other side: `/r/<token>`, the marking
//! editor and its Send back. Their POST carries the link's own form token,
//! as the client link's do.
use std::collections::BTreeSet;
use std::sync::Arc;
use axum::extract::{Path, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Extension, Form};
use minijinja::context;
use serde::Serialize;
use super::{AppState, Res, message, not_found_page, page, render};
use crate::audit::{self, Action, Entity, Entry};
use crate::forms::{self, Errors, Fields, err};
use crate::legal::{self, Head, Version};
use crate::reviews::{self, Link, Piece, Round};
use crate::session::{self, User};
use crate::{dates, embedded};
fn audit_entry<'a>(actor: &'a str, action: Action, id: i64, fields: &'a [String]) -> Entry<'a> {
Entry {
actor,
action,
entity: Entity::Review,
entity_id: Some(id),
person_id: None,
company_id: None,
fields,
}
}
/// A round as the contract page and the other side's page list it.
#[derive(Debug, Serialize)]
pub struct RoundView {
id: i64,
version: i32,
sent: String,
by: String,
message: String,
replied: Option<String>,
reply_name: String,
changes: usize,
highlights: usize,
}
fn round_view(r: &Round, versions: &[Version]) -> RoundView {
let pieces = r.pieces();
RoundView {
id: r.id,
version: versions
.iter()
.find(|v| v.id == r.version_id)
.map_or(0, |v| v.version),
sent: dates::fmt_datetime(r.sent_at),
by: r.sent_by.clone(),
message: r.message.clone(),
replied: r.replied_at.map(dates::fmt_datetime),
reply_name: r.reply_name.clone().unwrap_or_default(),
changes: reviews::changes(&pieces).len(),
highlights: reviews::highlights(&pieces).len(),
}
}
#[derive(Debug, Serialize)]
pub struct LinkView {
id: i64,
party: String,
open: bool,
state: String,
rounds: Vec<RoundView>,
}
/// The card on the contract page: the links with their rounds, and what a
/// version can be sent to.
pub async fn card(st: &AppState, contract: i64) -> anyhow::Result<Vec<LinkView>> {
let versions = legal::versions(&st.db, contract).await?;
Ok(reviews::for_contract(&st.db, contract)
.await?
.into_iter()
.map(|l| {
let state = match (l.link.closed_at, l.link.open()) {
(Some(at), _) => format!("closed {}", dates::fmt_datetime(at)),
(None, false) => "expired".to_string(),
(None, true) => match l.link.last_used_at {
Some(at) => format!("last opened {}", dates::fmt_datetime(at)),
None => "not opened yet".to_string(),
},
};
LinkView {
id: l.link.id,
open: l.link.open(),
state,
rounds: l.rounds.iter().map(|r| round_view(r, &versions)).collect(),
party: l.party,
}
})
.collect())
}
/// Sends a version to a party: a new round on their open link, or a new
/// link shown once.
pub async fn send(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
let Some(head) = legal::head(&st.db, id).await? else {
return Ok(not_found_page(&st));
};
let g = |k: &str| forms::get(&f, k).trim().to_string();
let party = legal::parties(&st.db, id)
.await?
.into_iter()
.find(|p| p.removed_at.is_none() && g("review_party") == p.id.to_string());
let versions = legal::versions(&st.db, id).await?;
let version = versions
.iter()
.find(|v| !v.body.is_empty() && g("review_version") == v.version.to_string());
let back = format!("/contracts/{id}#reviews");
let (Some(party), Some(version)) = (party, version) else {
return Ok(message(
&st,
StatusCode::UNPROCESSABLE_ENTITY,
"Choose the party and the version",
"Send a version with a text to one of the contract's parties.",
(&back, "Back to the contract"),
));
};
let note = g("review_message");
if note.chars().count() > 2000 {
return Ok(message(
&st,
StatusCode::UNPROCESSABLE_ENTITY,
"The message is too long",
"Write at most 2,000 characters to go with the version.",
(&back, "Back to the contract"),
));
}
let mut tx = st.db.begin().await?;
let (link, token, round) = reviews::send(
&mut tx,
&reviews::Send {
contract: &head,
party: party.id,
party_name: &party.name,
version,
message: &note,
},
&user.login,
)
.await?;
audit::record(
&mut *tx,
&audit_entry(&user.login, Action::Create, round.id, &[]),
)
.await?;
tx.commit().await?;
let url = token
.as_ref()
.map(|t| format!("{}/r/{t}", st.cfg.public_url));
let qr = url.as_deref().map(super::links::qr_svg);
Ok(page(
&st,
&user,
"review_made.html",
"Sent for review",
"contracts",
StatusCode::OK,
context! {
id, head, url, qr,
party => party.name,
review_version => version.version,
until => dates::fmt_date(link.expires_at.with_timezone(&dates::bangkok()).date_naive()),
},
))
}
pub async fn close(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, lid)): Path<(i64, i64)>,
) -> Res {
let (Some(head), Some(link)) = (
legal::head(&st.db, id).await?,
reviews::link(&st.db, id, lid).await?,
) else {
return Ok(not_found_page(&st));
};
let party = party_name(&st, link.party_id).await?;
let mut tx = st.db.begin().await?;
if reviews::close(&mut tx, &head, &link, &party, &user.login).await? {
let fields = ["closed".to_string()];
audit::record(
&mut *tx,
&audit_entry(&user.login, Action::Close, link.id, &fields),
)
.await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/contracts/{id}#reviews")).into_response())
}
async fn party_name(st: &AppState, party: i64) -> anyhow::Result<String> {
Ok(
sqlx::query_scalar("SELECT name FROM contract_parties WHERE id = $1")
.bind(party)
.fetch_one(&st.db)
.await?,
)
}
/// A round of this contract with its link, version and party.
async fn round_of(
st: &AppState,
contract: i64,
rid: i64,
) -> anyhow::Result<Option<(Head, Link, Round, Version, String)>> {
let Some(head) = legal::head(&st.db, contract).await? else {
return Ok(None);
};
let Some(round) = reviews::round(&st.db, rid).await? else {
return Ok(None);
};
let Some(link) = reviews::link(&st.db, contract, round.link_id).await? else {
return Ok(None);
};
let Some(version) = legal::versions(&st.db, contract)
.await?
.into_iter()
.find(|v| v.id == round.version_id)
else {
return Ok(None);
};
let party = party_name(st, link.party_id).await?;
Ok(Some((head, link, round, version, party)))
}
/// What came back: their markup, the git view and the changes to take.
pub async fn show(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, rid)): Path<(i64, i64)>,
) -> Res {
let Some((head, _link, round, version, party)) = round_of(&st, id, rid).await? else {
return Ok(not_found_page(&st));
};
let pieces = round.pieces();
audit::record(
&st.db,
&audit_entry(&user.login, Action::View, round.id, &[]),
)
.await?;
let replied = round.replied_at.is_some();
Ok(page(
&st,
&user,
"review.html",
&format!("{} review by {party}", head.code),
"contracts",
StatusCode::OK,
context! {
id, head, party, replied,
review_version => version.version,
round => round_view(&round, std::slice::from_ref(&version)),
reply_message => round.reply_message.clone().unwrap_or_default(),
reply_sha => round.reply_sha256.clone().unwrap_or_default(),
shown => reviews::shown(&pieces),
git => reviews::git_view(&pieces),
changes => reviews::changes(&pieces),
highlights => reviews::highlights(&pieces),
},
))
}
/// The ticked changes into the version form of the contract page.
pub async fn take(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, rid)): Path<(i64, i64)>,
// pairs, since every ticked box is one more `take`
Form(f): Form<Vec<(String, String)>>,
) -> Res {
let Some((_head, _link, round, version, party)) = round_of(&st, id, rid).await? else {
return Ok(not_found_page(&st));
};
let pieces = round.pieces();
let taken: BTreeSet<usize> = f
.iter()
.filter(|(k, _)| *k == "take")
.filter_map(|(_, v)| v.parse().ok())
.collect();
let all = reviews::changes(&pieces).len();
let body = reviews::apply(&pieces, &taken);
let day = round
.replied_at
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
.unwrap_or_default();
let note = match taken.len() {
0 => format!(
"Version {} again, after {party}'s review of {day}",
version.version
),
n if n == all => format!("{party}'s changes of {day} to version {}", version.version),
n => format!(
"{n} of {all} changes by {party} of {day} to version {}",
version.version
),
};
super::legal::contract_with_draft(&st, &user, id, note, body).await
}
// ------------------------------------------------------- the other side
fn closed(st: &AppState, title: &str, text: &str, status: StatusCode) -> Response {
render(
st,
"client_closed.html",
context! { title, text, v => embedded::STATIC_HASH },
status,
)
}
/// The link, if it still works; else the page that says why not.
async fn open_link(st: &AppState, token: &str) -> anyhow::Result<Result<Link, Response>> {
let link = reviews::by_token(&st.db, token).await?;
Ok(match link {
None => Err(closed(
st,
"This link does not work",
"There is no review link at this address. Check that you opened the whole link, or \
ask Lanna Desk for a new one.",
StatusCode::NOT_FOUND,
)),
Some(l) if !l.open() => Err(closed(
st,
"This link is closed",
"The review on this link has ended. Ask Lanna Desk for a new link if there is more to \
discuss.",
StatusCode::GONE,
)),
Some(l) => Ok(l),
})
}
/// What the other side's page shows, after a GET or a refused POST.
struct Editing {
pieces: Vec<Piece>,
name: String,
message: String,
errors: Errors,
status: StatusCode,
}
async fn party_page(st: &AppState, link: &Link, token: &str, e: Editing) -> Res {
let Some(head) = legal::head(&st.db, link.contract_id).await? else {
return Ok(not_found_page(st));
};
let versions = legal::versions(&st.db, link.contract_id).await?;
let rounds = reviews::rounds(&st.db, link.id).await?;
let Some(latest) = rounds.first() else {
return Ok(not_found_page(st));
};
let Some(version) = versions.iter().find(|v| v.id == latest.version_id) else {
return Ok(not_found_page(st));
};
let party = party_name(st, link.party_id).await?;
let client: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1")
.bind(head.client_id)
.fetch_one(&st.db)
.await?;
let pieces = if latest.replied_at.is_some() {
latest.pieces()
} else if e.pieces.is_empty() {
reviews::unmarked(&version.body)
} else {
e.pieces
};
let earlier: Vec<RoundView> = rounds
.iter()
.skip(1)
.map(|r| round_view(r, &versions))
.collect();
Ok(render(
st,
"party_review.html",
context! {
title => format!("{} {}", head.code, head.title),
v => embedded::STATIC_HASH,
demo => st.cfg.demo(),
head, party, client, earlier,
action => format!("/r/{token}"),
csrf => link.csrf.clone(),
round => round_view(latest, &versions),
round_id => latest.id,
replied => latest.replied_at.is_some(),
shown => reviews::shown(&pieces),
pieces => reviews::script_json(&pieces),
name => e.name,
reply_message => e.message,
errors => e.errors,
link_until => dates::fmt_date(link.expires_at.with_timezone(&dates::bangkok()).date_naive()),
},
e.status,
))
}
pub async fn party_show(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
let link = match open_link(&st, &token).await? {
Ok(l) => l,
Err(page) => return Ok(page),
};
reviews::used(&st.db, link.id).await?;
let actor = format!("review {}", link.id);
audit::record(&st.db, &audit_entry(&actor, Action::View, link.id, &[])).await?;
party_page(
&st,
&link,
&token,
Editing {
pieces: Vec::new(),
name: String::new(),
message: String::new(),
errors: Errors::new(),
status: StatusCode::OK,
},
)
.await
}
/// The other side sends their marked-up text back.
pub async fn party_reply(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
headers: HeaderMap,
Form(f): Form<Fields>,
) -> Res {
let link = match open_link(&st, &token).await? {
Ok(l) => l,
Err(page) => return Ok(page),
};
if !session::same_token(&forms::get(&f, "csrf"), &link.csrf) {
return Ok(closed(
&st,
"The page was too old",
"Go back, reload the page and send it again.",
StatusCode::FORBIDDEN,
));
}
let rounds = reviews::rounds(&st.db, link.id).await?;
let latest = match rounds.first() {
Some(r) if forms::get(&f, "round") == r.id.to_string() && r.replied_at.is_none() => r,
_ => {
return Ok(closed(
&st,
"This version was answered already",
"Lanna Desk has your reply to this version, or has sent a newer one since. \
Reload the link to see where things stand.",
StatusCode::CONFLICT,
));
}
};
let Some(head) = legal::head(&st.db, link.contract_id).await? else {
return Ok(not_found_page(&st));
};
let Some(version) = legal::versions(&st.db, link.contract_id)
.await?
.into_iter()
.find(|v| v.id == latest.version_id)
else {
return Ok(not_found_page(&st));
};
let name = forms::get(&f, "name").trim().to_string();
let note = forms::get(&f, "message").trim().to_string();
let mut errors = Errors::new();
let pieces = match reviews::check(&forms::get(&f, "pieces"), &version.body) {
Ok(p) => p,
Err(e) => {
err(&mut errors, "pieces", e);
Vec::new()
}
};
if name.is_empty() {
err(&mut errors, "name", "Say who sends this back.");
} else if name.chars().count() > 200 {
err(&mut errors, "name", "At most 200 characters.");
}
if note.chars().count() > 5000 {
err(&mut errors, "message", "At most 5,000 characters.");
}
if !errors.is_empty() {
return party_page(
&st,
&link,
&token,
Editing {
pieces,
name,
message: note,
errors,
status: StatusCode::UNPROCESSABLE_ENTITY,
},
)
.await;
}
let ip = super::client::client_ip(&headers);
let user_agent: String = headers
.get(axum::http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.chars()
.take(300)
.collect();
let party = party_name(&st, link.party_id).await?;
let mut tx = st.db.begin().await?;
let done = reviews::reply(
&mut tx,
&head,
&party,
version.version,
latest,
&reviews::Reply {
name: &name,
message: &note,
pieces: &pieces,
ip: &ip,
user_agent: &user_agent,
},
)
.await?;
if done {
let actor = format!("review {}", link.id);
audit::record(&mut *tx, &audit_entry(&actor, Action::Send, latest.id, &[])).await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/r/{token}?sent=1")).into_response())
}