| Conditions | 22 |
| Total Lines | 124 |
| Code Lines | 85 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like app.getemail.process_email_balances() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | #!/usr/bin/env python3 |
||
| 28 | def process_email_balances(): |
||
| 29 | """ |
||
| 30 | Process email inboxes for all users with email settings configured |
||
| 31 | and update their balance information from bank emails. |
||
| 32 | |||
| 33 | This function supports both SQLite and PostgreSQL through SQLAlchemy. |
||
| 34 | """ |
||
| 35 | # OUTER LOOP: Get all users with email settings configured |
||
| 36 | users_with_email = db.session.query(User, Email).join( |
||
| 37 | Email, User.id == Email.user_id |
||
| 38 | ).all() |
||
| 39 | |||
| 40 | for user, email_config in users_with_email: |
||
| 41 | user_id = user.id |
||
| 42 | username = email_config.email |
||
| 43 | password = email_config.password |
||
| 44 | imap_server = email_config.server |
||
| 45 | subjectstr = email_config.subjectstr |
||
| 46 | startstr = email_config.startstr |
||
| 47 | endstr = email_config.endstr |
||
| 48 | |||
| 49 | try: |
||
| 50 | # Create IMAP connection for THIS user |
||
| 51 | imap = imaplib.IMAP4_SSL(imap_server) |
||
| 52 | imap.login(username, password) |
||
| 53 | |||
| 54 | status, messages = imap.select("INBOX", readonly=True) |
||
| 55 | |||
| 56 | # Filter for emails from the past day to limit inbox processing |
||
| 57 | # IMAP SINCE searches for messages with Date on or after the specified date |
||
| 58 | yesterday = (datetime.now() - timedelta(days=1)).strftime("%d-%b-%Y") |
||
| 59 | status, message_ids = imap.search(None, f'SINCE {yesterday}') |
||
| 60 | |||
| 61 | # Parse message IDs from the search result |
||
| 62 | if message_ids[0]: |
||
| 63 | email_ids = message_ids[0].split() |
||
| 64 | else: |
||
| 65 | email_ids = [] |
||
| 66 | |||
| 67 | print(f"Found {len(email_ids)} email(s) from the past day for user {user_id}") |
||
| 68 | |||
| 69 | email_content = {} |
||
| 70 | |||
| 71 | # INNER LOOP: Process only emails from the past day |
||
| 72 | for email_id in email_ids: |
||
| 73 | try: |
||
| 74 | res, msg = imap.fetch(email_id, "(RFC822)") |
||
| 75 | for response in msg: |
||
| 76 | if isinstance(response, tuple): |
||
| 77 | msg = email.message_from_bytes(response[1]) |
||
| 78 | |||
| 79 | # Decode subject |
||
| 80 | subject, encoding = decode_header(msg["Subject"])[0] |
||
| 81 | if isinstance(subject, bytes): |
||
| 82 | try: |
||
| 83 | subject = subject.decode(encoding) |
||
| 84 | except: |
||
| 85 | subject = "subject" |
||
| 86 | |||
| 87 | # Decode sender |
||
| 88 | From, encoding = decode_header(msg.get("From"))[0] |
||
| 89 | if isinstance(From, bytes): |
||
| 90 | try: |
||
| 91 | From = From.decode(encoding) |
||
| 92 | except: |
||
| 93 | pass |
||
| 94 | |||
| 95 | # Extract email body |
||
| 96 | if msg.is_multipart(): |
||
| 97 | for part in msg.walk(): |
||
| 98 | content_type = part.get_content_type() |
||
| 99 | content_disposition = str(part.get("Content-Disposition")) |
||
| 100 | try: |
||
| 101 | body = part.get_payload(decode=True).decode() |
||
| 102 | except: |
||
| 103 | pass |
||
| 104 | if content_type == "text/plain" and "attachment" not in content_disposition: |
||
| 105 | try: |
||
| 106 | email_content[subject] = body |
||
| 107 | except: |
||
| 108 | pass |
||
| 109 | else: |
||
| 110 | content_type = msg.get_content_type() |
||
| 111 | body = msg.get_payload(decode=True).decode() |
||
| 112 | if content_type == "text/plain": |
||
| 113 | try: |
||
| 114 | email_content[subject] = body |
||
| 115 | except: |
||
| 116 | pass |
||
| 117 | except: |
||
| 118 | pass # Skip individual email errors |
||
| 119 | |||
| 120 | # Extract balance from emails for THIS user |
||
| 121 | try: |
||
| 122 | start_index = email_content[subjectstr].find(startstr) + len(startstr) |
||
| 123 | end_index = email_content[subjectstr].find(endstr) |
||
| 124 | new_balance = email_content[subjectstr][start_index:end_index].replace(',', '') |
||
| 125 | new_balance = new_balance.replace('$', '') |
||
| 126 | new_balance = float(new_balance) |
||
| 127 | |||
| 128 | # Insert balance WITH user_id using SQLAlchemy ORM |
||
| 129 | balance = Balance( |
||
| 130 | amount=new_balance, |
||
| 131 | date=datetime.today().date(), |
||
| 132 | user_id=user_id |
||
| 133 | ) |
||
| 134 | db.session.add(balance) |
||
| 135 | db.session.commit() |
||
| 136 | print(f"Successfully imported balance ${new_balance} for user {user_id}") |
||
| 137 | except KeyError: |
||
| 138 | # No email with the specified subject found |
||
| 139 | pass |
||
| 140 | except Exception as e: |
||
| 141 | # No balance found in emails for this user |
||
| 142 | print(f"Could not extract balance for user {user_id}: {e}") |
||
| 143 | |||
| 144 | # Close IMAP connection for THIS user |
||
| 145 | imap.close() |
||
| 146 | imap.logout() |
||
| 147 | |||
| 148 | except Exception as e: |
||
| 149 | # Failed to connect to IMAP for this user - skip to next user |
||
| 150 | print(f"Failed to process emails for user {user_id}: {e}") |
||
| 151 | continue |
||
| 152 | |||
| 284 |