-- visa.buildfor.life, task 7.6: agreements the client signs through their -- link (docs/PLAN.md "Phase 7"). -- -- An agreement (the processing of the client's data, later legal services -- or a consultation) has versions; a version's text never changes once it -- is published, so a signature always names the exact words signed. A new -- text is a new version, which every client signs again at their next -- link. The signed PDF is a document of the person (kind `agreement`). CREATE TABLE agreements ( id BIGSERIAL PRIMARY KEY, title TEXT NOT NULL CHECK (title <> ''), -- every client link asks for it while it is active active BOOLEAN NOT NULL DEFAULT true, created_by TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE agreement_versions ( id BIGSERIAL PRIMARY KEY, agreement_id BIGINT NOT NULL REFERENCES agreements (id), version INTEGER NOT NULL CHECK (version > 0), -- the text as legal wrote it: paragraphs separated by an empty line, -- "# " before a heading, "- " before a list item body TEXT NOT NULL CHECK (body <> ''), -- of the body, as UTF-8; printed on every signed copy sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), published_by TEXT NOT NULL, published_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE (agreement_id, version) ); CREATE FUNCTION agreement_versions_unchanged() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'a published agreement text never changes: publish a new version'; END $$; CREATE TRIGGER agreement_versions_no_change BEFORE UPDATE OR DELETE ON agreement_versions FOR EACH ROW EXECUTE FUNCTION agreement_versions_unchanged(); CREATE TABLE signatures ( id BIGSERIAL PRIMARY KEY, person_id BIGINT NOT NULL REFERENCES people (id), version_id BIGINT NOT NULL REFERENCES agreement_versions (id), -- the link it was signed through link_id BIGINT REFERENCES client_links (id), -- the name the client typed as their signature signed_name TEXT NOT NULL CHECK (signed_name <> ''), -- whether they also drew one (it is in the PDF only) drawn BOOLEAN NOT NULL DEFAULT false, signed_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- the client's address as the proxy forwarded it, and their browser ip TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '', -- the signed copy document_id BIGINT REFERENCES documents (id), UNIQUE (person_id, version_id) ); CREATE INDEX signatures_person ON signatures (person_id); 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' ) );