Skip to content

Commit

Permalink
Merge pull request #1917 from ResearchHub/remove-paper-event
Browse files Browse the repository at this point in the history
chore: Remove paper event
  • Loading branch information
gzurowski authored Oct 18, 2024
2 parents a297f95 + 03bfa41 commit 4aee193
Show file tree
Hide file tree
Showing 7 changed files with 24 additions and 206 deletions.
16 changes: 16 additions & 0 deletions src/analytics/migrations/0008_delete_paperevent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Generated by Django 4.2.15 on 2024-10-16 08:24

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
("analytics", "0007_alter_paperevent_created_location_meta"),
]

operations = [
migrations.DeleteModel(
name="PaperEvent",
),
]
38 changes: 0 additions & 38 deletions src/analytics/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from django.db import models
from django.db.models import JSONField

from researchhub.lib import CREATED_LOCATION_CHOICES
from user.models import User

INTERACTIONS = {
Expand All @@ -24,39 +22,3 @@ class WebsiteVisits(models.Model):

def __str__(self):
return f"{self.uuid}"


class PaperEvent(models.Model):
CLICK = "CLICK"
VIEW = "VIEW"
PAPER = "PAPER"

paper = models.ForeignKey(
"paper.Paper",
on_delete=models.SET_NULL,
related_name="events",
related_query_name="event",
null=True,
)
user = models.ForeignKey(
"user.User",
on_delete=models.SET_NULL,
related_name="paper_events",
related_query_name="paper_event",
null=True,
blank=True,
)
interaction = models.CharField(
choices=INTERACTION_CHOICES, max_length=255, default=None, null=True, blank=True
)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
created_location = models.CharField(
choices=CREATED_LOCATION_CHOICES,
max_length=255,
default=None,
null=True,
blank=True,
)
created_location_meta = JSONField(blank=True, null=True)
paper_is_boosted = models.BooleanField()
11 changes: 0 additions & 11 deletions src/analytics/permissions.py

This file was deleted.

16 changes: 1 addition & 15 deletions src/analytics/serializers.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,10 @@
from rest_framework import serializers

from analytics.models import PaperEvent, WebsiteVisits
from user.models import User
from analytics.models import WebsiteVisits


class WebsiteVisitsSerializer(serializers.ModelSerializer):

class Meta:
fields = '__all__'
model = WebsiteVisits


class PaperEventSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(),
many=False,
read_only=False,
required=False
)

class Meta:
model = PaperEvent
exclude = []
96 changes: 3 additions & 93 deletions src/analytics/views.py
Original file line number Diff line number Diff line change
@@ -1,101 +1,11 @@
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework import viewsets

from analytics.models import PaperEvent, WebsiteVisits
from analytics.permissions import UpdateOrDelete
from analytics.serializers import PaperEventSerializer, WebsiteVisitsSerializer
from reputation.models import Contribution
from reputation.tasks import create_contribution
from analytics.models import WebsiteVisits
from analytics.serializers import WebsiteVisitsSerializer


class WebsiteVisitsViewSet(viewsets.ModelViewSet):
queryset = WebsiteVisits.objects.all()
serializer_class = WebsiteVisitsSerializer
http_method_names = ["post"]
permission_classes = ()


class PaperEventViewSet(viewsets.ModelViewSet):
queryset = PaperEvent.objects.all()
serializer_class = PaperEventSerializer
permission_classes = [UpdateOrDelete]
filter_backends = [DjangoFilterBackend, OrderingFilter]
filterset_fields = [
"paper",
"created_date",
"created_location",
"interaction",
"paper_is_boosted",
]
ordering = ["-created_date"]
ordering_fields = ["created_date"]

def create(self, request, *args, **kwargs):
# Is deprecated?
user = request.user
if not user.is_anonymous:
request.data["user"] = user.id

created_location = request.data.get("created_location")
if created_location is not None:
created_location = created_location.upper()
request.data["created_location"] = created_location
else:
return Response(
"Missing required field `created_location`",
status=status.HTTP_400_BAD_REQUEST,
)

