Пример #1
0
    def update_recommend_by_reid(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'当前非管理员权限')  # 权限不足
        args = request.args.to_dict()
        logger.debug("update args is %s", args)
        data = request.json
        parameter_required(u'reid')
        logger.debug("update data is %s", data)
        reid = args.get('reid')
        recommend = {
            'REstarttime': get_db_time_str(data.get('restarttime')),
            'REendtime': get_db_time_str(data.get('reendtime')),
            'REfakeviewnum': data.get('reviewnum'),
            'RElikefakenum': data.get('relikenum'),
            'SUid': data.get('suid')
            # 'REisdelete': data.get('reisdelete')
        }
        recommend = {k: v for k, v in recommend.items() if v is not None}
        res = self.srecommend.update_recommend_by_reid(reid, recommend)
        if not res:
            raise SYSTEM_ERROR(u"信息修改错误")
        prid_list = data.get('prid_list')
        if prid_list:
            for item in prid_list:
                prid = item.get('prid')
                prisdelete = item.get('prisdelete')
                rpsort = item.get('rpsort')
                refilter = {'REid': reid, 'PRid': prid}
                already_exist_product = self.srecommend.get_exist_reproduct_by_filter(
                    refilter)
                if not already_exist_product:
                    add_model(
                        'RecommendProduct', **{
                            'REid': reid,
                            'PRid': prid,
                            'RPid': str(uuid.uuid4()),
                            'RPsort': rpsort
                        })
                else:
                    if prisdelete is True:
                        self.srecommend.del_reproduct_by_filter(refilter)
                    elif rpsort:
                        repr_changed = self.srecommend.get_exist_reproduct_by_filter(
                            {'RPsort': rpsort})
                        if repr_changed:
                            self.srecommend.update_exist_reproduct_by_filter(
                                {'RPid': repr_changed.RPid},
                                {'RPsort': already_exist_product.RPsort})
                    self.srecommend.update_exist_reproduct_by_filter(
                        refilter, {
                            'REid': reid,
                            'PRid': prid,
                            'RPsort': rpsort
                        })

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

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

        data = import_status("create_reward_success", "OK")
        data['data'] = {'raid': raid}
        return data
Пример #3
0
    def update_hot(self):
        """修改热文"""
        if not is_admin():
            return AUTHORITY_ERROR  # 权限不足
        data = request.json
        if 'hmid' not in data.keys():
            return PARAMS_MISS
        logger.debug("update hotmessage data is %s", data)
        hmid = data.get('hmid')
        # HMSkipType = data.get('hmskiptype')
        # HMdisplaytype = data.get("hmdisplaytype")
        # if str(HMdisplaytype) not in self.hotmessage_display_type:
        #     raise SYSTEM_ERROR(u'HMdisplaytype参数错误')
        hot = {
            "HMid": data.get("hmid"),
            "HMtext": data.get("hmtext"),
            # "HMcontent": data.get("hmcontent"),
            "HMstarttime": get_db_time_str(data.get("hmstarttime")),
            "HMsort": data.get("hmsort"),
            # "HMSkipType": HMSkipType
            # "HMdisplaytype": HMdisplaytype
        }
        hot = {k: v for k, v in hot.items() if v not in self.empty}
        if data.get("hmendtime"):
            hot["HMendtime"] = get_db_time_str(data.get("hmendtime"))
        if data.get('HMisdelete'):
            hot['HMisdelete'] = True

        from WeiDian.models.model import HotMessage
        filter_change = {HotMessage.HMid == hmid}
        hostmessage_change = self.s_hotmessage.get_hotmessage_by_filter(
            filter_change)
        if not hostmessage_change:
            raise SYSTEM_ERROR(u'热文不存在')

        # for key in self.hostmessage_update_key:
        #     if data.get(str(key).lower()):
        #         hot[key] = data.get(str(key))

        if data.get("hmsort"):
            filter_changed = {HotMessage.HMsort == data.get("hmsort")}
            hostmessage_changeed = self.s_hotmessage.get_hotmessage_by_filter(
                filter_changed)
            if hostmessage_changeed:
                self.s_hotmessage.update_hot_by_hmid(
                    hostmessage_changeed.HMid,
                    {"HMsort": hostmessage_change.HMsort})

        update_info = self.s_hotmessage.update_hot_by_hmid(hmid, hot)
        if not update_info:
            return SYSTEM_ERROR(u'热文不存在')
        response_update_hotmessage = import_status('update_hotmessage_success',
                                                   'OK')
        response_update_hotmessage['data'] = {'hmid': hmid}
        return response_update_hotmessage
