Skip to content

Commit

Permalink
refine
Browse files Browse the repository at this point in the history
  • Loading branch information
SamDudley committed Nov 29, 2024
1 parent 2714b0a commit e3bb37e
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 74 deletions.
1 change: 0 additions & 1 deletion config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,6 @@ def FILTERS_VERBOSE_LOOKUPS():
"core.no_cache_middleware.NoCacheMiddleware",
"simple_history.middleware.HistoryRequestMiddleware",
"axes.middleware.AxesMiddleware",
"core.middleware.DatabaseQueriesMiddleware",
"core.middleware.CoreRequestDataMiddleware",
]

Expand Down
35 changes: 2 additions & 33 deletions core/middleware.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,13 @@
from contextvars import ContextVar
from pprint import pprint

import sentry_sdk
from django.db import connection


class DatabaseQueriesMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
pre_query_count = len(connection.queries)

response = self.get_response(request)

post_query_count = len(connection.queries)
query_count = post_query_count - pre_query_count
pprint(connection.queries)
print(f"Database queries {query_count}")

# https://docs.sentry.io/platforms/python/performance/instrumentation/custom-instrumentation/#accessing-the-current-transaction
transaction = sentry_sdk.Hub.current.scope.transaction

if transaction is not None:
transaction.set_tag("database.query_count", query_count)

return response


_current_financial_year = ContextVar("current_financial_year", default=None)
from core.utils.generic_helpers import get_current_financial_year


class CoreRequestDataMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
request.current_financial_year = get_current_financial_year()

response = self.get_response(request)

_current_financial_year.set(None)

return response
7 changes: 0 additions & 7 deletions core/utils/generic_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,10 @@
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.contenttypes.models import ContentType

from core.middleware import _current_financial_year
from core.models import FinancialYear


def get_current_financial_year():
# FIXME: decide if to include this
if var := _current_financial_year.get():
return var

y = FinancialYear.objects.filter(current=True)
if y:
current_financial_year = y.last().financial_year
Expand All @@ -32,8 +27,6 @@ def get_current_financial_year():
# calendar year
current_financial_year -= 1

_current_financial_year.set(current_financial_year)

return current_financial_year


Expand Down
27 changes: 2 additions & 25 deletions forecast/serialisers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from django.db.models import Sum
from rest_framework import serializers

from .models import BudgetMonthlyFigure, FinancialCode, ForecastMonthlyFigure
from .models import FinancialCode, ForecastMonthlyFigure


class ForecastMonthlyFigureSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -29,7 +28,7 @@ def get_actual(self, obj):


class FinancialCodeSerializer(serializers.ModelSerializer):
budget = serializers.SerializerMethodField("get_budget")
budget = serializers.IntegerField(source="yearly_budget_amount")
monthly_figures = ForecastMonthlyFigureSerializer(
many=True,
read_only=True,
Expand Down Expand Up @@ -63,25 +62,3 @@ def get_programme_description(self, obj):

def get_nac_description(self, obj):
return obj.natural_account_code.natural_account_code_description

def get_budget(self, obj):
return obj.yearly_budget_amount
# FIXME: 400+ queries! try this as a prefetch similar to forecast or change to a lookup
financial_year = self.context["financial_year"]
budget = (
BudgetMonthlyFigure.objects.values(
"financial_code",
"financial_year",
)
.filter(
financial_code=obj.id,
financial_year_id=financial_year,
archived_status=None,
)
.annotate(yearly_amount=Sum("amount"))
)

if budget and "yearly_amount" in budget[0]:
return budget[0]["yearly_amount"]
else:
return 0
25 changes: 17 additions & 8 deletions forecast/views/edit_forecast.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,14 @@ def get_financial_codes_for_year(cost_centre_code, financial_year):
)


def get_financial_code_serialiser(cost_centre_code, financial_year):
def get_financial_code_serialiser(
cost_centre_code: str,
financial_year: FinancialYear,
current_financial_year: FinancialYear | None,
) -> FinancialCodeSerializer:
if current_financial_year is None:
current_financial_year = get_current_financial_year()

# Only selects the financial codes relevant to the financial year being edited.
# Financial codes are used in budgets and forecast/actuals.
forecasts = ForecastMonthlyFigure.objects.select_related("financial_period").filter(
Expand All @@ -97,8 +104,6 @@ def get_financial_code_serialiser(cost_centre_code, financial_year):
queryset=forecasts,
to_attr="monthly_figure_items",
),
# FIXME: check this isn't needed
# "forecast_forecastmonthlyfigures__financial_period",
)
.annotate(
yearly_budget_amount=Sum(
Expand All @@ -117,7 +122,7 @@ def get_financial_code_serialiser(cost_centre_code, financial_year):
many=True,
context={
"financial_year": financial_year,
"current_financial_year": get_current_financial_year(),
"current_financial_year": current_financial_year,
},
)
return financial_code_serialiser
Expand Down Expand Up @@ -338,6 +343,7 @@ def form_valid(self, form): # noqa: C901
financial_code_serialiser = get_financial_code_serialiser(
self.cost_centre_code,
self.financial_year,
self.request.current_financial_year,
)

return JsonResponse(
Expand Down Expand Up @@ -446,7 +452,9 @@ def form_valid(self, form):
monthly_figure.save()

financial_code_serialiser = get_financial_code_serialiser(
self.cost_centre_code, self.financial_year
self.cost_centre_code,
self.financial_year,
self.request.current_financial_year,
)

return JsonResponse(financial_code_serialiser.data, safe=False)
Expand All @@ -471,7 +479,6 @@ class EditForecastView(
def class_name(self):
return "wide-table"

# FIXME: Triple check this is safe
@cached_property
def cost_centre_details(self):
cost_centre = CostCentre.objects.select_related("directorate__group").get(
Expand All @@ -497,10 +504,12 @@ def get_context_data(self, **kwargs):
financial_code_serialiser = get_financial_code_serialiser(
self.cost_centre_code,
self.financial_year,
self.request.current_financial_year,
)
serialiser_data = financial_code_serialiser.data
forecast_dump = json.dumps(serialiser_data)
if self.financial_year == get_current_financial_year():

if self.financial_year == self.request.current_financial_year:
self.title = "Edit forecast"
actual_data = (
FinancialPeriod.financial_period_info.actual_period_code_list()
Expand Down Expand Up @@ -535,7 +544,7 @@ def get_payroll_forecast_report(self):
@cached_property
def future_year_display(self):
if self._future_year_display is None:
current_year = get_current_financial_year()
current_year = self.request.current_financial_year
if self.financial_year > current_year:
self._future_year_display = get_year_display(self.financial_year)
else:
Expand Down

0 comments on commit e3bb37e

Please sign in to comment.