-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2207 lines (1962 loc) Β· 103 KB
/
app.py
File metadata and controls
2207 lines (1962 loc) Β· 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, render_template_string, jsonify
import sqlite3
import pprint
import time
import math # For math.ceil
from urllib.parse import urlencode, quote_plus # Added quote_plus
import argparse
import os
app = Flask(__name__)
URL_PREFIX = os.environ.get('URL_PREFIX', '')
DB_PATH = "fec_contributions.db"
PAGE_SIZE = 50 # Items per page for pagination
PERSON_SEARCH_PAGE_SIZE = 10 # Specific page size for recent contributions on person page
# Custom Jinja2 filter for currency formatting
def format_currency(value):
# Handle None case explicitly
if value is None:
return "$0.00"
return "${:,.2f}".format(value)
app.jinja_env.filters['currency'] = format_currency
# Custom Jinja2 filter for comma-separated numbers
def format_comma(value):
if value is None:
return "0"
return "{:,}".format(int(value))
app.jinja_env.filters['comma'] = format_comma
app.jinja_env.globals['min'] = min
app.jinja_env.globals['max'] = max
app.jinja_env.globals['PREFIX'] = URL_PREFIX
app.jinja_env.filters['quote_plus'] = quote_plus # Changed from globals to filters
# Helper function to build CA app URLs with preserved parameters
def build_ca_app_url(route="/", params=None):
"""Build URL for CA app with preserved search parameters."""
if params is None:
params = {}
# Map national parameters to CA app parameters
ca_params = {}
for key, value in params.items():
if key in ["first_name", "last_name", "city", "state", "zip_code", "year", "sort_by", "order"]:
ca_params[key] = value
base_url = f"http://localhost:5001{route}"
if ca_params:
base_url += "?" + urlencode(ca_params)
return base_url
# Add to template globals
app.jinja_env.globals['build_ca_app_url'] = build_ca_app_url
# --- Helper Functions ---
def normalize_and_format_phone(phone_string):
"""Cleans and formats a phone number string.
Args:
phone_string: The raw phone number input.
Returns:
Formatted phone number as XXX-XXX-XXXX if input results in 10 digits,
otherwise None.
"""
if not phone_string:
return None
# 1. Remove non-digits
digits = ''.join(filter(str.isdigit, phone_string))
# 2. Handle leading '1' if 11 digits
if len(digits) == 11 and digits.startswith('1'):
digits = digits[1:]
# 3. Check if we have exactly 10 digits
if len(digits) == 10:
# 4. Format into XXX-XXX-XXXX
return f"{digits[0:3]}-{digits[3:6]}-{digits[6:10]}"
else:
# Return None if not 10 digits after cleaning
return None
# --- Security Headers ---
@app.after_request
def add_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-XSS-Protection'] = '1; mode=block'
# Update CSP to allow Google iframes needed for /person route
response.headers['Content-Security-Policy'] = "default-src 'self'; frame-src https://www.google.com/; style-src 'self' 'unsafe-inline'; script-src 'self'; object-src 'none';"
return response
# Known passthrough platforms like ActBlue and WinRed
KNOWN_CONDUITS = {
"C00401224": "ACTBLUE",
"C00694323": "WINRED",
"C00708504": "NATIONBUILDER",
"C00580100": "REPUBLICAN PLATFORM FUND",
}
def map_cmte_type(code):
return {
"H": "Candidate",
"S": "Candidate",
"P": "Candidate",
"X": "Party Committee",
"Y": "Party Committee",
}.get(code, "PAC")
def get_db():
return sqlite3.connect(DB_PATH)
def get_donor_percentiles_by_year(first_name, last_name, zip_code):
"""
Get percentile rankings for a donor across all years they have data.
Returns dict: {year: {"percentile": float, "rank": int, "total_amount": float, "total_donors": int}}
"""
if not zip_code or len(zip_code) < 5:
return {}
zip5 = zip_code[:5] # Use first 5 digits
donor_key = f"{first_name}|{last_name}|{zip5}"
conn = get_db()
cursor = conn.cursor()
# Get donor's totals by year
cursor.execute("""
SELECT year, total_amount, contribution_count
FROM donor_totals_by_year
WHERE donor_key = ?
ORDER BY year DESC
""", (donor_key,))
donor_years = cursor.fetchall()
if not donor_years:
conn.close()
return {}
percentiles = {}
for year, total_amount, contrib_count in donor_years:
# Count donors with higher totals in this year
cursor.execute("""
SELECT COUNT(*)
FROM donor_totals_by_year
WHERE year = ? AND total_amount > ?
""", (year, total_amount))
donors_above = cursor.fetchone()[0]
# Get total donor count for the year
cursor.execute("""
SELECT COUNT(*)
FROM donor_totals_by_year
WHERE year = ?
""", (year,))
total_donors = cursor.fetchone()[0]
if total_donors > 0:
# Calculate percentile (higher percentile = better rank)
percentile = ((total_donors - donors_above) / total_donors) * 100
rank = donors_above + 1
percentiles[year] = {
"percentile": percentile,
"rank": rank,
"total_amount": total_amount,
"contribution_count": contrib_count,
"total_donors": total_donors
}
conn.close()
return percentiles
@app.route("/", methods=["GET"])
def search():
# --- Get original search parameters ---
original_params = {
"first_name": request.args.get("first_name", "").strip().upper(),
"last_name": request.args.get("last_name", "").strip().upper(),
"zip_code": request.args.get("zip_code", "").strip().upper(),
"year": request.args.get("year", "").strip(),
"city": request.args.get("city", "").strip().upper(),
"state": request.args.get("state", "").strip().upper(),
"sort_by": request.args.get("sort_by", "contribution_date"),
"order": request.args.get("order", "desc")
}
page = request.args.get("page", 1, type=int)
if page < 1: page = 1
# Validate sort parameters
if original_params["sort_by"] not in {"contribution_date", "amount"}:
original_params["sort_by"] = "contribution_date"
if original_params["order"] not in {"asc", "desc"}:
original_params["order"] = "desc"
# Validate year format (only use if 4 digits)
year_filter = None
if original_params["year"] and original_params["year"].isdigit() and len(original_params["year"]) == 4:
year_filter = original_params["year"]
else:
original_params["year"] = "" # Clear invalid year from displayed params
# Determine if a search should be performed
search_criteria_provided = bool(
original_params["first_name"] or original_params["last_name"] or
original_params["zip_code"] or original_params["city"] or
original_params["state"] or year_filter
)
results = []
total_results = 0
total_pages = 0
effective_params = {} # To store the params that yielded results
cascade_message = "" # Message explaining which filters were dropped
no_results_detail_message = None # Initialize here
if search_criteria_provided:
conn = get_db()
cursor = conn.cursor()
# --- Define search attempts (cascading logic) ---
search_attempts = []
base_attempt_params = original_params.copy()
# Attempt 1: All provided filters
search_attempts.append({"params": base_attempt_params.copy(), "level": "All filters"})
# Attempt 2: Drop ZIP (if ZIP was provided)
if base_attempt_params["zip_code"]:
attempt_2_params = base_attempt_params.copy()
attempt_2_params["zip_code"] = "" # Drop zip
search_attempts.append({"params": attempt_2_params, "level": "Dropped ZIP Code"})
# Attempt 3: Drop City & ZIP (if City was provided)
# Note: State remains if it was provided independently
if base_attempt_params["city"]:
attempt_3_params = base_attempt_params.copy()
attempt_3_params["zip_code"] = "" # Drop zip (might have been dropped already, ensures it)
attempt_3_params["city"] = "" # Drop city
search_attempts.append({"params": attempt_3_params, "level": "Dropped City & ZIP Code"})
# --- Loop through attempts ---
found_results = False
for attempt in search_attempts:
current_params = attempt["params"]
level = attempt["level"]
# Build WHERE clauses and params for this attempt
where_clauses = ["c.recipient_name NOT IN ({})".format(",".join(["?"] * len(KNOWN_CONDUITS)))]
query_params_list = list(KNOWN_CONDUITS.keys())
is_name_search = False # Flag to track if name was searched
if current_params["first_name"]:
where_clauses.append("c.first_name = ?")
query_params_list.append(current_params["first_name"])
is_name_search = True
if current_params["last_name"]:
where_clauses.append("c.last_name = ?")
query_params_list.append(current_params["last_name"])
is_name_search = True
if current_params["zip_code"]: # Use the potentially modified zip
where_clauses.append("c.zip_code LIKE ?")
query_params_list.append(current_params["zip_code"] + "%")
if current_params["city"]: # Use the potentially modified city
where_clauses.append("c.city = ?")
query_params_list.append(current_params["city"])
# State handling: Only apply if explicitly provided by user
state_filter_applied = None # Keep track for logging/message clarity if needed
if current_params["state"]: # User provided state
where_clauses.append("c.state = ?")
query_params_list.append(current_params["state"])
state_filter_applied = current_params["state"]
# REMOVED: CA default logic
if year_filter: # Use validated year
start_date = f"{year_filter}-01-01"
end_date = f"{year_filter}-12-31"
where_clauses.append("c.contribution_date >= ? AND c.contribution_date <= ?")
query_params_list.extend([start_date, end_date])
where_string = " WHERE " + " AND ".join(where_clauses)
# Execute COUNT query for this attempt
count_query_sql = f"SELECT COUNT(*) FROM contributions c {where_string}"
print(f"\nπ Executing SQL (Count - Attempt: {level}):")
print(count_query_sql)
print("π With params:")
pprint.pprint(query_params_list)
cursor.execute(count_query_sql, query_params_list)
current_total_results = cursor.fetchone()[0]
if current_total_results > 0:
total_results = current_total_results
total_pages = math.ceil(total_results / PAGE_SIZE)
effective_params = current_params # Store the successful parameters
found_results = True
# Set cascade message if filters were dropped
cascade_parts = []
if level == "Dropped ZIP Code":
cascade_parts.append("dropped ZIP Code filter")
elif level == "Dropped City & ZIP Code":
cascade_parts.append("dropped City & ZIP Code filters")
# REMOVED: check for CA default application message
if cascade_parts:
cascade_message = f"(Results found after { ' and '.join(cascade_parts) })"
else:
cascade_message = "" # Explicitly clear for 'All filters'
# Calculate offset for pagination
offset = (page - 1) * PAGE_SIZE
# Construct and execute the main data query using effective criteria
base_select_for_data_columns = """
c.first_name, c.last_name, c.contribution_date,
COALESCE(m.name, c.recipient_name), c.amount,
COALESCE(m.type, ''), c.recipient_name,
c.city, c.state, c.zip_code
"""
from_join_clause = "FROM contributions c LEFT JOIN committees m ON c.recipient_name = m.committee_id"
# Rebuild WHERE clause and params for the successful attempt for data query
final_where_clauses = ["c.recipient_name NOT IN ({})".format(",".join(["?"] * len(KNOWN_CONDUITS)))]
final_query_params = list(KNOWN_CONDUITS.keys())
if effective_params["first_name"]:
final_where_clauses.append("c.first_name = ?")
final_query_params.append(effective_params["first_name"])
if effective_params["last_name"]:
final_where_clauses.append("c.last_name = ?")
final_query_params.append(effective_params["last_name"])
if effective_params["zip_code"]:
final_where_clauses.append("c.zip_code LIKE ?")
final_query_params.append(effective_params["zip_code"] + "%")
if effective_params["city"]:
final_where_clauses.append("c.city = ?")
final_query_params.append(effective_params["city"])
if effective_params["state"]: # User provided state in successful attempt
final_where_clauses.append("c.state = ?")
final_query_params.append(effective_params["state"])
# REMOVED: CA default application in final query
if year_filter: # Use validated year
start_date = f"{year_filter}-01-01"
end_date = f"{year_filter}-12-31"
final_where_clauses.append("c.contribution_date >= ? AND c.contribution_date <= ?")
final_query_params.extend([start_date, end_date])
final_where_string = " WHERE " + " AND ".join(final_where_clauses)
data_query_sql = (
f"SELECT {base_select_for_data_columns} {from_join_clause}{final_where_string} "
f"ORDER BY c.{effective_params['sort_by']} {effective_params['order']} LIMIT ? OFFSET ?"
)
paged_data_params = final_query_params + [PAGE_SIZE, offset]
print(f"\nπ Executing SQL (Data - Effective Level: {level}, State Filter: {state_filter_applied if state_filter_applied else 'None'}):") # Log state filter used
print(data_query_sql)
print("π With params:")
pprint.pprint(paged_data_params)
start_time = time.time()
cursor.execute(data_query_sql, paged_data_params)
results = cursor.fetchall()
end_time = time.time()
print(f"β±οΈ Query executed in {end_time - start_time:.4f} seconds")
break # Exit the loop once results are found
conn.close()
# Construct the final "No results" message if applicable
# no_results_detail_message = "" # No longer need to initialize here
if search_criteria_provided and not found_results:
print("\nβΉοΈ No results found after all cascade attempts on main search.")
# Use original_params to describe what was initially searched
initial_criteria_list = []
if original_params["first_name"]: initial_criteria_list.append(f"First Name: {original_params['first_name']}")
if original_params["last_name"]: initial_criteria_list.append(f"Last Name: {original_params['last_name']}")
if original_params["city"]: initial_criteria_list.append(f"City: {original_params['city']}")
if original_params["state"]: # State is only the explicitly provided one here
initial_criteria_list.append(f"State: {original_params['state']}")
# REMOVED: Mentioning CA default
if original_params["zip_code"]: initial_criteria_list.append(f"ZIP: {original_params['zip_code']}")
if year_filter: initial_criteria_list.append(f"Year: {year_filter}") # Use validated year
no_results_detail_message = f"No contributions found matching: { ', '.join(initial_criteria_list) }."
# Add details about failed cascades
original_had_zip = original_params["zip_code"]
original_had_city = original_params["city"]
cascade_attempts_failed_msg = ""
if original_had_zip and original_had_city:
cascade_attempts_failed_msg = " Also tried searching without ZIP, and without City & ZIP."
elif original_had_zip:
cascade_attempts_failed_msg = " Also tried searching without ZIP."
no_results_detail_message += cascade_attempts_failed_msg
no_results_detail_message += " Consider broadening your search criteria."
# Render template using original params for form fields,
# but effective params for pagination links
# Also pass cascade_message
# Regenerate pagination_params using effective_params (no default state logic needed)
pagination_params = {k: v for k, v in effective_params.items() if k not in ['page'] and v}
return render_template_string("""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FEC Contribution Search</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
h1, h2 { color: #2c3e50; margin-bottom: 20px; }
a { color: #3498db; text-decoration: none; }
a:hover { text-decoration: underline; }
.nav-links { margin-bottom: 20px; }
.nav-links a { margin-right: 15px; font-size: 1.1em; display: inline-block; }
form { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 30px; display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
form input[type="text"], form input[type="date"], form select { padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 1em; flex-grow: 1; min-width: 120px; }
form input[type="submit"], button { background-color: #3498db; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 1em; }
form input[type="submit"]:hover, button:hover { background-color: #2980b9; }
table { width: 100%; border-collapse: collapse; background-color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-radius: 8px; margin-top: 20px; }
th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; }
th { background-color: #eaf2f8; color: #333; font-weight: 600; }
tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #f1f1f1; }
.form-group { display: flex; flex-direction: column; }
.form-group label { margin-bottom: 5px; font-weight: 500; }
.form-group small { font-size: 0.8em; color: #777; margin-top: 3px; }
.pagination { margin: 25px 0; text-align: center; clear: both; }
.pagination a, .pagination span { display: inline-block; padding: 8px 14px; margin: 0 4px; border: 1px solid #ddd; border-radius: 4px; color: #3498db; text-decoration: none; font-size: 0.95em; }
.pagination a:hover { background-color: #eaf2f8; border-color: #c5ddec; }
.pagination .current-page { background-color: #3498db; color: white; border-color: #3498db; font-weight: bold; }
.results-summary { margin: 20px 0 5px 0; font-size: 0.9em; color: #555; }
.cascade-info { margin: 0 0 10px 0; font-size: 0.85em; color: #e67e22; font-style: italic; }
.info-link { text-decoration: none; margin-left: 5px; font-size: 0.9em; color: #7f8c8d; }
.info-link:hover { color: #3498db; }
</style>
</head>
<body>
<h1>FEC Contribution Search</h1>
<div class="nav-links">
<a href="{{ PREFIX }}/">π New Search</a>
<a href="{{ PREFIX }}/search_recipients">π₯ Search Recipients by Name</a>
<a href="{{ PREFIX }}/personsearch">π€ Person Search</a>
<a href="{{ build_ca_app_url('/', original_params) }}" style="color: #ff6b35;" target="_blank">ποΈ Search CA Data</a>
</div>
<form method="get" onsubmit="document.getElementById('mainSearchButton').disabled = true; document.getElementById('mainLoadingIndicator').style.display = 'block';">
<div class="form-group">
<label for="first_name">First Name:</label>
<input id="first_name" name="first_name" value="{{ original_params.first_name }}">
</div>
<div class="form-group">
<label for="last_name">Last Name:</label>
<input id="last_name" name="last_name" value="{{ original_params.last_name }}">
</div>
<div class="form-group">
<label for="zip_code">ZIP Code:</label>
<input id="zip_code" name="zip_code" value="{{ original_params.zip_code }}">
</div>
<div class="form-group">
<label for="city">City:</label>
<input id="city" name="city" value="{{ original_params.city }}">
</div>
<div class="form-group">
<label for="state">State:</label>
<input id="state" name="state" value="{{ original_params.state }}" maxlength="2" size="5">
{# REMOVED default CA helper text #}
</div>
<div class="form-group">
<label for="year">Year:</label>
<input id="year" type="text" name="year" value="{{ original_params.year }}" pattern="\\d{4}" title="Enter a 4-digit year" size="7">
</div>
<div class="form-group">
<label for="sort_by">Sort By:</label>
<select id="sort_by" name="sort_by">
<option value="contribution_date" {% if original_params.sort_by == 'contribution_date' %}selected{% endif %}>Date</option>
<option value="amount" {% if original_params.sort_by == 'amount' %}selected{% endif %}>Amount</option>
</select>
</div>
<div class="form-group">
<label for="order">Order:</label>
<select id="order" name="order">
<option value="desc" {% if original_params.order == 'desc' %}selected{% endif %}>Desc</option>
<option value="asc" {% if original_params.order == 'asc' %}selected{% endif %}>Asc</option>
</select>
</div>
<input type="submit" value="Search" id="mainSearchButton" style="align-self: flex-end;">
<span id="mainLoadingIndicator" style="display:none; color: #e67e22; font-weight: bold; margin-left: 10px; align-self: flex-end;">Searching...</span>
</form>
{% if results %}
<h2>Results</h2>
<div class="results-summary">
Showing {{ (page - 1) * PAGE_SIZE + 1 }} - {{ min(page * PAGE_SIZE, total_results) }} of {{ total_results }} contributions.
</div>
{% if cascade_message %}<div class="cascade-info"><strong>{{ cascade_message }}</strong></div>{% endif %}
<table>
<tr>
<th>First</th><th>Last</th><th>Date</th><th>Recipient</th><th>Amount</th><th>Type</th>
<th>City</th><th>State</th><th>ZIP</th>
</tr>
{% for fn, ln, date, recip, amt, typ, cmte_id, city, state, zip in results %}
<tr>
{# Pass city, state, zip to contributor view #}
<td><a href="{{ PREFIX }}/contributor?first={{ fn }}&last={{ ln }}&city={{ city|urlencode }}&state={{ state|urlencode }}&zip={{ zip|urlencode }}">{{ fn }}</a></td>
<td><a href="{{ PREFIX }}/contributor?first={{ fn }}&last={{ ln }}&city={{ city|urlencode }}&state={{ state|urlencode }}&zip={{ zip|urlencode }}">{{ ln }}</a></td>
<td>{{ date }}</td>
<td>
<a href="{{ PREFIX }}/recipient?committee_id={{ cmte_id }}">{{ recip }}</a>
<a href="https://www.google.com/search?q={{ recip|quote_plus }}" class="info-link" target="_blank" title="Search Google for {{ recip }}">ⓘ</a>
</td>
<td>{{ amt|currency }}</td>
<td>{{ typ|default("PAC") }}</td>
<td>{{ city }}</td>
<td>{{ state }}</td>
<td>{{ zip }}</td>
</tr>
{% endfor %}
</table>
{% if total_pages > 1 %}
<div class="pagination">
{% set base_url = PREFIX + "/?" + urlencode(pagination_params) %}
{% if page > 1 %}
<a href="{{ base_url }}&page={{ page - 1 }}">« Previous</a>
{% endif %}
<span>Page {{ page }} of {{ total_pages }}</span>
{% if page < total_pages %}
<a href="{{ base_url }}&page={{ page + 1 }}">Next »</a>
{% endif %}
</div>
{% endif %}
{% elif search_criteria_provided %}
{# Only show 'No results' if a search was actually attempted #}
<h2>No results found.</h2>
{# Display the detailed message constructed in the backend #}
<p>{{ no_results_detail_message }}</p>
{% endif %}
</body>
</html>
""",
results=results, page=page, total_pages=total_pages, total_results=total_results,
PAGE_SIZE=PAGE_SIZE, original_params=original_params, # Pass original params for form repopulation
pagination_params=pagination_params, # Pass effective params for pagination
urlencode=urlencode, # Pass urlencode for use in template
cascade_message=cascade_message, # Pass cascade message
search_criteria_provided=search_criteria_provided, # To control display of 'No results' message
no_results_detail_message=no_results_detail_message # Pass detailed no results message
)
@app.route("/contributor")
def contributor_view():
first = request.args.get("first", "").strip()
last = request.args.get("last", "").strip()
# Get optional address params, keep original case if needed for display
city = request.args.get("city", "").strip()
state = request.args.get("state", "").strip()
zip_code = request.args.get("zip", "").strip()
page = request.args.get("page", 1, type=int)
if page < 1: page = 1
offset = (page - 1) * PAGE_SIZE
if not first or not last:
return "Missing first and last name", 400
conn = get_db()
cursor = conn.cursor()
# --- Build base WHERE clause and params ---
base_where_clauses = ["c.first_name = ?", "c.last_name = ?"]
query_params = [first, last]
# Add address filters if provided
if city:
base_where_clauses.append("c.city = ?")
query_params.append(city)
if state:
base_where_clauses.append("c.state = ?")
query_params.append(state)
if zip_code:
base_where_clauses.append("c.zip_code LIKE ?")
query_params.append(zip_code + "%")
# Exclude known conduits
conduit_placeholders = ",".join(["?"] * len(KNOWN_CONDUITS))
base_where_clauses.append(f"c.recipient_name NOT IN ({conduit_placeholders})")
final_query_params = query_params + list(KNOWN_CONDUITS.keys())
where_string = " AND ".join(base_where_clauses)
from_clause = "FROM contributions c LEFT JOIN committees m ON c.recipient_name = m.committee_id"
# --- Count Query ---
count_query_sql = f"SELECT COUNT(*) {from_clause} WHERE {where_string}"
# --- Data Query ---
data_query_sql = f"""
SELECT c.contribution_date, COALESCE(m.name, c.recipient_name) as recipient_name,
c.amount, COALESCE(m.type, '') as recipient_type, c.recipient_name as committee_id,
c.city, c.state, c.zip_code
{from_clause}
WHERE {where_string}
ORDER BY c.contribution_date DESC LIMIT ? OFFSET ?
"""
paged_data_params = final_query_params + [PAGE_SIZE, offset]
# --- Sum Query ---
sum_query_sql = f"SELECT SUM(c.amount) {from_clause} WHERE {where_string}"
# --- Execute Queries ---
print("\nπ Executing SQL (/contributor count):")
print(count_query_sql)
print("π With params:")
pprint.pprint(final_query_params)
cursor.execute(count_query_sql, final_query_params) # Use final params for count
total_results = cursor.fetchone()[0]
total_pages = math.ceil(total_results / PAGE_SIZE)
print("\nπ Executing SQL (/contributor data):")
print(data_query_sql)
print("π With params:")
pprint.pprint(paged_data_params)
start_time = time.time()
cursor.execute(data_query_sql, paged_data_params)
rows = cursor.fetchall()
end_time = time.time()
print(f"β±οΈ Query executed in {end_time - start_time:.4f} seconds")
print("\nπ Executing SQL (/contributor sum):")
print(sum_query_sql)
print("π With params:")
pprint.pprint(final_query_params)
cursor.execute(sum_query_sql, final_query_params) # Use final params for sum query
total_amount_for_contributor = cursor.fetchone()[0] or 0
conn.close()
# Get percentile data for this donor
percentiles_by_year = {}
if zip_code: # Only calculate if we have ZIP for proper identification
percentiles_by_year = get_donor_percentiles_by_year(first, last, zip_code)
# --- Prepare Pagination URL ---
pagination_params = {"first": first, "last": last}
if city: pagination_params["city"] = city
if state: pagination_params["state"] = state
if zip_code: pagination_params["zip"] = zip_code
# Add any other persistent query params if needed (e.g., sort order from original search? - Not currently passed)
base_pagination_url = URL_PREFIX + "/contributor?" + urlencode(pagination_params)
# --- Render Template ---
# Construct a filter description string
filter_desc = f"{first} {last}"
location_parts = []
if city: location_parts.append(city)
if state: location_parts.append(state)
if zip_code: location_parts.append(zip_code)
if location_parts:
# Corrected f-string concatenation
filter_desc += f" from {', '.join(location_parts)}"
return render_template_string("""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contributions by {{ filter_desc }}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
h1, h2 { color: #2c3e50; margin-bottom: 10px; }
h1 { font-size: 1.8em; }
h2 { font-size: 1.2em; margin-top: 20px; }
.filter-info { font-size: 0.95em; color: #555; margin-bottom: 20px; }
a { color: #3498db; text-decoration: none; }
a:hover { text-decoration: underline; }
.nav-links { margin-bottom: 20px; }
.nav-links a { margin-right: 15px; font-size: 1.1em; display: inline-block; }
table { width: 100%; border-collapse: collapse; background-color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-radius: 8px; margin-top: 20px; }
th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; }
th { background-color: #eaf2f8; color: #333; font-weight: 600; }
tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #f1f1f1; }
.pagination { margin: 25px 0; text-align: center; clear: both; }
.pagination a, .pagination span { display: inline-block; padding: 8px 14px; margin: 0 4px; border: 1px solid #ddd; border-radius: 4px; color: #3498db; text-decoration: none; font-size: 0.95em; }
.pagination a:hover { background-color: #eaf2f8; border-color: #c5ddec; }
.pagination .current-page { background-color: #3498db; color: white; border-color: #3498db; font-weight: bold; }
.results-summary { margin: 20px 0 10px 0; font-size: 0.9em; color: #555; }
.info-link { text-decoration: none; margin-left: 5px; font-size: 0.9em; color: #7f8c8d; }
.info-link:hover { color: #3498db; }
</style>
</head>
<body>
<h1>Contributions by {{ first }} {{ last }}</h1>
<div class="filter-info">Showing contributions matching: {{ filter_desc }}</div>
<div class="nav-links">
<a href="{{ PREFIX }}/">π New Search</a>
<a href="{{ PREFIX }}/search_recipients">π₯ Search Recipients by Name</a>
<a href="{{ PREFIX }}/personsearch">π€ Person Search</a>
<a href="{{ build_ca_app_url('/contributor', {'first': first, 'last': last, 'city': city, 'state': state, 'zip': zip_code}) }}" style="color: #ff6b35;" target="_blank">ποΈ Search CA Data</a>
</div>
<h2>Total Contributed (matching filter, all pages): {{ total_amount_for_contributor|currency }}</h2>
{% if percentiles_by_year and zip_code %}
<div style="background-color: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin: 20px 0;">
<h3 style="margin-top: 0; color: #2c3e50;">π Donor Percentile Rankings</h3>
<p style="font-size: 0.9em; color: #666; margin-bottom: 15px;">
Based on total annual contributions among all donors identified as: {{ first }} {{ last }} ({{ zip_code[:5] }})
</p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
{% for year in percentiles_by_year.keys()|sort(reverse=True) %}
{% set data = percentiles_by_year[year] %}
<div style="background-color: #f8f9fa; padding: 10px; border-radius: 4px; border-left: 4px solid #3498db;">
<strong>{{ year }}</strong><br>
<span style="font-size: 1.1em; color: #2c3e50;">{{ data.percentile|round(1) }}th percentile</span><br>
<small style="color: #666;">
Rank {{ data.rank|comma }} of {{ data.total_donors|comma }}<br>
Total: {{ data.total_amount|currency }}
</small>
</div>
{% endfor %}
</div>
<p style="font-size: 0.8em; color: #888; margin-top: 10px; margin-bottom: 0;">
Higher percentile = higher rank among donors. Rankings based on yearly total contributions.
</p>
</div>
{% elif zip_code %}
<div style="background-color: #fff3cd; padding: 10px; border-radius: 4px; margin: 15px 0; font-size: 0.9em;">
π Percentile rankings will be available after running the percentile table builder script.
</div>
{% endif %}
<div class="results-summary">
Showing {{ (page - 1) * PAGE_SIZE + 1 if total_results > 0 else 0 }} - {{ min(page * PAGE_SIZE, total_results) }} of {{ total_results }} contributions.
</div>
<table>
<tr><th>Date</th><th>Recipient</th><th>Amount</th><th>Type</th>
<th>City</th><th>State</th><th>ZIP</th></tr>
{# Loop variable names adjusted slightly for clarity #}
{% for r_date, r_name, r_amt, r_type, r_cmte_id, r_city, r_state, r_zip in rows %}
<tr>
<td>{{ r_date }}</td>
<td>
<a href="{{ PREFIX }}/recipient?committee_id={{ r_cmte_id }}">{{ r_name }}</a>
<a href="https://www.google.com/search?q={{ r_name|quote_plus }}" class="info-link" target="_blank" title="Search Google for {{ r_name }}">ⓘ</a>
</td>
<td>{{ r_amt|currency }}</td>
<td>{{ r_type|default("PAC") }}</td>
{# Display the location from the contribution record itself #}
<td>{{ r_city }}</td>
<td>{{ r_state }}</td>
<td>{{ r_zip }}</td>
</tr>
{% endfor %}
</table>
{% if total_pages > 1 %}
<div class="pagination">
{% if page > 1 %}
<a href="{{ base_pagination_url }}&page={{ page - 1 }}">« Previous</a>
{% endif %}
<span>Page {{ page }} of {{ total_pages }}</span>
{% if page < total_pages %}
<a href="{{ base_pagination_url }}&page={{ page + 1 }}">Next »</a>
{% endif %}
</div>
{% endif %}
</body>
</html>
""",
first=first, last=last,
city=city, state=state, zip_code=zip_code, # Pass params for display/debug
filter_desc=filter_desc, # Pass constructed filter description
total_amount_for_contributor=total_amount_for_contributor, rows=rows,
page=page, total_pages=total_pages, total_results=total_results,
PAGE_SIZE=PAGE_SIZE,
base_pagination_url=base_pagination_url, # Use pre-built base URL for pagination
percentiles_by_year=percentiles_by_year # Pass percentile data
)
@app.route("/recipient")
def recipient_view():
committee_id = request.args.get("committee_id", "").strip()
page = request.args.get("page", 1, type=int)
if page < 1: page = 1
offset = (page - 1) * PAGE_SIZE
if not committee_id:
return "Missing committee_id", 400
if committee_id in KNOWN_CONDUITS:
return render_template_string(f"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{KNOWN_CONDUITS[committee_id]} - Passthrough</title>
<style>
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }}
h1 {{ color: #2c3e50; margin-bottom: 20px; }}
a {{ color: #3498db; text-decoration: none; }}
a:hover {{ text-decoration: underline; }}
.nav-links a {{ margin-right: 15px; font-size: 1.1em; display: inline-block; margin-bottom:20px;}}
</style>
</head>
<body>
<h1>{KNOWN_CONDUITS[committee_id]} is a passthrough platform. No direct contributors shown.</h1>
<div class="nav-links">
<a href='{{ PREFIX }}/'>π Back to search</a>
<a href="{{ PREFIX }}/personsearch">π€ Person Search</a>
</div>
</body>
</html>
""")
conn = get_db()
cursor = conn.cursor()
start_time_initial = time.time()
cursor.execute("SELECT name FROM committees WHERE committee_id = ?", (committee_id,))
name_row = cursor.fetchone()
end_time_initial = time.time()
print(f"β±οΈ Initial committee lookup executed in {end_time_initial - start_time_initial:.4f} seconds")
recipient_name = name_row[0] if name_row else committee_id
# Query for paged results
data_query_str = """
SELECT first_name, last_name, SUM(amount) as total
FROM contributions
WHERE recipient_name = ?
GROUP BY first_name, last_name
ORDER BY total DESC
LIMIT ? OFFSET ?
"""
data_params = [committee_id, PAGE_SIZE, offset]
# Count query for total groups of contributors
count_query_str = """
SELECT COUNT(*)
FROM (
SELECT 1
FROM contributions
WHERE recipient_name = ?
GROUP BY first_name, last_name
)
"""
count_params = [committee_id]
print("\nπ Executing SQL (/recipient count):")
print(count_query_str)
print("π With params:")
pprint.pprint(count_params)
cursor.execute(count_query_str, count_params)
total_results = cursor.fetchone()[0]
total_pages = math.ceil(total_results / PAGE_SIZE)
print("\nπ Executing SQL (/recipient data):")
print(data_query_str)
print("π With params:")
pprint.pprint(data_params)
start_time = time.time()
cursor.execute(data_query_str, data_params)
rows = cursor.fetchall()
end_time = time.time()
print(f"β±οΈ Query executed in {end_time - start_time:.4f} seconds")
conn.close()
return render_template_string("""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Top Contributors to {{ recipient_name }}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 20px; background-color: #f4f7f6; color: #333; }
h1, h2 { color: #2c3e50; margin-bottom: 20px; }
a { color: #3498db; text-decoration: none; }
a:hover { text-decoration: underline; }
.nav-links a { margin-right: 15px; font-size: 1.1em; display: inline-block; margin-bottom:20px;}
table { width: 100%; border-collapse: collapse; background-color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-radius: 8px; margin-top: 20px; }
th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; }
th { background-color: #eaf2f8; color: #333; font-weight: 600; }
tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #f1f1f1; }
.pagination {
margin: 25px 0;
text-align: center;
clear: both;
}
.pagination a, .pagination span {
display: inline-block;
padding: 8px 14px;
margin: 0 4px;
border: 1px solid #ddd;
border-radius: 4px;
color: #3498db;
text-decoration: none;
font-size: 0.95em;
}
.pagination a:hover {
background-color: #eaf2f8;
border-color: #c5ddec;
}
.pagination .current-page {
background-color: #3498db;
color: white;
border-color: #3498db;
font-weight: bold;
}
.results-summary {
margin: 20px 0 10px 0;
font-size: 0.9em;
color: #555;
}
.info-link {
text-decoration: none;
margin-left: 5px;
font-size: 0.9em;
color: #7f8c8d;
}
.info-link:hover {
color: #3498db;
}
</style>
</head>
<body>
<h1>Top Contributors to {{ recipient_name }}</h1>
<p style="color: #666; margin-bottom: 20px;"><em>Showing all-time contribution totals across all years in database</em></p>
<div class="nav-links">
<a href="{{ PREFIX }}/">π New Search</a>
<a href="{{ PREFIX }}/search_recipients">π₯ Search Recipients by Name</a>
<a href="{{ PREFIX }}/personsearch">π€ Person Search</a>
</div>
<div class="results-summary">
Showing top {{ (page - 1) * PAGE_SIZE + 1 if total_results > 0 else 0 }} - {{ min(page * PAGE_SIZE, total_results) }} of {{ total_results }} contributors.
</div>
<table>
<tr><th>First</th><th>Last</th><th>Total Contributed<br><small>(All Time)</small></th></tr>
{% for fn, ln, total in rows %}
<tr>
{# Pass first/last name, but address info isn't available here to add #}
<td><a href="{{ PREFIX }}/contributor?first={{ fn }}&last={{ ln }}">{{ fn }}</a></td>
<td><a href="{{ PREFIX }}/contributor?first={{ fn }}&last={{ ln }}">{{ ln }}</a></td>
<td>{{ total|currency }}</td>
</tr>
{% endfor %}
</table>
{% if total_pages > 1 %}
<div class="pagination">
{% set base_url = PREFIX + "/recipient?committee_id=" + committee_id + "&" + query_params_without_page %}
{% if page > 1 %}
<a href="{{ base_url }}&page={{ page - 1 }}">« Previous</a>
{% endif %}
<span>Page {{ page }} of {{ total_pages }}</span>
{% if page < total_pages %}
<a href="{{ base_url }}&page={{ page + 1 }}">Next »</a>
{% endif %}
</div>
{% endif %}
</body>
</html>
""", recipient_name=recipient_name, rows=rows, committee_id=committee_id,
page=page, total_pages=total_pages, total_results=total_results, PAGE_SIZE=PAGE_SIZE,
query_params_without_page=urlencode({k:v for k,v in request.args.items() if k not in ['page', 'committee_id']}))
@app.route("/search_recipients", methods=["GET"])
def search_recipients_by_name():
name_query = request.args.get("name_query", "").strip()
sort_by = request.args.get("sort_by", "recent_activity") # recent_activity, total_activity, alphabetical
page = request.args.get("page", 1, type=int)
if page < 1: page = 1
offset = (page - 1) * PAGE_SIZE
results = []
total_pages = 0
total_results = 0
if name_query:
conn = get_db()
cursor = conn.cursor()
# Check if recipient_lookup table exists
cursor.execute("""
SELECT COUNT(*) FROM sqlite_master
WHERE type='table' AND name='recipient_lookup'