diff --git a/docs/PLAN.md b/docs/PLAN.md index 1fbab6d..fe70ee0 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -246,6 +246,7 @@ dark at desktop and phone width, a commit and a push. | 8 | Reminders by Matrix room message and by email | | | 9 | The legal practice: lawyers, clients (Thai and foreign, people and organizations), general and artist contracts with versions that never change, paper copies with ids and places, the journal as a hash-chained ledger | built 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 | step 1 built Nov 22, 2026 | | later | Thai user interface, agency cases and fees, other visa categories' packs | | ### Phase 1: app, login, people @@ -662,6 +663,38 @@ person has its client with the same name and contact. room for finer access later (a client's team of lawyers, a role per section), so no page should assume more than the queries enforce. +### Phase 11: the conflict check and the journal's anchor + +**Step 1 (built November 22, 2026).** A contract's other side was one line +of text. Now each other party is a row (`contract_parties`, migration 0010) +with its names in English and Thai, an ID, passport or registration number +and its role; the old line became the first party. A party is never +deleted or rewritten: taking it off marks it removed, and adding and +removing are in the journal. + +The conflict check (`src/conflicts.rs`) looks for a name or number among +the clients, the other parties, the visa people and the employers. Names +match regardless of case, word order, punctuation and company words in +English and Thai, or when every word of the shorter name, at least two, is +in the longer one; numbers on their letters and digits. What a match means +depends on who is checked: + +- a new party that is a client, a visa client or an employer: a conflict; +- a new or renamed client that was on the other side of a contract: a + conflict; one with a client's name or number: perhaps the same client; +- everything else (the same party in another contract, a client who also + has a visa record): a note. + +A conflict or a possible duplicate stops the save until a lawyer ticks +that they looked at the matches, with what they checked; the matches and +the note go into the journal entry of the client or party. A check without +a match is noted too. `/conflicts` runs the check alone before a first +meeting and saves nothing. + +**Step 2 (next).** Once a day the app sends the journal's last entry +number and hash outside the server (email, a Matrix room), so a journal +rebuilt by someone with database access no longer matches the copies. + ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay diff --git a/migrations/0010_parties.sql b/migrations/0010_parties.sql new file mode 100644 index 0000000..2ea8813 --- /dev/null +++ b/migrations/0010_parties.sql @@ -0,0 +1,66 @@ +-- Lanna Desk, phase 11, step 1: the other parties of a contract, for the +-- conflict check (docs/PLAN.md "Phase 11"). +-- +-- A contract had its other side as one line of text. Now each other party +-- is a row with its names in English and Thai and its ID, registration or +-- passport number, so the conflict check can find it again when the same +-- name or number comes back as a client. A contract can have several: the +-- label and the publisher, the venue and the promoter. +-- +-- A party is never deleted: taking one off a contract marks it removed, +-- and both the adding and the removing are in the journal. + +CREATE TABLE contract_parties ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL REFERENCES contracts (id), + name TEXT NOT NULL CHECK (name <> ''), + name_th TEXT NOT NULL DEFAULT '', + -- a Thai ID number, a passport number or a registration number, as + -- given; the check compares its letters and digits only + id_no TEXT NOT NULL DEFAULT '', + -- what the party is in the contract: label, venue, landlord, employer + role TEXT NOT NULL DEFAULT '', + added_by TEXT NOT NULL, + added_at TIMESTAMPTZ NOT NULL DEFAULT now(), + removed_by TEXT, + removed_at TIMESTAMPTZ, + CHECK ((removed_at IS NULL) = (removed_by IS NULL)) +); +CREATE INDEX contract_parties_contract ON contract_parties (contract_id); + +CREATE FUNCTION contract_parties_kept() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'a party stays on record: mark it removed'; + END IF; + IF NEW.contract_id <> OLD.contract_id OR NEW.name <> OLD.name + OR NEW.name_th <> OLD.name_th OR NEW.id_no <> OLD.id_no + OR NEW.role <> OLD.role OR NEW.added_by <> OLD.added_by + OR NEW.added_at <> OLD.added_at OR OLD.removed_at IS NOT NULL THEN + RAISE EXCEPTION 'a party only gets removed: add a new one for a change'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER contract_parties_no_change +BEFORE UPDATE OR DELETE ON contract_parties +FOR EACH ROW EXECUTE FUNCTION contract_parties_kept(); + +-- The one line each contract had becomes its first party, added by whoever +-- opened the contract. +INSERT INTO contract_parties (contract_id, name, added_by, added_at) +SELECT id, counterparty, CASE WHEN created_by = '' THEN 'migration' ELSE created_by END, created_at +FROM contracts WHERE counterparty <> '' ORDER BY id; + +ALTER TABLE contracts DROP COLUMN counterparty; + +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' + ) +); diff --git a/src/audit.rs b/src/audit.rs index fd8e423..2b86625 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -74,6 +74,7 @@ pub enum Entity { Contract, ContractVersion, PaperCopy, + ContractParty, } impl Entity { @@ -100,6 +101,7 @@ impl Entity { Entity::Contract => "contract", Entity::ContractVersion => "contract-version", Entity::PaperCopy => "paper-copy", + Entity::ContractParty => "contract-party", } } } diff --git a/src/conflicts.rs b/src/conflicts.rs new file mode 100644 index 0000000..8c1f32b --- /dev/null +++ b/src/conflicts.rs @@ -0,0 +1,477 @@ +//! The conflict check (phase 11): before Lanna Desk takes on a client, or +//! writes down who is on the other side of a contract, the app looks for +//! the same name or number among everyone it already works for or has +//! worked against: the clients, the other parties of the contracts, the +//! people on the visa side and the employers. +//! +//! Names match without regard to case, word order, punctuation or the +//! company words around them ("Demo Records Co., Ltd." is "Demo Records", +//! "บริษัท เดโม เรคคอร์ดส จำกัด" is "เดโม เรคคอร์ดส"), and when all the words of +//! the shorter name, at least two, are in the longer ("Erika Mustermann" +//! and "MUSTERMANN, Erika Maria"). Numbers match on their letters and +//! digits only. The check finds candidates; a lawyer decides, and the +//! decision goes into the journal with what was found. + +use std::collections::BTreeSet; + +use anyhow::Result; +use serde::Serialize; +use sqlx::PgPool; + +/// Words around a name that say what kind of thing it is, not which. +const COMPANY_WORDS: &[&str] = &[ + "co", + "company", + "ltd", + "limited", + "inc", + "incorporated", + "corp", + "corporation", + "llc", + "plc", + "gmbh", + "public", + "partnership", + "the", + "and", + "mr", + "mrs", + "ms", + "miss", + "dr", +]; + +/// The same in Thai, written into the name without spaces: the longer +/// first, so "ห้างหุ้นส่วนจำกัด" goes as a whole. +const THAI_COMPANY_WORDS: &[&str] = &[ + "ห้างหุ้นส่วนจำกัด", + "ห้างหุ้นส่วนสามัญ", + "ห้างหุ้นส่วน", + "บริษัท", + "จำกัด", + "มหาชน", + "หจก", + "บจก", + "บมจ", +]; + +/// Titles in front of a Thai person's name. +const THAI_TITLES: &[&str] = &["นางสาว", "นาย", "นาง", "น.ส."]; + +fn is_thai(c: char) -> bool { + ('\u{0E00}'..='\u{0E7F}').contains(&c) +} + +/// The words of a name that tell it apart, in no order. +pub fn words(name: &str) -> BTreeSet { + let mut s = name.trim().to_lowercase(); + for t in THAI_TITLES { + if let Some(rest) = s.strip_prefix(t) { + s = rest.to_string(); + break; + } + } + for w in THAI_COMPANY_WORDS { + s = s.replace(w, " "); + } + let cleaned: String = s + .chars() + .map(|c| { + if c.is_alphanumeric() || is_thai(c) { + c + } else { + ' ' + } + }) + .collect(); + cleaned + .split_whitespace() + .filter(|w| !COMPANY_WORDS.contains(w)) + .map(str::to_string) + .collect() +} + +/// Whether two names are the same name, as the check reads them. +pub fn same_name(a: &str, b: &str) -> bool { + let (a, b) = (words(a), words(b)); + if a.is_empty() || b.is_empty() { + return false; + } + if a == b { + return true; + } + let (short, long) = if a.len() <= b.len() { + (&a, &b) + } else { + (&b, &a) + }; + short.len() >= 2 && short.is_subset(long) +} + +/// A number as compared: its letters and digits, in capitals. Too short a +/// number says nothing, so it gives None. +pub fn number(s: &str) -> Option { + let n: String = s + .chars() + .filter(|c| c.is_ascii_alphanumeric()) + .collect::() + .to_uppercase(); + (n.len() >= 5).then_some(n) +} + +/// What the check looks for. +#[derive(Debug, Default)] +pub struct Probe { + pub names: Vec, + pub numbers: Vec, +} + +impl Probe { + pub fn is_empty(&self) -> bool { + self.names.iter().all(|n| n.trim().is_empty()) + && self.numbers.iter().all(|n| number(n).is_none()) + } +} + +/// Who is being checked: a client (new, or one already on record), a +/// party for a contract of a client, or a name looked up before anyone is +/// taken on. +#[derive(Clone, Copy, Debug)] +pub enum For { + Client(Option), + Party { contract: i64, client: i64 }, + Search, +} + +/// One match. +#[derive(Clone, Debug, Serialize)] +pub struct Hit { + /// "conflict": Lanna Desk would act against someone it works for, or + /// for someone it acted against; "same": the same client twice; "note": + /// worth knowing, no conflict by itself. + pub level: &'static str, + pub what: String, + pub name: String, + pub href: String, + /// "same name", "same number 0105569000001" + pub why: String, + /// What it means for this check, in a sentence. + pub means: String, +} + +/// Whether any match must be cleared by a lawyer before saving. +pub fn needs_clearing(hits: &[Hit]) -> bool { + hits.iter().any(|h| h.level != "note") +} + +/// The check as the journal states it. +pub fn summary(hits: &[Hit], cleared: &str) -> String { + if hits.is_empty() { + return "Conflict check: no match.".into(); + } + let list: Vec = hits + .iter() + .map(|h| format!("{} {} ({})", h.what.to_lowercase(), h.name, h.why)) + .collect(); + let n = hits.len(); + let mut s = format!( + "Conflict check: {n} match{}: {}.", + if n == 1 { "" } else { "es" }, + list.join("; ") + ); + if needs_clearing(hits) { + if cleared.trim().is_empty() { + s.push_str(" Cleared: checked, no conflict."); + } else { + s.push_str(&format!(" Cleared: {}", cleared.trim())); + if !s.ends_with('.') { + s.push('.'); + } + } + } + s +} + +/// Why a candidate matches the probe, if it does. +fn why(probe: &Probe, names: &[&str], numbers: &[&str]) -> Option { + for n in numbers.iter().filter_map(|n| number(n)) { + if probe + .numbers + .iter() + .filter_map(|p| number(p)) + .any(|p| p == n) + { + return Some(format!("same number {n}")); + } + } + for c in names.iter().filter(|c| !c.trim().is_empty()) { + if probe.names.iter().any(|p| same_name(p, c)) { + return Some(format!("same name as {c}")); + } + } + None +} + +#[derive(sqlx::FromRow)] +struct ClientRow { + id: i64, + name: String, + name_th: String, + known_as: String, + thai_id: String, + passport_no: String, + registration_no: String, + status: String, +} + +#[derive(sqlx::FromRow)] +struct PartyRow { + name: String, + name_th: String, + id_no: String, + contract_id: i64, + code: String, + client_id: i64, + client: String, +} + +#[derive(sqlx::FromRow)] +struct PersonRow { + id: i64, + name: String, + given: String, + passports: String, +} + +#[derive(sqlx::FromRow)] +struct CompanyRow { + id: i64, + name: String, + name_th: String, + registration_no: String, +} + +/// Every match for the probe. The record being checked is left out of its +/// own matches. +pub async fn check(db: &PgPool, probe: &Probe, who: For) -> Result> { + let mut hits = Vec::new(); + if probe.is_empty() { + return Ok(hits); + } + let clients: Vec = sqlx::query_as( + "SELECT id, name, name_th, known_as, thai_id, passport_no, registration_no, status \ + FROM clients ORDER BY id", + ) + .fetch_all(db) + .await?; + for c in clients { + if let For::Client(Some(me)) = who + && me == c.id + { + continue; + } + let Some(why) = why( + probe, + &[&c.name, &c.name_th, &c.known_as], + &[&c.thai_id, &c.passport_no, &c.registration_no], + ) else { + continue; + }; + let former = if c.status == "former" { "former " } else { "" }; + let (level, means) = match who { + For::Party { client, .. } if client == c.id => ( + "conflict", + "This is the contract's own client: a client cannot be the other side of its own contract." + .to_string(), + ), + For::Party { .. } => ( + "conflict", + format!( + "Lanna Desk acts for this {former}client: this contract would put it on the other side." + ), + ), + For::Client(_) => ( + "same", + format!("Perhaps the same {former}client: add to that record instead of a second one."), + ), + For::Search => ("note", format!("A {former}client of Lanna Desk.")), + }; + hits.push(Hit { + level, + what: "Client".into(), + name: c.name, + href: format!("/clients/{}", c.id), + why, + means, + }); + } + let parties: Vec = sqlx::query_as( + "SELECT p.name, p.name_th, p.id_no, p.contract_id, c.code, c.client_id, cl.name AS client \ + FROM contract_parties p JOIN contracts c ON c.id = p.contract_id \ + JOIN clients cl ON cl.id = c.client_id \ + WHERE p.removed_at IS NULL ORDER BY p.id", + ) + .fetch_all(db) + .await?; + for p in parties { + if let For::Party { contract, .. } = who + && contract == p.contract_id + { + continue; + } + let Some(why) = why(probe, &[&p.name, &p.name_th], &[&p.id_no]) else { + continue; + }; + let (level, means) = match who { + For::Client(_) => ( + "conflict", + format!( + "The other side of {} for {}: Lanna Desk acted against them.", + p.code, p.client + ), + ), + For::Party { client, .. } if client == p.client_id => ( + "note", + format!("Also the other party of {} for the same client.", p.code), + ), + For::Party { .. } => ( + "note", + format!("Also the other party of {} for {}.", p.code, p.client), + ), + For::Search => ( + "note", + format!("The other party of {} for {}.", p.code, p.client), + ), + }; + hits.push(Hit { + level, + what: format!("Other party in {}", p.code), + name: p.name, + href: format!("/contracts/{}#parties", p.contract_id), + why, + means, + }); + } + let people: Vec = sqlx::query_as( + "SELECT p.id, p.surname AS name, concat_ws(' ', p.first_name, p.middle_name) AS given, \ + COALESCE((SELECT string_agg(number, ' ') FROM passports WHERE person_id = p.id), '') \ + AS passports FROM people p ORDER BY p.id", + ) + .fetch_all(db) + .await?; + for p in people { + let full = format!("{} {}", p.given, p.name); + let numbers: Vec<&str> = p.passports.split(' ').collect(); + let Some(why) = why(probe, &[&full], &numbers) else { + continue; + }; + let shown = format!("{}, {}", p.name, p.given.trim()); + let (level, means) = match who { + For::Party { .. } => ( + "conflict", + "A visa client of Lanna Desk: this contract would put them on the other side." + .to_string(), + ), + _ => ("note", "Has a visa record at Lanna Desk.".to_string()), + }; + hits.push(Hit { + level, + what: "Visa client".into(), + name: shown, + href: format!("/people/{}", p.id), + why, + means, + }); + } + let companies: Vec = + sqlx::query_as("SELECT id, name, name_th, registration_no FROM companies ORDER BY id") + .fetch_all(db) + .await?; + for c in companies { + let Some(why) = why(probe, &[&c.name, &c.name_th], &[&c.registration_no]) else { + continue; + }; + let (level, means) = match who { + For::Party { .. } => ( + "conflict", + "An employer Lanna Desk works for on the visa side: this contract would put it on the other side." + .to_string(), + ), + _ => ("note", "An employer on the visa side.".to_string()), + }; + hits.push(Hit { + level, + what: "Employer".into(), + name: c.name, + href: format!("/companies/{}", c.id), + why, + means, + }); + } + // the ones that need a decision first + hits.sort_by_key(|h| match h.level { + "conflict" => 0, + "same" => 1, + _ => 2, + }); + Ok(hits) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn company_words_and_order_do_not_count() { + assert!(same_name("Demo Records Co., Ltd.", "demo records")); + assert!(same_name("MUSTERMANN, Erika", "Erika Mustermann")); + assert!(same_name("Erika Mustermann", "MUSTERMANN, Erika Maria")); + assert!(same_name( + "บริษัท เดโม เรคคอร์ดส จำกัด", + "บริษัทเดโม เรคคอร์ดสจำกัด" + )); + assert!(same_name("นายสมชาย ใจดี", "สมชาย ใจดี")); + assert!(same_name("The Blue Hour Band", "Blue Hour Band Ltd")); + } + + #[test] + fn one_word_matches_only_itself() { + assert!(same_name("Somchai", "somchai")); + assert!(!same_name("Records", "Demo Records")); + assert!(!same_name("Demo Festival", "Demo Records")); + assert!(!same_name("Co., Ltd.", "Ltd"), "nothing left of either"); + assert!(!same_name("", "Demo")); + } + + #[test] + fn numbers_compare_on_letters_and_digits() { + assert_eq!( + number("0-1055-69000-01-2").as_deref(), + Some("0105569000012") + ); + assert_eq!(number("c01x 00t47").as_deref(), Some("C01X00T47")); + assert_eq!(number("12-3"), None, "too short to say anything"); + } + + #[test] + fn the_journal_says_what_was_found_and_who_cleared_it() { + assert_eq!(summary(&[], ""), "Conflict check: no match."); + let hit = |level| Hit { + level, + what: "Client".into(), + name: "Demo Records Co., Ltd.".into(), + href: String::new(), + why: "same name as Demo Records Co., Ltd.".into(), + means: String::new(), + }; + assert_eq!( + summary(&[hit("note")], "ignored"), + "Conflict check: 1 match: client Demo Records Co., Ltd. (same name as Demo Records Co., Ltd.)." + ); + assert!( + summary(&[hit("conflict"), hit("note")], "The label agreed in writing") + .ends_with("2 matches: client Demo Records Co., Ltd. (same name as Demo Records Co., Ltd.); client Demo Records Co., Ltd. (same name as Demo Records Co., Ltd.). Cleared: The label agreed in writing.") + ); + } +} diff --git a/src/legal.rs b/src/legal.rs index c95d8ba..d2d508a 100644 --- a/src/legal.rs +++ b/src/legal.rs @@ -193,9 +193,6 @@ const CONTRACT_FIELDS: &[Field] = &[ .wide(), field("kind", "Kind", Input::Choice(CONTRACT_KINDS)).req("Choose the kind of contract."), field("client_id", "Client", Input::Client).req("Choose the client."), - field("counterparty", "Other party", Input::Text) - .hint("The venue, label, employer, landlord or buyer on the other side.") - .wide(), field("status", "Status", Input::Choice(CONTRACT_STATUSES)).req("Choose the status."), field("lawyer_id", "Lawyer in charge", Input::Lawyer), field("signed_on", "Signed on", Input::Date).section("Dates"), @@ -421,7 +418,9 @@ pub struct Filter { pub async fn list_contracts(db: &PgPool, f: &Filter) -> Result> { Ok(sqlx::query_as( "SELECT c.id, c.code, c.title, c.kind, c.status, c.client_id, cl.name AS client, \ - c.counterparty, c.lawyer_id, l.name AS lawyer, c.ends_on, c.notice_by, \ + COALESCE((SELECT string_agg(p.name, ', ' ORDER BY p.id) FROM contract_parties p \ + WHERE p.contract_id = c.id AND p.removed_at IS NULL), '') AS counterparty, \ + c.lawyer_id, l.name AS lawyer, c.ends_on, c.notice_by, \ (SELECT count(*) FROM contract_versions v WHERE v.contract_id = c.id) AS versions, \ (SELECT count(*) FROM paper_copies p WHERE p.contract_id = c.id) AS papers \ FROM contracts c JOIN clients cl ON cl.id = c.client_id \ @@ -490,6 +489,162 @@ pub async fn list_clients(db: &PgPool, former: bool) -> Result> { .await?) } +// ------------------------------------------------------------- parties + +/// What a party is in a contract, for the form's suggestions. +pub const PARTY_ROLES: &[&str] = &[ + "Label", + "Publisher", + "Manager", + "Artist", + "Venue", + "Promoter", + "Festival", + "Sponsor", + "Employer", + "Employee", + "Landlord", + "Tenant", + "Buyer", + "Seller", + "Lender", + "Borrower", + "Service provider", + "Guarantor", +]; + +/// One of the other parties of a contract. +#[derive(Clone, Debug, sqlx::FromRow, Serialize)] +pub struct Party { + pub id: i64, + pub contract_id: i64, + pub name: String, + pub name_th: String, + pub id_no: String, + pub role: String, + pub added_by: String, + pub added_at: DateTime, + pub removed_by: Option, + pub removed_at: Option>, +} + +/// The parties of a contract in the order they were added, the removed +/// ones too. +pub async fn parties(db: &PgPool, contract: i64) -> Result> { + Ok( + sqlx::query_as("SELECT * FROM contract_parties WHERE contract_id = $1 ORDER BY id") + .bind(contract) + .fetch_all(db) + .await?, + ) +} + +/// A party as the form gives it. +#[derive(Clone, Debug, Default, Serialize)] +pub struct NewParty { + pub name: String, + pub name_th: String, + pub id_no: String, + pub role: String, +} + +impl NewParty { + /// The party as the journal states it. + pub fn said(&self) -> String { + let mut s = self.name.trim().to_string(); + if !self.name_th.trim().is_empty() { + s.push_str(&format!(" ({})", self.name_th.trim())); + } + if !self.id_no.trim().is_empty() { + s.push_str(&format!(", number {}", self.id_no.trim())); + } + if !self.role.trim().is_empty() { + s.push_str(&format!(", as {}", self.role.trim())); + } + s + } +} + +/// Adds a party, with the conflict check's words in its journal entry. +pub async fn add_party( + conn: &mut PgConnection, + head: &Head, + p: &NewParty, + check: &str, + by: &str, +) -> Result { + let party: Party = sqlx::query_as( + "INSERT INTO contract_parties (contract_id, name, name_th, id_no, role, added_by) \ + VALUES ($1, $2, $3, $4, $5, $6) RETURNING *", + ) + .bind(head.id) + .bind(p.name.trim()) + .bind(p.name_th.trim()) + .bind(p.id_no.trim()) + .bind(p.role.trim()) + .bind(by) + .fetch_one(&mut *conn) + .await?; + let mut detail = format!("{}: {}.", head.code, p.said()); + if !check.is_empty() { + detail.push(' '); + detail.push_str(check); + } + journal::append( + conn, + &journal::New { + actor: by, + client: Some(head.client_id), + contract: Some(head.id), + event: "party added", + detail, + }, + ) + .await?; + Ok(party) +} + +/// Takes a party off a contract: it stays on record as removed. False when +/// it is not a party of this contract, or removed already. +pub async fn remove_party( + conn: &mut PgConnection, + head: &Head, + party: i64, + by: &str, +) -> Result { + let row: Option = sqlx::query_as( + "UPDATE contract_parties SET removed_by = $3, removed_at = now() \ + WHERE id = $1 AND contract_id = $2 AND removed_at IS NULL RETURNING *", + ) + .bind(party) + .bind(head.id) + .bind(by) + .fetch_optional(&mut *conn) + .await?; + let Some(p) = row else { + return Ok(false); + }; + let said = NewParty { + name: p.name, + name_th: p.name_th, + id_no: p.id_no, + role: p.role, + } + .said(); + journal::append( + conn, + &journal::New { + actor: by, + client: Some(head.client_id), + contract: Some(head.id), + event: "party removed", + detail: format!("{}: {said}.", head.code), + }, + ) + .await?; + Ok(true) +} + // ------------------------------------------------------------ versions #[derive(Clone, Debug, sqlx::FromRow, Serialize)] @@ -865,11 +1020,11 @@ mod tests { old.insert("status".into(), "draft".into()); let mut new = old.clone(); new.insert("status".into(), "active".into()); - new.insert("counterparty".into(), "Demo Records".into()); + new.insert("notes".into(), "Signed at the label".into()); let opts = Options::default(); assert_eq!( changes_of(&CONTRACTS, &old, &new, &opts), - "Other party: (empty) -> Demo Records; Status: Draft -> In force" + "Status: Draft -> In force; Notes: (empty) -> Signed at the label" ); assert!(changes_of(&CONTRACTS, &old, &old, &opts).is_empty()); assert_eq!( diff --git a/src/lib.rs b/src/lib.rs index 93cdfae..79db116 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod agreements; pub mod audit; pub mod companies; pub mod config; +pub mod conflicts; pub mod countries; pub mod dates; pub mod db; diff --git a/src/seed/legal.rs b/src/seed/legal.rs index 49e3423..7e4635b 100644 --- a/src/seed/legal.rs +++ b/src/seed/legal.rs @@ -82,6 +82,32 @@ async fn add( }, ) .await?; + // the other side, as a party of the contract (phase 11) + let other = records::val(v, "counterparty"); + if kind.slug == "contracts" && !other.is_empty() { + let head = legal::head_of(conn, id).await?; + let role = match records::val(v, "kind") { + "artist-recording" => "Label", + "artist-management" => "Manager", + "artist-performance" => "Artist", + "lease" => "Landlord", + _ => "", + }; + // the label is a client too: the check found it, and a lawyer cleared it + let check = if other == "Demo Records Co., Ltd." { + "Conflict check: 1 match: client Demo Records Co., Ltd. (same name as Demo Records \ + Co., Ltd.). Cleared: both sides agreed in writing that Lanna Desk advises the artist \ + on this agreement and the label has its own counsel." + } else { + "Conflict check: no match." + }; + let party = legal::NewParty { + name: other.to_string(), + role: role.to_string(), + ..legal::NewParty::default() + }; + legal::add_party(conn, &head, &party, check, "seed").await?; + } Ok((id, code)) } diff --git a/src/web/legal.rs b/src/web/legal.rs index 6f4bdf7..e1d03ef 100644 --- a/src/web/legal.rs +++ b/src/web/legal.rs @@ -17,6 +17,7 @@ use super::documents::{FILE_LIMIT, FileQuery, read_field}; use super::{AppState, Res, message, not_found_page, page}; use crate::agreements; use crate::audit::{self, Action, Entity, Entry}; +use crate::conflicts::{self, For, Hit, Probe}; use crate::dates; use crate::documents::{self, Meta, NewFile, Owner}; use crate::files; @@ -63,6 +64,7 @@ fn form_page( opts: &Options, errors: &Errors, status: StatusCode, + check: &Check, ) -> Response { let (nav, list, crumb) = section(kind); let (heading, mode, action, cancel) = match id { @@ -98,10 +100,67 @@ fn form_page( cancel, crumb, crumb_href => list, + check, }, ) } +/// The conflict check as a form shows it: the matches, whether a lawyer +/// must clear them before the save goes through, and what they wrote. +#[derive(Debug, Default, Serialize)] +struct Check { + hits: Vec, + ask: bool, + note: String, +} + +/// The fields of a client the conflict check reads. +const CLIENT_CHECKED: &[&str] = &[ + "name", + "name_th", + "known_as", + "thai_id", + "passport_no", + "registration_no", +]; + +fn client_probe(v: &Values) -> Probe { + let g = |n: &str| records::val(v, n).to_string(); + Probe { + names: vec![g("name"), g("name_th"), g("known_as")], + numbers: vec![g("thai_id"), g("passport_no"), g("registration_no")], + } +} + +/// What a lawyer wrote when clearing matches, kept short. +fn cleared_note(f: &Fields) -> String { + crate::forms::get(f, "cleared_note") + .trim() + .chars() + .take(500) + .collect() +} + +/// Runs the check; Err holds the form's check when matches wait to be +/// cleared, Ok the check's words for the journal. +async fn run_check( + st: &AppState, + probe: &Probe, + who: For, + f: &Fields, +) -> anyhow::Result> { + let hits = conflicts::check(&st.db, probe, who).await?; + let note = cleared_note(f); + if conflicts::needs_clearing(&hits) && crate::forms::get(f, "cleared") != "1" { + return Ok(Err(Check { + hits, + ask: true, + note, + })); + } + Ok(Ok(conflicts::summary(&hits, ¬e))) +} + #[derive(Debug, Deserialize)] pub struct NewQuery { #[serde(default)] @@ -148,6 +207,7 @@ pub async fn new_form(kind: &'static Kind, st: Arc, user: User, q: New &opts, &Errors::new(), StatusCode::OK, + &Check::default(), )) } @@ -167,9 +227,37 @@ pub async fn create(kind: &'static Kind, st: Arc, user: User, f: Field if !errors.is_empty() { let status = StatusCode::UNPROCESSABLE_ENTITY; return Ok(form_page( - &st, &user, kind, None, &values, &opts, &errors, status, + &st, + &user, + kind, + None, + &values, + &opts, + &errors, + status, + &Check::default(), )); } + // a new client is checked against everyone on record first + let mut checked = String::new(); + if kind.slug == "clients" { + match run_check(&st, &client_probe(&values), For::Client(None), &f).await? { + Ok(said) => checked = said, + Err(check) => { + return Ok(form_page( + &st, + &user, + kind, + None, + &values, + &opts, + &errors, + StatusCode::CONFLICT, + &check, + )); + } + } + } let mut tx = st.db.begin().await?; let (id, detail) = if kind.slug == "contracts" { let (id, code) = legal::create_contract(&mut tx, &values, &user.login).await?; @@ -181,6 +269,11 @@ pub async fn create(kind: &'static Kind, st: Arc, user: User, f: Field let id = records::create(&mut tx, kind, None, &values).await?; (id, legal::detail_of(kind, &values, &opts)) }; + let detail = if checked.is_empty() { + detail + } else { + format!("{detail}. {checked}") + }; let (client, contract) = about(kind, id, &values); journal::append( &mut tx, @@ -223,6 +316,7 @@ pub async fn edit_form(kind: &'static Kind, st: Arc, user: User, id: i &opts, &Errors::new(), StatusCode::OK, + &Check::default(), )) } @@ -230,9 +324,9 @@ pub async fn update(kind: &'static Kind, st: Arc, user: User, id: i64, let opts = legal::options(&st.db).await?; let values = records::read(kind, &f); let errors = records::validate(kind, &values, &opts); - if records::get(&st.db, kind, None, id).await?.is_none() { + let Some(before) = records::get(&st.db, kind, None, id).await? else { return Ok(not_found_page(&st)); - } + }; if !errors.is_empty() { let status = StatusCode::UNPROCESSABLE_ENTITY; return Ok(form_page( @@ -244,8 +338,33 @@ pub async fn update(kind: &'static Kind, st: Arc, user: User, id: i64, &opts, &errors, status, + &Check::default(), )); } + // a client with a new name or number is checked again + let mut checked = String::new(); + if kind.slug == "clients" + && CLIENT_CHECKED + .iter() + .any(|n| records::val(&before.values, n) != records::val(&values, n)) + { + match run_check(&st, &client_probe(&values), For::Client(Some(id)), &f).await? { + Ok(said) => checked = said, + Err(check) => { + return Ok(form_page( + &st, + &user, + kind, + Some(id), + &values, + &opts, + &errors, + StatusCode::CONFLICT, + &check, + )); + } + } + } let (_, list, _) = section(kind); let mut tx = st.db.begin().await?; let Some(old) = records::get_for_update(&mut tx, kind, None, id).await? else { @@ -261,8 +380,10 @@ pub async fn update(kind: &'static Kind, st: Arc, user: User, id: i64, .fetch_one(&mut *tx) .await?; format!("{code}. {said}") - } else { + } else if checked.is_empty() { said + } else { + format!("{said}. {checked}") }; journal::append( &mut tx, @@ -629,7 +750,7 @@ struct PaperView { gone: bool, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Default, Deserialize)] pub struct ContractQuery { /// The version shown; the newest otherwise. #[serde(default)] @@ -639,11 +760,30 @@ pub struct ContractQuery { compare: Option, } +/// What the contract page's forms show again after a post: the version +/// form's, and the party form's with its conflict check. +#[derive(Default)] struct Shown { errors: Errors, note: String, body: String, status: StatusCode, + party: legal::NewParty, + party_errors: Errors, + check: Check, +} + +#[derive(Debug, Serialize)] +struct PartyView { + id: i64, + name: String, + name_th: String, + id_no: String, + role: String, + by: String, + added: String, + removed: Option, + removed_by: Option, } async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, form: Shown) -> Res { @@ -719,6 +859,22 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f holder: p.holder, }) .collect(); + let parties: Vec = legal::parties(&st.db, id) + .await? + .into_iter() + .map(|p| PartyView { + id: p.id, + added: dates::fmt_datetime(p.added_at), + removed: p.removed_at.map(dates::fmt_datetime), + removed_by: p.removed_by, + by: p.added_by, + name: p.name, + name_th: p.name_th, + id_no: p.id_no, + role: p.role, + }) + .collect(); + let live_parties = parties.iter().filter(|p| p.removed.is_none()).count(); let entries = journal_views(journal::list(&st.db, None, Some(id), 50).await?); let client_name: String = sqlx::query_scalar("SELECT name FROM clients WHERE id = $1") .bind(head.client_id) @@ -739,6 +895,11 @@ async fn contract_view(st: &AppState, user: &User, id: i64, q: &ContractQuery, f form.status, context! { id, shown, versions, papers, entries, client_name, diff, compare, + parties, live_parties, + party => form.party, + party_errors => form.party_errors, + check => form.check, + roles => legal::PARTY_ROLES, opened => dates::fmt_datetime(head.created_at), head, kind_label => records::label(legal::CONTRACT_KINDS, kind).unwrap_or("Other"), @@ -772,13 +933,7 @@ pub async fn contract_page( Path(id): Path, Query(q): Query, ) -> Res { - let form = Shown { - errors: Errors::new(), - note: String::new(), - body: String::new(), - status: StatusCode::OK, - }; - contract_view(&st, &user, id, &q, form).await + contract_view(&st, &user, id, &q, Shown::default()).await } /// The fields of the version form, as they arrived. @@ -946,11 +1101,9 @@ pub async fn add_version( note: form.note, body: form.body, status: StatusCode::UNPROCESSABLE_ENTITY, + ..Shown::default() }; - let q = ContractQuery { - v: None, - compare: None, - }; + let q = ContractQuery::default(); return contract_view(&st, &user, id, &q, shown).await; } let owner = Owner::Client(head.client_id); @@ -1045,6 +1198,147 @@ pub async fn version_file( // -------------------------------------------------------- paper copies +// ------------------------------------------------------------- parties + +fn party_of(f: &Fields) -> legal::NewParty { + let g = |n: &str| crate::forms::get(f, n).trim().to_string(); + legal::NewParty { + name: g("party_name"), + name_th: g("party_name_th"), + id_no: g("party_id_no"), + role: g("party_role"), + } +} + +/// Adds another party to a contract, after the conflict check: matches +/// that need a decision show on the form until a lawyer clears them. +pub async fn add_party( + State(st): State>, + Extension(user): Extension, + Path(id): Path, + Form(f): Form, +) -> Res { + let Some(head) = legal::head(&st.db, id).await? else { + return Ok(not_found_page(&st)); + }; + let party = party_of(&f); + let mut errors = Errors::new(); + if party.name.is_empty() { + err(&mut errors, "party_name", "Enter the other party's name."); + } + for (k, v) in [ + ("party_name", &party.name), + ("party_name_th", &party.name_th), + ("party_id_no", &party.id_no), + ("party_role", &party.role), + ] { + if v.len() > 300 { + err(&mut errors, k, "At most 300 characters."); + } + } + let q = ContractQuery::default(); + if !errors.is_empty() { + let form = Shown { + status: StatusCode::UNPROCESSABLE_ENTITY, + party, + party_errors: errors, + ..Shown::default() + }; + return contract_view(&st, &user, id, &q, form).await; + } + let probe = Probe { + names: vec![party.name.clone(), party.name_th.clone()], + numbers: vec![party.id_no.clone()], + }; + let who = For::Party { + contract: id, + client: head.client_id, + }; + let checked = match run_check(&st, &probe, who, &f).await? { + Ok(said) => said, + Err(check) => { + let form = Shown { + status: StatusCode::CONFLICT, + party, + check, + ..Shown::default() + }; + return contract_view(&st, &user, id, &q, form).await; + } + }; + let mut tx = st.db.begin().await?; + let p = legal::add_party(&mut tx, &head, &party, &checked, &user.login).await?; + audit::record( + &mut *tx, + &audit_entry(&user, Action::Create, Entity::ContractParty, p.id, &[]), + ) + .await?; + tx.commit().await?; + Ok(Redirect::to(&format!("/contracts/{id}#party-{}", p.id)).into_response()) +} + +/// Takes a party off a contract; it stays on record, marked removed. +pub async fn remove_party( + State(st): State>, + Extension(user): Extension, + Path((id, pid)): Path<(i64, i64)>, +) -> Res { + let Some(head) = legal::head(&st.db, id).await? else { + return Ok(not_found_page(&st)); + }; + let mut tx = st.db.begin().await?; + if !legal::remove_party(&mut tx, &head, pid, &user.login).await? { + return Ok(not_found_page(&st)); + } + audit::record( + &mut *tx, + &audit_entry(&user, Action::Delete, Entity::ContractParty, pid, &[]), + ) + .await?; + tx.commit().await?; + Ok(Redirect::to(&format!("/contracts/{id}#parties")).into_response()) +} + +#[derive(Debug, Deserialize)] +pub struct ConflictQuery { + #[serde(default)] + name: String, + #[serde(default)] + number: String, +} + +/// The conflict check on its own, before a first meeting: nothing is +/// saved, so nothing goes into the journal. +pub async fn conflicts_page( + State(st): State>, + Extension(user): Extension, + Query(q): Query, +) -> Res { + let (name, number) = (q.name.trim(), q.number.trim()); + let probe = Probe { + names: vec![name.to_string()], + numbers: vec![number.to_string()], + }; + let asked = !probe.is_empty(); + let hits = if asked { + conflicts::check(&st.db, &probe, For::Search).await? + } else { + Vec::new() + }; + Ok(page( + &st, + &user, + "conflicts.html", + "Conflict check", + "clients", + StatusCode::OK, + context! { + name, number, asked, + check => Check { hits, ask: false, note: String::new() }, + }, + )) +} + pub async fn add_paper( State(st): State>, Extension(user): Extension, diff --git a/src/web/mod.rs b/src/web/mod.rs index 7aaac31..762e037 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -431,6 +431,12 @@ pub fn router(st: Arc) -> Router { ) .route("/contracts/{id}/versions/{n}/file", get(l::version_file)) .route("/contracts/{id}/papers", post(l::add_paper)) + .route("/contracts/{id}/parties", post(l::add_party)) + .route( + "/contracts/{id}/parties/{pid}/remove", + post(l::remove_party), + ) + .route("/conflicts", get(l::conflicts_page)) .route("/papers", get(l::find_paper)) .route("/papers/{code}", get(l::paper_by_code)) .route("/papers/{pid}/move", post(l::move_paper)) diff --git a/static/app.css b/static/app.css index 51eddc2..3edd497 100644 --- a/static/app.css +++ b/static/app.css @@ -2084,3 +2084,85 @@ details.move[open] .mini { border-top: 1.4mm solid #f5c000; } } + +/* ---- the parties of a contract and the conflict check (phase 11) */ +.parties { + list-style: none; + margin: 0 0 12px; + padding: 0; +} +.parties li { + padding: 10px 0; + border-top: 1px solid var(--line); +} +.parties li:first-child { + border-top: 0; + padding-top: 0; +} +.parties li.old { + opacity: 0.6; +} +.parties .prow { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + flex-wrap: wrap; +} +.addparty > summary { + list-style: none; + cursor: pointer; + display: inline-block; +} +.addparty > summary::-webkit-details-marker { + display: none; +} +.addparty[open] > summary { + margin-bottom: 14px; +} +.conflicts { + margin: 0 0 16px; +} +.conflicts .cfhead { + margin: 0 0 10px; +} +.hits { + list-style: none; + margin: 0; + padding: 0; +} +.hit { + padding: 9px 0 9px 12px; + border-left: 3px solid var(--line); + margin-bottom: 8px; +} +.hit.conflict { + border-left-color: var(--bad); +} +.hit.same { + border-left-color: var(--warn); +} +.hit .hitwhat { + color: var(--mute); + font-size: 13px; + margin: 0 4px; +} +.hit .small { + margin-top: 3px; +} +.form .clearbox { + display: flex; + justify-content: flex-start; + gap: 10px; + align-items: baseline; + margin: 12px 0; + font-weight: 600; +} +.form .clearbox input { + width: auto; + flex: none; + margin: 0; +} +.warncard { + border-color: var(--bad); +} diff --git a/templates/_conflicts.html b/templates/_conflicts.html new file mode 100644 index 0000000..2513681 --- /dev/null +++ b/templates/_conflicts.html @@ -0,0 +1,25 @@ +{#- The conflict check's matches, and when they wait for a decision, the + box a lawyer ticks and what they write: both go into the journal. -#} +{% macro block(check) %} +
+ {% if check.ask %}

