diff --git a/docs/PLAN.md b/docs/PLAN.md index 511717f..d823e3a 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -248,6 +248,7 @@ dark at desktop and phone width, a commit and a push. | 10 | One client list: a visa record becomes part of a client; People becomes the visa clients | planned Nov 21, 2026 | | 11 | The conflict check and the other parties of a contract; the journal's last hash sent outside the server each day | built Nov 22, 2026 | | 12 | Originals in our care (passports, signed contracts, deeds: where each one is) and the inbox that files a pile of scans | step 1 built Nov 23, 2026 | +| 13 | The other side reviews a draft through a link: crosses out, adds, highlights; we take their changes one by one | step 1 built Nov 23, 2026 | | later | Thai user interface, agency cases and fees, other visa categories' packs | | ### Phase 1: app, login, people @@ -843,6 +844,44 @@ and record, with a suggestion to confirm. reminders once phase 8 sends them. - Phase 10 (one client list) turns an original's person into a client. +## Phase 13: the other side reviews a draft (planned Nov 23, 2026) + +Alex: when our lawyers draft a version, they send it to the other party +with a link; there the other party edits it and sends it back. It should +have an editor that crosses out words and highlights passages, and in the +end read like a git diff. + +### Step 1: the review link and the marking editor (built) + +- A lawyer sends a version with a text to one of the contract's parties + (Contract, Review by the other side). This makes a link for that party + (`/r/`, shown once, as the client links; 30 days) or, when the + party has an open one, a new round on the same link, so the other side + keeps one address for the whole negotiation. +- The other side's page shows our version in an editor that keeps every + change visible, as tracked changes do: what they delete stays in place, + crossed out in red; what they type is marked in green; the highlighter + marks a passage in yellow with an optional comment. Restore takes a mark + back. They send it back with their name and a covering message, once per + round; the page then shows what they sent until our next version. +- What they send is a list of pieces (same, added, crossed out, + highlighted). The server checks that the pieces without the added ones + give exactly the version we sent: nothing can change unseen. Their text + and its SHA-256 are kept unchanged (migration 0014, a trigger), and the + journal records each send and each reply with the fingerprints. +- Our review page shows their markup and a git-style diff (lines taken out + and added, the changed words marked), with each change numbered. The + lawyer ticks the changes to take; the contract page then opens with the + version form filled with our text plus those changes, to finish and add + as the next version, which can go back to them in the next round. + +### Step 2: later + +- Comments both ways on a highlighted passage (a thread per mark). +- Mail the link and each new round from reminders@ (phase 8 mail). +- Signing the agreed text on the link (with the agreements' drawing pad). +- Versions kept only as a file (a PDF draft): the editor works on text. + ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay diff --git a/fuzz/seeds/text/review-markup.txt b/fuzz/seeds/text/review-markup.txt new file mode 100644 index 0000000..d3192ea Binary files /dev/null and b/fuzz/seeds/text/review-markup.txt differ diff --git a/migrations/0014_reviews.sql b/migrations/0014_reviews.sql new file mode 100644 index 0000000..9f89a19 --- /dev/null +++ b/migrations/0014_reviews.sql @@ -0,0 +1,90 @@ +-- The other side reviews a draft (phase 13). A lawyer sends a version with +-- a text to one of the contract's parties: a link for that party (one open +-- at a time) and a round for the version. The other side marks the text up +-- (crossed out, added, highlighted) and sends it back once per round. +CREATE TABLE review_links ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL REFERENCES contracts (id), + party_id BIGINT NOT NULL REFERENCES contract_parties (id), + -- SHA-256 of the token in the link, as for the client links + token_hash BYTEA NOT NULL UNIQUE, + csrf TEXT NOT NULL, + created_by TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + first_used_at TIMESTAMPTZ, + last_used_at TIMESTAMPTZ, + closed_at TIMESTAMPTZ, + closed_by TEXT, + CHECK ((closed_at IS NULL) = (closed_by IS NULL)) +); +CREATE INDEX review_links_contract ON review_links (contract_id); +CREATE UNIQUE INDEX review_links_one_open ON review_links (party_id) WHERE closed_at IS NULL; + +CREATE TABLE review_rounds ( + id BIGSERIAL PRIMARY KEY, + link_id BIGINT NOT NULL REFERENCES review_links (id), + version_id BIGINT NOT NULL REFERENCES contract_versions (id), + -- what we wrote to them with this version + message TEXT NOT NULL DEFAULT '', + sent_by TEXT NOT NULL, + sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- their reply, written once + replied_at TIMESTAMPTZ, + reply_name TEXT, + reply_message TEXT, + -- the pieces: [["same"|"ins"|"del"|"mark", text, comment], ...] + reply_pieces JSONB, + -- their text: the pieces without the crossed-out ones + reply_body TEXT, + reply_sha256 TEXT CHECK (reply_sha256 ~ '^[0-9a-f]{64}$'), + reply_ip TEXT, + reply_user_agent TEXT, + CHECK ( + (replied_at IS NULL) = (reply_name IS NULL) + AND (replied_at IS NULL) = (reply_pieces IS NULL) + AND (replied_at IS NULL) = (reply_body IS NULL) + AND (replied_at IS NULL) = (reply_sha256 IS NULL) + ) +); +CREATE INDEX review_rounds_link ON review_rounds (link_id); + +-- A round never changes, but for its reply, written once. +CREATE FUNCTION review_rounds_kept() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'a review round stays on record'; + END IF; + IF OLD.replied_at IS NOT NULL + OR NEW.link_id <> OLD.link_id OR NEW.version_id <> OLD.version_id + OR NEW.message <> OLD.message OR NEW.sent_by <> OLD.sent_by + OR NEW.sent_at <> OLD.sent_at THEN + RAISE EXCEPTION 'a review round never changes; its reply is written once'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER review_rounds_no_change +BEFORE UPDATE OR DELETE ON review_rounds +FOR EACH ROW EXECUTE FUNCTION review_rounds_kept(); + +CREATE FUNCTION review_links_kept() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'a review link stays on record: close it'; +END +$$; +CREATE TRIGGER review_links_no_delete +BEFORE DELETE ON review_links +FOR EACH ROW EXECUTE FUNCTION review_links_kept(); + +ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check; +ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK ( + entity IN ( + 'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival', + 'extension', 'reentry-permit', 'report', 'work-permit', 'document', 'form', 'link', + 'agreement', 'signature', 'lawyer', 'client', 'contract', 'contract-version', + 'paper-copy', 'contract-party', 'original', 'review' + ) +); diff --git a/src/audit.rs b/src/audit.rs index 8ac6b57..9030033 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -77,6 +77,8 @@ pub enum Entity { ContractParty, /// An original in our care (`originals`). Original, + /// A review of a contract version by the other side (`reviews`). + Review, } impl Entity { @@ -105,6 +107,7 @@ impl Entity { Entity::PaperCopy => "paper-copy", Entity::ContractParty => "contract-party", Entity::Original => "original", + Entity::Review => "review", } } } diff --git a/src/fuzzing.rs b/src/fuzzing.rs index ff436d7..c6b117f 100644 --- a/src/fuzzing.rs +++ b/src/fuzzing.rs @@ -7,7 +7,7 @@ use chrono::NaiveDate; -use crate::{agreements, conflicts, dates, files, gps, legal, mrz, pack, records}; +use crate::{agreements, conflicts, dates, files, gps, legal, mrz, pack, records, reviews}; /// Run once before a fuzz target's first input. libFuzzer's panic hook /// aborts at once, even inside the app's own `catch_unwind` (around the PDF @@ -61,6 +61,13 @@ pub fn text(data: &[u8]) { let body = agreements::normalize(&s); let _ = agreements::check("Title", &body); let _ = agreements::blocks(&body); + // what a review page sends back, against the text we sent + if let Ok(pieces) = reviews::check(a, b) { + assert_eq!(reviews::ours(&pieces), b); + let _ = reviews::git_view(&pieces); + let all = reviews::changes(&pieces).iter().map(|c| c.n).collect(); + assert_eq!(reviews::apply(&pieces, &all), reviews::theirs(&pieces)); + } } /// The kinds of document an upload can be, which decide how it prints. diff --git a/src/lib.rs b/src/lib.rs index 26a2fff..9ba1a5d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ pub mod people; #[cfg(test)] mod props; pub mod records; +pub mod reviews; pub mod s3; pub mod seed; pub mod session; diff --git a/src/links.rs b/src/links.rs index 7d5f705..503984c 100644 --- a/src/links.rs +++ b/src/links.rs @@ -96,7 +96,7 @@ pub fn actor(id: i64) -> String { format!("link {id}") } -fn hash(token: &str) -> Vec { +pub(crate) fn hash(token: &str) -> Vec { ring::digest::digest(&ring::digest::SHA256, token.as_bytes()) .as_ref() .to_vec() diff --git a/src/props.rs b/src/props.rs index c1abf60..1526fa9 100644 --- a/src/props.rs +++ b/src/props.rs @@ -8,7 +8,7 @@ use chrono::{DateTime, Datelike, NaiveDate, Utc}; use proptest::prelude::*; -use crate::{agreements, conflicts, dates, gps, journal, legal, mrz, records}; +use crate::{agreements, conflicts, dates, gps, journal, legal, mrz, records, reviews}; fn today() -> NaiveDate { NaiveDate::from_ymd_opt(2026, 11, 17).unwrap() @@ -436,3 +436,64 @@ proptest! { prop_assert_ne!(hash(&a), hash(&b)); } } + +// ------------------------------------------------------- review markup + +/// A text cut into pieces, each kept, crossed out or highlighted, with the +/// other side's typing between them: any markup the editor can make. +fn markup() -> impl Strategy)> { + let part = (any_text(), 0u8..3, any_text(), "[a-z ]{0,12}"); + prop::collection::vec(part, 0..12).prop_map(|parts| { + let mut sent = String::new(); + let mut pieces = Vec::new(); + for (ours, kind, typed, comment) in parts { + let ours = ours.replace('\r', ""); + sent.push_str(&ours); + let op = [reviews::Op::Same, reviews::Op::Del, reviews::Op::Mark][kind as usize]; + pieces.push(reviews::Piece { + op, + text: ours, + comment: if op == reviews::Op::Mark { + comment.trim().to_string() + } else { + String::new() + }, + }); + pieces.push(reviews::Piece { + op: reviews::Op::Ins, + text: typed.replace('\r', ""), + comment: String::new(), + }); + } + (sent, pieces) + }) +} + +proptest! { + #[test] + fn any_markup_of_the_sent_text_is_accepted_and_taken_back_exactly((sent, pieces) in markup()) { + let json = reviews::to_json(&pieces).to_string(); + let checked = reviews::check(&json, &sent).unwrap(); + prop_assert_eq!(reviews::ours(&checked), sent.clone()); + let theirs = reviews::theirs(&checked); + let all: std::collections::BTreeSet = + reviews::changes(&checked).iter().map(|c| c.n).collect(); + prop_assert_eq!(reviews::apply(&checked, &Default::default()), sent.clone()); + prop_assert_eq!(reviews::apply(&checked, &all), theirs.clone()); + // what is stored reads back the same + prop_assert_eq!(reviews::from_json(&reviews::to_json(&checked)), checked.clone()); + if let Some(git) = reviews::git_view(&checked) + && sent == theirs + { + prop_assert!(git.is_empty()); + } + } + + #[test] + fn markup_that_changes_our_text_unseen_is_refused((sent, pieces) in markup(), extra in "[a-z]{1,5}") { + let mut changed = pieces.clone(); + changed.push(reviews::Piece { op: reviews::Op::Same, text: extra, comment: String::new() }); + let json = reviews::to_json(&changed).to_string(); + prop_assert!(reviews::check(&json, &sent).is_err()); + } +} diff --git a/src/reviews.rs b/src/reviews.rs new file mode 100644 index 0000000..f2ce259 --- /dev/null +++ b/src/reviews.rs @@ -0,0 +1,1002 @@ +//! The other side reviews a draft (phase 13). A lawyer sends a contract +//! version with a text to one of its parties: a link for that party +//! (`/r/`, one open at a time) and a round for the version. On the +//! link the other side marks the text up, as tracked changes do: what they +//! delete stays, crossed out; what they type is marked as added; a +//! highlighter marks a passage, with a comment. They send it back once a +//! round. +//! +//! What they send is a list of pieces. The pieces without the added ones +//! must give exactly the text we sent (`check`), so nothing changes unseen; +//! the pieces without the crossed-out ones are their text. Our side numbers +//! the changes (`changes`), shows them as a git-style diff (`git_view`) and +//! takes the ones a lawyer ticks (`apply`). + +use std::collections::BTreeSet; + +use anyhow::Result; +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sqlx::{PgConnection, PgPool}; + +use crate::files::sha256_hex; +use crate::oidc::random_token; +use crate::{journal, legal}; + +/// How long a link works after its last round was sent. +pub const LIFETIME_DAYS: i64 = 30; + +/// The most pieces a reply may have. +pub const MAX_PIECES: usize = 20_000; + +/// The longest comment on a highlight, in characters. +pub const COMMENT_LIMIT: usize = 500; + +// ------------------------------------------------------------- the pieces + +/// What a piece of the marked-up text is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Op { + /// our text, unchanged + Same, + /// typed by the other side + Ins, + /// our text, crossed out by the other side + Del, + /// our text, highlighted by the other side, maybe with a comment + Mark, +} + +impl Op { + fn from_slug(s: &str) -> Option { + match s { + "same" => Some(Op::Same), + "ins" => Some(Op::Ins), + "del" => Some(Op::Del), + "mark" => Some(Op::Mark), + _ => None, + } + } + + pub fn slug(self) -> &'static str { + match self { + Op::Same => "same", + Op::Ins => "ins", + Op::Del => "del", + Op::Mark => "mark", + } + } + + /// Whether the piece is part of the text we sent. + fn ours(self) -> bool { + self != Op::Ins + } + + /// Whether the piece is part of the other side's text. + fn theirs(self) -> bool { + self != Op::Del + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Piece { + pub op: Op, + pub text: String, + /// a highlight's comment; empty on every other piece + pub comment: String, +} + +fn piece(op: Op, text: &str, comment: &str) -> Piece { + Piece { + op, + text: text.to_string(), + comment: comment.to_string(), + } +} + +/// The pieces of a text nobody has marked yet. +pub fn unmarked(text: &str) -> Vec { + if text.is_empty() { + Vec::new() + } else { + vec![piece(Op::Same, text, "")] + } +} + +/// Joins neighbors of the same kind (highlights only with the same +/// comment) and drops empty pieces. +pub fn tidy(pieces: Vec) -> Vec { + let mut out: Vec = Vec::with_capacity(pieces.len()); + for p in pieces { + if p.text.is_empty() { + continue; + } + match out.last_mut() { + Some(last) if last.op == p.op && last.comment == p.comment => { + last.text.push_str(&p.text) + } + _ => out.push(p), + } + } + out +} + +/// The text we sent, read back from the pieces. +pub fn ours(pieces: &[Piece]) -> String { + pieces + .iter() + .filter(|p| p.op.ours()) + .map(|p| p.text.as_str()) + .collect() +} + +/// The other side's text. +pub fn theirs(pieces: &[Piece]) -> String { + pieces + .iter() + .filter(|p| p.op.theirs()) + .map(|p| p.text.as_str()) + .collect() +} + +/// Reads the pieces as the editor sends them (`[["same", "text", ""], +/// ...]`) and checks them against the text we sent: the pieces without the +/// added ones must be exactly that text. +pub fn check(json: &str, sent: &str) -> Result, &'static str> { + let value: serde_json::Value = + serde_json::from_str(json).map_err(|_| "The marked-up text did not arrive whole.")?; + let items = value + .as_array() + .ok_or("The marked-up text did not arrive whole.")?; + if items.len() > MAX_PIECES { + return Err("The text has too many separate marks; join some of them."); + } + let mut pieces = Vec::with_capacity(items.len()); + for it in items { + let parts = it + .as_array() + .ok_or("The marked-up text did not arrive whole.")?; + let op = parts + .first() + .and_then(|v| v.as_str()) + .and_then(Op::from_slug) + .ok_or("The marked-up text did not arrive whole.")?; + let text = parts + .get(1) + .and_then(|v| v.as_str()) + .ok_or("The marked-up text did not arrive whole.")?; + let comment = parts.get(2).and_then(|v| v.as_str()).unwrap_or("").trim(); + if comment.chars().count() > COMMENT_LIMIT { + return Err("A comment is longer than 500 characters."); + } + // what they typed has no carriage returns, as our text has none + let text = if op == Op::Ins { + text.replace('\r', "") + } else { + text.to_string() + }; + let comment = if op == Op::Mark { comment } else { "" }; + pieces.push(piece(op, &text, comment)); + } + let pieces = tidy(pieces); + if ours(&pieces) != sent { + return Err( + "The marked-up text does not match the version we sent. Reload the page: your \ + marks since then are lost, sorry.", + ); + } + if theirs(&pieces).chars().count() > legal::BODY_LIMIT { + return Err("The text has grown too long."); + } + Ok(pieces) +} + +/// The pieces as stored and sent to the editor. +pub fn to_json(pieces: &[Piece]) -> serde_json::Value { + serde_json::Value::Array( + pieces + .iter() + .map(|p| serde_json::json!([p.op.slug(), p.text, p.comment])) + .collect(), + ) +} + +/// The pieces as JSON to put inside a `&", "")]); + assert!( + !j.contains('<') && !j.contains('>') && !j.contains('&'), + "{j}" + ); + assert_eq!( + from_json(&serde_json::from_str(&j).unwrap())[0].text, + "&" + ); + let s = shown(&p); + assert_eq!(s.iter().filter_map(|x| x.n).collect::>(), [1, 2]); + } + + #[test] + fn the_git_view_shows_the_changed_lines_with_their_words() { + let v = git_view(&marked()).unwrap(); + let ops: Vec<&str> = v.iter().map(|l| l.op).collect(); + assert_eq!(ops[0], "hunk"); + let removed = v.iter().find(|l| l.op == "removed").unwrap(); + assert_eq!(removed.old, Some(2)); + assert_eq!( + removed.segs, + [ + Seg { + hl: true, + text: "Two".into() + }, + Seg { + hl: false, + text: " years from signing.".into() + } + ] + ); + let added: Vec = v + .iter() + .filter(|l| l.op == "added") + .map(|l| plain(&l.segs)) + .collect(); + assert_eq!( + added, + [ + "Three years from signing.", + "# 3. Territory", + "Thailand only." + ] + ); + // unchanged text far from a change is left out + let many: String = (1..=20).map(|i| format!("line {i}\n")).collect(); + let p = vec![ + piece(Op::Same, &many, ""), + piece(Op::Ins, "new", ""), + piece(Op::Same, &many, ""), + ]; + let v = git_view(&p).unwrap(); + assert!(v.len() < 12, "{}", v.len()); + assert_eq!(v.iter().filter(|l| l.op == "hunk").count(), 1); + } +} diff --git a/src/seed/legal.rs b/src/seed/legal.rs index ba612a2..b9e7b23 100644 --- a/src/seed/legal.rs +++ b/src/seed/legal.rs @@ -332,7 +332,7 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul .await?; let h = legal::head_of(t, rec).await?; legal::add_version(t, &h, "The label's first draft", RECORDING_V1, None, "seed").await?; - legal::add_version( + let v2 = legal::add_version( t, &h, "Our changes for the artist: term, royalties, reversion", @@ -341,6 +341,7 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul "seed", ) .await?; + label_review(t, &h, &v2).await?; // the management deal: in force, notice day near let mut v = contract( "Management agreement", @@ -571,6 +572,92 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul } } +/// The label's review of our version 2 (phase 13): sent on a link, marked +/// up and sent back. The link's token is thrown away, as the client links'. +async fn label_review( + t: &mut sqlx::PgConnection, + h: &legal::Head, + v2: &legal::Version, +) -> Result<()> { + use crate::reviews::{self, Op, Piece}; + let (party, name): (i64, String) = sqlx::query_as( + "SELECT id, name FROM contract_parties WHERE contract_id = $1 ORDER BY id LIMIT 1", + ) + .bind(h.id) + .fetch_one(&mut *t) + .await?; + let (_, _, round) = reviews::send( + t, + &reviews::Send { + contract: h, + party, + party_name: &name, + version: v2, + message: "Our changes for Little Bird. Please mark yours and send it back by Friday.", + }, + "seed", + ) + .await?; + // what the label did: (our words, what became of them) + let edits: &[(&str, Op, &str)] = &[ + ("three", Op::Del, "five"), + ( + "; any extension needs the Artist's written consent", + Op::Del, + "", + ), + ("18%", Op::Del, "14%"), + ("ten years", Op::Mark, "We need fifteen for the catalogue."), + ]; + let body = &v2.body; + let mut pieces = Vec::new(); + let mut at = 0; + let p = |op, text: &str, comment: &str| Piece { + op, + text: text.to_string(), + comment: comment.to_string(), + }; + for (words, op, then) in edits { + let i = at + + body[at..] + .find(words) + .expect("the demo text has these words"); + pieces.push(p(Op::Same, &body[at..i], "")); + match op { + Op::Mark => pieces.push(p(Op::Mark, words, then)), + _ => { + pieces.push(p(Op::Del, words, "")); + pieces.push(p(Op::Ins, then, "")); + } + } + at = i + words.len(); + } + pieces.push(p(Op::Same, &body[at..], "")); + pieces.push(p( + Op::Ins, + "\n\n# 6. Option\nThe Label has an option on a second album on the same terms.", + "", + )); + let pieces = reviews::tidy(pieces); + reviews::reply( + t, + h, + &name, + v2.version, + &round, + &reviews::Reply { + name: "Ploy Srisuk, A&R", + message: "Five years is our standard term, and 14% matches the rest of our roster. \ + We added the usual option. Happy to talk about the catalogue years.", + pieces: &pieces, + ip: "", + user_agent: "", + }, + ) + .await?; + Ok(()) +} + /// Originals in our care (phase 12): the first demo person's passport out /// at Immigration, a title deed and a house registration held, a company /// certificate already returned. diff --git a/src/web/client.rs b/src/web/client.rs index 9b175b9..a2405c3 100644 --- a/src/web/client.rs +++ b/src/web/client.rs @@ -1093,7 +1093,7 @@ fn drawing(f: &Fields) -> Result>, &'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()) diff --git a/src/web/legal.rs b/src/web/legal.rs index b72f696..db35159 100644 --- a/src/web/legal.rs +++ b/src/web/legal.rs @@ -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>, Extension(user): Extension, diff --git a/src/web/mod.rs b/src/web/mod.rs index 0052aff..7d6f70a 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -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) -> 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) -> 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>, mut req: Request, next: Next) -> Response { if is_public(req.uri().path()) { diff --git a/src/web/reviews.rs b/src/web/reviews.rs new file mode 100644 index 0000000..376ce2b --- /dev/null +++ b/src/web/reviews.rs @@ -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/`, 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, + 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, +} + +/// 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> { + 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>, + 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 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: ¬e, + }, + &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>, + Extension(user): Extension, + 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 { + 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> { + 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>, + Extension(user): Extension, + 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>, + Extension(user): Extension, + Path((id, rid)): Path<(i64, i64)>, + // pairs, since every ticked box is one more `take` + Form(f): Form>, +) -> 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 = 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> { + 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, + 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 = 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>, Path(token): Path) -> 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>, + Path(token): Path, + headers: HeaderMap, + Form(f): Form, +) -> 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: ¬e, + 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()) +} diff --git a/static/app.css b/static/app.css index 8e3c685..f59a076 100644 --- a/static/app.css +++ b/static/app.css @@ -2198,3 +2198,185 @@ details.move[open] .mini { .form + .tblwrap { margin-top: 18px; } + +/* ---- phase 13: the review by the other side */ +.rvtext { + white-space: pre-wrap; + overflow-wrap: anywhere; + font-size: 15.5px; + line-height: 1.7; + padding: 14px 16px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--field); +} +.rvedit { + min-height: 240px; + max-height: 70vh; + overflow-y: auto; + outline: none; + caret-color: var(--fg); +} +.rvedit:focus { + border-color: var(--stroke); + box-shadow: 0 0 0 3px var(--accent-s); +} +.rvtext ins, +.rvchanges ins { + text-decoration: none; + color: var(--ok); + background: var(--ok-s); + border-bottom: 2px solid var(--ok); +} +.rvtext del, +.rvchanges del { + color: var(--bad); + background: var(--bad-s); + text-decoration: line-through; + text-decoration-thickness: 2px; +} +.rvtext mark, +.rvhl mark, +.rvtools mark { + color: inherit; + background: color-mix(in srgb, #f5c000 38%, transparent); + border-radius: 2px; +} +.rvtext mark[title] { + border-bottom: 2px dotted var(--label); +} +.rvtools mark, +.rvtools del { + padding: 0 2px; +} +.rvc { + font-size: 12.5px; + color: var(--label); + font-style: italic; + margin: 0 4px; +} +.rvc::before { + content: "\2190 "; +} +.rvn { + display: inline-block; + min-width: 1.5em; + padding: 0 4px; + margin-right: 2px; + font: 600 11px/1.5 var(--sans); + text-align: center; + color: var(--on-pri); + background: var(--pri); + border-radius: 8px; + vertical-align: 0.35em; +} +.rvtools { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; + margin: 0 0 10px; +} +.rvtools .rvcomment { + flex: 1 1 220px; + min-width: 0; + width: auto; + padding-top: 5px; + padding-bottom: 5px; +} +.rvchanges { + list-style: none; + margin: 0 0 12px; + padding: 0; +} +.rvchanges li { + padding: 8px 0; + border-bottom: 1px dashed var(--line); + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.rvchanges label.check { + font-weight: 400; + cursor: pointer; + align-items: baseline; +} +.rvchanges label.check input { + margin-top: 0; +} +.rvchanges .rvn { + vertical-align: baseline; + flex: none; +} +.rvchange { + min-width: 0; +} +.rvhl { + margin: 0; + padding-left: 18px; +} +.rvhl li { + padding: 4px 0; +} +.rvrounds { + margin: 6px 0 0; + padding-left: 18px; +} +.rvrounds li { + padding: 2px 0; +} +.rvmsg { + border-left: 3px solid var(--label); + padding: 4px 0 4px 12px; +} +.gitdiff { + font: 13.5px/1.55 var(--mono); + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; +} +.gitdiff .gl { + display: grid; + grid-template-columns: 3.2em 3.2em 1fr; +} +.gitdiff .gn { + padding: 0 6px; + text-align: right; + color: var(--mute); + border-right: 1px solid var(--line); + user-select: none; +} +.gitdiff .gt { + padding: 0 10px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.gitdiff .gs { + display: inline-block; + width: 1.2em; + color: var(--mute); + user-select: none; +} +.gitdiff .removed { + background: var(--bad-s); +} +.gitdiff .added { + background: var(--ok-s); +} +.gitdiff .removed b { + font-weight: inherit; + background: color-mix(in srgb, var(--bad) 30%, transparent); + text-decoration: line-through; +} +.gitdiff .added b { + font-weight: inherit; + background: color-mix(in srgb, var(--ok) 32%, transparent); +} +.gitdiff .hunk { + color: var(--label); + background: var(--accent-s); +} +@media (max-width: 760px) { + .gitdiff .gl { + grid-template-columns: 2.4em 2.4em 1fr; + } +} diff --git a/static/review-editor.js b/static/review-editor.js new file mode 100644 index 0000000..8d6dfe7 --- /dev/null +++ b/static/review-editor.js @@ -0,0 +1,452 @@ +// The review editor (phase 13): the other side marks a contract version up. +// The text is a list of pieces {k, t, c}: "same" (ours, unchanged), "ins" +// (typed by them), "del" (ours, crossed out) and "mark" (ours, highlighted, +// c = its comment). Every edit works on that list and redraws the editor, +// so nothing of ours can vanish: deleting our text crosses it out, deleting +// their own typing removes it. The server checks the same rule +// (`reviews::check`). No inline script: the Content Security Policy allows +// none. +(function () { + "use strict"; + + var ed = document.querySelector("[data-rv-editor]"); + if (!ed) return; + var form = ed.closest("form"); + var out = document.getElementById("rv-pieces"); + var count = document.getElementById("rv-count"); + var note = document.getElementById("rv-note"); + var commentBox = document.getElementById("rv-comment"); + var pieces = JSON.parse(document.getElementById("rv-data").textContent).map(function (p) { + return { k: p[0], t: p[1], c: p[2] || "" }; + }); + var history = []; + var lastSel = null; + var dirty = false; + var sending = false; + + // ---- the flat form: one entry per UTF-16 unit, for the edits + function flat() { + var t = [], k = [], c = []; + pieces.forEach(function (p) { + for (var i = 0; i < p.t.length; i++) { + t.push(p.t[i]); + k.push(p.k); + c.push(p.c); + } + }); + return { t: t, k: k, c: c }; + } + + function build(f) { + var res = []; + for (var i = 0; i < f.t.length; i++) { + var last = res[res.length - 1]; + if (last && last.k === f.k[i] && last.c === f.c[i]) { + last.t += f.t[i]; + } else { + res.push({ k: f.k[i], t: f.t[i], c: f.c[i] }); + } + } + pieces = res; + } + + function remember() { + history.push(JSON.stringify(pieces)); + if (history.length > 300) history.shift(); + dirty = true; + } + + // ---- drawing, and caret positions as offsets into the whole text + function draw(caret) { + ed.textContent = ""; + pieces.forEach(function (p, i) { + var tag = p.k === "ins" ? "ins" : p.k === "del" ? "del" : p.k === "mark" ? "mark" : "span"; + var el = document.createElement(tag); + el.textContent = p.t; + el.setAttribute("data-i", i); + if (p.c) el.title = p.c; + ed.appendChild(el); + }); + // a last empty line shows only with something after it + var last = pieces[pieces.length - 1]; + if (!last || last.t.charAt(last.t.length - 1) === "\n") { + ed.appendChild(document.createElement("br")); + } + out.value = JSON.stringify( + pieces.map(function (p) { + return [p.k, p.t, p.c]; + }) + ); + tell(); + if (caret != null) place(caret); + } + + function lenOf(el) { + return el.nodeType === 1 && el.hasAttribute("data-i") ? el.textContent.length : 0; + } + + function offsetOf(node, off) { + var n = 0, x; + if (node === ed) { + x = ed.firstChild; + for (var i = 0; x && i < off; i++, x = x.nextSibling) n += lenOf(x); + return n; + } + var el = node.nodeType === 3 ? node.parentNode : node; + while (el && el.parentNode !== ed) el = el.parentNode; + if (!el) return null; + for (x = ed.firstChild; x && x !== el; x = x.nextSibling) n += lenOf(x); + if (node.nodeType === 3) return n + off; + return n + (off > 0 ? lenOf(el) : 0); + } + + function current() { + var s = window.getSelection(); + if (!s || !s.rangeCount) return null; + var r = s.getRangeAt(0); + if (!ed.contains(r.startContainer) || !ed.contains(r.endContainer)) return null; + var a = offsetOf(r.startContainer, r.startOffset); + var b = offsetOf(r.endContainer, r.endOffset); + if (a == null || b == null) return null; + return { s: Math.min(a, b), e: Math.max(a, b) }; + } + + function place(pos) { + var acc = 0; + var s = window.getSelection(); + var r = document.createRange(); + for (var x = ed.firstChild; x; x = x.nextSibling) { + var len = lenOf(x); + if (len && pos <= acc + len) { + r.setStart(x.firstChild, pos - acc); + r.collapse(true); + s.removeAllRanges(); + s.addRange(r); + lastSel = { s: pos, e: pos }; + return; + } + acc += len; + } + r.selectNodeContents(ed); + r.collapse(false); + s.removeAllRanges(); + s.addRange(r); + lastSel = { s: acc, e: acc }; + } + + // ---- the edits + // Crosses [s, e) out; returns how many units of it stay (theirs go). + function crossOut(f, s, e) { + var t = [], k = [], c = [], kept = 0; + for (var i = 0; i < f.t.length; i++) { + if (i >= s && i < e) { + if (f.k[i] === "ins") continue; + kept++; + t.push(f.t[i]); + k.push("del"); + c.push(""); + } else { + t.push(f.t[i]); + k.push(f.k[i]); + c.push(f.c[i]); + } + } + f.t = t; + f.k = k; + f.c = c; + return kept; + } + + function insert(f, p, text) { + var units = text.split(""); + var ks = units.map(function () { + return "ins"; + }); + var cs = units.map(function () { + return ""; + }); + f.t.splice.apply(f.t, [p, 0].concat(units)); + f.k.splice.apply(f.k, [p, 0].concat(ks)); + f.c.splice.apply(f.c, [p, 0].concat(cs)); + } + + function isLow(ch) { + var n = ch ? ch.charCodeAt(0) : 0; + return n >= 0xdc00 && n <= 0xdfff; + } + + function type(r, text) { + text = text.replace(/\r\n?/g, "\n"); + remember(); + var f = flat(); + var p = r.s; + if (r.e > r.s) p = r.s + crossOut(f, r.s, r.e); + // what is crossed out comes first, then what replaces it + while (p < f.t.length && f.k[p] === "del") p++; + insert(f, p, text); + build(f); + draw(p + text.length); + } + + function strike(r, caretAtEnd) { + remember(); + var f = flat(); + var kept = crossOut(f, r.s, r.e); + build(f); + draw(caretAtEnd ? r.s + kept : r.s); + } + + // one character, or a word, or the line before the caret, skipping what + // is crossed out already + function back(p, unit) { + var f = flat(); + while (p > 0 && f.k[p - 1] === "del") p--; + if (p === 0) return place(p); + var a = p - 1; + if (unit === "char") { + if (a > 0 && isLow(f.t[a])) a--; + } else if (unit === "word") { + while (a > 0 && /\s/.test(f.t[a])) a--; + while (a > 0 && !/\s/.test(f.t[a - 1])) a--; + } else { + while (a > 0 && f.t[a - 1] !== "\n") a--; + } + strike({ s: a, e: p }, false); + } + + function forward(p, unit) { + var f = flat(); + var n = f.t.length; + while (p < n && f.k[p] === "del") p++; + if (p === n) return place(p); + var b = p + 1; + if (unit === "char") { + if (b < n && isLow(f.t[b])) b++; + } else if (unit === "word") { + while (b < n && /\s/.test(f.t[b])) b++; + while (b < n && !/\s/.test(f.t[b])) b++; + } else { + while (b < n && f.t[b] !== "\n") b++; + } + strike({ s: p, e: b }, true); + } + + function highlight(r) { + if (!r || r.s === r.e) { + say("Select the words to highlight first."); + return; + } + var comment = (commentBox.value || "").trim().slice(0, 500); + remember(); + var f = flat(); + for (var i = r.s; i < r.e; i++) { + if (f.k[i] === "same" || f.k[i] === "mark") { + f.k[i] = "mark"; + f.c[i] = comment; + } + } + build(f); + commentBox.value = ""; + draw(r.e); + } + + // takes the marks back from the selection, or from the mark at the caret + function restore(r) { + if (!r) return; + var f = flat(); + var s = r.s, e = r.e; + if (s === e) { + var k = f.k[s] !== "same" && f.k[s] !== undefined ? f.k[s] : f.k[s - 1]; + if (!k || k === "same") { + say("Select what to restore, or put the caret in a mark."); + return; + } + var at = f.k[s] === k ? s : s - 1; + s = at; + e = at; + while (s > 0 && f.k[s - 1] === k) s--; + while (e < f.t.length && f.k[e] === k) e++; + } + remember(); + var t = [], ks = [], cs = []; + for (var i = 0; i < f.t.length; i++) { + if (i >= s && i < e) { + if (f.k[i] === "ins") continue; + t.push(f.t[i]); + ks.push("same"); + cs.push(""); + } else { + t.push(f.t[i]); + ks.push(f.k[i]); + cs.push(f.c[i]); + } + } + build({ t: t, k: ks, c: cs }); + draw(s); + } + + function undo() { + if (!history.length) return say("Nothing to undo."); + var caret = current(); + pieces = JSON.parse(history.pop()); + draw(caret ? Math.min(caret.s, total()) : null); + } + + function total() { + return pieces.reduce(function (n, p) { + return n + p.t.length; + }, 0); + } + + // what the browser changed itself (a keyboard's composition, an edit it + // would not let us cancel): compared with our text, taken as an edit + function resync() { + var mine = pieces + .map(function (p) { + return p.t; + }) + .join(""); + var theirs = ed.textContent; + if (mine === theirs) return; + var a = 0; + while (a < mine.length && a < theirs.length && mine[a] === theirs[a]) a++; + var b = 0; + while ( + b < mine.length - a && + b < theirs.length - a && + mine[mine.length - 1 - b] === theirs[theirs.length - 1 - b] + ) { + b++; + } + var added = theirs.slice(a, theirs.length - b); + remember(); + var f = flat(); + var p = a + crossOut(f, a, mine.length - b); + insert(f, p, added); + build(f); + draw(p + added.length); + } + + // ---- telling what is there + function say(text) { + note.textContent = text; + } + + function tell() { + var changes = 0, marks = 0, open = false; + pieces.forEach(function (p) { + if (p.k === "ins" || p.k === "del") { + if (!open) changes++; + open = true; + } else { + open = false; + if (p.k === "mark") marks++; + } + }); + count.textContent = + changes + (changes === 1 ? " change, " : " changes, ") + marks + (marks === 1 ? " highlight" : " highlights"); + } + + // ---- events + ed.addEventListener("beforeinput", function (ev) { + var t = ev.inputType || ""; + if (t === "insertCompositionText") return; + ev.preventDefault(); + var r = current(); + if (!r) return; + if (t === "historyUndo") return undo(); + if (t.indexOf("insert") === 0) { + var text = ev.data; + if (t === "insertParagraph" || t === "insertLineBreak") text = "\n"; + if (text == null && ev.dataTransfer) text = ev.dataTransfer.getData("text/plain"); + if (t === "insertFromDrop" || !text) return; + if (t === "insertReplacementText" && ev.getTargetRanges) { + var tr = ev.getTargetRanges()[0]; + if (tr) { + var s = offsetOf(tr.startContainer, tr.startOffset); + var e = offsetOf(tr.endContainer, tr.endOffset); + if (s != null && e != null) r = { s: s, e: e }; + } + } + return type(r, text); + } + if (t.indexOf("delete") === 0 && t !== "deleteByDrag") { + if (r.e > r.s) return strike(r, false); + var unit = /Word/.test(t) ? "word" : /Line/.test(t) ? "line" : "char"; + if (/Backward/.test(t)) back(r.s, unit); + else forward(r.s, unit); + } + }); + + ed.addEventListener("input", function (ev) { + if (!ev.isComposing) resync(); + }); + ed.addEventListener("compositionend", function () { + setTimeout(resync, 0); + }); + ed.addEventListener("drop", function (ev) { + ev.preventDefault(); + }); + ed.addEventListener("keydown", function (ev) { + if ((ev.ctrlKey || ev.metaKey) && !ev.shiftKey && (ev.key === "z" || ev.key === "Z")) { + ev.preventDefault(); + undo(); + } + }); + + document.addEventListener("selectionchange", function () { + var r = current(); + if (!r) return; + lastSel = r; + var p = pieces; + var acc = 0; + for (var i = 0; i < p.length; i++) { + if (r.s >= acc && r.s < acc + p[i].t.length) { + if (p[i].k === "mark") say(p[i].c ? "Highlighted: " + p[i].c : "Highlighted, without a comment."); + else if (p[i].k === "del") say("Crossed out. Restore takes it back."); + else if (p[i].k === "ins") say("Added by you."); + else say(""); + return; + } + acc += p[i].t.length; + } + }); + + document.addEventListener("click", function (ev) { + var b = ev.target.closest && ev.target.closest("[data-rv]"); + if (!b) return; + var what = b.getAttribute("data-rv"); + var r = current() || lastSel; + if (what === "undo") return undo(); + if (!r) return say("Put the caret in the text, or select a part of it, first."); + if (what === "del") { + if (r.s === r.e) return say("Select the words to cross out first."); + strike(r, false); + } else if (what === "mark") { + highlight(r); + } else if (what === "restore") { + restore(r); + } + ed.focus(); + }); + + form.addEventListener("submit", function (ev) { + var changed = pieces.some(function (p) { + return p.k !== "same"; + }); + if (!changed && !window.confirm("Send it back without any change or highlight?")) { + ev.preventDefault(); + return; + } + sending = true; + }); + + window.addEventListener("beforeunload", function (ev) { + if (dirty && !sending) { + ev.preventDefault(); + ev.returnValue = ""; + } + }); + + draw(null); +})(); diff --git a/templates/_review_marks.html b/templates/_review_marks.html new file mode 100644 index 0000000..b9afa3a --- /dev/null +++ b/templates/_review_marks.html @@ -0,0 +1,5 @@ +{#- A marked-up text: unchanged, added (green), crossed out (red), highlighted + (yellow, its comment on hover and after it); each change numbered. -#} +{% macro marked(shown, id="rv-marked") -%} +
{% for p in shown %}{% if p.n %}{{ p.n }}{% endif %}{% if p.op == "ins" %}{{ p.text }}{% elif p.op == "del" %}{{ p.text }}{% elif p.op == "mark" %}{{ p.text }}{% if p.comment %}{{ p.comment }}{% endif %}{% else %}{{ p.text }}{% endif %}{% endfor %}
+{%- endmacro %} diff --git a/templates/contract.html b/templates/contract.html index a7dfaf1..db567d4 100644 --- a/templates/contract.html +++ b/templates/contract.html @@ -74,6 +74,38 @@ {% for r in roles %}{% endfor %} +
+

