Пример #1
0
def addexpense(request):
    success = False
    if request.method == 'POST':
        form = ExpenseForm(request.user, request.POST)
        if form.is_valid():
            expense = Expense.objects.create(
                payer = form.cleaned_data['person'], 
                added = datetime.now(), modified = datetime.now(), 
                date = form.cleaned_data['date'])
            expense.save()
            for subexpense in generate_subexpenses(expense, form):
                subexpense.save()
            success = True
        else:
            return render(
                request,
                'app/addexpense.html',
                context_instance = RequestContext(request,
                {
                    'form':form,
                    'year':datetime.now().year,
                    'error':'Coś poszło nie tak... Najprawdopodobniej masz złe dane'
                })
            )
    return render(
        request,
        'app/addexpense.html',
        context_instance = RequestContext(request,
        {
            'form':ExpenseForm(request.user),
            'success':success
        })
    )
Пример #2
0
    def test_expense_form_valid_data(self):
        form = ExpenseForm(data={
            'title': 'expense1',
            'amount': 1000,
            'category': 'development'
        })

        self.assertTrue(form.is_valid())
Пример #3
0
def expense():
    form = ExpenseForm()
    budget = Budget.query.get(request.args.get("budget_id"))
    if form.validate_on_submit() and budget:
        expense = Expense(name=form.name.data, amount=form.amount.data,
                budget_id=budget.id, interval=form.interval.data,
                shared_by=form.shared_by.data)
        add_commit_model(expense)
        return redirect(url_for('expense', budget_id=budget.id))
    return render_template('expense.html', title="Expense", form=form,
            budget=budget)
Пример #4
0
def edit_expense(transaction_id):
    form = ExpenseForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    # print(request.get_json(), "<===== JSON object here")
    if form.validate_on_submit():
        # Edit the transaction.
        transaction_to_edit = Transaction.query.get(transaction_id)
        transaction_to_edit.group_id = form.data["group_id"]
        transaction_to_edit.payer_id = form.data["payer_id"]
        transaction_to_edit.paid_amount = form.data["amount"]
        transaction_to_edit.description = form.data["description"]
        transaction_to_edit.expense_date = form.data["expense_date"]
        transaction_to_edit.completed = False
        transaction_to_edit.updated_at = date.today()
        db.session.commit()

        # For each debtor, update or delete their expense.
        payed_amount = form.data["amount"]
        split_by = len(form.data["debtors"]) + 1
        remainder = payed_amount % split_by
        debtor_pays = (payed_amount - remainder) / split_by

        new_debtors = form.data["debtors"]

        for previous_expense in transaction_to_edit.expenses:
            previous_debtor = previous_expense.borrower_id
            if previous_debtor in new_debtors:
                previous_expense.lender_id = form.data["payer_id"]
                previous_expense.amount = debtor_pays
                previous_expense.completed = form.data["completed"]
                previous_expense.updated_at = date.today()
                new_debtors.remove(previous_debtor)
            else:
                db.session.delete(previous_expense)

        for new_debtor in new_debtors:
            new_expense = TransactionExpense(
                transaction_id=transaction_to_edit.id,
                lender_id=form.data["payer_id"],
                borrower_id=new_debtor,
                amount=debtor_pays,
                completed=form.data["completed"],
                updated_at=date.today())
            db.session.add(new_expense)

        db.session.commit()
        return {'message': 'Transaction Updated!'}

    return {'errors': validation_errors_to_error_messages(form.errors)}, 400
Пример #5
0
def expense_post():
    form = ExpenseForm(request.form)
    if form.validate():
        new_expense = Expense(form.date.data,
                              form.name.data,
                              form.amount.data,
                              user_id=session.get('user_id'))
        success = insert_expense(new_expense)
        if success:
            flash('Expense added successfully!', category='success')
        else:
            flash('Error adding expense', category='danger')
    else:
        flash_form_errors(form)
    return redirect(url_for('.expense_get_add'))
