Пример #1
0
def register_view(request):
    data = json.loads(request.body)

    username = data.get('username', '')
    password = data.get('password', '')
    currency = data.get('currency', '')

    form = BudgetUserForm(data={
        'username': username,
        'password': password,
        'currency': currency,
        'is_active': True
    })

    if form.is_valid():
        budget_user = form.save()

        for entry_type in EntryType.objects.filter(category='expense'):
            budget = Budget(user=budget_user, amount=0, entry_type=entry_type)
            budget.save()
        data = {
            "message": "Registration was successful!",
            "registered": True
        }
    else:
        field_name, error = form.errors.items()[0]
        data = {
            "message": field_name.capitalize() + ": " + error[0],
            "registered": False
        }

    return HttpResponse(json.dumps(data), content_type='application/json')
Пример #2
0
def createFinancialAcc(request):
	isLoged(request)
	accFina = ''
	accFinaName = ''
	trxs = ''
	balance = 0.0
	msj = ''
	page = 'financialInterest.html'
	if request.method == 'POST':
		faf = FinancialAccForm(request.POST)
     	faftname = request.POST.get('name','')
     	team = getSavedInSession(request, 'team')
     	exist = team.financialacc_set.filter(name = faftname)
     	accFina = team.financialacc_set.all()
     	if not exist:
	     	if faf.is_valid():
     	
	     		faft = faf.save(commit = False)
	     		acc = getCurrentAccount(request)
	     		
	     		grupo = acc.equipo_set.filter(nombre = team.nombre)
	     		accFinaName = faft.name
	     		faft.teamowner = grupo[0]
	     		
	     		faft.save()
	     		budget =  Budget(name='Budget ',accOwner=faft)
	     		
	     		budget.save()
	     		saveInSession(request, 'currentAccFina', faft)
	
		else:	
			msj = 'Esta cuenta ya existe en este grupo.'
	     	page = 'financialInterest.html'
	return render(request,page,{'msj':msj,'user':getLogin(request),'accFina':accFina,'currentAccFina':accFinaName,'trans':trxs,'balance':balance}) 
Пример #3
0
def createBudget(request):
	isLoged(request)
	accFina = team.financialacc_set.all()
	
	currentAccFinaName = request.GET.get('search','')
	if not currentAccFinaName:
		return HttpResponseRedirect('/homeview/')
	
	for acc in accFina:
		if acc.name == currentAccFinaName.strip():
			budget =  Budget(name='Budget '.join(acc.name),hasBudget=True,teamowner= acc)
			budget.save()

	return budgetByFinantialAcc(request)
Пример #4
0
def load_budgets():
    """ Load budget from budget.csv into database """

    Budget.query.delete()

    with open(budget_file) as f:
        for _ in range(1):
            next(f)

        for row in f:
            row = row.rstrip()
            budget_data = row.split(",")
            id = int(budget_data[0])
            budget = budget_data[1]
            category_id = budget_data[2]
            budget_userid = budget_data[3]
            budget_start_date = budget_data[4]
            budget_end_date = budget_data[5]

            budget = Budget(id=id,
                            budget=budget,
                            category_id=category_id,
                            budget_userid=budget_userid,
                            budget_start_date=get_datetime(budget_start_date),
                            budget_end_date=get_datetime(budget_end_date))

            db.session.add(budget)

        db.session.commit()
Пример #5
0
def process_row(org_id, dt, row, econ_ids, econ_ids_row):
    func_id = get_value(row[0], pattern1)
    for i, field in enumerate(row):
        econ_id = econ_ids_row[i]
        if econ_id in econ_ids:
            budget = Budget(func_id=func_id,
                            econ_id=econ_id,
                            amount=field,
                            org_id=org_id,
                            date_start=dt,
                            comm=None,
                            tags=None)
            yield budget