Пример #4
0
 def add_one(self):
     """添加推荐"""
     # 此处无需添加图片, 关联商品id即可
     if not is_admin():
         return AUTHORITY_ERROR(u'当前非管理员权限')
     data = request.json
     logger.debug("data is %s", data)
     parameter_required('PRid_list')
     now_time = datetime.strftime(datetime.now(), format_for_web_second)
     restarttime = get_db_time_str(data.get('REstarttime',
                                            now_time))  # 上线时间, 默认当前时间
     restarttime_str_to_time = datetime.strptime(restarttime, format_for_db)
     days_later = datetime.strftime(
         restarttime_str_to_time + timedelta(days=7), format_for_web_second)
     reendtime = get_db_time_str(data.get('REendtime',
                                          days_later))  # 推荐下线时间, 默认7天以后
     relikefakenum = data.get('RElikenum', 0)  # 喜欢数
     refakeviewnum = data.get('REviewnum', 0)  # 浏览数
     prid_list = data.get('PRid_list')
     if not prid_list:
         raise PARAMS_MISS(u'缺失PRid_list')
     reid = str(uuid.uuid4())
     try:
         re_info = {
             # 'REid': reid,
             # 'SUid': request.user.id,
             'RElikefakenum': relikefakenum,
             'REfakeviewnum': refakeviewnum,
             'REstarttime': restarttime,
             'REendtime': reendtime,
         }
         update_info = self.srecommend.update_recommend_by_reid
     except Exception as e:
         logger.debug("add Recommend error")
         raise SYSTEM_ERROR(u'添加Recommend错误')
     try:
         for item in prid_list:
             add_model(
                 'RecommendProduct', **{
                     'REid': reid,
                     'PRid': item.get('PRid'),
                     'RPid': str(uuid.uuid4()),
                     'RPsort': item.get('RPsort')
                 })
     except Exception as e:
         logger.debug("add recommondproduct list error")
         raise SYSTEM_ERROR(u'添加每日推荐商品RecommendProduct内容出错')
     response_make_recommend = import_status('add_recommend_success', 'OK')
     response_make_recommend['data'] = {
         'reid': reid,
     }
     return response_make_recommend
Пример #5
0
    def get_all(self):
        """活动所有热文"""
        if is_tourist():
            raise TOKEN_ERROR(u'未登录')
        args = request.args.to_dict()
        logger.debug("get hotmessage args is %s", args)
        lasting = args.get('lasting', 'true')
        htfilter = 1 if is_partner() else 0
        if is_admin():
            htfilter = [0, 1]
        try:
            hot_list = self.s_hotmessage.get_hotmsg_list_by_filter(htfilter)
            if str(lasting) == 'true':
                hot_list = filter(
                    lambda hot: hot.HMstarttime < get_db_time_str() < hot.
                    HMendtime, hot_list)
            for hotmsg in hot_list:
                hotmsg.HMstarttime = get_web_time_str(hotmsg.HMstarttime)
                hotmsg.HMendtime = get_web_time_str(hotmsg.HMendtime)

            data = import_status("get_hotmessage_list_success", "OK")
            data['data'] = hot_list
            return data
        except:
            logger.exception("get hotmessage error")
            raise SYSTEM_ERROR(u'服务器繁忙')
Пример #6
0
    def upload_task_img(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u"权限不足")
        formdata = request.form
        logger.info("formdata is %s", formdata)
        files = request.files.get("file")

        if platform.system() == "Windows":
            rootdir = "D:/task"
        else:
            rootdir = "/opt/WeiDian/imgs/task/"
        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.id + get_db_time_str() + "." + filessuffix
        filepath = os.path.join(rootdir, filename)
        print(filepath)
        files.save(filepath)
        response = import_status("save_photo_success", "OK")
        # url = Inforcode.ip + Inforcode.LinuxImgs + "/" + filename
        url = QRCODEHOSTNAME + "/imgs/task/" + filename
        # print(url)
        logger.info("this url is %s", url)
        response["data"] = url
        return response
Пример #7
0
 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
Пример #8
0
 def upload_file(self, rootdir, notimetag, filepath=None):
     logger.debug('get filetype %s', rootdir)
     from WeiDian.common.timeformat import get_db_time_str
     from WeiDian.config.setting import QRCODEHOSTNAME, LinuxRoot, LinuxImgs, LinuxStaticImgs
     files = request.files.get("file")
     if filepath:
         filepath = os.path.join(LinuxStaticImgs, filepath)
         url = QRCODEHOSTNAME + "/imgs/icon/" + filepath
     else:
         filename = files.filename
         if not isinstance(filename, basestring):
             filename = str(filename)
         filessuffix = filename.split(".")[-1]
         filedir = os.path.join(LinuxRoot, LinuxImgs, rootdir)
         logger.debug('get filedir is %s', filedir)
         if not os.path.isdir(filedir):
             os.mkdir(filedir)
         if not is_admin():
             filename_title = request.user.openid
         else:
             filename_title = request.user.id
         if str(notimetag) == 'true':
             filename = rootdir + filename_title + "." + filessuffix
         else:
             filename = rootdir + filename_title + get_db_time_str(
             ) + "." + filessuffix
         filepath = os.path.join(filedir, filename)
         url = QRCODEHOSTNAME + "/imgs/{0}/".format(rootdir) + filename
     print(filepath)
     files.save(filepath)
     return url
