def test_language_info(self):
        language_info = header_parser.parse_language(self.dummy_meta)
        self.assertEqual(language_info[0], False)
        self.assertEqual(language_info[1], 'default')

        self.dummy_meta = {'HTTP_ACCEPT_LANGUAGE': 'zh'}
        language_info = header_parser.parse_language(self.dummy_meta)
        self.assertEqual(language_info[0], True)
        self.assertEqual(language_info[1], 'aries_cn')
Example #2
0
    def post(self, request):
        language_info = header_parser.parse_language(request.META)

        try:
            coupon_data = coupon_util.event_coupon_validator(
                request, language_info[0])

            open_id = coupon_data['open_id']
            coupon_id = coupon_data['coupon_id']

            coupon_list = [(coupon_id, 0, self.r_code, 'ADMIN')]
            coupon_manager = CouponManagerV3(logger_info, logger_error)

            coupon_manager.create_coupon(open_id, coupon_list)
        except BusinessLogicError as instance:
            message = instance.args
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    message)
        except Exception as e:
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    str(e))
        else:
            result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        return Response(result.get_response(), result.get_code())
Example #3
0
    def post(self, request):
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')
        request_data = request.data

        try:
            open_id = request_data['open_id']
            product_list = request_data['product_list']
            order_id = request_data['order_id']
            hub_id = request_data['hub_id']
        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid(Token or Open id)')
            return Response(result.get_response(), result.get_code())

        language_info = header_parser.parse_language(request.META)
        date_info = product_util.get_date_information(hub_id, product_util.get_sales_time_str())

        product_manager = ProductManager(logger_info, logger_error, language_info, date_info)
        review_manager = ReviewManager(logger_info, logger_error)

        product_list = [product_manager.get_product(product['product_id']) for product in product_list]
        response_list = [review_manager.get_personal_review(language_info[2], open_id, order_id, product)
                         for product in product_list]

        result.set('reviews', response_list)
        result.set('review_items', review_manager.review_items)

        return Response(result.get_response(), result.get_code())
    def get(self, request):
        auth_info = header_parser.parse_authentication(request)
        language_info = header_parser.parse_language(request.META)

        event_manager = EventManager(self.logger_info, self.logger_error)

        try:
            # Get event manager
            event_object = event_manager.get_event_status(
                auth_info, None, language_info[0])
            event = event_object['event']

            if event['need_auth']:
                user_util.check_auth_info(auth_info)

            # Check game play condition
            event_util.check_play_condition(event, language_info[0])

            # Play the game
            reward_result = event_manager.draw_event(event['id'],
                                                     language_info[0])
            reward_id = reward_result[0]
            random_number = reward_result[1]

            # Make the history
            create_result = event_manager.create_event_history(
                event['id'], auth_info[0], reward_id, random_number,
                language_info[0])

            # Reward interface to purchase server
            reward_tuple = create_result[2]
            event_manager.create_coupon(auth_info[0], reward_tuple.target_id,
                                        language_info[0])

            # Coupon count increase
            event_manager.increase_coupon_count(auth_info[0], auth_info[1])
        except AuthInfoError as e:
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED, str(e))
        except BusinessLogicError as instance:
            message, err_code = instance.args
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    message)
            result.set_error(err_code)
        except Exception as e:
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    str(e))
        else:
            result = ResultResponse(code.ARIES_200_SUCCESS, 'success')
            result.set('event_reward', create_result[1])

        return Response(result.get_response(), result.get_code())
    def get(self, request):
        auth_info = header_parser.parse_authentication(request)
        language_info = header_parser.parse_language(request.META)

        event_manager = EventManager(self.logger_info, self.logger_error)

        try:
            event = event_manager.get_event_status(auth_info, None,
                                                   language_info[0])
        except Exception as e:
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    str(e))
        else:
            result = ResultResponse(code.ARIES_200_SUCCESS, 'success')
            result.set('event', event['event'])
            result.set('event_reward', event['event_reward'])
            result.set('event_info', event['event_info'])

        return Response(result.get_response(), result.get_code())
