コード例 #1
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     today = get_ist_datetime()
     self.fields['from_date'].initial = default_date_format(today -
                                                            timedelta(
                                                                days=364))
     self.fields['to_date'].initial = default_date_format(today)
コード例 #2
0
 def last_month(self, user=None, *args, **kwargs):
     today = get_ist_datetime().date()
     first_day = today.replace(day=1)
     prev_month = first_day - timedelta(days=7)
     qs = Expense.objects.this_month(user=user,
                                     year=prev_month.year,
                                     month=prev_month.month)
     return qs
コード例 #3
0
    def get(self, request, *args, **kwargs):
        user = request.user
        initial_data = {}
        message = ""
        defaults_message = []

        try:
            income = int(request.GET.get('income'))
            defaults_message.append(f'Income: {income:,}')
        except (ValueError, TypeError):
            income = None

        today = helpers.get_ist_datetime().date()
        month_income = user.incomes.filter(timestamp__year=today.year,
                                           timestamp__month=today.month)
        month_income_sum = aggregate_sum(month_income)
        defaults_message.append(
            f'This month\'s total income: <span id="month_income">{month_income_sum:,}</span>'
        )

        try:
            savings = user.saving_calculation
            message = markdown.markdown(
                savings.message if savings.message else "")
            initial_data['savings_fixed_amount'] = savings.savings_fixed_amount
            initial_data['savings_percentage'] = savings.savings_percentage
            initial_data[
                'amount_to_keep_in_bank'] = savings.amount_to_keep_in_bank

            BANK_AMOUNT = int(self.gen_bank_amount())

            if not savings.amount_to_keep_in_bank and savings.auto_fill_amount_to_keep_in_bank:
                initial_data[
                    'amount_to_keep_in_bank'] = self.return_in_multiples(
                        BANK_AMOUNT * BANK_AMOUNT_PCT)
                defaults_message.append(
                    f'Amount to keep in bank is <span id="bank_amount_pct">{int(BANK_AMOUNT_PCT*100)}</span>% of <span id="bank_amount">{BANK_AMOUNT:,}</span>'
                )

            if not savings.savings_fixed_amount and savings.auto_fill_savings_fixed_amount and income:
                initial_data[
                    'savings_fixed_amount'] = self.return_in_multiples(
                        income * FIXED_SAVINGS_PCT)
                defaults_message.append(
                    f"Savings fixed amount is {int(FIXED_SAVINGS_PCT*100)}% of {income:,}"
                )

        except SavingCalculation.DoesNotExist:
            pass

        context = self.context.copy()
        context['form'] = self.form_class(initial=initial_data)
        context['inv_form'] = self.inv_form_class(user=user)
        context['message'] = message
        context['defaults_message'] = defaults_message
        context['income'] = income
        return render(request, self.template_name, context)
コード例 #4
0
    def get(self, request, *args, **kwargs):
        context = {}
        date_str = ""
        user = request.user
        year = request.GET.get('year')
        now = helpers.get_ist_datetime()
        expenses = Expense.objects.all(user=user)

        if year:
            year = int(year)
            total_months = now.month if now.year == year else 12
            expenses = expenses.filter(timestamp__year=year)
            context['total'] = expenses.aggregate(
                Sum('amount'))['amount__sum'] or 0
            context['monthly_average'] = context['total'] // total_months
            date_str = f": {year}"
            context['remark_url'] = reverse('expense:goto_year_expense',
                                            kwargs={'year': int(year)})
            context['daywise_url'] = reverse(
                'expense:day-wise-expense') + f'?year={year}'
            alt_first_date = date(year, 1, 1)
            if year == now.year:
                latest_date = date(year, now.month, 1)
            else:
                latest_date = date(year, 12, 1)
        else:
            alt_first_date = now.date().replace(month=1, day=1)
            latest_date = now.date().replace(day=1)

        # doing this way to maintain continuity of months
        first_date = expenses.dates('timestamp', 'month',
                                    order='ASC').first() or alt_first_date
        dates = helpers.get_dates_list(first_date, latest_date, day=1)
        dates = helpers.get_paginator_object(request, dates, 12)

        data = []
        for dt in dates:
            month_expense = Expense.objects.this_month(user=user,
                                                       year=dt.year,
                                                       month=dt.month)
            amount = aggregate_sum(month_expense)
            month_income = user.incomes.filter(timestamp__year=dt.year,
                                               timestamp__month=dt.month)
            month_income_sum = aggregate_sum(month_income)
            month_expense_to_income_ratio = helpers.calculate_ratio(
                amount, month_income_sum)
            data.append({
                'date': dt,
                'amount': amount,
                'month_eir': month_expense_to_income_ratio,
            })

        context['title'] = f'Monthly Expense{date_str}'
        context['data'] = data
        context['objects'] = dates
        return render(request, self.template_name, context)
