Skip to content

Commit

Permalink
Merge pull request #4790 from freelawproject/3080-es-code-clean-ups
Browse files Browse the repository at this point in the history
3080 Clean up of the alert model
  • Loading branch information
mlissner authored Dec 6, 2024
2 parents b2b1804 + 6d6103b commit d1ccf3a
Show file tree
Hide file tree
Showing 14 changed files with 258 additions and 291 deletions.
28 changes: 27 additions & 1 deletion cl/alerts/api_serializers.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from django.core.exceptions import ValidationError
from django.http import QueryDict
from drf_dynamic_fields import DynamicFieldsMixin
from rest_framework import serializers

from cl.alerts.models import Alert, DocketAlert
from cl.alerts.models import Alert, DocketAlert, validate_alert_type
from cl.api.utils import HyperlinkedModelSerializerWithId
from cl.search.models import SEARCH_TYPES


class SearchAlertSerializer(
DynamicFieldsMixin, HyperlinkedModelSerializerWithId
):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
alert_type = serializers.CharField(required=False)

class Meta:
model = Alert
Expand All @@ -20,6 +24,28 @@ class Meta:
"date_last_hit",
)

def validate(self, attrs):
"""Validate the query type and set default for alert_type if not
provided."""
qd = QueryDict(attrs.get("query").encode(), mutable=True)
alert_type = qd.get("type")
if alert_type:
try:
validate_alert_type(alert_type)
attrs["alert_type"] = alert_type
except ValidationError as e:
raise serializers.ValidationError({"alert_type": e.messages})
else:
# If not type provided in the query it's an OPINION Alert.
attrs["alert_type"] = SEARCH_TYPES.OPINION
return attrs

def create(self, validated_data):
return super().create(validated_data)

def update(self, instance, validated_data):
return super().update(instance, validated_data)


class SearchAlertSerializerModel(
DynamicFieldsMixin, serializers.ModelSerializer
Expand Down
7 changes: 2 additions & 5 deletions cl/alerts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,12 @@ def clean_rate(self):
class Meta:
model = Alert
exclude = ("user", "secret_key")
fields = (
"name",
"query",
"rate",
)
fields = ("name", "query", "rate", "alert_type")
widgets = {
"query": HiddenInput(),
"name": TextInput(attrs={"class": "form-control"}),
"rate": Select(attrs={"class": "form-control"}),
"alert_type": HiddenInput(),
}


Expand Down
143 changes: 0 additions & 143 deletions cl/alerts/management/commands/clean_up_search_alerts.py

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Generated by Django 5.1.2 on 2024-12-04 23:12

import cl.alerts.models
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("alerts", "0012_add_schedule_alert_hit_content_type_index"),
]

operations = [
migrations.AlterField(
model_name="alert",
name="alert_type",
field=models.CharField(
choices=[
("o", "Opinions"),
("r", "RECAP"),
("oa", "Oral Arguments"),
],
help_text="The type of search alert this is, one of: o (Opinions), r (RECAP), oa (Oral Arguments)",
max_length=3,
validators=[cl.alerts.models.validate_alert_type],
),
),
migrations.AlterField(
model_name="alertevent",
name="alert_type",
field=models.CharField(
choices=[
("o", "Opinions"),
("r", "RECAP"),
("oa", "Oral Arguments"),
],
help_text="The type of search alert this is, one of: o (Opinions), r (RECAP), oa (Oral Arguments)",
max_length=3,
validators=[cl.alerts.models.validate_alert_type],
),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
BEGIN;
--
-- Alter field alert_type on alert
--
-- (no-op)
--
-- Alter field alert_type on alertevent
--
-- (no-op)
COMMIT;
24 changes: 16 additions & 8 deletions cl/alerts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,25 @@
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.http import QueryDict
from django.utils.crypto import get_random_string

from cl.lib.models import AbstractDateTimeModel
from cl.search.models import SEARCH_TYPES, Docket


def validate_alert_type(value):
"""Validate if the provided alert type is supported.
:param value: The alert type to validate.
:return: None.
"""
valid_types = dict(SEARCH_TYPES.SUPPORTED_ALERT_TYPES)
if value not in valid_types:
raise ValidationError(f"Unsupported alert type: {value}")


@pghistory.track()
class Alert(AbstractDateTimeModel):
REAL_TIME = "rt"
Expand Down Expand Up @@ -48,10 +58,12 @@ class Alert(AbstractDateTimeModel):
)
alert_type = models.CharField(
help_text="The type of search alert this is, one of: %s"
% ", ".join(f"{t[0]} ({t[1]})" for t in SEARCH_TYPES.NAMES),
% ", ".join(
f"{t[0]} ({t[1]})" for t in SEARCH_TYPES.SUPPORTED_ALERT_TYPES
),
max_length=3,
choices=SEARCH_TYPES.NAMES,
default=SEARCH_TYPES.OPINION,
validators=[validate_alert_type],
choices=SEARCH_TYPES.SUPPORTED_ALERT_TYPES,
)
secret_key = models.CharField(
verbose_name="A key to be used in links to access the alert without "
Expand All @@ -70,10 +82,6 @@ def save(self, *args, **kwargs):
"""Ensure we get a token when we save the first time."""
if self.pk is None:
self.secret_key = get_random_string(length=40)

# Set the search type based on the provided query.
qd = QueryDict(self.query.encode(), mutable=True)
self.alert_type = qd.get("type", SEARCH_TYPES.OPINION)
super().save(*args, **kwargs)


Expand Down
4 changes: 2 additions & 2 deletions cl/alerts/templates/includes/search_alerts/table_header.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
<tr>
<th data-label="Name and Query">Name and Query</th>
<th data-label="Alert&nbsp;Type">Alert&nbsp;Type</th>
<th data-label="Frequency">Frequency</th>
{% if is_profile_dashboard %}
<th data-label="Last&nbsp;Hit" colspan="2">Last&nbsp;Hit</th>
<th data-label="Last&nbsp;Hit">Last&nbsp;Hit</th>
{% endif %}
<th data-label="Frequency">Frequency</th>
</tr>
</thead>
2 changes: 1 addition & 1 deletion cl/alerts/templates/search_alert_confirmation.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<div class="text-center">
<h1> Please confirm your unsubscription </h1>
<h3 class="gray alt">&mdash; from &mdash;</h3>
<h3>Your {{alert.get_rate_display|lower}} {% if alert.alert_type == 'o' %}opinion{% elif alert.alert_type == 'oa' %}oral argument{% endif %} alert &mdash; <span class="gray">"{{ alert.name }}"</span></h3>
<h3>Your {{alert.get_rate_display|lower}} {% if alert.alert_type == 'o' %}opinion{% elif alert.alert_type == 'oa' %}oral argument{% elif alert.alert_type == 'r' %}RECAP{% endif %} alert &mdash; <span class="gray">"{{ alert.name }}"</span></h3>
<form id="confirmation" action="" method="post">{% csrf_token %}
<div class="form-group">
{{ form.hcaptcha }}
Expand Down
Loading

0 comments on commit d1ccf3a

Please sign in to comment.