Exemplo n.º 1
0
 def test_crud_create_read_multiple_json(self):
     with self.app_context():
         itm1 = ItemModel("2", "U00000001", "Details of an order 😂")
         itm2 = ItemModel(3, "U00000002", "Details of an order")
         # Field 'id' is assigned at write to the db
         itm1.save_to_db()
         self.assertEqual(itm1.id, 1)
         itm2.save_to_db()
         self.assertEqual(itm2.id, 2)
         found_itm2 = ItemModel.find_all_by_order_uuid(2)
         found_itm3 = ItemModel.find_all_by_order_uuid(3)
         # order_id is not written to json
         expected_json2 = {
             "id": 1,
             "user_id": "U00000001",
             "details": "Details of an order 😂"
         }
         expected_json3 = {
             "id": 2,
             "user_id": "U00000002",
             "details": "Details of an order"
         }
         self.assertEqual(len(found_itm2), 1)
         self.assertEqual(len(found_itm3), 1)
         self.assertDictEqual(found_itm2[0].json(), expected_json2)
         self.assertDictEqual(found_itm3[0].json(), expected_json3)
Exemplo n.º 2
0
 def post(self):
     result_dict, err_code = handle_request_validation_and_serialisation(
         item_creation_schema)
     if err_code:
         return result_dict, err_code
     with db.session.no_autoflush:
         item = ItemModel(**result_dict)
         if not item.categories:
             return {
                 "message": f'Item must have at lest one category.'
             }, 400
         for cat in item.categories:
             c_id = cat.id
             if not ItemCategoryModel.find_by_id(c_id):
                 return {
                     "message":
                     f"Category with id: {c_id} does not exists. "
                     f"Item's category id's must exist before the item can be created. "
                     f"Create this category and try again."
                 }, 404
     try:
         item.add_to_db()
     except IntegrityError:
         return {
             "message":
             "An integrity error has occurred while adding to the database."
         }, 400
     return {
         "message": "Entry successfully created.",
         "entry": item_schema.dump(item)
     }, 201
Exemplo n.º 3
0
 def test_json_details_empty(self):
     with self.app_context():
         # Details field is empty string
         itm = ItemModel(4, "U00000003", "")
         jsonres = itm.json()
         self.assertEqual(jsonres['user_id'], "U00000003")
         self.assertEqual(jsonres['details'], "")
         self.assertEqual(len(jsonres), 3)
Exemplo n.º 4
0
 def test_json_with_id(self):
     with self.app_context():
         itm = ItemModel(4, "U00000004", "Details of an order")
         itm.save_to_db()
         jsonres = itm.json()
         expected_json = {
             "id": 1,
             "user_id": "U00000004",
             "details": "Details of an order"
         }
         self.assertDictEqual(jsonres, expected_json)
Exemplo n.º 5
0
    def put(self, name):

        data = Item.parser.parse_args()

        item = ItemModel.find_by_name(name)

        if item is None:
            ItemModel(name, **data)
        else:
            item.price = data['price']
            item.store_id = data['store_id']

        item.add_to_db()
        return item.json()
Exemplo n.º 6
0
 def put(self, name):
     data = request.get_json()
     try:
         data_json = ItemPostSchema().load(data)
     except ValidationError as err:
         return err.messages
     item = ItemModel.find_by_name(name)
     if item:
         item.price = data_json["price"]
         item.store_id = data_json["store_id"]
     else:
         item = ItemModel(name, data_json["price"], data_json["store_id"])
     item.save_to_db()
     return {"message": "item was succesfully created/updated"}, 201
Exemplo n.º 7
0
 def delete(self, name):
     data_request = Item.parser.parse_args()
     item = ItemModel.find_by_name(name)
     if item:
         item.delete()
         return {"message": "your item was deleted"}
     return {"message": "there is no such a item."}
Exemplo n.º 8
0
 def put(self, name):
     data = Item.parser.parse_args()
     item = ItemModel.getItem(name)
     if item is None:
         item = ItemModel(name, data['price'], data['store_id'])
     else:
         item.price = data['price']
         item.store_id = data['store_id']
     item.save_to_db()
     return item.json()