Review by the other side

a link where a party marks up a version and sends it back
+ {% for l in reviews %} + + {% endfor %} + {% if live_parties and text_versions %} +
+ Send a version for review +
+ +
+ {{ fm.select("review_party", "To", "", review_parties, req=true, blank="Choose the party") }} + {{ fm.select("review_version", "Version", text_versions[0][0], text_versions, req=true, blank="Choose") }} + {{ fm.area("review_message", "Message to them", "", rows=3, fcls="wide", hint="Optional: what to look at, by when.") }} +
+
+
+
+ {% elif not live_parties %}

Add the other party above to send them a version to review.

+ {% else %}

Add a version with a text to send it for review: the editor works on the text.

{% endif %} +
{% if reading %}

{% if compare %}Version {{ reading }} against version {{ before }}{% else %}Version {{ reading }}{% endif %}{% if reading_note %}: {{ reading_note }}{% endif %}

diff --git a/templates/party_review.html b/templates/party_review.html new file mode 100644 index 0000000..2f9ebc4 --- /dev/null +++ b/templates/party_review.html @@ -0,0 +1,57 @@ +{% extends "client_base.html" %} +{% import "_review_marks.html" as rm %} +{% import "_fields.html" as fm %} +{% block main %} +
+
{{ head.code }}
+

