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.
1036 lines
32 KiB
Rust
1036 lines
32 KiB
Rust
//! The legal practice (phase 9): its lawyers, its clients (people and
|
|
//! organizations, Thai or foreign: artists, labels, festivals, companies),
|
|
//! and their contracts. A contract is a general one (services, employment,
|
|
//! a lease, a sale ...) or one of the artist contracts (recording,
|
|
//! management, publishing, performance ...). It has versions that never
|
|
//! change, each a text kept here, a file (a draft as PDF, the scan of the
|
|
//! signed paper) or both, and paper copies with an id written on them and
|
|
//! the place where they lie. Every change goes into the journal
|
|
//! (`journal.rs`) in words: what was added, and each field from what to what.
|
|
//!
|
|
//! Lawyers, clients and contracts are records (`records.rs`), so their
|
|
//! forms, checks and pages work as the companies' do.
|
|
|
|
use anyhow::{Result, bail};
|
|
use chrono::{DateTime, NaiveDate, Utc};
|
|
use serde::Serialize;
|
|
use sqlx::{PgConnection, PgPool};
|
|
|
|
use crate::agreements;
|
|
use crate::audit::Entity;
|
|
use crate::dates::{self, Status};
|
|
use crate::files;
|
|
use crate::forms::{Errors, err};
|
|
use crate::journal;
|
|
use crate::records::{self, DateOrder, Field, Input, Kind, Options, Values, field, no_status, val};
|
|
|
|
/// The longest contract text kept, in characters.
|
|
pub const BODY_LIMIT: usize = 400_000;
|
|
|
|
pub const LAWYER_STATUSES: &[(&str, &str)] =
|
|
&[("active", "In the team"), ("left", "Left the team")];
|
|
|
|
pub const CLIENT_KINDS: &[(&str, &str)] = &[
|
|
("person", "A person"),
|
|
(
|
|
"organization",
|
|
"An organization: a company, a label, a festival",
|
|
),
|
|
];
|
|
|
|
pub const CLIENT_STATUSES: &[(&str, &str)] =
|
|
&[("active", "Current client"), ("former", "Former client")];
|
|
|
|
/// The general contracts, then the artists' ones.
|
|
pub const CONTRACT_KINDS: &[(&str, &str)] = &[
|
|
("service", "Service agreement"),
|
|
("employment", "Employment contract"),
|
|
("lease", "Lease"),
|
|
("sale", "Sale and purchase"),
|
|
("loan", "Loan"),
|
|
("nda", "Non-disclosure agreement"),
|
|
("partnership", "Partnership or shareholders' agreement"),
|
|
("sponsorship", "Sponsorship"),
|
|
("artist-recording", "Artist: recording agreement"),
|
|
("artist-management", "Artist: management agreement"),
|
|
("artist-publishing", "Artist: music publishing"),
|
|
("artist-performance", "Artist: performance or booking"),
|
|
("artist-license", "Artist: license of recordings or works"),
|
|
("artist-merchandise", "Artist: merchandise"),
|
|
("other", "Other"),
|
|
];
|
|
|
|
pub fn is_artist(kind: &str) -> bool {
|
|
kind.starts_with("artist-")
|
|
}
|
|
|
|
pub const CONTRACT_STATUSES: &[(&str, &str)] = &[
|
|
("draft", "Draft"),
|
|
("negotiation", "In negotiation"),
|
|
("signed", "Signed, not yet in force"),
|
|
("active", "In force"),
|
|
("ended", "Ended"),
|
|
("terminated", "Terminated"),
|
|
("dropped", "Not concluded"),
|
|
];
|
|
|
|
pub const PAPER_STATES: &[(&str, &str)] = &[
|
|
("filed", "Filed"),
|
|
("out", "Taken out"),
|
|
("handed-over", "Handed over"),
|
|
("destroyed", "Destroyed"),
|
|
];
|
|
|
|
/// Suggestions for a paper copy's description.
|
|
pub const PAPER_WHATS: &[&str] = &[
|
|
"Signed original",
|
|
"Signed counterpart",
|
|
"Certified copy",
|
|
"Copy",
|
|
"Draft with handwritten changes",
|
|
];
|
|
|
|
// ------------------------------------------------------------- lawyers
|
|
|
|
const LAWYER_FIELDS: &[Field] = &[
|
|
field("name", "Name", Input::Text)
|
|
.req("Enter the lawyer's name.")
|
|
.wide(),
|
|
field("name_th", "Name in Thai", Input::Text).wide(),
|
|
field("license_no", "Lawyer's license number", Input::Text)
|
|
.hint("From the Lawyers Council of Thailand, as on the license card."),
|
|
field("status", "Status", Input::Choice(LAWYER_STATUSES)).req("Choose the status."),
|
|
field("email", "Email", Input::Text),
|
|
field("phone", "Phone", Input::Text),
|
|
field("login", "Login at id.cnx.network", Input::Text)
|
|
.hint("For a lawyer who uses this app: their contracts then show under My contracts."),
|
|
field("notes", "Notes", Input::Area),
|
|
];
|
|
|
|
pub static LAWYERS: Kind = Kind {
|
|
slug: "lawyers",
|
|
table: "lawyers",
|
|
entity: Entity::Lawyer,
|
|
one: "lawyer",
|
|
title: "Lawyers",
|
|
lead: "The lawyers of the team. Each client and each contract has a lawyer in charge.",
|
|
fields: LAWYER_FIELDS,
|
|
headline: &["name"],
|
|
order: "status, lower(name), id",
|
|
date_order: &[],
|
|
check: no_more,
|
|
status: no_status,
|
|
per_person: false,
|
|
};
|
|
|
|
// ------------------------------------------------------------- clients
|
|
|
|
const CLIENT_FIELDS: &[Field] = &[
|
|
field("kind", "Client", Input::Choice(CLIENT_KINDS)).req("Choose a person or an organization."),
|
|
field("name", "Name", Input::Text)
|
|
.req("Enter the client's name.")
|
|
.hint("A person's name as in their ID card or passport; an organization's as registered.")
|
|
.wide(),
|
|
field("name_th", "Name in Thai", Input::Text).wide(),
|
|
field("known_as", "Known as", Input::Text)
|
|
.hint("An artist's stage name, a label's or a festival's brand."),
|
|
field("nationality", "Nationality", Input::Text)
|
|
.hint("Thai, or the country of the passport; empty for an organization."),
|
|
field("thai_id", "Thai ID number", Input::Digits)
|
|
.section("Identification")
|
|
.hint("The 13 digits on a Thai ID card, or on a pink card."),
|
|
field("passport_no", "Passport number", Input::Code).hint("For a foreigner."),
|
|
field("registration_no", "Registration number", Input::Digits)
|
|
.hint("An organization's 13-digit juristic person number, which is also its tax ID."),
|
|
field("contact_person", "Contact person", Input::Text)
|
|
.section("Contact")
|
|
.hint("Who speaks for an organization, or a person's manager."),
|
|
field("email", "Email", Input::Text),
|
|
field("phone", "Phone", Input::Text),
|
|
field("address", "Address", Input::Area),
|
|
field("lawyer_id", "Lawyer in charge", Input::Lawyer).section("At Lanna Desk"),
|
|
field("status", "Status", Input::Choice(CLIENT_STATUSES)).req("Choose the status."),
|
|
field("notes", "Notes", Input::Area),
|
|
];
|
|
|
|
fn client_check(v: &Values, e: &mut Errors) {
|
|
let id = val(v, "thai_id");
|
|
if !id.is_empty() && !records::thai_id_valid(id) {
|
|
err(
|
|
e,
|
|
"thai_id",
|
|
"This is not a valid Thai ID number: check the 13 digits.",
|
|
);
|
|
}
|
|
let reg = val(v, "registration_no");
|
|
if !reg.is_empty() && reg.len() != 13 {
|
|
err(e, "registration_no", "The number has 13 digits.");
|
|
}
|
|
}
|
|
|
|
pub static CLIENTS: Kind = Kind {
|
|
slug: "clients",
|
|
table: "clients",
|
|
entity: Entity::Client,
|
|
one: "client",
|
|
title: "Clients",
|
|
lead: "A person or an organization, Thai or foreign, whom Lanna Desk advises or acts for.",
|
|
fields: CLIENT_FIELDS,
|
|
headline: &["name"],
|
|
order: "status, lower(name), id",
|
|
date_order: &[],
|
|
check: client_check,
|
|
status: no_status,
|
|
per_person: false,
|
|
};
|
|
|
|
// ----------------------------------------------------------- contracts
|
|
|
|
const CONTRACT_FIELDS: &[Field] = &[
|
|
field("title", "Title", Input::Text)
|
|
.req("Give the contract a title.")
|
|
.hint("As the parties call it, such as: Recording agreement for the album Blue Hour.")
|
|
.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("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"),
|
|
field("starts_on", "In force from", Input::Date),
|
|
field("ends_on", "Ends on", Input::Date),
|
|
field("notice_by", "Notice by", Input::Date)
|
|
.hint("The last day to give notice, for a contract that renews unless one side ends it."),
|
|
field("value_thb", "Value in THB", Input::Amount)
|
|
.hint("The fee, the price or the advance, as the contract states it."),
|
|
field("notes", "Notes", Input::Area),
|
|
];
|
|
|
|
fn no_more(_: &Values, _: &mut Errors) {}
|
|
|
|
/// A chip for a contract still under way, and for one in force with an end
|
|
/// or a notice day near; None for a contract that is over.
|
|
fn contract_status(v: &Values, today: NaiveDate) -> Option<Status> {
|
|
let chip = |level, label: &str| {
|
|
Some(Status {
|
|
level,
|
|
label: label.to_string(),
|
|
})
|
|
};
|
|
let soon = |name: &str, days: i64| {
|
|
dates::parse_date(val(v, name)).filter(|d| (*d - today).num_days() <= days)
|
|
};
|
|
match val(v, "status") {
|
|
"draft" => chip("warn", "Draft"),
|
|
"negotiation" => chip("warn", "In negotiation"),
|
|
"signed" => chip("ok", "Signed"),
|
|
"active" => {
|
|
if let Some(d) = soon("notice_by", 45) {
|
|
chip("bad", &format!("Notice by {}", dates::fmt_date(d)))
|
|
} else if let Some(d) = soon("ends_on", 60) {
|
|
chip("warn", &format!("Ends {}", dates::fmt_date(d)))
|
|
} else {
|
|
chip("ok", "In force")
|
|
}
|
|
}
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
pub static CONTRACTS: Kind = Kind {
|
|
slug: "contracts",
|
|
table: "contracts",
|
|
entity: Entity::Contract,
|
|
one: "contract",
|
|
title: "Contracts",
|
|
lead: "The contract's facts. Its texts and files are its versions, which are added on the contract's page and never change.",
|
|
fields: CONTRACT_FIELDS,
|
|
headline: &["title"],
|
|
order: "id DESC",
|
|
date_order: &[
|
|
DateOrder {
|
|
earlier: "starts_on",
|
|
later: "ends_on",
|
|
target: "ends_on",
|
|
message: "The contract cannot end before it is in force.",
|
|
},
|
|
DateOrder {
|
|
earlier: "notice_by",
|
|
later: "ends_on",
|
|
target: "notice_by",
|
|
message: "The notice day comes before the end.",
|
|
},
|
|
],
|
|
check: no_more,
|
|
status: contract_status,
|
|
per_person: false,
|
|
};
|
|
|
|
/// The lawyers and clients to choose from, by id: lawyers who left say so.
|
|
pub async fn options(db: &PgPool) -> Result<Options> {
|
|
let lawyers: Vec<(i64, String, String)> =
|
|
sqlx::query_as("SELECT id, name, status FROM lawyers ORDER BY status, lower(name), id")
|
|
.fetch_all(db)
|
|
.await?;
|
|
let clients: Vec<(i64, String, String)> =
|
|
sqlx::query_as("SELECT id, name, known_as FROM clients ORDER BY status, lower(name), id")
|
|
.fetch_all(db)
|
|
.await?;
|
|
Ok(Options {
|
|
lawyers: lawyers
|
|
.into_iter()
|
|
.map(|(id, n, s)| {
|
|
let label = if s == "left" {
|
|
format!("{n} (left)")
|
|
} else {
|
|
n
|
|
};
|
|
(id.to_string(), label)
|
|
})
|
|
.collect(),
|
|
clients: clients
|
|
.into_iter()
|
|
.map(|(id, n, k)| {
|
|
let label = if k.is_empty() || k == n {
|
|
n
|
|
} else {
|
|
format!("{n} ({k})")
|
|
};
|
|
(id.to_string(), label)
|
|
})
|
|
.collect(),
|
|
..Options::default()
|
|
})
|
|
}
|
|
|
|
/// A record as the journal states it: every field with a value.
|
|
pub fn detail_of(kind: &Kind, v: &Values, opts: &Options) -> String {
|
|
kind.fields
|
|
.iter()
|
|
.filter(|f| !val(v, f.name).is_empty())
|
|
.map(|f| {
|
|
format!(
|
|
"{}: {}",
|
|
f.label,
|
|
records::shown_value(f, val(v, f.name), opts).text
|
|
)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join("; ")
|
|
}
|
|
|
|
/// A change as the journal states it: each field from what to what. Empty
|
|
/// when nothing changed.
|
|
pub fn changes_of(kind: &Kind, old: &Values, new: &Values, opts: &Options) -> String {
|
|
let shown = |f: &Field, v: &Values| {
|
|
let raw = val(v, f.name);
|
|
if raw.is_empty() {
|
|
"(empty)".to_string()
|
|
} else {
|
|
records::shown_value(f, raw, opts).text
|
|
}
|
|
};
|
|
kind.fields
|
|
.iter()
|
|
.filter(|f| val(old, f.name) != val(new, f.name))
|
|
.map(|f| format!("{}: {} -> {}", f.label, shown(f, old), shown(f, new)))
|
|
.collect::<Vec<_>>()
|
|
.join("; ")
|
|
}
|
|
|
|
// ------------------------------------------------------- the contracts
|
|
|
|
/// What the contract page needs beyond its fields.
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Head {
|
|
pub id: i64,
|
|
pub code: String,
|
|
pub client_id: i64,
|
|
pub title: String,
|
|
pub created_by: String,
|
|
pub created_at: DateTime<Utc>,
|
|
}
|
|
|
|
pub async fn head(db: &PgPool, id: i64) -> Result<Option<Head>> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT id, code, client_id, title, created_by, created_at FROM contracts WHERE id = $1",
|
|
)
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
/// The head of a contract inside a transaction, as `head` reads it.
|
|
pub async fn head_of(conn: &mut PgConnection, id: i64) -> Result<Head> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT id, code, client_id, title, created_by, created_at FROM contracts WHERE id = $1",
|
|
)
|
|
.bind(id)
|
|
.fetch_one(conn)
|
|
.await?)
|
|
}
|
|
|
|
/// A new contract from its form's values; returns its id and code.
|
|
pub async fn create_contract(
|
|
conn: &mut PgConnection,
|
|
v: &Values,
|
|
by: &str,
|
|
) -> Result<(i64, String)> {
|
|
let id = records::create(&mut *conn, &CONTRACTS, None, v).await?;
|
|
let code: String =
|
|
sqlx::query_scalar("UPDATE contracts SET created_by = $2 WHERE id = $1 RETURNING code")
|
|
.bind(id)
|
|
.bind(by)
|
|
.fetch_one(conn)
|
|
.await?;
|
|
Ok((id, code))
|
|
}
|
|
|
|
/// One row of the Contracts page or a client's contracts.
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Listed {
|
|
pub id: i64,
|
|
pub code: String,
|
|
pub title: String,
|
|
pub kind: String,
|
|
pub status: String,
|
|
pub client_id: i64,
|
|
pub client: String,
|
|
pub counterparty: String,
|
|
pub lawyer_id: Option<i64>,
|
|
pub lawyer: Option<String>,
|
|
pub ends_on: Option<NaiveDate>,
|
|
pub notice_by: Option<NaiveDate>,
|
|
pub versions: i64,
|
|
pub papers: i64,
|
|
}
|
|
|
|
/// Which contracts a list shows.
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct Filter {
|
|
pub client: Option<i64>,
|
|
pub lawyer: Option<i64>,
|
|
/// "artist" or "general"
|
|
pub group: Option<String>,
|
|
/// Contracts that are over too.
|
|
pub all: bool,
|
|
}
|
|
|
|
pub async fn list_contracts(db: &PgPool, f: &Filter) -> Result<Vec<Listed>> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT c.id, c.code, c.title, c.kind, c.status, c.client_id, cl.name AS client, \
|
|
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 \
|
|
LEFT JOIN lawyers l ON l.id = c.lawyer_id \
|
|
WHERE ($1::bigint IS NULL OR c.client_id = $1) \
|
|
AND ($2::bigint IS NULL OR c.lawyer_id = $2) \
|
|
AND ($3::text IS NULL OR (c.kind LIKE 'artist-%') = ($3 = 'artist')) \
|
|
AND ($4 OR c.status NOT IN ('ended', 'terminated', 'dropped')) \
|
|
ORDER BY c.id DESC",
|
|
)
|
|
.bind(f.client)
|
|
.bind(f.lawyer)
|
|
.bind(f.group.as_deref())
|
|
.bind(f.all)
|
|
.fetch_all(db)
|
|
.await?)
|
|
}
|
|
|
|
/// The id of the lawyer who signs in as `login`, if one does.
|
|
pub async fn lawyer_of_login(db: &PgPool, login: &str) -> Result<Option<i64>> {
|
|
if login.is_empty() {
|
|
return Ok(None);
|
|
}
|
|
Ok(
|
|
sqlx::query_scalar("SELECT id FROM lawyers WHERE login = $1 ORDER BY id LIMIT 1")
|
|
.bind(login)
|
|
.fetch_optional(db)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
/// One card of the Clients page.
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct ClientRow {
|
|
pub id: i64,
|
|
pub kind: String,
|
|
pub name: String,
|
|
pub name_th: String,
|
|
pub known_as: String,
|
|
pub nationality: String,
|
|
pub status: String,
|
|
pub email: String,
|
|
pub phone: String,
|
|
pub lawyer: Option<String>,
|
|
pub contracts: i64,
|
|
pub open: i64,
|
|
pub artist: i64,
|
|
pub last: Option<DateTime<Utc>>,
|
|
}
|
|
|
|
pub async fn list_clients(db: &PgPool, former: bool) -> Result<Vec<ClientRow>> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT cl.id, cl.kind, cl.name, cl.name_th, cl.known_as, cl.nationality, cl.status, \
|
|
cl.email, cl.phone, l.name AS lawyer, \
|
|
(SELECT count(*) FROM contracts c WHERE c.client_id = cl.id) AS contracts, \
|
|
(SELECT count(*) FROM contracts c WHERE c.client_id = cl.id \
|
|
AND c.status NOT IN ('ended', 'terminated', 'dropped')) AS open, \
|
|
(SELECT count(*) FROM contracts c WHERE c.client_id = cl.id \
|
|
AND c.kind LIKE 'artist-%') AS artist, \
|
|
(SELECT max(j.at) FROM journal j WHERE j.client_id = cl.id) AS last \
|
|
FROM clients cl LEFT JOIN lawyers l ON l.id = cl.lawyer_id \
|
|
WHERE (cl.status = 'former') = $1 ORDER BY lower(cl.name), cl.id",
|
|
)
|
|
.bind(former)
|
|
.fetch_all(db)
|
|
.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<Utc>,
|
|
pub removed_by: Option<String>,
|
|
pub removed_at: Option<DateTime<Utc>>,
|
|
}
|
|
|
|
/// The parties of a contract in the order they were added, the removed
|
|
/// ones too.
|
|
pub async fn parties(db: &PgPool, contract: i64) -> Result<Vec<Party>> {
|
|
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<Party> {
|
|
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<bool> {
|
|
let row: Option<Party> = 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)]
|
|
pub struct Version {
|
|
pub id: i64,
|
|
pub contract_id: i64,
|
|
pub version: i32,
|
|
pub note: String,
|
|
pub body: String,
|
|
pub body_sha256: Option<String>,
|
|
pub document_id: Option<i64>,
|
|
pub file_sha256: Option<String>,
|
|
pub added_by: String,
|
|
pub added_at: DateTime<Utc>,
|
|
}
|
|
|
|
/// The newest first.
|
|
pub async fn versions(db: &PgPool, contract: i64) -> Result<Vec<Version>> {
|
|
Ok(sqlx::query_as(
|
|
"SELECT * FROM contract_versions WHERE contract_id = $1 ORDER BY version DESC",
|
|
)
|
|
.bind(contract)
|
|
.fetch_all(db)
|
|
.await?)
|
|
}
|
|
|
|
/// The file of a new version, stored already as the client's document.
|
|
pub struct VersionFile<'a> {
|
|
pub document: i64,
|
|
pub sha256: &'a str,
|
|
pub name: &'a str,
|
|
}
|
|
|
|
/// Adds a version, numbered after the last, and its journal entry.
|
|
pub async fn add_version(
|
|
conn: &mut PgConnection,
|
|
head: &Head,
|
|
note: &str,
|
|
body: &str,
|
|
file: Option<&VersionFile<'_>>,
|
|
by: &str,
|
|
) -> Result<Version> {
|
|
let body = agreements::normalize(body);
|
|
if body.is_empty() && file.is_none() {
|
|
bail!("a version without a text or a file");
|
|
}
|
|
// the contract's row orders its versions and papers
|
|
sqlx::query("SELECT id FROM contracts WHERE id = $1 FOR UPDATE")
|
|
.bind(head.id)
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
let body_sha = (!body.is_empty()).then(|| files::sha256_hex(body.as_bytes()));
|
|
let v: Version = sqlx::query_as(
|
|
"INSERT INTO contract_versions (contract_id, version, note, body, body_sha256, \
|
|
document_id, file_sha256, added_by) \
|
|
VALUES ($1, (SELECT COALESCE(max(version), 0) + 1 FROM contract_versions \
|
|
WHERE contract_id = $1), $2, $3, $4, $5, $6, $7) RETURNING *",
|
|
)
|
|
.bind(head.id)
|
|
.bind(note.trim())
|
|
.bind(&body)
|
|
.bind(&body_sha)
|
|
.bind(file.map(|f| f.document))
|
|
.bind(file.map(|f| f.sha256))
|
|
.bind(by)
|
|
.fetch_one(&mut *conn)
|
|
.await?;
|
|
let mut detail = format!("{} {}", journal::version_tag(v.version), note.trim());
|
|
if let Some(h) = &body_sha {
|
|
detail.push_str(&format!(
|
|
" Text: {} characters, SHA-256 {h}.",
|
|
body.chars().count()
|
|
));
|
|
}
|
|
if let Some(f) = file {
|
|
detail.push_str(&format!(
|
|
" File: {} (document {}), SHA-256 {}.",
|
|
f.name, f.document, f.sha256
|
|
));
|
|
}
|
|
journal::append(
|
|
conn,
|
|
&journal::New {
|
|
actor: by,
|
|
client: Some(head.client_id),
|
|
contract: Some(head.id),
|
|
event: "version added",
|
|
detail,
|
|
},
|
|
)
|
|
.await?;
|
|
Ok(v)
|
|
}
|
|
|
|
// -------------------------------------------------------- paper copies
|
|
|
|
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
|
|
pub struct Paper {
|
|
pub id: i64,
|
|
pub code: String,
|
|
pub contract_id: i64,
|
|
pub version_id: Option<i64>,
|
|
pub what: String,
|
|
pub location: String,
|
|
pub state: String,
|
|
pub holder: String,
|
|
pub created_by: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub moved_at: DateTime<Utc>,
|
|
}
|
|
|
|
pub async fn papers(db: &PgPool, contract: i64) -> Result<Vec<Paper>> {
|
|
Ok(
|
|
sqlx::query_as("SELECT * FROM paper_copies WHERE contract_id = $1 ORDER BY id")
|
|
.bind(contract)
|
|
.fetch_all(db)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
pub async fn paper(db: &PgPool, id: i64) -> Result<Option<Paper>> {
|
|
Ok(sqlx::query_as("SELECT * FROM paper_copies WHERE id = $1")
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
/// A paper by the id written on it, in any case and with stray spaces.
|
|
pub async fn paper_by_code(db: &PgPool, code: &str) -> Result<Option<Paper>> {
|
|
let code: String = code
|
|
.chars()
|
|
.filter(|c| !c.is_whitespace())
|
|
.collect::<String>()
|
|
.to_uppercase();
|
|
Ok(sqlx::query_as("SELECT * FROM paper_copies WHERE code = $1")
|
|
.bind(code)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
/// Every place papers lie or lay, for the form's suggestions.
|
|
pub async fn locations(db: &PgPool) -> Result<Vec<String>> {
|
|
Ok(
|
|
sqlx::query_scalar(
|
|
"SELECT DISTINCT location FROM paper_copies ORDER BY location LIMIT 200",
|
|
)
|
|
.fetch_all(db)
|
|
.await?,
|
|
)
|
|
}
|
|
|
|
pub fn paper_state(slug: &str) -> &'static str {
|
|
records::label(PAPER_STATES, slug).unwrap_or("Filed")
|
|
}
|
|
|
|
/// Registers a paper copy: it gets the contract's code with P and its
|
|
/// number (LD-2026-0007-P2), and a journal entry.
|
|
pub async fn add_paper(
|
|
conn: &mut PgConnection,
|
|
head: &Head,
|
|
version: Option<&Version>,
|
|
what: &str,
|
|
location: &str,
|
|
by: &str,
|
|
) -> Result<Paper> {
|
|
sqlx::query("SELECT id FROM contracts WHERE id = $1 FOR UPDATE")
|
|
.bind(head.id)
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
let n: i64 = sqlx::query_scalar("SELECT count(*) + 1 FROM paper_copies WHERE contract_id = $1")
|
|
.bind(head.id)
|
|
.fetch_one(&mut *conn)
|
|
.await?;
|
|
let code = format!("{}-P{n}", head.code);
|
|
let p: Paper = sqlx::query_as(
|
|
"INSERT INTO paper_copies (code, contract_id, version_id, what, location, created_by) \
|
|
VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
|
|
)
|
|
.bind(&code)
|
|
.bind(head.id)
|
|
.bind(version.map(|v| v.id))
|
|
.bind(what.trim())
|
|
.bind(location.trim())
|
|
.bind(by)
|
|
.fetch_one(&mut *conn)
|
|
.await?;
|
|
let of = match version {
|
|
Some(v) => format!(" of version {}", v.version),
|
|
None => String::new(),
|
|
};
|
|
journal::append(
|
|
conn,
|
|
&journal::New {
|
|
actor: by,
|
|
client: Some(head.client_id),
|
|
contract: Some(head.id),
|
|
event: "paper registered",
|
|
detail: format!("{code}: {}{of}, filed at {}.", p.what, p.location),
|
|
},
|
|
)
|
|
.await?;
|
|
Ok(p)
|
|
}
|
|
|
|
/// Where a paper went: its new place, state and holder, and a note.
|
|
#[derive(Debug)]
|
|
pub struct Move<'a> {
|
|
pub location: &'a str,
|
|
pub state: &'a str,
|
|
pub holder: &'a str,
|
|
pub note: &'a str,
|
|
}
|
|
|
|
/// Records a move; false when nothing changed.
|
|
pub async fn move_paper(
|
|
conn: &mut PgConnection,
|
|
head: &Head,
|
|
old: &Paper,
|
|
m: &Move<'_>,
|
|
by: &str,
|
|
) -> Result<bool> {
|
|
let state = m.state;
|
|
let (location, holder, note) = (m.location.trim(), m.holder.trim(), m.note.trim());
|
|
let mut said = Vec::new();
|
|
if location != old.location {
|
|
said.push(format!("from {} to {location}", old.location));
|
|
}
|
|
if state != old.state {
|
|
said.push(format!(
|
|
"{} -> {}",
|
|
paper_state(&old.state),
|
|
paper_state(state)
|
|
));
|
|
}
|
|
if holder != old.holder {
|
|
said.push(if holder.is_empty() {
|
|
format!("no longer with {}", old.holder)
|
|
} else {
|
|
format!("with {holder}")
|
|
});
|
|
}
|
|
if said.is_empty() {
|
|
return Ok(false);
|
|
}
|
|
sqlx::query(
|
|
"UPDATE paper_copies SET location = $2, state = $3, holder = $4, moved_at = now() \
|
|
WHERE id = $1",
|
|
)
|
|
.bind(old.id)
|
|
.bind(location)
|
|
.bind(state)
|
|
.bind(holder)
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
let mut detail = format!("{}: {}.", old.code, said.join(", "));
|
|
if !note.is_empty() {
|
|
detail.push_str(&format!(" {note}"));
|
|
}
|
|
journal::append(
|
|
conn,
|
|
&journal::New {
|
|
actor: by,
|
|
client: Some(head.client_id),
|
|
contract: Some(head.id),
|
|
event: "paper moved",
|
|
detail,
|
|
},
|
|
)
|
|
.await?;
|
|
Ok(true)
|
|
}
|
|
|
|
// ---------------------------------------------------------------- diff
|
|
|
|
/// A line of the comparison of two versions' texts.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
|
pub struct DiffLine {
|
|
/// "same", "added" or "removed"
|
|
pub op: &'static str,
|
|
pub text: String,
|
|
}
|
|
|
|
/// The lines of `b` against those of `a`, by their longest common
|
|
/// sequence; None when the texts are too long to compare here.
|
|
pub fn diff(a: &str, b: &str) -> Option<Vec<DiffLine>> {
|
|
let a: Vec<&str> = a.lines().collect();
|
|
let b: Vec<&str> = b.lines().collect();
|
|
let (n, m) = (a.len(), b.len());
|
|
if n.saturating_mul(m) > 4_000_000 {
|
|
return None;
|
|
}
|
|
// lcs[i][j]: the common length of a[i..] and b[j..]
|
|
let mut lcs = vec![vec![0u32; m + 1]; n + 1];
|
|
for i in (0..n).rev() {
|
|
for j in (0..m).rev() {
|
|
lcs[i][j] = if a[i] == b[j] {
|
|
lcs[i + 1][j + 1] + 1
|
|
} else {
|
|
lcs[i + 1][j].max(lcs[i][j + 1])
|
|
};
|
|
}
|
|
}
|
|
let line = |op, t: &str| DiffLine {
|
|
op,
|
|
text: t.to_string(),
|
|
};
|
|
let (mut i, mut j, mut out) = (0, 0, Vec::new());
|
|
while i < n && j < m {
|
|
if a[i] == b[j] {
|
|
out.push(line("same", a[i]));
|
|
i += 1;
|
|
j += 1;
|
|
} else if lcs[i + 1][j] >= lcs[i][j + 1] {
|
|
out.push(line("removed", a[i]));
|
|
i += 1;
|
|
} else {
|
|
out.push(line("added", b[j]));
|
|
j += 1;
|
|
}
|
|
}
|
|
out.extend(a[i..].iter().map(|t| line("removed", t)));
|
|
out.extend(b[j..].iter().map(|t| line("added", t)));
|
|
Some(out)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn the_diff_shows_what_changed_between_versions() {
|
|
let a = "# 1. Term\nTwo years.\n\n# 2. Fee\n10% of net receipts.";
|
|
let b = "# 1. Term\nThree years.\n\n# 2. Fee\n10% of net receipts.\n# 3. Territory";
|
|
let d = diff(a, b).unwrap();
|
|
let ops: Vec<(&str, &str)> = d.iter().map(|l| (l.op, l.text.as_str())).collect();
|
|
assert_eq!(
|
|
ops,
|
|
[
|
|
("same", "# 1. Term"),
|
|
("removed", "Two years."),
|
|
("added", "Three years."),
|
|
("same", ""),
|
|
("same", "# 2. Fee"),
|
|
("same", "10% of net receipts."),
|
|
("added", "# 3. Territory"),
|
|
]
|
|
);
|
|
assert!(diff("a", "a").unwrap().iter().all(|l| l.op == "same"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_contract_in_force_warns_of_its_notice_day_and_end() {
|
|
let today = NaiveDate::from_ymd_opt(2026, 11, 21).unwrap();
|
|
let mut v = Values::new();
|
|
v.insert("status".into(), "active".into());
|
|
assert_eq!(contract_status(&v, today).unwrap().label, "In force");
|
|
v.insert("ends_on".into(), "2027-01-10".into());
|
|
assert_eq!(contract_status(&v, today).unwrap().level, "warn");
|
|
v.insert("notice_by".into(), "2026-12-01".into());
|
|
let s = contract_status(&v, today).unwrap();
|
|
assert_eq!(
|
|
(s.level, s.label.as_str()),
|
|
("bad", "Notice by Dec 1, 2026")
|
|
);
|
|
v.insert("status".into(), "ended".into());
|
|
assert!(contract_status(&v, today).is_none(), "history");
|
|
}
|
|
|
|
#[test]
|
|
fn the_journal_states_a_change_field_by_field() {
|
|
let mut old = Values::new();
|
|
old.insert("title".into(), "Recording agreement".into());
|
|
old.insert("status".into(), "draft".into());
|
|
let mut new = old.clone();
|
|
new.insert("status".into(), "active".into());
|
|
new.insert("notes".into(), "Signed at the label".into());
|
|
let opts = Options::default();
|
|
assert_eq!(
|
|
changes_of(&CONTRACTS, &old, &new, &opts),
|
|
"Status: Draft -> In force; Notes: (empty) -> Signed at the label"
|
|
);
|
|
assert!(changes_of(&CONTRACTS, &old, &old, &opts).is_empty());
|
|
assert_eq!(
|
|
detail_of(&CONTRACTS, &old, &opts),
|
|
"Title: Recording agreement; Status: Draft"
|
|
);
|
|
}
|
|
}
|