def wrapper(*args, **kw): ckey = '' user_id = 'DEFAULT' request_util = RequestUtil() res = False if is_check_ckey: ckey = request_util.get_ckey(request) if ckey: if auth_ckey_url: try: r_data = {'ckey': ckey, 'system': 'meeting'} ret = requests.post(url=auth_ckey_url, json=r_data) if ret.json().get('ret'): if ret.json().get('data').get('d') != r_domain: return jsonify(ret=0, message="Error domain") res = True user_id = ret.json().get('data').get('u') except (requests.RequestException or KeyError) as e: meeting_logger.error("ckey api failed : {}".format(e)) # TODO notify developer to check # res = check_ckey(ckey, user_id) res, user_id = check_ckey(ckey) except Exception as e: meeting_logger.error("ckey api failed : {}".format(e)) else: res, user_id = check_ckey(ckey) if res: return func(user_id=user_id, ckey=ckey, *args, **kw) else: meeting_logger.info("user:{user} login failed, ckey : {ckey}, \ ".format(user=user_id, ckey=ckey)) return jsonify(ret=0, message="ckey check failed") return func(user_id=user_id, ckey=ckey, *args, **kw)
def update_config(): try: args = RequestUtil.get_request_args(request) business_id = args.get('business_id', '0') supplier_id = args.get('supplier_id') operator = args.get('operator', '').strip() status = args.get('status', '1').strip() default_questions = args.get('default_questions') if not isinstance(default_questions, list): default_questions = (default_questions or '').split(",") default_questions = [ x for x in [x.strip() for x in default_questions] if len(x) ] if business_id and supplier_id: supplier_id = idEncryptor.decrypt(supplier_id) try: SupplierRobotConfig.update(business_id, supplier_id, default_questions, operator, status) return common_response(status=0, data=None, message='success') except: logger.erro( "database update_config failed business_id={},supplier={}". format(business_id, supplier_id)) else: return common_response( status=1, data=None, message=' please input business_id and supplier_id') except: logger.error("api update_config failed") logger.error(traceback.format_exc())
def get_config(): try: args = RequestUtil.get_request_args(request) business_id = args.get('business_id') supplier_id = args.get('supplier_id') if business_id and supplier_id: supplier_id = idEncryptor.decrypt(supplier_id) try: data = SupplierRobotConfig.select_dict(business_id, supplier_id) return common_response(status=0, data=data, message='success') except: logger.error( "datebase get_config business_id={},supplier_id={} failed " .format(business_id, supplier_id)) else: return common_response( status=1, data={ "business_id": business_id, "supplier_id": supplier_id }, message='please input business_id, and supplier_id') except: logger.error("api config failed") logger.error(traceback.extract_stack())
def ignore_feedback(): try: args = RequestUtil.get_request_args(request) qid = args.get('id', '') business_id = args.get('business_id', '').strip() supplier_id = args.get('supplier_id', '').strip() status = 1 operator = args.get('operator', '').strip() if business_id and supplier_id and qid: supplier_id = idEncryptor.decrypt(supplier_id) try: n = SupplierQaHistory.ignore_feedback(qid, business_id, supplier_id, status, operator) if n: return common_response(status=0, data=None, message='success') else: return common_response(status=1, data=None, message='update data failded') except: logger.error( "database ignore_feedback failed business_id={},supplier_id={},qid={}" .format(business_id, supplier_id, qid)) else: return common_response( status=1, data=None, message='please input id,business_id and supplier_id') except: logger.error("api ignore_feedback failed") logger.error(traceback.format_exc())
def get_message_queue(): try: args = RequestUtil.get_request_args(request) robot_message = args.get('robot_message') if robot_message: get_message_queue(robot_message) logger.info( "get_message_queue robot_message={}".format(robot_message)) return common_response(status=0, data=None, message='success') else: return common_response( status=1, data=None, message='please input business_id, and supplier_id') except: logger.info("get_message_queue failed") logger.error(traceback.format_exc())
def update_qa_data(): try: args = RequestUtil.get_request_args(request) qaid = args.get('id', '').strip() business_id = args.get('business_id', '').strip() supplier_id = args.get('supplier_id', '').strip() question = args.get('question') if not isinstance(question, list): question = (question or '').split(",") question = [x for x in [x.strip() for x in question] if len(x)] answer = args.get('answer', '').strip() status = args.get('status', '1').strip() operator = args.get('operator', '').strip() if business_id and supplier_id: supplier_id = idEncryptor.decrypt(supplier_id) try: n = SupplierQaData.update(qaid, business_id, supplier_id, question, answer, status, operator) if n > 0: data = SupplierQaData.select_list(business_id, supplier_id) if data: write_qa_data(business_id, supplier_id) else: delete_qa_data(business_id, supplier_id) return common_response(status=0, data=None, message='success') else: return common_response(status=1, data=None, message='update data failded') except: logger.error( "database update_qa business_id={},supplier_id={} failed". format(business_id, supplier_id)) else: return common_response( status=1, data=None, message='please input business_id and supplier_id') except: logger.error("api update_qa failed") logger.error(traceback.format_exc())
def get_qa_data_list(): try: args = RequestUtil.get_request_args(request) business_id = args.get('business_id', '0') supplier_id = args.get('supplier_id') if business_id and supplier_id: supplier_id = idEncryptor.decrypt(supplier_id) try: data = SupplierQaData.select_list(business_id, supplier_id) return common_response(status=0, data=data, message='success') except: logger.error( "database get qa_{business_id}_{supplier_id} list failed". format(business_id=business_id, supplier_id=supplier_id)) else: return common_response( status=1, data=None, message=' please input business_id and supplier_id') except: logger.error("api qalist failed ") logger.error(traceback.format_exc())
def update_feedback(): try: args = RequestUtil.get_request_args(request) qid = args.get('id', '') business_id = args.get('business_id', '').strip() supplier_id = args.get('supplier_id', '').strip() answer = args.get('answer', '').strip() status = 1 intent_type = args.get("intent_type", 0) operator = args.get('operator', '').strip() if business_id and supplier_id and qid and intent_type and answer: supplier_id = idEncryptor.decrypt(supplier_id) try: n = SupplierQaHistory.update_feedback(qid, business_id, supplier_id, answer, intent_type, status, operator) print(n) if n: return common_response(status=0, data=None, message='success') else: return common_response(status=1, data=None, message='update data failded') except: logger.error( "database update_feedback failed business_id={},supplier_id={},qid={}" .format(business_id, supplier_id, qid)) else: return common_response( status=1, data=None, message='please input business_id and supplier_id') except: logger.error("api update_feedback failed") logger.error(traceback.format_exc())
def get_feedback(): try: args = RequestUtil.get_request_args(request) business_id = args.get('business_id', '') supplier_id = args.get('supplier_id', '') start_time = args.get('start_time', '') end_time = args.get('end_time', '') offset = int(args.get("offset", 0)) limit = int(args.get("limit", 20)) intent_type = args.get('intent_type', 0) status = args.get('status', 0) is_worked = args.get('is_worked', '') if business_id and supplier_id: supplier_id = idEncryptor.decrypt(supplier_id) try: data, total = SupplierQaHistory.select_feedback_dict( limit, offset, start_time, end_time, intent_type, status, is_worked, business_id, supplier_id) count = total.get("count") return common_response(status=0, data=data, count=count, message='success') except: logger.error( "database select_feedback_dict failed business_id={}, supplier_id={}" .format(business_id, supplier_id)) else: return common_response( status=1, data=None, count=0, message='please input business_id, and supplier_id') except: logger.error("api feedback failed") logger.error(traceback.format_exc())
if data == key: field_value = result[field_names[key]] request_data[key] = str(field_value) elif pre_field["scope"] == "variable": for data in request_data: field_names = pre_field["field"] for key in field_names: if data == key: field_value = result[field_names[key]] passport = re.search("passport=(.*)", str(field_value)).group(1) request_data[key] = passport if "access_token" in request_data and request_data.get( "access_token") == "": request_data['access_token'] = self.access_token req = RequestUtil() sign = GetDataSign().sign_body(req_url, request_data, self.api_host_obj["api_key"]) request_data["sign"] = sign print("url=====", req_url) req_url = self.api_host_obj["dict_value"] + case["url"] response = req.customRequest(req_url, method, headers=headers, param=request_data) return response def assertResponse(self, case, response): """ 断言响应内容,更新用例执行情况 """
def yes_no_api(): try: args = RequestUtil.get_request_args(request) is_worked = args.get("is_worked") question = args.get("question", "") answer = args.get("answer", "") qid = args.get("id", '') business_id = args.get('business_id', '') supplier_id = args.get('supplier_id', '') m_from = args.get("m_from", "") realfrom = args.get("realfrom", "") realto = args.get("realto", "") m_to = args.get("m_to", "") field = '' if qid == None: try: qid = SupplierQaHistory.select_by_question(question, answer).get("id") except: logger.error("database select_qid_by_question failed") abscount = SupplierQaHistory.get_abscount(qid) worked_status = SupplierQaHistory.get_worked_status(qid) data = {"id": qid, "is_worked": worked_status, "count": abscount} if abscount == 0: if qid and is_worked and business_id and supplier_id and m_from and realfrom and realto and m_to: if is_worked == '1': field = "right_count" elif is_worked == '0': field = "wrong_count" n1 = SupplierQaHistory.add_right_wrong(qid, field, is_worked, business_id, supplier_id) n2 = SupplierQaHistory.update_yn(qid, business_id, supplier_id, is_worked) data = {"id": qid, "is_worked": is_worked, "count": abscount} if n1 > 0 and n2 > 0: SendMessageUtil.send_yn_answer(m_from=m_from, real_from=realfrom, m_to=m_to, real_to=realto, is_worked=is_worked) return common_response(status=0, data=data, message='success') else: return common_response(status=1, data=data, message='update data failded') else: return common_response( status=1, data=None, message= 'failded,please input qid ,is_worked, business_id, supplier_id' ) else: return common_response(status=1, data=data, message='You have already operated!') except: logger.error("api yn_feedback failed") logger.error(traceback.format_exc())
def pay_success(): current_args = RequestUtil.get_request_args(request) logger = configure_logger("pay_success") logger.info("支付回调接口参数:" + json.dumps(current_args)) # 测试的时候暂不验签 pa = PayAlipay() status = pa.check_sign(**current_args) if not status: logger.info("验签失败") return "fail" # 商家的appid app_id = current_args['app_id'] if app_id != pay_config['appId']: logger.info("appid校验失败") return "fail" # 如果不是支付回调 直接返回fail if current_args['msg_method'] != 'alipay.fund.trans.order.changed': logger.info("msg_method 不是 alipay.fund.trans.order.changed") return "fail" current_args = json.loads(current_args['biz_content']) ''' { "action_type": "FINISH", "biz_scene": "PERSONAL_PAY", "order_id": "20190912110075000006740023648562", #支付宝系统的单据唯一ID "origin_interface": "alipay.fund.trans.app.pay", #支付的接口 "out_biz_no": "qt_20190912162507_298",#商户端的唯一订单号 "pay_date": "2019-09-12 16:25:15", "pay_fund_order_id": "20190912110075001506740023416000",#支付宝支付资金流水号(转账成功时才返回) "product_code": "STD_RED_PACKET", "status": "SUCCESS", "trans_amount": "0.01" } ''' # 只有成功的 才进行下一部 if current_args['status'] != 'SUCCESS': logger.info("本次status:%s ,直接返回success" % current_args['status']) return "success" # 支付宝交易号 pay_order_no = current_args['order_id'] pay_order_line = current_args['pay_fund_order_id'] # 商家唯一订单号 out_order_no = current_args['out_biz_no'] # 支付金额 amount = float(current_args['trans_amount']) # 付款时间 gmt_payment = current_args['pay_date'] red_instance = RedEnvelopeSql() conn = red_instance.get_pg_conn() pg_cursor = red_instance.get_pg_dict_cursor() sql = "Select id,state,order_type,credit from public.order_list where order_no=%s" try: pg_cursor.execute(sql, (out_order_no,)) row = pg_cursor.fetchone() conn.commit() except Exception as e: pg_cursor.close() logger.info("订单号order_no为:%s,数据库执行失败" % out_order_no) return "fail" if not row: pg_cursor.close() logger.info("订单未查找成功,订单号order_no为%s" % out_order_no) return "fail" if row['state'] != 'unpay': pg_cursor.close() logger.info("订单未查找成功,订单号order_no为%s;订单状态为%s,不在进行操作" % (out_order_no, row['state'])) if row['state'] == 'pay': return "success" return "fail" if row['order_type'] != 'red_envelope' and row['order_type'] != 'all_average': pg_cursor.close() logger.info("订单未查找成功,订单号order_no为%s;订单状态为%s,order_type:%s;直接退出" % (out_order_no, row['order_type'])) return "fail" if amount != float(row['credit']): pg_cursor.close() logger.info("支付金额与订单金额不符,支付金额 %s VS 订单金额 %s" % (amount, row['credit'])) return "fail" # 修改订单状态 # auth_no:pay_order_no # out_order_no:order_no # operation_id:pay_order_line # out_request_no:order_line # 插入订单流水 try: order_sql = """Update public.order_list set state='pay', pay_order_no=%(pay_order_no)s,pay_order_line=%(pay_order_line)s, pay_time=%(gmt_payment)s where order_no=%(out_order_no)s and state='unpay'""" pg_cursor.execute(order_sql, {"pay_order_no": pay_order_no, "pay_order_line": pay_order_line, "gmt_payment": gmt_payment, "out_order_no": out_order_no}) if 0 == parse_psycopg2_statusmessage(pg_cursor.statusmessage): pg_cursor.close() logger.info("订单未查找成功,订单号order_no为%s;更新失败" % out_order_no) return "fail" conn.commit() except Exception as e: pg_cursor.close() logger.info("订单号order_no为%s;更新成为pay状态失败" % out_order_no) return "fail" pay_order = PayOrder(id=row['id']) order_trace_result = pay_order.insert_order_trace(order_line=out_order_no) # 生成小红包 if row['order_type'] == 'red_envelope': try: rel = RedEnvelope(order_id=row['id']) except Exception as e: logger.info("订单号order_no为%s;红包不存在;error_code:%s" % (out_order_no, str(e))) return "fail" ret = rel.generate_sub_redenv() if not ret['ret']: return jsonify({"ret": False, "error_msg": "红包生成失败"}) # 发送红包消息 params = {"msg_type": "pay_success", "id": rel.id, "group_id": rel.group_chat_id[0]} rel.add_qtalk_message_queue(**params) elif row['order_type'] == 'all_average': try: aas = AllAverageSql() ret = aas.pay_success_callback(order_no=out_order_no, ) if not ret: print("aa状态数据库更新失败") return 'failed' pa = PayAlipay() payee_info = aas.get_aa_payee(order_no=out_order_no) print("获取 支付者信息 {}".format(payee_info)) order_line = order_trace_result['data']['order_line'] print("准备支付") print("...original order id: {}".format(pay_order.get_pay_order_no())) print("...order_no: {}".format(order_line)) print("...payee_info: {}".format(payee_info)) disburse_result = pa.disburse( order_no=str(order_line), original_order_id=str(pay_order.get_pay_order_no()), amount=float(row['credit']), payee_logon_id=str(payee_info), title=pay_config['all_average']['grab_bill_title'] ) print("支付返回 {}".format(disburse_result)) if not disburse_result['ret']: print("支付失败, 没有拿到返回, 结果 {}".format(disburse_result)) # pg_cursor_normal.execute("rollback") # message = message_prefix + "\n红包领取转账失败;\n返回结果:%s" % (json.dumps(disburse_result, ensure_ascii=False)) # 更新order_trace表 order_trace_result = pay_order.insert_order_trace(**{ "order_line": order_line, "op": "return_balance", "credit": float(row['credit']), "pay_order_no": "", "pay_status": "re_balance_faild", 'trace_comments': disburse_result }) else: order_trace_result = pay_order.insert_order_trace(**{ "order_line": order_line, "op": "return_balance", "credit": float(row['credit']), "pay_order_no": disburse_result['order_id'], "pay_status": "re_balance_ok", 'trace_comments': disburse_result }) if order_trace_result['ret'] != 1: print("插入失败") print("\n红包调用支付宝成功,插入order_trace失败,order_line:%s;请检order_list日志" % order_line) except Exception as e: print(e) print(traceback.print_exc()) print("aa状态更新失败") return "failed" return "success"
def wrapper(*args, **kw): ckey = '' user_id = 'DEFAULT' user = '' request_util = RequestUtil() res = False __args = request_util.get_request_args(request) user_id = __args.get('qtalkId', 'UNKOWN') user_domain = None if '@' in user_id: _user = user_id.split('@') user = _user[0] user_domain = _user[1] else: user = user_id if isinstance(r_domain, str): user_domain = r_domain user_id = user_id + '@' + user_domain if user_id in [ 'guanghui.yang@ejabhost1', 'jingyu.he@ejabhost1', 'chaos.dong@ejabhost1', 'binz.zhang@ejabhost1' ]: return func(user_id=user_id, args=__args, *args, **kw) elif is_check_ckey: ckey = request_util.get_ckey(request) if ckey: if auth_ckey_url: try: r_data = {'ckey': ckey, 'system': 'search'} ret = requests.post(url=auth_ckey_url, json=r_data) """{ "ret": true, "errcode": 0, "errmsg": "", "data": { "d": "qtalk.test.org", "u": "aaa.bb" } }""" if ret.json().get('ret') and ret.json().get( 'data', {}).get( 'u', '') + '@' + ret.json().get( 'data', {}).get('d', '') == user_id: if user_domain and ret.json().get('data').get( 'd') != user_domain: return jsonify(ret=False, errcode=500, msg="Error domain") # TODO remove this after domain check is soon needless elif not user_domain: user_domain = ret.json().get('data', {}).get('d') res = True # user = user_id + '@' + user_domain user = user + '@' + user_domain else: search_logger.error( "ckey api check failed : ret {} u {}".format( ret.json().get('ret'), user_id)) except (requests.RequestException or KeyError) as e: search_logger.error("ckey api failed : {}".format(e)) # TODO notify developer to check res, user = check_ckey(ckey) except Exception as e: search_logger.exception( "ckey api failed : {}".format(e)) else: res, user = check_ckey(ckey) if res: return func(user_id=user, args=__args, *args, **kw) else: search_logger.info("user:{user} login failed, ckey : {ckey}, \ ".format(user=user_id, ckey=ckey)) return jsonify(ret=False, errcode=0, message="ckey check failed") return func(user_id=user_id, args=__args, *args, **kw)
def get_request_need_args(**current_params): current_args = RequestUtil.get_request_args(request) has_var = current_params.keys() & current_args.keys() for pk in has_var: current_params[pk] = current_args[pk] return current_params
def main(): global ip, s_args args = RequestUtil.get_request_args(request) if not s_args: s_args = args try: username = args["key"].strip() user_id = args["qtalkId"].strip() except KeyError: return jsonify(ret=0, message="wrong parameters") if len(username) < 2: return jsonify(ret=0, message="length of key should greater than two") ckey = args.get("cKey", "") group_id = args.get("groupid", "") offset = int(args.get("start", 0)) limit = int(args.get("length", 5)) if is_check_ckey: res, user = check_ckey(ckey, user_id) if not res: logger.error('{} login FAILED. ckey : {}'.format(user_id, ckey)) return jsonify(ret=0, message="ckey failed") request_ip = request.remote_addr if ip != request_ip: ip = request_ip logger.info(ip + ' : {}'.format(json.dumps(s_args))) s_args = args result = list() data_array = list() userlib = UserLib() if group_id: if group_id == userGroup: user_array = userlib.search_user(username, user_id, limit + 1, offset) has_more, user_array = get_hasmore(user_array, limit) if user_array: result = make_result(label='联系人列表', groupid=userGroup, group_priority=0, todo_type=QTALK_OPEN_USER_VCARD, portrait=single_portrait, hasmore=has_more, info=user_array) elif group_id == groupGroup: group_array = userlib.search_group(user_id, username, limit + 1, offset) has_more, group_array = get_hasmore(group_array, limit) if group_array: result = make_result(label='群组列表', groupid=groupGroup, group_priority=0, todo_type=QTALK_OPEN_GROUP_VCARD, portrait=muc_portrait, hasmore=has_more, info=group_array) elif group_id == commonGroup: commonmuc_array = userlib.search_group_by_single( user_id, username, limit + 1, offset) has_more, commonmuc_array = get_hasmore(commonmuc_array, limit) if commonmuc_array: result = make_result(label='共同群组', groupid=commonGroup, group_priority=0, todo_type=QTALK_OPEN_GROUP_VCARD, portrait=muc_portrait, hasmore=has_more, info=commonmuc_array) else: return jsonify(errcode=500, msg='无法预期的groupId') userlib.conn.close() return jsonify(errcode=0, msg='', data=result) else: user_array = userlib.search_user(username, user_id, limit + 1, offset) group_array = userlib.search_group(user_id, username, limit + 1, offset) commonmuc_array = userlib.search_group_by_single( user_id, username, limit + 1, offset) if user_array: has_more, user_array = get_hasmore(array=user_array, limit=limit) result = make_result(label='联系人列表', groupid=userGroup, group_priority=0, todo_type=QTALK_OPEN_USER_VCARD, portrait=single_portrait, hasmore=has_more, info=user_array) data_array.append(result) if group_array: has_more, group_array = get_hasmore(array=group_array, limit=limit) result = make_result(label='群组列表', groupid=groupGroup, group_priority=0, todo_type=QTALK_OPEN_GROUP_VCARD, portrait=muc_portrait, hasmore=has_more, info=group_array) data_array.append(result) if commonmuc_array: has_more, commonmuc_array = get_hasmore(commonmuc_array, limit) result = make_result(label='共同群组', groupid=commonGroup, group_priority=0, todo_type=QTALK_OPEN_GROUP_VCARD, portrait=muc_portrait, hasmore=has_more, info=commonmuc_array) data_array.append(result) userlib.conn.close() return jsonify(errcode=0, msg='', data=data_array)