예제 #1
0
class CMyCenter(BaseMyCenterControl):
    def __init__(self):
        from WeiDian.service.SProduct import SProduct
        self.sproduct = SProduct()
        from WeiDian.service.SUser import SUser
        self.suser = SUser()
        from WeiDian.service.SMyCenter import SMyCenter
        self.smycenter = SMyCenter()
        from WeiDian.service.SLevelRules import SLevelRules
        self.slevelrules = SLevelRules()
        from WeiDian.service.SUserAddress import SUserAddress
        self.suesraddress = SUserAddress()
        from WeiDian.service.SBankCard import SBankCard
        self.sbankcard = SBankCard()
        self.sorder = SOrder()
        self.sraward = SRaward()
        self.spartnermatch = SPartnerSellOrInviteMatch()
        self.stopnav = STopNav()

    @verify_token_decorator
    def get_info_top(self):
        """个人中心需要的数据"""
        try:
            if is_tourist():
                return AUTHORITY_ERROR(u"未登录")
            data = dict()
            my_info = request.user
            level = my_info.level
            uslevel = userlevel.get(str(level), '普通用户')
            level = 'partner' if level > 0 else 'ordinary'

            my_info.fill(level, 'level')
            my_info.fill(uslevel, 'uslevel')
            data.setdefault('user', my_info)
            usid = my_info.id
            print(my_info.USname).encode('utf8')
            print(my_info.USid).encode('utf8')
            logger.debug("get my info by usid")
            show = 0
            # 正在进行中的指定等级的合伙人活动
            partner_match = self.spartnermatch.get_lasting_partner_match(
                level=my_info.USlevel)
            # 如果是合伙人, 且活动进行中
            if is_partner() and partner_match:
                show = 1
                data.setdefault('match_type', partner_match.PSIMtype)
                # 成功超过vip数量
                psimid = partner_match.PSIMid
                my_achev = self.spartnermatch.get_partner_match_mount_by_usidpsmid(
                    usid, psimid)
                my_achev_value = my_achev.sellorinvitemount if my_achev else 0  # 我的销售总额(人数)

                gt_my_sell_count = self.spartnermatch.get_partner_match_mount_gt_value(
                    psimid, my_achev_value)  # 营业额(人数)比我多的
                partner_num = self.suser.get_partner_count_in_current_level(
                    request.user.USlevel)  # 该等级vip总数
                lt_my_sell_count = partner_num - gt_my_sell_count  # 比我销售(人数)少的
                partner_num = partner_num or 1
                percents = int(float(lt_my_sell_count) / partner_num *
                               100)  # 超过的同等级的百分比
                my_info.fill(percents, 'overpercents')  # 超过%的vip
                data.setdefault('myranking', percents)
                # 未完成还需多少升级
                try:
                    partner_match.PSIMrule = match_rule = json.loads(
                        partner_match.PSIMrule)
                    achev_level_value = {
                        k: int(v) - my_achev_value
                        for k, v in match_rule.items()
                        if int(v) > my_achev_value
                    }
                    #
                    if achev_level_value:  # 是否有下一级
                        next_level = sorted(achev_level_value.keys())[0]
                        # 当前等级(未用到)
                        current_level = int(next_level) - 1
                        to_next = achev_level_value[next_level]
                        my_info.fill(to_next, 'next')
                        data.setdefault('next', to_next)
                    else:
                        my_info.fill(0, 'next')
                        current_level = sorted(achev_level_value.keys())[-1]

                except ValueError as e:
                    print('保级错误')
                    my_info.fill('0', 'next')
                #     pass
                # 保级差别
            response = import_status("get_my_info_success", "OK")
            data.setdefault('show', show)
            response["data"] = data
            return response
        except Exception as e:
            logger.exception("get myinfo error")
            raise SYSTEM_ERROR()

    @verify_token_decorator
    def set_schedual_show(self):
        """设置个人主页升级进度显示(vip数据统计), 素材圈显示, 待评价"""
        if not is_admin():
            raise TOKEN_ERROR(u'请使用管理员登录')
        # data = parameter_required(u'vip_match', u'material', u'wait_apply')
        data = request.json
        paras_list = ['vip_match', 'material', 'wait_apply']
        if not data or not filter(lambda x: x in paras_list, data):
            raise PARAMS_MISS()
        if 'vip_match' in data:  # vip进度, 写在model里
            vip_match_show = False if str(
                data.get('vip_match')) == '1' else True
            updated = self.spartnermatch.update_partner_match(
                1,
                {  # 更改: 这里的level没有用
                    'PSIMisclose': vip_match_show
                })
        if 'material' in data:  # 素材圈是否显示, 写在model里
            material_show = False if str(data.get('material')) == '1' else True
            updated = self.stopnav.update_topnav_by_tnidorname(
                data={'Tisdelete': material_show}, name='素材圈')

        if 'wait_apply' in data:  # 写在配置文件里
            wait_apply_show = data.get('wait_apply')
            wait_apply_show = '0' if str(wait_apply_show) == '0' else '1'
            Partner().set_item('show', 'wait_apply', wait_apply_show)
        msg = 'update_success'
        data = import_status(msg, "OK")
        return data

    def get_schedual_show(self):
        """获取控制中心显示隐藏详情"""
        match = self.spartnermatch.get_lasting_partner_match(level=1)
        vip_match = 1 if match else 0
        mater = self.stopnav.get_topnav_by_name('素材圈')
        material = 0 if mater.Tisdelete else 1
        wait_apply = Partner().get_item('show', 'wait_apply')
        data = import_status('get_success', 'OK')
        data['data'] = {
            'vip_match': vip_match,
            'material': material,
            'wait_apply': wait_apply,
        }
        return data

    @verify_token_decorator
    def get_today_total(self):
        """今日"""
        if not is_partner():
            raise TOKEN_ERROR(u'请使用vip登录')
        usid = request.user.id
        # 今日营业额
        today_orders = self.sorder.get_today_order_by_usid_status(
            usid, finished_pay_status)
        sold_mount_list = [x.OImount for x in today_orders] or [0]
        sold_mount = sum(sold_mount_list)
        # 今日赚
        today_earn = sold_mount * Partner().one_level_divide
        today_earn = round(today_earn, 2)
        # 额外赚
        # todo
        other_earn = 0
        # 新衣币
        new_cloth_bit = self.sraward.get_reward_by_usid(usid)
        bit_num_list = [x.RAnumber for x in new_cloth_bit] or [0]
        bit_num_mount = sum(bit_num_list)
        response = import_status('get_today_earn_success', 'OK')
        data = {
            'sold_mount': sold_mount,
            'today_earn': today_earn,
            'other_earn': other_earn,
            'bit_num_mount': bit_num_mount
        }
        response['data'] = data
        return response

    @verify_token_decorator
    def get_levelrules(self):
        if is_tourist():
            return AUTHORITY_ERROR(u"未登录")
        try:
            lr_list = self.slevelrules.get_rule_list()
            logger.debug("get level rules")
            map(lambda x: setattr(x, 'LRtext', re.sub('\s', '', x.LRtext)),
                lr_list)
            user = self.suser.get_user_by_user_id(request.user.id)
            if user.USlevel == 0:
                user.level = 'ordinary'
            if user.USlevel > 0:
                user.level = 'partner'
            user.add('level').hide('USid', 'USname', 'USheader')
            data = import_status("get_levelrules_success", "OK")
            data['data'] = lr_list
            data['userlevel'] = user.level
            return data
        except:
            logger.exception("get level rules error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def get_accountinfo(self):
        if is_tourist():
            return AUTHORITY_ERROR(u"未登录")
        usid = request.user.id
        user = self.suser.get_user_by_user_id(usid)
        logger.debug("get info success, this user is %s", user.USname)
        default_address = self.suesraddress.get_default_address_by_usid(usid)
        if not default_address:
            first_address = self.suesraddress.get_first_no_default_address(
                usid)
        address = default_address or first_address
        if address:
            logger.info("get user address success")
            location = self.suesraddress.get_addressinfo_by_areaid(
                address.areaid)
            logger.info("get address detail success")
            for area, city, provice in location:
                locationname = getattr(provice, "name", '') + getattr(
                    city, "name", '') + getattr(area, "name", '')
        else:
            locationname = ''
        # print ''.join([x[1] for x in area])
        bankcard = self.sbankcard.get_bankcard_by_usid(usid)
        response = import_status("get_accountinfo_success", "OK")
        response['data'] = {
            "user": user.hide('USid'),
            # "address": '%s%s' %(locationname, address.UAtext),
            "address": '%s%s' % (locationname, getattr(address, "UAtext", '')),
            "bankcard": getattr(bankcard, "BCnumber", '')
        }
        return response

    """用户地址信息"""

    @verify_token_decorator
    def get_useraddress(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        try:
            adderss_list = self.suesraddress.get_address_list_by_usid(
                request.user.id)
            logger.debug("get address list")
            self.fill_areainfo_by_areaid(adderss_list)
            data = import_status("get_useraddress_success", "OK")
            data['data'] = adderss_list
            return data
        except:
            logger.exception("get useraddress by usid error ")
            return SYSTEM_ERROR

    def fill_areainfo_by_areaid(self, address_list):
        for address in address_list:
            adr = self.suesraddress.get_address_by_uaid(address.UAid)
            addressinfoes = self.suesraddress.get_addressinfo_by_areaid(
                adr.areaid)
            for addressinfo in addressinfoes:
                address.addressinfo = addressinfo
                address.add("addressinfo")
        return address_list

    @verify_token_decorator
    def get_one_or_default_address(self):
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        uaid = request.args.to_dict().get('uaid')
        usid = request.user.id
        logger.debug("get uaid is %s", uaid)
        if uaid is not None:
            uafilter = {'UAid': uaid}
        else:
            uafilter = {'USid': usid, 'UAdefault': True, 'UAisdelete': False}
        default_address = self.suesraddress.get_one_or_default_address(
            uafilter)
        if not default_address:
            any_address = self.suesraddress.get_first_no_default_address(usid)
            if not any_address:
                raise NOT_FOUND(u'该用户未设置地址信息')
        address = default_address or any_address
        if address:
            logger.info("get address success, now to fill detail")
        addressinfoes = self.suesraddress.get_addressinfo_by_areaid(
            address.areaid)
        for addressinfo in addressinfoes:
            address.addressinfo = addressinfo
            address.add("addressinfo")
        response = import_status("messages_get_item_ok", "OK")
        response['data'] = address
        return response

    @verify_token_decorator
    def add_useraddress(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        parameter_required("areaid", "UAname", "UAphone", "UAtext")
        data = request.json
        logger.info("this is useraddress data %s", data)
        try:
            uaid = str(uuid.uuid1())
            logger.debug("get default address by usid")
            exist_default = self.suesraddress.get_default_address_by_usid(
                request.user.id)
            uadefault = True if not exist_default else data.get("UAdefault")
            if str(uadefault) not in ['True', 'False']:
                raise PARAMS_ERROR(u'uadefault参数不合法')
            if uadefault is True and exist_default:
                self.suesraddress.change_default_address_status(
                    exist_default.UAid, {'UAdefault': False})
            self.suesraddress.add_model(
                "UserAddress", **{
                    "UAid": uaid,
                    "USid": request.user.id,
                    "UAname": data.get("UAname"),
                    "UAphone": data.get("UAphone"),
                    "UAtext": data.get("UAtext"),
                    "areaid": data.get("areaid"),
                    "UAdefault": uadefault
                })
            response = import_status("add_address_success", "OK")
            response['data'] = {"UAid": uaid}
            return response
        except:
            logger.exception("add user address error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def update_address(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        args = request.args.to_dict()
        logger.debug("this is address args %s", args)
        data = request.json
        logger.debug("this is address data %s", data)
        uaid = args.get('uaid')
        uadefault = data.get("UAdefault")
        try:
            exist_default = self.suesraddress.get_default_address_by_usid(
                request.user.id)
            parameter_required("uaid", "areaid", "UAname", "UAphone", "UAtext",
                               "UAdefault")
            if uadefault == True and exist_default:
                self.suesraddress.change_default_address_status(
                    exist_default.UAid, {'UAdefault': False})
            update_address = self.suesraddress.update_address(
                uaid, {
                    "areaid": data.get("areaid"),
                    "UAname": data.get("UAname"),
                    "UAphone": data.get("UAphone"),
                    "UAtext": data.get("UAtext"),
                    "UAdefault": uadefault
                })
            logger.info("update address succress ")
            if not update_address:
                raise SYSTEM_ERROR(u'数据更新错误')
            response = import_status("update_useraddress_success", "OK")
            response['data'] = {"uaid": args["uaid"]}
            return response
        except:
            logger.exception("update address error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def del_address(self):
        if is_tourist():
            return TOKEN_ERROR(u"未登录, 或token错误")
        data = request.json
        logger.info("this is del address data %s", data)
        parameter_required("UAid")
        try:
            logger.debug("del address")
            del_address = self.suesraddress.delete_address(data.get("UAid"))
            if not del_address:
                return SYSTEM_ERROR
            exist_default = self.suesraddress.get_default_address_by_usid(
                request.user.id)
            if not exist_default:
                no_default_address = self.suesraddress.get_first_no_default_address(
                    request.user.id)
                if no_default_address:
                    self.suesraddress.change_default_address_status(
                        no_default_address.UAid, {'UAdefault': True})
            response = import_status("delete_useraddress_success", "OK")
            response['data'] = {"uaid": data.get("UAid")}
            return response
        except:
            logger.exception("del address error")
            return SYSTEM_ERROR

    """省市区地址"""

    def get_province(self):
        try:
            province_list = self.suesraddress.get_province()
            logger.debug("get province")
            # map(lambda x: x.hide('_id'), province_list)
            res = import_status("get_province_list_success", "OK")
            res["data"] = province_list
            return res
        except:
            logger.exception("get province error")
            return SYSTEM_ERROR

    def get_city_by_provincenum(self):
        args = request.args.to_dict()
        logger.info("get city list args is %s", args)
        parameter_required("provinceid")
        province_id = args["provinceid"]
        try:
            logger.debug("get citylist by province_id")
            city_list = self.suesraddress.get_citylist_by_provinceid(
                province_id)
            # map(lambda x: x.hide('_id'), city_list)
            res = import_status("get_city_list_success", "OK")
            res["data"] = city_list
            return res
        except:
            logger.exception("get city list error")
            return SYSTEM_ERROR

    def get_area_by_citynum(self):
        args = request.args.to_dict()
        logger.info("get area args is %s", args)
        parameter_required('cityid')
        city_id = args['cityid']
        try:
            logger.debug("get arealist by cityid")
            area_list = self.suesraddress.get_arealist_by_cityid(city_id)
            # map(lambda x: x.hide('_id'), area_list)
            res = import_status("get_area_list_success", "OK")
            res["data"] = area_list
            return res
        except:
            logger.exception("get area list error")
            return SYSTEM_ERROR

    """银行卡部分"""

    @verify_token_decorator
    def add_bankcard(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        data = request.json
        logger.info("this add bankcard info %s", data)
        parameter_required('BCusername', 'BCnumber', 'BCbankname', 'BCaddress')
        banknumber = str(data.get('BCnumber')).strip()
        self._verify_cardnum(banknumber, error='raise')
        usid = request.user.id
        try:
            bankcard = self.sbankcard.update_bankcard_by_usid(
                usid, {'BCisdelete': True})
            logger.debug("bankcard count is %s", bankcard)
            bcid = str(uuid.uuid1())
            self.sbankcard.add_model(
                "BankCard", **{
                    "BCid": bcid,
                    "USid": usid,
                    "BCusername": data.get("BCusername"),
                    "BCnumber": banknumber,
                    "BCbankname": data.get("BCbankname"),
                    "BCaddress": data.get("BCaddress")
                })
            response = import_status("add_bank_card_success", "OK")
            response['data'] = {"BCid": bcid}
            return response
        except:
            logger.exception("add bankcard error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def get_bankcard(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        args = request.args.to_dict()
        logger.info("get bankcard this is args %s", args)
        try:
            logger.debug("get bankcard")
            my_bankcard = self.sbankcard.get_bankcard_by_usid(request.user.id)

            if not my_bankcard or not my_bankcard.BCnumber or not my_bankcard.BCusername:
                my_bankcard = None

            response = import_status("get_bankcard_success", "OK")
            response['data'] = my_bankcard
            return response
        except:
            logger.exception("get bankcard error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def del_bankcard(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        data = request.json
        logger.info("this is del bankcard data %s", data)
        parameter_required("BCid")
        try:
            logger.debug("del bankcard")
            del_bankcard = self.sbankcard.del_bankcard(data.get("BCid"),
                                                       request.user.id)
            if not del_bankcard:
                return SYSTEM_ERROR
            response = import_status("delete_bankcard_success", "OK")
            response['data'] = {"bcid": data.get("BCid")}
            return response
        except:
            logger.exception("del address error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def update_bankcard(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        args = request.args.to_dict()
        logger.info("this is update bankcard args %s", args)
        data = request.json
        logger.info("this is update bankcard data %s", data)
        try:
            parameter_required("bcid", "BCusername", "BCnumber", "BCbankname",
                               "BCaddress")
            update_bankcard = self.sbankcard.update_bankcard(
                args["bcid"], data)
            logger.debug("update bankcard accress")
            if not update_bankcard:
                return SYSTEM_ERROR
            response = import_status("update_bankcard_success", "OK")
            response["data"] = {"bcid": args["bcid"]}
            return response
        except:
            logger.exception("update bankcard error")
            return SYSTEM_ERROR

    @verify_token_decorator
    def get_bankname_list(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        data = import_status("get_useraddress_success", "OK")
        data['data'] = BANK_MAP
        return data

    """发送/校验验证码"""

    @verify_token_decorator
    def get_inforcode(self):
        # return TIME_ERROR
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        user = self.suser.get_user_by_user_id(request.user.id)
        if not user:
            return SYSTEM_ERROR
        Utel = user.USphone
        # 拼接验证码字符串(6位)
        code = ""
        while len(code) < 6:
            import random
            item = random.randint(1, 9)
            code = code + str(item)

        # 获取当前时间,与上一次获取的时间进行比较,小于60秒的获取直接报错
        import datetime
        from WeiDian.common.timeformat import format_for_db
        time_time = datetime.datetime.now()
        time_str = datetime.datetime.strftime(time_time, format_for_db)

        # 根据电话号码获取时间
        time_up = self.smycenter.get_uptime_by_utel(Utel)
        logger.debug("this is time up %s", time_up)

        if time_up:
            time_up_time = datetime.datetime.strptime(time_up.ICtime,
                                                      format_for_db)
            delta = time_time - time_up_time
            if delta.seconds < 60:
                return import_status("ERROR_MESSAGE_GET_CODE_FAST",
                                     "WEIDIAN_ERROR",
                                     "ERROR_CODE_GET_CODE_FAST")

        new_inforcode = self.smycenter.add_inforcode(Utel, code, time_str)

        logger.debug("this is new inforcode %s ", new_inforcode)

        if not new_inforcode:
            return SYSTEM_ERROR
        from WeiDian.config.Inforcode import SignName, TemplateCode
        from WeiDian.common.Inforsend import send_sms
        params = '{\"code\":\"' + code + '\",\"product\":\"etech\"}'

        # params = u'{"name":"wqb","code":"12345678","address":"bz","phone":"13000000000"}'
        __business_id = uuid.uuid1()
        response_send_message = send_sms(__business_id, Utel, SignName,
                                         TemplateCode, params)

        response_send_message = json.loads(response_send_message)
        logger.debug("this is response %s", response_send_message)

        if response_send_message["Code"] == "OK":
            status = 200
        else:
            status = 405
        # 手机号中四位替换为星号
        # response_ok = {"usphone": Utel[:3] + '****' + Utel[-4: ]}
        response_ok = {"usphone": Utel}
        response_ok["status"] = status
        response_ok["messages"] = response_send_message["Message"]

        return response_ok

    @verify_token_decorator
    def verify_inforcode(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR(u"未登录, 或token错误")
        data = request.json
        user = self.suser.get_user_by_user_id(request.user.id)
        codeinfo = self.smycenter.get_inforcode_by_usphone(user.USphone)
        if not codeinfo:
            return SYSTEM_ERROR(u"用户验证信息错误")
        iccode = data.get("ICcode")
        verifystatus = True if iccode == codeinfo.ICcode else False
        verifymessage = u"验证码正确" if verifystatus is True else u"验证码错误"
        response = import_status("verify_inforcode_access", "OK")
        response["data"] = {
            "verifystatus": verifystatus,
            "verifymessage": verifymessage
        }
        return response

    def _verify_cardnum(self, num, error='ignore'):
        """获取所属行"""
        bank_url = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardNo={}&cardBinCheck=true'
        url = bank_url.format(num)
        response = requests.get(url).json()
        bank = response.get('bank')
        if not bank and error != 'ignore':
            raise SYSTEM_ERROR(u'卡号无效')
        return bank

    """设置获取微信分享参数"""

    @verify_token_decorator
    def set_share_params(self):
        if not is_admin():
            raise TOKEN_ERROR(u'请使用管理员登录')
        data = request.json
        title = data.get('title')
        # title = title.encode("utf8") if isinstance(title, unicode) else title

        content = data.get('content')
        img = data.get('img')

        parameter_required('title', 'content', 'img')
        Partner().set_item('share', 'title', title)
        Partner().set_item('share', 'content', content)
        Partner().set_item('share', 'img', img)
        response = import_status('set_success', 'OK')
        return response

    @verify_token_decorator
    def get_share_params(self):

        args = request.args.to_dict()
        prid = args.get('prid')
        logger.debug("get share params args is %s", args)
        if prid:
            from WeiDian.service.SActivity import SActivity
            actext_by_prid = get_model_return_dict(
                SActivity().get_one_act_by_prid(prid))['ACtext']
            title = actext_by_prid.split(u'。')[0]
            content = actext_by_prid.split(u'。')[-1]
            img = get_model_return_dict(
                self.sproduct.get_prmainpic_by_prid(prid))['PRmainpic']
        else:
            settings = Partner()
            title = settings.get_item('share', 'title')
            content = settings.get_item('share', 'content')
            img = settings.get_item('share', 'img')
        response = import_status("messages_get_item_ok", "OK")
        response['data'] = {'title': title, 'content': content, 'img': img}
        return response
예제 #2
0
class CComplain():
    def __init__(self):
        from WeiDian.service.SComplain import SComplain
        self.scomplain = SComplain()
        from WeiDian.service.SActivity import SActivity
        self.sactivity = SActivity()
        from WeiDian.service.SUser import SUser
        self.suser = SUser()

    @verify_token_decorator
    def get_complain_by_usid(self):
        """后台管理查看投诉记录"""
        if not hasattr(request, 'user'):
            raise TOKEN_ERROR()  # 未登录, 或token错误
        args = request.args.to_dict()
        logger.debug("get complain args is %s", args)
        page_size = args.get('page_size')
        page_size = 10 if not page_size else int(page_size)
        page_num = args.get('page_num')
        page_num = 1 if not page_num else int(page_num)
        try:
            complain_list = self.scomplain.admin_get_all_complain(
                page_size, page_num)
            complain_list_length = self.scomplain.admin_get_complain_count()
            from WeiDian.config.enums import complain_type
            data = import_status("get_complain_success", "OK")
            for complain in complain_list:
                colist = str(complain.COtype).split(",")
                logger.debug('get colist %s', colist)
                complaintype = ",".join([complain_type.get(i) for i in colist])
                logger.debug('convert complain type %s', complaintype)
                complain.COtype = complaintype
                user_info = self.suser.get_user_by_user_id(complain.USid)
                complain.fill(user_info.USname, 'usname')
                complain.COcreatetime = get_web_time_str(complain.COcreatetime)

            data['data'] = complain_list
            data['count'] = complain_list_length
            logger.debug("get complain by usid %s", complain_list)
            return data
        except:
            logger.exception("get complain by usid error")
            raise SYSTEM_ERROR(u'获取数据错误')

    @verify_token_decorator
    def add_complain(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token错误
        parameter_required("OIid", "COtype")
        data = request.json
        try:
            complain = self.scomplain.get_complain_by_oiid(data.get("OIid"))
            logger.debug("get complain by oiid %s", complain)
            if complain:
                return import_status("complain_repeat_error", "WD_ERROR",
                                     "error_complain_exit")
            coid = str(uuid.uuid1())
            cotype_list = [str(i) for i in data.get("COtype", [])]

            self.scomplain.add_model(
                "Complain", **{
                    "COid": coid,
                    "COcontent": data.get("COcontent"),
                    "COtype": ",".join(cotype_list),
                    "OIid": data.get("OIid"),
                    "USid": request.user.id,
                    "COtreatstatus": 1,
                })
            response = import_status("complain_success", "OK")
            response['data'] = {"COid": coid}
            return response
        except:
            logger.exception("add complain error")
            return SYSTEM_ERROR

    # @verify_token_decorator
    def update_status(self):
        # if not is_admin():
        #     raise TOKEN_ERROR
        parameter_required('coid', 'cotreatstatus')
        data = request.json
        logger.debug('get update complain status %s', data)
        complain = self.scomplain.get_complain_by_coid(data.get("coid"))
        if not complain:
            raise PARAMS_MISS('params coid is not right')
        if not re.match(r'^[0-2]$', str(data.get("cotreatstatus"))):
            raise PARAMS_MISS('params cotreatstatus is not right')
        cotreatstatus = int(data.get("cotreatstatus"))
        if cotreatstatus <= complain.COtreatstatus:
            raise PARAMS_MISS('params cotreatstatus is not right')
        update_result = self.scomplain.update_complain(
            data.get("coid"), {"COtreatstatus": cotreatstatus})
        if not update_result:
            raise SYSTEM_ERROR(u"服务器繁忙")
        return import_status('update_complain_success', "OK")
예제 #3
0
class CRaward():
    def __init__(self):
        from WeiDian.service.SRaward import SRaward
        self.sraward = SRaward()
        from WeiDian.service.SUser import SUser
        self.suser = SUser()
        from WeiDian.service.SSuperUser import SSuperUser
        self.ssuperuser = SSuperUser()
        from WeiDian.control.Cuser import CUser
        self.cuser = CUser()

    @verify_token_decorator
    def create_reward(self):
        """创建优惠券"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'当前账号权限不足')
        data = request.json
        logger.debug("create reward data is %s", data)
        raid = str(uuid.uuid1())
        ratype = data.get('ratype')
        rptid = data.get('rptid')
        if not re.match(r'^[0-4]$', str(ratype)):
            raise PARAMS_ERROR(u'ratype, 参数异常')
        now_time = get_db_time_str()
        nowtime_str_to_time = datetime.strptime(now_time, format_for_db)
        days_later = datetime.strftime(nowtime_str_to_time + timedelta(days=30), format_for_web_second)
        reendtime = get_db_time_str(data.get('raendtime', days_later))
        ratransfer = data.get('ratransfer', False)
        reward_dict = {
            'RAid': raid,
            'RAtype': ratype,
            'RAmaxusenum': data.get('ramaxusenum', 1),
            'RAmaxholdnum': data.get('ramaxholdnum', 1),
            'RAendtime': reendtime,
            'RAname': data.get('raname'),
            'RAtransfer': ratransfer,
            'SUid': request.user.id
        }
        if re.match(r'^[0-2]$', str(ratype)):
            if str(ratype) == '0':
                parameter_required('rafilter', 'raamount', 'ratype', 'raname')
                logger.info('This reward type 0 is created')
                reward_dict['RAfilter'] = data.get('rafilter')
                reward_dict['RAamount'] = data.get('raamount')
            elif str(ratype) == '1':
                parameter_required('raratio', 'ratype', 'raname')
                logger.info('This reward type 1 is created')
                reward_dict['RAratio'] = data.get('raratio')
            else:
                parameter_required('raamount', 'ratype', 'raname')
                logger.info('This reward type 2 is created')
                reward_dict['RAfilter'] = 0
                reward_dict['RAamount'] = data.get('raamount')
        if ratransfer == True:
            reward_dict['RAtransfereffectivetime'] = data.get('ratransfereffectivetime', 24)
        self.sraward.add_model('Raward', **reward_dict)

        if rptid:
            self.sraward.add_model('RewardPacketContact', **{
                'RPCid': str(uuid.uuid1()),
                'RAid': raid,
                'RPTid': rptid
            })

        data = import_status("create_reward_success", "OK")
        data['data'] = {'raid': raid}
        return data

    @verify_token_decorator
    def update_reward(self):
        """更换优惠券集合或删除"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.json
        logger.debug("update or del reward id is %s", data)
        raid = data.get('raid')
        raisdelete = data.get('raisdelete')
        rptid = data.get('rptid')
        if raisdelete:
            upinfo = self.sraward.update_reward({'RAid': raid}, {'RAisdelete': raisdelete})
            if not upinfo:
                raise NOT_FOUND(u'删除失败')
        elif rptid is not None:
            self.sraward.del_packet_reward(raid)
            if rptid:
                self.sraward.add_model('RewardPacketContact', **{
                    'RPCid': str(uuid.uuid1()),
                    'RAid': raid,
                    'RPTid': rptid
                })
        data = import_status("update_success", "OK")
        data['data'] = {'raid': raid}
        return data

    @verify_token_decorator
    def admin_giving_reward(self):
        """后台赠送用户优惠券"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.json
        logger.debug("admin giving reward data is %s", data)
        parameter_required('raid', 'usid')
        usid = data.get('usid')
        raid = data.get('raid')
        ranumber = int(data.get('ranumber', 1))  # 该优惠券分发数量
        is_hold = self.sraward.is_user_hold_reward({'USid': usid, 'RAid': raid})
        if is_hold:
            urid = is_hold.URid
            logger.info("The user already has this type of reward ")
            update_info = self.sraward.update_user_reward({'URid': is_hold.URid}, {'RAnumber': is_hold.RAnumber + ranumber})
            if not update_info:
                raise SYSTEM_ERROR(u'更新数据错误')
        else:
            logger.info("New reward to user")
            urid = str(uuid.uuid1())
            self.sraward.add_model('UserRaward', **{
            'URid': urid,
            'USid': usid,
            'RAid': raid,
            'RAnumber': ranumber
        })
        logger.info("now to write distribution the record")
        self.sraward.add_model('RewardGrantRecord', **{
            'RGRid': str(uuid.uuid1()),
            'SUid': request.user.id,
            'USid': usid,
            'RAid': raid,
            'RAnumber': ranumber
        })
        data = import_status("hand_out_reward_success", "OK")
        data['data'] = {'urid': urid}
        return data

    @verify_token_decorator
    def get_grant_record(self):
        """获取运营发放记录"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        args = request.args.to_dict()
        logger.debug('get grant record args : %s', args)
        pagenum, pagesize = self.cuser.get_pagesize_pagenum(args)
        record_list, count = self.sraward.get_grant_record(pagenum, pagesize)
        for record in record_list:
            if record:
                user = self.suser.get_user_by_user_id(record.USid)
                usname = user.USname
                suser = self.ssuperuser.get_one_super_by_suid(record.SUid)
                susername = suser.SUname
                reward_info = self.sraward.get_raward_by_id(record.RAid)
                reward_info = self.fill_reward_detail(reward_info)
                record_str = '运营 {0} 发放给 {1} {2}优惠券 {3}张'.format(susername.encode('utf8'), usname.encode('utf8'), reward_info.rewardstr, record.RAnumber)
                record.fill(reward_info.rewardstr, 'rewardname')
                record.fill(usname, 'usname')
                record.fill(susername, 'susername')
                record.fill(record_str, 'record_str')
                record.RGRcreatetime = get_web_time_str(record.RGRcreatetime)
        response = import_status('messages_get_item_ok', 'OK')
        response['data'] = record_list
        response['count'] = count
        return response

    @verify_token_decorator
    def user_receive_reward(self):
        """用户自己领取页面内的优惠券"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        data = request.json
        parameter_required('raid')
        logger.debug("user recevive data is", data)
        usid = request.user.id
        raid = data.get('raid')

        # 判断发放的优惠券是否还有领取数量
        hang_out = self.sraward.is_hand_out({'RAid': raid})
        if hang_out:
            if hang_out.RTcount <= 0:
                raise NOT_FOUND(u'该优惠券已领取完毕')
            else:
                self.sraward.update_is_hand_out({'RAid': hang_out.RAid}, {'RTcount': hang_out.RTcount - 1})

        # 判断用户是否已持有
        is_hold = self.sraward.is_user_hold_reward({'USid': usid, 'RAid': raid})
        if is_hold:
            logger.info("The user already has this type of reward ")
            reward_info = self.sraward.get_raward_by_id(raid)
            urid = is_hold.URid
            if is_hold.RAnumber < reward_info.RAmaxholdnum:
                self.sraward.update_user_reward({'RAid': raid}, {'RAnumber': is_hold.RAnumber + 1})
            else:
                raise PARAMS_REDUNDANCE(u'已拥有该券最大可持有数量')
        else:
            logger.info("New reward to user")
            urid = str(uuid.uuid1())
            self.sraward.add_model('UserRaward', **{
                'URid': urid,
                'USid': usid,
                'RAid': raid,
            })

        data = import_status("receive_reward_success", "OK")
        data['data'] = {'urid': urid
                        }
        return data

    @verify_token_decorator
    def get_one_reward(self):
        """获取单张优惠券详情"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        # parameter_required('raid')
        args = request.args.to_dict()
        raid = args.get('raid')
        urid = args.get('urid')
        logger.debug("get reward info is %s", args)

        if urid:
            # 是赠送者原表里的
            is_presenter_own_hold = self.sraward.is_user_hold_reward({'URid': urid})

            # 在赠送者转赠表中,送出去过,已退回,可以继续转赠
            is_presenter_gift_hold = self.sraward.is_user_hold_reward_in_gift(
                {'RFid': urid, 'RFstatus': 1})

            if is_presenter_own_hold:
                raid = is_presenter_own_hold.RAid
                reward = self.sraward.get_raward_by_id(raid)
                reward_detail = self.fill_reward_detail(reward)
                is_presenter_own_hold.fill(reward_detail, 'reward_detail')
            elif is_presenter_gift_hold:
                raid = is_presenter_gift_hold.RAid
                gift = self.fill_transfer_detail(is_presenter_gift_hold)
                gift_detail = self.sraward.get_raward_by_id(raid)
                gift_detail = self.fill_reward_detail(gift_detail)
                # 检验转赠券在各情况下的有效性
                gift_detail.valid = gift_detail.valid and gift.transfer_valid
                gift.fill(gift_detail, 'reward_detail')
                gift.RFcreatetime = get_web_time_str(gift.RFcreatetime)
                gift.RFendtime = get_web_time_str(gift.RFendtime)
                gift_dict = {
                    'urid': gift.RFid,
                    'usid': gift.USid,
                    'raid': gift.RAid,
                    'ranumber': gift.RAnumber,
                    'urcreatetime': gift.RFcreatetime,
                    'reendtime': gift.RFendtime,
                    'rffrom': gift.RFfrom,
                    'rfstatus': gift.RFstatus,
                    'urusetime': gift.RFusetime,
                    'remarks': gift.remarks,
                    'tag': gift.tag,
                    'usheader': gift.usheader,
                    'reward_detail': gift.reward_detail
                }
            else:
                raise NOT_FOUND(u'无此转赠优惠券信息')
            reward_detail = is_presenter_own_hold or gift_dict
        else:
            reward_info = self.sraward.get_raward_by_id(raid)
            if not reward_info:
                raise NOT_FOUND(u'无此券信息')
            reward_detail = self.fill_reward_detail(reward_info)

        presenter = self.suser.get_user_by_user_id(request.user.id)

        data = import_status("messages_get_item_ok", "OK")
        data['usname'] = presenter.USname
        data['usheader'] = presenter.USheader

        data['data'] = reward_detail
        return data

    @verify_token_decorator
    def hand_out_reward(self):
        """平台发放在页面内的优惠券"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.json
        logger.debug("hand out data is %s", data)
        raid = data.get('raid')
        rtid = str(uuid.uuid1())
        is_hand_out = self.sraward.is_hand_out({'RAid': raid})
        if is_hand_out:
            raise PARAMS_REDUNDANCE(u'该优惠券已在页面发放')
        else:
            self.sraward.add_model('RewardToUser', **{
                'RTid': rtid,
                'RAid': raid,
                'RTcount': data.get('rtcount', 10)
            })
        data = import_status("hand_out_reward_success", "OK")
        data['data'] = {'rtid': rtid}
        return data

    @verify_token_decorator
    def get_hand_out_reward(self):
        """获取平台发放在页面中的优惠券"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        horewards = self.sraward.get_all_hand_out()
        for horeward in horewards:
            reward = self.sraward.get_raward_by_id(horeward.RAid)
            reward_detail = self.fill_reward_detail(reward)
            horeward.fill(reward_detail, 'reward_detail')

        data = import_status("messages_get_item_ok", "OK")
        data['data'] = horewards
        return data

    @verify_token_decorator
    def get_transfer_reward(self):
        """接收者领取优惠券"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        data = request.json
        logger.debug('get transfer data is %s', data)
        urid = data.get('urid')
        usid = data.get('usid')
        presenter = self.suser.get_user_by_user_id(usid)
        if not presenter:
            raise NOT_FOUND(u'无此赠送用户')

        is_self_reward = self.sraward.is_user_hold_reward({'USid': request.user.id, 'URid': urid})
        is_self_gift_reward = self.sraward.is_user_hold_reward_in_gift({'RFfrom': request.user.id, 'RFid': urid})
        if is_self_reward or is_self_gift_reward:
            raise SYSTEM_ERROR(u'不能领取自己转赠的优惠券')

        # 在赠送者的普通券表中有
        is_own_hold = self.sraward.is_user_hold_reward({'USid': usid, 'URid': urid})

        # 赠送者送出去过,但是已退回,可以继续转赠
        is_own_gift_hold = self.sraward.is_user_hold_reward_in_gift(
            {'RFfrom': usid, 'RFid': urid, 'RFstatus': 1})

        if is_own_hold:
            raid = is_own_hold.RAid
        elif is_own_gift_hold:
            raid = is_own_gift_hold.RAid
        else:
            raise NOT_FOUND(u'用户无此优惠券')
        reward_info = self.sraward.get_raward_by_id(raid)
        if not reward_info:
            raise NOT_FOUND(u'该券已失效')
        elif reward_info.RAtransfer == False:
            raise SYSTEM_ERROR(u'该券不允许转赠')
        return_time = reward_info.RAtransfereffectivetime  # 转赠有效时间,退回时间

        # 已经赠送了该券给接收者,接收者还没用,且未到退回时间
        is_recivice_gift_hold = self.sraward.is_user_hold_reward_in_gift(
            {'RAid': raid, 'USid': request.user.id, 'RFstatus': 0, 'RFfrom': usid})
        if is_recivice_gift_hold:
            raise SYSTEM_ERROR(u'已领取过该券')

        # 接收者已经拥有其他人送的该券, 不影响, 忽略
        # is_recivice_hold_from_other = self.sraward.is_user_hold_reward({'USid': usid, 'RAid': raid})

        # 接收者原有表中已经拥有此券了
        is_recivice_hold = self.sraward.is_user_hold_reward({'USid': request.user.id, 'RAid': raid})

        if is_own_gift_hold:
            up_reward_info = self.sraward.update_reward_transfer_info(
                {'RFfrom': usid, 'RFid': urid, 'RFstatus': 1}, {'USid': request.user.id, 'RFstatus': 0})
            if not up_reward_info:
                raise SYSTEM_ERROR(u'该券经过再次转送失败')

        if is_own_hold and is_recivice_hold:
            if is_own_hold.RAnumber > 0 and is_recivice_hold.RAnumber < reward_info.RAmaxholdnum:
                logger.info("The user already has this type of reward ")
                update_reward = self.sraward.update_user_reward({'URid': is_own_hold.URid},
                                                                {'RAnumber': is_own_hold.RAnumber - 1})
                # self.sraward.update_user_reward({'RAid': raid}, {'RAnumber': is_recivice_hold.RAnumber + 1})
                rfid = str(uuid.uuid1())
                self.sraward.add_model('RewardTransfer', **{
                    'RFid': rfid,
                    'USid': request.user.id,
                    'RAid': raid,
                    'URFrom': usid,
                    'RAnumber': 1,
                    'RFendtime': (datetime.now() + timedelta(hours=int(return_time))).strftime(format_for_db),
                    'RFstatus': 0
                })

                if not update_reward:
                    raise PARAMS_ERROR(u'更新参数错误')
            else:
                raise NOT_FOUND(u'赠送者已没有可赠送数量或您已拥有该券最大可持有数')
        elif is_own_hold and not is_recivice_hold:
            if is_own_hold.RAnumber > 0:
                logger.info("New reward to user")
                rfid = str(uuid.uuid1())
                self.sraward.add_model('RewardTransfer', **{
                    'RFid': rfid,
                    'USid': request.user.id,
                    'RAid': raid,
                    'URFrom': usid,
                    'RAnumber': 1,
                    'RFendtime': (datetime.now() + timedelta(hours=int(return_time))).strftime(format_for_db),
                    'RFstatus': 0
                })
            else:
                raise NOT_FOUND(u'您已没有可赠送的数量')
        else:
            raise NOT_FOUND(u'您已没有可赠送的数量')
        data = import_status("give_to_others_success", "OK")
        data['data'] = {'urid': urid}
        return data

    @verify_token_decorator
    def give_reward_to_others(self):
        """转赠优惠券(暂时用不到)"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        data = request.json
        usid = data.get('usid')
        urid = data.get('urid')
        # 在自己的普通券表中拥有
        is_own_hold = self.sraward.is_user_hold_reward({'USid': request.user.id, 'URid': urid})

        # 送出去过,但是已退回,可以继续转赠
        is_own_gift_hold = self.sraward.is_user_hold_reward_in_gift({'RFfrom': request.user.id, 'RFid': urid, 'RFstatus': 1})

        if is_own_hold:
            raid = is_own_hold.RAid
        elif is_own_gift_hold:
            raid = is_own_gift_hold.RAid
        else:
            raise NOT_FOUND(u'用户无此优惠券')
        reward_info = self.sraward.get_raward_by_id(raid)
        if reward_info.RAtransfer == False:
            raise SYSTEM_ERROR(u'该券不允许转赠')
        return_time = reward_info.RAtransfereffectivetime  # 转赠有效时间,退回时间

        # 已经赠送了该券给接收者,接收者还没用,且未到退回时间
        is_recivice_gift_hold = self.sraward.is_user_hold_reward_in_gift({'RAid': raid, 'USid': usid, 'RFstatus': 0, 'RFfrom': request.user.id})
        if is_recivice_gift_hold:
            raise SYSTEM_ERROR(u'您已赠送过该券给用户')

        # 接收者已经拥有其他人送的该券, 不影响, 忽略
        # is_recivice_hold_from_other = self.sraward.is_user_hold_reward({'USid': usid, 'RAid': raid})

        # 接收者原来已经拥有此券了
        is_recivice_hold = self.sraward.is_user_hold_reward({'RAid': raid})

        if is_own_gift_hold:
            up_reward_info = self.sraward.update_reward_transfer_info({'RFfrom': request.user.id, 'RFid': urid, 'RFstatus': 1}, {'USid':usid, 'RFstatus': 0})
            if not up_reward_info:
                raise SYSTEM_ERROR(u'再次转送失败')

        if is_own_hold and is_recivice_hold:
            if is_own_hold.RAnumber > 0 and is_recivice_hold.RAnumber < reward_info.RAmaxholdnum:
                logger.info("The user already has this type of reward ")
                update_reward = self.sraward.update_user_reward({'URid': is_own_hold.URid}, {'RAnumber': is_own_hold.RAnumber - 1})
                # self.sraward.update_user_reward({'RAid': raid}, {'RAnumber': is_recivice_hold.RAnumber + 1})
                rfid = str(uuid.uuid1())
                self.sraward.add_model('RewardTransfer', **{
                    'RFid': rfid,
                    'USid': usid,
                    'RAid': raid,
                    'URFrom': request.user.id,
                    'RAnumber': 1,
                    'RFendtime': (datetime.now() + timedelta(hours=int(return_time))).strftime(format_for_db),
                    'RFstatus': 0
                })

                if not update_reward:
                    raise PARAMS_ERROR(u'更新参数错误')
            else:
                raise NOT_FOUND(u'您已没有可赠送数量或赠送用户已拥有该券最大可持有数')
        elif is_own_hold and not is_recivice_hold:
            if is_own_hold.RAnumber > 0:
                logger.info("New reward to user")
                rfid = str(uuid.uuid1())
                self.sraward.add_model('RewardTransfer', **{
                    'RFid': rfid,
                    'USid': usid,
                    'RAid': raid,
                    'URFrom': request.user.id,
                    'RAnumber': 1,
                    'RFendtime': (datetime.now() + timedelta(hours=int(return_time))).strftime(format_for_db),
                    'RFstatus': 0
                })
            else:
                raise NOT_FOUND(u'您已没有可赠送的数量')
        else:
            raise NOT_FOUND(u'您已没有可赠送的数量')
        data = import_status("give_to_others_success", "OK")
        data['data'] = {'urid': urid}
        return data

    @verify_token_decorator
    def get_user_reward(self):
        """获取用户(可转赠)优惠券"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        args = request.args.to_dict()
        logger.debug("get reward args is %s", args)
        allow_transfer = args.get('transfer')
        reward_info = self.sraward.get_reward_by_usid(request.user.id)

        from WeiDian.models.model import RewardTransfer
        gift_reward_info = self.sraward.get_gifts_by_usfrom_or_usid(
            (RewardTransfer.USid == request.user.id, RewardTransfer.RFfrom == request.user.id))

        reward_list = []
        for reward in reward_info:
            reward_detail = self.sraward.get_raward_by_id(reward.RAid)
            reward_detail = self.fill_reward_detail(reward_detail)
            reward.fill(reward_detail, 'reward_detail')
            reward = dict(reward)

            lower_reward = {}
            for i, j in reward.items():
                lower_reward[i.lower()] = j

            lower_reward['urcreatetime'] = get_web_time_str(lower_reward.get('urcreatetime'))
            reward_list.append(lower_reward)
        for gift in gift_reward_info:
            gift = self.fill_transfer_detail(gift)
            gift_detail = self.sraward.get_raward_by_id(gift.RAid)
            gift_detail = self.fill_reward_detail(gift_detail)
            # 检验转赠券在各情况下的有效性
            gift_detail.valid = gift_detail.valid and gift.transfer_valid
            gift.fill(gift_detail, 'reward_detail')

            gift.RFcreatetime = get_web_time_str(gift.RFcreatetime)
            gift.RFendtime = get_web_time_str(gift.RFendtime)
            gift_dict = {
                'urid': gift.RFid,
                'usid': gift.USid,
                'raid': gift.RAid,
                'ranumber': gift.RAnumber,
                'urcreatetime': gift.RFcreatetime,
                'reendtime': gift.RFendtime,
                'rffrom': gift.RFfrom,
                'rfstatus': gift.RFstatus,
                'urusetime': gift.RFusetime,
                'remarks': gift.remarks,
                'tag': gift.tag,
                'usheader': gift.usheader,
                'reward_detail': gift.reward_detail
            }
            reward_list.append(gift_dict)

        # reward_info = filter(lambda r: r.get('reward_detail')['RAtype'] in [0, 2], reward_list)
        reward_info = filter(lambda k: k.get('ranumber') != 0, reward_list)

        if str(allow_transfer) == 'true':
            reward_info = filter(lambda r: r.get('reward_detail')['valid'] == True, reward_info)
            reward_info = filter(lambda r: r.get('reward_detail')['RAtransfer'] == True, reward_info)

        data = import_status('messages_get_item_ok', "OK")
        data['data'] = reward_info
        return data

    @verify_token_decorator
    def get_user_pay_reward(self):
        """查看用户支付时的优惠券"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        data = request.json
        logger.debug("get pay reward data is %s", data)
        skus = data.get('sku')
        # parameter_required('sku')
        from WeiDian.service.SProductSkuKey import SProductSkuKey
        if skus:
            total_price = 0
            for sku in skus:
                price = SProductSkuKey().get_true_price(sku.get('pskid')) * int(sku.get('num'))
                total_price = total_price + price

        reward_info = self.sraward.get_reward_by_usid(request.user.id)
        from WeiDian.models.model import RewardTransfer
        gift_reward_info = self.sraward.get_gifts_by_usfrom_or_usid((RewardTransfer.USid==request.user.id, RewardTransfer.RFfrom==request.user.id))

        try:
            reward_list = []
            for reward in reward_info:
                if reward:
                    reward_detail = self.sraward.get_raward_by_id(reward.RAid)
                    reward_detail = self.fill_reward_detail(reward_detail, total_price)
                    reward.fill(reward_detail, 'reward_detail')
                    reward = dict(reward)

                lower_reward = {}
                for i, j in reward.items():
                    lower_reward[i.lower()] = j

                lower_reward['urcreatetime'] = get_web_time_str(lower_reward.get('urcreatetime'))
                reward_list.append(lower_reward)
            for gift in gift_reward_info:
                if gift not in ['', [], {}, None]:
                    gift = self.fill_transfer_detail(gift)
                    gift_detail = self.sraward.get_raward_by_id(gift.RAid)
                    gift_detail = self.fill_reward_detail(gift_detail, total_price)
                    # 检验转赠券在各情况下的有效性
                    gift_detail.valid = gift_detail.valid and gift.transfer_valid
                    gift.fill(gift_detail, 'reward_detail')

                    gift.RFcreatetime = get_web_time_str(gift.RFcreatetime)
                    gift.RFendtime = get_web_time_str(gift.RFendtime)
                    gift_dict = {
                        'urid': gift.RFid,
                        'usid': gift.USid,
                        'raid': gift.RAid,
                        'ranumber': gift.RAnumber,
                        'urcreatetime': gift.RFcreatetime,
                        'reendtime': gift.RFendtime,
                        'rffrom': gift.RFfrom,
                        'rfstatus': gift.RFstatus,
                        'urusetime': gift.RFusetime,
                        'remarks': gift.remarks,
                        'tag': gift.tag,
                        'usheader': gift.usheader,
                        'reward_detail': gift.reward_detail
                    }
                    reward_list.append(gift_dict)
            if reward_list not in [None, [], {}]:
                reward_info = filter(lambda r: r.get('reward_detail')['RAtype'] in [0, 2], reward_list)
                reward_info = filter(lambda k: k.get('ranumber') != 0, reward_info)

            data = import_status('messages_get_item_ok', "OK")
            data['data'] = reward_info
            return data
        except Exception as e:
            logger.exception("get user reward error")
            raise SYSTEM_ERROR(u'获取数据错误')

    @verify_token_decorator
    def create_rewardpacket(self):
        """创建优惠券集合"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.json
        logger.debug("create reward packet data is %s", data)
        rptid = str(uuid.uuid1())
        self.sraward.add_model('RewardPacket', **{
            'RPTid': rptid,
            'SUid': request.user.id,
            'RPTname': data.get('name')
        })
        data = import_status("create_reward_packet_success", "OK")
        data['data'] = {'rptid': rptid}
        return data

    @verify_token_decorator
    def get_rewardpacket(self):
        """获取优惠券集合"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        rewardpackets = self.sraward.get_reward_packet_list()
        logger.info(('get reward packet list success'))
        data = import_status("messages_get_item_ok", "OK")
        data['data'] = rewardpackets
        return data

    @verify_token_decorator
    def get_reward_packet_detail(self):
        """获取单个集合详情"""
        if is_tourist():
            raise TOKEN_ERROR(u"未登录")
        args = request.args.to_dict()
        rptid = args.get('rptid')
        logger.debug("get reward packet detail args is %s", args)
        reward_packet = self.sraward.get_reward_packet_detail(rptid)
        for reward_one in reward_packet:
            raid = reward_one.RAid
            reward = self.sraward.get_raward_by_id(raid)
            reward_detail = self.fill_reward_detail(reward)
            reward_one.fill(reward_detail, 'reward_detail')
            packet_contact = self.sraward.get_is_where_packet(raid)
            if packet_contact:
                packet_info = self.sraward.get_reward_in_packet_info(packet_contact.RPTid)
                reward.fill(packet_info.RPTname, 'rptname')
        data = import_status("messages_get_item_ok", "OK")
        data['data'] = reward_packet
        return data


    @verify_token_decorator
    def del_rewardpacket(self):
        """删除优惠券集合"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.json
        logger.debug("del reward packet id is %s", data)
        rptid = data.get('rptid')
        del_info = self.sraward.update_reward_packet({'RPTid': rptid}, {'RPTisdelete': True})
        self.sraward.del_packet_contact({'RPTid': rptid})
        if not del_info:
            raise NOT_FOUND(u'删除失败')
        data = import_status("delete_success", "OK")
        data['data'] = {'rptid': rptid}
        return data



    def fill_reward_detail(self, raward, price=None):
        reward_number = '{0}张'
        reward_number_ratio = '前{0}单'
        filter_str = '满{0}-{1}新衣币'
        ratio_str = '佣金上涨{0}%'
        amout_str = '{0}元无门槛新衣币'
        price_use = False
        if raward not in ['', None, [], {}]:
            if re.match(r'^[0-2]$', str(raward.RAtype)):
                if raward.RAtype == 0:
                    reward_str = filter_str.format(int(raward.RAfilter), int(raward.RAamount))
                elif raward.RAtype == 1:
                    reward_str = ratio_str.format(int(raward.RAratio))
                else:
                    reward_str = amout_str.format(int(raward.RAamount))
            zh_ratype = REWARD_TYPE.get(str(raward.RAtype))
            raward.fill(zh_ratype, 'zh_ratype')
            raward.fill(reward_str, 'rewardstr')
            time_valid = raward.RAcreatetime < get_db_time_str() < raward.RAendtime and not raward.RAisdelete
            if price:
                if raward.RAtype == 0:
                    price_use = price > raward.RAfilter
                elif raward.RAtype == 2:
                    price_use = True
                valid = time_valid and price_use
            else:
                valid = time_valid
            raward.fill(valid, 'valid')
            raward.RAendtime = get_web_time_str(raward.RAendtime)
            raward.RAcreatetime = get_web_time_str(raward.RAcreatetime)
        return raward

    def fill_transfer_detail(self, raward):
        from WeiDian.service.SUser import SUser
        if hasattr(raward, 'RFstatus'):
            reward_info = self.sraward.get_raward_by_id(raward.RAid)
            # if reward_info.RAtransfer == False:
            #     raise SYSTEM_ERROR(u'信息错误,该券不能被赠送')
            if not re.match(r'^[0-2]$', str(raward.RFstatus)):
                raise SYSTEM_ERROR(u'优惠券转赠状态异常')
            if raward.RFstatus == 0:
                presenter = SUser().get_user_by_user_id(raward.RFfrom)
                recipient = SUser().get_user_by_user_id(raward.USid)
                if not presenter or not recipient:
                    raise NOT_FOUND(u'转赠信息不正确')
                if raward.USid == request.user.id:
                    usheader = presenter.USheader
                    remarks = '由{0}赠送'.format((presenter.USname).encode('utf8'))
                    tag = '赠送'
                    transfer_valid = True
                elif raward.RFfrom == request.user.id:
                    usheader = recipient.USheader
                    remarks = '已赠送给{0}'.format((recipient.USname).encode('utf8'))
                    tag = '赠送'
                    transfer_valid = False
            elif raward.RFstatus == 1:
                recipient = SUser().get_user_by_user_id(raward.USid)
                presenter = SUser().get_user_by_user_id(raward.RFfrom)
                if raward.USid == request.user.id:
                    usheader = presenter.USheader
                    remarks = '因领取后{0}小时未使用已退还给{1}'.format(reward_info.RAtransfereffectivetime, (presenter.USname).encode('utf8'))
                    tag = '已退回'
                    transfer_valid = False
                elif raward.RFfrom == request.user.id:
                    usheader = recipient.USheader
                    remarks = '{0}领取后{1}小时未使用还回'.format((recipient.USname).encode('utf8'), reward_info.RAtransfereffectivetime)
                    tag = '已还回'
                    transfer_valid = True
            elif raward.RFstatus == 2:
                recipient = SUser().get_user_by_user_id(raward.USid)
                usheader = recipient.USheader
                remarks = '{0}已使用'.format(str(recipient.USname))
                tag = '已使用'
                transfer_valid = False

        raward.fill(transfer_valid, 'transfer_valid')
        raward.fill(usheader, 'usheader')
        raward.fill(remarks, 'remarks')
        raward.fill(tag, 'tag')
        return raward

    def check_holdnum_is_exceeded(self, reward):
        """检查持有的优惠券是否超出可拥有数量"""
        pass
예제 #4
0
class CActivity(BaseActivityControl, BaseTask):
    hmsk_type = ['3', '4']

    def __init__(self):
        from WeiDian.service.SActivity import SActivity
        self.sactivity = SActivity()
        from WeiDian.service.SActivityComment import SActivityComment
        self.sacomment = SActivityComment()
        from WeiDian.service.SActivityLike import SActivityLike
        self.salike = SActivityLike()
        from WeiDian.service.SSuperUser import SSuperUser
        self.ssuperuser = SSuperUser()
        from WeiDian.service.SActivityMedia import SActivityMedia
        self.smedia = SActivityMedia()
        from WeiDian.service.SActivityTag import SActivityTag
        self.stags = SActivityTag()
        from WeiDian.service.SActivityFoward import SActivityFoward
        self.foward = SActivityFoward()
        from WeiDian.service.SProduct import SProduct
        self.sproduct = SProduct()
        from WeiDian.service.SUser import SUser
        self.suser = SUser()
        from WeiDian.service.SBigActivity import SBigActivity
        self.sbigactivity = SBigActivity()
        from WeiDian.service.STopNav import STopNav
        self.stopnav = STopNav()
        from WeiDian.service.STask import STask
        self.stask = STask()
        self.empty = ['', None, [], {}]

    @verify_token_decorator
    def set_show_type(self):
        if not is_admin():
            raise TOKEN_ERROR(u'请使用管理员登录')
        data = parameter_required('skip_type')
        try:
            skip_type = str(data.get('skip_type'))
            if skip_type not in ['0', '1', '2']:
                raise TypeError()
        except TypeError as e:
            raise PARAMS_ERROR(u'参数skip_type错误')
        Partner().set_item('skip', 'skip_type', skip_type)
        response = import_status('set_success', 'OK')
        return response

    @verify_token_decorator
    def get_show_type(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员登录')
        settings = Partner()
        skiptype = settings.get_item('skip', 'skip_type')
        response = import_status("messages_get_item_ok", "OK")
        response['data'] = {'skiptype': skiptype}
        return response

    @verify_token_decorator
    def get_all(self):
        """获取条件下的所有活动
        """
        if is_tourist():
            return AUTHORITY_ERROR(u"未登录")
        args = request.args.to_dict()
        logger.info("this is get all activity args %s", args)
        parameter_required(u'tnid')
        tnid = args.get('tnid')  # 导航id
        suid = args.get('suid')  # 管理员id
        lasting = args.get('lasting', 'true')  # 是否正在进行的活动
        acid = args.get("acid")
        if not acid:
            acid = None
        start = int(args.get('start', 0))  # 起始位置
        count = int(args.get('count', 5))  # 取出条数
        page = (args.get('page'))
        # 过滤跳转类型
        skiptype = args.get('skiptype')
        if skiptype is None:
            settings = Partner()
            skiptype = settings.get_item('skip', 'skip_type')  # 配置文件中的过滤条件(默认)
        if skiptype == 'all':
            skiptype = None
        # 分页
        if not page:
            page = int(math.floor(start / count) + 1)
        if not (tnid or suid):
            raise PARAMS_MISS(u"参数缺失")
        try:
            topnav = self.stopnav.get_topnav_by_tnid(tnid)
            if not topnav:
                raise NOT_FOUND(u'无此tnid')
            if topnav.TNtype == 2 and str(tnid) != '1':  # '1'为每日十荐页tnid
                skiptype = 0
            print(skiptype)

            now_time = None

            if str(lasting) == 'true':
                now_time = datetime.strftime(datetime.now(), format_for_db)
            activity_list = self.sactivity.get_activity_by_topnavid(
                tnid, page, count, skiptype, acid, suid, now_time)
            logger.info("get activity_list success")

            # if suid:
            #     activity_list = self.sactivity.get_activity_by_suid(suid, page, count)
            # if not activity_list:
            #     raise SYSTEM_ERROR(u'数据库错误')

            for activity in activity_list:
                self.sactivity.update_view_num(activity.ACid)
                self.fill_detail(activity)
                self.fill_like_num(activity)
                self.fill_type(activity)
                activity.fill(activity.AClinkvalue, 'aclinkvalue')
                if activity.ACSkipType == 0:
                    self.fill_comment_two(activity)
                    activity.fill('none_skip', 'skip_type')
                    activity.fill('无跳转类型', 'zh_skip_type')
                elif activity.ACSkipType == 1:
                    baid = activity.AClinkvalue
                    activity.fill('bigactivity', 'skip_type')
                    activity.fill('专题', 'zh_skip_type')
                    bigactivity = self.sbigactivity.get_one_big_act(baid)
                    if not bigactivity:
                        # raise NOT_FOUND()
                        pass
                    else:
                        bigactivity_type = bigactivity.BAtype
                        big_activity_content = {'type': bigactivity_type}
                        big_activity_content.setdefault(
                            'baid', bigactivity.BAid)
                        # 图片类型专题
                        if bigactivity_type == 0:
                            big_activity_content.setdefault(
                                'baimage', bigactivity.BAlongimg)  # 返回字段不修改
                            big_activity_content.setdefault(
                                'baid', bigactivity.BAid)
                        activity.fill(big_activity_content, 'bigactivity')
                elif activity.ACSkipType == 2:
                    self.fill_soldnum(activity)
                    self.fill_product(activity)
                    activity.fill('product', 'skip_type')
                    activity.fill('商品', 'zh_skip_type')
                activity.ACstarttime = get_web_time_str(activity.ACstarttime)
                activity.ACendtime = get_web_time_str(activity.ACendtime)

            data = import_status("get_activity_list_success", "OK")
            data["count"] = request.all_count
            data["page_count"] = request.page_count
            data["data"] = activity_list
            return data
        except Exception as e:
            logger.exception("get activity error")
            generic_log(e)
            return e

    @verify_token_decorator
    def get_one(self):
        """通过acid获取活动及活动下的评论
        """
        if is_tourist():
            return AUTHORITY_ERROR(u"未登录或token错误")
        args = request.args.to_dict()
        logger.info("get one act args is %s", args)
        parameter_required('acid')
        acid = args.get('acid')  # 活动id
        try:
            activity = self.sactivity.get_activity_by_acid(acid)
            logger.debug("get one act access")
            if not activity:
                raise SYSTEM_ERROR(u'数据错误,无此内容')
            self.sactivity.update_view_num(activity.ACid)
            self.fill_detail(activity)
            self.fill_like_num(activity)
            self.fill_type(activity)
            if activity.ACSkipType == 0:
                self.fill_comment_two(activity)
                activity.fill('none_skip', 'skip_type')
                activity.fill('无跳转类型', 'zh_skip_type')
            elif activity.ACSkipType == 1:
                baid = activity.AClinkvalue
                activity.fill('bigactivity', 'skip_type')
                activity.fill('专题', 'zh_skip_type')
                bigactivity = self.sbigactivity.get_one_big_act(baid)
                if not bigactivity:
                    # raise NOT_FOUND()
                    pass
                else:
                    bigactivity_type = bigactivity.BAtype
                    big_activity_content = {'type': bigactivity_type}
                    big_activity_content.setdefault('baid', bigactivity.BAid)
                    # 图片类型专题
                    if bigactivity_type == 0:
                        big_activity_content.setdefault(
                            'baimage', bigactivity.BAlongimg)  # 返回字段不修改
                        big_activity_content.setdefault(
                            'baid', bigactivity.BAid)
                    activity.fill(big_activity_content, 'bigactivity')
            elif activity.ACSkipType == 2:
                self.fill_soldnum(activity)
                self.fill_product(activity)
                activity.fill('product', 'skip_type')
                activity.fill('商品', 'zh_skip_type')
            activity.ACstarttime = get_web_time_str(activity.ACstarttime)
            activity.ACendtime = get_web_time_str(activity.ACendtime)
            data = import_status("get_activity_info_success", "OK")
            data["data"] = activity
            return data
        except:
            logger.exception("get one act error")
            return SYSTEM_ERROR(u"服务器繁忙")

    @verify_token_decorator
    def stop_one(self):
        """手动截止活动"""
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token
        if not is_admin():
            return AUTHORITY_ERROR  # 权限不足
        data = request.json
        acid = data.get('acid')
        if not acid:
            return PARAMS_MISS
        self.sactivity.stop_activity(acid)
        response_stop_activity = import_status('stop_activity_success', 'OK')
        response_stop_activity['data'] = {}
        response_stop_activity['data']['acid'] = acid
        return response_stop_activity

    @verify_token_decorator
    def add_one(self):
        """添加一个活动, 需要管理员的登录状态"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'当前非管理员权限')
        data = request.json
        logger.debug("add activity data is %s", data)
        parameter_required(u'ACtext', u'TopnavId')
        now_time = datetime.strftime(datetime.now(), format_for_web_second)
        ACstarttime = get_db_time_str(data.get('ACstarttime',
                                               now_time))  # 活动开始时间, 默认当前时间
        ACstarttime_str_to_time = datetime.strptime(ACstarttime, format_for_db)
        three_days_later = datetime.strftime(
            ACstarttime_str_to_time + timedelta(days=3650),
            format_for_web_second)
        ACendtime = get_db_time_str(
            data.get('ACendtime',
                     three_days_later))  # 活动结束时间, 默认3天以后,后期需求公告教程部分非必填,默认改为十年
        TopnavId = data.get('TopnavId')  # 导航页面
        ACtext = data.get('ACtext')  # 文字内容
        media = data.get('media')  # 多媒体
        tags = data.get('tags')  # 右上角tag标签
        ACistop = data.get('ACistop', 0)
        ACtitle = data.get('ACtitle')
        AClinkvalue = data.get('AClinkvalue')
        SUid = data.get('SUid')
        SUid = request.user.id if not SUid else str(SUid)
        ACSkipType = int(data.get('ACSkipType', 0))  # 跳转类型
        ACProductsSoldFakeNum = str(data.get('ACProductsSoldFakeNum',
                                             '')).strip() or 0
        ACforwardFakenum = str(data.get('ACforwardFakenum', '')).strip() or 0
        ACbrowsenum = str(data.get('ACbrowsenum', '')).strip() or 0
        AClikeFakeNum = str(data.get('AClikeFakeNum', '')).strip() or 0
        accomments = data.get('accomments')

        if str(ACistop) == 'true':
            istop = self.sactivity.get_top_activity(TopnavId)
            if istop:
                self.sactivity.change_top_act_status(istop.ACid,
                                                     {'ACistop': False})

        # if not media or not ACtext or not prid or not topnavid:
        #     return PARAMS_MISS
        # relation_product = self.sproduct.get_product_by_prid(PRid)  # 关联的商品
        # if not relation_product:  # 如果没有该商品
        #     return SYSTEM_ERROR("prid错误,没有该商品")
        # 创建活动
        ACid = str(uuid.uuid1())
        # 创建media
        image_num = 0  # 标志用来限制图片或视频的数量
        if media:
            for img_or_video in media:
                img_or_video_keys = img_or_video.keys()
                if 'amimage' in img_or_video_keys and 'amvideo' not in img_or_video_keys:
                    """图片"""
                    self.smedia.add_model(
                        'ActivityMedia', **{
                            'AMid': str(uuid.uuid1()),
                            'ACid': ACid,
                            'AMimage': img_or_video.get('amimage'),
                            'AMsort': img_or_video.get('amsort', 1)
                        })
                    image_num += 1
                    if image_num > 9:
                        raise SYSTEM_ERROR(u"图片超出数量限制")
                elif 'amimage' not in img_or_video_keys and 'amvideo' in img_or_video_keys:
                    """视频"""
                    if image_num < 1:
                        # 只有在无图片的状况下才会添加视频
                        self.smedia.add_model(
                            'ActivityMedia', **{
                                'AMid': str(uuid.uuid1()),
                                'ACid': ACid,
                                'AMvideo': img_or_video.get('amvideo')
                            })
                        # 只可以添加一个视频, 且不可以再添加图片
                        break
        # 创建tag
        if tags:
            count = 0
            for tag in tags:
                state = tag.get('ATstate', 0)
                if str(state) not in ['0', '1']:
                    raise PARAMS_ERROR(u'atstate参数错误')
                if state == 1:
                    count += 1
                if count > 1:
                    raise PARAMS_ERROR(u'默认显示角标只能有一个')
            for tag in tags:
                atstate = tag.get('ATstate', 0)
                self.stags.add_model(
                    'ActivityTag', **{
                        'ATid': str(uuid.uuid1()),
                        'ACid': ACid,
                        'ATname': tag.get('ATname'),
                        'ATstate': atstate
                    })

        if accomments:
            for comments in accomments:
                self.sacomment.add_model(
                    'ActivityComment', **{
                        'ACOid': str(uuid.uuid4()),
                        'ACid': ACid,
                        'USid': 'robot',
                        'ACOrobot': comments.get('acorobot'),
                        'ACtext': comments.get('acotext'),
                        'ACOcreatetime': get_db_time_str()
                    })

        # 是否添加进入专题
        baid = data.get('BAid')
        model_dict = {
            'ACid': ACid,
            # 'PRid': relation_product.PRid,
            'ACSkipType': ACSkipType,
            'AClinkvalue': AClinkvalue,
            # 'BAid': BAid,
            # 'PRid': PRid,
            'SUid': SUid,
            'ACtype': data.get('ACtype'),  # 类型
            'TopnavId': TopnavId,
            'ACtext': ACtext,
            'AClikeFakeNum': AClikeFakeNum,  # 喜欢数
            'ACbrowsenum': ACbrowsenum,  # 浏览数
            'ACforwardFakenum': ACforwardFakenum,  # 转发数量
            'ACProductsSoldFakeNum': ACProductsSoldFakeNum,  # 商品的销售量
            'ACstarttime': ACstarttime,
            'ACendtime': ACendtime,
            'ACtitle': ACtitle,
            'ACistop': ACistop
        }
        if baid:
            if ACSkipType != 2:
                raise PARAMS_ERROR(u'参数不合理, 仅跳转到商品的推文可以加入专题')
            model_dict['BAid'] = baid
        self.sactivity.add_model('Activity', **model_dict)

        response_make_activity = import_status('add_activity_success', 'OK')
        response_make_activity['data'] = {'ACid': ACid}
        return response_make_activity

    @verify_token_decorator
    def update_activity(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'当前非管理员权限')
        args = request.args.to_dict()
        logger.debug("this is update activity args %s", args)
        data = request.json
        logger.debug("this is update activity data %s", data)
        parameter_required("acid")
        now_time = datetime.strftime(datetime.now(), format_for_web_second)
        acid = args.get('acid')
        ACstarttime = get_db_time_str(data.get('acstarttime',
                                               now_time))  # 活动开始时间, 默认当前时间
        ACstarttime_str_to_time = datetime.strptime(ACstarttime, format_for_db)
        three_days_later = datetime.strftime(
            ACstarttime_str_to_time + timedelta(days=3650), format_for_db)
        ACendtime = get_db_time_str(
            data.get('acendtime', get_web_time_str(
                three_days_later)))  # 活动结束时间, 默认3天以后,后期需求公告教程部分非必填,默认改为十年
        TopnavId = data.get('topnavid')  # 导航页面
        ACtext = data.get('actext')  # 文字内容
        media = data.get('media')  # 多媒体
        tags = data.get('tags')  # 右上角tag标签
        ACistop = data.get('acistop', 0)
        ACtitle = data.get('actitle')
        AClinkvalue = data.get('aclinkvalue')
        SUid = data.get('suid')
        SUid = request.user.id if not SUid else str(SUid)
        ACSkipType = int(data.get('acskiptype', 0))  # 跳转类型
        ACProductsSoldFakeNum = data.get('acproductssoldfakenum')
        ACforwardFakenum = data.get('acforwardFakenum')
        ACbrowsenum = data.get('acbrowsenum')
        AClikeFakeNum = data.get('aclikeFakeNum')
        accomments = data.get('accomments')

        if str(ACistop) == 'True':
            istop = self.sactivity.get_top_activity(TopnavId)
            if istop:
                self.sactivity.change_top_act_status(istop.ACid,
                                                     {'ACistop': False})

        image_num = 0  # 标志用来限制图片或视频的数量
        if media:
            self.smedia.del_media_by_acid(acid)
            for img_or_video in media:
                img_or_video_keys = img_or_video.keys()
                if 'amimage' in img_or_video_keys and 'amvideo' not in img_or_video_keys:
                    """图片"""
                    self.smedia.add_model(
                        'ActivityMedia', **{
                            'AMid': str(uuid.uuid1()),
                            'ACid': acid,
                            'AMimage': img_or_video.get('amimage'),
                            'AMsort': img_or_video.get('amsort', 1)
                        })

                    image_num += 1
                    if image_num > 9:
                        raise SYSTEM_ERROR(u"图片超出数量限制")
                elif 'amimage' not in img_or_video_keys and 'amvideo' in img_or_video_keys:
                    """视频"""
                    if image_num < 1:
                        # 只有在无图片的状况下才会添加视频
                        self.smedia.del_media_by_acid(acid)
                        self.smedia.add_model(
                            'ActivityMedia', **{
                                'AMid': str(uuid.uuid1()),
                                'ACid': acid,
                                'AMvideo': img_or_video.get('amvideo')
                            })
                        # 只可以添加一个视频, 且不可以再添加图片
                        break
        # 创建tag
        if tags:
            self.stags.del_tags_by_acid(acid)
            count = 0
            for tag in tags:
                state = tag.get('atstate', 0)
                if str(state) not in ['0', '1']:
                    raise PARAMS_ERROR(u'atstate参数错误')
                if state == 1:
                    count += 1
                elif count > 1:
                    raise PARAMS_ERROR(u'默认显示角标只能有一个')
            for tag in tags:
                atstate = tag.get('atstate', 0)
                self.stags.add_model(
                    'ActivityTag', **{
                        'ATid': str(uuid.uuid1()),
                        'ACid': acid,
                        'ATname': tag.get('atname'),
                        'ATstate': atstate
                    })

        if accomments:
            self.sacomment.del_robot_comment_by_acid(acid)
            for comments in accomments:
                self.sacomment.add_model(
                    'ActivityComment', **{
                        'ACOid': str(uuid.uuid4()),
                        'ACid': acid,
                        'USid': 'robot',
                        'ACOrobot': comments.get('acorobot'),
                        'ACtext': comments.get('acotext'),
                        'ACOcreatetime': get_db_time_str()
                    })

        # 是否添加进入专题
        baid = data.get('baid')
        model_dict = {
            'ACSkipType': ACSkipType,
            'AClinkvalue': AClinkvalue,
            'SUid': SUid,
            'ACtype': data.get('actype'),  # 类型
            'ACtext': ACtext,
            'AClikeFakeNum': AClikeFakeNum,  # 喜欢数
            'ACbrowsenum': ACbrowsenum,  # 浏览数
            'ACforwardFakenum': ACforwardFakenum,  # 转发数量
            'ACProductsSoldFakeNum': ACProductsSoldFakeNum,  # 商品的销售量
            'ACstarttime': ACstarttime,
            'ACendtime': ACendtime,
            'ACtitle': ACtitle,
            'ACistop': ACistop,
            'BAid': baid,
            'ACisdelete': data.get('acisdelete')
        }

        if baid:
            if ACSkipType != 2:
                raise PARAMS_ERROR(u'参数不合理, 仅跳转到商品的推文可以加入专题')
            model_dict['BAid'] = baid
        model_dict = {
            k: v
            for k, v in model_dict.items() if v not in self.empty
        }
        act_info = self.sactivity.update_activity_by_acid(acid, model_dict)
        if not act_info:
            raise SYSTEM_ERROR(u'数据错误')
        response = import_status('update_activity_success', 'OK')
        response['data'] = {'acid': acid}
        return response

    @verify_token_decorator
    def get_exist_tags(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        args = request.args.to_dict()
        logger.debug("get tags args is %s", args)
        try:
            tags_list = self.stags.get_exist_tags()
            logger.info("try to get tags")
            response = import_status("messages_get_item_ok", "OK")
            response['data'] = {"tags_list": tags_list}
            return response
        except Exception as e:
            logger.exception("get exist tags error")
            raise SYSTEM_ERROR(u"数据错误")

    @verify_token_decorator
    def upload_tags(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.json
        logger.debug("upload tags data is %s", data)
        tags = data.get('tags')
        atid_list = []
        try:
            for tag in tags:
                atid = str(uuid.uuid1())
                self.stags.add_model(
                    'ActivityTag', **{
                        'ATid': atid,
                        'ACid': 'customupload',
                        'ATname': tag.get('atname'),
                    })
                atid_list.append(atid)
            res = import_status("save_photo_success", "OK")
            res['data'] = {'atid_list': atid_list}
            return res
        except Exception as e:
            logger.exception("upload tags error")
            raise SYSTEM_ERROR(u"上传数据错误")

    @verify_token_decorator
    def del_exist_tags(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        atid = request.json.get('atid')
        logger.debug("del exist tags data is %s", request.data)
        del_info = self.stags.del_exist_tags(atid)
        if not del_info:
            raise NOT_FOUND(u"无删除内容")
        response = import_status("delete_success", "OK")
        response['data'] = {'atid': atid}
        return response

    @verify_token_decorator
    def share_activity(self):
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        data = request.json
        logger.debug("share qrcode data is %s", data)
        # data_url = data.get("dataurl")
        data_url = self.get_share_url(data.get("dataurl"))
        try:
            logger.info("get user info")
            user = self.suser.get_user_by_user_id(request.user.id)
            if not user:
                raise SYSTEM_ERROR(u'找不到该用户')
            save_path = LinuxRoot + LinuxImgs + "/qrcode/" + user.openid + '.png' if platform.system(
            ) == "Linux" else WindowsRoot + "qrcode/" + user.openid + '.png'
            make_qrcode(user.USheader, data_url, save_path)
            response = import_status("make_qrcode_success", "OK")
            response[
                "qrcodeurl"] = QRCODEHOSTNAME + '/' + LinuxImgs + '/qrcode/' + user.openid + '.png'
            response[
                "components"] = QRCODEHOSTNAME + '/' + LinuxImgs + '/components.png'
            logger.debug('response url is %s', response["qrcodeurl"])

            url = data_url.split('#')[-1]
            from WeiDian.common.get_url_params import GetUrlParams
            parse_dict = GetUrlParams.url_params_to_dict(url)
            if 'baid' in parse_dict or 'prid' in parse_dict:
                # 分享时更改转发数
                paramstype = bool(not 'baid' in parse_dict)
                filter_parameter = {
                    'AClinkvalue':
                    parse_dict['prid'] if paramstype else parse_dict['baid'],
                    'ACSkipType':
                    2 if paramstype else 1,
                    'ACisdelete':
                    False
                }
                act_list = self.sactivity.get_acid_by_filterid(
                    filter_parameter)
                for act in act_list:
                    if act.ACforwardFakenum != 0:
                        self.sactivity.update_forward_fakenum(act.ACid)
                    else:
                        self.sactivity.add_model(
                            'ActivityFoward', **{
                                'AFid': str(uuid.uuid1()),
                                'USid': request.user.id,
                                'ACid': act.ACid
                            })

                if is_partner():

                    self.do_shoppingtask_or_forwardtask(1)
            return response
        except:
            logger.exception("make qrcode error")
            return SYSTEM_ERROR(u'服务器繁忙')

    def get_share_url(self, url):
        if isinstance(url, unicode):
            _url = url.encode('utf8')
        else:
            _url = str(url)
        now_time = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')

        _url_punctuation = '& ' if '?' in _url else '?'
        _url = _url + "{0}time={1}".format(_url_punctuation, now_time)
        return _url

    @verify_token_decorator
    def generate_poster(self):
        # formdata = request.form
        data = request.json
        # logger.info("data is %s", data)   # 因为base64 太大,所以注释掉
        # files = request.files.get("file")
        if platform.system() == "Windows":
            rootdir = "D:/qrcode"
        else:
            rootdir = "/opt/WeiDian/imgs/shareposter/"
        if not os.path.isdir(rootdir):
            os.mkdir(rootdir)
        # if "FileType" not in formdata:
        #     return
        # filessuffix = str(files.filename).split(".")[-1]
        # index = formdata.get("index", 1)
        # filename = request.user.openid + get_db_time_str() + "." + filessuffix
        filename = request.user.openid + get_db_time_str() + ".png"
        filepath = os.path.join(rootdir, filename)
        print(filepath)
        # files.save(filepath)
        baseimg = data.get('baseimg')
        imgdata = baseimg.split(',')[-1]
        img = base64.b64decode(imgdata)
        file = open(filepath, 'wb')
        file.write(img)
        file.close()
        response = import_status("save_poster_success", "OK")
        # url = Inforcode.ip + Inforcode.LinuxImgs + "/" + filename
        url = QRCODEHOSTNAME + "/imgs/shareposter/" + filename
        # print(url)
        logger.info("this url is %s", url)
        response["data"] = url
        return response

    @verify_token_decorator
    def upload_home_images(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'权限不足')
        filetype = request.args.to_dict().get("filetype", 'home')
        notimetag = request.args.to_dict().get("notimetag", '')
        url = BaseFile().upload_file(filetype, notimetag)
        res = import_status("save_photo_success", "OK")
        res['data'] = url
        return res

    @verify_token_decorator
    def upload_static_image(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'权限不足')
        logger.debug('get args is %s', request.args.to_dict())
        filetype = request.args.to_dict().get('filetype')
        from WeiDian.config.enums import staticimage
        if filetype not in staticimage:
            raise PARAMS_MISS('filetype is not right')
        url = BaseFile().upload_file("", "", staticimage.get(filetype))
        res = import_status("save_photo_success", "OK")
        res['data'] = url
        return res

    @verify_token_decorator
    def get_activity_list_by_actitle(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'当前非管理员权限')
        args = request.args.to_dict()
        logger.debug('get arsgs %s', args)
        actitle = args.get("actitle")
        hmtype = args.get('hmtype', 3)
        if str(hmtype) not in self.hmsk_type:
            raise PARAMS_MISS(u"参数错误")

        from WeiDian.config.enums import HMSkipType
        topnav = self.stopnav.get_topnav_by_name(HMSkipType.get(str(hmtype)))
        acfilter = {
            Activity.ACtitle.contains(actitle),
            Activity.ACtext.contains(actitle)
        }
        activity_list = self.sactivity.get_activity_by_filter(
            acfilter, topnav.TNid)
        res = import_status("add_activity_success", "OK")
        res['data'] = activity_list
        return res
예제 #5
0
파일: Cuser.py 프로젝트: clove2han/Weidian
class CUser():
    def __init__(self):
        self.suser = SUser()
        self.stask = STask()
        self.smycenter = SMyCenter()
        self.sorder = SOrder()

    def login(self):
        json_data = request.json
        if not json_data:
            return PARAMS_MISS
        usname = json_data.get('usname')
        # uspassword = json_data.get('uspassword')
        # if not usname or not uspassword:
        #     raise PARAMS_MISS('请输入用户名或密码')
        user = self.suser.verify_user(usname)
        # if not user:
        #     raise SYSTEM_ERROR('用户名或者密码错误')
        if user.USlevel == 0:
            level = 'ordinary'
        if user.USlevel > 0:
            level = 'partner'
        token = usid_to_token(user.USid)
        data = import_status('generic_token_success', "OK")
        data['data'] = {
            'token': token,
            'level': level,
        }
        return data

    def weixin_callback(self):
        """回调, 通过code, 获取用户信息"""
        try:
            args = request.args.to_dict()
            code = args.get('code')
            state = args.get('url')
            # state = state.replace('$', '#').replace('~', '?').replace('+', '=')

            wxlogin = WeixinLogin(APP_ID, APP_SECRET_KEY)
            data = wxlogin.access_token(code)
            # 这是本人的openid
            openid = data.openid
            access_token = data.access_token
            user = self.suser.get_user_by_openid(openid)
            # 是否关注 todo
            wx_subscribe = self.get_wx_response(
                get_subscribe.format(access_token, openid), "get subscribe")
            generic_log(wx_subscribe)
            # if "subscribe" not in wx_subscribe:
            #     logger.error("get subscribe error %s", wx_subscribe)
            #     raise WeixinError(u'get subscribe error')
            # wx_subscribe = dict()
            subscribe = wx_subscribe.get("subscribe", 0)
            data = wxlogin.user_info(data.access_token, data.openid)
            head = self.get_local_head(data.get('headimgurl'), openid)
            if not user:
                # 新用户
                # 这是上级openid, 而非本人openid, 根据openid获取上级身份
                upper_list = re.findall(r'openid=(.*?)&?', state)
                upper = upper_list[0] if upper_list else None
                upperd = self.suser.get_user_by_openid(upper)
                if upperd:
                    # todo 记录邀请成功时间(如果活动进行中的话
                    upperd_id = upperd.USid

                else:
                    upperd_id = None
                # 添加用户
                usid = str(uuid.uuid1())
                self.suser.add_model(
                    "User", **{
                        "USid":
                        usid,
                        "openid":
                        openid,
                        "USlastlogin":
                        datetime.datetime.now().strftime(format_for_db),
                        "USheader":
                        head,
                        "USlevel":
                        0,
                        "USgender":
                        data.get('sex'),
                        "USname":
                        data.get('nickname'),
                        "UPPerd":
                        upperd_id,
                        "unionid":
                        data.get('openid'),
                        "subscribe":
                        subscribe,
                    })
            else:
                # 老用户
                usid = user.USid
                print(usid)
                update_dict = {
                    "USlastlogin":
                    datetime.datetime.now().strftime(format_for_db),
                    "USheader": head,
                    "USgender": data.get("sex"),
                    "USname": data.get("nickname"),
                    "unionid": data.get("unionid"),
                    "subscribe": subscribe,
                }
                update_result = self.suser.update_user(usid, update_dict)
                if not update_result:
                    raise SYSTEM_ERROR()
            # 生成token
            token = usid_to_token(usid)
            userlogintime = self.suser.get_user_login_time(usid)
            now = datetime.datetime.now().strftime(format_for_db)

            is_today_first = True
            if userlogintime:
                is_today_first = bool(
                    userlogintime.USTcreatetime[:-6] < now[:-6])
            self.suser.add_model(
                "UserLoginTime", **{
                    "ULTid": str(uuid.uuid1()),
                    "USid": usid,
                    "USTip": request.remote_addr,
                    "USTcreatetime": now,
                })
            params_data = {
                "is_first": int(bool(user)),
                "subscribe": subscribe,
                "newtoken": token,
                "openid": openid,
                "access_token": access_token,
                "wximg": wximg,
                'user_level': 0 if bool(user) else user.USlevel,
                "is_today_first": int(is_today_first),
                "token": usid_to_token(usid),
                "icon": icon
            }
            # params_str = urllib.urlencode(params_data, doseq=True)

            # redirect_url = state + "?"+params_str
            # logger.debug("get loggin redirect_url %s", redirect_url)
            # return redirect(redirect_url)
            return params_data
        except WeixinError as e:
            generic_log(e)
            return SYSTEM_ERROR(u'code error')

    def wx_login(self):
        data = request.json
        state_url = data.get('url') or request.url
        logger.debug('get state url %s', state_url)
        state_url = state_url.replace('#', '$').replace('?',
                                                        '~').replace('=', '+')
        state = str(state_url)
        logger.debug('get state %s, len(state) %s', state, len(state))
        login = WeixinLogin(APP_ID, APP_SECRET_KEY)
        redirect_url = login.authorize(QRCODEHOSTNAME +
                                       "/user/wechat_callback",
                                       'snsapi_userinfo',
                                       state=state)
        return {"data": {'redirect_url': redirect_url}, "status": 302}

    def get_accesstoken(self):
        args = request.args.to_dict()
        logger.info("args", args)
        true_params = ["code"]
        for key in true_params:
            if key not in args:
                return PARAMS_MISS

        # from WeiDian.config.urlconfig import get_access_toke, get_user_info, get_subscribe
        # 获取access_token openid

        # request_url = get_access_toke.format(APP_ID, APP_SECRET_KEY, args["code"])
        # strResult = None
        # try:
        #
        #     req = urllib2.Request(request_url)
        #     response = urllib2.urlopen(req)
        #     strResult = response.read()
        #     response.close()
        #     logger.debug(strResult)
        # except Exception as e:
        #     print(e)
        #     return NETWORK_ERROR

        # jsonResult = self.get_wx_response(request_url, "get access_token")
        # if "access_token" not in jsonResult or "openid" not in jsonResult:
        #     logger.error("get access token and openid error %s", jsonResult)
        #     return jsonResult
        # access_token = jsonResult["access_token"]
        # openid = jsonResult['openid']
        wxlogin = WeixinLogin(APP_ID, APP_SECRET_KEY)
        try:
            data = wxlogin.access_token(args["code"])
        except WeixinLoginError as e:
            logger.error('login error %s', e.message)
            return import_status('welcome', 'OK')
        openid = data.openid
        access_token = data.access_token
        logger.debug('get openid %s, access_token %s', openid, access_token)
        user = self.suser.get_user_by_openid(openid)
        is_first = not bool(user)
        print get_subscribe.format(mp.accesstoken(), openid)
        wx_subscribe = self.get_wx_response(
            get_subscribe.format(mp.accesstoken(), openid), "get subscribe")
        if "subscribe" not in wx_subscribe:
            logger.error("get subscribe error %s", wx_subscribe)
            # return wx_subscribe
            mp.update_access_token_and_jsticket(refresh=True)
            wx_subscribe = self.get_wx_response(
                get_subscribe.format(mp.accesstoken(), openid),
                "get subscribe retry")
            if "subscribe" not in wx_subscribe:
                logger.error("get subscribe retry error %s", wx_subscribe)
                return wx_subscribe

        subscribe = wx_subscribe.get("subscribe", 0)

        # user_info = self.get_wx_response(get_user_info.format(access_token, openid), "get user info")
        # if "errcode" in user_info or "errmsg" in user_info:
        #     response = import_status("get_user_info_error", "WD_ERROR", "error_get_user_info")
        #     response['data'] = user_info
        #     return response
        user_info = wxlogin.userinfo(access_token, openid)
        upperd = self.suser.get_user_by_openid(args.get("UPPerd", ""))

        upperd_id = upperd.USid if upperd else None
        user_level = 0 if is_first else user.USlevel
        ushead = self.get_local_head(user_info.get("headimgurl"), openid)
        if is_first:
            usid = str(uuid.uuid1())
            self.suser.add_model(
                "User", **{
                    "USid": usid,
                    "openid": openid,
                    "USlastlogin":
                    datetime.datetime.now().strftime(format_for_db),
                    "USheader": user_info.get("headimgurl"),
                    "USlevel": 0,
                    "USgender": user_info.get("sex"),
                    "USname": user_info.get("nickname"),
                    "UPPerd": upperd_id,
                    "unionid": user_info.get("unionid"),
                    "accesstoken": access_token,
                    "subscribe": subscribe,
                })
            # self.smycenter.add_model("MyCenter", **{
            #     "MYid": str(uuid.uuid1()),
            #     "USid": usid,
            #     "MYranking": '0',
            #     "MYrewards": '0'
            # })

            tasl_level = self.stask.get_tasklevel_by_level(1)
            task_list = self.stask.get_task_by_tlid(tasl_level.TLid)

            for task in task_list:
                self.suser.add_model(
                    "TaskUser", **{
                        "TUid": str(uuid.uuid1()),
                        "USid": usid,
                        "TAid": task.TAid,
                        "TUstatus": 0,
                        "TUnumber": 0
                    })

        else:
            usid = user.USid

            update_result = self.suser.update_user(
                usid, {
                    "USlastlogin":
                    datetime.datetime.now().strftime(format_for_db),
                    "USheader": ushead,
                    "USgender": user_info.get("sex"),
                    "USname": user_info.get("nickname"),
                    "unionid": user_info.get("unionid"),
                    "accesstoken": access_token,
                    "subscribe": subscribe,
                })
            if not update_result:
                return SYSTEM_ERROR
        userlogintime = self.suser.get_user_login_time(usid)
        now = datetime.datetime.now().strftime(format_for_db)

        is_today_first = True
        if userlogintime:
            is_today_first = bool(userlogintime.USTcreatetime[:-6] < now[:-6])
        self.suser.add_model(
            "UserLoginTime", **{
                "ULTid": str(uuid.uuid1()),
                "USid": usid,
                "USTip": request.remote_addr,
                "USTcreatetime": now,
            })
        response = import_status("SUCCESS_GET_OPENID", "OK")
        # from WeiDian.config.enums import icon
        response["data"] = {
            "is_first": int(is_first),
            "subscribe": subscribe,
            "openid": openid,
            "access_token": access_token,
            "wximg": wximg,
            'user_level': user_level,
            "is_today_first": int(is_today_first),
            "token": usid_to_token(usid),
            "icon": icon
        }
        logger.debug("get loggin response %s", response)
        return response

    # @verify_token_decorator
    def get_wx_config_accesstoken(self, url):
        import time
        import hashlib

        noncestr = self.__create_nonce_str()
        data = {
            "url": url,
            "jsapi_ticket": mp.jsticket(),
            'timestamp': int(time.time()),
            "noncestr": noncestr
        }
        logger.info("get wx config %s", data)
        try:
            # response_str = "&".join([str(k)+'='+str(v) for k, v in data.items()])
            # response_str = signature_str.format(**data)
            response_str = '&'.join(
                ['%s=%s' % (key.lower(), data[key]) for key in sorted(data)])
            logger.debug("get response: %s", response_str)
            signature = hashlib.sha1(response_str.encode('utf-8')).hexdigest()
            logger.debug('get signature: %s', signature)
            data['sign'] = signature
            data['appid'] = APP_ID
        except:
            logger.exception("Get wx config error")
            return SYSTEM_ERROR
        # response = import_status("SUCCESS_GET_CONFIG", "OK")
        # response['data'] = data
        # return response
        return data

    def __create_nonce_str(self):
        return ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(15))  # 创建随机字符串

    def get_wx_config(self):

        url = request.args.get("url", request.url)
        # url = request.json.get("url", request.url)
        logger.debug('get url %s', url)
        # data = mp.jsapi_sign(url=url)
        # data['ticket'] = mp.jsapi_ticket
        data = self.get_wx_config_accesstoken(url)
        data['ticket'] = data.pop('jsapi_ticket')
        data['appId'] = data.pop('appid')
        logger.debug("get wx config %s", data)
        response = import_status("SUCCESS_GET_CONFIG", "OK")
        response['data'] = data

        return response

    def get_wx_response(self, url, urltype):
        try:
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
            strResult = response.read()
            response.close()
            logger.info("%s is %s", urltype, strResult)
            return json.loads(strResult)
        except:
            logger.exception("%s error", urltype)
            raise NETWORK_ERROR

    def get_local_head(self, headurl, openid):
        data = requests.get(headurl)
        filename = openid + '.png'
        filepath = os.path.join(LinuxUserHead, filename)
        with open(filepath, 'wb') as head:
            head.write(data.content)

        url = QRCODEHOSTNAME + "/imgs/head/" + filename
        return url

    @verify_token_decorator
    def get_all_user(self):
        if not is_admin():
            raise TOKEN_ERROR(u'权限不足')
        data = request.args.to_dict()
        logger.debug('get all user args : %s', data)
        pagenum, pagesize = self.get_pagesize_pagenum(data)

        user_list, count = self.suser.get_all_user(pagesize, pagenum)
        map(self.fill_user_level, user_list)
        map(self.fill_user_perd, user_list)
        # map(self.fill_user_sub, user_list)
        map(self.fill_user_order_amout, user_list)
        response = import_status('messages_get_item_ok', 'OK')
        response['data'] = user_list
        response['count'] = count

        return response

    def fill_user_perd(self, user):
        perduser = self.suser.get_user_by_openid(user.UPPerd)
        if perduser:
            user.UPPerd = perduser.USname
        user.add("UPPerd")

    # def fill_user_sub(self, user):
    #     subuser = self.suser.get_sub_user(user.openid)
    #     user.USsub = subuser
    #     user.add('USsub')

    def fill_user_level(self, user):
        user_level = userlevel.get(str(user.USlevel) if user.USlevel else '0')
        user.USlevel = user_level
        user.add('USlevel')

    def fill_user_order_amout(self, user):
        user.BuyOrderCount, user.SellOrderCount = self.sorder.get_user_count_order(
            user.USid)
        user.add("BuyOrderCount", "SellOrderCount")

    @verify_token_decorator
    def get_user_sub(self):
        data = request.args.to_dict()
        sub = data.get('sub')
        usid = data.get('usid')
        if sub == None:
            if not is_admin():
                raise TOKEN_ERROR(u'权限不足')
        else:
            if not is_partner():
                raise TOKEN_ERROR(u'当前非合伙人')
        logger.debug('get user sub args: %s', data)
        # parameter_required('usid')
        pagenum, pagesize = self.get_pagesize_pagenum(data)
        if usid:
            user = self.suser.get_user_by_user_id(usid)
        else:
            user = self.suser.get_user_by_user_id(request.user.id)
        user_sub, count = self.suser.get_sub_user(user.openid, pagesize,
                                                  pagenum)
        response = import_status('messages_get_item_ok', 'OK')
        response['data'] = user_sub
        response['count'] = count
        return response

    @verify_token_decorator
    def get_user_by_usphone_or_usname(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'非管理员权限')
        data = request.args.to_dict()
        keywords = data.get('keywords').encode('utf8')
        from WeiDian.models.model import User
        usfilter = (User.USname.like("%{0}%".format(keywords)),
                    User.USphone.like("%{0}%".format(keywords)))
        user_res = self.suser.get_user_by_phone_or_name(usfilter)
        response = import_status('messages_get_item_ok', 'OK')
        response['data'] = user_res
        return response

    def get_pagesize_pagenum(self, data):
        pagesize = data.get('page_size')
        pagenum = data.get('page_num')
        if re.match(r'^\d+$', str(pagesize)):
            pagesize = int(pagesize)
        else:
            pagesize = 10
        if re.match(r'^\d+$', str(pagenum)):
            pagenum = int(pagenum)
        else:
            pagenum = 1
        pagenum = pagenum or 1
        pagesize = pagesize or 5

        return pagenum, pagesize