{{ head.title }}

+

Version {{ round.version }}, sent by Lanna Desk for {{ client }} to {{ party }} on {{ round.sent }}.

+ {% if round.message %}

{{ round.message }}

{% endif %} +
+{% if replied %} +
+

Thank you

+

You sent this version back on {{ round.replied }} with {{ round.changes }} {% if round.changes == 1 %}change{% else %}changes{% endif %} and {{ round.highlights }} {% if round.highlights == 1 %}highlight{% else %}highlights{% endif %}. Lanna Desk reads it and answers here with the next version. This is what you sent:

+ {{ rm.marked(shown) }} +
+{% else %} +
+ + + +
+

Your changes

+

Edit the text as you would any text. What you delete stays in place, crossed out; what you type is marked as added; so Lanna Desk sees every change. To mark a passage for discussion, select it and press Highlight, with a comment if you like. Restore takes your marks back from what you select.

+ {% if errors.pieces %}
{{ errors.pieces }}
{% endif %} + +
+

+ + +
+
+

Send it back

+
+ {{ fm.text("name", "Your name", name, err=errors.name, req=true, auto="name", hint="Who at " ~ party ~ " sends this.") }} + {{ fm.area("message", "Message to Lanna Desk", reply_message, err=errors.message, rows=4, fcls="wide", hint="Optional: what your changes are about.") }} +
+
+

