feat: Improve user credit calculation in get_user_credits (#3367)

Refactor the get_user_credits method in the Users class to improve the
calculation of monthly chat credits for a user. This change ensures that
the user's monthly chat credit is correctly deducted based on their
usage. If no user settings or monthly chat credit is found, a default
value of 25 is returned.

# Description

Please include a summary of the changes and the related issue. Please
also include relevant motivation and context.

## Checklist before requesting a review

Please delete options that are not relevant.

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my code
- [ ] I have commented hard-to-understand areas
- [ ] I have ideally added tests that prove my fix is effective or that
my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged

## Screenshots (if appropriate):
This commit is contained in:
Stan Girard 2024-10-14 15:53:44 +02:00 committed by GitHub
parent 367242a3d5
commit 5fc349cd78
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 22 additions and 16 deletions

View File

@ -110,17 +110,27 @@ class Users(UsersInterface):
self.db.table("users").delete().filter("id", "eq", str(user_id)).execute()
def get_user_credits(self, user_id):
user_usage_instance = user_usage.UserUsage(id=user_id)
try:
user_usage_instance = user_usage.UserUsage(id=user_id)
user_monthly_usage = user_usage_instance.get_user_monthly_usage(
time.strftime("%Y%m%d")
)
monthly_chat_credit = (
self.db.from_("user_settings")
.select("monthly_chat_credit")
.filter("user_id", "eq", str(user_id))
.execute()
.data[0]["monthly_chat_credit"]
)
user_monthly_usage = user_usage_instance.get_user_monthly_usage(
time.strftime("%Y%m%d")
)
response = self.db.from_("user_settings").select("monthly_chat_credit").filter(
"user_id", "eq", str(user_id)
).execute()
if not response.data:
raise ValueError("No data found for user settings")
return monthly_chat_credit - user_monthly_usage
monthly_chat_credit = response.data[0].get("monthly_chat_credit")
if monthly_chat_credit is None:
raise ValueError("Monthly chat credit not found")
return monthly_chat_credit - user_monthly_usage
except Exception as e:
# Log the exception or handle it as needed
print(f"An error occurred while getting user credits: {e}")
return 25 # or a default value, depending on your needs

View File

@ -56,11 +56,7 @@ class UserUsage(UserIdentity):
"""
Fetch the user monthly usage from the database
"""
posthog = PostHogSettings()
request = self.supabase_db.get_user_requests_count_for_month(self.id, date)
posthog.set_user_properties(
self.id, "MONTHLY_USAGE", {"monthly_chat_usage": request}
)
return request