Skip to content

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.

fix(platform): drop running balance from user transaction history (#13239)

Abhimanyu Yadav90564783d0b8
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index a49340d077..8a138dbf02 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -27,6 +27,7 @@ from backend.data.db import query_raw_with_schema
from backend.data.includes import MAX_CREDIT_REFUND_REQUESTS_FETCH
from backend.data.model import (
AutoTopUpConfig,
+ CreditTransactionItem,
RefundRequest,
TopUpType,
TransactionHistory,
@@ -903,10 +904,11 @@ class UserCredit(UserCreditBase):
logger.warning(
f"Adding extra info for dispute from {user_id} for ${amount / 100}"
)
- # Retrieve recent transaction history to support our evidence.
- # This provides a concise timeline that shows service usage and proper credit application.
- transaction_history = await self.get_transaction_history(
- user_id, transaction_count_limit=None
+ # Retrieve recent transaction rows directly from prisma to preserve
+ # per-row runningBalance in the dispute evidence narrative.
+ dispute_transactions = await CreditTransaction.prisma().find_many(
+ where={"userId": user_id, "isActive": True},
+ order={"createdAt": "desc"},
)
user = await get_user_by_id(user_id)
@@ -919,17 +921,19 @@ class UserCredit(UserCreditBase):
"were applied to the user’s account. Our records confirm that the funds were utilized for the intended services. "
"Below is a summary of recent transaction activity:\n"
)
- for tx in transaction_history.transactions:
- if tx.transaction_key == transaction.transactionKey:
+ for t in dispute_transactions:
+ if t.transactionKey == transaction.transactionKey:
additional_comment = (
" [This top-up transaction is the subject of the dispute]."
)
else:
additional_comment = ""
+ tx_time = t.createdAt.replace(tzinfo=timezone.utc)
+ running_balance = t.runningBalance or 0
evidence_text += (
- f"- {tx.description}: Amount ${tx.amount / 100:.2f} on {tx.transaction_time.isoformat()}, "
- f"resulting balance ${tx.running_balance / 100:.2f} {additional_comment}\n"
+ f"- {t.type} Transaction: Amount ${t.amount / 100:.2f} on {tx_time.isoformat()}, "
+ f"resulting balance ${running_balance / 100:.2f}{additional_comment}\n"
)
evidence_text += (
"\nThis evidence demonstrates that the transaction was authorized and that the charged amount was used to render the service as agreed."
@@ -1219,9 +1223,8 @@ class UserCredit(UserCreditBase):
take=transaction_count_limit,
)
- # doesn't fill current_balance, reason, user_email, admin_email, or extra_data
- grouped_transactions: dict[str, UserTransaction] = defaultdict(
- lambda: UserTransaction(user_id=user_id)
+ grouped_transactions: dict[str, CreditTransactionItem] = defaultdict(
+ lambda: CreditTransactionItem(user_id=user_id)
)
tx_time = None
for t in transactions:
@@ -1251,7 +1254,6 @@ class UserCredit(UserCreditBase):
if tx_time > gt.transaction_time:
gt.transaction_time = tx_time
- gt.running_balance = t.runningBalance or 0
return TransactionHistory(
transactions=list(grouped_transactions.values()),
diff --git a/autogpt_platform/backend/backend/data/credit_refund_test.py b/autogpt_platform/backend/backend/data/credit_refund_test.py
index c2f8b29714..3e24a7223b 100644
--- a/autogpt_platform/backend/backend/data/credit_refund_test.py
+++ b/autogpt_platform/backend/backend/data/credit_refund_test.py
@@ -220,11 +220,13 @@ async def test_handle_dispute_with_sufficient_balance(
async def test_handle_dispute_with_insufficient_balance(
mock_get_user, mock_stripe_modify, mock_settings, server: SpinTestServer
):
- """Test handling dispute when user has insufficient balance (evidence gets added)."""
- topup_tx = await setup_test_user_with_topup()
+ """Test handling dispute when user has insufficient balance (evidence gets added).
- # Save original method for restoration before any try blocks
- original_get_history = credit_system.get_transaction_history
+ handle_dispute reads CreditTransaction rows directly via prisma, so the
+ evidence-building path is exercised against the real DB state created by
+ setup_test_user_with_topup — this is an integration test by design.
+ """
+ topup_tx = await setup_test_user_with_topup()
try:
# Mock settings to have a high tolerance threshold so dispute isn't closed
@@ -235,13 +237,6 @@ async def test_handle_dispute_with_insufficient_balance(
mock_user.email = f"{REFUND_TEST_USER_ID}@example.com"
mock_get_user.return_value = mock_user
- # Mock the transaction history method to return an async result
- from unittest.mock import AsyncMock
-
- mock_history = MagicMock()
- mock_history.transactions = []
- credit_system.get_transaction_history = AsyncMock(return_value=mock_history)
-
# Create a mock dispute object for full amount (user has 1000, disputing 1000)
dispute = MagicMock(spec=stripe.Dispute)
dispute.id = "dp_test_dispute_pending"
@@ -270,7 +265,6 @@ async def test_handle_dispute_with_insufficient_balance(
assert user_balance.balance == 1000, "Balance should remain unchanged"
finally:
- credit_system.get_transaction_history = original_get_history
await cleanup_test_user()
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index a97fcbfdc5..43a9d4fdc1 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -815,8 +815,21 @@ class UserTransaction(BaseModel):
extra_data: str | None = None
+class CreditTransactionItem(BaseModel):
+ transaction_key: str = ""
+ transaction_time: datetime = datetime.min.replace(tzinfo=timezone.utc)
+ transaction_type: CreditTransactionType = CreditTransactionType.USAGE
+ amount: int = 0
+ description: str | None = None
+ usage_graph_id: str | None = None
+ usage_execution_id: str | None = None
+ usage_node_count: int = 0
+ usage_start_time: datetime = datetime.max.replace(tzinfo=timezone.utc)
+ user_id: str
+
+
class TransactionHistory(BaseModel):
- transactions: list[UserTransaction]
+ transactions: list[CreditTransactionItem]
next_transaction_time: datetime | None
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/AdminUserGrantHistory.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/AdminUserGrantHistory.tsx
index b843f9db3f..e00492380a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/AdminUserGrantHistory.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/spending/components/AdminUserGrantHistory.tsx
@@ -130,7 +130,10 @@ export async function AdminUserGrantHistory({
{transaction.admin_email}
</TableCell>
<TableCell className="font-medium text-green-600">
- ${(transaction.running_balance + -transaction.amount) / 100}
+ $
+ {((transaction.running_balance ?? 0) +
+ -transaction.amount) /
+ 100}
</TableCell>
<TableCell>
{formatAmount(
@@ -139,7 +142,7 @@ export async function AdminUserGrantHistory({
)}
</TableCell>
<TableCell className="font-medium text-green-600">
- ${transaction.running_balance / 100}
+ ${(transaction.running_balance ?? 0) / 100}
</TableCell>
{/* <TableCell className="font-medium text-green-600">
${transaction.current_balance / 100}
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx
index aeee97d73f..35b5b47154 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/credits/page.tsx
@@ -309,10 +309,6 @@ export default function CreditsPage() {
{/* Transaction History */}
<h3 className="text-lg font-medium">Transaction History</h3>
- <p className="text-neutral-600">
- Running balance might not be ordered accurately when concurrent
- executions are happening.
- </p>
{transactionHistory.transactions.length === 0 && (
<p className="text-neutral-600">No transactions found.</p>
)}
@@ -326,7 +322,6 @@ export default function CreditsPage() {
<TableHead>Date</TableHead>
<TableHead>Description</TableHead>
<TableHead>Amount</TableHead>
- <TableHead>Balance</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -353,9 +348,6 @@ export default function CreditsPage() {
>
<b>{formatCredits(transaction.amount)}</b>
</TableCell>
- <TableCell>
- {formatCredits(transaction.running_balance)}
- </TableCell>
</TableRow>
))}
</TableBody>
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
index 61df08c0fe..2c683a4821 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/__tests__/billing-cards.test.tsx
@@ -1005,7 +1005,6 @@ describe("UsageCard", () => {
transaction_type: "USAGE",
amount: -150,
description: "Agent run",
- running_balance: 850,
},
],
next_transaction_time: null,
@@ -1056,7 +1055,6 @@ describe("TransactionHistoryCard", () => {
transaction_type: "TOP_UP",
amount: 5000,
description: "Top up",
- running_balance: 5000,
},
{
transaction_key: "TXN-B",
@@ -1064,7 +1062,6 @@ describe("TransactionHistoryCard", () => {
transaction_type: "USAGE",
amount: -250,
description: "Agent run",
- running_balance: 4750,
},
],
next_transaction_time: null,
@@ -1077,6 +1074,7 @@ describe("TransactionHistoryCard", () => {
expect(screen.getByText("Agent run")).toBeDefined();
expect(screen.getByText("+$50.00")).toBeDefined();
expect(screen.getByText("-$2.50")).toBeDefined();
+ expect(screen.queryByText(/^Balance$/)).toBeNull();
});
it("renders ErrorCard with a Retry button on a 500", async () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx
index 8b61c846ef..3f0530d5cb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/TransactionHistoryCard.tsx
@@ -64,9 +64,6 @@ export function TransactionHistoryCard({ index = 0 }: Props) {
<Th className="hidden sm:table-cell">Date</Th>
<Th>Description</Th>
<Th align="right">Amount</Th>
- <Th align="right" className="hidden sm:table-cell">
- Balance
- </Th>
</tr>
</thead>
<motion.tbody
@@ -114,15 +111,6 @@ export function TransactionHistoryCard({ index = 0 }: Props) {
{transaction.amount}
</Text>
</td>
- <td className="hidden px-2 py-4 text-right sm:table-cell sm:px-4">
- <Text
- variant="body-medium"
- as="span"
- className="tabular-nums text-textBlack"
- >
- {transaction.balance}
- </Text>
- </td>
</motion.tr>
))}
</motion.tbody>
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts
index 812c7d26cc..76d5839f46 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/billing/components/AutomationCreditsTab/TransactionHistoryCard/useTransactionHistoryCard.ts
@@ -10,7 +10,6 @@ export interface TransactionRow {
date: string;
description: string;
amount: string;
- balance: string;
kind: "credit" | "debit";
}
@@ -42,7 +41,6 @@ export function useTransactionHistoryCard() {
: "—",
description: tx.description ?? tx.transaction_type ?? "Transaction",
amount: `${amountCents > 0 ? "+" : ""}${formatCents(amountCents)}`,
- balance: formatCents(tx.running_balance ?? 0),
kind: amountCents >= 0 ? "credit" : "debit",
};
},
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index aa1c92873e..115e5e3bc1 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -12067,6 +12067,53 @@
"required": ["id", "provider", "type", "title", "scopes", "username"],
"title": "CredentialsMetaResponse"
},
+ "CreditTransactionItem": {
+ "properties": {
+ "transaction_key": {
+ "type": "string",
+ "title": "Transaction Key",
+ "default": ""
+ },
+ "transaction_time": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Transaction Time",
+ "default": "0001-01-01T00:00:00Z"
+ },
+ "transaction_type": {
+ "$ref": "#/components/schemas/CreditTransactionType",
+ "default": "USAGE"
+ },
+ "amount": { "type": "integer", "title": "Amount", "default": 0 },
+ "description": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Description"
+ },
+ "usage_graph_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Usage Graph Id"
+ },
+ "usage_execution_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Usage Execution Id"
+ },
+ "usage_node_count": {
+ "type": "integer",
+ "title": "Usage Node Count",
+ "default": 0
+ },
+ "usage_start_time": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Usage Start Time",
+ "default": "9999-12-31T23:59:59.999999Z"
+ },
+ "user_id": { "type": "string", "title": "User Id" }
+ },
+ "type": "object",
+ "required": ["user_id"],
+ "title": "CreditTransactionItem"
+ },
"CreditTransactionType": {
"type": "string",
"enum": [
@@ -18867,7 +18914,7 @@
"TransactionHistory": {
"properties": {
"transactions": {
- "items": { "$ref": "#/components/schemas/UserTransaction" },
+ "items": { "$ref": "#/components/schemas/CreditTransactionItem" },
"type": "array",
"title": "Transactions"
},
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index ec68a32028..5934dcaf16 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -831,7 +831,7 @@ export interface CreditTransaction {
transaction_time: Date;
transaction_type: CreditTransactionType;
amount: number;
- running_balance: number;
+ running_balance?: number;
current_balance: number;
description: string;
usage_graph_id: GraphID;