Exemplo n.º 1
0
    def get(self, item_id):
        item = ItemModel.find_by_id(item_id)
        if item is None:
            return {'status': False, 'message': 'Item not found', 'data': None}

        product_id = item.json()['product_id']

        product = ProductModel.find_by_id(product_id)
        promotion_items = PromotionModel.find_promotion_items(product_id)

        sold_price = product.json()['price']

        if promotion_items:
            for p_item in promotion_items:
                sold_price -= (p_item.json()['discount'] /
                               100) * product.json()['price']
                p_item.used_items += 1
                p_item.save_to_db()

        order = OrderModel(item_id, float("{:.2f}".format(sold_price)))

        order.save_to_db()

        item.delete_from_db()

        return {
            'status': True,
            'message': 'A item has been sold.',
            'data': order.json()
        }
Exemplo n.º 2
0
    def post(self):
        status = request.json.get('status')
        objectID = request.json.get('objectID')
        weight = request.json.get('weight')
        profit = request.json.get('profit')
        location = request.json.get('location')
        address = request.json.get('address')
        sequence = request.json.get('sequence')
        UserID = request.json.get('UserID')

        if objectID is None:
            abort(400)

        order = OrderModel()
        order.status = status
        order.objectID = objectID
        order.weight = weight
        order.profit = profit
        order.location = location
        order.address = address
        order.sequence = sequence
        order.UserID = UserID

        db.session.add(order)
        db.session.commit()

        response = jsonify({'id': order.id})
        response.status_code = 201
        return response
