diff --git a/backend/api/routes/admin.py b/backend/api/routes/admin.py index 533a1cc0..84406b2e 100644 --- a/backend/api/routes/admin.py +++ b/backend/api/routes/admin.py @@ -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) diff --git a/backend/api/routes/users.py b/backend/api/routes/users.py index 6eb88f09..cf8b5636 100644 --- a/backend/api/routes/users.py +++ b/backend/api/routes/users.py @@ -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} diff --git a/backend/services/stripe_admin_service.py b/backend/services/stripe_admin_service.py new file mode 100644 index 00000000..e7af4193 --- /dev/null +++ b/backend/services/stripe_admin_service.py @@ -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 diff --git a/backend/tests/test_admin_payment_endpoints.py b/backend/tests/test_admin_payment_endpoints.py new file mode 100644 index 00000000..03fd6d8a --- /dev/null +++ b/backend/tests/test_admin_payment_endpoints.py @@ -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" diff --git a/backend/tests/test_stripe_admin_service.py b/backend/tests/test_stripe_admin_service.py new file mode 100644 index 00000000..ddecf436 --- /dev/null +++ b/backend/tests/test_stripe_admin_service.py @@ -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 diff --git a/frontend/app/admin/layout.tsx b/frontend/app/admin/layout.tsx index 91304e83..b47f4941 100644 --- a/frontend/app/admin/layout.tsx +++ b/frontend/app/admin/layout.tsx @@ -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" }) } } } diff --git a/frontend/app/admin/page.tsx b/frontend/app/admin/page.tsx index 7bed24e7..b450f598 100644 --- a/frontend/app/admin/page.tsx +++ b/frontend/app/admin/page.tsx @@ -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(null) + const [revenue, setRevenue] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(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} /> + = { + 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 {v.label} +} + +function PaymentMethodDisplay({ type, brand, last4 }: { type: string; brand: string; last4: string }) { + if (!type || type === "unknown") return - + if (type === "card" && brand && last4) { + return ( + + {brand} ...{last4} + + ) + } + return {type.replace("_", " ")} +} + +// ============================================================================= +// Revenue Overview Tab +// ============================================================================= + +function RevenueOverviewTab() { + const { showTestData } = useAdminSettings() + const [summary, setSummary] = useState(null) + const [chart, setChart] = useState([]) + const [balance, setBalance] = useState(null) + const [disputes, setDisputes] = useState([]) + 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 ( +
+ {/* Dispute Alert Banner */} + {openDisputes.length > 0 && ( +
+
+ + + {openDisputes.length} open dispute{openDisputes.length > 1 ? "s" : ""} requiring attention + +
+
+ {openDisputes.map(d => ( +
+ {formatCents(d.amount)} - {d.reason} - Evidence due {formatTimestamp(d.evidence_due_by)} +
+ ))} +
+
+ )} + + {/* Period selector */} +
+ + +
+ + {/* Stats Grid */} + + + 0 ? `${((summary.total_fees / summary.total_gross) * 100).toFixed(1)}% of gross` : ""} + icon={Receipt} + loading={loading} + /> + + + + + {/* Charts */} +
+ {/* Revenue Chart */} + + + Revenue Over Time + Daily gross and net revenue + + + {loading ? ( + + ) : chart.length > 0 ? ( + + + + new Date(v).toLocaleDateString("en-US", { month: "short", day: "numeric" })} + fontSize={12} + /> + `$${(v / 100).toFixed(0)}`} + fontSize={12} + /> + formatCents(value as number)} + /> + } + /> + + + + + ) : ( +
+ No revenue data for this period +
+ )} +
+
+ + {/* Revenue by Type + Balance */} +
+ + + By Product + + + {loading ? ( + + ) : pieData.length > 0 ? ( +
+ {pieData.map((item, i) => ( +
+
+
+ {item.name} +
+ {formatCents(item.value)} +
+ ))} +
+ ) : ( +
No data
+ )} + + + + + + Stripe Balance + + + {loading ? ( + + ) : balance ? ( +
+
+ Available + + {formatCents(balance.available)} + +
+
+ Pending + {formatCents(balance.pending)} +
+
+ ) : ( +
Unable to load
+ )} +
+
+ + {summary && summary.total_refunds > 0 && ( + + + Refunds + + + {formatCents(summary.total_refunds)} + + + )} +
+
+
+ ) +} + +// ============================================================================= +// Transactions Tab +// ============================================================================= + +function TransactionsTab() { + const { showTestData } = useAdminSettings() + const [data, setData] = useState({ payments: [], total: 0, has_more: false }) + const [loading, setLoading] = useState(true) + const [offset, setOffset] = useState(0) + const [filterType, setFilterType] = useState("all") + const [filterStatus, setFilterStatus] = useState("all") + const [emailSearch, setEmailSearch] = useState("") + const [selectedPayment, setSelectedPayment] = useState(null) + const [refundPayment, setRefundPayment] = useState(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 ( +
+ {/* Filters */} +
+ + + + +
+ setEmailSearch(e.target.value)} + className="w-[200px]" + /> + +
+ + + + + {data.total} payment{data.total !== 1 ? "s" : ""} + +
+ + {/* Table */} +
+ + + + Date + Customer + Type + Product + Amount + Fee + Net + Method + Status + + + + {loading ? ( + Array.from({ length: 5 }).map((_, i) => ( + + {Array.from({ length: 9 }).map((_, j) => ( + + ))} + + )) + ) : data.payments.length === 0 ? ( + + + No payments found + + + ) : ( + data.payments.map((payment) => ( + setSelectedPayment(payment)} + > + {formatDate(payment.created_at)} + {payment.customer_email} + + + {payment.order_type === "made_for_you" ? "MFY" : "Credits"} + + + {payment.product_description} + {formatCents(payment.amount_total)} + {formatCents(payment.stripe_fee)} + {formatCents(payment.net_amount)} + + + + + + )) + )} + +
+
+ + {/* Pagination */} + {data.total > limit && ( +
+ + Showing {offset + 1}-{Math.min(offset + limit, data.total)} of {data.total} + +
+ + +
+
+ )} + + {/* Payment Detail Sheet */} + setSelectedPayment(null)} + onRefund={(payment) => { + setSelectedPayment(null) + setRefundPayment(payment) + }} + /> + + {/* Refund Dialog */} + setRefundPayment(null)} + onSuccess={() => { + setRefundPayment(null) + loadData() + }} + /> +
+ ) +} + +// ============================================================================= +// Payouts Tab +// ============================================================================= + +function PayoutsTab() { + const [balance, setBalance] = useState(null) + const [payouts, setPayouts] = useState([]) + 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 ( +
+ {/* Balance */} + + + + + + + {/* Payouts Table */} + + + Payout History + When money hits the bank account + + + + + + Date + Amount + Status + Arrival + Method + ID + + + + {loading ? ( + Array.from({ length: 5 }).map((_, i) => ( + + {Array.from({ length: 6 }).map((_, j) => ( + + ))} + + )) + ) : payouts.length === 0 ? ( + + + No payouts found + + + ) : ( + payouts.map((payout) => ( + + {formatTimestamp(payout.created)} + {formatCents(payout.amount)} + + {formatTimestamp(payout.arrival_date)} + {payout.method || "-"} + {payout.id.slice(-8)} + + )) + )} + +
+
+
+
+ ) +} + +// ============================================================================= +// Webhook Events Tab +// ============================================================================= + +function WebhookEventsTab() { + const [events, setEvents] = useState([]) + const [loading, setLoading] = useState(true) + const [filterType, setFilterType] = useState("all") + const [filterStatus, setFilterStatus] = useState("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 ( +
+
+ + + + + +
+ +
+ + + + Time + Event Type + Status + Customer + Summary + + + + {loading ? ( + Array.from({ length: 5 }).map((_, i) => ( + + {Array.from({ length: 5 }).map((_, j) => ( + + ))} + + )) + ) : events.length === 0 ? ( + + + No webhook events found + + + ) : ( + events.map((event) => ( + + {formatDateTime(event.created_at)} + {event.event_type} + + {event.customer_email || "-"} + {event.summary || "-"} + + )) + )} + +
+
+
+ ) +} + +// ============================================================================= +// Main Page +// ============================================================================= + +export default function PaymentsPage() { + return ( +
+
+

