Exemplo n.º 1
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)
Exemplo n.º 2
0
    def get(self, request, *args, **kwargs):
        context = {}
        date_str = ""
        expense = request.user.expenses

        year = int(request.GET.get('year', 0))
        month = int(request.GET.get('month', 0))
        if year or month:
            if year:
                expense = expense.filter(timestamp__year=year)
                date_str = f": {year}"
            if month:
                expense = expense.filter(timestamp__month=month)
                dt = date(year, month, 1)
                date_str = f": {dt.strftime('%B %Y')}"

            context['total'] = expense.aggregate(
                Sum('amount'))['amount__sum'] or 0

        days = expense.dates('timestamp', 'day', order='DESC')
        days = helpers.get_paginator_object(request, days, 50)

        data = []
        for day in days:
            day_sum = aggregate_sum(expense.filter(timestamp=day))
            data.append({
                'day': day,
                'day_sum': day_sum,
            })

        context['title'] = f'Day-Wise Expense{date_str}'
        context['data'] = data
        context['objects'] = days
        return render(request, self.template_name, context)
Exemplo n.º 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)
Exemplo n.º 4
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')
Exemplo n.º 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)
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo n.º 8
0
    def gen_bank_amount(self):
        MONTHS = 3
        amounts = []
        incomes = self.request.user.incomes.exclude(amount=0)
        income_dates = incomes.dates('timestamp', 'month', order='DESC')

        for dt in income_dates[:MONTHS]:
            month_income = incomes.filter(timestamp__year=dt.year,
                                          timestamp__month=dt.month)
            amounts.append(aggregate_sum(month_income))

        if amounts:
            return max(statistics.mean(amounts), *amounts[:2])
        return 0
Exemplo n.º 9
0
    def get(self, request, *args, **kwargs):
        context = dict()
        date_str = ""
        from_date_str = to_date_str = None
        form = self.form_class(request.GET or None)

        if form.is_valid():
            remark = form.cleaned_data.get('remark', '').strip()
            from_date = form.cleaned_data.get('from_date')
            to_date = form.cleaned_data.get('to_date')
            objects = Expense.objects.all(user=request.user)

            if from_date and to_date:
                objects = objects.filter(timestamp__range=(from_date, to_date))
                from_date_str = default_date_format(from_date)
                to_date_str = default_date_format(to_date)
                date_str = f': {from_date_str} to {to_date_str}'
            elif from_date or to_date:
                the_date = from_date or to_date
                objects = objects.filter(timestamp=the_date)
                from_date_str = to_date_str = default_date_format(the_date)
                date_str = f': {from_date_str}'

            if remark == '""':
                objects = objects.filter(remark__isnull=True)
            elif remark:
                objects = helpers.search_expense_remark(objects, remark)

            total = aggregate_sum(objects)
            try:
                days = (to_date - from_date).days
                months = days / AVG_MONTH_DAYS
                if months > 1:
                    context['monthly_average'] = int(total / months)
            except:
                pass

            context['objects'] = helpers.get_paginator_object(
                request, objects, 30)
            context['total'] = total

        context['title'] = f'Expense Search{date_str}'
        context['form'] = form
        context['from_date'] = from_date_str
        context['to_date'] = to_date_str
        return render(request, self.template_name, context)
Exemplo n.º 10
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)
Exemplo n.º 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)
Exemplo n.º 12
0
    def get(self, request, *args, **kwargs):
        year = int(kwargs.get('year'))
        month = int(kwargs.get('month'))
        dt = date(year, month, 1)
        date_str = dt.strftime("%B %Y")

        from_date = default_date_format(dt)
        to_date = default_date_format(
            date(year, month,
                 calendar.monthrange(year, month)[1]))

        incomes = request.user.incomes
        incomes = incomes.filter(timestamp__year=year, timestamp__month=month)

        context = {
            "title": f"Income: {date_str}",
            "objects": incomes,
            "total": aggregate_sum(incomes),
            "year": year,
            "month": month,
            "from_date": from_date,
            "to_date": to_date,
        }
        return render(request, self.template_name, context)