Example #6
0
    def get(self, request):
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        # Get access token
        try:
            open_id = request.META['HTTP_OPEN_ID']
            access_token = str(request.META['HTTP_AUTHORIZATION']).split(' ')[1]

            language_info = header_parser.parse_language(request.META)
            cn_header = language_info[0]

            page = int(request.GET.get('page'))
            limit = int(request.GET.get('limit'))
            user = User.objects.get(access_token=access_token, open_id=open_id)
        except Exception as e:
            logger_error.error(str(e))
            result = ResultResponse(code.ARIES_401_UNAUTHORIZED, 'Token or user not found')
            return Response(result.get_response(), result.get_code())

        # My News part
        try:
            user_news_list = UserNews.objects.filter(user=user)
            user_news_count = user_news_list.count()
            paginator = Paginator(user_news_list, limit)

            user_news = paginator.page(page).object_list
            serializer = UserNewsSerializer(user_news, many=True)
            news_data = serializer.data

            user_manager = UserManager()
            news_list = [user_manager.parse_my_news(news, cn_header) for news in news_data]

            result.set('total_count', user_news_count)
            result.set('news', news_list)
        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data error')
            return Response(result.get_response(), result.get_code())

        return Response(result.get_response(), result.get_code())
Example #7
0
    def get(self, request):
        auth_info = header_parser.parse_authentication(request)
        language_info = header_parser.parse_language(request.META)

        try:
            coupon_util.auth_info_validator(auth_info, language_info[0])
            coupon_util.os_info_validator(request)

            coupon_manager = CouponManagerV3(logger_info, logger_error)
            coupon_manager.create_coupon_pack(auth_info, self.coupon_pack_info,
                                              language_info[0])
        except BusinessLogicError as instance:
            message, err_code = instance.args
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    message)
            result.set_error(err_code)
        except Exception as e:
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                    str(e))
        else:
            result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        return Response(result.get_response(), result.get_code())
