Files
grabowski 9ae4d7bd07
CI / secret scan (push) Successful in 8s
CI / fmt, clippy, tests (push) Successful in 1m14s
CI / release (push) Skipped
Phase 11, step 1: the parties of a contract and the conflict check
A contract's other side was one line of text. Now each other party is a
row with its names in English and Thai, an ID, passport or registration
number and its role (migration 0010; the old line became the first
party). Parties are never deleted or rewritten: taking one off marks it
removed, and both are in the journal.

The conflict check (src/conflicts.rs) looks for the 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 (Co., Ltd., บริษัท ... จำกัด), or when every word of the
shorter name, at least two, is in the longer one. A new party that is a
client, a visa client or an employer is a conflict; a new or renamed
client that was on the other side of a contract is one too; a client's
name or number again is perhaps the same client. Those stop the save
(409) until a lawyer ticks that they looked, with what they checked; the
matches and the note go into the journal entry. /conflicts runs the
check alone before a first meeting and saves nothing.

Tests: 119 unit, 63 integration.
2026-11-22 22:12:17 +07:00

718 lines
24 KiB
Rust

//! The legal practice: lawyers, clients, contracts, their versions that
//! never change, paper copies with ids and places, and the journal whose
//! chain shows any change made around the app.
use axum::http::StatusCode;
use sqlx::PgPool;
use crate::common::{local, pdf};
fn id_after(location: &str, base: &str) -> i64 {
location
.trim_start_matches(base)
.split(['#', '/', '?'])
.next()
.unwrap()
.parse()
.unwrap_or_else(|_| panic!("no id after {base} in {location:?}"))
}
/// A lawyer, a Thai client and a contract of theirs; returns the ids.
async fn practice(app: &crate::common::App) -> (i64, i64, i64) {
let r = app
.post(
"/lawyers",
&[
("name", "Malee Rakdee"),
("status", "active"),
("login", "local"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
let lawyer: i64 = sqlx::query_scalar("SELECT max(id) FROM lawyers")
.fetch_one(&app.pool)
.await
.unwrap();
let r = app
.post(
"/clients",
&[
("kind", "person"),
("name", "Nok Jaidee"),
("known_as", "Little Bird"),
("nationality", "Thai"),
("thai_id", "1101700123456"),
("status", "active"),
("lawyer_id", &lawyer.to_string()),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
let client = id_after(r.location(), "/clients/");
let r = app
.post(
"/contracts",
&[
("title", "Recording agreement"),
("kind", "artist-recording"),
("client_id", &client.to_string()),
("status", "draft"),
("lawyer_id", &lawyer.to_string()),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
(lawyer, client, id_after(r.location(), "/contracts/"))
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_contract_keeps_its_versions_and_the_journal_holds_them(pool: PgPool) {
let app = local(pool.clone());
// a Thai ID is checked
let r = app
.post(
"/clients",
&[
("kind", "person"),
("name", "Wrong Number"),
("thai_id", "1101700123457"),
("status", "active"),
],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("not a valid Thai ID number"));
let (_, client, contract) = practice(&app).await;
let code: String = sqlx::query_scalar("SELECT code FROM contracts WHERE id = $1")
.bind(contract)
.fetch_one(&pool)
.await
.unwrap();
assert!(
code.starts_with("LD-20") && code.ends_with("-0001"),
"{code}"
);
let base = format!("/contracts/{contract}/versions");
// a version needs a note, and something
let r = app.upload(&base, &[("note", ""), ("body", "")], &[]).await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
let t = r.text();
assert!(t.contains("Say what this version is"), "{t}");
assert!(t.contains("a version needs something new"), "{t}");
let v1 = "# 1. Term\nFive years.\n\n# 2. Royalties\n12% of net receipts.";
let r = app
.upload(&base, &[("note", "The label's draft"), ("body", v1)], &[])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
// the same text again is not a version
let r = app
.upload(&base, &[("note", "Again"), ("body", v1)], &[])
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
let v2 = "# 1. Term\nThree years.\n\n# 2. Royalties\n12% of net receipts.";
let r = app
.upload(&base, &[("note", "Our changes"), ("body", v2)], &[])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
// the signed scan: a file, the text unchanged
let scan = pdf("signed recording agreement");
let r = app
.upload(
&base,
&[("note", "Signed by both sides"), ("body", v2)],
&[("signed.pdf", &scan)],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
assert_eq!(r.location(), format!("/contracts/{contract}?v=3#versions"));
let kept: (String, Option<String>, Option<String>) = sqlx::query_as(
"SELECT body, body_sha256, file_sha256 FROM contract_versions \
WHERE contract_id = $1 AND version = 3",
)
.bind(contract)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(kept.0, "", "an unchanged text is not kept twice");
assert!(kept.1.is_none());
assert_eq!(
kept.2.as_deref(),
Some(visa::files::sha256_hex(&scan).as_str())
);
// the file opens, checked, and is the client's document
let f = app
.get(&format!("/contracts/{contract}/versions/3/file"))
.await;
assert_eq!(f.status, StatusCode::OK);
assert_eq!(f.bytes, scan);
let owner: Option<i64> = sqlx::query_scalar(
"SELECT client_id FROM documents WHERE kind = 'contract' ORDER BY id DESC LIMIT 1",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(owner, Some(client));
// no file for a version without one
let none = app
.get(&format!("/contracts/{contract}/versions/1/file"))
.await;
assert_eq!(none.status, StatusCode::NOT_FOUND);
// the page compares version 2 with 1
let p = app
.get(&format!("/contracts/{contract}?v=2&compare=1"))
.await
.text();
assert!(p.contains("Version 2 against version 1"), "{p}");
assert!(p.contains("<del>Five years.</del>"), "{p}");
assert!(p.contains("<ins>Three years.</ins>"), "{p}");
let p = app.get(&format!("/contracts/{contract}")).await.text();
assert!(p.contains(&code));
assert!(p.contains("Add version 4"), "{p}");
// the facts change, field by field in the journal
let r = app
.post(
&format!("/contracts/{contract}"),
&[
("title", "Recording agreement"),
("kind", "artist-recording"),
("client_id", &client.to_string()),
("status", "active"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
let changed: String = sqlx::query_scalar(
"SELECT detail FROM journal WHERE event = 'contract changed' ORDER BY seq DESC LIMIT 1",
)
.fetch_one(&pool)
.await
.unwrap();
assert!(changed.contains("Status: Draft -> In force"), "{changed}");
assert!(
changed.contains("Lawyer in charge: Malee Rakdee -> (empty)"),
"{changed}"
);
// the chain is whole, and says so
let check = visa::journal::verify(&pool).await.unwrap();
assert!(check.whole(), "{:?}", check.problems);
// lawyer, client, contract, three versions, the change
assert_eq!(check.entries, 7);
let j = app.get("/journal").await.text();
assert!(j.contains("The journal is whole."), "{j}");
assert!(j.contains(&check.head));
let csv = app.get("/journal.csv").await;
assert_eq!(csv.status, StatusCode::OK);
assert!(
csv.text().lines().count() == 8,
"a header and seven entries"
);
// the lists
let c = app.get("/clients").await.text();
assert!(c.contains("Nok Jaidee") && c.contains("Little Bird"), "{c}");
let k = app.get("/contracts?group=artist").await.text();
assert!(k.contains("Recording agreement"), "{k}");
let k = app.get("/contracts?group=general").await.text();
assert!(!k.contains("Recording agreement"));
// the lawyer who signs in as "local" has it under My contracts? It lost
// its lawyer above, so not
let k = app.get("/contracts?mine=1").await.text();
assert!(
k.contains("My contracts") && !k.contains(&format!("href=\"/contracts/{contract}\"")),
"{k}"
);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_database_refuses_to_change_what_is_on_record(pool: PgPool) {
let app = local(pool.clone());
let (_, _, contract) = practice(&app).await;
let base = format!("/contracts/{contract}/versions");
let r = app
.upload(
&base,
&[("note", "Draft"), ("body", "# Term\nOne year.")],
&[("draft.pdf", &pdf("draft"))],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.text());
for sql in [
"UPDATE contract_versions SET body = 'Two years.'",
"DELETE FROM contract_versions",
"UPDATE journal SET detail = 'nothing'",
"DELETE FROM journal",
"TRUNCATE journal CASCADE",
// the version's file
"DELETE FROM documents WHERE kind = 'contract'",
"UPDATE documents SET sha256 = repeat('0', 64) WHERE kind = 'contract'",
] {
let e = sqlx::query(sql).execute(&pool).await;
assert!(e.is_err(), "{sql} went through");
}
let r = app
.post(
&format!("/contracts/{contract}/papers"),
&[("what", "Signed original"), ("location", "Cabinet A")],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert!(
sqlx::query("UPDATE paper_copies SET code = 'X'")
.execute(&pool)
.await
.is_err()
);
assert!(
sqlx::query("DELETE FROM paper_copies")
.execute(&pool)
.await
.is_err()
);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_change_made_around_the_app_breaks_the_chain(pool: PgPool) {
let app = local(pool.clone());
let (_, _, contract) = practice(&app).await;
let r = app
.upload(
&format!("/contracts/{contract}/versions"),
&[("note", "Draft"), ("body", "# Fee\n10,000 THB.")],
&[],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert!(visa::journal::verify(&pool).await.unwrap().whole());
// someone with the database's rights rewrites an entry ...
sqlx::query("ALTER TABLE journal DISABLE TRIGGER journal_no_change")
.execute(&pool)
.await
.unwrap();
sqlx::query("UPDATE journal SET detail = 'Name: Someone else' WHERE seq = 2")
.execute(&pool)
.await
.unwrap();
let check = visa::journal::verify(&pool).await.unwrap();
assert!(!check.whole());
assert!(
check
.problems
.iter()
.any(|p| p.contains("Entry 2 was changed")),
"{:?}",
check.problems
);
let j = app.get("/journal").await.text();
assert!(j.contains("The journal is broken."), "{j}");
// ... or a version's text, with a fitting new fingerprint
let mut fresh = pool.acquire().await.unwrap();
sqlx::query("ALTER TABLE contract_versions DISABLE TRIGGER contract_versions_no_change")
.execute(&mut *fresh)
.await
.unwrap();
let forged = "# Fee\n100,000 THB.";
sqlx::query("UPDATE contract_versions SET body = $1, body_sha256 = $2")
.bind(forged)
.bind(visa::files::sha256_hex(forged.as_bytes()))
.execute(&mut *fresh)
.await
.unwrap();
let check = visa::journal::verify(&pool).await.unwrap();
assert!(
check
.problems
.iter()
.any(|p| p.contains("version 1: its fingerprint differs from the one in journal entry")),
"{:?}",
check.problems
);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn paper_copies_have_ids_and_their_moves_are_journaled(pool: PgPool) {
let app = local(pool.clone());
let (_, _, contract) = practice(&app).await;
let code: String = sqlx::query_scalar("SELECT code FROM contracts WHERE id = $1")
.bind(contract)
.fetch_one(&pool)
.await
.unwrap();
let base = format!("/contracts/{contract}/papers");
let r = app
.post(
&base,
&[
("what", "Signed original"),
("location", "Cabinet A, drawer 1"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
let r = app.post(&base, &[("what", "Copy"), ("location", "")]).await;
assert_eq!(
r.status,
StatusCode::UNPROCESSABLE_ENTITY,
"a place is needed"
);
let r = app
.post(&base, &[("what", "Copy"), ("location", "Inbox")])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
let papers: Vec<(i64, String)> =
sqlx::query_as("SELECT id, code FROM paper_copies ORDER BY id")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(papers[0].1, format!("{code}-P1"));
assert_eq!(papers[1].1, format!("{code}-P2"));
let pid = papers[0].0;
let r = app
.post(
&format!("/papers/{pid}/move"),
&[
("location", "Cabinet A, drawer 1"),
("state", "out"),
("holder", "Malee"),
("note", "For the signing"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert_eq!(r.location(), format!("/contracts/{contract}#paper-{pid}"));
let moved: String = sqlx::query_scalar(
"SELECT detail FROM journal WHERE event = 'paper moved' ORDER BY seq DESC LIMIT 1",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(
moved,
format!("{code}-P1: Filed -> Taken out, with Malee. For the signing")
);
// the same again changes nothing and writes nothing
let before: i64 = sqlx::query_scalar("SELECT count(*) FROM journal")
.fetch_one(&pool)
.await
.unwrap();
app.post(
&format!("/papers/{pid}/move"),
&[
("location", "Cabinet A, drawer 1"),
("state", "out"),
("holder", "Malee"),
],
)
.await;
let after: i64 = sqlx::query_scalar("SELECT count(*) FROM journal")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(before, after);
// found by its id, as typed from the paper
let typed = format!(" {}-p1 ", code.to_lowercase());
let r = app
.get(&format!("/papers?code={}", typed.replace(' ', "+")))
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert_eq!(r.location(), format!("/contracts/{contract}#paper-{pid}"));
let r = app.get(&format!("/papers/{code}-P2")).await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert_eq!(
app.get("/papers?code=LD-1999-0001-P1").await.status,
StatusCode::NOT_FOUND
);
// the label: the id, a QR code, where it belongs
let l = app.get(&format!("/papers/{pid}/label")).await.text();
assert!(l.contains(&format!("{code}-P1")), "{l}");
assert!(l.contains("<svg"), "the QR code");
assert!(l.contains("Belongs in: Cabinet A, drawer 1"));
assert!(visa::journal::verify(&pool).await.unwrap().whole());
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_demo_practice_shows_and_checks_whole(pool: PgPool) {
let app = local(pool.clone());
let today = visa::dates::today();
assert!(
visa::seed::legal::demo(&pool, app.st.files.as_ref(), today)
.await
.unwrap()
);
assert!(
!visa::seed::legal::demo(&pool, app.st.files.as_ref(), today)
.await
.unwrap(),
"only once"
);
let check = visa::journal::verify(&pool).await.unwrap();
assert!(check.whole(), "{:?}", check.problems);
let c = app.get("/clients").await.text();
for name in [
"Demo Records Co., Ltd.",
"Nok Jaidee",
"Max Mustermann",
"Somsri Meesuk",
] {
assert!(c.contains(name), "{name}: {c}");
}
assert!(c.contains(">DR</span>"), "the label's monogram");
let k = app.get("/contracts").await.text();
assert!(
k.contains("Notice by"),
"the management deal's notice day: {k}"
);
assert!(!k.contains("Non-disclosure agreement"), "it is over");
let k = app.get("/contracts?all=1").await.text();
assert!(k.contains("Non-disclosure agreement"));
// the festival's booking: two versions, the scan, two papers
let id: i64 = sqlx::query_scalar("SELECT id FROM contracts WHERE kind = 'artist-performance'")
.fetch_one(&pool)
.await
.unwrap();
let p = app.get(&format!("/contracts/{id}")).await.text();
assert!(p.contains("performance-signed.pdf"), "{p}");
assert!(
p.contains("Handed over") && p.contains("with Max Mustermann"),
"{p}"
);
for path in [
"/lawyers",
"/journal",
"/clients/1",
"/contracts/new?client=1",
"/clients/new",
] {
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("<b>DEMO RECORDS</b>"), "{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());
}