Exemplo n.º 3
0
    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.
        :return:
        """
        data = request.get_json() # token + list of item ids
        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():
            item = ItemModel.find_by_id(_id)
            if not item:
                return {"message": gettext("order_item_by_id_not_found").format(_id)}, 404

            items.append(ItemsInOrder(item_id=_id, quantity=count))

        order = OrderModel(items=items, status="pending")
        order.save_to_db()  # this does not submit to Stripe

        try:
            order.set_status("failed")
            order.charge_with_stripe(data["token"])
            order.set_status("complete")
            return order_schema.dump(order), 200
        except(error.CardError, error.RateLimitError, error.InvalidRequestError, error.AuthenticationError,
               error.APIConnectionError, error.StripeError) as e:
            return e.json_body, e.http_status
        except Exception as e:
            print(e)
            return {"message": gettext("order_error")}, 500
Exemplo n.º 4
0
    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

            items.append(ItemsInOrder(item_id=_id, quantity=count))

        order = OrderModel(items=items, status="pending")
        order.save_database()  # this does not submit to Stripe

        try:
            order.set_status(
                "failed")  # assume the order would fail until it's completed
            order.charge_stripe(data["token"])
            order.set_status("complete")  # charge succeeded
        except stripe.error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            print('Status is: %s' % e.http_status)
            print('Type is: %s' % e.error.type)
            print('Code is: %s' % e.error.code)
            # param is '' in this case
            print('Param is: %s' % e.error.param)
            print('Message is: %s' % e.error.message)
            return {"message": e.error.message}, e.http_status

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return {"message": e.error.message}, e.http_status

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return {"message": e.error.message}, e.http_status
        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return {"message": e.error.message}, e.http_status
        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            return {"message": e.error.message}, e.http_status
        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return {"message": e.error.message}, e.http_status
        except Exception as e:
            # Something else happened, completely unrelated to Stripe
            return {"message": e.error.message}, e.http_status

        return order_schema.dump(order), 200
Exemplo n.º 5
0
 def buynow(self, request):
     """立即购买"""
     self.response_["type"] = self.RESPONSE_TYPE_JSON
     id = request.GET.get("id")
     num = request.GET.get("num")
     try:
         customer = self.context["customer"]
         product = ProductModel.objects.get(id=id)
         newOrder = OrderModel(customer=customer)
         newOrder.save()
         newOrder.products.create(product=product, amount=num)
     except Exception as e:
         self.context = {
             "code": 4,
             "msg": "下单失败",
             "data": {
                 "pid": id,
                 "error": str(e)
             }
         }
     else:
         self.context = {
             "code": 200,
             "msg": "下单成功",
             "data": {
                 "oid": newOrder.id
             }
         }
Exemplo n.º 6
0
    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, 3, 5, 5, 5]
        items = []
        item_id_quantities = Counter(data["item_ids"])
        #  [(5, 3), (3, 1), (2, 1)]
        for _id, count in item_id_quantities.most_common(
        ):  #most common give u how many items in the order they happen
            item = ItemModel.find_by_id(_id)
            if not item:
                return {
                    "message":
                    gettext("order_item_by_id_not_found").format(_id)
                }, 404

            # items.append(item)
            items.append(ItemsInOrder(item_id=_id, quantity=count))

        order = OrderModel(items=items, status="pending")
        order.save_to_db()  #THIS DOES NOT SUBMIT TO STRIPE

        order.set_status(
            "failed")  # assume the order would fail until it's completed
        order.charge_with_stripe(data["token"])
        order.set_status("complete")  # charge succeeded

        return order_schema.dump(order), 200
Exemplo n.º 7
0
    def post(cls):
        """
        Expect a token and a list of item ids from the request body
        Construct an order and talk to the Stripe API to make a charge
        """
        data = request.get_json()  # token + list of item ids
        items = []
        item_id_quantities = Counter(data["item_idss"])

        for _id, count in item_id_quantities.most_common():
            item = ItemModel.find_by_id(_id)
            if not item:
                return {
                    "message":
                    gettext("order_item_by_id_not_found").format(_id)
                }, 404

            items.append(ItemsInOrder(item_id=_id, quantity=count))

        order = OrderModel(items=items, status="pending")
        order.save_to_db()

        order.set_status("failed")
        order.charge_with_stripe(data["token"])
        order.set_status("complete")
        return order_schema.dump(order)
Exemplo n.º 8
0
    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, 3, 5, 5, 5]
        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(
        ):  # -> [(5,3), (3,1), (2,1), (1,1)]
            item = ItemModel.find_by_id(_id)
            if not item:
                return {
                    "message":
                    gettext("order_item_by_id_not_found").format(_id)
                }, 404

            items.append(ItemsInOrder(item_id=_id, quantity=count))

        order = OrderModel(items=items, status="pending")
        order.save_to_db()  # this does not submit to Stripe

        order.set_status("failed")
        order.charge_with_stripe(data['token'])
        order.set_status("completed")
        return order_schema.dump(order)
Exemplo n.º 9
0
    def post(self, authorization, products):
        # parse the token
        token = parse_jwt(authorization)
        if not token:
            return {
                'success': False,
                'messages': ['INVALID_TOKEN']
            }, 401

        # construct a new order
        new_order = OrderModel(
            extract_uuid(token),
            products,
            '2017-10-10 20:00:00',
            False
        )

        # add the order to the database
        OrderModel.save_to_db(new_order)

        return {
            'success': True,
            'data': {
                'fulfilled': new_order.fulfilled,
                'id': new_order.id,
                'products': new_order.products 
            }
        }, 201
Exemplo n.º 10
0
    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 ,item_ids [1, 3, 3, 5, 5, 5]
        items = []
        item_id_quantities = Counter(data["item_ids"])

        for _id, count in item_id_quantities.most_common(
        ):  # [(5,3),(3,2),(1,1)]
            item = ItemModel.find_by_id(_id)
            if not item:
                return {
                    "message":
                    gettext("order_item_by_id_not_found").format(_id)
                }, 404
            """ItemsInOrder get item_id and quantity, however
            order_id will be set later on,
            when items is passed into OrderModel, because back_populates="order"
            it goes over to order column of ItemsInOrder table,
            and set order_id for each of those item in OrderModel
            to be the order to which you have added those items"""
            items.append(ItemsInOrder(item_id=_id, quantity=count))

        # items is a list of ItemsInOrder obj
        order = OrderModel(items=items,
                           status="pending")  # pending until send to Stripe
        order.save_to_db()  # this does not submit to Stripe

        try:
            order.set_status(
                "failed")  # assume the order would fail until it's completed
            order.charge_with_stripe(data["token"])
            order.set_status("complete")  # charge succeeded
            return order_schema.dump(order), 200
        # the following error handling is advised by Stripe, although the handling implementations are identical,
        # we choose to specify them separately just to give the students a better idea what we can expect
        except error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            return e.json_body, e.http_status
        except error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return e.json_body, e.http_status
        except error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return e.json_body, e.http_status
        except error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return e.json_body, e.http_status
        except error.APIConnectionError as e:
            # Network communication with Stripe failed
            return e.json_body, e.http_status
        except error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return e.json_body, e.http_status
        except Exception as e:
            # Something else happened, completely unrelated to Stripe
            print(e)
            return {"message": gettext("order_error")}, 500
Exemplo n.º 11
0
    def test_get_product(self):
        order = OrderModel.get(1)
        assert order != None

        orders = OrderModel.list()
        assert len(orders) == 1
        assert type(orders) == type([])
Exemplo n.º 12
0
    def get(self, rfid):
        user = UserModel.find_by_rfid(rfid)
        if user:
            current_order = int(user.current_order)
            recipe = RecipeModel.find_by_id(current_order)
            ingredients = RecipeModel.find_ingredients(current_order)
            durations = [0, 0, 0, 0]

            for ingredient in ingredients:
                durations[ingredient[0]['pump'] - 1] = ingredient[0]['portion']

            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            order = OrderModel(user.id, user.current_order, timestamp)
            order.save_to_db()
            return {"durations": durations}

        awaiting = UserCardRegistrationModel.awaiting_for_card

        if awaiting:
            if UserModel.find_by_username(awaiting):
                UserModel.update_card(awaiting, rfid)
                return {"durations": [0, 0, 0, 0]}
            else:
                return {"message": "No such user"}
        else:
            return {"durations": [0, 0, 0, 0]}
Exemplo n.º 13
0
    def get(cls):
        uid = get_jwt_identity()
        orders = []

        if StoreModel.find_by_id(uid):
            for order in OrderModel.find_all():
                if order.status == 'pending':
                    items = fetching_order(order.order_items)
                    message = order.message
                    orders.append({
                        'id': order.id,
                        'status': order.status,
                        'items': items,
                        'message': message
                    })
            return orders, 200
        elif CustomerModel.find_by_id(uid):
            for order in OrderModel.find_customer_completed_orders(
                    customer_id=uid):
                items = fetching_order(order.order_items)
                message = order.message
                orders.append({
                    'id': order.id,
                    'items': items,
                    'message': message
                })
            return orders, 200
        return 401
Exemplo n.º 14
0
 def get(self, name):
     a = []
     filtered_order = OrderModel.find_by_item_name(name)
     for item in filtered_order:
         order_id = item.order_id
         fil_order = OrderModel.find_by_order_id(order_id).first()
         a.append(fil_order.json())
     return a
Exemplo n.º 15
0
    def post(cls):
        """
        Expect a token and a list of item ids from the request body.
        Construct an order an talk to the Stripe API to make a charge.
        """
        data = request.get_json()  # token + list of item ids
        items = []
        item_id_quantities = Counter(
            data['item_ids']
        )  # you pass a list to the Counter and it will count for you

        # Iterate over items and retrieve them from the db
        for _id, count in item_id_quantities.most_common():
            item = ItemModel.find_by_id(_id)
            if not item:
                return {
                    'message':
                    gettext('order_item_by_id_not_found').format(_id)
                }, 404

            items.append(ItemsInOrder(item_id=_id, quantity=count))

        order = OrderModel(items=items, status='pending')
        order.save_to_db()

        # submit to Stripe
        try:
            order.set_status(
                "failed")  # assume the order would fail until it's completed
            order.charge_with_stripe(data["token"])
            order.set_status("complete")  # charge succeeded
            return order_schema.dump(order), 200
        # the following error handling is advised by Stripe, although the handling implementations are identical,
        # we choose to specify them separately just to give the students a better idea what we can expect
        except error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            return e.json_body, e.http_status
        except error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return e.json_body, e.http_status
        except error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return e.json_body, e.http_status
        except error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return e.json_body, e.http_status
        except error.APIConnectionError as e:
            # Network communication with Stripe failed
            return e.json_body, e.http_status
        except error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return e.json_body, e.http_status
        except Exception as e:
            # Something else happened, completely unrelated to Stripe
            print(e)
            return {"message": gettext("order_error")}, 500
Exemplo n.º 16
0
    def create_order(self, order_entity):
        order = OrderModel.get_by_main_order_id(self.db, order_entity.id)
        if order:
            # callback 订单已存在
            Log.info('order exist')
            return order

        order = OrderModel.new_order(self.db, order_entity)
        return order
Exemplo n.º 17
0
 def post(self, username):
     data = Order.parser.parse_args()
     order = OrderModel(username, **data)
     try:
         order.save_to_db()
     except:
         # Internal Server Error
         return {"message": "An error occured inserting the item."}, 500
     return {"message": "Success"}
Exemplo n.º 18
0
    def create_order(self, order_entity):
        order = OrderModel.get_by_main_order_id(self.db, order_entity.id)
        if order:
            # callback 订单已存在
            Log.info('order exist')
            return order

        order = OrderModel.new_order(self.db, order_entity)
        return order
Exemplo n.º 19
0
    def reset_order_status(self, order_entity):
        order = OrderModel.get_by_main_order_id(self.db, order_entity.id)
        if not order:
            raise JsonException(1, 'order not exist')

        pre_status = order.status

        OrderModel.change_order_status_by_main_order_id(self.db, order_entity.id, 0)
        OrderHistoryModel.set_order_status_by_server(self.db, order, pre_status, 0)
Exemplo n.º 20
0
 def post(self):
     order_id = self.get_argument('order_id', None)
     if not order_id:
         raise JsonException(-1, '缺少order_id')
     try:
         OrderModel.change_order_pay_by_main_order_id(self.db, order_id)
         self.finish_json()
     except Exception, e:
         raise JsonException(-1, e.message)
Exemplo n.º 21
0
def createOrder(data):
    
    order = OrderModel()
    order.productId = data['productId']
    order.productName = data['productName']
    order.productAmount = data['productAmount']
    order.productPrice = data['productPrice']
    order.deliveryAddress = data['deliveryAddress']
    order.deliveryState = data['deliveryState']
    order.save()
Exemplo n.º 22
0
    def post(self):
        data = OrderPost.parser.parse_args()
        order = OrderModel(**data)

        try:
            order.save_to_db()

        except:
            return {'message': 'An error occured inserting the order'}, 500

        return order.json(), 201
Exemplo n.º 23
0
    def reset_order_status(self, order_entity):
        order = OrderModel.get_by_main_order_id(self.db, order_entity.id)
        if not order:
            raise JsonException(1, 'order not exist')

        pre_status = order.status

        OrderModel.change_order_status_by_main_order_id(
            self.db, order_entity.id, 0)
        OrderHistoryModel.set_order_status_by_server(self.db, order,
                                                     pre_status, 0)
Exemplo n.º 24
0
    def post(self):
        data = Order.parser.parse_args()

        order = OrderModel(**data)

        try:
            order.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return order.json(), 201
Exemplo n.º 25
0
    def post(self, product_id):
        data = RequestedOrder.parser.parse_args()

        if OrderModel.search_requested_from_database_by_id(product_id):
            return {"message": "This product has been ordered"}, 400

        data.update({"renter_national_id": None, "accepted": None})

        OrderModel.add_to_database(OrderModel(**data))

        return {
            "message": "Order has been successfully delivered to the lender"
        }, 201
Exemplo n.º 26
0
    def get(self):
        """
		Devuelve la lista de pedidos hechos por un usuario, si es vendedor, la lista de pedidos recibidos.
		"""
        if current_identity.user_type == user_types['vendor']:
            return [
                order.json()
                for order in OrderModel.get_by_vendor(current_identity.id)
            ]
        return [
            order.json()
            for order in OrderModel.get_by_customer(current_identity.id)
        ]
Exemplo n.º 27
0
def create_order(session, submit_order):
    order = OrderModel.get_by_main_order_id(session, submit_order.id)
    if order:
        # callback 订单已存在
        Log.info('order exist')
        return order

    order = OrderModel.new_order(session, submit_order)
    if order:
        return order
    else:
        # callback 创建失败
        pass
Exemplo n.º 28
0
    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))

        order = OrderModel(items=items, status="pending")
        order.save_to_db()

        try:
            order.set_status("payment failed")
            order.charge_with_stripe(data["token"])
            order.set_status("payment completed")
            return orderSchema.dump(order)
        # the following error handling is advised by Stripe, although the handling implementations are identical,
        # we choose to specify them separately just to give the students a better idea what we can expect
        except error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            return e.json_body, e.http_status
        except error.RateLimitError as e:
            # Too many requests made to the API too quickly
            return e.json_body, e.http_status
        except error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            return e.json_body, e.http_status
        except error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            return e.json_body, e.http_status
        except error.APIConnectionError as e:
            # Network communication with Stripe failed
            return e.json_body, e.http_status
        except error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            return e.json_body, e.http_status
        except Exception as e:
            # Something else happened, completely unrelated to Stripe
            print(e)
            return {"message": "Order Error"}, 500
Exemplo n.º 29
0
    def post(self, product_id):
        data = ResponsedOrder.parser.parse_args()

        if not data["accepted"]:
            return {"message": "Your request has been denied"}, 400

        data.update({"notified": False, "expired": False})

        OrderModel.update_order(data)

        ProductModel.search_from_database_by_id(
            data["product_id"]).update_status(data["accepted"])

        return {"message": "The lender has been accepted your request"}, 200
Exemplo n.º 30
0
 def get(self, renter_id):
     return {
         "expiring": [
             expiring_order.json()
             for expiring_order in OrderModel.get_expiring_orders(renter_id)
         ]
     }, 200
Exemplo n.º 31
0
 def get(self, lender_id):
     return {
         "pending_requests": [
             request.json()
             for request in OrderModel.get_pending_requests(lender_id)
         ]
     }, 200
Exemplo n.º 32
0
    def get(self):
        merchant_id = self.current_user.merchant_id
        total = OrderModel.get_waiting_orders_count(self.db, merchant_id)

        self.finish_json(result={
            'total': total,
        })
Exemplo n.º 33
0
    def put(self, _id):
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': 'Admin privilege required.'}, 401

        parser = reqparse.RequestParser()
        parser.add_argument('food_id',
                            type=list,
                            required=True,
                            location='json',
                            help="every order need a list of food id!")
        data = Order.parser.parse_args()

        order = OrderModel.find_by_id(_id)

        if order:
            foods = [
                FoodModel.find_by_id(food).json() for food in data['food_id']
            ]
            total_price = sum([food['price'] for food in foods])
            order.total_price = total_price
            order.updated_at = datetime.now()
        else:
            return {'message': 'Order not found'}, 404

        try:
            order.save_to_db()
        except:
            return {"message": "An error occurred inserting the food."}, 500

        return order.json(), 201
Exemplo n.º 34
0
def send_order_sms(self, merchant_id, hotel_name, order_id, confirm_type):
    Log.info(u">>> send sms to merchant {} hotel {} order_id {} confirm type {}".format(merchant_id, hotel_name, order_id, confirm_type))

    order = OrderModel.get_by_id(self.session, order_id)
    breakfast_str = u'含早' if order.get_has_breakfast() else u'无早'
    customers = json.loads(order.customer_info)
    customer_str = " ".join([customer['name'] for customer in customers])


    if confirm_type == OrderModel.CONFIRM_TYPE_AUTO:
        content = u"尊敬的用户您好,系统收到编号{}自动确认订单:{},房型:{},入离日期:{}至{}( {}晚 ),入住人:{},总价:{},{}。订单号:{},请及时关注。客服联系电话:4006103330".format(merchant_id, hotel_name, order.roomtype_name, order.checkin_date, order.checkout_date, order.get_stay_days(), customer_str, order.total_price / 100, breakfast_str, order_id)
    elif confirm_type == OrderModel.CONFIRM_TYPE_MANUAL:
        content = u"尊敬的用户您好,系统收到编号{}待确认订单:{},房型:{},入离日期:{}至{}( {}晚 ),入住人:{},总价:{},{}。订单号:{},请尽快处理。客服联系电话:4006103330".format(merchant_id, hotel_name, order.roomtype_name, order.checkin_date, order.checkout_date, order.get_stay_days(), customer_str, order.total_price / 100, breakfast_str, order_id)
    send_sms_to_service(merchant_id, content)

    user =UserModel.get_user_by_merchantid_username(self.session, merchant_id, 'admin')
    if not user:
        Log.info("send sms no user(order {})".format(order_id))
        return
    phone = user.mobile
    if not phone:
        Log.info("send sms no phone(order {})".format(order_id))
        return

    Log.info(">> send sms to {}".format(phone))
    Log.info(u">> sms content: {}".format(content))
    
    send_sms([phone], content)
Exemplo n.º 35
0
    def get(self):
        merchant_id = self.current_user.merchant_id
        total = OrderModel.get_waiting_orders_count(self.db, merchant_id, self.current_user.hotel_id)

        self.finish_json(result={
            'total': total,
        })
Exemplo n.º 36
0
    def get(self, order_id):
        merchant_id = self.current_user.merchant_id
        order = OrderModel.get_by_merchant_and_id(self.db, merchant_id, order_id, self.current_user.hotel_id)

        self.finish_json(result={
            'order': order.todict() if order else None,
        })
Exemplo n.º 37
0
    def post(self):
        order_id = self.get_argument('order_id', None)
        status = self.get_argument('status', None)
        if not order_id:
            raise JsonException(-1, 'params : id not exists')
        if not status or int(status) not in [300, 500]:
            raise JsonException(-1, 'params: status is not validate')
        order = OrderModel.get_by_main_order_id(self.db, order_id)
        if not order:
            raise JsonException(1, 'order not exist')

        pre_status = order.status

        OrderModel.change_order_status_by_main_order_id(self.db, order_id, status)
        OrderHistoryModel.set_order_status_by_server(self.db, order, pre_status, status)
        self.finish_json()
Exemplo n.º 38
0
    def get(self):
        merchant_id = self.current_user.merchant_id

        order_id = self.get_query_argument('order_id', None)
        hotel_name = self.get_query_argument('hotel_name', None)
        checkin_date_start = self.get_query_argument(
            'checkin_date_start', None)
        checkin_date_end = self.get_query_argument('checkin_date_end', None)
        customer = self.get_query_argument('customer', None)
        order_status = self.get_query_argument('order_status', None)
        create_time_start = self.get_query_argument('create_time_start', None)
        create_time_end = self.get_query_argument('create_time_end', None)
        start = self.get_query_argument('start', 0)
        limit = self.get_query_argument('limit', 20)

        if order_status:
            order_status = order_status.split(',')

        orders, total = OrderModel.search(self.db,
                                          merchant_id, self.current_user.hotel_id, order_id, hotel_name,
                                          checkin_date_start, checkin_date_end, customer, order_status,
                                          create_time_start, create_time_end, start, limit)

        self.finish_json(result={
            'orders': [order.todict() for order in orders],
            'total': total,
            'start': start,
            'limit': limit,
        })
Exemplo n.º 39
0
def cancel_order_by_user(self, user, order_id, reason):
    session = self.session
    order = OrderModel.get_by_id(session, order_id)

    pre_status = order.status

    if order.merchant_id != user.merchant_id:
        raise CeleryException(100, 'merchant invalid')
    if order.status not in [0, 100]:
        raise CeleryException(1000, 'illegal status')

    if not callback_order_server(order_id):
        raise CeleryException(1000, 'callback order server error')


    task = Cancel.cancel_order_by_user.delay(order_id, reason)
    result = task.get()
    
    if task.status == 'SUCCESS':
        if result.status != pre_status:
            OrderHistoryModel.set_order_status_by_user(session, user, result, pre_status, result.status)
        PushInventoryTask().push_inventory.delay(order.roomtype_id)
        return result
    else:
        if isinstance(result, Exception):
            raise result
Exemplo n.º 40
0
    def get(self):
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': 'admin privilege required.'}, 401

        orders = [order.json() for order in OrderModel.find_all()]
        return {'orders': orders}, 200
Exemplo n.º 41
0
    def get(self):
        merchant_id = self.current_user.merchant_id
        start = self.get_query_argument('start', 0)
        limit = self.get_query_argument('limit', 20)

        orders, total = OrderModel.get_today_book_orders(self.db, merchant_id, start, limit, self.current_user.hotel_id)
        self.finish_json(result={
            'total': total,
            'start': start,
            'limit': limit,
            'orders': [order.todict() for order in orders],
        })
Exemplo n.º 42
0
    def get(self):
        merchant_id = self.current_user.merchant_id

        order_id = self.get_query_argument('order_id', None)
        hotel_name = self.get_query_argument('hotel_name', None)
        checkin_date_start = self.get_query_argument(
            'checkin_date_start', None)
        checkin_date_end = self.get_query_argument('checkin_date_end', None)
        customer = self.get_query_argument('customer', None)
        order_status = self.get_query_argument('order_status', None)
        create_time_start = self.get_query_argument('create_time_start', None)
        create_time_end = self.get_query_argument('create_time_end', None)

        order_ids = self.get_query_argument('order_ids', None)
        if order_ids:
            order_ids = [int(order_id_) for order_id_ in order_ids.split(',')]
        if order_status:
            order_status = order_status.split(',')

        orders, total = OrderModel.search_export_orders(self.db,
                                                        merchant_id, self.current_user.hotel_id, order_id, hotel_name,
                                                        checkin_date_start, checkin_date_end, customer, order_status,
                                                        create_time_start, create_time_end, order_ids)
        wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)
        sheet = wbk.add_sheet('EBooking订单列表')
        row = 0
        sheet.write(row, 0, '订单确认号')
        sheet.write(row, 1, '酒店名称')
        sheet.write(row, 2, '房型')
        sheet.write(row, 3, '床型')
        sheet.write(row, 4, '房间数')
        sheet.write(row, 5, '入店日期')
        sheet.write(row, 6, '离店日期')
        sheet.write(row, 7, '预约时间')
        sheet.write(row, 8, '入住人')
        sheet.write(row, 9, '确认类型')
        sheet.write(row, 10, '每日价格')
        sheet.write(row, 11, '总价')
        sheet.write(row, 12, '订单状态')

        for order in orders:
            row += 1
            self.write_one_row(sheet, row, order)
        export_time = datetime.datetime.now()
        file_name = 'orders_{}.xls'.format(export_time.strftime('%Y-%m-%d %H:%M:%S'))
        self.set_header('Content-type', 'application/vnd.ms-excel')
        self.set_header('Content-Disposition', 'attachment; filename="' + file_name + '"')
        sio = StringIO.StringIO()
        wbk.save(sio)
        self.write(sio.getvalue())
Exemplo n.º 43
0
    def post(self):
        merchant_id = self.get_argument('merchant_id', None)
        if not merchant_id:
            raise JsonException(-1, "缺少merchant_id")

        update_time = self.get_argument('update_time', None)
        start = int(self.get_argument('start', 0))
        limit = int(self.get_argument('limit', 20))
        order_id = self.get_argument('order_id', None)
        status = self.get_argument('status', None)
        try:
            limit = 100 if limit > 100 else limit
            orders, total = OrderModel.search_switch(self.db, merchant_id, update_time, start, limit, order_id, status)
        except Exception, e:
            raise JsonException(-1, e.message)
Exemplo n.º 44
0
def confirm_order_by_user(self, user, order_id):
    session = self.session
    order = OrderModel.get_by_id(session, order_id)
    pre_status = order.status
    if order.merchant_id != user.merchant_id:
        raise CeleryException(100, 'merchant not valid')
    if order.status != 100:
        raise CeleryException(200, 'illegal status')

    if callback_order_server(order_id):
        order.confirm_by_user(session)
        if order.status != pre_status:
            OrderHistoryModel.set_order_status_by_user(session, user, order, pre_status, order.status)
        return order
    else:
        raise CeleryException(1000, 'callback order server fail')
Exemplo n.º 45
0
def cancel_order_by_server(self, order_id):
    session = self.session
    order = OrderModel.get_by_id(session, order_id)

    pre_status = order.status

    if order.status == 0 or order.status == 100:
        _order = cancel_before_user_confirm(session, order.id)
    elif order.status == 200:
        raise CeleryException(1000, 'illegal status')
    elif order.status == 300:
        _order = cancel_after_user_confirm(session, order.id)
    elif order.status in [400, 500, 600]:
        return order
    else:
        raise CeleryException(1000, 'illegal status')


    if _order.status != pre_status:
        OrderHistoryModel.set_order_status_by_server(session, _order, pre_status, _order.status)
    return _order
Exemplo n.º 46
0
    def post(self, order_id):

        order = OrderModel.get_by_id(self.db, order_id)
        pre_status = order.status
        if order.merchant_id != self.merchant.id:
            raise JsonException(100, 'merchant not valid')
        if order.status != 100:
            raise JsonException(200, 'illegal status')
        if self.current_user.type == UserModel.TYPE_SUB and order.hotel_id != self.current_user.hotel_id:
            raise JsonException(500, 'illegal hotel')

        if (yield self.callback_order_server(order)):
            order.confirm_by_user(self.db)
            if order.status != pre_status:
                OrderHistoryModel.set_order_status_by_user(
                    self.db, self.current_user, order, pre_status, order.status)
        else:
            raise JsonException(1000, 'callback order server fail')

        self.finish_json(result=dict(
            order=order.todict(),
        ))
Exemplo n.º 47
0
    def cancel_order_by_server(self, order_id):
        order = OrderModel.get_by_id(self.db, order_id)
        if not order:
            raise JsonException(2000, 'no order')

        pre_status = order.status

        if order.status == 0 or order.status == 100:
            _order = yield self.cancel_before_user_confirm(order.id)
        elif order.status == 300:
            _order = yield self.cancel_after_user_confirm(order.id)
        elif order.status in [400, 500, 600]:
            raise gen.Return(order)
        elif self.current_user.type == UserModel.TYPE_SUB and order.hotel_id != self.current_user.hotel_id:
            raise JsonException(500, 'illegal hotel')
        else:
            raise JsonException(1000, 'illegal status')


        if _order.status != pre_status:
            OrderHistoryModel.set_order_status_by_server(self.db, _order, pre_status, _order.status)
        raise gen.Return(_order)
Exemplo n.º 48
0
    def post(self, order_id):
        merchant_id = self.current_user.merchant_id
        args = self.get_json_arguments()
        reason, = get_and_valid_arguments(args, 'reason')
        if not reason:
            raise JsonException(200, 'invalid reason')

        order = OrderModel.get_by_id(self.db, order_id)

        pre_status = order.status

        if order.merchant_id != merchant_id:
            raise JsonException(300, 'merchant invalid')
        if order.status not in [0, 100]:
            raise JsonException(400, 'illegal status')
        if self.current_user.type == UserModel.TYPE_SUB and order.hotel_id != self.current_user.hotel_id:
            raise JsonException(500, 'illegal hotel')

        if not (yield self.callback_order_server(order)):
            raise JsonException(1000, 'callback order server error')

        task = yield gen.Task(Cancel.cancel_order_by_user.apply_async,
                              args=[order_id, reason])

        if task.status == 'SUCCESS':
            order = task.result
            if order.status != pre_status:
                OrderHistoryModel.set_order_status_by_user(
                    self.db, self.current_user, order, pre_status, order.status)
            self.finish_json(result=dict(
                order=order.todict(),
            ))
        else:
            if isinstance(task.result, CeleryException):
                raise JsonException(1000, task.result.errmsg)
            else:
                raise JsonException(1000, 'network error')
Exemplo n.º 49
0
def get_order(session, order_id):
    return OrderModel.get_by_id(session, order_id)
Exemplo n.º 50
0
 def get(self, merchant_id):
     orders, total = OrderModel.get_waiting_orders(self.db, merchant_id)
     self.finish_json(result=dict(
         has_new_order=True if orders else False,
         ))
Exemplo n.º 51
0
 def get_order_in_date(self, merchant_id, year, month, pay_type, ota_ids=None):
     orders = OrderModel.get_success_order_by_checkout_date_in_month(self.db,
             merchant_id, year, month, pay_type, ota_ids)
     return orders