def ap_client(func, *args, **kw): try: return apcli(func, *args, **kw) except ApolloException as e: raise ThirdError(e.respmsg) except: log.warn(traceback.format_exc()) raise ThirdError('第三方服务错误')
def finance_client(func, *args, **kw): try: client = ThriftClient(config.FINANCE_SERVER, Finance) return client.call(func, *args, **kw) except ServerException as e: raise ThirdError(e.error_msg) except: log.warn(traceback.format_exc()) raise ThirdError('第三方服务错误')
def account2_client(func, *args, **kw): try: return thrift_callex(config.ACCOUNT2_SERVER, Account2, func, *args, **kw) except ServerError as e: raise ThirdError(e.msg) except: log.warn(traceback.format_exc()) raise ThirdError('第三方服务错误')
def org_client(func, *args, **kw): try: client = ThriftClient(config.ORG_API_SERVER, OrgServer, framed=True) return client.call(func, *args, **kw) except QudaoException as e: raise ThirdError(e.respmsg) except: log.warn(traceback.format_exc()) raise ThirdError('第三方服务错误')
def qt2_requests( url, data, method='get', appcode=config.WXY_QT2_CONF['appcode'], appkey=config.WXY_QT2_CONF['appkey'] ): '''qiantai2访问''' headers = { 'X-QF-APPCODE': appcode, 'X-QF-SIGN': make_sign(data, appkey) } try: client = HttpClient(config.QT2_SERVER) func = getattr(client, method) ret = func(url, data, headers=headers) data = json.loads(ret) except: log.warn(traceback.format_exc()) raise ThirdError('服务内部错误') respcd = data.pop('respcd', None) if respcd == '0000': return data else: raise MchntException(data['respmsg'], data['resperr'], respcd)
def get_userinfo(userid): '''获取店铺信息 通过apollo.findUserBriefsByIds获取商户的信息 Params: userids: 商户userid, 若userid为list或者tuple返回字典 否则, 返回直接返回商户信息 Raises: 仅当apollo报错时会抛出错误 ''' if isinstance(userid, (list, tuple)): mode = 'mul' userids = [int(i) for i in userid] else: mode = 'one' userids = [int(userid)] try: userinfos = apcli('findUserBriefsByIds', userids) or [] except: raise ThirdError('获取商户信息失败') userinfos = {i.uid: i.__dict__ for i in userinfos} return userinfos.get(int(userid)) if mode == 'one' else userinfos
def openid2userid(openid): if not openid: raise ParamError('未获取到openid') try: r = RequestsClient().get(config.OPENAPI_URL + '/push/v2/bind_query', {'openid': openid}) r = json.loads(r) except: log.warn('bind wx openid error: %s' % traceback.format_exc()) raise ThirdError('第三方服务失败') if r['respcd'] != '0000': raise ThirdError(u'第三方服务返回:%s' % (r['respmsg'] or r['resperr'])) return 0 if r['data']['userid'] == -1 else r['data']['userid']
def _create_coupon(self, data): c = {} c['status'] = 2 c['src'] = ACTIVITY_SRC c['mchnt_id'] = data['userid'] c['title'] = data['title'] c['amt_max'], c['amt_min'] = data['amt_max'], data['amt_min'] c['start_time'], c['expire_time'] = data['start_time'], data[ 'expire_time'] c['use_rule'] = json.dumps([['amt', '>=', data['use_limit_amt']]]) c['profile'] = CouponRuleProfile( **{ 'mchnt_limit': 2, 'effect_type': 2, 'effect_offset': data['coupon_offset'], 'effect_len': data['coupon_lifetime'] }) try: coupon = CouponRule(**c) cid = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'coupon_rule_create', coupon) except: log.warn('create coupon error: %s' % traceback.format_exc()) raise ThirdError('调用创建红包接口失败') return cid
def POST(self): actv = None with get_connection('qf_marketing') as db: actv = db.select_one(table='activity', where={ 'id': self.validator.data['id'], 'src': ACTIVITY_SRC }, fields='id, create_mchnt_id, status') if not actv: raise ParamError('活动不存在') if actv['create_mchnt_id'] != str(self.user.userid): if actv['create_mchnt_id'] == str(self.get_big_uid()): raise ParamError('此活动为总账户创建,你无法执行修改~') raise ParamError('暂无修改此活动的权限') if actv['status'] != COUPON_RULE_STATUS_CLOSE: try: act = Activity(id=actv['id'], status=COUPON_RULE_STATUS_CLOSE, src=ACTIVITY_SRC) thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'activity_change', act) except: log.warn(traceback.format_exc()) raise ThirdError('关闭活动失败') return self.write(success({}))
def get_members(self): members = self.get_members_ext(self.validator.data['filter_key']) if not members: return [] cids = [i['customer_id'] for i in members] profiles, tags = {}, {} if cids: spec = json.dumps({'user_id': cids}) try: profiles = thrift_callex(config.OPENUSER_SERVER, QFCustomer, 'get_profiles', config.OPENUSER_APPID, spec) profiles = {i.user_id:i.__dict__ for i in profiles} except: log.warn('get openuser_info error:%s' % traceback.format_exc()) raise ThirdError('获取消费者信息失败') tags = self.get_tags(cids) tags_dict = {flag.keys()[0]:flag.values()[0] for flag in config.MEMBER_FLAGS} for m in members: customer_id = m['customer_id'] info = profiles.get(customer_id,{}) m['avatar'] = info.get('avatar') or config.HJ_AVATAR m['gender'] = info.get('gender', 1) m['nickname'] = info.get('nickname') or customer_id m['last_txdtm'] = tstamp_to_str(m['last_txdtm']) m['tag'] = tags[customer_id] mem_tags = tags[customer_id] m['tag'] = [tag for tag in mem_tags if tag in tags_dict] m['is_auth'] = 1 if 'submit' in tags[customer_id] else 0 m['customer_id'] = hids.encode(customer_id) return members
def POST(self): actv = None with get_connection('qf_marketing') as db: actv = db.select_one( table= 'activity', where= { 'id': self.validator.data['coupon_id'], }, fields= 'id, create_mchnt_id, status, create_time') if not actv: raise ParamError('活动不存在') if actv['create_mchnt_id'] != str(self.user.userid): if actv['create_mchnt_id'] == str(self.get_big_uid()): raise ParamError('此活动为总账户创建,你无法执行修改~') raise ParamError('暂无修改此活动的权限') # 已经进行的活动不能删除 now = datetime.datetime.now() notify_datetime = get_notify_datetime(actv['create_time']) if not now < notify_datetime: raise ParamError('不能删除已经进行的红包推广活动!') if actv['status'] != 3: try: act = Activity(id=actv['id'], status=3, src='qpos') thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'activity_change', act) except: log.warn(traceback.format_exc()) raise ThirdError('关闭活动失败') return self.write(success({}))
def POST(self): params = self.req.input() userid = int(self.user.userid) new_username = params.get('new_username', '').strip() if not new_username: raise ParamError('新账号不能为空') # 验证grant_code grant_code = params.get('grant_code') or '' self.check_grant_code(userid, grant_code) # 验证verify_code verify_code = params.get('verify_code') or '' if not check_smscode(verify_code, new_username, mode=1): raise ParamError('验证信息错误') # 验证新账号是否被占用 with get_connection_exception('qf_core') as db: new_user = db.select_one('auth_user', where={'username': new_username}) if new_user: raise ParamError('新账号已经被占用') # apollo接口修改username try: apcli_ex('changeUsername', userid, new_username) except ApolloException as e: raise ThirdError(e.respmsg) # 将现有设备踢下线 kick_user(userid, mode='all') return success({})
def get_customer(actid, **cf): '''获取消费者信息''' customer_num, info = 0, [] try: # 查询消费者 where = {'activity_id':actid, 'status':COUPON_STATUS_USE} limit, offset = cf.get('limit', 5) , cf.get('offset', 0) with get_connection_exception('qf_marketing') as db: cps = db.select('coupon_bind', fields = 'distinct customer_id', where= where, other = 'order by create_time desc limit %s, %s' % (offset, limit)) cids, info = [i['customer_id'] for i in cps], [] # 查询总共有多少消费者 customer_num = db.select_one('coupon_bind', where = where, fields = 'count(distinct customer_id) as num')['num'] # 查询消费者信息 if cids: spec = json.dumps({"user_id":cids}) r = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_profiles', config.OPENUSER_APPID, spec) r = {str(i.user_id):i for i in r} # 处理返回值 for i in cids: if i in r: info.append({'id':i, 'avatar':r[i].avatar or config.HJ_AVATAR, 'nickname':r[i].nickname}) else: info.append({'id':i, 'avatar':config.HJ_AVATAR, 'nickname':i}) except: log.warn('get openuser_info error:%s' % traceback.format_exc()) if cf.get('raise_ex', ''): raise ThirdError('获取消费者信息失败') return customer_num, info
def get_user_bank_info(userid): try: bank_info = apcli('userprofile_by_id', userid)['bankInfo'] or {} except: raise ThirdError('获取商户详细信息失败') return bank_info
def get_user_detail_info(userid): try: detail_info = apcli('findUserByid', userid) or {} except: raise ThirdError('获取商户详细信息失败') detail_info = detail_info.__dict__ return detail_info
def get_linkids(userid): ''' 获取子商户 ''' try: relates = apcli('getUserRelation', int(userid), 'merchant') linkids = [i.userid for i in relates] except: raise ThirdError('获取子商户列表失败') return linkids
def POST(self): try: # 转换输入 d = self._trans_input() # 当商户已经注册时,提示错误 userid, respmsg = apocli.signup(self._get_UserProfile(d), allow_exist=False) if not userid: raise ThirdError(respmsg) return self.write(success({})) except MchntException, e: log.warn('ToBigMchnt error: %s' % e) return self.write(error(e.errcode, respmsg=e.errmsg))
def _query_qt2(): '''从qt2查询订单信息''' p = {'syssn': d['out_sn']} headers = { 'X-QF-APPCODE': config.QT2_APP_CODE, 'X-QF-SIGN': RechargeUtil.make_sign(p) } try: client = HttpClient(config.QT2_SERVER) r = json.loads( client.get('/trade/v1/query', params=p, headers=headers)) if r['respcd'] == '0000' and r['data']: return r['data'][0] except: log.warn('qt2 query error:%s' % traceback.format_exc()) raise ThirdError('获取订单信息失败')
def POST(self): params = self.req.input() code_info = self.get_code_info(params.get('code')) req_args = json.dumps({ 'verify_id': code_info['id'], 'userid': int(self.user.userid) }) try: thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'verify_actv_verify', req_args) except: log.warn(traceback.format_exc()) raise ThirdError('核销失败') return success({})
def POST(self): # 验证并获取用户和业务员信息 self.check_entry() # apollo signup userprofile = self.get_UserProfile() userid, respmsg = apcli.signup(userprofile, self._data['saleman_uid']) # 如果调apollo失败 if respmsg: raise ThirdError(respmsg) # 如果注册成功 elif userid: # 如果是大商户 # 需要自动绑定子商户 if self._mode == 'bigmchnt': apcli_ex('setUserRelation', int(self._big_uid), [UserRelation(int(userid), 'merchant')]) # 添加补充信息 self.add_user_ext(userid) # 自动过审 self.auto_apply(userid) # 绑定渠道商户关系 self.relate_mchnt(userid) # 添加注册标志 self.add_sign_tag(self._data['groupid'], userid) # 分发注册成功信息 publish( config.SIGNUP_MSGPASS_KEY, json.dumps({'userid': userid}), ) return success(self.adjust_ret(userid)) else: raise ParamError('用户注册失败')
def _create_activity(self, cid, data): try: a = {} a['status'] = 2 a['src'] = ACTIVITY_SRC a['type'] = ACTIVITY_TYPE_PAYMENT a['mchnt_id'] = data['userid'] a['total_amt'] = data['total_amt'] a['xx_type'] = ACTIVITY_SHARE_TYPE_COUPON obtain_rule, share_rule = [], [] # 消费返劵 if data['type'] == 20: a['sponsor_xx_id'] = cid a['sponsor_award_num'] = 1 obtain_rule = [["amt", ">=", data['obtain_limit_amt']], ["num_type", "=", 1], ["obtain_num", "<=", 1]] # 消费分享劵 else: a['obtain_xx_id'] = a['sponsor_xx_id'] = cid a['sponsor_award_num'] = 1 a['obtain_num'] = config.OBTAIN_NUM a['ext'] = self._get_act_ext(data) obtain_rule = [["amt", ">=", data['obtain_limit_amt']]] share_rule = [ ["amt", ">=", data['obtain_limit_amt']], ] a['title'] = data['title'] a['start_time'], a['expire_time'] = data['start_time'], data[ 'expire_time'] a['rule'] = json.dumps({ "obtain_rule": obtain_rule, 'share': share_rule }) r = thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'activity_create', Activity(**a)) return r except: log.warn('create activity error: %s' % traceback.format_exc()) raise ThirdError('调用活动接口失败')
def POST(self): userprofile = self.get_userprofile() # 当商户已经注册时,提示错误 userid, respmsg = apcli.signup(userprofile, allow_exist=False) # 如果调apollo失败 if respmsg: raise ThirdError(respmsg) # 如果注册成功 elif userid: #签约宝入网设置费率 if self.check_login(): self._set_user_fee(userid) # 绑定渠道商户关系 self.relate_mchnt(userid) # 添加注册标志 self.add_sign_tag(userprofile.user.groupid, userid) return success({'userid': userid})
def POST(self): userid = self.user.userid # 验证兑换码 code = self.req.input().get('code') de_code = hids.decode(code) if not de_code: raise ParamError('兑换码不存在') cb_id = de_code[0] # 获取红包绑定信息和活动信息 cb_info = {} act_id = '' with get_connection_exception('qf_marketing') as db: cb_info = db.select_one(table='coupon_bind', where={'id': cb_id}) if not cb_info: raise ParamError('兑换码不存在') act_id = cb_info.get('activity_id') if not act_id: raise ParamError('查询活动信息失败') amt = cb_info.get('amt') start_time = cb_info.get('start_time') expire_time = cb_info.get('expire_time') status = cb_info.get('status') coupon_mchnt_id = cb_info.get('mchnt_id') coupon_rule_id = cb_info.get('coupon_rule_id') now = datetime.datetime.now() if not (start_time < now < expire_time): raise ParamError('不在活动时间内') if status != COUPON_STATUS_BIND: raise ParamError('这张消费券不能使用了!') if not coupon_mchnt_id: mchnt_id_list = [] mchnt_id_json = '' with get_connection('qf_marketing') as db: mchnt_id_json = db.select_one( fields='mchnt_id_list', where={'coupon_rule_id': coupon_rule_id}) if not mchnt_id_json: raise ParamError('查询可使用商户列表失败') mchnt_id_list = json.loads(mchnt_id_json) if not (str(userid) in mchnt_id_list): raise ParamError('该消费券不能在该店铺使用') if int(coupon_mchnt_id) != int(userid): raise ParamError('该消费券不能在该店铺使用') # 使用红包 coas = CouponOperateArgs() coas.coupon_code = cb_info.get('coupon_code') coas.src = cb_info.get('src') coas.type = COUPON_STATUS_USE coas.trade_amt = int(amt) coas.customer_id = str(cb_info.get('customer_id')) coas.out_sn = str(getid()) coas.content = '交易使用消费券' coas.mchnt_id = userid try: thrift_callex(config.QF_MARKETING_SERVERS, QFMarketing, 'coupon_use', coas) except: log.warn(traceback.format_exc()) raise ThirdError('使用红包失败') return self.write(success({}))
class Send(BaseHandler): ''' 获取验证码, 发验证码 ''' _base_err = '获取验证码失败' def check_signup(self, mobile): ''' 登录验证码验证 ''' # 验证手机号是否注册 user = apcli.user_by_mobile(mobile) if user: raise ParamError('该手机已经注册') # 验证登录信息 if self.check_login(): self._groupid = self.get_groupid() # saleman_mobile d = self.req.input() if (not getattr(self, '_groupid', None) and 'saleman_mobile' in d and d['saleman_mobile']): user = apcli.user_by_mobile(d['saleman_mobile']) if user: self._groupid = user['groupid'] def check_reset_pwd(self, mobile): user = apcli.user_by_mobile(mobile) if not user: raise ParamError('该手机号还未注册') self._groupid = user['groupid'] def check_customer(self, mobile): ''' 消费者补充会员休息 ''' enuserid = self.req.input().get('enuserid') if enuserid: try: userid = hids.decode(enuserid)[0] except: if not is_valid_int(enuserid): return userid = int(enuserid) user = apcli('findUserBriefById', userid) if user: self._groupid = user.groupid @login def check_modify_username_grant(self, mobile): userid = int(self.user.userid) user = apcli_ex('findUserBriefById', userid) if not user: raise ParamError('商户不存在') if mobile != user.mobile: raise ParamError('账号信息错误, 联系客服更改') self._groupid = user.groupid @login def check_modify_username_verify(self, mobile): with get_connection_exception('qf_core') as db: new_user = db.select_one('auth_user', where={'mobile': mobile}) if new_user: raise ParamError('该手机已经注册') userid = int(self.user.userid) user = apcli_ex('findUserBriefById', userid) if not user: raise ParamError('商户不存在') self._groupid = user.groupid def check(self, mobile, mode): if not is_valid_mobile(mobile): raise ParamError('手机号码不合法') if mode not in PRESMS_FMT: raise ParamError('发送验证码模式错误') # 验证ip是否受限 ip = self.req.clientip() log.debug('ip:%s' % ip) if redis_pool.sismember('_mchnt_api_sms_code_ip_', ip): raise ParamError('ip受限') # 手机号码是不是频繁获取验证码 key = '_mchnt_api_sms_code_get_{}_'.format(mobile) if int(redis_pool.get(key) or 0) >= config.SMS_CODE_RULE['count_limit']: raise ParamError('该手机号频繁获取验证码') self._rkey = key self._groupid = None if mode.startswith('signup'): self.check_signup(mobile) elif callable(getattr(self, 'check_' + mode, None)): getattr(self, 'check_' + mode)(mobile) @dec_check() def GET(self): d = {k: v.strip() for k, v in self.req.input().iteritems()} mobile = d.get('mobile') mode = d.get('mode', 'signup') # 验证信息 self.check(mobile, mode) # 获取验证码 try: smsexpires = config.SMS_CODE_RULE.get('expires', 6 * 50) smslength = config.SMS_CODE_RULE.get('length', 6) smsmode = config.SMS_CODE_RULE.get('mode', 1) limit_time = config.SMS_CODE_RULE.get('limit_time', 60) code = thrift_callex(config.CAPTCHA_SERVERS, CaptchaServer, 'captcha_get_ex', ucode=mobile, src=config.CAPTCHA_SRC, expires=smsexpires, length=smslength, mode=smsmode, limit_time=limit_time) log.debug('获取验证码:%s' % code) except CaptchaException, e: raise ParamError(str(e.respmsg)) # 短信内容 groupid = getattr(self, '_groupid', None) if 'group' in d and d['group']: group = d['group'] else: group = redis_pool.get( '_mchnt_api_group_{}_'.format(groupid)) or 'hjsh' log.debug('groupid:{} group:{}'.format(groupid, group)) fmt = PRESMS_FMT.get(mode + '_' + group, PRESMS_FMT[mode]) csinfo = get_qd_conf_value( userid=None, mode=None, key='csinfo', groupid=groupid) or {} csinfo = {k: unicode_to_utf8_ex(v) for k, v in csinfo.iteritems()} content = fmt.format(code=code, **csinfo) log.debug('content:%s' % content) # 短信tag tags = config.PRESMS_TAG tag = tags.get(groupid or group, tags['hjsh']) r, respmsg = smscli.sendSms(mobile=mobile, content=str(content), tag=tag, source='merchant', target=mode) if not r: log.debug('调起发送短信服务失败:%s' % respmsg) raise ThirdError('发送验证码失败') # 设置获取验证码限制 if not redis_pool.exists(self._rkey): redis_pool.set(self._rkey, 0, config.SMS_CODE_RULE['expire_limit']) redis_pool.incr(self._rkey) return self.write(success({}))
def _get_members(self, d): limit_members = 10 r = {} r['overdue_warn'], r['overdue_note'] = 0, '' with get_connection_exception('qf_mchnt') as db: where = {'userid': d['userid']} # total_num r['total_num'] = db.select_one('member', where=where, fields='count(1) as num')['num'] # 若未开通服务或者付费过期 if d['mchnt_info'][ 'overdue'] and r['total_num'] > limit_members and ( d['limit'] + d['offset'] >= limit_members): r['overdue_warn'] = 1 r['overdue_note'] = '未开通会员服务,仅可显示{num}个会员信息'.format( num=limit_members) d['limit'] = max(min(limit_members - d['offset'], d['limit']), 0) # members r['members'] = [] if d['limit']: fields = 'customer_id, txamt, num, last_txdtm, userid' other = '%s limit %s offset %s' % (d['orderby'], d['limit'], d['offset']) r['members'] = db.select('member', where=where, other=other, fields=fields) # 统计今日增长笔数 td = str_to_tstamp(time.strftime(DATE_FMT), DATE_FMT) r['add_members'] = db.select_one('member', where={ 'userid': d['userid'], 'ctime': ('>', td) }, fields='count(1) as num')['num'] cids = [i['customer_id'] for i in r['members']] if cids: spec = json.dumps({"user_id": cids}) try: profiles = thrift_callex(config.OPENUSER_SERVER, OpenUser, 'get_profiles', config.OPENUSER_APPID, spec) profiles = {i.user_id: i.__dict__ for i in profiles} # 处理返回值 for m in r['members']: info = profiles.get(m['customer_id'], {}) m['avatar'] = info.get('avatar') or config.HJ_AVATAR m['gender'] = info.get('gender', 1) m['nickname'] = info.get('nickname') or m['customer_id'] m['last_txdtm'] = tstamp_to_str(m['last_txdtm'], DATETIME_FMT) except: log.warn('get openuser_info error:%s' % traceback.format_exc()) raise ThirdError('获取消费者信息失败') return r
def GET(self): params = self.req.input() userid = params.get("userid", '') usertype = params.get("usertype", '') try: usertype = int(usertype) except: raise ParamError("usertype参数错误") if usertype not in UserDefine.SIGNUP_USERTYPES: raise ParamError("usertype参数错误") if not userid: raise ParamError("userid参数错误") # 验证传入的userid是否属于当前业务员 curr_uid = self.user.userid qd_info = get_qd_mchnt(userid) if qd_info: slsm_uid = qd_info.slsm_uid if slsm_uid != int(curr_uid): return self.write(error(QFRET.DBERR, respmsg="商户id参数与当前操作员无绑定关系")) cate = self.get_cate(userid=userid) if cate == "bigmerchant": sub_uids = get_linkids(userid) if not sub_uids: return self.write(success(data={})) else: # 先筛选出状态为审核通过的商户 最新商户信息从审核通过商户中选取 with get_connection('qf_mis') as db: rows = db.select('apply', where={'user': ('in', sub_uids), 'state': APPLY_STATE.get("pass")}, fields='user') if rows: sub_uids = [i['user'] for i in rows] else: return self.write(success(data={})) ret = dict() # 查询出最新的userid, name和legalname with get_connection("qf_core") as db: rows = db.select("profile", where={"userid": ("in", sub_uids), "user_type": usertype}, fields="userid, name, legalperson, user_type", other="order by jointime desc") if len(rows) <= 0: return self.write(success(data={})) latest_uid = rows[0]['userid'] usertype = int(rows[0]['user_type']) name = rows[0]['name'] legal_name = rows[0]['legalperson'] if usertype == UserDefine.SIGNUP_USERTYPE_TINY: ret['name'] = name else: ret['name'] = legal_name try: detail_info = apcli('userprofile_by_id', latest_uid) except: log.debug(traceback.format_exc()) raise ThirdError("获取商户详情失败") user_info = detail_info['user'] bank_info = detail_info['bankInfo'] ret['banktype'] = bank_info['banktype'] ret['bankuser'] = bank_info['bankuser'] ret['bankaccount'] = bank_info['bankaccount'] ret['bankmobile'] = bank_info['bankmobile'] ret['bankProvince'] = bank_info['bankProvince'] bank_city = bank_info.get('bankCity', '') head_bankname = bank_info.get('headbankname', '') ret['bankCity'] = bank_city ret['headbankname'] = head_bankname with get_connection_exception('qf_mis') as db: r = db.select_one('tools_areacity', where={'city_name': bank_city}, fields='city_no, city_name') or {} head_bank = db.select_one('tools_bank', where={'bank_name': head_bankname, 'bank_display': 1}, fields='bank_name, bank_no') or {} ret['city_id'] = r.get('city_no', '') ret['headbankid'] = head_bank.get('bank_no', '') ret['bankcode'] = bank_info.get('bankcode', '') ret['bankname'] = bank_info['bankname'] ret['idnumber'] = user_info['idnumber'] ret['address'] = user_info['address'] user_ext = apcli_ex('getUserExt', int(latest_uid)) ret['shoptype_id'] = '' if user_ext: ret['shoptype_id'] = user_ext.shoptype_id # 身份证有效期, 照片, cert_names = ["idcardfront", "idcardback", "idcardinhand", "licensephoto"] # 常量对应 cert_imgurl = {"idcardfront": 'idcardfront_url', "idcardback": 'idcardback_url', "idcardinhand": "idcardinhand_url", "licensephoto": "license_photo_url"} all_img_info = get_img_info(latest_uid, cert_names) for i in all_img_info: ret.update({cert_imgurl[i['name']]: i['imgurl']}) with get_connection('qf_mis') as db: db_ret = db.select('apply', fields="idstatdate, idenddate", where={"user": latest_uid}, other="limit 1") if db_ret: ret.update(db_ret[0]) else: ret.update({ "idstatdate": "", # 身份证起始时间 "idenddate": "", # 身份证结束时间 }) return self.write(success(data=ret)) else: raise ParamError("角色错误")
def POST(self): params = self.req.input() username = params['username'] password = params['password'] udid = params.get('udid') opuid = params.get('opuid') params['password'] = '******' user = self.get_user(username) opinfo = None self.check_user(user['userid'], opuid) if opuid: opinfo = self.check_op(user['userid'], password, opuid) else: if not check_password(password, user['password']): self.password_error(user['userid'], password) raise UserError('账号或密码有误,请重新输入') # 获取用户信息 userinfo = apcli.user_by_id(user['userid']) if not userinfo: log.debug('[username:{} pwd:{}]'.format(username, password)) raise ThirdError('账号或密码有误,请重新输入') # 线下店铺信息 user_ext = apcli_ex('getUserExt', int(userinfo['uid'])) cf = {} # 线下店铺信息 cf['cate'] = self.get_cate(userinfo['uid'], userinfo['userCates']) # 如果禁止大商户登录 if (not getattr(config, 'BIGMCHNT_LOGIN_ALLOWED', True) and cf['cate'] == 'bigmerchant'): raise ParamError('商户角色错误') # 获取渠道信息 cf['qdinfo'] = self._qdinfo = get_qudaoinfo(userinfo['groupid']) # 设置用户session sid = self.set_session(udid=udid, userinfo=userinfo, opuid=opuid, cate=cf['cate'], language=self._qdinfo['language']) # 支持刷卡设备获取terminalids terminalids = [] user_agent = self.req.environ.get('HTTP_USER_AGENT', '').upper() if any(True for i in config.UA_CARD if i in user_agent): terms = None with get_connection('qf_core') as db: terms = db.select('termbind', where={'userid': user['userid']}, fields='terminalid') terminalids = [i['terminalid'] for i in terms or []] ret = UserUtil.ret_userinfo(userinfo, user_ext, sessionid=sid, opinfo=opinfo, terminalids=terminalids, **cf) self.resp.set_cookie('sessionid', sid, **config.COOKIE_CONFIG) conf_group_client_url = config.GROUP_CONF_CLIENT_URL.get( str(userinfo['groupid']), config.DEFAULT_CLIENT_URL) ret['pay_url'] = conf_group_client_url.get( "pay_url", config.DEFAULT_CLIENT_URL.get("pay_url")) ret['pay_trade_query_url'] = conf_group_client_url.get( "pay_trade_query_url", config.DEFAULT_CLIENT_URL.get("pay_url")) _, has_set = has_set_mpwd(user['userid']) ret['has_set_mpwd'] = 1 if has_set else 0 return success(ret)
def get_user_services(self, pos='all', addon=None, limit=None): ''' 获取用户功能列表 参数: pos all:全部功能 home_page:首页 head: 头部 addon 功能多加载的数据 limit 限制数量 ''' userid = int(self.user.userid) language = self.get_language() # 获取用户的信息 user = apcli('findUserBriefById', userid) if not user: raise ThirdError('商户不存在') user = user.__dict__ self._user = user # 获取用户的登录角色 user_cate = self.get_user_cate() # 获取渠道配置 qd_conf = get_qd_conf() # 用户服务列表 groupid = user['groupid'] default_services = get_qd_conf_value(userid, 'default', 'service', groupid=groupid, default=config.DEFAULT_SERVICES, qd_confs=qd_conf) user_service = apcli.user_service(userid) self._user_service = {i['code'] for i in user_service} | set(default_services) # 根据版本号和平台获取服务列表 version, platform = get_app_info( self.req.environ.get('HTTP_USER_AGENT', '')) log.info('user_agent:%s version:%s platform:%s userid:%s' % (self.req.environ.get('HTTP_USER_AGENT', ''), version, platform, userid)) sys_services = get_qd_conf_value(userid, 'services', 'service', groupid=groupid, default=config.SYSTEM_SERVICES, qd_confs=qd_conf) must_addon = [ 'recharge_link', 'group_link', 'condition', 'dis_groupids', 'nodis_groupids', 'dis_service', 'dis_condition', 'show_cate' ] addon = (addon or []) + must_addon services = get_services(version, platform, addon=addon, sys_services=sys_services) # 调整返回值 ret = [] payinfo = None user_open_service = {i['code'] for i in user_service} for service in services: # 若不满足条件, 直接跳过 if service['code'] not in self._user_service: continue # 指定角色才展示 show_cates = service.pop('show_cate') or [ 'merchant', 'submerchant' ] if user_cate not in show_cates: continue # 显示位置判断 tpos = service.pop('pos') or ['all'] if pos not in tpos: continue dis_condition = service.pop('dis_condition', None) if dis_condition: try: if not eval( dis_condition, { 'user': user, 'user_open': service['code'] in user_open_service }): continue except: log.warn(traceback.format_exc()) continue # 条件 condition = service.pop('condition', None) # 渠道link group_link = service.pop('group_link', None) # 渠道link # 根据grouid配置是否展示 dis_groupids = service.pop('dis_groupids') or config.QF_GROUPIDS nodis_groupids = service.pop( 'nodis_groupids') or config.QF_GROUPIDS # 付费后的链接 recharge_link = service.pop('recharge_link', None) # 余额提现链接 dis_service = service.pop('dis_service', '') # 根据条件判断 if condition: # 如果指定服务存在将不展示 if ('dis_service' in condition and dis_service in self._user_service): continue # 根据渠道判断 # 白牌渠道不展示 if 'group_dis' in condition: if groupid in qd_conf: continue # 根据渠道id来控制展示 if 'group_control' in condition: if groupid not in dis_groupids: continue # 根据渠道id来控制展示 if 'nogroup_control' in condition: if groupid in nodis_groupids: continue # 白牌渠道link if 'group_link' in condition: if groupid in qd_conf: service['link'] = group_link # 开通点餐服务 if 'diancan_service' in condition: if payinfo is None: payinfo = get_mchnt_paying(userid, code='diancan') if payinfo and str(payinfo['expire_time']) > time.strftime( DATETIME_FMT): service['link'] = recharge_link # 链接带上参数 service['link'] = service['link'].format(**user) # name根据语言可控制 if 'name' in service: service['name'] = get_constant(service['name'], language) ret.append(service) return ret[:limit]
def GET(self, userid=None): d = {k: v.strip() for k, v in self.req.input().iteritems()} # 分页信息 page, pagesize = int(d.get('page', 0)), int(d.get('pagesize', 10)) # 获取数据 try: # 获取账期 dates = thrift_call(FundService, 'findDebitpageInfo', config.FUND_SERVERS, userid, page, pagesize) if not dates: return self.write(success({'settles': []})) # 获取划款列表 debits = thrift_call(FundService, 'findDebitInfo', config.FUND_SERVERS, userid, dates) if not debits: return self.write(success({'settles': []})) debits = [i.__dict__ for i in debits] debits.sort(key=lambda d: d['expectdate'], reverse=True) except: raise ThirdError('获取列表失败') # 划款数据整理 settles = [] for expectdate, records in groupby(debits, lambda d: d['expectdate']): records = list(records) status_dict = defaultdict(int) total_payamt, cnt = 0, len(records) week_day = datetime.datetime.strptime(expectdate, DATE_FMT).isoweekday() for record in records: status_dict[record['status']] += 1 total_payamt += record['payamt'] # 全部已划款 if status_dict['havepay'] == cnt: status = UserDefine.SETTLE_STATUS_HAVE # 全部未划款 elif status_dict['nopay'] == cnt: status = UserDefine.SETTLE_STATUS_NO # 部分划款 else: # 只有已划款和等待划款 if status_dict['havepay'] + status_dict['nopay'] == cnt: status = UserDefine.SETTLE_STATUS_PART # 包含划款失败 elif status_dict['havepay'] or status_dict['nopay']: status = UserDefine.SETTLE_STATUS_PART_FAIL # 全部划款失败 else: status = UserDefine.SETTLE_STATUS_FAIL settles.append({ 'expectdate': expectdate, 'week_day': week_day, 'status': status, 'records': records, 'total_payamt': total_payamt, 'cnt': cnt }) return self.write(success({'settles': settles}))
def GET(self): d = self.req.input() page = d.get('page', 0) pagesize = d.get('pagesize', 10) userid = self.user.userid paging = (int(pagesize), int(pagesize) * int(page)) other = 'order by create_time desc limit {} offset {}'.format(*paging) ret = {'records': []} # 查询交易记录和消费品名称 records = [] titles = [] titles_dict = {} with get_connection_exception('qf_marketing') as db: records = db.select( table='record', fields=['customer_id', 'create_time', 'activity_id', 'xx_id'], where={ 'type': RECORD_STATUS_USE, 'xx_type': ACTIVITY_SHARE_TYPE_GOODS_COUPON, 'use_mchnt_id': userid, }, other=other) if not records: return self.write(success(ret)) act_ids = [record.get('activity_id') for record in records] titles = db.select(table='activity', fields=['title', 'id'], where={'id': ('in', act_ids)}) if not titles: raise ParamError('获取兑换商品失败') titles_dict = {title['id']: title['title'] for title in titles} # 查询消费者信息 cids = {i['customer_id'] for i in records} spec = json.dumps({'user_id': list(cids)}) client = ThriftClient(config.OPENUSER_SERVER, OpenUser) client.raise_except = True infos = [] try: infos = client.call('get_profiles', config.OPENUSER_APPID, spec) infos = {i.user_id: i.__dict__ for i in infos} except: log.warn(traceback.format_exc()) raise ThirdError('获取用户信息失败') # 整理信息 for i in records: cust_id = int(i['customer_id']) cust_info = infos.get(cust_id) or {} avatar_str = cust_info.get('avatar') or '' i['avatar_url'] = avatar_str.split(':', 1)[-1] i['gender'] = cust_info.get('gender') or 0 i['nickname'] = cust_info.get('nickname') or '微信支付顾客' i['exchange_time'] = i['create_time'].strftime('%H:%M:%S') i['goods_name'] = titles_dict.get(i.pop('activity_id'), '未知商品') i['exchange_code'] = hids.encode(i.pop('xx_id')) date_records = defaultdict(list) for i in records: t = i.pop('create_time').strftime(DATE_FMT) date_records[t].append(i) # 查询每日的交易数量 sql = ( 'select FROM_UNIXTIME(create_time, "%%Y-%%m-%%d") as date, ' 'count(id) as num from record ' 'where use_mchnt_id=%s and xx_type=%s and type=%d ' 'group by FROM_UNIXTIME(create_time, "%%Y%%m%%d") ' 'order by create_time desc' % (str(userid), ACTIVITY_SHARE_TYPE_GOODS_COUPON, RECORD_STATUS_USE)) data_infos = [] with get_connection('qf_marketing') as db: data_infos = db.query(sql) if not data_infos: raise ParamError('获取消费者数量失败') # 整理返回信息 ret = [] for i in data_infos: date = i['date'] tmp = {} tmp['date'] = i['date'] tmp['use_cnt'] = i['num'] tmp['customers'] = date_records.get(date) or [] ret.append(tmp) return self.write(success({'records': ret}))