Exemple #1
0
 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, [], {}]
Exemple #2
0
 def __init__(self):
     from WeiDian.service.SShoppingCart import SShoppingCart
     self.sshoppingcart = SShoppingCart()
     from WeiDian.service.SProduct import SProduct
     self.sproduct = SProduct()
     from WeiDian.service.SProductSkuKey import SProductSkuKey
     self.sproductskukey = SProductSkuKey()
     self.sproductskuvalue = SProductSkuValue()
Exemple #3
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()
Exemple #4
0
 def __init__(self):
     from WeiDian.service.SHotMessage import SHotMessage
     self.s_hotmessage = SHotMessage()
     from WeiDian.service.SProduct import SProduct
     self.sproduct = SProduct()
     self.hotmessage_type = ['0', '1', '2', '3', '4']
     self.hotmessage_display_type = ['0', '1']
     self.empty = ['', None, [], {}]
Exemple #5
0
    def get_content_by_seach(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token错误
        
        args = request.args.to_dict()
        logger.debug("get search args is %s", args)
        page = args.get('page')  # 页码
        page = 1 if not page else int(page)
        start = args.get('start')  # 起始位置
        count = args.get('count')  # 取出条数
        count = 5 if not count else int(count)
        start = int((page - 1) * count) if not start else int(start)
        serachact = args.get("serachact")
        tnid = args.get('tnid')
        from WeiDian.service.SProduct import SProduct
        from WeiDian.service.SActivity import SActivity
        from WeiDian.control.CActivity import CActivity
        prname = args.get("PRname")
        prname = prname.encode("utf8") if isinstance(prname, unicode) else prname
        sactivity = SActivity()
        activity_list = []
        if str(serachact) == 'true':
            logger.info("now we'll search act through actext")
            activity_list.extend(sactivity.get_activity_list_by_actext(prname, tnid))
        else:
            logger.info("now we'll search act with product through prname")
            prid_list = SProduct().get_products_by_prname(prname)
            for prid in prid_list:
                activity_list.extend(sactivity.get_activity_by_prid(prid.PRid))
            activity_list = filter(lambda act: act.ACstarttime < get_db_time_str() < act.ACendtime, activity_list)

        if count > 30:
            count = 30
        end = start + count
        len_aclist = len(activity_list)
        if end > len_aclist:
            end = len_aclist
        cactivity = CActivity()
        activity_list = map(cactivity.fill_detail, activity_list)
        for activity in activity_list:
            activity.fill(activity.AClinkvalue, 'aclinkvalue')
            sactivity.update_view_num(activity.ACid)
            activity.ACstarttime = get_web_time_str(activity.ACstarttime)
            activity.ACendtime = get_web_time_str(activity.ACendtime)

        activity_list = activity_list[start:end]
        # map(cactivity.fill_comment_two, activity_list)
        map(cactivity.fill_like_num, activity_list)

        map(cactivity.fill_type, activity_list)
        map(cactivity.fill_product, activity_list)
        data = import_status("get_activity_list_success", "OK")
        data["data"] = activity_list
        data["count"] = len_aclist
        return data
Exemple #6
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'
        ]
Exemple #7
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.STask import STask
     self.stask = STask()
     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()
     from WeiDian.service.SRaward import SRaward
     self.sraward = SRaward()
     from WeiDian.control.Cuser import CUser
     self.cuser = CUser()
     self.add_task_params = ['TAname', "TAtype", "TAhead", "TLid"]
     self.do_task_params = ["TUid"]
     self.add_task_level = [
         "TAlevel", "TArole", "TAcomplateNotifications", "reward"
     ]
Exemple #8
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
Exemple #9
0
 def __init__(self):
     self.sproductlike = SProductLike()
     self.sproduct = SProduct()
