def budget(): Budget.delete_expired() rows = Budget.query.filter_by(user_id=current_user.id).filter( Budget.status != 'EXPIRED') expired = Budget.query.filter_by(user_id=current_user.id).filter( Budget.status == 'EXPIRED') form = BudgetForm() if form.validate_on_submit(): amount = convert_usd(float(form.amount.data), g.code, rates) budget = Budget(user_id=current_user.id, amount=amount, category=form.category.data, notes=form.notes.data, start_date=form.startdate.data, end_date=form.enddate.data) db.session.add(budget) db.session.commit() flash('Budget Added!', 'success') return redirect(url_for('cashtrack.overview')) return rnd_tmp("budget.html", form=form, rows=rows, expires=expired, length=rows.count(), length_ex=expired.count(), icons=label_icons, colors=label_colors)
def interest(): """Calculate and Return Interest Value to User""" form = InterestForm() placeholder = 'Capital ({})'.format(rates[getfilter()]['symbol']) P = I = A = 0 if form.validate_on_submit(): P = float(form.capital.data) i = float(form.interest_rate.data) t = float(form.period.data) print(f'{P}, {i}, {t}') if str(form.type.data) == 'Simple': I = P * (i / 100) * t A = I + P elif str(form.type.data) == 'Compound': A = P * ((1 + i / 100)**t) I = A - P new = InterestHistory(user_id=current_user.id, bank_name=form.name.data, initial_capital=P, interest_rate=i, final_capital=A, period=t, type=form.type.data) db.session.add(new) db.session.commit() return rnd_tmp('interest.html', form=form, P=P, I=I, A=A, placeholder=placeholder)
def transactions_history(): # Getting all transactions linked to user id row = Transactions.query.filter_by(user_id=current_user.id).order_by( Transactions.date.desc(), Transactions.id.desc()) return rnd_tmp("history.html", title='Transactions', rows=row, length=row.count(), icons=label_icons, colors=label_colors)
def reset_request(): form = ResetRequestForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() send_reset_email(user) flash('An email with instructions to reset password has been sent.', 'info') logout_user() return redirect(url_for('users.login')) return rnd_tmp('reset_request.html', form=form)
def change_currency(): """ Change user's currency """ form = CurrencyForm() if form.validate_on_submit(): currency = form.rate.data redirected = redirect(url_for('cashtrack.overview')) redirected.set_cookie('filter', currency) symbol = rates[currency]['symbol'] flash(f'Currency has been changed to {currency} ({symbol})', 'success') return redirected return rnd_tmp('currency.html', form=form, rates=rates)
def change_password(): """" Change user password """ form = PassWordChangeForm() if form.validate_on_submit(): if check_password_hash(current_user.password_hash, form.old_password.data): current_user.password_hash = generate_password_hash( str(form.new_password.data)) db.session.commit() flash('Your Password has been updated', 'success') return redirect(url_for('users.account')) return rnd_tmp("change.html", form=form)
def reset_password(token): user = User.verify_reset_token(token) if not user: flash('This token is invalid or expired.', 'warning') return redirect(url_for('users.reset_request')) form = PassWordResetForm() if form.validate_on_submit(): hashed_pwd = generate_password_hash(str(form.new_password.data)) user.password_hash = hashed_pwd db.session.commit() flash('Your Password has been updated. You can now login.', 'success') return redirect(url_for('users.login')) return rnd_tmp("reset_password.html", form=form)
def interest_history(): # Getting all transactions linked to user id form = ClearHistoryForm() row = InterestHistory.query.filter_by(user_id=current_user.id).order_by( InterestHistory.id.desc()) if form.validate_on_submit(): delete_row = InterestHistory.query.filter_by(user_id=current_user.id) delete_row.delete() db.session.commit() flash('Interest History Cleared', 'success') return redirect(url_for('cashtrack.interest')) return rnd_tmp("history.html", title='Interest', form=form, rows=row, length=row.count(), filter=g.code)
def income(): form = IncomeForm() rows = Transactions.query.filter_by(user_id=current_user.id, type='Income', date=date.today()).order_by( Transactions.id.desc()) today = make_today_transactions(rows) if form.validate_on_submit(): # Record transactions to database amount = convert_usd(float(form.amount.data), g.code, rates) transactions = Transactions(user_id=current_user.id, amount=amount, type='Income', category=form.category.data, date=form.date.data, notes=form.notes.data) db.session.add(transactions) db.session.commit() # Update users Balance User.query.get(current_user.id).balance += amount db.session.commit() # Update daily income record = DailyRecords.query.filter_by(user_id=current_user.id, date=form.date.data, type='Income').first() if record: record.amount += amount db.session.commit() else: new = DailyRecords(user_id=current_user.id, amount=amount, type='Income', date=form.date.data) db.session.add(new) db.session.commit() # Redirect user to dashboard flash('Income Recorded', 'success') return redirect(url_for('cashtrack.overview')) return rnd_tmp("add.html", form=form, title="Income", icons=label_icons, colors=label_colors, rows=today, length=rows.count(), date=date.today())
def account(): """ Allows User to update account profile """ form = AccountUpdateForm() if form.validate_on_submit(): if form.picture.data: picture_file = save_picture(form.picture.data) current_user.image_file = picture_file current_user.username = form.username.data current_user.email = form.email.data db.session.commit() flash('Account Details Updated', 'success') return redirect(url_for('users.account')) elif request.method == 'GET': form.username.data = current_user.username form.email.data = current_user.email image_file = url_for('static', filename='/profile_pics/' + current_user.image_file) return rnd_tmp('account.html', image_file=image_file, form=form)
def register(): """Register new users into the site""" # Redirect to dashboard if logged in if current_user.is_authenticated: return redirect(url_for('cashtrack.overview')) form = RegistrationForm() if form.validate_on_submit(): hashed_pwd = generate_password_hash(form.password.data) user = User(username=form.username.data, email=form.email.data, password_hash=hashed_pwd) db.session.add(user) db.session.commit() flash( f'Account Created for {request.form.get("username")}! Please Log In.', 'success') return redirect(url_for('users.login')) return rnd_tmp("register.html", form=form)
def records(): """Shows graphs of user's transactions""" income = {} expense = {} weeklyrecord = {} # Extracting all transactions for the month dataMonth = DailyRecords.query.filter( DailyRecords.date.in_(find_month_complete( date.today()))).filter_by(user_id=current_user.id) # Convert transactions into weekly dictionary weekList = find_month_weekrange(date.today()) print(weekList) for week in weekList: weeklyrecord.update({week: {'Income': 0, 'Expense': 0}}) for data in dataMonth: week = find_weekrange(data.date) if week in weekList: weeklyrecord[week][data.type] += convert_currency_float( data.amount, g.code, rates) transactions = Transactions.query.filter_by(user_id=current_user.id) for transaction in transactions: trans_amount = convert_currency_float(transaction.amount, g.code, rates) if transaction.type == 'Income': if transaction.category in income: income[transaction.category] += trans_amount else: income.update({transaction.category: trans_amount}) else: if transaction.category in expense: expense[transaction.category] += trans_amount else: expense.update({transaction.category: trans_amount}) return rnd_tmp("records.html", income=income, expense=expense, month_data=weeklyrecord, month=calendar.month_name[date.today().month], colors=label_colors)
def overview(): """" Renders dashboard """ print(g.code) daily = DailyRecords.query.filter( extract('day', DailyRecords.date).between( date.today().day - 1, date.today().day + 1)).filter_by(user_id=current_user.id) recentRecord = {} for i in range(-1, 2): newDate = date.today() + timedelta(days=i) recentRecord.update( {newDate.strftime('%d/%m/%Y'): { 'Income': 0, 'Expense': 0 }}) for day in daily: dateOf = day.date.strftime('%d/%m/%Y') recentRecord[dateOf][day.type] += day.amount records = make_records_dict(recentRecord, rates) monthIncome = monthExpenses = 0 record_month = DailyRecords.query.filter_by( user_id=current_user.id).filter( extract('month', DailyRecords.date) == date.today().month) for record in record_month: if record.type == 'Income': monthIncome += float(record.amount) else: monthExpenses += float(record.amount) row = Transactions.query.filter_by(user_id=current_user.id).order_by( Transactions.date.desc(), Transactions.id.desc()).limit(5) return rnd_tmp('overview.html', record=records, rows=row, icons=label_icons, colors=label_colors, length=row.count(), monthIncome=monthIncome, monthExpenses=monthExpenses, month=calendar.month_name[date.today().month])
def login(): """Log users into their account""" # Redirect to dashboard if logged in if current_user.is_authenticated: return redirect(url_for('cashtrack.overview')) form = LogInForm() if form.validate_on_submit(): user = User.query.filter( or_(User.username == form.field.data, User.email == form.field.data)).first() if user and check_password_hash(user.password_hash, form.password.data): login_user(user, remember=form.remember.data) next_page = request.args.get('next') flash(f'Welcome, {user.username}!', 'success') return redirect(next_page) if next_page else redirect( url_for('cashtrack.overview')) else: flash( 'Login Unsuccessful. Please check username/email or password!', 'danger') return rnd_tmp("login.html", form=form)
def error_404(error): return rnd_tmp('errors/404.html'), 404
def transactions(): form = TransactionsForm() rows = Transactions.query.filter_by(user_id=current_user.id, type='Expense', date=date.today()).order_by( Transactions.date.desc()) today = make_today_transactions(rows) if form.validate_on_submit(): # Checking if Transaction can be made if current_user.balance == 0: flash( 'Your Balance is empty. Please add income to record expenses.', 'danger') return redirect(url_for('cashtrack.income')) if current_user.balance < form.amount.data: flash('You cannot afford the transaction. Please add income.', 'danger') return redirect(url_for('cashtrack.income')) amount = convert_usd(float(form.amount.data), g.code, rates) # Record transaction to database transactions = Transactions(user_id=current_user.id, amount=amount, type='Expense', category=form.category.data, date=form.date.data, notes=form.notes.data) db.session.add(transactions) db.session.commit() # Update users Total Balance and Expenses User.query.get(current_user.id).expenses += amount User.query.get(current_user.id).balance -= amount db.session.commit() # Update daily expense record = DailyRecords.query.filter_by(user_id=current_user.id, date=form.date.data, type='Expense').first() if record: record.amount += amount db.session.commit() else: new = DailyRecords(user_id=current_user.id, amount=amount, type='Expense', date=form.date.data) db.session.add(new) db.session.commit() # Update if budget for transaction type exists budget = Budget.query.filter_by( user_id=current_user.id, category=form.category.data).filter( Budget.status != 'EXPIRED').first() if budget: if form.date.data >= budget.start_date: budget.amount_used += amount db.session.commit() # Redirect user to dashboard flash('Transaction Recorded', 'success') return redirect(url_for('cashtrack.overview')) return rnd_tmp("add.html", form=form, title="Transactions", icons=label_icons, colors=label_colors, rows=today, length=rows.count(), date=date.today())
def error_500(error): return rnd_tmp('errors/500.html'), 500