Example #1
0
    def post(self):
        """
        Add expense
        """
        try:

            data = request.get_json(force=True)

            email = data['email']
            amount = data['amount']
            date = data['date']
            description = data['description']
            comments = data['comments']
            payor = data['payor']

            exp: Expense = Expense(user_id=email, amount=amount, date=date, description=description, comments=comments,
                                   payor=payor)
            repository.add_expense(exp)

            return ReturnDocument(exp.id, "success").asdict()

        except RepositoryException as err:
            return ReturnDocument(err.__doc__, "error").asdict()
        except KeyError as err:
            return ReturnDocument(f"{err.__str__()}-{err.__doc__}", "error").asdict()
        except ValueError as err:
            return ReturnDocument(f"{err.__str__()}-{err.__doc__}", "error").asdict()
Example #2
0
def image_handler(update: Update, context: CallbackContext):
    # the last image in the list is the original size sent
    # use the first image if you want a smaller size
    image = [photo.get_file() for photo in update.message.photo][-1]

    im = io.BytesIO(image.download_as_bytearray())
    res = _parse_receipt(im)

    prediction = res["predictions"][0]
    date = prediction["date"]["raw"]
    date = parser.parse(date).date()
    amount = float(prediction["total"]["amount"])
    merchant = prediction["merchant"]["name"]
    Expense.create(amount=amount, purchase_date=date, merchant=merchant)

    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=
        f"Success! Receipt from {merchant} for {amount} Euros has been processed",
    )
Example #3
0
def generate():
    catid = random.randrange(0, len(mdata) - 1)
    expid = random.randrange(0, len(mdata[catid]['list']) - 1)
    try:
        db.session.add(
            Expense(category=mdata[catid]['cat'],
                    amount=random.randrange(100, 500),
                    comment=mdata[catid]['list'][expid]))
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(f'DB ERROR : {str(e)}', file=sys.stderr)
    return redirect('/')
Example #4
0
async def send_expense(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        category = data.get('category')
        amount = message.text.split(' ')[0]
        comment = ' '.join(message.text.split(' ')[1:])

    await dp['db'].create_expense(Expense(
        category=category,
        amount=amount,
        comment=comment,
    ))

    await message.answer(text=text('Успешно добавлено ' + bold(amount) + ' рублей в категорию ' + bold(category), 'Вы можете продолжать добавлять расходы в эту категорию или выбрать другую.', sep='\n\n'), reply_markup=dp['kb'].budget_success())
Example #5
0
def create_expense(user_id, tag_id):
    """
    Returns: dictionary with (key) success/failure and (key) the expense created
    Refer to serialize in db.py to see how expenses are formatted

    Parameter user_id: the id of the specific user that will add this expense to their account
    Parameter tag_id: the id of the tag that is to be linked to this expense

    Adds an expense to a user's log
    """
    user = User.query.filter_by(id=user_id).first()
    #user = User.query.get(user_id)
    if not user:
        return json.dumps({'success': False, 'error': 'User not found!'}), 404

    # grabs data needed to create budget
    post_body = json.loads(request.data)
    title = post_body.get('title', '')
    amount = post_body.get('amount', 0.0)
    description = post_body.get('description', '')
    date = post_body.get('date', '')
    #tag = post_body.get('tag', 0)

    # creates an expense log
    expense = Expense(title=title,
                      amount=amount,
                      description=description,
                      date=date,
                      tag_id=tag_id)
    # for tag in tags:
    #     expense.tags.append(Tag.query.filter_by(id=tag).first())

    user.expenses.append(expense)
    db.session.add(expense)
    db.session.commit()
    return json.dumps({'success': True, 'data': expense.serialize()}), 201
Example #6
0
def report_handler(update: Update, context: CallbackContext):
    """ Get full report of expenses """

    Expense.select(fn.SUM(Expense.amount)).scalar()
    context.bot.send_message(chat_id=update.effective_chat.id, text="")
Example #7
0
def total_handler(update: Update, context: CallbackContext):
    """ Return the total spent so far """
    total = Expense.select(fn.SUM(Expense.amount)).scalar()
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text=f"Total amount : {total}")