예제 #1
0
    def transfer_post(self):

        form = TranferForm()

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                cat_from = Category.get_by_id(form.from_id.data)
                cat_to = Category.get_by_id(form.to_id.data)

                if not cat_from or not cat_to:
                    raise Exception(_('CATEGORY_TRANSFER_POSTS_CHECK_FAILED'))

                Category.transfer_posts(cat_from, cat_to)

                message = _('CATEGORY_TRANSFER_POSTS_SUCCESS',
                            from_name=cat_from.name,
                            to_name=cat_to.name)

                return render_view(url_for('CategoriesView:index'),
                                   message=message,
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/transfer.html',
                           form=form)
예제 #2
0
    def transfer_post(self):

        form = TranferForm()

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                cat_from = Category.get_by_id(form.from_id.data)
                cat_to = Category.get_by_id(form.to_id.data)

                if not cat_from or not cat_to:
                    raise Exception(_('CATEGORY_TRANSFER_POSTS_CHECK_FAILED'))

                Category.transfer_posts(cat_from, cat_to)

                message = _('CATEGORY_TRANSFER_POSTS_SUCCESS',
                            from_name=cat_from.name,
                            to_name=cat_to.name)

                return render_view(url_for('CategoriesView:index'),
                                   message=message,
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/transfer.html', form=form)
예제 #3
0
def manage_categoryitem(categoryitem_id=None, type_op=1):
    """
    Manage category item CRUD

    Args:
        param1: category item id
        param2: operation type (1 -> read, 2 -> new, 3 -> update, 4 -> delete)
    """
    item = CategoryItem.by_id(categoryitem_id)

    if item is None and type_op != 2:
        flash(_('no_found_rows'))

    if type_op == 4:
        db.session.delete(item)
        db.session.commit()
        flash(_('item_deleted_successfully'))
        return redirect(url_for('show_categories'))

    form = CategoryItemForm(request.form)
    form.category_id.choices = [(c.id, c.name) for c in Category.query.all()]
    form.brand_id.choices = [(b.id, b.name) for b in Brand.query.all()]

    if item is not None and request.method == 'GET':
        form.name.data = item.name
        form.description.data = item.description
        form.price.data = item.price
        form.category_id.data = item.category_id
        form.brand_id.data = item.brand_id

    if request.method == 'POST' and form.validate():
        if categoryitem_id is not None:
            item.name = form.name.data
            item.description = form.description.data
            item.price = form.price.data
            item.category = Category.get_by_id(id=form.category_id.data)
            item.brand = Brand.get_by_id(id=form.brand_id.data)
            item.user = User.get_by_id(login_session['user_id'])
            flash(_('item_updated_successfully'))
        else:
            item = CategoryItem(
                name=form.name.data,
                description=form.description.data,
                price=form.price.data,
                category=Category.get_by_id(id=form.category_id.data),  # noqa
                brand=Brand.get_by_id(id=form.brand_id.data),  # noqa
                user=User.get_by_id(login_session['user_id']))  # noqa
            flash(_('item_added_successfully'))
        db.session.add(item)
        db.session.commit()
        return redirect(
            url_for('show_categoryitem_read', categoryitem_id=item.id))  # noqa

    return render_template('categoryitem.html',
                           item=item,
                           type_op=type_op,
                           form=form)
예제 #4
0
    def transfer_post(self):
        trans = TranferCatForm()
        if trans.validate_on_submit():
            cat_from = Category.get_by_id(trans.from_id.data)
            cat_to = Category.get_by_id(trans.to_id.data)

            if cat_from and cat_to:
                Category.transfer_posts(cat_from, cat_to)
                flash(
                    gettext(
                        "The posts were transfered from %(from_name)s to %(to_name)s",
                        from_name=cat_from.name,
                        to_name=cat_to.name,
                    )
                )
            else:
                flash(gettext("Either category was not found"), "error")
        else:
            flash(trans.get_errors(), "error")

        return redirect(url_for("CategoriesView:index"))
예제 #5
0
    def delete(self, id):
        category = Category.get_by_id(id)

        try:
            if category is None:
                raise Exception(_('CATEGORY_NOT_FOUND'))

            if not category.can_edit():
                abort(401)

            if not Category.transfer_posts(category):
                raise Exception(_('CATEGORY_TRANSFER_POSTS_FAILED'))

            name = category.name
            Category.delete(category.id)

            flash(_('CATEGORY_REMOVE_SUCCESS', name=name))
        except Exception as e:
            flash(e.message, 'error')

        return render_view(url_for('CategoriesView:index'), redirect=True)
예제 #6
0
    def delete(self, id):
        category = Category.get_by_id(id)

        try:
            if category is None:
                raise Exception(_('CATEGORY_NOT_FOUND'))

            if not category.can_edit():
                abort(401)

            if not Category.transfer_posts(category):
                raise Exception(_('CATEGORY_TRANSFER_POSTS_FAILED'))

            name = category.name
            Category.delete(category.id)

            flash(_('CATEGORY_REMOVE_SUCCESS', name=name))
        except Exception as e:
            flash(e.message, 'error')

        return render_view(url_for('CategoriesView:index'),
                           redirect=True)
예제 #7
0
    def put(self, id):
        category = Category.get_by_id(id)

        if category is None:
            return render_view(url_for('CategoriesView:index'),
                               status=False,
                               redirect=True,
                               message=_('CATEGORY_NOT_FOUND'))

        if not category.can_edit():
            abort(401)

        form = CategoryForm(category=category)

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                if not form.slug.data:
                    form.slug.data = form.name.data

                if category.slug != form.slug.data:
                    form.slug.data = Category.urlify(form.slug.data)

                form.populate_obj(category)
                category.save()

                return render_view(url_for('CategoriesView:put',
                                           id=category.id),
                                   message=_('CATEGORY_SAVE_SUCCESS'),
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/edit.html',
                           form=form,
                           category=category)
예제 #8
0
    def delete(self, id):
        category = Category.get_by_id(id)
        if category is None:
            flash(gettext("The category was not found"), "error")
            return redirect(url_for("CategoriesView:index"))
        if not category.can_edit():
            abort(401)

        try:
            if not Category.transfer_posts(category):
                return util.redirect_json_or_html(
                    url_for("CategoriesView:index"), "category", gettext("Sorry, the last category can not be removed")
                )

            name = category.name
            Category.delete(category.id)
            flash(gettext('The category "%(name)s" was removed', name=name))
        except:
            return util.redirect_json_or_html(
                url_for("CategoriesView:index"), "category", gettext("Error while removing the category")
            )

        return util.redirect_json_or_html(url_for("CategoriesView:index"), "category")
예제 #9
0
    def put(self, id):
        category = Category.get_by_id(id)
        if category is None:
            flash(gettext("The category was not found"), "error")
            return redirect(url_for("CategoriesView:index"))
        if not category.can_edit():
            abort(401)

        if request.method in ["POST", "PUT"]:
            form = CategoryForm()
            if form.validate_on_submit():
                try:
                    form.populate_obj(category)
                    category.save()
                    flash(gettext("Category was succesfully saved"))
                    return util.redirect_json_or_html(url_for("CategoriesView:index"), "category")
                except:
                    return util.redirect_json_or_html(
                        url_for("CategoriesView:index"), "category", gettext("Error while updating the category")
                    )
            else:
                if request.is_xhr:
                    return util.redirect_json_or_html(
                        url_for("CategoriesView:index"),
                        "category",
                        gettext("Invalid submission, please check the message below"),
                    )
                else:
                    flash(gettext("Invalid submission, please check the message below"), "error")
        else:
            form = NewCategoryForm(category)
        return render_template(
            "admin/categories/edit.html",
            title=gettext("Edit Category: %(name)s", name=category.name),
            form=form,
            category=category,
        )
예제 #10
0
    def put(self, id):
        category = Category.get_by_id(id)

        if category is None:
            return render_view(url_for('CategoriesView:index'),
                               status=False,
                               redirect=True,
                               message=_('CATEGORY_NOT_FOUND'))

        if not category.can_edit():
            abort(401)

        form = CategoryForm(category=category)

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                if not form.slug.data:
                    form.slug.data = form.name.data

                if category.slug != form.slug.data:
                    form.slug.data = Category.urlify(form.slug.data)

                form.populate_obj(category)
                category.save()

                return render_view(url_for('CategoriesView:put', id=category.id),
                                   message=_('CATEGORY_SAVE_SUCCESS'),
                                   redirect=True)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/categories/edit.html',
                           form=form,
                           category=category)
