mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
feat: Stripe admin dashboard with revenue analytics and payment management (#461)
<!-- @coderabbitai ignore --> ## Summary - Full Stripe payment admin dashboard with revenue analytics, payment history, refund management, payout tracking, dispute monitoring, and webhook event audit log - New `StripeAdminService` backend service for payment data storage and analytics - Enhanced webhook handler to store enriched payment data and handle refunds/disputes - User payment history integration on admin user detail page - Backfill script for migrating existing payment data - 32 new unit/endpoint tests covering all P0 critical paths (refund logic, payment storage, credit deduction) - Production E2E tests for payments page and API endpoints - Bug fix: `auth_data[0]` subscript error in refund endpoint (AuthResult not subscriptable) ## Changes ### Backend (7 phases) - **New:** `backend/services/stripe_admin_service.py` - Core payment admin service (store, list, detail, refund, revenue summary, payouts, disputes, webhook events) - **New:** `scripts/backfill_stripe_payments.py` - One-time migration script for existing payments - **Modified:** `backend/api/routes/admin.py` - 9 new admin endpoints with Pydantic models - **Modified:** `backend/api/routes/users.py` - Enhanced webhook handler with payment storage, refund/dispute handling, event logging ### Frontend - **New:** `frontend/app/admin/payments/page.tsx` - 4-tab payments page (Revenue, Transactions, Payouts, Webhooks) - **New:** `frontend/components/admin/payment-detail.tsx` - Payment detail slide-out sheet - **New:** `frontend/components/admin/refund-dialog.tsx` - Refund dialog with credit deduction warning - **Modified:** `frontend/lib/api.ts` - 11 new TypeScript interfaces + adminApi methods - **Modified:** `frontend/app/admin/users/detail/page.tsx` - Payment history section - **Modified:** `frontend/components/admin/admin-sidebar.tsx` - Payments nav item - **Modified:** `frontend/app/admin/page.tsx` - Revenue card on dashboard ### Tests - **New:** `backend/tests/test_stripe_admin_service.py` - 21 unit tests - **New:** `backend/tests/test_admin_payment_endpoints.py` - 11 endpoint tests - **New:** `frontend/e2e/production/admin-payments.spec.ts` - Production E2E tests ## Post-deploy steps 1. Register webhook events in Stripe Dashboard: `charge.refunded`, `charge.dispute.created`, `charge.dispute.closed` 2. Run backfill: `python scripts/backfill_stripe_payments.py` 3. Create Firestore indexes if prompted ## Test plan - [x] 32 new tests pass (service + endpoint) - [x] 181 total tests pass (full suite, 1 pre-existing skip) - [ ] Visual verification of payments page after deploy - [ ] Backfill script dry-run against production - [ ] Verify webhook events are logged after deploy 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
6525bf8e1a
commit
d91c2c2b4e
15 files changed
+3866
-40
No files matched your search
@@ -2682,3 +2682,302 @@ async def override_audio_source(
|
||||
search_results_count=search_results_count,
|
||||
error=error_msg,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Payment Admin Endpoints
|
||||
# =============================================================================
|
||||
|
||||
class RevenueSummaryResponse(BaseModel):
|
||||
"""Revenue summary metrics."""
|
||||
total_gross: int
|
||||
total_fees: int
|
||||
total_net: int
|
||||
total_refunds: int
|
||||
transaction_count: int
|
||||
average_order_value: int
|
||||
revenue_by_type: Dict[str, int]
|
||||
|
||||
|
||||
class RevenueChartPoint(BaseModel):
|
||||
"""Single data point for revenue chart."""
|
||||
date: str
|
||||
gross: int
|
||||
net: int
|
||||
fees: int
|
||||
count: int
|
||||
|
||||
|
||||
class PaymentSummary(BaseModel):
|
||||
"""Payment record for list view."""
|
||||
session_id: str
|
||||
amount_total: int = 0
|
||||
currency: str = "usd"
|
||||
stripe_fee: int = 0
|
||||
net_amount: int = 0
|
||||
customer_email: str = ""
|
||||
customer_name: str = ""
|
||||
payment_method_type: str = ""
|
||||
card_brand: str = ""
|
||||
card_last4: str = ""
|
||||
order_type: str = ""
|
||||
product_description: str = ""
|
||||
status: str = ""
|
||||
refund_amount: int = 0
|
||||
created_at: Optional[str] = None
|
||||
is_test: bool = False
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class PaymentListResponse(BaseModel):
|
||||
"""Response for payment list."""
|
||||
payments: List[PaymentSummary]
|
||||
total: int
|
||||
has_more: bool
|
||||
|
||||
|
||||
class StripeBalanceResponse(BaseModel):
|
||||
"""Stripe account balance."""
|
||||
available: int
|
||||
pending: int
|
||||
currency: str = "usd"
|
||||
|
||||
|
||||
class PayoutItem(BaseModel):
|
||||
"""Payout record."""
|
||||
id: str
|
||||
amount: int
|
||||
currency: str = "usd"
|
||||
status: str = ""
|
||||
arrival_date: Optional[int] = None
|
||||
created: Optional[int] = None
|
||||
description: Optional[str] = None
|
||||
method: Optional[str] = None
|
||||
|
||||
|
||||
class DisputeItem(BaseModel):
|
||||
"""Dispute record."""
|
||||
id: str
|
||||
amount: int
|
||||
currency: str = "usd"
|
||||
status: str = ""
|
||||
reason: str = ""
|
||||
charge_id: Optional[str] = None
|
||||
created: Optional[int] = None
|
||||
evidence_due_by: Optional[int] = None
|
||||
payment_intent_id: Optional[str] = None
|
||||
|
||||
|
||||
class RefundRequest(BaseModel):
|
||||
"""Request to issue a refund."""
|
||||
amount: Optional[int] = None
|
||||
reason: str = "requested_by_customer"
|
||||
|
||||
|
||||
class RefundResponse(BaseModel):
|
||||
"""Response from refund processing."""
|
||||
success: bool
|
||||
message: str
|
||||
session_id: str
|
||||
|
||||
|
||||
class UserPaymentHistoryResponse(BaseModel):
|
||||
"""Payment history for a user."""
|
||||
email: str
|
||||
payments: List[PaymentSummary]
|
||||
total_spent: int
|
||||
total_refunded: int
|
||||
net_spent: int
|
||||
payment_count: int
|
||||
first_payment_at: Optional[str] = None
|
||||
last_payment_at: Optional[str] = None
|
||||
|
||||
|
||||
class WebhookEventItem(BaseModel):
|
||||
"""Webhook event record."""
|
||||
event_id: str = ""
|
||||
event_type: str = ""
|
||||
created_at: Optional[str] = None
|
||||
processed_at: Optional[str] = None
|
||||
status: str = ""
|
||||
error_message: Optional[str] = None
|
||||
session_id: Optional[str] = None
|
||||
customer_email: Optional[str] = None
|
||||
summary: Optional[str] = None
|
||||
|
||||
|
||||
@router.get("/payments/summary", response_model=RevenueSummaryResponse)
|
||||
async def get_payment_summary(
|
||||
days: int = 30,
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get revenue summary metrics for the given period."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
result = service.get_revenue_summary(days=days, exclude_test=exclude_test)
|
||||
# Remove internal cache key
|
||||
result.pop("_key", None)
|
||||
return RevenueSummaryResponse(**result)
|
||||
|
||||
|
||||
@router.get("/payments/revenue-chart", response_model=List[RevenueChartPoint])
|
||||
async def get_revenue_chart(
|
||||
days: int = 30,
|
||||
group_by: str = "day",
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get revenue data grouped by time period for charting."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
return service.get_revenue_by_period(days=days, group_by=group_by, exclude_test=exclude_test)
|
||||
|
||||
|
||||
@router.get("/payments", response_model=PaymentListResponse)
|
||||
async def list_payments(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
order_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
email: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""List payments with pagination and filters."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
result = service.list_payments(
|
||||
limit=limit, offset=offset, order_type=order_type,
|
||||
status=status, email=email, exclude_test=exclude_test,
|
||||
)
|
||||
return PaymentListResponse(**result)
|
||||
|
||||
|
||||
@router.get("/payments/balance", response_model=StripeBalanceResponse)
|
||||
async def get_stripe_balance(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get current Stripe account balance."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
return StripeBalanceResponse(**service.get_stripe_balance())
|
||||
|
||||
|
||||
@router.get("/payments/payouts", response_model=List[PayoutItem])
|
||||
async def get_payouts(
|
||||
limit: int = 20,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get recent payouts."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
return service.get_recent_payouts(limit=limit)
|
||||
|
||||
|
||||
@router.get("/payments/disputes", response_model=List[DisputeItem])
|
||||
async def get_disputes(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get open and recent disputes."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
return service.get_recent_disputes()
|
||||
|
||||
|
||||
@router.get("/payments/webhook-events", response_model=List[WebhookEventItem])
|
||||
async def get_webhook_events(
|
||||
limit: int = 50,
|
||||
event_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get recent webhook events for audit trail."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
return service.list_webhook_events(limit=limit, event_type=event_type, status=status)
|
||||
|
||||
|
||||
@router.get("/payments/by-user/{email}")
|
||||
async def get_user_payments(
|
||||
email: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get all payments for a specific user."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
return service.get_user_payment_history(email)
|
||||
|
||||
|
||||
@router.get("/payments/{session_id}")
|
||||
async def get_payment_detail(
|
||||
session_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Get full details for a single payment."""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
result = service.get_payment_detail(session_id)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Payment not found")
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/payments/{session_id}/refund", response_model=RefundResponse)
|
||||
async def refund_payment(
|
||||
session_id: str,
|
||||
request: RefundRequest,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Issue a full or partial refund for a payment.
|
||||
|
||||
If amount is not specified, issues a full refund.
|
||||
Automatically deducts proportional credits from user.
|
||||
"""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
service = get_stripe_admin_service()
|
||||
|
||||
# Get payment details first to determine credits to deduct
|
||||
payment = service.get_payment_detail(session_id)
|
||||
if not payment:
|
||||
raise HTTPException(status_code=404, detail="Payment not found")
|
||||
|
||||
success, message = service.process_refund(
|
||||
session_id=session_id,
|
||||
amount=request.amount,
|
||||
reason=request.reason,
|
||||
)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=400, detail=message)
|
||||
|
||||
# Deduct proportional credits if this was a credit purchase
|
||||
if payment.get("order_type") == "credit_purchase" and payment.get("credits_granted", 0) > 0:
|
||||
try:
|
||||
original_amount = payment.get("amount_total", 0)
|
||||
refund_amount = request.amount or original_amount
|
||||
credits_to_deduct = int(
|
||||
payment["credits_granted"] * (refund_amount / original_amount)
|
||||
)
|
||||
if credits_to_deduct > 0:
|
||||
user_email = payment.get("customer_email", "")
|
||||
user_service = get_user_service()
|
||||
user_service.add_credits(
|
||||
email=user_email,
|
||||
amount=-credits_to_deduct,
|
||||
reason=f"refund_{session_id}",
|
||||
)
|
||||
logger.info(
|
||||
f"Deducted {credits_to_deduct} credits from {user_email} "
|
||||
f"for refund on {session_id}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to deduct credits for refund {session_id}: {e}")
|
||||
|
||||
admin_email = getattr(auth_data, "user_email", None) or "unknown"
|
||||
logger.info(f"Admin {admin_email} issued refund for {session_id}: {message}")
|
||||
|
||||
return RefundResponse(success=True, message=message, session_id=session_id)
|
||||
+175
-37
@@ -10,6 +10,7 @@ Handles:
|
||||
"""
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
|
||||
@@ -810,6 +811,8 @@ async def stripe_webhook(
|
||||
This endpoint receives events from Stripe about payment status.
|
||||
It verifies the webhook signature and processes the event.
|
||||
"""
|
||||
from backend.services.stripe_admin_service import get_stripe_admin_service
|
||||
|
||||
if not stripe_signature:
|
||||
raise HTTPException(status_code=400, detail="Missing Stripe signature")
|
||||
|
||||
@@ -825,52 +828,187 @@ async def stripe_webhook(
|
||||
|
||||
# Handle the event
|
||||
event_type = event.get("type")
|
||||
event_id = event.get("id", "")
|
||||
logger.info(f"Received Stripe webhook: {event_type}")
|
||||
|
||||
if event_type == "checkout.session.completed":
|
||||
session = event["data"]["object"]
|
||||
session_id = session.get("id")
|
||||
metadata = session.get("metadata", {})
|
||||
# Log webhook event for audit trail
|
||||
admin_service = get_stripe_admin_service()
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="processing",
|
||||
)
|
||||
|
||||
# Idempotency check: Skip if this session was already processed
|
||||
if session_id and user_service.is_stripe_session_processed(session_id):
|
||||
logger.info(f"Skipping already processed session: {session_id}")
|
||||
return {"status": "received", "type": event_type, "note": "already_processed"}
|
||||
|
||||
# Check if this is a made-for-you order
|
||||
if metadata.get("order_type") == "made_for_you":
|
||||
# Handle made-for-you order - create a job
|
||||
await _handle_made_for_you_order(
|
||||
session_id=session_id,
|
||||
metadata=metadata,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
try:
|
||||
if event_type == "checkout.session.completed":
|
||||
session = event["data"]["object"]
|
||||
session_id = session.get("id")
|
||||
metadata = session.get("metadata", {})
|
||||
customer_email = (
|
||||
metadata.get("user_email")
|
||||
or metadata.get("customer_email")
|
||||
or session.get("customer_email", "")
|
||||
)
|
||||
else:
|
||||
# Handle regular credit purchase
|
||||
success, user_email, credits, _ = stripe_service.handle_checkout_completed(session)
|
||||
|
||||
if success and user_email and credits > 0:
|
||||
# Add credits to user account
|
||||
ok, new_balance, credit_msg = user_service.add_credits(
|
||||
email=user_email,
|
||||
amount=credits,
|
||||
reason="stripe_purchase",
|
||||
stripe_session_id=session_id,
|
||||
# Idempotency check: Skip if this session was already processed
|
||||
if session_id and user_service.is_stripe_session_processed(session_id):
|
||||
logger.info(f"Skipping already processed session: {session_id}")
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="skipped",
|
||||
session_id=session_id,
|
||||
customer_email=customer_email,
|
||||
summary="Already processed (idempotency check)",
|
||||
)
|
||||
return {"status": "received", "type": event_type, "note": "already_processed"}
|
||||
|
||||
if ok:
|
||||
# Send confirmation email
|
||||
email_service.send_credits_added(user_email, credits, new_balance)
|
||||
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
|
||||
else:
|
||||
logger.error(f"Failed to add credits: {credit_msg}")
|
||||
# Check if this is a made-for-you order
|
||||
if metadata.get("order_type") == "made_for_you":
|
||||
# Handle made-for-you order - create a job
|
||||
await _handle_made_for_you_order(
|
||||
session_id=session_id,
|
||||
metadata=metadata,
|
||||
user_service=user_service,
|
||||
email_service=email_service,
|
||||
)
|
||||
else:
|
||||
# Handle regular credit purchase
|
||||
success, user_email, credits, _ = stripe_service.handle_checkout_completed(session)
|
||||
|
||||
elif event_type == "checkout.session.expired":
|
||||
logger.info(f"Checkout session expired: {event['data']['object'].get('id')}")
|
||||
if success and user_email and credits > 0:
|
||||
# Add credits to user account
|
||||
ok, new_balance, credit_msg = user_service.add_credits(
|
||||
email=user_email,
|
||||
amount=credits,
|
||||
reason="stripe_purchase",
|
||||
stripe_session_id=session_id,
|
||||
)
|
||||
|
||||
elif event_type == "payment_intent.payment_failed":
|
||||
logger.warning(f"Payment failed: {event['data']['object'].get('id')}")
|
||||
if ok:
|
||||
# Send confirmation email
|
||||
email_service.send_credits_added(user_email, credits, new_balance)
|
||||
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
|
||||
else:
|
||||
logger.error(f"Failed to add credits: {credit_msg}")
|
||||
|
||||
# Store enriched payment data (non-blocking - failure won't break credit granting)
|
||||
try:
|
||||
import stripe as stripe_lib
|
||||
expanded_session = stripe_lib.checkout.Session.retrieve(
|
||||
session_id,
|
||||
expand=["payment_intent.latest_charge.balance_transaction"],
|
||||
)
|
||||
admin_service.store_payment(dict(expanded_session))
|
||||
except Exception as store_err:
|
||||
logger.warning(f"Failed to store payment data for {session_id}: {store_err}")
|
||||
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="success",
|
||||
session_id=session_id,
|
||||
customer_email=customer_email,
|
||||
summary=f"Payment ${session.get('amount_total', 0) / 100:.2f} processed",
|
||||
)
|
||||
|
||||
elif event_type == "charge.refunded":
|
||||
charge = event["data"]["object"]
|
||||
payment_intent_id = charge.get("payment_intent")
|
||||
refund_amount = charge.get("amount_refunded", 0)
|
||||
original_amount = charge.get("amount", 0)
|
||||
|
||||
# Find the payment by payment_intent_id
|
||||
try:
|
||||
collection = admin_service.db.collection("stripe_payments")
|
||||
docs = list(
|
||||
collection.where("payment_intent_id", "==", payment_intent_id)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
if docs:
|
||||
doc = docs[0]
|
||||
status = "refunded" if refund_amount >= original_amount else "partially_refunded"
|
||||
admin_service.update_payment_status(doc.id, {
|
||||
"status": status,
|
||||
"refund_amount": refund_amount,
|
||||
"refunded_at": datetime.utcnow(),
|
||||
})
|
||||
logger.info(f"Updated payment {doc.id} to {status} (refund: ${refund_amount / 100:.2f})")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to update refund status: {e}")
|
||||
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="success",
|
||||
summary=f"Refund ${refund_amount / 100:.2f} on {payment_intent_id}",
|
||||
)
|
||||
|
||||
elif event_type in ("charge.dispute.created", "charge.dispute.closed"):
|
||||
dispute = event["data"]["object"]
|
||||
payment_intent_id = dispute.get("payment_intent")
|
||||
dispute_status = dispute.get("status")
|
||||
dispute_amount = dispute.get("amount", 0)
|
||||
|
||||
try:
|
||||
collection = admin_service.db.collection("stripe_payments")
|
||||
docs = list(
|
||||
collection.where("payment_intent_id", "==", payment_intent_id)
|
||||
.limit(1)
|
||||
.stream()
|
||||
)
|
||||
if docs:
|
||||
doc = docs[0]
|
||||
new_status = "disputed" if event_type == "charge.dispute.created" else doc.to_dict().get("status", "succeeded")
|
||||
if event_type == "charge.dispute.closed" and dispute_status == "won":
|
||||
new_status = "succeeded"
|
||||
admin_service.update_payment_status(doc.id, {"status": new_status})
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to update dispute status: {e}")
|
||||
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="success",
|
||||
summary=f"Dispute {dispute_status}: ${dispute_amount / 100:.2f}",
|
||||
)
|
||||
|
||||
elif event_type == "checkout.session.expired":
|
||||
logger.info(f"Checkout session expired: {event['data']['object'].get('id')}")
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="success",
|
||||
session_id=event["data"]["object"].get("id"),
|
||||
summary="Checkout session expired",
|
||||
)
|
||||
|
||||
elif event_type == "payment_intent.payment_failed":
|
||||
logger.warning(f"Payment failed: {event['data']['object'].get('id')}")
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="success",
|
||||
summary=f"Payment failed: {event['data']['object'].get('id')}",
|
||||
)
|
||||
|
||||
else:
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="success",
|
||||
summary=f"Unhandled event type: {event_type}",
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
admin_service.log_webhook_event(
|
||||
event_id=event_id,
|
||||
event_type=event_type,
|
||||
status="error",
|
||||
error_message=str(e),
|
||||
)
|
||||
raise
|
||||
|
||||
# Return 200 to acknowledge receipt (Stripe will retry on non-2xx)
|
||||
return {"status": "received", "type": event_type}
|
||||
|
||||
@@ -0,0 +1,718 @@
|
||||
"""
|
||||
Stripe admin service for payment analytics and management.
|
||||
|
||||
Handles:
|
||||
- Storing enriched payment data from webhooks
|
||||
- Revenue analytics and reporting
|
||||
- Payment listing and detail views
|
||||
- Stripe balance and payout queries
|
||||
- Refund processing
|
||||
- Dispute monitoring
|
||||
- Webhook event logging
|
||||
"""
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any, List, Tuple
|
||||
|
||||
import stripe
|
||||
from google.cloud import firestore
|
||||
|
||||
from backend.config import get_settings
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STRIPE_PAYMENTS_COLLECTION = "stripe_payments"
|
||||
STRIPE_WEBHOOK_EVENTS_COLLECTION = "stripe_webhook_events"
|
||||
|
||||
|
||||
class StripeAdminService:
|
||||
"""Service for Stripe admin analytics and payment management."""
|
||||
|
||||
def __init__(self):
|
||||
self.settings = get_settings()
|
||||
self.db = firestore.Client()
|
||||
self._revenue_cache: Optional[Dict[str, Any]] = None
|
||||
self._revenue_cache_time: float = 0
|
||||
self._revenue_cache_ttl: float = 300 # 5 minutes
|
||||
|
||||
# =========================================================================
|
||||
# Payment Storage
|
||||
# =========================================================================
|
||||
|
||||
def store_payment(self, session: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Store enriched payment data from a completed Checkout Session.
|
||||
|
||||
Args:
|
||||
session: Stripe Checkout Session object (expanded with payment_intent,
|
||||
charge, and balance_transaction)
|
||||
|
||||
Returns:
|
||||
True if stored successfully
|
||||
"""
|
||||
try:
|
||||
session_id = session.get("id", "")
|
||||
metadata = session.get("metadata", {})
|
||||
|
||||
# Extract payment intent and charge details
|
||||
payment_intent = session.get("payment_intent", {})
|
||||
if isinstance(payment_intent, str):
|
||||
# Not expanded - just store the ID
|
||||
payment_intent_id = payment_intent
|
||||
charge_data = {}
|
||||
balance_txn = {}
|
||||
else:
|
||||
payment_intent_id = payment_intent.get("id", "")
|
||||
charges = payment_intent.get("latest_charge", {})
|
||||
if isinstance(charges, str):
|
||||
charge_data = {}
|
||||
balance_txn = {}
|
||||
else:
|
||||
charge_data = charges or {}
|
||||
bt = charge_data.get("balance_transaction", {})
|
||||
balance_txn = bt if isinstance(bt, dict) else {}
|
||||
|
||||
# Extract payment method details
|
||||
payment_method_details = charge_data.get("payment_method_details", {})
|
||||
pm_type = payment_method_details.get("type", "unknown")
|
||||
card_info = payment_method_details.get("card", {})
|
||||
|
||||
# Determine order type
|
||||
order_type = metadata.get("order_type", "credit_purchase")
|
||||
package_id = metadata.get("package_id")
|
||||
credits = 0
|
||||
try:
|
||||
credits = int(metadata.get("credits", 0))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# Build product description
|
||||
if order_type == "made_for_you":
|
||||
artist = metadata.get("artist", "")
|
||||
title = metadata.get("title", "")
|
||||
product_description = f"Made For You: {artist} - {title}"
|
||||
else:
|
||||
from backend.services.stripe_service import CREDIT_PACKAGES
|
||||
pkg = CREDIT_PACKAGES.get(package_id, {})
|
||||
product_description = pkg.get("name", f"{credits} Credits")
|
||||
|
||||
# Extract discount info
|
||||
total_details = session.get("total_details", {})
|
||||
discount_amount = 0
|
||||
promotion_code = None
|
||||
if total_details:
|
||||
discount_obj = total_details.get("amount_discount", 0)
|
||||
discount_amount = discount_obj if isinstance(discount_obj, int) else 0
|
||||
|
||||
# Determine if test payment
|
||||
is_test = not (session.get("livemode", False))
|
||||
|
||||
payment_data = {
|
||||
"session_id": session_id,
|
||||
"payment_intent_id": payment_intent_id,
|
||||
"charge_id": charge_data.get("id", ""),
|
||||
# Financial (cents)
|
||||
"amount_total": session.get("amount_total", 0),
|
||||
"currency": session.get("currency", "usd"),
|
||||
"stripe_fee": balance_txn.get("fee", 0),
|
||||
"net_amount": balance_txn.get("net", 0),
|
||||
# Customer
|
||||
"customer_email": (
|
||||
metadata.get("user_email")
|
||||
or metadata.get("customer_email")
|
||||
or session.get("customer_email", "")
|
||||
),
|
||||
"customer_name": session.get("customer_details", {}).get("name", ""),
|
||||
"stripe_customer_id": session.get("customer", ""),
|
||||
# Payment method
|
||||
"payment_method_type": pm_type,
|
||||
"card_brand": card_info.get("brand", ""),
|
||||
"card_last4": card_info.get("last4", ""),
|
||||
# Order details
|
||||
"order_type": order_type,
|
||||
"package_id": package_id,
|
||||
"credits_granted": credits,
|
||||
"product_description": product_description,
|
||||
# Made-for-you fields
|
||||
"artist": metadata.get("artist"),
|
||||
"title": metadata.get("title"),
|
||||
"job_id": metadata.get("job_id"),
|
||||
# Status
|
||||
"status": "succeeded",
|
||||
"refund_amount": 0,
|
||||
"refund_id": None,
|
||||
"refunded_at": None,
|
||||
"refund_reason": None,
|
||||
# Timestamps
|
||||
"created_at": datetime.utcnow(),
|
||||
"processed_at": datetime.utcnow(),
|
||||
# Metadata
|
||||
"is_test": is_test,
|
||||
"promotion_code": promotion_code,
|
||||
"discount_amount": discount_amount,
|
||||
}
|
||||
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc_ref.set(payment_data)
|
||||
|
||||
# Invalidate revenue cache
|
||||
self._revenue_cache = None
|
||||
|
||||
logger.info(
|
||||
f"Stored payment data for session {session_id}: "
|
||||
f"${payment_data['amount_total'] / 100:.2f} from {payment_data['customer_email']}"
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error storing payment data for session {session.get('id', 'unknown')}")
|
||||
return False
|
||||
|
||||
def update_payment_status(self, session_id: str, updates: Dict[str, Any]) -> bool:
|
||||
"""Update payment status fields (for refunds/disputes)."""
|
||||
try:
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
logger.warning(f"Payment {session_id} not found for status update")
|
||||
return False
|
||||
|
||||
doc_ref.update(updates)
|
||||
self._revenue_cache = None
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception(f"Error updating payment status for {session_id}")
|
||||
return False
|
||||
|
||||
# =========================================================================
|
||||
# Revenue Analytics
|
||||
# =========================================================================
|
||||
|
||||
def get_revenue_summary(
|
||||
self, days: int = 30, exclude_test: bool = True
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get revenue summary metrics.
|
||||
|
||||
Returns total gross, fees, net, refunds, count, AOV, revenue by product type.
|
||||
Uses in-memory cache with 5-minute TTL.
|
||||
"""
|
||||
cache_key = f"{days}_{exclude_test}"
|
||||
now = time.time()
|
||||
if (
|
||||
self._revenue_cache
|
||||
and self._revenue_cache.get("_key") == cache_key
|
||||
and (now - self._revenue_cache_time) < self._revenue_cache_ttl
|
||||
):
|
||||
return self._revenue_cache
|
||||
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = collection
|
||||
|
||||
if days > 0:
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
query = query.where("created_at", ">=", cutoff)
|
||||
|
||||
total_gross = 0
|
||||
total_fees = 0
|
||||
total_net = 0
|
||||
total_refunds = 0
|
||||
count = 0
|
||||
by_type: Dict[str, int] = {}
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
amount = data.get("amount_total", 0)
|
||||
total_gross += amount
|
||||
total_fees += data.get("stripe_fee", 0)
|
||||
total_net += data.get("net_amount", 0)
|
||||
total_refunds += data.get("refund_amount", 0)
|
||||
count += 1
|
||||
|
||||
order_type = data.get("order_type", "credit_purchase")
|
||||
by_type[order_type] = by_type.get(order_type, 0) + amount
|
||||
|
||||
aov = total_gross / count if count > 0 else 0
|
||||
|
||||
result = {
|
||||
"_key": cache_key,
|
||||
"total_gross": total_gross,
|
||||
"total_fees": total_fees,
|
||||
"total_net": total_net,
|
||||
"total_refunds": total_refunds,
|
||||
"transaction_count": count,
|
||||
"average_order_value": round(aov),
|
||||
"revenue_by_type": by_type,
|
||||
}
|
||||
|
||||
self._revenue_cache = result
|
||||
self._revenue_cache_time = now
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error calculating revenue summary")
|
||||
return {
|
||||
"total_gross": 0,
|
||||
"total_fees": 0,
|
||||
"total_net": 0,
|
||||
"total_refunds": 0,
|
||||
"transaction_count": 0,
|
||||
"average_order_value": 0,
|
||||
"revenue_by_type": {},
|
||||
}
|
||||
|
||||
def get_revenue_by_period(
|
||||
self,
|
||||
days: int = 30,
|
||||
group_by: str = "day",
|
||||
exclude_test: bool = True,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get revenue grouped by time period for charting.
|
||||
|
||||
Args:
|
||||
days: Number of days to look back
|
||||
group_by: 'day' or 'week' or 'month'
|
||||
exclude_test: Exclude test transactions
|
||||
|
||||
Returns:
|
||||
List of {date, gross, net, fees, count} dicts
|
||||
"""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
cutoff = datetime.utcnow() - timedelta(days=days)
|
||||
query = collection.where("created_at", ">=", cutoff)
|
||||
|
||||
buckets: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
created = data.get("created_at")
|
||||
if not created:
|
||||
continue
|
||||
if isinstance(created, str):
|
||||
try:
|
||||
created = datetime.fromisoformat(created.replace("Z", "+00:00"))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if group_by == "week":
|
||||
# Start of week (Monday)
|
||||
start = created - timedelta(days=created.weekday())
|
||||
key = start.strftime("%Y-%m-%d")
|
||||
elif group_by == "month":
|
||||
key = created.strftime("%Y-%m-01")
|
||||
else:
|
||||
key = created.strftime("%Y-%m-%d")
|
||||
|
||||
if key not in buckets:
|
||||
buckets[key] = {"date": key, "gross": 0, "net": 0, "fees": 0, "count": 0}
|
||||
|
||||
buckets[key]["gross"] += data.get("amount_total", 0)
|
||||
buckets[key]["net"] += data.get("net_amount", 0)
|
||||
buckets[key]["fees"] += data.get("stripe_fee", 0)
|
||||
buckets[key]["count"] += 1
|
||||
|
||||
result = sorted(buckets.values(), key=lambda x: x["date"])
|
||||
return result
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error getting revenue by period")
|
||||
return []
|
||||
|
||||
# =========================================================================
|
||||
# Payment Listing & Details
|
||||
# =========================================================================
|
||||
|
||||
def list_payments(
|
||||
self,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
order_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
email: Optional[str] = None,
|
||||
exclude_test: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
List payments with pagination and filters.
|
||||
|
||||
Returns:
|
||||
{payments: [...], total: int, has_more: bool}
|
||||
"""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = collection.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
|
||||
if order_type:
|
||||
query = collection.where("order_type", "==", order_type).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
if status:
|
||||
query = collection.where("status", "==", status).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
if email:
|
||||
query = collection.where("customer_email", "==", email.lower()).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
|
||||
# Stream and filter (Firestore doesn't support multiple inequality filters)
|
||||
payments = []
|
||||
skipped = 0
|
||||
total = 0
|
||||
|
||||
for doc in query.limit(1000).stream():
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
|
||||
if exclude_test and data.get("is_test"):
|
||||
continue
|
||||
|
||||
# Apply filters that couldn't be done in query
|
||||
if order_type and data.get("order_type") != order_type:
|
||||
continue
|
||||
if status and data.get("status") != status:
|
||||
continue
|
||||
if email and data.get("customer_email", "").lower() != email.lower():
|
||||
continue
|
||||
|
||||
total += 1
|
||||
if skipped < offset:
|
||||
skipped += 1
|
||||
continue
|
||||
if len(payments) < limit:
|
||||
# Convert datetime objects for JSON serialization
|
||||
for key in ["created_at", "processed_at", "refunded_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
payments.append(data)
|
||||
|
||||
return {
|
||||
"payments": payments,
|
||||
"total": total,
|
||||
"has_more": total > offset + limit,
|
||||
}
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error listing payments")
|
||||
return {"payments": [], "total": 0, "has_more": False}
|
||||
|
||||
def get_payment_detail(self, session_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Get full payment details for a single payment.
|
||||
|
||||
Combines Firestore data with on-demand Stripe API call for receipt_url.
|
||||
"""
|
||||
try:
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return None
|
||||
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
|
||||
# Convert datetime objects
|
||||
for key in ["created_at", "processed_at", "refunded_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
|
||||
# On-demand: fetch receipt URL from Stripe
|
||||
charge_id = data.get("charge_id")
|
||||
if charge_id:
|
||||
try:
|
||||
charge = stripe.Charge.retrieve(charge_id)
|
||||
data["receipt_url"] = charge.get("receipt_url")
|
||||
data["stripe_dashboard_url"] = (
|
||||
f"https://dashboard.stripe.com/payments/{data.get('payment_intent_id', '')}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not fetch charge {charge_id}: {e}")
|
||||
data["receipt_url"] = None
|
||||
|
||||
return data
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error getting payment detail for {session_id}")
|
||||
return None
|
||||
|
||||
def get_user_payment_history(self, email: str) -> Dict[str, Any]:
|
||||
"""Get all payments for a user with total_spent."""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_PAYMENTS_COLLECTION)
|
||||
query = (
|
||||
collection.where("customer_email", "==", email.lower())
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
)
|
||||
|
||||
payments = []
|
||||
total_spent = 0
|
||||
total_refunded = 0
|
||||
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
data["session_id"] = doc.id
|
||||
total_spent += data.get("amount_total", 0)
|
||||
total_refunded += data.get("refund_amount", 0)
|
||||
|
||||
for key in ["created_at", "processed_at", "refunded_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
|
||||
payments.append(data)
|
||||
|
||||
first_payment = payments[-1]["created_at"] if payments else None
|
||||
last_payment = payments[0]["created_at"] if payments else None
|
||||
|
||||
return {
|
||||
"email": email,
|
||||
"payments": payments,
|
||||
"total_spent": total_spent,
|
||||
"total_refunded": total_refunded,
|
||||
"net_spent": total_spent - total_refunded,
|
||||
"payment_count": len(payments),
|
||||
"first_payment_at": first_payment,
|
||||
"last_payment_at": last_payment,
|
||||
}
|
||||
|
||||
except Exception:
|
||||
logger.exception(f"Error getting payment history for {email}")
|
||||
return {
|
||||
"email": email,
|
||||
"payments": [],
|
||||
"total_spent": 0,
|
||||
"total_refunded": 0,
|
||||
"net_spent": 0,
|
||||
"payment_count": 0,
|
||||
"first_payment_at": None,
|
||||
"last_payment_at": None,
|
||||
}
|
||||
|
||||
# =========================================================================
|
||||
# Stripe Balance & Payouts
|
||||
# =========================================================================
|
||||
|
||||
def get_stripe_balance(self) -> Dict[str, Any]:
|
||||
"""Get current Stripe account balance (available + pending)."""
|
||||
try:
|
||||
balance = stripe.Balance.retrieve()
|
||||
available = sum(b.get("amount", 0) for b in balance.get("available", []))
|
||||
pending = sum(b.get("amount", 0) for b in balance.get("pending", []))
|
||||
return {
|
||||
"available": available,
|
||||
"pending": pending,
|
||||
"currency": "usd",
|
||||
}
|
||||
except Exception:
|
||||
logger.exception("Error fetching Stripe balance")
|
||||
return {"available": 0, "pending": 0, "currency": "usd"}
|
||||
|
||||
def get_recent_payouts(self, limit: int = 10) -> List[Dict[str, Any]]:
|
||||
"""Get recent payouts from Stripe."""
|
||||
try:
|
||||
payouts = stripe.Payout.list(limit=limit)
|
||||
result = []
|
||||
for p in payouts.get("data", []):
|
||||
result.append({
|
||||
"id": p.get("id"),
|
||||
"amount": p.get("amount"),
|
||||
"currency": p.get("currency"),
|
||||
"status": p.get("status"),
|
||||
"arrival_date": p.get("arrival_date"),
|
||||
"created": p.get("created"),
|
||||
"description": p.get("description"),
|
||||
"method": p.get("method"),
|
||||
})
|
||||
return result
|
||||
except Exception:
|
||||
logger.exception("Error fetching payouts")
|
||||
return []
|
||||
|
||||
# =========================================================================
|
||||
# Disputes
|
||||
# =========================================================================
|
||||
|
||||
def get_recent_disputes(self) -> List[Dict[str, Any]]:
|
||||
"""Get open and recent disputes from Stripe."""
|
||||
try:
|
||||
disputes = stripe.Dispute.list(limit=20)
|
||||
result = []
|
||||
for d in disputes.get("data", []):
|
||||
result.append({
|
||||
"id": d.get("id"),
|
||||
"amount": d.get("amount"),
|
||||
"currency": d.get("currency"),
|
||||
"status": d.get("status"),
|
||||
"reason": d.get("reason"),
|
||||
"charge_id": d.get("charge"),
|
||||
"created": d.get("created"),
|
||||
"evidence_due_by": d.get("evidence_details", {}).get("due_by"),
|
||||
"payment_intent_id": d.get("payment_intent"),
|
||||
})
|
||||
return result
|
||||
except Exception:
|
||||
logger.exception("Error fetching disputes")
|
||||
return []
|
||||
|
||||
# =========================================================================
|
||||
# Refund Processing
|
||||
# =========================================================================
|
||||
|
||||
def process_refund(
|
||||
self,
|
||||
session_id: str,
|
||||
amount: Optional[int] = None,
|
||||
reason: str = "requested_by_customer",
|
||||
) -> Tuple[bool, str]:
|
||||
"""
|
||||
Process a refund for a payment.
|
||||
|
||||
Args:
|
||||
session_id: Checkout session ID
|
||||
amount: Refund amount in cents (None for full refund)
|
||||
reason: Refund reason
|
||||
|
||||
Returns:
|
||||
(success, message)
|
||||
"""
|
||||
try:
|
||||
# Get payment record
|
||||
doc_ref = self.db.collection(STRIPE_PAYMENTS_COLLECTION).document(session_id)
|
||||
doc = doc_ref.get()
|
||||
if not doc.exists:
|
||||
return False, "Payment not found"
|
||||
|
||||
data = doc.to_dict()
|
||||
payment_intent_id = data.get("payment_intent_id")
|
||||
if not payment_intent_id:
|
||||
return False, "No payment intent ID found"
|
||||
|
||||
current_refund = data.get("refund_amount", 0)
|
||||
original_amount = data.get("amount_total", 0)
|
||||
refund_amount = amount or (original_amount - current_refund)
|
||||
|
||||
if refund_amount <= 0:
|
||||
return False, "Invalid refund amount"
|
||||
if current_refund + refund_amount > original_amount:
|
||||
return False, f"Refund would exceed original amount (${original_amount / 100:.2f})"
|
||||
|
||||
# Create Stripe refund
|
||||
refund_params: Dict[str, Any] = {
|
||||
"payment_intent": payment_intent_id,
|
||||
"amount": refund_amount,
|
||||
"reason": reason,
|
||||
}
|
||||
refund = stripe.Refund.create(**refund_params)
|
||||
|
||||
# Update Firestore record
|
||||
new_total_refund = current_refund + refund_amount
|
||||
new_status = "refunded" if new_total_refund >= original_amount else "partially_refunded"
|
||||
|
||||
doc_ref.update({
|
||||
"status": new_status,
|
||||
"refund_amount": new_total_refund,
|
||||
"refund_id": refund.get("id"),
|
||||
"refunded_at": datetime.utcnow(),
|
||||
"refund_reason": reason,
|
||||
})
|
||||
|
||||
self._revenue_cache = None
|
||||
|
||||
logger.info(
|
||||
f"Processed refund for {session_id}: "
|
||||
f"${refund_amount / 100:.2f} ({new_status})"
|
||||
)
|
||||
return True, f"Refund of ${refund_amount / 100:.2f} processed successfully"
|
||||
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Stripe refund error for {session_id}: {e}")
|
||||
return False, f"Stripe error: {str(e)}"
|
||||
except Exception:
|
||||
logger.exception(f"Error processing refund for {session_id}")
|
||||
return False, "Unexpected error processing refund"
|
||||
|
||||
# =========================================================================
|
||||
# Webhook Event Logging
|
||||
# =========================================================================
|
||||
|
||||
def log_webhook_event(
|
||||
self,
|
||||
event_id: str,
|
||||
event_type: str,
|
||||
status: str = "processing",
|
||||
session_id: Optional[str] = None,
|
||||
customer_email: Optional[str] = None,
|
||||
summary: Optional[str] = None,
|
||||
error_message: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Log a webhook event for audit trail."""
|
||||
try:
|
||||
doc_ref = self.db.collection(STRIPE_WEBHOOK_EVENTS_COLLECTION).document(event_id)
|
||||
data = {
|
||||
"event_id": event_id,
|
||||
"event_type": event_type,
|
||||
"created_at": datetime.utcnow(),
|
||||
"status": status,
|
||||
"session_id": session_id,
|
||||
"customer_email": customer_email,
|
||||
"summary": summary,
|
||||
"error_message": error_message,
|
||||
}
|
||||
if status in ("success", "error"):
|
||||
data["processed_at"] = datetime.utcnow()
|
||||
doc_ref.set(data, merge=True)
|
||||
except Exception:
|
||||
logger.exception(f"Error logging webhook event {event_id}")
|
||||
|
||||
def list_webhook_events(
|
||||
self,
|
||||
limit: int = 50,
|
||||
event_type: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""List recent webhook events."""
|
||||
try:
|
||||
collection = self.db.collection(STRIPE_WEBHOOK_EVENTS_COLLECTION)
|
||||
query = collection.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
|
||||
if event_type:
|
||||
query = collection.where("event_type", "==", event_type).order_by(
|
||||
"created_at", direction=firestore.Query.DESCENDING
|
||||
)
|
||||
|
||||
events = []
|
||||
for doc in query.limit(limit).stream():
|
||||
data = doc.to_dict()
|
||||
if status and data.get("status") != status:
|
||||
continue
|
||||
for key in ["created_at", "processed_at"]:
|
||||
if isinstance(data.get(key), datetime):
|
||||
data[key] = data[key].isoformat()
|
||||
events.append(data)
|
||||
|
||||
return events
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error listing webhook events")
|
||||
return []
|
||||
|
||||
|
||||
# Global instance
|
||||
_stripe_admin_service = None
|
||||
|
||||
|
||||
def get_stripe_admin_service() -> StripeAdminService:
|
||||
"""Get the global Stripe admin service instance."""
|
||||
global _stripe_admin_service
|
||||
if _stripe_admin_service is None:
|
||||
_stripe_admin_service = StripeAdminService()
|
||||
return _stripe_admin_service
|
||||
@@ -0,0 +1,291 @@
|
||||
"""
|
||||
Tests for admin payment API endpoints.
|
||||
|
||||
Tests cover:
|
||||
- Refund endpoint with credit deduction logic
|
||||
- Payment summary endpoint
|
||||
- Payment list endpoint
|
||||
- Payment detail endpoint (404 handling)
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
class TestRefundEndpoint:
|
||||
"""Tests for POST /api/admin/payments/{session_id}/refund."""
|
||||
|
||||
def test_full_refund_success(self, client):
|
||||
"""Test successful full refund."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 10,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund of $50.00 processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["success"] is True
|
||||
assert data["session_id"] == "cs_test"
|
||||
|
||||
# Verify credit deduction was called
|
||||
mock_us.add_credits.assert_called_once()
|
||||
call_kwargs = mock_us.add_credits.call_args[1]
|
||||
assert call_kwargs["email"] == "user@example.com"
|
||||
assert call_kwargs["amount"] == -10 # All credits deducted for full refund
|
||||
|
||||
def test_partial_refund_deducts_proportional_credits(self, client):
|
||||
"""Test that partial refund deducts proportional credits."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 10,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund of $25.00 processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"amount": 2500, "reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Proportional: 10 credits * (2500/5000) = 5 credits
|
||||
call_kwargs = mock_us.add_credits.call_args[1]
|
||||
assert call_kwargs["amount"] == -5
|
||||
|
||||
def test_made_for_you_refund_skips_credit_deduction(self, client):
|
||||
"""Test that made-for-you refund doesn't try to deduct credits."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_mfy",
|
||||
"order_type": "made_for_you",
|
||||
"credits_granted": 0,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_mfy/refund",
|
||||
json={"reason": "duplicate"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_us.add_credits.assert_not_called()
|
||||
|
||||
def test_refund_payment_not_found_returns_404(self, client):
|
||||
"""Test 404 when payment doesn't exist."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = None
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_nonexistent/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_refund_stripe_failure_returns_400(self, client):
|
||||
"""Test that Stripe refund failure returns 400."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 0,
|
||||
"amount_total": 5000,
|
||||
}
|
||||
mock_service.process_refund.return_value = (False, "Card declined")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Card declined" in response.json()["detail"]
|
||||
|
||||
def test_credit_deduction_failure_doesnt_fail_refund(self, client):
|
||||
"""Test that credit deduction failure doesn't roll back the refund."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"order_type": "credit_purchase",
|
||||
"credits_granted": 10,
|
||||
"amount_total": 5000,
|
||||
"customer_email": "user@example.com",
|
||||
}
|
||||
mock_service.process_refund.return_value = (True, "Refund processed")
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service), \
|
||||
patch("backend.api.routes.admin.get_user_service") as mock_user_svc:
|
||||
mock_us = Mock()
|
||||
mock_us.add_credits.side_effect = Exception("Firestore down")
|
||||
mock_user_svc.return_value = mock_us
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/payments/cs_test/refund",
|
||||
json={"reason": "requested_by_customer"},
|
||||
)
|
||||
|
||||
# Refund should still succeed
|
||||
assert response.status_code == 200
|
||||
assert response.json()["success"] is True
|
||||
|
||||
|
||||
class TestPaymentSummaryEndpoint:
|
||||
"""Tests for GET /api/admin/payments/summary."""
|
||||
|
||||
def test_returns_revenue_summary(self, client):
|
||||
"""Test that summary endpoint returns data."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_revenue_summary.return_value = {
|
||||
"total_gross": 10000,
|
||||
"total_fees": 350,
|
||||
"total_net": 9650,
|
||||
"total_refunds": 0,
|
||||
"transaction_count": 2,
|
||||
"average_order_value": 5000,
|
||||
"revenue_by_type": {"credit_purchase": 10000},
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments/summary?days=30")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total_gross"] == 10000
|
||||
assert data["transaction_count"] == 2
|
||||
|
||||
|
||||
class TestPaymentDetailEndpoint:
|
||||
"""Tests for GET /api/admin/payments/{session_id}."""
|
||||
|
||||
def test_returns_payment_detail(self, client):
|
||||
"""Test getting payment detail."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = {
|
||||
"session_id": "cs_test",
|
||||
"amount_total": 5000,
|
||||
"status": "succeeded",
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments/cs_test")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["session_id"] == "cs_test"
|
||||
|
||||
def test_returns_404_for_missing_payment(self, client):
|
||||
"""Test 404 when payment not found."""
|
||||
mock_service = Mock()
|
||||
mock_service.get_payment_detail.return_value = None
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments/cs_nonexistent")
|
||||
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestPaymentListEndpoint:
|
||||
"""Tests for GET /api/admin/payments."""
|
||||
|
||||
def test_returns_paginated_payments(self, client):
|
||||
"""Test payment list with pagination."""
|
||||
mock_service = Mock()
|
||||
mock_service.list_payments.return_value = {
|
||||
"payments": [
|
||||
{"session_id": "cs_1", "amount_total": 5000},
|
||||
{"session_id": "cs_2", "amount_total": 3000},
|
||||
],
|
||||
"total": 2,
|
||||
"has_more": False,
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get("/api/admin/payments?limit=50&offset=0")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["payments"]) == 2
|
||||
assert data["total"] == 2
|
||||
|
||||
def test_passes_filters_to_service(self, client):
|
||||
"""Test that query params are passed to service."""
|
||||
mock_service = Mock()
|
||||
mock_service.list_payments.return_value = {
|
||||
"payments": [],
|
||||
"total": 0,
|
||||
"has_more": False,
|
||||
}
|
||||
|
||||
with patch("backend.services.stripe_admin_service.get_stripe_admin_service", return_value=mock_service):
|
||||
response = client.get(
|
||||
"/api/admin/payments?order_type=credit_purchase&status=succeeded&email=user@example.com"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
mock_service.list_payments.assert_called_once()
|
||||
call_kwargs = mock_service.list_payments.call_args[1]
|
||||
assert call_kwargs["order_type"] == "credit_purchase"
|
||||
assert call_kwargs["status"] == "succeeded"
|
||||
assert call_kwargs["email"] == "user@example.com"
|
||||
@@ -0,0 +1,465 @@
|
||||
"""
|
||||
Unit tests for StripeAdminService.
|
||||
|
||||
Tests cover:
|
||||
- store_payment data extraction from expanded Checkout Sessions
|
||||
- process_refund validation and Stripe API interaction
|
||||
- get_revenue_summary aggregation and caching
|
||||
- update_payment_status
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def make_mock_firestore():
|
||||
"""Create a mock Firestore client with common patterns."""
|
||||
db = Mock()
|
||||
collection = Mock()
|
||||
doc_ref = Mock()
|
||||
db.collection.return_value = collection
|
||||
collection.document.return_value = doc_ref
|
||||
return db, collection, doc_ref
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service():
|
||||
"""Create a StripeAdminService with mocked dependencies."""
|
||||
with patch("backend.services.stripe_admin_service.get_settings") as mock_settings, \
|
||||
patch("backend.services.stripe_admin_service.firestore") as mock_fs:
|
||||
mock_settings.return_value = Mock()
|
||||
mock_fs.Client.return_value = Mock()
|
||||
from backend.services.stripe_admin_service import StripeAdminService
|
||||
svc = StripeAdminService()
|
||||
return svc
|
||||
|
||||
|
||||
class TestStorePayment:
|
||||
"""Tests for store_payment data extraction."""
|
||||
|
||||
def test_stores_expanded_session_correctly(self, service):
|
||||
"""Test extracting all fields from a fully expanded Checkout Session."""
|
||||
session = {
|
||||
"id": "cs_test_123",
|
||||
"amount_total": 5000,
|
||||
"currency": "usd",
|
||||
"livemode": True,
|
||||
"customer_email": "user@example.com",
|
||||
"customer": "cus_abc",
|
||||
"customer_details": {"name": "John Doe"},
|
||||
"metadata": {
|
||||
"order_type": "credit_purchase",
|
||||
"package_id": "10_credits",
|
||||
"credits": "10",
|
||||
"user_email": "user@example.com",
|
||||
},
|
||||
"total_details": {"amount_discount": 0},
|
||||
"payment_intent": {
|
||||
"id": "pi_test_456",
|
||||
"latest_charge": {
|
||||
"id": "ch_test_789",
|
||||
"payment_method_details": {
|
||||
"type": "card",
|
||||
"card": {"brand": "visa", "last4": "4242"},
|
||||
},
|
||||
"balance_transaction": {
|
||||
"fee": 175,
|
||||
"net": 4825,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
result = service.store_payment(session)
|
||||
|
||||
assert result is True
|
||||
# Verify Firestore was called
|
||||
service.db.collection.assert_called_with("stripe_payments")
|
||||
doc_ref = service.db.collection.return_value.document.return_value
|
||||
doc_ref.set.assert_called_once()
|
||||
|
||||
# Verify stored data
|
||||
stored = doc_ref.set.call_args[0][0]
|
||||
assert stored["session_id"] == "cs_test_123"
|
||||
assert stored["payment_intent_id"] == "pi_test_456"
|
||||
assert stored["charge_id"] == "ch_test_789"
|
||||
assert stored["amount_total"] == 5000
|
||||
assert stored["stripe_fee"] == 175
|
||||
assert stored["net_amount"] == 4825
|
||||
assert stored["customer_email"] == "user@example.com"
|
||||
assert stored["customer_name"] == "John Doe"
|
||||
assert stored["payment_method_type"] == "card"
|
||||
assert stored["card_brand"] == "visa"
|
||||
assert stored["card_last4"] == "4242"
|
||||
assert stored["order_type"] == "credit_purchase"
|
||||
assert stored["credits_granted"] == 10
|
||||
assert stored["status"] == "succeeded"
|
||||
assert stored["is_test"] is False
|
||||
assert stored["refund_amount"] == 0
|
||||
|
||||
def test_handles_unexpanded_payment_intent(self, service):
|
||||
"""Test storing when payment_intent is just a string ID (not expanded)."""
|
||||
session = {
|
||||
"id": "cs_test_abc",
|
||||
"amount_total": 3000,
|
||||
"currency": "usd",
|
||||
"livemode": False,
|
||||
"metadata": {"order_type": "credit_purchase", "credits": "5"},
|
||||
"payment_intent": "pi_string_only",
|
||||
}
|
||||
|
||||
result = service.store_payment(session)
|
||||
assert result is True
|
||||
|
||||
stored = service.db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert stored["payment_intent_id"] == "pi_string_only"
|
||||
assert stored["charge_id"] == ""
|
||||
assert stored["stripe_fee"] == 0
|
||||
assert stored["net_amount"] == 0
|
||||
assert stored["is_test"] is True
|
||||
|
||||
def test_handles_made_for_you_order(self, service):
|
||||
"""Test storing a made-for-you order with artist/title metadata."""
|
||||
session = {
|
||||
"id": "cs_mfy_123",
|
||||
"amount_total": 5000,
|
||||
"currency": "usd",
|
||||
"livemode": True,
|
||||
"metadata": {
|
||||
"order_type": "made_for_you",
|
||||
"artist": "Test Artist",
|
||||
"title": "Test Song",
|
||||
"customer_email": "buyer@example.com",
|
||||
"job_id": "job_abc",
|
||||
},
|
||||
"payment_intent": {"id": "pi_mfy", "latest_charge": "ch_string"},
|
||||
}
|
||||
|
||||
result = service.store_payment(session)
|
||||
assert result is True
|
||||
|
||||
stored = service.db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert stored["order_type"] == "made_for_you"
|
||||
assert stored["artist"] == "Test Artist"
|
||||
assert stored["title"] == "Test Song"
|
||||
assert stored["job_id"] == "job_abc"
|
||||
assert "Made For You" in stored["product_description"]
|
||||
|
||||
def test_handles_missing_metadata_gracefully(self, service):
|
||||
"""Test storing payment with minimal/missing data doesn't crash."""
|
||||
session = {
|
||||
"id": "cs_minimal",
|
||||
"amount_total": 1000,
|
||||
}
|
||||
|
||||
result = service.store_payment(session)
|
||||
assert result is True
|
||||
|
||||
stored = service.db.collection.return_value.document.return_value.set.call_args[0][0]
|
||||
assert stored["session_id"] == "cs_minimal"
|
||||
assert stored["amount_total"] == 1000
|
||||
assert stored["currency"] == "usd"
|
||||
assert stored["customer_email"] == ""
|
||||
|
||||
def test_returns_false_on_firestore_error(self, service):
|
||||
"""Test that Firestore errors are caught and return False."""
|
||||
service.db.collection.side_effect = Exception("Firestore down")
|
||||
|
||||
result = service.store_payment({"id": "cs_fail"})
|
||||
assert result is False
|
||||
|
||||
def test_invalidates_revenue_cache(self, service):
|
||||
"""Test that storing a payment invalidates the revenue cache."""
|
||||
service._revenue_cache = {"some": "data"}
|
||||
|
||||
session = {
|
||||
"id": "cs_cache_test",
|
||||
"amount_total": 1000,
|
||||
"metadata": {},
|
||||
"payment_intent": "pi_cache",
|
||||
}
|
||||
service.store_payment(session)
|
||||
assert service._revenue_cache is None
|
||||
|
||||
|
||||
class TestProcessRefund:
|
||||
"""Tests for process_refund logic."""
|
||||
|
||||
def _setup_payment_doc(self, service, data):
|
||||
"""Helper to set up a mock Firestore doc for refund tests."""
|
||||
doc_ref = Mock()
|
||||
doc = Mock()
|
||||
doc.exists = True
|
||||
doc.to_dict.return_value = data
|
||||
doc_ref.get.return_value = doc
|
||||
service.db.collection.return_value.document.return_value = doc_ref
|
||||
return doc_ref
|
||||
|
||||
def test_full_refund_success(self, service):
|
||||
"""Test full refund for a payment."""
|
||||
doc_ref = self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 0,
|
||||
})
|
||||
|
||||
with patch("backend.services.stripe_admin_service.stripe") as mock_stripe:
|
||||
mock_stripe.Refund.create.return_value = {"id": "re_test_123"}
|
||||
|
||||
success, message = service.process_refund("cs_test")
|
||||
|
||||
assert success is True
|
||||
assert "$50.00" in message
|
||||
mock_stripe.Refund.create.assert_called_once_with(
|
||||
payment_intent="pi_test",
|
||||
amount=5000,
|
||||
reason="requested_by_customer",
|
||||
)
|
||||
doc_ref.update.assert_called_once()
|
||||
update_data = doc_ref.update.call_args[0][0]
|
||||
assert update_data["status"] == "refunded"
|
||||
assert update_data["refund_amount"] == 5000
|
||||
|
||||
def test_partial_refund_success(self, service):
|
||||
"""Test partial refund."""
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 0,
|
||||
})
|
||||
|
||||
with patch("backend.services.stripe_admin_service.stripe") as mock_stripe:
|
||||
mock_stripe.Refund.create.return_value = {"id": "re_partial"}
|
||||
|
||||
success, message = service.process_refund("cs_test", amount=2500)
|
||||
|
||||
assert success is True
|
||||
assert "$25.00" in message
|
||||
doc_ref = service.db.collection.return_value.document.return_value
|
||||
update_data = doc_ref.update.call_args[0][0]
|
||||
assert update_data["status"] == "partially_refunded"
|
||||
assert update_data["refund_amount"] == 2500
|
||||
|
||||
def test_refund_after_partial_refund(self, service):
|
||||
"""Test refund on already partially refunded payment."""
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 2000,
|
||||
})
|
||||
|
||||
with patch("backend.services.stripe_admin_service.stripe") as mock_stripe:
|
||||
mock_stripe.Refund.create.return_value = {"id": "re_rest"}
|
||||
|
||||
success, message = service.process_refund("cs_test", amount=3000)
|
||||
|
||||
assert success is True
|
||||
doc_ref = service.db.collection.return_value.document.return_value
|
||||
update_data = doc_ref.update.call_args[0][0]
|
||||
assert update_data["status"] == "refunded"
|
||||
assert update_data["refund_amount"] == 5000
|
||||
|
||||
def test_refund_exceeding_original_fails(self, service):
|
||||
"""Test that refunding more than original amount fails."""
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 3000,
|
||||
})
|
||||
|
||||
success, message = service.process_refund("cs_test", amount=3000)
|
||||
|
||||
assert success is False
|
||||
assert "exceed" in message.lower()
|
||||
|
||||
def test_refund_payment_not_found(self, service):
|
||||
"""Test refund when payment doesn't exist."""
|
||||
doc = Mock()
|
||||
doc.exists = False
|
||||
service.db.collection.return_value.document.return_value.get.return_value = doc
|
||||
|
||||
success, message = service.process_refund("cs_nonexistent")
|
||||
|
||||
assert success is False
|
||||
assert "not found" in message.lower()
|
||||
|
||||
def test_refund_no_payment_intent_id(self, service):
|
||||
"""Test refund when payment has no payment_intent_id."""
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 0,
|
||||
})
|
||||
|
||||
success, message = service.process_refund("cs_test")
|
||||
|
||||
assert success is False
|
||||
assert "payment intent" in message.lower()
|
||||
|
||||
def test_refund_zero_amount_fails(self, service):
|
||||
"""Test that zero refund amount fails."""
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 5000, # Already fully refunded
|
||||
})
|
||||
|
||||
success, message = service.process_refund("cs_test")
|
||||
|
||||
assert success is False
|
||||
assert "invalid" in message.lower()
|
||||
|
||||
def test_stripe_error_handled(self, service):
|
||||
"""Test that Stripe API errors are caught and reported."""
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 0,
|
||||
})
|
||||
|
||||
with patch("backend.services.stripe_admin_service.stripe") as mock_stripe:
|
||||
mock_stripe.error.StripeError = Exception
|
||||
mock_stripe.Refund.create.side_effect = Exception("Card declined")
|
||||
|
||||
success, message = service.process_refund("cs_test")
|
||||
|
||||
assert success is False
|
||||
|
||||
def test_refund_invalidates_cache(self, service):
|
||||
"""Test that refund invalidates revenue cache."""
|
||||
service._revenue_cache = {"cached": True}
|
||||
self._setup_payment_doc(service, {
|
||||
"payment_intent_id": "pi_test",
|
||||
"amount_total": 5000,
|
||||
"refund_amount": 0,
|
||||
})
|
||||
|
||||
with patch("backend.services.stripe_admin_service.stripe") as mock_stripe:
|
||||
mock_stripe.Refund.create.return_value = {"id": "re_cache"}
|
||||
service.process_refund("cs_test")
|
||||
|
||||
assert service._revenue_cache is None
|
||||
|
||||
|
||||
class TestGetRevenueSummary:
|
||||
"""Tests for get_revenue_summary aggregation."""
|
||||
|
||||
def test_aggregates_correctly(self, service):
|
||||
"""Test revenue summary aggregation."""
|
||||
# Mock streaming docs
|
||||
docs = []
|
||||
for i, (amount, fee, net, refund, is_test, order_type) in enumerate([
|
||||
(5000, 175, 4825, 0, False, "credit_purchase"),
|
||||
(3000, 117, 2883, 0, False, "credit_purchase"),
|
||||
(5000, 175, 4825, 0, False, "made_for_you"),
|
||||
]):
|
||||
doc = Mock()
|
||||
doc.to_dict.return_value = {
|
||||
"amount_total": amount,
|
||||
"stripe_fee": fee,
|
||||
"net_amount": net,
|
||||
"refund_amount": refund,
|
||||
"is_test": is_test,
|
||||
"order_type": order_type,
|
||||
"created_at": datetime.utcnow(),
|
||||
}
|
||||
docs.append(doc)
|
||||
|
||||
query = Mock()
|
||||
query.stream.return_value = iter(docs)
|
||||
collection = Mock()
|
||||
collection.where.return_value = query
|
||||
service.db.collection.return_value = collection
|
||||
|
||||
result = service.get_revenue_summary(days=30, exclude_test=True)
|
||||
|
||||
assert result["total_gross"] == 13000
|
||||
assert result["total_fees"] == 467
|
||||
assert result["total_net"] == 12533
|
||||
assert result["transaction_count"] == 3
|
||||
assert result["average_order_value"] == round(13000 / 3)
|
||||
assert result["revenue_by_type"]["credit_purchase"] == 8000
|
||||
assert result["revenue_by_type"]["made_for_you"] == 5000
|
||||
|
||||
def test_excludes_test_transactions(self, service):
|
||||
"""Test that test transactions are excluded when flag is set."""
|
||||
docs = []
|
||||
for is_test in [False, True, False]:
|
||||
doc = Mock()
|
||||
doc.to_dict.return_value = {
|
||||
"amount_total": 1000,
|
||||
"stripe_fee": 0,
|
||||
"net_amount": 1000,
|
||||
"refund_amount": 0,
|
||||
"is_test": is_test,
|
||||
"order_type": "credit_purchase",
|
||||
}
|
||||
docs.append(doc)
|
||||
|
||||
query = Mock()
|
||||
query.stream.return_value = iter(docs)
|
||||
collection = Mock()
|
||||
collection.where.return_value = query
|
||||
service.db.collection.return_value = collection
|
||||
|
||||
result = service.get_revenue_summary(days=30, exclude_test=True)
|
||||
assert result["transaction_count"] == 2
|
||||
assert result["total_gross"] == 2000
|
||||
|
||||
def test_empty_collection_returns_zeros(self, service):
|
||||
"""Test revenue summary with no payments."""
|
||||
query = Mock()
|
||||
query.stream.return_value = iter([])
|
||||
collection = Mock()
|
||||
collection.where.return_value = query
|
||||
service.db.collection.return_value = collection
|
||||
|
||||
result = service.get_revenue_summary(days=30)
|
||||
|
||||
assert result["total_gross"] == 0
|
||||
assert result["transaction_count"] == 0
|
||||
assert result["average_order_value"] == 0
|
||||
|
||||
def test_uses_cache_within_ttl(self, service):
|
||||
"""Test that cached results are returned within TTL."""
|
||||
import time
|
||||
cached = {
|
||||
"_key": "30_True",
|
||||
"total_gross": 999,
|
||||
"transaction_count": 1,
|
||||
}
|
||||
service._revenue_cache = cached
|
||||
service._revenue_cache_time = time.time()
|
||||
|
||||
result = service.get_revenue_summary(days=30, exclude_test=True)
|
||||
|
||||
assert result == cached
|
||||
service.db.collection.assert_not_called()
|
||||
|
||||
|
||||
class TestUpdatePaymentStatus:
|
||||
"""Tests for update_payment_status."""
|
||||
|
||||
def test_updates_existing_payment(self, service):
|
||||
"""Test updating status of existing payment."""
|
||||
doc = Mock()
|
||||
doc.exists = True
|
||||
doc_ref = Mock()
|
||||
doc_ref.get.return_value = doc
|
||||
service.db.collection.return_value.document.return_value = doc_ref
|
||||
|
||||
result = service.update_payment_status("cs_test", {"status": "refunded"})
|
||||
|
||||
assert result is True
|
||||
doc_ref.update.assert_called_with({"status": "refunded"})
|
||||
|
||||
def test_returns_false_for_missing_payment(self, service):
|
||||
"""Test updating non-existent payment returns False."""
|
||||
doc = Mock()
|
||||
doc.exists = False
|
||||
service.db.collection.return_value.document.return_value.get.return_value = doc
|
||||
|
||||
result = service.update_payment_status("cs_missing", {"status": "refunded"})
|
||||
|
||||
assert result is False
|
||||
@@ -49,10 +49,14 @@ function AdminBreadcrumb() {
|
||||
breadcrumbs.push({ label: "Jobs", href: "/admin/jobs" })
|
||||
breadcrumbs.push({ label: decodeURIComponent(segments[2]) })
|
||||
}
|
||||
} else if (segments[1] === "payments") {
|
||||
breadcrumbs.push({ label: "Payments" })
|
||||
} else if (segments[1] === "searches") {
|
||||
breadcrumbs.push({ label: "Audio Searches" })
|
||||
} else if (segments[1] === "beta") {
|
||||
breadcrumbs.push({ label: "Beta Program" })
|
||||
} else if (segments[1] === "rate-limits") {
|
||||
breadcrumbs.push({ label: "Rate Limits" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { adminApi, AdminStatsOverview } from "@/lib/api"
|
||||
import { adminApi, AdminStatsOverview, RevenueSummary } from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Users,
|
||||
Briefcase,
|
||||
CreditCard,
|
||||
DollarSign,
|
||||
TestTube2,
|
||||
Clock,
|
||||
CheckCircle,
|
||||
@@ -22,6 +23,7 @@ import { Button } from "@/components/ui/button"
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const [stats, setStats] = useState<AdminStatsOverview | null>(null)
|
||||
const [revenue, setRevenue] = useState<RevenueSummary | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const { showTestData } = useAdminSettings()
|
||||
@@ -30,8 +32,12 @@ export default function AdminDashboardPage() {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
const data = await adminApi.getStats({ exclude_test: !showTestData })
|
||||
const [data, revenueData] = await Promise.all([
|
||||
adminApi.getStats({ exclude_test: !showTestData }),
|
||||
adminApi.getPaymentSummary({ days: 30, exclude_test: !showTestData }).catch(() => null),
|
||||
])
|
||||
setStats(data)
|
||||
setRevenue(revenueData)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "Failed to load statistics"
|
||||
setError(message)
|
||||
@@ -91,6 +97,14 @@ export default function AdminDashboardPage() {
|
||||
icon={Briefcase}
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Revenue (30d)"
|
||||
value={revenue ? `$${(revenue.total_gross / 100).toFixed(2)}` : "$0.00"}
|
||||
description={revenue ? `${revenue.transaction_count} payments, ${`$${(revenue.total_net / 100).toFixed(2)}`} net` : "Loading..."}
|
||||
icon={DollarSign}
|
||||
loading={loading}
|
||||
valueClassName="text-green-600 dark:text-green-400"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Credits Issued (30d)"
|
||||
value={stats?.total_credits_issued_30d ?? 0}
|
||||
|
||||
@@ -0,0 +1,845 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import {
|
||||
adminApi,
|
||||
RevenueSummary,
|
||||
RevenueChartPoint,
|
||||
PaymentRecord,
|
||||
PaymentListResponse,
|
||||
StripeBalance,
|
||||
PayoutRecord,
|
||||
DisputeRecord,
|
||||
WebhookEvent,
|
||||
} from "@/lib/api"
|
||||
import { useAdminSettings } from "@/lib/admin-settings"
|
||||
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
DollarSign,
|
||||
TrendingUp,
|
||||
CreditCard,
|
||||
Receipt,
|
||||
RefreshCw,
|
||||
Loader2,
|
||||
AlertTriangle,
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
Clock,
|
||||
ExternalLink,
|
||||
Search,
|
||||
Banknote,
|
||||
Webhook,
|
||||
ShieldAlert,
|
||||
} from "lucide-react"
|
||||
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"
|
||||
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, ResponsiveContainer, PieChart, Pie, Cell } from "recharts"
|
||||
import { PaymentDetailSheet } from "@/components/admin/payment-detail"
|
||||
import { RefundDialog } from "@/components/admin/refund-dialog"
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
function formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) return "-"
|
||||
return new Date(dateStr).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
function formatDateTime(dateStr?: string | null): string {
|
||||
if (!dateStr) return "-"
|
||||
return new Date(dateStr).toLocaleString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
function formatTimestamp(ts?: number | null): string {
|
||||
if (!ts) return "-"
|
||||
return new Date(ts * 1000).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
})
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const variants: Record<string, { variant: "default" | "secondary" | "destructive" | "outline"; label: string }> = {
|
||||
succeeded: { variant: "default", label: "Succeeded" },
|
||||
refunded: { variant: "destructive", label: "Refunded" },
|
||||
partially_refunded: { variant: "secondary", label: "Partial Refund" },
|
||||
disputed: { variant: "destructive", label: "Disputed" },
|
||||
processing: { variant: "secondary", label: "Processing" },
|
||||
success: { variant: "default", label: "Success" },
|
||||
error: { variant: "destructive", label: "Error" },
|
||||
skipped: { variant: "outline", label: "Skipped" },
|
||||
paid: { variant: "default", label: "Paid" },
|
||||
pending: { variant: "secondary", label: "Pending" },
|
||||
in_transit: { variant: "secondary", label: "In Transit" },
|
||||
canceled: { variant: "outline", label: "Canceled" },
|
||||
failed: { variant: "destructive", label: "Failed" },
|
||||
// Dispute statuses
|
||||
needs_response: { variant: "destructive", label: "Needs Response" },
|
||||
under_review: { variant: "secondary", label: "Under Review" },
|
||||
won: { variant: "default", label: "Won" },
|
||||
lost: { variant: "destructive", label: "Lost" },
|
||||
warning_needs_response: { variant: "destructive", label: "Needs Response" },
|
||||
warning_under_review: { variant: "secondary", label: "Under Review" },
|
||||
warning_closed: { variant: "outline", label: "Closed" },
|
||||
}
|
||||
const v = variants[status] || { variant: "outline" as const, label: status }
|
||||
return <Badge variant={v.variant}>{v.label}</Badge>
|
||||
}
|
||||
|
||||
function PaymentMethodDisplay({ type, brand, last4 }: { type: string; brand: string; last4: string }) {
|
||||
if (!type || type === "unknown") return <span className="text-muted-foreground">-</span>
|
||||
if (type === "card" && brand && last4) {
|
||||
return (
|
||||
<span className="text-sm">
|
||||
<span className="capitalize">{brand}</span> ...{last4}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return <span className="text-sm capitalize">{type.replace("_", " ")}</span>
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Revenue Overview Tab
|
||||
// =============================================================================
|
||||
|
||||
function RevenueOverviewTab() {
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [summary, setSummary] = useState<RevenueSummary | null>(null)
|
||||
const [chart, setChart] = useState<RevenueChartPoint[]>([])
|
||||
const [balance, setBalance] = useState<StripeBalance | null>(null)
|
||||
const [disputes, setDisputes] = useState<DisputeRecord[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [period, setPeriod] = useState(30)
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [summaryData, chartData, balanceData, disputeData] = await Promise.all([
|
||||
adminApi.getPaymentSummary({ days: period, exclude_test: !showTestData }),
|
||||
adminApi.getRevenueChart({ days: period, exclude_test: !showTestData }),
|
||||
adminApi.getStripeBalance(),
|
||||
adminApi.getDisputes(),
|
||||
])
|
||||
setSummary(summaryData)
|
||||
setChart(chartData)
|
||||
setBalance(balanceData)
|
||||
setDisputes(disputeData)
|
||||
} catch (err) {
|
||||
console.error("Failed to load revenue data:", err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [period, showTestData])
|
||||
|
||||
useEffect(() => { loadData() }, [loadData])
|
||||
|
||||
const openDisputes = disputes.filter(d => ["needs_response", "warning_needs_response", "under_review", "warning_under_review"].includes(d.status))
|
||||
|
||||
const chartConfig = {
|
||||
gross: { label: "Gross Revenue", color: "hsl(var(--chart-1))" },
|
||||
net: { label: "Net Revenue", color: "hsl(var(--chart-2))" },
|
||||
}
|
||||
|
||||
const pieData = summary?.revenue_by_type
|
||||
? Object.entries(summary.revenue_by_type).map(([type, amount]) => ({
|
||||
name: type === "credit_purchase" ? "Credits" : type === "made_for_you" ? "Made For You" : type,
|
||||
value: amount,
|
||||
}))
|
||||
: []
|
||||
const PIE_COLORS = ["hsl(var(--chart-1))", "hsl(var(--chart-2))", "hsl(var(--chart-3))"]
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Dispute Alert Banner */}
|
||||
{openDisputes.length > 0 && (
|
||||
<div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldAlert className="h-5 w-5 text-destructive" />
|
||||
<span className="font-medium text-destructive">
|
||||
{openDisputes.length} open dispute{openDisputes.length > 1 ? "s" : ""} requiring attention
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-2 space-y-1">
|
||||
{openDisputes.map(d => (
|
||||
<div key={d.id} className="text-sm text-muted-foreground">
|
||||
{formatCents(d.amount)} - {d.reason} - Evidence due {formatTimestamp(d.evidence_due_by)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Period selector */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Select value={String(period)} onValueChange={(v) => setPeriod(Number(v))}>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="7">Last 7 days</SelectItem>
|
||||
<SelectItem value="30">Last 30 days</SelectItem>
|
||||
<SelectItem value="90">Last 90 days</SelectItem>
|
||||
<SelectItem value="0">All time</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button variant="outline" size="sm" onClick={loadData} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
<StatsGrid>
|
||||
<StatsCard
|
||||
title="Total Revenue"
|
||||
value={summary ? formatCents(summary.total_gross) : "$0.00"}
|
||||
description={`${summary?.transaction_count ?? 0} transactions`}
|
||||
icon={DollarSign}
|
||||
loading={loading}
|
||||
valueClassName="text-green-600 dark:text-green-400"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Stripe Fees"
|
||||
value={summary ? formatCents(summary.total_fees) : "$0.00"}
|
||||
description={summary && summary.total_gross > 0 ? `${((summary.total_fees / summary.total_gross) * 100).toFixed(1)}% of gross` : ""}
|
||||
icon={Receipt}
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Net Revenue"
|
||||
value={summary ? formatCents(summary.total_net) : "$0.00"}
|
||||
description="After fees"
|
||||
icon={TrendingUp}
|
||||
loading={loading}
|
||||
valueClassName="text-green-600 dark:text-green-400"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Avg Order Value"
|
||||
value={summary ? formatCents(summary.average_order_value) : "$0.00"}
|
||||
description="Per transaction"
|
||||
icon={CreditCard}
|
||||
loading={loading}
|
||||
/>
|
||||
</StatsGrid>
|
||||
|
||||
{/* Charts */}
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{/* Revenue Chart */}
|
||||
<Card className="md:col-span-2">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Revenue Over Time</CardTitle>
|
||||
<CardDescription>Daily gross and net revenue</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loading ? (
|
||||
<Skeleton className="h-[250px] w-full" />
|
||||
) : chart.length > 0 ? (
|
||||
<ChartContainer config={chartConfig} className="h-[250px] w-full">
|
||||
<AreaChart data={chart}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis
|
||||
dataKey="date"
|
||||
tickFormatter={(v) => new Date(v).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
|
||||
fontSize={12}
|
||||
/>
|
||||
<YAxis
|
||||
tickFormatter={(v) => `$${(v / 100).toFixed(0)}`}
|
||||
fontSize={12}
|
||||
/>
|
||||
<ChartTooltip
|
||||
content={
|
||||
<ChartTooltipContent
|
||||
formatter={(value) => formatCents(value as number)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="gross"
|
||||
stroke="var(--color-gross)"
|
||||
fill="var(--color-gross)"
|
||||
fillOpacity={0.2}
|
||||
name="Gross"
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="net"
|
||||
stroke="var(--color-net)"
|
||||
fill="var(--color-net)"
|
||||
fillOpacity={0.2}
|
||||
name="Net"
|
||||
/>
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-[250px] text-muted-foreground">
|
||||
No revenue data for this period
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Revenue by Type + Balance */}
|
||||
<div className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">By Product</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loading ? (
|
||||
<Skeleton className="h-[100px]" />
|
||||
) : pieData.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{pieData.map((item, i) => (
|
||||
<div key={item.name} className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }}
|
||||
/>
|
||||
<span className="text-sm">{item.name}</span>
|
||||
</div>
|
||||
<span className="text-sm font-medium">{formatCents(item.value)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground">No data</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Stripe Balance</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loading ? (
|
||||
<Skeleton className="h-[60px]" />
|
||||
) : balance ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-sm text-muted-foreground">Available</span>
|
||||
<span className="text-sm font-medium text-green-600 dark:text-green-400">
|
||||
{formatCents(balance.available)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-sm text-muted-foreground">Pending</span>
|
||||
<span className="text-sm font-medium">{formatCents(balance.pending)}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground">Unable to load</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{summary && summary.total_refunds > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Refunds</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<span className="text-lg font-bold text-destructive">{formatCents(summary.total_refunds)}</span>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Transactions Tab
|
||||
// =============================================================================
|
||||
|
||||
function TransactionsTab() {
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [data, setData] = useState<PaymentListResponse>({ payments: [], total: 0, has_more: false })
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [filterType, setFilterType] = useState<string>("all")
|
||||
const [filterStatus, setFilterStatus] = useState<string>("all")
|
||||
const [emailSearch, setEmailSearch] = useState("")
|
||||
const [selectedPayment, setSelectedPayment] = useState<PaymentRecord | null>(null)
|
||||
const [refundPayment, setRefundPayment] = useState<PaymentRecord | null>(null)
|
||||
const limit = 50
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await adminApi.listPayments({
|
||||
limit,
|
||||
offset,
|
||||
order_type: filterType === "all" ? undefined : filterType,
|
||||
status: filterStatus === "all" ? undefined : filterStatus,
|
||||
email: emailSearch || undefined,
|
||||
exclude_test: !showTestData,
|
||||
})
|
||||
setData(result)
|
||||
} catch (err) {
|
||||
console.error("Failed to load payments:", err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [offset, filterType, filterStatus, emailSearch, showTestData])
|
||||
|
||||
useEffect(() => { loadData() }, [loadData])
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setOffset(0)
|
||||
loadData()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Filters */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Select value={filterType} onValueChange={(v) => { setFilterType(v); setOffset(0) }}>
|
||||
<SelectTrigger className="w-[160px]">
|
||||
<SelectValue placeholder="Order Type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Types</SelectItem>
|
||||
<SelectItem value="credit_purchase">Credit Purchase</SelectItem>
|
||||
<SelectItem value="made_for_you">Made For You</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={filterStatus} onValueChange={(v) => { setFilterStatus(v); setOffset(0) }}>
|
||||
<SelectTrigger className="w-[160px]">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Statuses</SelectItem>
|
||||
<SelectItem value="succeeded">Succeeded</SelectItem>
|
||||
<SelectItem value="refunded">Refunded</SelectItem>
|
||||
<SelectItem value="partially_refunded">Partial Refund</SelectItem>
|
||||
<SelectItem value="disputed">Disputed</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<form onSubmit={handleSearch} className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Search by email..."
|
||||
value={emailSearch}
|
||||
onChange={(e) => setEmailSearch(e.target.value)}
|
||||
className="w-[200px]"
|
||||
/>
|
||||
<Button type="submit" variant="outline" size="icon">
|
||||
<Search className="h-4 w-4" />
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={loadData} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
|
||||
<span className="text-sm text-muted-foreground ml-auto">
|
||||
{data.total} payment{data.total !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead>Customer</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Product</TableHead>
|
||||
<TableHead className="text-right">Amount</TableHead>
|
||||
<TableHead className="text-right">Fee</TableHead>
|
||||
<TableHead className="text-right">Net</TableHead>
|
||||
<TableHead>Method</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
Array.from({ length: 5 }).map((_, i) => (
|
||||
<TableRow key={i}>
|
||||
{Array.from({ length: 9 }).map((_, j) => (
|
||||
<TableCell key={j}><Skeleton className="h-4 w-16" /></TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : data.payments.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
|
||||
No payments found
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
data.payments.map((payment) => (
|
||||
<TableRow
|
||||
key={payment.session_id}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => setSelectedPayment(payment)}
|
||||
>
|
||||
<TableCell className="text-sm">{formatDate(payment.created_at)}</TableCell>
|
||||
<TableCell className="text-sm max-w-[160px] truncate">{payment.customer_email}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{payment.order_type === "made_for_you" ? "MFY" : "Credits"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm max-w-[140px] truncate">{payment.product_description}</TableCell>
|
||||
<TableCell className="text-right text-sm font-medium">{formatCents(payment.amount_total)}</TableCell>
|
||||
<TableCell className="text-right text-sm text-muted-foreground">{formatCents(payment.stripe_fee)}</TableCell>
|
||||
<TableCell className="text-right text-sm">{formatCents(payment.net_amount)}</TableCell>
|
||||
<TableCell>
|
||||
<PaymentMethodDisplay
|
||||
type={payment.payment_method_type}
|
||||
brand={payment.card_brand}
|
||||
last4={payment.card_last4}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell><StatusBadge status={payment.status} /></TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{data.total > limit && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Showing {offset + 1}-{Math.min(offset + limit, data.total)} of {data.total}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setOffset(Math.max(0, offset - limit))}
|
||||
disabled={offset === 0}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setOffset(offset + limit)}
|
||||
disabled={!data.has_more}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Payment Detail Sheet */}
|
||||
<PaymentDetailSheet
|
||||
payment={selectedPayment}
|
||||
onClose={() => setSelectedPayment(null)}
|
||||
onRefund={(payment) => {
|
||||
setSelectedPayment(null)
|
||||
setRefundPayment(payment)
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Refund Dialog */}
|
||||
<RefundDialog
|
||||
payment={refundPayment}
|
||||
onClose={() => setRefundPayment(null)}
|
||||
onSuccess={() => {
|
||||
setRefundPayment(null)
|
||||
loadData()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Payouts Tab
|
||||
// =============================================================================
|
||||
|
||||
function PayoutsTab() {
|
||||
const [balance, setBalance] = useState<StripeBalance | null>(null)
|
||||
const [payouts, setPayouts] = useState<PayoutRecord[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [balanceData, payoutData] = await Promise.all([
|
||||
adminApi.getStripeBalance(),
|
||||
adminApi.getPayouts(20),
|
||||
])
|
||||
setBalance(balanceData)
|
||||
setPayouts(payoutData)
|
||||
} catch (err) {
|
||||
console.error("Failed to load payouts:", err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => { loadData() }, [loadData])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Balance */}
|
||||
<StatsGrid columns={3}>
|
||||
<StatsCard
|
||||
title="Available Balance"
|
||||
value={balance ? formatCents(balance.available) : "$0.00"}
|
||||
description="Ready for payout"
|
||||
icon={Banknote}
|
||||
loading={loading}
|
||||
valueClassName="text-green-600 dark:text-green-400"
|
||||
/>
|
||||
<StatsCard
|
||||
title="Pending Balance"
|
||||
value={balance ? formatCents(balance.pending) : "$0.00"}
|
||||
description="Processing"
|
||||
icon={Clock}
|
||||
loading={loading}
|
||||
/>
|
||||
<StatsCard
|
||||
title="Recent Payouts"
|
||||
value={payouts.length}
|
||||
description="Shown below"
|
||||
icon={DollarSign}
|
||||
loading={loading}
|
||||
/>
|
||||
</StatsGrid>
|
||||
|
||||
{/* Payouts Table */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Payout History</CardTitle>
|
||||
<CardDescription>When money hits the bank account</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead className="text-right">Amount</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Arrival</TableHead>
|
||||
<TableHead>Method</TableHead>
|
||||
<TableHead>ID</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
Array.from({ length: 5 }).map((_, i) => (
|
||||
<TableRow key={i}>
|
||||
{Array.from({ length: 6 }).map((_, j) => (
|
||||
<TableCell key={j}><Skeleton className="h-4 w-16" /></TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : payouts.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
|
||||
No payouts found
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
payouts.map((payout) => (
|
||||
<TableRow key={payout.id}>
|
||||
<TableCell className="text-sm">{formatTimestamp(payout.created)}</TableCell>
|
||||
<TableCell className="text-right text-sm font-medium">{formatCents(payout.amount)}</TableCell>
|
||||
<TableCell><StatusBadge status={payout.status} /></TableCell>
|
||||
<TableCell className="text-sm">{formatTimestamp(payout.arrival_date)}</TableCell>
|
||||
<TableCell className="text-sm capitalize">{payout.method || "-"}</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground font-mono">{payout.id.slice(-8)}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Webhook Events Tab
|
||||
// =============================================================================
|
||||
|
||||
function WebhookEventsTab() {
|
||||
const [events, setEvents] = useState<WebhookEvent[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [filterType, setFilterType] = useState<string>("all")
|
||||
const [filterStatus, setFilterStatus] = useState<string>("all")
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await adminApi.getWebhookEvents({
|
||||
limit: 100,
|
||||
event_type: filterType === "all" ? undefined : filterType,
|
||||
status: filterStatus === "all" ? undefined : filterStatus,
|
||||
})
|
||||
setEvents(data)
|
||||
} catch (err) {
|
||||
console.error("Failed to load webhook events:", err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [filterType, filterStatus])
|
||||
|
||||
useEffect(() => { loadData() }, [loadData])
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Select value={filterType} onValueChange={setFilterType}>
|
||||
<SelectTrigger className="w-[240px]">
|
||||
<SelectValue placeholder="Event Type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All Events</SelectItem>
|
||||
<SelectItem value="checkout.session.completed">checkout.session.completed</SelectItem>
|
||||
<SelectItem value="charge.refunded">charge.refunded</SelectItem>
|
||||
<SelectItem value="charge.dispute.created">charge.dispute.created</SelectItem>
|
||||
<SelectItem value="payment_intent.payment_failed">payment_intent.payment_failed</SelectItem>
|
||||
<SelectItem value="checkout.session.expired">checkout.session.expired</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={filterStatus} onValueChange={setFilterStatus}>
|
||||
<SelectTrigger className="w-[140px]">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All</SelectItem>
|
||||
<SelectItem value="success">Success</SelectItem>
|
||||
<SelectItem value="error">Error</SelectItem>
|
||||
<SelectItem value="skipped">Skipped</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Button variant="outline" size="sm" onClick={loadData} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Time</TableHead>
|
||||
<TableHead>Event Type</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Customer</TableHead>
|
||||
<TableHead>Summary</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
Array.from({ length: 5 }).map((_, i) => (
|
||||
<TableRow key={i}>
|
||||
{Array.from({ length: 5 }).map((_, j) => (
|
||||
<TableCell key={j}><Skeleton className="h-4 w-20" /></TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : events.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
|
||||
No webhook events found
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
events.map((event) => (
|
||||
<TableRow key={event.event_id}>
|
||||
<TableCell className="text-sm">{formatDateTime(event.created_at)}</TableCell>
|
||||
<TableCell className="text-xs font-mono">{event.event_type}</TableCell>
|
||||
<TableCell><StatusBadge status={event.status} /></TableCell>
|
||||
<TableCell className="text-sm max-w-[160px] truncate">{event.customer_email || "-"}</TableCell>
|
||||
<TableCell className="text-sm max-w-[240px] truncate">{event.summary || "-"}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Main Page
|
||||
// =============================================================================
|
||||
|
||||
export default function PaymentsPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Payments</h1>
|
||||
<p className="text-muted-foreground">Revenue analytics, transactions, and Stripe management</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="overview">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview">Revenue</TabsTrigger>
|
||||
<TabsTrigger value="transactions">Transactions</TabsTrigger>
|
||||
<TabsTrigger value="payouts">Payouts</TabsTrigger>
|
||||
<TabsTrigger value="events">Webhook Events</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="overview">
|
||||
<RevenueOverviewTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="transactions">
|
||||
<TransactionsTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="payouts">
|
||||
<PayoutsTab />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="events">
|
||||
<WebhookEventsTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useSearchParams, useRouter } from "next/navigation"
|
||||
import { adminApi, AdminUserDetail } from "@/lib/api"
|
||||
import { adminApi, AdminUserDetail, UserPaymentHistory } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
Briefcase,
|
||||
Clock,
|
||||
Trash2,
|
||||
DollarSign,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
@@ -57,6 +58,8 @@ export default function AdminUserDetailPage() {
|
||||
const [user, setUser] = useState<AdminUserDetail | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [actionLoading, setActionLoading] = useState(false)
|
||||
const [paymentHistory, setPaymentHistory] = useState<UserPaymentHistory | null>(null)
|
||||
const [paymentsLoading, setPaymentsLoading] = useState(false)
|
||||
|
||||
// Delete dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
@@ -87,8 +90,22 @@ export default function AdminUserDetailPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const loadPayments = async () => {
|
||||
if (!email) return
|
||||
try {
|
||||
setPaymentsLoading(true)
|
||||
const data = await adminApi.getUserPayments(email)
|
||||
setPaymentHistory(data)
|
||||
} catch (err) {
|
||||
console.error("Failed to load payment history:", err)
|
||||
} finally {
|
||||
setPaymentsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadUser()
|
||||
loadPayments()
|
||||
}, [email])
|
||||
|
||||
const handleAddCredits = async () => {
|
||||
@@ -389,6 +406,88 @@ export default function AdminUserDetailPage() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Payment History */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<DollarSign className="w-5 h-5" />
|
||||
Payment History
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{paymentHistory ? (
|
||||
<>
|
||||
{paymentHistory.payment_count} payment{paymentHistory.payment_count !== 1 ? "s" : ""} - Lifetime spend: ${(paymentHistory.total_spent / 100).toFixed(2)}
|
||||
{paymentHistory.total_refunded > 0 && (
|
||||
<> (${(paymentHistory.total_refunded / 100).toFixed(2)} refunded)</>
|
||||
)}
|
||||
</>
|
||||
) : paymentsLoading ? (
|
||||
"Loading..."
|
||||
) : (
|
||||
"No payment data"
|
||||
)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{paymentsLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : !paymentHistory || paymentHistory.payments.length === 0 ? (
|
||||
<p className="text-muted-foreground text-sm">No payments found</p>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>Product</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paymentHistory.payments.map((p) => (
|
||||
<TableRow
|
||||
key={p.session_id}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => router.push(`/admin/payments?tab=transactions&email=${encodeURIComponent(p.customer_email)}`)}
|
||||
>
|
||||
<TableCell className="text-sm">
|
||||
{p.created_at ? new Date(p.created_at).toLocaleDateString() : "-"}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm font-medium">
|
||||
${(p.amount_total / 100).toFixed(2)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{p.order_type === "made_for_you" ? "MFY" : "Credits"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm max-w-[160px] truncate">
|
||||
{p.product_description}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={
|
||||
p.status === "succeeded" ? "default" :
|
||||
p.status === "refunded" ? "destructive" :
|
||||
"secondary"
|
||||
}>
|
||||
{p.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Recent Jobs */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
LayoutDashboard,
|
||||
Users,
|
||||
Briefcase,
|
||||
DollarSign,
|
||||
TestTube2,
|
||||
ArrowLeft,
|
||||
Settings,
|
||||
@@ -43,6 +44,11 @@ const navItems = [
|
||||
href: "/admin/jobs",
|
||||
icon: Briefcase,
|
||||
},
|
||||
{
|
||||
title: "Payments",
|
||||
href: "/admin/payments",
|
||||
icon: DollarSign,
|
||||
},
|
||||
{
|
||||
title: "Audio Searches",
|
||||
href: "/admin/searches",
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { adminApi, PaymentRecord } from "@/lib/api"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { ExternalLink, Receipt, Undo2, Loader2 } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
function formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) return "-"
|
||||
return new Date(dateStr).toLocaleString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const variants: Record<string, { variant: "default" | "secondary" | "destructive" | "outline"; label: string }> = {
|
||||
succeeded: { variant: "default", label: "Succeeded" },
|
||||
refunded: { variant: "destructive", label: "Refunded" },
|
||||
partially_refunded: { variant: "secondary", label: "Partial Refund" },
|
||||
disputed: { variant: "destructive", label: "Disputed" },
|
||||
}
|
||||
const v = variants[status] || { variant: "outline" as const, label: status }
|
||||
return <Badge variant={v.variant}>{v.label}</Badge>
|
||||
}
|
||||
|
||||
function DetailRow({ label, value, mono }: { label: string; value: React.ReactNode; mono?: boolean }) {
|
||||
return (
|
||||
<div className="flex justify-between items-start py-1">
|
||||
<span className="text-sm text-muted-foreground">{label}</span>
|
||||
<span className={`text-sm text-right max-w-[200px] truncate ${mono ? "font-mono text-xs" : ""}`}>
|
||||
{value || "-"}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface PaymentDetailSheetProps {
|
||||
payment: PaymentRecord | null
|
||||
onClose: () => void
|
||||
onRefund: (payment: PaymentRecord) => void
|
||||
}
|
||||
|
||||
export function PaymentDetailSheet({ payment, onClose, onRefund }: PaymentDetailSheetProps) {
|
||||
const [detail, setDetail] = useState<PaymentRecord | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!payment) {
|
||||
setDetail(null)
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
adminApi.getPaymentDetail(payment.session_id)
|
||||
.then(setDetail)
|
||||
.catch(() => setDetail(payment))
|
||||
.finally(() => setLoading(false))
|
||||
}, [payment])
|
||||
|
||||
const data = detail || payment
|
||||
const canRefund = data && data.status === "succeeded" && data.refund_amount < data.amount_total
|
||||
|
||||
return (
|
||||
<Sheet open={!!payment} onOpenChange={(open) => !open && onClose()}>
|
||||
<SheetContent className="overflow-y-auto">
|
||||
<SheetHeader>
|
||||
<SheetTitle>Payment Details</SheetTitle>
|
||||
<SheetDescription>
|
||||
{data?.product_description || "Payment"}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-4 mt-6">
|
||||
{Array.from({ length: 8 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-6 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : data ? (
|
||||
<div className="space-y-6 mt-6">
|
||||
{/* Status & Amount */}
|
||||
<div className="text-center space-y-2">
|
||||
<div className="text-3xl font-bold">{formatCents(data.amount_total)}</div>
|
||||
<StatusBadge status={data.status} />
|
||||
{data.refund_amount > 0 && (
|
||||
<div className="text-sm text-destructive">
|
||||
Refunded: {formatCents(data.refund_amount)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Customer */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-2">Customer</h4>
|
||||
<DetailRow label="Email" value={
|
||||
<Link
|
||||
href={`/admin/users/detail?email=${encodeURIComponent(data.customer_email)}`}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
{data.customer_email}
|
||||
</Link>
|
||||
} />
|
||||
<DetailRow label="Name" value={data.customer_name} />
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Financial */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-2">Financial</h4>
|
||||
<DetailRow label="Gross" value={formatCents(data.amount_total)} />
|
||||
<DetailRow label="Stripe Fee" value={formatCents(data.stripe_fee)} />
|
||||
<DetailRow label="Net" value={formatCents(data.net_amount)} />
|
||||
{data.discount_amount > 0 && (
|
||||
<DetailRow label="Discount" value={formatCents(data.discount_amount)} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Payment Method */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-2">Payment Method</h4>
|
||||
<DetailRow label="Type" value={
|
||||
<span className="capitalize">{data.payment_method_type?.replace("_", " ") || "-"}</span>
|
||||
} />
|
||||
{data.card_brand && <DetailRow label="Card" value={`${data.card_brand} ...${data.card_last4}`} />}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Order Details */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-2">Order</h4>
|
||||
<DetailRow label="Type" value={
|
||||
data.order_type === "made_for_you" ? "Made For You" : "Credit Purchase"
|
||||
} />
|
||||
<DetailRow label="Product" value={data.product_description} />
|
||||
{data.credits_granted > 0 && (
|
||||
<DetailRow label="Credits" value={data.credits_granted} />
|
||||
)}
|
||||
{data.artist && <DetailRow label="Song" value={`${data.artist} - ${data.title}`} />}
|
||||
{data.job_id && <DetailRow label="Job ID" value={data.job_id} mono />}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Timestamps */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-2">Timestamps</h4>
|
||||
<DetailRow label="Created" value={formatDate(data.created_at)} />
|
||||
<DetailRow label="Processed" value={formatDate(data.processed_at)} />
|
||||
{data.refunded_at && (
|
||||
<DetailRow label="Refunded" value={formatDate(data.refunded_at)} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* IDs */}
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-2">Stripe IDs</h4>
|
||||
<DetailRow label="Session" value={data.session_id} mono />
|
||||
<DetailRow label="Payment Intent" value={data.payment_intent_id} mono />
|
||||
<DetailRow label="Charge" value={data.charge_id} mono />
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-col gap-2 pt-2">
|
||||
{data.stripe_dashboard_url && (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={data.stripe_dashboard_url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="w-4 h-4 mr-2" />
|
||||
View in Stripe
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
{data.receipt_url && (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={data.receipt_url} target="_blank" rel="noopener noreferrer">
|
||||
<Receipt className="w-4 h-4 mr-2" />
|
||||
View Receipt
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
{canRefund && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => onRefund(data)}
|
||||
>
|
||||
<Undo2 className="w-4 h-4 mr-2" />
|
||||
Issue Refund
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { adminApi, PaymentRecord } from "@/lib/api"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { AlertTriangle, Loader2 } from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
interface RefundDialogProps {
|
||||
payment: PaymentRecord | null
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function RefundDialog({ payment, onClose, onSuccess }: RefundDialogProps) {
|
||||
const [isPartial, setIsPartial] = useState(false)
|
||||
const [amount, setAmount] = useState("")
|
||||
const [reason, setReason] = useState("requested_by_customer")
|
||||
const [processing, setProcessing] = useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
if (!payment) return null
|
||||
|
||||
const maxRefundable = payment.amount_total - (payment.refund_amount || 0)
|
||||
const refundAmount = isPartial ? Math.round(parseFloat(amount || "0") * 100) : maxRefundable
|
||||
const isValid = refundAmount > 0 && refundAmount <= maxRefundable
|
||||
|
||||
const creditsAtRisk = payment.order_type === "credit_purchase" && payment.credits_granted > 0
|
||||
? Math.floor(payment.credits_granted * (refundAmount / payment.amount_total))
|
||||
: 0
|
||||
|
||||
const handleRefund = async () => {
|
||||
if (!isValid) return
|
||||
setProcessing(true)
|
||||
try {
|
||||
const result = await adminApi.refundPayment(payment.session_id, {
|
||||
amount: isPartial ? refundAmount : undefined,
|
||||
reason,
|
||||
})
|
||||
toast({
|
||||
title: "Refund processed",
|
||||
description: result.message,
|
||||
})
|
||||
onSuccess()
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Refund failed"
|
||||
toast({
|
||||
title: "Refund failed",
|
||||
description: message,
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setProcessing(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog open={!!payment} onOpenChange={(open) => !open && onClose()}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Issue Refund</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Refund for {payment.customer_email} - {payment.product_description}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* Payment Summary */}
|
||||
<div className="rounded-lg border p-3 space-y-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Original amount</span>
|
||||
<span className="font-medium">{formatCents(payment.amount_total)}</span>
|
||||
</div>
|
||||
{payment.refund_amount > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Already refunded</span>
|
||||
<span className="text-destructive">{formatCents(payment.refund_amount)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between text-sm font-medium">
|
||||
<span>Max refundable</span>
|
||||
<span>{formatCents(maxRefundable)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Partial toggle */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="partial-refund"
|
||||
checked={isPartial}
|
||||
onCheckedChange={setIsPartial}
|
||||
/>
|
||||
<Label htmlFor="partial-refund">Partial refund</Label>
|
||||
</div>
|
||||
|
||||
{/* Amount input */}
|
||||
{isPartial && (
|
||||
<div className="space-y-2">
|
||||
<Label>Refund amount ($)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
max={(maxRefundable / 100).toFixed(2)}
|
||||
placeholder={(maxRefundable / 100).toFixed(2)}
|
||||
value={amount}
|
||||
onChange={(e) => setAmount(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Reason */}
|
||||
<div className="space-y-2">
|
||||
<Label>Reason</Label>
|
||||
<Select value={reason} onValueChange={setReason}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="requested_by_customer">Requested by customer</SelectItem>
|
||||
<SelectItem value="duplicate">Duplicate payment</SelectItem>
|
||||
<SelectItem value="fraudulent">Fraudulent</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Credit deduction warning */}
|
||||
{creditsAtRisk > 0 && (
|
||||
<div className="rounded-lg border border-yellow-500/50 bg-yellow-500/10 p-3 flex gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-yellow-500 mt-0.5 shrink-0" />
|
||||
<div className="text-sm">
|
||||
<span className="font-medium">Credit deduction:</span>{" "}
|
||||
{creditsAtRisk} credit{creditsAtRisk !== 1 ? "s" : ""} will be
|
||||
deducted from {payment.customer_email}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Refund summary */}
|
||||
{isValid && (
|
||||
<div className="rounded-lg bg-muted p-3 text-center">
|
||||
<span className="text-lg font-bold text-destructive">
|
||||
Refund {formatCents(refundAmount)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={processing}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleRefund}
|
||||
disabled={!isValid || processing}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{processing && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Process Refund
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { test, expect, Page } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Admin Payments Production Tests
|
||||
*
|
||||
* Tests the admin payments dashboard functionality on live production.
|
||||
* Requires KARAOKE_ADMIN_TOKEN environment variable with admin privileges.
|
||||
*
|
||||
* Run with:
|
||||
* KARAOKE_ADMIN_TOKEN=xxx npx playwright test e2e/production/admin-payments.spec.ts --reporter=list
|
||||
*/
|
||||
|
||||
const PROD_URL = "https://gen.nomadkaraoke.com";
|
||||
const API_URL = "https://api.nomadkaraoke.com";
|
||||
|
||||
function getAdminToken(): string | null {
|
||||
return process.env.KARAOKE_ADMIN_TOKEN || process.env.KARAOKE_ACCESS_TOKEN || null;
|
||||
}
|
||||
|
||||
async function validateAdminToken(
|
||||
token: string
|
||||
): Promise<{ isAdmin: boolean; email?: string; error?: string }> {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/api/users/me`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (!response.ok) {
|
||||
return { isAdmin: false, error: `API returned ${response.status}` };
|
||||
}
|
||||
const data = (await response.json()) as { user: { email: string; role: string } };
|
||||
const isAdmin =
|
||||
data.user?.role === "admin" || data.user?.email?.endsWith("@nomadkaraoke.com");
|
||||
return { isAdmin, email: data.user?.email };
|
||||
} catch (err) {
|
||||
return { isAdmin: false, error: `Failed to validate token: ${err}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function authenticatePage(page: Page, token: string): Promise<void> {
|
||||
await page.addInitScript((t) => {
|
||||
localStorage.setItem("karaoke_access_token", t);
|
||||
}, token);
|
||||
}
|
||||
|
||||
let adminToken: string | null = null;
|
||||
let tokenValidation: { isAdmin: boolean; email?: string; error?: string } | null = null;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
adminToken = getAdminToken();
|
||||
if (adminToken) {
|
||||
tokenValidation = await validateAdminToken(adminToken);
|
||||
if (!tokenValidation.isAdmin) {
|
||||
console.log(`⚠️ Token validation failed: ${tokenValidation.error}`);
|
||||
} else {
|
||||
console.log(`✓ Admin token validated for ${tokenValidation.email}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test.describe("Admin Payments Page - Production", () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
test.skip(!adminToken || !tokenValidation?.isAdmin, "Skipping: No valid admin token available");
|
||||
await authenticatePage(page, adminToken!);
|
||||
});
|
||||
|
||||
test("payments page loads with revenue tab", async ({ page }) => {
|
||||
await page.goto(`${PROD_URL}/admin/payments`);
|
||||
|
||||
// Wait for the page heading
|
||||
await expect(page.locator("h1")).toContainText("Payments", { timeout: 30000 });
|
||||
|
||||
// Revenue tab should be visible (default tab)
|
||||
await expect(page.getByText("Revenue")).toBeVisible();
|
||||
await expect(page.getByText("Transactions")).toBeVisible();
|
||||
await expect(page.getByText("Payouts")).toBeVisible();
|
||||
});
|
||||
|
||||
test("payments page shows revenue stats", async ({ page }) => {
|
||||
await page.goto(`${PROD_URL}/admin/payments`);
|
||||
|
||||
await expect(page.locator("h1")).toContainText("Payments", { timeout: 30000 });
|
||||
|
||||
// Check for key revenue metrics
|
||||
await expect(page.getByText("Total Revenue")).toBeVisible({ timeout: 15000 });
|
||||
await expect(page.getByText("Stripe Fees")).toBeVisible();
|
||||
await expect(page.getByText("Net Revenue")).toBeVisible();
|
||||
});
|
||||
|
||||
test("sidebar has payments link", async ({ page }) => {
|
||||
await page.goto(`${PROD_URL}/admin`);
|
||||
|
||||
await expect(page.locator("h1")).toContainText("Dashboard", { timeout: 30000 });
|
||||
|
||||
// Click Payments in sidebar
|
||||
await page.getByRole("link", { name: /Payments/i }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/payments/);
|
||||
await expect(page.locator("h1")).toContainText("Payments");
|
||||
});
|
||||
|
||||
test("transactions tab shows table", async ({ page }) => {
|
||||
await page.goto(`${PROD_URL}/admin/payments`);
|
||||
|
||||
await expect(page.locator("h1")).toContainText("Payments", { timeout: 30000 });
|
||||
|
||||
// Click transactions tab
|
||||
await page.getByRole("tab", { name: /Transactions/i }).click();
|
||||
|
||||
// Should show table or empty state
|
||||
const hasTable = await page.getByRole("table").isVisible().catch(() => false);
|
||||
const hasEmpty = await page.getByText(/no payments/i).isVisible().catch(() => false);
|
||||
|
||||
expect(hasTable || hasEmpty).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Admin Payments API - Production", () => {
|
||||
test.beforeEach(async () => {
|
||||
test.skip(!adminToken || !tokenValidation?.isAdmin, "Skipping: No valid admin token available");
|
||||
});
|
||||
|
||||
test("payment summary endpoint returns data", async ({ request }) => {
|
||||
const response = await request.get(`${API_URL}/api/admin/payments/summary?days=30`, {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(response.status()).toBe(200);
|
||||
|
||||
const data = await response.json();
|
||||
expect(data).toHaveProperty("total_gross");
|
||||
expect(data).toHaveProperty("total_fees");
|
||||
expect(data).toHaveProperty("total_net");
|
||||
expect(data).toHaveProperty("transaction_count");
|
||||
expect(typeof data.total_gross).toBe("number");
|
||||
|
||||
console.log(
|
||||
`Revenue (30d): $${(data.total_gross / 100).toFixed(2)} gross, ` +
|
||||
`${data.transaction_count} transactions`
|
||||
);
|
||||
});
|
||||
|
||||
test("payment list endpoint returns data", async ({ request }) => {
|
||||
const response = await request.get(`${API_URL}/api/admin/payments?limit=5`, {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(response.status()).toBe(200);
|
||||
|
||||
const data = await response.json();
|
||||
expect(data).toHaveProperty("payments");
|
||||
expect(data).toHaveProperty("total");
|
||||
expect(Array.isArray(data.payments)).toBe(true);
|
||||
|
||||
console.log(`Payments: ${data.total} total, fetched ${data.payments.length}`);
|
||||
});
|
||||
|
||||
test("balance endpoint returns data", async ({ request }) => {
|
||||
const response = await request.get(`${API_URL}/api/admin/payments/balance`, {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(response.status()).toBe(200);
|
||||
|
||||
const data = await response.json();
|
||||
expect(data).toHaveProperty("available");
|
||||
expect(data).toHaveProperty("pending");
|
||||
expect(typeof data.available).toBe("number");
|
||||
});
|
||||
|
||||
test("webhook events endpoint returns data", async ({ request }) => {
|
||||
const response = await request.get(`${API_URL}/api/admin/payments/webhook-events?limit=5`, {
|
||||
headers: { Authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
|
||||
expect(response.status()).toBe(200);
|
||||
|
||||
const data = await response.json();
|
||||
expect(Array.isArray(data)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -2006,6 +2006,111 @@ export const adminApi = {
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
// =========================================================================
|
||||
// Payments API
|
||||
// =========================================================================
|
||||
|
||||
async getPaymentSummary(params?: { days?: number; exclude_test?: boolean }): Promise<RevenueSummary> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.days) searchParams.set('days', String(params.days));
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
const url = `${API_BASE_URL}/api/admin/payments/summary${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, { headers: getAuthHeaders() });
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getRevenueChart(params?: { days?: number; group_by?: string; exclude_test?: boolean }): Promise<RevenueChartPoint[]> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.days) searchParams.set('days', String(params.days));
|
||||
if (params?.group_by) searchParams.set('group_by', params.group_by);
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
const url = `${API_BASE_URL}/api/admin/payments/revenue-chart${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, { headers: getAuthHeaders() });
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async listPayments(params?: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
order_type?: string;
|
||||
status?: string;
|
||||
email?: string;
|
||||
exclude_test?: boolean;
|
||||
}): Promise<PaymentListResponse> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.offset) searchParams.set('offset', String(params.offset));
|
||||
if (params?.order_type) searchParams.set('order_type', params.order_type);
|
||||
if (params?.status) searchParams.set('status', params.status);
|
||||
if (params?.email) searchParams.set('email', params.email);
|
||||
if (params?.exclude_test !== undefined) searchParams.set('exclude_test', String(params.exclude_test));
|
||||
const url = `${API_BASE_URL}/api/admin/payments${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, { headers: getAuthHeaders() });
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getPaymentDetail(sessionId: string): Promise<PaymentRecord> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/payments/${encodeURIComponent(sessionId)}`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getStripeBalance(): Promise<StripeBalance> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/payments/balance`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getPayouts(limit: number = 20): Promise<PayoutRecord[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/payments/payouts?limit=${limit}`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getDisputes(): Promise<DisputeRecord[]> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/payments/disputes`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getUserPayments(email: string): Promise<UserPaymentHistory> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/payments/by-user/${encodeURIComponent(email)}`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async getWebhookEvents(params?: { limit?: number; event_type?: string; status?: string }): Promise<WebhookEvent[]> {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (params?.limit) searchParams.set('limit', String(params.limit));
|
||||
if (params?.event_type) searchParams.set('event_type', params.event_type);
|
||||
if (params?.status) searchParams.set('status', params.status);
|
||||
const url = `${API_BASE_URL}/api/admin/payments/webhook-events${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
|
||||
const response = await fetch(url, { headers: getAuthHeaders() });
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async refundPayment(sessionId: string, request: RefundRequest): Promise<RefundResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/payments/${encodeURIComponent(sessionId)}/refund`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(request),
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
};
|
||||
|
||||
// Types for admin completion message API
|
||||
@@ -2505,5 +2610,131 @@ export interface FeedbackResponse {
|
||||
credits_granted: number;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Payment Admin Types
|
||||
// =============================================================================
|
||||
|
||||
export interface RevenueSummary {
|
||||
total_gross: number;
|
||||
total_fees: number;
|
||||
total_net: number;
|
||||
total_refunds: number;
|
||||
transaction_count: number;
|
||||
average_order_value: number;
|
||||
revenue_by_type: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface RevenueChartPoint {
|
||||
date: string;
|
||||
gross: number;
|
||||
net: number;
|
||||
fees: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface PaymentRecord {
|
||||
session_id: string;
|
||||
payment_intent_id?: string;
|
||||
charge_id?: string;
|
||||
amount_total: number;
|
||||
currency: string;
|
||||
stripe_fee: number;
|
||||
net_amount: number;
|
||||
customer_email: string;
|
||||
customer_name: string;
|
||||
stripe_customer_id?: string;
|
||||
payment_method_type: string;
|
||||
card_brand: string;
|
||||
card_last4: string;
|
||||
order_type: string;
|
||||
package_id?: string;
|
||||
credits_granted: number;
|
||||
product_description: string;
|
||||
artist?: string;
|
||||
title?: string;
|
||||
job_id?: string;
|
||||
status: string;
|
||||
refund_amount: number;
|
||||
refund_id?: string;
|
||||
refunded_at?: string;
|
||||
refund_reason?: string;
|
||||
created_at?: string;
|
||||
processed_at?: string;
|
||||
is_test: boolean;
|
||||
promotion_code?: string;
|
||||
discount_amount: number;
|
||||
receipt_url?: string;
|
||||
stripe_dashboard_url?: string;
|
||||
}
|
||||
|
||||
export interface PaymentListResponse {
|
||||
payments: PaymentRecord[];
|
||||
total: number;
|
||||
has_more: boolean;
|
||||
}
|
||||
|
||||
export interface StripeBalance {
|
||||
available: number;
|
||||
pending: number;
|
||||
currency: string;
|
||||
}
|
||||
|
||||
export interface PayoutRecord {
|
||||
id: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
status: string;
|
||||
arrival_date?: number;
|
||||
created?: number;
|
||||
description?: string;
|
||||
method?: string;
|
||||
}
|
||||
|
||||
export interface DisputeRecord {
|
||||
id: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
status: string;
|
||||
reason: string;
|
||||
charge_id?: string;
|
||||
created?: number;
|
||||
evidence_due_by?: number;
|
||||
payment_intent_id?: string;
|
||||
}
|
||||
|
||||
export interface UserPaymentHistory {
|
||||
email: string;
|
||||
payments: PaymentRecord[];
|
||||
total_spent: number;
|
||||
total_refunded: number;
|
||||
net_spent: number;
|
||||
payment_count: number;
|
||||
first_payment_at?: string;
|
||||
last_payment_at?: string;
|
||||
}
|
||||
|
||||
export interface WebhookEvent {
|
||||
event_id: string;
|
||||
event_type: string;
|
||||
created_at?: string;
|
||||
processed_at?: string;
|
||||
status: string;
|
||||
error_message?: string;
|
||||
session_id?: string;
|
||||
customer_email?: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export interface RefundRequest {
|
||||
amount?: number;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface RefundResponse {
|
||||
success: boolean;
|
||||
message: string;
|
||||
session_id: string;
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Backfill stripe_payments collection from processed_stripe_sessions.
|
||||
|
||||
For each processed session, retrieves the expanded Checkout Session from Stripe
|
||||
and stores enriched payment data in the stripe_payments collection.
|
||||
|
||||
Usage:
|
||||
python scripts/backfill_stripe_payments.py [--dry-run] [--limit N]
|
||||
|
||||
Requirements:
|
||||
- STRIPE_SECRET_KEY environment variable
|
||||
- GOOGLE_CLOUD_PROJECT=nomadkaraoke
|
||||
"""
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
# Add project root to path
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
||||
|
||||
import stripe
|
||||
from google.cloud import firestore
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Backfill stripe_payments from processed_stripe_sessions")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Preview without writing to Firestore")
|
||||
parser.add_argument("--limit", type=int, default=0, help="Max sessions to process (0 = all)")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Verify Stripe key
|
||||
secret_key = os.getenv("STRIPE_SECRET_KEY")
|
||||
if not secret_key:
|
||||
logger.error("STRIPE_SECRET_KEY not set")
|
||||
sys.exit(1)
|
||||
stripe.api_key = secret_key
|
||||
|
||||
# Init Firestore
|
||||
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
|
||||
db = firestore.Client()
|
||||
|
||||
# Read all processed sessions
|
||||
sessions_ref = db.collection("processed_stripe_sessions")
|
||||
payments_ref = db.collection("stripe_payments")
|
||||
|
||||
logger.info("Reading processed_stripe_sessions...")
|
||||
docs = list(sessions_ref.stream())
|
||||
logger.info(f"Found {len(docs)} processed sessions")
|
||||
|
||||
if args.limit > 0:
|
||||
docs = docs[:args.limit]
|
||||
logger.info(f"Processing first {args.limit} sessions")
|
||||
|
||||
processed = 0
|
||||
skipped = 0
|
||||
errors = 0
|
||||
|
||||
for doc in docs:
|
||||
session_id = doc.id
|
||||
data = doc.to_dict()
|
||||
|
||||
# Check if already in stripe_payments
|
||||
existing = payments_ref.document(session_id).get()
|
||||
if existing.exists:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
# Rate limiting: 50 requests/sec
|
||||
time.sleep(0.02)
|
||||
|
||||
# Fetch expanded session from Stripe
|
||||
session = stripe.checkout.Session.retrieve(
|
||||
session_id,
|
||||
expand=["payment_intent.latest_charge.balance_transaction"],
|
||||
)
|
||||
|
||||
if args.dry_run:
|
||||
logger.info(
|
||||
f"[DRY RUN] Would store payment for {session_id}: "
|
||||
f"${session.get('amount_total', 0) / 100:.2f} "
|
||||
f"from {data.get('email', 'unknown')}"
|
||||
)
|
||||
processed += 1
|
||||
continue
|
||||
|
||||
# Use the admin service to store
|
||||
# Import here to avoid import issues when running standalone
|
||||
from backend.services.stripe_admin_service import StripeAdminService
|
||||
|
||||
service = StripeAdminService()
|
||||
success = service.store_payment(dict(session))
|
||||
|
||||
if success:
|
||||
processed += 1
|
||||
if processed % 10 == 0:
|
||||
logger.info(f"Progress: {processed} stored, {skipped} skipped, {errors} errors")
|
||||
else:
|
||||
errors += 1
|
||||
logger.warning(f"Failed to store payment for {session_id}")
|
||||
|
||||
except stripe.error.InvalidRequestError as e:
|
||||
if "No such checkout.session" in str(e):
|
||||
logger.warning(f"Session {session_id} no longer exists in Stripe (expired?)")
|
||||
skipped += 1
|
||||
else:
|
||||
errors += 1
|
||||
logger.error(f"Stripe error for {session_id}: {e}")
|
||||
|
||||
except Exception as e:
|
||||
errors += 1
|
||||
logger.error(f"Error processing {session_id}: {e}")
|
||||
|
||||
logger.info(
|
||||
f"Backfill complete: {processed} stored, {skipped} skipped, {errors} errors"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user