예제 #1
0
class GMV(object):
    def __init__(self):
        self.sorder = SOrder()

    def total_gmv(self):
        """平台总gmv"""
        data = {'total_order': self.sorder.get_order_all()}

    def order_count(self):
        return len(self.order_all)

    @property
    def order_all(self):
        return self.sorder.get_order_all()
예제 #2
0
 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()
예제 #3
0
    def __init__(self):
        from WeiDian.service.SProduct import SProduct
        self.sproduct = SProduct()
        from WeiDian.service.SProductSkuValue import SProductSkuValue
        self.sproductskuvalue = SProductSkuValue()
        from WeiDian.service.SProductImage import SProductImage
        self.sproductimage = SProductImage()
        from WeiDian.service.SProductSkuKey import SProductSkuKey
        self.sproductskukey = SProductSkuKey()
        from WeiDian.service.SActivity import SActivity
        self.sactivity = SActivity()
        from WeiDian.service.SProductLike import SProductLike
        self.sproductlike = SProductLike()
        from WeiDian.control.Cuser import CUser
        self.cuser = CUser()
        from WeiDian.service.SBigActivity import SBigActivity
        self.sbigactivity = SBigActivity()
        from WeiDian.service.STopNav import STopNav
        self.stopnav = STopNav()
        from WeiDian.service.SOrder import SOrder
        self.sorder = SOrder()
        from WeiDian.service.SSuperUser import SSuperUser
        self.ssuperuser = SSuperUser()
        self.empty = ['', [], {}, None]
        # 后续修改
        self.partner = Partner()
        self.update_sku_params = [
            'PRid', "PSVid", 'PSKproductnum', 'PSKalias', 'PSKprice',
            'PSKpostfee', 'PSKactiviyid', 'PSKproperkey', "PSisdelete"
        ]

        self.update_product_params = [
            'PRmainpic', 'PRdetail', 'PRimporturl', 'PRishot', 'PRtitle',
            'PRname', 'Maketlias', 'PRalias', 'PRprice', 'PReditstate',
            'PRsalesvolume', 'PRoldprice', 'PRchannelname', 'PRvipprice',
            'PRlogisticsfee', 'PRchannelid', 'SUid', 'PRstock', 'PRsalestatus',
            'PRishhare', 'PRtarget', 'PRviewnum', 'PRfakeviewnum',
            'PRfakelikenum', 'PRsalefakenum', 'PRbaid'
        ]
