-
Notifications
You must be signed in to change notification settings - Fork 110
/
django.py
369 lines (312 loc) · 11.5 KB
/
django.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
import re
from datetime import date
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.functional import cached_property
from django.utils.html import strip_tags
from wagtail.admin.panels import FieldPanel
from wagtail.contrib.frontend_cache.utils import PurgeBatch
import regdown
# Labels always require at least 1 alphanumeric character, then any number of
# alphanumeric characters and hyphens.
label_re_str = r"[\w]+[-\w]*"
validate_label = RegexValidator(
re.compile(r"^" + label_re_str + r"$"),
"Enter a valid “label” consisting of letters, numbers, hyphens, "
"and no spaces.",
"invalid",
)
def sortable_label(label, separator="-"):
"""Create a sortable tuple out of a label.
Converts a dashed label into a tuple based on the following rules:
- If a segment is numeric, it will get three leading zero places
- If a segment is alphabetic and is already uppercase, it is
returned as is.
- If a segment is alphabetic but is not all uppercase, it is
lowercased entirely.
- Anything else is returned as-is.
Intended to be used like `sorted(sections, key=Section.sortable_label)`
"""
segments = []
for segment in label.split(separator):
if segment.isdigit():
segments.append(segment.zfill(4))
elif segment.isalpha() and segment.isupper():
segments.append(segment)
elif segment.isalpha():
segments.append(segment.lower())
else:
segments.append(segment)
return tuple(segments)
class Part(models.Model):
cfr_title_number = models.CharField(max_length=255)
chapter = models.CharField(max_length=255)
part_number = models.CharField(max_length=255)
title = models.CharField(max_length=255)
short_name = models.CharField(max_length=255, blank=True)
panels = [
FieldPanel("cfr_title_number"),
FieldPanel("title"),
FieldPanel("part_number"),
FieldPanel("short_name"),
FieldPanel("chapter"),
]
@property
def cfr_title(self):
return str(self)
def __str__(self):
name = f"{self.cfr_title_number} CFR Part {self.part_number}"
if self.short_name:
name += f" ({self.short_name})"
return name
class Meta:
ordering = ["part_number"]
@cached_property
def effective_version(self):
"""Return the current effective version of the regulation.
This selects based on effective_date being less than or equal to
the current date and version is not a draft."""
effective_version = (
self.versions.filter(draft=False, effective_date__lte=date.today())
.order_by("-effective_date")
.first()
)
return effective_version
class EffectiveVersion(models.Model):
authority = models.CharField(max_length=255, blank=True)
source = models.CharField(max_length=255, blank=True)
effective_date = models.DateField(default=date.today)
created = models.DateField(default=date.today)
draft = models.BooleanField(default=False)
part = models.ForeignKey(
Part, on_delete=models.CASCADE, related_name="versions"
)
panels = [
FieldPanel("authority"),
FieldPanel("source"),
FieldPanel("effective_date"),
FieldPanel("part"),
FieldPanel("draft"),
FieldPanel("created"),
]
def __str__(self):
return str(self.part) + f", Effective on {self.effective_date}"
@property
def live_version(self):
return self.part.effective_version == self
@property
def status(self):
if self.live_version:
return "LIVE"
if self.draft is True:
return "Unapproved draft"
if self.effective_date >= date.today():
return "Future version"
return "Previous version"
def validate_unique(self, exclude=None):
super().validate_unique(exclude=exclude)
# Enforce some uniqueness on the effective-date. It will need to be
# unique within a part, so if this part has a date the same as this
# one, we throw a validation error.
versions_with_this_date = self.part.versions.filter(
effective_date=self.effective_date
)
if self.pk:
versions_with_this_date = versions_with_this_date.exclude(
pk=self.pk
)
if versions_with_this_date.count() > 0:
raise ValidationError(
{
"effective_date": [
"The part selected below already has an effective "
"version with this date."
]
}
)
class Meta:
ordering = ["effective_date"]
default_related_name = "version"
class Subpart(models.Model):
label = models.CharField(
max_length=255,
validators=[validate_label],
help_text="Labels must be unique within this regulation version and "
"always require at least 1 alphanumeric character, "
"then any number of alphanumeric characters and hyphens, "
"with no spaces.",
)
title = models.CharField(max_length=255, blank=True)
version = models.ForeignKey(
EffectiveVersion, on_delete=models.CASCADE, related_name="subparts"
)
BODY = 0000
APPENDIX = 1000
INTERPRETATION = 2000
SUBPART_TYPE_CHOICES = (
(BODY, "Regulation Body"),
(APPENDIX, "Appendix"),
(INTERPRETATION, "Interpretation"),
)
subpart_type = models.IntegerField(
choices=SUBPART_TYPE_CHOICES,
default=BODY,
)
panels = [
FieldPanel("label"),
FieldPanel("title"),
FieldPanel("subpart_type"),
FieldPanel("version"),
]
def __str__(self):
return str(self.version) + ", " + self.title
@property
def type(self):
return dict(Subpart.SUBPART_TYPE_CHOICES)[self.subpart_type]
@property
def subpart_heading(self):
"""Keeping for now as possible hook into secondary nav"""
return ""
@property
def section_range(self):
if self.subpart_type != Subpart.BODY or not self.sections.exists():
return ""
sections = self.sections.all()
return f"{sections[0].numeric_label}–{sections.reverse()[0].numeric_label}" # noqa: E501
class Meta:
ordering = ["subpart_type", "label"]
class Section(models.Model):
label = models.CharField(
max_length=255,
validators=[validate_label],
help_text="Labels always require at least 1 alphanumeric character, "
"then any number of alphanumeric characters and hyphens, "
"with no spaces.",
)
title = models.CharField(max_length=255, blank=True)
contents = models.TextField(blank=True)
subpart = models.ForeignKey(
Subpart, on_delete=models.CASCADE, related_name="sections"
)
sortable_label = models.CharField(max_length=255)
panels = [
FieldPanel("label"),
FieldPanel("subpart"),
FieldPanel("title"),
FieldPanel("contents"),
]
@cached_property
def url_path(self):
"""
Lowercase label for proper url rendering
"""
return self.label.lower()
def __str__(self):
return str(self.subpart) + ", " + self.title
class Meta:
ordering = ["sortable_label"]
def extract_graphs(self):
"""Break out and store a section's paragraphs for indexing."""
part = self.subpart.version.part
section_tag = f"{part.part_number}-{self.label}"
extractor = regdown.extract_labeled_paragraph
paragraph_ids = re.findall(r"[^{]*{(?P<label>[\w\-]+)}", self.contents)
created = 0
deleted = 0
kept = 0
exclude_from_deletion = []
known_ids = []
dupes = []
for pid in paragraph_ids:
raw_graph = extractor(pid, self.contents, exact=True)
markup_graph = regdown.regdown(raw_graph)
index_graph = strip_tags(markup_graph).strip()
full_id = f"{section_tag}-{pid}"
graph, cr = SectionParagraph.objects.get_or_create(
paragraph=index_graph, paragraph_id=pid, section=self
)
if cr:
created += 1
else:
if full_id in known_ids:
dupes.append(full_id)
else:
known_ids.append(full_id)
kept += 1
exclude_from_deletion.append(graph.pk)
to_delete = SectionParagraph.objects.filter(
section__subpart__version__part=part, section__label=self.label
).exclude(pk__in=exclude_from_deletion)
deleted += to_delete.count()
for graph in to_delete:
graph.delete()
dupes = sorted(set(dupes))
return {
"section": section_tag,
"created": created,
"deleted": deleted,
"kept": kept,
"dupes": dupes,
}
def validate_unique(self, *args, **kwargs):
super().validate_unique(*args, **kwargs)
# Ensure that the section's label is unique within this version.
sections_with_duplicate_labels = self.__class__.objects.filter(
subpart__version=self.subpart.version, label=self.label
).exclude(pk=self.pk)
if sections_with_duplicate_labels.exists():
raise ValidationError(
{"label": "Section label must be unique to this version"}
)
def save(self, **kwargs):
self.sortable_label = "-".join(sortable_label(self.label))
super().save(**kwargs)
@cached_property
def part(self):
return self.subpart.version.part.part_number
@property
def section_number(self):
return self.label
@property
def numeric_label(self):
if self.label.isdigit():
return f"\xa7\xa0{self.part}.{int(self.label)}"
else:
return ""
@property
def title_content(self):
if self.numeric_label:
return self.title.replace(self.numeric_label, "").strip()
else:
return self.title
class SectionParagraph(models.Model):
"""Provide storage for section paragraphs."""
paragraph = models.TextField(blank=True)
paragraph_id = models.CharField(max_length=255, blank=True)
section = models.ForeignKey(
Section, on_delete=models.CASCADE, related_name="paragraphs"
)
def __str__(self):
return f"Section {self.section.part}-{self.section.label} paragraph {self.paragraph_id}" # noqa: E501
@receiver(post_save, sender=EffectiveVersion)
def effective_version_saved(sender, instance, **kwargs):
"""Invalidate the cache if the effective_version is not a draft"""
if not instance.draft:
batch = PurgeBatch()
for page in instance.part.page.all():
urls = page.get_urls_for_version(instance)
batch.add_urls(urls)
batch.purge()
@receiver(post_save, sender=Section)
def section_saved(sender, instance, **kwargs):
if not instance.subpart.version.draft:
batch = PurgeBatch()
for page in instance.subpart.version.part.page.all():
urls = page.get_urls_for_version(
instance.subpart.version, section=instance
)
batch.add_urls(urls)
batch.purge()