cleaned up code
This commit is contained in:
@@ -4,12 +4,13 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Tuple, Optional
|
||||
import enum
|
||||
import logging
|
||||
|
||||
from .. import crud, models, schemas, database
|
||||
from ..services import payment_service
|
||||
from config import load_config
|
||||
|
||||
ApplicationConfig = load_config()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
@@ -193,13 +194,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:
|
||||
logger.info(f"Payment profile ID is null for card {card_id}, refreshing from Authorize.Net")
|
||||
print(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)
|
||||
logger.info(f"After refresh, card {card_id} has payment_profile_id: {db_card.auth_net_payment_profile_id}")
|
||||
print(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:
|
||||
@@ -208,13 +209,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:
|
||||
logger.info(f"Successfully deleted old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
|
||||
print(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:
|
||||
logger.warning(f"Failed to delete old payment profile {db_card.auth_net_payment_profile_id} for card {card_id}")
|
||||
print(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(
|
||||
@@ -228,7 +229,7 @@ def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.
|
||||
db.add(db_card)
|
||||
db.commit()
|
||||
|
||||
logger.info(f"Successfully updated card {card_id} with new payment profile {new_payment_profile_id}")
|
||||
print(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}
|
||||
@@ -293,9 +294,9 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
|
||||
# 🚨 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}")
|
||||
logger.info(f"🔍 PRE-TRANSACTION CHECK: Customer {customer_id}, Card {db_card.id}")
|
||||
logger.info(f"🔍 Current auth_net_profile_id: '{db_customer.auth_net_profile_id}'")
|
||||
logger.info(f"🔍 Current payment_profile_id: '{db_card.auth_net_payment_profile_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}'")
|
||||
|
||||
# Check for missing payment profiles OR test validity of existing ones
|
||||
needs_recovery = False
|
||||
@@ -309,11 +310,11 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
|
||||
# Missing/null payment profile - needs recovery
|
||||
needs_recovery = True
|
||||
print("🐛 DEBUG: NULL/MISSING PAYMENT PROFILE DETECTED")
|
||||
logger.warning(f"🔧 NULL/MISSING PAYMENT PROFILE DETECTED - Triggering auto-recovery")
|
||||
print(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...")
|
||||
logger.info(f"🔍 Payment profile exists, testing validity in Authorize.net...")
|
||||
print(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}")
|
||||
@@ -326,55 +327,60 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
|
||||
if current_id not in profile_ids_as_strings:
|
||||
needs_recovery = True
|
||||
print(f"🐛 DEBUG: PAYMENT PROFILE {current_id} NOT FOUND - NEEDS RECOVERY")
|
||||
logger.warning(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} NOT FOUND IN AUTHORIZE.NET - Invalid ID!")
|
||||
logger.warning(f"🔧 Available profiles in Authorize.net: {test_profiles}")
|
||||
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}")
|
||||
else:
|
||||
print(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...")
|
||||
# Create a tiny test transaction (like $0.01) to validate the card works
|
||||
test_transaction_req = schemas.TransactionAuthorizeByCardID(
|
||||
card_id=db_card.id,
|
||||
preauthorize_amount="0.01" # Minimal test amount
|
||||
)
|
||||
if ApplicationConfig.penny_test_transaction:
|
||||
print(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...")
|
||||
# Create a tiny test transaction (like $0.01) to validate the card works
|
||||
test_transaction_req = schemas.TransactionAuthorizeByCardID(
|
||||
card_id=db_card.id,
|
||||
preauthorize_amount="0.01" # Minimal test amount
|
||||
)
|
||||
|
||||
test_response = payment_service.authorize_customer_profile(
|
||||
customer_profile_id=db_customer.auth_net_profile_id,
|
||||
payment_profile_id=db_card.auth_net_payment_profile_id,
|
||||
transaction_req=test_transaction_req,
|
||||
db_session=None, # Don't pass DB session for test transaction
|
||||
customer_id=None,
|
||||
card_id=None
|
||||
)
|
||||
test_response = payment_service.authorize_customer_profile(
|
||||
customer_profile_id=db_customer.auth_net_profile_id,
|
||||
payment_profile_id=db_card.auth_net_payment_profile_id,
|
||||
transaction_req=test_transaction_req,
|
||||
db_session=None, # Don't pass DB session for test transaction
|
||||
customer_id=None,
|
||||
card_id=None
|
||||
)
|
||||
|
||||
# Check if the test authorization worked
|
||||
from ..services import payment_service as ps # Need access to _parse_authnet_response
|
||||
test_status, _, test_reason = _parse_authnet_response(test_response)
|
||||
# Check if the test authorization worked
|
||||
from ..services import payment_service as ps # Need access to _parse_authnet_response
|
||||
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!")
|
||||
if "E00121" in str(test_reason) or test_status == 1: # 1 = DECLINED
|
||||
print(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}")
|
||||
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")
|
||||
|
||||
except Exception as e:
|
||||
print(f"🐛 DEBUG: Exception during usability test: {str(e)} - assuming profile needs recreation")
|
||||
needs_recovery = True
|
||||
logger.warning(f"🔧 PAYMENT PROFILE {db_card.auth_net_payment_profile_id} EXISTS BUT IS UNUSABLE - E00121 detected during test!")
|
||||
logger.warning(f"🔧 Test transaction failed: {test_reason}")
|
||||
else:
|
||||
print(f"🐛 DEBUG: Payment profile {db_card.auth_net_payment_profile_id} is VALID and USABLE")
|
||||
logger.info(f"✅ Payment profile {db_card.auth_net_payment_profile_id} is valid and usable in Authorize.net")
|
||||
print(f"🔧 Could not test payment profile usability: {str(e)} - assuming it needs recreation")
|
||||
else:
|
||||
print(f"🔍 Skipping penny test transaction (disabled in config)")
|
||||
|
||||
except Exception as e:
|
||||
print(f"🐛 DEBUG: Exception during usability test: {str(e)} - assuming profile needs recreation")
|
||||
needs_recovery = True
|
||||
logger.warning(f"🔧 Could not test payment profile usability: {str(e)} - assuming it needs recreation")
|
||||
|
||||
except Exception as e:
|
||||
print(f"🐛 DEBUG: Exception during profile validation: {str(e)}")
|
||||
logger.warning(f"🔧 Could not verify payment profile validity in Authorize.net: {str(e)}")
|
||||
print(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)
|
||||
logger.info(f"⚠️ Unable to verify profile validity - proceeding with transaction anyway")
|
||||
print(f"⚠️ Unable to verify profile validity - proceeding with transaction anyway")
|
||||
|
||||
if needs_recovery:
|
||||
logger.warning(f"🔧 DETECTED PAYMENT PROFILE ISSUE - Triggering auto-recovery for customer {customer_id}")
|
||||
print(f"🔧 DETECTED PAYMENT PROFILE ISSUE - Triggering auto-recovery for customer {customer_id}")
|
||||
|
||||
# Auto-recover: Refresh payment profiles before transaction
|
||||
from ..services import user_create
|
||||
@@ -383,14 +389,14 @@ def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionA
|
||||
)
|
||||
|
||||
if recovery_success:
|
||||
logger.info("✅ Auto-recovery successful - proceeding with transaction")
|
||||
print("✅ Auto-recovery successful - proceeding with transaction")
|
||||
|
||||
# Re-fetch card data to get updated payment profile ID
|
||||
db.refresh(db_card)
|
||||
db.refresh(db_customer)
|
||||
logger.info(f"🔍 After recovery - payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
|
||||
print(f"🔍 After recovery - payment_profile_id: '{db_card.auth_net_payment_profile_id}'")
|
||||
else:
|
||||
logger.error("❌ Auto-recovery failed - cannot proceed with transaction")
|
||||
print("❌ 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."
|
||||
@@ -398,13 +404,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:
|
||||
logger.error(f"❌ CRITICAL: Payment profile validation failed after recovery attempt")
|
||||
print(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"
|
||||
)
|
||||
|
||||
logger.info(f"✅ Payment profile validation passed - proceeding with authorization")
|
||||
print(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
|
||||
|
||||
Reference in New Issue
Block a user