/
models.py
2617 lines (2343 loc) · 133 KB
/
models.py
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
# ballot/models.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from candidate.models import CandidateCampaign
from config.base import get_environment_variable
from datetime import date, datetime
from django.db import models
from django.db.models import F, Q, Count
from election.models import ElectionManager
from exception.models import handle_exception, handle_record_found_more_than_one_exception
from geopy.geocoders import get_geocoder_for_service
from geopy.exc import GeocoderQuotaExceeded
from measure.models import ContestMeasureManager
from office.models import ContestOfficeManager
from polling_location.models import PollingLocationManager
import wevote_functions.admin
from wevote_functions.functions import convert_date_to_date_as_integer, convert_to_int, positive_value_exists
from wevote_settings.models import fetch_next_we_vote_id_ballot_returned_integer, fetch_site_unique_id_prefix
OFFICE = 'OFFICE'
CANDIDATE = 'CANDIDATE'
POLITICIAN = 'POLITICIAN'
MEASURE = 'MEASURE'
KIND_OF_BALLOT_ITEM_CHOICES = (
(OFFICE, 'Office'),
(CANDIDATE, 'Candidate'),
(POLITICIAN, 'Politician'),
(MEASURE, 'Measure'),
)
GOOGLE_MAPS_API_KEY = get_environment_variable("GOOGLE_MAPS_API_KEY")
logger = wevote_functions.admin.get_logger(__name__)
class BallotItem(models.Model):
"""
This is a generated table with ballot item data from a variety of sources, including Google Civic
One ballot item is either 1) a measure/referendum or 2) an office that is being competed for
"""
# The unique id of the voter for which this ballot was retrieved
voter_id = models.IntegerField(verbose_name="the voter unique id", default=0, null=False, blank=False)
# The polling location for which this ballot was retrieved
polling_location_we_vote_id = models.CharField(
verbose_name="we vote permanent id of the polling location", max_length=255, default=None, null=True,
blank=True, unique=False)
# The unique ID of this election. (Provided by Google Civic)
google_civic_election_id = models.CharField(verbose_name="google civic election id", max_length=20, null=False)
google_civic_election_id_new = models.PositiveIntegerField(
verbose_name="google civic election id", default=0, null=False)
state_code = models.CharField(verbose_name="state the ballot item is related to", max_length=2, null=True)
google_ballot_placement = models.BigIntegerField(
verbose_name="the order this item should appear on the ballot", null=True, blank=True, unique=False)
local_ballot_order = models.IntegerField(
verbose_name="locally calculated order this item should appear on the ballot", null=True, blank=True)
# The id for this contest office specific to this server.
# TODO contest_office_id should be positive integer as opposed to CharField
contest_office_id = models.CharField(verbose_name="local id for this contest office", max_length=255, null=True,
blank=True)
# The internal We Vote id for the ContestMeasure that this campaign taking a stance on
contest_office_we_vote_id = models.CharField(
verbose_name="we vote permanent id for this office", max_length=255, default=None, null=True,
blank=True, unique=False)
# The local database id for this measure, specific to this server.
# TODO contest_measure_id should be positive integer as opposed to CharField
contest_measure_id = models.CharField(
verbose_name="contest_measure unique id", max_length=255, null=True, blank=True)
# The internal We Vote id for the ContestMeasure that this campaign taking a stance on
contest_measure_we_vote_id = models.CharField(
verbose_name="we vote permanent id for this measure", max_length=255, default=None, null=True,
blank=True, unique=False)
# This is a sortable name, either the candidate name or the measure name
ballot_item_display_name = models.CharField(verbose_name="a label we can sort by", max_length=255, null=True,
blank=True)
measure_subtitle = models.TextField(verbose_name="google civic referendum subtitle",
null=True, blank=True, default="")
measure_text = models.TextField(verbose_name="measure text", null=True, blank=True, default="")
def is_contest_office(self):
if self.contest_office_id:
return True
return False
def is_contest_measure(self):
if self.contest_measure_id:
return True
return False
def display_ballot_item(self):
return self.ballot_item_display_name
def fetch_ballot_order(self):
return 3
def candidates_list(self):
candidates_list_temp = CandidateCampaign.objects.all()
candidates_list_temp = candidates_list_temp.filter(google_civic_election_id=self.google_civic_election_id)
candidates_list_temp = candidates_list_temp.filter(contest_office_id=self.contest_office_id)
return candidates_list_temp
class BallotItemManager(models.Model):
def retrieve_ballot_item(self, ballot_item_id=0):
ballot_item = BallotItem()
try:
if positive_value_exists(ballot_item_id):
ballot_item = BallotItem.objects.get(id=ballot_item_id)
if ballot_item.id:
ballot_item_found = True
status = "BALLOT_ITEM_FOUND_WITH_BALLOT_ITEM_ID "
else:
ballot_item_found = False
status = "ELECTION_NOT_FOUND_WITH_BALLOT_ITEM_ID "
success = True
else:
ballot_item_found = False
status = "Insufficient variables included to retrieve one ballot_item."
success = False
except BallotItem.MultipleObjectsReturned as e:
handle_record_found_more_than_one_exception(e, logger)
ballot_item_found = False
status = "ERROR_MORE_THAN_ONE_ELECTION_FOUND"
success = False
except BallotItem.DoesNotExist:
ballot_item_found = False
status = "ELECTION_NOT_FOUND"
success = True
results = {
'success': success,
'status': status,
'ballot_item_found': ballot_item_found,
'ballot_item': ballot_item,
}
return results
def update_or_create_ballot_item_for_voter(
self, voter_id, google_civic_election_id, google_ballot_placement,
ballot_item_display_name, measure_subtitle, measure_text, local_ballot_order,
contest_office_id=0, contest_office_we_vote_id='',
contest_measure_id=0, contest_measure_we_vote_id='', state_code=''):
exception_multiple_object_returned = False
new_ballot_item_created = False
# We require both contest_office_id and contest_office_we_vote_id
# OR both contest_measure_id and contest_measure_we_vote_id
required_office_ids_found = positive_value_exists(contest_office_id) \
and positive_value_exists(contest_office_we_vote_id)
required_measure_ids_found = positive_value_exists(contest_measure_id) \
and positive_value_exists(contest_measure_we_vote_id)
contest_or_measure_identifier_found = required_office_ids_found or required_measure_ids_found
if not contest_or_measure_identifier_found:
success = False
status = 'MISSING_SUFFICIENT_OFFICE_OR_MEASURE_IDS '
# If here, then we know that there are sufficient office or measure ids
elif not google_civic_election_id:
success = False
status = 'MISSING_GOOGLE_CIVIC_ELECTION_ID '
elif not voter_id:
success = False
status = 'MISSING_VOTER_ID '
else:
try:
# Retrieve list of ballot_items that match
# Use get_or_create to see if a ballot item exists
create_values = {
# Values we search against
'google_civic_election_id': google_civic_election_id,
'voter_id': voter_id,
# The rest of the values
'contest_office_id': contest_office_id,
'contest_office_we_vote_id': contest_office_we_vote_id,
'contest_measure_id': contest_measure_id,
'contest_measure_we_vote_id': contest_measure_we_vote_id,
'google_ballot_placement': google_ballot_placement,
'local_ballot_order': local_ballot_order,
'ballot_item_display_name': ballot_item_display_name,
'measure_subtitle': measure_subtitle,
'measure_text': measure_text,
'state_code': state_code,
}
# We search with contest_measure_id and contest_office_id because they are (will be) integers,
# which will be a faster search
ballot_item_on_stage, new_ballot_item_created = BallotItem.objects.get_or_create(
contest_measure_id__exact=contest_measure_id,
contest_office_id__exact=contest_office_id,
google_civic_election_id__exact=google_civic_election_id,
voter_id__exact=voter_id,
defaults=create_values)
# if a ballot_item is found (instead of just created), *then* update it
# Note, we never update google_civic_election_id or voter_id
if not new_ballot_item_created:
ballot_item_on_stage.contest_office_id = contest_office_id
ballot_item_on_stage.contest_office_we_vote_id = contest_office_we_vote_id
ballot_item_on_stage.contest_measure_id = contest_measure_id
ballot_item_on_stage.contest_measure_we_vote_id = contest_measure_we_vote_id
ballot_item_on_stage.google_ballot_placement = google_ballot_placement
ballot_item_on_stage.local_ballot_order = local_ballot_order
ballot_item_on_stage.ballot_item_display_name = ballot_item_display_name
ballot_item_on_stage.measure_subtitle = measure_subtitle
ballot_item_on_stage.measure_text = measure_text
ballot_item_on_stage.save()
success = True
status = 'BALLOT_ITEM_UPDATED '
else:
success = True
status = 'BALLOT_ITEM_CREATED '
except BallotItemManager.MultipleObjectsReturned as e:
handle_record_found_more_than_one_exception(e, logger=logger)
success = False
status = 'MULTIPLE_MATCHING_BALLOT_ITEMS_FOUND '
exception_multiple_object_returned = True
results = {
'success': success,
'status': status,
'MultipleObjectsReturned': exception_multiple_object_returned,
'new_ballot_item_created': new_ballot_item_created,
}
return results
def update_or_create_ballot_item_for_polling_location(
self, polling_location_we_vote_id, google_civic_election_id, google_ballot_placement,
ballot_item_display_name, measure_subtitle, measure_text, local_ballot_order,
contest_office_id=0, contest_office_we_vote_id='',
contest_measure_id=0, contest_measure_we_vote_id='', state_code=''):
exception_multiple_object_returned = False
new_ballot_item_created = False
# Make sure we have this polling_location
polling_location_manager = PollingLocationManager()
results = polling_location_manager.retrieve_polling_location_by_id(0, polling_location_we_vote_id)
if results['polling_location_found']:
polling_location_found = True
else:
polling_location_found = False
if positive_value_exists(contest_office_we_vote_id) and not positive_value_exists(contest_office_id):
# Look up contest_office_id
contest_office_manager = ContestOfficeManager()
contest_office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(
contest_office_we_vote_id)
elif positive_value_exists(contest_office_id) and not positive_value_exists(contest_office_we_vote_id):
# Look up contest_office_we_vote_id
contest_office_manager = ContestOfficeManager()
contest_office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(
contest_office_id)
if positive_value_exists(contest_measure_we_vote_id) and not positive_value_exists(contest_measure_id):
# Look up contest_measure_id
contest_measure_manager = ContestMeasureManager()
contest_measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(
contest_measure_we_vote_id)
elif positive_value_exists(contest_measure_id) and not positive_value_exists(contest_measure_we_vote_id):
# Look up contest_measure_id
contest_measure_manager = ContestMeasureManager()
contest_measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
contest_measure_id)
# We require both contest_office_id and contest_office_we_vote_id
# OR both contest_measure_id and contest_measure_we_vote_id
required_office_ids_found = positive_value_exists(contest_office_id) \
and positive_value_exists(contest_office_we_vote_id)
required_measure_ids_found = positive_value_exists(contest_measure_id) \
and positive_value_exists(contest_measure_we_vote_id)
contest_or_measure_identifier_found = required_office_ids_found or required_measure_ids_found
if not contest_or_measure_identifier_found:
success = False
status = 'MISSING_SUFFICIENT_OFFICE_OR_MEASURE_IDS-POLLING_LOCATION'
# If here, then we know that there are sufficient office or measure ids
elif not google_civic_election_id:
success = False
status = 'MISSING_GOOGLE_CIVIC_ELECTION_ID-POLLING_LOCATION'
elif not polling_location_we_vote_id:
success = False
status = 'MISSING_POLLING_LOCATION_WE_VOTE_ID'
# We Vote Server doesn't have a matching polling location yet.
# elif not polling_location_found:
# success = False
# status = 'MISSING_POLLING_LOCATION_LOCALLY'
else:
try:
# Use get_or_create to see if a ballot item exists
create_values = {
# Values we search against
'google_civic_election_id': google_civic_election_id,
'polling_location_we_vote_id': polling_location_we_vote_id,
# The rest of the values
'contest_office_id': contest_office_id,
'contest_office_we_vote_id': contest_office_we_vote_id,
'contest_measure_id': contest_measure_id,
'contest_measure_we_vote_id': contest_measure_we_vote_id,
'google_ballot_placement': google_ballot_placement,
'local_ballot_order': local_ballot_order,
'ballot_item_display_name': ballot_item_display_name,
'measure_subtitle': measure_subtitle,
'measure_text': measure_text,
'state_code': state_code,
}
# We search with contest_measure_id and contest_office_id because they are (will be) integers,
# which will be a faster search
ballot_item_on_stage, new_ballot_item_created = BallotItem.objects.get_or_create(
contest_measure_id__exact=contest_measure_id,
contest_office_id__exact=contest_office_id,
google_civic_election_id__exact=google_civic_election_id,
polling_location_we_vote_id__iexact=polling_location_we_vote_id,
defaults=create_values)
# if a ballot_item is found (instead of just created), *then* update it
# Note, we never update google_civic_election_id or voter_id
if not new_ballot_item_created:
ballot_item_on_stage.contest_office_id = contest_office_id
ballot_item_on_stage.contest_office_we_vote_id = contest_office_we_vote_id
ballot_item_on_stage.contest_measure_id = contest_measure_id
ballot_item_on_stage.contest_measure_we_vote_id = contest_measure_we_vote_id
ballot_item_on_stage.google_ballot_placement = google_ballot_placement
ballot_item_on_stage.local_ballot_order = local_ballot_order
ballot_item_on_stage.ballot_item_display_name = ballot_item_display_name
ballot_item_on_stage.measure_subtitle = measure_subtitle
ballot_item_on_stage.measure_text = measure_text
ballot_item_on_stage.state_code = state_code
ballot_item_on_stage.save()
success = True
status = 'BALLOT_ITEM_UPDATED-POLLING_LOCATION'
else:
success = True
status = 'BALLOT_ITEM_CREATED-POLLING_LOCATION'
except BallotItemManager.MultipleObjectsReturned as e:
handle_record_found_more_than_one_exception(e, logger=logger)
success = False
status = 'MULTIPLE_MATCHING_BALLOT_ITEMS_FOUND-POLLING_LOCATION '
exception_multiple_object_returned = True
results = {
'success': success,
'status': status,
'MultipleObjectsReturned': exception_multiple_object_returned,
'new_ballot_item_created': new_ballot_item_created,
}
return results
def create_ballot_item_row_entry(self, ballot_item_display_name, local_ballot_order, state_code,
google_civic_election_id, defaults):
"""
Create BallotItem table entry with BallotItem details
:param ballot_item_display_name:
:param local_ballot_order:
:param state_code:
:param google_civic_election_id:
:param defaults:
:return:
"""
new_ballot_item_created = False
new_ballot_item = ''
try:
new_ballot_item = BallotItem.objects.create(
ballot_item_display_name=ballot_item_display_name,
local_ballot_order=local_ballot_order,
state_code=state_code,
google_civic_election_id=google_civic_election_id)
if new_ballot_item:
success = True
status = "CONTEST_OFFICE_CREATED"
new_ballot_item_created = True
new_ballot_item.contest_office_id = defaults['contest_office_id']
new_ballot_item.contest_office_we_vote_id = defaults['contest_office_we_vote_id']
new_ballot_item.contest_measure_id = defaults['contest_measure_id']
new_ballot_item.contest_measure_we_vote_id = defaults['contest_measure_we_vote_id']
new_ballot_item.measure_subtitle = defaults['measure_subtitle']
new_ballot_item.polling_location_we_vote_id = defaults['polling_location_we_vote_id']
new_ballot_item.save()
else:
success = False
status = "BALLOT_ITEM_CREATE_FAILED"
except Exception as e:
success = False
new_ballot_item_created = False
status = "BALLOT_ITEM_RETRIEVE_ERROR"
handle_exception(e, logger=logger, exception_message=status)
results = {
'success': success,
'status': status,
'new_ballot_item_created': new_ballot_item_created,
'ballot_item': new_ballot_item,
}
return results
def update_ballot_item_row_entry(self, ballot_item_display_name, local_ballot_order, state_code,
google_civic_election_id, defaults):
"""
Update BallotItem table entry with matching we_vote_id
:param ballot_item_display_name:
:param local_ballot_order:
:param state_code:
:param google_civic_election_id:
:param defaults:
:return:
"""
success = False
status = ""
ballot_item_updated = False
existing_ballot_item_entry = ''
ballot_item_found = False
try:
if positive_value_exists(defaults['polling_location_we_vote_id']) and \
positive_value_exists(google_civic_election_id):
if positive_value_exists(defaults['contest_office_we_vote_id']):
existing_ballot_item_entry = BallotItem.objects.get(
contest_office_we_vote_id__iexact=defaults['contest_office_we_vote_id'],
polling_location_we_vote_id__iexact=defaults['polling_location_we_vote_id'],
google_civic_election_id=google_civic_election_id)
ballot_item_found = True
elif positive_value_exists(defaults['contest_measure_we_vote_id']):
existing_ballot_item_entry = BallotItem.objects.get(
contest_measure_we_vote_id__iexact=defaults['contest_measure_we_vote_id'],
polling_location_we_vote_id__iexact=defaults['polling_location_we_vote_id'],
google_civic_election_id=google_civic_election_id)
ballot_item_found = True
if ballot_item_found:
# found the existing entry, update the values
existing_ballot_item_entry.ballot_item_display_name = ballot_item_display_name
existing_ballot_item_entry.local_ballot_order = local_ballot_order
existing_ballot_item_entry.state_code = state_code
existing_ballot_item_entry.contest_office_id = defaults['contest_office_id']
existing_ballot_item_entry.contest_office_we_vote_id = defaults['contest_office_we_vote_id']
existing_ballot_item_entry.contest_measure_id = defaults['contest_measure_id']
existing_ballot_item_entry.contest_measure_we_vote_id = defaults['contest_measure_we_vote_id']
existing_ballot_item_entry.measure_subtitle = defaults['measure_subtitle']
# now go ahead and save this entry (update)
existing_ballot_item_entry.save()
ballot_item_updated = True
success = True
status = "BALLOT_ITEM_UPDATED"
except Exception as e:
success = False
ballot_item_updated = False
status = "BALLOT_ITEM_RETRIEVE_ERROR"
handle_exception(e, logger=logger, exception_message=status)
results = {
'success': success,
'status': status,
'ballot_item_updated': ballot_item_updated,
'ballot_item': existing_ballot_item_entry,
}
return results
class BallotItemListManager(models.Model):
"""
A way to work with a list of ballot_items
"""
def delete_all_ballot_items_for_voter(self, voter_id, google_civic_election_id):
ballot_item_list_deleted = False
try:
ballot_item_queryset = BallotItem.objects.filter(voter_id=voter_id)
if positive_value_exists(google_civic_election_id):
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
ballot_item_queryset.delete()
ballot_item_list_deleted = True
status = 'BALLOT_ITEMS_DELETED'
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_DELETED_DoesNotExist'
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED delete_all_ballot_items_for_voter ' \
'{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
results = {
'success': True if ballot_item_list_deleted else False,
'status': status,
'google_civic_election_id': google_civic_election_id,
'voter_id': voter_id,
'ballot_item_list_deleted': ballot_item_list_deleted,
}
return results
def retrieve_ballot_items_for_election(self, google_civic_election_id):
ballot_item_list = []
ballot_item_list_found = False
try:
# We cannot use 'readonly' because the result set sometimes gets modified with .save()
ballot_item_queryset = BallotItem.objects.all()
ballot_item_queryset = ballot_item_queryset.order_by('local_ballot_order', 'google_ballot_placement')
ballot_item_queryset = ballot_item_queryset.filter(
google_civic_election_id=google_civic_election_id)
ballot_item_list = list(ballot_item_queryset)
if positive_value_exists(ballot_item_list):
ballot_item_list_found = True
status = 'BALLOT_ITEMS_FOUND '
else:
status = 'NO_BALLOT_ITEMS_FOUND, not positive_value_exists '
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_FOUND '
ballot_item_list = []
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_ballot_items_for_election ' \
'{error} [type: {error_type}]'.format(error=e, error_type=type(e))
results = {
'success': True if ballot_item_list_found else False,
'status': status,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list,
}
return results
def retrieve_ballot_items_for_election_lacking_state(self, google_civic_election_id, number_to_retrieve=5000):
"""
:param google_civic_election_id:
:param number_to_retrieve: Repairing 1000 ballot items takes about 9 seconds.
:return:
"""
ballot_item_list = []
ballot_item_list_found = False
try:
ballot_item_queryset = BallotItem.objects.order_by('local_ballot_order', 'google_ballot_placement')
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
ballot_item_queryset = ballot_item_queryset.filter(Q(state_code=None) | Q(state_code=""))
ballot_item_list = list(ballot_item_queryset[:number_to_retrieve])
if positive_value_exists(ballot_item_list):
ballot_item_list_found = True
status = 'BALLOT_ITEMS_FOUND_WITHOUT_STATE '
else:
status = 'NO_BALLOT_ITEMS_WITHOUT_STATE_FOUND, not positive_value_exists '
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_WITHOUT_STATE_FOUND '
ballot_item_list = []
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_ballot_items_for_election_lacking_state ' \
'{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
results = {
'success': True if ballot_item_list_found else False,
'status': status,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list,
}
return results
def count_ballot_items_for_election_lacking_state(self, google_civic_election_id):
ballot_item_list_count = 0
success = False
try:
ballot_item_queryset = BallotItem.objects.order_by('local_ballot_order', 'google_ballot_placement')
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
ballot_item_queryset = ballot_item_queryset.filter(Q(state_code=None) | Q(state_code=""))
ballot_item_list_count = ballot_item_queryset.count()
status = 'BALLOT_ITEMS_WITHOUT_STATE_FOUND '
success = True
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_WITHOUT_STATE_FOUND '
success = True
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_ballot_items_for_election_lacking_state ' \
'{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
results = {
'success': success,
'status': status,
'ballot_item_list_count': ballot_item_list_count,
}
return results
def retrieve_all_ballot_items_for_contest_office(self, office_id, office_we_vote_id):
ballot_item_list = []
ballot_item_list_found = False
if not positive_value_exists(office_id) and not positive_value_exists(office_we_vote_id):
status = 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING'
results = {
'success': True if ballot_item_list_found else False,
'status': status,
'office_id': office_id,
'office_we_vote_id': office_we_vote_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list,
}
return results
try:
ballot_item_queryset = BallotItem.objects.all()
if positive_value_exists(office_id):
ballot_item_queryset = ballot_item_queryset.filter(contest_office_id=office_id)
elif positive_value_exists(office_we_vote_id):
ballot_item_queryset = ballot_item_queryset.filter(contest_office_we_vote_id=office_we_vote_id)
ballot_item_queryset = ballot_item_queryset.order_by('local_ballot_order', 'google_ballot_placement')
ballot_item_list = ballot_item_queryset
if len(ballot_item_list):
ballot_item_list_found = True
status = 'BALLOT_ITEMS_FOUND, retrieve_all_ballot_items_for_contest_office '
else:
status = 'NO_BALLOT_ITEMS_FOUND, retrieve_all_ballot_items_for_contest_office '
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_FOUND_DoesNotExist, retrieve_all_ballot_items_for_contest_office '
ballot_item_list = []
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_all_ballot_items_for_contest_office ' \
'{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
results = {
'success': True if ballot_item_list_found else False,
'status': status,
'office_id': office_id,
'office_we_vote_id': office_we_vote_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list,
}
return results
def retrieve_all_ballot_items_for_voter(self, voter_id, google_civic_election_id):
polling_location_we_vote_id = ''
ballot_item_list = []
ballot_item_list_found = False
try:
# Intentionally not using 'readonly' here
ballot_item_queryset = BallotItem.objects.all()
ballot_item_queryset = ballot_item_queryset.order_by('local_ballot_order', 'google_ballot_placement')
ballot_item_queryset = ballot_item_queryset.filter(voter_id=voter_id)
if positive_value_exists(google_civic_election_id):
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
ballot_item_list = ballot_item_queryset
if len(ballot_item_list):
ballot_item_list_found = True
status = 'BALLOT_ITEMS_FOUND, retrieve_all_ballot_items_for_voter '
else:
status = 'NO_BALLOT_ITEMS_FOUND_0 '
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_FOUND_DoesNotExist '
ballot_item_list = []
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_all_ballot_items_for_voter ' \
'{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
results = {
'success': True if ballot_item_list_found else False,
'status': status,
'google_civic_election_id': google_civic_election_id,
'voter_id': voter_id,
'polling_location_we_vote_id': polling_location_we_vote_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list,
}
return results
def retrieve_all_ballot_items_for_polling_location(self, polling_location_we_vote_id, google_civic_election_id,
for_editing=False):
voter_id = 0
ballot_item_list = []
ballot_item_list_found = False
try:
if positive_value_exists(for_editing):
ballot_item_queryset = BallotItem.objects.all()
else:
ballot_item_queryset = BallotItem.objects.using('readonly').all()
ballot_item_queryset = ballot_item_queryset.order_by('local_ballot_order', 'google_ballot_placement')
ballot_item_queryset = ballot_item_queryset.filter(polling_location_we_vote_id=polling_location_we_vote_id)
if positive_value_exists(google_civic_election_id):
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
ballot_item_list = ballot_item_queryset
if len(ballot_item_list):
ballot_item_list_found = True
status = 'BALLOT_ITEMS_FOUND, retrieve_all_ballot_items_for_polling_location '
else:
status = 'NO_BALLOT_ITEMS_FOUND, retrieve_all_ballot_items_for_polling_location '
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
status = 'NO_BALLOT_ITEMS_FOUND_DoesNotExist, retrieve_all_ballot_items_for_polling_location '
ballot_item_list = []
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_all_ballot_items_for_polling_location ' \
'{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
results = {
'success': True if ballot_item_list_found else False,
'status': status,
'google_civic_election_id': google_civic_election_id,
'voter_id': voter_id,
'polling_location_we_vote_id': polling_location_we_vote_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list,
}
return results
def fetch_most_recent_google_civic_election_id(self):
election_manager = ElectionManager()
results = election_manager.retrieve_elections_by_date()
if results['success']:
election_list = results['election_list']
for one_election in election_list:
ballot_item_queryset = BallotItem.objects.all()
ballot_item_queryset = ballot_item_queryset.filter(
google_civic_election_id=one_election.google_civic_election_id)
number_found = ballot_item_queryset.count()
if positive_value_exists(number_found):
# Since we are starting with the most recent election, as soon as we find
# any election with ballot items, we can exit.
return one_election.google_civic_election_id
return 0
def fetch_ballot_item_list_count_for_ballot_returned(self, polling_location_we_vote_id, google_civic_election_id):
google_civic_election_id = convert_to_int(google_civic_election_id)
try:
ballot_item_queryset = BallotItem.objects.all()
ballot_item_queryset = ballot_item_queryset.filter(
polling_location_we_vote_id__iexact=polling_location_we_vote_id)
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
return ballot_item_queryset.count()
except BallotItem.DoesNotExist:
# No ballot items found. Not a problem.
pass
except Exception as e:
pass
return 0
def copy_ballot_items(self, ballot_returned, to_voter_id):
status = ""
# Get all ballot items from the reference ballot_returned
if positive_value_exists(ballot_returned.polling_location_we_vote_id):
retrieve_results = self.retrieve_all_ballot_items_for_polling_location(
ballot_returned.polling_location_we_vote_id, ballot_returned.google_civic_election_id)
status += retrieve_results['status']
else:
retrieve_results = self.retrieve_all_ballot_items_for_voter(ballot_returned.voter_id,
ballot_returned.google_civic_election_id)
status += retrieve_results['status']
if not retrieve_results['ballot_item_list_found']:
error_results = {
'ballot_returned_copied': False,
'success': False,
'status': status,
}
return error_results
ballot_item_list = retrieve_results['ballot_item_list']
ballot_item_manager = BallotItemManager()
for ballot_item in ballot_item_list:
create_results = ballot_item_manager.update_or_create_ballot_item_for_voter(
to_voter_id, ballot_returned.google_civic_election_id, ballot_item.google_ballot_placement,
ballot_item.ballot_item_display_name, ballot_item.measure_subtitle, ballot_item.measure_text,
ballot_item.local_ballot_order,
ballot_item.contest_office_id, ballot_item.contest_office_we_vote_id,
ballot_item.contest_measure_id, ballot_item.contest_measure_we_vote_id, ballot_item.state_code)
if not create_results['success']:
status += create_results['status']
results = {
'ballot_returned_copied': True,
'success': True,
'status': status,
}
return results
def retrieve_possible_duplicate_ballot_items(self, ballot_item_display_name, google_civic_election_id,
polling_location_we_vote_id,
contest_office_we_vote_id, contest_measure_we_vote_id, state_code):
ballot_item_list_objects = []
filters = []
ballot_item_list_found = False
if not positive_value_exists(google_civic_election_id):
# We must have a google_civic_election_id
results = {
'success': False,
'status': "MISSING_GOOGLE_CIVIC_ELECTION_ID",
'google_civic_election_id': google_civic_election_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list_objects,
}
return results
elif not positive_value_exists(polling_location_we_vote_id):
# We must have a polling_location_we_vote_id to look up
results = {
'success': False,
'status': "MISSING_POLLING_LOCATION_WE_VOTE_ID",
'google_civic_election_id': google_civic_election_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list_objects,
}
return results
elif not positive_value_exists(ballot_item_display_name):
# We must have a ballot_item_display_name to look up
results = {
'success': False,
'status': "MISSING_BALLOT_ITEM_DISPLAY_NAME",
'google_civic_election_id': google_civic_election_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list_objects,
}
return results
elif not positive_value_exists(contest_office_we_vote_id) \
and not positive_value_exists(contest_measure_we_vote_id):
results = {
'success': False,
'status': "MISSING_MEASURE_AND_OFFICE_WE_VOTE_ID",
'google_civic_election_id': google_civic_election_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list_objects,
}
return results
try:
ballot_item_queryset = BallotItem.objects.all()
ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
ballot_item_queryset = ballot_item_queryset.filter(
polling_location_we_vote_id__iexact=polling_location_we_vote_id)
if positive_value_exists(state_code):
ballot_item_queryset = ballot_item_queryset.filter(state_code=state_code)
if positive_value_exists(contest_office_we_vote_id):
# Ignore entries with contest_office_we_vote_id coming in from master server
ballot_item_queryset = ballot_item_queryset.filter(~Q(
contest_office_we_vote_id__iexact=contest_office_we_vote_id))
elif positive_value_exists(contest_measure_we_vote_id):
# Ignore entries with contest_measure_we_vote_id coming in from master server
ballot_item_queryset = ballot_item_queryset.filter(~Q(
contest_measure_we_vote_id__iexact=contest_measure_we_vote_id))
# We want to find candidates with *any* of these values
if positive_value_exists(ballot_item_display_name):
new_filter = Q(ballot_item_display_name__iexact=ballot_item_display_name)
filters.append(new_filter)
# Add the first query
if len(filters):
final_filters = filters.pop()
# ...and "OR" the remaining items in the list
for item in filters:
final_filters |= item
ballot_item_queryset = ballot_item_queryset.filter(final_filters)
ballot_item_list_objects = ballot_item_queryset
if len(ballot_item_list_objects):
ballot_item_list_found = True
status = 'DUPLICATE_BALLOT_ITEMS_RETRIEVED '
success = True
else:
status = 'NO_DUPLICATE_BALLOT_ITEMS_RETRIEVED '
success = True
except BallotItem.DoesNotExist:
# No ballot_items found. Not a problem.
status = 'NO_DUPLICATE_BALLOT_ITEMS_FOUND_DoesNotExist '
ballot_item_list_objects = []
success = True
except Exception as e:
handle_exception(e, logger=logger)
status = 'FAILED retrieve_possible_duplicate_ballot_items ' \
'{error} [type: {error_type}]'.format(error=e, error_type=type(e))
success = False
results = {
'success': success,
'status': status,
'google_civic_election_id': google_civic_election_id,
'ballot_item_list_found': ballot_item_list_found,
'ballot_item_list': ballot_item_list_objects,
}
return results
class BallotReturned(models.Model):
"""
This is a generated table with a summary of address + election combinations returned ballot data
"""
we_vote_id = models.CharField(
verbose_name="we vote permanent id", max_length=255, default=None, null=True,
blank=True, unique=True)
# The unique id of the voter for which this ballot was retrieved
voter_id = models.IntegerField(verbose_name="the voter unique id", null=True, blank=True)
# The polling location for which this ballot was retrieved
polling_location_we_vote_id = models.CharField(
verbose_name="we vote permanent id of the polling location", max_length=255, default=None, null=True,
blank=True, unique=False)
# The unique ID of this election. (Provided by Google Civic)
google_civic_election_id = models.PositiveIntegerField(
verbose_name="google civic election id", default=0, null=False)
# state_code = models.CharField(verbose_name="state the ballot item is related to", max_length=2, null=True)
election_description_text = models.CharField(max_length=255, blank=False, null=False,
verbose_name='text label for this election')
election_date = models.DateField(verbose_name='election start date', null=True, auto_now=False)
# Should we show this ballot as an option for this election?
ballot_location_display_option_on = models.BooleanField(default=False)
ballot_location_display_name = models.CharField(verbose_name='name that shows in button',
max_length=255, blank=True, null=True)
ballot_location_shortcut = models.CharField(verbose_name='the url string to find this location',
max_length=255, blank=True, null=True)
ballot_location_order = models.PositiveIntegerField(
verbose_name="order of these ballot locations in display", default=0, null=False)
text_for_map_search = models.CharField(max_length=255, blank=False, null=False, verbose_name='address as entered')
latitude = models.FloatField(null=True, verbose_name='latitude returned from Google')
longitude = models.FloatField(null=True, verbose_name='longitude returned from Google')
normalized_line1 = models.CharField(max_length=255, blank=True, null=True,
verbose_name='normalized address line 1 returned from Google')
normalized_line2 = models.CharField(max_length=255, blank=True, null=True,
verbose_name='normalized address line 2 returned from Google')
normalized_city = models.CharField(max_length=255, blank=True, null=True,
verbose_name='normalized city returned from Google')
normalized_state = models.CharField(max_length=255, blank=True, null=True,
verbose_name='normalized state returned from Google')
normalized_zip = models.CharField(max_length=255, blank=True, null=True,
verbose_name='normalized zip returned from Google')
# We override the save function so we can auto-generate we_vote_id
def save(self, *args, **kwargs):
# Even if this voter_guide came from another source we still need a unique we_vote_id
if self.we_vote_id:
self.we_vote_id = self.we_vote_id.strip().lower()
if self.we_vote_id == "" or self.we_vote_id is None: # If there isn't a value...
self.generate_new_we_vote_id()
super(BallotReturned, self).save(*args, **kwargs)
def generate_new_we_vote_id(self):
# ...generate a new id
site_unique_id_prefix = fetch_site_unique_id_prefix()
next_local_integer = fetch_next_we_vote_id_ballot_returned_integer()
# "wv" = We Vote
# site_unique_id_prefix = a generated (or assigned) unique id for one server running We Vote
# "ballot" = tells us this is a unique id for a ballot_returned entry
# next_integer = a unique, sequential integer for this server - not necessarily tied to database id
self.we_vote_id = "wv{site_unique_id_prefix}ballot{next_integer}".format(
site_unique_id_prefix=site_unique_id_prefix,
next_integer=next_local_integer,
)
# TODO we need to deal with the situation where we_vote_id is NOT unique on save
return
def election_day_text(self):
if self.election_date:
return self.election_date.strftime('%Y-%m-%d')
else:
return ""
class BallotReturnedManager(models.Model):
"""
Scenario where we get an incomplete address and Google Civic can't find it:
1. A voter enters an address into text_for_map_search.
2. Try to get ballot from Google Civic, if no response found...
3. We search for the closest address for this election in the ballot_returned table.
4. We find the closest address.
5. We then assemble the ballot from the ballot items table so we can offer that to the new voter.
6. Copy these ballot items over to this new voter
New ballot comes in and we want to cache it:
1. Search by voter_id (or polling_location_we_vote_id) + google_civic_election_id to see if have an entry
2. If so, update it. If not...