コード例 #5
0
    def get(self, request, *args, **kwargs):
        user = request.user
        networths = user.net_worth.order_by('-date')
        networth = networths.first()

        x = 0
        avg_expense = 0
        YEARS = 3
        if networth and networth.amount > 0:
            now = get_ist_datetime()
            expense_months = user.expenses.exclude(amount=0)\
                                .exclude(timestamp__year=now.year, timestamp__month=now.month)\
                                .dates('timestamp', 'month', order='DESC')
            expense_sum = 0
            months = min(expense_months.count(), YEARS * 12)
            for dt in expense_months[:months]:
                expense = user.expenses.filter(timestamp__year=dt.year,
                                               timestamp__month=dt.month)
                expense_sum += aggregate_sum(expense)

            avg_expense = int(expense_sum / (months / 12))
            with suppress(ZeroDivisionError):
                x = round(networth.amount / avg_expense, 1)

        liabilities = []
        assets = []
        liability_amount = 0
        asset_amount = 0
        account_names = user.account_names.all()
        for account in account_names:
            amount = account.amounts.order_by('-date').first()
            data = {
                'account_name': account,
                'amount': amount,
            }
            if account.type == 0:
                liabilities.append(data)
                liability_amount += amount.amount if amount else 0
            else:
                assets.append(data)
                asset_amount += amount.amount if amount else 0

        context = {
            'title': 'NetWorth',
            'networth': networth,
            'avg_expense': avg_expense,
            'YEARS': YEARS,
            'x': x,
            'liabilities': liabilities,
            'liability_amount': liability_amount,
            'assets': assets,
            'asset_amount': asset_amount,
        }
        return render(request, self.template_name, context)
コード例 #6
0
 def this_day(self,
              user=None,
              year=None,
              month=None,
              day=None,
              *args,
              **kwargs):
     day = day if day else get_ist_datetime().day
     qs = Expense.objects.this_month(user=user, year=year,
                                     month=month).filter(timestamp__day=day)
     return qs
コード例 #7
0
    def get(self, request, *args, **kwargs):
        user = request.user
        incomes = user.incomes
        expenses = user.expenses

        now = helpers.get_ist_datetime()
        latest_date = now.date().replace(month=1, day=1)
        first_income_date = incomes.dates('timestamp', 'year',
                                          order='ASC').first() or latest_date
        first_expense_date = expenses.dates('timestamp', 'year',
                                            order='ASC').first() or latest_date
        first_date = min(first_income_date, first_expense_date)
        dates = helpers.get_dates_list(first_date, latest_date, month=1, day=1)

        dates = helpers.get_paginator_object(request, dates, 5)

        data = []
        for date in dates:
            income_sum = aggregate_sum(
                incomes.filter(timestamp__year=date.year))
            expense_sum = aggregate_sum(
                expenses.filter(timestamp__year=date.year))
            expense_ratio = helpers.calculate_ratio(expense_sum, income_sum)

            data.append({
                'date': date,
                'income_sum': income_sum,
                'expense_sum': expense_sum,
                'saved': income_sum - expense_sum,
                'expense_ratio': expense_ratio,
            })

        context = {
            'title': 'Report Card',
            'now': helpers.get_ist_datetime(),
            'eir': helpers.expense_to_income_ratio(user),
            'data': data,
            'BANK_AMOUNT_PCT': BANK_AMOUNT_PCT * 100,
            'objects': dates,
        }
        return render(request, self.template_name, context)
コード例 #8
0
def _save_networth(instance, *args, **kwargs):
    today_date = get_ist_datetime().date()
    user = instance.account_name.user
    account_names = user.account_names.all()
    networth_amount = 0
    for account in account_names:
        account_amount = account.amounts.order_by('-date').first()
        if account_amount:
            if account.type == 0:
                networth_amount -= account_amount.amount
            else:
                networth_amount += account_amount.amount
    try:
        networth = NetWorth.objects.get(user=user, date=today_date)
        networth.amount = networth_amount
        networth.save()
    except NetWorth.DoesNotExist:
        NetWorth.objects.create(user=user, amount=networth_amount, date=today_date)
