import os import sys file_path = 'core/views.py' with open(file_path, 'r') as f: lines = f.readlines() new_lines = [] skip_until = -1 for i, line in enumerate(lines): new_lines.append(line) if "call.status = 'completed';" in line and i + 1 < len(lines) and "call.save()" in lines[i+1]: # Found the spot indent = lines[i+1][:lines[i+1].find("call.save()")] new_lines.append(lines[i+1]) # Append call.save() # Add the new logic new_lines.append(f"{indent}if call_outcome == 'No Answer No Voice Mail':\n") new_lines.append(f"{indent} voter = call.voter\n") new_lines.append(f"{indent} # If no other pending calls, reset to 'to_be_called' instead of 'called'\n") new_lines.append(f"{indent} from core.models import Voter, ScheduledCall\n") new_lines.append(f"{indent} if not ScheduledCall.objects.filter(voter=voter, status='pending').exists():\n") new_lines.append(f"{indent} Voter.objects.filter(pk=voter.pk).update(call_queue_status='to_be_called')\n") skip_until = i + 1 # Skip next line since we manually added it if skip_until != -1: # We need to filter out the duplicate call.save() final_lines = [] skip = False for i, line in enumerate(lines): if i == skip_until: continue final_lines.append(line) if "call.status = 'completed';" in line and i + 1 < len(lines) and "call.save()" in lines[i+1]: final_lines.append(lines[i+1]) indent = lines[i+1][:lines[i+1].find("call.save()")] final_lines.append(f"{indent}if call_outcome == 'No Answer No Voice Mail':\n") final_lines.append(f"{indent} voter = call.voter\n") final_lines.append(f"{indent} # If no other pending calls, reset to 'to_be_called' instead of 'called'\n") final_lines.append(f"{indent} from core.models import Voter, ScheduledCall\n") final_lines.append(f"{indent} if not ScheduledCall.objects.filter(voter=voter, status='pending').exists():\n") final_lines.append(f"{indent} Voter.objects.filter(pk=voter.pk).update(call_queue_status='to_be_called')\n") # We skip the original next line because we already handled it # But we need to handle the loop correctly. # Actually let's just use a simpler replacement logic. with open(file_path, 'w') as f: f.writelines(final_lines) print("Patch applied.") else: print("Pattern not found.")