Пример #6
0
def add_budget():
    user = g.user
    form = BudgetForm()
    if form.validate_on_submit():
        budget = Budget(category=form.category.data,
                        limit=''.join(i for i in form.limit.data.strip()
                                      if i.isdigit()))
        db.session.add(budget)
        db.session.commit()
        flash(
            "You've created a budget for: {}".format(
                form.category.data.category_text.title()), 'success')
        return redirect(url_for('dashboard'))
    return render_template('add_budget.html', user=user, form=form)
Пример #7
0
def add_budget():
    """ Add a budget """
    from models import Budget, Expenditure, User, Category
    from utils import expenditure_total_amount_and_avg, budget_totals, get_dates_for_budget, get_progress, get_budget_per_category, connect_to_db 

    id = session.get('id')
    budget = request.form.get("budget")
    category_id = int(request.form.get("category"))
    start_date = request.form.get("start-date")
    end_date = request.form.get("end-date")

    user_budget_query = Budget.query.filter_by(budget_userid=id).all()

    # Check for budgets in the database under the user ID in particular categories;
    # delete budgets that exist to override them
    # Check to see if you can modify it instead
    for query in user_budget_query:
        if query.category_id == category_id:
            db.session.delete(query)
            db.session.commit()

    # Add the budget to the database. It will be the only budget for that
    # category in the database for the user
    new_budget = Budget(budget=budget,
                        category_id=category_id,
                        budget_userid=id,
                        budget_start_date=start_date,
                        budget_end_date=end_date)

    # Insert the new budget into the budget table and commit the insert
    db.session.add(new_budget)
    db.session.commit()

    # Call functions in utils.py
    total_cat_price, avg_cat_expenditures = expenditure_total_amount_and_avg(category_id, id, start_date, end_date)
    cat_budget_minus_expenses = budget_totals(category_id, id, total_cat_price)

    # Call get_progress in utils.py to calculate the progress bar totals
    category_progress = get_progress(cat_budget_minus_expenses, budget)

    # Return jsonified budget info to submit-budget.js
    return jsonify({
        'id': new_budget.id,
        'category': new_budget.category.category,
        'category_id': category_id,
        'budget': budget,
        'cat_budget_minus_expenses': cat_budget_minus_expenses,
        'category_progress': category_progress
    })
Пример #8
0
def makebudget():
    form = AddBudgetForm()
    if form.validate_on_submit():
        #Get data
        #amount of money to save
        saving_money = Decimal(form.monthlyincome.data) * percentify(
            form.percentsavings.data)
        #amount of money to spend
        spending_money = Decimal(form.monthlyincome.data) - Decimal(
            form.fixedexpenses.data) - saving_money

        #Save data to budget
        #check if data already exists
        otherbudget = Budget.query.filter_by(
            user_id=session["user_id"]).first()
        now = datetime.now()
        img_name = f"{session['user_id']}{now.year}{now.month}{now.day}{now.hour}{now.minute}.png"
        if otherbudget:
            #change data
            otherbudget.income = form.monthlyincome.data
            otherbudget.fixed_expenses = form.fixedexpenses.data
            otherbudget.saving_money = saving_money
            otherbudget.spending_money = spending_money
            otherbudget.spending_left = spending_money
            otherbudget.graph_link = img_name
            #commit changes
            db.session.commit()
            make_budget_chart(otherbudget)
        #if budget does not exist
        else:
            #create new budget
            mybudget = Budget(user_id=session["user_id"],
                              income=form.monthlyincome.data,
                              fixed_expenses=form.fixedexpenses.data,
                              saving_money=saving_money,
                              spending_money=spending_money,
                              spending_left=spending_money,
                              graph_link=img_name)

            db.session.add(mybudget)
            db.session.commit()
            make_budget_chart(mybudget)

        return redirect("/viewbudget")
    return render_template("makebudget.html", form=form)
Пример #9
0
def createBudget():
    if request.method == 'POST':
        params = request.json
        category = params['category']
        budget = float(params['amount'])
        customer_id = params['client_id']

    try:
        budget = Budget(
            customer_id,
            budget,
            category,
        )
        db.session.add(budget)
        db.session.commit()
        return "Budget added"
    except Exception as e:
        return (str(e))
