import arrow from typing import List, Any from Schemas import AccountRecords from jinja2 import Environment, FileSystemLoader from Controllers.Email.send_email import EmailSendModel, EmailService def render_email_template( headers: List[str], rows: List[List[Any]], balance_error: bool, bank_balance: str ) -> str: """ Render the HTML email template with the provided data. Args: headers: List of column headers for the table rows: List of data rows for the table balance_error: Flag indicating if there's a balance discrepancy bank_balance: Current bank balance formatted as string Returns: Rendered HTML template as string """ try: # Look for template in ServiceDepends directory env = Environment(loader=FileSystemLoader("/")) template = env.get_template("template_accounts.html") # Render template with variables return template.render( headers=headers, rows=rows, bank_balance=bank_balance, balance_error=balance_error, today=str(arrow.now().date()), ) except Exception as e: print('Exception render template:',e) err = e raise def send_email_to_given_address(send_to: str, html_template: str) -> bool: """ Send email with the rendered HTML template to the specified address. Args: send_to: Email address of the recipient html_template: Rendered HTML template content Returns: Boolean indicating if the email was sent successfully """ today = arrow.now() subject = f"{str(today.date())} Gunes Apt. Cari Durum Bilgilendirme Raporu" # Create email parameters using EmailSendModel email_params = EmailSendModel( subject=subject, html=html_template, receivers=[send_to], text=f"Gunes Apt. Cari Durum Bilgilendirme Raporu - {today.date()}" ) try: # Use the context manager to handle connection errors with EmailService.new_session() as email_session: # Send email through the service EmailService.send_email(email_session, email_params) return True except Exception as e: print(f'Exception send email: {e}') return False def set_account_records_to_send_email() -> bool: """ Retrieve account records from the database, format them, and send an email report. Usage: from app import set_account_records_to_send_email Returns: Boolean indicating if the process completed successfully """ # Get database session and retrieve records with AccountRecords.new_session() as db_session: account_records_query = AccountRecords.filter_all(db=db_session).query # Get the 3 most recent records account_records: List[AccountRecords] | [] = ( account_records_query.order_by( AccountRecords.bank_date.desc(), AccountRecords.bank_reference_code.desc() ) .limit(3) .all() ) # Check if we have enough records if len(account_records) < 2: return False # Check for balance discrepancy first_record, second_record = account_records[0], account_records[1] expected_second_balance = first_record.bank_balance - first_record.currency_value balance_error = expected_second_balance != second_record.bank_balance if balance_error: return False # Format rows for the email template list_of_rows = [] for record in account_records: list_of_rows.append([ record.bank_date.strftime("%d/%m/%Y %H:%M"), record.process_comment, f"{record.currency_value:,.2f}", f"{record.bank_balance:,.2f}" ]) # Get the most recent bank balance last_bank_balance = sorted(account_records, key=lambda x: x.bank_date, reverse=True)[0].bank_balance # Define headers for the table headers = ["Ulaştığı Tarih", "Banka Transaksiyonu Ek Bilgi", "Aktarım Değeri", "Banka Bakiyesi"] # Recipient email address send_to = "karatay@mehmetkaratay.com.tr" # Render email template html_template = render_email_template( headers=headers, rows=list_of_rows, balance_error=balance_error, bank_balance=f"{last_bank_balance:,.2f}", ) # Send the email return send_email_to_given_address(send_to=send_to, html_template=html_template) if __name__ == "__main__": success = set_account_records_to_send_email() exit_code = 0 if success else 1 exit(exit_code)