def create_address(self, open_id, address_data):
        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(open_id)

        address_service = UserAddressService(self.logger_info, self.logger_error)

        if address_data['delivery_area']:
            address_service.deselect_address(user_instance)

        user_address_data = address_service.create_address(user_instance, address_data)

        # Address count check and delete address
        address_count = address_service.read_address_count(user_instance)

        if address_count > self.ADDRESS_LIMIT:
            address_service.delete_old_address(user_instance)

        # If address can delivery, address setting
        if user_address_data['delivery_area']:
            hub_id = user_address_data['hub_id']
            address_id = user_address_data['id']

            user_service.set_delivery_address(user_instance, hub_id, address_id, user_address_data)

        return user_address_data
    def get_address_list(self, open_id):
        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(open_id)

        address_service = UserAddressService(self.logger_info, self.logger_error)
        address_list = address_service.read_address_list(user_instance)

        return address_list
    def get_user_cart_info_data(self, user_open_id):
        self.logger_info.info('[UserManagerV2][get_user_cart_info][' +
                              user_open_id + ']')

        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(user_open_id)
        cart_info = user_service.get_user_cart_info(user_instance)

        return cart_info
    def get_user_info(self, user_open_id):
        self.logger_info.info('[UserManagerV2][get_user_info][' +
                              user_open_id + ']')

        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(user_open_id)
        user_info = user_service.get_user_info_with_ins(user_instance)

        return UserInfoSerializer(user_info).data
    def get_user_data(self, user_open_id):
        self.logger_info.info('[UserManagerV2][get_default_hub_id][' +
                              user_open_id + ']')

        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(user_open_id)
        user_data = UserAccountSerializer(user_instance).data

        return user_data
    def delete_address(self, open_id, address_id):
        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(open_id)

        address_service = UserAddressService(self.logger_info, self.logger_error)
        user_address_data = address_service.delete_address(user_instance, int(address_id))

        # If address has changed
        if user_address_data is not None:
            hub_id = user_address_data['hub_id']
            address_id = user_address_data['id']

            user_data = user_service.set_delivery_address(user_instance, hub_id, address_id, user_address_data)

            current_delivery_type = user_data['current_delivery_type']
            default_address = user_data['default_address']
            default_address_id = user_data['default_address_id']
            default_recipient_name = user_data['default_recipient_name']
            default_recipient_mdn = user_data['default_recipient_mdn']
        else:
            # If user address data is none, get a new user instance
            user_instance = user_service.get_user_instance(open_id)
            current_delivery_type = user_instance.current_delivery_type
            default_address = user_instance.default_address
            default_address_id = user_instance.default_address_id
            default_recipient_name = user_instance.default_recipient_name
            default_recipient_mdn = user_instance.default_recipient_mdn

        result = {
            'current_delivery_type': current_delivery_type,
            'default_address': default_address,
            'default_address_id': default_address_id,
            'default_recipient_name': default_recipient_name,
            'default_recipient_mdn': default_recipient_mdn
        }

        return result
    def select_hub(self, open_id, cn_header, hub_id):
        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(open_id)

        address_service = UserAddressService(self.logger_info, self.logger_error)

        # Deselect addresses
        address_service.deselect_address(user_instance)

        # Select on site pickup
        user_service.set_delivery_pick_up(user_instance, cn_header, hub_id)

        address_list = address_service.read_address_list(user_instance)

        return address_list
    def select_address(self, open_id, address_id):
        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(open_id)

        address_service = UserAddressService(self.logger_info, self.logger_error)

        # Deselect address
        address_service.deselect_address(user_instance)

        # Select delivery address
        address_service.select_address(user_instance, address_id)
        user_address_data = address_service.read_address(user_instance, address_id)
        hub_id = user_address_data['hub_id']
        user_service.set_delivery_address(user_instance, hub_id, address_id, user_address_data)

        address_list = address_service.read_address_list(user_instance)

        return address_list
    def update_address(self, open_id, address_id, address_data):
        user_service = UserService(self.logger_info, self.logger_error)
        user_instance = user_service.get_user_instance(open_id)

        # Check delivery area
        if 'delivery_area' in address_data:
            adr_delivery_area = address_data['delivery_area']
        else:
            adr_delivery_area = False

        # Update address and select check
        if 'selected_address' in address_data:
            selected_address = address_data['selected_address']
            del address_data['selected_address']
        else:
            selected_address = False

        # User information overwrite check
        if 'overwrite_user_name' not in address_data:
            address_data['overwrite_user_name'] = False

        address_service = UserAddressService(self.logger_info, self.logger_error)
        updated_address = address_service.update_address(user_instance, int(address_id), address_data)

        # After update address, select address id
        if selected_address and adr_delivery_area:
            address_service.deselect_address(user_instance)
            address_service.select_address(user_instance, address_id)
            user_service.set_delivery_address(user_instance, updated_address['hub_id'], address_id, updated_address)

        # If not delivery area, select next address or None selected
        if selected_address and not adr_delivery_area:
            address_service.deselect_address(user_instance)
            next_address_id = address_service.read_latest_possible_adr(user_instance)

            if next_address_id != 0:
                address_service.select_address(user_instance, next_address_id)
            else:
                user_service.set_delivery_none(user_instance)

        return updated_address
    def send_sign_up_push(self, user_open_id, cn_header):
        self.logger_info.info('[UserManagerV2][send_sign_up_push][' +
                              str(user_open_id) + ']')
        try:
            user_service = UserService(self.logger_info, self.logger_error)
            referral_service = ReferralService(self.logger_info,
                                               self.logger_error)

            user_instance = user_service.get_user_instance(user_open_id)
            user_info_ins = user_service.get_user_info_with_ins(user_instance)
            referral_data = referral_service.read_referral_event(user_open_id)

            push_agreement = user_instance.push_agreement
            os_type = user_info_ins.os_type
            self.logger_info.info(
                '[UserManagerV2][send_sign_up_push][Push data read complete]')

            if (os_type == 0 or os_type
                    == 1) and 'friend_membership_count' in referral_data:
                self.logger_info.info('[UserManagerV2][send_sign_up_push][' +
                                      str(os_type) + ']')

                friend_count = referral_data['friend_membership_count']
                friend_check = True if friend_count == 1 or (friend_count %
                                                             5) == 0 else False

                if str(push_agreement).lower() == 'y' and friend_check:
                    self.logger_info.info(
                        '[UserManagerV2][send_sign_up_push][Push send]')
                    title = ''
                    if cn_header:
                        message = self.SIGN_UP_MSG_CN.format(str(friend_count))
                    else:
                        message = self.SIGN_UP_MSG_EN.format(str(friend_count))
                    push_sender = PushInstance.factory(os_type, user_open_id,
                                                       title, message,
                                                       self.REF_TARGET, '')
                    push_sender.send_push_notification()
        except Exception as e:
            self.logger_info.info(str(e))
