major claude changes

This commit is contained in:
2026-01-28 21:54:54 -05:00
parent 76e881d939
commit 1832c8ab62
15 changed files with 423 additions and 296 deletions

View File

@@ -1,6 +1,9 @@
## File: your_app/views.py
import logging
from fastapi import APIRouter, Depends, HTTPException
logger = logging.getLogger(__name__)
from sqlalchemy.orm import Session
from typing import Tuple, Optional
import enum
@@ -48,18 +51,18 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
Parse Authorize.net response with proper attribute access for SDK objects.
Authorize.net response objects don't have .text properties, they're direct attributes.
"""
print(f"DEBUG: Parsing response, type: {type(response)}")
print(f"DEBUG: Response exists: {response is not None}")
logger.debug(f"DEBUG: Parsing response, type: {type(response)}")
logger.debug(f"DEBUG: Response exists: {response is not None}")
if response is not None:
print("DEBUG: Checking for messages attribute...")
logger.debug("DEBUG: Checking for messages attribute...")
if hasattr(response, 'messages'):
print(f"DEBUG: Messages exist, resultCode: {getattr(response.messages, 'resultCode', 'NO resultCode')}")
logger.debug(f"DEBUG: Messages exist, resultCode: {getattr(response.messages, 'resultCode', 'NO resultCode')}")
else:
print("DEBUG: No messages attribute")
logger.debug("DEBUG: No messages attribute")
if response.messages.resultCode == "Ok":
print("✅✅ DEBUG: Taking APPROVED path")
logger.debug("✅✅ DEBUG: Taking APPROVED path")
status = TransactionStatus.APPROVED
auth_net_transaction_id = None
@@ -68,24 +71,24 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
if hasattr(response, 'transactionResponse') and response.transactionResponse is not None:
if hasattr(response.transactionResponse, 'transId') and response.transactionResponse.transId:
auth_net_transaction_id = str(response.transactionResponse.transId)
print(f"✅✅ DEBUG: FOUND transaction ID: {auth_net_transaction_id}")
logger.debug(f"✅✅ DEBUG: FOUND transaction ID: {auth_net_transaction_id}")
else:
print("DEBUG: transactionResponse exists but no transId")
logger.debug("DEBUG: transactionResponse exists but no transId")
else:
print("DEBUG: No transactionResponse in approved response")
logger.debug("DEBUG: No transactionResponse in approved response")
except Exception as e:
print(f"DEBUG: Exception extracting transaction ID: {e}")
print(f"DEBUG: Response object inspection:")
print(type(response))
logger.debug(f"DEBUG: Exception extracting transaction ID: {e}")
logger.debug(f"DEBUG: Response object inspection:")
logger.debug(type(response))
if hasattr(response, 'transactionResponse'):
print(f"TransactionResponse type: {type(response.transactionResponse)}")
print(dir(response.transactionResponse))
logger.debug(f"TransactionResponse type: {type(response.transactionResponse)}")
logger.debug(dir(response.transactionResponse))
rejection_reason = None
print(f"✅✅✅ DEBUG: APPROVED - ID: {auth_net_transaction_id}, rejection: {rejection_reason}")
logger.debug(f"✅✅✅ DEBUG: APPROVED - ID: {auth_net_transaction_id}, rejection: {rejection_reason}")
else:
print("DEBUG: Taking DECLINED path")
logger.debug("DEBUG: Taking DECLINED path")
status = TransactionStatus.DECLINED
auth_net_transaction_id = None
rejection_reason = "Payment declined by gateway."
@@ -94,22 +97,22 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
# Handle transaction response errors
if hasattr(response, 'transactionResponse') and response.transactionResponse is not None:
if hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors:
print("DEBUG: Using transactionResponse.errors")
logger.debug("DEBUG: Using transactionResponse.errors")
try:
error = response.transactionResponse.errors[0]
# Remove the .text access - use direct attributes
error_code = getattr(error, 'errorCode', 'Unknown')
error_text = getattr(error, 'errorText', 'Unknown error')
rejection_reason = f"{error_code}: {error_text}"
print(f"DEBUG: Transaction error: {rejection_reason}")
logger.debug(f"DEBUG: Transaction error: {rejection_reason}")
except Exception as e:
print(f"DEBUG: Exception parsing transaction error: {e}")
logger.debug(f"DEBUG: Exception parsing transaction error: {e}")
rejection_reason = "Failed to parse transaction error"
# Handle message-level errors
elif hasattr(response, 'messages') and response.messages:
if hasattr(response.messages, 'message') and response.messages.message:
print("DEBUG: Using response.messages.message")
logger.debug("DEBUG: Using response.messages.message")
try:
msg = response.messages.message
if isinstance(msg, list):
@@ -118,12 +121,12 @@ def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[Transa
code = getattr(msg, 'code', 'Unknown')
text = getattr(msg, 'text', 'Unknown error')
rejection_reason = f"{code}: {text}"
print(f"DEBUG: Message error: {rejection_reason}")
logger.debug(f"DEBUG: Message error: {rejection_reason}")
except Exception as e:
print(f"DEBUG: Exception parsing message error: {e}")
logger.debug(f"DEBUG: Exception parsing message error: {e}")
rejection_reason = "Failed to parse message error"
print(f"✅✅✅ DEBUG: FINAL RESULT - Status: {status}, ID: {auth_net_transaction_id}, Reason: {rejection_reason}")
logger.debug(f"✅✅✅ DEBUG: FINAL RESULT - Status: {status}, ID: {auth_net_transaction_id}, Reason: {rejection_reason}")
return status, auth_net_transaction_id, rejection_reason
@router.post("/customers/{customer_id}/cards", summary="Add a new payment card for a customer")
@@ -194,13 +197,13 @@ def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.
try:
# If payment profile ID is null, refresh from Authorize.Net to sync
if not db_card.auth_net_payment_profile_id:
print(f"Payment profile ID is null for card {card_id}, refreshing from Authorize.Net")
logger.debug(f"Payment profile ID is null for card {card_id}, refreshing from Authorize.Net")
from ..services import user_create
user_create.refresh_customer_payment_profiles(db, customer_id, db_customer.auth_net_profile_id)
# Re-fetch the card to get the updated payment profile ID
db.refresh(db_card)
print(f"After refresh, card {card_id} has payment_profile_id: {db_card.auth_net_payment_profile_id}")
logger.debug(f"After refresh, card {card_id} has payment_profile_id: {db_card.auth_net_payment_profile_id}")
# Delete existing payment profile if it exists
if db_card.auth_net_payment_profile_id:
@@ -209,13 +212,13 @@ def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.
db_customer.auth_net_profile_id, db_card.auth_net_payment_profile_id
)
if delete_success:
print(f"Successfully deleted old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
logger.debug(f"Successfully deleted old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
# Clear the payment profile ID since it was deleted
db_card.auth_net_payment_profile_id = None
db.add(db_card)
db.commit()
else:
print(f"Failed to delete old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
logger.debug(f"Failed to delete old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
# Create new payment profile with updated card information
new_payment_profile_id = payment_service.add_payment_profile_to_customer(
@@ -229,7 +232,7 @@ def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.
db.add(db_card)
db.commit()
print(f"Successfully updated card {card_id} with new payment profile {new_payment_profile_id}")
logger.debug(f"Successfully updated card {card_id} with new payment profile {new_payment_profile_id}")
# Return the new payment_profile_id
return {"payment_profile_id": new_payment_profile_id}
@@ -239,7 +242,7 @@ def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
db.rollback()
print(f"Failed to update card {card_id}: {str(e)}")
logger.debug(f"Failed to update card {card_id}: {str(e)}")
raise HTTPException(status_code=500, detail="An internal server error occurred.")
@router.post("/charge/saved-card/{customer_id}", response_model=schemas.Transaction, summary="Charge a customer using a saved card")
@@ -281,7 +284,7 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
Creates a pre-authorization on a customer's saved card.
This validates the card and reserves the funds.
"""
print("🐛 DEBUG: ENTERING authorize_saved_card ROUTER FUNCTION")
logger.debug("🐛 DEBUG: ENTERING authorize_saved_card ROUTER FUNCTION")
db_customer = crud.get_customer(db, customer_id=customer_id)
db_card = crud.get_card_by_id(db, card_id=transaction_req.card_id)
@@ -289,18 +292,18 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
if not db_customer or not db_card or db_card.user_id != customer_id:
raise HTTPException(status_code=404, detail="Customer or card not found for this account")
print("🐛 DEBUG: CUSTOMER AND CARD FOUND, STARTING PRE-VALIDATION")
logger.debug("🐛 DEBUG: CUSTOMER AND CARD FOUND, STARTING PRE-VALIDATION")
# 🚨 ENHANCED PRE-TRANSACTION VALIDATION 🚨
# Proactively check and fix payment profile issues before attempting transaction
print(f"🐛 DEBUG: Starting enhanced pre-validation for customer {customer_id}, card {db_card.id}")
print(f"🔍 PRE-TRANSACTION CHECK: Customer {customer_id}, Card {db_card.id}")
print(f"🔍 Current auth_net_profile_id: '{db_customer.auth_net_profile_id}'")
print(f"🔍 Current payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
logger.debug(f"🐛 DEBUG: Starting enhanced pre-validation for customer {customer_id}, card {db_card.id}")
logger.debug(f"🔍 PRE-TRANSACTION CHECK: Customer {customer_id}, Card {db_card.id}")
logger.debug(f"🔍 Current auth_net_profile_id: '{db_customer.auth_net_profile_id}'")
logger.debug(f"🔍 Current payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
# Check for missing payment profiles OR test validity of existing ones
needs_recovery = False
print(f"🐛 DEBUG: Checking payment profiles - customer_id: {db_customer.auth_net_profile_id}, card_id: {db_card.auth_net_payment_profile_id}")
logger.debug(f"🐛 DEBUG: Checking payment profiles - customer_id: {db_customer.auth_net_profile_id}, card_id: {db_card.auth_net_payment_profile_id}")
if (not db_customer.auth_net_profile_id or
not db_card.auth_net_payment_profile_id or
@@ -309,33 +312,33 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
db_card.auth_net_payment_profile_id is None):
# Missing/null payment profile - needs recovery
needs_recovery = True
print("🐛 DEBUG: NULL/MISSING PAYMENT PROFILE DETECTED")
print(f"🔧 NULL/MISSING PAYMENT PROFILE DETECTED - Triggering auto-recovery")
logger.debug("🐛 DEBUG: NULL/MISSING PAYMENT PROFILE DETECTED")
logger.debug(f"🔧 NULL/MISSING PAYMENT PROFILE DETECTED - Triggering auto-recovery")
else:
# Payment profile exists in DB, but let's test if it's valid in Authorize.net
print(f"🐛 DEBUG: Payment profile exists, testing validity in Authorize.net...")
print(f"🔍 Payment profile exists, testing validity in Authorize.net...")
logger.debug(f"🐛 DEBUG: Payment profile exists, testing validity in Authorize.net...")
logger.debug(f"🔍 Payment profile exists, testing validity in Authorize.net...")
try:
# Quick test: try to retrieve customer payment profiles to see if our ID is valid
print(f"🐛 DEBUG: Calling get_customer_payment_profiles for profile_id: {db_customer.auth_net_profile_id}")
logger.debug(f"🐛 DEBUG: Calling get_customer_payment_profiles for profile_id: {db_customer.auth_net_profile_id}")
test_profiles = payment_service.get_customer_payment_profiles(db_customer.auth_net_profile_id)
print(f"🐛 DEBUG: Got profiles from Authorize.net: {test_profiles}")
logger.debug(f"🐛 DEBUG: Got profiles from Authorize.net: {test_profiles}")
current_id = str(db_card.auth_net_payment_profile_id)
profile_ids_as_strings = [str(pid) for pid in test_profiles if pid]
print(f"🐛 DEBUG: Checking if '{current_id}' is in: {profile_ids_as_strings}")
logger.debug(f"🐛 DEBUG: Checking if '{current_id}' is in: {profile_ids_as_strings}")
if current_id not in profile_ids_as_strings:
needs_recovery = True
print(f"🐛 DEBUG: PAYMENT PROFILE {current_id} NOT FOUND - NEEDS RECOVERY")
print(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} NOT FOUND IN AUTHORIZE.NET - Invalid ID!")
print(f"🔧 Available profiles in Authorize.net: {test_profiles}")
logger.debug(f"🐛 DEBUG: PAYMENT PROFILE {current_id} NOT FOUND - NEEDS RECOVERY")
logger.debug(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} NOT FOUND IN AUTHORIZE.NET - Invalid ID!")
logger.debug(f"🔧 Available profiles in Authorize.net: {test_profiles}")
else:
if ApplicationConfig.penny_test_transaction:
print(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} exists in Authorize.net, testing usability...")
logger.debug(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} exists in Authorize.net, testing usability...")
# Profile exists in Authorize.net, but test if it's actually USABLE
# by doing a quick test authorization with minimal amount
try:
print(f"🐛 DEBUG: Testing if payment profile is actually usable...")
logger.debug(f"🐛 DEBUG: Testing if payment profile is actually usable...")
# Create a tiny test transaction (like $0.01) to validate the card works
test_transaction_req = schemas.TransactionAuthorizeByCardID(
card_id=db_card.id,
@@ -356,31 +359,31 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
test_status, _, test_reason = _parse_authnet_response(test_response)
if "E00121" in str(test_reason) or test_status == 1: # 1 = DECLINED
print(f"🐛 DEBUG: TEST AUTH FAILED - Payment profile exists but is INVALID!")
logger.debug(f"🐛 DEBUG: TEST AUTH FAILED - Payment profile exists but is INVALID!")
needs_recovery = True
print(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} EXISTS BUT IS UNUSABLE - E00121 detected during test!")
print(f"🔧 Test transaction failed: {test_reason}")
logger.debug(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} EXISTS BUT IS UNUSABLE - E00121 detected during test!")
logger.debug(f"🔧 Test transaction failed: {test_reason}")
else:
print(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} is VALID and USABLE")
print(f"✅ Payment profile {db_card.auth_net_payment_profile_id} is valid and usable in Authorize.net")
logger.debug(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} is VALID and USABLE")
logger.debug(f"✅ Payment profile {db_card.auth_net_payment_profile_id} is valid and usable in Authorize.net")
except Exception as e:
print(f"🐛 DEBUG: Exception during usability test: {str(e)} - assuming profile needs recreation")
logger.debug(f"🐛 DEBUG: Exception during usability test: {str(e)} - assuming profile needs recreation")
needs_recovery = True
print(f"🔧 Could not test payment profile usability: {str(e)} - assuming it needs recreation")
logger.debug(f"🔧 Could not test payment profile usability: {str(e)} - assuming it needs recreation")
else:
print(f"🔍 Skipping penny test transaction (disabled in config)")
logger.debug(f"🔍 Skipping penny test transaction (disabled in config)")
except Exception as e:
print(f"🐛 DEBUG: Exception during profile validation: {str(e)}")
print(f"🔧 Could not verify payment profile validity in Authorize.net: {str(e)}")
logger.debug(f"🐛 DEBUG: Exception during profile validation: {str(e)}")
logger.debug(f"🔧 Could not verify payment profile validity in Authorize.net: {str(e)}")
# If we can't verify, assume it's okay and let the transaction proceed
# (better to try and fail than to block legitimate transactions)
print(f"⚠️ Unable to verify profile validity - proceeding with transaction anyway")
logger.debug(f"⚠️ Unable to verify profile validity - proceeding with transaction anyway")
if needs_recovery:
print(f"🔧 DETECTED PAYMENT PROFILE ISSUE - Triggering auto-recovery for customer {customer_id}")
logger.debug(f"🔧 DETECTED PAYMENT PROFILE ISSUE - Triggering auto-recovery for customer {customer_id}")
# Auto-recover: Refresh payment profiles before transaction
from ..services import user_create
@@ -389,14 +392,14 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
)
if recovery_success:
print("✅ Auto-recovery successful - proceeding with transaction")
logger.debug("✅ Auto-recovery successful - proceeding with transaction")
# Re-fetch card data to get updated payment profile ID
db.refresh(db_card)
db.refresh(db_customer)
print(f"🔍 After recovery - payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
logger.debug(f"🔍 After recovery - payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
else:
print("❌ Auto-recovery failed - cannot proceed with transaction")
logger.debug("❌ Auto-recovery failed - cannot proceed with transaction")
raise HTTPException(
status_code=400,
detail="Payment profile setup error detected and auto-recovery failed. Please contact support."
@@ -404,13 +407,13 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
# Final validation before proceeding
if not db_customer.auth_net_profile_id or not db_card.auth_net_payment_profile_id:
print(f"❌ CRITICAL: Payment profile validation failed after recovery attempt")
logger.debug(f"❌ CRITICAL: Payment profile validation failed after recovery attempt")
raise HTTPException(
status_code=400,
detail="Payment profile is not set up correctly for this customer/card"
)
print(f"✅ Payment profile validation passed - proceeding with authorization")
logger.debug(f"✅ Payment profile validation passed - proceeding with authorization")
# 🚨 ENHANCED E00121 ERROR HANDLING 🚨
# If transaction still fails with E00121 despite pre-validation, force-nuke the problematic ID
@@ -426,7 +429,7 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
# Parse the transaction response (no need for E00121 nuclear cleanup since pre-validation should have caught it)
transaction_status, auth_net_transaction_id, rejection_reason = _parse_authnet_response(auth_net_response)
print(transaction_req)
logger.debug(transaction_req)
transaction_data = schemas.TransactionBase(
preauthorize_amount=transaction_req.preauthorize_amount,
transaction_type=TransactionType.AUTHORIZE, # This is key