Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dd9ab60e8 | ||
|
|
a4155548b8 |
No files matched your search
@@ -248,6 +248,7 @@ dark at desktop and phone width, a commit and a push.
|
|||||||
| 10 | One client list: a visa record becomes part of a client; People becomes the visa clients | planned Nov 21, 2026 |
|
| 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 |
|
| 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 |
|
| 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 | 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 | |
|
| later | Thai user interface, agency cases and fees, other visa categories' packs | |
|
||||||
|
|
||||||
### Phase 1: app, login, people
|
### Phase 1: app, login, people
|
||||||
@@ -843,6 +844,75 @@ and record, with a suggestion to confirm.
|
|||||||
reminders once phase 8 sends them.
|
reminders once phase 8 sends them.
|
||||||
- Phase 10 (one client list) turns an original's person into a client.
|
- Phase 10 (one client list) turns an original's person into a client.
|
||||||
|
|
||||||
|
## Phase 13: the shared draft (planned and built Nov 23, 2026)
|
||||||
|
|
||||||
|
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: review rounds (built, then replaced)
|
||||||
|
|
||||||
|
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: the shared draft (built)
|
||||||
|
|
||||||
|
- 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
|
## Open questions
|
||||||
|
|
||||||
1. B4L's BOI application: once B4L is promoted, its staff extend their stay
|
1. B4L's BOI application: once B4L is promoted, its staff extend their stay
|
||||||
|
|||||||
Binary file not shown.
@@ -0,0 +1,90 @@
|
|||||||
|
-- The other side reviews a draft (phase 13). A lawyer sends a version with
|
||||||
|
-- a text to one of the contract's parties: a link for that party (one open
|
||||||
|
-- at a time) and a round for the version. The other side marks the text up
|
||||||
|
-- (crossed out, added, highlighted) and sends it back once per round.
|
||||||
|
CREATE TABLE review_links (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
contract_id BIGINT NOT NULL REFERENCES contracts (id),
|
||||||
|
party_id BIGINT NOT NULL REFERENCES contract_parties (id),
|
||||||
|
-- SHA-256 of the token in the link, as for the client links
|
||||||
|
token_hash BYTEA NOT NULL UNIQUE,
|
||||||
|
csrf TEXT NOT NULL,
|
||||||
|
created_by TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
first_used_at TIMESTAMPTZ,
|
||||||
|
last_used_at TIMESTAMPTZ,
|
||||||
|
closed_at TIMESTAMPTZ,
|
||||||
|
closed_by TEXT,
|
||||||
|
CHECK ((closed_at IS NULL) = (closed_by IS NULL))
|
||||||
|
);
|
||||||
|
CREATE INDEX review_links_contract ON review_links (contract_id);
|
||||||
|
CREATE UNIQUE INDEX review_links_one_open ON review_links (party_id) WHERE closed_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE review_rounds (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
link_id BIGINT NOT NULL REFERENCES review_links (id),
|
||||||
|
version_id BIGINT NOT NULL REFERENCES contract_versions (id),
|
||||||
|
-- what we wrote to them with this version
|
||||||
|
message TEXT NOT NULL DEFAULT '',
|
||||||
|
sent_by TEXT NOT NULL,
|
||||||
|
sent_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
-- their reply, written once
|
||||||
|
replied_at TIMESTAMPTZ,
|
||||||
|
reply_name TEXT,
|
||||||
|
reply_message TEXT,
|
||||||
|
-- the pieces: [["same"|"ins"|"del"|"mark", text, comment], ...]
|
||||||
|
reply_pieces JSONB,
|
||||||
|
-- their text: the pieces without the crossed-out ones
|
||||||
|
reply_body TEXT,
|
||||||
|
reply_sha256 TEXT CHECK (reply_sha256 ~ '^[0-9a-f]{64}$'),
|
||||||
|
reply_ip TEXT,
|
||||||
|
reply_user_agent TEXT,
|
||||||
|
CHECK (
|
||||||
|
(replied_at IS NULL) = (reply_name IS NULL)
|
||||||
|
AND (replied_at IS NULL) = (reply_pieces IS NULL)
|
||||||
|
AND (replied_at IS NULL) = (reply_body IS NULL)
|
||||||
|
AND (replied_at IS NULL) = (reply_sha256 IS NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
CREATE INDEX review_rounds_link ON review_rounds (link_id);
|
||||||
|
|
||||||
|
-- A round never changes, but for its reply, written once.
|
||||||
|
CREATE FUNCTION review_rounds_kept() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'DELETE' THEN
|
||||||
|
RAISE EXCEPTION 'a review round stays on record';
|
||||||
|
END IF;
|
||||||
|
IF OLD.replied_at IS NOT NULL
|
||||||
|
OR NEW.link_id <> OLD.link_id OR NEW.version_id <> OLD.version_id
|
||||||
|
OR NEW.message <> OLD.message OR NEW.sent_by <> OLD.sent_by
|
||||||
|
OR NEW.sent_at <> OLD.sent_at THEN
|
||||||
|
RAISE EXCEPTION 'a review round never changes; its reply is written once';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER review_rounds_no_change
|
||||||
|
BEFORE UPDATE OR DELETE ON review_rounds
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION review_rounds_kept();
|
||||||
|
|
||||||
|
CREATE FUNCTION review_links_kept() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
RAISE EXCEPTION 'a review link stays on record: close it';
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
CREATE TRIGGER review_links_no_delete
|
||||||
|
BEFORE DELETE ON review_links
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION review_links_kept();
|
||||||
|
|
||||||
|
ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check;
|
||||||
|
ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK (
|
||||||
|
entity IN (
|
||||||
|
'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival',
|
||||||
|
'extension', 'reentry-permit', 'report', 'work-permit', 'document', 'form', 'link',
|
||||||
|
'agreement', 'signature', 'lawyer', 'client', 'contract', 'contract-version',
|
||||||
|
'paper-copy', 'contract-party', 'original', 'review'
|
||||||
|
)
|
||||||
|
);
|
||||||
@@ -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'
|
||||||
|
)
|
||||||
|
);
|
||||||
@@ -77,6 +77,10 @@ pub enum Entity {
|
|||||||
ContractParty,
|
ContractParty,
|
||||||
/// An original in our care (`originals`).
|
/// An original in our care (`originals`).
|
||||||
Original,
|
Original,
|
||||||
|
/// A review of a contract version by the other side (`reviews`).
|
||||||
|
Review,
|
||||||
|
/// A contract's shared draft (`drafts`).
|
||||||
|
Draft,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Entity {
|
impl Entity {
|
||||||
@@ -105,6 +109,8 @@ impl Entity {
|
|||||||
Entity::PaperCopy => "paper-copy",
|
Entity::PaperCopy => "paper-copy",
|
||||||
Entity::ContractParty => "contract-party",
|
Entity::ContractParty => "contract-party",
|
||||||
Entity::Original => "original",
|
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)))
|
||||||
|
}
|
||||||
+15
-1
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
|
|
||||||
use crate::{agreements, conflicts, dates, files, gps, legal, mrz, pack, records};
|
use crate::{agreements, conflicts, dates, files, gps, legal, mrz, pack, records, reviews};
|
||||||
|
|
||||||
/// Run once before a fuzz target's first input. libFuzzer's panic hook
|
/// Run once before a fuzz target's first input. libFuzzer's panic hook
|
||||||
/// aborts at once, even inside the app's own `catch_unwind` (around the PDF
|
/// aborts at once, even inside the app's own `catch_unwind` (around the PDF
|
||||||
@@ -61,6 +61,20 @@ pub fn text(data: &[u8]) {
|
|||||||
let body = agreements::normalize(&s);
|
let body = agreements::normalize(&s);
|
||||||
let _ = agreements::check("Title", &body);
|
let _ = agreements::check("Title", &body);
|
||||||
let _ = agreements::blocks(&body);
|
let _ = agreements::blocks(&body);
|
||||||
|
// 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);
|
||||||
|
// 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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The kinds of document an upload can be, which decide how it prints.
|
/// The kinds of document an upload can be, which decide how it prints.
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ pub mod dates;
|
|||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod deadlines;
|
pub mod deadlines;
|
||||||
pub mod documents;
|
pub mod documents;
|
||||||
|
pub mod drafts;
|
||||||
pub mod embedded;
|
pub mod embedded;
|
||||||
pub mod files;
|
pub mod files;
|
||||||
pub mod forms;
|
pub mod forms;
|
||||||
@@ -23,6 +24,7 @@ pub mod legal;
|
|||||||
pub mod links;
|
pub mod links;
|
||||||
pub mod mail;
|
pub mod mail;
|
||||||
pub mod mrz;
|
pub mod mrz;
|
||||||
|
pub mod notices;
|
||||||
pub mod oidc;
|
pub mod oidc;
|
||||||
pub mod originals;
|
pub mod originals;
|
||||||
pub mod pack;
|
pub mod pack;
|
||||||
@@ -31,6 +33,7 @@ pub mod people;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod props;
|
mod props;
|
||||||
pub mod records;
|
pub mod records;
|
||||||
|
pub mod reviews;
|
||||||
pub mod s3;
|
pub mod s3;
|
||||||
pub mod seed;
|
pub mod seed;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
|
|||||||
+1
-1
@@ -96,7 +96,7 @@ pub fn actor(id: i64) -> String {
|
|||||||
format!("link {id}")
|
format!("link {id}")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hash(token: &str) -> Vec<u8> {
|
pub(crate) fn hash(token: &str) -> Vec<u8> {
|
||||||
ring::digest::digest(&ring::digest::SHA256, token.as_bytes())
|
ring::digest::digest(&ring::digest::SHA256, token.as_bytes())
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.to_vec()
|
.to_vec()
|
||||||
|
|||||||
+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(())
|
||||||
|
}
|
||||||
+76
-1
@@ -8,7 +8,7 @@
|
|||||||
use chrono::{DateTime, Datelike, NaiveDate, Utc};
|
use chrono::{DateTime, Datelike, NaiveDate, Utc};
|
||||||
use proptest::prelude::*;
|
use proptest::prelude::*;
|
||||||
|
|
||||||
use crate::{agreements, conflicts, dates, gps, journal, legal, mrz, records};
|
use crate::{agreements, conflicts, dates, gps, journal, legal, mrz, records, reviews};
|
||||||
|
|
||||||
fn today() -> NaiveDate {
|
fn today() -> NaiveDate {
|
||||||
NaiveDate::from_ymd_opt(2026, 11, 17).unwrap()
|
NaiveDate::from_ymd_opt(2026, 11, 17).unwrap()
|
||||||
@@ -436,3 +436,78 @@ proptest! {
|
|||||||
prop_assert_ne!(hash(&a), hash(&b));
|
prop_assert_ne!(hash(&a), hash(&b));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------- the shared draft
|
||||||
|
|
||||||
|
/// 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::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 (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];
|
||||||
|
let by = if op == reviews::Op::Same {
|
||||||
|
""
|
||||||
|
} else {
|
||||||
|
side.as_str()
|
||||||
|
};
|
||||||
|
let c = if op == reviews::Op::Mark {
|
||||||
|
comment.trim().to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
pieces.push(reviews::piece(op, &text, &c, by));
|
||||||
|
pieces.push(reviews::piece(
|
||||||
|
reviews::Op::Ins,
|
||||||
|
&typed.replace('\r', ""),
|
||||||
|
"",
|
||||||
|
&side,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
(sent, reviews::tidy(pieces), side)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
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 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(reviews::Op::Same, &extra, "", ""));
|
||||||
|
prop_assert!(reviews::check_save(&reviews::unmarked(&sent), &changed, &side).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
+776
@@ -0,0 +1,776 @@
|
|||||||
|
//! The shared draft's text (phase 13). A draft is a list of pieces: the
|
||||||
|
//! agreed text (`same`) and tracked changes, each by a side (`us` for Lanna
|
||||||
|
//! Desk's team, `party:<id>` for another party): added (`ins`), crossed out
|
||||||
|
//! (`del`) or highlighted with a comment (`mark`). The text as it stands is
|
||||||
|
//! the pieces without the added ones (`base`); with every change taken it
|
||||||
|
//! is `proposed`.
|
||||||
|
//!
|
||||||
|
//! A save by one side may only touch that side's own marks (`check_save`):
|
||||||
|
//! it never changes the text as it stands, nor anyone else's change. Taking
|
||||||
|
//! a change in or dropping it (`settle`) and resolving a highlight
|
||||||
|
//! (`resolve`) are their own steps, journaled. Also the links each party
|
||||||
|
//! opens the draft with.
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::{PgConnection, PgPool};
|
||||||
|
|
||||||
|
use crate::legal;
|
||||||
|
use crate::oidc::random_token;
|
||||||
|
|
||||||
|
/// How long a party's link works after it was made or last used.
|
||||||
|
pub const LIFETIME_DAYS: i64 = 30;
|
||||||
|
|
||||||
|
/// The most pieces a draft may have.
|
||||||
|
pub const MAX_PIECES: usize = 20_000;
|
||||||
|
|
||||||
|
/// The longest comment on a highlight, in characters.
|
||||||
|
pub const COMMENT_LIMIT: usize = 500;
|
||||||
|
|
||||||
|
/// Lanna Desk's side.
|
||||||
|
pub const US: &str = "us";
|
||||||
|
|
||||||
|
pub fn party_side(id: i64) -> String {
|
||||||
|
format!("party:{id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn party_of(side: &str) -> Option<i64> {
|
||||||
|
side.strip_prefix("party:")?.parse().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn side_ok(side: &str) -> bool {
|
||||||
|
side == US || party_of(side).is_some_and(|id| id > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- the pieces
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Op {
|
||||||
|
/// the text as agreed so far
|
||||||
|
Same,
|
||||||
|
/// added by a side, not taken in yet
|
||||||
|
Ins,
|
||||||
|
/// crossed out by a side, not taken out yet
|
||||||
|
Del,
|
||||||
|
/// highlighted by a side, maybe with a comment
|
||||||
|
Mark,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Op {
|
||||||
|
fn from_slug(s: &str) -> Option<Op> {
|
||||||
|
match s {
|
||||||
|
"same" => Some(Op::Same),
|
||||||
|
"ins" => Some(Op::Ins),
|
||||||
|
"del" => Some(Op::Del),
|
||||||
|
"mark" => Some(Op::Mark),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn slug(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Op::Same => "same",
|
||||||
|
Op::Ins => "ins",
|
||||||
|
Op::Del => "del",
|
||||||
|
Op::Mark => "mark",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the piece is part of the text as it stands.
|
||||||
|
fn standing(self) -> bool {
|
||||||
|
self != Op::Ins
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Piece {
|
||||||
|
pub op: Op,
|
||||||
|
pub text: String,
|
||||||
|
/// a highlight's comment; empty on every other piece
|
||||||
|
pub comment: String,
|
||||||
|
/// who made the change; empty on the agreed text
|
||||||
|
pub side: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn piece(op: Op, text: &str, comment: &str, side: &str) -> Piece {
|
||||||
|
Piece {
|
||||||
|
op,
|
||||||
|
text: text.to_string(),
|
||||||
|
comment: comment.to_string(),
|
||||||
|
side: side.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pieces of a text nobody has marked yet.
|
||||||
|
pub fn unmarked(text: &str) -> Vec<Piece> {
|
||||||
|
tidy(vec![piece(Op::Same, text, "", "")])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Joins neighbors of the same kind, side and comment, and drops empty
|
||||||
|
/// pieces. The editor does the same, so both number changes alike.
|
||||||
|
pub fn tidy(pieces: Vec<Piece>) -> Vec<Piece> {
|
||||||
|
let mut out: Vec<Piece> = Vec::with_capacity(pieces.len());
|
||||||
|
for p in pieces {
|
||||||
|
if p.text.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match out.last_mut() {
|
||||||
|
Some(l) if l.op == p.op && l.comment == p.comment && l.side == p.side => {
|
||||||
|
l.text.push_str(&p.text)
|
||||||
|
}
|
||||||
|
_ => out.push(p),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text as it stands: what is agreed, crossed out or highlighted.
|
||||||
|
pub fn base(pieces: &[Piece]) -> String {
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.op.standing())
|
||||||
|
.map(|p| p.text.as_str())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text with every change taken.
|
||||||
|
pub fn proposed(pieces: &[Piece]) -> String {
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.op != Op::Del)
|
||||||
|
.map(|p| p.text.as_str())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
const BROKEN: &str = "The draft did not arrive whole. Reload the page.";
|
||||||
|
|
||||||
|
/// Reads pieces as the editor sends them (`[["same", "text", "", ""], ...]`)
|
||||||
|
/// and checks their form; `check_save` then checks what changed.
|
||||||
|
pub fn parse(json: &str) -> Result<Vec<Piece>, &'static str> {
|
||||||
|
let value: serde_json::Value = serde_json::from_str(json).map_err(|_| BROKEN)?;
|
||||||
|
let items = value.as_array().ok_or(BROKEN)?;
|
||||||
|
if items.len() > MAX_PIECES {
|
||||||
|
return Err("The draft has too many separate marks; resolve some of them.");
|
||||||
|
}
|
||||||
|
let mut pieces = Vec::with_capacity(items.len());
|
||||||
|
for it in items {
|
||||||
|
let parts = it.as_array().ok_or(BROKEN)?;
|
||||||
|
let op = parts
|
||||||
|
.first()
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.and_then(Op::from_slug)
|
||||||
|
.ok_or(BROKEN)?;
|
||||||
|
let text = parts.get(1).and_then(|v| v.as_str()).ok_or(BROKEN)?;
|
||||||
|
let comment = parts.get(2).and_then(|v| v.as_str()).unwrap_or("").trim();
|
||||||
|
let side = parts.get(3).and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
if comment.chars().count() > COMMENT_LIMIT {
|
||||||
|
return Err("A comment is longer than 500 characters.");
|
||||||
|
}
|
||||||
|
match op {
|
||||||
|
Op::Same if !side.is_empty() => return Err(BROKEN),
|
||||||
|
Op::Ins | Op::Del | Op::Mark if !side_ok(side) => return Err(BROKEN),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
// typing brings no carriage returns, as no saved text has any
|
||||||
|
let text = if op == Op::Ins {
|
||||||
|
text.replace('\r', "")
|
||||||
|
} else {
|
||||||
|
text.to_string()
|
||||||
|
};
|
||||||
|
let comment = if op == Op::Mark { comment } else { "" };
|
||||||
|
pieces.push(piece(op, &text, comment, side));
|
||||||
|
}
|
||||||
|
let pieces = tidy(pieces);
|
||||||
|
if proposed(&pieces).chars().count() > legal::BODY_LIMIT {
|
||||||
|
return Err("The draft has grown too long.");
|
||||||
|
}
|
||||||
|
Ok(pieces)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What each character of the text as it stands is: agreed, or marked by
|
||||||
|
/// a side (with the comment).
|
||||||
|
fn standing_marks(pieces: &[Piece]) -> Vec<(Op, &str, &str)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for p in pieces.iter().filter(|p| p.op.standing()) {
|
||||||
|
for _ in p.text.chars() {
|
||||||
|
out.push((p.op, p.side.as_str(), p.comment.as_str()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The added pieces of the sides other than `side`, each with its place in
|
||||||
|
/// the text as it stands; neighbors of one side at one place joined.
|
||||||
|
fn others_added<'a>(pieces: &'a [Piece], side: &str) -> Vec<(usize, &'a str, String)> {
|
||||||
|
let mut at = 0;
|
||||||
|
let mut out: Vec<(usize, &str, String)> = Vec::new();
|
||||||
|
for p in pieces {
|
||||||
|
match p.op {
|
||||||
|
Op::Ins if p.side != side => match out.last_mut() {
|
||||||
|
Some((o, s, t)) if *o == at && *s == p.side => t.push_str(&p.text),
|
||||||
|
_ => out.push((at, &p.side, p.text.clone())),
|
||||||
|
},
|
||||||
|
Op::Ins => {}
|
||||||
|
_ => at += p.text.chars().count(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks a save by `side`: the text as it stands is unchanged, and every
|
||||||
|
/// mark that changed was that side's own, or becomes one.
|
||||||
|
pub fn check_save(old: &[Piece], new: &[Piece], side: &str) -> Result<(), &'static str> {
|
||||||
|
if base(old) != base(new) {
|
||||||
|
return Err(
|
||||||
|
"This save would change the text as it stands. Reload the page; your last few \
|
||||||
|
seconds of typing may be lost, sorry.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let (a, b) = (standing_marks(old), standing_marks(new));
|
||||||
|
for (o, n) in a.iter().zip(&b) {
|
||||||
|
if o != n {
|
||||||
|
let own = |m: &(Op, &str, &str)| m.0 == Op::Same || m.1 == side;
|
||||||
|
if !own(o) || !own(n) {
|
||||||
|
return Err("This save would change another side's marks. Reload the page.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if others_added(old, side) != others_added(new, side) {
|
||||||
|
return Err("This save would change what another side added. Reload the page.");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_json(pieces: &[Piece]) -> serde_json::Value {
|
||||||
|
serde_json::Value::Array(
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.map(|p| serde_json::json!([p.op.slug(), p.text, p.comment, p.side]))
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads stored pieces; they were checked when they were saved.
|
||||||
|
pub fn from_json(v: &serde_json::Value) -> Vec<Piece> {
|
||||||
|
v.as_array()
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(|it| {
|
||||||
|
let op = Op::from_slug(it.get(0)?.as_str()?)?;
|
||||||
|
let text = it.get(1)?.as_str()?;
|
||||||
|
let comment = it.get(2).and_then(|c| c.as_str()).unwrap_or("");
|
||||||
|
let side = it.get(3).and_then(|c| c.as_str()).unwrap_or("");
|
||||||
|
Some(piece(op, text, comment, side))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// JSON to put inside a `<script type="application/json">`: `<`, `>` and
|
||||||
|
/// `&` written as escapes, so no text can end the script.
|
||||||
|
pub fn script_json(v: &serde_json::Value) -> String {
|
||||||
|
v.to_string()
|
||||||
|
.replace('<', "\\u003c")
|
||||||
|
.replace('>', "\\u003e")
|
||||||
|
.replace('&', "\\u0026")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ the changes
|
||||||
|
|
||||||
|
/// A change: neighboring added and crossed-out pieces of one side. `n`
|
||||||
|
/// counts from 1 in the text's order.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Change {
|
||||||
|
pub n: usize,
|
||||||
|
pub side: String,
|
||||||
|
pub removed: String,
|
||||||
|
pub added: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which change each piece belongs to.
|
||||||
|
fn change_of(pieces: &[Piece]) -> Vec<Option<usize>> {
|
||||||
|
let mut n = 0;
|
||||||
|
let mut open: Option<&str> = None;
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.map(|p| match p.op {
|
||||||
|
Op::Ins | Op::Del => {
|
||||||
|
if open != Some(p.side.as_str()) {
|
||||||
|
n += 1;
|
||||||
|
open = Some(p.side.as_str());
|
||||||
|
}
|
||||||
|
Some(n)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
open = None;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn changes(pieces: &[Piece]) -> Vec<Change> {
|
||||||
|
let mut out: Vec<Change> = Vec::new();
|
||||||
|
for (p, c) in pieces.iter().zip(change_of(pieces)) {
|
||||||
|
let Some(n) = c else { continue };
|
||||||
|
if out.last().is_none_or(|l| l.n != n) {
|
||||||
|
out.push(Change {
|
||||||
|
n,
|
||||||
|
side: p.side.clone(),
|
||||||
|
removed: String::new(),
|
||||||
|
added: String::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let last = out.last_mut().expect("pushed above");
|
||||||
|
match p.op {
|
||||||
|
Op::Del => last.removed.push_str(&p.text),
|
||||||
|
_ => last.added.push_str(&p.text),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes change `n` in (`accept`: its added text becomes agreed text, its
|
||||||
|
/// crossed-out text goes) or drops it. None when there is no such change.
|
||||||
|
pub fn settle(pieces: &[Piece], n: usize, accept: bool) -> Option<(Vec<Piece>, Change)> {
|
||||||
|
let change = changes(pieces).into_iter().find(|c| c.n == n)?;
|
||||||
|
let mut out = Vec::with_capacity(pieces.len());
|
||||||
|
for (p, c) in pieces.iter().zip(change_of(pieces)) {
|
||||||
|
if c != Some(n) {
|
||||||
|
out.push(p.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let keep = match p.op {
|
||||||
|
Op::Ins => accept,
|
||||||
|
_ => !accept,
|
||||||
|
};
|
||||||
|
if keep {
|
||||||
|
out.push(piece(Op::Same, &p.text, "", ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some((tidy(out), change))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A highlight with its comment; `k` counts from 1.
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct Highlight {
|
||||||
|
pub k: usize,
|
||||||
|
pub side: String,
|
||||||
|
pub text: String,
|
||||||
|
pub comment: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn highlights(pieces: &[Piece]) -> Vec<Highlight> {
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.op == Op::Mark)
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, p)| Highlight {
|
||||||
|
k: i + 1,
|
||||||
|
side: p.side.clone(),
|
||||||
|
text: p.text.clone(),
|
||||||
|
comment: p.comment.clone(),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves highlight `k`: its text stays, the highlight goes.
|
||||||
|
pub fn resolve(pieces: &[Piece], k: usize) -> Option<(Vec<Piece>, Highlight)> {
|
||||||
|
let h = highlights(pieces).into_iter().find(|h| h.k == k)?;
|
||||||
|
let mut seen = 0;
|
||||||
|
let out = pieces
|
||||||
|
.iter()
|
||||||
|
.map(|p| {
|
||||||
|
if p.op == Op::Mark {
|
||||||
|
seen += 1;
|
||||||
|
if seen == k {
|
||||||
|
return piece(Op::Same, &p.text, "", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.clone()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Some((tidy(out), h))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------- the git view
|
||||||
|
|
||||||
|
/// A part of a line in the git view; `hl` marks the changed words.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Seg {
|
||||||
|
pub hl: bool,
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A line of the git view: a hunk's header (`hunk`), or a line kept,
|
||||||
|
/// taken out or added, with its numbers before and after.
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct GitLine {
|
||||||
|
pub op: &'static str,
|
||||||
|
pub old: Option<usize>,
|
||||||
|
pub new: Option<usize>,
|
||||||
|
pub segs: Vec<Seg>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lines_of(parts: Vec<(bool, &str)>) -> Vec<Vec<Seg>> {
|
||||||
|
let mut lines = vec![Vec::new()];
|
||||||
|
for (hl, text) in parts {
|
||||||
|
for (i, chunk) in text.split('\n').enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
lines.push(Vec::new());
|
||||||
|
}
|
||||||
|
if !chunk.is_empty() {
|
||||||
|
let line = lines.last_mut().expect("never empty");
|
||||||
|
match line.last_mut() {
|
||||||
|
Some(Seg { hl: h, text: t }) if *h == hl => t.push_str(chunk),
|
||||||
|
_ => line.push(Seg {
|
||||||
|
hl,
|
||||||
|
text: chunk.to_string(),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(segs: &[Seg]) -> String {
|
||||||
|
segs.iter().map(|s| s.text.as_str()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lines kept around a change, as `git diff` shows them.
|
||||||
|
const CONTEXT: usize = 3;
|
||||||
|
|
||||||
|
/// The text as it stands against the text with every change taken, as
|
||||||
|
/// `git diff --word-diff` would show it. None when too long to compare.
|
||||||
|
pub fn git_view(pieces: &[Piece]) -> Option<Vec<GitLine>> {
|
||||||
|
let old = lines_of(
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.op.standing())
|
||||||
|
.map(|p| (p.op == Op::Del, p.text.as_str()))
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
let new = lines_of(
|
||||||
|
pieces
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.op != Op::Del)
|
||||||
|
.map(|p| (p.op == Op::Ins, p.text.as_str()))
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
let old_text: Vec<String> = old.iter().map(|l| plain(l)).collect();
|
||||||
|
let new_text: Vec<String> = new.iter().map(|l| plain(l)).collect();
|
||||||
|
let diff = legal::diff(&old_text.join("\n"), &new_text.join("\n"))?;
|
||||||
|
let (mut i, mut j) = (0, 0);
|
||||||
|
let mut all = Vec::with_capacity(diff.len());
|
||||||
|
for d in diff {
|
||||||
|
all.push(match d.op {
|
||||||
|
"same" => {
|
||||||
|
i += 1;
|
||||||
|
j += 1;
|
||||||
|
GitLine {
|
||||||
|
op: "same",
|
||||||
|
old: Some(i),
|
||||||
|
new: Some(j),
|
||||||
|
segs: vec![Seg {
|
||||||
|
hl: false,
|
||||||
|
text: d.text,
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"removed" => {
|
||||||
|
i += 1;
|
||||||
|
GitLine {
|
||||||
|
op: "removed",
|
||||||
|
old: Some(i),
|
||||||
|
new: None,
|
||||||
|
segs: old.get(i - 1).cloned().unwrap_or_default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
j += 1;
|
||||||
|
GitLine {
|
||||||
|
op: "added",
|
||||||
|
old: None,
|
||||||
|
new: Some(j),
|
||||||
|
segs: new.get(j - 1).cloned().unwrap_or_default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let changed: Vec<usize> = all
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, l)| l.op != "same")
|
||||||
|
.map(|(k, _)| k)
|
||||||
|
.collect();
|
||||||
|
let near = |k: usize| {
|
||||||
|
changed
|
||||||
|
.iter()
|
||||||
|
.any(|&c| k + CONTEXT >= c && k <= c + CONTEXT)
|
||||||
|
};
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut shown_last = false;
|
||||||
|
for (k, l) in all.into_iter().enumerate() {
|
||||||
|
if near(k) {
|
||||||
|
if !shown_last {
|
||||||
|
out.push(GitLine {
|
||||||
|
op: "hunk",
|
||||||
|
old: l.old,
|
||||||
|
new: l.new,
|
||||||
|
segs: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.push(l);
|
||||||
|
shown_last = true;
|
||||||
|
} else {
|
||||||
|
shown_last = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------- the links
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
||||||
|
pub struct Link {
|
||||||
|
pub id: i64,
|
||||||
|
pub contract_id: i64,
|
||||||
|
pub party_id: i64,
|
||||||
|
pub csrf: String,
|
||||||
|
pub created_by: String,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub expires_at: DateTime<Utc>,
|
||||||
|
pub first_used_at: Option<DateTime<Utc>>,
|
||||||
|
pub last_used_at: Option<DateTime<Utc>>,
|
||||||
|
pub closed_at: Option<DateTime<Utc>>,
|
||||||
|
pub closed_by: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Link {
|
||||||
|
pub fn open(&self) -> bool {
|
||||||
|
self.closed_at.is_none() && self.expires_at > Utc::now()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const LINK_COLUMNS: &str = "id, contract_id, party_id, csrf, created_by, created_at, \
|
||||||
|
expires_at, first_used_at, last_used_at, closed_at, closed_by";
|
||||||
|
|
||||||
|
/// The link with this token, whatever its state.
|
||||||
|
pub async fn by_token(db: &PgPool, token: &str) -> Result<Option<Link>> {
|
||||||
|
if token.len() != 43
|
||||||
|
|| !token
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
{
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(sqlx::query_as(&format!(
|
||||||
|
"SELECT {LINK_COLUMNS} FROM review_links WHERE token_hash = $1"
|
||||||
|
))
|
||||||
|
.bind(crate::links::hash(token))
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn link(db: &PgPool, contract: i64, id: i64) -> Result<Option<Link>> {
|
||||||
|
Ok(sqlx::query_as(&format!(
|
||||||
|
"SELECT {LINK_COLUMNS} FROM review_links WHERE contract_id = $1 AND id = $2"
|
||||||
|
))
|
||||||
|
.bind(contract)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A contract's links, newest first, with the party's name.
|
||||||
|
pub async fn for_contract(db: &PgPool, contract: i64) -> Result<Vec<(Link, String)>> {
|
||||||
|
let ids: Vec<(i64, String)> = sqlx::query_as(
|
||||||
|
"SELECT l.id, p.name FROM review_links l JOIN contract_parties p ON p.id = l.party_id \
|
||||||
|
WHERE l.contract_id = $1 ORDER BY l.id DESC",
|
||||||
|
)
|
||||||
|
.bind(contract)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut out = Vec::with_capacity(ids.len());
|
||||||
|
for (id, name) in ids {
|
||||||
|
if let Some(l) = link(db, contract, id).await? {
|
||||||
|
out.push((l, name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new link for a party, closing their open one; returns it with its
|
||||||
|
/// token, which nothing keeps: the page that made it shows it once.
|
||||||
|
pub async fn invite(
|
||||||
|
conn: &mut PgConnection,
|
||||||
|
contract: i64,
|
||||||
|
party: i64,
|
||||||
|
by: &str,
|
||||||
|
) -> Result<(Link, String)> {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE review_links SET closed_at = now(), closed_by = $2 \
|
||||||
|
WHERE party_id = $1 AND closed_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(party)
|
||||||
|
.bind(by)
|
||||||
|
.execute(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
let token = random_token();
|
||||||
|
let l: Link = sqlx::query_as(&format!(
|
||||||
|
"INSERT INTO review_links (contract_id, party_id, token_hash, csrf, created_by, \
|
||||||
|
expires_at) VALUES ($1, $2, $3, $4, $5, now() + make_interval(days => $6)) \
|
||||||
|
RETURNING {LINK_COLUMNS}"
|
||||||
|
))
|
||||||
|
.bind(contract)
|
||||||
|
.bind(party)
|
||||||
|
.bind(crate::links::hash(&token))
|
||||||
|
.bind(random_token())
|
||||||
|
.bind(by)
|
||||||
|
.bind(LIFETIME_DAYS as i32)
|
||||||
|
.fetch_one(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
Ok((l, token))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notes a use of a link, which keeps it working for another
|
||||||
|
/// `LIFETIME_DAYS`.
|
||||||
|
pub async fn used(db: &PgPool, link: i64) -> Result<()> {
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE review_links SET first_used_at = COALESCE(first_used_at, now()), \
|
||||||
|
last_used_at = now(), \
|
||||||
|
expires_at = GREATEST(expires_at, now() + make_interval(days => $2)) WHERE id = $1",
|
||||||
|
)
|
||||||
|
.bind(link)
|
||||||
|
.bind(LIFETIME_DAYS as i32)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Closes a link; false when it was closed already.
|
||||||
|
pub async fn close(conn: &mut PgConnection, link: &Link, by: &str) -> Result<bool> {
|
||||||
|
Ok(sqlx::query(
|
||||||
|
"UPDATE review_links SET closed_at = now(), closed_by = $2 \
|
||||||
|
WHERE id = $1 AND closed_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(link.id)
|
||||||
|
.bind(by)
|
||||||
|
.execute(&mut *conn)
|
||||||
|
.await?
|
||||||
|
.rows_affected()
|
||||||
|
> 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const SENT: &str = "# 1. Term\nTwo years from signing.\n\n# 2. Fee\n10% of net receipts.";
|
||||||
|
const LABEL: &str = "party:7";
|
||||||
|
|
||||||
|
fn marked() -> Vec<Piece> {
|
||||||
|
tidy(vec![
|
||||||
|
piece(Op::Same, "# 1. Term\n", "", ""),
|
||||||
|
piece(Op::Del, "Two", "", LABEL),
|
||||||
|
piece(Op::Ins, "Three", "", LABEL),
|
||||||
|
piece(Op::Same, " years from signing.\n\n# 2. Fee\n", "", ""),
|
||||||
|
piece(Op::Mark, "10%", "Too low for us", US),
|
||||||
|
piece(Op::Same, " of net receipts.", "", ""),
|
||||||
|
piece(Op::Ins, "\n# 3. Territory", "", US),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_save_touches_only_the_savers_own_marks() {
|
||||||
|
let old = marked();
|
||||||
|
assert_eq!(base(&old), SENT);
|
||||||
|
// the label crosses out "signing" and adds a word: fine
|
||||||
|
let mut new = old.clone();
|
||||||
|
new[3] = piece(Op::Same, " years from ", "", "");
|
||||||
|
new.insert(4, piece(Op::Del, "signing", "", LABEL));
|
||||||
|
new.insert(5, piece(Op::Ins, "release", "", LABEL));
|
||||||
|
new.insert(6, piece(Op::Same, ".\n\n# 2. Fee\n", "", ""));
|
||||||
|
let new = tidy(new);
|
||||||
|
assert!(check_save(&old, &new, LABEL).is_ok());
|
||||||
|
// but not as us: those marks are the label's
|
||||||
|
assert!(check_save(&old, &new, US).is_err());
|
||||||
|
// the label cannot drop our highlight or our added line
|
||||||
|
let no_mark: Vec<Piece> = old
|
||||||
|
.iter()
|
||||||
|
.map(|p| {
|
||||||
|
if p.op == Op::Mark {
|
||||||
|
piece(Op::Same, &p.text, "", "")
|
||||||
|
} else {
|
||||||
|
p.clone()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert!(check_save(&old, &tidy(no_mark.clone()), LABEL).is_err());
|
||||||
|
assert!(check_save(&old, &tidy(no_mark), US).is_ok());
|
||||||
|
let no_line: Vec<Piece> = old[..old.len() - 1].to_vec();
|
||||||
|
assert!(check_save(&old, &no_line, LABEL).is_err());
|
||||||
|
assert!(check_save(&old, &no_line, US).is_ok());
|
||||||
|
// nobody changes the text as it stands
|
||||||
|
let mut sneaky = old.clone();
|
||||||
|
sneaky[0] = piece(Op::Same, "# 1. Duration\n", "", "");
|
||||||
|
assert!(check_save(&old, &sneaky, US).is_err());
|
||||||
|
// the form is checked
|
||||||
|
assert!(parse(r#"[["same", "x", "", "us"]]"#).is_err());
|
||||||
|
assert!(parse(r#"[["ins", "x", "", "someone"]]"#).is_err());
|
||||||
|
assert!(parse(r#"[["ins", "x", "", "party:3"]]"#).is_ok());
|
||||||
|
assert_eq!(parse(&to_json(&old).to_string()).unwrap(), old);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn changes_are_accepted_or_rejected_one_by_one() {
|
||||||
|
let p = marked();
|
||||||
|
let c = changes(&p);
|
||||||
|
assert_eq!(c.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
(c[0].removed.as_str(), c[0].added.as_str()),
|
||||||
|
("Two", "Three")
|
||||||
|
);
|
||||||
|
assert_eq!(c[0].side, LABEL);
|
||||||
|
let (a, _) = settle(&p, 1, true).unwrap();
|
||||||
|
assert!(base(&a).contains("Three years"));
|
||||||
|
assert_eq!(changes(&a).len(), 1);
|
||||||
|
let (r, _) = settle(&p, 1, false).unwrap();
|
||||||
|
assert_eq!(base(&r), SENT);
|
||||||
|
let (all, _) = settle(&a, 1, true).unwrap();
|
||||||
|
assert_eq!(base(&all), proposed(&p));
|
||||||
|
assert!(settle(&p, 3, true).is_none());
|
||||||
|
let (h, hl) = resolve(&p, 1).unwrap();
|
||||||
|
assert_eq!(hl.comment, "Too low for us");
|
||||||
|
assert!(highlights(&h).is_empty());
|
||||||
|
assert_eq!(base(&h), base(&p));
|
||||||
|
let j = script_json(&to_json(&[piece(Op::Ins, "</script>&", "", US)]));
|
||||||
|
assert!(!j.contains('<') && !j.contains('&'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_git_view_shows_the_changed_lines_with_their_words() {
|
||||||
|
let v = git_view(&marked()).unwrap();
|
||||||
|
assert_eq!(v[0].op, "hunk");
|
||||||
|
let removed = v.iter().find(|l| l.op == "removed").unwrap();
|
||||||
|
assert_eq!(removed.old, Some(2));
|
||||||
|
assert_eq!(
|
||||||
|
removed.segs[0],
|
||||||
|
Seg {
|
||||||
|
hl: true,
|
||||||
|
text: "Two".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
let added: Vec<String> = v
|
||||||
|
.iter()
|
||||||
|
.filter(|l| l.op == "added")
|
||||||
|
.map(|l| plain(&l.segs))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(added, ["Three years from signing.", "# 3. Territory"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
+119
-1
@@ -332,7 +332,7 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul
|
|||||||
.await?;
|
.await?;
|
||||||
let h = legal::head_of(t, rec).await?;
|
let h = legal::head_of(t, rec).await?;
|
||||||
legal::add_version(t, &h, "The label's first draft", RECORDING_V1, None, "seed").await?;
|
legal::add_version(t, &h, "The label's first draft", RECORDING_V1, None, "seed").await?;
|
||||||
legal::add_version(
|
let v2 = legal::add_version(
|
||||||
t,
|
t,
|
||||||
&h,
|
&h,
|
||||||
"Our changes for the artist: term, royalties, reversion",
|
"Our changes for the artist: term, royalties, reversion",
|
||||||
@@ -341,6 +341,7 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul
|
|||||||
"seed",
|
"seed",
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
label_draft(t, &h, &v2).await?;
|
||||||
// the management deal: in force, notice day near
|
// the management deal: in force, notice day near
|
||||||
let mut v = contract(
|
let mut v = contract(
|
||||||
"Management agreement",
|
"Management agreement",
|
||||||
@@ -571,6 +572,123 @@ pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Resul
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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::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 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,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let body = &v2.body;
|
||||||
|
let mut pieces = Vec::new();
|
||||||
|
let mut at = 0;
|
||||||
|
for (words, op, then, side) in edits {
|
||||||
|
let i = at
|
||||||
|
+ body[at..]
|
||||||
|
.find(words)
|
||||||
|
.expect("the demo text has these words");
|
||||||
|
pieces.push(piece(Op::Same, &body[at..i], "", ""));
|
||||||
|
match op {
|
||||||
|
Op::Mark => pieces.push(piece(Op::Mark, words, then, side)),
|
||||||
|
_ => {
|
||||||
|
pieces.push(piece(Op::Del, words, "", side));
|
||||||
|
pieces.push(piece(Op::Ins, then, "", side));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at = i + words.len();
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
// 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,
|
||||||
|
&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?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Originals in our care (phase 12): the first demo person's passport out
|
/// Originals in our care (phase 12): the first demo person's passport out
|
||||||
/// at Immigration, a title deed and a house registration held, a company
|
/// at Immigration, a title deed and a house registration held, a company
|
||||||
/// certificate already returned.
|
/// certificate already returned.
|
||||||
|
|||||||
+1
-1
@@ -1093,7 +1093,7 @@ fn drawing(f: &Fields) -> Result<Option<Vec<u8>>, &'static str> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The client's address as the proxy in front of the app forwarded it.
|
/// The client's address as the proxy in front of the app forwarded it.
|
||||||
fn client_ip(headers: &axum::http::HeaderMap) -> String {
|
pub(crate) fn client_ip(headers: &axum::http::HeaderMap) -> String {
|
||||||
headers
|
headers
|
||||||
.get("x-forwarded-for")
|
.get("x-forwarded-for")
|
||||||
.and_then(|v| v.to_str().ok())
|
.and_then(|v| v.to_str().ok())
|
||||||
|
|||||||
@@ -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())
|
||||||
|
}
|
||||||
+12
-1
@@ -876,6 +876,17 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let live_parties = parties.iter().filter(|p| p.removed.is_none()).count();
|
let live_parties = parties.iter().filter(|p| p.removed.is_none()).count();
|
||||||
|
let text_versions: Vec<(String, String)> = all
|
||||||
|
.iter()
|
||||||
|
.filter(|v| !v.body.is_empty())
|
||||||
|
.map(|v| {
|
||||||
|
(
|
||||||
|
v.version.to_string(),
|
||||||
|
format!("Version {}: {}", v.version, v.note),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let draft = super::drafts::card(st, id).await?;
|
||||||
let entries = journal_views(journal::list(&st.db, None, Some(id), 50).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")
|
let client_name: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1")
|
||||||
.bind(head.client_id)
|
.bind(head.client_id)
|
||||||
@@ -896,7 +907,7 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f
|
|||||||
form.status,
|
form.status,
|
||||||
context! {
|
context! {
|
||||||
id, shown, versions, papers, entries, client_name, diff, compare,
|
id, shown, versions, papers, entries, client_name, diff, compare,
|
||||||
parties, live_parties,
|
parties, live_parties, text_versions, draft,
|
||||||
party => form.party,
|
party => form.party,
|
||||||
party_errors => form.party_errors,
|
party_errors => form.party_errors,
|
||||||
check => form.check,
|
check => form.check,
|
||||||
|
|||||||
+46
-1
@@ -7,6 +7,7 @@ pub mod client;
|
|||||||
pub mod companies;
|
pub mod companies;
|
||||||
pub mod dashboard;
|
pub mod dashboard;
|
||||||
pub mod documents;
|
pub mod documents;
|
||||||
|
pub mod drafts;
|
||||||
pub mod legal;
|
pub mod legal;
|
||||||
pub mod links;
|
pub mod links;
|
||||||
pub mod notifications;
|
pub mod notifications;
|
||||||
@@ -334,6 +335,15 @@ pub fn router(st: Arc<AppState>) -> Router {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// The other side's review page: open without a login, it checks its
|
||||||
|
// link. The marked-up text of a long Thai contract urlencodes to a few
|
||||||
|
// megabytes.
|
||||||
|
r = r.route("/r/{token}", get(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.
|
// The client's pages: open without a login, each checks its link.
|
||||||
r = r
|
r = r
|
||||||
.route("/c/{token}", get(client::overview))
|
.route("/c/{token}", get(client::overview))
|
||||||
@@ -443,6 +453,20 @@ pub fn router(st: Arc<AppState>) -> Router {
|
|||||||
post(l::remove_party),
|
post(l::remove_party),
|
||||||
)
|
)
|
||||||
.route("/conflicts", get(l::conflicts_page))
|
.route("/conflicts", get(l::conflicts_page))
|
||||||
|
.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(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", get(originals::list).post(originals::create))
|
||||||
.route("/originals/new", get(originals::new))
|
.route("/originals/new", get(originals::new))
|
||||||
.route("/originals/{code}", get(originals::show))
|
.route("/originals/{code}", get(originals::show))
|
||||||
@@ -494,8 +518,13 @@ fn is_public(path: &str) -> bool {
|
|||||||
| "/favicon.ico"
|
| "/favicon.ico"
|
||||||
) || path.starts_with("/static/")
|
) || path.starts_with("/static/")
|
||||||
|| path.starts_with("/c/")
|
|| path.starts_with("/c/")
|
||||||
|
|| path.starts_with("/r/")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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;
|
||||||
|
|
||||||
/// Lets a request through with its user, or sends the browser to the login.
|
/// Lets a request through with its user, or sends the browser to the login.
|
||||||
async fn gate(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
async fn gate(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||||
if is_public(req.uri().path()) {
|
if is_public(req.uri().path()) {
|
||||||
@@ -578,8 +607,14 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
|
|||||||
)
|
)
|
||||||
.into_response();
|
.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 (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,
|
Ok(b) => b,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
return (StatusCode::PAYLOAD_TOO_LARGE, "The form is too large.").into_response();
|
return (StatusCode::PAYLOAD_TOO_LARGE, "The form is too large.").into_response();
|
||||||
@@ -611,6 +646,16 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
|
|||||||
|
|
||||||
/// The addresses that take uploads: `/people/{id}/documents`,
|
/// The addresses that take uploads: `/people/{id}/documents`,
|
||||||
/// `/companies/{id}/documents` and a contract's `/contracts/{id}/versions`.
|
/// `/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 {
|
fn is_upload(path: &str) -> bool {
|
||||||
let parts: Vec<&str> = path.split('/').collect();
|
let parts: Vec<&str> = path.split('/').collect();
|
||||||
matches!(
|
matches!(
|
||||||
|
|||||||
+407
@@ -2198,3 +2198,410 @@ details.move[open] .mini {
|
|||||||
.form + .tblwrap {
|
.form + .tblwrap {
|
||||||
margin-top: 18px;
|
margin-top: 18px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- phase 13: the review by the other side */
|
||||||
|
.rvtext {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
font-size: 15.5px;
|
||||||
|
line-height: 1.7;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--field);
|
||||||
|
}
|
||||||
|
.rvedit {
|
||||||
|
min-height: 240px;
|
||||||
|
max-height: 70vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
outline: none;
|
||||||
|
caret-color: var(--fg);
|
||||||
|
}
|
||||||
|
.rvedit:focus {
|
||||||
|
border-color: var(--stroke);
|
||||||
|
box-shadow: 0 0 0 3px var(--accent-s);
|
||||||
|
}
|
||||||
|
.rvtext ins,
|
||||||
|
.rvchanges ins {
|
||||||
|
text-decoration: none;
|
||||||
|
color: var(--ok);
|
||||||
|
background: var(--ok-s);
|
||||||
|
border-bottom: 2px solid var(--ok);
|
||||||
|
}
|
||||||
|
.rvtext del,
|
||||||
|
.rvchanges del {
|
||||||
|
color: var(--bad);
|
||||||
|
background: var(--bad-s);
|
||||||
|
text-decoration: line-through;
|
||||||
|
text-decoration-thickness: 2px;
|
||||||
|
}
|
||||||
|
.rvtext mark,
|
||||||
|
.rvhl mark,
|
||||||
|
.rvtools mark {
|
||||||
|
color: inherit;
|
||||||
|
background: color-mix(in srgb, #f5c000 38%, transparent);
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
||||||
|
.rvtext mark[title] {
|
||||||
|
border-bottom: 2px dotted var(--label);
|
||||||
|
}
|
||||||
|
.rvtools mark,
|
||||||
|
.rvtools del {
|
||||||
|
padding: 0 2px;
|
||||||
|
}
|
||||||
|
.rvc {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--label);
|
||||||
|
font-style: italic;
|
||||||
|
margin: 0 4px;
|
||||||
|
}
|
||||||
|
.rvc::before {
|
||||||
|
content: "\2190 ";
|
||||||
|
}
|
||||||
|
.rvn {
|
||||||
|
display: inline-block;
|
||||||
|
min-width: 1.5em;
|
||||||
|
padding: 0 4px;
|
||||||
|
margin-right: 2px;
|
||||||
|
font: 600 11px/1.5 var(--sans);
|
||||||
|
text-align: center;
|
||||||
|
color: var(--on-pri);
|
||||||
|
background: var(--pri);
|
||||||
|
border-radius: 8px;
|
||||||
|
vertical-align: 0.35em;
|
||||||
|
}
|
||||||
|
.rvtools {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
margin: 0 0 10px;
|
||||||
|
}
|
||||||
|
.rvtools .rvcomment {
|
||||||
|
flex: 1 1 220px;
|
||||||
|
min-width: 0;
|
||||||
|
width: auto;
|
||||||
|
padding-top: 5px;
|
||||||
|
padding-bottom: 5px;
|
||||||
|
}
|
||||||
|
.rvchanges {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0 0 12px;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.rvchanges li {
|
||||||
|
padding: 8px 0;
|
||||||
|
border-bottom: 1px dashed var(--line);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.rvchanges label.check {
|
||||||
|
font-weight: 400;
|
||||||
|
cursor: pointer;
|
||||||
|
align-items: baseline;
|
||||||
|
}
|
||||||
|
.rvchanges label.check input {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.rvchanges .rvn {
|
||||||
|
vertical-align: baseline;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.rvchange {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.rvhl {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
}
|
||||||
|
.rvhl li {
|
||||||
|
padding: 4px 0;
|
||||||
|
}
|
||||||
|
.rvrounds {
|
||||||
|
margin: 6px 0 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
}
|
||||||
|
.rvrounds li {
|
||||||
|
padding: 2px 0;
|
||||||
|
}
|
||||||
|
.rvmsg {
|
||||||
|
border-left: 3px solid var(--label);
|
||||||
|
padding: 4px 0 4px 12px;
|
||||||
|
}
|
||||||
|
.gitdiff {
|
||||||
|
font: 13.5px/1.55 var(--mono);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.gitdiff .gl {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 3.2em 3.2em 1fr;
|
||||||
|
}
|
||||||
|
.gitdiff .gn {
|
||||||
|
padding: 0 6px;
|
||||||
|
text-align: right;
|
||||||
|
color: var(--mute);
|
||||||
|
border-right: 1px solid var(--line);
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.gitdiff .gt {
|
||||||
|
padding: 0 10px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.gitdiff .gs {
|
||||||
|
display: inline-block;
|
||||||
|
width: 1.2em;
|
||||||
|
color: var(--mute);
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
.gitdiff .removed {
|
||||||
|
background: var(--bad-s);
|
||||||
|
}
|
||||||
|
.gitdiff .added {
|
||||||
|
background: var(--ok-s);
|
||||||
|
}
|
||||||
|
.gitdiff .removed b {
|
||||||
|
font-weight: inherit;
|
||||||
|
background: color-mix(in srgb, var(--bad) 30%, transparent);
|
||||||
|
text-decoration: line-through;
|
||||||
|
}
|
||||||
|
.gitdiff .added b {
|
||||||
|
font-weight: inherit;
|
||||||
|
background: color-mix(in srgb, var(--ok) 32%, transparent);
|
||||||
|
}
|
||||||
|
.gitdiff .hunk {
|
||||||
|
color: var(--label);
|
||||||
|
background: var(--accent-s);
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.gitdiff .gl {
|
||||||
|
grid-template-columns: 2.4em 2.4em 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- 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);
|
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
|
// a label's Print button
|
||||||
document.querySelectorAll("[data-print]").forEach(function (b) {
|
document.querySelectorAll("[data-print]").forEach(function (b) {
|
||||||
b.addEventListener("click", function () {
|
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);
|
||||||
|
})();
|
||||||
@@ -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>
|
||||||
+4
-1
@@ -17,7 +17,10 @@
|
|||||||
{% include "_mark.html" %}
|
{% include "_mark.html" %}
|
||||||
<span class="nm">Lanna Desk</span><span class="sub">Back office</span>
|
<span class="nm">Lanna Desk</span><span class="sub">Back office</span>
|
||||||
</a>
|
</a>
|
||||||
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
<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>
|
</header>
|
||||||
<div class="app">
|
<div class="app">
|
||||||
<aside class="side">
|
<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>
|
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
||||||
</header>
|
</header>
|
||||||
<main class="cmain" id="main">
|
<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 %}
|
{% 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 %}
|
{% 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>
|
</main>
|
||||||
|
|||||||
@@ -74,6 +74,36 @@
|
|||||||
</details>
|
</details>
|
||||||
<datalist id="roles">{% for r in roles %}<option value="{{ r }}"></option>{% endfor %}</datalist>
|
<datalist id="roles">{% for r in roles %}<option value="{{ r }}"></option>{% endfor %}</datalist>
|
||||||
</section>
|
</section>
|
||||||
|
<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 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>
|
||||||
|
{% 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 %}
|
{% if reading %}
|
||||||
<section class="card" id="reading">
|
<section class="card" id="reading">
|
||||||
<header><h2>{% if compare %}Version {{ reading }} against version {{ before }}{% else %}Version {{ reading }}{% endif %}{% if reading_note %}: {{ reading_note }}{% endif %}</h2>
|
<header><h2>{% if compare %}Version {{ reading }} against version {{ before }}{% else %}Version {{ reading }}{% endif %}{% if reading_note %}: {{ reading_note }}{% endif %}</h2>
|
||||||
|
|||||||
@@ -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 %}
|
||||||
+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);
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ mod companies;
|
|||||||
mod deadlines;
|
mod deadlines;
|
||||||
mod demo;
|
mod demo;
|
||||||
mod documents;
|
mod documents;
|
||||||
|
mod drafts;
|
||||||
mod fuzz_cases;
|
mod fuzz_cases;
|
||||||
mod garage;
|
mod garage;
|
||||||
mod legal;
|
mod legal;
|
||||||
|
|||||||
@@ -101,7 +101,26 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
// 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![
|
let mut pages = vec![
|
||||||
|
(
|
||||||
|
format!("/contracts/{draft_contract}/draft"),
|
||||||
|
"The shared draft for".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(),
|
"/originals".to_string(),
|
||||||
"Chiang Mai Immigration".to_string(),
|
"Chiang Mai Immigration".to_string(),
|
||||||
|
|||||||
Reference in new issue
Block a user