コード例 #9
0
    def get(self, request, *args, **kwargs):
        user = request.user
        context = self.context.copy()
        now = helpers.get_ist_datetime()

        incomes = Income.objects.filter(user=user)
        year = request.GET.get('year')
        if year:
            year = int(year)
            total_months = now.month if year == now.year else 12
            incomes = incomes.filter(timestamp__year=year)
            context['title'] = f"{context['title']}: {year}"
            context['total'] = aggregate_sum(incomes)
            context['monthly_average'] = context['total'] // total_months
            alt_first_date = date(year, 1, 1)
            if year == now.year:
                latest_date = date(year, now.month, 1)
            else:
                latest_date = date(year, 12, 1)
        else:
            alt_first_date = now.date().replace(month=1, day=1)
            latest_date = now.date().replace(day=1)

        # doing this way to maintain continuity of months
        first_date = incomes.dates('timestamp', 'month',
                                   order='ASC').first() or alt_first_date
        dates = helpers.get_dates_list(first_date, latest_date, day=1)
        dates = helpers.get_paginator_object(request, dates, 12)

        data = []
        for dt in dates:
            amount = incomes.filter(
                timestamp__year=dt.year,
                timestamp__month=dt.month,
            ).aggregate(Sum('amount'))['amount__sum'] or 0
            data.append({
                'date': dt,
                'amount': amount,
            })

        context['data'] = data
        context['objects'] = dates
        return render(request, self.template_name, context)
コード例 #10
0
    def get(self, request, *args, **kwargs):
        user = request.user
        today = helpers.get_ist_datetime().date()
        data = dict()

        today_expense = aggregate_sum(Expense.objects.this_day(user=user))
        this_month_expense = aggregate_sum(
            Expense.objects.this_month(user=user))

        data['today_expense'] = f"{today_expense:,}"
        data['this_month_expense'] = f"{this_month_expense:,}"

        try:
            bank_balance = user.saving_calculation.amount_to_keep_in_bank * BANK_AMOUNT_PCT
            bank_balance_date = today.replace(day=1)
        except SavingCalculation.DoesNotExist:
            bank_balance = 0
            bank_balance_date = None

        if not bank_balance:
            incomes = user.incomes.exclude(amount=0)
            last_income_date = incomes.dates('timestamp',
                                             'month',
                                             order='DESC').first()
            if last_income_date:
                last_income = incomes.filter(
                    timestamp__year=last_income_date.year,
                    timestamp__month=last_income_date.month)
                bank_balance = aggregate_sum(last_income) * BANK_AMOUNT_PCT
                bank_balance_date = last_income_date

        if bank_balance:
            expense_sum = aggregate_sum(
                user.expenses.filter(timestamp__range=(bank_balance_date,
                                                       today)))
            data['this_month_eir'] = helpers.calculate_ratio(
                expense_sum, bank_balance)
            spending_power = max(0, bank_balance - expense_sum)
            data['spending_power'] = f"{int(spending_power):,}"

        data = json.dumps(data)
        return HttpResponse(data, content_type='application/json')
コード例 #11
0
    def get(self, request, *args, **kwargs):
        user = request.user
        now = get_ist_datetime()
        incomes = Income.objects.filter(user=user)

        latest_date = now.date().replace(month=1, day=1)
        first_date = incomes.dates('timestamp', 'year',
                                   order='ASC').first() or latest_date
        dates = helpers.get_dates_list(first_date, latest_date, month=1, day=1)
        dates = helpers.get_paginator_object(request, dates, 5)

        data = []
        for dt in dates:
            total_months = now.month if dt.year == now.year else 12
            amount = aggregate_sum(incomes.filter(timestamp__year=dt.year))
            avg_income = amount // total_months
            data.append((dt, amount, avg_income))

        self.context['data'] = data
        self.context['objects'] = dates
        return render(request, self.template_name, self.context)