You can send this version back once. Lanna Desk then answers with its next version on this same link.

+
+
+ +{% endif %} +{% if earlier %} +
+

Earlier versions

+
    {% for r in earlier %}
  • Version {{ r.version }}, sent {{ r.sent }}{% if r.replied %}; you sent it back {{ r.replied }} with {{ r.changes }} {% if r.changes == 1 %}change{% else %}changes{% endif %}{% else %}; not sent back{% endif %}
  • {% endfor %}
+
+{% endif %} +
This link works until {{ link_until }}. Only Lanna Desk's team, who act for {{ client }}, see what you send here.
+{% endblock %} diff --git a/templates/review.html b/templates/review.html new file mode 100644 index 0000000..a783f4d --- /dev/null +++ b/templates/review.html @@ -0,0 +1,53 @@ +{% extends "base.html" %} +{% import "_review_marks.html" as rm %} +{% block main %} +
+ +

{{ party }}'s review of version {{ review_version }}

+

Sent {{ round.sent }} by {{ round.by }}.{% if replied %} Sent back {{ round.replied }} by {{ round.reply_name }}: {{ round.changes }} {% if round.changes == 1 %}change{% else %}changes{% endif %}, {{ round.highlights }} {% if round.highlights == 1 %}highlight{% else %}highlights{% endif %}.{% endif %}

