-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmodels.py
306 lines (258 loc) · 11.2 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
from decimal import Decimal
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Sum
from django.urls import reverse
from django.utils import timezone
from expenses import utils
# Create your models here.
class ExpenseManager(models.Manager):
def add_testuser_expenses(self, request):
if str(request.user) == "testuser1":
test_user_expenses = Expense.objects.filter(owner=request.user)
if not test_user_expenses:
Expense.objects.create_test_expenses(request.user)
def create_test_expenses(self, owner, expenses=None):
if expenses:
expenses = expenses
else:
expenses_by_date = utils.get_data_from_json(
"expenses/data/expensesByDate.json"
)
eg = utils.ExpenseGenerator(expenses_by_date)
expenses = eg.generate_expenses()
for expense in expenses:
exp = self.model(
amount=expense["amount"],
content=expense["content"],
category=expense["category"],
source=expense["source"],
date=expense["date"],
owner=owner,
)
exp.save()
def delete_testuser_expenses(self, request):
if str(request.user) == "testuser1" or str(request.user) == "testuser3":
test_user_expenses = Expense.objects.filter(owner=request.user)
for expense in test_user_expenses:
expense.delete()
def delete_testuser_budget(self, request):
if str(request.user) == "testuser1" or str(request.user) == "testuser3":
test_user_budget = Budget.objects.all()
test_user_budget.delete()
def get_user_expenses(self, owner):
return Expense.objects.filter(owner=owner)
def get_total_expenses(self, owner):
total_expenses = self.get_user_expenses(owner).aggregate(amount=Sum("amount"))[
"amount"
]
return utils.safely_round(total_expenses)
def get_max_expense(self, owner):
"""Returns the user's highest."""
max_expense = self.get_user_expenses(owner).order_by("amount").last()
return max_expense
def get_max_expense_content(self, owner):
"""Returns the content of the user's highest expense."""
max_expense = self.get_user_expenses(owner).order_by("amount").last()
return max_expense.content if max_expense else "There are no expenses yet."
def get_min_expense(self, owner):
"""Returns the user's lowest expense."""
min_expense = self.get_user_expenses(owner).order_by("amount").first()
return min_expense
def get_min_expense_content(self, owner):
"""Returns the content of the user's lowest expense."""
min_expense = self.get_user_expenses(owner).order_by("amount").first()
return min_expense.content if min_expense else "There are no expenses yet."
def get_weekly_expense_sum(self, owner, week_timedelta_num=0):
"""
Returns the total expenses for the given week.
Passing week_timedelta_num will add or substract to current week,
so week_timedelta_num=0(current week), week_timedelta_num=1(next week),
week_timedelta_num=-1(last week), and so on.
"""
current_week_num = utils.get_week_iso_num(week_timedelta_num)
weekly_expenses = self.get_user_expenses(owner).filter(
date__week=current_week_num
)
weekly_expenses = weekly_expenses.aggregate(
amount=Sum("amount"))["amount"]
return utils.safely_round(weekly_expenses)
def get_monthly_expense_sum(self, owner, month_timedelta_num=0):
"""
Returns the total expenses for the given month.
A month_timedelta_num will add or substract to current month,
so month_timedelta_num=0(current month) month_timedelta_num=1(next month),
month_timedelta_num=-1(last month), and so on.
"""
current_month_num = utils.get_month_num(month_timedelta_num)
current_month_num = 12 if current_month_num < 1 else current_month_num
monthly_expenses = self.get_user_expenses(owner).filter(
date__month=current_month_num
)
monthly_expenses = monthly_expenses.aggregate(
amount=Sum("amount"))["amount"]
return utils.safely_round(monthly_expenses)
def get_monthly_expense_average(self, owner):
months = utils.get_months_list()
monthly_expenses_data = []
for month in months:
month_num = months.index(month) + 1
monthly_expenses = self.get_user_expenses(owner).filter(
date__month=month_num
)
if monthly_expenses:
monthly_expenses_sum = round(
monthly_expenses.aggregate(amount=Sum("amount"))[
"amount"], 2
)
monthly_expenses_data.append(monthly_expenses_sum)
if monthly_expenses_data:
monthly_expense_average = round(
sum(monthly_expenses_data) / len(monthly_expenses_data), 2
)
else:
monthly_expense_average = 0
return monthly_expense_average
def get_expense_amounts_by_category(self, owner):
expense_amounts_by_category = {}
for exp in self.get_user_expenses(owner):
if exp.category not in expense_amounts_by_category:
expense_amounts_by_category[exp.category] = float(exp.amount)
else:
expense_amounts_by_category[exp.category] += float(exp.amount)
return expense_amounts_by_category
def get_biggest_category_expenditure(self, owner):
"""
Returns a dictionary with both the amount and the category
of the user's highest expense.
"""
expense_amounts_by_category = self.get_expense_amounts_by_category(
owner)
if expense_amounts_by_category:
biggest_category_expense = max(
expense_amounts_by_category.values())
biggest_category = [
cat
for (cat, amount) in expense_amounts_by_category.items()
if amount == biggest_category_expense
][0]
biggest_category_expense = round(biggest_category_expense, 2)
else:
biggest_category = ("No expenses",)
biggest_category_expense = 0
return {"category": biggest_category, "amount": biggest_category_expense}
def get_smallest_category_expenditure(self, owner):
"""
Returns a dictionary with both the amount and the category
of the user's lowest expense.
"""
expense_amounts_by_category = self.get_expense_amounts_by_category(
owner)
if expense_amounts_by_category:
smallest_category_expense = min(
expense_amounts_by_category.values())
smallest_category = [
cat
for (cat, amount) in expense_amounts_by_category.items()
if amount == smallest_category_expense
][0]
smallest_category_expense = round(smallest_category_expense, 2)
else:
smallest_category = ("No expenses",)
smallest_category_expense = 0
return {"category": smallest_category, "amount": smallest_category_expense}
def get_curr_and_last_month_expenses_percentage_diff(self, owner):
"""
Returns the percentage difference between the current month
and the last months expenses.
"""
curr_month_expenses = self.get_monthly_expense_sum(owner)
one_month_ago_expenses = self.get_monthly_expense_sum(owner, -1)
percentage_diff = utils.get_percentage_diff(
curr_month_expenses, one_month_ago_expenses
)
return percentage_diff
def get_daily_expense_average(self, owner):
expenses = Expense.objects.filter(owner=owner).values("date", "amount")
date_and_amount_data = {}
for exp in expenses:
if exp["date"] not in date_and_amount_data:
date_and_amount_data[exp["date"]] = exp["amount"]
else:
date_and_amount_data[exp["date"]] += exp["amount"]
if date_and_amount_data:
daily_expense_average = round(
sum(date_and_amount_data.values()) /
len(date_and_amount_data.values()),
2,
)
else:
daily_expense_average = 0
return daily_expense_average
def get_statistics(self, owner):
statistics = {
"sum_expense": self.get_total_expenses(owner),
"max_expense": self.get_max_expense(owner),
"max_expense_content": self.get_max_expense_content(owner),
"min_expense": self.get_min_expense(owner),
"min_expense_content": self.get_min_expense_content(owner),
"biggest_category_expenditure": self.get_biggest_category_expenditure(
owner
),
"smallest_category_expenditure": self.get_smallest_category_expenditure(
owner
),
"monthly_percentage_diff": self.get_curr_and_last_month_expenses_percentage_diff(
owner
),
"monthly_expense_average": self.get_monthly_expense_average(owner),
"daily_expense_average": self.get_daily_expense_average(owner),
"curr_month_expense_sum": self.get_monthly_expense_sum(owner),
"one_month_ago_expense_sum": self.get_monthly_expense_sum(owner, -1),
}
return statistics
def get_budget(self, owner):
budget = Budget.objects.filter(owner=owner).first()
return budget.amount if budget else 0
class Expense(models.Model):
amount = models.DecimalField(
blank=False,
default=10,
decimal_places=2,
max_digits=10,
validators=[MinValueValidator(Decimal("0.01")), ]
)
content = models.CharField(max_length=100, blank=False)
CATEGORY_CHOICES = (
("Bar tabs", "Bar tabs"),
("Monthly bill", "Monthly bill"),
("Online shopping", "Online shopping"),
("Electronics", "Electronics"),
("Groceries", "Groceries"),
("Taxi fare", "Taxi fare"),
("Miscellaneous", "Miscellaneous"),
)
category = models.CharField(
max_length=20, choices=CATEGORY_CHOICES, null=True, blank=False)
source = models.CharField(max_length=30, blank=False)
date = models.DateTimeField(default=timezone.now, blank=False)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
objects = ExpenseManager()
def __str__(self):
return str(self.amount)
def get_date_without_time(self):
date_without_time = utils.reformat_date(self.date, "%Y-%m-%d")
return date_without_time
class Meta:
ordering = ["-date"]
class Budget(models.Model):
amount = models.DecimalField(
default=10,
decimal_places=2,
max_digits=5,
validators=[MinValueValidator(Decimal("0.01"))],
)
owner = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.amount)