Files
visa/src/seed/legal.rs
T
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

598 lines
18 KiB
Rust

//! Demo data of the legal practice: invented lawyers, clients (Thai and
//! foreign, people and organizations) and contracts, general ones and
//! artists', with versions, paper copies and their moves. They go through
//! the same functions as the pages, so the journal holds them too and
//! checks whole.
use anyhow::Result;
use chrono::{Duration, NaiveDate};
use sqlx::PgPool;
use crate::documents::{self, Meta, NewFile, Owner};
use crate::files::{self, Store};
use crate::journal::{self, New};
use crate::legal::{self, CLIENTS, CONTRACTS, LAWYERS};
use crate::records::{self, Kind, Values};
/// In every demo client's notes, so the seed knows they are there.
pub const MARKER: &str = "Demo client, invented for development.";
fn vals(pairs: &[(&str, String)]) -> Values {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect()
}
fn s(v: &str) -> String {
v.to_string()
}
fn day(d: NaiveDate) -> String {
d.format("%Y-%m-%d").to_string()
}
/// A record and its journal entry, as the form adds them.
async fn add(
conn: &mut sqlx::PgConnection,
kind: &'static Kind,
v: &Values,
) -> Result<(i64, String)> {
let opts = {
// the options as they stand in this transaction
let lawyers: Vec<(i64, String)> = sqlx::query_as("SELECT id, name FROM lawyers")
.fetch_all(&mut *conn)
.await?;
let clients: Vec<(i64, String)> = sqlx::query_as("SELECT id, name FROM clients")
.fetch_all(&mut *conn)
.await?;
records::Options {
lawyers: lawyers
.into_iter()
.map(|(i, n)| (i.to_string(), n))
.collect(),
clients: clients
.into_iter()
.map(|(i, n)| (i.to_string(), n))
.collect(),
..records::Options::default()
}
};
let (id, code, detail) = if kind.slug == "contracts" {
let (id, code) = legal::create_contract(conn, v, "seed").await?;
let d = format!("{code}. {}", legal::detail_of(kind, v, &opts));
(id, code, d)
} else {
let id = records::create(conn, kind, None, v).await?;
(id, String::new(), legal::detail_of(kind, v, &opts))
};
let (client, contract) = match kind.slug {
"clients" => (Some(id), None),
"contracts" => (records::val(v, "client_id").parse().ok(), Some(id)),
_ => (None, None),
};
journal::append(
conn,
&New {
actor: "seed",
client,
contract,
event: &format!("{} added", kind.one),
detail,
},
)
.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))
}
const RECORDING_V1: &str = "# Recording agreement\n\
Between Demo Records Co., Ltd. (the Label) and Nok Jaidee, known as Little Bird (the Artist).\n\
\n\
# 1. Term\n\
The term is five years from signing, and the Label may extend it by two more albums.\n\
\n\
# 2. Recordings\n\
The Artist records one album of at least ten tracks a year.\n\
\n\
# 3. Royalties\n\
The Label pays the Artist 12% of net receipts.\n\
- Advances are recouped from all royalties.\n\
- Statements twice a year.\n\
\n\
# 4. Rights\n\
The Label owns the master recordings for the life of copyright.";
const RECORDING_V2: &str = "# Recording agreement\n\
Between Demo Records Co., Ltd. (the Label) and Nok Jaidee, known as Little Bird (the Artist).\n\
\n\
# 1. Term\n\
The term is three years from signing; any extension needs the Artist's written consent.\n\
\n\
# 2. Recordings\n\
The Artist records one album of at least ten tracks a year.\n\
\n\
# 3. Royalties\n\
The Label pays the Artist 18% of net receipts.\n\
- Advances are recouped from the Artist's royalties on this album only.\n\
- Statements twice a year, with the right to audit once a year.\n\
\n\
# 4. Rights\n\
The Label holds the master recordings for ten years; then they revert to the Artist.\n\
\n\
# 5. ภาษาไทย\n\
สัญญานี้ทำขึ้นเป็นภาษาไทยและภาษาอังกฤษ หากมีข้อขัดแย้งให้ใช้ฉบับภาษาไทย";
const PERFORMANCE_V1: &str = "# Performance agreement, Demo Festival 2026\n\
The Festival books DJ Muster for one set of 90 minutes on the main stage.\n\
\n\
# 1. Fee\n\
45,000 THB, half on signing and half after the set.\n\
\n\
# 2. Travel\n\
The Festival pays the flight from Berlin and three nights in Pai.\n\
\n\
# 3. Cancellation\n\
- by the Festival less than 30 days before: the whole fee\n\
- by the Artist: the deposit is returned";
/// Adds the demo practice unless it is there; true when it did. Files
/// (the signed scans) only with a store.
pub async fn demo(db: &PgPool, store: Option<&Store>, today: NaiveDate) -> Result<bool> {
let present: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM clients WHERE notes = $1)")
.bind(MARKER)
.fetch_one(db)
.await?;
if present {
return Ok(false);
}
let mut tx = db.begin().await?;
let t = &mut *tx;
let (somchai, _) = add(
t,
&LAWYERS,
&vals(&[
("name", s("Somchai Jaidee")),
("name_th", s("สมชาย ใจดี")),
("license_no", s("1234/2550")),
("status", s("active")),
("email", s("somchai@example.com")),
("notes", s("Demo lawyer, invented for development.")),
]),
)
.await?;
let (malee, _) = add(
t,
&LAWYERS,
&vals(&[
("name", s("Malee Rakdee")),
("name_th", s("มาลี รักดี")),
("license_no", s("5678/2558")),
("status", s("active")),
("email", s("malee@example.com")),
("notes", s("Demo lawyer: music and artists.")),
]),
)
.await?;
add(
t,
&LAWYERS,
&vals(&[
("name", s("Anna Beispiel")),
("status", s("left")),
("notes", s("Demo lawyer who left the team.")),
]),
)
.await?;
let client = |kind: &str, name: &str, rest: &[(&str, String)], lawyer: i64| {
let mut v = vals(rest);
v.insert("kind".into(), kind.into());
v.insert("name".into(), name.into());
v.insert("status".into(), "active".into());
v.insert("lawyer_id".into(), lawyer.to_string());
v.insert("notes".into(), MARKER.into());
v
};
let (label, _) = add(
t,
&CLIENTS,
&client(
"organization",
"Demo Records Co., Ltd.",
&[
("name_th", s("บริษัท เดโม เรคคอร์ดส จำกัด")),
("known_as", s("Demo Records")),
("registration_no", s("0505566000001")),
("contact_person", s("Khun Ploy, managing director")),
("email", s("office@demo-records.example")),
(
"address",
s("99 Nimmanhaemin Road, Suthep, Mueang Chiang Mai, Chiang Mai 50200"),
),
],
somchai,
),
)
.await?;
let (nok, _) = add(
t,
&CLIENTS,
&client(
"person",
"Nok Jaidee",
&[
("name_th", s("นก ใจดี")),
("known_as", s("Little Bird")),
("nationality", s("Thai")),
("thai_id", s("1101700123456")),
("phone", s("081 234 5678")),
("contact_person", s("Her manager, Khun Dao")),
],
malee,
),
)
.await?;
let (max, _) = add(
t,
&CLIENTS,
&client(
"person",
"Max Mustermann",
&[
("known_as", s("DJ Muster")),
("nationality", s("German")),
("passport_no", s("C01X00T47")),
("email", s("max@example.com")),
],
malee,
),
)
.await?;
let (festival, _) = add(
t,
&CLIENTS,
&client(
"organization",
"Demo Festival Foundation",
&[
("name_th", s("มูลนิธิเดโมเฟสติวัล")),
("known_as", s("Demo Festival")),
("contact_person", s("The festival director")),
],
somchai,
),
)
.await?;
let (somsri, _) = add(
t,
&CLIENTS,
&client(
"person",
"Somsri Meesuk",
&[
("name_th", s("สมศรี มีสุข")),
("nationality", s("Thai")),
("thai_id", s("3509900123450")),
("address", s("12 Moo 3, Mae Rim, Chiang Mai 50180")),
],
somchai,
),
)
.await?;
let contract =
|title: &str, kind: &str, client: i64, other: &str, status: &str, lawyer: i64| {
vals(&[
("title", s(title)),
("kind", s(kind)),
("client_id", client.to_string()),
("counterparty", s(other)),
("status", s(status)),
("lawyer_id", lawyer.to_string()),
])
};
// the artist's recording deal, two drafts to compare
let (rec, _) = add(
t,
&CONTRACTS,
&contract(
"Recording agreement for the album Blue Hour",
"artist-recording",
nok,
"Demo Records Co., Ltd.",
"negotiation",
malee,
),
)
.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,
"Our changes for the artist: term, royalties, reversion",
RECORDING_V2,
None,
"seed",
)
.await?;
// the management deal: in force, notice day near
let mut v = contract(
"Management agreement",
"artist-management",
nok,
"Demo Management",
"active",
malee,
);
v.insert("signed_on".into(), day(today - Duration::days(700)));
v.insert("starts_on".into(), day(today - Duration::days(700)));
v.insert("ends_on".into(), day(today + Duration::days(50)));
v.insert("notice_by".into(), day(today + Duration::days(20)));
v.insert(
"notes".into(),
s("Renews for a year unless notice is given 30 days before the end."),
);
add(t, &CONTRACTS, &v).await?;
// the festival's booking: text, then the signed scan, papers
let mut v = contract(
"Performance agreement, Demo Festival 2026",
"artist-performance",
festival,
"Max Mustermann (DJ Muster)",
"active",
somchai,
);
v.insert("signed_on".into(), day(today - Duration::days(30)));
v.insert("starts_on".into(), day(today - Duration::days(30)));
v.insert("ends_on".into(), day(today + Duration::days(120)));
v.insert("value_thb".into(), s("45000"));
let (perf, _) = add(t, &CONTRACTS, &v).await?;
let hp = legal::head_of(t, perf).await?;
legal::add_version(t, &hp, "Final text", PERFORMANCE_V1, None, "seed").await?;
let mut written = Vec::new();
let signed = match store {
Some(store) => {
let pdf = crate::seed::demo_pdf(
"Performance agreement, signed (demo)",
&[
format!("{} - signed by both sides", hp.code),
"Demo Festival Foundation and Max Mustermann".into(),
"An invented scan for development.".into(),
],
);
let doc = file(
t,
store,
Owner::Client(festival),
&hp.code,
"performance-signed.pdf",
pdf,
)
.await?;
written.push(doc.0);
Some(doc)
}
None => None,
};
let v2 = match &signed {
Some((doc, sha)) => Some(
legal::add_version(
t,
&hp,
"Signed by both sides (scan)",
"",
Some(&legal::VersionFile {
document: *doc,
sha256: sha,
name: "performance-signed.pdf",
}),
"seed",
)
.await?,
),
None => None,
};
legal::add_paper(
t,
&hp,
v2.as_ref(),
"Signed original",
"Office, cabinet A, drawer 1, folder Demo Festival",
"seed",
)
.await?;
let p2 = legal::add_paper(
t,
&hp,
v2.as_ref(),
"Signed counterpart",
"Office, inbox",
"seed",
)
.await?;
legal::move_paper(
t,
&hp,
&p2,
&legal::Move {
location: "With the artist",
state: "handed-over",
holder: "Max Mustermann",
note: "Given to him at the sound check.",
},
"seed",
)
.await?;
// the label's office lease: a signed scan only, its paper taken out
let mut v = contract(
"Office lease, Nimmanhaemin",
"lease",
label,
"Demo Property Co., Ltd.",
"active",
somchai,
);
v.insert("signed_on".into(), day(today - Duration::days(200)));
v.insert("starts_on".into(), day(today - Duration::days(180)));
v.insert("ends_on".into(), day(today + Duration::days(550)));
v.insert("value_thb".into(), s("540000"));
let (lease, _) = add(t, &CONTRACTS, &v).await?;
let hl = legal::head_of(t, lease).await?;
if let Some(store) = store {
let pdf = crate::seed::demo_pdf(
"Office lease, signed (demo)",
&[
format!("{} - lease of the office, Nimmanhaemin", hl.code),
"An invented scan for development.".into(),
],
);
let (doc, sha) = file(
t,
store,
Owner::Client(label),
&hl.code,
"lease-signed.pdf",
pdf,
)
.await?;
written.push(doc);
let v = legal::add_version(
t,
&hl,
"Signed lease (scan)",
"",
Some(&legal::VersionFile {
document: doc,
sha256: &sha,
name: "lease-signed.pdf",
}),
"seed",
)
.await?;
let p = legal::add_paper(
t,
&hl,
Some(&v),
"Signed original",
"Office, cabinet B, drawer 3, folder Demo Records",
"seed",
)
.await?;
legal::move_paper(
t,
&hl,
&p,
&legal::Move {
location: "Office, cabinet B, drawer 3, folder Demo Records",
state: "out",
holder: "Somchai Jaidee",
note: "For the meeting with the landlord.",
},
"seed",
)
.await?;
}
// a foreign artist's own deal, being negotiated
add(
t,
&CONTRACTS,
&contract(
"License of the DJ mix Pai Sunrise",
"artist-license",
max,
"Demo Streaming Ltd.",
"negotiation",
malee,
),
)
.await?;
// a private client's land lease, a draft
add(
t,
&CONTRACTS,
&contract(
"Thirty-year land lease, Mae Rim",
"lease",
somsri,
"A buyer from Bangkok",
"draft",
somchai,
),
)
.await?;
// an old one, over
let mut v = contract(
"Non-disclosure agreement, sponsor talks",
"nda",
festival,
"Demo Beverages",
"ended",
somchai,
);
v.insert("ends_on".into(), day(today - Duration::days(90)));
add(t, &CONTRACTS, &v).await?;
match tx.commit().await {
Ok(()) => Ok(true),
Err(e) => {
if let Some(store) = store {
for d in written {
let _ = store.remove(d).await;
}
}
Err(e.into())
}
}
}
/// A file as the client's document of kind `contract`.
async fn file(
conn: &mut sqlx::PgConnection,
store: &Store,
owner: Owner,
code: &str,
name: &str,
bytes: Vec<u8>,
) -> Result<(i64, String)> {
let sha = files::sha256_hex(&bytes);
let meta = Meta {
kind: "contract".into(),
note: format!("{code}: demo"),
..Meta::default()
};
let nf = NewFile {
name,
content_type: "application/pdf",
size: i32::try_from(bytes.len())?,
sha256: &sha,
};
let id = documents::insert(conn, owner, &meta, &nf, "seed").await?;
store.put(id, bytes).await?;
Ok((id, sha))
}