def set_linkcontent(self): body = request.json admin = Admin.query.filter(Admin.isdelete == false(), Admin.ADid == getattr(request, 'user').id).first() current_app.logger.info('当前管理员是 {}'.format(admin.ADname)) lcid = body.get('lcid') lccontent = body.get('lccontent') with db.auto_commit(): if lcid: lc = LinkContent.query.filter( LinkContent.LCid == lcid, LinkContent.isdelete == False).first() if body.get('delete'): current_app.logger.info('开始删除富文本内容 lcid = {}'.format(lcid)) if not lc: raise ParamsError('该内容已删除') lc.isdelete = True return Success('删除成功', data=lcid) if lc: current_app.logger.info('开始更新富文本内容 lcid = {}'.format(lcid)) if lccontent: lc.LCcontent = lccontent db.session.add(lc) return Success('更新成功', data=lcid) if not lccontent: raise ParamsError('富文本内容不能为空') lc = LinkContent.create({ 'LCid': str(uuid.uuid1()), 'LCcontent': lccontent }) current_app.logger.info('开始创建富文本内容 lcid = {}'.format(lc.LCid)) db.session.add(lc) return Success('添加成功', data=lc.LCid)
def check_lat_and_long(lat, long): try: if not -90 <= float(lat) <= 90: raise ParamsError('纬度错误,范围 -90 ~ 90') if not -180 <= float(long) <= 180: raise ParamsError('经度错误,范围 -180 ~ 180') except (TypeError, ValueError): raise ParamsError('经纬度应为合适范围内的浮点数') return str(lat), str(long)
def set_supplizeraccount(self): if not is_supplizer(): raise AuthorityError data = request.json cardno = data.get('sacardno') cardno = re.sub(r'\s', '', str(cardno)) self.cuser._CUser__check_card_num(cardno) check_res = self.cuser._verify_cardnum(cardno) # 检验卡号 if not check_res.data.get('validated'): raise ParamsError('请输入正确的银行卡号') checked_res = self.cuser._verify_cardnum(data.get('sabankaccount')) # if not checked_res.data.get('validated'): # raise ParamsError('请输入正确的开票账户银行卡号') checked_name = self.cuser._verify_chinese(data.get('sacardname')) if not checked_name or len(checked_name[0]) < 2: raise ParamsError('请输入正确的开户人姓名') current_app.logger.info('用户输入银行名为:{}'.format(data.get('sabankname'))) bankname = check_res.data.get('cnbankname') try: WexinBankCode(bankname) except Exception: raise ParamsError('系统暂不支持该银行提现,请更换银行后重新保存') data['sabankname'] = bankname current_app.logger.info('校验后更改银行名为:{}'.format(data.get('sabankname'))) sa = SupplizerAccount.query.filter( SupplizerAccount.SUid == request.user.id, SupplizerAccount.isdelete == false()).first() if sa: for key in sa.__dict__: if str(key).lower() in data: if re.match(r'^(said|suid)$', str(key).lower()): continue if str(key).lower() == 'sacardno': setattr(sa, key, cardno) continue setattr(sa, key, data.get(str(key).lower())) else: sa_dict = {} for key in SupplizerAccount.__dict__: if str(key).lower() in data: if not data.get(str(key).lower()): continue if str(key).lower() == 'suid': continue if str(key).lower() == 'sacardno': sa_dict.setdefault(key, cardno) continue sa_dict.setdefault(key, data.get(str(key).lower())) sa_dict.setdefault('SAid', str(uuid.uuid1())) sa_dict.setdefault('SUid', request.user.id) sa = SupplizerAccount.create(sa_dict) db.session.add(sa) return Success('设置供应商账户信息成功')
def create_product(self): """创建商品""" if is_admin(): product_from = ProductFrom.platform.value elif is_supplizer(): product_from = ProductFrom.supplizer.value else: raise AuthorityError('当前用户无权进行该操作') data = request.json product_dict = self._validate_ticket_param(data) if Product.query.filter(Product.isdelete == false(), Product.PRname == data.get('prname')).first(): raise ParamsError('该商品名称已存在') with db.auto_commit(): product_dict.update({'PRid': str(uuid.uuid1()), 'CreatorId': getattr(request, 'user').id, 'CreatorType': getattr(request, 'user').model, 'PRname': data.get('prname'), 'PRimg': data.get('primg'), 'PRdetails': data.get('prdetails'), # 'PRstatus': ProductStatus.ready.value if product_dict.get( # 'PRtimeLimeted') else ProductStatus.active.value, 'PRstatus': ProductStatus.pending.value }) product = Product.create(product_dict) db.session.add(product) # 0702 增加审批 # if product.PRtimeLimeted: # 限时商品,添加异步任务 # add_async_task(func=start_product, start_time=product.PRissueStartTime, func_args=(product.PRid,), # conn_id='start_product{}'.format(product.PRid)) # add_async_task(func=end_product, start_time=product.PRissueEndTime, func_args=(product.PRid,), # conn_id='end_product{}'.format(product.PRid)) self.base_approval.create_approval('toshelves', request.user.id, product.PRid, product_from) self.base_admin.create_action(AdminActionS.insert.value, 'Product', product.PRid) return Success('创建成功', data={'prid': product.PRid})
def get_linkcontent(self): data = parameter_required('lcid') lcid = data.get('lcid') lc = LinkContent.query.filter_by(LCid=lcid, isdelete=False).first() if not lc: raise ParamsError('链接失效') return Success(data=lc)
def _pay_to_bankcard(self, cn): """ 付款到银行卡号 :param cn: :return: """ try: enc_bank_no = self._to_encrypt(cn.CNcardNo) enc_true_name = self._to_encrypt(cn.CNcardName) bank_code = WexinBankCode(cn.CNbankName).zh_value except Exception as e: current_app.logger.error('提现到银行卡,参数加密出错:{}'.format(e)) raise ParamsError('服务器繁忙,请稍后再试') try: result = self.wx_pay.pay_individual_to_card( partner_trade_no=self.wx_pay.nonce_str, enc_bank_no=enc_bank_no, enc_true_name=enc_true_name, bank_code=bank_code, amount=int(Decimal(cn.CNcashNum).quantize(Decimal('0.00')) * 100) ) current_app.logger.info('微信提现到银行卡, response: {}'.format(request)) except Exception as e: current_app.logger.error('微信提现返回错误:{}'.format(e)) raise StatusError('微信商户平台: {}'.format(e)) return result
def upload_to_oss(file_data, file_name, msg=''): if current_app.config.get('IMG_TO_OSS'): try: ali_oss.save(data=file_data, filename=file_name) except Exception as e: current_app.logger.error(">>> {} 上传到OSS出错 : {} <<<".format(msg, e)) raise ParamsError('上传失败,请稍后再试')
def _check_roletype(self, amtype): try: amtype_ = int(amtype or 0) amtype_ = RoleType(amtype_).value return amtype_ except: current_app.logger.info('非法类型 {}'.format(amtype)) raise ParamsError('规则不存在')
def __get_approvalcontent(self, pt, startid, avcontentid, **kwargs): start, content = self.__fill_approval(pt, startid, avcontentid, **kwargs) current_app.logger.info('get start {0} content {1}'.format( start, content)) if not (start or content): raise ParamsError('审批流创建失败,发起人或需审批内容已被删除') return start, content
def _trans_time(self, time): if isinstance(time, datetime): return time try: time = datetime.strptime(str(time), '%Y-%m-%d %H:%M:%S') return time except Exception as e: current_app.logger.info('时间格式不正确 time str {} error {}'.format(time, e)) raise ParamsError('时间格式不正确')
def refuse_action(self, approval_model, refuse_abo): if not approval_model: return if approval_model.PTid == 'tocash': self.refuse_cash(approval_model, refuse_abo) elif approval_model.PTid == 'toshelves': self.refuse_shelves(approval_model, refuse_abo) else: return ParamsError('参数异常,请检查审批类型是否被删除。如果新增了审批类型,请联系开发实现后续逻辑')
def __fill_approval(self, pt, start, content, **kwargs): if pt.PTid == 'tocash': return self.__fill_cash(start, content, **kwargs) elif pt.PTid == 'toshelves': return self.__fill_shelves(start, content) elif pt.PTid == 'touplevel': return self.__filluplevel() else: raise ParamsError('参数异常, 请检查审批类型是否被删除。如果新增了审批类型,请联系开发实现后续逻辑')
def validate_suid(self, raw): if is_supplizer(): self.suid.data = request.user.id else: if not raw.data: raise ParamsError('供应商suid不可为空') supplizer = Supplizer.query.filter( Supplizer.SUid == raw.data, Supplizer.isdelete == False).first_('供应商不存在') self.supplizer = supplizer
def _check_time(self, check_time): if not check_time: return if not isinstance(check_time, datetime): try: check_time = datetime.strptime(str(check_time), format_for_web_second) except: return ParamsError('日期格式不对,具体格式为{}'.format(format_for_web_second)) return check_time
def _check_date(self, check_date): if not check_date: return if not isinstance(check_date, date): try: check_date = datetime.strptime(str(check_date), format_forweb_no_HMS).date() except: return ParamsError('日期格式不对,具体格式为{}'.format(format_forweb_no_HMS)) return check_date
def valid_suregisteredtime(self, raw): try: if re.match(r'^\d{4}-\d{1,2}-\d{1,2}$', raw): self.suregisteredtime.date = datetime.datetime.strptime( raw, '%Y-%m-%d') elif re.match(r'^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$', raw): self.suregisteredtime.date = datetime.datetime.strptime( raw, '%Y-%m-%d %H:%M:%S') except Exception: raise ParamsError('注册时间格式错误')
def update_role(self): data = parameter_required('amtype') # amtype = int(data.get('amtype', 0) or 0) with db.auto_commit(): amtype = self._check_roletype(data.get('amtype', 0)) role = Agreement.query.filter_by(AMtype=amtype, isdelete=False).first() if not role: raise ParamsError('规则失效') role.AMcontent = data.get('amcontent') return Success('更新成功')
def get_verifier(self): form = GetVerifier().valid_data() suid = form.suid.data if is_supplizer(): suid = request.user.id if not suid: raise ParamsError('未指定供应商') tv_list = ProductVerifier.query.filter_by( SUid=suid, isdelete=False).order_by(ProductVerifier.createtime.desc()).all() phone_list = [tv.PVphone for tv in tv_list] return Success(data=phone_list)
def product_verified(self): """商品核销""" data = parameter_required('param') param = data.get('param') try: omid, secret_usid = str(param).split('&') if not omid.startswith('omid'): raise ValueError except ValueError: raise ParamsError('该二维码无效') current_app.logger.info('omid: {}, secret_usid: {}'.format(omid, secret_usid)) omid = str(omid).split('=')[-1] secret_usid = str(secret_usid).split('=')[-1] current_app.logger.info('splited, omid: {}, secret_usid: {}'.format(omid, secret_usid)) if not omid or not secret_usid: raise StatusError('该试用码无效') ticket_usid = self.cuser._base_decode(secret_usid) ticket_user = User.query.filter(User.isdelete == false(), User.USid == ticket_usid).first_('无效试用码') om = OrderMain.query.filter(OrderMain.isdelete == false(), OrderMain.OMid == omid).first_('订单状态异常') if om.OMstatus != OrderStatus.has_won.value: current_app.logger.error('om status: {}'.format(om.TSOstatus)) raise StatusError('提示:该二维码已被核销过') pr = Product.query.filter(Product.PRid == om.PRid).first() if pr.PRtimeLimeted and (pr.PRuseStartTime <= datetime.now() <= pr.PRuseEndTime): raise StatusError('当前时间不在该券有效使用时间内') user = User.query.join(ProductVerifier, ProductVerifier.PVphone == User.UStelephone ).join(Product, Product.SUid == ProductVerifier.SUid ).filter(User.isdelete == false(), User.USid == getattr(request, 'user').id, ProductVerifier.SUid == pr.SUid ).first_('请确认您是否拥有该券的核销权限') with db.auto_commit(): # 订单改状态 om.update({'OMstatus': OrderStatus.completed.value}) db.session.add(om) # 核销记录 tvr = ProductVerifiedRecord.create({'PVRid': str(uuid.uuid1()), 'ownerId': ticket_user.USid, 'VerifierId': user.USid, 'OMid': om.OMid, 'param': param}) db.session.add(tvr) return Success('二维码验证成功', data=tvr.PVRid)
def img_check(filepath, msg='图片'): """ 图片校验 :param msg: msg :param filepath: 完整的绝对路径 :return: """ try: filesize = os.path.getsize(filepath) except FileNotFoundError: current_app.logger.error('FileNotFoundError: {}'.format(filepath)) raise StatusError('服务器繁忙, 请稍后再试') current_app.logger.info('size {} MB'.format( round(filesize / 1048576, 2))) if filesize > 1024 * 1024: current_app.logger.info( 'content size out of limit, path :{}'.format(filepath)) # 图片太大 from PIL import Image img = Image.open(filepath) x, y = img.size x_ = 750 y_ = int(y * (x / x_)) if y_ > 1000: y_ = 1000 time_now = datetime.now() year = str(time_now.year) month = str(time_now.month) day = str(time_now.day) tmp_path = os.path.join(current_app.config['BASEDIR'], 'img', 'temp', year, month, day) if not os.path.isdir(tmp_path): os.makedirs(tmp_path) tmp_path = os.path.join(tmp_path, os.path.basename(filepath)) img.resize((x_, y_), Image.LANCZOS).save(tmp_path) filepath = tmp_path current_app.logger.info('compressed size {} MB, path :{}'.format( round(os.path.getsize(filepath) / 1048576, 2), filepath)) try: check_result = mp_miniprogram.img_sec_check(filepath) current_app.logger.info(check_result) except WeixinMPError as e: current_app.logger.info('error is {}'.format(e)) current_app.logger.error('傻逼在发黄色图片 usid = {}'.format( getattr(request, 'user').id)) raise ParamsError('{}可能存在违法违规等不良信息,请检查后重试'.format(msg))
def update_activationtype(self): data = parameter_required('attid') attid = data.pop('attid') with db.auto_commit(): att = ActivationType.query.filter_by(ATTid=attid, isdelete=False).first_('活跃度获取方式未被记录') admin = Admin.query.filter( Admin.ADid == getattr(request, 'user').id, Admin.isdelete == false()).first_('用户信息有误') update_dict = { 'ADid': admin.ADid } for key in att.keys(): lower_key = str(key).lower() value = data.get(lower_key) if value or value == 0: if key != 'ATTname' and not str(value).isdigit(): raise ParamsError('{} 只能是自然数'.format(getattr(ActivationType, key).comment)) update_dict.setdefault(key, value) att.update(update_dict) db.session.add(att) return Success('修改成功', data=attid)
def upload_img(self): if is_anonymous(): current_app.logger.info(">>> Tourist Uploading Files <<<") else: current_app.logger.info(">>> {} Uploading Files <<<".format(request.user.model)) self.check_file_size() file = request.files.get('file') data = parameter_required() if not data: data = request.form current_app.logger.info('form : {}'.format(data)) current_app.logger.info('type is {}'.format(data.get('type'))) folder = self.allowed_folder(data.get('type')) if not file: raise ParamsError(u'上传有误') file_data, video_thum, video_dur, upload_type = self._upload_file(file, folder) # return Success('上传成功', data={'url': file_data, 'video_thum': video_thum, 'video_dur': video_dur, # 'upload_type': upload_type}) return Success('上传成功', data=file_data).get_body(video_thum=video_thum, video_dur=video_dur, upload_type=upload_type)
def agree_shelves(self, approval_model, data): parameter_required({ 'prlineprice': '划线价格', 'prtrueprice': '实际价格' }, datafrom=data) product = Product.query.filter_by_( PRid=approval_model.AVcontent, PRstatus=ProductStatus.pending.value).first_('商品已处理') prlineprice = validate_price(data.get('prlineprice'), can_zero=False) prtrueprice = validate_price( data.get('prtrueprice'), can_zero=True if product.PRtimeLimeted else False) current_app.logger.info(f'划线价, 实际价 = {prlineprice}, {prtrueprice}') from datetime import datetime now = datetime.now() if product.PRtimeLimeted: if product.PRissueStartTime > now: # 同意时未到发放开始时间 product.PRstatus = ProductStatus.ready.value # 状态为 未开始 add_async_task(func=start_product, start_time=product.PRissueStartTime, func_args=(product.PRid, ), conn_id='start_product{}'.format(product.PRid)) add_async_task(func=end_product, start_time=product.PRissueEndTime, func_args=(product.PRid, ), conn_id='end_product{}'.format(product.PRid)) elif product.PRissueStartTime <= now < product.PRissueEndTime: # 已到开始发放时间 未到 结束时间 product.PRstatus = ProductStatus.active.value # 状态为 活动中 add_async_task(func=end_product, start_time=product.PRissueEndTime, func_args=(product.PRid, ), conn_id='end_product{}'.format(product.PRid)) else: raise ParamsError('当前时间已超出商品发放时间范围,请联系供应商重新提交申请') else: product.PRstatus = ProductStatus.active.value product.PRlinePrice = prlineprice product.PRtruePrice = prtrueprice
def batch_upload(self): if is_anonymous(): current_app.logger.info(">>> Tourist Bulk Uploading Files <<<") else: current_app.logger.info(">>> {} Bulk Uploading Files <<<".format(request.user.model)) self.check_file_size() files = request.files.to_dict() current_app.logger.info(">>> Uploading {} Files <<<".format(len(files))) if len(files) > 30: raise ParamsError('最多可同时上传30张图片') data = parameter_required() folder = self.allowed_folder(data.get('type')) file_url_list = [] for file in files.values(): file_data, video_thum, video_dur, upload_type = self._upload_file(file, folder) file_dict = { 'url': file_data, 'video_thum': video_thum, 'video_dur': video_dur, 'upload_type': upload_type } file_url_list.append(file_dict) return Success('上传成功', file_url_list)
def validate_suid(self, raw): if is_supplizer(): self.suid.data = request.user.id else: if not raw.data: raise ParamsError('供应商suid不可为空')
def validate_suemail(self, raw): if raw.data: if not re.match( r'^[A-Za-z\d]+([\-\_\.]+[A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$', raw.data): raise ParamsError('联系邮箱格式错误')
def pay(self): """购买""" data = parameter_required() prid, ompaytype = data.get('prid'), data.get('ompaytype') try: ompaytype = PayType(int(ompaytype)).value except (ValueError, AttributeError, TypeError): raise ParamsError('支付方式错误') # if not is_user(): # raise AuthorityError user = self._current_user('请重新登录') opayno = self._opayno() now = datetime.now() product = Product.query.filter(Product.PRid == prid, Product.PRstatus == ProductStatus.active.value, Product.isdelete == false()).first_('商品已下架') if product.PRtimeLimeted: starttime = self._check_time(product.PRissueStartTime) endtime = self._check_time(product.PRissueEndTime) if starttime and now < starttime: raise StatusError('商品未到发放时间') if endtime and now > endtime: raise StatusError('商品已过发放时间') trade = self._query_traded(prid, user.USid) # 直购不限制 redirect = False omid = str(uuid.uuid1()) with db.auto_commit(): if ompaytype == PayType.cash.value: # 直购 mount_price = Decimal(product.PRtruePrice) if mount_price == Decimal('0'): redirect = True trade = False elif ompaytype == PayType.scorepay.value: # 活跃分 # if not user.USrealname: # 暂时除去实名验证 # raise StatusError('用户未进行信用认证') if not product.PRtimeLimeted: raise StatusError('活跃分支持限时商品') mount_price = 0 redirect = True else: raise StatusError('支付方式错误') if trade: raise StatusError('您已申请成功,请在“我的 - 我的试用”中查看') omdict = { "OMid": omid, "OMno": self._generic_omno(), "OPayno": opayno, "USid": user.USid, "PRid": prid, "OMmount": product.PRlinePrice, "OMtrueMount": mount_price, "OMpayType": ompaytype, "PRcreateId": product.CreatorId, "PRname": product.PRname, "PRimg": product.PRimg, "OPnum": 1, # 目前没有添加数量 } if ompaytype == PayType.cash.value: user_subcommision = UserSubCommission.query.filter(UserSubCommission.USid == user.USid, UserSubCommission.isdelete == 0)\ .first() user_super_level = user_subcommision.USCsuperlevel if user_super_level == 3: pass elif user_super_level == 2: omdict.setdefault('UPperid3', user_subcommision.USCsupper3) elif user_super_level == 1: omdict.setdefault('UPperid2', user_subcommision.USCsupper2) omdict.setdefault('UPperid3', user_subcommision.USCsupper3) else: omdict.setdefault('UPperid', user_subcommision.USCsupper1) omdict.setdefault('UPperid2', user_subcommision.USCsupper2) omdict.setdefault('UPperid3', user_subcommision.USCsupper3) if data.get('shareid'): omdict.setdefault('UPshareid', data.get('shareid')) # 极差分佣暂时不需要 # omdict.setdefault('USCommission1', user.USCommission1) # omdict.setdefault('USCommission2', user.USCommission2) # omdict.setdefault('USCommission3', user.USCommission3) om = OrderMain.create(omdict) # product.PRnum -= 1 # 商品库存修改 # 0618 fix 非商品逻辑,不能改库存数 # 月销量 修改或新增 today = datetime.now() month_sale_instance = ProductMonthSaleValue.query.filter( ProductMonthSaleValue.isdelete == false(), ProductMonthSaleValue.PRid == product.PRid, extract('month', ProductMonthSaleValue.createtime) == today.month, extract('year', ProductMonthSaleValue.createtime) == today.year, ).first() if not month_sale_instance: month_sale_instance = ProductMonthSaleValue.create({'PMSVid': str(uuid.uuid1()), 'PRid': prid, 'PMSVnum': 1, 'PMSVfakenum': 1 }) else: month_sale_instance.update({'PMSVnum': ProductMonthSaleValue.PMSVnum + 1, 'PMSVfakenum': ProductMonthSaleValue.PMSVfakenum + 1}) db.session.add(month_sale_instance) db.session.add(product) db.session.add(om) body = product.PRname[:16] + '...' openid = user.USopenid1 # 直购订单 不付款 5秒后 自动取消 if not product.PRtimeLimeted: # add_async_task(auto_cancle_order, now + timedelta(minutes=1), (omid,), conn_id='autocancle{}'.format(omid)) auto_cancle_order.apply_async(args=(omid,), countdown=5, expires=10, queue='high_priority') pay_args = self._add_pay_detail(opayno=opayno, body=body, mount_price=mount_price, openid=openid, opayType=ompaytype, redirect=redirect) response = { 'pay_type': 'wechat_pay', 'opaytype': ompaytype, # 'tscode': tscode_list, 'args': pay_args, 'redirect': redirect } current_app.logger.info('response = {}'.format(response)) return Success(data=response)
def validate_sustatus(self, raw): from tickets.config.enums import UserStatus try: self.sustatus.data = getattr(UserStatus, raw.data).value except: raise ParamsError('状态参数不正确')
def update(self): """平台分销佣金设置""" # form = CommsionUpdateForm().valid_data() data = parameter_required() levelcommision = data.get('levelcommision') invitenum = data.get('invitenum', 0) groupsale = data.get('groupsale', 0) pesonalsale = data.get('pesonalsale', 0) invitenumscale = data.get('invitenumscale', 0) groupsalescale = data.get('groupsalescale', 0) pesonalsalescale = data.get('pesonalsalescale', 0) reduceratio = data.get('reduceratio') increaseratio = data.get('increaseratio') deviderate = data.get('deviderate') if not levelcommision or len(levelcommision) != 5: raise ParamsError('请设置五级佣金比') for comm in levelcommision: if comm <= 0 or comm > 100: raise ParamsError('佣金比不合适 需小于100, 大于0') # todo 其他参数校验,目前用不到,忽略校验 leveluptwo = data.get('leveluptwo', 10) levelupthree = data.get('levelupthree', 10) leveldowntwo = data.get('leveldowntwo', 10) leveldownone = data.get('leveldownone', 10) leveldownzero = data.get('leveldownzero', 1) leveldowntworep = data.get('leveldowntworep', 10) leveldownonerep = data.get('leveldownonerep', 10) leveldownzerorep = data.get('leveldownzerorep', 2) leveluptworeward = data.get('leveluptworeward', 5) levelupthreereward = data.get('levelupthreereward', 100) checktime = data.get('checktime', 7) with db.auto_commit(): commision = Commision.query.filter( Commision.isdelete == False).first() if not commision: commision = Commision() from tickets import JSONEncoder commission_dict = { 'Levelcommision': json.dumps(levelcommision, cls=JSONEncoder), 'InviteNum': invitenum, 'GroupSale': groupsale, 'PesonalSale': pesonalsale, 'InviteNumScale': invitenumscale, 'GroupSaleScale': groupsalescale, 'PesonalSaleScale': pesonalsalescale, 'ReduceRatio': json.dumps(reduceratio, cls=JSONEncoder), 'IncreaseRatio': json.dumps(increaseratio, cls=JSONEncoder), 'DevideRate': deviderate, 'LevelUpTwo': leveluptwo, 'LevelUpThree': levelupthree, 'LevelDownTwo': leveldowntwo, 'LevelDownOne': leveldownone, 'LevelDownZero': leveldownzero, 'LevelDownTwoRep': leveldowntworep, 'LevelDownOneRep': leveldownonerep, 'LevelDownZeroRep': leveldownzerorep, 'LevelUpTwoReward': leveluptworeward, 'LevelUpThreeReward': levelupthreereward, 'CheckTime': checktime } [ setattr(commision, k, v) for k, v in commission_dict.items() if v is not None and v != '[]' ] # if not commision.InviteNum and not commision.PesonalSale and not commision.GroupSale: # raise ParamsError('升级条件不可全为0') usercommision = levelcommision[:-2] if sum(usercommision) > 100: raise ParamsError('总佣金比大于100') db.session.add(commision) # BASEADMIN().create_action(AdminActionS.update.value, 'Commision', commision.COid) return Success('修改成功')
def validate_sulinkphone(self, raw): if raw.data: if not re.match('^1\d{10}$', raw.data): raise ParamsError('联系人手机号格' '式错误')