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.
This commit is contained in:
1 parent
a4155548b8
commit
3dd9ab60e8
36 files changed
+3790
-2139
No files matched your search
+64
-33
@@ -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/<token>`, 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
|
||||
|
||||
|
||||
Binary file not shown.
@@ -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:<login>" or "party:<id>", 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:<id>"
|
||||
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'
|
||||
)
|
||||
);
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+628
@@ -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<String>,
|
||||
pub editor_name: Option<String>,
|
||||
pub editor_until: Option<DateTime<Utc>>,
|
||||
pub opened_by: String,
|
||||
pub opened_at: DateTime<Utc>,
|
||||
pub changed_at: DateTime<Utc>,
|
||||
pub locked_at: Option<DateTime<Utc>>,
|
||||
pub locked_version_id: Option<i64>,
|
||||
}
|
||||
|
||||
impl Draft {
|
||||
pub fn pieces(&self) -> Vec<Piece> {
|
||||
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:<login>` or
|
||||
/// `party:<id>`) 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<T> = Result<std::result::Result<T, Refused>>;
|
||||
|
||||
pub async fn get(db: &PgPool, contract: i64) -> Result<Option<Draft>> {
|
||||
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<Option<Draft>> {
|
||||
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<Draft> {
|
||||
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<Draft> = 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<Draft> {
|
||||
let d: Option<Draft> = 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<Draft> = 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<std::result::Result<Draft, Refused>> {
|
||||
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<i32> {
|
||||
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<i32> {
|
||||
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::<String>())
|
||||
} 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<String> {
|
||||
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<i32> {
|
||||
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<i32> {
|
||||
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<Vec<String>> {
|
||||
let parties: Vec<i64> = 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<Utc>,
|
||||
}
|
||||
|
||||
/// The agreements given at a revision.
|
||||
pub async fn agreements(
|
||||
db: impl sqlx::PgExecutor<'_>,
|
||||
contract: i64,
|
||||
revision: i32,
|
||||
) -> Result<Vec<Agreement>> {
|
||||
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<Agreed> {
|
||||
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<String> = have.iter().map(|a| a.actor.clone()).collect::<Vec<_>>();
|
||||
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)))
|
||||
}
|
||||
+12
-5
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+128
@@ -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<Utc>,
|
||||
pub contract_id: Option<i64>,
|
||||
pub kind: String,
|
||||
pub actor: String,
|
||||
pub by_login: String,
|
||||
pub text: String,
|
||||
pub href: String,
|
||||
}
|
||||
|
||||
pub struct New<'a> {
|
||||
pub contract: Option<i64>,
|
||||
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<i64> {
|
||||
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<i64> {
|
||||
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<Vec<(i64, i64)>> {
|
||||
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<Vec<Notice>> {
|
||||
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(())
|
||||
}
|
||||
+53
-39
@@ -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<Value = (String, Vec<reviews::Piece>)> {
|
||||
/// 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<Value = (String, Vec<reviews::Piece>, 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 {
|
||||
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: reviews::Op::Ins,
|
||||
text: typed.replace('\r', ""),
|
||||
comment: 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<usize> =
|
||||
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());
|
||||
}
|
||||
}
|
||||
+295
-521
File diff suppressed because it is too large.
Load diff
+77
-46
@@ -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::<Vec<_>>()
|
||||
.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?;
|
||||
|
||||
@@ -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/<token>`; 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<serde_json::Value> {
|
||||
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<Vec<(String, String)>> {
|
||||
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<i32>,
|
||||
) -> anyhow::Result<serde_json::Value> {
|
||||
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<i32> = 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<T: std::str::FromStr>(f: &Fields, k: &str) -> Option<T> {
|
||||
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::<usize>(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::<usize>(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::<String>();
|
||||
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<i32> = 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<i32>,
|
||||
}
|
||||
|
||||
/// 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<Option<Ctx>> {
|
||||
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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, what)): Path<(i64, String)>,
|
||||
Query(q): Query<StateQuery>,
|
||||
) -> 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<serde_json::Value> = 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, action)): Path<(i64, String)>,
|
||||
headers: HeaderMap,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let Some(head) = legal::head(&st.db, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, lid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let (Some(head), Some(link)) = (
|
||||
legal::head(&st.db, id).await?,
|
||||
reviews::link(&st.db, id, lid).await?,
|
||||
) else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let 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<String>,
|
||||
changes: usize,
|
||||
highlights: usize,
|
||||
have: usize,
|
||||
need: usize,
|
||||
locked_version: Option<i32>,
|
||||
parties: Vec<PartyLink>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PartyLink {
|
||||
id: i64,
|
||||
name: String,
|
||||
link: Option<i64>,
|
||||
link_state: String,
|
||||
}
|
||||
|
||||
pub async fn card(st: &AppState, contract: i64) -> anyhow::Result<Card> {
|
||||
let links = reviews::for_contract(&st.db, contract).await?;
|
||||
let parties: Vec<PartyLink> = 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<Result<(Ctx, Link), Response>> {
|
||||
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<Arc<AppState>>, Path(token): Path<String>) -> 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<Arc<AppState>>,
|
||||
Path((token, what)): Path<(String, String)>,
|
||||
Query(q): Query<StateQuery>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Path((token, action)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
) -> 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<Row> = 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
) -> 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<HashMap<i64, i64>> {
|
||||
Ok(notices::unread_by_contract(&st.db, login)
|
||||
.await?
|
||||
.into_iter()
|
||||
.collect())
|
||||
}
|
||||
+2
-25
@@ -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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
|
||||
+34
-11
@@ -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<AppState>) -> Router {
|
||||
// The other side's review page: open without a login, it checks its
|
||||
// link. The marked-up text of a long Thai contract urlencodes to a few
|
||||
// megabytes.
|
||||
r = r.route(
|
||||
"/r/{token}",
|
||||
get(reviews::party_show)
|
||||
.post(reviews::party_reply)
|
||||
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<AppState>) -> Router {
|
||||
post(l::remove_party),
|
||||
)
|
||||
.route("/conflicts", get(l::conflicts_page))
|
||||
.route("/contracts/{id}/reviews", post(reviews::send))
|
||||
.route("/contracts/{id}/reviews/{rid}", get(reviews::show))
|
||||
.route("/contracts/{id}/reviews/{rid}/take", post(reviews::take))
|
||||
.route("/contracts/{id}/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<Arc<AppState>>, 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<Arc<AppState>>, 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!(
|
||||
|
||||
@@ -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/<token>`, the marking
|
||||
//! editor and its Send back. Their POST carries the link's own form token,
|
||||
//! as the client link's do.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use axum::{Extension, Form};
|
||||
use minijinja::context;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{AppState, Res, message, not_found_page, page, render};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::forms::{self, Errors, Fields, err};
|
||||
use crate::legal::{self, Head, Version};
|
||||
use crate::reviews::{self, Link, Piece, Round};
|
||||
use crate::session::{self, User};
|
||||
use crate::{dates, embedded};
|
||||
|
||||
fn audit_entry<'a>(actor: &'a str, action: Action, id: i64, fields: &'a [String]) -> Entry<'a> {
|
||||
Entry {
|
||||
actor,
|
||||
action,
|
||||
entity: Entity::Review,
|
||||
entity_id: Some(id),
|
||||
person_id: None,
|
||||
company_id: None,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
/// A round as the contract page and the other side's page list it.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RoundView {
|
||||
id: i64,
|
||||
version: i32,
|
||||
sent: String,
|
||||
by: String,
|
||||
message: String,
|
||||
replied: Option<String>,
|
||||
reply_name: String,
|
||||
changes: usize,
|
||||
highlights: usize,
|
||||
}
|
||||
|
||||
fn round_view(r: &Round, versions: &[Version]) -> RoundView {
|
||||
let pieces = r.pieces();
|
||||
RoundView {
|
||||
id: r.id,
|
||||
version: versions
|
||||
.iter()
|
||||
.find(|v| v.id == r.version_id)
|
||||
.map_or(0, |v| v.version),
|
||||
sent: dates::fmt_datetime(r.sent_at),
|
||||
by: r.sent_by.clone(),
|
||||
message: r.message.clone(),
|
||||
replied: r.replied_at.map(dates::fmt_datetime),
|
||||
reply_name: r.reply_name.clone().unwrap_or_default(),
|
||||
changes: reviews::changes(&pieces).len(),
|
||||
highlights: reviews::highlights(&pieces).len(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct LinkView {
|
||||
id: i64,
|
||||
party: String,
|
||||
open: bool,
|
||||
state: String,
|
||||
rounds: Vec<RoundView>,
|
||||
}
|
||||
|
||||
/// The card on the contract page: the links with their rounds, and what a
|
||||
/// version can be sent to.
|
||||
pub async fn card(st: &AppState, contract: i64) -> anyhow::Result<Vec<LinkView>> {
|
||||
let versions = legal::versions(&st.db, contract).await?;
|
||||
Ok(reviews::for_contract(&st.db, contract)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let state = match (l.link.closed_at, l.link.open()) {
|
||||
(Some(at), _) => format!("closed {}", dates::fmt_datetime(at)),
|
||||
(None, false) => "expired".to_string(),
|
||||
(None, true) => match l.link.last_used_at {
|
||||
Some(at) => format!("last opened {}", dates::fmt_datetime(at)),
|
||||
None => "not opened yet".to_string(),
|
||||
},
|
||||
};
|
||||
LinkView {
|
||||
id: l.link.id,
|
||||
open: l.link.open(),
|
||||
state,
|
||||
rounds: l.rounds.iter().map(|r| round_view(r, &versions)).collect(),
|
||||
party: l.party,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Sends a version to a party: a new round on their open link, or a new
|
||||
/// link shown once.
|
||||
pub async fn send(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let Some(head) = legal::head(&st.db, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let g = |k: &str| forms::get(&f, k).trim().to_string();
|
||||
let party = legal::parties(&st.db, id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|p| p.removed_at.is_none() && g("review_party") == p.id.to_string());
|
||||
let versions = legal::versions(&st.db, id).await?;
|
||||
let version = versions
|
||||
.iter()
|
||||
.find(|v| !v.body.is_empty() && g("review_version") == v.version.to_string());
|
||||
let back = format!("/contracts/{id}#reviews");
|
||||
let (Some(party), Some(version)) = (party, version) else {
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"Choose the party and the version",
|
||||
"Send a version with a text to one of the contract's parties.",
|
||||
(&back, "Back to the contract"),
|
||||
));
|
||||
};
|
||||
let note = g("review_message");
|
||||
if note.chars().count() > 2000 {
|
||||
return Ok(message(
|
||||
&st,
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"The message is too long",
|
||||
"Write at most 2,000 characters to go with the version.",
|
||||
(&back, "Back to the contract"),
|
||||
));
|
||||
}
|
||||
let mut tx = st.db.begin().await?;
|
||||
let (link, token, round) = reviews::send(
|
||||
&mut tx,
|
||||
&reviews::Send {
|
||||
contract: &head,
|
||||
party: party.id,
|
||||
party_name: &party.name,
|
||||
version,
|
||||
message: ¬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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, lid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let (Some(head), Some(link)) = (
|
||||
legal::head(&st.db, id).await?,
|
||||
reviews::link(&st.db, id, lid).await?,
|
||||
) else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let party = party_name(&st, link.party_id).await?;
|
||||
let mut tx = st.db.begin().await?;
|
||||
if reviews::close(&mut tx, &head, &link, &party, &user.login).await? {
|
||||
let fields = ["closed".to_string()];
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&audit_entry(&user.login, Action::Close, link.id, &fields),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Redirect::to(&format!("/contracts/{id}#reviews")).into_response())
|
||||
}
|
||||
|
||||
async fn party_name(st: &AppState, party: i64) -> anyhow::Result<String> {
|
||||
Ok(
|
||||
sqlx::query_scalar("SELECT name FROM contract_parties WHERE id = $1")
|
||||
.bind(party)
|
||||
.fetch_one(&st.db)
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
|
||||
/// A round of this contract with its link, version and party.
|
||||
async fn round_of(
|
||||
st: &AppState,
|
||||
contract: i64,
|
||||
rid: i64,
|
||||
) -> anyhow::Result<Option<(Head, Link, Round, Version, String)>> {
|
||||
let Some(head) = legal::head(&st.db, contract).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(round) = reviews::round(&st.db, rid).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(link) = reviews::link(&st.db, contract, round.link_id).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(version) = legal::versions(&st.db, contract)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|v| v.id == round.version_id)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let party = party_name(st, link.party_id).await?;
|
||||
Ok(Some((head, link, round, version, party)))
|
||||
}
|
||||
|
||||
/// What came back: their markup, the git view and the changes to take.
|
||||
pub async fn show(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>,
|
||||
) -> Res {
|
||||
let Some((head, _link, round, version, party)) = round_of(&st, id, rid).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let pieces = round.pieces();
|
||||
audit::record(
|
||||
&st.db,
|
||||
&audit_entry(&user.login, Action::View, round.id, &[]),
|
||||
)
|
||||
.await?;
|
||||
let replied = round.replied_at.is_some();
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
"review.html",
|
||||
&format!("{} review by {party}", head.code),
|
||||
"contracts",
|
||||
StatusCode::OK,
|
||||
context! {
|
||||
id, head, party, replied,
|
||||
review_version => version.version,
|
||||
round => round_view(&round, std::slice::from_ref(&version)),
|
||||
reply_message => round.reply_message.clone().unwrap_or_default(),
|
||||
reply_sha => round.reply_sha256.clone().unwrap_or_default(),
|
||||
shown => reviews::shown(&pieces),
|
||||
git => reviews::git_view(&pieces),
|
||||
changes => reviews::changes(&pieces),
|
||||
highlights => reviews::highlights(&pieces),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// The ticked changes into the version form of the contract page.
|
||||
pub async fn take(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, rid)): Path<(i64, i64)>,
|
||||
// pairs, since every ticked box is one more `take`
|
||||
Form(f): Form<Vec<(String, String)>>,
|
||||
) -> Res {
|
||||
let Some((_head, _link, round, version, party)) = round_of(&st, id, rid).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let pieces = round.pieces();
|
||||
let taken: BTreeSet<usize> = f
|
||||
.iter()
|
||||
.filter(|(k, _)| *k == "take")
|
||||
.filter_map(|(_, v)| v.parse().ok())
|
||||
.collect();
|
||||
let all = reviews::changes(&pieces).len();
|
||||
let body = reviews::apply(&pieces, &taken);
|
||||
let day = round
|
||||
.replied_at
|
||||
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
|
||||
.unwrap_or_default();
|
||||
let note = match taken.len() {
|
||||
0 => format!(
|
||||
"Version {} again, after {party}'s review of {day}",
|
||||
version.version
|
||||
),
|
||||
n if n == all => format!("{party}'s changes of {day} to version {}", version.version),
|
||||
n => format!(
|
||||
"{n} of {all} changes by {party} of {day} to version {}",
|
||||
version.version
|
||||
),
|
||||
};
|
||||
super::legal::contract_with_draft(&st, &user, id, note, body).await
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- the other side
|
||||
|
||||
fn closed(st: &AppState, title: &str, text: &str, status: StatusCode) -> Response {
|
||||
render(
|
||||
st,
|
||||
"client_closed.html",
|
||||
context! { title, text, v => embedded::STATIC_HASH },
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
/// The link, if it still works; else the page that says why not.
|
||||
async fn open_link(st: &AppState, token: &str) -> anyhow::Result<Result<Link, Response>> {
|
||||
let link = reviews::by_token(&st.db, token).await?;
|
||||
Ok(match link {
|
||||
None => Err(closed(
|
||||
st,
|
||||
"This link does not work",
|
||||
"There is no review link at this address. Check that you opened the whole link, or \
|
||||
ask Lanna Desk for a new one.",
|
||||
StatusCode::NOT_FOUND,
|
||||
)),
|
||||
Some(l) if !l.open() => Err(closed(
|
||||
st,
|
||||
"This link is closed",
|
||||
"The review on this link has ended. Ask Lanna Desk for a new link if there is more to \
|
||||
discuss.",
|
||||
StatusCode::GONE,
|
||||
)),
|
||||
Some(l) => Ok(l),
|
||||
})
|
||||
}
|
||||
|
||||
/// What the other side's page shows, after a GET or a refused POST.
|
||||
struct Editing {
|
||||
pieces: Vec<Piece>,
|
||||
name: String,
|
||||
message: String,
|
||||
errors: Errors,
|
||||
status: StatusCode,
|
||||
}
|
||||
|
||||
async fn party_page(st: &AppState, link: &Link, token: &str, e: Editing) -> Res {
|
||||
let Some(head) = legal::head(&st.db, link.contract_id).await? else {
|
||||
return Ok(not_found_page(st));
|
||||
};
|
||||
let versions = legal::versions(&st.db, link.contract_id).await?;
|
||||
let rounds = reviews::rounds(&st.db, link.id).await?;
|
||||
let Some(latest) = rounds.first() else {
|
||||
return Ok(not_found_page(st));
|
||||
};
|
||||
let Some(version) = versions.iter().find(|v| v.id == latest.version_id) else {
|
||||
return Ok(not_found_page(st));
|
||||
};
|
||||
let party = party_name(st, link.party_id).await?;
|
||||
let client: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1")
|
||||
.bind(head.client_id)
|
||||
.fetch_one(&st.db)
|
||||
.await?;
|
||||
let pieces = if latest.replied_at.is_some() {
|
||||
latest.pieces()
|
||||
} else if e.pieces.is_empty() {
|
||||
reviews::unmarked(&version.body)
|
||||
} else {
|
||||
e.pieces
|
||||
};
|
||||
let earlier: Vec<RoundView> = rounds
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|r| round_view(r, &versions))
|
||||
.collect();
|
||||
Ok(render(
|
||||
st,
|
||||
"party_review.html",
|
||||
context! {
|
||||
title => format!("{} {}", head.code, head.title),
|
||||
v => embedded::STATIC_HASH,
|
||||
demo => st.cfg.demo(),
|
||||
head, party, client, earlier,
|
||||
action => format!("/r/{token}"),
|
||||
csrf => link.csrf.clone(),
|
||||
round => round_view(latest, &versions),
|
||||
round_id => latest.id,
|
||||
replied => latest.replied_at.is_some(),
|
||||
shown => reviews::shown(&pieces),
|
||||
pieces => reviews::script_json(&pieces),
|
||||
name => e.name,
|
||||
reply_message => e.message,
|
||||
errors => e.errors,
|
||||
link_until => dates::fmt_date(link.expires_at.with_timezone(&dates::bangkok()).date_naive()),
|
||||
},
|
||||
e.status,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn party_show(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
|
||||
let link = match open_link(&st, &token).await? {
|
||||
Ok(l) => l,
|
||||
Err(page) => return Ok(page),
|
||||
};
|
||||
reviews::used(&st.db, link.id).await?;
|
||||
let actor = format!("review {}", link.id);
|
||||
audit::record(&st.db, &audit_entry(&actor, Action::View, link.id, &[])).await?;
|
||||
party_page(
|
||||
&st,
|
||||
&link,
|
||||
&token,
|
||||
Editing {
|
||||
pieces: Vec::new(),
|
||||
name: String::new(),
|
||||
message: String::new(),
|
||||
errors: Errors::new(),
|
||||
status: StatusCode::OK,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The other side sends their marked-up text back.
|
||||
pub async fn party_reply(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Path(token): Path<String>,
|
||||
headers: HeaderMap,
|
||||
Form(f): Form<Fields>,
|
||||
) -> Res {
|
||||
let link = match open_link(&st, &token).await? {
|
||||
Ok(l) => l,
|
||||
Err(page) => return Ok(page),
|
||||
};
|
||||
if !session::same_token(&forms::get(&f, "csrf"), &link.csrf) {
|
||||
return Ok(closed(
|
||||
&st,
|
||||
"The page was too old",
|
||||
"Go back, reload the page and send it again.",
|
||||
StatusCode::FORBIDDEN,
|
||||
));
|
||||
}
|
||||
let rounds = reviews::rounds(&st.db, link.id).await?;
|
||||
let latest = match rounds.first() {
|
||||
Some(r) if forms::get(&f, "round") == r.id.to_string() && r.replied_at.is_none() => r,
|
||||
_ => {
|
||||
return Ok(closed(
|
||||
&st,
|
||||
"This version was answered already",
|
||||
"Lanna Desk has your reply to this version, or has sent a newer one since. \
|
||||
Reload the link to see where things stand.",
|
||||
StatusCode::CONFLICT,
|
||||
));
|
||||
}
|
||||
};
|
||||
let Some(head) = legal::head(&st.db, link.contract_id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let Some(version) = legal::versions(&st.db, link.contract_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|v| v.id == latest.version_id)
|
||||
else {
|
||||
return Ok(not_found_page(&st));
|
||||
};
|
||||
let name = forms::get(&f, "name").trim().to_string();
|
||||
let note = forms::get(&f, "message").trim().to_string();
|
||||
let mut errors = Errors::new();
|
||||
let pieces = match reviews::check(&forms::get(&f, "pieces"), &version.body) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
err(&mut errors, "pieces", e);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
if name.is_empty() {
|
||||
err(&mut errors, "name", "Say who sends this back.");
|
||||
} else if name.chars().count() > 200 {
|
||||
err(&mut errors, "name", "At most 200 characters.");
|
||||
}
|
||||
if note.chars().count() > 5000 {
|
||||
err(&mut errors, "message", "At most 5,000 characters.");
|
||||
}
|
||||
if !errors.is_empty() {
|
||||
return party_page(
|
||||
&st,
|
||||
&link,
|
||||
&token,
|
||||
Editing {
|
||||
pieces,
|
||||
name,
|
||||
message: note,
|
||||
errors,
|
||||
status: StatusCode::UNPROCESSABLE_ENTITY,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let ip = super::client::client_ip(&headers);
|
||||
let user_agent: String = headers
|
||||
.get(axum::http::header::USER_AGENT)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.take(300)
|
||||
.collect();
|
||||
let party = party_name(&st, link.party_id).await?;
|
||||
let mut tx = st.db.begin().await?;
|
||||
let done = reviews::reply(
|
||||
&mut tx,
|
||||
&head,
|
||||
&party,
|
||||
version.version,
|
||||
latest,
|
||||
&reviews::Reply {
|
||||
name: &name,
|
||||
message: ¬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())
|
||||
}
|
||||
+225
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 () {
|
||||
|
||||
@@ -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);
|
||||
})();
|
||||
@@ -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);
|
||||
})();
|
||||
@@ -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. -#}
|
||||
<div class="drwrap" id="draft-editor" data-draft>
|
||||
<div class="drbar" id="dr-bar">
|
||||
<span class="drstate" id="dr-state" aria-live="polite">Loading the draft…</span>
|
||||
<span class="drbtns">
|
||||
<button type="button" class="btn sm pri" id="dr-edit" hidden>Edit</button>
|
||||
<button type="button" class="btn sm" id="dr-done" hidden>Done editing</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="rvtools" id="dr-tools" role="toolbar" aria-label="Marking tools" aria-controls="dr-text" hidden>
|
||||
<button type="button" class="btn sm" data-rv="del" title="Cross out the selection (Delete)"><del>Cross out</del></button>
|
||||
<button type="button" class="btn sm" data-rv="mark" title="Highlight the selection"><mark>Highlight</mark></button>
|
||||
<input type="text" id="dr-comment" class="rvcomment" placeholder="Comment for the highlight" aria-label="Comment for the highlight" maxlength="500" autocomplete="off">
|
||||
<button type="button" class="btn sm ghost" data-rv="restore" title="Take your own marks back from the selection">Restore</button>
|
||||
<button type="button" class="btn sm ghost" data-rv="undo" title="Undo (Ctrl+Z)">Undo</button>
|
||||
</div>
|
||||
<div class="drcols">
|
||||
<div class="drmain">
|
||||
<div class="rvtext rvedit dr" id="dr-text" spellcheck="true" role="textbox" aria-multiline="true" aria-label="The contract text"></div>
|
||||
<p class="muted small" id="dr-note" aria-live="polite"></p>
|
||||
<ul class="drlegend" id="dr-legend" aria-label="Whose marks are which color"></ul>
|
||||
</div>
|
||||
<aside class="drside">
|
||||
<section id="dr-changes-box"><h3 class="minihead">Open changes <span class="muted" id="dr-changes-n"></span></h3><ol class="drlist" id="dr-changes"></ol></section>
|
||||
<section id="dr-marks-box"><h3 class="minihead">Highlights <span class="muted" id="dr-marks-n"></span></h3><ol class="drlist" id="dr-marks"></ol></section>
|
||||
<section id="dr-agree-box"><h3 class="minihead">Agreement</h3>
|
||||
<ul class="drsides" id="dr-sides"></ul>
|
||||
<div id="dr-agree-form">
|
||||
{% if not staff %}<label class="drname">Your name <input type="text" id="dr-name" autocomplete="name" maxlength="200"></label>{% endif %}
|
||||
<button type="button" class="btn pri" id="dr-agree">Agree to this text</button>
|
||||
<p class="muted small" id="dr-agree-note"></p>
|
||||
</div>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
<noscript><p class="notice warn">The draft needs JavaScript in the browser.</p></noscript>
|
||||
<script type="application/json" id="dr-data">{{ data|safe }}</script>
|
||||
</div>
|
||||
<script src="/static/draft-editor.js?v={{ v }}" defer></script>
|
||||
@@ -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") -%}
|
||||
<div class="rvtext" id="{{ id }}">{% for p in shown %}{% if p.n %}<sup class="rvn" aria-label="change {{ p.n }}">{{ p.n }}</sup>{% endif %}{% if p.op == "ins" %}<ins>{{ p.text }}</ins>{% elif p.op == "del" %}<del>{{ p.text }}</del>{% elif p.op == "mark" %}<mark{% if p.comment %} title="{{ p.comment }}"{% endif %}>{{ p.text }}</mark>{% if p.comment %}<span class="rvc">{{ p.comment }}</span>{% endif %}{% else %}{{ p.text }}{% endif %}{% endfor %}</div>
|
||||
{%- endmacro %}
|
||||
@@ -17,7 +17,10 @@
|
||||
{% include "_mark.html" %}
|
||||
<span class="nm">Lanna Desk</span><span class="sub">Back office</span>
|
||||
</a>
|
||||
<span class="topacts">
|
||||
<a class="ib bell" href="/notices" id="bell" aria-label="Notices" title="Notices"><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M12 22a2.5 2.5 0 0 0 2.45-2h-4.9A2.5 2.5 0 0 0 12 22Zm7-6V11a7 7 0 0 0-5.5-6.84V3.5a1.5 1.5 0 0 0-3 0v.66A7 7 0 0 0 5 11v5l-2 2v1h18v-1l-2-2Z"/></svg><span class="bellcount" id="bell-count" hidden></span></a>
|
||||
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
||||
</span>
|
||||
</header>
|
||||
<div class="app">
|
||||
<aside class="side">
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
||||
</header>
|
||||
<main class="cmain" id="main">
|
||||
{% if demo %}<p class="demo-note" id="demo-note"><b>Demo.</b> This is the page a client sees on their link, with invented details. It starts over every night; uploads are off.</p>{% endif %}
|
||||
{% if demo %}<p class="demo-note" id="demo-note"><b>Demo.</b> {{ demo_text or "This is the page a client sees on their link, with invented details." }} It starts over every night; uploads are off.</p>{% endif %}
|
||||
{% block main %}{% endblock %}
|
||||
{% if until %}<footer class="ft">This link works until {{ until }}. What you save here goes to Lanna Desk, which looks after your visa and stay in Thailand; nobody else sees it.</footer>{% endif %}
|
||||
</main>
|
||||
|
||||
+26
-28
@@ -74,37 +74,35 @@
|
||||
</details>
|
||||
<datalist id="roles">{% for r in roles %}<option value="{{ r }}"></option>{% endfor %}</datalist>
|
||||
</section>
|
||||
<section class="card" id="reviews">
|
||||
<header><h2>Review by the other side</h2><span class="muted small">a link where a party marks up a version and sends it back</span></header>
|
||||
{% for l in reviews %}
|
||||
<div class="item{% if not l.open %} old{% endif %}" id="review-link-{{ l.id }}">
|
||||
<div class="row"><b>{{ l.party }}</b><span class="muted small">{{ l.state }}</span>
|
||||
{% if l.open %}<form method="post" action="/contracts/{{ id }}/review-links/{{ l.id }}/close" class="inline-form" data-confirm="Close {{ l.party }}'s review link? It stops working; sending again makes a new one."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm ghost">Close the link</button></form>{% endif %}
|
||||
</div>
|
||||
<section class="card" id="draft">
|
||||
<header><h2>Shared draft</h2><span class="muted small">one text for every side, with tracked changes, until all agree</span></header>
|
||||
{% if draft.state == "open" %}
|
||||
<p><b>Open for edits</b>, revision {{ draft.revision }}, last change {{ draft.changed }}.{% if draft.editing %} <span class="chip warn">{{ draft.editing }} is editing</span>{% endif %}</p>
|
||||
<p>{% if draft.changes %}<span class="chip warn">{{ draft.changes }} open {% if draft.changes == 1 %}change{% else %}changes{% endif %}</span> {% endif %}{% if draft.highlights %}<span class="chip plain">{{ draft.highlights }} {% if draft.highlights == 1 %}highlight{% else %}highlights{% endif %}</span> {% endif %}<span class="chip {% if draft.have == draft.need %}ok{% else %}plain{% endif %}">{{ draft.have }} of {{ draft.need }} sides agree</span></p>
|
||||
<div class="formactions"><a class="btn pri" href="/contracts/{{ id }}/draft" id="open-draft">Open the draft</a></div>
|
||||
{% elif draft.state == "locked" %}
|
||||
<p><span class="chip ok">Locked</span> Every side agreed; the text is <a href="/contracts/{{ id }}?v={{ draft.locked_version }}#reading">version {{ draft.locked_version }}</a>, which never changes. <a href="/contracts/{{ id }}/draft">See the draft</a>.</p>
|
||||
{% endif %}
|
||||
{% if draft.state != "open" %}
|
||||
{% if text_versions %}
|
||||
<form method="post" action="/contracts/{{ id }}/draft/open" class="form inline-form" id="draft-open-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<div class="grid">{{ fm.select("draft_version", "Start a shared draft from", text_versions[0][0], text_versions, req=true, blank="Choose") }}</div>
|
||||
<div class="formactions"><button type="submit" class="btn pri" id="draft-open">{% if draft.state == "locked" %}Start a new draft{% else %}Start the shared draft{% endif %}</button></div>
|
||||
</form>
|
||||
{% else %}<p class="empty-inline">Add a version with a text to start a shared draft: the editor works on the text.</p>{% endif %}
|
||||
{% endif %}
|
||||
{% if draft.parties %}
|
||||
<h3 class="minihead">The other parties' links</h3>
|
||||
<ul class="rvrounds">
|
||||
{% for r in l.rounds %}
|
||||
<li id="round-{{ r.id }}">Version {{ r.version }} sent {{ r.sent }} by {{ r.by }}:
|
||||
{% if r.replied %}<a href="/contracts/{{ id }}/reviews/{{ r.id }}">sent back {{ r.replied }}</a>, <span class="chip {% if r.changes %}warn{% else %}ok{% endif %}">{{ r.changes }} {% if r.changes == 1 %}change{% else %}changes{% endif %}</span>{% if r.highlights %} <span class="chip plain">{{ r.highlights }} {% if r.highlights == 1 %}highlight{% else %}highlights{% endif %}</span>{% endif %}
|
||||
{% elif loop.first %}<span class="muted">waiting for them</span>{% else %}<span class="muted">not sent back; a newer version followed</span>{% endif %}</li>
|
||||
{% for p in draft.parties %}
|
||||
<li id="party-link-{{ p.id }}"><b>{{ p.name }}</b>: {{ p.link_state }}
|
||||
<form method="post" action="/contracts/{{ id }}/invites" class="inline-form"><input type="hidden" name="csrf" value="{{ csrf }}"><input type="hidden" name="party" value="{{ p.id }}"><button type="submit" class="btn sm ghost">{% if p.link %}New link{% else %}Make the link{% endif %}</button></form>
|
||||
{% if p.link %}<form method="post" action="/contracts/{{ id }}/review-links/{{ p.link }}/close" class="inline-form" data-confirm="Close {{ p.name }}'s link? It stops working at once."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm ghost">Close the link</button></form>{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% if live_parties and text_versions %}
|
||||
<details class="addparty"{% if not reviews %} open{% endif %}>
|
||||
<summary class="btn sm" id="send-review-open">Send a version for review</summary>
|
||||
<form method="post" action="/contracts/{{ id }}/reviews" class="form" id="send-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<div class="grid">
|
||||
{{ fm.select("review_party", "To", "", review_parties, req=true, blank="Choose the party") }}
|
||||
{{ fm.select("review_version", "Version", text_versions[0][0], text_versions, req=true, blank="Choose") }}
|
||||
{{ fm.area("review_message", "Message to them", "", rows=3, fcls="wide", hint="Optional: what to look at, by when.") }}
|
||||
</div>
|
||||
<div class="formactions"><button type="submit" class="btn pri" id="send-review">Send</button></div>
|
||||
</form>
|
||||
</details>
|
||||
{% elif not live_parties %}<p class="empty-inline">Add the other party above to send them a version to review.</p>
|
||||
{% else %}<p class="empty-inline">Add a version with a text to send it for review: the editor works on the text.</p>{% endif %}
|
||||
{% elif not live_parties %}<p class="empty-inline">Add the other parties above: each gets a link to the draft, and each must agree before it locks.</p>{% endif %}
|
||||
</section>
|
||||
{% if reading %}
|
||||
<section class="card" id="reading">
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/contracts">Contracts</a> <span class="sep">/</span> <a href="/contracts/{{ id }}#draft">{{ head.code }}</a></div>
|
||||
<div class="pagehead">
|
||||
<div><div class="ccode mono">{{ head.code }}</div><h1>{{ head.title }}</h1></div>
|
||||
<div class="actions"><a class="btn sm" href="/contracts/{{ id }}/draft/diff" id="draft-diff">As a diff</a></div>
|
||||
</div>
|
||||
<p class="meta">The shared draft for {{ client }}. Every side edits the same text; changes stay marked in their author's color until the other side accepts or rejects them. When no change is open and every side agrees, the text locks as a contract version.</p>
|
||||
</div>
|
||||
{% include "_draft_editor.html" %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,19 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/contracts">Contracts</a> <span class="sep">/</span> <a href="/contracts/{{ id }}#draft">{{ head.code }}</a> <span class="sep">/</span> <a href="/contracts/{{ id }}/draft">Shared draft</a></div>
|
||||
<div class="pagehead"><h1>The draft as a diff</h1></div>
|
||||
<p class="meta">The text as it stands against the text with every open change taken, at revision {{ rev }}.</p>
|
||||
</div>
|
||||
{% if changes %}
|
||||
<section class="card" id="changes">
|
||||
<header><h2>Open changes</h2></header>
|
||||
<ol class="rvchanges">{% for c in changes %}<li id="change-{{ c.n }}"><span class="rvn">{{ c.n }}</span> <span class="muted">{{ c.who }}:</span> {% if c.removed %}<del>{{ c.removed }}</del>{% endif %}{% if c.added %}<ins>{{ c.added }}</ins>{% endif %}</li>{% endfor %}</ol>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="card" id="diff">
|
||||
{% if git %}
|
||||
<div class="gitdiff">{% for l in git %}{% if l.op == "hunk" %}<div class="gl hunk"><span class="gn"></span><span class="gn"></span><span class="gt">@@ line {{ l.old or l.new }} @@</span></div>{% else %}<div class="gl {{ l.op }}"><span class="gn">{{ l.old or "" }}</span><span class="gn">{{ l.new or "" }}</span><span class="gt"><span class="gs" aria-hidden="true">{% if l.op == "removed" %}-{% elif l.op == "added" %}+{% else %} {% endif %}</span>{% for s in l.segs %}{% if s.hl %}<b>{{ s.text }}</b>{% else %}{{ s.text }}{% endif %}{% endfor %}</span></div>{% endif %}{% else %}<p class="empty-inline">No open change: the text stands as it is.</p>{% endfor %}</div>
|
||||
{% else %}<p class="empty-inline">The text is too long to compare here.</p>{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,17 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/contracts">Contracts</a> <span class="sep">/</span> <a href="/contracts/{{ id }}#draft">{{ head.code }}</a></div>
|
||||
<div class="pagehead"><h1>The link for {{ party }}</h1></div>
|
||||
</div>
|
||||
<section class="card linkcard" id="invite-made">
|
||||
<p>Give this link to {{ party }}: by email or chat, or let them scan the code. On it they see the shared draft, edit it with tracked changes, and agree to it. It works until {{ until }}, and longer while they use it.</p>
|
||||
<div class="linkrow">
|
||||
<input type="text" readonly value="{{ url }}" id="link-url" aria-label="The link" data-select-all>
|
||||
<button type="button" class="btn" data-copy="#link-url">Copy</button>
|
||||
</div>
|
||||
<div class="qr" aria-label="The link as a QR code">{{ qr|safe }}</div>
|
||||
<p class="notice warn">The link is shown only now: the app keeps only a fingerprint of it. Copy it before you leave this page; otherwise make a new one, which closes this one.</p>
|
||||
<div class="formactions"><a class="btn pri" href="/contracts/{{ id }}#draft">Done</a></div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,16 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="pagehead"><h1>Notices</h1></div>
|
||||
<p class="meta">What the other sides did on the shared drafts, and what colleagues did that you should know. The bell counts what you have not seen yet; this page marks it seen.</p>
|
||||
{% if rows %}
|
||||
<div class="card flush">
|
||||
<ul class="notices" id="notice-list">
|
||||
{% for n in rows %}
|
||||
<li class="{% if n.new %}new{% endif %} k-{{ n.kind }}"><a href="{{ n.href }}">{{ n.text }}</a><span class="muted small">{{ n.at }}</span>{% if n.new %} <span class="chip warn">new</span>{% endif %}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="card"><p class="empty-inline">Nothing yet. When another party edits or agrees to a shared draft, it shows here and on the bell.</p></div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,12 @@
|
||||
{% extends "client_base.html" %}
|
||||
{% block main %}
|
||||
<section class="card" id="draft-head">
|
||||
<div class="ccode mono">{{ head.code }}</div>
|
||||
<h1>{{ head.title }}</h1>
|
||||
<p>The draft Lanna Desk shares with {{ me }}, for {{ client }}. Press Edit to change it: what you delete stays crossed out and what you type is marked, in your color, until the other side accepts or rejects it. Highlight a passage to discuss it. When no change is open and every side agrees, the text is locked and becomes the contract to sign.</p>
|
||||
</section>
|
||||
<section class="card">
|
||||
{% include "_draft_editor.html" %}
|
||||
</section>
|
||||
<footer class="ft">Only Lanna Desk's team, who act for {{ client }}, and the other parties to this contract see this draft.</footer>
|
||||
{% endblock %}
|
||||
@@ -1,57 +0,0 @@
|
||||
{% extends "client_base.html" %}
|
||||
{% import "_review_marks.html" as rm %}
|
||||
{% import "_fields.html" as fm %}
|
||||
{% block main %}
|
||||
<section class="card" id="review-head">
|
||||
<div class="ccode mono">{{ head.code }}</div>
|
||||
<h1>{{ head.title }}</h1>
|
||||
<p>Version {{ round.version }}, sent by Lanna Desk for {{ client }} to {{ party }} on {{ round.sent }}.</p>
|
||||
{% if round.message %}<p class="pre rvmsg">{{ round.message }}</p>{% endif %}
|
||||
</section>
|
||||
{% if replied %}
|
||||
<section class="card" id="sent-back">
|
||||
<h2>Thank you</h2>
|
||||
<p>You sent this version back on {{ round.replied }} with {{ round.changes }} {% if round.changes == 1 %}change{% else %}changes{% endif %} and {{ round.highlights }} {% if round.highlights == 1 %}highlight{% else %}highlights{% endif %}. Lanna Desk reads it and answers here with the next version. This is what you sent:</p>
|
||||
{{ rm.marked(shown) }}
|
||||
</section>
|
||||
{% else %}
|
||||
<form method="post" action="{{ action }}" class="form" id="review-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<input type="hidden" name="round" value="{{ round_id }}">
|
||||
<input type="hidden" name="pieces" id="rv-pieces" value="">
|
||||
<section class="card" id="editor-card">
|
||||
<header><h2>Your changes</h2><span class="muted small" id="rv-count" aria-live="polite"></span></header>
|
||||
<p class="hint">Edit the text as you would any text. What you delete stays in place, crossed out; what you type is marked as added; so Lanna Desk sees every change. To mark a passage for discussion, select it and press Highlight, with a comment if you like. Restore takes your marks back from what you select.</p>
|
||||
{% if errors.pieces %}<div class="notice warn">{{ errors.pieces }}</div>{% endif %}
|
||||
<div class="rvtools" role="toolbar" aria-label="Marking tools" aria-controls="rv-editor">
|
||||
<button type="button" class="btn sm" data-rv="del" title="Cross out the selection (Delete)"><del>Cross out</del></button>
|
||||
<button type="button" class="btn sm" data-rv="mark" title="Highlight the selection"><mark>Highlight</mark></button>
|
||||
<input type="text" id="rv-comment" class="rvcomment" placeholder="Comment for the highlight" aria-label="Comment for the highlight" maxlength="500" autocomplete="off">
|
||||
<button type="button" class="btn sm ghost" data-rv="restore" title="Take your marks back from the selection">Restore</button>
|
||||
<button type="button" class="btn sm ghost" data-rv="undo" title="Undo (Ctrl+Z)">Undo</button>
|
||||
</div>
|
||||
<div class="rvtext rvedit" id="rv-editor" contenteditable="true" spellcheck="true" role="textbox" aria-multiline="true" aria-label="The contract text, to mark up" data-rv-editor></div>
|
||||
<p class="muted small" id="rv-note" aria-live="polite"></p>
|
||||
<noscript><p class="notice warn">The editor needs JavaScript. Without it, write your changes in the message below.</p></noscript>
|
||||
<script type="application/json" id="rv-data">{{ pieces|safe }}</script>
|
||||
</section>
|
||||
<section class="card" id="send-back">
|
||||
<header><h2>Send it back</h2></header>
|
||||
<div class="grid">
|
||||
{{ fm.text("name", "Your name", name, err=errors.name, req=true, auto="name", hint="Who at " ~ party ~ " sends this.") }}
|
||||
{{ fm.area("message", "Message to Lanna Desk", reply_message, err=errors.message, rows=4, fcls="wide", hint="Optional: what your changes are about.") }}
|
||||
</div>
|
||||
<div class="formactions"><button type="submit" class="btn pri" id="send-review">Send it back</button></div>
|
||||
<p class="muted small">You can send this version back once. Lanna Desk then answers with its next version on this same link.</p>
|
||||
</section>
|
||||
</form>
|
||||
<script src="/static/review-editor.js?v={{ v }}" defer></script>
|
||||
{% endif %}
|
||||
{% if earlier %}
|
||||
<section class="card" id="earlier">
|
||||
<header><h2>Earlier versions</h2></header>
|
||||
<ul class="rvrounds">{% for r in earlier %}<li>Version {{ r.version }}, sent {{ r.sent }}{% if r.replied %}; you sent it back {{ r.replied }} with {{ r.changes }} {% if r.changes == 1 %}change{% else %}changes{% endif %}{% else %}; not sent back{% endif %}</li>{% endfor %}</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
<footer class="ft">This link works until {{ link_until }}. Only Lanna Desk's team, who act for {{ client }}, see what you send here.</footer>
|
||||
{% endblock %}
|
||||
@@ -1,53 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_review_marks.html" as rm %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/contracts">Contracts</a> <span class="sep">/</span> <a href="/contracts/{{ id }}#reviews">{{ head.code }}</a></div>
|
||||
<div class="pagehead"><h1>{{ party }}'s review of version {{ review_version }}</h1></div>
|
||||
<p class="meta">Sent {{ round.sent }} by {{ round.by }}.{% if replied %} Sent back {{ round.replied }} by {{ round.reply_name }}: {{ round.changes }} {% if round.changes == 1 %}change{% else %}changes{% endif %}, {{ round.highlights }} {% if round.highlights == 1 %}highlight{% else %}highlights{% endif %}.{% endif %}</p>
|
||||
</div>
|
||||
{% if not replied %}
|
||||
<section class="card"><h2>Nothing back yet</h2><p>{{ party }} has not sent this version back yet.</p></section>
|
||||
{% else %}
|
||||
{% if reply_message %}
|
||||
<section class="card" id="reply-message">
|
||||
<header><h2>Their message</h2></header>
|
||||
<p class="pre">{{ reply_message }}</p>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="card" id="take">
|
||||
<header><h2>The changes</h2></header>
|
||||
{% if changes %}
|
||||
<form method="post" action="/contracts/{{ id }}/reviews/{{ round.id }}/take" id="take-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<p class="hint">Tick the changes to take. The contract page then opens with the version form filled with version {{ review_version }} and those changes, to finish and add as the next version.</p>
|
||||
<ol class="rvchanges">
|
||||
{% for c in changes %}
|
||||
<li id="change-{{ c.n }}"><label class="check"><input type="checkbox" name="take" value="{{ c.n }}" checked><span class="rvn">{{ c.n }}</span><span class="rvchange"><span class="muted">{{ c.before }}</span>{% if c.removed %}<del>{{ c.removed }}</del>{% endif %}{% if c.added %}<ins>{{ c.added }}</ins>{% endif %}<span class="muted">{{ c.after }}</span></span></label></li>
|
||||
{% endfor %}
|
||||
</ol>
|
||||
<div class="formactions"><button type="submit" class="btn pri" id="take-changes">Take the ticked changes</button></div>
|
||||
</form>
|
||||
{% else %}
|
||||
<p class="empty-inline">They changed nothing{% if highlights %}; they highlighted what is listed below{% endif %}.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% if highlights %}
|
||||
<section class="card" id="highlights">
|
||||
<header><h2>Highlighted</h2></header>
|
||||
<ul class="rvhl">{% for h in highlights %}<li><mark>{{ h.text }}</mark>{% if h.comment %}<div class="sub">{{ h.comment }}</div>{% endif %}</li>{% endfor %}</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
<section class="card" id="diff">
|
||||
<header><h2>As a diff</h2><span class="muted small">our version {{ review_version }} against their text</span></header>
|
||||
{% if git %}
|
||||
<div class="gitdiff">{% for l in git %}{% if l.op == "hunk" %}<div class="gl hunk"><span class="gn"></span><span class="gn"></span><span class="gt">@@ line {{ l.old or l.new }} @@</span></div>{% else %}<div class="gl {{ l.op }}"><span class="gn">{{ l.old or "" }}</span><span class="gn">{{ l.new or "" }}</span><span class="gt"><span class="gs" aria-hidden="true">{% if l.op == "removed" %}-{% elif l.op == "added" %}+{% else %} {% endif %}</span>{% for s in l.segs %}{% if s.hl %}<b>{{ s.text }}</b>{% else %}{{ s.text }}{% endif %}{% endfor %}</span></div>{% endif %}{% else %}<p class="empty-inline">No line changed.</p>{% endfor %}</div>
|
||||
{% else %}<p class="empty-inline">The texts are too long to compare here.</p>{% endif %}
|
||||
</section>
|
||||
<section class="card" id="markup">
|
||||
<header><h2>As they marked it</h2></header>
|
||||
{{ rm.marked(shown) }}
|
||||
<p class="muted small mono hashline">Their text, SHA-256 {{ reply_sha }}</p>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -1,23 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/contracts">Contracts</a> <span class="sep">/</span> <a href="/contracts/{{ id }}">{{ head.code }}</a></div>
|
||||
<div class="pagehead"><h1>Sent for review</h1></div>
|
||||
</div>
|
||||
<section class="card linkcard" id="review-made">
|
||||
{% if url %}
|
||||
<header><h2>The link for {{ party }}</h2></header>
|
||||
<p>Give this link to {{ party }}: by email or chat, or let them scan the code. On it they read version {{ review_version }}, cross out, add and highlight, and send it back. It works until {{ until }}; every version you send them later comes on the same link.</p>
|
||||
<div class="linkrow">
|
||||
<input type="text" readonly value="{{ url }}" id="link-url" aria-label="The link" data-select-all>
|
||||
<button type="button" class="btn" data-copy="#link-url">Copy</button>
|
||||
</div>
|
||||
{% if qr %}<div class="qr" aria-label="The link as a QR code">{{ qr|safe }}</div>{% endif %}
|
||||
<p class="notice warn">The link is shown only now: the app keeps only a fingerprint of it. Copy it before you leave this page; otherwise close the link on the contract page and send again, which makes a new one.</p>
|
||||
{% else %}
|
||||
<header><h2>On {{ party }}'s link</h2></header>
|
||||
<p>Version {{ review_version }} is now on the link {{ party }} has already. Tell them it is there; the link works until {{ until }}.</p>
|
||||
{% endif %}
|
||||
<div class="formactions"><a class="btn pri" href="/contracts/{{ id }}#reviews">Done</a></div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
//! The shared draft (phase 13): opened from a version, edited with tracked
|
||||
//! changes by our team and a party on its link, one editor at a time;
|
||||
//! changes accepted, agreement voided by a later change, and the text
|
||||
//! locked as a version once every side agrees. The other side's work
|
||||
//! shows on the bell.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::Value;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::common::{App, local};
|
||||
|
||||
const SAME: &[(&str, &str)] = &[("sec-fetch-site", "same-origin")];
|
||||
|
||||
async fn performance(pool: &PgPool) -> (i64, i64, String) {
|
||||
sqlx::query_as(
|
||||
"SELECT c.id, p.id, v.body FROM contracts c \
|
||||
JOIN contract_parties p ON p.contract_id = c.id AND p.removed_at IS NULL \
|
||||
JOIN contract_versions v ON v.contract_id = c.id \
|
||||
WHERE c.title LIKE 'Performance agreement%' AND v.body <> '' \
|
||||
ORDER BY v.version DESC LIMIT 1",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn json(text: &str) -> Value {
|
||||
serde_json::from_str(text).unwrap_or_else(|e| panic!("{e}: {text}"))
|
||||
}
|
||||
|
||||
/// The JSON in the editor's data block.
|
||||
fn data_of(page: &str) -> Value {
|
||||
let at = page.find("id=\"dr-data\">").expect("the editor's data") + 13;
|
||||
let end = at + page[at..].find("</script>").unwrap();
|
||||
json(&page[at..end])
|
||||
}
|
||||
|
||||
struct Party<'a> {
|
||||
app: &'a App,
|
||||
path: String,
|
||||
csrf: String,
|
||||
}
|
||||
|
||||
impl Party<'_> {
|
||||
async fn act(&self, action: &str, fields: &[(&str, &str)]) -> (StatusCode, Value) {
|
||||
let mut pairs = vec![("csrf", self.csrf.as_str())];
|
||||
pairs.extend_from_slice(fields);
|
||||
let r = self
|
||||
.app
|
||||
.post_raw(&format!("{}/{action}", self.path), &pairs, SAME)
|
||||
.await;
|
||||
(r.status, json(&r.text()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn staff(app: &App, c: i64, action: &str, fields: &[(&str, &str)]) -> (StatusCode, Value) {
|
||||
let r = app
|
||||
.post(&format!("/contracts/{c}/draft/{action}"), fields)
|
||||
.await;
|
||||
(r.status, json(&r.text()))
|
||||
}
|
||||
|
||||
fn rev(v: &Value) -> String {
|
||||
v["state"]["rev"]
|
||||
.as_i64()
|
||||
.or(v["rev"].as_i64())
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn both_sides_edit_one_draft_until_all_agree_and_it_locks(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let today = visa::dates::today();
|
||||
visa::seed::demo(&pool, today).await.unwrap();
|
||||
visa::seed::legal::demo(&pool, None, today).await.unwrap();
|
||||
let (c, party, body) = performance(&pool).await;
|
||||
let versions_before: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM contract_versions WHERE contract_id = $1")
|
||||
.bind(c)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// the demo's own notice is seen already
|
||||
app.get("/notices").await;
|
||||
|
||||
// the contract page offers the draft; it opens from version 1
|
||||
let t = app.get(&format!("/contracts/{c}")).await.text();
|
||||
assert!(t.contains("id=\"draft-open-form\""), "{t}");
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/contracts/{c}/draft/open"),
|
||||
&[("draft_version", "1")],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.location(), format!("/contracts/{c}/draft"));
|
||||
let page = app.get(&format!("/contracts/{c}/draft")).await.text();
|
||||
let state = &data_of(&page)["state"];
|
||||
assert_eq!(state["state"], "open");
|
||||
assert_eq!(state["need"], 2, "Lanna Desk and the festival");
|
||||
|
||||
// the festival's link
|
||||
let made = app
|
||||
.post(
|
||||
&format!("/contracts/{c}/invites"),
|
||||
&[("party", &party.to_string())],
|
||||
)
|
||||
.await
|
||||
.text();
|
||||
let at = made.find("/r/").expect("the link is shown");
|
||||
let token: String = made[at + 3..]
|
||||
.chars()
|
||||
.take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '-' || *ch == '_')
|
||||
.collect();
|
||||
let path = format!("/r/{token}");
|
||||
let r = app.get(&path).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
|
||||
let page = r.text();
|
||||
assert!(!page.contains("/desk"), "nothing of the back office");
|
||||
let data = data_of(&page);
|
||||
let them = Party {
|
||||
app: &app,
|
||||
path: path.clone(),
|
||||
csrf: data["csrf"].as_str().unwrap().to_string(),
|
||||
};
|
||||
let mut now = data["state"]["rev"].as_i64().unwrap().to_string();
|
||||
|
||||
// one editor at a time
|
||||
let (s, _) = staff(&app, c, "take", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
let (s, v) = them.act("take", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::CONFLICT);
|
||||
assert!(v["error"].as_str().unwrap().contains("is editing"), "{v}");
|
||||
staff(&app, c, "release", &[("rev", &now)]).await;
|
||||
let (s, _) = them.act("take", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
|
||||
// the festival's tracked changes: the fee, and a highlight
|
||||
let side = format!("party:{party}");
|
||||
let (head, rest) = body.split_once("45,000").unwrap();
|
||||
let (mid, tail) = rest.split_once("flight from Berlin").unwrap();
|
||||
let pieces = serde_json::json!([
|
||||
["same", head, "", ""],
|
||||
["del", "45,000", "", side],
|
||||
["ins", "60,000", "", side],
|
||||
["same", mid, "", ""],
|
||||
[
|
||||
"mark",
|
||||
"flight from Berlin",
|
||||
"Business class, please.",
|
||||
side
|
||||
],
|
||||
["same", tail, "", ""]
|
||||
])
|
||||
.to_string();
|
||||
// a change to the text as it stands is refused
|
||||
let sneaky =
|
||||
serde_json::json!([["same", body.replace("45,000", "90,000"), "", ""]]).to_string();
|
||||
let (s, _) = them
|
||||
.act("save", &[("rev", &now), ("pieces", &sneaky)])
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
// marks made in our name too
|
||||
let forged = pieces.replace(&side, "us");
|
||||
let (s, _) = them
|
||||
.act("save", &[("rev", &now), ("pieces", &forged)])
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let (s, v) = them
|
||||
.act("save", &[("rev", &now), ("pieces", &pieces)])
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::OK, "{v}");
|
||||
now = rev(&v);
|
||||
// we cannot save while they edit
|
||||
let (s, _) = staff(&app, c, "save", &[("rev", &now), ("pieces", &pieces)]).await;
|
||||
assert_eq!(s, StatusCode::CONFLICT);
|
||||
them.act("release", &[("rev", &now)]).await;
|
||||
|
||||
// the bell rings for us, and the list marks it seen
|
||||
let n = json(&app.get("/notices/count").await.text());
|
||||
assert_eq!(n["unread"], 1, "{n}");
|
||||
let t = app.get("/notices").await.text();
|
||||
assert!(t.contains("changed the draft of"), "{t}");
|
||||
assert_eq!(json(&app.get("/notices/count").await.text())["unread"], 0);
|
||||
|
||||
// our view has their change; we take it in
|
||||
let st = json(&app.get(&format!("/contracts/{c}/draft/state")).await.text());
|
||||
assert_eq!(st["rev"].as_i64().unwrap().to_string(), now);
|
||||
let (s, v) = staff(&app, c, "accept", &[("rev", &now), ("n", "1")]).await;
|
||||
assert_eq!(s, StatusCode::OK, "{v}");
|
||||
now = rev(&v);
|
||||
// they cannot accept their own; nothing is left to accept anyway
|
||||
let (s, _) = them.act("accept", &[("rev", &now), ("n", "1")]).await;
|
||||
assert_eq!(s, StatusCode::CONFLICT);
|
||||
|
||||
// an open highlight blocks an agreement; resolved, we agree
|
||||
let (s, _) = staff(&app, c, "agree", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let (_, v) = staff(&app, c, "resolve", &[("rev", &now), ("k", "1")]).await;
|
||||
now = rev(&v);
|
||||
// we agree; their next edit voids it
|
||||
let (s, v) = staff(&app, c, "agree", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::OK, "{v}");
|
||||
assert_eq!(v["state"]["have"], 1);
|
||||
them.act("take", &[("rev", &now)]).await;
|
||||
let added = format!(
|
||||
"{},[\"ins\",\"\\nSound check at 18:00.\",\"\",\"{side}\"]]",
|
||||
&pieces[..pieces.len() - 1]
|
||||
);
|
||||
let accepted = added
|
||||
.replace(&format!("[\"del\",\"45,000\",\"\",\"{side}\"],"), "")
|
||||
.replace(
|
||||
&format!("[\"ins\",\"60,000\",\"\",\"{side}\"]"),
|
||||
"[\"same\",\"60,000\",\"\",\"\"]",
|
||||
);
|
||||
let (s, v) = them
|
||||
.act("save", &[("rev", &now), ("pieces", &accepted)])
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::OK, "{v}");
|
||||
now = rev(&v);
|
||||
assert_eq!(v["state"]["have"], 0, "a change asks everyone again");
|
||||
them.act("release", &[("rev", &now)]).await;
|
||||
// open changes block an agreement
|
||||
let (s, _) = them.act("agree", &[("rev", &now), ("name", "Ann")]).await;
|
||||
assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let (_, v) = staff(&app, c, "reject", &[("rev", &now), ("n", "1")]).await;
|
||||
now = rev(&v);
|
||||
let (_, v) = them.act("resolve", &[("rev", &now), ("k", "1")]).await;
|
||||
now = rev(&v);
|
||||
|
||||
// both agree: the text locks as a new version
|
||||
let (s, _) = staff(&app, c, "agree", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::OK);
|
||||
let (s, _) = them.act("agree", &[("rev", &now), ("name", "")]).await;
|
||||
assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY, "a name goes with it");
|
||||
let (s, v) = them
|
||||
.act("agree", &[("rev", &now), ("name", "Ann Festival")])
|
||||
.await;
|
||||
assert_eq!(s, StatusCode::OK, "{v}");
|
||||
assert_eq!(v["state"]["state"], "locked");
|
||||
let (count, text): (i64, String) = sqlx::query_as(
|
||||
"SELECT (SELECT count(*) FROM contract_versions WHERE contract_id = $1), \
|
||||
(SELECT body FROM contract_versions WHERE contract_id = $1 ORDER BY version DESC LIMIT 1)",
|
||||
)
|
||||
.bind(c)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, versions_before + 1);
|
||||
assert!(text.contains("60,000") && !text.contains("45,000") && !text.contains("Sound check"));
|
||||
let events: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT event FROM journal WHERE contract_id = $1 AND seq > 0 ORDER BY seq",
|
||||
)
|
||||
.bind(c)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for e in [
|
||||
"draft opened",
|
||||
"draft link made",
|
||||
"change accepted",
|
||||
"change rejected",
|
||||
"highlight resolved",
|
||||
"text agreed",
|
||||
"draft locked",
|
||||
] {
|
||||
assert!(events.iter().any(|x| x == e), "{e} missing in {events:?}");
|
||||
}
|
||||
assert!(visa::journal::verify(&pool).await.unwrap().whole());
|
||||
let t = app.get(&format!("/contracts/{c}")).await.text();
|
||||
assert!(t.contains("Every side agreed") && t.contains("Start a new draft"));
|
||||
|
||||
// locked is locked
|
||||
let (s, _) = staff(&app, c, "take", &[("rev", &now)]).await;
|
||||
assert_eq!(s, StatusCode::CONFLICT);
|
||||
assert!(
|
||||
sqlx::query("UPDATE contract_drafts SET pieces = '[]' WHERE contract_id = $1")
|
||||
.bind(c)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
sqlx::query("DELETE FROM draft_saves")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
sqlx::query("DELETE FROM draft_agreements")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
// the link's form token is its own, and a closed link ends
|
||||
let r = app
|
||||
.post_raw(
|
||||
&format!("{path}/take"),
|
||||
&[("csrf", &"x".repeat(43)), ("rev", &now)],
|
||||
SAME,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let link: i64 =
|
||||
sqlx::query_scalar("SELECT id FROM review_links WHERE party_id = $1 AND closed_at IS NULL")
|
||||
.bind(party)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
app.post(&format!("/contracts/{c}/review-links/{link}/close"), &[])
|
||||
.await;
|
||||
assert_eq!(app.get(&path).await.status, StatusCode::GONE);
|
||||
assert_eq!(
|
||||
app.get(&format!("/r/{}", "a".repeat(43))).await.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_demo_draft_shows_the_labels_changes_as_a_diff(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let today = visa::dates::today();
|
||||
visa::seed::demo(&pool, today).await.unwrap();
|
||||
visa::seed::legal::demo(&pool, None, today).await.unwrap();
|
||||
let c: i64 = sqlx::query_scalar("SELECT contract_id FROM contract_drafts LIMIT 1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let st = json(&app.get(&format!("/contracts/{c}/draft/state")).await.text());
|
||||
let pieces = st["pieces"].as_array().unwrap();
|
||||
let changes = pieces
|
||||
.windows(2)
|
||||
.filter(|w| {
|
||||
let k = |p: &Value| p[0].as_str().unwrap().to_string();
|
||||
(k(&w[1]) == "ins" || k(&w[1]) == "del") && !(k(&w[0]) == "ins" || k(&w[0]) == "del")
|
||||
})
|
||||
.count();
|
||||
assert_eq!(changes, 4, "{st}");
|
||||
let t = app.get(&format!("/contracts/{c}/draft/diff")).await.text();
|
||||
assert!(
|
||||
t.contains("class=\"gitdiff\"") && t.contains("id=\"change-4\""),
|
||||
"{t}"
|
||||
);
|
||||
let t = app.get(&format!("/contracts/{c}")).await.text();
|
||||
assert!(
|
||||
t.contains("4 open changes") && t.contains("0 of 2 sides agree"),
|
||||
"{t}"
|
||||
);
|
||||
assert_eq!(json(&app.get("/notices/count").await.text())["unread"], 1);
|
||||
}
|
||||
+1
-1
@@ -11,6 +11,7 @@ mod companies;
|
||||
mod deadlines;
|
||||
mod demo;
|
||||
mod documents;
|
||||
mod drafts;
|
||||
mod fuzz_cases;
|
||||
mod garage;
|
||||
mod legal;
|
||||
@@ -22,7 +23,6 @@ mod pages;
|
||||
mod papers;
|
||||
mod people;
|
||||
mod records;
|
||||
mod reviews;
|
||||
|
||||
#[test]
|
||||
fn every_test_file_is_a_module() {
|
||||
|
||||
+11
-9
@@ -101,24 +101,26 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// the label's review of the recording agreement (phase 13)
|
||||
let (review_contract, review_round): (i64, i64) = sqlx::query_as(
|
||||
"SELECT l.contract_id, r.id FROM review_rounds r JOIN review_links l ON l.id = r.link_id \
|
||||
WHERE r.replied_at IS NOT NULL LIMIT 1",
|
||||
)
|
||||
// the shared draft of the recording agreement (phase 13)
|
||||
let draft_contract: i64 = sqlx::query_scalar("SELECT contract_id FROM contract_drafts LIMIT 1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut pages = vec![
|
||||
(
|
||||
format!("/contracts/{review_contract}/reviews/{review_round}"),
|
||||
"As a diff".to_string(),
|
||||
format!("/contracts/{draft_contract}/draft"),
|
||||
"The shared draft for".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/contracts/{review_contract}"),
|
||||
"Review by the other side".to_string(),
|
||||
format!("/contracts/{draft_contract}/draft/diff"),
|
||||
"The draft as a diff".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/contracts/{draft_contract}"),
|
||||
"Shared draft".to_string(),
|
||||
),
|
||||
("/notices".to_string(), "changed the draft".to_string()),
|
||||
(
|
||||
"/originals".to_string(),
|
||||
"Chiang Mai Immigration".to_string(),
|
||||
|
||||
@@ -1,287 +0,0 @@
|
||||
//! The other side reviews a draft (phase 13): a version sent on a link,
|
||||
//! marked up there and sent back, read as a diff and taken change by
|
||||
//! change into the next version; every step in the journal.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::common::{App, local};
|
||||
|
||||
const SAME: &[(&str, &str)] = &[("sec-fetch-site", "same-origin")];
|
||||
|
||||
/// The value of the input `name` in a page.
|
||||
fn input(page: &str, name: &str) -> String {
|
||||
let at = page
|
||||
.find(&format!("name=\"{name}\""))
|
||||
.unwrap_or_else(|| panic!("no {name} in {page}"));
|
||||
let rest = &page[at..];
|
||||
let v = rest.find("value=\"").unwrap() + 7;
|
||||
rest[v..v + rest[v..].find('"').unwrap()].to_string()
|
||||
}
|
||||
|
||||
async fn performance(pool: &PgPool) -> (i64, i64, String) {
|
||||
sqlx::query_as(
|
||||
"SELECT c.id, p.id, v.body FROM contracts c \
|
||||
JOIN contract_parties p ON p.contract_id = c.id \
|
||||
JOIN contract_versions v ON v.contract_id = c.id \
|
||||
WHERE c.title LIKE 'Performance agreement%' AND v.body <> '' \
|
||||
ORDER BY v.version DESC LIMIT 1",
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn send(app: &App, contract: i64, party: i64) -> String {
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/contracts/{contract}/reviews"),
|
||||
&[
|
||||
("review_party", &party.to_string()),
|
||||
("review_version", "1"),
|
||||
("review_message", "Please look at the fee."),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
|
||||
r.text()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_other_side_marks_a_version_up_and_we_take_their_changes(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let today = visa::dates::today();
|
||||
visa::seed::demo(&pool, today).await.unwrap();
|
||||
visa::seed::legal::demo(&pool, None, today).await.unwrap();
|
||||
let (contract, party, body) = performance(&pool).await;
|
||||
|
||||
// the contract page offers the review; sending makes a link shown once
|
||||
let t = app.get(&format!("/contracts/{contract}")).await.text();
|
||||
assert!(
|
||||
t.contains("id=\"reviews\"") && t.contains("id=\"send-form\""),
|
||||
"{t}"
|
||||
);
|
||||
let made = send(&app, contract, party).await;
|
||||
let at = made.find("/r/").expect("the link is shown");
|
||||
let token: String = made[at + 3..]
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
|
||||
.collect();
|
||||
assert_eq!(token.len(), 43);
|
||||
let path = format!("/r/{token}");
|
||||
|
||||
// their page: the text in the editor, nothing of the staff's app
|
||||
let r = app.get(&path).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{}", r.text());
|
||||
let page = r.text();
|
||||
assert!(page.contains("id=\"rv-editor\"") && page.contains("Please look at the fee."));
|
||||
assert!(page.contains("review-editor.js"));
|
||||
assert!(!page.contains("/desk"), "no link into the back office");
|
||||
let csrf = input(&page, "csrf");
|
||||
let round = input(&page, "round");
|
||||
|
||||
// their marks: the fee changed, the travel highlighted, a line added
|
||||
let (head, rest) = body.split_once("45,000").unwrap();
|
||||
let (mid, tail) = rest.split_once("flight from Berlin").unwrap();
|
||||
let pieces = serde_json::json!([
|
||||
["same", head, ""],
|
||||
["del", "45,000", ""],
|
||||
["ins", "60,000", ""],
|
||||
["same", mid, ""],
|
||||
["mark", "flight from Berlin", "Business class, please."],
|
||||
["same", tail, ""],
|
||||
[
|
||||
"ins",
|
||||
"\n\n# 4. Sound\nThe Festival provides two CDJ-3000 and a DJM-A9.",
|
||||
""
|
||||
]
|
||||
])
|
||||
.to_string();
|
||||
let post = |pieces: String, name: &'static str, csrf: String| {
|
||||
let path = path.clone();
|
||||
let round = round.clone();
|
||||
let app = &app;
|
||||
async move {
|
||||
app.post_raw(
|
||||
&path,
|
||||
&[
|
||||
("csrf", &csrf),
|
||||
("round", &round),
|
||||
("pieces", &pieces),
|
||||
("name", name),
|
||||
("message", "Our counter offer."),
|
||||
],
|
||||
SAME,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
// a change to our text without a mark is refused
|
||||
let sneaky = serde_json::json!([["same", body.replace("45,000", "90,000"), ""]]).to_string();
|
||||
let r = post(sneaky, "Ann", csrf.clone()).await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(r.text().contains("does not match the version we sent"));
|
||||
// without a name the marks come back in the editor
|
||||
let r = post(pieces.clone(), "", csrf.clone()).await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let t = r.text();
|
||||
assert!(
|
||||
t.contains("Say who sends this back") && t.contains("60,000"),
|
||||
"{t}"
|
||||
);
|
||||
// the staff's token is no token here
|
||||
let r = post(pieces.clone(), "Ann", "x".repeat(43)).await;
|
||||
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||
let r = post(pieces.clone(), "Ann Festival", csrf.clone()).await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
|
||||
// once a round
|
||||
let r = post(pieces.clone(), "Ann Festival", csrf.clone()).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT);
|
||||
let t = app.get(&path).await.text();
|
||||
assert!(
|
||||
t.contains("Thank you") && t.contains("2 changes and 1 highlight"),
|
||||
"{t}"
|
||||
);
|
||||
|
||||
// the journal has both, with the fingerprint of their text
|
||||
let events: Vec<(String, String)> = sqlx::query_as(
|
||||
"SELECT event, detail FROM journal WHERE contract_id = $1 AND event IN \
|
||||
('sent for review', 'review returned') ORDER BY seq",
|
||||
)
|
||||
.bind(contract)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(events.len(), 2, "{events:?}");
|
||||
assert!(
|
||||
events[1]
|
||||
.1
|
||||
.contains("(Ann Festival) sent version 1 back with 2 changes and 1 highlight")
|
||||
);
|
||||
let sha: String = sqlx::query_scalar("SELECT reply_sha256 FROM review_rounds WHERE id = $1")
|
||||
.bind(round.parse::<i64>().unwrap())
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(events[1].1.contains(&sha));
|
||||
assert!(visa::journal::verify(&pool).await.unwrap().whole());
|
||||
|
||||
// our side: the changes, the highlight and the git view
|
||||
let review = format!("/contracts/{contract}/reviews/{round}");
|
||||
let t = app.get(&review).await.text();
|
||||
assert!(t.contains("id=\"take-form\"") && t.contains("Business class, please."));
|
||||
assert!(t.contains("class=\"gitdiff\"") && t.contains("Our counter offer."));
|
||||
// take only the fee: the version form starts with it, without the sound
|
||||
let r = app.post(&format!("{review}/take"), &[("take", "1")]).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
let t = r.text();
|
||||
assert!(t.contains("60,000 THB") && !t.contains("CDJ-3000"), "{t}");
|
||||
assert!(t.contains("1 of 2 changes by"));
|
||||
// every ticked box counts
|
||||
let t = app
|
||||
.post(&format!("{review}/take"), &[("take", "1"), ("take", "2")])
|
||||
.await
|
||||
.text();
|
||||
assert!(t.contains("60,000 THB") && t.contains("CDJ-3000"));
|
||||
assert!(
|
||||
t.contains("Ann Festival") || t.contains("changes of"),
|
||||
"{t}"
|
||||
);
|
||||
|
||||
// the next version goes on the same link, as a new round
|
||||
let made = send(&app, contract, party).await;
|
||||
assert!(
|
||||
made.contains("on the link") && !made.contains("/r/"),
|
||||
"{made}"
|
||||
);
|
||||
let t = app.get(&path).await.text();
|
||||
assert!(t.contains("id=\"rv-editor\"") && t.contains("id=\"earlier\""));
|
||||
// a reply to the old round is refused
|
||||
let r = post(pieces, "Ann Festival", csrf).await;
|
||||
assert_eq!(r.status, StatusCode::CONFLICT);
|
||||
|
||||
// the database keeps what they sent
|
||||
assert!(
|
||||
sqlx::query("UPDATE review_rounds SET reply_body = 'other' WHERE id = $1")
|
||||
.bind(round.parse::<i64>().unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
sqlx::query("DELETE FROM review_rounds")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
// closing the link ends it
|
||||
let link: i64 = sqlx::query_scalar("SELECT id FROM review_links WHERE party_id = $1")
|
||||
.bind(party)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/contracts/{contract}/review-links/{link}/close"),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(app.get(&path).await.status, StatusCode::GONE);
|
||||
assert_eq!(
|
||||
app.get(&format!("/r/{}", "a".repeat(43))).await.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn only_a_live_party_and_a_version_with_a_text_can_be_sent(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let today = visa::dates::today();
|
||||
visa::seed::demo(&pool, today).await.unwrap();
|
||||
visa::seed::legal::demo(&pool, None, today).await.unwrap();
|
||||
let (contract, party, _) = performance(&pool).await;
|
||||
let other: i64 =
|
||||
sqlx::query_scalar("SELECT id FROM contract_parties WHERE contract_id <> $1 LIMIT 1")
|
||||
.bind(contract)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let to = format!("/contracts/{contract}/reviews");
|
||||
for form in [
|
||||
vec![
|
||||
("review_party", other.to_string()),
|
||||
("review_version", "1".to_string()),
|
||||
],
|
||||
vec![
|
||||
("review_party", party.to_string()),
|
||||
("review_version", "9".to_string()),
|
||||
],
|
||||
] {
|
||||
let pairs: Vec<(&str, &str)> = form.iter().map(|(a, b)| (*a, b.as_str())).collect();
|
||||
assert_eq!(
|
||||
app.post(&to, &pairs).await.status,
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
// the demo's label review reads as a diff with its four changes
|
||||
let (c, round): (i64, i64) = sqlx::query_as(
|
||||
"SELECT l.contract_id, r.id FROM review_rounds r JOIN review_links l ON l.id = r.link_id \
|
||||
WHERE r.replied_at IS NOT NULL LIMIT 1",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let t = app
|
||||
.get(&format!("/contracts/{c}/reviews/{round}"))
|
||||
.await
|
||||
.text();
|
||||
assert!(
|
||||
t.contains("id=\"change-4\"") && !t.contains("id=\"change-5\""),
|
||||
"{t}"
|
||||
);
|
||||
assert!(t.contains("We need fifteen for the catalogue."));
|
||||
let t = app.get(&format!("/contracts/{c}")).await.text();
|
||||
assert!(t.contains("sent back") && t.contains("4 changes"));
|
||||
}
|
||||
Reference in new issue
Block a user