autoilux/main/views.py

106 lines
3.5 KiB
Python

from calendar import monthrange
from collections import defaultdict
from datetime import date, timedelta
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Avg, Max, Min, Sum
from django.utils import timezone
from django.views.generic import CreateView, ListView, TemplateView
from .forms import FuelPurchaseForm
from .models import FuelPurchase, MonthlyTrip
class FuelPurchaseMonthlyListView(ListView):
model = FuelPurchase
template_name = "fuelpurchase_list.html"
context_object_name = "purchases"
def get_queryset(self):
year = int(self.kwargs.get("year", timezone.now().year))
month = int(self.kwargs.get("month", timezone.now().month))
self.current_year = year
self.current_month = month
# Haetaan MonthlyTrip heti
self.monthly_trip = MonthlyTrip.objects.filter(year=year, month=month).first()
if not self.monthly_trip:
# Jos ei ole olemassa, ei ole ostoksiakaan
return FuelPurchase.objects.none()
return (
FuelPurchase.objects
.filter(monthly_trip=self.monthly_trip)
.select_related("monthly_trip")
.order_by("-purchase_date")
)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
qs = self.object_list
summary = qs.aggregate(
total_cost_sum=Sum("total_cost"),
total_litres_sum=Sum("amount_litres"),
avg_price=Avg("price_per_litre"),
min_price=Min("price_per_litre"),
max_price=Max("price_per_litre"),
)
context["summary"] = summary
context["current_year"] = self.current_year
context["current_month"] = self.current_month
context["month_kilometers"] = self.monthly_trip.kilometers if self.monthly_trip else 0
# Kuukausinavigointi
current_date = date(self.current_year, self.current_month, 1)
prev_month = current_date - timedelta(days=1)
next_month = (current_date.replace(day=28) + timedelta(days=4)).replace(day=1)
context["prev_year"] = prev_month.year
context["prev_month"] = prev_month.month
context["next_year"] = next_month.year
context["next_month"] = next_month.month
# Kaikki kuukaudet alasvetovalikkoon
context["available_months"] = FuelPurchase.objects.dates(
"purchase_date", "month", order="DESC"
)
return context
class FuelPurchaseCreateView(LoginRequiredMixin, CreateView):
model = FuelPurchase
form_class = FuelPurchaseForm
template_name = "fuelpurchase_add.html"
success_url = "/"
class MonthlyTripView(TemplateView):
template_name = 'main/monthly_trips.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
all_distances = MonthlyTrip.objects.all().order_by('year', 'month')
years = sorted(set(d.year for d in all_distances))
table_data = defaultdict(dict)
year_totals = defaultdict(int)
for entry in all_distances:
table_data[entry.month][entry.year] = entry.kilometers
year_totals[entry.year] += entry.kilometers
month_names = dict(MonthlyTrip.MONTH_CHOICES)
context.update({
'years': years,
'table_data': table_data,
'month_names': month_names,
'year_totals': year_totals,
})
return context