Exemple #10
0
class CProductLike():
    def __init__(self):
        self.sproductlike = SProductLike()
        self.sproduct = SProduct()

    @verify_token_decorator
    def add_like(self):
        """添加(删除)喜欢(收藏)"""
        if is_tourist():
            return TOKEN_ERROR()
        json_data = parameter_required('prid')
        prid = json_data.get('prid')
        # 该用户是否已经收藏了此商品
        already_like = self.sproductlike.get_productlike_by_usidprid(
            request.user.id, prid)
        if not already_like:
            pl_dict = dict(plid=str(uuid.uuid4()),
                           usid=request.user.id,
                           prid=prid)
            dict_add_models('ProductLike', pl_dict)
            self.sproduct.update_like_num(prid)
            data = import_status('add_productlike_success', 'OK')
        else:
            # 删除
            self.sproductlike.del_productlike_usidprid(request.user.id, prid)
            self.sproduct.update_like_num(prid, -1)
            data = import_status('cancel_product_like_success', 'OK')
        plid = already_like.PLid if already_like else pl_dict['plid']
        data['data'] = {'plid': plid}
        return data

    @verify_token_decorator
    def get_like_list(self):
        """获取用户的收藏列表"""
        if is_tourist():
            return TOKEN_ERROR(u'未登录')
        args = request.args.to_dict()
        logger.debug("get like list args is %s", args)
        parameter_required("page_size", "page_num")
        page_num = args.get("page_num")
        page_size = args.get("page_size")
        page_num = 1 if not page_num else int(page_num)
        page_size = 5 if not page_size else int(page_size)
        try:
            productlike_list = self.sproductlike.get_productlike_list_by_usid(
                request.user.id, page_num, page_size)
            if not productlike_list:
                raise NOT_FOUND(u'用户无收藏信息')
            logger.info("get product like list success")
            map(self.fill_productinfo, productlike_list)
            # 获取转发数
            from WeiDian.service.SActivity import SActivity
            from WeiDian.service.SActivityFoward import SActivityFoward
            total_forward = 0
            for prlike in productlike_list:
                forward_act = SActivity().get_acid_by_filterid({
                    'AClinkvalue':
                    prlike.PRid,
                    'ACSkipType':
                    2,
                })
                for act in forward_act:
                    forward_num = SActivityFoward().get_fowardnum_by_acid(
                        act.ACid)
                    total_forward = total_forward + forward_num

                prlike.forwardnum = total_forward
                prlike.add("forwardnum")
            prlikecount = self.sproductlike.get_prlike_count_by_usid(
                request.user.id)
            data = import_status("get_product_like_success", "OK")
            data["count"] = prlikecount
            data["data"] = productlike_list
            return data
        except Exception as e:
            logger.exception("get product like error")
            raise SYSTEM_ERROR(u'收藏信息不存在')

    @verify_token_decorator
    def batch_delete_prlike(self):
        if is_tourist():
            return TOKEN_ERROR(u'未登录')
        data = request.json
        plid_list = data.get("plid").split(
            ',') if data and 'plid' in data else None
        logger.info("batch del prlike data is %s", data)
        print plid_list
        try:
            self.sproductlike.batch_delete_prlike(plid_list)
            response = import_status('delete_activity_success', 'OK')
            response['data'] = {"plidlist": plid_list}
            return response
        except:
            logger.exception("batch del prlike error")
            return SYSTEM_ERROR

    def fill_productinfo(self, prlike):
        prid = prlike.PRid
        prlike.productinfo = self.sproduct.get_product_by_prid(prid)
        if not prlike.productinfo:
            raise SYSTEM_ERROR(u'无此收藏商品')
        prlike.productinfo.fields = ['PRmainpic', 'PRsalestatus']
        prlike.add('productinfo')
        return prlike
Exemple #11
0
 def __init__(self):
     self.srecommend = SRecommend()
     self.sproduct = SProduct()
     self.ssuperuser = SSuperUser()
     self.srecommendlike = SRecommendLike()
Exemple #12
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
            })
Exemple #13
0
 def __init__(self):
     self.sactivity = SActivity()
     self.salike = SActivityLike()
     self.sproduct = SProduct()
     self.sproductlike = SProductLike()
Exemple #14
0
class CActivityLike():
    def __init__(self):
        self.sactivity = SActivity()
        self.salike = SActivityLike()
        self.sproduct = SProduct()
        self.sproductlike = SProductLike()

    @verify_token_decorator
    def like_or_cancel(self):
        if is_tourist():
            raise AUTHORITY_ERROR(u"未登录")
        print(request.user.USname.encode('utf8'))
        json_data = request.json
        logger.debug("act like data is %s", json_data)
        parameter_required('acid')
        acid = json_data.get('acid')
        usid = request.user.id
        already_like = self.salike.is_like(usid, acid)
        activity = self.sactivity.get_activity_by_acid(acid)
        if not already_like:
            logger.info("this is not already_like to add activitylike")
            al_dict = {
                'ALid': str(uuid.uuid4()),
                'USid': request.user.id,
                'ACid': acid
            }
            self.salike.add_model('ActivityLike', **al_dict)
            self.salike.add_like_by_acid(acid)
            data = import_status('add_activity_like_success', 'OK')
            # data = import_status('add_productlike_success', 'OK')
            if activity.ACSkipType == 2 and activity.AClinkvalue:
                logger.info("this is add productlike")
                pl_dict = {
                    'PLid': str(uuid.uuid4()),
                    'USid': request.user.id,
                    'PRid': activity.AClinkvalue
                }
                self.sproductlike.add_model('ProductLike', **pl_dict)
                self.sproduct.update_like_num(activity.AClinkvalue)
                data = import_status('add_ac_pr_like_success', 'OK')
        # elif not already_like:
        # al_dict = dict(
        #     alid=str(uuid.uuid4()),
        #     usid=request.user.id,
        #     acid=acid
        # )
        # dict_add_models('ActivityLike', al_dict)
        # self.salike.add_like_by_acid(acid)
        # data = import_status('add_activity_like_success', 'OK')
        # # data = import_status('add_productlike_success', 'OK')

        # elif already_like and not activity.PRid:
        #     self.salike.del_like(request.user.id, acid)
        #     self.salike.cancel_like_by_acid(acid)
        #     data = import_status('cancel_activity_like_success', 'OK')
        else:
            logger.info("this is already like activity to cancel like")
            self.salike.del_like(usid, acid)
            product_like = self.sproductlike.get_product_is_like_by_prid(
                usid, activity.AClinkvalue)
            logger.info("this is already like product to cancel like")
            if product_like:
                self.sproductlike.del_productlike_usidprid(
                    usid, activity.AClinkvalue)
            self.salike.cancel_like_by_acid(acid)
            self.sproduct.update_like_num(activity.AClinkvalue, -1)
            data = import_status('cancel_activity_like_success', 'OK')
        alid = already_like.ALid if already_like else al_dict['ALid']
        data['data'] = {'alid': alid}
        return data
