Exemplo n.º 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, [], {}]
Exemplo n.º 2
0
 def __init__(self):
     from WeiDian.service.SActivityComment import SActivityComment
     self.sactivitycomment = SActivityComment()
     from WeiDian.service.SActivity import SActivity
     self.sactivity = SActivity()
     from WeiDian.service.SUser import SUser
     self.suser = SUser()
     from WeiDian.service.SSuperUser import SSuperUser
     self.ssuperuser = SSuperUser()
Exemplo n.º 3
0
 def __init__(self):
     from WeiDian.service.SComplain import SComplain
     self.scomplain = SComplain()
     from WeiDian.service.SActivity import SActivity
     self.sactivity = SActivity()
     from WeiDian.service.SUser import SUser
     self.suser = SUser()
Exemplo n.º 4
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'
        ]
Exemplo n.º 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
Exemplo n.º 6
0
 def __init__(self):
     self.act = SActivity()
     self.session = scoped_session(
         sessionmaker(autocommit=False,
                      autoflush=False,
                      bind=model.mysql_engine))
     self.user_id = self.generic_uuid()
     self.activity_id = self.generic_uuid()
     self.media_id = self.generic_uuid()
     self.comment_id = self.generic_uuid()
     self.tag_id = self.generic_uuid()
     self.banner_id = self.generic_uuid()
     self.product_id = self.generic_uuid()
     self.hotmessege_id = self.generic_uuid()
     self.topnav_id = self.generic_uuid()[:4]
     self.recommendbanner_id = self.generic_uuid()
Exemplo n.º 7
0
    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'收藏信息不存在')
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
class CActivityComment(BaseActivityCommentControl):
    def __init__(self):
        from WeiDian.service.SActivityComment import SActivityComment
        self.sactivitycomment = SActivityComment()
        from WeiDian.service.SActivity import SActivity
        self.sactivity = SActivity()
        from WeiDian.service.SUser import SUser
        self.suser = SUser()
        from WeiDian.service.SSuperUser import SSuperUser
        self.ssuperuser = SSuperUser()

    @verify_token_decorator
    def add_comment(self):
        """添加评论数据"""
        if is_tourist():
            return AUTHORITY_ERROR(u'未登录')
        data = parameter_required(u'ACtext')
        acid = data.get('acid')
        acoid = data.get('acoid')
        usid = request.user.id
        actext = data.get('ACtext')
        # 添加评论
        if acid:
            activity = self.sactivity.get_activity_by_acid(acid)
            if not activity:
                raise NOT_FOUND(u'推文不存在')
            model_data = {
                'ACOid': str(uuid.uuid4()),
                'ACid': acid,
                'USid': usid,
                'ACtext': actext,
                'ACOcreatetime': datetime.strftime(datetime.now(),
                                                   format_for_db)
            }
        # 如果是添加回复
        elif acoid:
            if not is_admin():
                raise TOKEN_ERROR(u'请使用管理员回复')
            comment = self.sactivitycomment.get_comment_by_acoid(acoid)
            if not comment:
                raise NOT_FOUND(u'不存在的评论')
            acid = comment.ACid
            model_data = {
                'ACOid': str(uuid.uuid4()),
                'ACid': acid,
                'ACOparentid': acoid,
                'USid': request.user.id,
                'ACtext': actext,
                'ACOcreatetime': datetime.strftime(datetime.now(),
                                                   format_for_db)
            }
        else:
            raise PARAMS_MISS(u'请指定回复类型')
        self.sactivity.add_model('ActivityComment', **model_data)
        data = import_status('add_activity_comment_success', 'OK')
        data['data'] = {'acoid': model_data['ACOid']}
        return data

    @verify_token_decorator
    def del_comment_admin(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'当前非管理员')
        data = request.json
        acoid = data.get('acoid')
        logger.debug('del comment data is %s', data)
        up_info = self.sactivitycomment.delete_comment_by_acoid(acoid)
        if not up_info:
            raise NOT_FOUND(u'要删除的数据不存在')
        data = import_status("delete_success", "OK")
        data['acoid'] = acoid
        return data

    def get_comment_list(self):
        """获取评论列表"""
        try:
            args = request.args.to_dict()
            acid = args.get('acid')
            if not acid:
                raise PARAMS_MISS(u'必要的参数缺失: acid;')
            reply = True if args.get('reply') else False
            page = int(args.get('page', 1))  # 页码
            # start = int(args.get('start', 0))  # 起始位置
            count = int(args.get('count', 15))  # 取出条数
            # if not start:
            #     start = (page -1) * count
            comment_list = self.sactivitycomment.get_comment_by_activity_id(
                acid, page, count, reply)
            # end = start + count
            # len_comment_list = len(comment_list)
            # if end > len_comment_list:
            #     end = len_comment_list
            # comment_list = comment_list[start: end]
            map(self.fill_user, comment_list)
            map(self.fill_comment_apply_for, comment_list)
            data = import_status('get_acvity_comment_list_success', 'OK')
            data['data'] = comment_list
            return data
        except Exception as e:
            generic_log(e)
            raise e

    def get_comment_with_apply(self):
        """获取推文的评论列表(评论回复嵌套)"""
        try:
            args = request.args.to_dict()
            acid = args.get('acid')
            if not acid:
                raise PARAMS_MISS(u'必要的参数缺失: acid;')
            page = int(args.get('page', 1))  # 页码
            count = int(args.get('count', 15))  # 取出条数
            comment_list = self.sactivitycomment.get_comment_by_activity_id(
                acid, page, count)
            for comment in comment_list:
                self.fill_user(comment)
                comment.ACOcreatetime = get_web_time_str(comment.ACOcreatetime)
                replys = self.sactivitycomment.get_apply_by_acoid(
                    comment.ACOid)
                if replys:
                    for reply in replys:
                        comment.fill(replys, 'reply')
                        reply.hide('USid')
                        # 改: 所有的回复都是管理员回复
                        admin_user = self.ssuperuser.get_one_super_by_suid(
                            reply.USid)
                        if admin_user:
                            user = admin_user
                            admin_user.fill(0, 'robot')
                            user.hide('SUid')
                        else:
                            user = {'name': u'运营人员', 'robot': 1}
                        reply.ACOcreatetime = get_web_time_str(
                            reply.ACOcreatetime)
                        reply.fill(user, 'user')

            data = import_status('get_acvity_comment_list_success', 'OK')
            data['data'] = comment_list
            data["count"] = request.all_count
            data["page_count"] = request.page_count
            return data
        except Exception as e:
            generic_log(e)
            raise e
