From 3dd9ab60e897ccec19820c10fec4182c34feb313 Mon Sep 17 00:00:00 2001 From: grabowski Date: Mon, 23 Nov 2026 16:14:14 +0700 Subject: [PATCH] One shared draft a contract, locked when all agree (phase 13, step 2) Until a contract is set, it is one open text for every side, as Alex asked: our team edits it in the app, each other party on its link. Edits are tracked changes in the author's color (crossed out, added, highlighted with a comment) until the other side accepts or rejects them. When no change or highlight is open and Lanna Desk and every party agree, the text becomes a contract version that never changes, and the draft locks. - One side edits at a time: Edit takes the draft for 45 seconds, which every save renews; Done editing, leaving the page or silence gives it up. The editor saves 0.7 s after the last keystroke; the other pages ask for news every 3 s, so each side sees edits, who edits, agreements and the lock without reloading. - A save may only touch the saver's own marks (reviews::check_save); accept, reject (or withdraw) and resolve are their own steps, journaled with the text concerned. A later change voids the agreements given. - Notices: the other side's edits (one a half hour of editing), settled changes, agreements, the lock. The bell in the top bar counts the unseen (every 15 s); Notices lists them and marks them seen. - The draft as a diff: the standing text against every open change taken. - Migration 0015: contract_drafts, draft_saves and draft_agreements (both kept unchanged by a trigger), notices, notice_reads; drops step 1's review_rounds (only the demo held any). The review links stay as each party's way in. - Property tests for the save rule and settling, the fuzz text target runs the parser, the save check and settling; integration tests play both sides to the lock. The demo's recording agreement has an open draft with the label's changes and a notice. - PLAN: phase 13 rewritten; step 3 is the PDF and signing. --- docs/PLAN.md | 97 ++-- fuzz/seeds/text/review-markup.txt | Bin 137 -> 173 bytes migrations/0015_shared_drafts.sql | 124 +++++ src/audit.rs | 3 + src/drafts.rs | 628 ++++++++++++++++++++++ src/fuzzing.rs | 17 +- src/lib.rs | 2 + src/notices.rs | 128 +++++ src/props.rs | 98 ++-- src/reviews.rs | 840 +++++++++++------------------- src/seed/legal.rs | 123 +++-- src/web/drafts.rs | 796 ++++++++++++++++++++++++++++ src/web/legal.rs | 27 +- src/web/mod.rs | 45 +- src/web/reviews.rs | 543 ------------------- static/app.css | 225 ++++++++ static/app.js | 27 + static/draft-editor.js | 809 ++++++++++++++++++++++++++++ static/review-editor.js | 452 ---------------- templates/_draft_editor.html | 40 ++ templates/_review_marks.html | 5 - templates/base.html | 5 +- templates/client_base.html | 2 +- templates/contract.html | 60 ++- templates/draft.html | 12 + templates/draft_diff.html | 19 + templates/invite_made.html | 17 + templates/notices.html | 16 + templates/party_draft.html | 12 + templates/party_review.html | 57 -- templates/review.html | 53 -- templates/review_made.html | 23 - tests/drafts.rs | 353 +++++++++++++ tests/main.rs | 2 +- tests/pages.rs | 26 +- tests/reviews.rs | 287 ---------- 36 files changed, 3812 insertions(+), 2161 deletions(-) create mode 100644 migrations/0015_shared_drafts.sql create mode 100644 src/drafts.rs create mode 100644 src/notices.rs create mode 100644 src/web/drafts.rs delete mode 100644 src/web/reviews.rs create mode 100644 static/draft-editor.js delete mode 100644 static/review-editor.js create mode 100644 templates/_draft_editor.html delete mode 100644 templates/_review_marks.html create mode 100644 templates/draft.html create mode 100644 templates/draft_diff.html create mode 100644 templates/invite_made.html create mode 100644 templates/notices.html create mode 100644 templates/party_draft.html delete mode 100644 templates/party_review.html delete mode 100644 templates/review.html delete mode 100644 templates/review_made.html create mode 100644 tests/drafts.rs delete mode 100644 tests/reviews.rs diff --git a/docs/PLAN.md b/docs/PLAN.md index d823e3a..61a46b5 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -248,7 +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 | +| 13 | One shared draft per contract: every side edits with tracked changes, one at a time; it locks as a version when all agree; then a PDF to sign | steps 1 and 2 built Nov 23, 2026 | | later | Thai user interface, agency cases and fees, other visa categories' packs | | ### Phase 1: app, login, people @@ -844,43 +844,74 @@ 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) +## Phase 13: the shared draft (planned and built 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. +Alex: when our lawyers draft a version, the other party should edit it +through a link, with an editor that crosses out words and highlights +passages and reads like a git diff in the end. Then, the same day: the +team should see the other side's work in the app without looking for it, +and until the contract is set, it is one open document for edits, like +CryptPad; once both parties agree it becomes a version that never +changes, and a PDF that can be signed. His choices: saved as you type and +seen by the others within seconds, one editor at a time; an edit is a +tracked change in its author's color until the other side accepts or +rejects it; our lawyer and every other party must agree; signing in the +app with a drawn signature, or on paper with the scan uploaded. -### Step 1: the review link and the marking editor (built) +### Step 1: review rounds (built, then replaced) -- 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. +A version sent to a party on a link, marked up and sent back once a round. +Step 2 replaced it the same day; migration 0015 drops its table, which +only the demo ever held. -### Step 2: later +### Step 2: the shared draft (built) -- 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. +- A lawyer starts the draft from a version with a text (Contract, Shared + draft), and makes a link for each other party (shown once; it works 30 + days after its last use). The text then lives in `contract_drafts` + (migration 0015) as pieces: agreed text, and changes by a side (us, or + a party): added, crossed out, highlighted with a comment. +- One side edits at a time. Edit takes the draft for 45 seconds, which + every save renews; Done editing, leaving the page or silence gives it + up. The editor saves 0.7 seconds after the last keystroke; every other + page of the draft asks for news every 3 seconds, so each side sees the + other's edits, who is editing, agreements and the lock without + reloading. A save may only touch the saver's own marks: the server + refuses any that changes the text as it stands or another side's marks. +- Each change is listed with its author's color: the other side accepts + or rejects it, its author can withdraw it. Anyone resolves a highlight. + Each is a journal entry. +- Agree to this text is possible once no change and no highlight is open, + and a later change voids the agreements given. When Lanna Desk and every + party on the contract agree, the text becomes a new contract version, + which never changes, and the draft locks. A locked draft can start over + from a newer version (an amendment). +- Notices: the other side's edits (one notice per half hour of editing), + accepted and rejected changes, agreements and the lock. The bell in the + top bar counts the unseen ones (asked every 15 seconds); Notices lists + them and marks them seen. A colleague's actions show too; one's own do + not. +- The draft as a diff: the text as it stands against the text with every + open change taken, as `git diff --word-diff` shows it. + +### Step 3: the PDF and signing (next) + +- The locked version as a PDF (the agreements' renderer: code, version, + SHA-256 of the text on every page), downloadable on both sides. +- Signing in the app: each signer (our client, each party's signatory) + types their name and draws the signature on the link (the agreements' + drawing pad); when all have signed, the signed PDF (with a page of who + signed when, from where) is kept as the contract's document and the + contract's status moves to signed. Our client signs on their own link + or on the lawyer's device in the office. +- On paper: print the PDF, sign, upload the scan as the signed version + (the version form takes a file already). + +### Later + +- Mail the link and the notices (phase 8 mail, from reminders@). +- A party who agreed by email: a lawyer records the agreement for them. +- Comment threads on a highlight. ## Open questions diff --git a/fuzz/seeds/text/review-markup.txt b/fuzz/seeds/text/review-markup.txt index d3192ea5f237356118fd420df64be6930ab30c85..d9fdfbc5b1a9fe067360dee3a0696df4ff9441a4 100644 GIT binary patch delta 84 zcmeBVT+28?(n?23DOM+1DJ3;WNk=K9JRe8`Q9)u+Nu`w`SSmBG7$lWZl$wenInhRP NVvr0cT=B$Q835vS7%~6= delta 69 zcmZ3>*vU9S(jrzTS}7$pM@dI1q&y!;DuDzt^NK+N8AYk7FrnhaTo7BKGBvTNST81T KVz%tWNzwqYNEC_y diff --git a/migrations/0015_shared_drafts.sql b/migrations/0015_shared_drafts.sql new file mode 100644 index 0000000..34c0d0d --- /dev/null +++ b/migrations/0015_shared_drafts.sql @@ -0,0 +1,124 @@ +-- The shared draft (phase 13, step 2): one draft a contract, open for edits +-- by our team and the other parties until all agree, then locked as a +-- contract version. It replaces the review rounds of step 1, which only +-- the demo ever held: the links stay, as each party's way in. +DROP TRIGGER review_rounds_no_change ON review_rounds; +DROP FUNCTION review_rounds_kept(); +DROP TABLE review_rounds; + +CREATE TABLE contract_drafts ( + contract_id BIGINT PRIMARY KEY REFERENCES contracts (id), + -- the version the draft started from + base_version_id BIGINT NOT NULL REFERENCES contract_versions (id), + -- the text with its tracked changes: [[op, text, comment, side], ...] + pieces JSONB NOT NULL, + -- counts every save, accepted or rejected change and resolved highlight + revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0), + state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'locked')), + -- who edits now: "us:" or "party:", until the lease ends + editor TEXT, + editor_name TEXT, + editor_until TIMESTAMPTZ, + opened_by TEXT NOT NULL, + opened_at TIMESTAMPTZ NOT NULL DEFAULT now(), + changed_at TIMESTAMPTZ NOT NULL DEFAULT now(), + locked_at TIMESTAMPTZ, + locked_version_id BIGINT REFERENCES contract_versions (id), + CHECK ((editor IS NULL) = (editor_until IS NULL)), + CHECK ((state = 'locked') = (locked_at IS NOT NULL)), + CHECK ((state = 'locked') = (locked_version_id IS NOT NULL)) +); + +-- Every change to a draft, by whom: kept, never changed. +CREATE TABLE draft_saves ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL REFERENCES contracts (id), + revision INTEGER NOT NULL, + -- "us" or "party:" + side TEXT NOT NULL, + -- the staff login, or the name the party gave + actor TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('opened', 'edit', 'accept', 'reject', 'resolve')), + -- SHA-256 of the pieces after the change + sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (contract_id, revision) +); + +-- A side's agreement to the text at one revision; a later change voids it. +CREATE TABLE draft_agreements ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL REFERENCES contracts (id), + revision INTEGER NOT NULL, + side TEXT NOT NULL, + actor TEXT NOT NULL, + -- SHA-256 of the text agreed to + text_sha256 TEXT NOT NULL CHECK (text_sha256 ~ '^[0-9a-f]{64}$'), + ip TEXT NOT NULL DEFAULT '', + user_agent TEXT NOT NULL DEFAULT '', + at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (contract_id, revision, side) +); + +CREATE FUNCTION drafts_kept() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'the history of a draft never changes'; +END +$$; +CREATE TRIGGER draft_saves_no_change +BEFORE UPDATE OR DELETE ON draft_saves +FOR EACH ROW EXECUTE FUNCTION drafts_kept(); +CREATE TRIGGER draft_agreements_no_change +BEFORE UPDATE OR DELETE ON draft_agreements +FOR EACH ROW EXECUTE FUNCTION drafts_kept(); + +-- A locked draft stays as it was locked. +CREATE FUNCTION contract_drafts_locked() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'a draft stays on record'; + END IF; + IF OLD.state = 'locked' AND NEW.state = 'locked' AND NEW.pieces <> OLD.pieces THEN + RAISE EXCEPTION 'a locked draft never changes: open a new one'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER contract_drafts_kept +BEFORE UPDATE OR DELETE ON contract_drafts +FOR EACH ROW EXECUTE FUNCTION contract_drafts_locked(); + +-- What the team should see: the other side's edits, agreements, locks. +CREATE TABLE notices ( + id BIGSERIAL PRIMARY KEY, + at TIMESTAMPTZ NOT NULL DEFAULT now(), + contract_id BIGINT REFERENCES contracts (id), + -- "edited", "accepted", "rejected", "agreed", "locked", "opened" + kind TEXT NOT NULL, + -- who did it, as shown: "Demo Records Co., Ltd. (Ploy Srisuk)" + actor TEXT NOT NULL, + -- the staff login that did it, so it is not news to them + by_login TEXT NOT NULL DEFAULT '', + text TEXT NOT NULL, + href TEXT NOT NULL +); +CREATE INDEX notices_contract ON notices (contract_id); + +-- The newest notice each staff member has seen. +CREATE TABLE notice_reads ( + login TEXT PRIMARY KEY, + seen_id BIGINT NOT NULL DEFAULT 0, + seen_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +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', 'draft' + ) +); diff --git a/src/audit.rs b/src/audit.rs index 9030033..37eb920 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -79,6 +79,8 @@ pub enum Entity { Original, /// A review of a contract version by the other side (`reviews`). Review, + /// A contract's shared draft (`drafts`). + Draft, } impl Entity { @@ -108,6 +110,7 @@ impl Entity { Entity::ContractParty => "contract-party", Entity::Original => "original", Entity::Review => "review", + Entity::Draft => "draft", } } } diff --git a/src/drafts.rs b/src/drafts.rs new file mode 100644 index 0000000..6db3f4b --- /dev/null +++ b/src/drafts.rs @@ -0,0 +1,628 @@ +//! The shared draft of a contract (phase 13): open for tracked edits by our +//! team and every other party until all agree, then locked as a contract +//! version. One side edits at a time: the editor holds a lease that each +//! save renews and that ends by itself after `LEASE_SECS`, so a closed tab +//! never keeps the draft. Every change is a row in `draft_saves`; taking a +//! change in or dropping it, resolving a highlight, agreeing and locking +//! are journal entries too. Any change voids the agreements given so far, +//! since they are tied to the revision they were given at. + +use anyhow::{Result, bail}; +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sqlx::{PgConnection, PgPool}; + +use crate::files::sha256_hex; +use crate::reviews::{self, Piece, US}; +use crate::{journal, legal}; + +/// How long an editor keeps the draft without a save or a sign of life. +pub const LEASE_SECS: i32 = 45; + +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Draft { + pub contract_id: i64, + pub base_version_id: i64, + pub pieces: serde_json::Value, + pub revision: i32, + pub state: String, + pub editor: Option, + pub editor_name: Option, + pub editor_until: Option>, + pub opened_by: String, + pub opened_at: DateTime, + pub changed_at: DateTime, + pub locked_at: Option>, + pub locked_version_id: Option, +} + +impl Draft { + pub fn pieces(&self) -> Vec { + reviews::from_json(&self.pieces) + } + + pub fn open(&self) -> bool { + self.state == "open" + } + + /// Who edits now, if anyone: their key and name. + pub fn editing(&self) -> Option<(&str, &str)> { + match (&self.editor, &self.editor_until) { + (Some(k), Some(until)) if *until > Utc::now() => { + Some((k.as_str(), self.editor_name.as_deref().unwrap_or("Someone"))) + } + _ => None, + } + } +} + +/// Who acts on a draft: a side, the key of this editor (`us:` or +/// `party:`) and the name others see. +#[derive(Clone, Debug)] +pub struct Actor { + pub side: String, + pub key: String, + pub name: String, + /// the staff login; empty for a party + pub login: String, +} + +impl Actor { + pub fn staff(login: &str, name: &str) -> Actor { + Actor { + side: US.to_string(), + key: format!("us:{login}"), + name: format!("{name} (Lanna Desk)"), + login: login.to_string(), + } + } + + pub fn party(id: i64, party: &str) -> Actor { + Actor { + side: reviews::party_side(id), + key: reviews::party_side(id), + name: party.to_string(), + login: String::new(), + } + } +} + +/// Why a change to the draft did not happen. +#[derive(Debug, PartialEq, Eq)] +pub enum Refused { + /// someone else edits now + Busy(String), + /// the page showed an older revision + Stale, + /// the draft is locked + Locked, + /// the change itself is wrong + Wrong(&'static str), +} + +impl Refused { + pub fn message(&self) -> String { + match self { + Refused::Busy(name) => format!("{name} is editing the draft right now."), + Refused::Stale => { + "The draft changed in the meantime. It has been reloaded; try again.".into() + } + Refused::Locked => "The draft is locked: all sides agreed to it.".into(), + Refused::Wrong(m) => (*m).to_string(), + } + } +} + +pub type Outcome = Result>; + +pub async fn get(db: &PgPool, contract: i64) -> Result> { + Ok( + sqlx::query_as("SELECT * FROM contract_drafts WHERE contract_id = $1") + .bind(contract) + .fetch_optional(db) + .await?, + ) +} + +async fn for_update(conn: &mut PgConnection, contract: i64) -> Result> { + Ok( + sqlx::query_as("SELECT * FROM contract_drafts WHERE contract_id = $1 FOR UPDATE") + .bind(contract) + .fetch_optional(&mut *conn) + .await?, + ) +} + +fn pieces_sha(pieces: &[Piece]) -> String { + sha256_hex(reviews::to_json(pieces).to_string().as_bytes()) +} + +async fn saved( + conn: &mut PgConnection, + contract: i64, + revision: i32, + who: &Actor, + kind: &str, + pieces: &[Piece], +) -> Result<()> { + let actor = if who.login.is_empty() { + who.name.clone() + } else { + who.login.clone() + }; + sqlx::query( + "INSERT INTO draft_saves (contract_id, revision, side, actor, kind, sha256) \ + VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(contract) + .bind(revision) + .bind(&who.side) + .bind(actor) + .bind(kind) + .bind(pieces_sha(pieces)) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// Opens the draft from a version with a text. A locked draft can start +/// over from a newer version (an amendment); an open one cannot. +pub async fn open( + conn: &mut PgConnection, + head: &legal::Head, + version: &legal::Version, + by: &Actor, +) -> Result { + if version.body.is_empty() { + bail!("a draft needs a version with a text"); + } + let pieces = reviews::unmarked(&version.body); + let json = reviews::to_json(&pieces); + let d: Option = sqlx::query_as( + "INSERT INTO contract_drafts (contract_id, base_version_id, pieces, opened_by) \ + VALUES ($1, $2, $3, $4) \ + ON CONFLICT (contract_id) DO UPDATE SET base_version_id = $2, pieces = $3, \ + opened_by = $4, opened_at = now(), changed_at = now(), state = 'open', \ + revision = contract_drafts.revision + 1, editor = NULL, editor_name = NULL, \ + editor_until = NULL, locked_at = NULL, locked_version_id = NULL \ + WHERE contract_drafts.state = 'locked' RETURNING *", + ) + .bind(head.id) + .bind(version.id) + .bind(&json) + .bind(&by.login) + .fetch_optional(&mut *conn) + .await?; + let Some(d) = d else { + bail!("the contract has an open draft already"); + }; + saved(conn, head.id, d.revision, by, "opened", &pieces).await?; + journal::append( + conn, + &journal::New { + actor: &by.login, + client: Some(head.client_id), + contract: Some(head.id), + event: "draft opened", + detail: format!( + "A shared draft opened from version {}. Text SHA-256 {}.", + version.version, + version.body_sha256.as_deref().unwrap_or("none") + ), + }, + ) + .await?; + Ok(d) +} + +/// Takes the draft for editing, or renews the lease of whoever has it. +pub async fn take(conn: &mut PgConnection, contract: i64, who: &Actor) -> Outcome { + let d: Option = sqlx::query_as( + "UPDATE contract_drafts SET editor = $2, editor_name = $3, \ + editor_until = now() + make_interval(secs => $4) \ + WHERE contract_id = $1 AND state = 'open' \ + AND (editor IS NULL OR editor_until < now() OR editor = $2) RETURNING *", + ) + .bind(contract) + .bind(&who.key) + .bind(&who.name) + .bind(LEASE_SECS) + .fetch_optional(&mut *conn) + .await?; + if let Some(d) = d { + return Ok(Ok(d)); + } + let now: Option = sqlx::query_as("SELECT * FROM contract_drafts WHERE contract_id = $1") + .bind(contract) + .fetch_optional(&mut *conn) + .await?; + Ok(Err(match now { + Some(d) if !d.open() => Refused::Locked, + Some(d) => Refused::Busy(d.editing().map_or("Someone".into(), |(_, n)| n.to_string())), + None => Refused::Wrong("There is no shared draft."), + })) +} + +/// Gives the draft up, if this editor has it. +pub async fn release(conn: &mut PgConnection, contract: i64, who: &Actor) -> Result<()> { + sqlx::query( + "UPDATE contract_drafts SET editor = NULL, editor_name = NULL, editor_until = NULL \ + WHERE contract_id = $1 AND editor = $2", + ) + .bind(contract) + .bind(&who.key) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// The draft for a change at `revision`: open, at that revision, and +/// either nobody's or this editor's. +async fn ready( + conn: &mut PgConnection, + contract: i64, + who: &Actor, + revision: i32, + must_hold: bool, +) -> Result> { + let Some(d) = for_update(conn, contract).await? else { + return Ok(Err(Refused::Wrong("There is no shared draft."))); + }; + if !d.open() { + return Ok(Err(Refused::Locked)); + } + match d.editing() { + Some((k, name)) if k != who.key => return Ok(Err(Refused::Busy(name.to_string()))), + None if must_hold => { + return Ok(Err(Refused::Wrong( + "Your editing time ran out. Press Edit to go on.", + ))); + } + _ => {} + } + if d.revision != revision { + return Ok(Err(Refused::Stale)); + } + Ok(Ok(d)) +} + +async fn store( + conn: &mut PgConnection, + contract: i64, + pieces: &[Piece], + renew_for: Option<&Actor>, +) -> Result { + let rev: i32 = sqlx::query_scalar( + "UPDATE contract_drafts SET pieces = $2, revision = revision + 1, changed_at = now(), \ + editor_until = CASE WHEN editor = $3 THEN now() + make_interval(secs => $4) \ + ELSE editor_until END \ + WHERE contract_id = $1 RETURNING revision", + ) + .bind(contract) + .bind(reviews::to_json(pieces)) + .bind(renew_for.map(|a| a.key.as_str())) + .bind(LEASE_SECS) + .fetch_one(&mut *conn) + .await?; + Ok(rev) +} + +/// Saves the editor's tracked edits; returns the new revision, or the old +/// one when nothing changed (the lease is renewed either way). +pub async fn save( + conn: &mut PgConnection, + contract: i64, + who: &Actor, + revision: i32, + new: &[Piece], +) -> Outcome { + let d = match ready(conn, contract, who, revision, true).await? { + Ok(d) => d, + Err(r) => return Ok(Err(r)), + }; + let old = d.pieces(); + if let Err(m) = reviews::check_save(&old, new, &who.side) { + return Ok(Err(Refused::Wrong(m))); + } + if old == new { + take(conn, contract, who).await?.ok(); + return Ok(Ok(d.revision)); + } + let rev = store(conn, contract, new, Some(who)).await?; + saved(conn, contract, rev, who, "edit", new).await?; + Ok(Ok(rev)) +} + +/// At most `n` characters of a text, on one line, for the journal. +fn short(text: &str, n: usize) -> String { + let one: String = text + .chars() + .map(|c| if c == '\n' { ' ' } else { c }) + .collect(); + let one = one.trim(); + if one.chars().count() > n { + format!("{}…", one.chars().take(n).collect::()) + } else { + one.to_string() + } +} + +/// The name of a side: Lanna Desk or a party's. +pub async fn side_name(db: impl sqlx::PgExecutor<'_>, side: &str) -> Result { + match reviews::party_of(side) { + Some(id) => Ok(sqlx::query_scalar::<_, String>( + "SELECT name FROM contract_parties WHERE id = $1", + ) + .bind(id) + .fetch_optional(db) + .await? + .unwrap_or_else(|| "a former party".into())), + None => Ok("Lanna Desk".into()), + } +} + +/// Takes change `n` in or drops it. Only another side takes a change in; +/// its own side may withdraw it. +pub async fn settle( + conn: &mut PgConnection, + head: &legal::Head, + who: &Actor, + revision: i32, + n: usize, + accept: bool, +) -> Outcome { + let d = match ready(conn, head.id, who, revision, false).await? { + Ok(d) => d, + Err(r) => return Ok(Err(r)), + }; + let Some((new, change)) = reviews::settle(&d.pieces(), n, accept) else { + return Ok(Err(Refused::Stale)); + }; + if accept && change.side == who.side { + return Ok(Err(Refused::Wrong( + "The other side takes your own changes in; you can withdraw them.", + ))); + } + let rev = store(conn, head.id, &new, None).await?; + saved( + conn, + head.id, + rev, + who, + if accept { "accept" } else { "reject" }, + &new, + ) + .await?; + let by = side_name(&mut *conn, &change.side).await?; + let what = match (change.removed.is_empty(), change.added.is_empty()) { + (false, false) => format!( + "\"{}\" becomes \"{}\"", + short(&change.removed, 120), + short(&change.added, 120) + ), + (false, true) => format!("\"{}\" taken out", short(&change.removed, 120)), + _ => format!("\"{}\" added", short(&change.added, 120)), + }; + let verb = match (accept, change.side == who.side) { + (true, _) => "accepted", + (false, true) => "withdrew", + (false, false) => "rejected", + }; + journal::append( + conn, + &journal::New { + actor: &actor_of(who), + client: Some(head.client_id), + contract: Some(head.id), + event: if accept { + "change accepted" + } else { + "change rejected" + }, + detail: format!( + "{} {verb} a change by {by} (draft revision {rev}): {what}.", + who.name + ), + }, + ) + .await?; + Ok(Ok(rev)) +} + +fn actor_of(who: &Actor) -> String { + if who.login.is_empty() { + who.key.clone() + } else { + who.login.clone() + } +} + +/// Resolves highlight `k`: the text stays, the highlight goes. +pub async fn resolve( + conn: &mut PgConnection, + head: &legal::Head, + who: &Actor, + revision: i32, + k: usize, +) -> Outcome { + let d = match ready(conn, head.id, who, revision, false).await? { + Ok(d) => d, + Err(r) => return Ok(Err(r)), + }; + let Some((new, h)) = reviews::resolve(&d.pieces(), k) else { + return Ok(Err(Refused::Stale)); + }; + let rev = store(conn, head.id, &new, None).await?; + saved(conn, head.id, rev, who, "resolve", &new).await?; + let by = side_name(&mut *conn, &h.side).await?; + journal::append( + conn, + &journal::New { + actor: &actor_of(who), + client: Some(head.client_id), + contract: Some(head.id), + event: "highlight resolved", + detail: format!( + "{} resolved a highlight by {by} on \"{}\"{}.", + who.name, + short(&h.text, 120), + if h.comment.is_empty() { + String::new() + } else { + format!(" (\"{}\")", short(&h.comment, 200)) + } + ), + }, + ) + .await?; + Ok(Ok(rev)) +} + +/// The sides that must agree: Lanna Desk and every party still on the +/// contract. +pub async fn required(db: impl sqlx::PgExecutor<'_>, contract: i64) -> Result> { + let parties: Vec = sqlx::query_scalar( + "SELECT id FROM contract_parties WHERE contract_id = $1 AND removed_at IS NULL ORDER BY id", + ) + .bind(contract) + .fetch_all(db) + .await?; + let mut out = vec![US.to_string()]; + out.extend(parties.into_iter().map(reviews::party_side)); + Ok(out) +} + +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Agreement { + pub side: String, + pub actor: String, + pub at: DateTime, +} + +/// The agreements given at a revision. +pub async fn agreements( + db: impl sqlx::PgExecutor<'_>, + contract: i64, + revision: i32, +) -> Result> { + Ok(sqlx::query_as( + "SELECT side, actor, at FROM draft_agreements WHERE contract_id = $1 AND revision = $2 \ + ORDER BY id", + ) + .bind(contract) + .bind(revision) + .fetch_all(db) + .await?) +} + +/// What an agreement did. +#[derive(Debug, PartialEq, Eq)] +pub enum Agreed { + /// noted; other sides still have to agree + Waiting, + /// the last side agreed: the text is now this contract version + Locked(i32), +} + +/// Records a side's agreement to the text at `revision`. Open changes +/// must be settled first. When every side has agreed, the text becomes a +/// contract version and the draft locks. +pub async fn agree( + conn: &mut PgConnection, + head: &legal::Head, + who: &Actor, + person: &str, + revision: i32, + ip: &str, + user_agent: &str, +) -> Outcome { + let d = match ready(conn, head.id, who, revision, false).await? { + Ok(d) => d, + Err(r) => return Ok(Err(r)), + }; + let pieces = d.pieces(); + if !reviews::changes(&pieces).is_empty() { + return Ok(Err(Refused::Wrong( + "Accept or reject every open change first: the text to agree to is what stands.", + ))); + } + // a highlight is an open question + if !reviews::highlights(&pieces).is_empty() { + return Ok(Err(Refused::Wrong( + "Resolve every highlight first: each is a question still open.", + ))); + } + let text = reviews::base(&pieces); + let sha = sha256_hex(text.as_bytes()); + let fresh = sqlx::query( + "INSERT INTO draft_agreements (contract_id, revision, side, actor, text_sha256, ip, \ + user_agent) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT DO NOTHING", + ) + .bind(head.id) + .bind(revision) + .bind(&who.side) + .bind(person) + .bind(&sha) + .bind(ip) + .bind(user_agent) + .execute(&mut *conn) + .await? + .rows_affected() + > 0; + if fresh { + journal::append( + conn, + &journal::New { + actor: &actor_of(who), + client: Some(head.client_id), + contract: Some(head.id), + event: "text agreed", + detail: format!( + "{} ({person}) agreed to the draft at revision {revision}. Text SHA-256 {sha}.", + who.name + ), + }, + ) + .await?; + } + let need = required(&mut *conn, head.id).await?; + let have = agreements(&mut *conn, head.id, revision).await?; + if !need.iter().all(|s| have.iter().any(|a| &a.side == s)) { + return Ok(Ok(Agreed::Waiting)); + } + // every side agreed: the text is set in stone + let names: Vec = have.iter().map(|a| a.actor.clone()).collect::>(); + let v = legal::add_version( + conn, + head, + "Agreed by all sides in the shared draft, locked", + &text, + None, + &actor_of(who), + ) + .await?; + sqlx::query( + "UPDATE contract_drafts SET state = 'locked', locked_at = now(), locked_version_id = $2, \ + editor = NULL, editor_name = NULL, editor_until = NULL WHERE contract_id = $1", + ) + .bind(head.id) + .bind(v.id) + .execute(&mut *conn) + .await?; + journal::append( + conn, + &journal::New { + actor: &actor_of(who), + client: Some(head.client_id), + contract: Some(head.id), + event: "draft locked", + detail: format!( + "Every side agreed ({}); the draft is locked as version {}. Text SHA-256 {sha}.", + names.join(", "), + v.version + ), + }, + ) + .await?; + Ok(Ok(Agreed::Locked(v.version))) +} diff --git a/src/fuzzing.rs b/src/fuzzing.rs index c6b117f..80a8487 100644 --- a/src/fuzzing.rs +++ b/src/fuzzing.rs @@ -61,12 +61,19 @@ 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); + // what the shared draft's editor saves, against an unmarked text + if let Ok(pieces) = reviews::parse(a) { + let old = reviews::unmarked(b); + if reviews::check_save(&old, &pieces, "party:1").is_ok() { + assert_eq!(reviews::base(&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)); + // taking every change in, one by one, gives the proposed text + let mut p = pieces.clone(); + while !reviews::changes(&p).is_empty() { + p = reviews::settle(&p, 1, true).expect("change 1 exists").0; + } + assert_eq!(reviews::base(&p), reviews::proposed(&pieces)); } } diff --git a/src/lib.rs b/src/lib.rs index 9ba1a5d..936e111 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ pub mod dates; pub mod db; pub mod deadlines; pub mod documents; +pub mod drafts; pub mod embedded; pub mod files; pub mod forms; @@ -23,6 +24,7 @@ pub mod legal; pub mod links; pub mod mail; pub mod mrz; +pub mod notices; pub mod oidc; pub mod originals; pub mod pack; diff --git a/src/notices.rs b/src/notices.rs new file mode 100644 index 0000000..eab9df4 --- /dev/null +++ b/src/notices.rs @@ -0,0 +1,128 @@ +//! The team's notices (phase 13): what happened on a contract that +//! someone should look at, such as the other side's edits, agreements and +//! locks. The bell in the top bar counts the ones a staff member has not +//! seen; opening the list marks them seen. A notice is not news to the +//! staff member who caused it. + +use anyhow::Result; +use chrono::{DateTime, Utc}; +use serde::Serialize; +use sqlx::{PgConnection, PgPool}; + +/// Edits by one side within this many minutes make one notice. +const EDITS_JOIN_MINUTES: i32 = 30; + +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Notice { + pub id: i64, + pub at: DateTime, + pub contract_id: Option, + pub kind: String, + pub actor: String, + pub by_login: String, + pub text: String, + pub href: String, +} + +pub struct New<'a> { + pub contract: Option, + pub kind: &'a str, + pub actor: &'a str, + /// the staff login that caused it, or empty + pub by_login: &'a str, + pub text: &'a str, + pub href: &'a str, +} + +/// Adds a notice. Edits by the same actor on the same contract within +/// half an hour join the newest one, which moves up again. +pub async fn add(conn: &mut PgConnection, n: &New<'_>) -> Result<()> { + if n.kind == "edited" { + // a joined notice takes a new id, so it counts as news again + let joined = sqlx::query( + "UPDATE notices SET at = now(), text = $4, id = nextval('notices_id_seq') \ + WHERE id = (SELECT id FROM notices WHERE contract_id IS NOT DISTINCT FROM $1 \ + AND kind = 'edited' AND actor = $2 AND at > now() - make_interval(mins => $3) \ + ORDER BY id DESC LIMIT 1)", + ) + .bind(n.contract) + .bind(n.actor) + .bind(EDITS_JOIN_MINUTES) + .bind(n.text) + .execute(&mut *conn) + .await? + .rows_affected(); + if joined > 0 { + return Ok(()); + } + } + sqlx::query( + "INSERT INTO notices (contract_id, kind, actor, by_login, text, href) \ + VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(n.contract) + .bind(n.kind) + .bind(n.actor) + .bind(n.by_login) + .bind(n.text) + .bind(n.href) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// The newest notice this staff member has seen. +pub async fn seen(db: &PgPool, login: &str) -> Result { + Ok( + sqlx::query_scalar("SELECT seen_id FROM notice_reads WHERE login = $1") + .bind(login) + .fetch_optional(db) + .await? + .unwrap_or(0), + ) +} + +/// How many notices this staff member has not seen. +pub async fn unread(db: &PgPool, login: &str) -> Result { + Ok(sqlx::query_scalar( + "SELECT count(*) FROM notices WHERE by_login <> $1 AND id > COALESCE((SELECT seen_id \ + FROM notice_reads WHERE login = $1), 0)", + ) + .bind(login) + .fetch_one(db) + .await?) +} + +/// The unseen notices of each contract, for the contracts list. +pub async fn unread_by_contract(db: &PgPool, login: &str) -> Result> { + Ok(sqlx::query_as( + "SELECT contract_id, count(*) FROM notices WHERE contract_id IS NOT NULL \ + AND by_login <> $1 AND id > COALESCE((SELECT seen_id FROM notice_reads \ + WHERE login = $1), 0) GROUP BY contract_id", + ) + .bind(login) + .fetch_all(db) + .await?) +} + +pub async fn list(db: &PgPool, limit: i64) -> Result> { + Ok( + sqlx::query_as("SELECT * FROM notices ORDER BY id DESC LIMIT $1") + .bind(limit) + .fetch_all(db) + .await?, + ) +} + +/// Marks everything up to `upto` seen. +pub async fn mark_seen(db: &PgPool, login: &str, upto: i64) -> Result<()> { + sqlx::query( + "INSERT INTO notice_reads (login, seen_id) VALUES ($1, $2) ON CONFLICT (login) \ + DO UPDATE SET seen_id = GREATEST(notice_reads.seen_id, $2), seen_at = now()", + ) + .bind(login) + .bind(upto) + .execute(db) + .await?; + Ok(()) +} diff --git a/src/props.rs b/src/props.rs index 1526fa9..7a24869 100644 --- a/src/props.rs +++ b/src/props.rs @@ -437,63 +437,77 @@ proptest! { } } -// ------------------------------------------------------- review markup +// ------------------------------------------------------- the shared draft -/// 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)> { +/// A text cut into pieces, each kept, crossed out or highlighted by one +/// side, with additions between them: any markup a side's editor can make +/// on an unmarked text. +fn markup() -> impl Strategy, String)> { let part = (any_text(), 0u8..3, any_text(), "[a-z ]{0,12}"); - prop::collection::vec(part, 0..12).prop_map(|parts| { + (prop::collection::vec(part, 0..12), prop::bool::ANY).prop_map(|(parts, ours)| { + let side = if ours { + reviews::US.to_string() + } else { + reviews::party_side(3) + }; 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); + for (text, kind, typed, comment) in parts { + let text = text.replace('\r', ""); + sent.push_str(&text); 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(), - }); + let by = if op == reviews::Op::Same { + "" + } else { + side.as_str() + }; + let c = if op == reviews::Op::Mark { + comment.trim().to_string() + } else { + String::new() + }; + pieces.push(reviews::piece(op, &text, &c, by)); + pieces.push(reviews::piece( + reviews::Op::Ins, + &typed.replace('\r', ""), + "", + &side, + )); } - (sent, pieces) + (sent, reviews::tidy(pieces), side) }) } 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()); + fn a_sides_markup_saves_and_settles_back_exactly((sent, pieces, side) in markup()) { + let parsed = reviews::parse(&reviews::to_json(&pieces).to_string()).unwrap(); + prop_assert_eq!(&parsed, &pieces); + let old = reviews::unmarked(&sent); + prop_assert!(reviews::check_save(&old, &pieces, &side).is_ok()); + prop_assert_eq!(reviews::base(&pieces), sent.clone()); + // nobody else may save it as theirs + let other = if side == reviews::US { reviews::party_side(4) } else { reviews::US.to_string() }; + if pieces.iter().any(|p| p.op != reviews::Op::Same) { + prop_assert!(reviews::check_save(&old, &pieces, &other).is_err()); } + // taking every change in gives the proposed text; dropping every + // change gives the text sent + let (mut yes, mut no) = (pieces.clone(), pieces.clone()); + while !reviews::changes(&yes).is_empty() { + yes = reviews::settle(&yes, 1, true).unwrap().0; + } + while !reviews::changes(&no).is_empty() { + no = reviews::settle(&no, 1, false).unwrap().0; + } + prop_assert_eq!(reviews::base(&yes), reviews::proposed(&pieces)); + prop_assert_eq!(reviews::base(&no), sent); } #[test] - fn markup_that_changes_our_text_unseen_is_refused((sent, pieces) in markup(), extra in "[a-z]{1,5}") { + fn a_save_that_changes_the_standing_text_is_refused((sent, pieces, side) 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()); + changed.push(reviews::piece(reviews::Op::Same, &extra, "", "")); + prop_assert!(reviews::check_save(&reviews::unmarked(&sent), &changed, &side).is_err()); } } diff --git a/src/reviews.rs b/src/reviews.rs index f2ce259..b9d3aa8 100644 --- a/src/reviews.rs +++ b/src/reviews.rs @@ -1,50 +1,60 @@ -//! 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. +//! The shared draft's text (phase 13). A draft is a list of pieces: the +//! agreed text (`same`) and tracked changes, each by a side (`us` for Lanna +//! Desk's team, `party:` for another party): added (`ins`), crossed out +//! (`del`) or highlighted with a comment (`mark`). The text as it stands is +//! the pieces without the added ones (`base`); with every change taken it +//! is `proposed`. //! -//! 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; +//! A save by one side may only touch that side's own marks (`check_save`): +//! it never changes the text as it stands, nor anyone else's change. Taking +//! a change in or dropping it (`settle`) and resolving a highlight +//! (`resolve`) are their own steps, journaled. Also the links each party +//! opens the draft with. use anyhow::Result; use chrono::{DateTime, Utc}; use serde::Serialize; use sqlx::{PgConnection, PgPool}; -use crate::files::sha256_hex; +use crate::legal; use crate::oidc::random_token; -use crate::{journal, legal}; -/// How long a link works after its last round was sent. +/// How long a party's link works after it was made or last used. pub const LIFETIME_DAYS: i64 = 30; -/// The most pieces a reply may have. +/// The most pieces a draft may have. pub const MAX_PIECES: usize = 20_000; /// The longest comment on a highlight, in characters. pub const COMMENT_LIMIT: usize = 500; +/// Lanna Desk's side. +pub const US: &str = "us"; + +pub fn party_side(id: i64) -> String { + format!("party:{id}") +} + +pub fn party_of(side: &str) -> Option { + side.strip_prefix("party:")?.parse().ok() +} + +fn side_ok(side: &str) -> bool { + side == US || party_of(side).is_some_and(|id| id > 0) +} + // ------------------------------------------------------------- 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 + /// the text as agreed so far Same, - /// typed by the other side + /// added by a side, not taken in yet Ins, - /// our text, crossed out by the other side + /// crossed out by a side, not taken out yet Del, - /// our text, highlighted by the other side, maybe with a comment + /// highlighted by a side, maybe with a comment Mark, } @@ -68,15 +78,10 @@ impl Op { } } - /// Whether the piece is part of the text we sent. - fn ours(self) -> bool { + /// Whether the piece is part of the text as it stands. + fn standing(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)] @@ -85,27 +90,26 @@ pub struct Piece { pub text: String, /// a highlight's comment; empty on every other piece pub comment: String, + /// who made the change; empty on the agreed text + pub side: String, } -fn piece(op: Op, text: &str, comment: &str) -> Piece { +pub fn piece(op: Op, text: &str, comment: &str, side: &str) -> Piece { Piece { op, text: text.to_string(), comment: comment.to_string(), + side: side.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, "")] - } + tidy(vec![piece(Op::Same, text, "", "")]) } -/// Joins neighbors of the same kind (highlights only with the same -/// comment) and drops empty pieces. +/// Joins neighbors of the same kind, side and comment, and drops empty +/// pieces. The editor does the same, so both number changes alike. pub fn tidy(pieces: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(pieces.len()); for p in pieces { @@ -113,8 +117,8 @@ pub fn tidy(pieces: Vec) -> Vec { continue; } match out.last_mut() { - Some(last) if last.op == p.op && last.comment == p.comment => { - last.text.push_str(&p.text) + Some(l) if l.op == p.op && l.comment == p.comment && l.side == p.side => { + l.text.push_str(&p.text) } _ => out.push(p), } @@ -122,97 +126,133 @@ pub fn tidy(pieces: Vec) -> Vec { out } -/// The text we sent, read back from the pieces. -pub fn ours(pieces: &[Piece]) -> String { +/// The text as it stands: what is agreed, crossed out or highlighted. +pub fn base(pieces: &[Piece]) -> String { pieces .iter() - .filter(|p| p.op.ours()) + .filter(|p| p.op.standing()) .map(|p| p.text.as_str()) .collect() } -/// The other side's text. -pub fn theirs(pieces: &[Piece]) -> String { +/// The text with every change taken. +pub fn proposed(pieces: &[Piece]) -> String { pieces .iter() - .filter(|p| p.op.theirs()) + .filter(|p| p.op != Op::Del) .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.")?; +const BROKEN: &str = "The draft did not arrive whole. Reload the page."; + +/// Reads pieces as the editor sends them (`[["same", "text", "", ""], ...]`) +/// and checks their form; `check_save` then checks what changed. +pub fn parse(json: &str) -> Result, &'static str> { + let value: serde_json::Value = serde_json::from_str(json).map_err(|_| BROKEN)?; + let items = value.as_array().ok_or(BROKEN)?; if items.len() > MAX_PIECES { - return Err("The text has too many separate marks; join some of them."); + return Err("The draft has too many separate marks; resolve 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 parts = it.as_array().ok_or(BROKEN)?; 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.")?; + .ok_or(BROKEN)?; + let text = parts.get(1).and_then(|v| v.as_str()).ok_or(BROKEN)?; let comment = parts.get(2).and_then(|v| v.as_str()).unwrap_or("").trim(); + let side = parts.get(3).and_then(|v| v.as_str()).unwrap_or(""); 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 + match op { + Op::Same if !side.is_empty() => return Err(BROKEN), + Op::Ins | Op::Del | Op::Mark if !side_ok(side) => return Err(BROKEN), + _ => {} + } + // typing brings no carriage returns, as no saved text has any 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)); + pieces.push(piece(op, &text, comment, side)); } 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."); + if proposed(&pieces).chars().count() > legal::BODY_LIMIT { + return Err("The draft has grown too long."); } Ok(pieces) } -/// The pieces as stored and sent to the editor. +/// What each character of the text as it stands is: agreed, or marked by +/// a side (with the comment). +fn standing_marks(pieces: &[Piece]) -> Vec<(Op, &str, &str)> { + let mut out = Vec::new(); + for p in pieces.iter().filter(|p| p.op.standing()) { + for _ in p.text.chars() { + out.push((p.op, p.side.as_str(), p.comment.as_str())); + } + } + out +} + +/// The added pieces of the sides other than `side`, each with its place in +/// the text as it stands; neighbors of one side at one place joined. +fn others_added<'a>(pieces: &'a [Piece], side: &str) -> Vec<(usize, &'a str, String)> { + let mut at = 0; + let mut out: Vec<(usize, &str, String)> = Vec::new(); + for p in pieces { + match p.op { + Op::Ins if p.side != side => match out.last_mut() { + Some((o, s, t)) if *o == at && *s == p.side => t.push_str(&p.text), + _ => out.push((at, &p.side, p.text.clone())), + }, + Op::Ins => {} + _ => at += p.text.chars().count(), + } + } + out +} + +/// Checks a save by `side`: the text as it stands is unchanged, and every +/// mark that changed was that side's own, or becomes one. +pub fn check_save(old: &[Piece], new: &[Piece], side: &str) -> Result<(), &'static str> { + if base(old) != base(new) { + return Err( + "This save would change the text as it stands. Reload the page; your last few \ + seconds of typing may be lost, sorry.", + ); + } + let (a, b) = (standing_marks(old), standing_marks(new)); + for (o, n) in a.iter().zip(&b) { + if o != n { + let own = |m: &(Op, &str, &str)| m.0 == Op::Same || m.1 == side; + if !own(o) || !own(n) { + return Err("This save would change another side's marks. Reload the page."); + } + } + } + if others_added(old, side) != others_added(new, side) { + return Err("This save would change what another side added. Reload the page."); + } + Ok(()) +} + 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])) + .map(|p| serde_json::json!([p.op.slug(), p.text, p.comment, p.side])) .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]); + assert_eq!(c[0].side, LABEL); + let (a, _) = settle(&p, 1, true).unwrap(); + assert!(base(&a).contains("Three years")); + assert_eq!(changes(&a).len(), 1); + let (r, _) = settle(&p, 1, false).unwrap(); + assert_eq!(base(&r), SENT); + let (all, _) = settle(&a, 1, true).unwrap(); + assert_eq!(base(&all), proposed(&p)); + assert!(settle(&p, 3, true).is_none()); + let (h, hl) = resolve(&p, 1).unwrap(); + assert_eq!(hl.comment, "Too low for us"); + assert!(highlights(&h).is_empty()); + assert_eq!(base(&h), base(&p)); + let j = script_json(&to_json(&[piece(Op::Ins, "&", "", US)])); + assert!(!j.contains('<') && !j.contains('&')); } #[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"); + assert_eq!(v[0].op, "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() - } - ] + removed.segs[0], + Seg { + hl: true, + text: "Two".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); + assert_eq!(added, ["Three years from signing.", "# 3. Territory"]); } } diff --git a/src/seed/legal.rs b/src/seed/legal.rs index b9e7b23..c76ad9f 100644 --- a/src/seed/legal.rs +++ b/src/seed/legal.rs @@ -341,7 +341,7 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul "seed", ) .await?; - label_review(t, &h, &v2).await?; + label_draft(t, &h, &v2).await?; // the management deal: in force, notice day near let mut v = contract( "Management agreement", @@ -572,86 +572,117 @@ 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( +/// The shared draft of the recording agreement (phase 13): opened from our +/// version 2, with the label's tracked changes and highlight, our own +/// highlight, and the notice of the label's edits. The label's link token +/// is thrown away, as the client links' are. +async fn label_draft( t: &mut sqlx::PgConnection, h: &legal::Head, v2: &legal::Version, ) -> Result<()> { - use crate::reviews::{self, Op, Piece}; + use crate::drafts::{self, Actor}; + use crate::reviews::{self, Op, US, 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"), + let us = Actor::staff("seed", "Malee"); + let d = drafts::open(t, h, v2, &us).await?; + reviews::invite(t, h.id, party, "seed").await?; + let label = reviews::party_side(party); + // what the label did: (our words, what became of them, by whom) + let edits: &[(&str, Op, &str, &str)] = &[ + ("three", Op::Del, "five", &label), ( "; any extension needs the Artist's written consent", Op::Del, "", + &label, + ), + ("18%", Op::Del, "14%", &label), + ( + "twice a year", + Op::Mark, + "Quarterly statements are what we ask of every label.", + US, + ), + ( + "ten years", + Op::Mark, + "We need fifteen for the catalogue.", + &label, ), - ("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 { + for (words, op, then, side) in edits { let i = at + body[at..] .find(words) .expect("the demo text has these words"); - pieces.push(p(Op::Same, &body[at..i], "")); + pieces.push(piece(Op::Same, &body[at..i], "", "")); match op { - Op::Mark => pieces.push(p(Op::Mark, words, then)), + Op::Mark => pieces.push(piece(Op::Mark, words, then, side)), _ => { - pieces.push(p(Op::Del, words, "")); - pieces.push(p(Op::Ins, then, "")); + pieces.push(piece(Op::Del, words, "", side)); + pieces.push(piece(Op::Ins, then, "", side)); } } at = i + words.len(); } - pieces.push(p(Op::Same, &body[at..], "")); - pieces.push(p( + pieces.push(piece(Op::Same, &body[at..], "", "")); + pieces.push(piece( Op::Ins, "\n\n# 6. Option\nThe Label has an option on a second album on the same terms.", "", + &label, )); let pieces = reviews::tidy(pieces); - reviews::reply( + // the two sides' marks, saved by each side as the editor would + let ours: Vec<_> = pieces + .iter() + .map(|p| { + if p.side == label { + reviews::unmarked(&if p.op == Op::Ins { + String::new() + } else { + p.text.clone() + }) + } else { + vec![p.clone()] + } + }) + .collect::>() + .concat(); + let ours = reviews::tidy(ours); + drafts::take(t, h.id, &us) + .await? + .map_err(|r| anyhow::anyhow!("{r:?}"))?; + drafts::save(t, h.id, &us, d.revision, &ours) + .await? + .map_err(|r| anyhow::anyhow!("{r:?}"))?; + drafts::release(t, h.id, &us).await?; + let them = Actor::party(party, &name); + drafts::take(t, h.id, &them) + .await? + .map_err(|r| anyhow::anyhow!("{r:?}"))?; + drafts::save(t, h.id, &them, d.revision + 1, &pieces) + .await? + .map_err(|r| anyhow::anyhow!("{r:?}"))?; + drafts::release(t, h.id, &them).await?; + crate::notices::add( 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: "", + &crate::notices::New { + contract: Some(h.id), + kind: "edited", + actor: &name, + by_login: "", + text: &format!("{name} changed the draft of {}", h.code), + href: &format!("/contracts/{}/draft", h.id), }, ) .await?; diff --git a/src/web/drafts.rs b/src/web/drafts.rs new file mode 100644 index 0000000..c3c011a --- /dev/null +++ b/src/web/drafts.rs @@ -0,0 +1,796 @@ +//! The shared draft's pages (phase 13, `crate::drafts`). Our team works on +//! `/contracts/{id}/draft`, each other party on its link `/r/`; both +//! run the same editor and the same actions (`act`): take the draft for +//! editing, save, give it up, accept or reject a change, resolve a +//! highlight, agree. The editor polls `.../state` every few seconds, so a +//! side sees the other's edits, agreements and the lock without reloading. +//! The party's POSTs carry the link's own form token, as the client links'. + +use std::collections::HashMap; +use std::sync::Arc; + +use axum::extract::{Path, Query, State}; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Json, Redirect, Response}; +use axum::{Extension, Form}; +use minijinja::context; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use super::{AppState, Res, message, not_found_page, page, render}; +use crate::audit::{self, Action, Entity, Entry}; +use crate::drafts::{self, Actor, Agreed, Draft, Refused}; +use crate::forms::{self, Fields}; +use crate::legal::{self, Head}; +use crate::notices; +use crate::reviews::{self, Link, US}; +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::Draft, + entity_id: Some(id), + person_id: None, + company_id: None, + fields, + } +} + +/// The colors of the sides, in the order `drafts::required` gives them. +fn sides_json(names: &[(String, String)], agreed: &[drafts::Agreement]) -> Vec { + names + .iter() + .enumerate() + .map(|(i, (side, name))| { + let a = agreed.iter().find(|a| &a.side == side); + json!({ + "side": side, + "name": name, + "color": i % 6, + "agreed": a.is_some(), + "by": a.map(|a| a.actor.clone()), + "at": a.map(|a| dates::fmt_datetime(a.at)), + }) + }) + .collect() +} + +/// Every side that must agree, with its name, Lanna Desk first; a former +/// party whose marks are still in the text comes after. +async fn side_names( + st: &AppState, + contract: i64, + d: &Draft, +) -> anyhow::Result> { + let mut sides = drafts::required(&st.db, contract).await?; + for p in d.pieces() { + if !p.side.is_empty() && !sides.contains(&p.side) { + sides.push(p.side.clone()); + } + } + let mut out = Vec::with_capacity(sides.len()); + for s in sides { + let name = drafts::side_name(&st.db, &s).await?; + out.push((s, name)); + } + Ok(out) +} + +/// What the editor needs to know; the pieces only when the revision it +/// has (`since`) is not the current one. +async fn state_json( + st: &AppState, + d: &Draft, + who: &Actor, + since: Option, +) -> anyhow::Result { + let names = side_names(st, d.contract_id, d).await?; + let required = drafts::required(&st.db, d.contract_id).await?; + let agreed = drafts::agreements(&st.db, d.contract_id, d.revision).await?; + let pieces = d.pieces(); + let locked_version: Option = match d.locked_version_id { + Some(v) => { + sqlx::query_scalar("SELECT version FROM contract_versions WHERE id = $1") + .bind(v) + .fetch_optional(&st.db) + .await? + } + None => None, + }; + let editing = d + .editing() + .map(|(k, n)| json!({ "name": n, "mine": k == who.key })); + Ok(json!({ + "rev": d.revision, + "state": d.state, + "changed": dates::fmt_datetime(d.changed_at), + "editor": editing, + "pieces": if since == Some(d.revision) { serde_json::Value::Null } else { reviews::to_json(&pieces) }, + "sides": sides_json(&names, &agreed), + "need": required.len(), + "have": agreed.iter().filter(|a| required.contains(&a.side)).count(), + "me": who.side, + "locked_version": locked_version, + "lease": drafts::LEASE_SECS, + })) +} + +fn refused(status: StatusCode, r: &Refused, state: serde_json::Value) -> Response { + ( + status, + Json(json!({ "ok": false, "error": r.message(), "state": state })), + ) + .into_response() +} + +fn status_of(r: &Refused) -> StatusCode { + match r { + Refused::Wrong(_) => StatusCode::UNPROCESSABLE_ENTITY, + _ => StatusCode::CONFLICT, + } +} + +/// Who acts, on which contract, and where their pages are. +struct Ctx { + head: Head, + who: Actor, + /// the staff login, for the notices; empty for a party + login: String, + href: String, +} + +fn num(f: &Fields, k: &str) -> Option { + forms::get(f, k).trim().parse().ok() +} + +/// The actions of the editor, for both sides. +async fn act(st: &AppState, c: &Ctx, action: &str, f: &Fields, headers: &HeaderMap) -> Res { + let contract = c.head.id; + let Some(d) = drafts::get(&st.db, contract).await? else { + return Ok(not_found_page(st)); + }; + let rev: i32 = num(f, "rev").unwrap_or(0); + let mut tx = st.db.begin().await?; + let mut notice: Option<(&str, String)> = None; + let outcome: Result<(), Refused> = match action { + "take" => drafts::take(&mut tx, contract, &c.who).await?.map(|_| ()), + "release" => { + drafts::release(&mut tx, contract, &c.who).await?; + Ok(()) + } + "save" => { + let new = match reviews::parse(&forms::get(f, "pieces")) { + Ok(p) => p, + Err(m) => { + tx.rollback().await?; + let s = state_json(st, &d, &c.who, None).await?; + return Ok(refused( + StatusCode::UNPROCESSABLE_ENTITY, + &Refused::Wrong(m), + s, + )); + } + }; + match drafts::save(&mut tx, contract, &c.who, rev, &new).await? { + Ok(r) if r != rev && c.who.side != US => { + notice = Some(( + "edited", + format!("{} changed the draft of {}", c.who.name, c.head.code), + )); + Ok(()) + } + Ok(_) => Ok(()), + Err(e) => Err(e), + } + } + "accept" | "reject" => { + let accept = action == "accept"; + match num::(f, "n") { + Some(n) => drafts::settle(&mut tx, &c.head, &c.who, rev, n, accept) + .await? + .map(|_| { + notice = Some(( + if accept { "accepted" } else { "rejected" }, + format!( + "{} {} a change in the draft of {}", + c.who.name, + if accept { "accepted" } else { "rejected" }, + c.head.code + ), + )); + }), + None => Err(Refused::Stale), + } + } + "resolve" => match num::(f, "k") { + Some(k) => drafts::resolve(&mut tx, &c.head, &c.who, rev, k) + .await? + .map(|_| { + notice = Some(( + "resolved", + format!( + "{} resolved a highlight in the draft of {}", + c.who.name, c.head.code + ), + )); + }), + None => Err(Refused::Stale), + }, + "agree" => { + let person = forms::get(f, "name") + .trim() + .chars() + .take(200) + .collect::(); + if person.is_empty() { + Err(Refused::Wrong("Say who agrees: your name.")) + } else { + let ip = super::client::client_ip(headers); + let ua: String = headers + .get(axum::http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .chars() + .take(300) + .collect(); + match drafts::agree(&mut tx, &c.head, &c.who, &person, rev, &ip, &ua).await? { + Ok(Agreed::Waiting) => { + notice = Some(( + "agreed", + format!( + "{} ({person}) agreed to the draft of {}", + c.who.name, c.head.code + ), + )); + Ok(()) + } + Ok(Agreed::Locked(v)) => { + notice = Some(( + "locked", + format!( + "Every side agreed: {} is locked as version {v}", + c.head.code + ), + )); + Ok(()) + } + Err(e) => Err(e), + } + } + } + _ => { + tx.rollback().await?; + return Ok(not_found_page(st)); + } + }; + if let Err(r) = outcome { + tx.rollback().await?; + let d = drafts::get(&st.db, contract).await?.unwrap_or(d); + let s = state_json(st, &d, &c.who, None).await?; + return Ok(refused(status_of(&r), &r, s)); + } + if let Some((kind, text)) = ¬ice { + notices::add( + &mut tx, + ¬ices::New { + contract: Some(contract), + kind, + actor: &c.who.name, + by_login: &c.login, + text, + href: &format!("/contracts/{contract}/draft"), + }, + ) + .await?; + } + tx.commit().await?; + let d = drafts::get(&st.db, contract).await?.unwrap_or(d); + let since: Option = num(f, "have"); + let s = state_json(st, &d, &c.who, since).await?; + Ok(Json(json!({ "ok": true, "state": s })).into_response()) +} + +#[derive(Debug, Default, Deserialize)] +pub struct StateQuery { + #[serde(default)] + rev: Option, +} + +/// The page around the editor, for both sides. +async fn editor_page(st: &AppState, c: &Ctx, d: &Draft, csrf: &str, user: Option<&User>) -> Res { + let state = state_json(st, d, &c.who, None).await?; + let data = json!({ "base": c.href, "csrf": csrf, "state": state }); + let client: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1") + .bind(c.head.client_id) + .fetch_one(&st.db) + .await?; + let ctx = context! { + head => &c.head, + client, + staff => user.is_some(), + me => &c.who.name, + data => reviews::script_json(&data), + id => c.head.id, + }; + Ok(match user { + Some(u) => page( + st, + u, + "draft.html", + &format!("{} shared draft", c.head.code), + "contracts", + StatusCode::OK, + ctx, + ), + None => render( + st, + "party_draft.html", + context! { + title => format!("{} {}", c.head.code, c.head.title), + v => embedded::STATIC_HASH, + demo => st.cfg.demo(), + demo_text => "This is the page another party to a contract sees on its link, with invented details.", + ..ctx + }, + StatusCode::OK, + ), + }) +} + +// ------------------------------------------------------------ our side + +async fn staff_ctx(st: &AppState, user: &User, id: i64) -> anyhow::Result> { + Ok(legal::head(&st.db, id).await?.map(|head| Ctx { + head, + who: Actor::staff(&user.login, &user.name), + login: user.login.clone(), + href: format!("/contracts/{id}/draft"), + })) +} + +pub async fn staff_page( + State(st): State>, + Extension(user): Extension, + Path(id): Path, +) -> Res { + let Some(c) = staff_ctx(&st, &user, id).await? else { + return Ok(not_found_page(&st)); + }; + let Some(d) = drafts::get(&st.db, id).await? else { + return Ok(Redirect::to(&format!("/contracts/{id}#draft")).into_response()); + }; + audit::record(&st.db, &audit_entry(&user.login, Action::View, id, &[])).await?; + editor_page(&st, &c, &d, &user.csrf, Some(&user)).await +} + +/// `state` (the editor's poll) and `diff` (the git view). +pub async fn staff_get( + State(st): State>, + Extension(user): Extension, + Path((id, what)): Path<(i64, String)>, + Query(q): Query, +) -> Res { + let (Some(c), Some(d)) = ( + staff_ctx(&st, &user, id).await?, + drafts::get(&st.db, id).await?, + ) else { + return Ok(not_found_page(&st)); + }; + match what.as_str() { + "state" => Ok(Json(state_json(&st, &d, &c.who, q.rev).await?).into_response()), + "diff" => { + let pieces = d.pieces(); + let names = side_names(&st, id, &d).await?; + let changes: Vec = reviews::changes(&pieces) + .into_iter() + .map(|ch| { + let who = names + .iter() + .find(|(s, _)| *s == ch.side) + .map_or("", |(_, n)| n.as_str()); + json!({ "n": ch.n, "who": who, "removed": ch.removed, "added": ch.added }) + }) + .collect(); + Ok(page( + &st, + &user, + "draft_diff.html", + &format!("{} draft as a diff", c.head.code), + "contracts", + StatusCode::OK, + context! { + id, head => &c.head, changes, + git => reviews::git_view(&pieces), + rev => d.revision, + }, + )) + } + _ => Ok(not_found_page(&st)), + } +} + +pub async fn staff_act( + State(st): State>, + Extension(user): Extension, + Path((id, action)): Path<(i64, String)>, + headers: HeaderMap, + Form(f): Form, +) -> Res { + let Some(c) = staff_ctx(&st, &user, id).await? else { + return Ok(not_found_page(&st)); + }; + if action == "open" { + return open(&st, &user, &c, &f).await; + } + let mut f = f; + if action == "agree" { + f.insert("name".into(), user.name.clone()); + } + act(&st, &c, &action, &f, &headers).await +} + +/// Opens the draft from a version with a text. +async fn open(st: &AppState, user: &User, c: &Ctx, f: &Fields) -> Res { + let id = c.head.id; + let versions = legal::versions(&st.db, id).await?; + let Some(v) = versions + .iter() + .find(|v| !v.body.is_empty() && forms::get(f, "draft_version") == v.version.to_string()) + else { + return Ok(message( + st, + StatusCode::UNPROCESSABLE_ENTITY, + "Choose a version with a text", + "The shared draft starts from a version kept as a text in the app.", + (&format!("/contracts/{id}#draft"), "Back to the contract"), + )); + }; + if drafts::get(&st.db, id).await?.is_some_and(|d| d.open()) { + return Ok(Redirect::to(&format!("/contracts/{id}/draft")).into_response()); + } + let mut tx = st.db.begin().await?; + drafts::open(&mut tx, &c.head, v, &c.who).await?; + audit::record(&mut *tx, &audit_entry(&user.login, Action::Create, id, &[])).await?; + tx.commit().await?; + Ok(Redirect::to(&format!("/contracts/{id}/draft")).into_response()) +} + +/// A party's link: new, shown once; their open one closes. +pub async fn invite( + 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 Some(party) = legal::parties(&st.db, id) + .await? + .into_iter() + .find(|p| p.removed_at.is_none() && forms::get(&f, "party") == p.id.to_string()) + else { + return Ok(not_found_page(&st)); + }; + let mut tx = st.db.begin().await?; + let (link, token) = reviews::invite(&mut tx, id, party.id, &user.login).await?; + audit::record( + &mut *tx, + &audit_entry(&user.login, Action::Create, link.id, &[]), + ) + .await?; + crate::journal::append( + &mut tx, + &crate::journal::New { + actor: &user.login, + client: Some(head.client_id), + contract: Some(id), + event: "draft link made", + detail: format!( + "A link to the shared draft for {} (link {}).", + party.name, link.id + ), + }, + ) + .await?; + tx.commit().await?; + let url = format!("{}/r/{token}", st.cfg.public_url); + Ok(page( + &st, + &user, + "invite_made.html", + "The link to the draft", + "contracts", + StatusCode::OK, + context! { + id, head, url, + qr => super::links::qr_svg(&url), + party => party.name, + until => dates::fmt_date(link.expires_at.with_timezone(&dates::bangkok()).date_naive()), + }, + )) +} + +pub async fn close_link( + 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 mut tx = st.db.begin().await?; + if reviews::close(&mut tx, &link, &user.login).await? { + let party = drafts::side_name(&mut *tx, &reviews::party_side(link.party_id)).await?; + crate::journal::append( + &mut tx, + &crate::journal::New { + actor: &user.login, + client: Some(head.client_id), + contract: Some(id), + event: "draft link closed", + detail: format!( + "The link of {party} to the shared draft was closed (link {}).", + link.id + ), + }, + ) + .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}#draft")).into_response()) +} + +/// The card on the contract page. +#[derive(Debug, Default, Serialize)] +pub struct Card { + state: String, + revision: i32, + changed: String, + editing: Option, + changes: usize, + highlights: usize, + have: usize, + need: usize, + locked_version: Option, + parties: Vec, +} + +#[derive(Debug, Serialize)] +struct PartyLink { + id: i64, + name: String, + link: Option, + link_state: String, +} + +pub async fn card(st: &AppState, contract: i64) -> anyhow::Result { + let links = reviews::for_contract(&st.db, contract).await?; + let parties: Vec = legal::parties(&st.db, contract) + .await? + .into_iter() + .filter(|p| p.removed_at.is_none()) + .map(|p| { + let open = links.iter().find(|(l, _)| l.party_id == p.id && l.open()); + PartyLink { + id: p.id, + name: p.name, + link: open.map(|(l, _)| l.id), + link_state: match open { + Some((l, _)) => match l.last_used_at { + Some(at) => format!("link last opened {}", dates::fmt_datetime(at)), + None => "link not opened yet".into(), + }, + None => "no link yet".into(), + }, + } + }) + .collect(); + let Some(d) = drafts::get(&st.db, contract).await? else { + return Ok(Card { + parties, + ..Card::default() + }); + }; + let pieces = d.pieces(); + let need = drafts::required(&st.db, contract).await?; + let have = drafts::agreements(&st.db, contract, d.revision) + .await? + .iter() + .filter(|a| need.contains(&a.side)) + .count(); + let locked_version = match d.locked_version_id { + Some(v) => { + sqlx::query_scalar("SELECT version FROM contract_versions WHERE id = $1") + .bind(v) + .fetch_optional(&st.db) + .await? + } + None => None, + }; + Ok(Card { + state: d.state.clone(), + revision: d.revision, + changed: dates::fmt_datetime(d.changed_at), + editing: d.editing().map(|(_, n)| n.to_string()), + changes: reviews::changes(&pieces).len(), + highlights: reviews::highlights(&pieces).len(), + have, + need: need.len(), + locked_version, + parties, + }) +} + +// ------------------------------------------------------- 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, + ) +} + +async fn party_ctx(st: &AppState, token: &str) -> anyhow::Result> { + let link = match reviews::by_token(&st.db, token).await? { + None => { + return Ok(Err(closed( + st, + "This link does not work", + "There is no draft 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() => { + return Ok(Err(closed( + st, + "This link is closed", + "This link to the draft no longer works. Ask Lanna Desk for a new one.", + StatusCode::GONE, + ))); + } + Some(l) => l, + }; + let Some(head) = legal::head(&st.db, link.contract_id).await? else { + return Ok(Err(not_found_page(st))); + }; + let name = drafts::side_name(&st.db, &reviews::party_side(link.party_id)).await?; + Ok(Ok(( + Ctx { + head, + who: Actor::party(link.party_id, &name), + login: String::new(), + href: format!("/r/{token}"), + }, + link, + ))) +} + +pub async fn party_page(State(st): State>, Path(token): Path) -> Res { + let (c, link) = match party_ctx(&st, &token).await? { + Ok(x) => x, + Err(r) => return Ok(r), + }; + let Some(d) = drafts::get(&st.db, c.head.id).await? else { + return Ok(closed( + &st, + "No draft yet", + "Lanna Desk has not opened the draft yet. Try again later.", + StatusCode::NOT_FOUND, + )); + }; + reviews::used(&st.db, link.id).await?; + let actor = format!("review {}", link.id); + audit::record(&st.db, &audit_entry(&actor, Action::View, c.head.id, &[])).await?; + editor_page(&st, &c, &d, &link.csrf, None).await +} + +pub async fn party_state( + State(st): State>, + Path((token, what)): Path<(String, String)>, + Query(q): Query, +) -> Res { + let (c, _) = match party_ctx(&st, &token).await? { + Ok(x) => x, + Err(r) => return Ok(r), + }; + let Some(d) = drafts::get(&st.db, c.head.id).await? else { + return Ok(not_found_page(&st)); + }; + if what != "state" { + return Ok(not_found_page(&st)); + } + Ok(Json(state_json(&st, &d, &c.who, q.rev).await?).into_response()) +} + +pub async fn party_act( + State(st): State>, + Path((token, action)): Path<(String, String)>, + headers: HeaderMap, + Form(f): Form, +) -> Res { + let (c, link) = match party_ctx(&st, &token).await? { + Ok(x) => x, + Err(r) => return Ok(r), + }; + if !session::same_token(&forms::get(&f, "csrf"), &link.csrf) { + return Ok(( + StatusCode::FORBIDDEN, + Json(json!({ "ok": false, "error": "The page was too old: reload it." })), + ) + .into_response()); + } + reviews::used(&st.db, link.id).await?; + act(&st, &c, &action, &f, &headers).await +} + +// ---------------------------------------------------------- the notices + +pub async fn notices_page( + State(st): State>, + Extension(user): Extension, +) -> Res { + let seen = notices::seen(&st.db, &user.login).await?; + let list = notices::list(&st.db, 100).await?; + #[derive(Serialize)] + struct Row { + text: String, + href: String, + at: String, + new: bool, + kind: String, + } + let rows: Vec = list + .iter() + .map(|n| Row { + text: n.text.clone(), + href: n.href.clone(), + at: dates::fmt_datetime(n.at), + new: n.id > seen && n.by_login != user.login, + kind: n.kind.clone(), + }) + .collect(); + if let Some(top) = list.first() { + notices::mark_seen(&st.db, &user.login, top.id).await?; + } + Ok(page( + &st, + &user, + "notices.html", + "Notices", + "notices", + StatusCode::OK, + context! { rows }, + )) +} + +pub async fn notices_count( + State(st): State>, + Extension(user): Extension, +) -> Res { + let n = notices::unread(&st.db, &user.login).await?; + Ok(Json(json!({ "unread": n })).into_response()) +} + +/// The unseen notices of each contract, for the contracts list. +pub async fn unread_by_contract(st: &AppState, login: &str) -> anyhow::Result> { + Ok(notices::unread_by_contract(&st.db, login) + .await? + .into_iter() + .collect()) +} diff --git a/src/web/legal.rs b/src/web/legal.rs index db35159..9befbd7 100644 --- a/src/web/legal.rs +++ b/src/web/legal.rs @@ -876,11 +876,6 @@ 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()) @@ -891,7 +886,7 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f ) }) .collect(); - let reviews = super::reviews::card(st, id).await?; + let draft = super::drafts::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) @@ -912,7 +907,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, review_parties, text_versions, reviews, + parties, live_parties, text_versions, draft, party => form.party, party_errors => form.party_errors, check => form.check, @@ -944,24 +939,6 @@ 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 7d6f70a..b97e533 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -7,6 +7,7 @@ pub mod client; pub mod companies; pub mod dashboard; pub mod documents; +pub mod drafts; pub mod legal; pub mod links; pub mod notifications; @@ -15,7 +16,6 @@ pub mod pack; pub mod papers; pub mod people; pub mod records; -pub mod reviews; use std::sync::{Arc, RwLock}; use std::time::Duration; @@ -338,10 +338,10 @@ 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) + r = r.route("/r/{token}", get(drafts::party_page)).route( + "/r/{token}/{action}", + get(drafts::party_state) + .post(drafts::party_act) .layer(DefaultBodyLimit::max(REVIEW_LIMIT)), ); // The client's pages: open without a login, each checks its link. @@ -453,13 +453,20 @@ 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}/draft", get(drafts::staff_page)) + .route( + "/contracts/{id}/draft/{action}", + get(drafts::staff_get) + .post(drafts::staff_act) + .layer(DefaultBodyLimit::max(REVIEW_LIMIT)), + ) + .route("/contracts/{id}/invites", post(drafts::invite)) .route( "/contracts/{id}/review-links/{lid}/close", - post(reviews::close), + post(drafts::close_link), ) + .route("/notices", get(drafts::notices_page)) + .route("/notices/count", get(drafts::notices_count)) .route("/originals", get(originals::list).post(originals::create)) .route("/originals/new", get(originals::new)) .route("/originals/{code}", get(originals::show)) @@ -514,7 +521,7 @@ fn is_public(path: &str) -> bool { || path.starts_with("/r/") } -/// The largest reply from the review page: the pieces of a text of +/// The largest save from the draft's editor: the pieces of a text of /// `legal::BODY_LIMIT` characters, urlencoded. const REVIEW_LIMIT: usize = 8 * 1024 * 1024; @@ -600,8 +607,14 @@ async fn forms_guard(State(st): State>, req: Request, next: Next) ) .into_response(); } + // the shared draft's editor saves the whole marked-up text at once + let limit = if is_draft_save(req.uri().path()) { + REVIEW_LIMIT + } else { + FORM_LIMIT + }; let (parts, body) = req.into_parts(); - let bytes = match axum::body::to_bytes(body, FORM_LIMIT).await { + let bytes = match axum::body::to_bytes(body, limit).await { Ok(b) => b, Err(_) => { return (StatusCode::PAYLOAD_TOO_LARGE, "The form is too large.").into_response(); @@ -633,6 +646,16 @@ async fn forms_guard(State(st): State>, req: Request, next: Next) /// The addresses that take uploads: `/people/{id}/documents`, /// `/companies/{id}/documents` and a contract's `/contracts/{id}/versions`. +/// `/contracts/{id}/draft/save`. +fn is_draft_save(path: &str) -> bool { + let parts: Vec<&str> = path.split('/').collect(); + matches!( + parts.as_slice(), + ["", "contracts", id, "draft", "save"] + if !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()) + ) +} + fn is_upload(path: &str) -> bool { let parts: Vec<&str> = path.split('/').collect(); matches!( diff --git a/src/web/reviews.rs b/src/web/reviews.rs deleted file mode 100644 index 376ce2b..0000000 --- a/src/web/reviews.rs +++ /dev/null @@ -1,543 +0,0 @@ -//! 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 f59a076..d546cd4 100644 --- a/static/app.css +++ b/static/app.css @@ -2380,3 +2380,228 @@ details.move[open] .mini { grid-template-columns: 2.4em 2.4em 1fr; } } + +/* ---- phase 13 step 2: the bell and the shared draft */ +.topacts { + display: flex; + align-items: center; + gap: 8px; +} +.ib.bell { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + text-decoration: none; +} +.ib.bell.has { + border-color: var(--label); +} +.bellcount { + position: absolute; + top: -6px; + right: -7px; + min-width: 18px; + height: 18px; + padding: 0 5px; + border-radius: 9px; + font: 700 11px/18px var(--sans); + text-align: center; + color: #fff; + background: var(--bad); +} +.notices { + list-style: none; + margin: 0; + padding: 0; +} +.notices li { + display: flex; + flex-wrap: wrap; + gap: 4px 10px; + align-items: baseline; + padding: 10px 16px; + border-bottom: 1px solid var(--line); +} +.notices li:last-child { + border-bottom: 0; +} +.notices li.new { + background: var(--accent-s); +} +.notices li a { + flex: 1 1 260px; +} +.minihead { + font-size: 13px; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--label); + margin: 14px 0 6px; +} +/* the sides' colors: Lanna Desk first */ +.w0 { --who: #2563c9; } +.w1 { --who: #8b3fd9; } +.w2 { --who: #0e8a7e; } +.w3 { --who: #c2570c; } +.w4 { --who: #b3245f; } +.w5 { --who: #6b7280; } +:root[data-theme="dark"] .w0 { --who: #7aa7ff; } +:root[data-theme="dark"] .w1 { --who: #c39bff; } +:root[data-theme="dark"] .w2 { --who: #4fd1c0; } +:root[data-theme="dark"] .w3 { --who: #ffa55c; } +:root[data-theme="dark"] .w4 { --who: #ff7ab0; } +:root[data-theme="dark"] .w5 { --who: #a5adba; } +.dr ins { + text-decoration: none; + color: var(--who); + background: color-mix(in srgb, var(--who) 13%, transparent); + border-bottom: 2px solid var(--who); +} +.dr del { + color: color-mix(in srgb, var(--who) 80%, var(--fg)); + background: color-mix(in srgb, var(--who) 9%, transparent); + text-decoration: line-through 2px var(--who); +} +.dr mark { + color: inherit; + background: color-mix(in srgb, #f5c000 38%, transparent); + border-bottom: 2px dotted var(--who); +} +.dr del + ins { + margin-left: 2px; +} +/* the party's page of the draft takes the width the editor needs */ +.cmain:has(#draft-editor) { + max-width: 1240px; +} +.dr .flash { + outline: 3px solid var(--accent); + outline-offset: 2px; +} +.drwrap .rvedit:not(.on) { + cursor: default; + caret-color: transparent; +} +.drwrap .rvedit.on { + border-color: var(--label); +} +.drbar { + display: flex; + flex-wrap: wrap; + gap: 8px 14px; + align-items: center; + justify-content: space-between; + padding: 10px 12px; + margin-bottom: 10px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--panel); +} +.drstate { + font-weight: 600; +} +.drbtns { + display: flex; + gap: 8px; +} +.drcols { + display: grid; + grid-template-columns: minmax(0, 1fr) 320px; + gap: 18px; + align-items: start; +} +.drside { + position: sticky; + top: calc(var(--toph) + 12px); + max-height: calc(100vh - var(--toph) - 24px); + overflow-y: auto; +} +.drside .minihead:first-child { + margin-top: 0; +} +.drlist, +.drsides, +.drlegend { + list-style: none; + margin: 0; + padding: 0; +} +.drlist li, +.drsides li { + display: flex; + gap: 8px; + align-items: baseline; + padding: 7px 0; + border-bottom: 1px dashed var(--line); + font-size: 14px; +} +.drwhat { + flex: 1; + min-width: 0; + cursor: pointer; + overflow-wrap: anywhere; +} +.drwhat del { + color: var(--bad); + margin-right: 4px; +} +.drwhat ins { + color: var(--ok); + text-decoration: none; + border-bottom: 1px solid var(--ok); +} +.drwhat mark { + color: inherit; + background: color-mix(in srgb, #f5c000 38%, transparent); +} +.drwhat .sub { + display: block; +} +.dracts { + display: flex; + gap: 4px; + flex: none; +} +.drdot { + flex: none; + width: 10px; + height: 10px; + border-radius: 50%; + background: var(--who); + transform: translateY(1px); +} +.drsides li.ok { + color: var(--ok); +} +.drlegend { + display: flex; + flex-wrap: wrap; + gap: 6px 14px; + margin-top: 6px; + font-size: 13px; + color: var(--mute); +} +.drlegend li { + display: flex; + gap: 6px; + align-items: baseline; +} +.drname { + display: grid; + gap: 4px; + margin: 10px 0 8px; + font-size: 13px; +} +#dr-agree { + margin-top: 10px; +} +@media (max-width: 1000px) { + .drcols { + grid-template-columns: 1fr; + } + .drside { + position: static; + max-height: none; + } +} diff --git a/static/app.js b/static/app.js index 8b4ba3e..4e87c9e 100644 --- a/static/app.js +++ b/static/app.js @@ -192,6 +192,33 @@ }); document.addEventListener("DOMContentLoaded", applyShownWhen); + // ---- the bell: how many notices this staff member has not seen, asked + // for now and every 15 seconds while the page is open + function bell() { + var count = document.getElementById("bell-count"); + if (!count || !window.fetch) return; + fetch("/notices/count", { credentials: "same-origin", headers: { accept: "application/json" } }) + .then(function (r) { + return r.ok ? r.json() : null; + }) + .then(function (j) { + if (!j) return; + count.hidden = !j.unread; + count.textContent = j.unread > 99 ? "99+" : String(j.unread); + var b = document.getElementById("bell"); + b.setAttribute("aria-label", j.unread ? "Notices, " + j.unread + " new" : "Notices"); + b.classList.toggle("has", j.unread > 0); + }) + .catch(function () { + /* offline for a moment: the next try tells */ + }); + } + document.addEventListener("DOMContentLoaded", function () { + if (!document.getElementById("bell-count")) return; + bell(); + setInterval(bell, 15000); + }); + // a label's Print button document.querySelectorAll("[data-print]").forEach(function (b) { b.addEventListener("click", function () { diff --git a/static/draft-editor.js b/static/draft-editor.js new file mode 100644 index 0000000..c795175 --- /dev/null +++ b/static/draft-editor.js @@ -0,0 +1,809 @@ +// The shared draft's editor (phase 13), on our page and on a party's link. +// The text is a list of pieces {k, t, c, s}: "same" (agreed text), "ins" +// (added by side s), "del" (crossed out by side s) and "mark" (highlighted +// by side s, c = its comment). Edits work on that list and redraw, so no +// side can change the text as it stands or another side's marks; the +// server checks the same rule (reviews::check_save). One side edits at a +// time: Edit takes the draft for a while that each save renews; the others +// see the saves within seconds, as the page asks for news every 3 seconds. +// No inline script: the Content Security Policy allows none. +(function () { + "use strict"; + + var root = document.querySelector("[data-draft]"); + if (!root) return; + var data = JSON.parse(document.getElementById("dr-data").textContent); + var base = data.base; + var csrf = data.csrf; + var ed = document.getElementById("dr-text"); + var $ = function (id) { + return document.getElementById(id); + }; + var state = data.state; + var me = state.me; + var rev = state.rev; + var pieces = []; + var editing = false; + var dirty = false; + var saving = false; + var lastSave = 0; + var history = []; + var lastSel = null; + var sides = {}; + var saveTimer = null; + + // ---- talking to the server + function post(action, fields) { + var body = new URLSearchParams(); + body.set("csrf", csrf); + body.set("rev", String(rev)); + // a save makes the next revision, whose pieces the editor has + body.set("have", String(action === "save" ? rev + 1 : rev)); + Object.keys(fields || {}).forEach(function (k) { + body.set(k, fields[k]); + }); + return fetch(base + "/" + action, { + method: "POST", + credentials: "same-origin", + headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, + body: body.toString(), + }).then(function (r) { + return r + .json() + .catch(function () { + return { ok: false, error: "The server did not answer properly. Reload the page." }; + }) + .then(function (j) { + if (j.state) take(j.state, !j.ok); + if (!j.ok && j.error) say(j.error); + return j; + }); + }); + } + + function poll() { + if (document.hidden) return; + fetch(base + "/state?rev=" + rev, { credentials: "same-origin", headers: { accept: "application/json" } }) + .then(function (r) { + return r.ok ? r.json() : null; + }) + .then(function (s) { + if (s) take(s, false); + }) + .catch(function () {}); + } + + // A state from the server: the pieces replace ours unless we are the + // editor with our own edits, or `force` (a refused change). + function take(s, force) { + state = s; + sides = {}; + (s.sides || []).forEach(function (x) { + sides[x.side] = x; + }); + if (s.pieces && (!editing || force)) { + pieces = s.pieces.map(function (p) { + return { k: p[0], t: p[1], c: p[2] || "", s: p[3] || "" }; + }); + dirty = false; + draw(null); + } + // only one side edits: the server's revision is always the one to + // build on, also with edits of ours not saved yet + rev = s.rev; + if (editing && !(s.editor && s.editor.mine)) { + stopEditing(); + say("Your editing time ran out, or someone else took the draft. Press Edit to go on."); + } + panels(); + } + + // ---- drawing + function color(side) { + return sides[side] ? sides[side].color : 5; + } + + function nameOf(side) { + return sides[side] ? sides[side].name : "a former party"; + } + + // which change each piece belongs to, as the server counts them + function changeOf() { + var n = 0, open = null; + return pieces.map(function (p) { + if (p.k === "ins" || p.k === "del") { + if (open !== p.s) { + n++; + open = p.s; + } + return n; + } + open = null; + return 0; + }); + } + + function draw(caret) { + var top = ed.scrollTop; + var of = changeOf(); + var markNo = 0; + 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.k !== "same") { + el.className = "w" + color(p.s); + el.title = (p.k === "ins" ? "Added by " : p.k === "del" ? "Crossed out by " : "Highlighted by ") + + nameOf(p.s) + (p.c ? ": " + p.c : ""); + } + if (of[i] && (i === 0 || of[i - 1] !== of[i])) el.setAttribute("data-ch", of[i]); + if (p.k === "mark") el.setAttribute("data-mk", ++markNo); + ed.appendChild(el); + }); + var last = pieces[pieces.length - 1]; + if (!last || last.t.charAt(last.t.length - 1) === "\n") ed.appendChild(document.createElement("br")); + ed.scrollTop = top; + if (caret != null) place(caret); + } + + function short(t, n) { + t = t.replace(/\s+/g, " ").trim(); + return t.length > n ? t.slice(0, n) + "…" : t; + } + + function li(cls) { + var el = document.createElement("li"); + if (cls) el.className = cls; + return el; + } + + function button(label, cls, fn) { + var b = document.createElement("button"); + b.type = "button"; + b.className = "btn sm " + (cls || ""); + b.textContent = label; + b.addEventListener("click", fn); + return b; + } + + function dot(side) { + var d = document.createElement("span"); + d.className = "drdot w" + color(side); + d.setAttribute("aria-hidden", "true"); + return d; + } + + function panels() { + var locked = state.state === "locked"; + var other = state.editor && !state.editor.mine; + // the bar + var text; + if (locked) { + text = "Locked: every side agreed. The text is version " + state.locked_version + " and never changes."; + } else if (editing) { + text = saving || dirty ? "You are editing. Saving…" : "You are editing. Every change is saved."; + } else if (other) { + text = state.editor.name + " is editing. Their changes show here as they save."; + } else { + text = "Open for edits. Last change " + state.changed + "."; + } + $("dr-state").textContent = text; + $("dr-edit").hidden = locked || editing; + $("dr-edit").disabled = !!other; + $("dr-done").hidden = !editing; + $("dr-tools").hidden = !editing; + ed.contentEditable = editing ? "true" : "false"; + ed.classList.toggle("on", editing); + // the changes + var list = $("dr-changes"); + list.textContent = ""; + var ch = []; + var of = changeOf(); + pieces.forEach(function (p, i) { + if (!of[i]) return; + var c = ch[of[i] - 1]; + if (!c) c = ch[of[i] - 1] = { n: of[i], s: p.s, removed: "", added: "" }; + if (p.k === "del") c.removed += p.t; + else c.added += p.t; + }); + ch.forEach(function (c) { + var el = li(); + el.appendChild(dot(c.s)); + var what = document.createElement("span"); + what.className = "drwhat"; + var who = document.createElement("b"); + who.textContent = c.n + ". " + nameOf(c.s) + " "; + what.appendChild(who); + if (c.removed) { + var d = document.createElement("del"); + d.textContent = short(c.removed, 60); + what.appendChild(d); + } + if (c.added) { + var a = document.createElement("ins"); + a.textContent = short(c.added, 60); + what.appendChild(a); + } + what.addEventListener("click", function () { + show("[data-ch='" + c.n + "']"); + }); + el.appendChild(what); + if (!locked) { + var acts = document.createElement("span"); + acts.className = "dracts"; + if (c.s !== me) { + acts.appendChild(button("Accept", "pri", function () { + settle("accept", c.n); + })); + acts.appendChild(button("Reject", "ghost", function () { + settle("reject", c.n); + })); + } else { + acts.appendChild(button("Withdraw", "ghost", function () { + settle("reject", c.n); + })); + } + el.appendChild(acts); + } + list.appendChild(el); + }); + $("dr-changes-n").textContent = ch.length ? "(" + ch.length + ")" : ""; + if (!ch.length) { + var none = li("muted"); + none.textContent = "None: the text stands as it is."; + list.appendChild(none); + } + // the highlights + var marks = $("dr-marks"); + marks.textContent = ""; + var k = 0; + pieces.forEach(function (p) { + if (p.k !== "mark") return; + var n = ++k; + var el = li(); + el.appendChild(dot(p.s)); + var what = document.createElement("span"); + what.className = "drwhat"; + var m = document.createElement("mark"); + m.textContent = short(p.t, 50); + what.appendChild(m); + var c = document.createElement("span"); + c.className = "sub"; + c.textContent = nameOf(p.s) + (p.c ? ": " + p.c : ""); + what.appendChild(c); + what.addEventListener("click", function () { + show("[data-mk='" + n + "']"); + }); + el.appendChild(what); + if (!locked) { + var acts = document.createElement("span"); + acts.className = "dracts"; + acts.appendChild(button("Resolve", "ghost", function () { + act("resolve", { k: String(n) }); + })); + el.appendChild(acts); + } + marks.appendChild(el); + }); + $("dr-marks-n").textContent = k ? "(" + k + ")" : ""; + $("dr-marks-box").hidden = !k; + // the sides and their agreement + var sl = $("dr-sides"); + sl.textContent = ""; + var legend = $("dr-legend"); + legend.textContent = ""; + (state.sides || []).forEach(function (x) { + var el = li(x.agreed ? "ok" : ""); + el.appendChild(dot(x.side)); + var t = document.createElement("span"); + t.textContent = x.name + (x.side === me ? " (you)" : "") + ": " + + (x.agreed ? "agreed, " + x.by + ", " + x.at : "not agreed yet"); + el.appendChild(t); + sl.appendChild(el); + var lg = li(); + lg.appendChild(dot(x.side)); + lg.appendChild(document.createTextNode(x.name)); + legend.appendChild(lg); + }); + var mine = sides[me] && sides[me].agreed; + var agree = $("dr-agree"); + agree.disabled = locked || ch.length > 0 || k > 0 || mine || !!other || dirty; + $("dr-agree-form").hidden = locked; + $("dr-agree-note").textContent = locked + ? "" + : ch.length || k + ? "Accept or reject the open changes and resolve the highlights first: you agree to the text as it stands." + : mine + ? "You agree to this text. A new change would ask everyone again." + : state.have + " of " + state.need + " sides agree. When all do, the text locks as a contract version."; + } + + function show(sel) { + var el = ed.querySelector(sel); + if (!el) return; + el.scrollIntoView({ block: "center", behavior: "smooth" }); + el.classList.add("flash"); + setTimeout(function () { + el.classList.remove("flash"); + }, 1200); + } + + function say(t) { + $("dr-note").textContent = t || ""; + } + + // ---- caret positions as offsets into the whole text + 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, s = window.getSelection(), 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, on a flat form: one entry per UTF-16 unit + function flat() { + var f = { t: [], k: [], c: [], a: [] }; + pieces.forEach(function (p) { + for (var i = 0; i < p.t.length; i++) { + f.t.push(p.t[i]); + f.k.push(p.k); + f.c.push(p.c); + f.a.push(p.s); + } + }); + return f; + } + + function build(f) { + var res = []; + for (var i = 0; i < f.t.length; i++) { + var l = res[res.length - 1]; + if (l && l.k === f.k[i] && l.c === f.c[i] && l.s === f.a[i]) l.t += f.t[i]; + else res.push({ k: f.k[i], t: f.t[i], c: f.c[i], s: f.a[i] }); + } + pieces = res; + } + + // what this side may not touch: anything crossed out, and the other + // sides' additions and highlights + function fixed(f, i) { + return f.k[i] === "del" || (f.k[i] !== "same" && f.a[i] !== me); + } + + function changed() { + dirty = true; + clearTimeout(saveTimer); + saveTimer = setTimeout(save, 700); + panels(); + } + + function remember() { + history.push(JSON.stringify(pieces)); + if (history.length > 300) history.shift(); + } + + // crosses [s, e) out; returns how many units of it stay + function crossOut(f, s, e) { + var out = { t: [], k: [], c: [], a: [] }, kept = 0, blocked = 0; + for (var i = 0; i < f.t.length; i++) { + var inside = i >= s && i < e; + if (inside && f.k[i] === "ins" && f.a[i] === me) continue; + out.t.push(f.t[i]); + if (inside) kept++; + if (inside && !fixed(f, i)) { + out.k.push("del"); + out.c.push(""); + out.a.push(me); + } else { + if (inside && f.k[i] !== "del") blocked++; + out.k.push(f.k[i]); + out.c.push(f.c[i]); + out.a.push(f.a[i]); + } + } + f.t = out.t; + f.k = out.k; + f.c = out.c; + f.a = out.a; + if (blocked) say("Another side's additions and highlights stay: accept, reject or resolve them in the list."); + return kept; + } + + function insert(f, p, text) { + // never inside another side's addition: after it + while (p > 0 && p < f.t.length && f.k[p] === "ins" && f.a[p] !== me && f.k[p - 1] === "ins" && f.a[p - 1] === f.a[p]) p++; + // what is crossed out comes first, then what replaces it + while (p < f.t.length && f.k[p] === "del") p++; + var u = text.split(""); + var fill = function (v) { + return u.map(function () { + return v; + }); + }; + f.t.splice.apply(f.t, [p, 0].concat(u)); + f.k.splice.apply(f.k, [p, 0].concat(fill("ins"))); + f.c.splice.apply(f.c, [p, 0].concat(fill(""))); + f.a.splice.apply(f.a, [p, 0].concat(fill(me))); + return p + u.length; + } + + 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); + var end = insert(f, p, text); + build(f); + draw(end); + changed(); + } + + function strike(r, atEnd) { + remember(); + var f = flat(); + var kept = crossOut(f, r.s, r.e); + build(f); + draw(atEnd ? r.s + kept : r.s); + changed(); + } + + function back(p, unit) { + var f = flat(); + while (p > 0 && fixed(f, p - 1)) 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]) && !fixed(f, 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(), n = f.t.length; + while (p < n && fixed(f, p)) 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]) && !fixed(f, 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) return say("Select the words to highlight first."); + var comment = ($("dr-comment").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.a[i] === me)) { + f.k[i] = "mark"; + f.c[i] = comment; + f.a[i] = me; + } + } + build(f); + $("dr-comment").value = ""; + draw(r.e); + changed(); + } + + function restore(r) { + if (!r) return; + var f = flat(); + var s = r.s, e = r.e; + var own = function (i) { + return f.k[i] !== undefined && f.k[i] !== "same" && f.a[i] === me; + }; + if (s === e) { + var at = own(s) ? s : own(s - 1) ? s - 1 : -1; + if (at < 0) return say("Select what to restore, or put the caret in one of your own marks."); + var kind = f.k[at]; + s = at; + e = at; + while (s > 0 && own(s - 1) && f.k[s - 1] === kind) s--; + while (e < f.t.length && own(e) && f.k[e] === kind) e++; + } + remember(); + var out = { t: [], k: [], c: [], a: [] }; + for (var i = 0; i < f.t.length; i++) { + var mine = i >= s && i < e && own(i); + if (mine && f.k[i] === "ins") continue; + out.t.push(f.t[i]); + out.k.push(mine ? "same" : f.k[i]); + out.c.push(mine ? "" : f.c[i]); + out.a.push(mine ? "" : f.a[i]); + } + build(out); + draw(s); + changed(); + } + + function undo() { + if (!history.length) return say("Nothing to undo."); + var caret = current(); + pieces = JSON.parse(history.pop()); + draw(caret ? caret.s : null); + changed(); + } + + // what the browser changed itself (a keyboard's composition), taken as + // an edit + function resync() { + var mine = pieces.map(function (p) { + return p.t; + }).join(""); + var now = ed.textContent; + if (mine === now) return; + var a = 0; + while (a < mine.length && a < now.length && mine[a] === now[a]) a++; + var b = 0; + while (b < mine.length - a && b < now.length - a && mine[mine.length - 1 - b] === now[now.length - 1 - b]) b++; + var added = now.slice(a, now.length - b); + remember(); + var f = flat(); + var p = a + crossOut(f, a, mine.length - b); + var end = added ? insert(f, p, added) : p; + build(f); + draw(end); + changed(); + } + + // ---- editing: take, save, give up + function save() { + if (!editing || !dirty) return Promise.resolve(); + if (saving) { + clearTimeout(saveTimer); + saveTimer = setTimeout(save, 400); + return Promise.resolve(); + } + saving = true; + dirty = false; + panels(); + var json = JSON.stringify(pieces.map(function (p) { + return [p.k, p.t, p.c, p.s]; + })); + return post("save", { pieces: json }) + .then(function (j) { + saving = false; + lastSave = Date.now(); + if (!j.ok) stopEditing(); + panels(); + }) + .catch(function () { + saving = false; + dirty = true; + say("Not saved: the connection dropped. It tries again in a moment."); + saveTimer = setTimeout(save, 3000); + }); + } + + function startEditing() { + post("take").then(function (j) { + if (!j.ok) return; + editing = true; + lastSave = Date.now(); + say(""); + panels(); + ed.focus(); + }); + } + + function stopEditing() { + editing = false; + dirty = false; + clearTimeout(saveTimer); + panels(); + } + + function done() { + save().then(function () { + // not editing any more before the answer comes, which shows nobody + // editing + stopEditing(); + post("release"); + }); + } + + function act(action, fields) { + var go = function () { + return post(action, fields).then(function (j) { + if (j.ok) say(""); + }); + }; + if (editing && dirty) save().then(go); + else go(); + } + + function settle(action, n) { + act(action, { n: String(n) }); + } + + // ---- events + ed.addEventListener("beforeinput", function (ev) { + if (!editing) return ev.preventDefault(); + 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 (editing && !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(); + if (editing) undo(); + } + }); + document.addEventListener("selectionchange", function () { + var r = current(); + if (r) lastSel = r; + }); + root.addEventListener("click", function (ev) { + var b = ev.target.closest && ev.target.closest("[data-rv]"); + if (!b || !editing) 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(); + }); + $("dr-edit").addEventListener("click", startEditing); + $("dr-done").addEventListener("click", done); + $("dr-agree").addEventListener("click", function () { + var nameBox = $("dr-name"); + var name = nameBox ? nameBox.value.trim() : "staff"; + if (!name) { + nameBox.focus(); + return say("Write your name: it goes with your agreement."); + } + try { + if (nameBox) localStorage.setItem("draft-name", name); + } catch (e) { + /* storage blocked */ + } + if (!window.confirm("Agree to the text as it stands now? When every side has agreed, it locks.")) return; + act("agree", { name: name }); + }); + if ($("dr-name")) { + try { + $("dr-name").value = localStorage.getItem("draft-name") || ""; + } catch (e) { + /* storage blocked */ + } + } + window.addEventListener("pagehide", function () { + if (!editing) return; + var body = new URLSearchParams(); + body.set("csrf", csrf); + if (dirty) { + body.set("rev", String(rev)); + body.set("pieces", JSON.stringify(pieces.map(function (p) { + return [p.k, p.t, p.c, p.s]; + }))); + navigator.sendBeacon(base + "/save", body); + } + var rel = new URLSearchParams(); + rel.set("csrf", csrf); + navigator.sendBeacon(base + "/release", rel); + }); + window.addEventListener("beforeunload", function (ev) { + if (dirty || saving) { + ev.preventDefault(); + ev.returnValue = ""; + } + }); + + // news every 3 seconds; while editing, a sign of life keeps the draft + setInterval(function () { + if (editing) { + if (!dirty && !saving && Date.now() - lastSave > 20000) { + lastSave = Date.now(); + post("take"); + } + } else { + poll(); + } + }, 3000); + document.addEventListener("visibilitychange", function () { + if (!document.hidden && !editing) poll(); + }); + + take(state, true); +})(); diff --git a/static/review-editor.js b/static/review-editor.js deleted file mode 100644 index 8d6dfe7..0000000 --- a/static/review-editor.js +++ /dev/null @@ -1,452 +0,0 @@ -// 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/_draft_editor.html b/templates/_draft_editor.html new file mode 100644 index 0000000..b88e6cf --- /dev/null +++ b/templates/_draft_editor.html @@ -0,0 +1,40 @@ +{#- The shared draft's editor, on our page and on a party's link; the + script draws it from the data and keeps it up to date. -#} +
+
+ Loading the draft… + + + + +
+ +
+
+
+

+
    +
    + +
    + + +
    + diff --git a/templates/_review_marks.html b/templates/_review_marks.html deleted file mode 100644 index b9afa3a..0000000 --- a/templates/_review_marks.html +++ /dev/null @@ -1,5 +0,0 @@ -{#- 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/base.html b/templates/base.html index c17c7d4..a90fa67 100644 --- a/templates/base.html +++ b/templates/base.html @@ -17,7 +17,10 @@ {% include "_mark.html" %} Lanna DeskBack office - + + + +