-- Add visibility field to forms ALTER TABLE forms ADD COLUMN IF NOT EXISTS visibility VARCHAR(20) DEFAULT 'restricted'; -- Set all existing forms to restricted (only author has access by default) UPDATE forms SET visibility = 'restricted' WHERE visibility IS NULL; -- Create form_access_rules table CREATE TABLE IF NOT EXISTS form_access_rules ( id SERIAL PRIMARY KEY, form_id INTEGER NOT NULL REFERENCES forms(id) ON DELETE CASCADE, organization_id INTEGER NOT NULL REFERENCES organizations(id) ON DELETE CASCADE, target_type VARCHAR(10) NOT NULL CHECK (target_type IN ('user', 'role')), target_id INTEGER NOT NULL, access_level VARCHAR(20) NOT NULL DEFAULT 'participate' CHECK (access_level IN ('participate', 'view_all', 'admin')), created_at TIMESTAMP DEFAULT NOW() ); -- Unique constraint: one rule per form + target CREATE UNIQUE INDEX IF NOT EXISTS form_access_rules_unique ON form_access_rules(form_id, target_type, target_id); -- Indexes for performance CREATE INDEX IF NOT EXISTS form_access_rules_form_idx ON form_access_rules(form_id); CREATE INDEX IF NOT EXISTS form_access_rules_org_idx ON form_access_rules(organization_id);