Payments

+

Revenue analytics, transactions, and Stripe management

+
+ + + + Revenue + Transactions + Payouts + Webhook Events + + + + + + + + + + + + + + + + + + +
+ ) +} diff --git a/frontend/app/admin/users/detail/page.tsx b/frontend/app/admin/users/detail/page.tsx index 67c65b78..c5916b40 100644 --- a/frontend/app/admin/users/detail/page.tsx +++ b/frontend/app/admin/users/detail/page.tsx @@ -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(null) const [loading, setLoading] = useState(true) const [actionLoading, setActionLoading] = useState(false) + const [paymentHistory, setPaymentHistory] = useState(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() {
+ {/* Payment History */} + + +
+
+ + + Payment History + + + {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" + )} + +
+
+
+ + {paymentsLoading ? ( +
+ +
+ ) : !paymentHistory || paymentHistory.payments.length === 0 ? ( +

No payments found

+ ) : ( + + + + Date + Amount + Type + Product + Status + + + + {paymentHistory.payments.map((p) => ( + router.push(`/admin/payments?tab=transactions&email=${encodeURIComponent(p.customer_email)}`)} + > + + {p.created_at ? new Date(p.created_at).toLocaleDateString() : "-"} + + + ${(p.amount_total / 100).toFixed(2)} + + + + {p.order_type === "made_for_you" ? "MFY" : "Credits"} + + + + {p.product_description} + + + + {p.status} + + + + ))} + +
+ )} +
+
+ {/* Recent Jobs */} diff --git a/frontend/components/admin/admin-sidebar.tsx b/frontend/components/admin/admin-sidebar.tsx index 799fb7e1..f523a350 100644 --- a/frontend/components/admin/admin-sidebar.tsx +++ b/frontend/components/admin/admin-sidebar.tsx @@ -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", diff --git a/frontend/components/admin/payment-detail.tsx b/frontend/components/admin/payment-detail.tsx new file mode 100644 index 00000000..09d8cc3e --- /dev/null +++ b/frontend/components/admin/payment-detail.tsx @@ -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 = { + 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 {v.label} +} + +function DetailRow({ label, value, mono }: { label: string; value: React.ReactNode; mono?: boolean }) { + return ( +
+ {label} + + {value || "-"} + +
+ ) +} + +interface PaymentDetailSheetProps { + payment: PaymentRecord | null + onClose: () => void + onRefund: (payment: PaymentRecord) => void +} + +export function PaymentDetailSheet({ payment, onClose, onRefund }: PaymentDetailSheetProps) { + const [detail, setDetail] = useState(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 ( + !open && onClose()}> + + + Payment Details + + {data?.product_description || "Payment"} + + + + {loading ? ( +
+ {Array.from({ length: 8 }).map((_, i) => ( + + ))} +
+ ) : data ? ( +
+ {/* Status & Amount */} +
+
{formatCents(data.amount_total)}
+ + {data.refund_amount > 0 && ( +
+ Refunded: {formatCents(data.refund_amount)} +
+ )} +
+ + + + {/* Customer */} +
+

Customer

+ + {data.customer_email} + + } /> + +
+ + + + {/* Financial */} +
+

Financial

+ + + + {data.discount_amount > 0 && ( + + )} +
+ + + + {/* Payment Method */} +
+

Payment Method

+ {data.payment_method_type?.replace("_", " ") || "-"} + } /> + {data.card_brand && } +
+ + + + {/* Order Details */} +
+

Order

+ + + {data.credits_granted > 0 && ( + + )} + {data.artist && } + {data.job_id && } +
+ + + + {/* Timestamps */} +
+

Timestamps

+ + + {data.refunded_at && ( + + )} +
+ + + + {/* IDs */} +
+

Stripe IDs

+ + + +
+ + {/* Actions */} +
+ {data.stripe_dashboard_url && ( + + )} + {data.receipt_url && ( + + )} + {canRefund && ( + + )} +
+
+ ) : null} +
+
+ ) +} diff --git a/frontend/components/admin/refund-dialog.tsx b/frontend/components/admin/refund-dialog.tsx new file mode 100644 index 00000000..68918c8e --- /dev/null +++ b/frontend/components/admin/refund-dialog.tsx @@ -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 ( + !open && onClose()}> + + + Issue Refund + + Refund for {payment.customer_email} - {payment.product_description} + + + +
+ {/* Payment Summary */} +
+
+ Original amount + {formatCents(payment.amount_total)} +
+ {payment.refund_amount > 0 && ( +
+ Already refunded + {formatCents(payment.refund_amount)} +
+ )} +
+ Max refundable + {formatCents(maxRefundable)} +
+
+ + {/* Partial toggle */} +
+ + +
+ + {/* Amount input */} + {isPartial && ( +
+ + setAmount(e.target.value)} + /> +
+ )} + + {/* Reason */} +
+ + +
+ + {/* Credit deduction warning */} + {creditsAtRisk > 0 && ( +
+ +
+ Credit deduction:{" "} + {creditsAtRisk} credit{creditsAtRisk !== 1 ? "s" : ""} will be + deducted from {payment.customer_email} +
+
+ )} + + {/* Refund summary */} + {isValid && ( +
+ + Refund {formatCents(refundAmount)} + +
+ )} +
+ + + Cancel + + {processing && } + Process Refund + + +
+
+ ) +} diff --git a/frontend/e2e/production/admin-payments.spec.ts b/frontend/e2e/production/admin-payments.spec.ts new file mode 100644 index 00000000..82761389 --- /dev/null +++ b/frontend/e2e/production/admin-payments.spec.ts @@ -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 { + 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); + }); +}); diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index 7ae3d6fe..238d597b 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -2006,6 +2006,111 @@ export const adminApi = { ); return handleResponse(response); }, + + // ========================================================================= + // Payments API + // ========================================================================= + + async getPaymentSummary(params?: { days?: number; exclude_test?: boolean }): Promise { + 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 { + 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 { + 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 { + const response = await fetch( + `${API_BASE_URL}/api/admin/payments/${encodeURIComponent(sessionId)}`, + { headers: getAuthHeaders() } + ); + return handleResponse(response); + }, + + async getStripeBalance(): Promise { + const response = await fetch( + `${API_BASE_URL}/api/admin/payments/balance`, + { headers: getAuthHeaders() } + ); + return handleResponse(response); + }, + + async getPayouts(limit: number = 20): Promise { + const response = await fetch( + `${API_BASE_URL}/api/admin/payments/payouts?limit=${limit}`, + { headers: getAuthHeaders() } + ); + return handleResponse(response); + }, + + async getDisputes(): Promise { + const response = await fetch( + `${API_BASE_URL}/api/admin/payments/disputes`, + { headers: getAuthHeaders() } + ); + return handleResponse(response); + }, + + async getUserPayments(email: string): Promise { + 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 { + 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 { + 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; +} + +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 }; diff --git a/scripts/backfill_stripe_payments.py b/scripts/backfill_stripe_payments.py new file mode 100644 index 00000000..546352f6 --- /dev/null +++ b/scripts/backfill_stripe_payments.py @@ -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()