quivr/backend/core/models/users.py

56 lines
1.6 KiB
Python
Raw Normal View History

from typing import Optional
2023-06-28 20:39:27 +03:00
from uuid import UUID
2023-06-28 20:39:27 +03:00
from logger import get_logger
from models.databases.supabase.supabase import SupabaseDB
from models.settings import get_supabase_db
2023-06-28 20:39:27 +03:00
from pydantic import BaseModel
2023-06-28 20:39:27 +03:00
logger = get_logger(__name__)
2023-06-29 19:26:03 +03:00
# [TODO] Rename the user table and its references to 'user_usage'
class User(BaseModel):
2023-06-28 20:39:27 +03:00
id: UUID
email: Optional[str]
user_openai_api_key: Optional[str] = None
2023-06-28 20:39:27 +03:00
requests_count: int = 0
@property
def supabase_db(self) -> SupabaseDB:
return get_supabase_db()
# [TODO] Rename the user table and its references to 'user_usage'
2023-06-28 20:39:27 +03:00
2023-06-29 19:26:03 +03:00
def create_user(self, date):
2023-07-10 20:28:38 +03:00
"""
Create a new user entry in the database
Args:
date (str): Date of the request
"""
2023-06-28 20:39:27 +03:00
logger.info(f"New user entry in db document for user {self.email}")
return self.supabase_db.create_user(self.id, self.email, date)
2023-06-28 20:39:27 +03:00
def get_user_request_stats(self):
2023-07-10 20:28:38 +03:00
"""
Fetch the user request stats from the database
"""
request = self.supabase_db.get_user_request_stats(self.id)
2023-06-28 20:39:27 +03:00
return request.data
2023-06-28 20:39:27 +03:00
def increment_user_request_count(self, date):
2023-07-10 20:28:38 +03:00
"""
Increment the user request count in the database
"""
response = self.supabase_db.fetch_user_requests_count(self.id, date)
userItem = next(iter(response.data or []), {"requests_count": 0})
requests_count = userItem["requests_count"] + 1
2023-06-28 20:39:27 +03:00
logger.info(f"User {self.email} request count updated to {requests_count}")
self.supabase_db.update_user_request_count(self.id, requests_count, date)
2023-06-28 20:39:27 +03:00
self.requests_count = requests_count