Exemplo n.º 9
0
 def delete(self):
     try:
         item = item_schema.load(request.get_json())
     except ValidationError as err:
         return err.messages, 400
     name = item.name
     item_check = ItemModel.find_by_name(name)
     if item_check:
         item_check.delete_from_db()
         return {"msg": "Item deleted successfully"}
     return {"msg": "Item not found"}, 404
Exemplo n.º 10
0
    def delete(self, name):
        item = ItemModel.find(name)
        if not item:
            return {"item": None}, 404

        try:
            item.delete()
        except:
            return {"message": "An error occurred deleting the item"}, 500

        return {"message": "Item deleted"}
Exemplo n.º 11
0
 def test_crud_create_read_delete(self):
     with self.app_context():
         itm = ItemModel("0001", "U00000000", "Details of an order")
         self.assertListEqual(
             ItemModel.find_by_order_uuid_and_user_id(order_uuid="1",
                                                      user_id="U00000000"),
             [])
         itm.save_to_db()
         self.assertEqual(
             len(
                 ItemModel.find_by_order_uuid_and_user_id(
                     order_uuid="1", user_id="U00000000")), 1)
         itm.delete_from_db()
         self.assertListEqual(
             ItemModel.find_by_order_uuid_and_user_id(order_uuid="1",
                                                      user_id="U00000000"),
             [])
Exemplo n.º 12
0
def _validate_items_existence(elements: List[OrderElementModel]) -> List[int]:
    """
    Validates the existence of item_id for every order element.

    Returns: List of nonexistent items.
    """
    invalid_elements = []
    with db.session.no_autoflush:
        for elem in elements:
            if not ItemModel.find_by_id(elem.item_id):
                invalid_elements.append(elem.item_id)
    return invalid_elements
Exemplo n.º 13
0
 def post(self, name):
     if ItemModel.getItem(name):
         return {"message": "item already exists"}, 400
     data = Item.parser.parse_args()
     item = ItemModel(name, data['price'], data['store_id'])
     item.save_to_db()
     return item.json(), 201
Exemplo n.º 14
0
 def test_crud_create_read_delete_multi(self):
     with self.app_context():
         itm = ItemModel("2", "U00000001", "Details of an order 😂")
         self.assertListEqual(
             ItemModel.find_by_order_uuid_and_user_id(order_uuid="2",
                                                      user_id="U00000001"),
             [])
         itm.save_to_db()
         self.assertEqual(
             len(
                 ItemModel.find_by_order_uuid_and_user_id(
                     order_uuid="2", user_id="U00000001")), 1)
         found_item = ItemModel.find_by_order_uuid_and_user_id(
             order_uuid="2", user_id="U00000001")[0]
         self.assertEqual(found_item.order_id, 2)
         self.assertEqual(found_item.user_id, "U00000001")
         self.assertEqual(found_item.details, "Details of an order 😂")
         itm.delete_from_db()
         self.assertListEqual(
             ItemModel.find_by_order_uuid_and_user_id(order_uuid="2",
                                                      user_id="U00000001"),
             [])
Exemplo n.º 15
0
    def get(self):
        try:
            data = item_schema.load(request.get_json())
            print(data.name)
        except ValidationError as err:
            return err.messages, 400
        print(data)
        name = data.name
        item = ItemModel.find_by_name(name)

        if item:
            return item_schema.dump(item)
        return {"msg": "Item not found"}
Exemplo n.º 16
0
    def put(self, name):
        payload = ItemController.parser.parse_args()
        item = ItemModel.find_by_name(name)
        if item is None:
            item = ItemModel(name, **payload)
        else:
            item.price = payload.get('price')

        item.save_to_db()

        return item.json()
Exemplo n.º 17
0
    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")
        order.change_status("success")

        return order_schema.dump(order)
Exemplo n.º 18
0
	def put(self, name):
		data = Item.parser.parse_args()

		item = ItemModel.find_by_name(name)

		if not item:
			item = ItemModel(name, **data)
		else:
			item.price = data["price"]
		item.save_to_db()
		return item.json()
