-- +goose Up -- Accounts ask the platform's admins for help. A ticket belongs to the -- account that opened it, even a suspended one; deleting the account -- deletes its tickets. It may point at an organization and things in it -- the question is about; deleting those leaves the ticket. CREATE TABLE support_tickets ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, org_id uuid REFERENCES orgs (id) ON DELETE SET NULL, monitor_id uuid REFERENCES monitors (id) ON DELETE SET NULL, channel_id uuid REFERENCES notification_channels (id) ON DELETE SET NULL, alert_group_id uuid REFERENCES alert_groups (id) ON DELETE SET NULL, status_page_id uuid REFERENCES status_pages (id) ON DELETE SET NULL, incident_id uuid REFERENCES incidents (id) ON DELETE SET NULL, subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 200), -- open waits for the admins, answered for the account. status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'answered', 'closed')), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX support_tickets_user_idx ON support_tickets (user_id, updated_at DESC); CREATE INDEX support_tickets_status_idx ON support_tickets (status, updated_at DESC); CREATE TABLE support_messages ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), ticket_id uuid NOT NULL REFERENCES support_tickets (id) ON DELETE CASCADE, -- author_id is empty once the admin who wrote it is deleted. author_id uuid REFERENCES users (id) ON DELETE SET NULL, from_staff boolean NOT NULL, body text NOT NULL CHECK (length(body) BETWEEN 1 AND 10000), created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX support_messages_ticket_idx ON support_messages (ticket_id, created_at); ALTER TABLE support_tickets ENABLE ROW LEVEL SECURITY; ALTER TABLE support_tickets FORCE ROW LEVEL SECURITY; CREATE POLICY support_tickets_own ON support_tickets FOR ALL USING (app_scope_system() OR user_id = app_user_id()) WITH CHECK (app_scope_system() OR user_id = app_user_id()); ALTER TABLE support_messages ENABLE ROW LEVEL SECURITY; ALTER TABLE support_messages FORCE ROW LEVEL SECURITY; CREATE POLICY support_messages_own ON support_messages FOR ALL USING (app_scope_system() OR EXISTS ( SELECT 1 FROM support_tickets t WHERE t.id = ticket_id AND t.user_id = app_user_id())) WITH CHECK (app_scope_system() OR (NOT from_staff AND EXISTS ( SELECT 1 FROM support_tickets t WHERE t.id = ticket_id AND t.user_id = app_user_id()))); -- +goose Down DROP TABLE support_messages; DROP TABLE support_tickets;