예제 #4
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
예제 #5
0
class CProduct(BaseProductControl):
    def __init__(self):
        from WeiDian.service.SProduct import SProduct
        self.sproduct = SProduct()
        from WeiDian.service.SProductSkuValue import SProductSkuValue
        self.sproductskuvalue = SProductSkuValue()
        from WeiDian.service.SProductImage import SProductImage
        self.sproductimage = SProductImage()
        from WeiDian.service.SProductSkuKey import SProductSkuKey
        self.sproductskukey = SProductSkuKey()
        from WeiDian.service.SActivity import SActivity
        self.sactivity = SActivity()
        from WeiDian.service.SProductLike import SProductLike
        self.sproductlike = SProductLike()
        from WeiDian.control.Cuser import CUser
        self.cuser = CUser()
        from WeiDian.service.SBigActivity import SBigActivity
        self.sbigactivity = SBigActivity()
        from WeiDian.service.STopNav import STopNav
        self.stopnav = STopNav()
        from WeiDian.service.SOrder import SOrder
        self.sorder = SOrder()
        from WeiDian.service.SSuperUser import SSuperUser
        self.ssuperuser = SSuperUser()
        self.empty = ['', [], {}, None]
        # 后续修改
        self.partner = Partner()
        self.update_sku_params = [
            'PRid', "PSVid", 'PSKproductnum', 'PSKalias', 'PSKprice',
            'PSKpostfee', 'PSKactiviyid', 'PSKproperkey', "PSisdelete"
        ]

        self.update_product_params = [
            'PRmainpic', 'PRdetail', 'PRimporturl', 'PRishot', 'PRtitle',
            'PRname', 'Maketlias', 'PRalias', 'PRprice', 'PReditstate',
            'PRsalesvolume', 'PRoldprice', 'PRchannelname', 'PRvipprice',
            'PRlogisticsfee', 'PRchannelid', 'SUid', 'PRstock', 'PRsalestatus',
            'PRishhare', 'PRtarget', 'PRviewnum', 'PRfakeviewnum',
            'PRfakelikenum', 'PRsalefakenum', 'PRbaid'
        ]

    @verify_token_decorator
    def add_product_list(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token错误
        if not is_admin():
            return AUTHORITY_ERROR  # 权限不足
        json_data = request.json
        product_list = json_data.get('products')
        logger.debug('get product list %s', product_list)
        product_list = self.fix_product_list(product_list)
        list_add_models('Product', product_list)
        data = import_status('add_product_list_success', 'OK')
        data['data'] = {'prid': self.prid_list}
        return data

    # 删除商品
    @verify_token_decorator
    def delete_product(self):
        if not is_admin():
            return AUTHORITY_ERROR(u'权限不足')
        data = parameter_required('productid')
        logger.debug('get delete_product data %s', data)
        product = self.sproduct.get_product_by_productid(data.get('productid'))
        if not product:
            return import_status('no_product', 'OK')

        update_result = self.sproduct.update_product_by_productid(
            data.get('productid'), {
                "PRisdelete": True,
                'PRmodifytime': get_db_time_str()
            })
        if not update_result:
            raise SYSTEM_ERROR(u'服务器繁忙')
        return import_status('delete_product_success', 'OK')

    # 上下架商品
    @verify_token_decorator
    def shelves_product(self):
        """状态改成0 上架  1下架"""
        if not is_admin():
            return AUTHORITY_ERROR(u'权限不足')
        data = parameter_required('productid')
        prstatus = data.get("prstatus", 1)
        logger.debug('get prestatus. %s', prstatus)
        logger.debug('get productid. %s', data.get('productid'))
        if not re.match(r'^[0-2]$', str(prstatus)):
            raise PARAMS_MISS(u'prstatus, 参数异常')
        prstatus = int(prstatus)
        prstatus = 0 if int(prstatus) else 1
        product = self.sproduct.get_product_by_productid(data.get('productid'))
        logger.debug('get product %s', product)
        if not product and prstatus != 1:
            return import_status('no_product', 'OK')
        update_result = self.sproduct.update_product_by_productid(
            data.get('productid'), {
                "PRstatus": prstatus,
                'PRmodifytime': get_db_time_str()
            })
        if not update_result:
            raise SYSTEM_ERROR(u'服务器繁忙')
        return import_status('update_product_success', 'OK')

    # 更新sku
    @verify_token_decorator
    def update_sku(self):
        if not is_admin():
            return AUTHORITY_ERROR(u'权限不足')
        data = parameter_required('psskuid', 'productid')
        logger.debug('get update_sku data %s', data)
        pskpropervalue = data.get('pskpropervalue')
        skukey = {}
        product = self.sproduct.get_product_by_productid(data.get('productid'))
        if not product:
            return import_status('no_product', 'OK')

        for key in self.update_sku_params:
            if not data.get(key.lower()) and data.get(key.lower()) != 0:
                continue
            skukey[key] = data.get(key.lower())

        if skukey.get("PSKproperkey"):
            skukey['_PSKproperkey'] = json.dumps(skukey.pop('PSKproperkey'))

        productsku = self.sproductskukey.get_psk_by_psskuid(
            data.get("psskuid"), product.PRid)
        if not productsku:
            psv = self.sproductskuvalue.get_skvalue_by_prid(product.PRid)
            skukey['PSKid'] = str(uuid.uuid1())
            skukey['PRid'] = product.PRid
            skukey['PSVid'] = psv.PSVid
            skukey['PSskuid'] = data.get("psskuid")
            self.sproductskukey.add_model("ProductSkuKey", **skukey)
        else:
            update_result = self.sproductskukey.update_product_sku(
                data.get("psskuid"), product.PRid, skukey)
            if not update_result:
                raise SYSTEM_ERROR(u'服务器繁忙')

        if pskpropervalue and product:
            update_result = self.sproductskuvalue.update_skuvalue(
                product.PRid, {"_PSVpropervalue": json.dumps(pskpropervalue)})
            if not update_result:
                raise SYSTEM_ERROR(u'服务器繁忙')
        return import_status('update_product_sku_success', 'OK')

    # 更新商品
    @verify_token_decorator
    def update_product(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'权限不足')

        data = parameter_required('productid')
        logger.debug('get update_product data %s', data)
        productid = data.get('productid')
        product = self.sproduct.get_product_by_productid(productid)
        if not product:
            return import_status('no_product', 'OK')
        product = {}
        for key in self.update_product_params:
            if not data.get(key.lower()) and data.get(key.lower()) != 0:
                continue
            product[key] = data.get(key.lower())
        product['PRmodifytime'] = get_db_time_str()
        update_result = self.sproduct.update_product_by_productid(
            productid, product)
        if not update_result:
            raise SYSTEM_ERROR(u'服务器繁忙')
        return import_status('update_product_success', 'OK')

    # 更新商品
    @verify_token_decorator
    def update_product_image(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'权限不足')

        data = parameter_required('productid', 'images')
        logger.debug('get update_product_image data %s', data)
        product = self.sproduct.get_product_by_productid(data.get("productid"))
        if not product:
            raise PARAMS_MISS(u"商品不存在或已删除")
        # for image in data.get("images"):
        #     primage = self.sproductimage.get_images_by_prid_pisort(product.PRid, image.get('pisort', 0))
        #     if primage:
        #         update_result = self.sproductimage.update_image(
        #             primage.PIid, {"PIurl": image.get("piurl"), "PIexist": image.get("piexist", 1)})
        #         if not update_result:
        #             logger.error('update product image error, sort is %s', image.get("pisort", 0))
        #             raise SYSTEM_ERROR(u"数据库异常")
        #     else:
        #         self.sproductimage.add_model("ProductImage", **{
        #             "PIid": str(uuid.uuid1()),
        #             "PRid": product.PRid,
        #             "PIurl": image.get("piurl"),
        #             "PIsort": image.get("pisort", 0),
        #             "PIexist": image.get("piexist", 1),
        #         })
        self.sproductimage.update_image_by_prid(product.PRid, {"PIexist": 0})
        for image in data.get('images'):
            self.sproductimage.add_model(
                "ProductImage", **{
                    "PIid": str(uuid.uuid1()),
                    "PRid": product.PRid,
                    "PIurl": image.get("piurl"),
                    "PIsort": image.get("pisort", 0),
                    "PIexist": image.get("piexist", 1),
                })

        return import_status('update_product_image_success', 'OK')

    @verify_token_decorator
    def get_product_pools(self):
        """后台获取商品池列表内容"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        args = request.args.to_dict()
        logger.debug("Get Commodity Pools data is %s", args)
        page, count = self.cuser.get_pagesize_pagenum(args)
        time_start = args.get('time_start')
        if time_start:
            time_start = get_db_time_str(time_start)
        time_end = args.get('time_end')
        if time_end:
            time_end = get_db_time_str(time_end)
        status = args.get('status')
        kw = args.get('kw')
        if kw not in self.empty:
            kw = kw.encode('utf8')
        isdelete = args.get('isdelete', 0)  # 0  or  1
        if str(isdelete) == '0':
            isdelete = False
        elif str(isdelete) == '1':
            isdelete = True
        else:
            isdelete = None
        product_list = self.sproduct.get_product_filter(
            kw, time_start, time_end, isdelete, status, page, count)
        for product in product_list:
            self.sproduct.update_view_num(product.PRid)
            self.fill_prbaid(product)
            self.fill_prtarget(product)
            if product.PRcreatetime:
                prcreatetime = get_web_time_str(product.PRcreatetime)
                product.fill(prcreatetime, 'prcreatetime')
            if product.SUmodifyid:
                isclaim = True
                canclaim = True if product.SUmodifyid == request.user.id else False
                caneditact = True if product.SUmodifyid == request.user.id else False
            else:
                isclaim = False
                canclaim = True
                caneditact = False
            product.fill(product.SUmodifyid or '', "claimid")
            product.fill(isclaim, "isclaim")
            product.fill(canclaim, "canclaim")
            product.fill(caneditact, "caneditact")
            isbig = False
            if product.PRtarget:
                isbig = True if product.PRtarget[0] == '101' else False
            product.fill(isbig, 'isbig')
            pv = product.PRviewnum
            product.fill(pv, 'pv')
            salesvolume = product.PRsalesvolume
            transform = 0 if pv == 0 else salesvolume / float(pv)
            ortransform = "%.2f%%" % (transform * 100)
            product.fill(ortransform, 'ortransform')
            refund_list = self.sorder.get_refund_product()
            redfund_num = 0
            if refund_list:
                for refund in refund_list:
                    refund_product = self.sorder.get_orderproductinfo_by_opiid(
                        refund.OPIid)
                    if refund_product:
                        redfund_num = redfund_num + refund_product.OPIproductnum
            refundrate_f = 0 if salesvolume == 0 else redfund_num / float(
                salesvolume)
            refundrate = "%.2f%%" % (refundrate_f * 100)
            product.fill(refundrate, 'refundrate')
            product.fill(product.prbaid, 'prbaid')
            product.fill(product.PRstatus, 'prstatus')
            activitystatus = 0
            acid = None
            ac_list = self.sactivity.get_acid_by_filterid({
                'AClinkvalue':
                product.PRid,
                'ACSkipType':
                2,
                'ACisdelete':
                False
            })
            if ac_list not in self.empty:
                for act in ac_list:
                    temp_num = -1 if act.ACeditstatus is None else act.ACeditstatus
                    activitystatus = temp_num + 1
                    acid = act.ACid
            zh_activitystatus = activity_edit_status.get(str(activitystatus))
            product.fill(activitystatus, 'activitystatus')
            product.fill(zh_activitystatus, 'zh_activitystatus')
            product.fill(acid, 'acid')
        data = import_status('get_product_list_success', 'OK')
        data['data'] = product_list
        data["count"] = request.all_count
        data["page_count"] = request.page_count
        return data

    @verify_token_decorator
    def update_sku_price(self):
        """更新sku里的售价/进价/利润"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        data = request.json
        pskid = data.get('pskid')
        parameter_required('pskid')
        logger.debug("update sku price data is %s", data)
        sku_info = self.sproductskukey.get_psk_by_pskid(pskid)
        if not sku_info:
            raise NOT_FOUND(u'没有找到相应的sku')
        price_dict = {
            "PSKprice": data.get('pskprice'),
            "PSKprofict": data.get('pskprofict'),
            "PSKpurchase": data.get('pskpurchase')
        }
        price_dict = {
            k: v
            for k, v in price_dict.items() if v not in self.empty
        }
        if price_dict not in self.empty:
            up_info = self.sproductskukey.update_sku_price_by_filter(
                {'PSKid': pskid}, price_dict)
            if not up_info:
                raise SYSTEM_ERROR(u'更新数据错误')
        # 操作日志
        operation_dict = {
            "PSKprice": u'更新售价',
            "PSKprofict": u'更新利润',
            "PSKpurchase": u'更新进货价'
        }
        if price_dict not in self.empty:
            for i in price_dict.keys():
                self.__make_product_recording(sku_info.PRid, sku_info.PSskuid,
                                              operation_dict[i])
        response = import_status("update_success", "OK")
        response['data'] = {'pskid': pskid}
        return response

    @verify_token_decorator
    def shelf_product_and_claim_act(self):
        """商品上下架/删除商品/推文认领"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        data = request.json
        logger.debug("shelf product and claim act data is %s", data)
        prid = data.get('prid')
        parameter_required('prid')
        shelf = data.get('shelf')  # 0 下架 1 上架
        claim = data.get('claim')  # 0 取消认领 1 认领推文
        prdel = data.get('prdel')  # 1 删除
        modifyid = None
        if shelf not in self.empty and claim not in self.empty:
            raise PARAMS_MISS(u'参数错误,只能进行一项操作')
        pr_info = self.sproduct.get_product_by_prid(prid)
        if not pr_info:
            raise NOT_FOUND(u'无该商品信息')
        if pr_info.PRisdelete == True:
            raise NOT_FOUND(u'数据错误,该商品已被删除')
        if shelf not in self.empty:
            if not re.match(r'^[0-1]$', str(shelf)):
                raise PARAMS_MISS(u'shelf, 参数异常')
            if pr_info.PRstatus == int(shelf):
                raise SYSTEM_ERROR(u'已完成上/下架操作')
            upinfo = self.sproduct.update_product_info_by_filter(
                {'PRid': prid}, {
                    'PRmodifytime': get_db_time_str(),
                    'PRstatus': int(shelf)
                })
            if not upinfo:
                raise SYSTEM_ERROR(u'更新数据错误')
            # 操作日志
            shelf_operation = u'上架商品' if str(shelf) == '1' else u'下架商品'
            self.__make_product_recording(prid, prid, shelf_operation)
        if claim not in self.empty:
            if not re.match(r'^[0-1]$', str(claim)):
                raise PARAMS_MISS(u'claim, 参数异常')
            if pr_info.SUmodifyid:
                if pr_info.SUmodifyid != request.user.id:
                    raise SYSTEM_ERROR(u'该推文已被其他运营认领')
                else:
                    if str(claim) == '1':
                        raise SYSTEM_ERROR(u'您已完成认领')
            else:
                if str(claim) == '0':
                    raise SYSTEM_ERROR(u'您没有认领该商品的关联推文,不能进行解除操作')
            modifyid = request.user.id if str(claim) == '1' else None
            upinfo = self.sproduct.update_product_info_by_filter(
                {'PRid': prid}, {
                    'PRmodifytime': get_db_time_str(),
                    'SUmodifyid': modifyid
                })
            if not upinfo:
                raise SYSTEM_ERROR(u'更新数据错误')
            # 操作日志
            operation = u'认领推文' if str(claim) == '1' else u'解除推文认领'
            self.__make_product_recording(prid, prid, operation)
        if prdel not in self.empty:
            if str(prdel) == '1':
                update_result = self.sproduct.update_product_info_by_filter(
                    {'PRid': prid}, {
                        "PRisdelete": True,
                        'PRmodifytime': get_db_time_str()
                    })
                if not update_result:
                    raise SYSTEM_ERROR(u'删除数据错误')
                # 操作日志
                self.__make_product_recording(prid, prid, u'删除商品')
        response = import_status("update_success", "OK")
        response['data'] = {'prid': prid, 'claimid': modifyid or ''}
        return response

    @verify_token_decorator
    def get_product_operation_record(self):
        """获取商品操作记录"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        args = request.args.to_dict()
        prid = args.get('prid')
        page_num, page_size = self.cuser.get_pagesize_pagenum(args)
        record_list = self.sproduct.get_product_operation_record(
            page_num, page_size, prid)
        if record_list:
            for record in record_list:
                portarget = record.PRid if not record.PORtarget else record.PORtarget
                record.PORcreatetime = get_web_time_str(record.PORcreatetime)
                suser = self.ssuperuser.get_one_super_by_suid(record.SUid)
                suname = suser.SUname if suser else ''
                record.fill(suname, 'suname')
                record.fill(portarget, 'portarget')
        response = import_status("messages_get_item_ok", "OK")
        response['data'] = record_list
        response['page_count'] = request.page_count
        response['count'] = request.all_count
        return response

    @verify_token_decorator
    def update_product_relate_prtarget(self):
        """商品池修改商品与模块的关联"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        data = request.json
        logger.debug("update product relate prtarget data is %s", data)
        prid = data.get('prid')
        prtargets = data.get('prtarget')
        if prtargets:
            if len(prtargets) > 3:
                raise SYSTEM_ERROR(u'每个商品最多只能关联三个模块')
            ptid = str(uuid.uuid1())
            if '101' in prtargets:
                del_info = self.sproduct.del_product_target_by_filter(
                    {"PRid": prid})
                logger.debug(
                    "del prtarget relation success before add operation, del count: %s",
                    del_info)
                self.sproduct.add_model(
                    "ProductTarget", **{
                        'PTid': ptid,
                        'PRid': prid,
                        'PRtarget': '101'
                    })
                # 操作记录
                self.__make_product_recording(prid, prid, u'更改为大礼包商品')
            else:
                topnav_list = self.stopnav.get_all_tnid()
                tnid_list = []
                [tnid_list.append(topnav.TNid) for topnav in topnav_list]
                with self.sproduct.auto_commit() as session:
                    model_beans = []
                    for targetid in prtargets:
                        if str(targetid) not in tnid_list:
                            raise PARAMS_MISS(u'prtarget参数错误,未找到要关联的模块')
                        prtarget_dict = dict(PTid=str(uuid.uuid4()),
                                             PRid=prid,
                                             PRtarget=targetid)
                        prtarget_info = ProductTarget.create(prtarget_dict)
                        model_beans.append(prtarget_info)
                        # 操作记录
                        self.__make_product_recording(prid, targetid,
                                                      u'更改模块关联')
                    session.query(ProductTarget).filter(
                        ProductTarget.PRid == prid).delete()
                    session.add_all(model_beans)
        elif prtargets == []:
            # 操作记录
            try:
                target_info = self.sproduct.get_product_target_by_prid(prid)
                if target_info:
                    for tgid in target_info:
                        self.__make_product_recording(prid, tgid.PRtarget,
                                                      u'解除模块关联')
            except Exception as e:
                logger.exception("not found prtargetid ,error is %s", e)
                self.__make_product_recording(prid, prid, u'解除模块关联')
            del_info = self.sproduct.del_product_target_by_filter(
                {"PRid": prid})
            logger.debug("del prtarget relation success this is none list: %s",
                         del_info)
        response = import_status("update_success", "OK")
        response['data'] = {'prid': prid}
        return response

    @verify_token_decorator
    def get_product_relate_bigactivity(self):
        """商品池获取商品与专题的关联详情"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        prid = request.args.to_dict().get('prid')
        parameter_required('prid')
        logger.debug("get product relate bigactivity PRID is %s", prid)
        prbaids = self.sproduct.get_product_baid_by_prid(prid)
        list_baid = []
        suid = ''
        suname = u'批量导入'
        updatetime = ''
        for prbaid in prbaids:
            record_info = self.sproduct.get_singel_record_by_filter({
                'PRid':
                prid,
                'PORtarget':
                prbaid.BAid
            })
            if record_info:
                suid = record_info.SUid
                suser_info = self.ssuperuser.get_one_super_by_suid(suid)
                suname = suser_info.SUname if suser_info else ''
                updatetime = get_web_time_str(record_info.PORcreatetime)
            dict_baid = {
                'pbid': prbaid.PBid,
                'baid': prbaid.BAid,
                'claimid': suid,
                'clainname': suname,
                'updatetime': updatetime
            }
            list_baid.append(dict_baid)
        response = import_status("messages_get_item_ok", "OK")
        response['data'] = list_baid
        return response

    @verify_token_decorator
    def update_product_relate_bigactivity(self):
        """商品池修改商品与专题的关联"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        data = request.json
        logger.debug("update product relate bigactivity data is %s", data)
        pbid = data.get('pbid')
        baid = data.get('baid')
        prid = data.get('prid')
        option = data.get('option')
        if not re.match(r'^[0-2]$', str(option)):
            raise PARAMS_MISS(u'option 参数异常')
        if baid == '':
            raise PARAMS_MISS(u'baid 参数异常')
        elif baid not in self.empty:
            bigact = self.sbigactivity.get_one_big_act(baid)
            if not bigact:
                raise NOT_FOUND(u'输入的关联专题不存在')
        if prid == '':
            raise PARAMS_MISS(u'prid 参数异常')
        elif prid not in self.empty:
            product = self.sproduct.get_product_by_prid(prid)
            if not product:
                raise NOT_FOUND(u'商品信息不存在')
        if str(option) == '0':  # 0 删除
            parameter_required('pbid')
            # 操作记录
            pbinfo = self.sproduct.get_single_productbigactivity_by_filter(
                {'PBid': pbid})
            if pbinfo:
                self.__make_product_recording(pbinfo.PRid, pbinfo.BAid,
                                              u'解除专题关联')
            del_info = self.sproduct.del_productbigactivity_by_filter(
                {'PBid': pbid})
            if not del_info:
                raise NOT_FOUND(u'错误,未找到要删除的关联专题')
        elif str(option) == '1':  # 1 添加
            parameter_required('prid', 'baid')
            prbaid_list = self.sproduct.get_product_baid_by_prid(prid)
            if prbaid_list:
                logger.debug("exist prbaid count is %s", len(prbaid_list))
                if len(prbaid_list) >= 3:
                    raise SYSTEM_ERROR(u'每个商品最多只能关联三个专题')
                for prbaid in prbaid_list:
                    if baid == prbaid.BAid:
                        raise SYSTEM_ERROR(u'已与此专题进行过关联')
            pbid = str(uuid.uuid1())
            self.sproduct.add_model(
                'ProductBigActivity', **{
                    'PBid': pbid,
                    'PRid': prid,
                    'BAid': baid
                })
            # 操作记录
            self.__make_product_recording(prid, baid, u'添加专题关联')
        elif str(option) == '2':  # 2 修改
            parameter_required('pbid', 'baid')
            pbact = self.sproduct.update_productbigactivity_by_filter(
                {'PBid': pbid}, {'BAid': baid})
            if not pbact:
                raise NOT_FOUND(u'修改失败')
            # 操作记录
            pbinfo = self.sproduct.get_single_productbigactivity_by_filter(
                {'PBid': pbid})
            if pbinfo:
                self.__make_product_recording(pbinfo.PRid, baid, u'修改专题关联')
        response = import_status("update_success", "OK")
        response['data'] = {'pbid': pbid}
        return response

    def get_product_list(self):
        args = request.args.to_dict()
        logger.debug("get product list args is %s", args)
        page = args.get('page_num')  # 页码
        count = args.get('page_size')  # 取出条数
        page = 1 if page in self.empty else int(page)
        count = 15 if count in self.empty else int(count)
        time_start = None
        time_end = None
        kw = args.get('kw')
        if kw not in ['', None]:
            kw = kw.encode('utf8')
        else:
            kw = None
        status = args.get('status')
        status = 1 if status in self.empty else int(status)
        try:
            isdelete = int(args.get('isdelete'))  # 0  or  1
            isdelete = False if isdelete else True
        except Exception as e:
            isdelete = None
        product_list = self.sproduct.get_product_filter(
            kw, time_start, time_end, isdelete, status, page, count)
        for product in product_list:
            self.sproduct.update_view_num(product.PRid)
        data = import_status('get_product_list_success', 'OK')
        data['data'] = product_list
        data["count"] = request.all_count
        data["page_count"] = request.page_count
        return data

    @verify_token_decorator
    def get_product_one(self):
        logger.info(request.detail)
        args = request.args.to_dict()
        prid = args.get('prid')
        if is_tourist():
            usid = None
        else:
            usid = request.user.id
        if not prid:
            raise PARAMS_MISS()
        product = self.sproduct.get_product_by_prid(prid)
        if not product:
            raise NOT_FOUND(u'无此商品')
        # 是管理员或客服则显示全部信息
        if is_admin() or is_customerservice():
            product.fields = product.all
            print '是管理员或客服'
        else:
            # 如果是游客, 或者是未购买开店大礼包的普通用户
            if is_tourist() or is_ordirnaryuser():
                print '是游客或者普通用户'
                product = self.trans_product_for_fans(product)
            else:  # 合伙人(即已购买开店大礼包的用户)
                print '合伙人'
                product = self.trans_product_for_shopkeeper(product)
            product = self.fill_product_nums(product)
        # 填充一些都需要的信息
        self.fill_product_alreadylike(product, usid)
        self.fill_images(product)
        self.fill_prtarget(product)
        self.fill_prbaid(product)
        self.fill_product_sku_key(product)
        self.fill_product_sku_value(product)
        self.sproduct.update_view_num(prid)
        data = import_status('get_product_success', 'OK')
        data['data'] = product
        return data

    @verify_token_decorator
    def get_one_by_productid(self):
        logger.info(request.detail)
        args = request.args.to_dict()
        prid = args.get('productid')
        usid = request.user.id
        if not prid:
            raise PARAMS_MISS()
        product = self.sproduct.get_product_by_productid(prid)
        if not product:
            raise NOT_FOUND(u"无此商品")
        # 是管理员或客服则显示全部信息
        if is_admin() or is_customerservice():
            product.fields = product.all
            print '是管理员或客服'
        else:
            # 如果是游客, 或者是未购买开店大礼包的普通用户
            if is_tourist() or is_ordirnaryuser():
                print '是游客或者普通用户'
                product = self.trans_product_for_fans(product)
            else:  # 合伙人(即已购买开店大礼包的用户)
                print '合伙人'
                product = self.trans_product_for_shopkeeper(product)
            product = self.fill_product_nums(product)
        # 填充一些都需要的信息
        self.fill_product_alreadylike(product, usid)
        self.fill_images(product)
        self.fill_prtarget(product)
        self.fill_product_sku_key(product)
        self.fill_product_sku_value(product)
        self.sproduct.update_view_num(product.PRid)
        data = import_status('get_product_success', 'OK')
        data['data'] = product
        return data

    def __make_product_recording(self, prid, portarget, poraction):
        """创建商品操作记录"""
        self.sproduct.add_model(
            'ProductOperationRecord', **{
                'PORid': str(uuid.uuid1()),
                'PRid': prid,
                'PORcreatetime': get_db_time_str(),
                'SUid': request.user.id,
                'PORtarget': portarget,
                'PORaction': poraction
            })
예제 #6
0
 def __init__(self):
     self.sorder = SOrder()
예제 #7
0
파일: Cuser.py 프로젝트: clove2han/Weidian
 def __init__(self):
     self.suser = SUser()
     self.stask = STask()
     self.smycenter = SMyCenter()
     self.sorder = SOrder()
예제 #8
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