示例#1
0
def expense(request, id=0):
    """ Get or Create/Update an expense """

    status = 400
    expense = None
    errors = {}

    if request.method == 'PUT':
        data = json.loads(request.body)
        expense = get_object_or_404(Expense, pk=id, user=request.user)
        form = ExpenseForm(data, instance=expense)
        if form.is_valid():
            balance = Balance.objects.get(user=request.user)
            # Reset balance because we're updating an expense.
            balance.amount -= expense.amount

            form.save()
            balance.amount += expense.amount
            balance.save()
            status = 200
        else:
            errors = {'errors':form.errors}
    elif request.method == 'POST':
        data = json.loads(request.body)
        form = ExpenseForm(data)
        if form.is_valid():
            form.cleaned_data['user'] = request.user
            expense = Expense(**form.cleaned_data)
            expense.save()
            try:
                balance = Balance.objects.get(user=request.user)
            except Balance.DoesNotExist:
                # This user doesn't have a balance yet, create one.
                balance = Balance.objects.create(amount=0.0, user=request.user)

            balance.amount += expense.amount
            balance.save()
            status = 201
        else:
            errors = {'errors':form.errors}
    elif request.method == 'DELETE':
        expense = get_object_or_404(Expense, pk=id, user=request.user)
        try:
            # Make sure to update balance depending on the transaction type.
            balance = Balance.objects.get(user=request.user)
            balance.amount -= expense.amount
            balance.save()
            expense.delete()
        except:
            status = 500
        return HttpResponse(status=status)
    else:
        try:
            expense = get_object_or_404(Expense, pk=id)
        except Expense.DoesNotExist:
            logging.error('expense does not exist: ' + id)
            status = 404

    response = errors if errors else serialize(expense, ignore=[auth.models.User])
    return HttpResponse(content=json.dumps(response), status=status, content_type='application/json')
示例#2
0
def expense_edit(request, pk):
    expense = get_object_or_404(Expense, pk=pk, user=request.user)
    if expense.is_bill:
        return HttpResponseRedirect(expense.get_absolute_url())
    form = ExpenseForm(instance=expense, user=request.user)

    if request.method == "POST":
        form = ExpenseForm(request.POST, instance=expense, user=request.user)
        if form.is_valid():
            expense = form.save(commit=False)
            expense.user = request.user
            expense.is_bill = False
            expense.save()
            form.save_m2m()
            return HttpResponseRedirect(expense.get_absolute_url())

    return render(
        request,
        "expenses/expense_add_edit.html",
        {
            "htmltitle": str(expense),
            "pid": "expense_edit",
            "expense": expense,
            "form": form,
            "mode": "edit",
        },
    )
示例#3
0
文件: tests.py 项目: tlam/spendalot
    def test_create_form(self):
        form_data = {}
        form = ExpenseForm(data=form_data)
        self.assertFalse(form.is_valid())

        form_data = {
            'amount': Decimal('10.12'),
            'date': datetime.now().strftime('%Y-%m-%d'),
            'description': 'Testing expense',
            'category': self.category.id,
        }
        form = ExpenseForm(data=form_data)
        self.assertTrue(form.is_valid())
        self.assertEqual(Expense.objects.count(), 1)
        form.save()
        self.assertEqual(Expense.objects.count(), 2)
示例#4
0
文件: tests.py 项目: tlam/spendalot
    def test_create_form(self):
        form_data = {}
        form = ExpenseForm(data=form_data)
        self.assertFalse(form.is_valid())

        form_data = {
            'amount': Decimal('10.12'),
            'date': datetime.now().strftime('%Y-%m-%d'),
            'description': 'Testing expense',
            'category': self.category.id,
        }
        form = ExpenseForm(data=form_data)
        self.assertTrue(form.is_valid())
        self.assertEqual(Expense.objects.count(), 1)
        form.save()
        self.assertEqual(Expense.objects.count(), 2)
示例#5
0
def new_expense(request):
    if request.method == 'POST':
        form = ExpenseForm(request.POST)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Expense added!")
            return redirect('expense_new')
    else:
        form = ExpenseForm()
    return render(request, 'expenses/expense.html', {'form': form})
示例#6
0
文件: views.py 项目: regeve/Spending
def create(request):
    if request.method == "POST":
        form = ExpenseForm(request.POST)
        if form.is_valid():
            o = form.save()
            return redirect(reverse("expenses:detail", args=(o.id, )))
    else:
        form = ExpenseForm()

    return render(request, "expenses/expense_form.html", {
        'form': form,
    })
示例#7
0
def update(request, id):
    o = get_object_or_404(models.Expense, id=id, user=request.user)
    if request.method == "POST":
        form = ExpenseForm(request.POST, request.FILES, instance=o)
        if form.is_valid():
            o = form.save()
            return redirect(reverse("expenses:detail", args=(o.id,)))
    else:
        form = ExpenseForm(instance=o)

    return render(request, "expenses/expense_form.html", {
        'form': form,
    })
示例#8
0
def create(request):
    if request.method == "POST":
        form = ExpenseForm(request.POST)
        if form.is_valid():
            o = form.save()
            return redirect("expenses:detail", id=o.id)
    else:
        # method = GET
        form = ExpenseForm()

    d = {
        'form': form,
    }
    return render(request, "expenses/form.html", d)