Пример #9
0
 def fill_reward_detail(self, raward, price=None):
     reward_number = '{0}张'
     reward_number_ratio = '前{0}单'
     filter_str = '满{0}-{1}新衣币'
     ratio_str = '佣金上涨{0}%'
     amout_str = '{0}元无门槛新衣币'
     price_use = False
     if raward not in ['', None, [], {}]:
         if re.match(r'^[0-2]$', str(raward.RAtype)):
             if raward.RAtype == 0:
                 reward_str = filter_str.format(int(raward.RAfilter), int(raward.RAamount))
             elif raward.RAtype == 1:
                 reward_str = ratio_str.format(int(raward.RAratio))
             else:
                 reward_str = amout_str.format(int(raward.RAamount))
         zh_ratype = REWARD_TYPE.get(str(raward.RAtype))
         raward.fill(zh_ratype, 'zh_ratype')
         raward.fill(reward_str, 'rewardstr')
         time_valid = raward.RAcreatetime < get_db_time_str() < raward.RAendtime and not raward.RAisdelete
         if price:
             if raward.RAtype == 0:
                 price_use = price > raward.RAfilter
             elif raward.RAtype == 2:
                 price_use = True
             valid = time_valid and price_use
         else:
             valid = time_valid
         raward.fill(valid, 'valid')
         raward.RAendtime = get_web_time_str(raward.RAendtime)
         raward.RAcreatetime = get_web_time_str(raward.RAcreatetime)
     return raward
Пример #10
0
 def add_one(self):
     """添加活动热文, 需要管理员登录"""
     if not is_admin():
         return AUTHORITY_ERROR  # 权限不足
     data = request.json
     logger.debug("add hotmessage data is ", data)
     parameter_required('HMtext', 'HMsort', 'HMSkipType')
     now_time = datetime.strftime(datetime.now(), format_for_db)
     HMstarttime = get_db_time_str(data.get('HMstarttime',
                                            now_time))  # 热文开始时间
     hmstarttime_str_to_time = datetime.strptime(HMstarttime, format_for_db)
     # 7天以后
     seven_days_later = datetime.strftime(
         hmstarttime_str_to_time + timedelta(days=7), format_for_db)
     HMendtime = get_db_time_str(data.get(
         'HMendtime', seven_days_later))  # 热文结束时间, 默认7天以后
     # if not self.sproduct.get_product_by_prid(prid):
     #     return SYSTEM_ERROR
     HMSkipType = data.get('HMSkipType')
     if str(HMSkipType) not in self.hotmessage_type:
         raise SYSTEM_ERROR(u'HMSkipType参数错误')
     HMdisplaytype = data.get("HMdisplaytype")
     if str(HMdisplaytype) not in self.hotmessage_display_type:
         raise SYSTEM_ERROR(u'HMdisplaytype参数错误')
     try:
         HMid = str(uuid.uuid1())
         self.s_hotmessage.add_model(
             'HotMessage', **{
                 'HMid': HMid,
                 'HMtext': data.get('HMtext'),
                 'HMstarttime': HMstarttime,
                 'HMendtime': HMendtime,
                 'HMsort': data.get('HMsort'),
                 'HMSkipType': HMSkipType,
                 "HMcontent": data.get("HMcontent"),
                 "HMdisplaytype": HMdisplaytype
             })
         response_make_hotmesasge = import_status('add_hotmessage_success',
                                                  'OK')
         response_make_hotmesasge['data'] = {'HMid': HMid}
         return response_make_hotmesasge
     except:
         logger.exception("create hotmessage error")
         return SYSTEM_ERROR(u'服务器繁忙')
Пример #11
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
Пример #12
0
 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
         })