Пример #6
0
def expense_put(id_):
    form = ExpenseForm(request.form)
    if form.validate():
        edited_expense = Expense(form.date.data,
                                 form.name.data,
                                 form.amount.data,
                                 user_id=session.get('user_id'))
        success = update_expense(id_, edited_expense)
        if success:
            flash('Expense updated successfully!', category='success')
        else:
            flash('Error updating expense', category='danger')
    else:
        flash_form_errors(form)
    return redirect(url_for('site.home'))
Пример #7
0
def generate_bar_tab(msg, arr):
    """ Generate a graph of bars with tabs from array of data"""

    d_date = [d["date"] for d in arr if d["user_name"] == "ivo"]
    d_amount = [d["amount"] for d in arr if d["user_name"] == "ivo"]
    fig1 = figure(width=300, height=200)
    fig1.vbar(x=d_date, width=0.5, bottom=0, top=d_amount, color="green")
    tab1 = Panel(child=fig1, title="ivo")

    d_date = [d["date"] for d in arr if d["user_name"] == "aline"]
    d_amount = [d["amount"] for d in arr if d["user_name"] == "aline"]
    fig2 = figure(width=300, height=200)
    fig2.vbar(x=d_date, width=0.5, bottom=0, top=d_amount, color="blue")
    tab2 = Panel(child=fig2, title="aline")

    tabs = Tabs(tabs=[tab1, tab2])

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    script, div = components(tabs)
    html = flask.render_template('demo.html',
                                 plot_script=script,
                                 plot_div=div,
                                 js_resources=js_resources,
                                 css_resources=css_resources,
                                 form=ExpenseForm(),
                                 message=msg)
    return encode_utf8(html)
Пример #8
0
def generate_sample_bar_tab(msg):
    """ Generate a sample graph of bars with tabs """

    fig1 = figure(width=600, height=400)
    fig1.vbar(x=[1, 2, 3],
              width=0.5,
              bottom=0,
              top=[1.2, 2.5, 3.7],
              color="firebrick")
    tab1 = Panel(child=fig1, title="User_1")

    fig2 = figure(width=600, height=400)
    fig2.vbar(x=[1, 2, 3],
              width=0.5,
              bottom=0,
              top=[3.2, 6.5, 5.7],
              color="brown")
    tab2 = Panel(child=fig2, title="User_2")

    tabs = Tabs(tabs=[tab1, tab2])

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    script, div = components(tabs)
    html = flask.render_template('demo.html',
                                 plot_script=script,
                                 plot_div=div,
                                 js_resources=js_resources,
                                 css_resources=css_resources,
                                 form=ExpenseForm(),
                                 message=msg)
    return encode_utf8(html)
Пример #9
0
def home():
    #placeholder info
    form = ExpenseForm()
    form2 = DeleteEntryForm()
    if form.validate_on_submit():
        expense = Expense(type=form.type.data,
                          amount=form.amount.data,
                          user=current_user)
        db.session.add(expense)
        db.session.commit()
        flash('Added expenses')
        return redirect(url_for('home'))
    date = datetime.utcnow()
    #daily sum
    day_start = date.strftime("%Y-%m-%d 00:00")
    day_end = date.strftime("%Y-%m-%d 23:59")
    daily = Expense.query.filter(Expense.timestamp.between(day_start, day_end))
    daily_sum = daily.with_entities(func.sum(Expense.amount)).scalar()
    #monthly sum
    month_start = date.strftime("%Y-%m-01 00:00")
    if date.month == 12:
        year = int(date.year) + 1
        month_end = str(year) + "-01-01 00:00"
    else:
        month = int(date.month) + 1
        month_end = date.strftime("%Y-" + str(month) + "-01 00:00")
    monthly = Expense.query.filter(
        Expense.timestamp.between(month_start, month_end))
    monthly_sum = monthly.with_entities(func.sum(Expense.amount)).scalar()
    #pagination
    page = request.args.get('page', 1, type=int)
    expenses = current_user.posted_expenses().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('home', page = expenses.next_num) \
        if expenses.has_next else None
    prev_url = url_for('home', page = expenses.prev_num) \
        if expenses.has_prev else None
    return render_template('home.html',
                           form=form,
                           form2=form2,
                           expenses=expenses.items,
                           next_url=next_url,
                           prev_url=prev_url,
                           daily_sum=daily_sum,
                           monthly_sum=monthly_sum)