예제 #11
0
    def post(self):
        """
        @api {POST} /api/v1/categories Create category for an account
        @apiVersion 0.0.1
        @apiName CreateCategory
        @apiGroup Categories
        @apiDescription Create a category for an account

        @apiHeader {String} Authorization Users auth token
        @apiHeader {String} Content-Type="application/json" Content-Type (should be application/json for every post requests)

        @apiHeaderExample {json} Header-Example:
        {
            "Authorization": "Bearer auth_token_here"
        }

        @apiParam {Number} acc_id Account ID
        @apiParam {String} name Category name
        @apiParam {String} type Category type
        @apiParam {Number=null} parent_id Parent category ID (omit if no parent)

        @apiParamExample {json} Request-Example:
        {
            "acc_id": 1,
            "name": "Cat",
            "type": "expense"
        }

        @apiParamExample {json} Request-Example with parent_id:
        {
            "acc_id": 1,
            "parent_id": 1,
            "name": "Dog meat",
            "type": "expense"
        }

        @apiSuccess (Success) {String} status Status
        @apiSuccess (Success) {String} message Message

        @apiSampleRequest /api/v1/transactions

        @apiExample cURL example
        $ curl -H "Content-Type: application/json" -H "Authorization": "Bearer auth_token_here" -X POST
            -d '{"acc_id": 1, "name": "Cat", "type": "expense"}'
            http://ec2-35-153-68-36.compute-1.amazonaws.com/api/v1/categories

        @apiSuccessExample {json} Success-Response:
            HTTP/1.0 200 OK
            {
                "message": "Successfully created new category",
                "status": "success"
            }
        """
        ctx = _request_ctx_stack.top
        current_user = ctx.user
        request_body = request.get_json()
        acc_id, parent_id, name, type = get_dict_value_by_key(
            request_body, 'acc_id', 'parent_id', 'name', 'type')
        account = Account.get_by_id(acc_id, current_user.id)
        if account is None:
            return response('failed', 'This account belongs to another user',
                            401)
        new_category = Category.create(name, type.lower(), acc_id)
        if parent_id:
            parent_category = Category.get_by_id(parent_id)
            parent_category.children.append(new_category)
        try:
            new_category.save()
        except IntegrityError:
            return response('failed', 'Duplicate category name', 400)
        else:
            return response('success', 'Successfully created new category',
                            200)
예제 #12
0
    def post(self):
        """
        @api {POST} /api/v1/transactions Create transaction for an account
        @apiVersion 0.0.1
        @apiName CreateTransaction
        @apiGroup Transactions
        @apiDescription Create a transaction for an account

        @apiHeader {String} Authorization Users auth token
        @apiHeader {String} Content-Type="application/json" Content-Type (should be application/json for every post requests)

        @apiHeaderExample {json} Header-Example:
        {
            "Authorization": "Bearer auth_token_here"
        }

        @apiParam {Number} acc_id Account ID
        @apiParam {Number} cat_id Category ID
        @apiParam {String} created_at Create time
        @apiParam {String} note Note
        @apiParam {Number} amount Amount

        @apiParamExample {json} Request-Example:
        {
            "acc_id": 13,
            "cat_id": 20,
            "created_at": "2018-12-14T03:55",
            "note": "note",
            "amount": 60000000
        }

        @apiSuccess (Success) {String} created_at Date created
        @apiSuccess (Success) {Number} pre_bal Pre-transaction balance
        @apiSuccess (Success) {Number} post_bal Post-transaction balance
        @apiSuccess (Success) {String} category Category
        @apiSuccess (Success) {String} note Note
        @apiSuccess (Success) {Number} amount Amount
        @apiSuccess (Success) {String} status Status
        @apiSuccess (Success) {String="expense","income"} type Transaction type

        @apiSampleRequest /api/v1/transactions

        @apiExample cURL example
        $ curl -H "Content-Type: application/json" -H "Authorization": "Bearer auth_token_here" -X POST
            -d '{"acc_id": 13, "cat_id": 20, "note": "note", "amount": 60000000}'
            http://ec2-35-153-68-36.compute-1.amazonaws.com/api/v1/transactions

        @apiSuccessExample {json} Success-Response:
            HTTP/1.0 200 OK
            {
                "amount": 60000000,
                "category": "Salary",
                "created_at": "2018-12-14T03:55:00",
                "note": "note",
                "pre_bal": 40000,
                "post_bal": 60040000,
                "status": "success",
                "type": "income"
            }
        """
        ctx = _request_ctx_stack.top
        current_user = ctx.user
        request_body = request.get_json()
        acc_id, cat_id, created_at, note, amount = get_dict_value_by_key(
            request_body, 'acc_id', 'cat_id', 'created_at', 'note', 'amount')
        try:
            account = Account.get_by_id(acc_id, current_user.id)
            if account is None:
                return response('failed',
                                'This account belongs to another user', 401)
            category = Category.get_by_id(cat_id)
            cur_bal = account.get_current_balance()
            post_bal = account.update_balance(category.type, amount)
        except ValueError:
            return response(
                'failed',
                'Failed to create transaction, please check your balance', 400)
        else:
            new_transaction = Transaction.create(
                account_id=acc_id,
                category_id=cat_id,
                created_at=created_at,
                transaction_type=category.type,
                note=note,
                amount=amount,
                pre_transaction_balance=cur_bal,
                post_transaction_balance=post_bal)
            new_transaction.save()
            return response_created_transaction(new_transaction, 200)