Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ae4d7bd07 | ||
|
|
f7fb2c7af4 | ||
|
|
684dd27bad | ||
|
|
e9066c0445 |
No files matched your search
+115
-1
@@ -19,7 +19,8 @@
|
||||
> its `/` now leads to the back office, and the texts clients read name Lanna
|
||||
> Desk rather than B4L. Phase 9, the legal practice
|
||||
> (clients, lawyers, contracts with versions, paper copies, the journal),
|
||||
> followed that night. **Resume here: phase 8, reminders.**
|
||||
> followed that night, and phase 10, one client list, was planned. **Resume
|
||||
> here: phase 8, reminders, or phase 10, whose questions are decided.**
|
||||
|
||||
Lanna Desk keeps the immigration records of the foreigners that it
|
||||
looks after: their passports, addresses in Thailand, arrivals with the Thailand
|
||||
@@ -244,6 +245,8 @@ dark at desktop and phone width, a commit and a push.
|
||||
| 7 | The client link: a client fills in their own record on a phone, the MRZ read from a photo, and signs Lanna Desk's agreements | built Nov 20, 2026 |
|
||||
| 8 | Reminders by Matrix room message and by email | |
|
||||
| 9 | The legal practice: lawyers, clients (Thai and foreign, people and organizations), general and artist contracts with versions that never change, paper copies with ids and places, the journal as a hash-chained ledger | built Nov 21, 2026 |
|
||||
| 10 | One client list: a visa record becomes part of a client; People becomes the visa clients | planned Nov 21, 2026 |
|
||||
| 11 | The conflict check and the other parties of a contract; the journal's last hash sent outside the server each day | step 1 built Nov 22, 2026 |
|
||||
| later | Thai user interface, agency cases and fees, other visa categories' packs | |
|
||||
|
||||
### Phase 1: app, login, people
|
||||
@@ -581,6 +584,117 @@ message, the backup); contract templates; signing contracts on the client
|
||||
link; reminders of notice days and ends (phase 8); links between a client
|
||||
and their visa record.
|
||||
|
||||
### Phase 10: one client list (planned)
|
||||
|
||||
Since phase 9 there are two lists of the people Lanna Desk works for:
|
||||
Clients (the legal practice) and People (the visa records), and nothing ties
|
||||
Erika's visa record to a client. Alex asked on November 21, 2026 whether
|
||||
People should become Clients; the plan is one list in which a visa record is
|
||||
part of a client. Not started: build it when Alex says so.
|
||||
|
||||
**The model.** `clients` is everyone Lanna Desk works for. `people` stays as
|
||||
the visa record of a person client, so passports, addresses, stays,
|
||||
documents, client links, signatures, the deadlines, the forms, the pack and
|
||||
the audit log keep their `person_id` and work as they do.
|
||||
|
||||
- `people.client_id` references `clients`, unique and, once filled, not
|
||||
null: a client has at most one visa record, every visa record has a client.
|
||||
- One place for each fact. The passport-style name (surname, first and
|
||||
middle name, title, sex, date and place of birth) stays on the visa record,
|
||||
since the forms need it as printed. Phone and email move to the client
|
||||
(`people.phone` and `people.email` go after the copy); the client link's
|
||||
Contact page and the forms read them there. A visa client's name on the
|
||||
client list is taken from the visa record ("Erika Mustermann") and is not
|
||||
edited on the client form.
|
||||
- Nationality becomes an ISO alpha-3 code on clients too, with the country
|
||||
list the person form uses, so both say "Germany" the same way.
|
||||
- Archiving is the client's: a former client's visa record is archived with
|
||||
it, and restoring the client restores it.
|
||||
- The audit log keeps the visa side (views and changes of a person); the
|
||||
journal keeps the client, contracts and papers, and adds an entry when a
|
||||
visa record is opened for a client or the client's contact changes.
|
||||
|
||||
**Migration 0010** creates a client for every person (kind person, the name,
|
||||
nationality, phone and email from the person, status from `archived_at`, no
|
||||
lawyer), sets `client_id`, then the constraint, and writes one journal entry
|
||||
per client ("client added from the visa record of person N"). It runs by
|
||||
itself at the first start after cnx01 fetches the release, on the live
|
||||
records, and a rollback does not undo it, so it needs a test that loads
|
||||
people through the migrations up to 0009, applies 0010 and checks every
|
||||
person has its client with the same name and contact.
|
||||
|
||||
**The pages.**
|
||||
|
||||
- Clients: every client; a chip on the cards of those with a visa record and
|
||||
their next deadline; tabs All, With contracts, With a visa record.
|
||||
- A client's page: a "Visa and stay" card with the stay and the next dates,
|
||||
linking to the visa record's pages, which keep their `/people/{id}/...`
|
||||
addresses (client links, bookmarks and audit rows point there). A client
|
||||
without one gets "Open a visa record", which asks for the passport-style
|
||||
name.
|
||||
- The visa record's pages show "Clients / name" above the tabs and a link
|
||||
to the client's contracts.
|
||||
- The sidebar: under Visas and stays, People becomes "Visa clients", the
|
||||
same clients filtered to those with a visa record; Deadlines stays the
|
||||
start page.
|
||||
- "+ New client" on the visa side opens the client and the visa record in
|
||||
one step, as `/people/new-client` does now.
|
||||
|
||||
**Steps.**
|
||||
|
||||
1. Migration 0010, the backfill test, contact read from the client.
|
||||
2. The client page's visa card, the visa pages' crumb, the list filters and
|
||||
the sidebar.
|
||||
3. The client link writes the contact to the client; the journal entries.
|
||||
4. Docs, screenshots, release; on cnx01, `visa-admin` checks that the
|
||||
number of people equals the number of clients with a visa record.
|
||||
|
||||
**Decided with Alex (November 21, 2026).**
|
||||
|
||||
1. A visa client's name reads as on the visa side: "MUSTERMANN, Erika".
|
||||
2. Companies and organization clients become one list too: the company
|
||||
record (registration, address, director, the pack's documents) becomes
|
||||
part of an organization client, as the visa record is part of a person
|
||||
client. Employees stay linked to the company record, so the forms and the
|
||||
pack keep working. This adds a step after step 3: migration 0011 creates
|
||||
an organization client per company, and the company pages move as the
|
||||
visa pages do.
|
||||
3. Every lawyer and staff member sees every client for now. The model leaves
|
||||
room for finer access later (a client's team of lawyers, a role per
|
||||
section), so no page should assume more than the queries enforce.
|
||||
|
||||
### Phase 11: the conflict check and the journal's anchor
|
||||
|
||||
**Step 1 (built November 22, 2026).** A contract's other side was one line
|
||||
of text. Now each other party is a row (`contract_parties`, migration 0010)
|
||||
with its names in English and Thai, an ID, passport or registration number
|
||||
and its role; the old line became the first party. A party is never
|
||||
deleted or rewritten: taking it off marks it removed, and adding and
|
||||
removing are in the journal.
|
||||
|
||||
The conflict check (`src/conflicts.rs`) looks for a 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, or when every word of the shorter name, at least two, is
|
||||
in the longer one; numbers on their letters and digits. What a match means
|
||||
depends on who is checked:
|
||||
|
||||
- a new party that is a client, a visa client or an employer: a conflict;
|
||||
- a new or renamed client that was on the other side of a contract: a
|
||||
conflict; one with a client's name or number: perhaps the same client;
|
||||
- everything else (the same party in another contract, a client who also
|
||||
has a visa record): a note.
|
||||
|
||||
A conflict or a possible duplicate stops the save until a lawyer ticks
|
||||
that they looked at the matches, with what they checked; the matches and
|
||||
the note go into the journal entry of the client or party. A check without
|
||||
a match is noted too. `/conflicts` runs the check alone before a first
|
||||
meeting and saves nothing.
|
||||
|
||||
**Step 2 (next).** Once a day the app sends the journal's last entry
|
||||
number and hash outside the server (email, a Matrix room), so a journal
|
||||
rebuilt by someone with database access no longer matches the copies.
|
||||
|
||||
## Open questions
|
||||
|
||||
1. B4L's BOI application: once B4L is promoted, its staff extend their stay
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
-- Lanna Desk, phase 11, step 1: the other parties of a contract, for the
|
||||
-- conflict check (docs/PLAN.md "Phase 11").
|
||||
--
|
||||
-- A contract had its other side as one line of text. Now each other party
|
||||
-- is a row with its names in English and Thai and its ID, registration or
|
||||
-- passport number, so the conflict check can find it again when the same
|
||||
-- name or number comes back as a client. A contract can have several: the
|
||||
-- label and the publisher, the venue and the promoter.
|
||||
--
|
||||
-- A party is never deleted: taking one off a contract marks it removed,
|
||||
-- and both the adding and the removing are in the journal.
|
||||
|
||||
CREATE TABLE contract_parties (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
contract_id BIGINT NOT NULL REFERENCES contracts (id),
|
||||
name TEXT NOT NULL CHECK (name <> ''),
|
||||
name_th TEXT NOT NULL DEFAULT '',
|
||||
-- a Thai ID number, a passport number or a registration number, as
|
||||
-- given; the check compares its letters and digits only
|
||||
id_no TEXT NOT NULL DEFAULT '',
|
||||
-- what the party is in the contract: label, venue, landlord, employer
|
||||
role TEXT NOT NULL DEFAULT '',
|
||||
added_by TEXT NOT NULL,
|
||||
added_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
removed_by TEXT,
|
||||
removed_at TIMESTAMPTZ,
|
||||
CHECK ((removed_at IS NULL) = (removed_by IS NULL))
|
||||
);
|
||||
CREATE INDEX contract_parties_contract ON contract_parties (contract_id);
|
||||
|
||||
CREATE FUNCTION contract_parties_kept() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
RAISE EXCEPTION 'a party stays on record: mark it removed';
|
||||
END IF;
|
||||
IF NEW.contract_id <> OLD.contract_id OR NEW.name <> OLD.name
|
||||
OR NEW.name_th <> OLD.name_th OR NEW.id_no <> OLD.id_no
|
||||
OR NEW.role <> OLD.role OR NEW.added_by <> OLD.added_by
|
||||
OR NEW.added_at <> OLD.added_at OR OLD.removed_at IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'a party only gets removed: add a new one for a change';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
CREATE TRIGGER contract_parties_no_change
|
||||
BEFORE UPDATE OR DELETE ON contract_parties
|
||||
FOR EACH ROW EXECUTE FUNCTION contract_parties_kept();
|
||||
|
||||
-- The one line each contract had becomes its first party, added by whoever
|
||||
-- opened the contract.
|
||||
INSERT INTO contract_parties (contract_id, name, added_by, added_at)
|
||||
SELECT id, counterparty, CASE WHEN created_by = '' THEN 'migration' ELSE created_by END, created_at
|
||||
FROM contracts WHERE counterparty <> '' ORDER BY id;
|
||||
|
||||
ALTER TABLE contracts DROP COLUMN counterparty;
|
||||
|
||||
ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check;
|
||||
ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK (
|
||||
entity IN (
|
||||
'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival',
|
||||
'extension', 'reentry-permit', 'report', 'work-permit', 'document', 'form', 'link',
|
||||
'agreement', 'signature', 'lawyer', 'client', 'contract', 'contract-version',
|
||||
'paper-copy', 'contract-party'
|
||||
)
|
||||
);
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# The demo instance: the app with invented data on its own database
|
||||
# (visa_demo) and files (.dev/demo-files) on :8041, beside the dev server,
|
||||
# so the dev data stays as it is. Used for the pitch deck's screenshots.
|
||||
# The first start creates the database; dev.sh seeds the demo data (it
|
||||
# adds only what is missing). Start over: drop visa_demo, rm -rf .dev/demo-files.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
export PATH="$HOME/.cargo/bin:/c/Program Files/Git/cmd:$PATH"
|
||||
docker exec visa-pg psql -U visa -d postgres -Atc "SELECT 1 FROM pg_database WHERE datname='visa_demo'" | grep -q 1 ||
|
||||
docker exec visa-pg psql -U visa -d postgres -qc "CREATE DATABASE visa_demo OWNER visa"
|
||||
base=$(sed -n 's/^export VISA_DATABASE_URL=\${VISA_DATABASE_URL:-\(.*\)}$/\1/p' scripts/dev.sh)
|
||||
export VISA_DATABASE_URL="${base%/visa}/visa_demo"
|
||||
export VISA_LISTEN=127.0.0.1:8041
|
||||
export VISA_FILES_DIR=.dev/demo-files
|
||||
exec bash scripts/dev.sh
|
||||
@@ -74,6 +74,7 @@ pub enum Entity {
|
||||
Contract,
|
||||
ContractVersion,
|
||||
PaperCopy,
|
||||
ContractParty,
|
||||
}
|
||||
|
||||
impl Entity {
|
||||
@@ -100,6 +101,7 @@ impl Entity {
|
||||
Entity::Contract => "contract",
|
||||
Entity::ContractVersion => "contract-version",
|
||||
Entity::PaperCopy => "paper-copy",
|
||||
Entity::ContractParty => "contract-party",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//! The conflict check (phase 11): before Lanna Desk takes on a client, or
|
||||
//! writes down who is on the other side of a contract, the app looks for
|
||||
//! the same name or number among everyone it already works for or has
|
||||
//! worked against: the clients, the other parties of the contracts, the
|
||||
//! people on the visa side and the employers.
|
||||
//!
|
||||
//! Names match without regard to case, word order, punctuation or the
|
||||
//! company words around them ("Demo Records Co., Ltd." is "Demo Records",
|
||||
//! "บริษัท เดโม เรคคอร์ดส จำกัด" is "เดโม เรคคอร์ดส"), and when all the words of
|
||||
//! the shorter name, at least two, are in the longer ("Erika Mustermann"
|
||||
//! and "MUSTERMANN, Erika Maria"). Numbers match on their letters and
|
||||
//! digits only. The check finds candidates; a lawyer decides, and the
|
||||
//! decision goes into the journal with what was found.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde::Serialize;
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// Words around a name that say what kind of thing it is, not which.
|
||||
const COMPANY_WORDS: &[&str] = &[
|
||||
"co",
|
||||
"company",
|
||||
"ltd",
|
||||
"limited",
|
||||
"inc",
|
||||
"incorporated",
|
||||
"corp",
|
||||
"corporation",
|
||||
"llc",
|
||||
"plc",
|
||||
"gmbh",
|
||||
"public",
|
||||
"partnership",
|
||||
"the",
|
||||
"and",
|
||||
"mr",
|
||||
"mrs",
|
||||
"ms",
|
||||
"miss",
|
||||
"dr",
|
||||
];
|
||||
|
||||
/// The same in Thai, written into the name without spaces: the longer
|
||||
/// first, so "ห้างหุ้นส่วนจำกัด" goes as a whole.
|
||||
const THAI_COMPANY_WORDS: &[&str] = &[
|
||||
"ห้างหุ้นส่วนจำกัด",
|
||||
"ห้างหุ้นส่วนสามัญ",
|
||||
"ห้างหุ้นส่วน",
|
||||
"บริษัท",
|
||||
"จำกัด",
|
||||
"มหาชน",
|
||||
"หจก",
|
||||
"บจก",
|
||||
"บมจ",
|
||||
];
|
||||
|
||||
/// Titles in front of a Thai person's name.
|
||||
const THAI_TITLES: &[&str] = &["นางสาว", "นาย", "นาง", "น.ส."];
|
||||
|
||||
fn is_thai(c: char) -> bool {
|
||||
('\u{0E00}'..='\u{0E7F}').contains(&c)
|
||||
}
|
||||
|
||||
/// The words of a name that tell it apart, in no order.
|
||||
pub fn words(name: &str) -> BTreeSet<String> {
|
||||
let mut s = name.trim().to_lowercase();
|
||||
for t in THAI_TITLES {
|
||||
if let Some(rest) = s.strip_prefix(t) {
|
||||
s = rest.to_string();
|
||||
break;
|
||||
}
|
||||
}
|
||||
for w in THAI_COMPANY_WORDS {
|
||||
s = s.replace(w, " ");
|
||||
}
|
||||
let cleaned: String = s
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || is_thai(c) {
|
||||
c
|
||||
} else {
|
||||
' '
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
cleaned
|
||||
.split_whitespace()
|
||||
.filter(|w| !COMPANY_WORDS.contains(w))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether two names are the same name, as the check reads them.
|
||||
pub fn same_name(a: &str, b: &str) -> bool {
|
||||
let (a, b) = (words(a), words(b));
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
let (short, long) = if a.len() <= b.len() {
|
||||
(&a, &b)
|
||||
} else {
|
||||
(&b, &a)
|
||||
};
|
||||
short.len() >= 2 && short.is_subset(long)
|
||||
}
|
||||
|
||||
/// A number as compared: its letters and digits, in capitals. Too short a
|
||||
/// number says nothing, so it gives None.
|
||||
pub fn number(s: &str) -> Option<String> {
|
||||
let n: String = s
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric())
|
||||
.collect::<String>()
|
||||
.to_uppercase();
|
||||
(n.len() >= 5).then_some(n)
|
||||
}
|
||||
|
||||
/// What the check looks for.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Probe {
|
||||
pub names: Vec<String>,
|
||||
pub numbers: Vec<String>,
|
||||
}
|
||||
|
||||
impl Probe {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.names.iter().all(|n| n.trim().is_empty())
|
||||
&& self.numbers.iter().all(|n| number(n).is_none())
|
||||
}
|
||||
}
|
||||
|
||||
/// Who is being checked: a client (new, or one already on record), a
|
||||
/// party for a contract of a client, or a name looked up before anyone is
|
||||
/// taken on.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum For {
|
||||
Client(Option<i64>),
|
||||
Party { contract: i64, client: i64 },
|
||||
Search,
|
||||
}
|
||||
|
||||
/// One match.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct Hit {
|
||||
/// "conflict": Lanna Desk would act against someone it works for, or
|
||||
/// for someone it acted against; "same": the same client twice; "note":
|
||||
/// worth knowing, no conflict by itself.
|
||||
pub level: &'static str,
|
||||
pub what: String,
|
||||
pub name: String,
|
||||
pub href: String,
|
||||
/// "same name", "same number 0105569000001"
|
||||
pub why: String,
|
||||
/// What it means for this check, in a sentence.
|
||||
pub means: String,
|
||||
}
|
||||
|
||||
/// Whether any match must be cleared by a lawyer before saving.
|
||||
pub fn needs_clearing(hits: &[Hit]) -> bool {
|
||||
hits.iter().any(|h| h.level != "note")
|
||||
}
|
||||
|
||||
/// The check as the journal states it.
|
||||
pub fn summary(hits: &[Hit], cleared: &str) -> String {
|
||||
if hits.is_empty() {
|
||||
return "Conflict check: no match.".into();
|
||||
}
|
||||
let list: Vec<String> = hits
|
||||
.iter()
|
||||
.map(|h| format!("{} {} ({})", h.what.to_lowercase(), h.name, h.why))
|
||||
.collect();
|
||||
let n = hits.len();
|
||||
let mut s = format!(
|
||||
"Conflict check: {n} match{}: {}.",
|
||||
if n == 1 { "" } else { "es" },
|
||||
list.join("; ")
|
||||
);
|
||||
if needs_clearing(hits) {
|
||||
if cleared.trim().is_empty() {
|
||||
s.push_str(" Cleared: checked, no conflict.");
|
||||
} else {
|
||||
s.push_str(&format!(" Cleared: {}", cleared.trim()));
|
||||
if !s.ends_with('.') {
|
||||
s.push('.');
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Why a candidate matches the probe, if it does.
|
||||
fn why(probe: &Probe, names: &[&str], numbers: &[&str]) -> Option<String> {
|
||||
for n in numbers.iter().filter_map(|n| number(n)) {
|
||||
if probe
|
||||
.numbers
|
||||
.iter()
|
||||
.filter_map(|p| number(p))
|
||||
.any(|p| p == n)
|
||||
{
|
||||
return Some(format!("same number {n}"));
|
||||
}
|
||||
}
|
||||
for c in names.iter().filter(|c| !c.trim().is_empty()) {
|
||||
if probe.names.iter().any(|p| same_name(p, c)) {
|
||||
return Some(format!("same name as {c}"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct ClientRow {
|
||||
id: i64,
|
||||
name: String,
|
||||
name_th: String,
|
||||
known_as: String,
|
||||
thai_id: String,
|
||||
passport_no: String,
|
||||
registration_no: String,
|
||||
status: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct PartyRow {
|
||||
name: String,
|
||||
name_th: String,
|
||||
id_no: String,
|
||||
contract_id: i64,
|
||||
code: String,
|
||||
client_id: i64,
|
||||
client: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct PersonRow {
|
||||
id: i64,
|
||||
name: String,
|
||||
given: String,
|
||||
passports: String,
|
||||
}
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
struct CompanyRow {
|
||||
id: i64,
|
||||
name: String,
|
||||
name_th: String,
|
||||
registration_no: String,
|
||||
}
|
||||
|
||||
/// Every match for the probe. The record being checked is left out of its
|
||||
/// own matches.
|
||||
pub async fn check(db: &PgPool, probe: &Probe, who: For) -> Result<Vec<Hit>> {
|
||||
let mut hits = Vec::new();
|
||||
if probe.is_empty() {
|
||||
return Ok(hits);
|
||||
}
|
||||
let clients: Vec<ClientRow> = sqlx::query_as(
|
||||
"SELECT id, name, name_th, known_as, thai_id, passport_no, registration_no, status \
|
||||
FROM clients ORDER BY id",
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
for c in clients {
|
||||
if let For::Client(Some(me)) = who
|
||||
&& me == c.id
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(why) = why(
|
||||
probe,
|
||||
&[&c.name, &c.name_th, &c.known_as],
|
||||
&[&c.thai_id, &c.passport_no, &c.registration_no],
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let former = if c.status == "former" { "former " } else { "" };
|
||||
let (level, means) = match who {
|
||||
For::Party { client, .. } if client == c.id => (
|
||||
"conflict",
|
||||
"This is the contract's own client: a client cannot be the other side of its own contract."
|
||||
.to_string(),
|
||||
),
|
||||
For::Party { .. } => (
|
||||
"conflict",
|
||||
format!(
|
||||
"Lanna Desk acts for this {former}client: this contract would put it on the other side."
|
||||
),
|
||||
),
|
||||
For::Client(_) => (
|
||||
"same",
|
||||
format!("Perhaps the same {former}client: add to that record instead of a second one."),
|
||||
),
|
||||
For::Search => ("note", format!("A {former}client of Lanna Desk.")),
|
||||
};
|
||||
hits.push(Hit {
|
||||
level,
|
||||
what: "Client".into(),
|
||||
name: c.name,
|
||||
href: format!("/clients/{}", c.id),
|
||||
why,
|
||||
means,
|
||||
});
|
||||
}
|
||||
let parties: Vec<PartyRow> = sqlx::query_as(
|
||||
"SELECT p.name, p.name_th, p.id_no, p.contract_id, c.code, c.client_id, cl.name AS client \
|
||||
FROM contract_parties p JOIN contracts c ON c.id = p.contract_id \
|
||||
JOIN clients cl ON cl.id = c.client_id \
|
||||
WHERE p.removed_at IS NULL ORDER BY p.id",
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
for p in parties {
|
||||
if let For::Party { contract, .. } = who
|
||||
&& contract == p.contract_id
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(why) = why(probe, &[&p.name, &p.name_th], &[&p.id_no]) else {
|
||||
continue;
|
||||
};
|
||||
let (level, means) = match who {
|
||||
For::Client(_) => (
|
||||
"conflict",
|
||||
format!(
|
||||
"The other side of {} for {}: Lanna Desk acted against them.",
|
||||
p.code, p.client
|
||||
),
|
||||
),
|
||||
For::Party { client, .. } if client == p.client_id => (
|
||||
"note",
|
||||
format!("Also the other party of {} for the same client.", p.code),
|
||||
),
|
||||
For::Party { .. } => (
|
||||
"note",
|
||||
format!("Also the other party of {} for {}.", p.code, p.client),
|
||||
),
|
||||
For::Search => (
|
||||
"note",
|
||||
format!("The other party of {} for {}.", p.code, p.client),
|
||||
),
|
||||
};
|
||||
hits.push(Hit {
|
||||
level,
|
||||
what: format!("Other party in {}", p.code),
|
||||
name: p.name,
|
||||
href: format!("/contracts/{}#parties", p.contract_id),
|
||||
why,
|
||||
means,
|
||||
});
|
||||
}
|
||||
let people: Vec<PersonRow> = sqlx::query_as(
|
||||
"SELECT p.id, p.surname AS name, concat_ws(' ', p.first_name, p.middle_name) AS given, \
|
||||
COALESCE((SELECT string_agg(number, ' ') FROM passports WHERE person_id = p.id), '') \
|
||||
AS passports FROM people p ORDER BY p.id",
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
for p in people {
|
||||
let full = format!("{} {}", p.given, p.name);
|
||||
let numbers: Vec<&str> = p.passports.split(' ').collect();
|
||||
let Some(why) = why(probe, &[&full], &numbers) else {
|
||||
continue;
|
||||
};
|
||||
let shown = format!("{}, {}", p.name, p.given.trim());
|
||||
let (level, means) = match who {
|
||||
For::Party { .. } => (
|
||||
"conflict",
|
||||
"A visa client of Lanna Desk: this contract would put them on the other side."
|
||||
.to_string(),
|
||||
),
|
||||
_ => ("note", "Has a visa record at Lanna Desk.".to_string()),
|
||||
};
|
||||
hits.push(Hit {
|
||||
level,
|
||||
what: "Visa client".into(),
|
||||
name: shown,
|
||||
href: format!("/people/{}", p.id),
|
||||
why,
|
||||
means,
|
||||
});
|
||||
}
|
||||
let companies: Vec<CompanyRow> =
|
||||
sqlx::query_as("SELECT id, name, name_th, registration_no FROM companies ORDER BY id")
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
for c in companies {
|
||||
let Some(why) = why(probe, &[&c.name, &c.name_th], &[&c.registration_no]) else {
|
||||
continue;
|
||||
};
|
||||
let (level, means) = match who {
|
||||
For::Party { .. } => (
|
||||
"conflict",
|
||||
"An employer Lanna Desk works for on the visa side: this contract would put it on the other side."
|
||||
.to_string(),
|
||||
),
|
||||
_ => ("note", "An employer on the visa side.".to_string()),
|
||||
};
|
||||
hits.push(Hit {
|
||||
level,
|
||||
what: "Employer".into(),
|
||||
name: c.name,
|
||||
href: format!("/companies/{}", c.id),
|
||||
why,
|
||||
means,
|
||||
});
|
||||
}
|
||||
// the ones that need a decision first
|
||||
hits.sort_by_key(|h| match h.level {
|
||||
"conflict" => 0,
|
||||
"same" => 1,
|
||||
_ => 2,
|
||||
});
|
||||
Ok(hits)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn company_words_and_order_do_not_count() {
|
||||
assert!(same_name("Demo Records Co., Ltd.", "demo records"));
|
||||
assert!(same_name("MUSTERMANN, Erika", "Erika Mustermann"));
|
||||
assert!(same_name("Erika Mustermann", "MUSTERMANN, Erika Maria"));
|
||||
assert!(same_name(
|
||||
"บริษัท เดโม เรคคอร์ดส จำกัด",
|
||||
"บริษัทเดโม เรคคอร์ดสจำกัด"
|
||||
));
|
||||
assert!(same_name("นายสมชาย ใจดี", "สมชาย ใจดี"));
|
||||
assert!(same_name("The Blue Hour Band", "Blue Hour Band Ltd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_word_matches_only_itself() {
|
||||
assert!(same_name("Somchai", "somchai"));
|
||||
assert!(!same_name("Records", "Demo Records"));
|
||||
assert!(!same_name("Demo Festival", "Demo Records"));
|
||||
assert!(!same_name("Co., Ltd.", "Ltd"), "nothing left of either");
|
||||
assert!(!same_name("", "Demo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_compare_on_letters_and_digits() {
|
||||
assert_eq!(
|
||||
number("0-1055-69000-01-2").as_deref(),
|
||||
Some("0105569000012")
|
||||
);
|
||||
assert_eq!(number("c01x 00t47").as_deref(), Some("C01X00T47"));
|
||||
assert_eq!(number("12-3"), None, "too short to say anything");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_journal_says_what_was_found_and_who_cleared_it() {
|
||||
assert_eq!(summary(&[], ""), "Conflict check: no match.");
|
||||
let hit = |level| Hit {
|
||||
level,
|
||||
what: "Client".into(),
|
||||
name: "Demo Records Co., Ltd.".into(),
|
||||
href: String::new(),
|
||||
why: "same name as Demo Records Co., Ltd.".into(),
|
||||
means: String::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
summary(&[hit("note")], "ignored"),
|
||||
"Conflict check: 1 match: client Demo Records Co., Ltd. (same name as Demo Records Co., Ltd.)."
|
||||
);
|
||||
assert!(
|
||||
summary(&[hit("conflict"), hit("note")], "The label agreed in writing")
|
||||
.ends_with("2 matches: client Demo Records Co., Ltd. (same name as Demo Records Co., Ltd.); client Demo Records Co., Ltd. (same name as Demo Records Co., Ltd.). Cleared: The label agreed in writing.")
|
||||
);
|
||||
}
|
||||
}
|
||||
+161
-6
@@ -193,9 +193,6 @@ const CONTRACT_FIELDS: &[Field] = &[
|
||||
.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("counterparty", "Other party", Input::Text)
|
||||
.hint("The venue, label, employer, landlord or buyer on the other side.")
|
||||
.wide(),
|
||||
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"),
|
||||
@@ -421,7 +418,9 @@ pub struct Filter {
|
||||
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, \
|
||||
c.counterparty, c.lawyer_id, l.name AS lawyer, c.ends_on, c.notice_by, \
|
||||
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 \
|
||||
@@ -490,6 +489,162 @@ pub async fn list_clients(db: &PgPool, former: bool) -> Result<Vec<ClientRow>> {
|
||||
.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)]
|
||||
@@ -865,11 +1020,11 @@ mod tests {
|
||||
old.insert("status".into(), "draft".into());
|
||||
let mut new = old.clone();
|
||||
new.insert("status".into(), "active".into());
|
||||
new.insert("counterparty".into(), "Demo Records".into());
|
||||
new.insert("notes".into(), "Signed at the label".into());
|
||||
let opts = Options::default();
|
||||
assert_eq!(
|
||||
changes_of(&CONTRACTS, &old, &new, &opts),
|
||||
"Other party: (empty) -> Demo Records; Status: Draft -> In force"
|
||||
"Status: Draft -> In force; Notes: (empty) -> Signed at the label"
|
||||
);
|
||||
assert!(changes_of(&CONTRACTS, &old, &old, &opts).is_empty());
|
||||
assert_eq!(
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod agreements;
|
||||
pub mod audit;
|
||||
pub mod companies;
|
||||
pub mod config;
|
||||
pub mod conflicts;
|
||||
pub mod countries;
|
||||
pub mod dates;
|
||||
pub mod db;
|
||||
|
||||
@@ -82,6 +82,32 @@ async fn add(
|
||||
},
|
||||
)
|
||||
.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))
|
||||
}
|
||||
|
||||
|
||||
+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>,
|
||||
|
||||
@@ -431,6 +431,12 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
)
|
||||
.route("/contracts/{id}/versions/{n}/file", get(l::version_file))
|
||||
.route("/contracts/{id}/papers", post(l::add_paper))
|
||||
.route("/contracts/{id}/parties", post(l::add_party))
|
||||
.route(
|
||||
"/contracts/{id}/parties/{pid}/remove",
|
||||
post(l::remove_party),
|
||||
)
|
||||
.route("/conflicts", get(l::conflicts_page))
|
||||
.route("/papers", get(l::find_paper))
|
||||
.route("/papers/{code}", get(l::paper_by_code))
|
||||
.route("/papers/{pid}/move", post(l::move_paper))
|
||||
|
||||
@@ -2084,3 +2084,85 @@ details.move[open] .mini {
|
||||
border-top: 1.4mm solid #f5c000;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the parties of a contract and the conflict check (phase 11) */
|
||||
.parties {
|
||||
list-style: none;
|
||||
margin: 0 0 12px;
|
||||
padding: 0;
|
||||
}
|
||||
.parties li {
|
||||
padding: 10px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.parties li:first-child {
|
||||
border-top: 0;
|
||||
padding-top: 0;
|
||||
}
|
||||
.parties li.old {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.parties .prow {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.addparty > summary {
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
display: inline-block;
|
||||
}
|
||||
.addparty > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.addparty[open] > summary {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.conflicts {
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.conflicts .cfhead {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
.hits {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.hit {
|
||||
padding: 9px 0 9px 12px;
|
||||
border-left: 3px solid var(--line);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.hit.conflict {
|
||||
border-left-color: var(--bad);
|
||||
}
|
||||
.hit.same {
|
||||
border-left-color: var(--warn);
|
||||
}
|
||||
.hit .hitwhat {
|
||||
color: var(--mute);
|
||||
font-size: 13px;
|
||||
margin: 0 4px;
|
||||
}
|
||||
.hit .small {
|
||||
margin-top: 3px;
|
||||
}
|
||||
.form .clearbox {
|
||||
display: flex;
|
||||
justify-content: flex-start;
|
||||
gap: 10px;
|
||||
align-items: baseline;
|
||||
margin: 12px 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form .clearbox input {
|
||||
width: auto;
|
||||
flex: none;
|
||||
margin: 0;
|
||||
}
|
||||
.warncard {
|
||||
border-color: var(--bad);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{#- The conflict check's matches, and when they wait for a decision, the
|
||||
box a lawyer ticks and what they write: both go into the journal. -#}
|
||||
{% macro block(check) %}
|
||||
<div class="conflicts{% if check.ask %} ask{% endif %}" id="conflicts">
|
||||
{% if check.ask %}<p class="cfhead"><b>Conflict check: {{ check.hits|length }} match{% if check.hits|length != 1 %}es{% endif %} to look at before saving</b></p>{% endif %}
|
||||
<ul class="hits">
|
||||
{% for h in check.hits %}
|
||||
<li class="hit {{ h.level }}">
|
||||
<span class="chip {% if h.level == "conflict" %}bad{% elif h.level == "same" %}warn{% else %}plain{% endif %}">{% if h.level == "conflict" %}Conflict{% elif h.level == "same" %}Same client?{% else %}Note{% endif %}</span>
|
||||
<span class="hitwhat">{{ h.what }}</span>
|
||||
<a class="strong" href="{{ h.href }}" target="_blank" rel="noopener">{{ h.name }}</a>
|
||||
<div class="small">{{ h.means }} <span class="muted">({{ h.why }})</span></div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% if check.ask %}
|
||||
<label class="clearbox"><input type="checkbox" name="cleared" value="1" id="f-cleared" required> I looked at these matches: there is no conflict, or the clients agreed to it in writing.</label>
|
||||
<div class="field wide">
|
||||
<label for="f-cleared_note">What you checked</label>
|
||||
<input id="f-cleared_note" name="cleared_note" value="{{ check.note }}" maxlength="500" placeholder="Such as: another company with a similar name; both clients agreed in writing on Nov 22">
|
||||
<p class="hint">Goes into the journal with the matches.</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
@@ -2,7 +2,7 @@
|
||||
{% block main %}
|
||||
<div class="pagehead">
|
||||
<h1>{% if former %}Former clients{% else %}Clients{% endif %}</h1>
|
||||
<div class="actions"><a class="btn pri" href="/clients/new" id="new-client">+ New client</a></div>
|
||||
<div class="actions"><a class="btn sm ghost" href="/conflicts" id="conflict-check">Conflict check</a> <a class="btn pri" href="/clients/new" id="new-client">+ New client</a></div>
|
||||
</div>
|
||||
<p class="meta">People and organizations, Thai or foreign, whom Lanna Desk advises or acts for: artists, labels, festivals, companies and private clients. Each has a lawyer in charge and their contracts.</p>
|
||||
{% if cards or n_former %}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_fields.html" as fm %}
|
||||
{% import "_conflicts.html" as cf %}
|
||||
{% block main %}
|
||||
<div class="crumbs"><a href="/clients">Clients</a></div>
|
||||
<div class="pagehead"><h1>Conflict check</h1></div>
|
||||
<p class="meta">Before a first meeting, look up a name or a number among the clients, the other parties of the contracts, the visa clients and the employers. Nothing is saved here. Adding a client or a party runs the same check and writes it into the journal.</p>
|
||||
<form method="get" action="/conflicts" class="form" id="conflict-search">
|
||||
<section class="card">
|
||||
<div class="grid">
|
||||
{{ fm.text("name", "Name", name, cls="wide", hint="In English or Thai. Word order, capitals and words such as Co., Ltd. or บริษัท do not count.") }}
|
||||
{{ fm.text("number", "ID, passport or registration number", number, hint="Compared on its letters and digits.") }}
|
||||
</div>
|
||||
<div class="formactions"><button type="submit" class="btn pri" id="check">Check</button></div>
|
||||
</section>
|
||||
</form>
|
||||
{% if asked %}
|
||||
<section class="card" id="results">
|
||||
<header><h2>{% if check.hits %}{{ check.hits|length }} match{% if check.hits|length != 1 %}es{% endif %}{% else %}No match{% endif %}</h2></header>
|
||||
{% if check.hits %}{{ cf.block(check) }}{% else %}<p class="empty-inline">Nobody on record has this name or number.</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -2,6 +2,7 @@
|
||||
{% import "_fields.html" as fm %}
|
||||
{% import "_agreement_text.html" as ag %}
|
||||
{% import "_journal.html" as jn %}
|
||||
{% import "_conflicts.html" as cf %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/contracts">Contracts</a> <span class="sep">/</span> <a href="/clients/{{ head.client_id }}">{{ client_name }}</a></div>
|
||||
@@ -42,6 +43,37 @@
|
||||
{% endfor %}
|
||||
</section>
|
||||
</div>
|
||||
<section class="card" id="parties">
|
||||
<header><h2>Parties</h2><span class="muted small">each one added is checked for conflicts</span></header>
|
||||
<ul class="parties">
|
||||
<li><div class="prow"><span><a class="strong" href="/clients/{{ head.client_id }}">{{ client_name }}</a> <span class="tag gold">our client</span></span></div></li>
|
||||
{% for p in parties %}
|
||||
<li id="party-{{ p.id }}"{% if p.removed %} class="old"{% endif %}>
|
||||
<div class="prow">
|
||||
<span><b>{{ p.name }}</b>{% if p.name_th %} <span lang="th">{{ p.name_th }}</span>{% endif %}{% if p.role %} <span class="tag">{{ p.role }}</span>{% endif %}{% if p.removed %} <span class="chip plain">removed</span>{% endif %}</span>
|
||||
{% if not p.removed %}<form method="post" action="/contracts/{{ id }}/parties/{{ p.id }}/remove" class="inline-form" data-confirm="Take {{ p.name }} off this contract? It stays on record, marked removed."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm ghost">Remove</button></form>{% endif %}
|
||||
</div>
|
||||
<div class="sub">{% if p.id_no %}<span class="mono">{{ p.id_no }}</span> · {% endif %}added {{ p.added }} by {{ p.by }}{% if p.removed %} · removed {{ p.removed }} by {{ p.removed_by }}{% endif %}</div>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% if not live_parties %}<p class="empty-inline">No other party yet: add the other side, and the check looks for it among everyone on record.</p>{% endif %}
|
||||
<details class="addparty"{% if check.hits or party_errors %} open{% endif %}>
|
||||
<summary class="btn sm" id="add-party-open">Add a party</summary>
|
||||
<form method="post" action="/contracts/{{ id }}/parties" class="form" id="party-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
{% if check.hits %}{{ cf.block(check) }}{% endif %}
|
||||
<div class="grid">
|
||||
{{ fm.text("party_name", "Name", party.name, err=party_errors.party_name, req=true, cls="wide", hint="As registered, or as in the ID card or passport.") }}
|
||||
{{ fm.text("party_name_th", "Name in Thai", party.name_th, err=party_errors.party_name_th, cls="wide") }}
|
||||
{{ fm.text("party_id_no", "ID, passport or registration number", party.id_no, err=party_errors.party_id_no, hint="The check compares numbers too.") }}
|
||||
{{ fm.text("party_role", "Role", party.role, err=party_errors.party_role, list="roles", ph="Label, venue, landlord") }}
|
||||
</div>
|
||||
<div class="formactions"><button type="submit" class="btn pri" id="add-party">{% if check.ask %}Add the party{% else %}Check and add{% endif %}</button></div>
|
||||
</form>
|
||||
</details>
|
||||
<datalist id="roles">{% for r in roles %}<option value="{{ r }}"></option>{% endfor %}</datalist>
|
||||
</section>
|
||||
{% if reading %}
|
||||
<section class="card" id="reading">
|
||||
<header><h2>{% if compare %}Version {{ reading }} against version {{ before }}{% else %}Version {{ reading }}{% endif %}{% if reading_note %}: {{ reading_note }}{% endif %}</h2>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_fields.html" as fm %}
|
||||
{% import "_conflicts.html" as cf %}
|
||||
{% block main %}
|
||||
{% if p %}
|
||||
{% include "_person_head.html" %}
|
||||
@@ -9,6 +10,7 @@
|
||||
{% endif %}
|
||||
<form method="post" action="{{ action }}" class="form" id="record-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
{% if check and check.hits %}<section class="card warncard">{{ cf.block(check) }}</section>{% endif %}
|
||||
<section class="card">
|
||||
{% if p %}<header><h2>{{ heading }}</h2></header>{% endif %}
|
||||
{% if lead %}<p class="hint lead">{{ lead }}</p>{% endif %}
|
||||
|
||||
+217
-2
@@ -57,7 +57,6 @@ async fn practice(app: &crate::common::App) -> (i64, i64, i64) {
|
||||
("title", "Recording agreement"),
|
||||
("kind", "artist-recording"),
|
||||
("client_id", &client.to_string()),
|
||||
("counterparty", "Demo Records"),
|
||||
("status", "draft"),
|
||||
("lawyer_id", &lawyer.to_string()),
|
||||
],
|
||||
@@ -184,7 +183,6 @@ async fn a_contract_keeps_its_versions_and_the_journal_holds_them(pool: PgPool)
|
||||
("title", "Recording agreement"),
|
||||
("kind", "artist-recording"),
|
||||
("client_id", &client.to_string()),
|
||||
("counterparty", "Demo Records"),
|
||||
("status", "active"),
|
||||
],
|
||||
)
|
||||
@@ -500,3 +498,220 @@ async fn the_demo_practice_shows_and_checks_whole(pool: PgPool) {
|
||||
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());
|
||||
}
|
||||
Reference in new issue
Block a user