Пример #10
0
def expense_get_edit(id_):
    expense_ = find_expense(id_)
    form = ExpenseForm(obj=expense_)
    return render_template('expense.html',
                           form=form,
                           method='PUT',
                           operation='Edit',
                           title='Edit Expense',
                           action='edit-expense/{}'.format(expense_._id))
Пример #11
0
def expense_add_edit(record_id='0'):
    if record_id == '0':
        record = Expense(user=current_user)
    else:
        record = Expense.query.by_user(current_user).filter(
            Expense.id == record_id).first()
    form = ExpenseForm(obj=record)
    try:
        form.populate_obj(record)
    except:
        pass
    if form.validate_on_submit():  # it's submit!
        db.session.add(record)
        db.session.commit()
        if record_id == '0':
            return redirect('/expenses')
        else:
            return redirect('/expense/' + record_id)

    print_errors(form)
    return render_template('forms/expense_modal.html',
                           form=form,
                           record=record)
Пример #12
0
def view_budget(request, budget_id):
    context = {}

    try:
        budget = Budget.objects.get(user=request.user, id=budget_id)
    except Budget.DoesNotExist:
        raise Http404("Budget not found...")

    context['budget'] = budget
    budget_expenses = Expense.objects.filter(budget=budget)
    context['expenses_history'] = budget_expenses.order_by('-date_time')
    context['expense_form'] = ExpenseForm()

    return render(request, 'app/view_budget.html', context)
Пример #13
0
def create_expense(request, budget_id):
    context = {}

    form = ExpenseForm()

    if request.method == 'POST':
        form = ExpenseForm(request.POST)

        try:
            budget = Budget.objects.get(user=request.user, id=budget_id)
        except Budget.DoesNotExist:
            raise Http404("Budget not found...")

        if form.is_valid():
            try:
                obj = form.save(commit=False)
                obj.budget = budget
                obj.user = request.user

                # If datetime is not fit for the budget
                if obj.date_time.year != budget.year or obj.date_time.month != budget.month:
                    obj.date_time = datetime.datetime(budget.year,
                                                      budget.month, 1)

                obj.save()

                if obj.expense_type == 'INC':
                    budget.balance = budget.balance + obj.amount
                else:
                    budget.balance = budget.balance - obj.amount

                budget.save()
                messages.success(request, 'Expense added')
            except:
                messages.error(request, 'Expense not recorded.')

            return redirect('view_budget', budget_id=budget.id)
        else:
            messages.error(request, 'Invalid data.')

    if budget:
        context['budget'] = budget
        budget_expenses = Expense.objects.filter(budget=budget)
        context['expenses_history'] = budget_expenses.order_by('-date_time')
        context['expense_form'] = form

        return render(request, 'app/view_budget.html', context)
        #return redirect('view_budget', budget_id=budget.id)

    return redirect("budgets")
Пример #14
0
def generate_sample_graph(msg):
    """ Generate a sample dummy diagram """

    # Create a polynomial line graph with those arguments
    x_list = list(range(1, 6))
    fig = figure(title="Polynomial")
    fig.line(x_list, [i**2 for i in x_list], color="blue", line_width=2)

    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    script, div = components(fig)
    html = flask.render_template('demo.html',
                                 plot_script=script,
                                 plot_div=div,
                                 js_resources=js_resources,
                                 css_resources=css_resources,
                                 form=ExpenseForm(),
                                 message=msg)
    return encode_utf8(html)
Пример #15
0
def expense_get_add():
    return render_template('expense.html',
                           form=ExpenseForm(),
                           operation='Add',
                           title='Add Expense',
                           action='expense')
