-- 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' ) );