Exemplo n.º 13
0
    def get(self, request, *args, **kwargs):
        user = request.user
        day = int(kwargs.get('day', 0))
        month = int(kwargs.get('month', 0))
        year = int(kwargs.get('year', 0))
        date_str = ""

        date_form = self.date_form_class(request.GET or None)
        from_date = to_date = None
        objects = user.expenses
        incomes = user.incomes

        if day:
            objects = Expense.objects.this_day(user=user,
                                               year=year,
                                               month=month,
                                               day=day)
            incomes = incomes.filter(timestamp__year=year,
                                     timestamp__month=month,
                                     timestamp__day=day)
            _day = date(year, month, day)
            date_str = f': {_day.strftime("%d %b %Y")}'
        elif month:
            objects = Expense.objects.this_month(user=user,
                                                 year=year,
                                                 month=month)
            incomes = incomes.filter(timestamp__year=year,
                                     timestamp__month=month)
            _month = date(year, month, 1)
            date_str = f': {_month.strftime("%b %Y")}'
            from_date = default_date_format(date(year, month, 1))
            to_date = default_date_format(
                date(year, month,
                     calendar.monthrange(year, month)[1]))
        elif year:
            objects = Expense.objects.this_year(user=user, year=year)
            incomes = incomes.filter(timestamp__year=year)
            date_str = f': {year}'
            from_date = default_date_format(date(year, 1, 1))
            to_date = default_date_format(date(year, 12, 31))
        elif date_form.is_valid():
            remark = date_form.cleaned_data.get('remark')
            _from_date = date_form.cleaned_data.get('from_date')
            _to_date = date_form.cleaned_data.get('to_date')
            objects = user.expenses
            if _from_date and _to_date:
                objects = objects.filter(timestamp__range=(_from_date,
                                                           _to_date))
                incomes = incomes.filter(timestamp__range=(_from_date,
                                                           _to_date))
                from_date = default_date_format(_from_date)
                to_date = default_date_format(_to_date)
                date_str = f': {from_date} to {to_date}'
            if remark:
                objects = helpers.search_expense_remark(objects, remark)

        objects = objects.select_related('remark')
        remarks = set()
        for instance in objects:
            remarks.add(instance.remark)

        expense_sum = aggregate_sum(objects)
        income_sum = aggregate_sum(incomes)

        remark_data = []
        for remark in remarks:
            amount = aggregate_sum(objects.filter(remark=remark))
            expense_ratio = helpers.calculate_ratio(amount, expense_sum)
            expense_to_income_ratio = helpers.calculate_ratio(
                amount, income_sum)
            remark_data.append({
                'remark': remark,
                'amount': amount,
                'eir': expense_to_income_ratio,
                'expense_ratio': expense_ratio,
            })

        remark_data = sorted(remark_data,
                             key=lambda x: x['amount'],
                             reverse=True)

        context = {
            "title": f"Remark-Wise Expenses{date_str}",
            "remarks": remark_data,
            "total": expense_sum,
            "from_date": from_date,
            "to_date": to_date,
        }

        return render(request, self.template_name, context)
Exemplo n.º 14
0
    def get(self, request, *args, **kwargs):
        user = request.user
        month = int(request.GET.get('month', 0))
        year = int(request.GET.get('year', 0))
        from_date = to_date = None
        date_str = ""

        date_form = self.date_form_class(request.GET or None)
        incomes = user.incomes

        if month and year:
            objects = incomes.filter(timestamp__year=year,
                                     timestamp__month=month)
            _month = date(year, month, 1)
            date_str = f': {_month.strftime("%b %Y")}'
            from_date = default_date_format(_month)
            to_date = default_date_format(
                date(year, month,
                     calendar.monthrange(year, month)[1]))
        elif year:
            objects = incomes.filter(timestamp__year=year)
            date_str = f': {year}'
            from_date = default_date_format(date(year, 1, 1))
            to_date = default_date_format(date(year, 12, 31))
        elif date_form.is_valid():
            source_name_search = date_form.cleaned_data.get('source')
            _from_date = date_form.cleaned_data.get('from_date')
            _to_date = date_form.cleaned_data.get('to_date')
            objects = incomes
            if _from_date and _to_date:
                objects = objects.filter(timestamp__range=(_from_date,
                                                           _to_date))
                from_date = default_date_format(_from_date)
                to_date = default_date_format(_to_date)
                date_str = f': {from_date} to {to_date}'
            if source_name_search:
                objects = objects.filter(source__name=source_name_search)
        else:
            objects = incomes

        objects = objects.select_related('source')
        sources = set()
        for instance in objects:
            sources.add(instance.source)

        income_sum = aggregate_sum(objects)

        source_data = []
        for source in sources:
            amount = aggregate_sum(objects.filter(source=source))
            source_data.append({
                'source': source,
                'amount': amount,
            })

        source_data = sorted(source_data,
                             key=lambda x: x['amount'],
                             reverse=True)

        context = {
            "title": f"Source-Wise Income{date_str}",
            "sources": source_data,
            "total": income_sum,
            "from_date": from_date,
            "to_date": to_date,
        }

        return render(request, self.template_name, context)
Exemplo n.º 15
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)