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.
This commit is contained in:
1 parent
f7fb2c7af4
commit
9ae4d7bd07
16 files changed
+1464
-25
No files matched your search
+310
-16
@@ -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<Hit>,
|
||||
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<Result<String, Check>> {
|
||||
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<AppState>, user: User, q: New
|
||||
&opts,
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
&Check::default(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -167,9 +227,37 @@ pub async fn create(kind: &'static Kind, st: Arc<AppState>, 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<AppState>, 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<AppState>, user: User, id: i
|
||||
&opts,
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
&Check::default(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -230,9 +324,9 @@ pub async fn update(kind: &'static Kind, st: Arc<AppState>, 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<AppState>, 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<AppState>, 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<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
removed_by: Option<String>,
|
||||
}
|
||||
|
||||
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<PartyView> = 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<i64>,
|
||||
Query(q): Query<ContractQuery>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
Form(f): Form<Fields>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Query(q): Query<ConflictQuery>,
|
||||
) -> 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<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
|
||||
Reference in new issue
Block a user