Пример #10
0
def add_budget(budget_request: BudgetRequest, db: Session = Depends(get_db)):
    print(budget_request)
    budget_entry = Budget()
    budget_entry.name = budget_request.name
    budget_entry.amount = budget_request.amount
    budget_entry.category_id = budget_request.category_id
    budget_entry.importance = budget_request.importance

    db.add(budget_entry)
    db.commit()

    #     background_tasks.add_task(fetch_stock_data, stock.id)

    return {
        "code": "success",
        "message": "budget entry was added to the database"
    }
Пример #11
0
def check_shops_budgets():
    """"
    Method to checks all shops' budgets and 
    expenditures for the current month and notify shop.
    """

    # Create MySQL DB connection
    database = Database()
    try:
        data = database.fetch_budgets()
        shop_ids_to_offline = []
        shop_ids_to_update_notify_status = []
        for item in data:
            budget = Budget(shop_id=str(item[0]),
                            budget_amount=item[1],
                            amount_spent=item[2],
                            month=str(item[3]),
                            notify_status=item[4])
            if (budget.budget_percentage >= 100):
                # case they reach 100% of the current
                # month's budget.
                shop_ids_to_offline.append(budget.shop_id)

                if budget.notify_status == 0:
                    shop_ids_to_update_notify_status.append(budget.shop_id)

                # Notify shop
                budget.notify_shop()
            else:
                # case they reach 50% of the current
                # month's budget.
                if budget.notify_status == 0:
                    shop_ids_to_update_notify_status.append(budget.shop_id)
                    # Notify shop
                    budget.notify_shop()

        if shop_ids_to_offline:
            database.set_shop_offline(shop_ids=shop_ids_to_offline)
        if shop_ids_to_update_notify_status:
            database.update_notify_status(
                shop_ids=shop_ids_to_update_notify_status)
    except Exception as error:
        raise error
def set_budget():
    budget = Budget(available_sum=512000, is_empty=False)
    session.add(budget)
    session.commit()
Пример #13
0
Файл: run.py Проект: clauda/til
# -*- coding: UTF-8 -*-


class FeeCalculator(object):
    def calculate(self, budget, callback):
        amount = callback.apply(budget)
        print(amount)


if __name__ == '__main__':
    from models import Budget, Item
    from fee import VehicleFee, ProductFee, ServiceFee, BreathingFee, ThinkingFee

    calculator = FeeCalculator()

    budget = Budget()
    budget.add(Item('Car', 100.0))
    budget.add(Item('Laundry', 50.0))
    budget.add(Item('Cake', 350.0))

    print('Applying BreathingFee:')
    calculator.calculate(budget, BreathingFee())
    print('Applying ThinkingFee:')
    calculator.calculate(budget, ThinkingFee())
    print('Applying ServiceFee:')
    calculator.calculate(budget, ServiceFee())
    print('Applying VehicleFee:')
    calculator.calculate(budget, VehicleFee())
    print('Applying ProductFee:')
    calculator.calculate(budget, ProductFee())
    print('Applying VehicleFee over ProductFee:')
Пример #14
0
def getBudgetByUser(user_id):
    try:
        budget = Budget.query.filter_by(customer_id=user_id).all()
        return jsonify(Budget.serialize_list(budget))
    except Exception as e:
        return (str(e))
Пример #15
0
Файл: run.py Проект: clauda/til
# -*- coding: UTF-8 -*-
from discount import DiscountPerItems, DiscountPerValue, NoDiscountAtAll


class DiscountCalculator(object):
    def calculate(self, budget):
        discounter = DiscountPerItems(DiscountPerValue(NoDiscountAtAll()))

        return discounter.apply(budget)


if __name__ == '__main__':
    from models import Budget, Item

    budget = Budget()
    budget.add(Item('Item A', 100.0))
    budget.add(Item('Item B', 50.0))
    budget.add(Item('Item C', 400.0))

    calculator = DiscountCalculator()
    discount = calculator.calculate(budget)
    print('Discount applied: %s' % (discount))