+
+{% if not replied %} +

Nothing back yet

{{ party }} has not sent this version back yet.

+{% else %} +{% if reply_message %} +
+

Their message

+

{{ reply_message }}

+
+{% endif %} +
+

The changes

+ {% if changes %} +
+ +

Tick the changes to take. The contract page then opens with the version form filled with version {{ review_version }} and those changes, to finish and add as the next version.

+
    + {% for c in changes %} +
  1. + {% endfor %} +
+
+
+ {% else %} +

They changed nothing{% if highlights %}; they highlighted what is listed below{% endif %}.

+ {% endif %} +
+{% if highlights %} +
+

Highlighted

+
    {% for h in highlights %}
  • {{ h.text }}{% if h.comment %}
    {{ h.comment }}
    {% endif %}
  • {% endfor %}
+
+{% endif %} +
+

As a diff

our version {{ review_version }} against their text
+ {% if git %} +
{% for l in git %}{% if l.op == "hunk" %}
@@ line {{ l.old or l.new }} @@
{% else %}
{{ l.old or "" }}{{ l.new or "" }}{% for s in l.segs %}{% if s.hl %}{{ s.text }}{% else %}{{ s.text }}{% endif %}{% endfor %}
{% endif %}{% else %}

No line changed.

{% endfor %}
+ {% else %}

