2023-06-28 20:39:27 +03:00
|
|
|
from uuid import UUID
|
2023-06-04 00:12:42 +03:00
|
|
|
|
2023-06-28 20:39:27 +03:00
|
|
|
from logger import get_logger
|
|
|
|
from models.settings import common_dependencies
|
|
|
|
from pydantic import BaseModel
|
2023-06-04 00:12:42 +03:00
|
|
|
|
2023-06-28 20:39:27 +03:00
|
|
|
logger = get_logger(__name__)
|
2023-06-29 19:26:03 +03:00
|
|
|
|
|
|
|
|
2023-06-20 10:54:23 +03:00
|
|
|
class User(BaseModel):
|
2023-06-28 20:39:27 +03:00
|
|
|
id: UUID
|
2023-06-04 00:12:42 +03:00
|
|
|
email: str
|
2023-06-28 20:39:27 +03:00
|
|
|
user_openai_api_key: str = None
|
|
|
|
requests_count: int = 0
|
|
|
|
|
|
|
|
# [TODO] Rename the user table and its references to 'user_usage'
|
2023-06-29 19:26:03 +03:00
|
|
|
def create_user(self, date):
|
2023-06-28 20:39:27 +03:00
|
|
|
|
|
|
|
commons = common_dependencies()
|
|
|
|
logger.info(f"New user entry in db document for user {self.email}")
|
|
|
|
|
2023-06-29 19:26:03 +03:00
|
|
|
return (commons['supabase'].table("users").insert(
|
2023-06-28 20:39:27 +03:00
|
|
|
{"user_id": self.id, "email": self.email, "date": date, "requests_count": 1}).execute())
|
|
|
|
|
|
|
|
def get_user_request_stats(self):
|
|
|
|
commons = common_dependencies()
|
|
|
|
requests_stats = commons['supabase'].from_('users').select(
|
|
|
|
'*').filter("user_id", "eq", self.id).execute()
|
|
|
|
return requests_stats.data
|
|
|
|
|
|
|
|
def fetch_user_requests_count(self, date):
|
|
|
|
commons = common_dependencies()
|
|
|
|
response = (
|
|
|
|
commons["supabase"]
|
|
|
|
.from_("users")
|
|
|
|
.select("*")
|
|
|
|
.filter("user_id", "eq", self.id)
|
|
|
|
.filter("date", "eq", date)
|
|
|
|
.execute()
|
|
|
|
)
|
|
|
|
userItem = next(iter(response.data or []), {"requests_count": 0})
|
|
|
|
|
|
|
|
return userItem["requests_count"]
|
|
|
|
|
|
|
|
def increment_user_request_count(self, date):
|
|
|
|
commons = common_dependencies()
|
|
|
|
requests_count = self.fetch_user_requests_count(date) + 1
|
|
|
|
logger.info(f"User {self.email} request count updated to {requests_count}")
|
|
|
|
commons['supabase'].table("users").update(
|
2023-06-29 19:26:03 +03:00
|
|
|
{"requests_count": requests_count}).match({"user_id": self.id, "date": date}).execute()
|
2023-06-28 20:39:27 +03:00
|
|
|
self.requests_count = requests_count
|
|
|
|
|