Files
visa/src/seed/legal.rs
T
grabowski 16e4cdc73d
CI / secret scan (push) Successful in 7s
CI / fmt, clippy, tests (push) Successful in 45s
CI / release (push) Skipped
The legal practice: clients, lawyers, contracts, papers, the journal
Lanna Desk's larger work is contracts, general ones and artists', for
clients who are Thai or foreign, people or organizations, with several
lawyers in the team. The back office gets a Legal section (phase 9 in
docs/PLAN.md):

- Lawyers: license number, contact, the login of one who uses the app
  (then "My contracts"), in the team or left.
- Clients, as record cards: person or organization, names in English and
  Thai, stage name or brand, a Thai ID number (checked), a passport or a
  registration number, the lawyer in charge.
- Contracts: code LD-<year>-<n>, the general kinds and the artist kinds
  (recording, management, publishing, performance, license,
  merchandise), other party, status, lawyer, dates and value; a contract
  in force shows its notice day and its end ahead. Filters: general or
  artists, a lawyer, mine, those over.
- Versions: a text kept here, a file (PDF or scan, encrypted as the
  client's document) or both. They never change: the database refuses
  UPDATE and DELETE, a version's file cannot be deleted and no document's
  checksum can change. Any version reads against the one before as a
  line diff.
- Paper copies: the id <code>-P<n> to write on the paper or print as a
  90 x 50 mm label with a QR code; where it lies, its state and holder,
  each move journaled; found again by its id.
- The journal: every change in words, in the change's transaction, each
  entry chained to the one before by SHA-256. The database refuses to
  change, delete or truncate it; /journal checks the chain and every
  version's text and fingerprints against its entry, shows the last hash
  and exports CSV.

The sidebar groups its sections: Legal, Visas and stays, Office. Demo data
(seed-demo) adds three lawyers, six clients and seven contracts with
versions, papers and moves. Documents take a third owner, the client
(migration 0009).

Checks: fmt, clippy, 115 unit and 62 integration tests (new: versions and
the journal, the database refusing changes, a change around the app
breaking the chain, paper ids and moves, the demo checking whole);
screenshots of the new pages in light, dark and on a phone.
2026-11-21 23:20:20 +07:00

572 lines
17 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?;
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))
}