def get_regions(city, province, adcode): '''通过qudao_api获取商圈''' client = ThriftClient(config.QUDAO_SERVERS, QudaoServer, framed=True) req_data = RegionQueryArg( status=[ 0, ], audit_status=[ 2, ], query_meta=QueryMeta(offset=0, count=10000), ) if city: req_data.city = city elif province: req_data.province = province elif adcode: area = None area_no = adcode[:2] with get_connection('qf_mis') as db: area = db.select_one('tools_area', where={'area_no': area_no}) if area: req_data.province = unicode_to_utf8(area['area_name']) region_ids = client.region_query(req_data) if not region_ids: return [] return client.region_get(region_ids)
def GET(self): userid = int(self.user.userid) ret = {} userinfo = apcli('findUserByid', userid).__dict__ ret['shopinfo'] = {} ret['shopinfo']['shopname'] = userinfo.get('shopname') ret['shopinfo']['city'] = userinfo.get('city') ret['shopinfo']['province'] = userinfo.get('province') ret['shopinfo']['telephone'] = userinfo.get('telephone') ret['shopinfo']['address'] = userinfo.get('address') # 同步审核后的商户名称 apply_info = {} with get_connection('qf_mis') as db: apply_info = db.select_one(table='merchant_change_apply', where={ 'userid': userid, 'changetype': 2, 'status': 3 }, fields='applyjson', other='order by modifytime desc') val = {} if apply_info: apply_dict = json.loads(apply_info['applyjson']) val['shopname'] = unicode_to_utf8( apply_dict['change_apply']['nickname']) if val['shopname'] != ret['shopinfo']['shopname']: apcli_ex('updateUser', int(userinfo['uid']), User(**val)) ret['shopinfo']['shopname'] = val['shopname'] return success(ret)
def POST(self): userid = self.get_userid_login_or_ip() d = self.validator.data update_data = {} if d['status'] not in [None, 0, 1]: raise ParamError('状态非法') with get_connection_exception('qf_core') as db: opuser = db.select_one(table='opuser', where={ 'userid': int(userid), 'opuid': int(d['opuid']) }) or {} if not opuser: raise UserError('操作员不存在') fields = ['mobile', 'status', 'opname', 'password'] for field in fields: if d[field] is not None: if field == 'password': if not check_password(d['password'], opuser['password']): update_data[field] = enc_password(d['password']) elif d[field] != unicode_to_utf8(opuser[field]): update_data[field] = d[field] if not update_data: return success({}) with get_connection('qf_core') as db: db.update('opuser', update_data, where={ 'userid': userid, 'opuid': int(d['opuid']) }) # 如果更新了状态,则剔除操作员 if update_data.get('status') == 0 or update_data.get('password'): kick_user(userid, int(d['opuid']), mode='opuser') return success({})
def POST(self): try: params = self.req.inputjson() device_id = params.get('device_id', '') mchnt_id = params.get('mch_id', '') content = params.get('content', '') receiptId = params.get('receiptId', '') sign = params.get('sign', '') filter = [ 'device_id', 'mch_id', 'content', 'receiptId', 'nonce_str' ] filter_dict = {k: v for k, v in params.items() if k in filter} sort_dict = sorted(filter_dict.iteritems(), key=lambda d: d[0]) string = '&'.join([ '{0}={1}'.format(k, unicode_to_utf8(v)) for (k, v) in sort_dict if v not in ['', None] ]) string = string + '&key={key}'.format(key=config.RECEIPT_DATA_KEY) sign_string = hashlib.md5(string).hexdigest().upper() now = int(time.time()) if sign_string == sign: a = self.db.insert('receipt_data', values={ 'device_id': device_id, 'mchnt_id': mchnt_id, 'content': content, 'receipt_id': receiptId, 'ctime': now, 'utime': now }) return self.write(json.dumps({'code': 'SUCCESS', 'msg': '成功'})) else: return self.write(json.dumps({'code': 'FAIL', 'msg': '签名失败'})) except Exception, e: log.warn('error :%s' % traceback.format_exc()) return self.write(json.dumps({'code': 'FAIL', 'msg': '服务错误'}))
def GET(self): userid = int(self.user.userid) price = get_qd_conf_value(mode='msg_price', key='ext', groupid=self.get_groupid()) template = config.MESSAGE_TEMPLATE user = apcli_ex('findUserBriefById', userid) log.info(user) shopname = user.shopname if user else '' log.info(shopname) coupon = self.coupon_actvs(userid) card = self.card_actv() prepaid = self.prepaid_actv() vip_template = [] common_temp = [] if coupon: coupon_content = template['coupon'].format( max(coupon) / 100.0, shopname) vip_template.append({ 'title': '红包模板', 'content': coupon_content, 'type': 1 }) if card: exchange_pt = unicode_to_utf8(card.get('exchange_pt', '')) goods_name = unicode_to_utf8(card.get('goods_name', '')) card_content = template['card'].format(exchange_pt, goods_name, shopname) vip_template.append({ 'content': card_content, 'title': '集点模板', 'type': 2 }) if prepaid: card_content = template['prepaid'].format(prepaid / 100.0, shopname) vip_template.append({ 'content': card_content, 'title': '储值模板', 'type': 3 }) for i in template['common_template']: content = i['content'].format(shopname) title = i['title'] common_temp.append({ 'title': title, 'content': content, 'type': i['type'] }) with get_connection('qf_mchnt') as db: total = db.select_one('member_tag', where={ 'userid': userid, 'submit': ('>=', 1) }, fields='count(1) as num')['num'] return self.write( success({ 'now': time.strftime(DATETIME_FMT), 'vip_temp': vip_template, 'common_temp': common_temp, 'price': price if price else config.DEFAULT_PRICE, 'total_auth': total, 'send_total': total, 'items': config.ITEM_1 if total else config.ITEM_0 }))
def send_message(p): where = {'id': int(p.get('id') or 0)} with get_connection_exception('qf_mchnt') as db: messages = db.select_one(table='messages', where=where) if not messages: raise ParamError('订单不存在') content = unicode_to_utf8(messages.get('content', '')) + ' 回复TD退订' # s_content = content[0] + ' 回复TD退订【'+ content[1] userid = p['userid'] with get_connection('qf_mchnt') as db: members = db.select_join(table1='member m', table2='member_tag mt', on={ 'm.userid': 'mt.userid', 'm.customer_id': 'mt.customer_id' }, where={ 'm.userid': userid, 'mt.userid': userid, 'mt.submit': ('>', 0), }, fields=('m.customer_id, m.userid')) cids = [i['customer_id'] for i in members] profiles = {} 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()) mobiles = [] for m in members: customer_id = m['customer_id'] info = profiles.get(customer_id, {}) mobile = info.get('mobile', '') if mobile and re.match(MOBILE_PATTERN, mobile): mobiles.append(mobile) if mobiles: try: r, respmsg = PreSms(config.PRESMS_SERVERS).sendSms( mobile=mobiles, content=content, tag=config.PRESMS_MARKETING_CONFIG['tag'], source=config.PRESMS_MARKETING_CONFIG['source'], target=config.PRESMS_MARKETING_CONFIG['target']) if not r: log.info('调起发送短信服务失败:%s' % respmsg) else: log.info('update messages') with get_connection_exception('qf_mchnt') as db: where = { 'id': int(p.get('id') or 0), } data = { 'utime': int(time.time()), 'out_sn': p['out_sn'], 'status': 1 } updated = db.update('messages', data, where) except Exception, e: log.warn(traceback.format_exc())
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"服务错误"))