The texts are too long to compare here.

{% endif %} +
+
+

As they marked it

+ {{ rm.marked(shown) }} +

Their text, SHA-256 {{ reply_sha }}

+
+{% endif %} +{% endblock %} diff --git a/templates/review_made.html b/templates/review_made.html new file mode 100644 index 0000000..7eeae4c --- /dev/null +++ b/templates/review_made.html @@ -0,0 +1,23 @@ +{% extends "base.html" %} +{% block main %} +
+ +

Sent for review

+
+
+ {% if url %} +

The link for {{ party }}

+

Give this link to {{ party }}: by email or chat, or let them scan the code. On it they read version {{ review_version }}, cross out, add and highlight, and send it back. It works until {{ until }}; every version you send them later comes on the same link.

+
+ + +
+ {% if qr %}
{{ qr|safe }}
{% endif %} +

The link is shown only now: the app keeps only a fingerprint of it. Copy it before you leave this page; otherwise close the link on the contract page and send again, which makes a new one.

+ {% else %} +

On {{ party }}'s link

+

Version {{ review_version }} is now on the link {{ party }} has already. Tell them it is there; the link works until {{ until }}.

+ {% endif %} + +
+{% endblock %} diff --git a/tests/main.rs b/tests/main.rs index b7cc496..caef60c 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -22,6 +22,7 @@ mod pages; mod papers; mod people; mod records; +mod reviews; #[test] fn every_test_file_is_a_module() { diff --git a/tests/pages.rs b/tests/pages.rs index ab33cd0..32c55d0 100644 --- a/tests/pages.rs +++ b/tests/pages.rs @@ -101,7 +101,24 @@ async fn every_page_renders_with_demo_data(pool: PgPool) { .await .unwrap(); + // the label's review of the recording agreement (phase 13) + let (review_contract, review_round): (i64, i64) = sqlx::query_as( + "SELECT l.contract_id, r.id FROM review_rounds r JOIN review_links l ON l.id = r.link_id \ + WHERE r.replied_at IS NOT NULL LIMIT 1", + ) + .fetch_one(&pool) + .await + .unwrap(); + let mut pages = vec![ + ( + format!("/contracts/{review_contract}/reviews/{review_round}"), + "As a diff".to_string(), + ), + ( + format!("/contracts/{review_contract}"), + "Review by the other side".to_string(), + ), ( "/originals".to_string(), "Chiang Mai Immigration".to_string(), diff --git a/tests/reviews.rs b/tests/reviews.rs new file mode 100644 index 0000000..9493494 --- /dev/null +++ b/tests/reviews.rs @@ -0,0 +1,287 @@ +//! The other side reviews a draft (phase 13): a version sent on a link, +//! marked up there and sent back, read as a diff and taken change by +//! change into the next version; every step in the journal. + +use axum::http::StatusCode; +use sqlx::PgPool; + +use crate::common::{App, local}; + +const SAME: &[(&str, &str)] = &[("sec-fetch-site", "same-origin")]; + +/// The value of the input `name` in a page. +fn input(page: &str, name: &str) -> String { + let at = page + .find(&format!("name=\"{name}\"")) + .unwrap_or_else(|| panic!("no {name} in {page}")); + let rest = &page[at..]; + let v = rest.find("value=\"").unwrap() + 7; + rest[v..v + rest[v..].find('"').unwrap()].to_string() +} + +async fn performance(pool: &PgPool) -> (i64, i64, String) { + sqlx::query_as( + "SELECT c.id, p.id, v.body FROM contracts c \ + JOIN contract_parties p ON p.contract_id = c.id \ + JOIN contract_versions v ON v.contract_id = c.id \ + WHERE c.title LIKE 'Performance agreement%' AND v.body <> '' \ + ORDER BY v.version DESC LIMIT 1", + ) + .fetch_one(pool) + .await + .unwrap() +} + +async fn send(app: &App, contract: i64, party: i64) -> String { + let r = app + .post( + &format!("/contracts/{contract}/reviews"), + &[ + ("review_party", &party.to_string()), + ("review_version", "1"), + ("review_message", "Please look at the fee."), + ], + ) + .await; + assert_eq!(r.status, StatusCode::OK, "{}", r.text()); + r.text() +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_other_side_marks_a_version_up_and_we_take_their_changes(pool: PgPool) { + let app = local(pool.clone()); + let today = visa::dates::today(); + visa::seed::demo(&pool, today).await.unwrap(); + visa::seed::legal::demo(&pool, None, today).await.unwrap(); + let (contract, party, body) = performance(&pool).await; + + // the contract page offers the review; sending makes a link shown once + let t = app.get(&format!("/contracts/{contract}")).await.text(); + assert!( + t.contains("id=\"reviews\"") && t.contains("id=\"send-form\""), + "{t}" + ); + let made = send(&app, contract, party).await; + let at = made.find("/r/").expect("the link is shown"); + let token: String = made[at + 3..] + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + assert_eq!(token.len(), 43); + let path = format!("/r/{token}"); + + // their page: the text in the editor, nothing of the staff's app + let r = app.get(&path).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.text()); + let page = r.text(); + assert!(page.contains("id=\"rv-editor\"") && page.contains("Please look at the fee.")); + assert!(page.contains("review-editor.js")); + assert!(!page.contains("/desk"), "no link into the back office"); + let csrf = input(&page, "csrf"); + let round = input(&page, "round"); + + // their marks: the fee changed, the travel highlighted, a line added + let (head, rest) = body.split_once("45,000").unwrap(); + let (mid, tail) = rest.split_once("flight from Berlin").unwrap(); + let pieces = serde_json::json!([ + ["same", head, ""], + ["del", "45,000", ""], + ["ins", "60,000", ""], + ["same", mid, ""], + ["mark", "flight from Berlin", "Business class, please."], + ["same", tail, ""], + [ + "ins", + "\n\n# 4. Sound\nThe Festival provides two CDJ-3000 and a DJM-A9.", + "" + ] + ]) + .to_string(); + let post = |pieces: String, name: &'static str, csrf: String| { + let path = path.clone(); + let round = round.clone(); + let app = &app; + async move { + app.post_raw( + &path, + &[ + ("csrf", &csrf), + ("round", &round), + ("pieces", &pieces), + ("name", name), + ("message", "Our counter offer."), + ], + SAME, + ) + .await + } + }; + // a change to our text without a mark is refused + let sneaky = serde_json::json!([["same", body.replace("45,000", "90,000"), ""]]).to_string(); + let r = post(sneaky, "Ann", csrf.clone()).await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + assert!(r.text().contains("does not match the version we sent")); + // without a name the marks come back in the editor + let r = post(pieces.clone(), "", csrf.clone()).await; + assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY); + let t = r.text(); + assert!( + t.contains("Say who sends this back") && t.contains("60,000"), + "{t}" + ); + // the staff's token is no token here + let r = post(pieces.clone(), "Ann", "x".repeat(43)).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + let r = post(pieces.clone(), "Ann Festival", csrf.clone()).await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + // once a round + let r = post(pieces.clone(), "Ann Festival", csrf.clone()).await; + assert_eq!(r.status, StatusCode::CONFLICT); + let t = app.get(&path).await.text(); + assert!( + t.contains("Thank you") && t.contains("2 changes and 1 highlight"), + "{t}" + ); + + // the journal has both, with the fingerprint of their text + let events: Vec<(String, String)> = sqlx::query_as( + "SELECT event, detail FROM journal WHERE contract_id = $1 AND event IN \ + ('sent for review', 'review returned') ORDER BY seq", + ) + .bind(contract) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(events.len(), 2, "{events:?}"); + assert!( + events[1] + .1 + .contains("(Ann Festival) sent version 1 back with 2 changes and 1 highlight") + ); + let sha: String = sqlx::query_scalar("SELECT reply_sha256 FROM review_rounds WHERE id = $1") + .bind(round.parse::().unwrap()) + .fetch_one(&pool) + .await + .unwrap(); + assert!(events[1].1.contains(&sha)); + assert!(visa::journal::verify(&pool).await.unwrap().whole()); + + // our side: the changes, the highlight and the git view + let review = format!("/contracts/{contract}/reviews/{round}"); + let t = app.get(&review).await.text(); + assert!(t.contains("id=\"take-form\"") && t.contains("Business class, please.")); + assert!(t.contains("class=\"gitdiff\"") && t.contains("Our counter offer.")); + // take only the fee: the version form starts with it, without the sound + let r = app.post(&format!("{review}/take"), &[("take", "1")]).await; + assert_eq!(r.status, StatusCode::OK); + let t = r.text(); + assert!(t.contains("60,000 THB") && !t.contains("CDJ-3000"), "{t}"); + assert!(t.contains("1 of 2 changes by")); + // every ticked box counts + let t = app + .post(&format!("{review}/take"), &[("take", "1"), ("take", "2")]) + .await + .text(); + assert!(t.contains("60,000 THB") && t.contains("CDJ-3000")); + assert!( + t.contains("Ann Festival") || t.contains("changes of"), + "{t}" + ); + + // the next version goes on the same link, as a new round + let made = send(&app, contract, party).await; + assert!( + made.contains("on the link") && !made.contains("/r/"), + "{made}" + ); + let t = app.get(&path).await.text(); + assert!(t.contains("id=\"rv-editor\"") && t.contains("id=\"earlier\"")); + // a reply to the old round is refused + let r = post(pieces, "Ann Festival", csrf).await; + assert_eq!(r.status, StatusCode::CONFLICT); + + // the database keeps what they sent + assert!( + sqlx::query("UPDATE review_rounds SET reply_body = 'other' WHERE id = $1") + .bind(round.parse::().unwrap()) + .execute(&pool) + .await + .is_err() + ); + assert!( + sqlx::query("DELETE FROM review_rounds") + .execute(&pool) + .await + .is_err() + ); + + // closing the link ends it + let link: i64 = sqlx::query_scalar("SELECT id FROM review_links WHERE party_id = $1") + .bind(party) + .fetch_one(&pool) + .await + .unwrap(); + let r = app + .post( + &format!("/contracts/{contract}/review-links/{link}/close"), + &[], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert_eq!(app.get(&path).await.status, StatusCode::GONE); + assert_eq!( + app.get(&format!("/r/{}", "a".repeat(43))).await.status, + StatusCode::NOT_FOUND + ); +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn only_a_live_party_and_a_version_with_a_text_can_be_sent(pool: PgPool) { + let app = local(pool.clone()); + let today = visa::dates::today(); + visa::seed::demo(&pool, today).await.unwrap(); + visa::seed::legal::demo(&pool, None, today).await.unwrap(); + let (contract, party, _) = performance(&pool).await; + let other: i64 = + sqlx::query_scalar("SELECT id FROM contract_parties WHERE contract_id <> $1 LIMIT 1") + .bind(contract) + .fetch_one(&pool) + .await + .unwrap(); + let to = format!("/contracts/{contract}/reviews"); + for form in [ + vec![ + ("review_party", other.to_string()), + ("review_version", "1".to_string()), + ], + vec![ + ("review_party", party.to_string()), + ("review_version", "9".to_string()), + ], + ] { + let pairs: Vec<(&str, &str)> = form.iter().map(|(a, b)| (*a, b.as_str())).collect(); + assert_eq!( + app.post(&to, &pairs).await.status, + StatusCode::UNPROCESSABLE_ENTITY + ); + } + // the demo's label review reads as a diff with its four changes + let (c, round): (i64, i64) = sqlx::query_as( + "SELECT l.contract_id, r.id FROM review_rounds r JOIN review_links l ON l.id = r.link_id \ + WHERE r.replied_at IS NOT NULL LIMIT 1", + ) + .fetch_one(&pool) + .await + .unwrap(); + let t = app + .get(&format!("/contracts/{c}/reviews/{round}")) + .await + .text(); + assert!( + t.contains("id=\"change-4\"") && !t.contains("id=\"change-5\""), + "{t}" + ); + assert!(t.contains("We need fifteen for the catalogue.")); + let t = app.get(&format!("/contracts/{c}")).await.text(); + assert!(t.contains("sent back") && t.contains("4 changes")); +}