interaction = request.data.get("interaction", None)
if interaction is not None:
interaction = interaction.upper()
request.data["interaction"] = interaction

paper_id = request.data["paper"]
res = super().create(request, *args, **kwargs)
paper_event_id = res.data["id"]
if created_location == PaperEvent.PAPER and PaperEvent.VIEW:
create_contribution.apply_async(
(
Contribution.SUPPORTER,
{"app_label": "analytics", "model": "paperevent"},
user.id,
paper_id,
paper_event_id,
),
priority=2,
countdown=10,
)

@action(detail=False, methods=["POST"], permission_classes=[])
def batch_views(self, request, *args, **kwargs):
user = request.user
if not user.is_anonymous:
request.data["user"] = user

created_location = request.data.get("created_location")
if created_location is not None:
created_location = created_location.upper()
request.data["created_location"] = created_location
else:
return Response(
"Missing required field `created_location`",
status=status.HTTP_400_BAD_REQUEST,
)

interaction = request.data.get("interaction", None)
if interaction is not None:
interaction = interaction.upper()
request.data["interaction"] = interaction

events = []
paper_ids = request.data["paper_ids"]
del request.data["paper_ids"]
for id in paper_ids:
events.append(PaperEvent(paper_id=id, **request.data))

PaperEvent.objects.bulk_create(events)
return Response({"msg": "Events Created"}, 201)
49 changes: 4 additions & 45 deletions src/purchase/serializers/purchase_serializer.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import datetime

import rest_framework.serializers as serializers
from django.db.models import CharField, Count, F, Func, IntegerField, Sum, Value
from django.db.models import IntegerField, Sum
from django.db.models.functions import Cast

from analytics.models import INTERACTIONS, PaperEvent
from analytics.models import INTERACTIONS
from discussion.serializers import (
CommentSerializer,
DynamicCommentSerializer,
Expand Down Expand Up @@ -194,49 +194,10 @@ def get_purchases(self, purchase):
return data

def get_stats(self, purchase):
distinct_views = purchase.purchases.filter(
paper__event__interaction=INTERACTIONS["VIEW"],
paper__event__paper_is_boosted=True,
).distinct()
distinct_clicks = purchase.purchases.filter(
paper__event__interaction=INTERACTIONS["CLICK"],
paper__event__paper_is_boosted=True,
).distinct()

total_views = distinct_views.values("paper__event").count()
total_clicks = distinct_clicks.values("paper__event").count()
total_amount = sum(
map(float, purchase.purchases.values_list("amount", flat=True))
)

distinct_views_ids = distinct_views.values_list("paper__event", flat=True)
views = (
PaperEvent.objects.filter(id__in=distinct_views_ids)
.values(
date=Func(
F("created_date"),
Value("YYYY-MM-DD"),
function="to_char",
output_field=CharField(),
)
)
.annotate(views=Count("date"))
)

distinct_clicks_ids = distinct_clicks.values_list("paper__event", flat=True)
clicks = (
PaperEvent.objects.filter(id__in=distinct_clicks_ids)
.values(
date=Func(
F("created_date"),
Value("YYYY-MM-DD"),
function="to_char",
output_field=CharField(),
)
)
.annotate(clicks=Count("date"))
)

created_date = purchase.created_date

max_boost = (
Expand All @@ -250,10 +211,8 @@ def get_stats(self, purchase):
end_date = (created_date + timedelta).isoformat()

stats = {
"views": views,
"clicks": clicks,
"total_views": total_views,
"total_clicks": total_clicks,
"total_views": 0, # TODO: Remove deprecated field
"total_clicks": 0, # TODO: Remove deprecated field
"total_amount": total_amount,
"end_date": end_date,
}
Expand Down
4 changes: 0 additions & 4 deletions src/researchhub/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,6 @@
basename="websiteviews",
)

router.register(
r"events/paper", analytics.views.PaperEventViewSet, basename="events_paper"
)

router.register(r"purchase", purchase.views.PurchaseViewSet, basename="purchase")

router.register(r"transactions", purchase.views.BalanceViewSet, basename="transactions")
Expand Down

0 comments on commit 4aee193

Please sign in to comment.