AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): admin CSV exports — credit transactions + copilot weekly usage (#12958)
Zamil Majdy09cb340acded
diff --git a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.pyindex c84ca292d9..c442b801c5 100644--- a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py+++ b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes.py@@ -1,11 +1,24 @@import loggingimport typing+from datetime import datetime, timezonefrom autogpt_libs.auth import get_user_id, requires_admin_user-from fastapi import APIRouter, Body, Security+from fastapi import APIRouter, Body, HTTPException, Query, Securityfrom prisma.enums import CreditTransactionType+from pydantic import BaseModel-from backend.data.credit import admin_get_user_history, get_user_credit_model+from backend.data.credit import (+ CREDIT_EXPORT_MAX_DAYS,+ admin_export_user_history,+ admin_get_user_history,+ get_user_credit_model,+)+from backend.data.model import UserTransaction+from backend.data.platform_cost import (+ COPILOT_USAGE_EXPORT_MAX_DAYS,+ CopilotWeeklyUsageRow,+ get_copilot_weekly_usage_for_export,+)from backend.util.json import SafeJsonfrom .model import AddUserCreditsResponse, UserHistoryResponse@@ -74,3 +87,135 @@ async def admin_get_all_user_history(except Exception as e:logger.exception(f"Error getting grant history: {e}")raise e+++class CreditTransactionsExportResponse(BaseModel):+ transactions: list[UserTransaction]+ total_rows: int+ window_days: int+ max_window_days: int+++ "/transactions/export",+ response_model=CreditTransactionsExportResponse,+ summary="Export Credit Transactions",+)+async def export_credit_transactions(+ # Typed Optional so orval generates `Date | null` and the URL builder+ # handles the union correctly. Both are validated as required below.+ start: typing.Optional[datetime] = Query(+ None, description="ISO timestamp (inclusive)"+ ),+ end: typing.Optional[datetime] = Query(+ None, description="ISO timestamp (inclusive)"+ ),+ transaction_type: typing.Optional[CreditTransactionType] = Query(None),+ user_id: typing.Optional[str] = Query(None),+ include_inactive: bool = Query(+ False,+ description=(+ "Include inactive rows (e.g. abandoned Stripe checkouts). "+ "Off by default so phantom rows aren't surfaced in normal exports."+ ),+ ),+ admin_user_id: str = Security(get_user_id),+) -> CreditTransactionsExportResponse:+ """Export CreditTransaction rows in [start, end] for finance reporting.++ Capped at CREDIT_EXPORT_MAX_DAYS days and CREDIT_EXPORT_MAX_ROWS rows;+ over-cap requests fail fast with 400 so callers narrow the window+ instead of receiving silently truncated data.+ """+ if start is None or end is None:+ raise HTTPException(+ status_code=400, detail="start and end query params are required"+ )+ # Coerce naive datetimes to UTC at the boundary so neither the data layer+ # nor the response builder hits a TypeError on (end - start) when callers+ # send mixed naive/aware shapes.+ if start.tzinfo is None:+ start = start.replace(tzinfo=timezone.utc)+ if end.tzinfo is None:+ end = end.replace(tzinfo=timezone.utc)+ logger.info(+ "Admin %s exporting credit transactions [%s..%s] type=%s user=%s incl_inactive=%s",+ admin_user_id,+ start.isoformat(),+ end.isoformat(),+ transaction_type.value if transaction_type else None,+ user_id,+ include_inactive,+ )+ try:+ history = await admin_export_user_history(+ start=start,+ end=end,+ transaction_type=transaction_type,+ user_id=user_id,+ include_inactive=include_inactive,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return CreditTransactionsExportResponse(+ transactions=history,+ total_rows=len(history),+ window_days=(end - start).days,+ max_window_days=CREDIT_EXPORT_MAX_DAYS,+ )+++class CopilotUsageExportResponse(BaseModel):+ rows: list[CopilotWeeklyUsageRow]+ total_rows: int+ window_days: int+ max_window_days: int+++ "/copilot-usage/export",+ response_model=CopilotUsageExportResponse,+ summary="Export Copilot Weekly Usage vs Rate Limit",+)+async def export_copilot_weekly_usage(+ # Typed Optional so orval generates `Date | null` and the URL builder+ # handles the union correctly. Both are validated as required below.+ start: typing.Optional[datetime] = Query(+ None, description="ISO timestamp (inclusive)"+ ),+ end: typing.Optional[datetime] = Query(+ None, description="ISO timestamp (inclusive)"+ ),+ admin_user_id: str = Security(get_user_id),+) -> CopilotUsageExportResponse:+ """Export per-(user, ISO week) copilot spend with the user's tier limit.++ Uses the same 90-day window cap and 100k row cap as the credit export.+ """+ if start is None or end is None:+ raise HTTPException(+ status_code=400, detail="start and end query params are required"+ )+ # Coerce naive datetimes to UTC at the boundary so neither the data layer+ # nor the response builder hits a TypeError on (end - start) when callers+ # send mixed naive/aware shapes.+ if start.tzinfo is None:+ start = start.replace(tzinfo=timezone.utc)+ if end.tzinfo is None:+ end = end.replace(tzinfo=timezone.utc)+ logger.info(+ "Admin %s exporting copilot weekly usage [%s..%s]",+ admin_user_id,+ start.isoformat(),+ end.isoformat(),+ )+ try:+ rows = await get_copilot_weekly_usage_for_export(start=start, end=end)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return CopilotUsageExportResponse(+ rows=rows,+ total_rows=len(rows),+ window_days=(end - start).days,+ max_window_days=COPILOT_USAGE_EXPORT_MAX_DAYS,+ )diff --git a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.pyindex d590f95a5f..da86994340 100644--- a/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/admin/credit_admin_routes_test.py@@ -314,3 +314,150 @@ def test_admin_endpoints_require_admin_role(mock_jwt_user) -> None:# Test users_history endpointresponse = client.get("/admin/users_history")assert response.status_code == 403++ # Test new export endpoints+ response = client.get(+ "/admin/transactions/export",+ params={"start": "2026-01-01T00:00:00", "end": "2026-01-31T00:00:00"},+ )+ assert response.status_code == 403+ response = client.get(+ "/admin/copilot-usage/export",+ params={"start": "2026-01-01T00:00:00", "end": "2026-01-31T00:00:00"},+ )+ assert response.status_code == 403+++def test_export_credit_transactions_success(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_export = AsyncMock(+ return_value=[+ UserTransaction(+ user_id="user-1",+ user_email="[email protected]",+ amount=1000,+ running_balance=2500,+ reason="Initial grant",+ admin_email="[email protected]",+ transaction_type=prisma.enums.CreditTransactionType.GRANT,+ ),+ UserTransaction(+ user_id="user-2",+ user_email="[email protected]",+ amount=-50,+ running_balance=4500,+ reason="",+ transaction_type=prisma.enums.CreditTransactionType.USAGE,+ ),+ ]+ )+ mocker.patch(+ "backend.api.features.admin.credit_admin_routes.admin_export_user_history",+ mock_export,+ )++ response = client.get(+ "/admin/transactions/export",+ params={+ "start": "2026-01-01T00:00:00",+ "end": "2026-01-31T00:00:00",+ "transaction_type": "GRANT",+ "user_id": "user-1",+ },+ )++ assert response.status_code == 200+ body = response.json()+ assert body["total_rows"] == 2+ assert body["window_days"] == 30+ assert body["max_window_days"] == 90+ assert body["transactions"][0]["user_email"] == "[email protected]"++ call_kwargs = mock_export.call_args.kwargs+ assert call_kwargs["transaction_type"] == prisma.enums.CreditTransactionType.GRANT+ assert call_kwargs["user_id"] == "user-1"+++def test_export_credit_transactions_window_too_wide_returns_400(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch(+ "backend.api.features.admin.credit_admin_routes.admin_export_user_history",+ AsyncMock(side_effect=ValueError("Export window must be <= 90 days")),+ )+ response = client.get(+ "/admin/transactions/export",+ params={+ "start": "2025-01-01T00:00:00",+ "end": "2026-01-01T00:00:00",+ },+ )+ assert response.status_code == 400+ assert "90 days" in response.json()["detail"]+++def test_export_credit_transactions_missing_window_is_400() -> None:+ response = client.get("/admin/transactions/export")+ assert response.status_code == 400+++def test_export_copilot_weekly_usage_success(+ mocker: pytest_mock.MockerFixture,+) -> None:+ from datetime import datetime, timezone++ from backend.data.platform_cost import CopilotWeeklyUsageRow++ rows = [+ CopilotWeeklyUsageRow(+ user_id="user-1",+ user_email="[email protected]",+ week_start=datetime(2026, 1, 5, tzinfo=timezone.utc),+ week_end=datetime(2026, 1, 12, tzinfo=timezone.utc),+ copilot_cost_microdollars=2_500_000,+ tier="PRO",+ weekly_limit_microdollars=25_000_000,+ percent_used=10.0,+ ),+ ]+ mock_export = AsyncMock(return_value=rows)+ mocker.patch(+ "backend.api.features.admin.credit_admin_routes.get_copilot_weekly_usage_for_export",+ mock_export,+ )++ response = client.get(+ "/admin/copilot-usage/export",+ params={+ "start": "2026-01-01T00:00:00",+ "end": "2026-01-31T00:00:00",+ },+ )++ assert response.status_code == 200+ body = response.json()+ assert body["total_rows"] == 1+ assert body["max_window_days"] == 90+ row = body["rows"][0]+ assert row["user_id"] == "user-1"+ assert row["tier"] == "PRO"+ assert row["weekly_limit_microdollars"] == 25_000_000+ assert row["percent_used"] == 10.0+++def test_export_copilot_weekly_usage_window_too_wide_returns_400(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch(+ "backend.api.features.admin.credit_admin_routes.get_copilot_weekly_usage_for_export",+ AsyncMock(side_effect=ValueError("Export window must be <= 90 days")),+ )+ response = client.get(+ "/admin/copilot-usage/export",+ params={+ "start": "2025-01-01T00:00:00",+ "end": "2026-01-01T00:00:00",+ },+ )+ assert response.status_code == 400diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex 0f84ff2f04..d90d72904d 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -3,7 +3,7 @@ import loggingimport timefrom abc import ABC, abstractmethodfrom collections import defaultdict-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezonefrom typing import TYPE_CHECKING, Any, castimport stripe@@ -2721,3 +2721,105 @@ async def admin_get_user_history(page_size=page_size,),)+++# Limits for credit-transaction CSV export. Window cap matches a typical+# finance-month query; row cap protects the API from accidental wide pulls+# (one big tenant can easily exceed 100k rows in 90 days).+CREDIT_EXPORT_MAX_DAYS = 90+CREDIT_EXPORT_MAX_ROWS = 100_000+++async def admin_export_user_history(+ start: datetime,+ end: datetime,+ transaction_type: CreditTransactionType | None = None,+ user_id: str | None = None,+ include_inactive: bool = False,+) -> list[UserTransaction]:+ """Return all CreditTransactions in the [start, end] window for export.++ Caps the window at CREDIT_EXPORT_MAX_DAYS and the row count at+ CREDIT_EXPORT_MAX_ROWS — callers should validate the window before calling+ so the user sees a 4xx instead of a silently truncated CSV.++ By default filters out `isActive=False` rows (e.g. abandoned Stripe+ checkouts whose `runningBalance` snapshot never advanced the user's real+ balance). Pass `include_inactive=True` to surface them when debugging+ why a checkout never completed.+ """+ # Normalize naive datetimes to UTC so direct API callers that send+ # `2026-01-01T00:00:00` (no tz) don't trip a TypeError when subtracted+ # against an aware `2026-01-31T00:00:00Z` partner.+ if start.tzinfo is None:+ start = start.replace(tzinfo=timezone.utc)+ if end.tzinfo is None:+ end = end.replace(tzinfo=timezone.utc)+ if end < start:+ raise ValueError("end must be >= start")+ # Compare timedeltas directly so 90d + any sub-day remainder still trips+ # the cap (.days truncates fractional days and was letting ~91d through).+ if (end - start) > timedelta(days=CREDIT_EXPORT_MAX_DAYS):+ raise ValueError(+ f"Export window must be <= {CREDIT_EXPORT_MAX_DAYS} days "+ f"(got {(end - start).total_seconds() / 86400:.2f} days)"+ )++ where: CreditTransactionWhereInput = {+ "createdAt": {"gte": start, "lte": end},+ }+ if transaction_type:+ where["type"] = transaction_type+ if user_id:+ where["userId"] = user_id+ if not include_inactive:+ where["isActive"] = True++ # Fetch one over the cap and reject — avoids the TOCTOU race a separate+ # count() + take=cap pair would have if rows land between the two queries.+ transactions = await CreditTransaction.prisma().find_many(+ where=where,+ include={"User": True},+ order={"createdAt": "desc"},+ take=CREDIT_EXPORT_MAX_ROWS + 1,+ )+ if len(transactions) > CREDIT_EXPORT_MAX_ROWS:+ raise ValueError(+ f"Export would return more than {CREDIT_EXPORT_MAX_ROWS} rows; "+ "narrow the window or add filters."+ )++ admin_id_to_email: dict[str, str] = {}++ async def _resolve_admin_email(admin_id: str) -> str:+ if admin_id in admin_id_to_email:+ return admin_id_to_email[admin_id]+ email = await get_user_email_by_id(admin_id) or ""+ admin_id_to_email[admin_id] = email+ return email++ history: list[UserTransaction] = []+ for tx in transactions:+ metadata: dict = cast(dict, tx.metadata) or {}+ admin_id = metadata.get("admin_id") or ""+ admin_email = await _resolve_admin_email(admin_id) if admin_id else ""+ # _top_up_credits writes reason as {"reason": "..."}; unwrap so the CSV+ # column carries a plain string regardless of source.+ raw_reason = metadata.get("reason", "") if metadata else ""+ if isinstance(raw_reason, dict):+ raw_reason = raw_reason.get("reason", "")+ reason = str(raw_reason) if raw_reason is not None else ""+ history.append(+ UserTransaction(+ transaction_key=tx.transactionKey,+ transaction_time=tx.createdAt,+ transaction_type=tx.type,+ amount=tx.amount,+ running_balance=tx.runningBalance or 0,+ user_id=tx.userId,+ user_email=tx.User.email if tx.User else None,+ reason=reason,+ admin_email=admin_email,+ )+ )+ return historydiff --git a/autogpt_platform/backend/backend/data/platform_cost.py b/autogpt_platform/backend/backend/data/platform_cost.pyindex ac5329c799..b5b5f415b1 100644--- a/autogpt_platform/backend/backend/data/platform_cost.py+++ b/autogpt_platform/backend/backend/data/platform_cost.py@@ -719,6 +719,139 @@ async def get_platform_cost_logs(EXPORT_MAX_ROWS = 100_000+# Caps for the copilot weekly-usage CSV export. Window cap matches the credit+# transactions export (CREDIT_EXPORT_MAX_DAYS in backend/data/credit.py) so+# finance has a consistent shape across both exports — keep them in sync.+COPILOT_USAGE_EXPORT_MAX_DAYS = 90+COPILOT_USAGE_EXPORT_MAX_ROWS = 100_000+++class CopilotWeeklyUsageRow(BaseModel):+ user_id: str+ user_email: str | None = None+ week_start: datetime+ week_end: datetime+ copilot_cost_microdollars: int+ tier: str+ weekly_limit_microdollars: int+ percent_used: float+++async def get_copilot_weekly_usage_for_export(+ start: datetime,+ end: datetime,+) -> list[CopilotWeeklyUsageRow]:+ """Aggregate copilot:* PlatformCostLog rows by (user, ISO week) for export.++ Joins User to surface the email and subscription tier in a single query,+ then computes the per-tier weekly limit from `get_tier_multipliers()` so+ `percent_used` reflects what's actually enforced (LD overrides included).++ Caveats:+ - Tier is the user's **current** tier — `PlatformCostLog` has no historical+ tier snapshot, so a recent upgrade/downgrade will retroactively reweight+ old weeks' `percent_used`. Filter by `week_start` and join with billing+ events outside this CSV if you need historically-correct attribution.+ - `NO_TIER` users have no enforced rate limit; their `percent_used` will+ report `0.0` (no denominator) — interpret these rows as "unmetered".+ """+ # Normalize naive datetimes to UTC so direct API callers that send+ # `2026-01-01T00:00:00` (no tz) don't trip a TypeError when subtracted+ # against an aware `2026-01-31T00:00:00Z` partner.+ if start.tzinfo is None:+ start = start.replace(tzinfo=timezone.utc)+ if end.tzinfo is None:+ end = end.replace(tzinfo=timezone.utc)+ if end < start:+ raise ValueError("end must be >= start")+ # Compare timedeltas directly so 90d + any sub-day remainder still trips+ # the cap (.days truncates fractional days and was letting ~91d through).+ if (end - start) > timedelta(days=COPILOT_USAGE_EXPORT_MAX_DAYS):+ raise ValueError(+ f"Export window must be <= {COPILOT_USAGE_EXPORT_MAX_DAYS} days "+ f"(got {(end - start).total_seconds() / 86400:.2f} days)"+ )++ # date_trunc('week', timestamptz) uses the session time zone by default,+ # which makes the per-week buckets non-deterministic across replicas in+ # different time zones. Convert to UTC explicitly via AT TIME ZONE so+ # the boundary is always Monday 00:00 UTC.+ rows = await query_raw_with_schema(+ 'SELECT log."userId" AS user_id,'+ ' u."email" AS user_email,'+ ' u."subscriptionTier" AS tier,'+ " (date_trunc('week', log.\"createdAt\" AT TIME ZONE 'UTC') AT TIME ZONE 'UTC')"+ " AS week_start,"+ ' SUM(COALESCE(log."costMicrodollars", 0))::bigint AS cost_microdollars'+ ' FROM {schema_prefix}"PlatformCostLog" log'+ ' LEFT JOIN {schema_prefix}"User" u ON u."id" = log."userId"'+ ' WHERE log."createdAt" >= $1::timestamptz'+ ' AND log."createdAt" <= $2::timestamptz'+ " AND log.\"blockName\" ILIKE 'copilot:%'"+ ' GROUP BY log."userId", u."email", u."subscriptionTier",'+ " (date_trunc('week', log.\"createdAt\" AT TIME ZONE 'UTC') AT TIME ZONE 'UTC')"+ " ORDER BY week_start ASC, cost_microdollars DESC"+ f" LIMIT {COPILOT_USAGE_EXPORT_MAX_ROWS + 1}",+ start,+ end,+ )++ if len(rows) > COPILOT_USAGE_EXPORT_MAX_ROWS:+ raise ValueError(+ f"Export would return {len(rows)} rows (cap is "+ f"{COPILOT_USAGE_EXPORT_MAX_ROWS}); narrow the window."+ )++ # Lazy import: backend.copilot.config and rate_limit pull settings which+ # transitively imports back into this module at startup.+ from backend.copilot.config import ChatConfig+ from backend.copilot.rate_limit import (+ DEFAULT_TIER,+ SubscriptionTier,+ get_tier_multipliers,+ )++ base_weekly = ChatConfig().weekly_cost_limit_microdollars+ # Use the LD-aware multipliers so percent_used reflects the limit that's+ # actually enforced for each user, not the static default.+ tier_multipliers = await get_tier_multipliers()++ out: list[CopilotWeeklyUsageRow] = []+ for r in rows:+ week_start: datetime = r["week_start"]+ if week_start.tzinfo is None:+ week_start = week_start.replace(tzinfo=timezone.utc)+ # Inclusive end-of-week (Sunday 23:59:59.999999 UTC) — matches finance+ # conventions where "the week" is Mon–Sun, not Mon–next Mon.+ week_end = week_start + timedelta(days=7, microseconds=-1)+ cost = int(r.get("cost_microdollars") or 0)+ tier_str = r.get("tier") or DEFAULT_TIER.value+ try:+ tier_enum = SubscriptionTier(tier_str)+ except ValueError:+ tier_enum = DEFAULT_TIER+ multiplier = tier_multipliers.get(tier_enum.value, 1.0)+ # Clamp to >= 0 so a misconfigured/negative multiplier never emits+ # negative limits in the CSV.+ weekly_limit = max(0, int(base_weekly * multiplier))+ if weekly_limit > 0:+ percent_used = round(100.0 * cost / weekly_limit, 2)+ else:+ percent_used = 0.0+ out.append(+ CopilotWeeklyUsageRow(+ user_id=r["user_id"],+ user_email=r.get("user_email"),+ week_start=week_start,+ week_end=week_end,+ copilot_cost_microdollars=cost,+ tier=tier_enum.value,+ weekly_limit_microdollars=weekly_limit,+ percent_used=percent_used,+ )+ )+ return out+async def get_platform_cost_logs_for_export(start: datetime | None = None,diff --git a/autogpt_platform/backend/backend/data/spending_export_test.py b/autogpt_platform/backend/backend/data/spending_export_test.pynew file mode 100644index 0000000000..95a2025bf9--- /dev/null+++ b/autogpt_platform/backend/backend/data/spending_export_test.py@@ -0,0 +1,357 @@+"""Unit tests for the admin CSV export functions on credit + platform_cost.++Mocks prisma + raw-SQL helpers so these run fast without the docker postgres.+"""++from datetime import datetime, timedelta, timezone+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from prisma.enums import CreditTransactionType++from backend.data.credit import (+ CREDIT_EXPORT_MAX_DAYS,+ CREDIT_EXPORT_MAX_ROWS,+ admin_export_user_history,+)+from backend.data.platform_cost import (+ COPILOT_USAGE_EXPORT_MAX_DAYS,+ get_copilot_weekly_usage_for_export,+)+++def _make_tx(+ *,+ user_id: str = "u1",+ amount: int = 100,+ running_balance: int = 1000,+ metadata: dict | None = None,+ user_email: str | None = "[email protected]",+ tx_type: CreditTransactionType = CreditTransactionType.GRANT,+ created_at: datetime | None = None,+) -> MagicMock:+ tx = MagicMock()+ tx.transactionKey = "tx-key"+ tx.createdAt = created_at or datetime(2026, 4, 1, tzinfo=timezone.utc)+ tx.type = tx_type+ tx.amount = amount+ tx.runningBalance = running_balance+ tx.userId = user_id+ tx.metadata = metadata or {}+ user = MagicMock()+ user.email = user_email+ tx.User = user if user_email is not None else None+ return tx+++class TestAdminExportUserHistory:+ @pytest.mark.asyncio+ async def test_rejects_inverted_window(self):+ with pytest.raises(ValueError, match="end must be >= start"):+ await admin_export_user_history(+ start=datetime(2026, 4, 30, tzinfo=timezone.utc),+ end=datetime(2026, 4, 1, tzinfo=timezone.utc),+ )++ @pytest.mark.asyncio+ async def test_rejects_window_exceeding_cap_by_subday_remainder(self):+ # 90 days + 1 second — `.days` would round to 90 and pass; timedelta+ # comparison must still reject this.+ start = datetime(2026, 1, 1, tzinfo=timezone.utc)+ end = start + timedelta(days=CREDIT_EXPORT_MAX_DAYS, seconds=1)+ with pytest.raises(ValueError, match="must be <="):+ await admin_export_user_history(start=start, end=end)++ @pytest.mark.asyncio+ async def test_returns_empty_for_no_rows(self):+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = AsyncMock(return_value=[])+ result = await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert result == []++ @pytest.mark.asyncio+ async def test_maps_basic_row(self):+ tx = _make_tx(metadata={"reason": "Initial grant"})+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = AsyncMock(return_value=[tx])+ result = await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert len(result) == 1+ assert result[0].user_id == "u1"+ assert result[0].user_email == "[email protected]"+ assert result[0].amount == 100+ assert result[0].running_balance == 1000+ assert result[0].reason == "Initial grant"+ assert result[0].admin_email == ""++ @pytest.mark.asyncio+ async def test_unwraps_nested_reason_from_top_up_credits_metadata(self):+ # _top_up_credits writes reason as {"reason": "..."} — the export+ # must flatten this for the CSV column.+ tx = _make_tx(+ tx_type=CreditTransactionType.TOP_UP,+ metadata={"reason": {"reason": "Auto top up"}},+ )+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = AsyncMock(return_value=[tx])+ result = await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert result[0].reason == "Auto top up"++ @pytest.mark.asyncio+ async def test_resolves_admin_email_once_per_unique_admin(self):+ # Two rows from same admin → email lookup hits cache on second.+ tx_a = _make_tx(user_id="u1", metadata={"admin_id": "admin-1"})+ tx_b = _make_tx(user_id="u2", metadata={"admin_id": "admin-1"})+ email_lookup = AsyncMock(return_value="[email protected]")+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ email_lookup,+ ):+ ct.prisma.return_value.find_many = AsyncMock(return_value=[tx_a, tx_b])+ result = await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert email_lookup.call_count == 1+ assert all(r.admin_email == "[email protected]" for r in result)++ @pytest.mark.asyncio+ async def test_admin_email_empty_when_lookup_misses(self):+ # When get_user_email_by_id returns None, admin_email is "" not "Unknown+ # Admin: <uuid>" so the column doesn't mix email + UUID formats.+ tx = _make_tx(metadata={"admin_id": "deleted-admin"})+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ AsyncMock(return_value=None),+ ):+ ct.prisma.return_value.find_many = AsyncMock(return_value=[tx])+ result = await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert result[0].admin_email == ""++ @pytest.mark.asyncio+ async def test_passes_filters_to_prisma_where_clause(self):+ find_many = AsyncMock(return_value=[])+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = find_many+ await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ transaction_type=CreditTransactionType.TOP_UP,+ user_id="u1",+ )+ where = find_many.call_args.kwargs["where"]+ assert where["type"] == CreditTransactionType.TOP_UP+ assert where["userId"] == "u1"+ assert "createdAt" in where+ # take must be cap+1 to detect over-cap rowsets without a separate count.+ assert find_many.call_args.kwargs["take"] == CREDIT_EXPORT_MAX_ROWS + 1++ @pytest.mark.asyncio+ async def test_filters_inactive_rows_by_default(self):+ find_many = AsyncMock(return_value=[])+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = find_many+ await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert find_many.call_args.kwargs["where"]["isActive"] is True++ @pytest.mark.asyncio+ async def test_include_inactive_drops_isactive_filter(self):+ find_many = AsyncMock(return_value=[])+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = find_many+ await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ include_inactive=True,+ )+ assert "isActive" not in find_many.call_args.kwargs["where"]++ @pytest.mark.asyncio+ async def test_rejects_when_fetched_rowset_exceeds_cap(self):+ oversize = [_make_tx() for _ in range(CREDIT_EXPORT_MAX_ROWS + 1)]+ with patch("backend.data.credit.CreditTransaction") as ct, patch(+ "backend.data.credit.get_user_email_by_id",+ new_callable=AsyncMock,+ ):+ ct.prisma.return_value.find_many = AsyncMock(return_value=oversize)+ with pytest.raises(ValueError, match="more than"):+ await admin_export_user_history(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+++class TestGetCopilotWeeklyUsageForExport:+ @pytest.mark.asyncio+ async def test_rejects_inverted_window(self):+ with pytest.raises(ValueError, match="end must be >= start"):+ await get_copilot_weekly_usage_for_export(+ start=datetime(2026, 4, 30, tzinfo=timezone.utc),+ end=datetime(2026, 4, 1, tzinfo=timezone.utc),+ )++ @pytest.mark.asyncio+ async def test_rejects_window_exceeding_cap_by_subday_remainder(self):+ start = datetime(2026, 1, 1, tzinfo=timezone.utc)+ end = start + timedelta(days=COPILOT_USAGE_EXPORT_MAX_DAYS, hours=2)+ with pytest.raises(ValueError, match="must be <="):+ await get_copilot_weekly_usage_for_export(start=start, end=end)++ @pytest.mark.asyncio+ async def test_empty_result_when_no_copilot_usage(self):+ with patch(+ "backend.data.platform_cost.query_raw_with_schema",+ new_callable=AsyncMock,+ return_value=[],+ ):+ result = await get_copilot_weekly_usage_for_export(+ start=datetime(2026, 4, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert result == []++ @pytest.mark.asyncio+ async def test_computes_inclusive_week_end_and_percent_used(self):+ rows = [+ {+ "user_id": "u1",+ "user_email": "[email protected]",+ "tier": "PRO",+ "week_start": datetime(2026, 3, 30, tzinfo=timezone.utc),+ "cost_microdollars": 5_000_000,+ }+ ]+ with patch(+ "backend.data.platform_cost.query_raw_with_schema",+ new_callable=AsyncMock,+ return_value=rows,+ ), patch(+ "backend.copilot.rate_limit.get_tier_multipliers",+ new_callable=AsyncMock,+ return_value={"PRO": 5.0, "BETA": 1.0, "NO_TIER": 0.0},+ ):+ result = await get_copilot_weekly_usage_for_export(+ start=datetime(2026, 3, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert len(result) == 1+ row = result[0]+ assert row.user_id == "u1"+ assert row.tier == "PRO"+ # week_end is inclusive end-of-Sunday, NOT next Monday.+ assert row.week_end == datetime(+ 2026, 4, 5, 23, 59, 59, 999999, tzinfo=timezone.utc+ )+ assert row.copilot_cost_microdollars == 5_000_000++ @pytest.mark.asyncio+ async def test_no_tier_user_gets_zero_percent(self):+ rows = [+ {+ "user_id": "u1",+ "user_email": "[email protected]",+ "tier": "NO_TIER",+ "week_start": datetime(2026, 3, 30, tzinfo=timezone.utc),+ "cost_microdollars": 1_000_000,+ }+ ]+ with patch(+ "backend.data.platform_cost.query_raw_with_schema",+ new_callable=AsyncMock,+ return_value=rows,+ ), patch(+ "backend.copilot.rate_limit.get_tier_multipliers",+ new_callable=AsyncMock,+ return_value={"PRO": 5.0, "BETA": 1.0, "NO_TIER": 0.0},+ ):+ result = await get_copilot_weekly_usage_for_export(+ start=datetime(2026, 3, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert result[0].weekly_limit_microdollars == 0+ assert result[0].percent_used == 0.0++ @pytest.mark.asyncio+ async def test_unknown_tier_falls_back_to_default(self):+ rows = [+ {+ "user_id": "u1",+ "user_email": "[email protected]",+ "tier": "MARS", # not a real SubscriptionTier value+ "week_start": datetime(2026, 3, 30, tzinfo=timezone.utc),+ "cost_microdollars": 100_000,+ }+ ]+ with patch(+ "backend.data.platform_cost.query_raw_with_schema",+ new_callable=AsyncMock,+ return_value=rows,+ ), patch(+ "backend.copilot.rate_limit.get_tier_multipliers",+ new_callable=AsyncMock,+ return_value={"PRO": 5.0, "BETA": 1.0, "NO_TIER": 0.0},+ ):+ result = await get_copilot_weekly_usage_for_export(+ start=datetime(2026, 3, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ # Falls back to DEFAULT_TIER (NO_TIER)+ assert result[0].tier == "NO_TIER"++ @pytest.mark.asyncio+ async def test_naive_week_start_gets_utc_tzinfo(self):+ rows = [+ {+ "user_id": "u1",+ "user_email": "[email protected]",+ "tier": "PRO",+ "week_start": datetime(2026, 3, 30), # naive+ "cost_microdollars": 1,+ }+ ]+ with patch(+ "backend.data.platform_cost.query_raw_with_schema",+ new_callable=AsyncMock,+ return_value=rows,+ ), patch(+ "backend.copilot.rate_limit.get_tier_multipliers",+ new_callable=AsyncMock,+ return_value={"PRO": 5.0},+ ):+ result = await get_copilot_weekly_usage_for_export(+ start=datetime(2026, 3, 1, tzinfo=timezone.utc),+ end=datetime(2026, 4, 30, tzinfo=timezone.utc),+ )+ assert result[0].week_start.tzinfo == timezone.utcdiff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/ExportCopilotUsageButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/ExportCopilotUsageButton.test.tsxnew file mode 100644index 0000000000..4c5d747a8a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/ExportCopilotUsageButton.test.tsx@@ -0,0 +1,151 @@+import {+ render,+ screen,+ fireEvent,+ waitFor,+ cleanup,+} from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { ExportCopilotUsageButton } from "../components/ExportCopilotUsageButton";++const toastSpy = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast: toastSpy }),+}));++const exportSpy = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({+ getV2ExportCopilotWeeklyUsageVsRateLimit: (+ ...args: Parameters<typeof exportSpy>+ ): ReturnType<typeof exportSpy> => exportSpy(...args),+}));++beforeEach(() => {+ toastSpy.mockReset();+ exportSpy.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("ExportCopilotUsageButton", () => {+ test("renders the trigger button", () => {+ render(<ExportCopilotUsageButton />);+ expect(+ screen.getByRole("button", { name: /Copilot Usage CSV/i }),+ ).toBeDefined();+ });++ test("opens a dialog with date inputs when clicked", async () => {+ render(<ExportCopilotUsageButton />);+ fireEvent.click(screen.getByRole("button", { name: /Copilot Usage CSV/i }));+ await waitFor(() => {+ expect(screen.getByLabelText(/Start date/i)).toBeDefined();+ expect(screen.getByLabelText(/End date/i)).toBeDefined();+ });+ });++ test("triggers a CSV download on success", async () => {+ exportSpy.mockResolvedValue({+ status: 200,+ data: {+ rows: [+ {+ user_id: "u1",+ user_email: "[email protected]",+ week_start: "2026-03-30T00:00:00Z",+ week_end: "2026-04-05T23:59:59.999Z",+ copilot_cost_microdollars: 1_500_000,+ tier: "PRO",+ weekly_limit_microdollars: 25_000_000,+ percent_used: 6.0,+ },+ ],+ total_rows: 1,+ window_days: 30,+ max_window_days: 90,+ },+ });+ const createUrl = vi+ .spyOn(URL, "createObjectURL")+ .mockReturnValue("blob:mock");+ const revokeUrl = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => {});+ const click = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(() => {});++ render(<ExportCopilotUsageButton />);+ fireEvent.click(screen.getByRole("button", { name: /Copilot Usage CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));++ await waitFor(() => expect(click).toHaveBeenCalledTimes(1));+ expect(createUrl).toHaveBeenCalledTimes(1);+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Export ready" }),+ );++ createUrl.mockRestore();+ revokeUrl.mockRestore();+ click.mockRestore();+ });++ test("surfaces 400 detail as a toast when the window is too large", async () => {+ exportSpy.mockRejectedValue(+ new ApiError("Export window must be <= 90 days (got 200.00 days)", 400, {+ detail: "Export window must be <= 90 days (got 200.00 days)",+ }),+ );+ render(<ExportCopilotUsageButton />);+ fireEvent.click(screen.getByRole("button", { name: /Copilot Usage CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));+ await waitFor(() => expect(exportSpy).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Window too large",+ variant: "destructive",+ }),+ ),+ );+ });++ test("falls back to a generic toast when the API throws a non-ApiError", async () => {+ exportSpy.mockRejectedValue(new Error("network blip"));+ render(<ExportCopilotUsageButton />);+ fireEvent.click(screen.getByRole("button", { name: /Copilot Usage CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));+ await waitFor(() => expect(exportSpy).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Export failed",+ description: "network blip",+ variant: "destructive",+ }),+ ),+ );+ });++ test("warns when the response is missing the expected success shape", async () => {+ exportSpy.mockResolvedValue({ status: 204, data: null });+ render(<ExportCopilotUsageButton />);+ fireEvent.click(screen.getByRole("button", { name: /Copilot Usage CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));+ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Export failed",+ variant: "destructive",+ }),+ ),+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/ExportCreditTransactionsButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/ExportCreditTransactionsButton.test.tsxnew file mode 100644index 0000000000..7271840635--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/ExportCreditTransactionsButton.test.tsx@@ -0,0 +1,154 @@+import {+ render,+ screen,+ fireEvent,+ waitFor,+ cleanup,+} from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { ExportCreditTransactionsButton } from "../components/ExportCreditTransactionsButton";++const toastSpy = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ useToast: () => ({ toast: toastSpy }),+}));++const exportSpy = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({+ getV2ExportCreditTransactions: (+ ...args: Parameters<typeof exportSpy>+ ): ReturnType<typeof exportSpy> => exportSpy(...args),+}));++beforeEach(() => {+ toastSpy.mockReset();+ exportSpy.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("ExportCreditTransactionsButton", () => {+ test("renders the trigger button", () => {+ render(<ExportCreditTransactionsButton />);+ expect(screen.getByRole("button", { name: /Export CSV/i })).toBeDefined();+ });++ test("opens a dialog with date inputs and a type filter when clicked", async () => {+ render(<ExportCreditTransactionsButton />);+ fireEvent.click(screen.getByRole("button", { name: /Export CSV/i }));+ await waitFor(() => {+ expect(screen.getByLabelText(/Start date/i)).toBeDefined();+ expect(screen.getByLabelText(/End date/i)).toBeDefined();+ expect(screen.getByLabelText(/User ID/i)).toBeDefined();+ });+ });++ test("surfaces a 400 detail in the toast when the API rejects the window", async () => {+ exportSpy.mockRejectedValue(+ new ApiError("Export window must be <= 90 days (got 200.00 days)", 400, {+ detail: "Export window must be <= 90 days (got 200.00 days)",+ }),+ );+ render(<ExportCreditTransactionsButton />);+ fireEvent.click(screen.getByRole("button", { name: /Export CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));+ await waitFor(() => expect(exportSpy).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Window too large",+ variant: "destructive",+ }),+ ),+ );+ });++ test("triggers a CSV download on success", async () => {+ exportSpy.mockResolvedValue({+ status: 200,+ data: {+ transactions: [+ {+ transaction_key: "tx-1",+ user_id: "u1",+ user_email: "[email protected]",+ transaction_time: "2026-04-01T00:00:00Z",+ transaction_type: "GRANT",+ amount: 1000,+ running_balance: 5000,+ current_balance: 5000,+ reason: "Initial grant",+ admin_email: "[email protected]",+ },+ ],+ total_rows: 1,+ window_days: 30,+ max_window_days: 90,+ },+ });+ const createUrl = vi+ .spyOn(URL, "createObjectURL")+ .mockReturnValue("blob:mock");+ const revokeUrl = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => {});+ const click = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(() => {});++ render(<ExportCreditTransactionsButton />);+ fireEvent.click(screen.getByRole("button", { name: /Export CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));++ await waitFor(() => expect(click).toHaveBeenCalledTimes(1));+ expect(createUrl).toHaveBeenCalledTimes(1);+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Export ready" }),+ );++ createUrl.mockRestore();+ revokeUrl.mockRestore();+ click.mockRestore();+ });++ test("falls back to a generic toast when the API throws a non-ApiError", async () => {+ exportSpy.mockRejectedValue(new Error("network blip"));+ render(<ExportCreditTransactionsButton />);+ fireEvent.click(screen.getByRole("button", { name: /Export CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));+ await waitFor(() => expect(exportSpy).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Export failed",+ description: "network blip",+ variant: "destructive",+ }),+ ),+ );+ });++ test("warns when the response is missing the expected success shape", async () => {+ // Simulate an unexpected non-200 that didn't throw — okData() returns+ // undefined and the operator should see a clear error instead of a crash.+ exportSpy.mockResolvedValue({ status: 204, data: null });+ render(<ExportCreditTransactionsButton />);+ fireEvent.click(screen.getByRole("button", { name: /Export CSV/i }));+ await waitFor(() => screen.getByLabelText(/Start date/i));+ fireEvent.click(screen.getByRole("button", { name: /Download CSV/i }));+ await waitFor(() =>+ expect(toastSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Export failed",+ variant: "destructive",+ }),+ ),+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/helpers.test.tsnew file mode 100644index 0000000000..4d8fd3281c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/__tests__/helpers.test.ts@@ -0,0 +1,203 @@+import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";+import type { CopilotWeeklyUsageRow } from "@/app/api/__generated__/models/copilotWeeklyUsageRow";+import type { UserTransaction } from "@/app/api/__generated__/models/userTransaction";++import {+ buildCopilotUsageCsv,+ buildCreditTransactionsCsv,+ dateInputToUtcIso,+ dateInputToUtcIsoEnd,+ defaultEndDate,+ defaultStartDate,+ downloadCsv,+} from "../helpers";++function makeTx(overrides: Partial<UserTransaction> = {}): UserTransaction {+ return {+ transaction_key: "tx-1",+ transaction_time: "2026-04-01T10:00:00Z",+ transaction_type: "TOP_UP",+ amount: 5000,+ running_balance: 12500,+ current_balance: 12500,+ user_id: "user-1",+ user_email: "[email protected]",+ reason: "Stripe checkout",+ admin_email: null,+ ...overrides,+ } as UserTransaction;+}++function makeUsage(+ overrides: Partial<CopilotWeeklyUsageRow> = {},+): CopilotWeeklyUsageRow {+ return {+ user_id: "user-1",+ user_email: "[email protected]",+ week_start: "2026-03-30T00:00:00Z",+ week_end: "2026-04-05T23:59:59.999Z",+ copilot_cost_microdollars: 1_500_000,+ tier: "PRO",+ weekly_limit_microdollars: 25_000_000,+ percent_used: 6.0,+ ...overrides,+ } as CopilotWeeklyUsageRow;+}++describe("buildCreditTransactionsCsv", () => {+ test("emits header followed by one CRLF-terminated row per transaction", () => {+ const csv = buildCreditTransactionsCsv([makeTx()]);+ const lines = csv.split("\r\n");+ expect(lines).toHaveLength(2);+ expect(lines[0]).toBe(+ [+ '"transaction_id"',+ '"user_id"',+ '"user_email"',+ '"created_at"',+ '"type"',+ '"amount_usd"',+ '"running_balance_usd"',+ '"admin_email"',+ '"reason"',+ ].join(","),+ );+ });++ test("converts cents to USD with two decimals", () => {+ const csv = buildCreditTransactionsCsv([+ makeTx({ amount: 12345, running_balance: -678 }),+ ]);+ const row = csv.split("\r\n")[1];+ expect(row).toContain('"123.45"');+ expect(row).toContain('"-6.78"');+ });++ test("escapes embedded quotes by doubling them", () => {+ const csv = buildCreditTransactionsCsv([+ makeTx({ reason: 'has "quotes" inside' }),+ ]);+ expect(csv).toContain('"has ""quotes"" inside"');+ });++ test("emits empty string for null fields without breaking row shape", () => {+ const csv = buildCreditTransactionsCsv([+ makeTx({ user_email: null, admin_email: null, reason: null }),+ ]);+ const row = csv.split("\r\n")[1];+ expect(row.split(",")).toHaveLength(9);+ expect(row).toContain('""');+ });++ test("renders each transaction as its own row", () => {+ const csv = buildCreditTransactionsCsv([+ makeTx({ transaction_key: "tx-a" }),+ makeTx({ transaction_key: "tx-b" }),+ ]);+ expect(csv.split("\r\n")).toHaveLength(3);+ });+});++describe("buildCopilotUsageCsv", () => {+ test("converts microdollars to USD (6dp for cost, 2dp for limit)", () => {+ const csv = buildCopilotUsageCsv([+ makeUsage({+ copilot_cost_microdollars: 2_500_000,+ weekly_limit_microdollars: 25_000_000,+ }),+ ]);+ const row = csv.split("\r\n")[1];+ expect(row).toContain('"2.500000"');+ expect(row).toContain('"25.00"');+ });++ test("formats percent_used with two decimal places", () => {+ const csv = buildCopilotUsageCsv([makeUsage({ percent_used: 33.7 })]);+ expect(csv.split("\r\n")[1]).toContain('"33.70"');+ });++ test("emits the expected header row", () => {+ const csv = buildCopilotUsageCsv([]);+ expect(csv).toBe(+ [+ '"user_id"',+ '"user_email"',+ '"week_start"',+ '"week_end"',+ '"copilot_cost_usd"',+ '"tier"',+ '"weekly_limit_usd"',+ '"percent_used"',+ ].join(","),+ );+ });+});++describe("dateInputToUtcIso / dateInputToUtcIsoEnd", () => {+ test("returns null for an empty string", () => {+ expect(dateInputToUtcIso("")).toBeNull();+ expect(dateInputToUtcIsoEnd("")).toBeNull();+ });++ test("anchors start to UTC midnight of the input date", () => {+ expect(dateInputToUtcIso("2026-03-15")).toBe("2026-03-15T00:00:00.000Z");+ });++ test("anchors end to UTC end-of-day so the inclusive filter covers the day", () => {+ expect(dateInputToUtcIsoEnd("2026-03-15")).toBe("2026-03-15T23:59:59.999Z");+ });+});++describe("defaultStartDate / defaultEndDate", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ test("defaultStartDate returns 30 UTC days before now", () => {+ vi.setSystemTime(new Date("2026-04-30T12:34:56Z"));+ expect(defaultStartDate()).toBe("2026-03-31");+ });++ test("defaultEndDate returns today's UTC date string", () => {+ vi.setSystemTime(new Date("2026-04-30T23:59:00Z"));+ expect(defaultEndDate()).toBe("2026-04-30");+ });++ test("UTC arithmetic — late-night-PST viewer still gets correct UTC date", () => {+ // 2026-04-30 23:30 PST ⇒ 2026-05-01 06:30 UTC+ vi.setSystemTime(new Date("2026-05-01T06:30:00Z"));+ expect(defaultEndDate()).toBe("2026-05-01");+ expect(defaultStartDate()).toBe("2026-04-01");+ });+});++describe("downloadCsv", () => {+ test("clicks an anchor and defers URL.revokeObjectURL via setTimeout", () => {+ const createUrl = vi+ .spyOn(URL, "createObjectURL")+ .mockReturnValue("blob:mock");+ const revokeUrl = vi+ .spyOn(URL, "revokeObjectURL")+ .mockImplementation(() => {});+ const anchorClick = vi+ .spyOn(HTMLAnchorElement.prototype, "click")+ .mockImplementation(() => {});++ vi.useFakeTimers();+ downloadCsv("col1\r\nval1", "out.csv");+ expect(createUrl).toHaveBeenCalledTimes(1);+ expect(anchorClick).toHaveBeenCalledTimes(1);+ // revoke is deferred via setTimeout so the download stream gets to start+ expect(revokeUrl).not.toHaveBeenCalled();+ vi.runAllTimers();+ expect(revokeUrl).toHaveBeenCalledWith("blob:mock");++ createUrl.mockRestore();+ revokeUrl.mockRestore();+ anchorClick.mockRestore();+ vi.useRealTimers();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/ExportCopilotUsageButton.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/ExportCopilotUsageButton.tsxnew file mode 100644index 0000000000..07f93f13f8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/ExportCopilotUsageButton.tsx@@ -0,0 +1,169 @@+"use client";++import { useEffect, useState } from "react";+import { ChartLineIcon } from "@phosphor-icons/react";+import { Button } from "@/components/atoms/Button/Button";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { getV2ExportCopilotWeeklyUsageVsRateLimit } from "@/app/api/__generated__/endpoints/admin/admin";+import { okData } from "@/app/api/helpers";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import {+ buildCopilotUsageCsv,+ dateInputToUtcIso,+ dateInputToUtcIsoEnd,+ defaultEndDate,+ defaultStartDate,+ downloadCsv,+} from "../helpers";++export function ExportCopilotUsageButton() {+ const { toast } = useToast();+ const [open, setOpen] = useState(false);+ const [start, setStart] = useState(defaultStartDate);+ const [end, setEnd] = useState(defaultEndDate);+ const [exporting, setExporting] = useState(false);++ // Refresh the default window each time the dialog opens — the lazy useState+ // initializer only runs once on mount, so without this the dates would+ // freeze at component-mount time and drift on a long-lived page.+ useEffect(() => {+ if (open) {+ setStart(defaultStartDate());+ setEnd(defaultEndDate());+ }+ }, [open]);++ async function handleExport() {+ if (!start || !end) {+ toast({+ title: "Pick a date range",+ description: "Both start and end dates are required.",+ variant: "destructive",+ });+ return;+ }+ setExporting(true);+ try {+ const startIso = dateInputToUtcIso(start);+ const endIso = dateInputToUtcIsoEnd(end);+ if (!startIso || !endIso) return;+ // Pass ISO strings as-is — orval calls .toString() on Date params, which+ // produces a localised string FastAPI rejects (422). Strings round-trip.+ const response = await getV2ExportCopilotWeeklyUsageVsRateLimit({+ start: startIso as unknown as Date,+ end: endIso as unknown as Date,+ });+ const data = okData(response);+ if (!data) {+ toast({+ title: "Export failed",+ description: "Unexpected response shape from the export endpoint.",+ variant: "destructive",+ });+ return;+ }+ const csv = buildCopilotUsageCsv(data.rows);+ downloadCsv(csv, `copilot_weekly_usage_${start}_${end}.csv`);+ toast({+ title: "Export ready",+ description: `${data.total_rows} (user, week) rows downloaded.`,+ });+ setOpen(false);+ } catch (err) {+ // customMutator throws ApiError on non-2xx. Surface backend cap-exceed+ // detail (400) so the operator can narrow their range without a refresh.+ if (err instanceof ApiError) {+ const detail =+ (err.response as { detail?: string } | undefined)?.detail ??+ err.message;+ toast({+ title: err.status === 400 ? "Window too large" : "Export failed",+ description: detail,+ variant: "destructive",+ });+ } else {+ toast({+ title: "Export failed",+ description: err instanceof Error ? err.message : "Unknown error",+ variant: "destructive",+ });+ }+ } finally {+ setExporting(false);+ }+ }++ return (+ <Dialog+ title="Export copilot weekly usage"+ styling={{ maxWidth: "30rem" }}+ controlled={{ isOpen: open, set: setOpen }}+ >+ <Dialog.Trigger>+ <Button+ variant="secondary"+ size="small"+ leftIcon={<ChartLineIcon weight="bold" />}+ >+ Copilot Usage CSV+ </Button>+ </Dialog.Trigger>+ <Dialog.Content>+ <div className="flex flex-col gap-4">+ <p className="text-sm text-muted-foreground">+ Aggregates copilot:* spend by user and ISO week and joins each row+ against the user's tier-derived weekly limit.+ </p>+ <div className="flex gap-3">+ <div className="flex flex-1 flex-col gap-1">+ <label htmlFor="copilot-export-start" className="text-sm">+ Start date (UTC)+ </label>+ <input+ id="copilot-export-start"+ type="date"+ className="rounded border px-3 py-1.5 text-sm"+ value={start}+ onChange={(e) => setStart(e.target.value)}+ />+ </div>+ <div className="flex flex-1 flex-col gap-1">+ <label htmlFor="copilot-export-end" className="text-sm">+ End date (UTC)+ </label>+ <input+ id="copilot-export-end"+ type="date"+ className="rounded border px-3 py-1.5 text-sm"+ value={end}+ onChange={(e) => setEnd(e.target.value)}+ />+ </div>+ </div>+ <p className="text-xs text-muted-foreground">+ Window is capped at 90 days and 100k rows.+ </p>+ </div>+ <Dialog.Footer>+ <Button+ variant="secondary"+ size="small"+ onClick={() => setOpen(false)}+ disabled={exporting}+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ size="small"+ onClick={handleExport}+ loading={exporting}+ >+ Download CSV+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/ExportCreditTransactionsButton.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/ExportCreditTransactionsButton.tsxnew file mode 100644index 0000000000..8c97cad04c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/ExportCreditTransactionsButton.tsx@@ -0,0 +1,226 @@+"use client";++import { useEffect, useState } from "react";+import { DownloadSimpleIcon } from "@phosphor-icons/react";+import { Button } from "@/components/atoms/Button/Button";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/__legacy__/ui/select";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { getV2ExportCreditTransactions } from "@/app/api/__generated__/endpoints/admin/admin";+import { okData } from "@/app/api/helpers";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { CreditTransactionType } from "@/app/api/__generated__/models/creditTransactionType";+import {+ buildCreditTransactionsCsv,+ dateInputToUtcIso,+ dateInputToUtcIsoEnd,+ defaultEndDate,+ defaultStartDate,+ downloadCsv,+} from "../helpers";++type TypeFilter = "ALL" | CreditTransactionType;++const TYPE_OPTIONS: { value: TypeFilter; label: string }[] = [+ { value: "ALL", label: "All types" },+ { value: CreditTransactionType.TOP_UP, label: "Top up" },+ { value: CreditTransactionType.USAGE, label: "Usage" },+ { value: CreditTransactionType.GRANT, label: "Grant" },+ { value: CreditTransactionType.REFUND, label: "Refund" },+ { value: CreditTransactionType.CARD_CHECK, label: "Card check" },+ { value: CreditTransactionType.SUBSCRIPTION, label: "Subscription" },+];++export function ExportCreditTransactionsButton() {+ const { toast } = useToast();+ const [open, setOpen] = useState(false);+ const [start, setStart] = useState(defaultStartDate);+ const [end, setEnd] = useState(defaultEndDate);+ const [typeFilter, setTypeFilter] = useState<TypeFilter>("ALL");+ const [userId, setUserId] = useState("");+ const [exporting, setExporting] = useState(false);++ // Refresh the default window each time the dialog opens — the lazy useState+ // initializer only runs once on mount, so without this the dates would+ // freeze at component-mount time and drift on a long-lived page.+ useEffect(() => {+ if (open) {+ setStart(defaultStartDate());+ setEnd(defaultEndDate());+ }+ }, [open]);++ async function handleExport() {+ if (!start || !end) {+ toast({+ title: "Pick a date range",+ description: "Both start and end dates are required.",+ variant: "destructive",+ });+ return;+ }+ setExporting(true);+ try {+ const startIso = dateInputToUtcIso(start);+ const endIso = dateInputToUtcIsoEnd(end);+ if (!startIso || !endIso) return;+ // Pass ISO strings as-is — orval calls .toString() on Date params, which+ // produces a localised string FastAPI rejects (422). Strings round-trip.+ const response = await getV2ExportCreditTransactions({+ start: startIso as unknown as Date,+ end: endIso as unknown as Date,+ transaction_type:+ typeFilter === "ALL"+ ? undefined+ : (typeFilter as CreditTransactionType),+ user_id: userId.trim() || undefined,+ });+ const data = okData(response);+ if (!data) {+ toast({+ title: "Export failed",+ description: "Unexpected response shape from the export endpoint.",+ variant: "destructive",+ });+ return;+ }+ const csv = buildCreditTransactionsCsv(data.transactions);+ downloadCsv(csv, `credit_transactions_${start}_${end}.csv`);+ toast({+ title: "Export ready",+ description: `${data.total_rows} transactions downloaded.`,+ });+ setOpen(false);+ } catch (err) {+ // customMutator throws ApiError on non-2xx. Surface backend cap-exceed+ // detail (400) so the operator can narrow their range without a refresh.+ if (err instanceof ApiError) {+ const detail =+ (err.response as { detail?: string } | undefined)?.detail ??+ err.message;+ toast({+ title: err.status === 400 ? "Window too large" : "Export failed",+ description: detail,+ variant: "destructive",+ });+ } else {+ toast({+ title: "Export failed",+ description: err instanceof Error ? err.message : "Unknown error",+ variant: "destructive",+ });+ }+ } finally {+ setExporting(false);+ }+ }++ return (+ <Dialog+ title="Export credit transactions"+ styling={{ maxWidth: "30rem" }}+ controlled={{ isOpen: open, set: setOpen }}+ >+ <Dialog.Trigger>+ <Button+ variant="secondary"+ size="small"+ leftIcon={<DownloadSimpleIcon weight="bold" />}+ >+ Export CSV+ </Button>+ </Dialog.Trigger>+ <Dialog.Content>+ <div className="flex flex-col gap-4">+ <div className="flex gap-3">+ <div className="flex flex-1 flex-col gap-1">+ <label htmlFor="credit-export-start" className="text-sm">+ Start date (UTC)+ </label>+ <input+ id="credit-export-start"+ type="date"+ className="rounded border px-3 py-1.5 text-sm"+ value={start}+ onChange={(e) => setStart(e.target.value)}+ />+ </div>+ <div className="flex flex-1 flex-col gap-1">+ <label htmlFor="credit-export-end" className="text-sm">+ End date (UTC)+ </label>+ <input+ id="credit-export-end"+ type="date"+ className="rounded border px-3 py-1.5 text-sm"+ value={end}+ onChange={(e) => setEnd(e.target.value)}+ />+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-sm" htmlFor="credit-export-type">+ Transaction type+ </label>+ <Select+ value={typeFilter}+ onValueChange={(v) => setTypeFilter(v as TypeFilter)}+ >+ <SelectTrigger id="credit-export-type" className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {TYPE_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex flex-col gap-1">+ <label className="text-sm" htmlFor="credit-export-user-id">+ User ID (optional)+ </label>+ <input+ id="credit-export-user-id"+ type="text"+ placeholder="Filter by a single user ID"+ className="rounded border px-3 py-1.5 text-sm"+ value={userId}+ onChange={(e) => setUserId(e.target.value)}+ />+ </div>+ <p className="text-xs text-muted-foreground">+ Window is capped at 90 days and 100k rows. Narrow the range if the+ backend returns a 400.+ </p>+ </div>+ <Dialog.Footer>+ <Button+ variant="secondary"+ size="small"+ onClick={() => setOpen(false)}+ disabled={exporting}+ >+ Cancel+ </Button>+ <Button+ variant="primary"+ size="small"+ onClick={handleExport}+ loading={exporting}+ >+ Download CSV+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/spending/helpers.tsnew file mode 100644index 0000000000..92c7b03e04--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/helpers.ts@@ -0,0 +1,114 @@+import type { CopilotWeeklyUsageRow } from "@/app/api/__generated__/models/copilotWeeklyUsageRow";+import type { UserTransaction } from "@/app/api/__generated__/models/userTransaction";++const MICRODOLLARS_PER_USD = 1_000_000;+const CREDIT_CENTS_PER_USD = 100;++function csvEscape(val: unknown): string {+ const s = val == null ? "" : String(val);+ return `"${s.replace(/"/g, '""')}"`;+}++const CREDIT_CSV_HEADERS = [+ "transaction_id",+ "user_id",+ "user_email",+ "created_at",+ "type",+ "amount_usd",+ "running_balance_usd",+ "admin_email",+ "reason",+];++export function buildCreditTransactionsCsv(rows: UserTransaction[]): string {+ const header = CREDIT_CSV_HEADERS.map(csvEscape).join(",");+ const body = rows.map((tx) =>+ [+ tx.transaction_key,+ tx.user_id,+ tx.user_email,+ tx.transaction_time,+ tx.transaction_type,+ ((tx.amount ?? 0) / CREDIT_CENTS_PER_USD).toFixed(2),+ ((tx.running_balance ?? 0) / CREDIT_CENTS_PER_USD).toFixed(2),+ tx.admin_email,+ tx.reason,+ ]+ .map(csvEscape)+ .join(","),+ );+ return [header, ...body].join("\r\n");+}++const COPILOT_CSV_HEADERS = [+ "user_id",+ "user_email",+ "week_start",+ "week_end",+ "copilot_cost_usd",+ "tier",+ "weekly_limit_usd",+ "percent_used",+];++export function buildCopilotUsageCsv(rows: CopilotWeeklyUsageRow[]): string {+ const header = COPILOT_CSV_HEADERS.map(csvEscape).join(",");+ const body = rows.map((row) =>+ [+ row.user_id,+ row.user_email,+ row.week_start,+ row.week_end,+ (row.copilot_cost_microdollars / MICRODOLLARS_PER_USD).toFixed(6),+ row.tier,+ (row.weekly_limit_microdollars / MICRODOLLARS_PER_USD).toFixed(2),+ row.percent_used.toFixed(2),+ ]+ .map(csvEscape)+ .join(","),+ );+ return [header, ...body].join("\r\n");+}++export function downloadCsv(csv: string, filename: string): void {+ const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = filename;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ // Defer revoke so the browser has time to start the download stream —+ // some browsers (older Firefox/Edge, mobile WebViews) cancel the download+ // if the object URL is revoked synchronously after click().+ setTimeout(() => URL.revokeObjectURL(url), 0);+}++// "YYYY-MM-DD" -> ISO 8601 UTC string. The orval URL builder calls .toString()+// on params, which on a Date produces a localised string FastAPI rejects (422);+// returning a string keeps .toString() a no-op and the ISO format intact.+export function dateInputToUtcIso(input: string): string | null {+ if (!input) return null;+ return new Date(`${input}T00:00:00Z`).toISOString();+}++// Same conversion but pinned to end-of-day so the inclusive `end` filter+// covers the entire selected day.+export function dateInputToUtcIsoEnd(input: string): string | null {+ if (!input) return null;+ return new Date(`${input}T23:59:59.999Z`).toISOString();+}++// Use UTC arithmetic so the default 30-day window matches the UI's UTC label+// regardless of the viewer's local timezone.+export function defaultStartDate(): string {+ const d = new Date();+ d.setUTCDate(d.getUTCDate() - 30);+ return d.toISOString().slice(0, 10);+}++export function defaultEndDate(): string {+ return new Date().toISOString().slice(0, 10);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/page.tsxindex 4b9d5a7eac..d24d4f03ff 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/spending/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/page.tsx@@ -2,6 +2,8 @@ import type { CreditTransactionType } from "@/lib/autogpt-server-api";import { withRoleAccess } from "@/lib/withRoleAccess";import { Suspense } from "react";import { AdminUserGrantHistory } from "./components/AdminUserGrantHistory";+import { ExportCopilotUsageButton } from "./components/ExportCopilotUsageButton";+import { ExportCreditTransactionsButton } from "./components/ExportCreditTransactionsButton";type SpendingDashboardPageSearchParams = {page?: string;@@ -26,6 +28,10 @@ function SpendingDashboard({<h1 className="text-3xl font-bold">User Spending</h1><p className="text-gray-500">Manage user spending balances</p></div>+ <div className="flex items-center gap-2">+ <ExportCreditTransactionsButton />+ <ExportCopilotUsageButton />+ </div></div><Suspensediff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 2996b73d65..3356b0af30 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -3065,6 +3065,163 @@"security": [{ "HTTPBearerJWT": [] }]}},+ "/api/credits/admin/copilot-usage/export": {+ "get": {+ "tags": ["v2", "admin", "credits", "admin"],+ "summary": "Export Copilot Weekly Usage vs Rate Limit",+ "description": "Export per-(user, ISO week) copilot spend with the user's tier limit.\n\nUses the same 90-day window cap and 100k row cap as the credit export.",+ "operationId": "getV2Export copilot weekly usage vs rate limit",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "start",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "description": "ISO timestamp (inclusive)",+ "title": "Start"+ },+ "description": "ISO timestamp (inclusive)"+ },+ {+ "name": "end",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "description": "ISO timestamp (inclusive)",+ "title": "End"+ },+ "description": "ISO timestamp (inclusive)"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CopilotUsageExportResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },+ "/api/credits/admin/transactions/export": {+ "get": {+ "tags": ["v2", "admin", "credits", "admin"],+ "summary": "Export Credit Transactions",+ "description": "Export CreditTransaction rows in [start, end] for finance reporting.\n\nCapped at CREDIT_EXPORT_MAX_DAYS days and CREDIT_EXPORT_MAX_ROWS rows;\nover-cap requests fail fast with 400 so callers narrow the window\ninstead of receiving silently truncated data.",+ "operationId": "getV2Export credit transactions",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "start",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "description": "ISO timestamp (inclusive)",+ "title": "Start"+ },+ "description": "ISO timestamp (inclusive)"+ },+ {+ "name": "end",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "description": "ISO timestamp (inclusive)",+ "title": "End"+ },+ "description": "ISO timestamp (inclusive)"+ },+ {+ "name": "transaction_type",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ { "$ref": "#/components/schemas/CreditTransactionType" },+ { "type": "null" }+ ],+ "title": "Transaction Type"+ }+ },+ {+ "name": "user_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "User Id"+ }+ },+ {+ "name": "include_inactive",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Include inactive rows (e.g. abandoned Stripe checkouts). Off by default so phantom rows aren't surfaced in normal exports.",+ "default": false,+ "title": "Include Inactive"+ },+ "description": "Include inactive rows (e.g. abandoned Stripe checkouts). Off by default so phantom rows aren't surfaced in normal exports."+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreditTransactionsExportResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/credits/admin/users_history": {"get": {"tags": ["v2", "admin", "credits", "admin"],@@ -10632,6 +10789,61 @@],"title": "ContentType"},+ "CopilotUsageExportResponse": {+ "properties": {+ "rows": {+ "items": { "$ref": "#/components/schemas/CopilotWeeklyUsageRow" },+ "type": "array",+ "title": "Rows"+ },+ "total_rows": { "type": "integer", "title": "Total Rows" },+ "window_days": { "type": "integer", "title": "Window Days" },+ "max_window_days": { "type": "integer", "title": "Max Window Days" }+ },+ "type": "object",+ "required": ["rows", "total_rows", "window_days", "max_window_days"],+ "title": "CopilotUsageExportResponse"+ },+ "CopilotWeeklyUsageRow": {+ "properties": {+ "user_id": { "type": "string", "title": "User Id" },+ "user_email": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "User Email"+ },+ "week_start": {+ "type": "string",+ "format": "date-time",+ "title": "Week Start"+ },+ "week_end": {+ "type": "string",+ "format": "date-time",+ "title": "Week End"+ },+ "copilot_cost_microdollars": {+ "type": "integer",+ "title": "Copilot Cost Microdollars"+ },+ "tier": { "type": "string", "title": "Tier" },+ "weekly_limit_microdollars": {+ "type": "integer",+ "title": "Weekly Limit Microdollars"+ },+ "percent_used": { "type": "number", "title": "Percent Used" }+ },+ "type": "object",+ "required": [+ "user_id",+ "week_start",+ "week_end",+ "copilot_cost_microdollars",+ "tier",+ "weekly_limit_microdollars",+ "percent_used"+ ],+ "title": "CopilotWeeklyUsageRow"+ },"CostBucket": {"properties": {"bucket": { "type": "string", "title": "Bucket" },@@ -10974,6 +11186,26 @@],"title": "CreditTransactionType"},+ "CreditTransactionsExportResponse": {+ "properties": {+ "transactions": {+ "items": { "$ref": "#/components/schemas/UserTransaction" },+ "type": "array",+ "title": "Transactions"+ },+ "total_rows": { "type": "integer", "title": "Total Rows" },+ "window_days": { "type": "integer", "title": "Window Days" },+ "max_window_days": { "type": "integer", "title": "Max Window Days" }+ },+ "type": "object",+ "required": [+ "transactions",+ "total_rows",+ "window_days",+ "max_window_days"+ ],+ "title": "CreditTransactionsExportResponse"+ },"DeleteFileResponse": {"properties": { "deleted": { "type": "boolean", "title": "Deleted" } },"type": "object",