Exemplo n.º 1
0
    def post(self):
        result_dict, err_code = handle_request_validation_and_serialisation(
            order_creation_schema)
        if err_code:
            return result_dict, err_code

        if not result_dict['elements']:
            return {
                "message":
                "Cannot create an empty order. The order must have at least one element."
            }, 400

        elements = result_dict['elements']
        result_dict['elements'] = []
        order = OrderModel(**result_dict)

        if not UserModel.find_by_id(order.user_id):
            return {
                "message":
                f"User with id: {order.user_id} does nor exist. "
                f"Cannot create an order for nonexistent user."
            }, 400

        elements = [
            OrderElementModel(**order_element_creation_schema.load(e))
            for e in elements
        ]
        if err_msg := _validate_order_elements(elements):
            return err_msg, 400
Exemplo n.º 2
0
 def put(self,_id):
     value = self.parser.parse_args()
     order = OrderModel.find_by_id(_id)
     if order is not None:
         order.menu = value['menu']
         order.res = value['res']
         order.userid = value['userid']
         order.save_to_db()
         return order.json()
     return {'msg','no user'},400
Exemplo n.º 3
0
def checkOrderStatus(orderId):
    order = OrderModel.get(orderId)
    if order is None:
        raise Exception('order data does not exists!')
    
    result = {
        'orderStatus': order.orderStatus,
        'transactionStatus': order.transactionStatus
    }
    return result
def handler(event, context):
    print(event)

    orderId = event['orderId']
    order = OrderModel.get(orderId)

    if order is None:
        raise Exception('order data does not exists!')

    else:
        order.update(
            actions=[OrderModel.orderStatus.set(OrderStatusEnum.FAILED)])
        return 'order cancelled'
Exemplo n.º 5
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.º 6
0
def handler(event, context):
    print(event)

    orderId = event['orderId']
    order = OrderModel.get(orderId)

    if order is None:
        raise Exception('order data does not exists!')
    
    else:
        order.update(actions=[
            OrderModel.orderStatus.set(OrderStatusEnum.SUCCEEDED)
        ])
        return 'order successfully confirmed.'
Exemplo n.º 7
0
def handler(event, context):
    orderId = event['orderId']

    order = OrderModel.get(orderId)

    if order is None:
        raise Exception('order data does not exists!')

    else:
        order.update(actions=[
            OrderModel.orderStatus.set(OrderStatusEnum.FAILED),
            OrderModel.transactionStatus.set(TransactionStatusEnum.DONE)
        ])
        return 'order failed'
Exemplo n.º 8
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)
def handler(event, context):
    orderId = event['orderId']

    order = OrderModel.get(orderId)

    if order is None:
        raise Exception('order data does not exists!')

    sqs = boto3.resource('sqs')
    queue = sqs.get_queue_by_name(QueueName='jawsdays2020_demo_order_queue')
    response = queue.send_message(MessageBody=json.dumps(order.to_dict()))

    if response.get('MessageId'):
        return 'sending order confirm event'
    else:
        raise Exception('error sending message to sqs queue.')
Exemplo n.º 10
0
    def put(self, order_id: int):
        result_dict, err_code = handle_request_validation_and_serialisation(
            order_creation_schema)
        if err_code:
            return result_dict, err_code

        if not result_dict['elements']:
            return {
                "message":
                "The order cannot be empty. The order must have at least one element."
            }, 400

        order = OrderModel.find_by_id(order_id)
        if not order:
            return {
                "message": f"Order with id: {order_id} does not exist."
            }, 404

        new_elements = result_dict['elements']
        old_elements = [
            order_element_creation_schema.dump(e) for e in order.elements
        ]

        old_to_delete = [
            e['item_id'] for e in old_elements if e not in new_elements
        ]
        new_to_add = [e for e in new_elements if e not in old_elements]
        # useful for debugging purposes
        # print('O', old_elements)
        # print('N', new_elements)
        # print(old_to_delete)
        # print(new_to_add)

        # for x in order.elements:
        #     print(x.item_id in old_to_delete)

        old_to_delete = list(
            filter(lambda x: x.item_id in old_to_delete, order.elements))
        OrderElementModel.delete_all_from_db(old_to_delete)

        new_to_add = [
            OrderElementModel(**order_element_creation_schema.load(e))
            for e in new_to_add
        ]
        if err_msg := _validate_order_elements(new_to_add):
            return err_msg, 400
Exemplo n.º 11
0
    def post(self):
        vl = req.get_json()

        for value in vl:
            if not bool(value.get('orderId')) or not bool(value.get('proId')):
                return gettex('NOT_FOUND'),404

            isExistOrderId = OrderModel.findById(value['orderId'])
            isExistProId = ProductModel.findByProId(value['proId'])
            if not bool(isExistOrderId) or not bool(isExistProId):
                return gettex('NOT_FOUND'),404

        data = OrderHistorySchema(many=True).load(vl,session=db.session)
        try:
            OrderHistoryModel.insertMany(data)
        except:
            return gettex('SOMETHING_WRONG'),500

        return gettex('SUCCESS'),201
