Exemplo n.º 1
0
def update_order(order_id):
    data = request.get_json()
    get_order = Order.query.get(order_id)
    if data.get('amount'):
        get_order.amount = data['amount']
    if data.get('products'):
        get_order.amount = data['products']
    get_order.createdAt = date()
    db.session.add(get_order)
    db.session.commit()
    order_schema = OrderSchema()
    order = order_schema.dump(get_order)
    return make_response(jsonify({"order": order}))
Exemplo n.º 2
0
def create_order():
    data = request.get_json()
    if 'products' in data:
        products = data['products']
        if not products:
            return make_response("empty order", 400)
        for product in products:
            r = requests.get(os.environ['INVENTORY_ADDRESS'] +
                             '/api/products/' + str(product['id']))
            if not r.json()['product']:
                return make_response("non existent product", 404)
            if r.json()['product']['stock'] < int(product['quantity']):
                return make_response(
                    "not enough stock for product" + str(product['id']), 400)
            new_stock = int(r.json()['product']['stock']) - int(
                product['quantity'])
            requests.put(os.environ['INVENTORY_ADDRESS'] + '/api/products/' +
                         str(product['id']),
                         json={'stock': str(new_stock)})
    order_schema = OrderSchema()
    order = order_schema.load(data)
    result = order_schema.dump(order.create())
    return make_response(jsonify({"order": result}), 200)
Exemplo n.º 3
0
class TestOrder(BaseTest):
    items_to_order = ItemsToOrderSchema()
    order_schema = OrderSchema()
    item_schema = ItemSchema()

    def setUp(self):
        BaseTest.setUp(self)
        with self.app_context():
            new_item = self.item_schema.load({
                "name": "test_name",
                "price": "22.43"
            })
            new_item1 = self.item_schema.load({
                "name": "test_name1",
                "price": "23.47"
            })
            new_item1.upsert_item()
            new_item.upsert_item()
            order = OrderModel(
                items_list=[
                    ItemsToOrders(item_id=1, quantity=3),
                    ItemsToOrders(item_id=2, quantity=2),
                ],
                status="pending",
            )
            order.save_to_db()

    def test_order(self):
        with self.app_context():
            print(self.order_schema.dump(OrderModel.find_all(), many=True))

    def test_set_status(self):
        with self.app_context():
            order1 = OrderModel.find_by_id(1)
            order1.set_status("failed")
            self.assertEqual("failed", order1.status)

    def test_amount(self):
        with self.app_context():
            order1 = OrderModel.find_by_id(1)
            self.assertEqual(11527, order1.amount)

    def test_description(self):
        with self.app_context():
            order1 = OrderModel.find_by_id(1)
            self.assertListEqual(["3 x test_name1", "2 x test_name"],
                                 order1.description)
Exemplo n.º 4
0
from collections import Counter
import stripe
from flask_restful import Resource
from flask import request
from models.item import ItemModel
from models.order import OrderModel, ItemsInOrder
from schemas.order import OrderSchema

order_schema = OrderSchema()
list_orders_schema = OrderSchema(many=True)


class Order(Resource):
    @classmethod
    def post(cls):
        """
        Expect a token and a list of item ids from the request body.
        Construct an order and talk to the Strip API to make a charge.
        """
        data = request.get_json(
        )  # token + list of item ids  [1, 2, 4, 4, 5, 2, 1, 1, 4]
        items = []
        item_id_quantities = Counter(data["item_ids"])

        # Iterate over items and retrieve them from the database
        for _id, count in item_id_quantities.most_common(
        ):  # [(1,3),(2,2),(4,3),(5,1)]
            item = ItemModel.find_by_id(_id)
            if not item:
                return {"message": "Item {} Not Found.".format(_id)}, 404
Exemplo n.º 5
0
from flask_restful import Resource
from flask import request
from model.item import ItemModel
from model.order import OrderModel, ItemsInOrder
from schemas.order import OrderSchema
from collections import Counter

order_schema = OrderSchema()


class Order(Resource):
    @classmethod
    def post(cls):
        data = request.get_json()
        items = []
        item_quantity = Counter(data["items"])

        for name, count in item_quantity.most_common():
            res = ItemModel.find_by_name(name)
            if not res:
                return {"msg": "Item not present {}".format(name)}, 404
            items.append(
                ItemsInOrder(item_id=ItemModel.find_id(name), quantity=count))
        print(items)

        order = OrderModel(items=items, status="pending")
        order.save_to_db()  #save orders to database

        order.change_status("failed")
        order.request_with_stripe()  #send the order details to stripe
        print("Payment Done")
