def post(self,id_user): """Post a user budget""" data = request.get_json() budget = Budget(id_user=id_user, name=data.get('name')) db.session.add(budget) db.session.commit() return jsonify(budget.asDict())
def test_get_sum_from_dates_returns_right_total_income(self): Budget.objects.bulk_create( [ Budget(amount=2300, category=self.category_obj, transaction_at='2021-01-01'), Budget(amount=300, category=self.category_obj, transaction_at='2021-02-01'), Budget(amount=-100, category=self.category_obj, transaction_at='2021-01-01') ] ) response = self.obj.get(reverse('get_income_sum_from_dates'), {'start_date': '2021-01-01', 'end_date': '2021-01-31'}) self.assertEquals(response.content.decode(), '{"total_income": 2300.0}')
def test_get_filtered_transactions_with_filters_returns_right_records(self): category_obj = Category.objects.create(type='general') Budget.objects.bulk_create( [ Budget(amount=2300, category=category_obj, transaction_at='2021-01-01'), Budget(amount=-100, category=category_obj, transaction_at='2021-01-02') ] ) response = self.obj.get(reverse('get_filtered_transactions'), data={'category': 'general', 'transaction_at': '2021-01-01'}) self.assertEquals(response.content.decode(), '{"results": [{"id": 1, "amount": 2300.0, "category__type": "general", "transaction_at": "2021-01-01"}]}')
def test_get_balance_returns_balance_of_today(self): self.obj = Client() category_obj = Category.objects.create(type='general') Budget.objects.bulk_create( [ Budget(amount=200, category=category_obj, transaction_at='2020-01-01'), Budget(amount=-130, category=category_obj, transaction_at='2021-01-01') ] ) response = self.obj.get(reverse('get_balance')) self.assertEquals(response.status_code, 200) self.assertEquals(response.content.decode(), '{"balance": 70.0}')
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 test_get_filtered_transactions_with_no_filters_returns_all_records(self): category_obj = Category.objects.create(type='general') Budget.objects.bulk_create( [ Budget(amount=2300, category=category_obj, transaction_at='2021-01-01'), Budget(amount=-100, category=category_obj, transaction_at='2021-01-01') ] ) response = self.obj.get(reverse('get_filtered_transactions')) results = [ {"id": 1, "amount": 2300.0, "category__type": "general", "transaction_at": "2021-01-01"}, {"id": 2, "amount": -100.0, "category__type": "general", "transaction_at": "2021-01-01"} ] self.assertEquals(response.content.decode(), json.dumps({'results': results}))
def create_budget(name, allocation, user_id): budget = Budget(id=randrange(9999999), name=name, allocation=allocation, user_id=user_id) db.session.add(budget) db.session.commit() add_action(BudgetActions.CREATED_BUDGET.value, name, user_id)
def create_budget(self, user_id, dailyBudget, creationDate): """ Returns a budget object """ budget = Budget(user_id=user_id, daily=dailyBudget, creation_date=creationDate) return budget
def test_budget_model(self): """ Test number of records in Budget table """ self.assertEqual(Budget.query.count(), 0) budget = Budget(daily=40, user_id=1) db.session.add(budget) db.session.commit() self.assertEqual(Budget.query.count(), 1)
def seedBudgets(): """Seed the db with budgets""" db.create_all() budget1 = Budget("Budget 1", 5000) budget2 = Budget("Budget 2", 7000) budget3 = Budget("Budget 3", 2000) budget4 = Budget("Budget 4", 1500) db.session.add(budget1) db.session.add(budget2) db.session.add(budget3) db.session.add(budget4) db.session.commit() print("Seeded the database with budgets") budgetList = Budget.query.all() print(budgetList)
def new_entry(): form = BudgetForm() if form.validate_on_submit(): budg = Budget(user_id=current_user.id) form.populate_obj(budg) db.session.add(budg) db.session.commit() flash('A new estimate entry was created.', 'success') return redirect(url_for('budget.home')) return render_template('budget/new.html', title='New entry', form=form)
def create_budget(self, user_id, budget_name, budget_amount): budget = Budget.query.filter_by(owner_id=user_id, name=budget_name).first() if budget: return "You are already using this budget name. Use a different name" else: new_budget = Budget(owner_id=user_id, name=budget_name, amount=budget_amount) db.session.add(new_budget) db.session.commit() response = {} response['name'] = new_budget.name response['amount'] = new_budget.amount return json.dumps({'New Budget': response})
def budget_edit(): response = {} if request.args.get('action', '') == 'save': data = request.args.to_dict() print('Data Recieved: ') print(data) if not 'id' in data and not db.session.query(Budget).filter( Budget.name == data['name']).all(): new_budget_item = Budget(name=data['name'], amount=data['amount']) try: db.session.add(new_budget_item) db.session.commit() response['A'] = ('New Budget {} added'.format( new_budget_item.name)) except Exception as e: print(e) response['A'] = str(e) else: print('Existing Budget Detected') result = db.session.query(Budget).filter( Budget.id == int(data['id'])).update({ 'name': data['name'], 'amount': int(data['amount']) }) try: db.session.commit() response['A'] = ('Budget {} updated'.format(result)) except Exception as e: print(e) response['A'] = str(e) elif request.args.get('action', '') == 'edit': print("Edit Budget Clicked") data = request.args.to_dict() print('Data Recieved: ') print(data) budgets = db.session.query(Budget).all() response['A'] = [t.to_dict() for t in budgets] elif request.args.get('action', '') == 'delete': print('Deleting Budget {}'.format(request.args.get('id', ''))) del_row = db.session.query(Budget).filter( Budget.id == request.args.get('id', '')).one() db.session.delete(del_row) try: db.session.commit() response['A'] = 'Row Deleted' except: db.session.rollback() response['A'] = 'Error Deleting Row' elif request.args.get('action', '') == 'view': print('Budget View Requested') test = db.session.query( Budget.name, Budget.amount, func.sum(Transaction.amount).label("total")).join( Transaction, Budget.transactions).filter( Transaction.date >= anyMonthStart(date.today())).group_by( Budget.name, Budget.amount) response["A"] = [r._asdict() for r in test.all()] return jsonify(response)
def budget_maintenance(click_time, prev_table, prev_time, new_name, new_amount, submit, m_close, m_open, curr_data): # print('Budget Maintence Callback Initial Values') print('click_time: ', click_time) # print('Previous Data: ', prev_table) # print('Name Entered: ', new_name) # print('Amount Entered: ', new_amount) # print('Submit Button: ', submit) # print('Add Modal Close: ', m_close) # print('Add Modal Open: ', m_open) # print('Current Data: ', curr_data) if click_time is None: print('Budget Modal No Action') raise dash.exceptions.PreventUpdate elif datetime.fromtimestamp( click_time / 1000) > datetime.now() - timedelta(seconds=1): print('Modal Launch') return True, pd.read_sql( db.session.query(Budget).statement, db.session.bind).to_dict("rows") if new_amount and new_name and not submit: print('Typing...') return dash.no_update, dash.no_update elif new_amount and new_name and datetime.fromtimestamp( submit / 1000) < datetime.now() - timedelta(seconds=1): print('Typing...') return dash.no_update, dash.no_update elif new_name and new_amount and datetime.fromtimestamp( submit / 1000) > datetime.now() - timedelta(seconds=1): print('To Be Databased...') print('Current Data: ', curr_data) print('Name Entered: ', new_name) print('Amount Entered: ', new_amount) new_budget = Budget(name=new_name, amount=new_amount) db.session.add(new_budget) try: db.session.commit() print('New Budget Added') except: db.session.rollback() print('Error Adding Budget') return dash.no_update, pd.read_sql( db.session.query(Budget).statement, db.session.bind).to_dict("rows") if prev_table is not None and datetime.fromtimestamp( prev_time / 1000) > datetime.now() - timedelta(seconds=1): print("Table Changed, Deleting ROw") new = pd.DataFrame(curr_data) old = pd.DataFrame(prev_table) df = old.merge( new, how='outer', indicator=True).loc[lambda x: x['_merge'] == 'left_only'] to_delete = df.to_dict("records") del_row = db.session.query(Budget).filter( Budget.id == to_delete[0]["id"]).one() db.session.delete(del_row) try: db.session.commit() print('Row Deleted') except: db.session.rollback() print('Error Deleting Row') return dash.no_update, pd.read_sql( db.session.query(Budget).statement, db.session.bind).to_dict("rows")