示例#1
0
    def post(self):
        if self.request.get('minAmount') != '' and self.request.get('maxAmount') != '':
            expenses = Expense.query(Expense.amount >= int(self.request.get('minAmount')) * 100,
                Expense.amount <= int(self.request.get('maxAmount')) * 100)
        elif self.request.get('minAmount') == '' and self.request.get('maxAmount') == '':
            self.response.out.write(json.dumps([]))
            self.response.out.http_status_message(200)
            return
        elif self.request.get('minAmount') == '':
            expenses = Expense.query(Expense.amount <= int(self.request.get('maxAmount')) * 100)
        elif self.request.get('maxAmount') == '':
            expenses = Expense.query(Expense.amount >= int(self.request.get('minAmount')) * 100)

        jArray = []
        for expense in expenses:
            j = {
                'amount': "{0:.2f}".format(expense.amount * 1.0/100),
                'desc': expense.desc,
                'date': str(expense.date),
                'tags': expense.tags,
                'keyId': int(expense.key.id()),
            }
            jArray.append(j)

        self.response.out.write(json.dumps(jArray))
        self.response.out.http_status_message(200)
示例#2
0
    def post(self):
        if self.request.get('from') != '' and self.request.get('to') != '':
            fromDate = datetime.datetime.strptime(self.request.get('from'), '%m/%d/%Y').date()
            toDate = datetime.datetime.strptime(self.request.get('to'), '%m/%d/%Y').date()
            expenses = Expense.query(Expense.date >= fromDate, Expense.date <= toDate).fetch()
        elif self.request.get('from') == '' and self.request.get('to') == '':
            self.response.out.write(json.dumps([]))
            self.response.out.http_status_message(200)
            return
        elif self.request.get('from') == '':
            toDate = datetime.datetime.strptime(self.request.get('to'), '%m/%d/%Y').date()
            expenses = Expense.query(Expense.date <= toDate).fetch()
        elif self.request.get('to') == '':
            fromDate = datetime.datetime.strptime(self.request.get('from'), '%m/%d/%Y').date()
            expenses = Expense.query(Expense.date >= fromDate).fetch()

        jArray = []
        for expense in expenses:
            j = {
                'amount': "{0:.2f}".format(expense.amount * 1.0/100),
                'desc': expense.desc,
                'date': str(expense.date),
                'tags': expense.tags,
                'keyId': int(expense.key.id()),
            }
            jArray.append(j)

        self.response.out.write(json.dumps(jArray))
        self.response.out.http_status_message(200)
示例#3
0
 def add_expense(self,
                 name: str = None,
                 expense_type: str = None,
                 amount: str = None):
     if name is None or expense_type is None or amount is None:
         return [False, "Need name, expense_type and amount"]
     new_expense = Expense(name, expense_type, amount)
     self._expenses.append(new_expense.json())
     return [True, "User added"]
示例#4
0
 def db_query():
     data = request.json
     if data is None:
         return Expense(db).get_user_expenses(identifier)
     else:
         if 'start_date' not in data:
             data['start_date'] = '2000-01-01'
         if 'end_date' not in data:
             data['end_date'] = time.strftime('%Y-%m-%d')
         return Expense(db).get_user_expenses_from_to(data, identifier)
示例#5
0
 def update_expense(self, expense_uuid, new_expense):
     i = 0
     for idx, l_expense in enumerate(self._expenses):
         if 'expense_uuid' in l_expense:
             c_expense = Expense()
             c_expense.from_mongo(l_expense)
             if c_expense.expense_uuid == expense_uuid:
                 self._expenses[idx] = new_expense.json()
                 return [True, "expense found and updated"]
         i += 1
     return [False, "expense not found"]
 def create_expense(figure,
                    user,
                    category,
                    currency="GBP",
                    date=date.today()):
     """Function create an Expense object and save it to database."""
     expense = Expense(figure=figure,
                       user=user,
                       category=category,
                       currency=currency,
                       created_at=date)
     expense.save()
     return expense
示例#7
0
    def delete_expense(self, _expense_uuid=None, delete_all: bool = False):
        i = 0
        if delete_all:
            self._expenses = []
            return [True, "deleted all events"]

        for idx, l_expense in enumerate(self._expenses):
            if 'expense_uuid' in l_expense:
                c_expense = Expense()
                c_expense.from_mongo(l_expense)
                if c_expense.expense_uuid == _expense_uuid:
                    del self._expenses[idx]
                    return [True, "expense found and deleted"]
            i += 1
        return [False, "expense not found"]