Пример #16
0
Файл: run.py Проект: clauda/til
# -*- coding: UTF-8 -*-
# By definition, the Strategy Pattern defines a family of
# an algorithm and encapsulate each of them in you own class,
# that way it will enable that the strategy can be interchanged.


class FeeCalculator(object):
    def calculate(self, budget, callback):
        amount = callback.apply(budget)
        print(amount)


if __name__ == '__main__':
    from models import Budget
    from fee import ServiceFee, ProductFee

    budget = Budget(500.0)
    calculator = FeeCalculator()
    print('Applying ServiceFee:')
    calculator.calculate(budget, ServiceFee())
    print('Applying ProductFee:')
    calculator.calculate(budget, ProductFee())
Пример #17
0
Файл: run.py Проект: clauda/til
# -*- coding: UTF-8 -*-
# State is a behavioral design pattern that lets an
# object alter its behavior when its internal state
# changes. It appears as if the object changed its class.
from models import Budget, Item

if __name__ == '__main__':
    budget = Budget()
    budget.add(Item('Car', 100.0))
    budget.add(Item('Laundry', 50.0))
    budget.add(Item('Cake', 400))

    print(budget.amount)
    print(budget.status)

    budget.approve()  # or budget.disapprove()
    print(budget.status)

    budget.apply_bonus()
    print(budget.amount)

    budget.finish()
    print(budget.status)
Пример #18
0
def init_dev_data():
    """Initializes database with data for development and testing"""
    db.drop_all()
    db.create_all()

    print("Initialized Cashify Database.")
    a1 = Account(balance=400.00)
    u1 = User(username="******", password_hash="Vogel")
    a2 = Account(balance=0.00)
    u2 = User(username="******", password_hash="Torpey")

    db.session.add(a1)
    db.session.add(u1)
    db.session.add(a2)
    db.session.add(u2)

    u1.account = a1
    u2.account = a2

    # Transaction dummy data for Tyler
    balance = 400.00
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t1 = Transaction(amount=amount, date="2019-05-11", category="Other", current_balance=round(balance, 2))
    db.session.add(t1)
    a1.transactions.append(t1)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t2 = Transaction(amount=amount, date="2019-05-11", category="Income", current_balance=round(balance, 2))
    db.session.add(t2)
    a1.transactions.append(t2)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t3 = Transaction(amount=amount, date="2019-06-11", category="Entertainment", current_balance=round(balance, 2))
    db.session.add(t3)
    a1.transactions.append(t3)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t4 = Transaction(amount=amount, date="2019-06-11", category="Restaurants", current_balance=round(balance, 2))
    db.session.add(t4)
    a1.transactions.append(t4)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t5 = Transaction(amount=amount, date="2019-06-11", category="Restaurants", current_balance=round(balance, 2))
    db.session.add(t5)
    a1.transactions.append(t5)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t6 = Transaction(amount=amount, date="2019-07-04", category="Savings", current_balance=round(balance, 2))
    db.session.add(t6)
    a1.transactions.append(t6)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t7 = Transaction(amount=amount, date="2019-07-06", category="Income", current_balance=round(balance, 2))
    db.session.add(t7)
    a1.transactions.append(t7)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t8 = Transaction(amount=amount, date="2019-07-08", category="Other", current_balance=round(balance, 2))
    db.session.add(t8)
    a1.transactions.append(t8)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t9 = Transaction(amount=amount, date="2019-07-10", category="Groceries", current_balance=round(balance, 2))
    db.session.add(t9)
    a1.transactions.append(t9)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t10 = Transaction(amount=amount, date="2019-07-12", category="Utilities", current_balance=round(balance, 2))
    db.session.add(t10)
    a1.transactions.append(t10)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t11 = Transaction(amount=amount, date="2019-07-14", category="Other", current_balance=round(balance, 2))
    db.session.add(t11)
    a1.transactions.append(t11)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t12 = Transaction(amount=amount, date="2019-07-15", category="Other", current_balance=round(balance, 2))
    db.session.add(t12)
    a1.transactions.append(t12)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t13 = Transaction(amount=amount, date="2019-07-16", category="Income", current_balance=round(balance, 2))
    db.session.add(t13)
    a1.transactions.append(t13)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t14 = Transaction(amount=amount, date="2019-07-18", category="Entertainment", current_balance=round(balance, 2))
    db.session.add(t14)
    a1.transactions.append(t14)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t15 = Transaction(amount=amount, date="2019-07-19", category="Other", current_balance=round(balance, 2))
    db.session.add(t15)
    a1.transactions.append(t15)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t16 = Transaction(amount=amount, date="2019-07-19", category="Auto", current_balance=round(balance, 2))
    db.session.add(t16)
    a1.transactions.append(t16)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t17 = Transaction(amount=amount, date="2019-07-20", category="Income", current_balance=round(balance, 2))
    db.session.add(t17)
    a1.transactions.append(t17)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t18 = Transaction(amount=amount, date="2019-07-22", category="Healthcare", current_balance=round(balance, 2))
    db.session.add(t18)
    a1.transactions.append(t18)
    amount = -round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t19 = Transaction(amount=amount, date="2019-07-22", category="Restaurants", current_balance=round(balance, 2))
    db.session.add(t19)
    a1.transactions.append(t19)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t20 = Transaction(amount=amount, date="2019-07-23", category="Other", current_balance=round(balance, 2))
    db.session.add(t20)
    a1.transactions.append(t20)
    amount = round(random.uniform(1.00, 100.00), 2)
    balance += amount
    t21 = Transaction(amount=amount, date="2019-07-24", category="Other", current_balance=round(balance, 2))
    db.session.add(t21)
    a1.transactions.append(t21)

    a1.balance = balance


    #Setup Budget
    b = Budget(income = 1000, rent = 200, education = 100, groceries = 50, 
    home_improvement = 50, entertainment = 75, savings = 100, utilities = 25, \
    auto_gas = 50, healthcare = 50, restaurants = 50, shopping = 50, travel = 100, other = 200)

    a1.budget = b

    db.session.commit()
    print("Added dummy data.")
