Advertisement
mikhailemv

Untitled

Jun 13th, 2023
1,083
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.24 KB | None | 0 0
  1. @login_required
  2. def main(request):
  3.     accounts = Account.objects.filter(user=request.user)
  4.     daily_operations = Operation.objects.filter(user=request.user)
  5.     regular_transactions = RegularTransaction.objects.filter(user=request.user)
  6.  
  7.     if request.method == 'POST':
  8.         form = OperationFilterForm(request.user, request.POST)
  9.         if form.is_valid():
  10.             account = form.cleaned_data['account']
  11.             period = form.cleaned_data['period']
  12.             start_date = form.cleaned_data['start_date']
  13.             end_date = form.cleaned_data['end_date']
  14.  
  15.             if account:
  16.                 daily_operations = daily_operations.filter(account=account)
  17.                 regular_transactions = regular_transactions.filter(account=account)
  18.  
  19.             if period == 'day':
  20.                 start_date = end_date
  21.             elif period == 'week':
  22.                 start_date = end_date - timedelta(days=6)
  23.             elif period == 'month':
  24.                 start_date = end_date.replace(day=1)
  25.             elif period == 'year':
  26.                 start_date = end_date.replace(month=1, day=1)
  27.  
  28.             daily_operations = daily_operations.filter(date__range=(start_date, end_date))
  29.             regular_transactions = regular_transactions.filter(date__range=(start_date, end_date))
  30.  
  31.     else:
  32.         form = OperationFilterForm(request.user)
  33.  
  34.     expense_operations_daily = daily_operations.filter(key=Operation.EXPENSES)
  35.     income_operations_daily = daily_operations.filter(key=Operation.INCOME)
  36.     expense_operations_regular = regular_transactions.filter(key=RegularTransaction.EXPENSES)
  37.     income_operations_regular = regular_transactions.filter(key=RegularTransaction.INCOME)
  38.  
  39.     # Объединение операций по типу (Расходы или Доходы)
  40.     expense_operations = list(expense_operations_daily) + list(expense_operations_regular)
  41.     income_operations = list(income_operations_daily) + list(income_operations_regular)
  42.  
  43.     combined_operations = list(daily_operations) + list(regular_transactions)
  44.     sorted_operations = reversed(sorted(combined_operations, key=lambda op: op.date))
  45.  
  46.     data_expenses = []
  47.     labels_expenses = []
  48.     for expense_operation in expense_operations:
  49.         data_expenses.append(int(expense_operation.amount))
  50.         labels_expenses.append(str(expense_operation.category.category_name))
  51.  
  52.     # ===============================
  53.     data_expenses_new = []
  54.     labels_expenses_new = []
  55.  
  56.     seen_labels = set()
  57.  
  58.     for i in range(len(labels_expenses)):
  59.         label = labels_expenses[i]
  60.         if label not in seen_labels:
  61.             seen_labels.add(label)
  62.             total_amount = data_expenses[i]
  63.             for j in range(i + 1, len(labels_expenses)):
  64.                 if labels_expenses[j] == label:
  65.                     total_amount += data_expenses[j]
  66.             data_expenses_new.append(total_amount)
  67.             labels_expenses_new.append(label)
  68.  
  69.     data_expenses = data_expenses_new
  70.     labels_expenses = labels_expenses_new
  71.  
  72.     # Создание словаря
  73.     expenses_dict = dict(zip(labels_expenses, data_expenses))
  74.  
  75.     # Сортировка словаря по значениям в порядке убывания
  76.     sorted_expenses = sorted(expenses_dict.items(), key=lambda x: x[1], reverse=True)
  77.  
  78.     # Получение трех самых дорогих категорий
  79.     top_expenses = sorted_expenses[:3]
  80.  
  81.     # Вычисление суммы остальных расходов
  82.     other_expenses_sum = sum(value for _, value in sorted_expenses[3:])
  83.  
  84.     # Создание массивов для записи результатов
  85.     top_categories = []
  86.     top_amounts = []
  87.  
  88.     # Запись трех самых дорогих категорий в массивы
  89.     for category, amount in top_expenses:
  90.         top_categories.append(category)
  91.         top_amounts.append(amount)
  92.  
  93.     # Добавление 'Другое' в массивы
  94.     if len(sorted_expenses) > 3:
  95.         top_categories.append('Другое')
  96.         top_amounts.append(other_expenses_sum)
  97.  
  98.     if len(sorted_expenses) == 4 and top_amounts[3] == 0:
  99.         top_amounts.pop()
  100.         top_categories.pop()
  101.  
  102.     # ===============================
  103.  
  104.     data_incomes = []
  105.     labels_incomes = []
  106.     for income_operation in income_operations:
  107.         data_incomes.append(int(income_operation.amount))
  108.         labels_incomes.append(str(income_operation.category.category_name))
  109.  
  110.     # ===============================
  111.     data_incomes_new = []
  112.     labels_incomes_new = []
  113.  
  114.     s_seen_labels = set()
  115.  
  116.     for i in range(len(labels_incomes)):
  117.         label = labels_incomes[i]
  118.         if label not in s_seen_labels:
  119.             s_seen_labels.add(label)
  120.             total_amount = data_incomes[i]
  121.             for j in range(i + 1, len(labels_incomes)):
  122.                 if labels_incomes[j] == label:
  123.                     total_amount += data_incomes[j]
  124.             data_incomes_new.append(total_amount)
  125.             labels_incomes_new.append(label)
  126.  
  127.     data_incomes = data_incomes_new
  128.     labels_incomes = labels_incomes_new
  129.  
  130.     # Создание словаря
  131.     incomes_dict_inc = dict(zip(labels_incomes, data_incomes))
  132.  
  133.     # Сортировка словаря по значениям в порядке убывания
  134.     sorted_incomes = sorted(incomes_dict_inc.items(), key=lambda x: x[1], reverse=True)
  135.  
  136.     # Получение трех самых дорогих категорий
  137.     top_incomes = sorted_incomes[:3]
  138.  
  139.     # Вычисление суммы остальных расходов
  140.     other_incomes_sum = sum(value for _, value in sorted_incomes[3:])
  141.  
  142.     # Создание массивов для записи результатов
  143.     top_categories_incomes = []
  144.     top_amounts_incomes = []
  145.  
  146.     # Запись трех самых дорогих категорий в массивы
  147.     for category, amount in top_incomes:
  148.         top_categories_incomes.append(category)
  149.         top_amounts_incomes.append(amount)
  150.  
  151.     # Добавление 'Другое' в массивы
  152.     if len(sorted_incomes) > 3:
  153.         top_categories_incomes.append('Другое')
  154.         top_amounts_incomes.append(other_incomes_sum)
  155.  
  156.     if len(sorted_incomes) == 4 and top_amounts_incomes[3] == 0:
  157.         top_amounts_incomes.pop()
  158.         top_categories_incomes.pop()
  159.  
  160.     # ===============================
  161.  
  162.     full_expenses_sum = sum(data_expenses)
  163.     full_incomes_sum = sum(data_incomes)
  164.  
  165.     context = {
  166.         'accounts': accounts,
  167.         'combined_data_expenses': zip(top_categories, top_amounts),
  168.         'combined_data_incomes': zip(top_categories_incomes, top_amounts_incomes),
  169.         'full_expenses_sum': full_expenses_sum,
  170.         'full_incomes_sum': full_incomes_sum,
  171.         'daily_operations': daily_operations,
  172.         'regular_transactions': regular_transactions,
  173.         'sorted_operations': sorted_operations,
  174.         'top_amounts': top_amounts,
  175.         'top_categories': top_categories,
  176.         'top_amounts_incomes': top_amounts_incomes,
  177.         'top_categories_incomes': top_categories_incomes,
  178.         'form': form,
  179.     }
  180.  
  181.     return render(request, 'profile/main.html', context=context)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement