Пример #1
0
 def update_address(self):
     if not hasattr(request, 'user'):
         return TOKEN_ERROR(u"未登录, 或token错误")
     args = request.args.to_dict()
     logger.debug("this is address args %s", args)
     data = request.json
     logger.debug("this is address data %s", data)
     uaid = args.get('uaid')
     uadefault = data.get("UAdefault")
     try:
         exist_default = self.suesraddress.get_default_address_by_usid(
             request.user.id)
         parameter_required("uaid", "areaid", "UAname", "UAphone", "UAtext",
                            "UAdefault")
         if uadefault == True and exist_default:
             self.suesraddress.change_default_address_status(
                 exist_default.UAid, {'UAdefault': False})
         update_address = self.suesraddress.update_address(
             uaid, {
                 "areaid": data.get("areaid"),
                 "UAname": data.get("UAname"),
                 "UAphone": data.get("UAphone"),
                 "UAtext": data.get("UAtext"),
                 "UAdefault": uadefault
             })
         logger.info("update address succress ")
         if not update_address:
             raise SYSTEM_ERROR(u'数据更新错误')
         response = import_status("update_useraddress_success", "OK")
         response['data'] = {"uaid": args["uaid"]}
         return response
     except:
         logger.exception("update address error")
         return SYSTEM_ERROR
Пример #2
0
    def add_complain(self):
        if not hasattr(request, 'user'):
            return TOKEN_ERROR  # 未登录, 或token错误
        parameter_required("OIid", "COtype")
        data = request.json
        try:
            complain = self.scomplain.get_complain_by_oiid(data.get("OIid"))
            logger.debug("get complain by oiid %s", complain)
            if complain:
                return import_status("complain_repeat_error", "WD_ERROR",
                                     "error_complain_exit")
            coid = str(uuid.uuid1())
            cotype_list = [str(i) for i in data.get("COtype", [])]

            self.scomplain.add_model(
                "Complain", **{
                    "COid": coid,
                    "COcontent": data.get("COcontent"),
                    "COtype": ",".join(cotype_list),
                    "OIid": data.get("OIid"),
                    "USid": request.user.id,
                    "COtreatstatus": 1,
                })
            response = import_status("complain_success", "OK")
            response['data'] = {"COid": coid}
            return response
        except:
            logger.exception("add complain error")
            return SYSTEM_ERROR
Пример #3
0
 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
Пример #4
0
 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
Пример #5
0
 def add_useraddress(self):
     if not hasattr(request, 'user'):
         return TOKEN_ERROR(u"未登录, 或token错误")
     parameter_required("areaid", "UAname", "UAphone", "UAtext")
     data = request.json
     logger.info("this is useraddress data %s", data)
     try:
         uaid = str(uuid.uuid1())
         logger.debug("get default address by usid")
         exist_default = self.suesraddress.get_default_address_by_usid(
             request.user.id)
         uadefault = True if not exist_default else data.get("UAdefault")
         if str(uadefault) not in ['True', 'False']:
             raise PARAMS_ERROR(u'uadefault参数不合法')
         if uadefault is True and exist_default:
             self.suesraddress.change_default_address_status(
                 exist_default.UAid, {'UAdefault': False})
         self.suesraddress.add_model(
             "UserAddress", **{
                 "UAid": uaid,
                 "USid": request.user.id,
                 "UAname": data.get("UAname"),
                 "UAphone": data.get("UAphone"),
                 "UAtext": data.get("UAtext"),
                 "areaid": data.get("areaid"),
                 "UAdefault": uadefault
             })
         response = import_status("add_address_success", "OK")
         response['data'] = {"UAid": uaid}
         return response
     except:
         logger.exception("add user address error")
         return SYSTEM_ERROR
Пример #6
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
Пример #7
0
 def del_address(self):
     if is_tourist():
         return TOKEN_ERROR(u"未登录, 或token错误")
     data = request.json
     logger.info("this is del address data %s", data)
     parameter_required("UAid")
     try:
         logger.debug("del address")
         del_address = self.suesraddress.delete_address(data.get("UAid"))
         if not del_address:
             return SYSTEM_ERROR
         exist_default = self.suesraddress.get_default_address_by_usid(
             request.user.id)
         if not exist_default:
             no_default_address = self.suesraddress.get_first_no_default_address(
                 request.user.id)
             if no_default_address:
                 self.suesraddress.change_default_address_status(
                     no_default_address.UAid, {'UAdefault': True})
         response = import_status("delete_useraddress_success", "OK")
         response['data'] = {"uaid": data.get("UAid")}
         return response
     except:
         logger.exception("del address error")
         return SYSTEM_ERROR
Пример #8
0
 def login(self):
     """超级用户登录"""
     json_data = request.json
     suname = json_data.get('suname').encode('utf8')
     supassword = json_data.get('supassword')
     logger.debug("super user login data is %s", json_data)
     # if not suname or not supassword:
     #     return PARAMS_MISS
     parameter_required('suname', 'supassword')
     try:
         suuser = self.ssuperuser.verify_super(suname, supassword)
         # if not suuser:
         #     return SYSTEM_ERROR
         if suuser.SUlevel == 0:
             level = 'customerservice'
         if suuser.SUlevel == 1:
             level = 'ordinaryadmin'
         if suuser.SUlevel == 2:
             level = 'superadmin'
         token = usid_to_token(suuser.SUid, 'SuperUser')
         token_data = {
             'token': token,
             'level': level,
             'head': suuser.SUheader
         }
         data = import_status('generic_token_success', 'OK')
         data['data'] = token_data
         return data
     except:
         logger.exception('super user login in error')
         raise SYSTEM_ERROR(u'用户名或密码错误')
Пример #9
0
 def add_bankcard(self):
     if not hasattr(request, 'user'):
         return TOKEN_ERROR(u"未登录, 或token错误")
     data = request.json
     logger.info("this add bankcard info %s", data)
     parameter_required('BCusername', 'BCnumber', 'BCbankname', 'BCaddress')
     banknumber = str(data.get('BCnumber')).strip()
     self._verify_cardnum(banknumber, error='raise')
     usid = request.user.id
     try:
         bankcard = self.sbankcard.update_bankcard_by_usid(
             usid, {'BCisdelete': True})
         logger.debug("bankcard count is %s", bankcard)
         bcid = str(uuid.uuid1())
         self.sbankcard.add_model(
             "BankCard", **{
                 "BCid": bcid,
                 "USid": usid,
                 "BCusername": data.get("BCusername"),
                 "BCnumber": banknumber,
                 "BCbankname": data.get("BCbankname"),
                 "BCaddress": data.get("BCaddress")
             })
         response = import_status("add_bank_card_success", "OK")
         response['data'] = {"BCid": bcid}
         return response
     except:
         logger.exception("add bankcard error")
         return SYSTEM_ERROR
Пример #10
0
 def get_one_or_default_address(self):
     if is_tourist():
         raise TOKEN_ERROR(u'未登录')
     uaid = request.args.to_dict().get('uaid')
     usid = request.user.id
     logger.debug("get uaid is %s", uaid)
     if uaid is not None:
         uafilter = {'UAid': uaid}
     else:
         uafilter = {'USid': usid, 'UAdefault': True, 'UAisdelete': False}
     default_address = self.suesraddress.get_one_or_default_address(
         uafilter)
     if not default_address:
         any_address = self.suesraddress.get_first_no_default_address(usid)
         if not any_address:
             raise NOT_FOUND(u'该用户未设置地址信息')
     address = default_address or any_address
     if address:
         logger.info("get address success, now to fill detail")
     addressinfoes = self.suesraddress.get_addressinfo_by_areaid(
         address.areaid)
     for addressinfo in addressinfoes:
         address.addressinfo = addressinfo
         address.add("addressinfo")
     response = import_status("messages_get_item_ok", "OK")
     response['data'] = address
     return response
Пример #11
0
 def get_grant_record(self):
     """获取运营发放记录"""
     if not is_admin():
         raise AUTHORITY_ERROR(u'非管理员权限')
     args = request.args.to_dict()
     logger.debug('get grant record args : %s', args)
     pagenum, pagesize = self.cuser.get_pagesize_pagenum(args)
     record_list, count = self.sraward.get_grant_record(pagenum, pagesize)
     for record in record_list:
         if record:
             user = self.suser.get_user_by_user_id(record.USid)
             usname = user.USname
             suser = self.ssuperuser.get_one_super_by_suid(record.SUid)
             susername = suser.SUname
             reward_info = self.sraward.get_raward_by_id(record.RAid)
             reward_info = self.fill_reward_detail(reward_info)
             record_str = '运营 {0} 发放给 {1} {2}优惠券 {3}张'.format(susername.encode('utf8'), usname.encode('utf8'), reward_info.rewardstr, record.RAnumber)
             record.fill(reward_info.rewardstr, 'rewardname')
             record.fill(usname, 'usname')
             record.fill(susername, 'susername')
             record.fill(record_str, 'record_str')
             record.RGRcreatetime = get_web_time_str(record.RGRcreatetime)
     response = import_status('messages_get_item_ok', 'OK')
     response['data'] = record_list
     response['count'] = count
     return response
Пример #12
0
    def get_wx_config_accesstoken(self, url):
        import time
        import hashlib

        noncestr = self.__create_nonce_str()
        data = {
            "url": url,
            "jsapi_ticket": mp.jsticket(),
            'timestamp': int(time.time()),
            "noncestr": noncestr
        }
        logger.info("get wx config %s", data)
        try:
            # response_str = "&".join([str(k)+'='+str(v) for k, v in data.items()])
            # response_str = signature_str.format(**data)
            response_str = '&'.join(
                ['%s=%s' % (key.lower(), data[key]) for key in sorted(data)])
            logger.debug("get response: %s", response_str)
            signature = hashlib.sha1(response_str.encode('utf-8')).hexdigest()
            logger.debug('get signature: %s', signature)
            data['sign'] = signature
            data['appid'] = APP_ID
        except:
            logger.exception("Get wx config error")
            return SYSTEM_ERROR
        # response = import_status("SUCCESS_GET_CONFIG", "OK")
        # response['data'] = data
        # return response
        return data
Пример #13
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'服务器繁忙')
Пример #14
0
 def get_accountinfo(self):
     if is_tourist():
         return AUTHORITY_ERROR(u"未登录")
     usid = request.user.id
     user = self.suser.get_user_by_user_id(usid)
     logger.debug("get info success, this user is %s", user.USname)
     default_address = self.suesraddress.get_default_address_by_usid(usid)
     if not default_address:
         first_address = self.suesraddress.get_first_no_default_address(
             usid)
     address = default_address or first_address
     if address:
         logger.info("get user address success")
         location = self.suesraddress.get_addressinfo_by_areaid(
             address.areaid)
         logger.info("get address detail success")
         for area, city, provice in location:
             locationname = getattr(provice, "name", '') + getattr(
                 city, "name", '') + getattr(area, "name", '')
     else:
         locationname = ''
     # print ''.join([x[1] for x in area])
     bankcard = self.sbankcard.get_bankcard_by_usid(usid)
     response = import_status("get_accountinfo_success", "OK")
     response['data'] = {
         "user": user.hide('USid'),
         # "address": '%s%s' %(locationname, address.UAtext),
         "address": '%s%s' % (locationname, getattr(address, "UAtext", '')),
         "bankcard": getattr(bankcard, "BCnumber", '')
     }
     return response
Пример #15
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
Пример #16
0
    def set_commission(self):
        """佣金设置"""
        if not is_admin():
            raise AUTHORITY_ERROR(u'请使用管理员账号重新登录')
        # todo 设置周周奖 (开始时间/结束时间 分周)
        # todo 设置额外活动
        data = request.json
        logger.debug("SET commission data is %s", data)
        # 设置合伙人三级佣金比例
        divide_one = data.get('divide_one')
        if divide_one not in self.empty and divide_one.isdigit():
            divide_one = float(divide_one) / 100
            self.pn.one_level_divide = str(divide_one)
        divide_two = data.get('divide_two')
        if divide_two not in self.empty and divide_two.isdigit():
            divide_two = float(divide_two) / 100
            self.pn.two_level_divide = str(divide_two)
        divide_three = data.get('divide_three')
        if divide_three not in self.empty and divide_three.isdigit():
            divide_three = float(divide_three) / 100
            self.pn.three_level_divide = str(divide_three)
        # 设置专粉单数及佣金限制
        limit_time_one = data.get('time_one')  # [1,5]
        fans_price_one = data.get('fans_price_one')  # 30
        if fans_price_one not in self.empty:
            fans_price_one = float(fans_price_one) / 100
            self.pn.set_item("level_limit_1", "profit", fans_price_one)
        if limit_time_one not in self.empty:
            self.pn.set_item("level_limit_1", "min", limit_time_one[0])
            self.pn.set_item("level_limit_1", "max", limit_time_one[-1])

        limit_time_two = data.get('time_two')  # [6, 20]
        fans_price_two = data.get('fans_price_two')  # 30
        if fans_price_two not in self.empty:
            fans_price_two = float(fans_price_two) / 100
            self.pn.set_item("level_limit_1", "profit", fans_price_two)
        if limit_time_two not in self.empty:
            if limit_time_two[0] - limit_time_one[-1] != 1:
                raise PARAMS_ERROR(u'timeone 参数错误')
            self.pn.set_item("level_limit_2", "min", limit_time_two[0])
            self.pn.set_item("level_limit_2", "max", limit_time_two[-1])

        limit_time_three = data.get('time_three')  # 21
        fans_price_three = data.get('fans_price_three')  # 30
        if fans_price_three not in self.empty:
            fans_price_three = float(fans_price_three) / 100
            self.pn.set_item("level_limit_1", "profit", fans_price_three)
        if limit_time_three not in self.empty:
            if limit_time_three[0] - limit_time_two[-1] != 1:
                raise PARAMS_ERROR(u'timeone 参数错误')
            self.pn.set_item("level_limit_3", "min", limit_time_three)

        response = import_status("set_success", "OK")
        response['data'] = {
            "divide_one": self.pn.one_level_divide,
            "divide_two": self.pn.two_level_divide,
            "divide_three": self.pn.three_level_divide
        }
        return response