class ReferralManager:

    def __init__(self, logger_info, logger_error):
        self.logger_info = logger_info
        self.logger_error = logger_error

        # Check user service when decouple user and ucc domain
        self.referral_service = ReferralService(logger_info, logger_error)
        self.user_service = UserService(logger_info, logger_error)

    def get_referral_status(self, open_id, access_token, accept_lang):
        # Get referral event data
        referral_event_data = self.referral_service.read_referral_event(open_id)
        friend_coupon_status = referral_event_data['friend_coupon_status']
        first_coupon_status = referral_event_data['first_coupon_status']

        # Check qr code exists
        if not referral_event_data['has_invitation_image']:
            unique_id = referral_event_data['share_id']
            qr_result = ref_util.generate_qr_code(unique_id, open_id, access_token)

            if qr_result:
                self.referral_service.update_referral_qr_code(open_id, unique_id)

            referral_event_data = self.referral_service.read_referral_event(open_id)
            friend_coupon_status = referral_event_data['friend_coupon_status']
            first_coupon_status = referral_event_data['first_coupon_status']

        # Friend membership count
        if referral_event_data['friend_membership_count'] > 25:
            referral_event_data['friend_membership_count'] = 25
            referral_event_data['friend_membership_over'] = True

        # Thumbnail data change with language and add share description to referral event
        ref_util.get_image_with_language(referral_event_data, accept_lang)
        ref_util.get_share_information(referral_event_data, accept_lang)

        # Get coupon description
        referral_event_data['description'] = ref_util.get_coupon_description(30, accept_lang)

        # Get coupon id and description
        coupon_ids = []
        for coupon in friend_coupon_status:
            coupon['description'] = ref_util.get_coupon_description(30, accept_lang)
            coupon_ids.append(coupon['id'])

        for coupon in first_coupon_status:
            coupon['description'] = ref_util.get_coupon_description(30, accept_lang)
            coupon_ids.append(coupon['id'])

        coupon_info = get_coupon_information(coupon_ids, accept_lang)

        for coupon in coupon_info:
            coupon_id = coupon['id']
            cash_discount = int(coupon['cash_discount'])
            for friend_coupon in friend_coupon_status:
                if friend_coupon['id'] == coupon_id:
                    friend_coupon['name'] = ref_util.friend_coupon_naming(str(cash_discount), accept_lang)

            for first_coupon in first_coupon_status:
                if first_coupon['id'] == coupon_id:
                    first_coupon['name'] = ref_util.pur_coupon_naming(str(cash_discount), accept_lang)

        # First purchase coupon calculate
        first_purchase_rest_count = referral_event_data['first_purchase_rest_count']
        result_purchase_coupon_list = []

        if first_purchase_rest_count > 0:
            first_coupon = first_coupon_status[0]
            for index in range(first_purchase_rest_count):
                result_purchase_coupon_list.append(first_coupon)
            referral_event_data['first_coupon_available'] = True

        referral_event_data['first_coupon_status'] = result_purchase_coupon_list
        return referral_event_data

    def get_referral_information(self, accept_lang):
        friend_type = 0
        first_type = 1

        friend_coupon_status = self.referral_service.read_referral_information(friend_type)
        first_coupon_status = self.referral_service.read_referral_information(first_type)

        coupon_ids = []
        for coupon in friend_coupon_status:
            coupon_ids.append(coupon['id'])

        for coupon in first_coupon_status:
            coupon_ids.append(coupon['id'])

        coupon_info = get_coupon_information(coupon_ids, accept_lang)

        for coupon in coupon_info:
            coupon_id = coupon['id']
            cash_discount = int(coupon['cash_discount'])

            for friend_coupon in friend_coupon_status:
                if friend_coupon['id'] == coupon_id:
                    friend_coupon['name'] = ref_util.friend_coupon_naming(str(cash_discount), accept_lang)

            for first_coupon in first_coupon_status:
                if first_coupon['id'] == coupon_id:
                    first_coupon['name'] = ref_util.pur_coupon_naming(str(cash_discount), accept_lang)

        referral_info_data = {
            'friend_coupon_status': friend_coupon_status,
            'first_coupon_status': first_coupon_status
        }

        return referral_info_data

    def issue_referral_coupon(self, open_id, cn_header, coupon_type, coupon_list):
        referral_event = self.referral_service.read_referral_event(open_id)

        if coupon_type == 0:
            target_coupon_list = referral_event['friend_coupon_status']
            user_reward_count = referral_event['friend_membership_count']
        else:
            target_coupon_list = referral_event['first_coupon_status']
            user_reward_count = referral_event['first_purchase_rest_count']

        # Find target coupons
        issue_coupon_list = []
        coupon_reward_count = 0

        for req_coupon in coupon_list:
            for tag_coupon in target_coupon_list:
                if tag_coupon['id'] == req_coupon['id']:
                    # Coupon reward condition check
                    coupon_reward_count = tag_coupon['reward_count']
                    coupon_issue_complete = tag_coupon['issue_complete']

                    if coupon_issue_complete:
                        raise BusinessLogicError(message_mapper.get(3202, cn_header), 3202, None)

                    if user_reward_count < coupon_reward_count:
                        raise BusinessLogicError(message_mapper.get(3201, cn_header), 3201, None)

                    issue_coupon_list.append(tag_coupon)

        # Coupon reward point update
        if coupon_type == 1:
            all_reward_count = len(coupon_list)*coupon_reward_count
            self.referral_service.update_referral_first_information(open_id, all_reward_count)

        # Coupon issue and User coupon_count update
        coupon_code = 'referral_20180725'
        sender_id = 'Admin'
        issue_coupon(open_id, cn_header, issue_coupon_list, coupon_code, sender_id)

        # Get new referral information
        referral_event = self.referral_service.read_referral_event(open_id)
        if coupon_type == 0:
            target_coupon_list = referral_event['friend_coupon_status']
            user_reward_count = referral_event['friend_membership_count']
        else:
            target_coupon_list = referral_event['first_coupon_status']
            user_reward_count = referral_event['first_purchase_rest_count']

        # Rest coupon status check
        has_reset = False

        if coupon_type == 0:
            for coupon in issue_coupon_list:
                for user_coupon in target_coupon_list:
                    if coupon['id'] == user_coupon['id']:
                        user_coupon['issue_available'] = False
                        user_coupon['issue_complete'] = True
        else:
            if user_reward_count <= 0:
                for coupon in target_coupon_list:
                    coupon['issue_available'] = False
                    coupon['issue_complete'] = False
            else:
                for coupon in target_coupon_list:
                    coupon['issue_available'] = True
                    coupon['issue_complete'] = False

        self.referral_service.update_referral_coupon_status(open_id, coupon_type, target_coupon_list)

        # Get new referral information
        referral_event = self.referral_service.read_referral_event(open_id)
        if coupon_type == 0:
            target_coupon_list = referral_event['friend_coupon_status']
        else:
            target_coupon_list = referral_event['first_coupon_status']

        # Get coupon id and description, name
        accept_lang = 'zh' if cn_header else 'en'

        coupon_ids = []
        for coupon in target_coupon_list:
            coupon['description'] = ref_util.get_coupon_description(30, accept_lang)
            coupon_ids.append(coupon['id'])

        coupon_info = get_coupon_information(coupon_ids, accept_lang)

        for coupon in coupon_info:
            coupon_id = coupon['id']

            for target_coupon in target_coupon_list:
                if target_coupon['id'] == coupon_id:
                    cash_discount = int(coupon['cash_discount'])
                    if coupon_type == 0:
                        target_coupon['name'] = ref_util.friend_coupon_naming(str(cash_discount), accept_lang)
                    else:
                        target_coupon['name'] = ref_util.pur_coupon_naming(str(cash_discount), accept_lang)

        # Result mapping from coupon_list
        if coupon_type == 0:
            friend_membership_count = referral_event['friend_membership_count']

            # Friend membership count
            if friend_membership_count > 25:
                friend_membership_count = 25
                referral_over = True
            else:
                referral_over = False
                if referral_event['friend_membership_over']:
                    self.referral_service.update_referral_over_flag(open_id, False)

            result = {
                'coupon_status': target_coupon_list, 'has_reset': has_reset,
                'friend_membership_count': friend_membership_count, 'friend_membership_over': referral_over
            }
        else:
            rest_point = referral_event['first_purchase_rest_count']
            result_coupon_list = []

            if len(target_coupon_list) >= 1:
                coupon = target_coupon_list[0]
                for index in range(rest_point):
                    result_coupon_list.append(coupon)

            result = {
                'coupon_status': result_coupon_list, 'has_reset': has_reset
            }

        return result

    def check_coupon_reset(self, open_id):
        referral_event = self.referral_service.read_referral_event(open_id)
        friend_coupon_list = referral_event['friend_coupon_status']
        user_membership_count = referral_event['friend_membership_count']

        all_clear = True
        for coupon in friend_coupon_list:
            if not coupon['issue_complete']:
                all_clear = False

        if all_clear:
            self.referral_service.update_referral_reset_friend_info(open_id)
            user_membership_count -= 25

            for coupon in friend_coupon_list:
                if coupon['reward_count'] <= user_membership_count:
                    coupon['issue_available'] = True
                else:
                    coupon['issue_available'] = False
                coupon['issue_complete'] = False

            self.referral_service.update_referral_coupon_status(open_id, 0, friend_coupon_list)

        return all_clear

    def get_open_id_from_unique_id(self, share_id):
        referral_event = self.referral_service.read_referral_with_unique_id(share_id)

        if referral_event is None:
            raise DataValidationError('Do not find unique id', None)

        referral_result = {'open_id': referral_event.open_id, 'share_id': referral_event.share_id}

        return referral_result

    def do_first_purchase_up(self, open_id):
        referral = self.referral_service.first_order_up(open_id)
        rest_count = str(referral.first_purchase_rest_count)

        user_ins = self.user_service.get_user_instance(open_id)
        user_locale = user_ins.locale

        if user_locale == 'en' or user_locale == 'En':
            push_message = 'Good friends you have! You’ve got {} coupon you can use right now~'.format(rest_count)
        else:
            push_message = '好友送福利!你获得{}张优惠礼券,快去使用吧~'.format(rest_count)

        payload = {
            'code': 200, 'message': 'success', 'order': '', 'type': 0,
            'order_id': '', 'title': push_message
        }
        url = urlmapper.get_url('HUB_MESSAGE_ANDROID')
        response = requests.post(url, json=payload)
        self.logger_info.info(response.content)
