""" Notification Handler Module This module handles failed payment notifications and ticket creation. """ import logging from payment_services.payment_service import create_customer_friendly_message from notification_service import NotificationService logger = logging.getLogger(__name__) def handle_failed_payment_notification(payment_record, error_details: str, cust_stripe_details: dict, payment_type: str = "batch"): """ Handle notification and ticket creation for failed payments. Args: payment_record: Database payment record (Payments or SinglePayments) error_details: Error message details payment_type: Type of payment ("batch" or "single") """ # Import here to avoid circular dependencies from splynx import Splynx, SPLYNX_URL, SPLYNX_KEY, SPLYNX_SECRET from config import Config try: # Initialize services splynx = Splynx(url=SPLYNX_URL, key=SPLYNX_KEY, secret=SPLYNX_SECRET) notification_service = NotificationService() # Get customer information from Splynx try: customer_data = splynx.Customer(payment_record.Splynx_ID) customer_name = customer_data.get('name', 'Unknown Customer') if customer_data != 'unknown' else 'Unknown Customer' except: customer_name = 'Unknown Customer' # Prepare payment data for notification payment_data = { 'payment_id': payment_record.id, 'splynx_id': payment_record.Splynx_ID, 'amount': abs(payment_record.Payment_Amount), 'error': error_details, 'payment_method': payment_record.Payment_Method or 'Unknown', 'customer_name': customer_name, 'payment_type': payment_type, 'stripe_customer_id': payment_record.Stripe_Customer_ID, 'payment_intent': payment_record.Payment_Intent } # Revert pending invoices back to "not_paid" (only in live mode) from payment_services.payment_service import find_set_pending_splynx_invoices_to_unpaid updated_invoices = find_set_pending_splynx_invoices_to_unpaid(splynx, payment_record.Splynx_ID) if updated_invoices: logger.info(f"Payment failure: pending invoices reverted to not_paid for Splynx ID {payment_record.Splynx_ID}") else: logger.warning(f"No pending invoices to revert for Splynx ID {payment_record.Splynx_ID}") # Send email notification email_sent = notification_service.send_payment_failure_notification(payment_data) if email_sent: logger.info(f"Payment failure email sent for payment {payment_record.id}") else: logger.error(f"Failed to send payment failure email for payment {payment_record.id}") # Create Splynx ticket ticket_subject = f"Payment Failure - Customer {payment_record.Splynx_ID} - ${abs(payment_record.Payment_Amount):.2f}" internal_message = f"""