-- A workspace's own filled contract documents: for now the AVV, which staff -- fill in from the released master with the company's details (name, -- address, management, who gives instructions) and upload as a PDF to the -- document bucket. The row records which master version it was made from, -- the PDF's SHA-256 (checked before every download), the digest of the -- details filled in (the details themselves are not stored here) and the -- staff member who made it. Rows are never changed: a corrected document is a -- new row, and the newest per tenant and kind is the current one. CREATE TABLE tenant_contract_documents ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, doc_kind TEXT NOT NULL CHECK (doc_kind IN ('avv')), version TEXT NOT NULL CHECK (version ~ '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'), sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), object_key TEXT NOT NULL CHECK (char_length(object_key) BETWEEN 1 AND 512), values_sha256 TEXT NOT NULL CHECK (values_sha256 ~ '^[0-9a-f]{64}$'), created_by TEXT NOT NULL CHECK (char_length(created_by) BETWEEN 1 AND 200), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX tenant_contract_documents_current ON tenant_contract_documents (tenant_id, doc_kind, id DESC); CREATE FUNCTION tenant_contract_documents_immutable() RETURNS trigger AS $$ BEGIN RAISE EXCEPTION 'tenant_contract_documents: rows are never changed; insert a new one'; END $$ LANGUAGE plpgsql; CREATE TRIGGER tenant_contract_documents_immutable BEFORE UPDATE ON tenant_contract_documents FOR EACH ROW EXECUTE FUNCTION tenant_contract_documents_immutable();