|
| 1 | +import logging |
| 2 | +from typing import Dict, Any, Optional |
| 3 | +from datetime import datetime |
| 4 | +import uuid |
| 5 | +from app.database.supabase.client import get_supabase_client |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | +supabase = get_supabase_client() |
| 9 | + |
| 10 | + |
| 11 | +async def ensure_user_exists( |
| 12 | + user_id: str, |
| 13 | + platform: str, |
| 14 | + username: Optional[str] = None, |
| 15 | + display_name: Optional[str] = None, |
| 16 | + avatar_url: Optional[str] = None |
| 17 | +) -> Optional[str]: |
| 18 | + """ |
| 19 | + Ensure a user exists in the database. If not, create them. |
| 20 | + Returns the user's UUID, or None if an error occurs. |
| 21 | +
|
| 22 | + Args: |
| 23 | + user_id: Platform-specific user ID (e.g., discord_id, slack_id) |
| 24 | + platform: Platform name (discord, slack, github) |
| 25 | + username: Platform username |
| 26 | + display_name: Display name for the user |
| 27 | + avatar_url: Avatar URL |
| 28 | +
|
| 29 | + Returns: |
| 30 | + User UUID as string, or None on error |
| 31 | + """ |
| 32 | + try: |
| 33 | + platform_id_column = f"{platform}_id" |
| 34 | + platform_username_column = f"{platform}_username" |
| 35 | + |
| 36 | + # Check if user exists |
| 37 | + response = await supabase.table("users").select("id").eq(platform_id_column, user_id).limit(1).execute() |
| 38 | + |
| 39 | + if response.data: |
| 40 | + user_uuid = response.data[0]['id'] |
| 41 | + logger.info(f"User found: {user_uuid} for {platform_id_column}: {user_id}") |
| 42 | + |
| 43 | + # Update last_active timestamp |
| 44 | + last_active_column = f"last_active_{platform}" |
| 45 | + await supabase.table("users").update({ |
| 46 | + last_active_column: datetime.now().isoformat() |
| 47 | + }).eq("id", user_uuid).execute() |
| 48 | + |
| 49 | + return user_uuid |
| 50 | + |
| 51 | + # User doesn't exist, create new user |
| 52 | + logger.info(f"Creating new user for {platform_id_column}: {user_id}") |
| 53 | + |
| 54 | + new_user = { |
| 55 | + "id": str(uuid.uuid4()), |
| 56 | + platform_id_column: user_id, |
| 57 | + "display_name": display_name or username or f"{platform}_user_{user_id[:8]}", |
| 58 | + } |
| 59 | + |
| 60 | + if username: |
| 61 | + new_user[platform_username_column] = username |
| 62 | + if avatar_url: |
| 63 | + new_user["avatar_url"] = avatar_url |
| 64 | + |
| 65 | + # Set last_active timestamp |
| 66 | + last_active_column = f"last_active_{platform}" |
| 67 | + new_user[last_active_column] = datetime.now().isoformat() |
| 68 | + |
| 69 | + insert_response = await supabase.table("users").insert(new_user).execute() |
| 70 | + |
| 71 | + if insert_response.data: |
| 72 | + user_uuid = insert_response.data[0]['id'] |
| 73 | + logger.info(f"User created successfully: {user_uuid}") |
| 74 | + return user_uuid |
| 75 | + else: |
| 76 | + logger.error(f"Failed to create user: {insert_response}") |
| 77 | + return None |
| 78 | + |
| 79 | + except Exception as e: |
| 80 | + logger.error(f"Error ensuring user exists: {str(e)}") |
| 81 | + return None |
| 82 | + |
| 83 | + |
| 84 | +async def store_interaction( |
| 85 | + user_uuid: str, |
| 86 | + platform: str, |
| 87 | + platform_specific_id: str, |
| 88 | + channel_id: Optional[str] = None, |
| 89 | + thread_id: Optional[str] = None, |
| 90 | + content: Optional[str] = None, |
| 91 | + interaction_type: Optional[str] = None, |
| 92 | + intent_classification: Optional[str] = None, |
| 93 | + topics_discussed: Optional[list] = None, |
| 94 | + metadata: Optional[Dict[str, Any]] = None |
| 95 | +) -> bool: |
| 96 | + """ |
| 97 | + Store an interaction in the database. |
| 98 | +
|
| 99 | + Args: |
| 100 | + user_uuid: User's UUID from users table |
| 101 | + platform: Platform name (discord, slack, github) |
| 102 | + platform_specific_id: Platform-specific message/interaction ID |
| 103 | + channel_id: Channel ID where interaction occurred |
| 104 | + thread_id: Thread ID where interaction occurred |
| 105 | + content: Content of the interaction |
| 106 | + interaction_type: Type of interaction (message, comment, pr, etc.) |
| 107 | + intent_classification: Classification of user intent |
| 108 | + topics_discussed: List of topics discussed |
| 109 | + metadata: Additional metadata |
| 110 | +
|
| 111 | + Returns: |
| 112 | + True if successful, False otherwise |
| 113 | + """ |
| 114 | + try: |
| 115 | + interaction_data = { |
| 116 | + "id": str(uuid.uuid4()), |
| 117 | + "user_id": user_uuid, |
| 118 | + "platform": platform, |
| 119 | + "platform_specific_id": platform_specific_id, |
| 120 | + } |
| 121 | + |
| 122 | + if channel_id: |
| 123 | + interaction_data["channel_id"] = channel_id |
| 124 | + if thread_id: |
| 125 | + interaction_data["thread_id"] = thread_id |
| 126 | + if content: |
| 127 | + interaction_data["content"] = content |
| 128 | + if interaction_type: |
| 129 | + interaction_data["interaction_type"] = interaction_type |
| 130 | + if intent_classification: |
| 131 | + interaction_data["intent_classification"] = intent_classification |
| 132 | + if topics_discussed: |
| 133 | + interaction_data["topics_discussed"] = topics_discussed |
| 134 | + if metadata: |
| 135 | + interaction_data["metadata"] = metadata |
| 136 | + |
| 137 | + response = await supabase.table("interactions").insert(interaction_data).execute() |
| 138 | + |
| 139 | + if response.data: |
| 140 | + logger.info(f"Interaction stored successfully for user {user_uuid}") |
| 141 | + |
| 142 | + # Atomically increment user's total_interactions_count |
| 143 | + try: |
| 144 | + rpc_response = await supabase.rpc("increment_user_interaction_count", {"user_uuid": user_uuid}).execute() |
| 145 | + if rpc_response.data is not None: |
| 146 | + logger.debug(f"Updated interaction count for user {user_uuid}: {rpc_response.data}") |
| 147 | + else: |
| 148 | + logger.warning(f"User {user_uuid} not found when incrementing interaction count") |
| 149 | + except Exception as e: |
| 150 | + logger.exception("Error incrementing user interaction count") |
| 151 | + |
| 152 | + # Not failing the entire operation if incrementing the interaction count fails |
| 153 | + return True |
| 154 | + |
| 155 | + except Exception as e: |
| 156 | + logger.error(f"Error storing interaction: {str(e)}") |
| 157 | + return False |
| 158 | + |
| 159 | + |
| 160 | +async def get_conversation_context(user_uuid: str) -> Optional[Dict[str, Any]]: |
| 161 | + """ |
| 162 | + Retrieve conversation context for a user. |
| 163 | +
|
| 164 | + Args: |
| 165 | + user_uuid: User's UUID from users table |
| 166 | +
|
| 167 | + Returns: |
| 168 | + Dictionary containing conversation context, or None if not found |
| 169 | + """ |
| 170 | + try: |
| 171 | + response = await supabase.table("conversation_context").select("*").eq("user_id", user_uuid).limit(1).execute() |
| 172 | + |
| 173 | + if response.data: |
| 174 | + context = response.data[0] |
| 175 | + logger.info(f"Retrieved conversation context for user {user_uuid}") |
| 176 | + return { |
| 177 | + "conversation_summary": context.get("conversation_summary"), |
| 178 | + "key_topics": context.get("key_topics", []), |
| 179 | + "total_interactions": context.get("total_interactions", 0), |
| 180 | + "session_start_time": context.get("session_start_time"), |
| 181 | + "session_end_time": context.get("session_end_time"), |
| 182 | + } |
| 183 | + else: |
| 184 | + logger.info(f"No conversation context found for user {user_uuid}") |
| 185 | + return None |
| 186 | + |
| 187 | + except Exception as e: |
| 188 | + logger.error(f"Error retrieving conversation context: {str(e)}") |
| 189 | + return None |
0 commit comments