## File: your_app/views.py from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from typing import Tuple, Optional import enum from .. import crud, models, schemas, database from ..services import payment_service from config import load_config ApplicationConfig = load_config() AuthNetResponse = object router = APIRouter( prefix="/payments", tags=["Payments & Transactions"], ) class TransactionStatus(enum.IntEnum): APPROVED = 0 DECLINED = 1 class TransactionType(enum.IntEnum): CHARGE = 0 AUTHORIZE = 1 CAPTURE = 3 # --- NEW CIM CORE FUNCTIONS --- STATE_ID_TO_ABBREVIATION = { 0: "MA", 1: "RI", 2: "NH", 3: "ME", 4: "VT", 5: "CT", 6: "NY" } def _parse_authnet_response(response: Optional[AuthNetResponse]) -> Tuple[TransactionStatus, Optional[str], Optional[str]]: """ 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}") if response is not None: print("DEBUG: Checking for messages attribute...") if hasattr(response, 'messages'): print(f"DEBUG: Messages exist, resultCode: {getattr(response.messages, 'resultCode', 'NO resultCode')}") else: print("DEBUG: No messages attribute") if response.messages.resultCode == "Ok": print("DEBUG: Taking APPROVED path") status = TransactionStatus.APPROVED auth_net_transaction_id = None # Extract transaction ID with proper error handling try: if hasattr(response, 'transactionResponse') and response.transactionResponse: 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}") else: print("DEBUG: transactionResponse exists but no transId") else: print("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)) if hasattr(response, 'transactionResponse'): print(f"TransactionResponse type: {type(response.transactionResponse)}") print(dir(response.transactionResponse)) rejection_reason = None print(f"DEBUG: APPROVED - ID: {auth_net_transaction_id}, rejection: {rejection_reason}") else: print("DEBUG: Taking DECLINED path") status = TransactionStatus.DECLINED auth_net_transaction_id = None rejection_reason = "Payment declined by gateway." if response is not None: # Handle transaction response errors if hasattr(response, 'transactionResponse') and response.transactionResponse: if hasattr(response.transactionResponse, 'errors') and response.transactionResponse.errors: print("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}") except Exception as e: print(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") try: msg = response.messages.message if isinstance(msg, list): msg = msg[0] if msg else None if msg: code = getattr(msg, 'code', 'Unknown') text = getattr(msg, 'text', 'Unknown error') rejection_reason = f"{code}: {text}" print(f"DEBUG: Message error: {rejection_reason}") except Exception as e: print(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}") return status, auth_net_transaction_id, rejection_reason @router.post("/customers/{customer_id}/cards", summary="Add a new payment card for a customer") def add_card_to_customer(customer_id: int, card_info: schemas.CardCreate, db: Session = Depends(database.get_db)): """ Adds a new credit card to a customer. - If the customer doesn't have an Authorize.Net profile, it creates one. - If they do, it adds a new payment method to their existing profile. Returns the payment_profile_id from Authorize.Net. """ db_customer = crud.get_customer(db, customer_id=customer_id) if not db_customer: raise HTTPException(status_code=404, detail="Customer not found") # We still need this schema for the payment service call customer_schema = schemas.Customer.from_orm(db_customer) payment_profile_id = None try: # This part now works because the service hard-codes the state to "MA" if not db_customer.auth_net_profile_id: profile_id, payment_id = payment_service.create_customer_profile( customer=customer_schema, card_info=card_info ) crud.update_customer_auth_net_profile_id(db, customer_id=customer_id, profile_id=profile_id) payment_profile_id = payment_id else: payment_profile_id = payment_service.add_payment_profile_to_customer( customer_profile_id=db_customer.auth_net_profile_id, customer=customer_schema, card_info=card_info ) # Return the payment_profile_id return {"payment_profile_id": payment_profile_id} except ValueError as e: # This will catch errors from the payment service raise HTTPException(status_code=400, detail=str(e)) except Exception as e: # This will catch any other unexpected errors, like from the database raise HTTPException(status_code=500, detail="An internal server error occurred.") @router.put("/customers/{customer_id}/cards/{card_id}", summary="Update an existing payment card for a customer") def update_card_for_customer(customer_id: int, card_id: int, card_info: schemas.CardCreate, db: Session = Depends(database.get_db)): """ Updates an existing credit card for a customer. - If the card has an existing Authorize.Net payment profile, deletes it first. - Creates a new payment profile with updated card information. - Updates the database card record with the new payment_profile_id. Returns the new payment_profile_id from Authorize.Net. """ db_customer = crud.get_customer(db, customer_id=customer_id) if not db_customer: raise HTTPException(status_code=404, detail="Customer not found") db_card = crud.get_card_by_id(db, card_id=card_id) if not db_card or db_card.user_id != customer_id: raise HTTPException(status_code=404, detail="Card not found for this customer") if not db_customer.auth_net_profile_id: raise HTTPException(status_code=400, detail="Customer does not have an Authorize.Net profile") customer_schema = schemas.Customer.from_orm(db_customer) 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") 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}") # Delete existing payment profile if it exists if db_card.auth_net_payment_profile_id: from ..services import user_delete delete_success = user_delete._delete_payment_profile( 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}") # 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}") # Create new payment profile with updated card information new_payment_profile_id = payment_service.add_payment_profile_to_customer( customer_profile_id=db_customer.auth_net_profile_id, customer=customer_schema, card_info=card_info ) # Update the database card with the new payment profile ID db_card.auth_net_payment_profile_id = new_payment_profile_id db.add(db_card) db.commit() 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} except ValueError as e: db.rollback() raise HTTPException(status_code=400, detail=str(e)) except Exception as e: db.rollback() print(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") def charge_saved_card(customer_id: int, transaction_req: schemas.TransactionCreateByCardID, db: Session = Depends(database.get_db)): db_customer = crud.get_customer(db, customer_id=customer_id) db_card = crud.get_card_by_id(db, card_id=transaction_req.card_id) 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") if not db_customer.auth_net_profile_id or not db_card.auth_net_payment_profile_id: raise HTTPException(status_code=400, detail="Payment profile is not set up correctly for this customer/card") auth_net_response = payment_service.charge_customer_profile( customer_profile_id=db_customer.auth_net_profile_id, payment_profile_id=db_card.auth_net_payment_profile_id, transaction_req=transaction_req ) status, auth_net_transaction_id, rejection_reason = _parse_authnet_response(auth_net_response) transaction_data = schemas.TransactionBase( charge_amount=transaction_req.charge_amount, transaction_type=TransactionType.CHARGE, service_id=transaction_req.service_id, delivery_id=transaction_req.delivery_id, card_id=transaction_req.card_id, rejection_reason=rejection_reason ) return crud.create_transaction(db=db, transaction=transaction_data, customer_id=customer_id, status=status, auth_net_transaction_id=auth_net_transaction_id) @router.post("/authorize/saved-card/{customer_id}", response_model=schemas.Transaction, summary="Authorize a payment on a saved card") def authorize_saved_card(customer_id: int, transaction_req: schemas.TransactionAuthorizeByCardID, db: Session = Depends(database.get_db)): """ 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") db_customer = crud.get_customer(db, customer_id=customer_id) db_card = crud.get_card_by_id(db, card_id=transaction_req.card_id) 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") # 🚨 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}'") # 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}") if (not db_customer.auth_net_profile_id or not db_card.auth_net_payment_profile_id or db_card.auth_net_payment_profile_id.strip() == "" or str(db_card.auth_net_payment_profile_id).lower() == "none" or 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") 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...") 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}") test_profiles = payment_service.get_customer_payment_profiles(db_customer.auth_net_profile_id) print(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}") 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}") else: 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 ) # 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!") 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 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 profile validation: {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) print(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}") # Auto-recover: Refresh payment profiles before transaction from ..services import user_create recovery_success = user_create.refresh_customer_payment_profiles( db, customer_id, db_customer.auth_net_profile_id ) if recovery_success: 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) print(f"🔍 After recovery - payment_profile_id: '{db_card.auth_net_payment_profile_id}'") else: 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." ) # 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") 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") # 🚨 ENHANCED E00121 ERROR HANDLING 🚨 # If transaction still fails with E00121 despite pre-validation, force-nuke the problematic ID auth_net_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=transaction_req, db_session=db, customer_id=customer_id, card_id=db_card.id ) # 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) transaction_data = schemas.TransactionBase( preauthorize_amount=transaction_req.preauthorize_amount, transaction_type=TransactionType.AUTHORIZE, # This is key service_id=transaction_req.service_id, delivery_id=transaction_req.delivery_id, auto_id=transaction_req.auto_id, card_id=transaction_req.card_id, rejection_reason=rejection_reason ) db_transaction = crud.create_transaction( db=db, transaction=transaction_data, customer_id=customer_id, status=transaction_status, auth_net_transaction_id=auth_net_transaction_id ) return db_transaction def _nuclear_e00121_payment_profile_cleanup(db: Session, customer_id: int, card_id: int, corrupted_profile_id: str, customer_profile_id: str) -> bool: """ DEDICATED E00121 NUKER: Forcefully removes problematic payment profile IDs from both database and Authorize.net. This is the nuclear option for when E00121 payment profile errors persist despite all attempts to recover. Args: db: Database session customer_id: Customer ID card_id: Card ID that has the corrupted profile corrupted_profile_id: The problematic payment profile ID causing E00121 customer_profile_id: Customer profile ID in Authorize.net Returns: bool: True if cleanup successful and card can be retried """ print("💣 NUCLEAR E00121 CLEANUP INITIATED! 💣") print(f"💣 Target: Card {card_id}, Profile {corrupted_profile_id}") try: from .. import crud from ..services import user_delete # Step 1: Get the card from database card = crud.get_card_by_id(db, card_id) if not card: print(f"💣 ERROR: Card {card_id} not found in database") return False # Step 2: NUKE FROM AUTHORIZE.NET FIRST print(f"💣 Deleting corrupted profile {corrupted_profile_id} from Authorize.net...") try: delete_success = user_delete._delete_payment_profile(customer_profile_id, corrupted_profile_id) if delete_success: print("✅ Successfully deleted corrupted profile from Authorize.net") else: print("⚠️ Profile may not have existed in Authorize.net or delete failed") except Exception as e: print(f"⚠️ Exception deleting from Authorize.net: {str(e)} - continuing anyway") # Step 3: NUKE FROM DATABASE REGARDLESS print(f"💣 Clearing corrupted profile ID {corrupted_profile_id} from database card {card_id}") card.auth_net_payment_profile_id = None db.add(card) db.commit() print("✅ Successfully cleared corrupted profile ID from database") # Step 4: Attempt immediate recreation of payment profile print("💣 Attempting immediate recreation of payment profile...") try: customer = crud.get_customer(db, customer_id) # Format card data for recreation # Convert to string first to handle cases where database returns int instead of string exp_year_str = str(card.expiration_year) exp_month_str = str(card.expiration_month) exp_year = exp_year_str.zfill(4) if len(exp_year_str) < 4 else exp_year_str exp_month = exp_month_str.zfill(2) if len(exp_month_str) < 2 else exp_month_str exp_date = f"{exp_year}-{exp_month}" card_create_data = schemas.CardCreate( card_number=card.card_number, expiration_date=exp_date, cvv=card.security_number ) from ..services import payment_service new_profile_id = payment_service.add_payment_profile_to_customer( customer_profile_id, customer, card_create_data, is_default=(card.main_card == True) ) if new_profile_id: print(f"✅ IMMEDIATE RECREATION SUCCESSFUL: New profile {new_profile_id}") card.auth_net_payment_profile_id = str(new_profile_id) db.add(card) db.commit() print(f"💣 Nuclear cleanup COMPLETE - Card {card_id} has new profile {new_profile_id}") return True else: print("❌ Immediate recreation failed - no new profile ID") return False except Exception as recreate_e: print(f"❌ Immediate recreation failed: {str(recreate_e)}") print("💣 Database cleared but recreation failed - needs manual recreation later") return False except Exception as nuke_e: print(f"💣 CRITICAL ERROR in nuclear cleanup: {str(nuke_e)}") db.rollback() return False # --- CAPTURE ENDPOINT MOVED TO TRANSACTION ROUTER ---