Exemplo n.º 6
0
from collections import Counter
from flask import request
from flask_restful import Resource
from stripe import error

from libs.strings import gettext
from models.item import ItemModel
from models.order import OrderModel, ItemsInOrder
from schemas.order import OrderSchema

order_schema = OrderSchema()
multiple_order_schema = OrderSchema(many=True)


class Order(Resource):
    @classmethod
    def get(cls):
        # return multiple_order_schema.dump(OrderModel.find_all()), 200
        return order_schema.dump(OrderModel.find_all(), many=True), 200

    @classmethod
    def post(cls):
        """
        Expect a token and a list of item ids from the request body.
        Construct a order to talk with Strip API to make a charge.
        """
        data = request.get_json()  # token + list of item ids
        items = []
        item_id_quantities = Counter(data["item_ids"])

        #   iterate from list of items and retrieve from the database
Exemplo n.º 7
0
@app.route("/orders", methods=["GET"])
def route_order_get_all():
    orders = Order.query.all
    return jsonify({"orders":[i.as_dict() for i in orders()]})

@app.route("/orders/<int:order_id>", methods=["GET"])
def route_order_get_by_id(order_id):
    order = Order.query.filter(Order.id == order_id).first()
    if not order:
      return abort(400, "The order with id: {0} does not exists".format(order_id))
    return jsonify(order.as_dict())


@app.route("/orders", methods=["POST"])
@marshal_with(OrderSchema())
@use_kwargs(
    {
        "name": fields.Str(),
        "description": fields.Str(),
        "buyer_id": fields.Int(),
        "seller_id": fields.Int(),
        "lineitems": fields.List(fields.Dict(), required=True),
    }
)
def route_order_create(name, description, buyer_id, seller_id, lineitems):
    buyer = Company.query.filter(Company.id == buyer_id).first()
    seller = Company.query.filter(Company.id == seller_id).first()
    order_items = []
    order = Order(
        name=name,
Exemplo n.º 8
0
from flask_restful import Resource
from flask import request
from flask_jwt_extended import jwt_required, fresh_jwt_required
from models.order import OrderModel
from schemas.order import OrderSchema
from libs.strings import gettext

order_schema = OrderSchema()
order_list_schema = OrderSchema(many=True)


class Order(Resource):
    @classmethod
    def get(cls, name: str):
        order = OrderModel.find_by_name(name)
        if order:
            return order_schema.dump(order), 200

        return {"message": gettext("order_not_found")}, 404


class OrderList(Resource):
    @classmethod
    def get(cls):
        return {"items": order_list_schema.dump(OrderModel.find_all())}, 200
Exemplo n.º 9
0
from collections import Counter
from flask import request
from flask_restful import Resource
from stripe import error

from models.item import ItemModel
from models.order import OrderModel, ItemsInOrder
from schemas.order import OrderSchema

orderSchema = OrderSchema()
orderListSchema = OrderSchema(many=True)


class Order(Resource):
    @classmethod
    def post(cls):
        """
        Expects a token and a list of item ids from the request body.
        Constructs an order and talks to the Stripe API to make a charge.
        """
        data = request.get_json()
        items = []
        item_id_quantities = Counter(data["items_id"])

        for _id, count in item_id_quantities.most_common():
            item = ItemModel.find_by_id(_id)

            if not item:
                return {"message": f"Item {_id} Not Found."}, 404

            items.append(ItemsInOrder(item_id=_id, quantity=count))
Exemplo n.º 10
0
def get_orders_by_user(user_id):
    get_orders = Order.query.filter(Order.idUser == user_id)
    order_schema = OrderSchema(many=True)
    orders = order_schema.dump(get_orders)
    return make_response(jsonify({"orders": orders}))
Exemplo n.º 11
0
def get_one_order(order_id):
    get_order = Order.query.get(order_id)
    order_schema = OrderSchema()
    order = order_schema.dump(get_order)
    return make_response(jsonify({"order": order}))
Exemplo n.º 12
0
def get_all_orders():
    get_orders = Order.query.all()
    order_schema = OrderSchema(many=True)
    orders = order_schema.dump(get_orders)

    return make_response(jsonify({"orders": orders}))