diff --git a/README.md b/README.md index 4999a53..473442a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # Lanna Desk (lannadesk.com) -Lanna Desk, the app `visa`, keeps the immigration records of the foreigners that Lanna Desk +Lanna Desk, the app `visa`, is the back office of Lanna Desk, the legal side of buildfor.life. Its +legal practice keeps the clients, Thai and foreign, their contracts (general +ones and artists') with versions that never change, the paper copies and +where they lie, and a journal of every change that chains by SHA-256. It +also keeps the immigration records of the foreigners that Lanna Desk looks after in Thailand: their passports, addresses and TM.30 receipts, visas, arrivals with the TDAC, extensions of stay, re-entry permits, 90-day reports and work permits, and the companies that employ them. From those diff --git a/docs/PLAN.md b/docs/PLAN.md index af5464c..bad19a1 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -17,7 +17,9 @@ > too. Later that day lannadesk.com became Lanna Desk's own static website > (B4L/lannadesk-web, Astro), and the app moved to https://app.lannadesk.com; > its `/` now leads to the back office, and the texts clients read name Lanna -> Desk rather than B4L. **Resume here: phase 8, reminders.** +> 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.** Lanna Desk keeps the immigration records of the foreigners that it looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -241,6 +243,7 @@ dark at desktop and phone width, a commit and a push. | 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | built Nov 20, 2026 | | 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 | | later | Thai user interface, agency cases and fees, other visa categories' packs | | ### Phase 1: app, login, people @@ -531,6 +534,53 @@ Planned on November 20, 2026, from Alex's answers (decisions table). next link; the person's page says who has signed which version. An agreement switched off is no longer asked for. +### Phase 9: the legal practice + +Lanna Desk does more than visas: its larger work is contracts, general ones +and artists', for clients who are Thai or foreign, people or organizations +(Alex, Nov 21, 2026). Several lawyers work in the team. + +- **Lawyers** (`/lawyers`): name, Thai name, license number of the Lawyers + Council of Thailand, contact, the id.cnx.network login of one who uses + the app (then "My contracts" shows theirs), in the team or left. +- **Clients** (`/clients`, record cards): a person or an organization; the + name in English and Thai, a stage name or brand, nationality, a Thai ID + number (checked), a passport number or a registration number, a contact + person, the lawyer in charge, current or former. +- **Contracts** (`/contracts`): code `LD--` from a sequence, + title, kind (service, employment, lease, sale, loan, NDA, partnership, + sponsorship; the artist kinds recording, management, publishing, + performance, license, merchandise), client, other party, status (draft, + in negotiation, signed, in force, ended, terminated, not concluded), the + lawyer in charge, the dates (signed, in force, ends, notice by) and the + value. A contract in force shows its notice day 45 days ahead and its end + 60 days ahead. Filters: general or artists, a lawyer, mine, those over. +- **Versions**: each a text kept in the app, a file (PDF or scan, encrypted + as the client's document of kind `contract`) or both, with a note of what + it is. Numbered per contract, never changed (a trigger refuses UPDATE and + DELETE, and a version's file cannot be deleted or its checksum changed). + A text equal to the last is not kept again. Any version reads against the + one before as a line diff. +- **Paper copies**: the paper of a version gets the id `-P`, to + write on it or to print as a 90 x 50 mm label with a QR code to its page + (`/papers/`); its place, state (filed, out, handed over, destroyed) + and holder change, every move into the journal; id, contract, version + and description never change. Contracts has a box to find a paper by id. +- **Journal** (`/journal`): every change to the above, in words (what was + added; each field from what to what) in the transaction of the change. + Entries chain: each holds the SHA-256 of the one before and its own over + its number, time, actor, client, contract, event, detail and the hash + before. The database refuses UPDATE, DELETE and TRUNCATE. The page checks + the whole chain and every version's text and fingerprints against its + entry, and shows the last hash; the CSV export is a copy to keep outside. + Someone with the database's own rights could still rewrite the chain from + the start; a last hash written down or kept elsewhere shows that. + +Open: anchoring the last hash outside the server each day (a Matrix +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. + ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay diff --git a/migrations/0009_legal.sql b/migrations/0009_legal.sql new file mode 100644 index 0000000..9f22113 --- /dev/null +++ b/migrations/0009_legal.sql @@ -0,0 +1,224 @@ +-- Lanna Desk, phase 9: the legal practice (docs/PLAN.md "Phase 9"). +-- +-- Clients are people or organizations, Thai or foreign: an artist, a label, +-- a festival, a company, someone buying land. Lawyers are the team; each +-- client and each contract has a lawyer in charge. A contract (a general +-- contract, or one of the artist contracts) has versions, and a version's +-- text and file never change once added (the table refuses it): a new +-- text is a new version. The paper copies of a contract each carry an id, +-- written on the paper, and the record of where they lie. +-- +-- Every change to these tables is also written to the journal: a ledger +-- whose entries chain by SHA-256, each naming the hash of the one before, +-- so an entry changed or taken out later breaks the chain where it was. +-- The database refuses to change or delete journal entries. + +CREATE TABLE lawyers ( + id BIGSERIAL PRIMARY KEY, + name TEXT NOT NULL CHECK (name <> ''), + name_th TEXT NOT NULL DEFAULT '', + -- the Lawyers Council of Thailand license number + license_no TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + -- the id.cnx.network login of a lawyer who uses the app: "My contracts" + login TEXT NOT NULL DEFAULT '', + -- for the list of lawyers to choose from; leaving keeps the history + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'left')), + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE TABLE clients ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('person', 'organization')), + name TEXT NOT NULL CHECK (name <> ''), + name_th TEXT NOT NULL DEFAULT '', + -- an artist's stage name, a label's brand + known_as TEXT NOT NULL DEFAULT '', + nationality TEXT NOT NULL DEFAULT '', + -- a Thai person's 13-digit ID number, a foreigner's passport number, + -- an organization's registration (juristic person) number + thai_id TEXT NOT NULL DEFAULT '', + passport_no TEXT NOT NULL DEFAULT '', + registration_no TEXT NOT NULL DEFAULT '', + -- who speaks for an organization + contact_person TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + address TEXT NOT NULL DEFAULT '', + lawyer_id BIGINT REFERENCES lawyers (id), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'former')), + notes TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- The numbers of the contract codes: they run on across the years. +CREATE SEQUENCE contract_codes; + +CREATE TABLE contracts ( + id BIGSERIAL PRIMARY KEY, + -- LD-2026-0007, the year it was opened in Chiang Mai: on every page, + -- label and paper copy of the contract + code TEXT NOT NULL UNIQUE CHECK (code ~ '^LD-[0-9]{4}-[0-9]{4,}$') DEFAULT ( + 'LD-' || to_char(now() AT TIME ZONE 'Asia/Bangkok', 'YYYY') || '-' + || lpad(nextval('contract_codes')::text, 4, '0') + ), + client_id BIGINT NOT NULL REFERENCES clients (id), + title TEXT NOT NULL CHECK (title <> ''), + kind TEXT NOT NULL, + -- the other side: a venue, a label, an employer, a buyer + counterparty TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'draft', + lawyer_id BIGINT REFERENCES lawyers (id), + signed_on DATE, + starts_on DATE, + ends_on DATE, + -- the day by which either side must give notice, if it renews by itself + notice_by DATE, + value_thb BIGINT, + notes TEXT NOT NULL DEFAULT '', + created_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX contracts_client ON contracts (client_id); + +-- The contract files are documents of the client, so they are encrypted +-- in the store like every other document. +ALTER TABLE documents ADD COLUMN client_id BIGINT REFERENCES clients (id); +ALTER TABLE documents DROP CONSTRAINT documents_check; +ALTER TABLE documents ADD CONSTRAINT documents_one_owner + CHECK (num_nonnulls(person_id, company_id, client_id) = 1); +CREATE INDEX documents_client ON documents (client_id) WHERE client_id IS NOT NULL; + +-- A document's file never changes, whoever owns it: the checksum stays the +-- file's. +CREATE FUNCTION documents_file_unchanged() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.sha256 <> OLD.sha256 OR NEW.size_bytes <> OLD.size_bytes + OR NEW.content_type <> OLD.content_type THEN + RAISE EXCEPTION 'a document''s file never changes: upload a new one'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER documents_file_no_change +BEFORE UPDATE ON documents +FOR EACH ROW EXECUTE FUNCTION documents_file_unchanged(); + +CREATE TABLE contract_versions ( + id BIGSERIAL PRIMARY KEY, + contract_id BIGINT NOT NULL REFERENCES contracts (id), + version INTEGER NOT NULL CHECK (version > 0), + -- what this version is: "first draft", "the label's changes", "signed" + note TEXT NOT NULL CHECK (note <> ''), + -- the text, when it is kept in the app (paragraphs, "# " headings, "- " + -- items, as in the agreements), and its SHA-256 as UTF-8 + body TEXT NOT NULL DEFAULT '', + body_sha256 TEXT CHECK (body_sha256 ~ '^[0-9a-f]{64}$'), + -- the file: a draft as PDF, the scan of the signed paper. ON DELETE + -- is refused, so the file stays as long as the version. + document_id BIGINT REFERENCES documents (id), + file_sha256 TEXT CHECK (file_sha256 ~ '^[0-9a-f]{64}$'), + added_by TEXT NOT NULL, + added_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (contract_id, version), + CHECK (body <> '' OR document_id IS NOT NULL), + CHECK ((body = '') = (body_sha256 IS NULL)), + CHECK ((document_id IS NULL) = (file_sha256 IS NULL)) +); + +CREATE FUNCTION contract_versions_unchanged() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'a contract version never changes: add a new version'; +END +$$; +CREATE TRIGGER contract_versions_no_change +BEFORE UPDATE OR DELETE ON contract_versions +FOR EACH ROW EXECUTE FUNCTION contract_versions_unchanged(); + +CREATE TABLE paper_copies ( + id BIGSERIAL PRIMARY KEY, + -- LD-2026-0007-P1, written on the paper or on its label + code TEXT NOT NULL UNIQUE, + contract_id BIGINT NOT NULL REFERENCES contracts (id), + -- the version the paper is, when known + version_id BIGINT REFERENCES contract_versions (id), + -- "Signed original", "Certified copy" ... + what TEXT NOT NULL CHECK (what <> ''), + -- where it lies now, as anyone in the office finds it again: + -- "Office, cabinet A, drawer 2, folder Poy Records" + location TEXT NOT NULL CHECK (location <> ''), + state TEXT NOT NULL DEFAULT 'filed' + CHECK (state IN ('filed', 'out', 'handed-over', 'destroyed')), + -- who has it while it is out, or whom it was handed to + holder TEXT NOT NULL DEFAULT '', + created_by TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + moved_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX paper_copies_contract ON paper_copies (contract_id); + +-- A paper's id, contract, version and description never change; where it +-- lies does, and every move is in the journal. +CREATE FUNCTION paper_copies_fixed() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'a paper copy stays on record: mark it handed over or destroyed'; + END IF; + IF NEW.code <> OLD.code OR NEW.contract_id <> OLD.contract_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id OR NEW.what <> OLD.what THEN + RAISE EXCEPTION 'a paper copy''s id, contract, version and description never change'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER paper_copies_no_change +BEFORE UPDATE OR DELETE ON paper_copies +FOR EACH ROW EXECUTE FUNCTION paper_copies_fixed(); + +CREATE TABLE journal ( + -- the place in the chain, from 1 without gaps + seq BIGINT PRIMARY KEY CHECK (seq > 0), + at TIMESTAMPTZ NOT NULL, + actor TEXT NOT NULL, + client_id BIGINT REFERENCES clients (id), + contract_id BIGINT REFERENCES contracts (id), + event TEXT NOT NULL CHECK (event <> ''), + -- in words, with the fingerprints of what was added + detail TEXT NOT NULL, + -- the hash of entry seq - 1 (64 zeros for the first) and of this entry + prev_hash TEXT NOT NULL CHECK (prev_hash ~ '^[0-9a-f]{64}$'), + hash TEXT NOT NULL UNIQUE CHECK (hash ~ '^[0-9a-f]{64}$') +); +CREATE INDEX journal_client ON journal (client_id) WHERE client_id IS NOT NULL; +CREATE INDEX journal_contract ON journal (contract_id) WHERE contract_id IS NOT NULL; + +CREATE FUNCTION journal_append_only() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'the journal is append-only'; +END +$$; +CREATE TRIGGER journal_no_change +BEFORE UPDATE OR DELETE ON journal +FOR EACH ROW EXECUTE FUNCTION journal_append_only(); +CREATE TRIGGER journal_no_truncate +BEFORE TRUNCATE ON journal +FOR EACH STATEMENT EXECUTE FUNCTION journal_append_only(); + +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' + ) +); diff --git a/src/audit.rs b/src/audit.rs index 197d9a4..fd8e423 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -67,6 +67,13 @@ pub enum Entity { Agreement, /// A client's signature of an agreement. Signature, + /// The legal practice (`legal`): its lawyers, clients, contracts, their + /// versions and paper copies. The journal holds them in full. + Lawyer, + Client, + Contract, + ContractVersion, + PaperCopy, } impl Entity { @@ -88,6 +95,11 @@ impl Entity { Entity::Link => "link", Entity::Agreement => "agreement", Entity::Signature => "signature", + Entity::Lawyer => "lawyer", + Entity::Client => "client", + Entity::Contract => "contract", + Entity::ContractVersion => "contract-version", + Entity::PaperCopy => "paper-copy", } } } diff --git a/src/documents.rs b/src/documents.rs index 3643f21..9f26199 100644 --- a/src/documents.rs +++ b/src/documents.rs @@ -20,20 +20,29 @@ use crate::s3::Put; pub enum Owner { Person(i64), Company(i64), + /// A client of the legal practice: the files of their contracts. + Client(i64), } impl Owner { pub fn person(self) -> Option { match self { Owner::Person(id) => Some(id), - Owner::Company(_) => None, + _ => None, } } pub fn company(self) -> Option { match self { Owner::Company(id) => Some(id), - Owner::Person(_) => None, + _ => None, + } + } + + pub fn client(self) -> Option { + match self { + Owner::Client(id) => Some(id), + _ => None, } } @@ -42,6 +51,7 @@ impl Owner { match self { Owner::Person(id) => format!("/people/{id}/documents"), Owner::Company(id) => format!("/companies/{id}/documents"), + Owner::Client(id) => format!("/clients/{id}/documents"), } } @@ -49,6 +59,7 @@ impl Owner { match self { Owner::Person(_) => PERSON_KINDS, Owner::Company(_) => COMPANY_KINDS, + Owner::Client(_) => CLIENT_KINDS, } } } @@ -109,6 +120,12 @@ pub const COMPANY_KINDS: &[Kind] = &[ k("other", "Other", None), ]; +/// A client's documents: the files of their contracts' versions. +pub const CLIENT_KINDS: &[Kind] = &[ + k("contract", "Contract version", None), + k("other", "Other", None), +]; + /// The kinds that are cards with two sides: uploaded as two pictures at /// once, the first is the front and the second the back, and the pack /// prints both on one A4 sheet. @@ -375,11 +392,12 @@ pub async fn set_back(tx: &mut Transaction<'_, Postgres>, back: i64, front: i64) pub async fn list(db: &PgPool, owner: Owner) -> Result> { let docs: Vec = sqlx::query_as( - "SELECT * FROM documents \ - WHERE person_id IS NOT DISTINCT FROM $1 AND company_id IS NOT DISTINCT FROM $2", + "SELECT * FROM documents WHERE person_id IS NOT DISTINCT FROM $1 \ + AND company_id IS NOT DISTINCT FROM $2 AND client_id IS NOT DISTINCT FROM $3", ) .bind(owner.person()) .bind(owner.company()) + .bind(owner.client()) .fetch_all(db) .await?; Ok(sorted(owner, docs)) @@ -387,12 +405,13 @@ pub async fn list(db: &PgPool, owner: Owner) -> Result> { pub async fn get(db: &PgPool, owner: Owner, id: i64) -> Result> { Ok(sqlx::query_as( - "SELECT * FROM documents WHERE id = $1 \ - AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3", + "SELECT * FROM documents WHERE id = $1 AND person_id IS NOT DISTINCT FROM $2 \ + AND company_id IS NOT DISTINCT FROM $3 AND client_id IS NOT DISTINCT FROM $4", ) .bind(id) .bind(owner.person()) .bind(owner.company()) + .bind(owner.client()) .fetch_optional(db) .await?) } @@ -402,11 +421,12 @@ pub async fn same_file(db: &PgPool, owner: Owner, sha256: &str) -> Result