Пример #13
0
 def get_commsion_list(self):
     """后台获取佣金统计表格"""
     if not is_admin():
         raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
     args = request.args.to_dict()
     logger.debug("Get commsion list args is %s", args)
     kw = args.get('kw')
     kw = kw.encode('utf8') if kw not in self.empty else None
     time_start = args.get('time_start')
     time_start = get_db_time_str(time_start) if time_start not in self.empty else None
     time_end = args.get('time_end')
     time_end = get_db_time_str(time_end) if time_end not in self.empty else None
     pagenum, pagesize = self.cuser.get_pagesize_pagenum(args)
     user_list, count = self.suser.get_all_partner_by_filter(pagenum, pagesize, kw)
     commision_list = []
     try:
         for user in user_list:
             usid = user.USid
             data = {
                 'usname': user.USname,
                 'usphone': user.USphone,
                 'total': self._total_commision(usid),                                     # 总额
                 'sold_income': self._user_commision(usid, 0, time_start, time_end),       # !销售佣金
                 'invite_open': self._user_commision(usid, 10, time_start, time_end),      # !邀请开店佣金
                 'fans_outincome': self._user_commision(usid, 20, time_start, time_end),   # !专粉佣金
                 'group_income': self._team_commision(usid),                               # 团队佣金
                 'remain': self._remain_commision(usid),                                   # 余额
                 'reward_income': self._user_commision(usid, 40, time_start, time_end),    # 周周奖佣金
                 'novice_reward': self._user_commision(usid, 45, time_start, time_end),    # !新手任务佣金
                 'priview': self._privew_commision(usid),                                  # 预估到帐
                 'extracting': self._extract_commision(usid)                               # 正在提现的佣金
             }
             commision_list.append(data)
     except Exception as e:
         generic_log(e)
         raise e
     response = import_status('get_success', 'OK')
     response['data'] = commision_list
     response['count'] = count
     return response
Пример #14
0
    def add_task(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u"权限不足")
        data = request.json
        logger.info("add task body %s", data)
        parameter_required(*self.add_task_params)
        task = {k: data.get(k) for k in self.add_task_params}

        logger.debug('get tatype is %s and type of tatype is %s',
                     task.get("TAtype"), type(task.get("TAtype")))
        tatype = int(task.get("TAtype"))
        if tatype == 0 and "TAurl" not in data:
            raise PARAMS_ERROR(u"参数TAurl缺失")
        task['TAstartTime'] = get_db_time_str(data.get("TAstartTime"))
        if data.get("TAendTime"):
            task['TAendTime'] = get_db_time_str(data.get("TAendTime"))
        if data.get("TAduration"):
            task['TAduration'] = data.get("TAduration")
        task['TAstatus'] = data.get("TAstatus", 0)
        task['TAmessage'] = data.get("TAmessage")
        task['TAurl'] = data.get("TAurl", 1)
        task['TAtype'] = tatype
        logger.debug('add task : task is %s', task)
        try:
            if data.get("TAid"):
                update_result = self.stask.update_task(data.get("TAid"), task)
                if not update_result:
                    raise SYSTEM_ERROR(u"数据库异常")
                task["TAid"] = data.get("TAid")
            else:
                task['TAid'] = str(uuid.uuid1())
                self.stask.add_model("Task", **task)
            # self.add_or_update_task_raward(task['TAid'], task['RAid'], task.get("RAnumber", 1))
        except:
            logger.exception("add task error")
            return SYSTEM_ERROR(u'服务器繁忙')
        return import_status("add_task_success", "OK")
Пример #15
0
    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')
Пример #16
0
    def add_image(self):
        if not is_admin():
            return AUTHORITY_ERROR(u"权限不足")
        # parameter_required(*self.add_image_params)
        data = request.json
        adimage_list_web = data.get("adimage", [])
        if not adimage_list_web:
            raise PARAMS_MISS('adimage')
        for adimage_web in adimage_list_web:
            aitype = int(adimage_web.get("aitype"))
            if not adimage_web.get("aiimage") or not (0 <= aitype < 15):
                continue
            adimage = {
                'AIimage': adimage_web.get("aiimage"),
                'AItype': adimage_web.get("aitype"),
                'AIsize': adimage_web.get("aisize"),
                'ACid': adimage_web.get("acid"),
            }

            adimage_list = self.sadimage.get_image_by_aitype(aitype)
            if aitype != 10:
                if adimage_list:
                    update_result = self.sadimage.update_image(
                        adimage_list[0].AIid, adimage)
                    if not update_result:
                        raise SYSTEM_ERROR(u"数据更新异常")
                else:
                    adimage['AIid'] = str(uuid.uuid1())
                    self.sadimage.add_model("AdImage", **adimage)

            else:
                if len(adimage_list) == 3:
                    adimage['AIcreatetime'] = get_db_time_str()
                    update_result = self.sadimage.update_image(
                        adimage_list[1].AIid, adimage)
                    if not update_result:
                        raise SYSTEM_ERROR(u"数据更新异常")
                else:
                    adimage['AIid'] = str(uuid.uuid1())
                    self.sadimage.add_model("AdImage", **adimage)

        return import_status('save_photo_success', 'OK')
Пример #17
0
    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')
Пример #18
0
 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')
Пример #19
0
 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
Пример #20
0
    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
Пример #21
0
    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
Пример #22
0
 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