#!/usr/bin/env python3 # Debug script to test payment processing functions directly import sys import os from datetime import datetime from time import perf_counter from sqlalchemy import func # Import directly from the draft-first-work.py file in the same directory sys.path.insert(0, '/draft') # Import the necessary functions and classes directly from the file from draft_first_work import * # Import everything for simplicity def debug_find_unpaid_debts(build_parts_id, session): """Find unpaid debts directly using raw SQL for debugging.""" print(f"\nDEBUG: Finding unpaid debts for build part ID: {build_parts_id}") # Set session for the model BuildDecisionBookPayments.set_session(session) # Get payment types payment_types = get_enums_from_database() for payment_type in payment_types: print(f"\nChecking payment type: {payment_type.key}") # Find debits that don't have account_records_id set (unpaid) query = session.query(BuildDecisionBookPayments).filter( BuildDecisionBookPayments.build_parts_id == build_parts_id, BuildDecisionBookPayments.payment_types_id == payment_type.id, BuildDecisionBookPayments.account_is_debit == True, BuildDecisionBookPayments.account_records_id.is_(None) ) # Print the SQL query print(f"SQL Query: {query}") # Execute the query unpaid_debts = query.all() print(f"Found {len(unpaid_debts)} unpaid debts") # Print details of each unpaid debt for i, debt in enumerate(unpaid_debts[:5]): # Limit to first 5 for brevity print(f" Debt {i+1}:") print(f" ID: {debt.id}") print(f" UUID: {debt.uu_id}") print(f" Amount: {abs(debt.payment_amount):,.2f} TL") print(f" Process Date: {debt.process_date}") print(f" Account Records ID: {debt.account_records_id}") # Check if any payments have been made for this debt credit_query = session.query( func.sum(func.abs(BuildDecisionBookPayments.payment_amount)) ).filter( BuildDecisionBookPayments.ref_id == str(debt.uu_id), BuildDecisionBookPayments.account_is_debit == False ) credit_amount = credit_query.scalar() or 0 print(f" Payments made: {credit_amount:,.2f} TL") print(f" Remaining to pay: {abs(debt.payment_amount) - credit_amount:,.2f} TL") def debug_process_payment(build_parts_id, session): """Process a single payment for debugging purposes.""" print(f"\nDEBUG: Processing payment for build part ID: {build_parts_id}") # Set session for all models AccountRecords.set_session(session) BuildDecisionBookPayments.set_session(session) # Get payment types in priority order payment_type_list = get_enums_from_database() # Get account records with positive currency_value account_query = AccountRecords.query.filter( AccountRecords.build_parts_id == build_parts_id, AccountRecords.currency_value > 0, AccountRecords.bank_date >= '2022-01-01' ).order_by(AccountRecords.id.desc()).limit(5) print(f"Account query: {account_query}") account_records = account_query.all() print(f"Found {len(account_records)} account records with funds") # Print account details for i, account in enumerate(account_records): available_funds = abs(account.currency_value) - abs(account.remainder_balance) print(f" Account {i+1}: ID: {account.id}, Build Part ID: {account.build_parts_id}, Value: {account.currency_value:,.2f} TL, Available: {available_funds:,.2f} TL") if not account_records: print("No account records found with funds. Cannot process payments.") return # Use the first account with funds account_record = account_records[0] money_in_account = abs(account_record.currency_value) - abs(account_record.remainder_balance) print(f"\nUsing account ID: {account_record.id} with available funds: {money_in_account:,.2f} TL") # Get the first payment type payment_type = payment_type_list[0] print(f"Using payment type: {payment_type.key}") # Find unpaid debts for this payment type query = session.query(BuildDecisionBookPayments).filter( BuildDecisionBookPayments.build_parts_id == build_parts_id, BuildDecisionBookPayments.payment_types_id == payment_type.id, BuildDecisionBookPayments.account_is_debit == True, BuildDecisionBookPayments.account_records_id.is_(None) ).limit(1) print(f"Unpaid debt query: {query}") unpaid_debt = query.first() if not unpaid_debt: print(f"No unpaid debts found for payment type {payment_type.key}") return print(f"\nFound unpaid debt:") print(f" ID: {unpaid_debt.id}") print(f" UUID: {unpaid_debt.uu_id}") print(f" Amount: {abs(unpaid_debt.payment_amount):,.2f} TL") # Calculate amount to pay debt_amount = abs(unpaid_debt.payment_amount) payment_amount = min(debt_amount, money_in_account) print(f"\nProcessing payment:") print(f" Debt amount: {debt_amount:,.2f} TL") print(f" Available funds: {money_in_account:,.2f} TL") print(f" Will pay: {payment_amount:,.2f} TL") # Make payment try: print("Creating payment record...") before_state = session.query(BuildDecisionBookPayments).filter( BuildDecisionBookPayments.uu_id == unpaid_debt.uu_id ).first() print(f"Before payment - account_records_id: {before_state.account_records_id}") new_payment = close_payment_book(unpaid_debt, account_record, payment_amount, session) # Verify the payment was created after_state = session.query(BuildDecisionBookPayments).filter( BuildDecisionBookPayments.uu_id == unpaid_debt.uu_id ).first() print(f"After payment - account_records_id: {after_state.account_records_id}") # Check if the new payment record was created if new_payment: print(f"New payment record created with ID: {new_payment.id}") print(f"New payment amount: {abs(new_payment.payment_amount):,.2f} TL") print(f"New payment ref_id: {new_payment.ref_id}") print(f"New payment account_is_debit: {new_payment.account_is_debit}") else: print("Failed to create new payment record") # Commit the transaction session.commit() print("Transaction committed successfully") except Exception as e: session.rollback() print(f"Error making payment: {str(e)}") print("Transaction rolled back") if __name__ == "__main__": start_time = perf_counter() print("\n===== PAYMENT PROCESSING DEBUG =====\n") # Create a session session_factory = get_session_factory() session = session_factory() # Set the build part ID to debug build_part_id = 14 # Change this to the build part ID you want to debug # Find unpaid debts debug_find_unpaid_debts(build_part_id, session) # Process a single payment debug_process_payment(build_part_id, session) end_time = perf_counter() print(f"\nDebug completed in {end_time - start_time:.3f} seconds")