示例#8
0
    def get(self):
        user = users.get_current_user()

        if user:
            expenses = Expense.query(Expense.userID == user.user_id()).fetch()
            
            for expense in expenses:
                expense.tags = map(str, expense.tags)

            jArray = []
            for expense in expenses:
                j = {
                    'amount': "{0:.2f}".format(expense.amount * 1.0/100),
                    'desc': expense.desc,
                    'date': str(expense.date),
                    'tags': expense.tags,
                    'keyId': int(expense.key.id())
                }
                jArray.append(j)

            template_values = {
                'expenses': jArray,
            }


            template = jinja_environment.get_template('history.html')
            self.response.write(template.render(template_values))
        else:
            template = jinja_environment.get_template('login.html')
            self.response.write(template.render())
示例#9
0
    def post(self):
        tags = map(str,self.request.get('tags').split(','))

        if len(tags) == 0:
            self.response.out.write(json.dumps([]))
            self.response.out.http_status_message(200)
            return
        else:
            query = Expense.query(Expense.userID == users.get_current_user().user_id())

            for i, tag in enumerate(tags):
                query = query.filter(Expense.tags == tag)         

            expenses = query.fetch()

        jArray = []
        for expense in expenses:
            j = {
                'amount': "{0:.2f}".format(expense.amount * 1.0/100),
                'desc': expense.desc,
                'date': str(expense.date),
                'tags': expense.tags,
                'keyId': int(expense.key.id()),
            }
            jArray.append(j)

        self.response.out.write(json.dumps(jArray))
        self.response.out.http_status_message(200)
 def get(self, id):
     expense = Expense.get_by_id(id)
     if expense:
         return {'expense': expense.data}, HTTPStatus.OK
     else:
         return {
             'message': 'Expense with specify ID not found.'
         }, HTTPStatus.NOT_FOUND
示例#11
0
    def progress(self):
        from models.expense import Expense
        from models.expectation import Expectation

        expenses = Expense.all(user_id=self['_id'])
        savings = [ x for x in expenses if Tag.get(_id=x['tag_id'])['name'] == 'saving' ]
        expectation = Expectation.get(user_id=self['_id'])

        total_savings = sum(float(x['cost']) for x in savings)

        return int((float(expectation['cost']) - total_savings * 100) / float(expectation['cost']))
示例#12
0
def create_expense(cats_id):
    """ Create an expense """
    try:
        if len(storage.getobject(CategorySub, "id", cats_id)) == 0:
            return jsonify({"Error": "CategorySub id not found"}), 404
        data = request.get_json(force=True)
        for at in attr:
            if at not in data.keys():
                return jsonify({"Error": str("Missing " + at)})
        new_obj = Expense()
        set_obj(new_obj, **data)
        new_obj.CategorySub_id = cats_id
        storage.insert(new_obj)
        #Actualización de kilometraje alertas
        second_last = storage.get_second_last(Expense)
        print("new_obj ", new_obj.mileage)
        act_alerts(new_obj.mileage, second_last.mileage)
        return jsonify(new_obj.to_dict())
    except Exception:
        abort(404)
 def delete(self, id):
     expense = Expense.get_by_id(id)
     if expense:
         expense.delete()
         return {
             'message': f'Expense with ID {id} has been deleted.'
         }, HTTPStatus.OK
     else:
         return {
             'message': 'Expense with specify ID not found.'
         }, HTTPStatus.NOT_FOUND
示例#14
0
def create_expense():

    try:
        data = request.json
        expense = Expense(data["date"], data["category_id"],
                          data["description"], data["amount"])
        db.session.add(expense)
        db.session.commit()
        return (Response(), 200)

    except:
        db.session.rollback()
        return (Response(), 400)
示例#15
0
 def add_new_expense(self):
     desc = self.expenseDescriptionEdit.toPlainText().strip()
     price = self.priceEdit.toPlainText().strip().replace(",", ".")
     date = self.expenseDateEdit.date().toPyDate()
     category = Category(self.categoryComboBox.currentText())
     if desc == "" and price == "":
         show_dialog("Description or price is empty", "New Expense")
     elif category.name == "Choose category":
         show_dialog("Choose category", "New Expense")
     else:
         self.db.add_expense(Expense(desc, float(price), date, category))
         self.infoTopLabel.setText(f"Expense '{desc}' added")
         self.clear_addExpense_UI()
