factorising BalanceStat views

This commit is contained in:
Qwann 2017-01-24 16:54:02 +01:00
parent 947de3b638
commit df2a9bb1b3
2 changed files with 59 additions and 71 deletions

View file

@ -81,20 +81,11 @@ urlpatterns = [
url('^accounts/(?P<trigramme>.{3})/stat/balance/$', url('^accounts/(?P<trigramme>.{3})/stat/balance/$',
views.AccountStatBalanceAll.as_view(), views.AccountStatBalanceAll.as_view(),
name = 'kfet.account.stat.balance'), name = 'kfet.account.stat.balance'),
url('^accounts/(?P<trigramme>.{3})/stat/balance/month/$', url('^accounts/(?P<trigramme>.{3})/stat/balance/d/(?P<nb_date>\d*)/$',
views.AccountStatBalanceMonth.as_view(), views.AccountStatBalance.as_view(),
name = 'kfet.account.stat.balance.month'), name = 'kfet.account.stat.balance.days'),
url('^accounts/(?P<trigramme>.{3})/stat/balance/treemonths/$',
views.AccountStatBalanceThreeMonths.as_view(),
name = 'kfet.account.stat.balance.treemonths'),
url('^accounts/(?P<trigramme>.{3})/stat/balance/sixmonths/$',
views.AccountStatBalanceSixMonths.as_view(),
name = 'kfet.account.stat.balance.sixmonths'),
url('^accounts/(?P<trigramme>.{3})/stat/balance/year/$',
views.AccountStatBalanceYear.as_view(),
name = 'kfet.account.stat.balance.year'),
url('^accounts/(?P<trigramme>.{3})/stat/balance/anytime/$', url('^accounts/(?P<trigramme>.{3})/stat/balance/anytime/$',
views.AccountStatBalanceAnytime.as_view(), views.AccountStatBalance.as_view(),
name = 'kfet.account.stat.balance.anytime'), name = 'kfet.account.stat.balance.anytime'),
# ----- # -----

View file

@ -2039,9 +2039,13 @@ class ObjectResumeStat(DetailView):
def get_object_url_kwargs(self, **kwargs): def get_object_url_kwargs(self, **kwargs):
return {'pk': self.object.id} return {'pk': self.object.id}
def url_kwargs(self, **kwargs):
return [{}] * self.nb_stat
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# On hérite pas # On hérite pas
object_id = self.object.id object_id = self.object.id
url_kwargs = self.url_kwargs()
context = {} context = {}
stats = {} stats = {}
for i in range(self.nb_stat): for i in range(self.nb_stat):
@ -2051,7 +2055,11 @@ class ObjectResumeStat(DetailView):
object_id, object_id,
i), i),
'url': reverse_lazy(self.stat_urls[i], 'url': reverse_lazy(self.stat_urls[i],
kwargs=self.get_object_url_kwargs()), kwargs=dict(
self.get_object_url_kwargs(),
**url_kwargs[i]
),
),
} }
prefix = "%s_%d" % (self.id_prefix, object_id) prefix = "%s_%d" % (self.id_prefix, object_id)
context['id_prefix'] = prefix context['id_prefix'] = prefix
@ -2066,11 +2074,11 @@ class ObjectResumeStat(DetailView):
# Evolution Balance perso # Evolution Balance perso
# ----------------------- # -----------------------
ID_PREFIX_ACC_BALANCE = "balance_acc" ID_PREFIX_ACC_BALANCE = "balance_acc"
ID_PREFIX_ACC_BALANCE_MONTH = "balance_month_acc" # ID_PREFIX_ACC_BALANCE_MONTH = "balance_month_acc"
ID_PREFIX_ACC_BALANCE_THREE_MONTHS = "balance_three_months_acc" # ID_PREFIX_ACC_BALANCE_THREE_MONTHS = "balance_three_months_acc"
ID_PREFIX_ACC_BALANCE_SIX_MONTHS = "balance_six_months_acc" # ID_PREFIX_ACC_BALANCE_SIX_MONTHS = "balance_six_months_acc"
ID_PREFIX_ACC_BALANCE_YEAR = "balance_year_acc" # ID_PREFIX_ACC_BALANCE_YEAR = "balance_year_acc"
ID_PREFIX_ACC_BALANCE_ANYTIME = "balance_anytime_acc" # ID_PREFIX_ACC_BALANCE_ANYTIME = "balance_anytime_acc"
# Un résumé de toutes les vues ArticleStatBalance # Un résumé de toutes les vues ArticleStatBalance
@ -2081,13 +2089,10 @@ class AccountStatBalanceAll(ObjectResumeStat):
trigramme_url_kwarg = 'trigramme' trigramme_url_kwarg = 'trigramme'
id_prefix = ID_PREFIX_ACC_BALANCE id_prefix = ID_PREFIX_ACC_BALANCE
nb_stat = 5 nb_stat = 5
nb_default = 4 nb_default = 0
stat_labels = ["Tout le temps", "1 an", "6 mois", "3 mois", "30 jours"] stat_labels = ["Tout le temps", "1 an", "6 mois", "3 mois", "30 jours"]
stat_urls = ['kfet.account.stat.balance.anytime', stat_urls = ['kfet.account.stat.balance.anytime'] \
'kfet.account.stat.balance.year', + ['kfet.account.stat.balance.days'] * 4
'kfet.account.stat.balance.sixmonths',
'kfet.account.stat.balance.treemonths',
'kfet.account.stat.balance.month']
def get_object(self, **kwargs): def get_object(self, **kwargs):
trigramme = self.kwargs.get(self.trigramme_url_kwarg) trigramme = self.kwargs.get(self.trigramme_url_kwarg)
@ -2096,6 +2101,15 @@ class AccountStatBalanceAll(ObjectResumeStat):
def get_object_url_kwargs(self, **kwargs): def get_object_url_kwargs(self, **kwargs):
return {'trigramme': self.object.trigramme} return {'trigramme': self.object.trigramme}
def url_kwargs(self, **kwargs):
context_list = (super(AccountStatBalanceAll, self)
.url_kwargs(**kwargs))
context_list[1] = {'nb_date': 365}
context_list[2] = {'nb_date': 183}
context_list[3] = {'nb_date': 90}
context_list[4] = {'nb_date': 30}
return context_list
@method_decorator(login_required) @method_decorator(login_required)
def dispatch(self, *args, **kwargs): def dispatch(self, *args, **kwargs):
return super(AccountStatBalanceAll, self).dispatch(*args, **kwargs) return super(AccountStatBalanceAll, self).dispatch(*args, **kwargs)
@ -2104,17 +2118,16 @@ class AccountStatBalanceAll(ObjectResumeStat):
class AccountStatBalance(HybridDetailView): class AccountStatBalance(HybridDetailView):
""" """
Returns a graph (or a JSON Response) of the evolution a the personnal Returns a graph (or a JSON Response) of the evolution a the personnal
balance of a trigramm between begin_date and end_date balance of a trigramm between timezone.now() and `nb_days`
ago (specified to the view as an argument)
takes intto account the Operations and the Transfers takes intto account the Operations and the Transfers
does not takes intto account the balance offset does not takes intto account the balance offset
""" """
model = Account model = Account
trigramme_url_kwarg = 'trigramme' trigramme_url_kwarg = 'trigramme'
nb_date_url_kwargs = 'nb_date'
template_name = 'kfet/account_stat_balance.html' template_name = 'kfet/account_stat_balance.html'
context_object_name = 'account' context_object_name = 'account'
begin_date = this_morning()
end_date = timezone.now() # ne gère pas encore autre chose que now
anytime = False # un cas particulier
id_prefix = "lol" id_prefix = "lol"
def get_object(self, **kwargs): def get_object(self, **kwargs):
@ -2123,24 +2136,33 @@ class AccountStatBalance(HybridDetailView):
def get_changes_list(self, **kwargs): def get_changes_list(self, **kwargs):
account = self.object account = self.object
nb_date = self.kwargs.get(self.nb_date_url_kwargs, None)
end_date = this_morning()
if nb_date is None:
begin_date = timezone.datetime(year=1980, month=1, day=1)
anytime = True
else:
begin_date = this_morning() \
- timezone.timedelta(days=int(nb_date))
anytime = False
# On récupère les opérations # On récupère les opérations
# TODO: retirer les opgroup dont tous les op sont annulées # TODO: retirer les opgroup dont tous les op sont annulées
opgroups = list(OperationGroup.objects opgroups = list(OperationGroup.objects
.filter(on_acc=account) .filter(on_acc=account)
.filter(at__gte=self.begin_date) .filter(at__gte=begin_date)
.filter(at__lte=self.end_date)) .filter(at__lte=end_date))
# On récupère les transferts reçus # On récupère les transferts reçus
received_transfers = list(Transfer.objects received_transfers = list(Transfer.objects
.filter(to_acc=account) .filter(to_acc=account)
.filter(canceled_at=None) .filter(canceled_at=None)
.filter(group__at__gte=self.begin_date) .filter(group__at__gte=begin_date)
.filter(group__at__lte=self.end_date)) .filter(group__at__lte=end_date))
# On récupère les transferts émis # On récupère les transferts émis
emitted_transfers = list(Transfer.objects emitted_transfers = list(Transfer.objects
.filter(from_acc=account) .filter(from_acc=account)
.filter(canceled_at=None) .filter(canceled_at=None)
.filter(group__at__gte=self.begin_date) .filter(group__at__gte=begin_date)
.filter(group__at__lte=self.end_date)) .filter(group__at__lte=end_date))
# On transforme tout ça en une liste de dictionnaires sous la forme # On transforme tout ça en une liste de dictionnaires sous la forme
# {'at': date, # {'at': date,
# 'amount': changement de la balance (négatif si diminue la balance, # 'amount': changement de la balance (négatif si diminue la balance,
@ -2153,7 +2175,7 @@ class AccountStatBalance(HybridDetailView):
actions = [ actions = [
# Maintenant (à changer si on gère autre chose que now) # Maintenant (à changer si on gère autre chose que now)
{ {
'at': self.end_date.isoformat(), 'at': end_date.isoformat(),
'amout': 0, 'amout': 0,
'label': "actuel", 'label': "actuel",
'balance': 0, 'balance': 0,
@ -2184,11 +2206,11 @@ class AccountStatBalance(HybridDetailView):
'balance': 0, 'balance': 0,
} for tr in emitted_transfers } for tr in emitted_transfers
] ]
if not self.anytime: if not anytime:
actions += [ actions += [
# Date de début : # Date de début :
{ {
'at': self.begin_date.isoformat(), 'at': begin_date.isoformat(),
'amount': 0, 'amount': 0,
'label': "début", 'label': "début",
'balance': 0, 'balance': 0,
@ -2206,9 +2228,15 @@ class AccountStatBalance(HybridDetailView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = {} context = {}
changes = self.get_changes_list() changes = self.get_changes_list()
nb_days = self.kwargs.get(self.nb_date_url_kwargs, None)
if nb_days is None:
nb_days_string = 'anytime'
else:
nb_days_string = str(int(nb_days))
context['changes'] = changes context['changes'] = changes
context['chart_id'] = "%s_%s" % (self.id_prefix, context['chart_id'] = "%s_%s_%s_days" % (self.id_prefix,
self.object.id) self.object.id,
nb_days_string)
context['min_date'] = changes[len(changes)-1]['at'] context['min_date'] = changes[len(changes)-1]['at']
context['max_date'] = changes[0]['at'] context['max_date'] = changes[0]['at']
# TODO: offset # TODO: offset
@ -2219,37 +2247,6 @@ class AccountStatBalance(HybridDetailView):
return super(AccountStatBalance, self).dispatch(*args, **kwargs) return super(AccountStatBalance, self).dispatch(*args, **kwargs)
# Rend l'évolution de la balance perso de ces 30 derniers jours
class AccountStatBalanceMonth(AccountStatBalance):
begin_date = this_morning() - timezone.timedelta(days=30)
id_prefix = ID_PREFIX_ACC_BALANCE_MONTH
# Rend l'évolution de la balance perso de ces 3 derniers mois
class AccountStatBalanceThreeMonths(AccountStatBalance):
begin_date = this_morning() - timezone.timedelta(days=30*3)
id_prefix = ID_PREFIX_ACC_BALANCE_THREE_MONTHS
# Rend l'évolution de la balance perso de ces 6 derniers mois
class AccountStatBalanceSixMonths(AccountStatBalance):
begin_date = this_morning() - timezone.timedelta(days=30*6)
id_prefix = ID_PREFIX_ACC_BALANCE_SIX_MONTHS
# Rend l'évolution de la balance perso de la dernière annnée
class AccountStatBalanceYear(AccountStatBalance):
begin_date = this_morning() - timezone.timedelta(days=365)
id_prefix = ID_PREFIX_ACC_BALANCE_YEAR
# Rend l'évolution de la balance perso depuis toujours
class AccountStatBalanceAnytime(AccountStatBalance):
begin_date = timezone.datetime(year=1980, month=1, day=1)
id_prefix = ID_PREFIX_ACC_BALANCE_ANYTIME
anytime = True
# ------------------------ # ------------------------
# Consommation personnelle # Consommation personnelle
# ------------------------ # ------------------------