major claude changes
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import logging
|
||||
import pprint
|
||||
import traceback
|
||||
from authorizenet import apicontractsv1
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from authorizenet.apicontrollers import (
|
||||
createCustomerProfileController,
|
||||
createCustomerPaymentProfileController
|
||||
@@ -64,7 +65,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
|
||||
"message": f"Customer {customer_id} not found",
|
||||
"profile_id": None
|
||||
}
|
||||
print(f"Found customer id={customer}")
|
||||
logger.debug(f"Found customer id={customer}")
|
||||
# Get customer's cards from database
|
||||
cards = crud.get_customer_cards(db, customer_id)
|
||||
if not cards:
|
||||
@@ -79,9 +80,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
|
||||
|
||||
# Get the first card to use for initial profile creation
|
||||
first_card = cards[0]
|
||||
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}")
|
||||
logger.debug(f"Using card ID={first_card.id} (****{first_card.card_number[-4:] if first_card.card_number else '----'}) for profile creation")
|
||||
|
||||
# Create CardCreate object for the first card
|
||||
# Format expiration date for string values - pad year to 4 digits and month to 2 digits
|
||||
@@ -97,8 +96,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
|
||||
cvv=first_card.security_number
|
||||
)
|
||||
|
||||
print(f"Card info expiration_date: {card_info.expiration_date}")
|
||||
print(f"Processing Authorize.net profile for customer {customer_id} with {len(cards)} cards")
|
||||
logger.debug(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:
|
||||
@@ -107,7 +105,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)
|
||||
print(f"API call failed: {error_str}")
|
||||
logger.debug(f"API call failed: {error_str}")
|
||||
|
||||
return {
|
||||
"success": False,
|
||||
@@ -118,7 +116,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
|
||||
}
|
||||
|
||||
if not auth_profile_id:
|
||||
print("No auth_profile_id returned from API")
|
||||
logger.debug("No auth_profile_id returned from API")
|
||||
return {
|
||||
"success": False,
|
||||
"message": "Failed to create customer profile - no profile ID returned",
|
||||
@@ -130,12 +128,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
|
||||
)
|
||||
print(f"Successfully added first payment profile: {first_payment_profile_id} (default)")
|
||||
logger.debug(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:
|
||||
print(f"Failed to add payment profile for first card: {str(e)}")
|
||||
logger.debug(f"Failed to add payment profile for first card: {str(e)}")
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"Failed to add first payment profile: {str(e)}",
|
||||
@@ -162,19 +160,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
|
||||
)
|
||||
print(f"Successfully added additional payment profile ID '{payment_profile_id}' for card {card.id}")
|
||||
logger.debug(f"Successfully added additional payment profile ID '{payment_profile_id}' for card {card.id}")
|
||||
except ValueError as e:
|
||||
print(f"Failed to add payment profile for additional card {card.id}: {str(e)}")
|
||||
logger.debug(f"Failed to add payment profile for additional card {card.id}: {str(e)}")
|
||||
else:
|
||||
auth_profile_id = customer.auth_net_profile_id
|
||||
print(f"Using existing Authorize.net profile {auth_profile_id}")
|
||||
logger.debug(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)
|
||||
print(f"DEBUG: Retrieved {len(payment_profile_ids)} payment profile IDs: {payment_profile_ids}")
|
||||
logger.debug(f"DEBUG: Retrieved {len(payment_profile_ids)} payment profile IDs: {payment_profile_ids}")
|
||||
except ValueError as e:
|
||||
print(f"Failed to retrieve payment profiles: {str(e)}")
|
||||
logger.debug(f"Failed to retrieve payment profiles: {str(e)}")
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"Failed to retrieve payment profiles: {str(e)}",
|
||||
@@ -183,21 +181,21 @@ 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))
|
||||
print(f"Assigning {num_to_update} payment profile IDs to cards")
|
||||
logger.debug(f"Assigning {num_to_update} payment profile IDs to cards")
|
||||
|
||||
if len(payment_profile_ids) != len(cards):
|
||||
print(f"Mismatch between payment profile count ({len(payment_profile_ids)}) and card count ({len(cards)})")
|
||||
print("This could cause incorrect payment profile assignments!")
|
||||
logger.debug(f"Mismatch between payment profile count ({len(payment_profile_ids)}) and card count ({len(cards)})")
|
||||
logger.debug("This could cause incorrect payment profile assignments!")
|
||||
|
||||
cards_updated = 0
|
||||
for i in range(num_to_update):
|
||||
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])
|
||||
print(f"Successfully assigned payment profile ID '{payment_profile_ids[i]}' to card {cards[i].id}")
|
||||
logger.debug(f"Successfully assigned payment profile ID '{payment_profile_ids[i]}' to card {cards[i].id}")
|
||||
cards_updated += 1
|
||||
else:
|
||||
print(f"Missing or invalid payment profile ID '{payment_profile_ids[i]}' for card {cards[i].id}")
|
||||
logger.debug(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:
|
||||
@@ -206,35 +204,35 @@ def create_user_account(db: Session, customer_id: int) -> dict:
|
||||
|
||||
# Commit all changes
|
||||
db.commit()
|
||||
print(f"Successfully committed payment profile IDs to database ({cards_updated} cards updated)")
|
||||
logger.debug(f"Successfully committed payment profile IDs to database ({cards_updated} cards updated)")
|
||||
|
||||
# Enhanced verification - check what was actually saved
|
||||
print("Verifying payment profile IDs were saved correctly:")
|
||||
logger.debug("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:
|
||||
print(f"SUCCESS: Card {card.id} has payment profile ID '{committed_card.auth_net_payment_profile_id}'")
|
||||
logger.debug(f"SUCCESS: Card {card.id} has payment profile ID '{committed_card.auth_net_payment_profile_id}'")
|
||||
else:
|
||||
print(f"ERROR: Card {card.id} is missing payment profile ID")
|
||||
logger.debug(f"ERROR: Card {card.id} is missing payment profile ID")
|
||||
all_saved_correctly = False
|
||||
|
||||
if not all_saved_correctly:
|
||||
print("PAYMENT PROFILE ASSIGNMENT ERRORS DETECTED - This may cause transaction failures!")
|
||||
logger.debug("PAYMENT PROFILE ASSIGNMENT ERRORS DETECTED - This may cause transaction failures!")
|
||||
|
||||
operation_type = "created" if not original_profile_id else "updated"
|
||||
print(f"Successfully {operation_type} Authorize.net profile {auth_profile_id} for customer {customer_id} with {len(cards)} cards")
|
||||
logger.debug(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
|
||||
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]}")
|
||||
logger.debug(f"🔄 Auto-refresh START: customer_id={customer_id}, auth_profile_id={auth_profile_id}")
|
||||
logger.debug(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)
|
||||
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")
|
||||
logger.debug(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.debug(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,
|
||||
@@ -244,7 +242,7 @@ def create_user_account(db: Session, customer_id: int) -> dict:
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Critical exception during user account creation for customer {customer_id}: {traceback.format_exc()}")
|
||||
logger.debug(f"Critical exception during user account creation for customer {customer_id}: {traceback.format_exc()}")
|
||||
db.rollback()
|
||||
return {
|
||||
"success": False,
|
||||
@@ -275,31 +273,31 @@ 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)
|
||||
print(f"🔄 Refresh START: customer_id={customer_id}, profile_id={auth_profile_id}, current cards={len(cards_before)}")
|
||||
logger.debug(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)
|
||||
print(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}")
|
||||
logger.debug(f"🔄 Retrieved {len(payment_profile_ids)} payment profiles from Authorize.net: {payment_profile_ids}")
|
||||
except Exception as e:
|
||||
print(f"🔄 Could not retrieve payment profiles from Authorize.net: {str(e)}")
|
||||
print("🔄 Will attempt to recreate missing payment profiles")
|
||||
logger.debug(f"🔄 Could not retrieve payment profiles from Authorize.net: {str(e)}")
|
||||
logger.debug("🔄 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)
|
||||
print(f"🔄 Card {card.id} needs payment profile ID assignment")
|
||||
logger.debug(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)
|
||||
print(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} but it's not found in Authorize.net - NEEDS RECREATION")
|
||||
logger.debug(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:
|
||||
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...")
|
||||
logger.debug(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,
|
||||
@@ -316,33 +314,33 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
|
||||
_, _, test_reason = payment_service._parse_authnet_response(test_response)
|
||||
if "E00121" in str(test_reason):
|
||||
cards_need_update.append(card)
|
||||
print(f"🔄 Card {card.id} has profile {card.auth_net_payment_profile_id} that EXISTS but is CORRUPTED - NEEDS RECREATION")
|
||||
logger.debug(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}")
|
||||
logger.debug(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:
|
||||
print(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}")
|
||||
logger.debug(f"🔄 Failed to delete corrupted profile {card.auth_net_payment_profile_id}: {str(del_e)}")
|
||||
else:
|
||||
print(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}")
|
||||
logger.debug(f"🔄 Card {card.id} has valid and usable payment profile ID {card.auth_net_payment_profile_id}")
|
||||
except Exception as test_e:
|
||||
print(f"🔄 Could not test usability of profile {card.auth_net_payment_profile_id} for card {card.id}: {str(test_e)} - assuming it's okay")
|
||||
logger.debug(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)")
|
||||
print(f"🔄 Card {card.id} has payment profile ID {card.auth_net_payment_profile_id} in Authorize.net - skipping usability test (config disabled)")
|
||||
logger.debug(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:
|
||||
print(f"🔄 Need to recreate {len(cards_need_update)} payment profiles")
|
||||
logger.debug(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:
|
||||
print(f"🔄 Clearing invalid payment profile ID {card.auth_net_payment_profile_id} for card {card.id}")
|
||||
logger.debug(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)
|
||||
|
||||
@@ -364,7 +362,7 @@ def refresh_customer_payment_profiles(db: Session, customer_id: int, auth_profil
|
||||
cvv=card.security_number
|
||||
)
|
||||
|
||||
print(f"🔄 Recreating payment profile for card {card.id} (**** **** **** {card.last_four_digits})")
|
||||
logger.debug(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)
|
||||
)
|
||||
@@ -373,43 +371,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)
|
||||
print(f"✅ Successfully recreated payment profile {new_payment_profile_id} for card {card.id}")
|
||||
logger.debug(f"✅ Successfully recreated payment profile {new_payment_profile_id} for card {card.id}")
|
||||
else:
|
||||
print(f"❌ Failed to recreate payment profile for card {card.id} - no ID returned")
|
||||
logger.debug(f"❌ Failed to recreate payment profile for card {card.id} - no ID returned")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Failed to recreate payment profile for card {card.id}: {str(e)}")
|
||||
logger.debug(f"❌ Failed to recreate payment profile for card {card.id}: {str(e)}")
|
||||
continue
|
||||
|
||||
if recreated_cards:
|
||||
db.commit()
|
||||
print(f"✅ Successfully recreated and saved {len(recreated_cards)} payment profiles")
|
||||
logger.debug(f"✅ Successfully recreated and saved {len(recreated_cards)} payment profiles")
|
||||
else:
|
||||
print("❌ No payment profiles could be recreated - this is a critical failure")
|
||||
logger.debug("❌ No payment profiles could be recreated - this is a critical failure")
|
||||
return False
|
||||
else:
|
||||
print(f"🔄 All {len(cards_before)} cards have valid payment profile IDs")
|
||||
logger.debug(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)
|
||||
print("🔄 FINAL VERIFICATION:")
|
||||
logger.debug("🔄 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"
|
||||
print(f"🔄 {status} Card {card.id}: auth_net_payment_profile_id='{card.auth_net_payment_profile_id}'")
|
||||
logger.debug(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:
|
||||
print(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs")
|
||||
logger.debug(f"🔄 Refresh COMPLETE: All {len(cards_final)} cards have valid payment profile IDs")
|
||||
return True
|
||||
else:
|
||||
print("🔄 Refresh PARTIAL: Some cards may still have invalid payment profile IDs")
|
||||
logger.debug("🔄 Refresh PARTIAL: Some cards may still have invalid payment profile IDs")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"🔄 Refresh FAILED for customer {customer_id}: {str(e)}")
|
||||
print(f"🔄 Refresh traceback: {traceback.format_exc()}")
|
||||
logger.debug(f"🔄 Refresh FAILED for customer {customer_id}: {str(e)}")
|
||||
logger.debug(f"🔄 Refresh traceback: {traceback.format_exc()}")
|
||||
db.rollback()
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user