Skip to content

Add business-only Analytics tab with basic credit usage tracking #617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions app_users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ def cached_workspaces(self) -> list["Workspace"]:
from workspaces.models import Workspace

return list(
Workspace.objects.filter(
memberships__user=self, memberships__deleted__isnull=True
).order_by("-is_personal", "-created_at")
Workspace.objects.select_related("subscription")
.filter(memberships__user=self, memberships__deleted__isnull=True)
.order_by("-is_personal", "-created_at")
) or [self.get_or_create_personal_workspace()[0]]

def get_handle(self) -> Handle | None:
Expand Down
1 change: 1 addition & 0 deletions daras_ai_v2/icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
chevron_right = '<i class="fa-sharp-duotone fa-solid fa-sm fa-chevron-right"></i>'
check = '<i class="fa-solid fa-check"></i>'
octopus = '<i class="fa-regular fa-octopus"></i>'
analytics = '<i class="fa-regular fa-chart-pie-simple-circle-dollar"></i>'

# brands
github = '<i class="fa-brands fa-github"></i>'
Expand Down
80 changes: 77 additions & 3 deletions routers/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from daras_ai_v2.profiles import edit_user_profile_page
from daras_ai_v2.urls import paginate_queryset, paginate_button
from managed_secrets.widgets import manage_secrets_table
from payments.plans import PricingPlan
from payments.webhooks import PaypalWebhookHandler
from routers.custom_api_router import CustomAPIRouter
from routers.root import explore_page, page_wrapper, get_og_url_path
Expand Down Expand Up @@ -175,7 +176,7 @@ def api_keys_route(request: Request):
@gui.route(app, "/workspaces/members/")
def members_route(request: Request):
with account_page_wrapper(request, AccountTabs.members) as current_workspace:
if current_workspace.is_personal:
if not current_workspace or current_workspace.is_personal:
raise gui.RedirectException(get_route_path(profile_route))
workspaces_page(request.user, request.session)

Expand All @@ -191,6 +192,16 @@ def members_route(request: Request):
)


@gui.route(app, "/workspaces/analytics/")
def analytics_route(request: Request):
with account_page_wrapper(request, AccountTabs.analytics) as current_workspace:
if AccountTabs.analytics not in AccountTabs.get_tabs_for_user(
request.user, workspace=current_workspace
):
raise gui.RedirectException(get_route_path(account_route))
analytics_tab(request=request, workspace=current_workspace)