Conflict check: {{ check.hits|length }} match{% if check.hits|length != 1 %}es{% endif %} to look at before saving

{% endif %} +
    + {% for h in check.hits %} +
  • + {% if h.level == "conflict" %}Conflict{% elif h.level == "same" %}Same client?{% else %}Note{% endif %} + {{ h.what }} + {{ h.name }} +
    {{ h.means }} ({{ h.why }})
    +
  • + {% endfor %} +
+ {% if check.ask %} + +
+ + +

Goes into the journal with the matches.

+
+ {% endif %} +
+{% endmacro %} diff --git a/templates/clients.html b/templates/clients.html index ab1540a..514129d 100644 --- a/templates/clients.html +++ b/templates/clients.html @@ -2,7 +2,7 @@ {% block main %}

{% if former %}Former clients{% else %}Clients{% endif %}

- +

People and organizations, Thai or foreign, whom Lanna Desk advises or acts for: artists, labels, festivals, companies and private clients. Each has a lawyer in charge and their contracts.

{% if cards or n_former %} diff --git a/templates/conflicts.html b/templates/conflicts.html new file mode 100644 index 0000000..58933bc --- /dev/null +++ b/templates/conflicts.html @@ -0,0 +1,23 @@ +{% extends "base.html" %} +{% import "_fields.html" as fm %} +{% import "_conflicts.html" as cf %} +{% block main %} + +

