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 view counters to trips and user profiles #219

Merged
merged 6 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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: 17 additions & 0 deletions app/logger/migrations/0045_add_trip_view_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2 on 2023-12-18 10:43

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("logger", "0044_remove_trip_trip_report_trip_public_notes_and_more"),
]

operations = [
migrations.AddField(
model_name="trip",
name="view_count",
field=models.IntegerField(default=0),
),
]
10 changes: 10 additions & 0 deletions app/logger/models/trip.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.contrib.gis.db import models
from django.core.exceptions import ValidationError
from django.db.models import Sum
from django.http.request import HttpRequest
from django.urls import reverse

from ..validators import (
Expand Down Expand Up @@ -321,6 +322,7 @@ class Trip(models.Model):
followers = models.ManyToManyField(
settings.AUTH_USER_MODEL, blank=True, related_name="followed_trips"
)
view_count = models.IntegerField(default=0)
featured_photo = models.ForeignKey(
"logger.TripPhoto",
null=True,
Expand Down Expand Up @@ -485,6 +487,14 @@ def get_liked_str(self, for_user=None, for_user_friends=None):

return self._build_liked_str(liked_user_names, self_liked)

def add_view(self, request: HttpRequest, commit=True):
if request.user.is_anonymous or self.user == request.user:
anorthall marked this conversation as resolved.
Show resolved Hide resolved
return

self.view_count += 1
if commit:
self.save(update_fields=["view_count"])

@property
def latitude(self):
return self.cave_coordinates.y if self.cave_coordinates else None
Expand Down
13 changes: 10 additions & 3 deletions app/logger/services.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import typing

import boto3
from django.conf import settings
from django.core.paginator import EmptyPage, Paginator
from django.db.models import Case, Count, Exists, OuterRef, Q, Value, When
from django.http import HttpRequest
from users.models import CavingUser

from .models import Trip, TripPhoto
Expand Down Expand Up @@ -90,14 +93,12 @@ def get_trips_context(request, ordering, page=1):
sanitised_trips = [x for x in trips if x.is_viewable_by(request.user)]

try:
paginated_trips = Paginator(
return Paginator(
anorthall marked this conversation as resolved.
Show resolved Hide resolved
object_list=sanitised_trips, per_page=10, allow_empty_first_page=False
).page(page)
except EmptyPage:
return []

return paginated_trips


def get_liked_str_context(request, trips):
"""Return a dictionary of liked strings for each trip
Expand All @@ -109,3 +110,9 @@ def get_liked_str_context(request, trips):
liked_str_index[trip.pk] = trip.get_liked_str(request.user, friends)

return liked_str_index


def bulk_update_view_count(request: HttpRequest, trips: typing.Iterable[Trip]):
anorthall marked this conversation as resolved.
Show resolved Hide resolved
for trip in trips:
trip.add_view(request, commit=False)
Trip.objects.bulk_update(trips, ["view_count"])
4 changes: 4 additions & 0 deletions app/logger/views/feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def get_authenticated_context(self, **kwargs):
# If there are no trips, show the new user page
if context["trips"]:
self.template_name = "logger/social_feed.html"
services.bulk_update_view_count(self.request, context["trips"])
else:
self.template_name = "core/new_user.html"

Expand Down Expand Up @@ -158,4 +159,7 @@ def get_context_data(self, **kwargs):
context["liked_str"] = services.get_liked_str_context(
self.request, context["trips"]
)

services.bulk_update_view_count(self.request, context["trips"])

return context
5 changes: 5 additions & 0 deletions app/logger/views/trips.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ class TripDetail(TripContextMixin, ViewableObjectDetailView):
slug_field = "uuid"
slug_url_kwarg = "uuid"

def get_object(self, *args, **kwargs):
obj = super().get_object(*args, **kwargs)
obj.add_view(self.request)
return obj

def get_queryset(self):
qs = (
Trip.objects.all()
Expand Down
2 changes: 2 additions & 0 deletions app/logger/views/userprofile.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def setup(self, *args, **kwargs):
"""Assign self.profile_user and perform permissions checks"""
super().setup(*args, **kwargs)
self.profile_user = get_object_or_404(User, username=self.kwargs["username"])
self.profile_user.add_profile_view(self.request)
anorthall marked this conversation as resolved.
Show resolved Hide resolved

def get_context_data(self, **kwargs):
context = super().get_context_data()
Expand All @@ -37,6 +38,7 @@ def get_context_data(self, **kwargs):
context["photos"] = self.profile_user.get_photos(for_user=self.request.user)
context["quick_stats"] = self.profile_user.quick_stats
context["show_stats_link"] = self.profile_user == self.request.user
context["private_stats"] = self.profile_user == self.request.user

if self.request.user not in self.profile_user.friends.all():
if self.profile_user.allow_friend_username:
Expand Down
9 changes: 8 additions & 1 deletion app/templates/logger/_quick_stats.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<span class="quick-stat-value">{{ quick_stats.qs_longest_trip|shortdelta }}</span>
</div>

{% if private_stats %}
{% if private_stats is True %}
<div class="nav-item quick-stat border-top pt-2 mt-2">
<span class="quick-stat-name">Last trip</span>
<span class="quick-stat-value">
Expand Down Expand Up @@ -97,6 +97,13 @@
<span class="quick-stat-value">{{ quick_stats.qs_friends }}</span>
</div>

{% if private_stats is True %}
<div class="nav-item quick-stat">
<span class="quick-stat-name">Profile views</span>
<span class="quick-stat-value">{{ user.profile_view_count }}</span>
</div>
{% endif %}

{% if user.has_social_media_links %}
<div class="nav-item quick-stat">
<span class="quick-stat-name">Social media</span>
Expand Down
8 changes: 8 additions & 0 deletions app/templates/logger/_trip_data_blocks.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{% load users_tags %}
{% load logger_tags %}
{% load humanize %}

{% if trip.cavers.all %}
<div class="row mb-3">
Expand Down Expand Up @@ -86,4 +87,11 @@
</div>
{% endfor %}
{% endif %}

{% if user == trip.user %}
<div class="col">
<span class="trip-field">View count</span>
{{ trip.view_count|intcomma }}
</div>
{% endif %}
</div>
8 changes: 7 additions & 1 deletion app/templates/logger/profile.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{% load markdownify %}
{% load core_tags %}
{% load logger_tags %}
{% load humanize %}

{% block stylesheets %}
{% if photos %}
Expand Down Expand Up @@ -302,7 +303,12 @@ <h3 class="my-3">{{ profile_user.name }}</h3>
<dt class="col-sm-4">Account age</dt>
<dd class="col-sm-8">{{ profile_user.date_joined|timesince }}</dd>

{% if user.has_social_media_links %}
{% if private_stats is True %}
<dt class="col-sm-4">Profile views</dt>
<dd class="col-sm-8">{{ profile_user.profile_view_count|intcomma }}</dd>
{% endif %}

{% if profile_user.has_social_media_links %}
<dt class="col-sm-4">Social media</dt>
<dd class="col-sm-8 social-media-links">
{% include "logger/_social_media_links.html" with user=profile_user %}
Expand Down
2 changes: 1 addition & 1 deletion app/templates/sidebars/_profile_page.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@

{% if not private_profile %}
{% include "logger/_quick_stats.html" with quick_stats=quick_stats user=profile_user %}
{% include "logger/_quick_friends.html" with friends=mutual_friends %}
{% include "logger/_quick_friends.html" with friends=mutual_friends private_stats=private_stats%}
{% endif %}
</div>
17 changes: 17 additions & 0 deletions app/users/migrations/0043_cavinguser_profile_view_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2 on 2023-12-18 10:27

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("users", "0042_remove_cavinguser_private_notes"),
]

operations = [
migrations.AddField(
model_name="cavinguser",
name="profile_view_count",
field=models.IntegerField(default=0),
),
]
11 changes: 11 additions & 0 deletions app/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from django.core.validators import MinLengthValidator, RegexValidator
from django.db import models
from django.db.models import Count, Max, QuerySet, Sum
from django.http import HttpRequest
from django.urls import reverse
from django.utils import timezone as django_tz
from django.utils.functional import cached_property
Expand Down Expand Up @@ -191,6 +192,9 @@ class CavingUser(AbstractBaseUser, PermissionsMixin):
help_text="A profile picture to display on your public profile.",
)

# Profile views
profile_view_count = models.IntegerField(default=0)

#
# Settings
#
Expand Down Expand Up @@ -445,6 +449,13 @@ def get_photos(self, for_user: Union["User", "CavingUser", None] = None):

return qs

def add_profile_view(self, request: HttpRequest):
if request.user == self or request.user.is_anonymous:
return

self.profile_view_count += 1
self.save(update_fields=["profile_view_count"])

@property
def trips(self):
return Trip.objects.filter(user=self)
Expand Down