separate views out 2/2
This commit is contained in:
0
games/views/__init__.py
Normal file
0
games/views/__init__.py
Normal file
102
games/views/device.py
Normal file
102
games/views/device.py
Normal file
@ -0,0 +1,102 @@
|
||||
from typing import Any
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse
|
||||
|
||||
from games.forms import DeviceForm
|
||||
from games.models import Device
|
||||
from games.views.general import dateformat
|
||||
|
||||
|
||||
@login_required
|
||||
def list_devices(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[Any, Any] = {}
|
||||
page_number = request.GET.get("page", 1)
|
||||
limit = request.GET.get("limit", 10)
|
||||
devices = Device.objects.order_by("-created_at")
|
||||
page_obj = None
|
||||
if int(limit) != 0:
|
||||
paginator = Paginator(devices, limit)
|
||||
page_obj = paginator.get_page(page_number)
|
||||
devices = page_obj.object_list
|
||||
|
||||
context = {
|
||||
"title": "Manage devices",
|
||||
"page_obj": page_obj or None,
|
||||
"elided_page_range": (
|
||||
page_obj.paginator.get_elided_page_range(
|
||||
page_number, on_each_side=1, on_ends=1
|
||||
)
|
||||
if page_obj
|
||||
else None
|
||||
),
|
||||
"data": {
|
||||
"columns": [
|
||||
"Name",
|
||||
"Type",
|
||||
"Created",
|
||||
"Actions",
|
||||
],
|
||||
"rows": [
|
||||
[
|
||||
device.name,
|
||||
device.get_type_display(),
|
||||
device.created_at.strftime(dateformat),
|
||||
render_to_string(
|
||||
"components/button_group_sm.html",
|
||||
{
|
||||
"buttons": [
|
||||
{
|
||||
"href": reverse("edit_device", args=[device.pk]),
|
||||
"text": "Edit",
|
||||
},
|
||||
{
|
||||
"href": reverse("delete_device", args=[device.pk]),
|
||||
"text": "Delete",
|
||||
"color": "red",
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
for device in devices
|
||||
],
|
||||
},
|
||||
}
|
||||
return render(request, "list_purchases.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def edit_device(request: HttpRequest, device_id: int = 0) -> HttpResponse:
|
||||
device = get_object_or_404(Device, id=device_id)
|
||||
form = DeviceForm(request.POST or None, instance=device)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_devices")
|
||||
|
||||
context: dict[str, Any] = {"form": form, "title": "Edit device"}
|
||||
return render(request, "add.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_device(request: HttpRequest, device_id: int) -> HttpResponse:
|
||||
device = get_object_or_404(Device, id=device_id)
|
||||
device.delete()
|
||||
return redirect("list_sessions")
|
||||
|
||||
|
||||
@login_required
|
||||
def add_device(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[str, Any] = {}
|
||||
form = DeviceForm(request.POST or None)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("index")
|
||||
|
||||
context["form"] = form
|
||||
context["title"] = "Add New Device"
|
||||
return render(request, "add.html", context)
|
144
games/views/edition.py
Normal file
144
games/views/edition.py
Normal file
@ -0,0 +1,144 @@
|
||||
from typing import Any
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse
|
||||
|
||||
from common.utils import truncate_with_popover
|
||||
from games.forms import EditionForm
|
||||
from games.models import Edition, Game
|
||||
from games.views.general import dateformat
|
||||
|
||||
|
||||
@login_required
|
||||
def list_editions(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[Any, Any] = {}
|
||||
page_number = request.GET.get("page", 1)
|
||||
limit = request.GET.get("limit", 10)
|
||||
editions = Edition.objects.order_by("-created_at")
|
||||
page_obj = None
|
||||
if int(limit) != 0:
|
||||
paginator = Paginator(editions, limit)
|
||||
page_obj = paginator.get_page(page_number)
|
||||
editions = page_obj.object_list
|
||||
|
||||
context = {
|
||||
"title": "Manage editions",
|
||||
"page_obj": page_obj or None,
|
||||
"elided_page_range": (
|
||||
page_obj.paginator.get_elided_page_range(
|
||||
page_number, on_each_side=1, on_ends=1
|
||||
)
|
||||
if page_obj
|
||||
else None
|
||||
),
|
||||
"data": {
|
||||
"columns": [
|
||||
"Game",
|
||||
"Name",
|
||||
"Sort Name",
|
||||
"Platform",
|
||||
"Year",
|
||||
"Wikidata",
|
||||
"Created",
|
||||
"Actions",
|
||||
],
|
||||
"rows": [
|
||||
[
|
||||
truncate_with_popover(edition.game.name),
|
||||
truncate_with_popover(
|
||||
edition.name
|
||||
if edition.game.name != edition.name
|
||||
else "(identical)"
|
||||
),
|
||||
truncate_with_popover(
|
||||
edition.sort_name
|
||||
if edition.sort_name is not None
|
||||
and edition.game.name != edition.sort_name
|
||||
else "(identical)"
|
||||
),
|
||||
truncate_with_popover(str(edition.platform)),
|
||||
edition.year_released,
|
||||
edition.wikidata,
|
||||
edition.created_at.strftime(dateformat),
|
||||
render_to_string(
|
||||
"components/button_group_sm.html",
|
||||
{
|
||||
"buttons": [
|
||||
{
|
||||
"href": reverse("edit_edition", args=[edition.pk]),
|
||||
"text": "Edit",
|
||||
},
|
||||
{
|
||||
"href": reverse(
|
||||
"delete_edition", args=[edition.pk]
|
||||
),
|
||||
"text": "Delete",
|
||||
"color": "red",
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
for edition in editions
|
||||
],
|
||||
},
|
||||
}
|
||||
return render(request, "list_purchases.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def edit_edition(request: HttpRequest, edition_id: int = 0) -> HttpResponse:
|
||||
edition = get_object_or_404(Edition, id=edition_id)
|
||||
form = EditionForm(request.POST or None, instance=edition)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_editions")
|
||||
|
||||
context: dict[str, Any] = {"form": form, "title": "Edit edition"}
|
||||
return render(request, "add.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_edition(request: HttpRequest, edition_id: int) -> HttpResponse:
|
||||
edition = get_object_or_404(Edition, id=edition_id)
|
||||
edition.delete()
|
||||
return redirect("list_editions")
|
||||
|
||||
|
||||
@login_required
|
||||
def add_edition(request: HttpRequest, game_id: int = 0) -> HttpResponse:
|
||||
context: dict[str, Any] = {}
|
||||
if request.method == "POST":
|
||||
form = EditionForm(request.POST or None)
|
||||
if form.is_valid():
|
||||
edition = form.save()
|
||||
if "submit_and_redirect" in request.POST:
|
||||
return HttpResponseRedirect(
|
||||
reverse(
|
||||
"add_purchase_for_edition", kwargs={"edition_id": edition.id}
|
||||
)
|
||||
)
|
||||
else:
|
||||
return redirect("index")
|
||||
else:
|
||||
if game_id:
|
||||
game = get_object_or_404(Game, id=game_id)
|
||||
form = EditionForm(
|
||||
initial={
|
||||
"game": game,
|
||||
"name": game.name,
|
||||
"sort_name": game.sort_name,
|
||||
"year_released": game.year_released,
|
||||
}
|
||||
)
|
||||
else:
|
||||
form = EditionForm()
|
||||
|
||||
context["form"] = form
|
||||
context["title"] = "Add New Edition"
|
||||
context["script_name"] = "add_edition.js"
|
||||
return render(request, "add_edition.html", context)
|
193
games/views/game.py
Normal file
193
games/views/game.py
Normal file
@ -0,0 +1,193 @@
|
||||
from typing import Any
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse
|
||||
|
||||
from common.time import format_duration
|
||||
from common.utils import safe_division, safe_getattr, truncate_with_popover
|
||||
from games.forms import GameForm
|
||||
from games.models import Game, Purchase, Session
|
||||
from games.views.general import dateformat, use_custom_redirect
|
||||
|
||||
|
||||
@login_required
|
||||
def list_games(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[Any, Any] = {}
|
||||
page_number = request.GET.get("page", 1)
|
||||
limit = request.GET.get("limit", 10)
|
||||
games = Game.objects.order_by("-created_at")
|
||||
page_obj = None
|
||||
if int(limit) != 0:
|
||||
paginator = Paginator(games, limit)
|
||||
page_obj = paginator.get_page(page_number)
|
||||
games = page_obj.object_list
|
||||
|
||||
context = {
|
||||
"title": "Manage games",
|
||||
"page_obj": page_obj or None,
|
||||
"elided_page_range": (
|
||||
page_obj.paginator.get_elided_page_range(
|
||||
page_number, on_each_side=1, on_ends=1
|
||||
)
|
||||
if page_obj
|
||||
else None
|
||||
),
|
||||
"data": {
|
||||
"columns": [
|
||||
"Name",
|
||||
"Sort Name",
|
||||
"Year",
|
||||
"Wikidata",
|
||||
"Created",
|
||||
"Actions",
|
||||
],
|
||||
"rows": [
|
||||
[
|
||||
truncate_with_popover(game.name),
|
||||
truncate_with_popover(
|
||||
game.sort_name
|
||||
if game.sort_name is not None and game.name != game.sort_name
|
||||
else "(identical)"
|
||||
),
|
||||
game.year_released,
|
||||
game.wikidata,
|
||||
game.created_at.strftime(dateformat),
|
||||
render_to_string(
|
||||
"components/button_group_sm.html",
|
||||
{
|
||||
"buttons": [
|
||||
{
|
||||
"href": reverse("edit_game", args=[game.pk]),
|
||||
"text": "Edit",
|
||||
},
|
||||
{
|
||||
"href": reverse("delete_game", args=[game.pk]),
|
||||
"text": "Delete",
|
||||
"color": "red",
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
for game in games
|
||||
],
|
||||
},
|
||||
}
|
||||
return render(request, "list_purchases.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def add_game(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[str, Any] = {}
|
||||
form = GameForm(request.POST or None)
|
||||
if form.is_valid():
|
||||
game = form.save()
|
||||
if "submit_and_redirect" in request.POST:
|
||||
return HttpResponseRedirect(
|
||||
reverse("add_edition_for_game", kwargs={"game_id": game.id})
|
||||
)
|
||||
else:
|
||||
return redirect("list_games")
|
||||
|
||||
context["form"] = form
|
||||
context["title"] = "Add New Game"
|
||||
context["script_name"] = "add_game.js"
|
||||
return render(request, "add_game.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_game(request: HttpRequest, game_id: int) -> HttpResponse:
|
||||
game = get_object_or_404(Game, id=game_id)
|
||||
game.delete()
|
||||
return redirect("list_sessions")
|
||||
|
||||
|
||||
@login_required
|
||||
@use_custom_redirect
|
||||
def edit_game(request: HttpRequest, game_id: int) -> HttpResponse:
|
||||
context = {}
|
||||
purchase = get_object_or_404(Game, id=game_id)
|
||||
form = GameForm(request.POST or None, instance=purchase)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_sessions")
|
||||
context["title"] = "Edit Game"
|
||||
context["form"] = form
|
||||
return render(request, "add.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def view_game(request: HttpRequest, game_id: int) -> HttpResponse:
|
||||
game = Game.objects.get(id=game_id)
|
||||
nongame_related_purchases_prefetch: Prefetch[Purchase] = Prefetch(
|
||||
"related_purchases",
|
||||
queryset=Purchase.objects.exclude(type=Purchase.GAME).order_by(
|
||||
"date_purchased"
|
||||
),
|
||||
to_attr="nongame_related_purchases",
|
||||
)
|
||||
game_purchases_prefetch: Prefetch[Purchase] = Prefetch(
|
||||
"purchase_set",
|
||||
queryset=Purchase.objects.filter(type=Purchase.GAME).prefetch_related(
|
||||
nongame_related_purchases_prefetch
|
||||
),
|
||||
to_attr="game_purchases",
|
||||
)
|
||||
editions = (
|
||||
Edition.objects.filter(game=game)
|
||||
.prefetch_related(game_purchases_prefetch)
|
||||
.order_by("year_released")
|
||||
)
|
||||
|
||||
sessions = Session.objects.prefetch_related("device").filter(
|
||||
purchase__edition__game=game
|
||||
)
|
||||
session_count = sessions.count()
|
||||
session_count_without_manual = (
|
||||
Session.objects.without_manual().filter(purchase__edition__game=game).count()
|
||||
)
|
||||
|
||||
if sessions:
|
||||
playrange_start = sessions.earliest().timestamp_start.strftime("%b %Y")
|
||||
latest_session = sessions.latest()
|
||||
playrange_end = latest_session.timestamp_start.strftime("%b %Y")
|
||||
|
||||
playrange = (
|
||||
playrange_start
|
||||
if playrange_start == playrange_end
|
||||
else f"{playrange_start} — {playrange_end}"
|
||||
)
|
||||
else:
|
||||
playrange = "N/A"
|
||||
latest_session = None
|
||||
|
||||
total_hours = float(format_duration(sessions.total_duration_unformatted(), "%2.1H"))
|
||||
total_hours_without_manual = float(
|
||||
format_duration(sessions.calculated_duration_unformatted(), "%2.1H")
|
||||
)
|
||||
context = {
|
||||
"edition_count": editions.count(),
|
||||
"editions": editions,
|
||||
"game": game,
|
||||
"playrange": playrange,
|
||||
"purchase_count": Purchase.objects.filter(edition__game=game).count(),
|
||||
"session_average_without_manual": round(
|
||||
safe_division(
|
||||
total_hours_without_manual, int(session_count_without_manual)
|
||||
),
|
||||
1,
|
||||
),
|
||||
"session_count": session_count,
|
||||
"sessions_with_notes_count": sessions.exclude(note="").count(),
|
||||
"sessions": sessions.order_by("-timestamp_start"),
|
||||
"title": f"Game Overview - {game.name}",
|
||||
"hours_sum": total_hours,
|
||||
"latest_session_id": safe_getattr(latest_session, "pk"),
|
||||
}
|
||||
|
||||
request.session["return_path"] = request.path
|
||||
return render(request, "view_game.html", context)
|
510
games/views/general.py
Normal file
510
games/views/general.py
Normal file
@ -0,0 +1,510 @@
|
||||
from typing import Any, Callable
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db.models import Avg, Count, ExpressionWrapper, F, Q, Sum, fields
|
||||
from django.db.models.functions import TruncDate, TruncMonth
|
||||
from django.db.models.manager import BaseManager
|
||||
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
|
||||
from django.shortcuts import redirect, render
|
||||
from django.urls import reverse
|
||||
|
||||
from common.time import format_duration
|
||||
from common.utils import safe_division
|
||||
from games.models import Edition, Game, Platform, Purchase, Session
|
||||
|
||||
dateformat: str = "%d/%m/%Y"
|
||||
datetimeformat: str = "%d/%m/%Y %H:%M"
|
||||
timeformat: str = "%H:%M"
|
||||
durationformat: str = "%2.1H hours"
|
||||
durationformat_manual: str = "%H hours"
|
||||
|
||||
|
||||
def model_counts(request: HttpRequest) -> dict[str, bool]:
|
||||
return {
|
||||
"game_available": Game.objects.exists(),
|
||||
"edition_available": Edition.objects.exists(),
|
||||
"platform_available": Platform.objects.exists(),
|
||||
"purchase_available": Purchase.objects.exists(),
|
||||
"session_count": Session.objects.exists(),
|
||||
}
|
||||
|
||||
|
||||
def use_custom_redirect(
|
||||
func: Callable[..., HttpResponse],
|
||||
) -> Callable[..., HttpResponse]:
|
||||
"""
|
||||
Will redirect to "return_path" session variable if set.
|
||||
"""
|
||||
|
||||
def wrapper(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
|
||||
response = func(request, *args, **kwargs)
|
||||
if isinstance(response, HttpResponseRedirect) and (
|
||||
next_url := request.session.get("return_path")
|
||||
):
|
||||
return HttpResponseRedirect(next_url)
|
||||
return response
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
@login_required
|
||||
def stats_alltime(request: HttpRequest) -> HttpResponse:
|
||||
year = "Alltime"
|
||||
this_year_sessions = Session.objects.all().select_related("purchase__edition")
|
||||
this_year_sessions_with_durations = this_year_sessions.annotate(
|
||||
duration=ExpressionWrapper(
|
||||
F("timestamp_end") - F("timestamp_start"),
|
||||
output_field=fields.DurationField(),
|
||||
)
|
||||
)
|
||||
longest_session = this_year_sessions_with_durations.order_by("-duration").first()
|
||||
this_year_games = Game.objects.filter(
|
||||
edition__purchase__session__in=this_year_sessions
|
||||
).distinct()
|
||||
this_year_games_with_session_counts = this_year_games.annotate(
|
||||
session_count=Count("edition__purchase__session"),
|
||||
)
|
||||
game_highest_session_count = this_year_games_with_session_counts.order_by(
|
||||
"-session_count"
|
||||
).first()
|
||||
selected_currency = "CZK"
|
||||
unique_days = (
|
||||
this_year_sessions.annotate(date=TruncDate("timestamp_start"))
|
||||
.values("date")
|
||||
.distinct()
|
||||
.aggregate(dates=Count("date"))
|
||||
)
|
||||
this_year_played_purchases = Purchase.objects.filter(
|
||||
session__in=this_year_sessions
|
||||
).distinct()
|
||||
|
||||
this_year_purchases = Purchase.objects.all()
|
||||
this_year_purchases_with_currency = this_year_purchases.select_related(
|
||||
"edition"
|
||||
).filter(price_currency__exact=selected_currency)
|
||||
this_year_purchases_without_refunded = this_year_purchases_with_currency.filter(
|
||||
date_refunded=None
|
||||
)
|
||||
this_year_purchases_refunded = this_year_purchases_with_currency.refunded()
|
||||
|
||||
this_year_purchases_unfinished_dropped_nondropped = (
|
||||
this_year_purchases_without_refunded.filter(date_finished__isnull=True)
|
||||
.filter(infinite=False)
|
||||
.filter(Q(type=Purchase.GAME) | Q(type=Purchase.DLC))
|
||||
) # do not count battle passes etc.
|
||||
|
||||
this_year_purchases_unfinished = (
|
||||
this_year_purchases_unfinished_dropped_nondropped.filter(
|
||||
date_dropped__isnull=True
|
||||
)
|
||||
)
|
||||
this_year_purchases_dropped = (
|
||||
this_year_purchases_unfinished_dropped_nondropped.filter(
|
||||
date_dropped__isnull=False
|
||||
)
|
||||
)
|
||||
|
||||
this_year_purchases_without_refunded_count = (
|
||||
this_year_purchases_without_refunded.count()
|
||||
)
|
||||
this_year_purchases_unfinished_count = this_year_purchases_unfinished.count()
|
||||
this_year_purchases_unfinished_percent = int(
|
||||
safe_division(
|
||||
this_year_purchases_unfinished_count,
|
||||
this_year_purchases_without_refunded_count,
|
||||
)
|
||||
* 100
|
||||
)
|
||||
|
||||
purchases_finished_this_year: BaseManager[Purchase] = Purchase.objects.finished()
|
||||
purchases_finished_this_year_released_this_year = (
|
||||
purchases_finished_this_year.all().order_by("date_finished")
|
||||
)
|
||||
purchased_this_year_finished_this_year = (
|
||||
this_year_purchases_without_refunded.all()
|
||||
).order_by("date_finished")
|
||||
|
||||
this_year_spendings = this_year_purchases_without_refunded.aggregate(
|
||||
total_spent=Sum(F("price"))
|
||||
)
|
||||
total_spent = this_year_spendings["total_spent"] or 0
|
||||
|
||||
games_with_playtime = (
|
||||
Game.objects.filter(edition__purchase__session__in=this_year_sessions)
|
||||
.annotate(
|
||||
total_playtime=Sum(
|
||||
F("edition__purchase__session__duration_calculated")
|
||||
+ F("edition__purchase__session__duration_manual")
|
||||
)
|
||||
)
|
||||
.values("id", "name", "total_playtime")
|
||||
)
|
||||
month_playtimes = (
|
||||
this_year_sessions.annotate(month=TruncMonth("timestamp_start"))
|
||||
.values("month")
|
||||
.annotate(playtime=Sum("duration_calculated"))
|
||||
.order_by("month")
|
||||
)
|
||||
for month in month_playtimes:
|
||||
month["playtime"] = format_duration(month["playtime"], "%2.0H")
|
||||
|
||||
highest_session_average_game = (
|
||||
Game.objects.filter(edition__purchase__session__in=this_year_sessions)
|
||||
.annotate(
|
||||
session_average=Avg("edition__purchase__session__duration_calculated")
|
||||
)
|
||||
.order_by("-session_average")
|
||||
.first()
|
||||
)
|
||||
top_10_games_by_playtime = games_with_playtime.order_by("-total_playtime")[:10]
|
||||
for game in top_10_games_by_playtime:
|
||||
game["formatted_playtime"] = format_duration(game["total_playtime"], "%2.0H")
|
||||
|
||||
total_playtime_per_platform = (
|
||||
this_year_sessions.values("purchase__platform__name")
|
||||
.annotate(total_playtime=Sum(F("duration_calculated") + F("duration_manual")))
|
||||
.annotate(platform_name=F("purchase__platform__name"))
|
||||
.values("platform_name", "total_playtime")
|
||||
.order_by("-total_playtime")
|
||||
)
|
||||
for item in total_playtime_per_platform:
|
||||
item["formatted_playtime"] = format_duration(item["total_playtime"], "%2.0H")
|
||||
|
||||
backlog_decrease_count = (
|
||||
Purchase.objects.all().intersection(purchases_finished_this_year).count()
|
||||
)
|
||||
|
||||
first_play_date = "N/A"
|
||||
last_play_date = "N/A"
|
||||
if this_year_sessions:
|
||||
first_session = this_year_sessions.earliest()
|
||||
first_play_game = first_session.purchase.edition.game
|
||||
first_play_date = first_session.timestamp_start.strftime("%x")
|
||||
last_session = this_year_sessions.latest()
|
||||
last_play_game = last_session.purchase.edition.game
|
||||
last_play_date = last_session.timestamp_start.strftime("%x")
|
||||
|
||||
all_purchased_this_year_count = this_year_purchases_with_currency.count()
|
||||
all_purchased_refunded_this_year_count: int = this_year_purchases_refunded.count()
|
||||
|
||||
this_year_purchases_dropped_count = this_year_purchases_dropped.count()
|
||||
this_year_purchases_dropped_percentage = int(
|
||||
safe_division(this_year_purchases_dropped_count, all_purchased_this_year_count)
|
||||
* 100
|
||||
)
|
||||
context = {
|
||||
"total_hours": format_duration(
|
||||
this_year_sessions.total_duration_unformatted(), "%2.0H"
|
||||
),
|
||||
"total_2023_games": this_year_played_purchases.all().count(),
|
||||
"top_10_games_by_playtime": top_10_games_by_playtime,
|
||||
"year": year,
|
||||
"total_playtime_per_platform": total_playtime_per_platform,
|
||||
"total_spent": total_spent,
|
||||
"total_spent_currency": selected_currency,
|
||||
"spent_per_game": int(
|
||||
safe_division(total_spent, this_year_purchases_without_refunded_count)
|
||||
),
|
||||
"this_year_finished_this_year_count": purchases_finished_this_year_released_this_year.count(),
|
||||
"total_sessions": this_year_sessions.count(),
|
||||
"unique_days": unique_days["dates"],
|
||||
"unique_days_percent": int(unique_days["dates"] / 365 * 100),
|
||||
"purchased_unfinished_count": this_year_purchases_unfinished_count,
|
||||
"unfinished_purchases_percent": this_year_purchases_unfinished_percent,
|
||||
"dropped_count": this_year_purchases_dropped_count,
|
||||
"dropped_percentage": this_year_purchases_dropped_percentage,
|
||||
"refunded_percent": int(
|
||||
safe_division(
|
||||
all_purchased_refunded_this_year_count,
|
||||
all_purchased_this_year_count,
|
||||
)
|
||||
* 100
|
||||
),
|
||||
"all_purchased_refunded_this_year": this_year_purchases_refunded,
|
||||
"all_purchased_refunded_this_year_count": all_purchased_refunded_this_year_count,
|
||||
"all_purchased_this_year_count": all_purchased_this_year_count,
|
||||
"backlog_decrease_count": backlog_decrease_count,
|
||||
"longest_session_time": (
|
||||
format_duration(longest_session.duration, "%2.0Hh %2.0mm")
|
||||
if longest_session
|
||||
else 0
|
||||
),
|
||||
"longest_session_game": (
|
||||
longest_session.purchase.edition.game if longest_session else None
|
||||
),
|
||||
"highest_session_count": (
|
||||
game_highest_session_count.session_count
|
||||
if game_highest_session_count
|
||||
else 0
|
||||
),
|
||||
"highest_session_count_game": (
|
||||
game_highest_session_count if game_highest_session_count else None
|
||||
),
|
||||
"highest_session_average": (
|
||||
format_duration(
|
||||
highest_session_average_game.session_average, "%2.0Hh %2.0mm"
|
||||
)
|
||||
if highest_session_average_game
|
||||
else 0
|
||||
),
|
||||
"highest_session_average_game": highest_session_average_game,
|
||||
"first_play_game": first_play_game,
|
||||
"first_play_date": first_play_date,
|
||||
"last_play_game": last_play_game,
|
||||
"last_play_date": last_play_date,
|
||||
"title": f"{year} Stats",
|
||||
}
|
||||
|
||||
request.session["return_path"] = request.path
|
||||
return render(request, "stats.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def stats(request: HttpRequest, year: int = 0) -> HttpResponse:
|
||||
selected_year = request.GET.get("year")
|
||||
if selected_year:
|
||||
return HttpResponseRedirect(reverse("stats_by_year", args=[selected_year]))
|
||||
if year == 0:
|
||||
return HttpResponseRedirect(reverse("stats_alltime"))
|
||||
this_year_sessions = Session.objects.filter(
|
||||
timestamp_start__year=year
|
||||
).select_related("purchase__edition")
|
||||
this_year_sessions_with_durations = this_year_sessions.annotate(
|
||||
duration=ExpressionWrapper(
|
||||
F("timestamp_end") - F("timestamp_start"),
|
||||
output_field=fields.DurationField(),
|
||||
)
|
||||
)
|
||||
longest_session = this_year_sessions_with_durations.order_by("-duration").first()
|
||||
this_year_games = Game.objects.filter(
|
||||
edition__purchase__session__in=this_year_sessions
|
||||
).distinct()
|
||||
this_year_games_with_session_counts = this_year_games.annotate(
|
||||
session_count=Count(
|
||||
"edition__purchase__session",
|
||||
filter=Q(edition__purchase__session__timestamp_start__year=year),
|
||||
)
|
||||
)
|
||||
game_highest_session_count = this_year_games_with_session_counts.order_by(
|
||||
"-session_count"
|
||||
).first()
|
||||
selected_currency = "CZK"
|
||||
unique_days = (
|
||||
this_year_sessions.annotate(date=TruncDate("timestamp_start"))
|
||||
.values("date")
|
||||
.distinct()
|
||||
.aggregate(dates=Count("date"))
|
||||
)
|
||||
this_year_played_purchases = Purchase.objects.filter(
|
||||
session__in=this_year_sessions
|
||||
).distinct()
|
||||
|
||||
this_year_purchases = Purchase.objects.filter(date_purchased__year=year)
|
||||
this_year_purchases_with_currency = this_year_purchases.select_related(
|
||||
"edition"
|
||||
).filter(price_currency__exact=selected_currency)
|
||||
this_year_purchases_without_refunded = this_year_purchases_with_currency.filter(
|
||||
date_refunded=None
|
||||
)
|
||||
this_year_purchases_refunded = this_year_purchases_with_currency.refunded()
|
||||
|
||||
this_year_purchases_unfinished_dropped_nondropped = (
|
||||
this_year_purchases_without_refunded.filter(date_finished__isnull=True)
|
||||
.filter(infinite=False)
|
||||
.filter(Q(type=Purchase.GAME) | Q(type=Purchase.DLC))
|
||||
) # do not count battle passes etc.
|
||||
|
||||
this_year_purchases_unfinished = (
|
||||
this_year_purchases_unfinished_dropped_nondropped.filter(
|
||||
date_dropped__isnull=True
|
||||
)
|
||||
)
|
||||
this_year_purchases_dropped = (
|
||||
this_year_purchases_unfinished_dropped_nondropped.filter(
|
||||
date_dropped__isnull=False
|
||||
)
|
||||
)
|
||||
|
||||
this_year_purchases_without_refunded_count = (
|
||||
this_year_purchases_without_refunded.count()
|
||||
)
|
||||
this_year_purchases_unfinished_count = this_year_purchases_unfinished.count()
|
||||
this_year_purchases_unfinished_percent = int(
|
||||
safe_division(
|
||||
this_year_purchases_unfinished_count,
|
||||
this_year_purchases_without_refunded_count,
|
||||
)
|
||||
* 100
|
||||
)
|
||||
|
||||
purchases_finished_this_year = Purchase.objects.filter(date_finished__year=year)
|
||||
purchases_finished_this_year_released_this_year = (
|
||||
purchases_finished_this_year.filter(edition__year_released=year).order_by(
|
||||
"date_finished"
|
||||
)
|
||||
)
|
||||
purchased_this_year_finished_this_year = (
|
||||
this_year_purchases_without_refunded.filter(date_finished__year=year)
|
||||
).order_by("date_finished")
|
||||
|
||||
this_year_spendings = this_year_purchases_without_refunded.aggregate(
|
||||
total_spent=Sum(F("price"))
|
||||
)
|
||||
total_spent = this_year_spendings["total_spent"] or 0
|
||||
|
||||
games_with_playtime = (
|
||||
Game.objects.filter(edition__purchase__session__in=this_year_sessions)
|
||||
.annotate(
|
||||
total_playtime=Sum(
|
||||
F("edition__purchase__session__duration_calculated")
|
||||
+ F("edition__purchase__session__duration_manual")
|
||||
)
|
||||
)
|
||||
.values("id", "name", "total_playtime")
|
||||
)
|
||||
month_playtimes = (
|
||||
this_year_sessions.annotate(month=TruncMonth("timestamp_start"))
|
||||
.values("month")
|
||||
.annotate(playtime=Sum("duration_calculated"))
|
||||
.order_by("month")
|
||||
)
|
||||
for month in month_playtimes:
|
||||
month["playtime"] = format_duration(month["playtime"], "%2.0H")
|
||||
|
||||
highest_session_average_game = (
|
||||
Game.objects.filter(edition__purchase__session__in=this_year_sessions)
|
||||
.annotate(
|
||||
session_average=Avg("edition__purchase__session__duration_calculated")
|
||||
)
|
||||
.order_by("-session_average")
|
||||
.first()
|
||||
)
|
||||
top_10_games_by_playtime = games_with_playtime.order_by("-total_playtime")[:10]
|
||||
for game in top_10_games_by_playtime:
|
||||
game["formatted_playtime"] = format_duration(game["total_playtime"], "%2.0H")
|
||||
|
||||
total_playtime_per_platform = (
|
||||
this_year_sessions.values("purchase__platform__name")
|
||||
.annotate(total_playtime=Sum(F("duration_calculated") + F("duration_manual")))
|
||||
.annotate(platform_name=F("purchase__platform__name"))
|
||||
.values("platform_name", "total_playtime")
|
||||
.order_by("-total_playtime")
|
||||
)
|
||||
for item in total_playtime_per_platform:
|
||||
item["formatted_playtime"] = format_duration(item["total_playtime"], "%2.0H")
|
||||
|
||||
backlog_decrease_count = (
|
||||
Purchase.objects.filter(date_purchased__year__lt=year)
|
||||
.intersection(purchases_finished_this_year)
|
||||
.count()
|
||||
)
|
||||
|
||||
first_play_date = "N/A"
|
||||
last_play_date = "N/A"
|
||||
first_play_game = None
|
||||
last_play_game = None
|
||||
if this_year_sessions:
|
||||
first_session = this_year_sessions.earliest()
|
||||
first_play_game = first_session.purchase.edition.game
|
||||
first_play_date = first_session.timestamp_start.strftime("%x")
|
||||
last_session = this_year_sessions.latest()
|
||||
last_play_game = last_session.purchase.edition.game
|
||||
last_play_date = last_session.timestamp_start.strftime("%x")
|
||||
|
||||
all_purchased_this_year_count = this_year_purchases_with_currency.count()
|
||||
all_purchased_refunded_this_year_count = this_year_purchases_refunded.count()
|
||||
|
||||
this_year_purchases_dropped_count = this_year_purchases_dropped.count()
|
||||
this_year_purchases_dropped_percentage = int(
|
||||
safe_division(this_year_purchases_dropped_count, all_purchased_this_year_count)
|
||||
* 100
|
||||
)
|
||||
context = {
|
||||
"total_hours": format_duration(
|
||||
this_year_sessions.total_duration_unformatted(), "%2.0H"
|
||||
),
|
||||
"total_games": this_year_played_purchases.count(),
|
||||
"total_2023_games": this_year_played_purchases.filter(
|
||||
edition__year_released=year
|
||||
).count(),
|
||||
"top_10_games_by_playtime": top_10_games_by_playtime,
|
||||
"year": year,
|
||||
"total_playtime_per_platform": total_playtime_per_platform,
|
||||
"total_spent": total_spent,
|
||||
"total_spent_currency": selected_currency,
|
||||
"all_purchased_this_year": this_year_purchases_without_refunded,
|
||||
"spent_per_game": int(
|
||||
safe_division(total_spent, this_year_purchases_without_refunded_count)
|
||||
),
|
||||
"all_finished_this_year": purchases_finished_this_year.select_related(
|
||||
"edition"
|
||||
).order_by("date_finished"),
|
||||
"all_finished_this_year_count": purchases_finished_this_year.count(),
|
||||
"this_year_finished_this_year": purchases_finished_this_year_released_this_year.select_related(
|
||||
"edition"
|
||||
).order_by("date_finished"),
|
||||
"this_year_finished_this_year_count": purchases_finished_this_year_released_this_year.count(),
|
||||
"purchased_this_year_finished_this_year": purchased_this_year_finished_this_year.select_related(
|
||||
"edition"
|
||||
).order_by("date_finished"),
|
||||
"total_sessions": this_year_sessions.count(),
|
||||
"unique_days": unique_days["dates"],
|
||||
"unique_days_percent": int(unique_days["dates"] / 365 * 100),
|
||||
"purchased_unfinished": this_year_purchases_unfinished,
|
||||
"purchased_unfinished_count": this_year_purchases_unfinished_count,
|
||||
"unfinished_purchases_percent": this_year_purchases_unfinished_percent,
|
||||
"dropped_count": this_year_purchases_dropped_count,
|
||||
"dropped_percentage": this_year_purchases_dropped_percentage,
|
||||
"refunded_percent": int(
|
||||
safe_division(
|
||||
all_purchased_refunded_this_year_count,
|
||||
all_purchased_this_year_count,
|
||||
)
|
||||
* 100
|
||||
),
|
||||
"all_purchased_refunded_this_year": this_year_purchases_refunded,
|
||||
"all_purchased_refunded_this_year_count": all_purchased_refunded_this_year_count,
|
||||
"all_purchased_this_year": this_year_purchases_with_currency.order_by(
|
||||
"date_purchased"
|
||||
),
|
||||
"all_purchased_this_year_count": all_purchased_this_year_count,
|
||||
"backlog_decrease_count": backlog_decrease_count,
|
||||
"longest_session_time": (
|
||||
format_duration(longest_session.duration, "%2.0Hh %2.0mm")
|
||||
if longest_session
|
||||
else 0
|
||||
),
|
||||
"longest_session_game": (
|
||||
longest_session.purchase.edition.game if longest_session else None
|
||||
),
|
||||
"highest_session_count": (
|
||||
game_highest_session_count.session_count
|
||||
if game_highest_session_count
|
||||
else 0
|
||||
),
|
||||
"highest_session_count_game": (
|
||||
game_highest_session_count if game_highest_session_count else None
|
||||
),
|
||||
"highest_session_average": (
|
||||
format_duration(
|
||||
highest_session_average_game.session_average, "%2.0Hh %2.0mm"
|
||||
)
|
||||
if highest_session_average_game
|
||||
else 0
|
||||
),
|
||||
"highest_session_average_game": highest_session_average_game,
|
||||
"first_play_game": first_play_game,
|
||||
"first_play_date": first_play_date,
|
||||
"last_play_game": last_play_game,
|
||||
"last_play_date": last_play_date,
|
||||
"title": f"{year} Stats",
|
||||
"month_playtimes": month_playtimes,
|
||||
}
|
||||
|
||||
request.session["return_path"] = request.path
|
||||
return render(request, "stats.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def index(request: HttpRequest) -> HttpResponse:
|
||||
return redirect("list_sessions")
|
108
games/views/platform.py
Normal file
108
games/views/platform.py
Normal file
@ -0,0 +1,108 @@
|
||||
from typing import Any
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse
|
||||
|
||||
from games.forms import PlatformForm
|
||||
from games.models import Platform
|
||||
from games.views.general import dateformat, use_custom_redirect
|
||||
|
||||
|
||||
@login_required
|
||||
def list_platforms(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[Any, Any] = {}
|
||||
page_number = request.GET.get("page", 1)
|
||||
limit = request.GET.get("limit", 10)
|
||||
platforms = Platform.objects.order_by("-created_at")
|
||||
page_obj = None
|
||||
if int(limit) != 0:
|
||||
paginator = Paginator(platforms, limit)
|
||||
page_obj = paginator.get_page(page_number)
|
||||
platforms = page_obj.object_list
|
||||
|
||||
context = {
|
||||
"title": "Manage platforms",
|
||||
"page_obj": page_obj or None,
|
||||
"elided_page_range": (
|
||||
page_obj.paginator.get_elided_page_range(
|
||||
page_number, on_each_side=1, on_ends=1
|
||||
)
|
||||
if page_obj
|
||||
else None
|
||||
),
|
||||
"data": {
|
||||
"columns": [
|
||||
"Name",
|
||||
"Group",
|
||||
"Created",
|
||||
"Actions",
|
||||
],
|
||||
"rows": [
|
||||
[
|
||||
platform.name,
|
||||
platform.group,
|
||||
platform.created_at.strftime(dateformat),
|
||||
render_to_string(
|
||||
"components/button_group_sm.html",
|
||||
{
|
||||
"buttons": [
|
||||
{
|
||||
"href": reverse(
|
||||
"edit_platform", args=[platform.pk]
|
||||
),
|
||||
"text": "Edit",
|
||||
},
|
||||
{
|
||||
"href": reverse(
|
||||
"delete_platform", args=[platform.pk]
|
||||
),
|
||||
"text": "Delete",
|
||||
"color": "red",
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
for platform in platforms
|
||||
],
|
||||
},
|
||||
}
|
||||
return render(request, "list_purchases.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_platform(request: HttpRequest, platform_id: int) -> HttpResponse:
|
||||
platform = get_object_or_404(Platform, id=platform_id)
|
||||
platform.delete()
|
||||
return redirect("list_platforms")
|
||||
|
||||
|
||||
@login_required
|
||||
@use_custom_redirect
|
||||
def edit_platform(request: HttpRequest, platform_id: int) -> HttpResponse:
|
||||
context = {}
|
||||
platform = get_object_or_404(Platform, id=platform_id)
|
||||
form = PlatformForm(request.POST or None, instance=platform)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_platforms")
|
||||
context["title"] = "Edit Platform"
|
||||
context["form"] = form
|
||||
return render(request, "add.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def add_platform(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[str, Any] = {}
|
||||
form = PlatformForm(request.POST or None)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("index")
|
||||
|
||||
context["form"] = form
|
||||
context["title"] = "Add New Platform"
|
||||
return render(request, "add.html", context)
|
177
games/views/purchase.py
Normal file
177
games/views/purchase.py
Normal file
@ -0,0 +1,177 @@
|
||||
from typing import Any
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import (
|
||||
HttpRequest,
|
||||
HttpResponse,
|
||||
HttpResponseBadRequest,
|
||||
HttpResponseRedirect,
|
||||
)
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from common.utils import truncate_with_popover
|
||||
from games.forms import PurchaseForm
|
||||
from games.models import Edition, Purchase
|
||||
from games.views.general import dateformat, use_custom_redirect
|
||||
|
||||
|
||||
@login_required
|
||||
def list_purchases(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[Any, Any] = {}
|
||||
page_number = request.GET.get("page", 1)
|
||||
limit = request.GET.get("limit", 10)
|
||||
purchases = Purchase.objects.order_by("-date_purchased")
|
||||
page_obj = None
|
||||
if int(limit) != 0:
|
||||
paginator = Paginator(purchases, limit)
|
||||
page_obj = paginator.get_page(page_number)
|
||||
purchases = page_obj.object_list
|
||||
|
||||
context = {
|
||||
"title": "Manage purchases",
|
||||
"page_obj": page_obj or None,
|
||||
"elided_page_range": (
|
||||
page_obj.paginator.get_elided_page_range(
|
||||
page_number, on_each_side=1, on_ends=1
|
||||
)
|
||||
if page_obj
|
||||
else None
|
||||
),
|
||||
"data": {
|
||||
"columns": [
|
||||
"Name",
|
||||
"Platform",
|
||||
"Price",
|
||||
"Currency",
|
||||
"Infinite",
|
||||
"Purchased",
|
||||
"Refunded",
|
||||
"Finished",
|
||||
"Dropped",
|
||||
"Created",
|
||||
"Actions",
|
||||
],
|
||||
"rows": [
|
||||
[
|
||||
truncate_with_popover(purchase.edition.name),
|
||||
purchase.platform,
|
||||
purchase.price,
|
||||
purchase.price_currency,
|
||||
purchase.infinite,
|
||||
purchase.date_purchased.strftime(dateformat),
|
||||
(
|
||||
purchase.date_refunded.strftime(dateformat)
|
||||
if purchase.date_refunded
|
||||
else "-"
|
||||
),
|
||||
(
|
||||
purchase.date_finished.strftime(dateformat)
|
||||
if purchase.date_finished
|
||||
else "-"
|
||||
),
|
||||
(
|
||||
purchase.date_dropped.strftime(dateformat)
|
||||
if purchase.date_dropped
|
||||
else "-"
|
||||
),
|
||||
purchase.created_at.strftime(dateformat),
|
||||
render_to_string(
|
||||
"components/button_group_sm.html",
|
||||
{
|
||||
"buttons": [
|
||||
{
|
||||
"href": reverse(
|
||||
"edit_purchase", args=[purchase.pk]
|
||||
),
|
||||
"text": "Edit",
|
||||
},
|
||||
{
|
||||
"href": reverse(
|
||||
"delete_purchase", args=[purchase.pk]
|
||||
),
|
||||
"text": "Delete",
|
||||
"color": "red",
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
for purchase in purchases
|
||||
],
|
||||
},
|
||||
}
|
||||
return render(request, "list_purchases.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def add_purchase(request: HttpRequest, edition_id: int = 0) -> HttpResponse:
|
||||
context: dict[str, Any] = {}
|
||||
initial = {"date_purchased": timezone.now()}
|
||||
|
||||
if request.method == "POST":
|
||||
form = PurchaseForm(request.POST or None, initial=initial)
|
||||
if form.is_valid():
|
||||
purchase = form.save()
|
||||
if "submit_and_redirect" in request.POST:
|
||||
return HttpResponseRedirect(
|
||||
reverse(
|
||||
"add_session_for_purchase", kwargs={"purchase_id": purchase.id}
|
||||
)
|
||||
)
|
||||
else:
|
||||
return redirect("list_purchases")
|
||||
else:
|
||||
if edition_id:
|
||||
edition = Edition.objects.get(id=edition_id)
|
||||
form = PurchaseForm(
|
||||
initial={
|
||||
**initial,
|
||||
"edition": edition,
|
||||
"platform": edition.platform,
|
||||
}
|
||||
)
|
||||
else:
|
||||
form = PurchaseForm(initial=initial)
|
||||
|
||||
context["form"] = form
|
||||
context["title"] = "Add New Purchase"
|
||||
context["script_name"] = "add_purchase.js"
|
||||
return render(request, "add_purchase.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
@use_custom_redirect
|
||||
def edit_purchase(request: HttpRequest, purchase_id: int) -> HttpResponse:
|
||||
context = {}
|
||||
purchase = get_object_or_404(Purchase, id=purchase_id)
|
||||
form = PurchaseForm(request.POST or None, instance=purchase)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_sessions")
|
||||
context["title"] = "Edit Purchase"
|
||||
context["form"] = form
|
||||
context["purchase_id"] = str(purchase_id)
|
||||
context["script_name"] = "add_purchase.js"
|
||||
return render(request, "add_purchase.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_purchase(request: HttpRequest, purchase_id: int) -> HttpResponse:
|
||||
purchase = get_object_or_404(Purchase, id=purchase_id)
|
||||
purchase.delete()
|
||||
return redirect("list_sessions")
|
||||
|
||||
|
||||
def related_purchase_by_edition(request: HttpRequest) -> HttpResponse:
|
||||
edition_id = request.GET.get("edition")
|
||||
if not edition_id:
|
||||
return HttpResponseBadRequest("Invalid edition_id")
|
||||
form = PurchaseForm()
|
||||
form.fields["related_purchase"].queryset = Purchase.objects.filter(
|
||||
edition_id=edition_id, type=Purchase.GAME
|
||||
).order_by("edition__sort_name")
|
||||
return render(request, "partials/related_purchase_field.html", {"form": form})
|
191
games/views/session.py
Normal file
191
games/views/session.py
Normal file
@ -0,0 +1,191 @@
|
||||
from typing import Any
|
||||
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.paginator import Paginator
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.template.loader import render_to_string
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from common.time import format_duration
|
||||
from common.utils import truncate_with_popover
|
||||
from games.forms import SessionForm
|
||||
from games.models import Purchase, Session
|
||||
from games.views.general import (
|
||||
dateformat,
|
||||
datetimeformat,
|
||||
durationformat,
|
||||
durationformat_manual,
|
||||
timeformat,
|
||||
use_custom_redirect,
|
||||
)
|
||||
|
||||
|
||||
@login_required
|
||||
def list_sessions(request: HttpRequest) -> HttpResponse:
|
||||
context: dict[Any, Any] = {}
|
||||
page_number = request.GET.get("page", 1)
|
||||
limit = request.GET.get("limit", 10)
|
||||
sessions = Session.objects.order_by("-timestamp_start")
|
||||
page_obj = None
|
||||
if int(limit) != 0:
|
||||
paginator = Paginator(sessions, limit)
|
||||
page_obj = paginator.get_page(page_number)
|
||||
sessions = page_obj.object_list
|
||||
|
||||
context = {
|
||||
"title": "Manage sessions",
|
||||
"page_obj": page_obj or None,
|
||||
"elided_page_range": (
|
||||
page_obj.paginator.get_elided_page_range(
|
||||
page_number, on_each_side=1, on_ends=1
|
||||
)
|
||||
if page_obj
|
||||
else None
|
||||
),
|
||||
"data": {
|
||||
"columns": [
|
||||
"Name",
|
||||
"Date",
|
||||
"Duration",
|
||||
"Duration (manual)",
|
||||
"Device",
|
||||
"Created",
|
||||
"Actions",
|
||||
],
|
||||
"rows": [
|
||||
[
|
||||
truncate_with_popover(session.purchase.edition.name),
|
||||
f"{session.timestamp_start.strftime(datetimeformat)}{f" — {session.timestamp_end.strftime(timeformat)}" if session.timestamp_end else ""}",
|
||||
(
|
||||
format_duration(session.duration_calculated, durationformat)
|
||||
if session.duration_calculated
|
||||
else "-"
|
||||
),
|
||||
(
|
||||
format_duration(session.duration_manual, durationformat_manual)
|
||||
if session.duration_manual
|
||||
else "-"
|
||||
),
|
||||
session.device,
|
||||
session.created_at.strftime(dateformat),
|
||||
render_to_string(
|
||||
"components/button_group_sm.html",
|
||||
{
|
||||
"buttons": [
|
||||
{
|
||||
"href": reverse("edit_session", args=[session.pk]),
|
||||
"text": "Edit",
|
||||
},
|
||||
{
|
||||
"href": reverse(
|
||||
"delete_session", args=[session.pk]
|
||||
),
|
||||
"text": "Delete",
|
||||
"color": "red",
|
||||
},
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
for session in sessions
|
||||
],
|
||||
},
|
||||
}
|
||||
return render(request, "list_purchases.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
def add_session(request: HttpRequest, purchase_id: int = 0) -> HttpResponse:
|
||||
context = {}
|
||||
initial: dict[str, Any] = {"timestamp_start": timezone.now()}
|
||||
|
||||
last = Session.objects.last()
|
||||
if last != None:
|
||||
initial["purchase"] = last.purchase
|
||||
|
||||
if request.method == "POST":
|
||||
form = SessionForm(request.POST or None, initial=initial)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_sessions")
|
||||
else:
|
||||
if purchase_id:
|
||||
purchase = Purchase.objects.get(id=purchase_id)
|
||||
form = SessionForm(
|
||||
initial={
|
||||
**initial,
|
||||
"purchase": purchase,
|
||||
}
|
||||
)
|
||||
else:
|
||||
form = SessionForm(initial=initial)
|
||||
|
||||
context["title"] = "Add New Session"
|
||||
context["form"] = form
|
||||
return render(request, "add_session.html", context)
|
||||
|
||||
|
||||
@login_required
|
||||
@use_custom_redirect
|
||||
def edit_session(request: HttpRequest, session_id: int) -> HttpResponse:
|
||||
context = {}
|
||||
session = get_object_or_404(Session, id=session_id)
|
||||
form = SessionForm(request.POST or None, instance=session)
|
||||
if form.is_valid():
|
||||
form.save()
|
||||
return redirect("list_sessions")
|
||||
context["title"] = "Edit Session"
|
||||
context["form"] = form
|
||||
return render(request, "add_session.html", context)
|
||||
|
||||
|
||||
def clone_session_by_id(session_id: int) -> Session:
|
||||
session = get_object_or_404(Session, id=session_id)
|
||||
clone = session
|
||||
clone.pk = None
|
||||
clone.timestamp_start = timezone.now()
|
||||
clone.timestamp_end = None
|
||||
clone.note = ""
|
||||
clone.save()
|
||||
return clone
|
||||
|
||||
|
||||
@login_required
|
||||
@use_custom_redirect
|
||||
def new_session_from_existing_session(
|
||||
request: HttpRequest, session_id: int, template: str = ""
|
||||
) -> HttpResponse:
|
||||
session = clone_session_by_id(session_id)
|
||||
if request.htmx:
|
||||
context = {
|
||||
"session": session,
|
||||
"session_count": int(request.GET.get("session_count", 0)) + 1,
|
||||
}
|
||||
return render(request, template, context)
|
||||
return redirect("list_sessions")
|
||||
|
||||
|
||||
@login_required
|
||||
@use_custom_redirect
|
||||
def end_session(
|
||||
request: HttpRequest, session_id: int, template: str = ""
|
||||
) -> HttpResponse:
|
||||
session = get_object_or_404(Session, id=session_id)
|
||||
session.timestamp_end = timezone.now()
|
||||
session.save()
|
||||
if request.htmx:
|
||||
context = {
|
||||
"session": session,
|
||||
"session_count": request.GET.get("session_count", 0),
|
||||
}
|
||||
return render(request, template, context)
|
||||
return redirect("list_sessions")
|
||||
|
||||
|
||||
@login_required
|
||||
def delete_session(request: HttpRequest, session_id: int = 0) -> HttpResponse:
|
||||
session = get_object_or_404(Session, id=session_id)
|
||||
session.delete()
|
||||
return redirect("list_sessions")
|
Reference in New Issue
Block a user