示例#9
0
文件: views.py 项目: tlam/spendalot
def create(request):
    if request.method == 'POST':
        form = ExpenseForm(request.POST)
        if form.is_valid():
            expense = form.save()
            expense.payment = constants.CASH
            expense.save()
            messages.success(request, 'Expense created')
            return redirect('expenses:create')
    else:
        form = ExpenseForm()
    context = {
        'form': form,
    }

    return render(request, 'expenses/create.html', context)
示例#10
0
    def post(self, request):
        form = ExpenseForm(request.POST)
        jsonstr = request.POST['json_string']
        if form.is_valid():
            exp_date = form.cleaned_data['date']
            comment = form.cleaned_data['comment']
            total_cost = form.cleaned_data['total']
        else:
            return HttpResponse('invalid form')

        expense_dict = json.loads(jsonstr)
        self.context['expense_form'] = ExpenseForm()
        try:
            category = Category.objects.filter(name=expense_dict['category'])[0]
            itm = None
            qty= None
            cst=None
            for item in expense_dict['items']:
                itm_name = str(list(item.keys())[0])
                itm = Item.objects.all().filter(name=itm_name)[0]

                qty = float(item[itm_name]['quantity'])
                cst = int(item[itm_name]['cost'])
                if qty==0 or cst==0:
                    self.context['message'] = 'Zero value for some items'
                    return render(request, 'expenses/index.html', self.context)
                                
            expenses = Expense.objects.filter(date=exp_date, category=category)
            expense=None
            if len(expenses) == 0: # means no expense yet for the day on the same category
                expense = Expense(date=exp_date, category=category, comment=comment, cost=total_cost)
                expense.save()
            else: # already exists, add total
                expense = expenses[0]
                expense.cost+=total_cost
                expense.comment+='<br>'+comment
                expense.save()
            # save the item expense ( as it depends on expense)
            if len(expense_dict['items']) > 0:
                itm_exp = ItemExpense(expense=expense, item=itm, 
                            quantity=qty, cost=cst)
                itm_exp.save()

            self.context['message'] = 'Expense added'
            return render(request, 'expenses/index.html', self.context)
        except Exception as e:
            return HttpResponse(repr(e))
def expense_add(request):
    form = ExpenseForm(user=request.user)
    if request.method == "POST":
        form = ExpenseForm(request.POST, user=request.user)
        if form.is_valid():
            inst = form.save(commit=False)
            inst.user = request.user
            inst.is_bill = False
            inst.save()
            form.save_m2m()
            return HttpResponseRedirect(reverse("expenses:expense_list"))

    return render(
        request,
        "expenses/expense_add_edit.html",
        {"htmltitle": _("Add an expense"), "pid": "expense_add", "form": form, "mode": "add",},
    )
示例#12
0
def dashboard(request):
    msg = ''
    form = ExpenseForm()
    if request.method == 'POST':
        form = ExpenseForm(request.POST)
        if form.is_valid():
            expenses = Expenses()
            expenses.client = request.user
            expenses.title = form.cleaned_data['title']
            expenses.description = form.cleaned_data['description']
            expenses.amount = form.cleaned_data['amount']
            expenses.currency = form.cleaned_data['currency']
            expenses.date = form.cleaned_data['date']
            expenses.save()
            form = ExpenseForm()
            msg = 'Expense added successfully'
    return render(request, 'dashboard.html', {'form': form, 'msg': msg})
示例#13
0
def update_expense(request, pk):
    expense_info = Expense.objects.get(id=pk)
    expenseform = ExpenseForm(instance=expense_info)

    if request.user.username:
        if request.method == "POST":
            expenseform = ExpenseForm(request.POST, instance=expense_info)
            if expenseform.is_valid():
                expenseform.save()
                return redirect("/profile/")

        else:
            context = {
                "expenseform": expenseform,
                "current_date": datetime.now().date(),
                "expense_info": expense_info,
            }
            return render(request, "expenses/update_expense.html", context)
示例#14
0
def create(request):
	""" Create an expense. Update the current Balance. """

	status = 201
	form = ExpenseForm(request.POST)
	if form.is_valid():
		expense = form.save()
		try:
			balance = Balance.objects.get(pk=1)
		except Balance.DoesNotExist:
			# We're just now starting the app or something happened to the db, create the expense record.
			balance = Balance.objects.create(amount=0.0)

		balance.amount += expense.amount
		balance.save()
	else:
		status = 500
		logging.error(form.errors)
	return HttpResponse(status=status)
示例#15
0
文件: views.py 项目: tlam/spendalot
def create(request):
    if request.method == 'POST':
        form = ExpenseForm(request.POST)
        if form.is_valid():
            expense = form.save()
            expense.payment = constants.CASH
            expense.save()
            messages.success(request, 'Expense created')
            return redirect('expenses:create')
    else:
        form = ExpenseForm()
    context = {
        'form': form,
    }

    return render(
        request,
        'expenses/create.html',
        context)
示例#16
0
def update(request, id):
	status = 201
	expense = get_object_or_404(Expense, pk=id)

	old_amount = expense.amount
	form = ExpenseForm(request.POST, instance=expense)
	if form.is_valid():
		new_expense = form.save()
		try:
			balance = Balance.objects.get(pk=1)
		except Balance.DoesNotExist:
			logging.error('Missing Balance record. What happened? Panic!')
			status = 500
		else:
			balance.amount -= old_amount
			balance.amount += new_expense.amount
			balance.save()
	else:
		logging.error(form.errors)
		status = 500
	return HttpResponse(status=status)