示例#16
0
    def post(self):
        json_data = self.request.body
        data = json.loads(json_data) 

        expense = Expense()
        expense.userID = users.get_current_user().user_id()
        expense.amount = int(data['amount'])
        expense.desc = str(data['desc'])
        expense.tags = map(str.lower, map(str.strip, map(str, data['tags'].split(','))))
        expense.put()

        self.response.out.write(json.dumps({
            'added':int(data['amount']),
            'id':expense.key.id()}))
        self.response.out.http_status_message(200)
示例#17
0
    def get(self):
        user = users.get_current_user()

        if user:
            current = datetime.datetime.strptime("01/" + str(datetime.datetime.now().strftime("%m/%Y")), '%m/%d/%Y').date()
            expenses = Expense.query(Expense.userID == user.user_id(), Expense.date >= current).fetch()
            total = sum([expense.amount for expense in expenses])

            template_values = {
                'totalThisMonth': "{0:.2f}".format(total * 1.0/100)
            }

            template = jinja_environment.get_template('index.html')
            self.response.write(template.render(template_values))
        else:
            template = jinja_environment.get_template('login.html')
            self.response.write(template.render())
示例#18
0
    def get(self):
        user = users.get_current_user()

        if user:
            expenses = Expense.query(Expense.userID == user.user_id()).fetch()
            
            for expense in expenses:
                expense.tags = map(str, expense.tags)

            template_values = {
                'expenses': expenses,
            }

            template = jinja_environment.get_template('stats.html')
            self.response.write(template.render(template_values))

        else:
            template = jinja_environment.get_template('login.html')
            self.response.write(template.render())
示例#19
0
    def post(self):
        user = users.get_current_user()

        if user:            
            json_data = self.request.body
            data = json.loads(json_data) 
            localExps = data['localDB'] 

            expenses = Expense.query(Expense.userID == user.user_id()).fetch()

            deletedExpenses = []
            newExpenses = []
            expensesEIDs = []

            for expense in expenses:
                expensesEIDs.append(int(expense.key.id()))
                if int(expense.key.id()) not in localExps:
                    j = {
                        'amount': expense.amount,
                        'desc': expense.desc,
                        'date': str(expense.date),
                        'tags': expense.tags,
                        'keyId': long(expense.key.id())
                    }
                    newExpenses.append(j)

            for eid in localExps:
                if eid not in expensesEIDs:
                    deletedExpenses.append(eid)

            data = {
                'newExpenses' : newExpenses,
                'deletedExpenses' : deletedExpenses
            }
                
            self.response.write(json.dumps(data))
示例#20
0
 def func():
     return Expense(db).download_expenses(identifier)
示例#21
0
 def db_query():
     data = request.json
     return Expense(db).store_expense(data)
示例#22
0
 def db_query():
     return Expense(db).get_user_expenses(identifier)
示例#23
0
from flask import Flask, jsonify, request

from models.expense import Expense, ExpenseSchema
from models.income import Income, IncomeSchema
from models.transaction_type import TransactionType

app = Flask(__name__)

transactions = [
    Income('Salary', 5000),
    Income('Dividends', 200),
    Expense('pizza', 50),
    Expense('Rock Concert', 100)
]


@app.route('/incomes')
def get_incomes():
    schema = IncomeSchema(many=True)
    incomes = schema.dump(
        filter(lambda t: t.type == TransactionType.INCOME, transactions))
    return jsonify(incomes.data)


@app.route('/incomes', methods=['POST'])
def add_income():
    income = IncomeSchema().load(request.get_json())
    transactions.append(income.data)
    return "", 204

 def get(self):
     expenses = Expense.get_all()
     data = [expense.data for expense in expenses]
     return {'expenses': data}, HTTPStatus.OK
 def get(self, year, month):
     expenses = Expense.get_by_year_and_month(year, month)
     data = [expense.data for expense in expenses]
     return {'expenses': data}, HTTPStatus.OK
 def get(self, year):
     expenses = Expense.get_by_year(year)
     data = [expense.data for expense in expenses]
     return {'expenses': data}, HTTPStatus.OK