Пример #16
0
def create_expense():
    form = ExpenseForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        # Create the new transaction.
        new_transaction = Transaction(group_id=form.data["group_id"],
                                      payer_id=form.data["payer_id"],
                                      paid_amount=form.data["amount"],
                                      description=form.data["description"],
                                      expense_date=form.data["expense_date"],
                                      completed=False,
                                      updated_at=date.today())

        db.session.add(new_transaction)
        db.session.commit()
        requestinfo = request.json
        # For each debtor, create a new transaction expense.
        print("LOOK HERE ========", requestinfo)
        payed_amount = form.data["amount"]
        split_by = len(form.data["debtors"]) + 1
        remainder = payed_amount % split_by
        debtor_pays = (payed_amount - remainder) / split_by
        all_associated_transaction = []

        for debtor in form.data["debtors"]:
            info = [
                new_transaction.id, form.data["payer_id"], debtor, debtor_pays,
                False,
                date.today()
            ]
            print(info, "LOOK ===== HERE -========")
            new_expense = TransactionExpense(transaction_id=new_transaction.id,
                                             lender_id=form.data["payer_id"],
                                             borrower_id=debtor,
                                             amount=debtor_pays,
                                             completed=False,
                                             updated_at=date.today())
            users = requestinfo['groupUsers']
            payer_id = requestinfo["payer_id"]
            debtor_firstname = ""
            if payer_id == current_user.id:
                current_user_lender = 'You'
            else:
                for user in users:
                    if user['user_id'] == payer_id:
                        current_user_lender = user['first_name']
            for user in users:
                if user['user_id'] == debtor:
                    debtor_firstname = user['first_name']
            all_associated_transaction.append({
                'payer_id':
                payer_id,
                'paid_amount':
                payed_amount,
                'expense_date':
                requestinfo["expense_date"],
                'borrower_id':
                debtor,
                'first_name':
                debtor_firstname,
                'amount':
                debtor_pays,
                'description':
                requestinfo['description'],
                'current_user_lender':
                current_user_lender
            })
            db.session.add(new_expense)
        db.session.commit()

        response_transaction = {new_transaction.id: all_associated_transaction}
        return {
            'message': 'Transaction Created!',
            'transaction': response_transaction
        }
    return {'errors': validation_errors_to_error_messages(form.errors)}, 400
Пример #17
0
    def test_expense_form_no_data(self):
        form = ExpenseForm(data={})

        self.assertFalse(form.is_valid())
        self.assertEquals(len(form.errors), 3)
Пример #18
0
def edit_expense(request, expense_id):
    context = {}

    try:
        expense = Expense.objects.get(user=request.user, id=expense_id)
        context['expense'] = expense

    except Expense.DoesNotExist:
        raise Http404("Expense not found...")

    if request.POST:
        form = ExpenseForm(request.POST)

        if form.is_valid():
            obj = {}
            obj['date_time'] = form.cleaned_data['date_time']
            obj['expense_type'] = form.cleaned_data['expense_type']
            obj['amount'] = form.cleaned_data['amount']
            obj['description'] = form.cleaned_data['description']

            try:
                #obj = form.save(commit=False, instance=expense)
                budget = Budget.objects.get(user=request.user,
                                            id=expense.budget.id)
            except Budget.DoesNotExist:
                raise Http404("Budget not found...")

            try:
                # If datetime is not fit for the budget
                if obj['date_time'].year != budget.year or obj[
                        'date_time'].month != budget.month:
                    messages.error(request, 'Invalid date')
                else:
                    expense.date_time = obj['date_time']

                if expense.expense_type != obj['expense_type']:
                    expense.expense_type = obj['expense_type']
                    if obj['expense_type'] == 'INC':
                        budget.balance = budget.balance + obj[
                            'amount'] + expense.amount
                    else:
                        budget.balance = budget.balance - obj[
                            'amount'] + expense.amount
                elif expense.amount != obj['amount']:
                    if obj['expense_type'] == 'INC':
                        budget.balance = budget.balance + obj[
                            'amount'] - expense.amount
                    else:
                        budget.balance = budget.balance - obj[
                            'amount'] + expense.amount

                expense.amount = obj['amount']
                expense.description = obj['description']
                expense.save()
                budget.save()
                messages.success(request, 'Expense updated')
            except:
                messages.error(request, 'Expense not updated')

            if budget:
                return redirect('view_budget', budget_id=budget.id)
        else:
            context['expense_form'] = form
            messages.error(request, 'Invalid data')

    else:
        budget = Budget.objects.get(user=request.user, id=expense.budget.id)
        context['budget'] = budget
        context['expense_form'] = ExpenseForm(instance=expense)

    return render(request, 'app/edit_expense.html', context)