示例#1
0
 def like_or_cancel(self):
     if not is_partner():
         return AUTHORITY_ERROR
     print '是合伙人'
     json_data = parameter_required('reid')
     reid = json_data.get('reid')
     already_like = self.srecommendlike.get_recommend_like_by_usidreid(request.user.id, reid)
     # recommend = self.srecommend.get_recommend_by_reid(reid)
     if not already_like:
         rl_dict = dict(
             rlid=str(uuid.uuid4()),
             usid=request.user.id,
             reid=reid
         )
         dict_add_models('RecommendLike', rl_dict)
         rlid = already_like.RLid if already_like else rl_dict['rlid']
         self.srecommend.add_like_num(reid)  # 数量更改
         data = import_status('add_recommend_like_success', 'OK')
         data['data'] = {'rlid': rlid}
         return data
     else:
         # 删除点赞
         self.srecommendlike.del_like(request.user.id, reid)
         self.srecommend.del_like_num(reid)
         response_make_like = import_status('cancel_recommend_like_success', 'OK')
         response_make_like['data'] = {'reid': reid}
         return response_make_like
示例#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 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"服务器繁忙")
示例#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 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
示例#6
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
示例#7
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
示例#8
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'服务器繁忙')
示例#9
0
 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
示例#10
0
 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
示例#11
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
示例#12
0
 def add_one(self):
     """添加一个轮播图, 需要管理员的登录状态"""
     if not hasattr(request, 'user'):
         return TOKEN_ERROR  # 未登录, 或token错误
     if not is_admin():
         return AUTHORITY_ERROR  # 权限不足
     data = request.json
     now_time = datetime.strftime(datetime.now(), format_for_db)
     rbstarttime = data.get('rbstarttime', now_time)  # 轮播 开始时间
     rbstarttime_str_to_time = datetime.strptime(rbstarttime, format_for_db)
     one_days_later = datetime.strftime(
         rbstarttime_str_to_time + timedelta(days=1), format_for_db)
     rbentime = data.get('rbendtime', one_days_later)  # 轮播结束时间, 默认1天以后
     rbid = str(uuid.uuid1())
     rbimage = data.get('rbimage')
     rbsort = data.get('rbsort')
     prid = data.get('prid')
     if not rbimage or not prid:
         return PARAMS_MISS
     if not self.sproduct.get_product_by_prid(prid):
         return SYSTEM_ERROR("缺少对应的商品id")
     add_model(
         'RecommendBanner', **{
             'RBid': rbid,
             'RBimage': rbimage,
             'RRid': prid,
             'RBstarttime': rbstarttime,
             'RBendtime': rbentime,
             'RBsort': rbsort
         })
     response_make_banner = import_status('add_recommendbanner_success',
                                          'OK')
     response_make_banner['data'] = {'rbid': rbid}
     return response_make_banner
示例#13
0
 def add_one(self):
     """添加一个首页上部导航, 需要管理员的登录状态"""
     if not hasattr(request, 'user'):
         return TOKEN_ERROR  # 未登录, 或token错误
     if not is_admin():
         return AUTHORITY_ERROR  # 权限不足
     data = request.json
     tnid = str(uuid.uuid1())
     tnname = data.get('tnname')
     tsort = data.get('tsort')
     tnurl = data.get('tnurl')
     tntype = data.get('tntype')
     tnparentid = data.get('tnparentid')
     if not tnid or not tnname:
         return PARAMS_MISS
     add_model(
         'TopNav', **{
             'TNid': tnid,
             'TNname': tnname,
             'TSort': tsort,
             'TNurl': tnurl,
             'TNtype': tntype,
             'TNparentid': tnparentid
         })
     response_make_topnav = import_status('add_topnav_success', 'OK')
     response_make_topnav['data'] = {'tnid': tnid}
     return response_make_topnav
示例#14
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
示例#15
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
示例#16
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
示例#17
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
示例#18
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
示例#19
0
    def get_complain_by_usid(self):
        """后台管理查看投诉记录"""
        if not hasattr(request, 'user'):
            raise TOKEN_ERROR()  # 未登录, 或token错误
        args = request.args.to_dict()
        logger.debug("get complain args is %s", args)
        page_size = args.get('page_size')
        page_size = 10 if not page_size else int(page_size)
        page_num = args.get('page_num')
        page_num = 1 if not page_num else int(page_num)
        try:
            complain_list = self.scomplain.admin_get_all_complain(
                page_size, page_num)
            complain_list_length = self.scomplain.admin_get_complain_count()
            from WeiDian.config.enums import complain_type
            data = import_status("get_complain_success", "OK")
            for complain in complain_list:
                colist = str(complain.COtype).split(",")
                logger.debug('get colist %s', colist)
                complaintype = ",".join([complain_type.get(i) for i in colist])
                logger.debug('convert complain type %s', complaintype)
                complain.COtype = complaintype
                user_info = self.suser.get_user_by_user_id(complain.USid)
                complain.fill(user_info.USname, 'usname')
                complain.COcreatetime = get_web_time_str(complain.COcreatetime)

            data['data'] = complain_list
            data['count'] = complain_list_length
            logger.debug("get complain by usid %s", complain_list)
            return data
        except:
            logger.exception("get complain by usid error")
            raise SYSTEM_ERROR(u'获取数据错误')
