def GET(self): voucher_list = [] token = '' try: uid = int(self._userid) if self._userid else 0 vouchers = self.db.select('mis_upgrade_voucher', where={'user_id': uid}) log.info("voucher :%s", vouchers) for v in vouchers: voucher_list.append({ 'name': v['name'], 'name_cn': CERT_NAME.get(v['name']) if CERT_NAME.has_key(v['name']) else CERT_NAME.get(OLD2NEW_CERT.get(v['name'], ''), ''), 'url_middle': self.makeImgurl(uid, v['name'], v['imgname'], 'middle'), }) token = hids.encode(uid, uid) except: log.warn('get vouchears fail: %s' % traceback.forat_exc()) return self.write(error(QFRET.DBERR, respmsg='数据库错误')) return self.write( success({ 'token': token, 'voucher_list': voucher_list }))
def POST(self): ''' 修改用户权限 ''' d = self.validator.data userid = int(self.user.userid) if not d['opuid']: raise ParamError('参数错误') if d['status'] is not None and d['status'] not in [0, 1]: raise ParamError('状态非法') if d['type'] is None: type = 'refund' else: type = d['type'] # 更新数据 where = {'userid': userid, 'opuid': int(d['opuid'])} perms = {} with get_connection('qf_core') as db: opuser = db.select_one(table='opuser', fields=['perms'], where=where) if opuser: try: perms = json.loads(opuser['perms']) perms[type] = d['status'] except: perms[type] = d['status'] finally: db.update('opuser', {'perms': json.dumps(perms)}, where) return self.write(success({})) else: return self.write(error(QFRET.PARAMERR, respmsg='操作员信息不存在'))
def POST(self): cate = self.get_cate() params = self.req.input() sub_mchnt_id = params.get('shopid', '') try: userid = self.user.userid sub_mchnt_id = int(sub_mchnt_id) if not sub_mchnt_id: raise ParamError("子商户错误") else: if cate == "bigmerchant": subids = get_linkids(userid) if sub_mchnt_id not in subids: raise ParamError("非大商户的子商户") except: log.warn('sub merchant error : %s ' % traceback.format_exc()) raise ParamError("无法识别子商户") try: thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'unbindRelation', int(userid), int(sub_mchnt_id), 'merchant') except: log.warn('user ({userid}) remove sub merchant({sub_mchnt_id}) error : {reason}'.format(userid=userid, sub_mchnt_id = sub_mchnt_id, reason = traceback.format_exc())) return self.write(error(QFRET.THIRDERR)) return self.write(success(data={}))
def GET(self): perms_list = { 'refund': 1, 'coupon': 1, 'member': 1, 'sales': 1, 'prepaid': 1, 'card': 1, 'shop_notice': 1 } userid = int(self.user.userid) opuid = int(self.user.ses.get('opuid', 0)) if opuid: where = {'userid': userid, 'opuid': opuid} with get_connection('qf_core') as db: opuser = db.select_one(table='opuser', fields=['perms'], where=where) if opuser: try: perms = json.loads(opuser['perms']) for i in perms_list.keys(): perms_list[i] = perms.get(i, 0) except: keys = perms_list.keys() perms_list = dict.fromkeys(keys, 0) return self.write(success(perms_list)) else: return self.write(error(QFRET.PARAMERR, respmsg='操作员信息不存在')) else: return self.write(success(perms_list))
def GET(self): try: userid = int(self.user.userid) results = [] with get_connection('qf_mchnt') as db: invoices = db.select( table='invoices', where={'userid': userid}, other='order by ctime desc limit 5') or [] for i in invoices: tmp = {} tmp['title'] = i.get('title', '') tmp['tax_no'] = i.get('tax_no', '') tmp['address'] = i.get('address', '') tmp['telephone'] = i.get('telephone', '') tmp['bank_name'] = i.get('bank_name', '') tmp['bank_num'] = i.get('bank_num', '') results.append(tmp) return self.write(success(data=results)) except: log.warn('error :%s' % traceback.format_exc()) return self.write(error(QFRET.SERVERERR, respmsg='内部错误'))
def POST(self): try: params = self.req.inputjson() banktype = params.get('banktype', '') bankuser = params.get('bankuser', '') bankaccount = params.get('bankaccount', '') headbankname = params.get('headbankname', '') bankname = params.get('bankname', '') brchbank_code = params.get('brchbank_code', '') bankprovince = params.get('bankprovince', '') bankcity = params.get('bankcity', '') img_name = params.get('img_name', '') img_type = params.get('img_type', '') userid = int(self.user.userid) value = { 'userid': userid, 'banktype': banktype, 'bankuser': bankuser, 'bankaccount': bankaccount, 'headbankname': headbankname, 'brchbank_code': brchbank_code, 'bankname': bankname, 'bankprovince': bankprovince, 'bankcity': bankcity, 'applyuser': userid, 'applytype': 5, 'modifytime': datetime.now(), 'create_time': datetime.now(), 'status': UserDefine.BANK_APPLY_WAIT, 'sync_tl_status': UserDefine.BANK_SYNC_NO } value['operatorgroup'] = json.dumps(config.OPERATE_GROUP) with get_connection('qf_mis') as db: db.insert('bankchange_apply', value) where = {'userid': userid} if img_name: apy = db.select_one( 'bankchange_apply', where=where, other='order by modifytime desc') or {} id = apy.get('id', 0) if img_type == '1': img_type = 'BANK_CARD' if img_type == '2': img_type = 'OPEN_LICENSE' db.insert('bankchange_apply_img', values={ 'change_apply_id': int(id), 'img': img_name, 'img_type': img_type, 'created': datetime.now(), 'updated': datetime.now() }) return self.write(success({'message': '申请提交成功,请耐心等待审核结果'})) except: log.warn('error :%s' % traceback.format_exc()) return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))
def POST(self): try: if not self.customer.is_login(): return self.write( error(QFRET.LOGINERR, resperr="user not login", respmsg="用户未登陆")) params = self.req.input() userid = params.get('userid', '') try: userid = hids.decode(userid)[0] except: raise ParamError("商户id错误") customer_id = self.customer.customer_id title = params.get('title', '') tax_no = params.get('taxNumber', '') address = params.get('companyAddress', '') phone = params.get('telephone', '') bank_name = params.get('bankName', '') bank_num = params.get('bankAccount', '') now = int(time.time()) values = {'utime': now, 'ctime': now} values['userid'] = userid values['customer_id'] = customer_id values['title'] = title values['tax_no'] = tax_no values['address'] = address values['telephone'] = phone values['bank_name'] = bank_name values['bank_num'] = bank_num with get_connection('qf_mchnt') as db: db.insert('invoices', values=values) return self.write(success({})) except: log.warn('error :%s' % traceback.format_exc()) return self.write(error(QFRET.SERVERERR, respmsg='内部错误'))
def GET(self): d = {k:v.strip() for k, v in self.req.input().iteritems()} try: fmt = d.get('fmt', DATETIME_FMT) ret = time.strftime(fmt) except: log.warn('[fmt:%s] fmt is not legal, %s' % (fmt, traceback.format_exc())) return self.write(error(QFRET.PARAMERR, respmsg='获取系统时间失败')) return self.write(success({'sysdt':ret}))
def __(self, *args, **kwargs): try: # 错误信息 module_name = getattr(self, '__module__', '') class_name = getattr(getattr(self, '__class__', ''), '__name__', '') func_name = getattr(func, '__name__', '') errinfo = '%s %s %s' % (module_name, class_name, func_name) return func(self, *args, **kwargs) except SLAException, e: log.warn('[%s] error: %s' % (errinfo, e)) return self.write(error(e.errcode, respmsg=e.errmsg))
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 _regioncities(self, records): ret, areacities = [], records.get('records', []) try: for area_no, city_noes in CCONF.get('region_areas', {}).iteritems(): meet_area = next((i for i in areacities if i['areaid'] == area_no), None) if meet_area: meet_cities = [i for i in meet_area['cities'] if i['cityid'] in city_noes] meet_area['cities'] = meet_cities ret.append(meet_area) log.debug('ret:%s' % ret) except: log.warn('get regioncities fail, %s' % traceback.format_exc()) return self.write(error(QFRET.THIRDERR, respmsg='获取商圈城市列表失败')) return self.write(success({'records' : ret}))
def GET(self): params = self.req.input() begin_time = params.get("begin_time", '') end_time = params.get("end_time", '') if not begin_time or not end_time: return self.write(error(QFRET.PARAMERR, respmsg="开始时间或者结束时间没有")) if not is_valid_datetime(begin_time) or not is_valid_datetime( end_time): return self.write(error(QFRET.PARAMERR, respmsg="开始时间或者结束时间格式不对")) with get_connection_exception("qf_core") as db: try: rows = db.select( "extra_mchinfo", where={"supply_time": ("between", (begin_time, end_time))}, fields="userid") except: log.debug(traceback.format_exc()) return self.write(error(QFRET.DBERR, respmsg="查询出现异常")) return self.write( success(data={"supplied_userids": [i['userid'] for i in rows]}))
def POST(self): try: # 转换并验证输入 d = self._trans_input() # 关联老商户 relation = UserRelation(userid=d['linkid'], link_cate='merchant') if not apocli.set_user_relation(d['userid'], relation)[0]: raise ParamError('关联失败,请稍候再试') return self.write(success({})) except MchntException, e: log.warn('BindMchnt error: %s' % e) return self.write(error(e.errcode, respmsg=e.errmsg))
def GET(self): try: userid = int(self.user.userid) r = apcli.userprofile_by_id(userid) if not r: raise ParamError('未获取到账户类型') else: bankinfo = r.get('bankInfo', {}) return self.write( success({ 'banktype': bankinfo.get('banktype', ''), 'name': bankinfo.get('bankuser', '') })) except: log.warn('error :%s' % traceback.format_exc()) return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))
def POST(self): params = {k: str(v).strip() for k, v in self.req.input().iteritems()} card_id = params.get("card_id") encrypt_code = params.get("encrypt_code") openid = params.get("openid") client = ThriftClient(config.WXCARD_SERVERS, WXCard) client.raise_except = True info = CardInterfaceActiveInfo(card_id=card_id, encrypt_code=encrypt_code, openid=openid) try: client.call("card_interface_active", info, 0) return self.write(success(data={})) except WXCardError as e: log.debug(traceback.format_exc()) return self.write(error(QFRET.THIRDERR, respmsg=e.respmsg))
def GET(self): userid = int(self.req.input().get('userid').strip()) r = None with get_connection('qf_mchnt') as db: now = int(time.time()) r = db.select_one('card_actv', where={ 'userid': self.get_userid_condition(userid), 'expire_time': ('>', now), 'start_time': ('<', now) }, fields=[ 'exchange_pt', 'goods_name', 'goods_amt', 'obtain_amt', 'status', 'obtain_limit' ], other='order by ctime desc') or {} if not r: return error(QFRET.NODATA) return success(r)
def GET(self): try: params = self.req.inputjson() userid = self.user.userid try: page = int(params.get('page', 0)) pagesize = int(params.get('pagesize', 10)) except: log.debug(traceback.format_exc()) return self.write(error(QFRET.PARAMERR, respmsg=u"分页参数错误")) union_activity = get_union_activty(userid) coupon_dic = union_activity.get('coupon_dic', {}) all_actids = coupon_dic.keys() # 这个id是activity_union表的id res = dict() res['total_num'] = 0 res['total_amount'] = 0 res['commission_amount'] = 0 res['coupon_amount'] = 0 res['count'] = 0 res['is_activity'] = 0 res['activitys'] = [] if not all_actids: return self.write(success(data=res)) else: # 再关联下activity表的id with get_connection('qf_marketing') as db: rows = db.select('activity', fields='id, union_id', where={'union_id': ('in', all_actids)}) if rows: activity_ids = set() # coupon_dic2 = dict() # 增加一个变量记录下activity_id: union_id的对应关系 actid_union_dic = {} for i in rows: activity_ids.add(i['id']) # coupon_dic2.update({i['id']: coupon_dic[i['union_id']]}) actid_union_dic.update({i['id']: i['union_id']}) where = { 'xx_type': ACTIVITY_SHARE_TYPE_COUPON, 'activity_id': ('in', activity_ids), 'use_mchnt_id': userid, 'type': ('in', (RECORD_STATUS_USE, RECORD_STATUS_DESTROY)) } with get_connection_exception('qf_marketing') as conn: rows = conn.select( 'record', fields= 'use_mchnt_id, activity_id, amt, (total_amt - amt) as payamt, type, out_sn, orig_out_sn', where=where) # 先找出所有的origin_out_sn的数据,撤销交易要原单号 all_orig_out_sns = [] destory_trade = {} for i in rows: if i['type'] == 3: all_orig_out_sns.append(i['orig_out_sn']) destory_trade.update({i['orig_out_sn']: i}) temp = dict() for i in all_actids: temp.update({ '{}'.format(i): { 'trade_amount': 0, 'commi_amount': 0, 'trade_num': 0, 'commi_rate': coupon_dic.get(int(i)).get('rate', 0), 'actname': coupon_dic.get(int(i)).get('title', ''), 'status': 0 if coupon_dic.get(int(i)).get('status', '') == 3 else 1, 'ctime': coupon_dic.get(int(i)).get('ctime', ''), 'actid': str(i), 'coupon_amount': 0, } }) for i in rows: if int(i['type']) == RECORD_STATUS_DESTROY: continue if i['out_sn'] in set(all_orig_out_sns): continue key = '{}'.format(actid_union_dic.get( i['activity_id'])) rate = coupon_dic.get( int(actid_union_dic.get( i['activity_id']))).get('rate') res['total_num'] += 1 res['total_amount'] += int(i['payamt']) res['coupon_amount'] += int(i['amt']) temp[key]['trade_num'] += 1 temp[key]['trade_amount'] += int(i['payamt']) temp[key]['coupon_amount'] += int(i['amt']) fee = float(i['payamt']) * float(rate) / 100.0 / 100.0 fee = math.floor(fee * 100) temp[key]['commi_amount'] += fee res['commission_amount'] += fee for k, v in temp.iteritems(): res['activitys'].append(v) res['activitys'] = sorted(res['activitys'], key=itemgetter( 'status', 'ctime'), reverse=True) res['count'] = len(res['activitys']) start = page * pagesize end = page * pagesize + pagesize res['activitys'] = res['activitys'][start:end] res['is_activity'] = 1 return self.write(success(data=res)) except: log.warn('error :%s' % traceback.format_exc()) return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))
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)) except: log.warn('ToBigMchnt error: %s' % traceback.format_exc()) return self.write(error(QFRET.PARAMERR, respmsg='注册失败,请稍后再试')) class BindMchnt(BaseHandler): ''' 关联商户 只验证ip ''' def _check_user(self, username, password): try: thrift_callex(config.APOLLO_SERVERS, ApolloServer, 'checkUser', username, password) except ApolloException, e: if e.respcd == ApolloRet.APOLLO_ERR_USER_NOT_EXIST: raise ParamError('该账号未注册') elif e.respcd == ApolloRet.APOLLO_ERR_PASSWD:
def GET(self): d = {k: v.strip() for k, v in self.req.input().iteritems()} biznum = d.get('biznum') if not biznum: raise ParamError('参数错误') try: records = thrift_callex(config.FINANCE_SERVERS, Finance, 'get_tradeinfo_by_biznum', biznum) if not records: return error(QFRET.NODATA) except: raise ThirdError('第三方服务错误') try: monthfees = thrift_callex(config.FINANCE_SERVERS, Finance, "get_withhold_history_by_biznum", str(biznum)) except: raise ThirdError('第三方服务错误') # 到账记录详细信息 cp_chnlids = getattr(config, 'SETTLE_CP_CHNLIDS', []) totalmoney = totalfee = 0 detaillist = [] bills = defaultdict(int) for r in records: totalmoney += r.tradeamt totalfee += r.fee cp_amt = 0 # 特定的通道将红包金额加入好近补贴 if r.chnlid in cp_chnlids: bills['hj_coupon'] += r.coupon_amt cp_amt = r.coupon_amt # 到账分支付类型总计 bills[r.tradetype] += (r.tradeamt - r.fee - cp_amt) detaillist.append({ 'tradetime': r.tradetime, 'tradeamt': r.tradeamt, 'fee': -r.fee, 'type': r.tradetype, 'coupon_fee': r.ori_coupon_amt - r.coupon_amt, 'ori_coupon_amt': r.ori_coupon_amt }) # 到账分支付类型总计 billlist = [] # 支付类型列表 bill_types = getattr( config, 'BILL_TYPES', ('alipay', 'tenpay', 'jdpay', 'card', 'hj_coupon')) for i in bill_types: if not bills[i] or i not in config.BILL_TYPE_DETAIL: continue billlist.append({ 'name': config.BILL_TYPE_DETAIL[i], 'value': bills[i], 'type': i }) # 扣款列表 fee_detail_list = [] for monthfee in monthfees: #费用是正的是补给用户的,加到总额里面去 if monthfee.amount > 0: totalmoney += monthfee.amount #扣费加到手续费里面去 else: totalfee += -monthfee.amount is_rent_fee = False if isinstance(monthfee.title, types.UnicodeType): monthfee.title = monthfee.title.encode('utf-8') #修改title如果是月租费的话 etc 12月QPOS月服务费 if monthfee.title == 'QPOS月服务费': monthfee.title = '%s月%s' % (monthfee.evidence_date[5:7], monthfee.title) is_rent_fee = True #存在的话,就合并 is_exist = False for fee in fee_detail_list: if monthfee.title == fee['name'] and is_rent_fee: fee['value'] += monthfee.amount is_exist = True break if not is_exist: fee_detail_list.append({ 'name': monthfee.title, 'value': monthfee.amount, 'month': monthfee.evidence_date }) return success({ 'totalmoney': totalmoney, 'totalfee': -totalfee, 'detaillist': detaillist, 'feedetail': fee_detail_list, 'billlist': billlist })
def GET(self): d = {k: v.strip() for k, v in self.req.input().iteritems()} # userid userid = int(self.user.ses.get('userid', '')) # 分页信息 page, pagesize = d.get('page', 0), d.get('pagesize', 10) if not all(map(is_valid_int, (pagesize, page))): raise ParamError('分页信息错误') try: records = thrift_callex(config.FINANCE_SERVERS, Finance, 'get_debitinfo', userid=userid, appsrc='qf', page=int(page) + 1, maxnum=int(pagesize)) except: raise ThirdError('第三方服务错误') if not records: return error(QFRET.NODATA) searchdate = [] for r in records: if r.expectdate in ACCOUNT_PERIOD_CACHE: continue searchdate.append(r.expectdate) acnt_period_date = [] if searchdate: try: acnt_period_date = thrift_callex(config.FINANCE_SERVERS, Finance, "get_account_period", search_date_list=searchdate) except: raise ThirdError('第三方服务错误') if not acnt_period_date: return error(QFRET.NODATA) #将新的更新到缓存中 for d in acnt_period_date: ACCOUNT_PERIOD_CACHE[d.search_date] = d data_lst = [] sys_time = datetime.datetime.now() for r in records: period_date = ACCOUNT_PERIOD_CACHE.get(r.expectdate, '') if not period_date: continue expectdate_tm = '' if not r.status else datetime.datetime.strptime( r.expectdate + " 18:00:00", DATETIME_FMT) #如果是已经划款 if r.status == 'havepay': #超过18:00点,则变成已经到账 if expectdate_tm and expectdate_tm < sys_time: r.status = 'inaccount' data = { 'status': DEBIT_STATUS.get(r.status, '未知'), 'payamt': r.payamt, 'biznum': r.biznum, 'expectdate': r.expectdate, 'week_day': datetime.datetime.strptime(r.expectdate, DATE_FMT).isoweekday(), 'period': { "end": period_date.end_date, "start": period_date.start_date, "paydate": "" if not r.paytime else datetime.datetime.strptime( r.paytime, DATETIME_FMT).strftime(DATE_FMT), "paytime": r.paytime, } } data_lst.append(data) return success({ 'count': len(data_lst), 'systime': sys_time, 'records': data_lst, 'total': len(data_lst) })
def GET(self): params = self.req.input() if params.has_key("shopid"): shopid = params.get("shopid") try: userid = int(shopid) except: raise ParamError("子商户参数错误") # 判断下当前传入的userid是否是子商户 if userid not in get_linkids(self.user.userid): raise ParamError("传入的子商户不属于此商户") else: userid = int(self.user.ses.get('userid', 0)) url = config.QRCODE_URL % hids.encode(userid) # 获取用户信息 user = apcli.user_by_id(userid) if not user: return self.write(error(QFRET.PARAMERR, respmsg='查询用户信息失败')) mchnt_name = user['shopname'] # 获取图片信息 img_conf = get_qd_conf_value( mode=None, key='qrcode', groupid=user['groupid']) or {} if not params.has_key("shopid"): # 操作员信息 opinfo = self.get_opinfo() opuid, opname = opinfo.get('opuid'), opinfo.get('opname', '') if opuid: url += '&o=' + str(opuid) op_img_conf = { k[3:]: v for k, v in img_conf.iteritems() if k.startswith('op_') } img_conf = op_img_conf or img_conf opname = '%04d' % int(opuid) else: img_conf = { k: v for k, v in img_conf.iteritems() if not k.startswith('op_') } else: return self.write( success({ "qrcode": url, "img_conf": { k: v for k, v in img_conf.iteritems() if not k.startswith('op_') } })) return self.write( success({ 'qrcode': url, 'img_conf': img_conf, 'mchnt_name': mchnt_name, 'opname': opname }))
def raise_excp(info='参数错误'): def _(func): def __(self, *args, **kwargs): try: # 错误信息 module_name = getattr(self, '__module__', '') class_name = getattr(getattr(self, '__class__', ''), '__name__', '') func_name = getattr(func, '__name__', '') errinfo = '%s %s %s' % (module_name, class_name, func_name) return func(self, *args, **kwargs) except SLAException, e: log.warn('[%s] error: %s' % (errinfo, e)) return self.write(error(e.errcode, respmsg=e.errmsg)) except: log.warn('[%s] error:%s' % (errinfo, traceback.format_exc())) return self.write(error(QFRET.PARAMERR, respmsg=info)) return __ return _ def thrift_callex_framed(server_config, mod, func, *args, **kwargs): client = ThriftClient(server_config, mod, framed=True) client.raise_except = True return client.call(func, *args, **kwargs)
def GET(self): try: params = self.req.inputjson() act_id = params.get('actid', '') email = params.get('email', '') userid = self.user.userid try: page = int(params.get('page', 0)) pagesize = int(params.get('pagesize', 10)) except: log.debug(traceback.format_exc()) return self.write(error(QFRET.PARAMERR, respmsg=u"分页参数错误")) if not act_id: return self.write(error(QFRET.PARAMERR, respmsg='参数错误')) if email and not re.match(EMAIL_PATTERN, email): return self.write(error(QFRET.PARAMERR, respmsg='邮箱不合法')) union_activity = self.get_activity_info(act_id) coupon_dic = union_activity.get('coupon_dic', {}) all_actids = coupon_dic.keys() # 这个id是activity_union表的id res = dict() res['total_num'] = 0 res['total_amount'] = 0 res['commission_amount'] = 0 res['coupon_amount'] = 0 res['count'] = 0 res['records'] = [] try: userinfos = apcli_ex('findUserBriefsByIds', [ int(userid), ]) or [] except: raise ThirdError('获取商户信息失败') userinfos = {i.uid: i.__dict__ for i in userinfos} # 再关联下activity表的id with get_connection('qf_marketing') as db: rows = db.select('activity', fields='id, union_id', where={'union_id': act_id}) if rows: activity_ids = set() # coupon_dic2 = dict() # 增加一个变量记录下activity_id: union_id的对应关系 actid_union_dic = {} for i in rows: activity_ids.add(i['id']) # coupon_dic2.update({i['id']: coupon_dic[i['union_id']]}) actid_union_dic.update({i['id']: i['union_id']}) where = { 'xx_type': ACTIVITY_SHARE_TYPE_COUPON, 'activity_id': ('in', activity_ids), 'use_mchnt_id': userid, 'type': ('in', (RECORD_STATUS_USE, RECORD_STATUS_DESTROY)) } with get_connection_exception('qf_marketing') as conn: rows = conn.select( 'record', fields= 'amt, (total_amt - amt) as payamt, type, create_time, orig_out_sn, out_sn', where=where, other='order by create_time desc') # 先找出所有的origin_out_sn的数据,撤销交易要原单号 all_orig_out_sns = [] destory_trade = {} for i in rows: if i['type'] == 3: all_orig_out_sns.append(i['orig_out_sn']) destory_trade.update({i['orig_out_sn']: i}) rate = coupon_dic.get(int(act_id), {}).get('rate', 0) actname = coupon_dic.get(int(act_id), {}).get('title', '') shopname = userinfos.get(int(userid), {}).get('shopname', '') status = 0 if coupon_dic.get(int(act_id), {}).get( 'status', '') == 3 else 1 for i in rows: status = int(i['type']) if status == RECORD_STATUS_DESTROY: continue if i['out_sn'] in set(all_orig_out_sns): i = destory_trade.get(i['out_sn']) temp = dict() temp['actname'] = actname temp['shopname'] = shopname temp['commi_rate'] = rate temp['trade_time'] = i['create_time'].strftime( DATETIME_FMT) temp['syyn'] = str( i['orig_out_sn']) if i['orig_out_sn'] else str( i['out_sn']) temp['trade_status'] = int(i['type']) temp['trade_amount'] = i['payamt'] temp['coupon_amount'] = i['amt'] commi_amount, temp['commi_amount'] = 0, 0 if int(i['type']) == RECORD_STATUS_USE: res['total_num'] += 1 commi_amount = float( i['payamt']) * float(rate) / 100.0 / 100.0 temp['commi_amount'] = math.floor(commi_amount * 100) res['total_amount'] += i['payamt'] res['coupon_amount'] += i['amt'] res['commission_amount'] += temp['commi_amount'] res['records'].append(temp) res['status'] = status res['rate'] = rate res['actname'] = actname res['count'] = len(res['records']) if email: wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("%s" % u'抽佣明细') head_remit = (u"交易门店", u'活动名称', u"交易时间", u"交易流水号", u"交易状态", u"交易金额/元", u'抽佣比例', u"抽佣金额/元") for index, value in enumerate(head_remit): ws.write(0, index, value) if res['records']: for index, value in enumerate(res['records']): ws.write(index + 1, 0, value.get('shopname', '')) ws.write(index + 1, 1, value.get('actname', '')) ws.write(index + 1, 2, value.get('trade_time', '')) ws.write(index + 1, 3, value.get('syyn', 0)) ws.write(index + 1, 4, re_trade_status(value.get('trade_status', 0))) ws.write( index + 1, 5, float('%.2f' % (value.get('trade_amount', 0) / 100.0))) ws.write(index + 1, 6, str(value.get('commi_rate', 0)) + '%') ws.write( index + 1, 7, float('%.2f' % (value.get('commi_amount', 0) / 100.0))) sio = StringIO.StringIO() wb.save(sio) #标题 subject = unicode_to_utf8(actname) m = MailMessage(subject, '*****@*****.**', email, '') sio.seek(0) filename1 = '{}_抽佣明细.xls'.format(subject) m.append_data(sio.read(), attachname='=?utf-8?b?' + base64.b64encode(filename1) + '?=') sender = MailSender('smtp.exmail.qq.com', '*****@*****.**', 'Aa!@#$%^7') send_status = sender.send(m) if send_status: log.info('send mail success, msg:mail to {}'.format(email)) return self.write(success({})) else: log.info('send mail fail, msg:mail to {}'.format(email)) return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误")) else: start = page * pagesize end = page * pagesize + pagesize res['records'] = res['records'][start:end] return self.write(success(data=res)) except: log.warn('error :%s' % traceback.format_exc()) return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))
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("角色错误")