Conflict check

+

Before a first meeting, look up a name or a number among the clients, the other parties of the contracts, the visa clients and the employers. Nothing is saved here. Adding a client or a party runs the same check and writes it into the journal.

+ +{% if asked %} +
+

{% if check.hits %}{{ check.hits|length }} match{% if check.hits|length != 1 %}es{% endif %}{% else %}No match{% endif %}

+ {% if check.hits %}{{ cf.block(check) }}{% else %}

Nobody on record has this name or number.

{% endif %} +
+{% endif %} +{% endblock %} diff --git a/templates/contract.html b/templates/contract.html index 2fa4b52..a7dfaf1 100644 --- a/templates/contract.html +++ b/templates/contract.html @@ -2,6 +2,7 @@ {% import "_fields.html" as fm %} {% import "_agreement_text.html" as ag %} {% import "_journal.html" as jn %} +{% import "_conflicts.html" as cf %} {% block main %}
@@ -42,6 +43,37 @@ {% endfor %}
+
+

Parties

each one added is checked for conflicts
+
    +
  • + {% for p in parties %} +
  • +
    + {{ p.name }}{% if p.name_th %} {{ p.name_th }}{% endif %}{% if p.role %} {{ p.role }}{% endif %}{% if p.removed %} removed{% endif %} + {% if not p.removed %}
    {% endif %} +
    +
    {% if p.id_no %}{{ p.id_no }} · {% endif %}added {{ p.added }} by {{ p.by }}{% if p.removed %} · removed {{ p.removed }} by {{ p.removed_by }}{% endif %}
    +
  • + {% endfor %} +
