Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add backend implementation for alert system #359

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion backend/composer/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from django import forms

from composer.models import (
AlertType,
Phenotype,
Sex,
ConnectivityStatement,
Expand All @@ -19,6 +20,7 @@
Profile,
Sentence,
Specie,
StatementAlert,
Tag,
Via,
FunctionalCircuitRole,
Expand Down Expand Up @@ -68,6 +70,17 @@ class NoteConnectivityStatementInline(admin.StackedInline):
sortable_options = "disabled"


class AlertTypeAdmin(admin.ModelAdmin):
list_display = ('name', 'uri')
search_fields = ('name', 'uri')

class StatementAlertInline(admin.StackedInline):
model = StatementAlert
extra = 1
autocomplete_fields = ('alert_type', )
fields = ('alert_type', 'text', 'saved_by', 'created_at', 'updated_at')
readonly_fields = ('created_at', 'updated_at')

class ConnectivityStatementInline(nested_admin.NestedStackedInline):
model = ConnectivityStatement
extra = 1
Expand Down Expand Up @@ -245,7 +258,7 @@ class ConnectivityStatementAdmin(

fieldsets = ()

inlines = (ProvenanceInline, NoteConnectivityStatementInline, ViaInline, DestinationInline)
inlines = (ProvenanceInline, NoteConnectivityStatementInline, ViaInline, DestinationInline, StatementAlertInline)

@admin.display(description="Knowledge Statement")
def short_ks(self, obj):
Expand Down Expand Up @@ -296,6 +309,7 @@ def get_form(self, request, obj=None, change=False, **kwargs):
return super().get_form(request, obj=obj, change=change, **kwargs)



# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Expand All @@ -315,6 +329,7 @@ def get_form(self, request, obj=None, change=False, **kwargs):
admin.site.register(Tag)
admin.site.register(FunctionalCircuitRole)
admin.site.register(ProjectionPhenotype)
admin.site.register(AlertType, AlertTypeAdmin)
# admin.site.register(ExportMetrics)


Expand Down
53 changes: 51 additions & 2 deletions backend/composer/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from ..enums import SentenceState, CSState
from ..models import (
AlertType,
AnatomicalEntity,
Phenotype,
ProjectionPhenotype,
Expand All @@ -20,6 +21,7 @@
Profile,
Sentence,
Specie,
StatementAlert,
Tag,
Via, Destination, AnatomicalEntityIntersection, AnatomicalEntityMeta, GraphRenderingState,
)
Expand Down Expand Up @@ -68,7 +70,7 @@ class UserSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = ("id", "username", "first_name", "last_name", "email")
fields = ("id", "username", "first_name", "last_name", "email", "is_staff")


class ProfileSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -506,7 +508,31 @@ def to_representation(self, instance):
return {
'serialized_graph': representation['serialized_graph'],
}

class AlertTypeSerializer(serializers.ModelSerializer):
class Meta:
model = AlertType
fields = ('id', 'name', 'uri')

class StatementAlertSerializer(serializers.ModelSerializer):
alert_type = serializers.PrimaryKeyRelatedField(queryset=AlertType.objects.all(), required=True)
id = serializers.IntegerField(required=False)
class Meta:
model = StatementAlert
fields = ('id', 'alert_type', 'text', 'saved_by', 'created_at', 'updated_at')
read_only_fields = ('created_at', 'updated_at', 'saved_by', 'alert_type')

def create(self, validated_data):
request = self.context.get('request')
user = request.user if request else None
validated_data['saved_by'] = user
return super().create(validated_data)

def update(self, instance, validated_data):
request = self.context.get('request')
user = request.user if request else None
validated_data['saved_by'] = user
return super().update(instance, validated_data)

class ConnectivityStatementSerializer(BaseConnectivityStatementSerializer):
"""Connectivity Statement"""
Expand All @@ -533,6 +559,8 @@ class ConnectivityStatementSerializer(BaseConnectivityStatementSerializer):
statement_preview = serializers.SerializerMethodField()
errors = serializers.SerializerMethodField()
graph_rendering_state = GraphStateSerializer(required=False, allow_null=True)
statement_alerts = StatementAlertSerializer(many=True, read_only=False, required=False)


def get_available_transitions(self, instance) -> list[CSState]:
request = self.context.get("request", None)
Expand Down Expand Up @@ -661,7 +689,8 @@ class Meta(BaseConnectivityStatementSerializer.Meta):
"has_notes",
"statement_preview",
"errors",
"graph_rendering_state"
"graph_rendering_state",
"statement_alerts"
)


Expand Down Expand Up @@ -705,13 +734,15 @@ class Meta:
"statement_preview",
"errors",
"graph_rendering_state",
"statement_alerts",
)
read_only_fields = ("state","owner", "owner_id")

def update(self, instance, validated_data):
validated_data.pop("owner", None)
validated_data.pop("owner_id", None)