Exemple #15
0
 def __init__(self):
     from WeiDian.service.SRecommendBanner import SRecommendBanner
     self.srecommendbanner = SRecommendBanner()
     from WeiDian.service.SProduct import SProduct
     self.sproduct = SProduct()
Exemple #16
0
class CRecommendBanner():
    def __init__(self):
        from WeiDian.service.SRecommendBanner import SRecommendBanner
        self.srecommendbanner = SRecommendBanner()
        from WeiDian.service.SProduct import SProduct
        self.sproduct = SProduct()

    @verify_token_decorator
    def get_all(self):
        args = request.args.to_dict()
        if not is_partner():
            return AUTHORITY_ERROR
        print '是合伙人'
        lasting = args.get('lasting', 'true')  # 有效时间内的轮播
        if lasting == 'true':
            banner_list = self.srecommendbanner.get_all_lasting_banner()
        else:
            banner_list = self.srecommendbanner.get_all_banner()
        data = import_status("get_recommendbanner_success", "OK")
        data['data'] = banner_list
        return data

    @verify_token_decorator
    def get_one(self):
        args = request.args.to_dict()
        if not is_partner():
            return AUTHORITY_ERROR
        print '是合伙人'
        rbid = args.get('rbid')
        if rbid:
            banner = self.srecommendbanner.get_one_by_rbid(rbid)
            if banner:
                banner = self.fill_product(banner)
                data = import_status("get_recommendbanner_success", "OK")
                data['data'] = banner
                return data
            else:
                return SYSTEM_ERROR

    @verify_token_decorator
    def add_one(self):
        """添加一个轮播图, 需要管理员的登录状态"""
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token错误
        if not is_admin():
            return AUTHORITY_ERROR  # 权限不足
        data = request.json
        now_time = datetime.strftime(datetime.now(), format_for_db)
        rbstarttime = data.get('rbstarttime', now_time)  # 轮播 开始时间
        rbstarttime_str_to_time = datetime.strptime(rbstarttime, format_for_db)
        one_days_later = datetime.strftime(
            rbstarttime_str_to_time + timedelta(days=1), format_for_db)
        rbentime = data.get('rbendtime', one_days_later)  # 轮播结束时间, 默认1天以后
        rbid = str(uuid.uuid1())
        rbimage = data.get('rbimage')
        rbsort = data.get('rbsort')
        prid = data.get('prid')
        if not rbimage or not prid:
            return PARAMS_MISS
        if not self.sproduct.get_product_by_prid(prid):
            return SYSTEM_ERROR("缺少对应的商品id")
        add_model(
            'RecommendBanner', **{
                'RBid': rbid,
                'RBimage': rbimage,
                'RRid': prid,
                'RBstarttime': rbstarttime,
                'RBendtime': rbentime,
                'RBsort': rbsort
            })
        response_make_banner = import_status('add_recommendbanner_success',
                                             'OK')
        response_make_banner['data'] = {'rbid': rbid}
        return response_make_banner

    @verify_token_decorator
    def del_one(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token错误
        if not is_admin():
            return AUTHORITY_ERROR  # 权限不足
        data = request.json
        rbid = data.get('rbid')
        if not rbid:
            return PARAMS_MISS
        if not self.srecommendbanner.del_banner(rbid):
            return SYSTEM_ERROR("轮播图不存在")
        response_make_banner = import_status('del_recommendbanner_success',
                                             'OK')
        response_make_banner['data'] = {'rbid': rbid}
        return response_make_banner

    def fill_product(self, banner):
        prid = banner.PRid
        product = self.sproduct.get_product_by_prid(prid)
        banner.product = product
        banner.add('product')
        return banner