Exemplo n.º 12
0
    def put(self, order_id: int):
        result_dict, err_code = handle_request_validation_and_serialisation(
            order_update_schema)
        if err_code:
            return result_dict, err_code

        order = OrderModel.find_by_id(order_id)
        if not order:
            return {
                "message": f"Order with id: {order_id} does not exist."
            }, 400

        order.user_id = result_dict.get('user_id', order.user_id)
        order.status = result_dict.get('status', order.status)
        order.comments = result_dict.get('comments', order.comments)
        order.update_in_db()

        return {
            "message": f"The order with id: {order.id} updated successfully.",
            "entry": order_schema.dump(order)
        }, 200
Exemplo n.º 13
0
def startOrder(item):

    order = OrderModel()
    order.init()

    paymentIntent = stripe.PaymentIntent.create(
      amount=1099,
      currency='jpy',
      metadata={
        'orderId': str(order.id),
      },
    )
    
    order.paymentId = paymentIntent.id
    order.itemId = item['id']
    order.title = item['title']
    order.subtitle = item['subtitle']
    order.price = item['price']
    order.save()

    result = {}
    result['paymentIntent'] = paymentIntent
    result['order'] = order.to_dict()

    return result
Exemplo n.º 14
0
def db_populate():
    users = [
        UserModel(id=1,
                  name='Karol Krawczyk',
                  email='*****@*****.**'),
        UserModel(id=2, name='Monica Geller', email='*****@*****.**'),
        UserModel(id=3, name='Rachel Green', email='*****@*****.**'),
        UserModel(id=4, name='Paweł Okrutnik', email='*****@*****.**'),
        UserModel(id=5, name='Danuta Norek', email='*****@*****.**'),
    ]
    categories = [
        ItemCategoryModel(name='fun'),
        ItemCategoryModel(name='antique'),
        ItemCategoryModel(name='music'),
        ItemCategoryModel(name='computer'),
    ]
    items = [
        ItemModel(id=1,
                  name='Good Processor',
                  price=199.9,
                  categories=[categories[0], categories[3]]),
        ItemModel(id=2,
                  name='Komputer 100 Giga',
                  price=2499.99,
                  categories=[categories[0], categories[3]]),
        ItemModel(id=3,
                  name='Wiadro firmy WiadroPOL',
                  price=120,
                  categories=[categories[1]]),
        ItemModel(id=4,
                  name='Fleetwood Mac - Tango In The Night, vinyl',
                  price=26.99,
                  categories=[categories[2]]),
        ItemModel(id=5,
                  name='Keyboard 3000',
                  price=549.99,
                  categories=[categories[0], categories[2]]),
    ]
    orders = [
        OrderModel(id=1,
                   status=OrderStatus.awaiting_payment,
                   user_id=2,
                   elements=[
                       OrderElementModel(id=1, count=4, order_id=1, item_id=1),
                       OrderElementModel(id=2, count=10, order_id=1, item_id=3)
                   ]),
        OrderModel(id=2,
                   status=OrderStatus.delivered,
                   user_id=4,
                   elements=[
                       OrderElementModel(id=3, count=2, order_id=2, item_id=5),
                       OrderElementModel(id=4, count=1, order_id=2, item_id=4),
                       OrderElementModel(id=5, count=1, order_id=2, item_id=2),
                   ])
    ]
    for user in users:
        db.session.add(user)
    for category in categories:
        db.session.add(category)
    for item in items:
        db.session.add(item)
    for order in orders:
        db.session.add(order)
    db.session.commit()
Exemplo n.º 15
0
    def post(self):

        value = self.parser.parse_args()
        order = OrderModel(**value)
        order.save_to_db()
        return order.json()
Exemplo n.º 16
0
 def get(self):
     order = OrderModel.fetch()
     return order.json()
Exemplo n.º 17
0
#
# Cautions
#
# Since both OrderModel(pynamodb) and boto3 refers from
# AWS credentials set on your local machine,
# check if the AWS region on your local profile has been set to
# the intended region.
#
# For this demo, ap-northeast-1 (Tokyo) is used.
#

import sys
sys.path.append('..')

from model.order import OrderModel

# OrderModel.delete_table()
OrderModel.create_table()

import boto3
sqs = boto3.resource('sqs')
queue = sqs.create_queue(QueueName='jawsdays2020_demo_order_queue')
Exemplo n.º 18
0
 def get(self,_id):
     order = OrderModel.find_by_id(_id)
     if order:
         return order.json()
     return {"msg":'No user'},400
Exemplo n.º 19
0
 def delete(self,_id):
     order = OrderModel.find_by_id(_id)
     if order:
         order.delete_from_db()
         return order.json()
     return {"msg":'No user'},400