Exemplo n.º 10
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
            })
Exemplo n.º 11
0
 def __init__(self):
     self.sactivity = SActivity()
     self.salike = SActivityLike()
     self.sproduct = SProduct()
     self.sproductlike = SProductLike()
Exemplo n.º 12
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
Exemplo n.º 13
0
 def __init__(self):
     from WeiDian.service.SAdImage import SAdImage
     self.sadimage = SAdImage()
     from WeiDian.service.SActivity import SActivity
     self.sactivity = SActivity()
     self.add_image_params = ['aiimage', "aitype"]
Exemplo n.º 14
0
class CActivity(BaseActivityControl, BaseTask):
    hmsk_type = ['3', '4']

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

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

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

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

            now_time = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if is_partner():

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

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

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

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

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

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

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

        from WeiDian.config.enums import HMSkipType
        topnav = self.stopnav.get_topnav_by_name(HMSkipType.get(str(hmtype)))
        acfilter = {
            Activity.ACtitle.contains(actitle),
            Activity.ACtext.contains(actitle)
        }
        activity_list = self.sactivity.get_activity_by_filter(
            acfilter, topnav.TNid)
        res = import_status("add_activity_success", "OK")
        res['data'] = activity_list
        return res
Exemplo n.º 15
0
 def __init__(self):
     from WeiDian.service.SBanner import SBnner
     self.sbanner = SBnner()
     from WeiDian.service.SActivity import SActivity
     self.sactivity = SActivity()
Exemplo n.º 16
0
class CBanner():
    def __init__(self):
        from WeiDian.service.SBanner import SBnner
        self.sbanner = SBnner()
        from WeiDian.service.SActivity import SActivity
        self.sactivity = SActivity()

    def get_all(self):
        args = request.args.to_dict()
        lasting = args.get('lasting', 'true')  # 有效时间内的轮播
        if lasting == 'true':
            banner_list = self.sbanner.get_all_lasting_banner()
        else:
            banner_list = self.sbanner.get_all_banner()
        data = import_status("get_banner_success", "OK")
        data['data'] = banner_list
        return data

    def get_one(self):
        args = request.args.to_dict()
        baid = args.get('baid')
        if baid:
            banner = self.sbanner.get_one_by_baid(baid)
            if banner:
                banner = self.fill_activity(banner)
                data = import_status("get_banner_success", "OK")
                data['data'] = banner
                return data
            else:
                pass

    @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)
        bastarttime = data.get('bastarttime', now_time)  # 轮播 开始时间
        bastarttime_str_to_time = datetime.strptime(bastarttime, format_for_db)
        # 7天以后
        seven_days_later = datetime.strftime(bastarttime_str_to_time + timedelta(days=7), format_for_db)
        baentime = data.get('baendtime', seven_days_later)  # 轮播结束时间, 默认7天以后
        baid = str(uuid.uuid1())
        baimage = data.get('baimage')
        basort = data.get('basort')
        acid = data.get('acid')
        if not baimage or not acid:
            return PARAMS_MISS
        # if not self.sactivity.get_activity_by_acid(acid):
        #     return SYSTEM_ERROR
        add_model('Banner', **{
            'BAid': baid,
            'BAimage': baimage,
            'ACid': acid,
            'BAstarttime': bastarttime,
            'BAendtime': baentime,
            'BAsort': basort
        })
        response_make_banner = import_status('add_banner_success', 'OK')
        response_make_banner['data'] = {'baid': baid}
        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
        baid = data.get('baid')
        if not baid:
            return PARAMS_MISS
        res = self.sbanner.del_banner(baid)
        if not res:
            return SYSTEM_ERROR
        response_make_banner = import_status('delete_banner_success', 'OK')
        response_make_banner['data'] = {'baid': baid}
        return response_make_banner


    def fill_activity(self, banner):
        acid = banner.ACid
        activity = self.sactivity.get_activity_by_acid(acid)
        banner.activity = activity
        banner.add('activity')
        return banner