-- Email Activity Log System -- Tracks all actions and events for emails CREATE TABLE IF NOT EXISTS email_activity_log ( id SERIAL PRIMARY KEY, email_id INTEGER NOT NULL REFERENCES email_messages(id) ON DELETE CASCADE, event_type VARCHAR(50) NOT NULL, -- fetched, saved, classified, workflow_executed, rule_matched, status_changed, read, attachment_downloaded, linked, etc. event_category VARCHAR(30) NOT NULL DEFAULT 'system', -- system, user, workflow, rule, integration description TEXT NOT NULL, metadata JSONB, -- Flexible storage for event-specific data user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL, -- NULL for system events created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_by VARCHAR(255) -- email or system identifier ); -- Indexes for performance CREATE INDEX IF NOT EXISTS idx_email_activity_log_email_id ON email_activity_log(email_id); CREATE INDEX IF NOT EXISTS idx_email_activity_log_event_type ON email_activity_log(event_type); CREATE INDEX IF NOT EXISTS idx_email_activity_log_created_at ON email_activity_log(created_at DESC); CREATE INDEX IF NOT EXISTS idx_email_activity_log_category ON email_activity_log(event_category); -- View for easy email timeline CREATE OR REPLACE VIEW email_timeline AS SELECT eal.id, eal.email_id, em.subject, em.sender_email, eal.event_type, eal.event_category, eal.description, eal.metadata, eal.user_id, u.username as user_name, eal.created_at, eal.created_by FROM email_activity_log eal LEFT JOIN email_messages em ON eal.email_id = em.id LEFT JOIN users u ON eal.user_id = u.user_id ORDER BY eal.created_at DESC; -- Helper function to log email events CREATE OR REPLACE FUNCTION log_email_event( p_email_id INTEGER, p_event_type VARCHAR(50), p_event_category VARCHAR(30), p_description TEXT, p_metadata JSONB DEFAULT NULL, p_user_id INTEGER DEFAULT NULL, p_created_by VARCHAR(255) DEFAULT 'system' ) RETURNS INTEGER AS $$ DECLARE v_log_id INTEGER; BEGIN INSERT INTO email_activity_log ( email_id, event_type, event_category, description, metadata, user_id, created_by ) VALUES ( p_email_id, p_event_type, p_event_category, p_description, p_metadata, p_user_id, p_created_by ) RETURNING id INTO v_log_id; RETURN v_log_id; END; $$ LANGUAGE plpgsql; COMMENT ON TABLE email_activity_log IS 'Complete audit trail of all email events and actions'; COMMENT ON FUNCTION log_email_event IS 'Helper function to log email events with consistent format';