+ {% if not live_parties %}

No other party yet: add the other side, and the check looks for it among everyone on record.

{% endif %} +
+ Add a party +
+ + {% if check.hits %}{{ cf.block(check) }}{% endif %} +
+ {{ fm.text("party_name", "Name", party.name, err=party_errors.party_name, req=true, cls="wide", hint="As registered, or as in the ID card or passport.") }} + {{ fm.text("party_name_th", "Name in Thai", party.name_th, err=party_errors.party_name_th, cls="wide") }} + {{ fm.text("party_id_no", "ID, passport or registration number", party.id_no, err=party_errors.party_id_no, hint="The check compares numbers too.") }} + {{ fm.text("party_role", "Role", party.role, err=party_errors.party_role, list="roles", ph="Label, venue, landlord") }} +
+
+
+
+ {% for r in roles %}{% endfor %} +
{% if reading %}

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

diff --git a/templates/record_form.html b/templates/record_form.html index c20cc92..23a2ca8 100644 --- a/templates/record_form.html +++ b/templates/record_form.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% import "_fields.html" as fm %} +{% import "_conflicts.html" as cf %} {% block main %} {% if p %} {% include "_person_head.html" %} @@ -9,6 +10,7 @@ {% endif %}
+ {% if check and check.hits %}
{{ cf.block(check) }}
{% endif %}
{% if p %}