class ReceiptManager:

    SIGN_UP_MSG_EN = 'You have got good friends who got you {} coupon just now!'
    SIGN_UP_MSG_CN = '你的好友刚刚为你赢得{}张优惠礼券!'

    REF_TARGET = 101

    def __init__(self, logger_info, logger_error):
        self.logger_info = logger_info
        self.logger_error = logger_error

        self.user_service = UserService(self.logger_info, self.logger_error)
        self.receipt_service = UserReceiptService(self.logger_info,
                                                  self.logger_error)

    def create_user_receipt(self, user_open_id, user_receipt_data, cn_header):
        """
        Create user receipt
        :param user_open_id: User open id
        :param user_receipt_data: User receipt data to create
        :param cn_header: Language data
        :return: Created user and user receipt list json object
        """
        user_instance = self.user_service.get_user_instance(user_open_id)
        receipt_count = self.receipt_service.read_user_receipt_count(
            user_instance)

        if receipt_count >= 5:
            err_code = code.ERROR_1201_RECEIPT_LIMIT_ERROR
            err_msg = message_mapper.get(err_code, cn_header)
            raise BusinessLogicError(err_msg, err_code, None)

        receipt_data = self.receipt_service.create_user_receipt(
            user_instance, user_receipt_data)
        receipt_id = receipt_data['id']
        self.receipt_service.select_receipt(user_instance, receipt_id)
        return self.receipt_service.read_user_receipt(user_instance, cn_header)

    def read_user_receipt(self, user_open_id, cn_header=True):
        """
        Read user's receipt list
        :param user_open_id: User open id
        :param cn_header: User language header
        :return: User's receipt list json object
        """
        user_instance = self.user_service.get_user_instance(user_open_id)
        return self.receipt_service.read_user_receipt(user_instance, cn_header)

    def update_user_receipt(self, user_open_id, user_receipt_id,
                            user_receipt_data, cn_header):
        """
        Update user's receipt data
        :param user_open_id: User open id
        :param user_receipt_id: Receipt id
        :param user_receipt_data: Receipt data for update
        :param cn_header: Language header info
        :return: Updated receipt json object
        """
        user_instance = self.user_service.get_user_instance(user_open_id)
        self.receipt_service.update_user_receipt(user_instance,
                                                 user_receipt_id,
                                                 user_receipt_data)

        return self.receipt_service.read_user_receipt(user_instance, cn_header)

    def delete_user_receipt(self, user_open_id, user_receipt_id, cn_header):
        """
        Delete user's receipt
        :param user_open_id: User open id
        :param user_receipt_id: User receipt id
        :param cn_header: Language header
        :return: Deleted number. Please check user's selected receipt issue
        """
        user_instance = self.user_service.get_user_instance(user_open_id)
        self.receipt_service.delete_user_receipt(user_instance,
                                                 user_receipt_id)

        return self.receipt_service.read_user_receipt(user_instance, cn_header)

    def select_user_receipt(self, user_open_id, user_receipt_id):
        """
        Select user receipt
        :param user_open_id: User open id
        :param user_receipt_id: User receipt id
        :return: Selected receipt data
        """
        user_instance = self.user_service.get_user_instance(user_open_id)
        selected_id = self.receipt_service.select_receipt(
            user_instance, user_receipt_id)

        return selected_id
    def post(self, request):
        result = ResultResponse(code.ARIES_200_SUCCESS, 'success')
        request_data = request.data
        lang_info = parse_language_v2(request.META)

        logger_info.info(request_data)

        try:
            login_type = request_data['login_type']
            login_key = request_data['login_key']
            login_value = request_data['login_value']
            login_sns_open_id = ''
            login_sns_access_token = ''
            login_sns_refresh_token = ''

            login_type = int(login_type)
        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())

        # Mobile app/web: 0, QQ: 1, WeChat: 2, Password registration: 3
        # Check sms verification & user count
        if login_type == 0:
            user_count = User.objects.filter(mdn=login_key).count()

            # MDN is only one in member pool
            if user_count >= 1:
                result = ResultResponse(
                    code.ARIES_500_INTERNAL_SERVER_ERROR,
                    get_msg(code.ERROR_1005_USER_ALREADY_REGISTRATION))
                result.set_error(code.ERROR_1005_USER_ALREADY_REGISTRATION)
                logger_error.error(
                    get_msg(code.ERROR_1005_USER_ALREADY_REGISTRATION))
                return Response(result.get_response(), result.get_code())

            today = datetime.datetime.today()
            sms_auth = SmsAuthHistory.objects.filter(
                date=today, target_mdn=login_key).latest('id')
            sms_auth_count = sms_auth.verification_count

            if not sms_auth.has_verified or sms_auth_count > 3:
                result = ResultResponse(
                    code.ARIES_500_INTERNAL_SERVER_ERROR,
                    get_msg(code.ERROR_1008_SMS_VALIDATION_INFO_NOT_FOUND))
                result.set_error(code.ERROR_1008_SMS_VALIDATION_INFO_NOT_FOUND)
                logger_error.error(
                    get_msg(code.ERROR_1008_SMS_VALIDATION_INFO_NOT_FOUND))
                return Response(result.get_response(), result.get_code())

            response = requests.get(
                urlmapper.get_url('USER_SMS_VERIFICATION') + login_key)

            if response.status_code != code.ARIES_200_SUCCESS:
                result = ResultResponse(
                    code.ARIES_500_INTERNAL_SERVER_ERROR,
                    get_msg(code.ERROR_1008_SMS_VALIDATION_INFO_NOT_FOUND))
                result.set_error(code.ERROR_1008_SMS_VALIDATION_INFO_NOT_FOUND)
                logger_error.error(
                    get_msg(code.ERROR_1008_SMS_VALIDATION_INFO_NOT_FOUND))
                return Response(result.get_response(), result.get_code())

            # create open id
            random_token = str(uuid.uuid4()).split('-')
            open_id = str(random_token[0] + random_token[2] +
                          random_token[4]).upper()

            # get token from server
            if login_type is 0:
                payload = {'user_open_id': open_id, 'user_account': login_key}
            else:
                payload = {
                    'user_open_id': open_id,
                    'user_account': login_sns_open_id
                }
            response = requests.post(urlmapper.get_url('PLATFORM_SERVER'),
                                     json=payload)

            if response.status_code == code.ARIES_200_SUCCESS:
                response_json = response.json()
                token = response_json['token']
                token = str(token).upper()
            else:
                result = ResultResponse(code.ARIES_500_INTERNAL_SERVER_ERROR,
                                        'API connection fail')
                result.set_error(code.ERROR_9000_INTERNAL_API_CALL_FAILED)
                logger_error.error(response.text)
                return Response(result.get_response(), result.get_code())

            # Sign-up user
            if login_type is 0:
                user_instance = User.objects.create(open_id=open_id,
                                                    mdn=login_key,
                                                    name=login_key,
                                                    mdn_verification=True,
                                                    access_token=token,
                                                    parent_type=0)
            else:
                user_instance = User.objects.create(open_id=open_id,
                                                    mdn='',
                                                    name=open_id[:6],
                                                    mdn_verification=False,
                                                    access_token=token)

            UserLoginInfo.objects.create(
                user=user_instance,
                login_type=login_type,
                login_key=login_key,
                login_value=login_value,
                login_sns_open_id=login_sns_open_id,
                login_sns_access_token=login_sns_access_token,
                login_sns_refresh_token=login_sns_refresh_token)

            UserInfo.objects.create(user=user_instance, number_of_logon=0)

            user_notify_info = UserNotifyInfo.objects.create(
                user=user_instance)

            UserGrade.objects.create(user=user_instance,
                                     type=0,
                                     extra_meal_point=0,
                                     upgrade_date=datetime.datetime.now())

            ShoppingBag.objects.create(user=user_instance, )

            user_serializer = UserAccountSerializer(user_instance)
            user_data = user_serializer.data

            # User notify data
            notify_info = UserNotifyInfo.objects.get(user=user_instance)
            notify_info_serializer = UserNotifyInfoSerializer(notify_info)
            notify_info_data = notify_info_serializer.data
            del notify_info_data['id']
            del notify_info_data['user']
            user_data['notification_info'] = notify_info_data

            # User grade data
            user_grade = UserGrade.objects.get(user=user_instance)
            grade_serializer = UserGradeSerializer(user_grade)
            user_data['grade'] = grade_serializer.data
            user_data['connection_account'] = json.loads(
                user_data['connection_account'])

            result.set('auto_registration', False)
            result.set('user', user_data)

            # If there is Member promotion, call member coupon interface
            member_promo_result = request_member_promotion(
                open_id, 0, lang_info.accept_lang)
            result.set_map(member_promo_result)
            logger_info.info('[views_sign][SignUp][post][' +
                             str(member_promo_result) + ']')

            if member_promo_result['has_member_promotion']:
                user_notify_info.has_new_coupon = True
                user_notify_info.coupon_count = 1
                user_notify_info.save()

            # If there is a registration with referrer, update referrer count
            if 'referrer_id' in request_data:
                logger_info.info('[views_sign][SignUp][post][' +
                                 'REFERRER SIGNUP' + ']')
                user_mdn = user_instance.mdn
                user_referral_service = UserReferralService(
                    logger_info, logger_error)

                # Check if its mdn was used for registration before
                registration_check = user_referral_service.read_user_referral_info_check(
                    user_mdn)

                if registration_check:
                    share_id = request_data['referrer_id']
                    referrer_open_id = request_share_id_validation(share_id)

                    # Save User referral history
                    logger_info.info('[views_sign][SignUp][post][' +
                                     str(open_id) + ']')
                    logger_info.info('[views_sign][SignUp][post][' +
                                     str(user_mdn) + ']')
                    logger_info.info('[views_sign][SignUp][post][' +
                                     str(share_id) + ']')
                    logger_info.info('[views_sign][SignUp][post][' +
                                     str(referrer_open_id) + ']')

                    ref = user_referral_service.create_user_referral_info(
                        open_id, user_mdn, share_id, referrer_open_id)
                    logger_info.info('[views_sign][SignUp][post][' + str(ref) +
                                     ']')

                    user_service = UserService(logger_info, logger_error)
                    referrer_user = user_service.get_user_instance(
                        referrer_open_id)
                    referrer_notify_info = user_service.get_user_notify_info(
                        referrer_user)
                    referrer_notify_info.has_referral_event = True
                    referrer_notify_info.save()
                    logger_info.info(
                        '[views_sign][SignUp][post][Notification information saved]'
                    )

                    # Send notification
                    user_manager_v2 = UserManagerV2(logger_info, logger_error)
                    user_manager_v2.send_sign_up_push(referrer_open_id, True)
                    logger_info.info(
                        '[views_sign][SignUp][post][Send push completed]')
                else:
                    logger_info.info(
                        '[views_sign][SignUp][post][Referral already registration.]'
                    )

            # Change user info
            user_info = UserInfo.objects.get(user=user_instance)
            user_info.number_of_logon = F('number_of_logon') + 1
            user_info.date_account_last_modified = datetime.datetime.now()
            if 'os_type' in request_data:
                if request_data['os_type'] == 0 or request_data['os_type'] == 1:
                    user_info.os_type = request_data['os_type']
            user_info.save()

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

        else:
            result = ResultResponse(code.ARIES_400_BAD_REQUEST,
                                    'Sign up method not supported')
            logger_info.info('Sign up method not supported')
            return Response(result.get_response(), result.get_code())