コード例 #12
0
    def get(self, request, *args, **kwargs):
        user = request.user
        now = helpers.get_ist_datetime()
        expense_sum = user.expenses.aggregate(
            Sum('amount'))['amount__sum'] or 0
        income_sum = user.incomes.aggregate(Sum('amount'))['amount__sum'] or 0

        latest_date = now.date().replace(month=1, day=1)
        first_date = user.expenses.dates('timestamp', 'year',
                                         order='ASC').first() or latest_date
        dates = helpers.get_dates_list(first_date, latest_date, month=1, day=1)
        dates = helpers.get_paginator_object(request, dates, 5)

        data = []
        for date in dates:
            year = date.year
            total_months = now.month if now.year == year else 12
            amount = aggregate_sum(
                Expense.objects.this_year(user=user, year=year))
            year_income_sum = aggregate_sum(
                user.incomes.filter(timestamp__year=year))

            expense_ratio = helpers.calculate_ratio(amount, expense_sum)
            expense_to_income_ratio = helpers.calculate_ratio(
                amount, income_sum)
            year_expense_to_income_ratio = helpers.calculate_ratio(
                amount, year_income_sum)

            data.append({
                'year': year,
                'amount': amount,
                'monthly_average': amount // total_months,
                'year_eir': year_expense_to_income_ratio,
                'eir': expense_to_income_ratio,
                'expense_ratio': expense_ratio,
            })

        self.context['data'] = data
        self.context['objects'] = dates
        return render(request, self.template_name, self.context)
コード例 #13
0
    def post(self, request, *args, **kwargs):
        account_name = self.get_object()
        context = self.context.copy()
        form = self.form_class(request.POST)
        if form.is_valid():
            amount = form.cleaned_data['amount']
            data = {
                'account_name': account_name,
                'date': get_ist_datetime().date(),
            }
            account_name_amount = AccountNameAmount.objects.filter(
                **data).first()
            if account_name_amount:
                account_name_amount.amount = amount
                account_name_amount.save()
            else:
                AccountNameAmount.objects.create(amount=amount, **data)
            messages.success(request, "Account updated!")
            return HttpResponseRedirect(reverse('account:networth-dashboard'))

        context['form'] = form
        return render(request, self.template_name, context)
コード例 #14
0
 def this_month(self, user=None, year=None, month=None, *args, **kwargs):
     month = month if month else get_ist_datetime().month
     qs = Expense.objects.this_year(
         user=user, year=year).filter(timestamp__month=month)
     return qs
コード例 #15
0
 def this_year(self, user=None, year=None, *args, **kwargs):
     year = year if year else get_ist_datetime().year
     qs = super(ExpenseManager,
                self).filter(user=user).filter(timestamp__year=year)
     return qs
コード例 #16
0
def show_calculator(income_object):
    now = helpers.get_ist_datetime()
    later_created_time = income_object.created_at + timedelta(hours=36)
    if now < later_created_time:
        return True
    return False
コード例 #17
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields['timestamp'].initial = default_date_format(
         get_ist_datetime())
コード例 #18
0
    def get(self, request, *args, **kwargs):
        user = request.user
        year = int(kwargs['year'])
        incomes = user.incomes.filter(timestamp__year=year)
        expenses = user.expenses.filter(timestamp__year=year)

        now = get_ist_datetime()
        if year == now.year:
            last_month = now.month
        else:
            last_month = 12
        latest_date = date(year, last_month, 1)
        first_date = date(year, 1, 1)
        dates = helpers.get_dates_list(first_date, latest_date, day=1)

        data = []
        for dt in dates:
            income_sum = aggregate_sum(
                incomes.filter(timestamp__month=dt.month))
            expense_sum = aggregate_sum(
                expenses.filter(timestamp__month=dt.month))
            expense_ratio = helpers.calculate_ratio(expense_sum, income_sum)

            data.append({
                'date': dt,
                'income_sum': income_sum,
                'expense_sum': expense_sum,
                'saved': income_sum - expense_sum,
                'expense_ratio': expense_ratio,
            })

        incomes_total = aggregate_sum(incomes)
        expenses_total = aggregate_sum(expenses)
        saved_total = incomes_total - expenses_total
        eir = helpers.calculate_ratio(expenses_total, incomes_total)

        total = {
            'income_sum': incomes_total,
            'expense_sum': expenses_total,
            'saved': saved_total,
            'expense_ratio': eir,
        }

        monthly_average = {
            'income_sum': int(incomes_total / last_month),
            'expense_sum': int(expenses_total / last_month),
            'saved': int(saved_total / last_month),
            'expense_ratio': eir,
        }

        context = {
            'title': f'Report Card: {year}',
            'year': year,
            'now': now,
            'eir': eir,
            'data': data,
            'BANK_AMOUNT_PCT': BANK_AMOUNT_PCT * 100,
            'total': total,
            'monthly_average': monthly_average,
        }
        return render(request, self.template_name, context)