cleaned up code

This commit is contained in:
2025-10-06 20:01:12 -04:00
parent d052fde8b7
commit 23a11a7009
7 changed files with 878 additions and 346 deletions

View File

@@ -22,51 +22,18 @@ ApplicationConfig = load_config()
# Set Authorize.net environment based on configuration
if ApplicationConfig.CURRENT_SETTINGS == 'PRODUCTION':
#constants.environment = constants.PRODUCTION
print("Constants:", ApplicationConfig.CURRENT_SETTINGS)
print("Authorize.Net URL:", constants.environment)
API_LOGIN_ID = '4d2Mn6H23R'
TRANSACTION_KEY = '7B94d8xfTQXv37WS'
API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID
TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY
# Override to standard production endpoint
constants.environment = "https://api.authorize.net/xml/v1/request.api"
print("Overridden Authorize.Net URL:", constants.environment)
else:
print("Constants:", ApplicationConfig.CURRENT_SETTINGS)
constants.environment = constants.SANDBOX
print("Authorize.Net URL:", constants.environment)
API_LOGIN_ID = ApplicationConfig.API_LOGIN_ID
TRANSACTION_KEY = ApplicationConfig.TRANSACTION_KEY
constants.show_url_on_request = True
constants.show_url_on_request = True
def _get_error_message(response):
"""
Robust error parsing function that correctly handles the API's response format.
"""
if response is None:
return "No response from payment gateway."
try:
if hasattr(response, 'messages') and response.messages is not None:
if hasattr(response, 'transactionResponse') and response.transactionResponse and hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors:
error = response.transactionResponse.errors[0]
return f"Error {error.errorCode}: {error.errorText}"
if hasattr(response.messages, 'message'):
message_list = response.messages.message
if not isinstance(message_list, list):
message_list = [message_list]
if message_list:
msg = message_list[0]
code = msg.code if hasattr(msg, 'code') else 'Unknown'
text = msg.text if hasattr(msg, 'text') else 'No details provided.'
return f"Error {code}: {text}"
except Exception as e:
logger.error(f"Error while parsing Auth.Net error message: {e}")
return "An unparsable error occurred with the payment gateway."
return "An unknown error occurred with the payment gateway."
def create_user_account(db: Session, customer_id: int) -> dict:
"""
@@ -92,7 +59,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
"message": f"Customer {customer_id} not found",
"profile_id": None
}
print(customer)
print(f"Found customer id={customer}")
# Get customer's cards from database
cards = crud.get_customer_cards(db, customer_id)
if not cards:
@@ -107,9 +74,9 @@ def create_user_account(db: Session, customer_id: int) -> dict:
# Get the first card to use for initial profile creation
first_card = cards[0]
logger.info(f"Using first card ID={first_card.id} for profile creation")
logger.info(f"Card Number: {first_card.card_number[:4]}**** ****{first_card.card_number[-4:]}")
logger.info(f"Expiration: {first_card.expiration_month}/{first_card.expiration_year}")
print(f"Using first card ID={first_card.id} for profile creation")
print(f"Card Number: {first_card.card_number[:4]}**** ****{first_card.card_number[-4:]}")
print(f"Expiration: {first_card.expiration_month}/{first_card.expiration_year}")
# Create CardCreate object for the first card
# Format expiration date for string values - pad year to 4 digits and month to 2 digits
@@ -125,8 +92,8 @@ def create_user_account(db: Session, customer_id: int) -> dict:
cvv=first_card.security_number
)
logger.info(f"Card info expiration_date: {card_info.expiration_date}")
logger.info(f"Processing Authorize.net profile for customer {customer_id} with {len(cards)} cards")
print(f"Card info expiration_date: {card_info.expiration_date}")
print(f"Processing Authorize.net profile for customer {customer_id} with {len(cards)} cards")
# Create customer profile and payment profiles if not exists
if not customer.auth_net_profile_id:
@@ -135,7 +102,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
auth_profile_id, _ = payment_service.create_customer_profile(customer, card_info)
except ValueError as e:
error_str = str(e)
logger.error(f"API call failed: {error_str}")
print(f"API call failed: {error_str}")
return {
"success": False,
@@ -146,7 +113,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
}
if not auth_profile_id:
logger.error("No auth_profile_id returned from API")
print("No auth_profile_id returned from API")
return {
"success": False,
"message": "Failed to create customer profile - no profile ID returned",
@@ -158,12 +125,12 @@ def create_user_account(db: Session, customer_id: int) -> dict:
first_payment_profile_id = payment_service.add_payment_profile_to_customer(
auth_profile_id, customer, card_info, is_default=True
)
logger.info(f"Successfully added first payment profile: {first_payment_profile_id} (default)")
print(f"Successfully added first payment profile: {first_payment_profile_id} (default)")
# Assign to first_card
first_card.auth_net_payment_profile_id = first_payment_profile_id
db.add(first_card)
except ValueError as e:
logger.error(f"Failed to add payment profile for first card: {str(e)}")
print(f"Failed to add payment profile for first card: {str(e)}")
return {
"success": False,
"message": f"Failed to add first payment profile: {str(e)}",
@@ -190,19 +157,19 @@ def create_user_account(db: Session, customer_id: int) -> dict:
payment_profile_id = payment_service.add_payment_profile_to_customer(
auth_profile_id, customer, card_info_additional, is_default=False
)
logger.info(f"Successfully added additional payment profile ID '{payment_profile_id}' for card {card.id}")
print(f"Successfully added additional payment profile ID '{payment_profile_id}' for card {card.id}")
except ValueError as e:
logger.error(f"Failed to add payment profile for additional card {card.id}: {str(e)}")
print(f"Failed to add payment profile for additional card {card.id}: {str(e)}")
else:
auth_profile_id = customer.auth_net_profile_id
logger.info(f"Using existing Authorize.net profile {auth_profile_id}")
print(f"Using existing Authorize.net profile {auth_profile_id}")
# RETRIEVE ALL PAYMENT PROFILE IDs - This is the key step
try:
payment_profile_ids = payment_service.get_customer_payment_profiles(auth_profile_id)
logger.info(f"DEBUG: Retrieved {len(payment_profile_ids)} payment profile IDs: {payment_profile_ids}")
print(f"DEBUG: Retrieved {len(payment_profile_ids)} payment profile IDs: {payment_profile_ids}")
except ValueError as e:
logger.error(f"Failed to retrieve payment profiles: {str(e)}")
print(f"Failed to retrieve payment profiles: {str(e)}")
return {
"success": False,
"message": f"Failed to retrieve payment profiles: {str(e)}",
@@ -211,7 +178,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
# Assign payment profile IDs to cards
num_to_update = min(len(cards), len(payment_profile_ids))
logger.info(f"Assigning {num_to_update} payment profile IDs to cards")
print(f"Assigning {num_to_update} payment profile IDs to cards")
if len(payment_profile_ids) != len(cards):
logger.warning(f"Mismatch between payment profile count ({len(payment_profile_ids)}) and card count ({len(cards)})")
@@ -222,10 +189,10 @@ def create_user_account(db: Session, customer_id: int) -> dict:
if payment_profile_ids[i] and str(payment_profile_ids[i]).strip(): # Validate the ID exists and isn't empty
cards[i].auth_net_payment_profile_id = str(payment_profile_ids[i]) # Ensure string
db.add(cards[i])
logger.info(f"Successfully assigned payment profile ID '{payment_profile_ids[i]}' to card {cards[i].id}")
print(f"Successfully assigned payment profile ID '{payment_profile_ids[i]}' to card {cards[i].id}")
cards_updated += 1
else:
logger.error(f"Missing or invalid payment profile ID '{payment_profile_ids[i]}' for card {cards[i].id}")
print(f"Missing or invalid payment profile ID '{payment_profile_ids[i]}' for card {cards[i].id}")
# Save customer profile ID if not set (handle both new and existing case)
if not customer.auth_net_profile_id:
@@ -234,35 +201,35 @@ def create_user_account(db: Session, customer_id: int) -> dict:
# Commit all changes
db.commit()
logger.info(f"Successfully committed payment profile IDs to database ({cards_updated} cards updated)")
print(f"Successfully committed payment profile IDs to database ({cards_updated} cards updated)")
# Enhanced verification - check what was actually saved
logger.info("Verifying payment profile IDs were saved correctly:")
print("Verifying payment profile IDs were saved correctly:")
all_saved_correctly = True
for i, card in enumerate(cards[:num_to_update]):
committed_card = crud.get_card_by_id(db, card.id)
if committed_card and committed_card.auth_net_payment_profile_id:
logger.info(f"SUCCESS: Card {card.id} has payment profile ID '{committed_card.auth_net_payment_profile_id}'")
print(f"SUCCESS: Card {card.id} has payment profile ID '{committed_card.auth_net_payment_profile_id}'")
else:
logger.error(f"ERROR: Card {card.id} is missing payment profile ID")
print(f"ERROR: Card {card.id} is missing payment profile ID")
all_saved_correctly = False
if not all_saved_correctly:
logger.error("PAYMENT PROFILE ASSIGNMENT ERRORS DETECTED - This may cause transaction failures!")
print("PAYMENT PROFILE ASSIGNMENT ERRORS DETECTED - This may cause transaction failures!")
operation_type = "created" if not original_profile_id else "updated"
logger.info(f"Successfully {operation_type} Authorize.net profile {auth_profile_id} for customer {customer_id} with {len(cards)} cards")
print(f"Successfully {operation_type} Authorize.net profile {auth_profile_id} for customer {customer_id} with {len(cards)} cards")
# 🔄 PROACTIVELY REFRESH PAYMENT PROFILES TO ENSURE VALIDITY
logger.info(f"🔄 Auto-refresh START: customer_id={customer_id}, auth_profile_id={auth_profile_id}")
logger.info(f"🔄 Auto-refresh BEFORE: Cards have these payment profile IDs: {[f'card_{c.id}={c.auth_net_payment_profile_id}' for c in cards]}")
print(f"🔄 Auto-refresh START: customer_id={customer_id}, auth_profile_id={auth_profile_id}")
print(f"🔄 Auto-refresh BEFORE: Cards have these payment profile IDs: {[f'card_{c.id}={c.auth_net_payment_profile_id}' for c in cards]}")
# Check what changed after refresh
cards_after = crud.get_customer_cards(db, customer_id)
logger.info(f"🔄 Auto-refresh AFTER: Cards now have these payment profile IDs: {[f'card_{c.id}={c.auth_net_payment_profile_id}' for c in cards_after]}")
logger.info(f"🔄 Auto-refresh COMPLETE - IDs changed: {len([c for c in cards if c.auth_net_payment_profile_id != cards_after[cards.index(c)].auth_net_payment_profile_id])} cards updated")
print(f"🔄 Auto-refresh AFTER: Cards now have these payment profile IDs: {[f'card_{c.id}={c.auth_net_payment_profile_id}' for c in cards_after]}")
print(f"🔄 Auto-refresh COMPLETE - IDs changed: {len([c for c in cards if c.auth_net_payment_profile_id != cards_after[cards.index(c)].auth_net_payment_profile_id])} cards updated")
return {
"success": True,
@@ -272,7 +239,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
}
except Exception as e:
logger.error(f"Critical exception during user account creation for customer {customer_id}: {traceback.format_exc()}")
print(f"Critical exception during user account creation for customer {customer_id}: {traceback.format_exc()}")
db.rollback()
return {
"success": False,
@@ -303,70 +270,74 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
# Get customer's current cards from database
cards_before = crud.get_customer_cards(db, customer_id)
customer = crud.get_customer(db, customer_id)
logger.info(f"🔄 Refresh START: customer_id={customer_id}, profile_id={auth_profile_id}, current cards={len(cards_before)}")
print(f"🔄 Refresh START: customer_id={customer_id}, profile_id={auth_profile_id}, current cards={len(cards_before)}")
# STEP 1: Try to get actual payment profiles from Authorize.net
payment_profile_ids = []
try:
payment_profile_ids = payment_service.get_customer_payment_profiles(auth_profile_id)
logger.info(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}")
print(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}")
except Exception as e:
logger.warning(f"🔄 Could not retrieve payment profiles from Authorize.net: {str(e)}")
logger.info("🔄 Will attempt to recreate missing payment profiles")
print("🔄 Will attempt to recreate missing payment profiles")
# STEP 2: Check if we have enough payment profiles for our cards
cards_need_update = []
for card in cards_before:
if not card.auth_net_payment_profile_id or card.auth_net_payment_profile_id.strip() == "":
cards_need_update.append(card)
logger.info(f"🔄 Card {card.id} needs payment profile ID assignment")
print(f"🔄 Card {card.id} needs payment profile ID assignment")
elif str(card.auth_net_payment_profile_id) not in [str(pid) for pid in payment_profile_ids if pid]:
# Payment profile ID exists in DB but not found in Authorize.net - likely invalid
cards_need_update.append(card)
logger.warning(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} but it's not found in Authorize.net - NEEDS RECREATION")
else:
# Profile exists in Authorize.net, but let's double-check it's usable by doing a quick test
logger.info(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - testing usability...")
try:
test_req = schemas.TransactionAuthorizeByCardID(
card_id=card.id,
preauthorize_amount="0.01"
)
test_response = payment_service.authorize_customer_profile(
customer_profile_id=customer.auth_net_profile_id,
payment_profile_id=card.auth_net_payment_profile_id,
transaction_req=test_req,
db_session=None, customer_id=None, card_id=None
)
if ApplicationConfig.penny_test_transaction:
# Profile exists in Authorize.net, but let's double-check it's usable by doing a quick test
print(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - testing usability...")
try:
test_req = schemas.TransactionAuthorizeByCardID(
card_id=card.id,
preauthorize_amount="0.01"
)
test_response = payment_service.authorize_customer_profile(
customer_profile_id=customer.auth_net_profile_id,
payment_profile_id=card.auth_net_payment_profile_id,
transaction_req=test_req,
db_session=None, customer_id=None, card_id=None
)
# Check test result
_, _, test_reason = payment_service._parse_authnet_response(test_response)
if "E00121" in str(test_reason):
cards_need_update.append(card)
logger.warning(f"🔄 Card {card.id} has profile {card.auth_net_payment_profile_id} that EXISTS but is CORRUPTED - NEEDS RECREATION")
# Explicitly delete the corrupted profile first
try:
from . import user_delete
delete_success = user_delete._delete_payment_profile(customer.auth_net_profile_id, card.auth_net_payment_profile_id)
if delete_success:
logger.info(f"🔄 Successfully deleted corrupted payment profile {card.auth_net_payment_profile_id}")
card.auth_net_payment_profile_id = None
db.add(card)
except Exception as del_e:
logger.warning(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}")
else:
logger.debug(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}")
except Exception as test_e:
logger.warning(f"🔄 Could not test usability of profile {card.auth_net_payment_profile_id} for card {card.id}: {str(test_e)} - assuming it's okay")
# Check test result
_, _, test_reason = payment_service._parse_authnet_response(test_response)
if "E00121" in str(test_reason):
cards_need_update.append(card)
logger.warning(f"🔄 Card {card.id} has profile {card.auth_net_payment_profile_id} that EXISTS but is CORRUPTED - NEEDS RECREATION")
# Explicitly delete the corrupted profile first
try:
from . import user_delete
delete_success = user_delete._delete_payment_profile(customer.auth_net_profile_id, card.auth_net_payment_profile_id)
if delete_success:
print(f"🔄 Successfully deleted corrupted payment profile {card.auth_net_payment_profile_id}")
card.auth_net_payment_profile_id = None
db.add(card)
except Exception as del_e:
logger.warning(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}")
else:
logger.debug(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}")
except Exception as test_e:
logger.warning(f"🔄 Could not test usability of profile {card.auth_net_payment_profile_id} for card {card.id}: {str(test_e)} - assuming it's okay")
else:
print(f"🔄 Skipping penny test transaction for card {card.id} (disabled in config)")
logger.debug(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - skipping usability test (config disabled)")
# STEP 3: If we don't have enough valid payment profiles, recreate missing ones
if len(cards_need_update) > 0:
logger.info(f"🔄 Need to recreate {len(cards_need_update)} payment profiles")
print(f"🔄 Need to recreate {len(cards_need_update)} payment profiles")
# Clear payment profile IDs for cards that need recreation (they're invalid anyway)
for card in cards_need_update:
if card.auth_net_payment_profile_id:
logger.info(f"🔄 Clearing invalid payment profile ID {card.auth_net_payment_profile_id} for card {card.id}")
print(f"🔄 Clearing invalid payment profile ID {card.auth_net_payment_profile_id} for card {card.id}")
card.auth_net_payment_profile_id = None
db.add(card)
@@ -388,7 +359,7 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
cvv=card.security_number
)
logger.info(f"🔄 Recreating payment profile for card {card.id} (**** **** **** {card.last_four_digits})")
print(f"🔄 Recreating payment profile for card {card.id} (**** **** **** {card.last_four_digits})")
new_payment_profile_id = payment_service.add_payment_profile_to_customer(
auth_profile_id, customer, card_create_data, is_default=(card.main_card == True)
)
@@ -397,43 +368,43 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
card.auth_net_payment_profile_id = str(new_payment_profile_id)
db.add(card)
recreated_cards.append(card)
logger.info(f"✅ Successfully recreated payment profile {new_payment_profile_id} for card {card.id}")
print(f"✅ Successfully recreated payment profile {new_payment_profile_id} for card {card.id}")
else:
logger.error(f"❌ Failed to recreate payment profile for card {card.id} - no ID returned")
print(f"❌ Failed to recreate payment profile for card {card.id} - no ID returned")
except Exception as e:
logger.error(f"❌ Failed to recreate payment profile for card {card.id}: {str(e)}")
print(f"❌ Failed to recreate payment profile for card {card.id}: {str(e)}")
continue
if recreated_cards:
db.commit()
logger.info(f"✅ Successfully recreated and saved {len(recreated_cards)} payment profiles")
print(f"✅ Successfully recreated and saved {len(recreated_cards)} payment profiles")
else:
logger.error("❌ No payment profiles could be recreated - this is a critical failure")
print("❌ No payment profiles could be recreated - this is a critical failure")
return False
else:
logger.info(f"🔄 All {len(cards_before)} cards have valid payment profile IDs")
print(f"🔄 All {len(cards_before)} cards have valid payment profile IDs")
# STEP 4: Final verification that everything looks good
cards_final = crud.get_customer_cards(db, customer_id)
logger.info("🔄 FINAL VERIFICATION:")
print("🔄 FINAL VERIFICATION:")
all_valid = True
for card in cards_final:
status = "✅ VALID" if card.auth_net_payment_profile_id and card.auth_net_payment_profile_id.strip() else "❌ INVALID"
logger.info(f"🔄 {status} Card {card.id}: auth_net_payment_profile_id='{card.auth_net_payment_profile_id}'")
print(f"🔄 {status} Card {card.id}: auth_net_payment_profile_id='{card.auth_net_payment_profile_id}'")
if not card.auth_net_payment_profile_id or card.auth_net_payment_profile_id.strip() == "":
all_valid = False
if all_valid:
logger.info(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs")
print(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs")
return True
else:
logger.warning("🔄 Refresh PARTIAL: Some cards may still have invalid payment profile IDs")
return False
except Exception as e:
logger.error(f"🔄 Refresh FAILED for customer {customer_id}: {str(e)}")
logger.error(f"🔄 Refresh traceback: {traceback.format_exc()}")
print(f"🔄 Refresh FAILED for customer {customer_id}: {str(e)}")
print(f"🔄 Refresh traceback: {traceback.format_exc()}")
db.rollback()
return False