示例#20
0
    def set_schedual_show(self):
        """设置个人主页升级进度显示(vip数据统计), 素材圈显示, 待评价"""
        if not is_admin():
            raise TOKEN_ERROR(u'请使用管理员登录')
        # data = parameter_required(u'vip_match', u'material', u'wait_apply')
        data = request.json
        paras_list = ['vip_match', 'material', 'wait_apply']
        if not data or not filter(lambda x: x in paras_list, data):
            raise PARAMS_MISS()
        if 'vip_match' in data:  # vip进度, 写在model里
            vip_match_show = False if str(
                data.get('vip_match')) == '1' else True
            updated = self.spartnermatch.update_partner_match(
                1,
                {  # 更改: 这里的level没有用
                    'PSIMisclose': vip_match_show
                })
        if 'material' in data:  # 素材圈是否显示, 写在model里
            material_show = False if str(data.get('material')) == '1' else True
            updated = self.stopnav.update_topnav_by_tnidorname(
                data={'Tisdelete': material_show}, name='素材圈')

        if 'wait_apply' in data:  # 写在配置文件里
            wait_apply_show = data.get('wait_apply')
            wait_apply_show = '0' if str(wait_apply_show) == '0' else '1'
            Partner().set_item('show', 'wait_apply', wait_apply_show)
        msg = 'update_success'
        data = import_status(msg, "OK")
        return data
示例#21
0
 def get_today_total(self):
     """今日"""
     if not is_partner():
         raise TOKEN_ERROR(u'请使用vip登录')
     usid = request.user.id
     # 今日营业额
     today_orders = self.sorder.get_today_order_by_usid_status(
         usid, finished_pay_status)
     sold_mount_list = [x.OImount for x in today_orders] or [0]
     sold_mount = sum(sold_mount_list)
     # 今日赚
     today_earn = sold_mount * Partner().one_level_divide
     today_earn = round(today_earn, 2)
     # 额外赚
     # todo
     other_earn = 0
     # 新衣币
     new_cloth_bit = self.sraward.get_reward_by_usid(usid)
     bit_num_list = [x.RAnumber for x in new_cloth_bit] or [0]
     bit_num_mount = sum(bit_num_list)
     response = import_status('get_today_earn_success', 'OK')
     data = {
         'sold_mount': sold_mount,
         'today_earn': today_earn,
         'other_earn': other_earn,
         'bit_num_mount': bit_num_mount
     }
     response['data'] = data
     return response
示例#22
0
 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
示例#23
0
 def get_all_task_type(self):
     response = import_status("get_task_success", "OK")
     task_type = []
     for tatype in TASK_TYPE:
         task_type.insert(int(tatype), TASK_TYPE.get(tatype))
     response['data'] = task_type
     return response
示例#24
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'用户名或密码错误')
示例#25
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
示例#26
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
示例#27
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
示例#28
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')
示例#29
0
 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
示例#30
0
 def update_shoppingcart(self):
     """购物车添加或者修改"""
     if is_tourist():
         return TOKEN_ERROR  # token无效或者未登录的用户
     data = request.json
     scid = data.get('scid')  # 如果是scid则是修改
     pskid = data.get('pskid')
     scnums = data.get('num')
     update_nums = data.get('update_num')
     if not scnums and not update_nums:
         raise PARAMS_MISS()
     if not pskid:
         raise PARAMS_MISS()
     productsku = self.sproductskukey.get_psk_by_pskid(pskid)
     if not productsku:
         raise NOT_FOUND(u'sku不存在')
     usid = request.user.id
     cart = self.sshoppingcart.get_shoppingcar_by_usidandpskid(usid, pskid)
     # 如果是已经存在的购物车
     if cart:
         scid = cart.SCid
         if update_nums:
             scnums = cart.SCnums + update_nums
         elif scnums:
             scnums = scnums
         if scnums < 1:
             # 删除
             return self.delete_shoppingcart(scid)
         self.sshoppingcart.update_shoppingcart(cart, scnums)
     # 创建
     else:
         if update_nums:
             scnums = update_nums
         elif scnums:
             scnums = scnums
         if scnums < 1:
             return self.delete_shoppingcart(scid)
         psk = self.sproductskukey.get_psk_by_pskid(pskid)
         if not psk:
             raise SYSTEM_ERROR('不存在的商品')
         prid = psk.PRid
         cartdict = {
             'USid': usid,
             'PSKid': pskid,
             'SCnums': scnums,
             'PRid': prid
         }
         if scid:
             self.sshoppingcart.update_shoppingcat_by_scid(scid, cartdict)
         else:
             scid = str(uuid.uuid4())
             cartdict['SCid'] = scid
             dict_add_models('ShoppingCart', cartdict)
     data = import_status('update_cart_success', 'OK')
     data['data'] = {
         'scid': scid
     }
     return data