Пример #17
0
    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'服务器繁忙')
Пример #18
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
Пример #19
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
Пример #20
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
Пример #21
0
 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
Пример #22
0
 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"服务器繁忙")
Пример #23
0
 def del_task(self):
     if not is_admin():
         raise AUTHORITY_ERROR(u'权限不足')
     data = request.json
     parameter_required("TAid")
     logger.debug('get del task data, %s', data)
     update_result = self.stask.update_task(data.get("TAid"),
                                            {"TAstatus": 4})
     if not update_result:
         raise SYSTEM_ERROR(u'数据库异常')
     return import_status("delete_success", "OK")
Пример #24
0
 def get_province(self):
     try:
         province_list = self.suesraddress.get_province()
         logger.debug("get province")
         # map(lambda x: x.hide('_id'), province_list)
         res = import_status("get_province_list_success", "OK")
         res["data"] = province_list
         return res
     except:
         logger.exception("get province error")
         return SYSTEM_ERROR
Пример #25
0
 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
Пример #26
0
 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
Пример #27
0
 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
Пример #28
0
    def del_task_level(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u'权限不足')
        data = request.json
        parameter_required("tlid")
        logger.debug('get del task level data, %s', data)
        tasklevel = self.stask.get_task_level_by_tlid(data.get("tlid"))
        if not tasklevel:
            return SYSTEM_ERROR(u'该任务等级不存在或已删除')
        self.stask.update_task_by_tlid(tasklevel.TLid, {"TAstatus": 4})
        self.stask.update_task_level(data.get("tlid"), {"TLisdelete": True})

        return import_status("delete_success", "OK")
Пример #29
0
 def get_useraddress(self):
     if not hasattr(request, 'user'):
         return TOKEN_ERROR(u"未登录, 或token错误")
     try:
         adderss_list = self.suesraddress.get_address_list_by_usid(
             request.user.id)
         logger.debug("get address list")
         self.fill_areainfo_by_areaid(adderss_list)
         data = import_status("get_useraddress_success", "OK")
         data['data'] = adderss_list
         return data
     except:
         logger.exception("get useraddress by usid error ")
         return SYSTEM_ERROR
Пример #30
0
    def add_or_update_task_level(self):
        if not is_admin():
            raise AUTHORITY_ERROR(u"权限不足")
        parameter_required(*self.add_task_level)
        data = request.json
        logger.debug('get request data : %s', data)
        reward_list = data.get("reward")
        try:
            tasklevel = self.stask.get_tasklevel_by_level(
                int(data.get("TAlevel")))

            if not tasklevel:
                tlid = str(uuid.uuid1())
                self.stask.add_model(
                    "TaskLevel", **{
                        "TLid":
                        tlid,
                        "TAlevel":
                        data.get("TAlevel"),
                        "TArole":
                        data.get("TArole"),
                        "TAcomplateNotifications":
                        data.get("TAcomplateNotifications"),
                        "TLisdelete":
                        0
                    })

                for reward in reward_list:
                    self.add_task_raward(tlid, reward)

            else:
                update_result = self.stask.update_task_level(
                    tasklevel.TLid, {
                        "TAlevel":
                        data.get("TAlevel", 0),
                        "TArole":
                        data.get("TArole"),
                        "TAcomplateNotifications":
                        data.get("TAcomplateNotifications")
                    })
                if not update_result:
                    return import_status("update_data_error", "WEIDIAN_ERROR",
                                         "error_update_data")
                self.sraward.delte_task_raward_by_tlid(tasklevel.TLid)
                for reward in reward_list:
                    self.add_task_raward(tasklevel.TLid, reward)
            return import_status('add_task_success', 'OK')
        except:
            logger.exception('add or update task level error')
            return SYSTEM_ERROR(u"服务器繁忙")