142 lines
5.1 KiB
Python
142 lines
5.1 KiB
Python
import os
|
|
import sys
|
|
import django
|
|
import re
|
|
import json
|
|
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
|
django.setup()
|
|
|
|
# Read the file
|
|
with open('core/views.py', 'r') as f:
|
|
content = f.read()
|
|
|
|
lines = content.split('\n')
|
|
start_line = -1
|
|
end_line = -1
|
|
for i, line in enumerate(lines):
|
|
if line.startswith('def door_visits(request):'):
|
|
start_line = i
|
|
elif start_line != -1 and (line.startswith('@role_required([') or line.startswith('def log_door_visit')):
|
|
end_line = i
|
|
break
|
|
|
|
optimized_code = """def door_visits(request):
|
|
\"\"\"
|
|
Manage door knocking visits. Groups unvisited targeted voters by household.
|
|
\"\"\"
|
|
selected_tenant_id = request.session.get("tenant_id")
|
|
if not selected_tenant_id:
|
|
messages.warning(request, "Please select a campaign first.")
|
|
return redirect("index")
|
|
|
|
tenant = get_object_or_404(Tenant, id=selected_tenant_id)
|
|
|
|
city_filter = request.GET.get("city", "").strip()
|
|
district_filter = request.GET.get('district', '').strip()
|
|
neighborhood_filter = request.GET.get('neighborhood', '').strip()
|
|
address_filter = request.GET.get('address', '').strip()
|
|
|
|
voters = Voter.objects.filter(tenant=tenant, door_visit=False, is_targeted=True)
|
|
|
|
if city_filter:
|
|
voters = voters.filter(city__icontains=city_filter)
|
|
if district_filter:
|
|
voters = voters.filter(district=district_filter)
|
|
if neighborhood_filter:
|
|
voters = voters.filter(neighborhood__icontains=neighborhood_filter)
|
|
if address_filter:
|
|
voters = voters.filter(Q(address__icontains=address_filter) | Q(address_street__icontains=address_filter))
|
|
|
|
voters_data = list(voters.values(
|
|
'id', 'first_name', 'last_name', 'address_street', 'city', 'state',
|
|
'zip_code', 'neighborhood', 'district', 'latitude', 'longitude'
|
|
))
|
|
|
|
households_dict = {}
|
|
for v in voters_data:
|
|
key = (v['address_street'], v['city'], v['state'], v['zip_code'])
|
|
if key not in households_dict:
|
|
street_number = ""
|
|
street_name = v['address_street'] or ""
|
|
match = re.match(r'^(\\d+)\\s+(.*)$', street_name)
|
|
if match:
|
|
street_number = match.group(1)
|
|
street_name = match.group(2)
|
|
|
|
try:
|
|
street_number_sort = int(street_number)
|
|
except (ValueError, TypeError):
|
|
street_number_sort = 0
|
|
|
|
households_dict[key] = {
|
|
'address_street': v['address_street'],
|
|
'city': v['city'],
|
|
'state': v['state'],
|
|
'zip_code': v['zip_code'],
|
|
'neighborhood': v['neighborhood'],
|
|
'district': v['district'],
|
|
'latitude': float(v['latitude']) if v['latitude'] else None,
|
|
'longitude': float(v['longitude']) if v['longitude'] else None,
|
|
'street_name_sort': street_name.lower(),
|
|
'street_number_sort': street_number_sort,
|
|
'target_voters': [],
|
|
'voters_json': []
|
|
}
|
|
households_dict[key]['target_voters'].append(v)
|
|
households_dict[key]['voters_json'].append({'id': v['id'], 'name': f"{v['first_name']} {v['last_name']}"})
|
|
|
|
households_list = list(households_dict.values())
|
|
households_list.sort(key=lambda x: (
|
|
(x['neighborhood'] or '').lower(),
|
|
x['street_name_sort'],
|
|
x['street_number_sort']
|
|
))
|
|
|
|
map_data = []
|
|
if len(households_list) < 3000:
|
|
map_data = [
|
|
{
|
|
'lat': h['latitude'],
|
|
'lng': h['longitude'],
|
|
'address_street': h['address_street'],
|
|
'city': h['city'],
|
|
'state': h['state'],
|
|
'zip_code': h['zip_code'],
|
|
'address': f"{h['address_street']}, {h['city']}",
|
|
'voters': ", ".join([f"{v['first_name']} {v['last_name']}" for v in h['target_voters']])
|
|
}
|
|
for h in households_list if h['latitude'] and h['longitude']
|
|
]
|
|
|
|
for h in households_list:
|
|
h['voters_json_str'] = json.dumps(h['voters_json'])
|
|
|
|
paginator = Paginator(households_list, 50)
|
|
page_number = request.GET.get('page')
|
|
households_page = paginator.get_page(page_number)
|
|
|
|
from core.forms import DoorVisitLogForm
|
|
context = {
|
|
'selected_tenant': tenant,
|
|
'households': households_page,
|
|
'district_filter': district_filter,
|
|
'neighborhood_filter': neighborhood_filter,
|
|
'address_filter': address_filter,
|
|
"city_filter": city_filter,
|
|
'map_data_json': json.dumps(map_data),
|
|
'GOOGLE_MAPS_API_KEY': getattr(settings, 'GOOGLE_MAPS_API_KEY', ''),
|
|
'visit_form': DoorVisitLogForm(),
|
|
}
|
|
return render(request, 'core/door_visits.html', context)
|
|
"""
|
|
|
|
if start_line != -1 and end_line != -1:
|
|
lines[start_line:end_line] = [optimized_code]
|
|
with open('core/views.py', 'w') as f:
|
|
f.write('\n'.join(lines))
|
|
print("Successfully patched door_visits in core/views.py")
|
|
else:
|
|
print(f"Failed to find door_visits function: start={start_line}, end={end_line}")
|
|
sys.exit(1)
|