{{ heading }}

{% endif %} {% if lead %}

{{ lead }}

{% endif %} diff --git a/tests/legal.rs b/tests/legal.rs index a0629c6..769d593 100644 --- a/tests/legal.rs +++ b/tests/legal.rs @@ -57,7 +57,6 @@ async fn practice(app: &crate::common::App) -> (i64, i64, i64) { ("title", "Recording agreement"), ("kind", "artist-recording"), ("client_id", &client.to_string()), - ("counterparty", "Demo Records"), ("status", "draft"), ("lawyer_id", &lawyer.to_string()), ], @@ -184,7 +183,6 @@ async fn a_contract_keeps_its_versions_and_the_journal_holds_them(pool: PgPool) ("title", "Recording agreement"), ("kind", "artist-recording"), ("client_id", &client.to_string()), - ("counterparty", "Demo Records"), ("status", "active"), ], ) @@ -500,3 +498,220 @@ async fn the_demo_practice_shows_and_checks_whole(pool: PgPool) { assert_eq!(app.get(path).await.status, StatusCode::OK, "{path}"); } } + +/// The last journal entry of an event. +async fn last_said(pool: &PgPool, event: &str) -> String { + sqlx::query_scalar("SELECT detail FROM journal WHERE event = $1 ORDER BY seq DESC LIMIT 1") + .bind(event) + .fetch_one(pool) + .await + .unwrap() +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_conflict_check_finds_both_sides_and_asks_before_saving(pool: PgPool) { + let app = local(pool.clone()); + let (_, nok, contract) = practice(&app).await; + let r = app + .post( + "/clients", + &[ + ("kind", "organization"), + ("name", "Demo Records Co., Ltd."), + ("name_th", "บริษัท เดโม เรคคอร์ดส จำกัด"), + ("registration_no", "0105569000012"), + ("status", "active"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + let label = id_after(r.location(), "/clients/"); + assert!( + last_said(&pool, "client added") + .await + .ends_with("Conflict check: no match.") + ); + + // the label as the other side of the artist's contract: Lanna Desk acts + // for it, so the form asks first and nothing is saved + let party = |extra: &'static [(&'static str, &'static str)]| { + let mut f = vec![ + ("party_name", "DEMO RECORDS"), + ("party_id_no", "0-1055-69000-01-2"), + ("party_role", "Label"), + ]; + f.extend_from_slice(extra); + f + }; + let r = app + .post(&format!("/contracts/{contract}/parties"), &party(&[])) + .await; + assert_eq!(r.status, StatusCode::CONFLICT); + let t = r.text(); + assert!(t.contains("Lanna Desk acts for this client"), "{t}"); + assert!(t.contains(&format!("href=\"/clients/{label}\"")), "{t}"); + assert!(t.contains("same number 0105569000012"), "{t}"); + assert!(t.contains("name=\"cleared\""), "{t}"); + let n: i64 = sqlx::query_scalar("SELECT count(*) FROM contract_parties") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(n, 0, "nothing saved before the lawyer decides"); + + // cleared, with what the lawyer checked: saved, and the journal says so + let r = app + .post( + &format!("/contracts/{contract}/parties"), + &party(&[ + ("cleared", "1"), + ("cleared_note", "Both sides agreed in writing"), + ]), + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text()); + let said = last_said(&pool, "party added").await; + assert!( + said.contains("DEMO RECORDS, number 0-1055-69000-01-2, as Label."), + "{said}" + ); + assert!( + said.contains("Conflict check: 1 match: client Demo Records Co., Ltd."), + "{said}" + ); + assert!( + said.ends_with("Cleared: Both sides agreed in writing."), + "{said}" + ); + let page = app.get(&format!("/contracts/{contract}")).await.text(); + assert!(page.contains("id=\"parties\""), "{page}"); + assert!(page.contains("DEMO RECORDS"), "{page}"); + let list = app.get("/contracts").await.text(); + assert!(list.contains("with DEMO RECORDS"), "{list}"); + + // a party nobody knows goes in at once, the check noted + let r = app + .post( + &format!("/contracts/{contract}/parties"), + &[ + ("party_name", "Blue Sky Venue Co., Ltd."), + ("party_role", "Venue"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + let venue = id_after(r.location(), &format!("/contracts/{contract}#party-")); + assert!( + last_said(&pool, "party added") + .await + .ends_with("Conflict check: no match.") + ); + + // the venue comes as a client later: it was on the other side + let client = [ + ("kind", "organization"), + ("name", "blue sky venue"), + ("status", "active"), + ]; + let r = app.post("/clients", &client).await; + assert_eq!(r.status, StatusCode::CONFLICT); + let t = r.text(); + assert!(t.contains("Lanna Desk acted against them"), "{t}"); + assert!( + t.contains("value=\"blue sky venue\""), + "the form keeps what was typed" + ); + let mut cleared = client.to_vec(); + cleared.push(("cleared", "1")); + let r = app.post("/clients", &cleared).await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + let said = last_said(&pool, "client added").await; + assert!(said.ends_with("Cleared: checked, no conflict."), "{said}"); + + // the same client twice is asked about too, and a rename is checked again + let r = app + .post( + "/clients", + &[ + ("kind", "person"), + ("name", "JAIDEE, Nok"), + ("status", "active"), + ], + ) + .await; + assert_eq!(r.status, StatusCode::CONFLICT); + assert!(r.text().contains("Same client?")); + let r = app + .post( + &format!("/clients/{label}"), + &[ + ("kind", "organization"), + ("name", "Demo Records Co., Ltd."), + ("name_th", "บริษัท เดโม เรคคอร์ดส จำกัด"), + ("registration_no", "0105569000012"), + ("notes", "The label of Little Bird"), + ("status", "active"), + ], + ) + .await; + assert_eq!( + r.status, + StatusCode::SEE_OTHER, + "only the notes changed: no check" + ); + let r = app + .post( + &format!("/clients/{nok}"), + &[ + ("kind", "person"), + ("name", "Nok Jaidee"), + ("known_as", "Blue Sky Venue"), + ("status", "active"), + ], + ) + .await; + assert_eq!( + r.status, + StatusCode::CONFLICT, + "a new stage name is checked" + ); + + // the search before a first meeting finds the words in any order + let t = app.get("/conflicts?name=records+demo").await.text(); + assert!(t.contains("2 matches"), "{t}"); + assert!(t.contains("Other party in LD-"), "{t}"); + let t = app.get("/conflicts?name=Nobody+Known").await.text(); + assert!(t.contains("No match"), "{t}"); + + // a party is taken off, never deleted, and never rewritten + let r = app + .post( + &format!("/contracts/{contract}/parties/{venue}/remove"), + &[], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert!( + last_said(&pool, "party removed") + .await + .contains("Blue Sky Venue Co., Ltd., as Venue.") + ); + let r = app + .post( + &format!("/contracts/{contract}/parties/{venue}/remove"), + &[], + ) + .await; + assert_eq!(r.status, StatusCode::NOT_FOUND, "removed already"); + for sql in [ + "DELETE FROM contract_parties", + "UPDATE contract_parties SET name = 'Someone else'", + ] { + assert!(sqlx::query(sql).execute(&pool).await.is_err(), "{sql}"); + } + let list = app.get("/contracts").await.text(); + assert!( + !list.contains("Blue Sky Venue Co."), + "a removed party leaves the list" + ); + assert!(visa::journal::verify(&pool).await.unwrap().whole()); +}