class ExpenseModelTest(unittest.TestCase): def setUp(self): self.user_ben = User(username='******', password='******', email='*****@*****.**') self.new_expense = Expense(category='Eat Out', description='Dinner with friends', ammount=200, date='2020-10-10', user=self.user_ben) def tearDown(self): Expense.query.delete() User.query.delete() def test_check_instance_variables(self): self.assertEquals(self.new_expense.category, 'Eat Out') self.assertEquals(self.new_expense.description, 'Dinner with friends') self.assertEquals(self.new_expense.ammount, 200) self.assertEquals(self.new_expense.date, '2020-10-10') self.assertEquals(self.new_expense.user, self.user_ben) def test_save_expense(self): self.new_expense.save_expense() self.assertTrue(len(Expense.query.all()) > 0)
def add_expense(): if not session['logged_in']: return redirect(url_for('index')) form = AddExpenseForm() if request.method == "POST": # def __init__(expdate, expdesc, expamount, expcat, vendor): e = Expense( request.form['expdate'], request.form['expdesc'], request.form['expamount'], request.form['expcat'], request.form['vendor']) e.create() return redirect(url_for('expenses')) # "> [{'expcat': 'Books/magazine', 'id': 2}, {'expcat': 'Cars: gas', 'id': 14}, # {'expcat': 'maxxixma', 'id': 150}, {'expcat': 'Miscellaneous', 'id': 98}, {'expcat': 'coffee', 'id': 39}] taxes = [8.75, 8.95, 9.25] the_cats = Expcat.get_expcats() form.expcat.choices = [(c['id'], c['expcat']) for c in the_cats] # choices = Expcat.get_expcats() return render_template('add_expense.html', form=form, header_text="Add expense", taxes=taxes)
def load_expenses(user_id): if (request.method == 'GET'): expenses = db.session.query(Expense).filter(Expense.user_id == user_id) expenses_dict = {} for expense in expenses: expenses_dict[expense.id] = expense.to_dict() return {'expenses': expenses_dict}, 200 elif (request.method == 'POST'): data = request.get_json() expense = Expense(description=data['description'], amount=data['amount'], category_id=data['category_id'], user_id=user_id) db.session.add(expense) db.session.commit() expenses = db.session.query(Expense).filter(Expense.user_id == user_id) expenses_dict = {} for expense in expenses: expenses_dict[expense.id] = expense.to_dict() return {'expenses': expenses_dict}, 200 elif (request.method == 'DELETE'): data = request.get_json() id = data['id'] expense = Expense.query.filter(Expense.id == id).first() db.session.delete(expense) db.session.commit() expenses = db.session.query(Expense).filter(Expense.user_id == user_id) expenses_dict = {} for expense in expenses: expenses_dict[expense.id] = expense.to_dict() return {'expenses': expenses_dict}, 200
def setUp(self): self.user_ben = User(username='******', password='******', email='*****@*****.**') self.new_expense = Expense(category='Eat Out', description='Dinner with friends', ammount=200, date='2020-10-10', user=self.user_ben)
def post(self, new_data): '''Create new expense.''' amount = new_data.pop('amount') user_id = get_jwt_identity() expense.current_user = User.query.get(user_id) exp = Expense(**new_data) exp.amount = amount exp.user_id = user_id db.session.add(exp) db.session.commit() return exp
def add_expense(current_user): category = request.args.get('category') amount = request.args.get('amount') dt = request.args.get('date') private = request.args.get('private') if not category or not amount: return jsonify({'message': 'Insufficient parameters'}), 400 exp = Expense(category=category, amount=amount, SpentBy=current_user) if dt: exp.date = dt if private: exp.private = private db.session.add(exp) db.session.commit() return jsonify({'message': 'Expense added'}), 201
def add_finances(entity, finances, ftype): # Add revenues and expenses to an entity. if finances: for f in finances: if ftype == 'revenue': years = [r.year for r in entity.revenues] if f['year'] not in years: # Add only if year doesn't exist to avoid duplicates. revenue = Revenue(f['amount'], f['year']) entity.revenues.append(revenue) db.flush() else: # Update amount if year exists. oldrevenue = entity.revenues.filter_by( year=f['year']).first() if oldrevenue: oldrevenue.amount = f['amount'] elif ftype == 'expenses': years = [e.year for e in entity.expenses] if f['year'] not in years: # Add only if year doesn't exist to avoid duplicates. expense = Expense(f['amount'], f['year']) entity.expenses.append(expense) db.flush() else: # Update amount if year exists. oldexpense = entity.expenses.filter_by( year=f['year']).first() if oldexpense: oldexpense.amount = f['amount']
def expenses(): if not session['logged_in']: return redirect(url_for('index')) expense_list = Expense.get_expenses() bankitems = BankItem.get_bankitems() return render_template('expenses.html', expense_list=expense_list, bankitems=bankitems, header_text="Expenses")
def GET(self): dates = [datetime.today() - timedelta(i) for i in range(1000)] categories = 'foo bar baz qux quux corge grault'.split() notes = [ s.strip() for s in '''Past the sticky heritage relaxes a waved aunt. A widest noise resigns a barred cue. When can the patience stagger? A vowel beards the victory. Her market damages the disposable anarchy. An alcoholic release mounts the preferable routine. The mighty concentrate breathes within the muddle.''' .split('\n') ] amounts = range(-30, 15) for _ in xrange(1000): e = Expense(user_id=self.current_user().id, date=random.choice(dates), category=random.choice(categories), note=random.choice(notes), amount=random.choice(amounts)) web.ctx.orm.add(e) if not Categories.exists(e.category, self.current_user().id): web.ctx.orm.add( Categories.new(e.category, self.current_user().id)) web.ctx.orm.commit() raise web.found('/')
def POST(self): form = expenses_import() if not form.validates(): return jsonify(success=False, errors=dict((i.name, i.note) for i in form.inputs if i.note is not None)) else: expenses = [ Expense(user_id=self.current_user().id, date=date, category=category, amount=amount, note=note) for (date, category, amount, note) in parsers.expenses(form.d.data) ] web.ctx.orm.add_all(expenses) web.ctx.orm.commit() expenses = [web.ctx.orm.merge(e) for e in expenses] return jsonify(success=True, expenses=[ ExpenseSerializer(e, self.current_user().currency) for e in expenses ])
def POST(self): attachment = UploadedFile('attachment') form = expenses_add() if not form.validates(): return jsonify(success=False, errors=dict((i.name, i.note) for i in form.inputs if i.note is not None)) else: url = (os.path.join(web.ctx.home, web.ctx.uploadman.add(attachment)) if attachment else None) e = Expense(user_id=self.current_user().id, amount=parsers.amount(form.d.amount), category=form.d.category, note=form.d.note, date=parsers.date_us(form.d.date), attachment=url) web.ctx.orm.add(e) web.ctx.orm.commit() e = web.ctx.orm.merge(e) if not Categories.exists(e.category, self.current_user().id): web.ctx.orm.add( Categories.new(e.category, self.current_user().id)) web.ctx.orm.commit() return jsonify(success=True, expense=ExpenseSerializer( e, self.current_user().currency))
def expenses(): expense_list = Expense.get_expenses() bankitems = BankItem.get_bankitems() return render_template('expenses.html', expense_list=expense_list, bankitems=bankitems, header_text="Expenses")
def db_with_related_expenses(db): '''An expense can be related to a budget entry either by foreign key or by same description. ''' db.session.query(Expense).delete() db.session.query(Budget).delete() budget_entry = Budget(user_id=1, item='Budget item 1', estimate=5000) related_expenses = [] dates = [datetime.date(2020, 10, 20), datetime.date(2021, 2, 5)] amount = 1000 for i in range(2): exp = Expense(user_id=1, description='Related expense', date=dates[i], mode_id=1) amount += 1000 exp.amount = amount related_expenses.append(exp) budget_entry.expenses = related_expenses db.session.add(budget_entry) related_expense = Expense(user_id=1, description='Budget item 1', date=datetime.date(2021, 3, 2), mode_id=1) related_expense.amount = 500 db.session.add(related_expense) # other expenses for i in range(5): exp = Expense(user_id=1, description=('Item ' + str(i + 1)), date=datetime.date(2021, 2, i + 1), mode_id=1) exp.amount = 100 db.session.add(exp) db.session.commit() yield db.session.query(Expense).delete() db.session.query(Budget).delete() db.session.commit() db.session.close()
def POST(self, id): attachment = UploadedFile('attachment') form = expenses_edit() if not form.validates(): return jsonify(success=False, errors=dict((i.name, i.note) for i in form.inputs if i.note is not None)) else: url = (os.path.join(web.ctx.home, web.ctx.uploadman.add(attachment)) if attachment else None) e = self.current_item() # Add a new expense being the copy of the current expense before # the edit operations have been applied deleted = Expense(original_id=e.id, user_id=self.current_user().id, amount=e.amount, category=e.category, note=e.note, date=e.date, deleted=True, attachment=e.attachment, created=e.created) # Now apply edit operations on the current expense e.amount = parsers.amount(form.d.amount) e.category = form.d.category e.note = form.d.note e.date = parsers.date_us(form.d.date) if attachment: e.attachment = url # Touch the creation date not to break the algo used to return # categories sorted by the first time they were used e.created = datetime.now() # Bulk add web.ctx.orm.add_all([deleted, e]) web.ctx.orm.commit() e = web.ctx.orm.merge(e) # Add the associated category if not already present if not Categories.exists(e.category, self.current_user().id): web.ctx.orm.add( Categories.new(e.category, self.current_user().id)) web.ctx.orm.commit() return jsonify(success=True, expense=ExpenseSerializer( e, self.current_user().currency))
def db_with_expense_amounts(db): expense.current_user = User.query.get(1) db.session.query(Expense).delete() amts = [150, 200, 300, 350, 400] for i in range(5): exp = Expense(user_id=1, description=('Item ' + str(i + 1)), date=datetime.date(2021, 1, i + 1), mode_id=1) exp.amount = amts[i] db.session.add(exp) db.session.commit() yield db.session.query(Expense).delete() db.session.commit() db.session.close()
def create_and_save_expense(self, user_id, item, cost, category, date): """ Create an expense object and save it to database """ expense = Expense(user_id=user_id, item=item, cost=cost, category=category, date=date) db.session.add(expense) db.session.commit()
def db_with_expenses(db): db.session.query(Expense).delete() for i in range(15): exp = Expense(user_id=1, description=('Item ' + str(i + 1)), date=datetime.date(2021, 1, i + 1), mode_id=random.choice([1, 2])) exp.amount = random.randrange(100, 1000) db.session.add(exp) exp_user2 = Expense(user_id=2, description='Item user2', date=datetime.date(2021, 2, 1), mode_id=1) exp_user2.amount = 100 db.session.add(exp_user2) db.session.commit() yield db.session.query(Expense).delete() db.session.commit() # remove session else sqlalchemy warning may appear. db.session.close()
def db_with_months_data(db): db.session.query(Expense).delete() k = 0 for i in range(3): for j in range(5): k += 1 exp = Expense(user_id=1, description=('Item ' + str(k)), date=datetime.date(2021, i + 1, j + 1), mode_id=1) exp.amount = 100 db.session.add(exp) db.session.commit() yield db.session.query(Expense).delete() db.session.commit() db.session.close()
def create_expense(): print('in create_expense') data = request.get_json() or {} print('') if 'description' not in data or 'cost' not in data or 'user_id' not in data or 'event_id' not in data or 'datetime_recorded' not in data: print('bad request') return bad_request( 'Must include description, cost, user_id, event_id, and datetime_recorded fields.' ) expense = Expense() print('expense = Expense()') expense.from_dict(data) print('expense.from_dict') db.session.add(expense) print('session.add(expense)') db.session.commit() print('session.commit') response = jsonify(expense.to_dict()) print('jsonify response') response.status_code = 201 response.headers['Location'] = url_for('api.get_expense', id=expense.id) return response
def test_expense_model(self): """ Test number of records in Expense table """ self.assertEqual(Expense.query.count(), 0) expense = Expense(item="coffee", cost="2.00", category="Food", user_id=1) db.session.add(expense) db.session.commit() self.assertEqual(Expense.query.count(), 1)
def db_with_expense_tags(db): db.session.query(Expense).delete() db.session.query(Tag).delete() tag1 = Tag(tagname='tag1', user_id=1) tag2 = Tag(tagname='tag2', user_id=1) tag3 = Tag(tagname='tag3', user_id=1) for i in range(2): exp = Expense(user_id=1, description=('Item ' + str(i + 1)), date=datetime.date(2021, 1, i + 1), mode_id=1, tags=[tag1]) exp.amount = 150 db.session.add(exp) exp = Expense(user_id=1, description='Item 3', date=datetime.date(2021, 1, 3), mode_id=1, tags=[tag1, tag2, tag3]) exp.amount = 200 db.session.add(exp) for i in range(4, 6): exp = Expense(user_id=1, description=('Item ' + str(i)), date=datetime.date(2021, 1, i), mode_id=1, tags=[tag2]) exp.amount = 250 db.session.add(exp) db.session.commit() yield db.session.query(Expense).delete() db.session.query(Tag).delete() db.session.commit() db.session.close()
def edit_expense(id): i = None if id!="0": i = Expense.query.filter_by(id=id).first_or_404() form = EditExpenseForm() if form.validate_on_submit(): if id == "0": i = Expense() i.user_id = current_user.id db.session.add(i) i.description = form.description.data db.session.commit() flash(_('Your changes have been saved.')) return redirect(url_for('expenses')) elif request.method == 'GET': if id == "0": form.id.data = 0 form.description.data = "" else: form.id.data = i.id form.description.data = i.description return render_template('edit_expense.html', title=_('Edit Expense'), form=form)
def db_with_budget_expenses(db): db.session.query(Expense).delete() db.session.query(Budget).delete() desc = ['Item 1'] * 3 + ['Item 2'] * 2 amount = 1000 for i in range(5): exp = Expense(user_id=1, description=desc[i], date=datetime.date(2021, 2, i + 1), mode_id=1) exp.amount = amount amount += 1000 db.session.add(exp) db.session.commit() yield db.session.query(Expense).delete() db.session.query(Budget).delete() db.session.commit() db.session.close()
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'))
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'))
def post(self, request, **kwargs): print request, kwargs expense = Expense( expense_type = ExpenseType.objects.get(id=self.CONTENT["expense_type"]["id"]), amount = self.CONTENT["amount"], event = Event.objects.get(id=self.CONTENT["event"]["id"]), payer = Participant.objects.get(id=self.CONTENT["payer"]["id"]), date = datetime.now() ) expense.save() expense.participants = [Participant.objects.get(id=participant["id"]) for participant in self.CONTENT["participants"]] expense.save()
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)
def form_submit(expense_form, income_form): if expense_form.validate_on_submit(): expense = Expense(expense=expense_form.expense.data, price=expense_form.price.data, occurence=expense_form.occurence.data, expenseDate=expense_form.expenseDate.data) db.session.add(expense) db_commit() if income_form.validate_on_submit(): income = Income( income=income_form.income.data, price=income_form.price.data, occurence=income_form.occurence.data, payday=income_form.payday.data, ) db.session.add(income) db_commit()
def update_finance(finances, ftype): # Delete any finances which have been removed. new_finances = [finance['id'] for finance in finances if finance['id']] if ftype == 'revenues': entity.revenues = [ revenue for revenue in entity.revenues if revenue.id in new_finances ] elif ftype == 'expenses': entity.expenses = [ expense for expense in entity.expenses if expense.id in new_finances ] # Do this or else list comprehensions don't work as expected. db.commit() # Create or update. for finance in finances: if finance['id']: # Finance exists, update data. oldfinance = Finance.query.get(finance['id']) if oldfinance.amount != finance['amount']: oldfinance.amount = finance['amount'] app.logger.debug('UPDATING ' + ftype + ' AMOUNT: ' + str(oldfinance.amount)) if oldfinance.year != finance['year']: oldfinance.year = finance['year'] app.logger.debug('UPDATING ' + ftype + ' YEAR: ' + str(oldfinance.year)) else: # Finance doesn't exist, create it. if ftype is 'revenues': revenue = Revenue(finance['amount'], finance['year']) entity.revenues.append(revenue) app.logger.debug('NEW REVENUE -- ' + str(revenue.year) + ': ' + str(revenue.amount)) elif ftype is 'expenses': expense = Expense(finance['amount'], finance['year']) entity.expenses.append(expense) app.logger.debug('NEW EXPENSE -- ' + str(expense.year) + ': ' + str(expense.amount)) db.commit()
def add_expense(): form = ExpenseForm(form_name='PickExpense') form.client_id.choices = [(row.id, row.name) for row in Client.query.all()] form.project_id.choices = [(row.id, row.name) for row in Project.query.all()] if request.method == 'GET': page = request.args.get('page', 1, type=int) pagination = current_user.my_expenses().paginate(page, 4, False) expenses = pagination.items return render_template('expenses/add_expense.html', title='Add an expense', form=form, expenses=expenses, pagination=pagination) if current_user.can(Permission.WRITE) and form.validate_on_submit( ) and request.form['form_name'] == 'PickExpense': expense = Expense(date=form.date.data, name=form.name.data, location=form.location.data, category_id=form.category_id.data.id, category_type_id=form.category_type_id.data.id, amount=form.amount.data, currency_id=form.currency_id.data.id, guest=form.guest.data, guest_list=form.guest_list.data, client_id=form.client_id.data.id, project_id=form.project_id.data.id, user_expense=current_user) db.session.add(expense) db.session.commit() flash('Your Expense has been added!', 'success') return redirect(url_for('expenses.add_expense')) page = request.args.get('page', 1, type=int) pagination = current_user.my_expenses().paginate(page, 4, False) expenses = pagination.items return render_template('expenses/add_expense.html', title='Add an expense', form=form, expenses=expenses, pagination=pagination)
def db_with_books(db_with_expenses): book1 = Expense(user_id=1, description='Flask cookbook', date=datetime.date(2021, 2, 1), mode_id=1) book1.amount = 1200 book2 = Expense(user_id=1, description='Rest api', comments='Book on Rest api.', date=datetime.date(2021, 2, 10), mode_id=2) book2.amount = 1500 _db.session.add_all([book1, book2]) _db.session.commit() _db.session.close()
participant = participant_b, weight = 3.0 ) weight_b_hotel.save() weight_c_hotel = Weight( expense_type = expense_type_hotel, participant = participant_c, weight = 3.0 ) weight_c_hotel.save() expense_john_food = Expense( event = event, expense_type = expense_type_food, amount = 150.4, payer = participant_a, date = datetime.now() ) expense_john_food.save() expense_john_food.participants = [participant_a, participant_b] expense_john_food.save() expense_jack_food = Expense( event = event, expense_type = expense_type_food, amount = 55.7, payer = participant_b, date = datetime.now() ) expense_jack_food.save()