Example #8
0
    def post(self, request):
        result = ResultResponse(code.ARIES_200_SUCCESS, self.SUCCESS_MSG)

        language_info = header_parser.parse_language(request.META)
        cn_header = language_info[0]
        target_db = language_info[1]

        result_list = list()
        result_product_list = list()

        try:
            request_data = request.data
            os_type = request_data.get('os_type', 0)
            hub_id = request_data.get('hub_id', 1)
            product_list = request.data['product_list']
            delivery_schedule = request.data['delivery_schedule']
        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid')
            return Response(result.get_response(), result.get_code())

        first_product = True
        product_order_name = ''
        sales_time = 0

        # Time bomb service
        product_service = ProductService(logger_info, logger_error)
        time_bomb_service = TimeBombService(logger_info, logger_error)

        time_bomb_id = time_bomb_service.get_current_time_bomb_id(hub_id, os_type)
        discount_info = {}

        if time_bomb_id is not None:
            discount_list = product_service.read_product_discount_info_with_id(time_bomb_id)
            discount_info.update(get_discount_info_map(discount_list, cn_header))

        for product in product_list:
            try:
                product_instance = Product.objects.get(id=product['product_id'])
                menu_instance = Menu.objects.using(target_db).get(id=product_instance.menu.id)
                hub_stock = HubStock.objects.get(hub=product_instance.hub, menu=menu_instance)

                # Check sales_time
                sales_time = product_instance.sales_time

                # Check real stock unit
                order_quantity = product['quantity']
                stock = hub_stock.stock

                if stock < order_quantity:
                    result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR, 'Product already sold')
                    error_code = code.ERROR_3001_PRODUCT_ALREADY_SOLD
                    result.set_error(error_code)
                    error_message = get_msg(error_code, cn_header)
                    error_message += ' [' + menu_instance.name + ']'
                    result.set_error_message(error_message)
                    return Response(result.get_response(), result.get_code())

                # Check schedule time
                if not check_delivery_schedule(delivery_schedule):
                    result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR, 'Schedule invalid')
                    error_code = code.ERROR_3015_PRODUCT_DELIVERY_TIME_INVALID
                    error_message = get_msg(error_code, cn_header)
                    result.set_error(error_code)
                    result.set_error_message(error_message)
                    return Response(result.get_response(), result.get_code())

                # Product information
                product_serializer = ProductListInfoSerializer(product_instance)
                product_data = product_serializer.data

                menu_serializer = MenuValidationSerializer(menu_instance)
                menu_data = menu_serializer.data

                product_data['menu'] = menu_data
                product_data['quantity'] = product['quantity']

                # Add time bomb information
                if product_data['id'] in discount_info:
                    add_discount_information(product_data, discount_info[product_data['id']])

                result_product_list.append(product_data)

                if first_product:
                    product_order_name = product_instance.menu.name
                    # product_order_name = menu_instance.name
                    first_product = False

                logger_info.info(str(stock) + ' ' + str(product['quantity']))

                if stock >= product['quantity']:
                    result_list.append(product['product_id'])

            except Exception as e:
                print(e)

        result.set('product_title', product_order_name)
        # Check if result list is zero, don't display more
        if int(len(result_list)-1) != 0:
            result.set('product_sub', '(and ' + str(len(result_list)-1) + ' more)')
        else:
            result.set('product_sub', '')

        result.set('sales_time', sales_time)
        result.set('product_count', len(result_list))
        result.set('product_index_list', result_list)
        result.set('product_list', result_product_list)

        return Response(result.get_response(), result.get_code())
    def get(self, request, hub_id):
        # Query the DeliverySchedule DB

        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')

        language_info = header_parser.parse_language(request.META)
        target_db = language_info[1]

        sales_time = 'ALL_DAY'
        if request.query_params.get('sales_time'):
            sales_time = request.query_params.get('sales_time').upper()

        today = datetime.datetime.today()
        next_working_day = today + datetime.timedelta(days=30)
        try:
            dlv_schedules = DeliverySchedule.objects.filter(working_day__range=[today, next_working_day])

            if dlv_schedules.count() <= 0:
                result.set('timetable', json.loads('[]'))
            else:
                target_schedule = dlv_schedules[0]
                delivery_day = today

                if delivery_day.time() > dlv_schedules[0].delivery_end:
                    if dlv_schedules.count() > 1:
                        target_schedule = dlv_schedules[1]
                        next_day = target_schedule.working_day
                    else:
                        target_schedule = dlv_schedules[0]
                        next_day = today + datetime.timedelta(days=1)
                else:
                    next_day = today

                if sales_time == 'LUNCH':
                    time_table = target_schedule.delivery_time_table_lunch
                elif sales_time == 'DINNER':
                    time_table = target_schedule.delivery_time_table_dinner
                else:
                    time_table = target_schedule.delivery_time_table

                time_slots = json.loads(time_table)
                result.set('working_day', next_day.strftime('%Y.%m.%d'))
                available_time = 0
                matched_index = []

                for target_slot in time_slots:
                    time = datetime.datetime.strptime(
                        next_day.strftime("%Y.%m.%d") + ' ' + target_slot["starttime"], "%Y.%m.%d %I:%M %p"
                    )

                    if today > time:
                        available_time += 1
                    else:
                        matched_index.append(target_slot['index'])

                try:
                    shipping_avail = ShippingAvailability.objects.get(hub_id=hub_id, ds_id=target_schedule)
                except ShippingAvailability.DoesNotExist:
                    shipping_avail = ShippingAvailability(hub_id=hub_id, ds_id=target_schedule)
                    shipping_avail.save()

                time_slots_avail = json.loads(shipping_avail.shipping_availability_table)
                result_list = [target_time for slot in matched_index for target_time in time_slots_avail
                               if slot == target_time['index']]

                if sales_time == 'LUNCH':
                    result_table = result_list
                elif sales_time == 'DINNER':
                    result_table = result_list
                else:
                    result_table = time_slots_avail[available_time:]

                result.set('timetable', result_table)
        except DeliverySchedule.DoesNotExist:
            today = datetime.datetime.today()
            today = today + datetime.timedelta(1)
            result.set('timetable', json.loads('[]'))
            result.set('working_day', today.strftime("%Y.%m.%d"))
            result.set('shipping_detail', json.loads('[]'))
            return Response(result.get_response(), result.get_code())

        try:
            shipping_methods = ShippingMethod.objects.using(target_db).filter(hub_id=hub_id)
            shipping_method_list = ShippingMethodListSerializer(shipping_methods, many=True).data
            result.set('shipping_detail', shipping_method_list)
        except ShippingMethod.DoesNotExist:
            print("ShippingMethod is not defined for hub id: {0}".format(hub_id))
            result.set('shipping_detail', json.loads('[]'))
        except Exception as e:
            print(e)
            result.set('shipping_detail', json.loads('[]'))

        return Response(result.get_response(), result.get_code())
    def post(self, request):
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')
        request_data = request.data

        logger_info.info(request_data)

        language_info = header_parser.parse_language(request.META)
        cn_header = language_info[0]

        order_data = dict()
        coupon_instance_list = list()

        # for getting daily order index
        order_manager_v2 = OrderManagerV2(logger_info, logger_error)

        # Step 1. Request data parsing
        try:
            open_id = request.META['HTTP_OPEN_ID']
            access_token = str(request.META['HTTP_AUTHORIZATION']).split(' ')[1]
            order_id = request_data['order_id']
            payment_data = request_data['payment_data']
            notification_order = request_data.get('alipay_notification_order', False)
        except Exception as e:
            logger_info.info(str(e))
            result = ResultResponse(code.ARIES_400_BAD_REQUEST, 'Request data invalid(Token or Open id)')
            return Response(result.get_response(), result.get_code())

        # Step 1.5
        order_count = Order.objects.filter(order_id=order_id, open_id=open_id).count()

        if order_count == 1:
            order = Order.objects.get(order_id=order_id, open_id=open_id)
            purchase_order = PurchaseOrder.objects.get(order_id=order_id, open_id=open_id)
            purchase_order_serializer = UpcomingPurchaseOrderSerializer(purchase_order)
            purchase_order_data = purchase_order_serializer.data
            purchase_order_data['order_details'] = json.loads(purchase_order_data['order_details'])
            purchase_order_data['shipping_detail'] = json.loads(purchase_order_data['shipping_detail'])
            del purchase_order_data['product_list']
            del purchase_order_data['coupon_list']
            del purchase_order_data['order_hash']

            order_data = UpcomingOrderSerializer(order).data
            order_data['order_start_date'] = dateformatter.get_ordering_complete_date_fmt(order.order_start_date)
            order_data['order_status_history'] = json.loads(order_data['order_status_history'])
            order_data['purchase_order'] = purchase_order_data
            order_data['order_cancel_date'] = ''

            # Get Timetable
            order_data['timetable'] = json.loads('[]')

            result.set('upcoming_order', order_data)
            return Response(result.get_response(), result.get_code())

        # Step 2. Check payment data validation and coupon check
        try:
            purchase_order = PurchaseOrder.objects.get(order_id=order_id, open_id=open_id,
                                                       status=self.PURCHASE_ORDER_STATUS_CREATED)

            order_data['purchase_order'] = purchase_order.id

            payment_type = purchase_order.payment_type

            # Check payment data validation
            payload = {'open_id': open_id, 'order_id': order_id, 'payment_type': payment_type,
                       'payment_raw_data': payment_data, 'price_unit': purchase_order.price_unit,
                       'price_total': purchase_order.price_total}

            if notification_order:
                payload['notification_order'] = True
            else:
                payload['notification_order'] = False

            payment_url = payment_util.get_payment_app_url(purchase_order.payment_type)
            response = requests.post(payment_url, json=payload)
            logger_info.info(response.text)
            payment_result = response.json()

            if response.status_code != code.ARIES_200_SUCCESS:
                if response.status_code == code.ARIES_400_BAD_REQUEST:
                    result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                            get_msg(code.ERROR_9000_INTERNAL_API_CALL_FAILED, cn_header))
                elif payment_result['error_code'] == code.ERROR_4001_PAYMENT_VALIDATION_FAILED:
                    result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                            get_msg(code.ERROR_4001_PAYMENT_VALIDATION_FAILED, cn_header))
                    result.set_error(code.ERROR_4001_PAYMENT_VALIDATION_FAILED)
                elif payment_result['error_code'] == code.ERROR_4005_PAYMENT_SYNC_ERROR:
                    result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                            get_msg(code.ERROR_4005_PAYMENT_SYNC_ERROR, cn_header))
                purchase_order.status = 3
                purchase_order.save()
                return Response(result.get_response(), result.get_code())

            logger_info.info('Payment finished')

            # Order saved and coupon using section
            coupon_list = json.loads(purchase_order.coupon_list)
            logger_info.info(coupon_list)

            for coupon in coupon_list:
                coupon_id = coupon['coupon_id']
                coupon_count = CustomerCoupon.objects.filter(id=coupon_id).count()

                if coupon_count == 1:
                    coupon_instance = CustomerCoupon.objects.get(id=coupon_id)
                    coupon_instance.status = 1
                    coupon_instance.used_date = datetime.now()
                    coupon_instance_list.append(coupon_instance)
                else:
                    logger_error.error(get_msg(code.ERROR_4001_PAYMENT_VALIDATION_FAILED))
                    result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                            get_msg(code.ERROR_4001_PAYMENT_VALIDATION_FAILED))
                    result.set_error(code.ERROR_4001_PAYMENT_VALIDATION_FAILED)
                    purchase_order.status = 3
                    purchase_order.save()
                    return Response(result.get_response(), result.get_code())

        except Exception as e:
            logger_error.error(str(e))
            error_code = code.ERROR_3002_PURCHASE_ORDER_NOT_FOUND
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR, get_msg(error_code), cn_header)
            result.set_error(error_code)
            return Response(result.get_response(), result.get_code())

        # Step 3 Order data section
        logger_info.info('Order data section')

        # Order data
        order_data['open_id'] = open_id
        order_data['hub_id'] = purchase_order.hub_id
        order_data['order_id'] = order_id
        order_data['order_status'] = self.ORDER_STATUS_CREATED
        history_date = dateformatter.get_yyyymmdd_now()
        history_payload = [{'status': 0, 'datetime': history_date}]
        order_data['order_status_history'] = json.dumps(history_payload)
        order_data['order_daily_index'] = order_manager_v2.get_daily_order_index()

        # Delivery data
        is_on_site_pickup = purchase_order.delivery_on_site
        address_id = purchase_order.delivery_address_id

        # Check if it was on-site pickup or not
        if is_on_site_pickup:
            logger_info.info('On site pickup')
            hub_name = hub_data.get_hub_name(cn_header, purchase_order.hub_id)
            complete_address = hub_name + '\n - ' + hub_data.get_hub_address(cn_header, purchase_order.hub_id)
            order_data['delivery_on_site'] = purchase_order.delivery_on_site
            order_data['delivery_address'] = complete_address
        else:
            logger_info.info('NOT on site pickup')
            try:
                headers = {'open-id': str(open_id), 'authorization': 'bearer ' + access_token,
                           'Content-Type': 'application/json'}
                response = requests.get(urlmapper.get_url('PRODUCT_ADDRESS_DETAIL') + '/' + str(address_id),
                                        headers=headers)
            except Exception as e:
                logger_info.info(str(e))

            if response.status_code == code.ARIES_200_SUCCESS:
                response_json = response.json()['user_address']
                logger_info.info(response_json)

                # Set delivery address
                recipient_name = response_json['recipient_name']
                recipient_mdn = response_json['recipient_mdn']

                if len(recipient_mdn) <= 0 and len(recipient_name) <= 0:
                    delivery_address = response_json['name']
                else:
                    delivery_address = response_json['name'] + ' - ' + response_json['detail']

                if len(delivery_address) > 300:
                    delivery_address = delivery_address[:300]
                order_data['delivery_address'] = delivery_address
                order_data['delivery_address_lat'] = response_json['latitude']
                order_data['delivery_address_lng'] = response_json['longitude']
                order_data['delivery_recipient_name'] = recipient_name
                order_data['delivery_recipient_mdn'] = recipient_mdn
            else:
                # New address check
                logger_info.info('Address not found error')
                result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                        'Address not found')
                result.set_error(code.ERROR_9000_INTERNAL_API_CALL_FAILED)
                return Response(result.get_response(), result.get_code())

        logger_info.info('After on site pickup')
        order_data['user_name'] = purchase_order.user_name
        order_data['user_telephone'] = purchase_order.user_telephone
        order_data['user_receipt'] = purchase_order.user_receipt
        order_data['delivery_date'] = purchase_order.delivery_date
        order_data['delivery_schedule'] = purchase_order.delivery_schedule
        order_data['delivery_as_fast'] = purchase_order.delivery_as_fast
        order_data['delivery_customer_name'] = purchase_order.user_name
        order_data['delivery_telephone_state'] = 0
        order_data['delivery_telephone'] = 'Delivery telephone'
        pre_time = purchase_order.delivery_start_time
        post_time = purchase_order.delivery_end_time
        delivery_date = str(purchase_order.delivery_date).replace('-', '.')
        order_data['delivery_time'] = delivery_date + ', ' + pre_time + '~' + post_time

        # Shipping data
        order_data['shipping_method'] = purchase_order.shipping_method
        order_data['shipping_status'] = 0

        # Step 4
        logger_info.info('STEP 4')
        order_count = Order.objects.filter(order_id=order_id, open_id=open_id).count()

        if order_count == 1:
            logger_info.info('Order exists')

            order = Order.objects.get(order_id=order_id, open_id=open_id)
            purchase_order = PurchaseOrder.objects.get(order_id=order_id, open_id=open_id)
            purchase_order_serializer = UpcomingPurchaseOrderSerializer(purchase_order)
            purchase_order_data = purchase_order_serializer.data
            purchase_order_data['order_details'] = json.loads(purchase_order_data['order_details'])
            purchase_order_data['shipping_detail'] = json.loads(purchase_order_data['shipping_detail'])
            del purchase_order_data['product_list']
            del purchase_order_data['coupon_list']
            del purchase_order_data['order_hash']

            order_data = UpcomingOrderSerializer(order).data
            order_data['order_start_date'] = dateformatter.get_ordering_complete_date_fmt(order.order_start_date)
            order_data['order_status_history'] = json.loads(order_data['order_status_history'])
            order_data['purchase_order'] = purchase_order_data
            order_data['order_cancel_date'] = ''

            # Get Timetable
            order_data['timetable'] = json.loads('[]')

            result.set('upcoming_order', order_data)
            return Response(result.get_response(), result.get_code())

        # Step 5
        # Create order object and send order data to client
        logger_info.info('Step 5')

        try:
            order_serializer = OrderSerializer(data=order_data)

            if order_serializer.is_valid():
                order_serializer.save()
                logger_info.info('Order valid and save success')

                # Order save success and coupon save
                for coupon_ins in coupon_instance_list:
                    coupon_ins.save()

                # User notification url call
                url = urlmapper.get_url('USER_NOTIFICATION') + '/coupon/1/' + str(len(coupon_instance_list))
                headers = {'open-id': open_id, 'authorization': 'bearer ' + access_token}
                requests.get(url, headers=headers)

                # Get special instruction and include cutlery information
                include_cutlery = purchase_order.include_cutlery
                special_inst = purchase_order.special_instruction

                # Special instruction and include cutlery save call
                url = urlmapper.get_url('USER_CART_INFO_SAVE')
                headers = {'open-id': open_id, 'authorization': 'bearer ' + access_token}
                json_data = {'include_cutlery': include_cutlery, 'special_instruction': special_inst}
                requests.put(url, headers=headers, json=json_data)

                # After user notification
                logger_info.info('After user notification request')
                purchase_order_serializer = UpcomingPurchaseOrderSerializer(purchase_order)
                purchase_order_data = purchase_order_serializer.data
                purchase_order_data['order_details'] = json.loads(purchase_order_data['order_details'])
                purchase_order_data['shipping_detail'] = json.loads(purchase_order_data['shipping_detail'])
                del purchase_order_data['product_list']
                del purchase_order_data['coupon_list']
                del purchase_order_data['order_hash']

                order_data = order_serializer.data
                order = Order.objects.get(id=order_data['id'])
                order_data = UpcomingOrderSerializer(order).data
                order_data['order_start_date'] = dateformatter.get_ordering_complete_date_fmt(order.order_start_date)
                order_data['order_status_history'] = json.loads(order_data['order_status_history'])
                order_data['purchase_order'] = purchase_order_data
                order_data['order_cancel_date'] = ''

                # Get Timetable
                logger_info.info('Get time table')
                order_data['timetable'] = json.loads('[]')

                result.set('upcoming_order', order_data)

                # Check on first purchase
                logger_info.info('Check first purchase')
                first_order_count = Order.objects.filter(open_id=open_id, order_status__lte=10).count()
                if first_order_count == 1:
                    hub_id = purchase_order.hub_id
                    event_order_service = EventOrderService(logger_info, logger_error)
                    event_order_service.create_event_order(0, hub_id, open_id, order_id)
            else:
                logger_error.error(order_serializer.errors)
                result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR, 'Internal server error')
                return Response(result.get_response(), result.get_code())

            purchase_order.status = 1
            purchase_order.save()
            logger_info.info('Purchase order save')

            # Product stock update
            product_list = json.loads(purchase_order.product_list)
            payload = {'trade_type': 0, 'product_list': product_list, 'validate_str': 'GoDbAcKeNdS'}
            url = urlmapper.get_url('PRODUCT_STOCK')
            response = requests.post(url, json=payload)
            logger_info.info(response.text)

            # Order complete
            headers = {'open-id': open_id, 'authorization': 'bearer ' + access_token}
            payload = {'order_id': order_id}
            url = urlmapper.get_url('OPERATION_ORDER_COMPLETE')
            response = requests.post(url, headers=headers, json=payload)
            logger_info.info(response.text)

        except Exception as e:
            logger_error.error(str(e))
            result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR, 'Internal server error')
            return Response(result.get_response(), result.get_code())

        # Step 6
        # Save payment method and notify to admin server
        # Upcoming order notification added
        logger_info.info('Step 6')

        headers = {'AUTHORIZATION': request.META['HTTP_AUTHORIZATION']}
        payload = {'latest_payment_method': purchase_order.payment_type}
        url = urlmapper.get_url('USER_INFO') + '/' + open_id + '/info'
        response = requests.put(url, headers=headers, json=payload)
        logger_info.info(response.json())

        try:
            # Hub message
            logger_info.info('Hub message')

            order_manager = OrderManager(logger_info, logger_error)
            order_list_detail = order_manager.get_order_list(order_id)
            payload = {
                'code': 200, 'message': 'success', 'order': order_list_detail, 'type': 1,
                'order_id': order_id, 'title': 'Here comes a new order'
            }
            url = urlmapper.get_url('HUB_MESSAGE_ANDROID')
            response = requests.post(url, json=payload)
            logger_info.info(response.text)
        except Exception as e:
            logger_info.info(str(e))

        return Response(result.get_response(), result.get_code())