@gui.route(app, "/workspaces/{workspace_slug}/invite/{email}-{invite_id}")
def invitation_route(
request: Request,
Expand Down Expand Up @@ -238,24 +249,33 @@ class AccountTabs(TabData, Enum):
saved = TabData(title=f"{icons.save} Saved", route=saved_route)
api_keys = TabData(title=f"{icons.api} API Keys", route=api_keys_route)
billing = TabData(title=f"{icons.billing} Billing", route=account_route)
analytics = TabData(title=f"{icons.analytics} Analytics", route=analytics_route)

@property
def url_path(self) -> str:
return get_route_path(self.route)

@classmethod
def get_tabs_for_user(
cls, user: typing.Optional["AppUser"], workspace: Workspace | None
cls, user: "AppUser", workspace: Workspace | None
) -> list["AccountTabs"]:

ret = list(cls)

if workspace.is_personal:
if not workspace or workspace.is_personal:
ret.remove(cls.members)
ret.remove(cls.analytics)
else:
ret.remove(cls.profile)
if not workspace.memberships.get(user=user).can_edit_workspace():
ret.remove(cls.billing)
ret.remove(cls.analytics)
elif not workspace.subscription or (
PricingPlan.from_db_value(workspace.subscription.plan)
not in (PricingPlan.BUSINESS, PricingPlan.ENTERPRISE)
):
# only for business and enterprise plans
ret.remove(cls.analytics)

return ret

Expand Down Expand Up @@ -356,6 +376,60 @@ def _render_run(pr: PublishedRun):
paginate_button(url=request.url, cursor=cursor)


def analytics_tab(request: Request, workspace: Workspace):
gui.write("# Usage & Limits")
gui.caption(
f"Member, API & Integration usage for **{workspace.display_name(request.user)}**."
)

with gui.div(className="table-responsive"), gui.tag("table", className="table"):
with gui.tag("thead"), gui.tag("tr"):
with gui.tag("th", scope="col"):
gui.html("Name")
with gui.tag("th", scope="col"):
gui.html("Type")
with gui.tag("th", scope="col"):
gui.html("Runs")
with gui.tag("th", scope="col"):
gui.html("Credits Used")
with gui.tag("th", scope="col"):
gui.html("")

with gui.tag("tbody"):
for m in workspace.memberships.all():
with gui.tag("tr", className="no-margin"):
with gui.tag("td"):
gui.write(m.user.full_name())
with gui.tag("td"):
gui.html("User")
with gui.tag("td"):
gui.html(f"{m.get_run_count()}")
with gui.tag("td"):
gui.html(f"{m.get_credit_usage()} Cr")
with gui.tag("td"):
gui.html("")

with gui.tag("tr", className="no-margin"):
with gui.tag("td"):
gui.write(f"[API Keys]({get_route_path(api_keys_route)})")
with gui.tag("td"):
gui.html("API Key")
with gui.tag("td"):
gui.html(f"{workspace.get_api_key_run_count()}")
with gui.tag("td"):
gui.html(f"{workspace.get_api_key_credit_usage()} Cr")

with gui.tag("tr", className="no-margin"):
with gui.tag("td"):
gui.write("Bot Integrations")
with gui.tag("td"):
gui.html("Bot")
with gui.tag("td"):
gui.html(f"{workspace.get_bot_run_count()}")
with gui.tag("td"):
gui.html(f"{workspace.get_bot_credit_usage()} Cr")


def api_keys_tab(request: Request):
workspace = get_current_workspace(request.user, request.session)

Expand Down
45 changes: 45 additions & 0 deletions workspaces/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from django.db import models, transaction, IntegrityError
from django.db.backends.base.schema import logger
from django.db.models.aggregates import Sum
from django.db.models.functions import Abs
from django.db.models.query_utils import Q
from django.utils import timezone
from django.utils.text import slugify
Expand Down Expand Up @@ -294,6 +295,35 @@ def add_balance(
pass
raise

def get_api_key_run_count(self) -> int:
return (
self.saved_runs.filter(is_api_call=True, price__gt=0)
.exclude(messages__isnull=False)
.count()
)

def get_api_key_credit_usage(self) -> int:
return (
self.saved_runs.filter(is_api_call=True)
.exclude(messages__isnull=False) # exclude bot-integration runs
.aggregate(total=Sum("price"))
.get("total")
or 0
)

def get_bot_run_count(self) -> int:
return self.saved_runs.filter(
is_api_call=True, price__gt=0, messages__isnull=False
).count()

def get_bot_credit_usage(self) -> int:
return (
self.saved_runs.filter(is_api_call=True, messages__isnull=False)
.aggregate(total=Sum("price"))
.get("total")
or 0
)

def get_or_create_stripe_customer(self) -> stripe.Customer:
customer = None

Expand Down Expand Up @@ -509,6 +539,21 @@ def can_invite(self):
and not self.workspace.is_personal
)

def get_run_count(self) -> int:
return self.workspace.saved_runs.filter(
uid=self.user.uid,
price__gt=0, # proxy for successful runs
is_api_call=False,
).count()

def get_credit_usage(self) -> int:
return (
self.workspace.saved_runs.filter(
uid=self.user.uid, price__gt=0, is_api_call=False
).aggregate(total=Sum("price"))["total"]
or 0
)


class WorkspaceInviteQuerySet(models.QuerySet):
def create_and_send_invite(
Expand Down