Exemplo n.º 19
0
    def put(self, name):
        data = Item.parser.parse_args()

        item = ItemModel.find(name)
        if not item:
            item = ItemModel(name, **data)
        else:
            item.price = data["price"]
            item.store_id = data["store_id"]

        try:
            item.save()
            return item.json()
        except:
            return {"message": "An error occurred updating the item"}, 500
Exemplo n.º 20
0
    def put(self, name):
        data_request = Item.parser.parse_args()
        item = ItemModel.find_by_name(name)
        # updated_item = ItemModel(name, data_request["price"])

        if not item:
            item = ItemModel(name=name, **data_request)

        else:
            item.price = data_request["price"]
        item.save_to_db()
        return item.json()
Exemplo n.º 21
0
    def put(self, name):
        req = Item.parser.parse_args()

        i = ItemModel.get_item_by_name(name)
        if i is None:
            i = ItemModel(name, req['price'])
        else:
            i.price = req['price']

        i.save_to_db()

        return i.json(), 201
Exemplo n.º 22
0
    def post(cls):
        data= request.get_json()
        items=[]
        ordered_list = data['items'] # list of dictionaries

        for ordered_item in data['items']:
            name = ordered_item['name']
            count = ordered_item['qty']
            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")
        order.change_status("success")

        return order_schema.dump(order)
Exemplo n.º 23
0
    def get(self, name):
        """Get specific item
        :endpoint: /item/<item name>

        :param name: item name
        :type name: str
        :return: item name and item price
        :rtype: JSON
        """
        item = ItemModel.find_by_name(name)
        if item:
            return item.json(), 200

        return {"Message": "Item did not exists."}, 404
Exemplo n.º 24
0
    def put(self):
        data = request.get_json()
        name = data["name"]
        price = data["price"]

        item = ItemModel.find_by_name(name)

        if item:
            item.price = price
        else:
            return item.json()

        item.save_to_db()

        return item_schema.dump(item), 200
Exemplo n.º 25
0
 def test_crud_create_read_query_uuid_type(self):
     # Check if query method can handel uuid of both types
     with self.app_context():
         itm = ItemModel(3, "U00000002", "Details of an order")
         itm.save_to_db()
         found_item_str = ItemModel.find_by_order_uuid_and_user_id(
             order_uuid="3", user_id="U00000002")[0]
         found_item_int = ItemModel.find_by_order_uuid_and_user_id(
             order_uuid=3, user_id="U00000002")[0]
         self.assertEquals(found_item_int.order_id, found_item_str.order_id)
Exemplo n.º 26
0
    def put(self, name, category, unit):
        data = Item.parser.parse_args()

        item = ItemModel.find_by_name(name)

        if item is None:
            item = ItemModel(name, **data)
        else:
            item.category = data['category']
            item.unit = data['unit']

        item.save_to_db()

        return item.json
Exemplo n.º 27
0
    def delete(self, name):
        #FIXME:
        """Delete specific item
        :note:
            What ever item is exists or not.

        :param name: item name
        :type name: str
        :return:  
        :rtype: JSON
        """
        item = ItemModel.find_by_name(name)
        if item:
            item.delete()

        return {'Message': "Delete Successful!"}, 200
Exemplo n.º 28
0
	def post(self, name):
		if ItemModel.find_by_name(name):
			return {"message":f"An item with name {name} already exists."}, 400 # 400: something wrong with the request
		data = Item.parser.parse_args()
		item = ItemModel(name, **data)
		try:
			item.save_to_db()
		except Exception as e:
			return {"message":"An error occurred inserting the item."}, 500 # 500: internal server error

		return item.json(), 201
Exemplo n.º 29
0
    def post(self, name):
        if ItemModel.find(name):
            return {"message": "Item {} already exists.".format(name)}, 400

        data = Item.parser.parse_args()
        item = ItemModel(name, **data)

        try:
            item.save()
            return item.json()
        except:
            return {"message": "An error occurred creating the item"}, 500
Exemplo n.º 30
0
    def post(self, name):
        if ItemModel.find_by_name(name):
            return {"message": "An item with the name {} already exists".format(name)}, 400

        payload = ItemController.parser.parse_args()
        item = ItemModel(name, **payload)
        try:
            item.save_to_db()
        except:
            return {"message": "An error ocurred while inserting the item"}, 500

        return item.json(), 201