Пример #19
0
    def put(self):
        args = parser.parse_args()

        total_budget = args['Total Budget']
        income = args['Income']
        rent = args['Rent']
        education = args['Education']
        groceries = args['Groceries']
        home_improvement = args['Home Improvement']
        entertainment = args['Entertainment']
        savings = args['Savings']
        utilities = args['Utilities']
        auto_gas = args['Auto']
        healthcare = args['Healthcare']
        restaurants = args['Restaurants']
        shopping = args['Shopping']
        travel = args['Travel']
        other = args['Other']


        # Get the user
        username = session["username"]

        user = User.query.get(1)
        for u in User.query.all():
            if u.username == username:
                user = u

        account = user.account

        # Create the Budget
        b = Budget(account_id=account.id, total_budget=total_budget, income=income, rent=rent, education=education, groceries=groceries, home_improvement=home_improvement,
                   entertainment=entertainment, savings=savings, utilities=utilities, auto_gas=auto_gas, healthcare=healthcare, restaurants=restaurants,
                   shopping=shopping, travel=travel, other=other)

        record = db.session.query(Budget).filter(Budget.account_id == account.id).first()

        if record is None:
            db.session.add(b)
            account.budget = b

        else:

            record.total_budget = total_budget
            record.income = income
            record.rent = rent
            record.education = education
            record.groceries = groceries
            record.home_improvement = home_improvement
            record.entertainment = entertainment
            record.savings = savings
            record.utilities = utilities
            record.auto_gas = auto_gas
            record.healthcare = healthcare
            record.restaurants = restaurants
            record.shopping = shopping
            record.travel = travel
            record.other = other

        db.session.commit()

        return b.id, 201