-
Notifications
You must be signed in to change notification settings - Fork 16
/
models.py
783 lines (644 loc) · 22.9 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
import datetime
import os
import pytz
from django.db import models
from django.contrib.gis.db import models as geo_models
from django.conf import settings
from django.urls import reverse, NoReverseMatch
from django.utils import timezone
from django.db.models import Case, When
from django.db.models.functions import Cast, Now
from django.utils.functional import cached_property
from django.core.files.storage import FileSystemStorage
from proxy_overrides.related import ProxyForeignKey
import opencivicdata.legislative.models
import opencivicdata.core.models
static_storage = FileSystemStorage(
location=os.path.join(settings.STATIC_ROOT), base_url="/"
)
MANUAL_HEADSHOTS = (
settings.MANUAL_HEADSHOTS if hasattr(settings, "MANUAL_HEADSHOTS") else {}
)
class CastToDateTimeMixin:
@classmethod
def _cast(cls, field, field_type):
"""
Cast a given field from a CharField to a DateField or a DateTimeField,
converting empty strings to NULL in the process. Useful for CharFields
that store timestamps as strings.
"""
return Cast(
Case(
When(**{field: "", "then": None}),
default=field,
output_field=models.CharField(),
),
field_type,
)
@classmethod
def cast_to_date(cls, field):
return cls._cast(field, models.DateField())
@classmethod
def cast_to_datetime(cls, field):
return cls._cast(field, models.DateTimeField())
class Person(opencivicdata.core.models.Person):
person = models.OneToOneField(
opencivicdata.core.models.Person,
on_delete=models.CASCADE,
related_name="councilmatic_person",
parent_link=True,
)
headshot = models.FileField(
upload_to="images/headshots",
storage=static_storage,
default="images/headshot_placeholder.png",
)
# The root Person model from OCD has a biography field, however it is overwritten
# if a Person is updated. This field is for storing biographic information provided
# via Councilmatic.
councilmatic_biography = models.TextField(null=True, blank=True)
slug = models.SlugField(unique=True)
def delete(self, **kwargs):
kwargs["keep_parents"] = kwargs.get("keep_parents", True)
super().delete(**kwargs)
def __str__(self):
return self.name
@property
def current_memberships(self):
return self.memberships.filter(end_date_dt__gt=Now())
@property
def latest_council_seat(self):
m = self.latest_council_membership
if m and m.post:
return m.post.label
return ""
@property
def headshot_source(self):
sources = self.sources.filter(url=self.headshot.url)
if sources:
return sources.get().note
elif self.headshot:
return settings.CITY_VOCAB["SOURCE"]
else:
return None
@property
def primary_sponsorships(self):
primary_sponsorships = self.billsponsorship_set.filter(
primary=True
).prefetch_related("bill")
def sponsorship_sort(sponsorship):
"""
Sponsorships of bills without recent action dates should appear last.
"""
return sponsorship.bill.last_action_date or pytz.utc.localize(
datetime.date(datetime.MINYEAR, 1, 1)
)
return sorted(
(s for s in primary_sponsorships), key=sponsorship_sort, reverse=True
)
@property
def chair_role_memberships(self):
if hasattr(settings, "COMMITTEE_CHAIR_TITLE"):
return self.current_memberships.filter(role=settings.COMMITTEE_CHAIR_TITLE)
else:
return []
@property
def member_role_memberships(self):
if hasattr(settings, "COMMITTEE_MEMBER_TITLE"):
return self.current_memberships.filter(role=settings.COMMITTEE_MEMBER_TITLE)
else:
return []
@property
def latest_council_membership(self):
filter_kwarg = {"organization__name": settings.OCD_CITY_COUNCIL_NAME}
city_council_memberships = self.memberships.filter(**filter_kwarg)
if city_council_memberships.count():
return city_council_memberships.order_by("-start_date", "-end_date").first()
return None
@property
def current_council_seat(self):
m = self.latest_council_membership
if m and m.end_date_dt > timezone.now():
return m
@property
def link_html(self):
return "<a href='{}'>{}</a>".format(
reverse("person", args=[self.slug]), self.name
)
class Organization(opencivicdata.core.models.Organization, CastToDateTimeMixin):
organization = models.OneToOneField(
opencivicdata.core.models.Organization,
on_delete=models.CASCADE,
related_name="councilmatic_organization",
parent_link=True,
)
slug = models.SlugField(max_length=200, unique=True)
def delete(self, **kwargs):
kwargs["keep_parents"] = kwargs.get("keep_parents", True)
super().delete(**kwargs)
def __str__(self):
return self.name
@classmethod
def committees(cls):
"""
grabs all organizations (1) classified as a committee & (2) with at least one member
"""
return (
cls.objects.filter(classification="committee")
.annotate(
memberships_end_date_dt=cls.cast_to_datetime("memberships__end_date")
)
.filter(memberships_end_date_dt__gte=Now())
.distinct()
)
@property
def recent_activity(self):
# setting arbitrary max of 300 b/c otherwise page will take forever to
# load
return self.actions.order_by("-date", "-bill__identifier", "-order")[:300]
@property
def recent_events(self):
# need to look up event participants by name
events = Event.objects.filter(
participants__entity_type="organization", participants__name=self.name
)
events = events.order_by("-start_date").all()
return events
@property
def upcoming_events(self):
"""
grabs events in the future
"""
# need to look up event participants by name
events = (
Event.objects.filter(
participants__entity_type="organization", participants__name=self.name
)
.filter(start_time__gt=timezone.now())
.order_by("start_time")
.all()
)
return events
@property
def chairs(self):
if hasattr(settings, "COMMITTEE_CHAIR_TITLE"):
chairs = (
self.memberships.filter(role=settings.COMMITTEE_CHAIR_TITLE)
.filter(end_date_dt__gt=timezone.now())
.select_related("person__councilmatic_person")
)
for chair in chairs:
chair.person = chair.person.councilmatic_person
return chairs
else:
return []
@property
def non_chair_members(self):
if hasattr(settings, "COMMITTEE_MEMBER_TITLE"):
return self.memberships.filter(role=settings.COMMITTEE_MEMBER_TITLE).filter(
end_date_dt__gt=timezone.now()
)
else:
return []
@property
def all_members(self):
return self.memberships.filter(end_date_dt__gt=timezone.now())
@property
def vice_chairs(self):
if hasattr(settings, "COMMITTEE_VICE_CHAIR_TITLE"):
return self.memberships.filter(
role=settings.COMMITTEE_VICE_CHAIR_TITLE
).filter(end_date_dt__gt=timezone.now())
else:
return []
@property
def link_html(self):
link_fmt = '<a href="{0}">{1}</a>'
if self.classification == "committee":
try:
link_path = reverse(
"{}:committee_detail".format(settings.APP_NAME), args=(self.slug,)
)
except NoReverseMatch:
link_path = reverse("committee_detail", args=(self.slug,))
return link_fmt.format(link_path, self.name)
if self.classification == "legislature":
try:
link_path = reverse("{}:council_members".format(settings.APP_NAME))
except NoReverseMatch:
link_path = reverse("council_members")
return link_fmt.format(link_path, self.name)
return self.name
class Post(opencivicdata.core.models.Post):
post = models.OneToOneField(
opencivicdata.core.models.Post,
on_delete=models.CASCADE,
related_name="councilmatic_post",
parent_link=True,
)
organization = ProxyForeignKey(
Organization,
related_name="posts",
help_text="The Organization in which the post is held.",
on_delete=models.CASCADE,
)
shape = geo_models.GeometryField(null=True)
@cached_property
def current_member(self):
membership = (
self.memberships.filter(end_date_dt__gt=timezone.now())
.order_by("-end_date", "-start_date")
.select_related("person__councilmatic_person")
.first()
)
if membership:
membership.person = membership.person.councilmatic_person
return membership
class MembershipManager(CastToDateTimeMixin, models.Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.annotate(
end_date_dt=self.cast_to_datetime("end_date"),
start_date_dt=self.cast_to_datetime("start_date"),
)
)
class Membership(opencivicdata.core.models.Membership, CastToDateTimeMixin):
class Meta:
proxy = True
base_manager_name = "objects"
objects = MembershipManager()
organization = ProxyForeignKey(
Organization,
related_name="memberships",
# memberships will go away if the org does
on_delete=models.CASCADE,
help_text="A link to the Organization in which the Person is a member.",
)
person = ProxyForeignKey(
Person,
related_name="memberships",
null=True,
# Membership will just unlink if the person goes away
on_delete=models.SET_NULL,
help_text="A link to the Person that is a member of the Organization.",
)
post = ProxyForeignKey(
Post,
related_name="memberships",
null=True,
# Membership will just unlink if the post goes away
on_delete=models.SET_NULL,
help_text=" The Post held by the member in the Organization.",
)
class EventManager(CastToDateTimeMixin, models.Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.annotate(start_time=self.cast_to_datetime("start_date"))
)
class Event(opencivicdata.legislative.models.Event):
event = models.OneToOneField(
opencivicdata.legislative.models.Event,
on_delete=models.CASCADE,
related_name="councilmatic_event",
parent_link=True,
)
slug = models.SlugField(max_length=200, unique=True)
def delete(self, **kwargs):
kwargs["keep_parents"] = kwargs.get("keep_parents", True)
super().delete(**kwargs)
objects = EventManager()
@property
def event_page_url(self):
try:
link = reverse(
"{}:event_detail".format(settings.APP_NAME), args=(self.slug,)
)
except NoReverseMatch:
link = reverse("event_detail", args=(self.slug,))
return link
@property
def link_html(self):
return '<a href="{0}" title="View Event Details">{1}</a>'.format(
self.event_page_url, self.name
)
@property
def clean_agenda_items(self):
agenda_items = self.agenda.order_by("order").all()
agenda_deduped = []
descriptions_seen = []
for a in agenda_items:
if a.description not in descriptions_seen:
descriptions_seen.append(a.description)
agenda_deduped.append(a)
return agenda_deduped
@classmethod
def next_city_council_meeting(cls):
if hasattr(settings, "CITY_COUNCIL_MEETING_NAME"):
return (
cls.objects.filter(name__icontains=settings.CITY_COUNCIL_MEETING_NAME)
.filter(start_time__gt=timezone.now())
.order_by("start_time")
.first()
)
else:
return None
@classmethod
def most_recent_past_city_council_meeting(cls):
if hasattr(settings, "CITY_COUNCIL_MEETING_NAME"):
return (
cls.objects.filter(name__icontains=settings.CITY_COUNCIL_MEETING_NAME)
.filter(start_time__lt=timezone.now())
.order_by("-start_time")
.first()
)
else:
return None
@classmethod
def upcoming_committee_meetings(cls):
return (
cls.objects.filter(start_time__gt=timezone.now())
.exclude(name__icontains=settings.CITY_COUNCIL_MEETING_NAME)
.order_by("start_time")
.all()[:3]
)
@property
def local_start_time(self):
return timezone.localtime(self.start_time)
class Bill(opencivicdata.legislative.models.Bill):
bill = models.OneToOneField(
opencivicdata.legislative.models.Bill,
on_delete=models.CASCADE,
related_name="councilmatic_bill",
parent_link=True,
)
slug = models.SlugField(unique=True)
restrict_view = models.BooleanField(default=False)
last_action_date = models.DateField(blank=True, null=True)
def delete(self, **kwargs):
kwargs["keep_parents"] = kwargs.get("keep_parents", True)
super().delete(**kwargs)
def __str__(self):
return self.friendly_name
@property
def bill_type(self):
type = self.extras.get("local_classification")
if not type:
(type,) = self.classification
return type
@property
def full_text(self):
return self.extras.get("rtf_text")
@property
def ocr_full_text(self):
return self.extras.get("plain_text")
@property
def html_text(self):
return self.extras.get("html_text")
@property
def web_source(self):
return self.sources.filter(note="web").get()
@property
def controlling_body(self):
"""
grabs the organization that's currently 'responsible' for a bill
"""
if self.current_action:
related_orgs = self.current_action.related_entities.filter(
entity_type="organization"
).all()
# when a bill is referred from city council
# to a committee, controlling body is the organization
# the bill was referred to (a related org)
if related_orgs:
controlling_bodies = [rel.organization for rel in related_orgs]
return controlling_bodies
# otherwise, the controlling body is usually whatever organization
# performed the most recent action (this is the case most of the
# time)
else:
return [self.current_action.organization]
else:
return None
@property
def last_action_org(self):
"""
grabs whatever organization performed the most recent action
"""
return self.current_action.organization if self.current_action else None
@property
def ordered_actions(self):
"""
returns all actions ordered by date in descending order
"""
return self.actions.order_by("-order")
@property
def current_action(self):
"""
grabs the most recent action on a bill
"""
return self.actions.last()
@property
def first_action(self):
"""
grabs the first action on a bill
"""
return self.actions.first() if self.actions.all() else None
@property
def date_passed(self):
return self.actions.filter(classification="passage").last().date_dt
@property
def friendly_name(self):
"""
the bill title/headers displayed throughout the site (bill listings, bill detail pages)
by default this returns the bill identifier - override this in
custom subclass to construct a friendly name that makes sense locally
"""
return self.identifier
@property
def primary_sponsor(self):
"""
grabs the primary sponsorship for a bill
"""
return self.sponsorships.filter(primary=True).first()
@property
def pseudo_topics(self):
"""
returns a list of artificial topics for a bill, from the committees
that have been involved in the bill's history (the actions)
this serves as a backup when there isn't data on the real topics,
so that bill listings can still have some useful tags populated
"""
if self.actions.all():
orgs = set(
[
a.organization.name
for a in self.actions.all()
if (
a.organization.name != "Mayor"
and a.organization.name != settings.CITY_COUNCIL_NAME
)
]
)
if (
not orgs
and self.controlling_body
and self.controlling_body[0].name != settings.CITY_COUNCIL_NAME
):
orgs = self.controlling_body
return list(orgs)
else:
return []
@property
def topics(self):
"""
returns a list of topics for a bill
override this in custom subclass for richer topic logic
"""
return []
@property
def addresses(self):
"""
returns a list of relevant addresses for a bill
override this in custom subclass
"""
return []
@property
def inferred_status(self):
"""
infers bill status, to be displayed in colored labels next to bill names
override this in custom subclass w/ richer logic for determining
bill status, e.g. active, passed, approved, failed, stale
"""
return None
@property
def listing_description(self):
abstract = self.abstracts.first()
if abstract:
return abstract
return self.title
@property
def full_text_doc_url(self):
"""
override this if instead of having full text as string stored in
full_text, it is a PDF document that you can embed on the page
"""
return None
@classmethod
def bills_since(cls, date_cutoff):
"""
grabs all bills that have had activity since a given date
"""
return cls.objects.filter(last_action_date__gte=date_cutoff)
@classmethod
def new_bills_since(cls, date_cutoff):
"""
grabs all bills that have been added since a given date
(bills_since = new_bills_since + updated_bills_since)
"""
all_bills_since = cls.bills_since(date_cutoff)
new_bills_since = [
b for b in all_bills_since if b.first_action.date >= date_cutoff
]
return new_bills_since
@classmethod
def updated_bills_since(cls, date_cutoff):
"""
grabs all previously existing bills that have had activity since a given date
(bills_since = new_bills_since + updated_bills_since)
"""
all_bills_since = cls.bills_since(date_cutoff)
updated_bills_since = [
b for b in all_bills_since if b.first_action.date < date_cutoff
]
return updated_bills_since
@property
def unique_related_upcoming_events(self):
events = [
r.agenda_item.event
for r in self.eventrelatedentity_set.filter(
agenda_item__event__start_date__gte=timezone.now()
).all()
]
return list(set(events))
def get_last_action_date(self):
"""
Return the date of the most recent action. If there is no action,
return the date of the most recent past event for which the bill
appears on the agenda. Otherwise, return None.
"""
current_action = self.current_action
if current_action:
return current_action.date_dt
try:
last_agenda = Event.objects.filter(
start_time__lte=timezone.now(), agenda__related_entities__bill=self
).latest("start_time")
except Event.DoesNotExist:
return None
else:
return last_agenda.start_time.date()
class BillSponsorship(opencivicdata.legislative.models.BillSponsorship):
class Meta:
proxy = True
bill = ProxyForeignKey(Bill, related_name="sponsorships", on_delete=models.CASCADE)
organization = ProxyForeignKey(Organization, null=True, on_delete=models.SET_NULL)
person = ProxyForeignKey(Person, null=True, on_delete=models.SET_NULL)
class BillActionManager(CastToDateTimeMixin, models.Manager):
def get_queryset(self):
return super().get_queryset().annotate(date_dt=self.cast_to_date("date"))
class BillAction(opencivicdata.legislative.models.BillAction):
class Meta:
proxy = True
objects = BillActionManager()
bill = ProxyForeignKey(Bill, related_name="actions", on_delete=models.CASCADE)
organization = ProxyForeignKey(
Organization,
related_name="actions",
# don't let an org delete wipe out a bunch of bill actions
on_delete=models.PROTECT,
)
@property
def label(self):
c = self.classification
if not c:
return "default"
c = c[0]
if c == "committee-passage":
return "success"
if c == "passage":
return "success"
if c == "executive-signature":
return "success"
if c == "amendment-passage":
return "success"
if c == "amendment-introduction":
return "default"
if c == "introduction":
return "default"
if c == "committee-referral":
return "default"
if c == "filing":
return "default"
if c == "executive-received":
return "default"
if c == "deferred":
return "primary"
else:
return "default"
@cached_property
def referred_org(self):
if self.description == "Referred":
related_entity = self.related_entities.get()
if related_entity:
return related_entity.organization
class BillActionRelatedEntity(opencivicdata.legislative.models.BillActionRelatedEntity):
class Meta:
proxy = True
action = ProxyForeignKey(
BillAction, related_name="related_entities", on_delete=models.CASCADE
)
organization = ProxyForeignKey(Organization, null=True, on_delete=models.SET_NULL)