# Handle graph_rendering_state
graph_rendering_state_data = validated_data.pop("graph_rendering_state", None)
if graph_rendering_state_data is not None:
graph_state, _ = GraphRenderingState.objects.get_or_create(
Expand All @@ -730,6 +761,24 @@ def update(self, instance, validated_data):
if origins is not None:
instance.origins.set(origins)

# Handle statement alerts
alerts_data = validated_data.pop('statement_alerts', [])
for alert_data in alerts_data:
alert_id = alert_data.get('id')
if alert_id:
# Update existing alert
alert_instance = StatementAlert.objects.get(id=alert_id)
alert_instance.text = alert_data.get('text', alert_instance.text)
alert_instance.save()
else:
# Create new alert if id is not provided
StatementAlert.objects.create(
connectivity_statement=instance,
alert_type=alert_data['alert_type'],
text=alert_data.get('text', '')
)


return super().update(instance, validated_data)

def to_representation(self, instance):
Expand Down
5 changes: 4 additions & 1 deletion backend/composer/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
KnowledgeStatementViewSet,
jsonschemas,
NoteViewSet,
AlertTypeViewSet,
ProfileViewSet,
SentenceViewSet,
SpecieViewSet,
TagViewSet,
ViaViewSet,
SexViewSet, DestinationViewSet,
SexViewSet,
DestinationViewSet,
)

# Create a router and register our viewsets with it.
Expand All @@ -34,6 +36,7 @@
router.register(r"note-tag", TagViewSet, basename="note-tag")
router.register(r"sentence", SentenceViewSet, basename="sentence")
router.register(r"specie", SpecieViewSet, basename="specie")
router.register(r"alert", AlertTypeViewSet, basename="alert")
router.register(r"profile", ProfileViewSet, basename="profile")
router.register(r"tag", TagViewSet, basename="tag")
router.register(r"via", ViaViewSet, basename="via")
Expand Down
12 changes: 11 additions & 1 deletion backend/composer/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
DestinationFilter,
)
from .serializers import (
AlertTypeSerializer,
AnatomicalEntitySerializer,
PhenotypeSerializer,
ProjectionPhenotypeSerializer,
Expand All @@ -50,6 +51,7 @@
IsOwnerOfConnectivityStatementOrReadOnly,
)
from ..models import (
AlertType,
AnatomicalEntity,
Phenotype,
ProjectionPhenotype,
Expand Down Expand Up @@ -325,6 +327,14 @@ class NoteViewSet(viewsets.ModelViewSet):
filterset_class = NoteFilter


class AlertTypeViewSet(viewsets.ReadOnlyModelViewSet):
"""
A viewset for viewing the list of alert types.
"""

queryset = AlertType.objects.all()
serializer_class = AlertTypeSerializer

class ConnectivityStatementViewSet(
ProvenanceMixin,
SpecieMixin,
Expand All @@ -348,7 +358,7 @@ class ConnectivityStatementViewSet(
service = ConnectivityStatementStateService

def get_serializer_class(self):
if self.action in ['update', 'partial_update']:
if self.action in ["update", "partial_update"]:
return ConnectivityStatementUpdateSerializer
if self.action == "list":
return BaseConnectivityStatementSerializer
Expand Down
77 changes: 77 additions & 0 deletions backend/composer/migrations/0062_alerttype_statementalert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Generated by Django 4.1.4 on 2024-11-14 17:01

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("composer", "0061_graphrenderingstate_and_more"),
]

operations = [
migrations.CreateModel(
name="AlertType",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=200, unique=True)),
("uri", models.URLField()),
],
),
migrations.CreateModel(
name="StatementAlert",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("text", models.TextField()),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"alert_type",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="statement_alerts",
to="composer.alerttype",
),
),
(
"connectivity_statement",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="statement_alerts",
to="composer.connectivitystatement",
),
),
(
"saved_by",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"unique_together": {("connectivity_statement", "alert_type")},
},
),
]
37 changes: 36 additions & 1 deletion backend/composer/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -887,7 +887,6 @@ def __str__(self):
class Meta:
verbose_name_plural = "Provenances"


class Note(models.Model):
"""Note"""

Expand Down Expand Up @@ -1013,3 +1012,39 @@ class Meta:
name="unique_state_per_export_batch",
),
]


class AlertType(models.Model):
name = models.CharField(max_length=200, unique=True)
uri = models.URLField()

def __str__(self):
return self.name


class StatementAlert(models.Model):
connectivity_statement = models.ForeignKey(
ConnectivityStatement,
on_delete=models.CASCADE,
related_name='statement_alerts'
)
alert_type = models.ForeignKey(
AlertType,
on_delete=models.CASCADE,
related_name='statement_alerts'
)
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
saved_by = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True
)

class Meta:
unique_together = ('connectivity_statement', 'alert_type')

def __str__(self):
return f"{self.alert_type.name} for Statement {self.connectivity_statement.id}"
Loading