def isFlagExist(flag): try: print(Redis.read(flag)) openid = Redis.read(flag) return json.loads(Redis.read(openid)) except Exception as e: return None
def handle_deltask(): """ 任务软删除 :return: json """ res = ResMsg() req = request.get_json(force=True) taskid= int(req.get("id", 1)) status= int(req.get("status", 3)) update_dict = { "status": status, } update_dict_ready = helpers.rmnullkeys( update_dict ) db.session.query(EtTask).filter(EtTask.id == taskid).update(update_dict_ready) try: db.session.commit() Redis.delete(task_info_key) Redis.delete(task_detail_key+str(taskid)) res_data= dict() res.update(code=ResponseCode.Success, data=res_data, msg=f'任务删除成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={},msg=f'修改失败,数据异常{why}') return res.data
def handle_configs(): """ 获取系统信息接口 :return: json """ res = ResMsg() id = request.args.get("id", 1) sysid = 1 sys_configs = db.session.query(EtGlobalConfig).filter( EtGlobalConfig.id == sysid).first() res_data = dict() if sys_configs: res_data['data'] = helpers.model_to_dict(sys_configs) # logger.error(Redis.hgetall(redis_key_sys)) if Redis.hgetall(redis_key_sys) == {}: del res_data['data']['update_time'] cache_data = helpers.rmnullkeys(res_data['data']) logger.error(res_data['data']) ret = Redis.hmset(redis_key_sys, cache_data) logger.error(ret) res.update(code=ResponseCode.Success, data=res_data, msg='系统信息获取成功') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='系统信息数据异常') return res.data
def handle_edituser(): """ 用户信息修改接口 :return: json """ res = ResMsg() req = request.get_json(force=True) memberid = req.get("id") status = req.get("status") username = req.get("username") update_dict = { "name": username, "status": status, } update_dict_ready = helpers.rmnullkeys(update_dict) user = db.session.query(EtMember).filter(EtMember.id == memberid).first() if user: db.session.query(EtMember).filter(EtMember.id == memberid).update(update_dict_ready) try: db.session.commit() Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) res.update(code=ResponseCode.Success, data={}, msg='修改成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'修改失败,请稍后再试{why}') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='修改失败,请稍后再试') return res.data
def test_redis_write(): """ 测试redis写入 """ # 写入 Redis.write("test_key", "test_value", 60) return "ok"
def handle_verifytask(): """ 新增任务审核 :return: json """ res = ResMsg() req = request.get_json(force=True) taskid= int(req.get("id", 1)) status= int(req.get("status", 2)) update_dict = { "status": status, "check_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) } update_dict_ready = helpers.rmnullkeys( update_dict ) db.session.query(EtTask).filter(EtTask.id == taskid).update(update_dict_ready) try: db.session.commit() Redis.delete(task_info_key) Redis.delete(task_detail_key+str(taskid)) res_data= dict() res.update(code=ResponseCode.Success, data=res_data, msg=f'任务状态变更成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={},msg=f'修改失败,数据异常{why}') return res.data
def handle_drpconfig_edit(): """ 分销设置修改接口 :return: json """ res = ResMsg() req = request.get_json(force=True) now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) sysid = 1 drp_layers = req.get("drp_layers", 1) profit_percentage = req.get("profit_percentage", '') need_setreal = req.get("need_setreal", 1) daily_max = int(req.get("daily_max", 1)) handling_fee = req.get("handling_fee", 1) min_money = int(req.get("min_money", 1)) withdrawal_condition = req.get("withdrawal_condition", '') daily_withdrawal = req.get("daily_withdrawal", 9) update_dict = { "drp_layers": drp_layers, "profit_percentage": profit_percentage, "need_setreal": need_setreal, "daily_max": daily_max, "handling_fee": handling_fee, "min_money": min_money, "withdrawal_condition": withdrawal_condition, "daily_withdrawal": daily_withdrawal, "update_time": now_timestr } update_dict_ready = helpers.rmnullkeys(update_dict) drpconfigs = db.session.query(EtDrpConfig).filter( EtDrpConfig.id == sysid).first() if drpconfigs: db.session.query(EtDrpConfig).filter( EtDrpConfig.id == sysid).update(update_dict_ready) try: db.session.commit() Redis.delete(redis_key_drp) r_data = helpers.model_to_dict(drpconfigs) del r_data['update_time'] Redis.hmset(redis_key_drp, r_data) res.update(code=ResponseCode.Success, data={}, msg=f'分销设置配置成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'修改失败,请稍后再试{why}') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='修改失败,请稍后再试') return res.data
def handle_gen_blacklist(): """ 设置黑名单用户 blacklists列表 到redis集合 :@param: phone 如果设置phone,则在set中新增一个phone :return: json """ res = ResMsg() phone = request.args.get("phone", '') if phone: p.sadd(blacklist_key, phone) blacklist = db.session.execute( "SELECT phone FROM et_blacklists").fetchall() counts = db.session.execute("SELECT count(*) FROM et_blacklists").first() res_data = dict() blacklists = [{key: value for (key, value) in row.items()} for row in blacklist] # pipeline multi-set r = Redis._get_r() with r.pipeline(transaction=False) as p: for value in blacklists: p.sadd(blacklist_key, value['phone']) p.execute() Redis.expire(blacklist_key, 60 * 60 * 10 * 90) if blacklist: # res_data['list'] = blacklists res_data['length'] = counts[0] res.update(code=ResponseCode.Success, data=res_data, msg='app用户blacklist列表获取成功') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='app用户blacklist数据为空or异常') return res.data
def test_get_verification_code(): """ 获取手机验证码 :return: """ now = datetime.now() res = ResMsg() category = request.args.get("category", None) # category 参数如下: # authentication: 身份验证 # login_confirmation: 登陆验证 # login_exception: 登陆异常 # user_registration: 用户注册 # change_password: 修改密码 # information_change: 信息修改 phone = request.args.get('phone', None) # 验证手机号码正确性 re_phone = PhoneTool.check_phone(phone) if phone is None or re_phone is None: res.update(code=ResponseCode.MobileNumberError) return res.data if category is None: res.update(code=ResponseCode.InvalidParameter) return res.data try: # 获取手机验证码设置时间 flag = Redis.hget(re_phone, 'expire_time') if flag is not None: flag = datetime.strptime(flag, '%Y-%m-%d %H:%M:%S') # 判断是否重复操作 if (flag - now).total_seconds() < 60: res.update(code=ResponseCode.FrequentOperation) return res.data # 获取随机验证码 code = "".join([str(random.randint(0, 9)) for _ in range(6)]) template_param = {"code": code} # 发送验证码 sms = SendSms(phone=re_phone, category=category, template_param=template_param) sms.send_sms() # 将验证码存入redis,方便接下来的验证 Redis.hset(re_phone, "code", code) # 设置重复操作屏障 Redis.hset(re_phone, "expire_time", (now + timedelta(minutes=1)).strftime('%Y-%m-%d %H:%M:%S')) # 设置验证码过去时间 Redis.expire(re_phone, 60 * 3) return res.data except Exception as e: logger.exception(e) res.update(code=ResponseCode.Fail) return res.data
def eventSubscribe(msg): Redis.write(msg.scene_id, msg.source) # 创建 access_token access_token = Auth.generate_access_token(user_id=msg.source) if access_token: access_token = access_token.decode('utf-8') logger.debug("用户初次订阅行为,flag为: ", msg.scene_id) # 查询用户详细信息 user = client.user.get(msg.source) # 开始用户登陆或注册 user_login = wx_login_or_register(user) # 缓存用户信息 Redis.write( msg.source, json.dumps( dict(user_id=user_login['id'], access_token=access_token, headimgurl=user['headimgurl'], nickname=user['nickname'], admin=user_login['admin'])))
def eventscan(msg): Redis.write(msg.scene_id, msg.source) # 创建 access_token access_token = Auth.generate_access_token(user_id=msg.source) if access_token: access_token = access_token.decode('utf-8') logger.debug("已订阅用户扫描行为,flag为: ", msg.scene_id) # 查询用户详细信息 client = C_WeChatClient._get_wechatclient() user = client.user.get(msg.source) # 开始用户登陆或注册 user_login = wx_login_or_register(user) # 缓存用户信息 Redis.write( msg.source, json.dumps( dict(user_id=user_login['id'], access_token=access_token, headimgurl=user['headimgurl'], nickname=user['nickname'], admin=user_login['admin'])))
def handle_drpconfigs(): """ 获取系统分销配置信息接口 :return: json """ res = ResMsg() sysid = 1 drp_configs = db.session.query(EtDrpConfig).filter( EtDrpConfig.id == sysid).first() res_data = dict() if drp_configs: res_data['data'] = helpers.model_to_dict(drp_configs) del res_data['data']['update_time'] Redis.hmset(redis_key_drp, res_data['data']) res.update(code=ResponseCode.Success, data=res_data, msg=f'分销信息获取成功') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='分销信息数据异常') return res.data
def handle_task_order_stat(): """ 获取每个订单的二维码推广效果数据 :return: json """ res = ResMsg() order_id = request.args.get("id") res_data = dict() task_order = db.session.query(EtTaskOrder).filter( EtTaskOrder.id == order_id).first() if task_order: task_order_dict = dict(helpers.model_to_dict(task_order)) task_id = task_order_dict['task_id'] member_id = task_order_dict['member_id'] ipcounts_redis_key = f'enterip_from_task_{member_id}_{task_id}' try: stats = Redis.zrange(ipcounts_redis_key, 0, -1, desc=True, withscores=True) res_data['stats_list'] = stats res_data['stats_len'] = len(stats) res_data['order_info'] = task_order_dict res.update(code=ResponseCode.Success, data=res_data, msg=f'数据获取成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'二维码数据异常{why}') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='订单数据异常') return res.data
def handle_copytask(): """ 复制一条任务 :return: json """ res = ResMsg() taskid = request.args.get("id") res_data = dict() task = db.session.query(EtTask).filter(EtTask.id == taskid).first() if task: task_dict = dict(helpers.model_to_dict(task)) del task_dict["id"] copy_task = EtTask(**task_dict) copy_task.count_tasks = 0 copy_task.edit_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) db.session.add(copy_task) try: db.session.commit() Redis.delete(task_info_key) Redis.delete(task_detail_key + str(taskid)) Redis.delete(tasks_high_info_key) res_data = dict() res.update(code=ResponseCode.Success, data=res_data, msg=f'复制任务成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'任务数据异常{why}') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='任务数据异常') return res.data
def auto_handle_wd(app_context, wd_id: int, member_id: int, status: int = 2): with app_context: res = {} verify_log = '系统自动发放' account_name = 'system' now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) verify_orders = db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == wd_id, EtMemberWithdrawal.member_id == member_id).first() if not verify_orders: res.update(code=ResponseCode.Success, data={}, msg=f'数据异常') return res if verify_orders.pay_status == 3: res.update( dict(code=ResponseCode.Success, data={}, msg=f'该单已发放无法再次提现')) return res # if verify_orders.pay_status==2: # res.update(dict(code=ResponseCode.Success, data={}, # msg=f'正在支付走账')) # return res user = db.session.query( EtMember.id, EtMember.nickname, EtMember.status, EtMember.m_class, EtMember.realname, EtMember.mobile, EtMember.IIUV, EtMember.balance, EtMember.balance_version, EtMember.setreal, EtMember.alipayid).filter( EtMember.id == member_id).first() if not user: res.update( dict(code=ResponseCode.Success, data={}, msg=f'用户信息异常')) return res user_info = (dict(zip(user.keys(), user))) pay_status = 2 if user_info['status'] == 2: verify_log = '账号违规,无法发放提现' pay_status = 4 verify = 1 status = 1 update_dict = { "verify": status, "verify_log": verify_log, "account": account_name, "check_time": now_timestr, "pay_status": pay_status } update_dict_ready = helpers.rmnullkeys(update_dict) db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == wd_id).update(update_dict_ready) res_data = dict() ret = '' try: if user_info['status'] == 2: # back balace to member drp_config = Redis.hgetall(redis_key_drp) handling_fee_s = drp_config[b'handling_fee'] handling_fee = float( str(handling_fee_s, encoding="utf-8")) add_balance = 0 if handling_fee == 0: add_balance = verify_orders.amounts else: handling_fee = (1 - float(handling_fee) / 100) add_balance = round( verify_orders.amounts / handling_fee, 2) if verify_orders.origin_amount: add_balance = verify_orders.origin_amount user_update_dict = { "balance": user_info['balance'] + add_balance * 100, "balance_version": int(time.time()) } db.session.query(EtMember).filter( EtMember.id == mid, EtMember.balance_version == user_info['balance_version']).update( user_update_dict) db.session.commit() # verify pass go alipay ret = async_alipay_service.delay( serial_number=wd_id, alipay_account=user_info['alipayid'], real_name=user_info['realname'], pay_amount=verify_orders.amounts, mid=member_id) res.update(code=ResponseCode.Success, data=res_data, msg=f'提现审核成功,系统将发放收益到用户收款账户,请留意支付返回消息') return res except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'用户提现订单审核失败,数据异常{why}') return res
def handle_orders_lists(): """ 流水统计报表 """ res = ResMsg() now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) page_index = int(request.args.get("page", 1)) page_size = int(request.args.get("limit", 10)) date = int(request.args.get("date", 1)) start_time = request.args.get("tstart", '') end_time = request.args.get("end", '') member_id = request.args.get("member_id", '') task_id = request.args.get("task_id", '') task_order_id = request.args.get("task_order_id", '') nickname = request.args.get("nickname", '') mobile = request.args.get("mobile", '') IIUV = request.args.get("IIUV", '') realname = request.args.get("realname", '') cond_by = '' if mobile: cond_by = f' WHERE m.mobile={mobile} ' query_dict = { "member_id": int(member_id) if member_id else None, "task_id": int(task_id) if task_id else None, "task_order_id": int(task_order_id) if task_order_id else None, } filters = helpers.rmnullkeys(query_dict) flatten_filters = ' AND '.join("{!s}={!r}".format(key, val) for (key, val) in filters.items()) p_i, p_num = (page_index - 1) * page_size, page_size where_cond = '' if flatten_filters: where_cond = f" AND {flatten_filters} " if start_time and end_time: where_cond += f" AND add_time>'{start_time}' AND add_time<='{end_time}' " else: if start_time and end_time: where_cond = f" AND add_time>'{start_time}' AND add_time<='{end_time}' " fetch_columns = "e.id,e.add_time,t.name AS task_name,t.task_reward,t.id as task_id,e.member_id,mr.parent_id as lv1_id,mr1.parent_id as lv2_id,mr2.parent_id as lv3_id" earning_sql = f"SELECT {fetch_columns} FROM ( SELECT id, amounts, member_id, task_order_id, task_id, amount_type, add_time FROM et_member_earnings WHERE task_order_id>0 {where_cond} ) AS e LEFT JOIN et_tasks AS t ON e.task_id = t.id \ LEFT JOIN et_member_relations as mr ON mr.member_id=e.member_id \ LEFT JOIN et_member_relations as mr1 ON mr.parent_id=mr1.member_id \ LEFT JOIN et_member_relations as mr2 ON mr1.parent_id=mr2.member_id \ WHERE mr.top_parent_id IS NOT NULL LIMIT {p_i},{p_num}" count_earning_sql = f"SELECT {fetch_columns} FROM ( SELECT id, amounts, member_id, task_order_id, task_id, amount_type, add_time FROM et_member_earnings WHERE task_order_id>0 ) AS e LEFT JOIN et_tasks AS t ON e.task_id = t.id \ LEFT JOIN et_member_relations as mr ON mr.member_id=e.member_id \ LEFT JOIN et_member_relations as mr1 ON mr.parent_id=mr1.member_id \ LEFT JOIN et_member_relations as mr2 ON mr1.parent_id=mr2.member_id \ WHERE mr.top_parent_id IS NOT NULL" earnings = db.session.execute(earning_sql).fetchall() counts = db.session.execute(count_earning_sql).fetchall() drp_config = Redis.hgetall(redis_key_drp) per_sets = json.loads(drp_config[b'profit_percentage'].decode('utf8')) logger.info(per_sets) profit_percentage_arr = [] for i in range(len(per_sets)): profit_percentage_arr.append(per_sets[i]['per']) res_data = dict() if earnings: res_data['list'] = [{k: v for (k, v) in row.items()} for row in earnings] res_data['length'] = len(counts) res_data['drpconfig'] = profit_percentage_arr res.update(code=ResponseCode.Success, data=res_data, msg='流水报表数据获取成功') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='流水报表数据数据为空or异常') return res.data
def handle_sysconfig_edit(): """ 系统全局设置修改 :return: json """ res = ResMsg() req = request.get_json(force=True) now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) sysid = 1 notice = req.get("notice", '') domains = req.get("domains", '') share_domains = req.get("share_domains", '') task_limit = req.get("task_limit", 20) banners = req.get("banners", '') limit_withdrawal = req.get("limit_withdrawal", '') sys_status = int(req.get("status", 1)) rules = req.get("rules", 1) helper = req.get("helpers", 1) start_page = req.get("start_page", 1) upgrade = int(req.get("upgrade", 10)) update_dict = { "notice": notice, "domains": domains, "share_domains": share_domains, "task_limit": task_limit, "banners": banners, "limit_withdrawal": limit_withdrawal, "sys_status": sys_status, "rules": rules, "helpers": helper, "start_page": start_page, "upgrade": upgrade, "update_time": now_timestr } update_dict_ready = helpers.rmnullkeys(update_dict) sysdata = db.session.query(EtGlobalConfig).filter( EtGlobalConfig.id == sysid).first() if sysdata: db.session.query(EtGlobalConfig).filter( EtGlobalConfig.id == sysid).update(update_dict_ready) if notice: data = {'content': notice, 'time': now_timestr} json_data = json.dumps(data) redis_res = Redis.lpush(system_logging, json_data) try: db.session.commit() Redis.delete(redis_key_sys) res_data = helpers.queryToDict(sysdata) del res_data['update_time'] Redis.hmset(redis_key_sys, res_data) res.update(code=ResponseCode.Success, data={}, msg='系统全局配置成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'修改失败,请稍后再试{why}') return res.data else: res.update(code=ResponseCode.Success, data={}, msg='修改失败,请稍后再试') return res.data
def calculating_earnings(task_order:dict, task_id:int, type_set:int =1): ''' 计算该用户收益 同时异步完成该用户 所有上级 收益更新 #type_set 收益来源:1:任务收益 2:分销佣金3:新手红包奖励 ''' res = ResMsg() if isinstance(task_order, dict): task = db.session.query(EtTask).filter(EtTask.id == task_id).first() logger.info('发放父亲节点收益') if task: task_dict= dict(helpers.model_to_dict(task)) logger.info(task_dict) if task_dict['task_class']==3: type_set = 3 task_earning_money= float(task_dict['task_reward']) earning_dict ={ "member_id": task_order['member_id'], "task_id": task_id, "amounts": task_earning_money, "task_order_id": task_order['id'], "amount_type": type_set } logger.info(earning_dict) new_earning = EtMemberEarning(**earning_dict) isearn_sended= user = db.session.query(EtMemberEarning).filter( EtMemberEarning.task_order_id == task_order['id']).first() if isearn_sended: logger.info("该用户订单收益已发放") return "该用户订单收益已发放'" db.session.add(new_earning) user = db.session.query(EtMember).filter( EtMember.id == task_order['member_id']).first() if user.status==2: res.update(dict(code=ResponseCode.Success, data={}, msg=f'该用户已禁用,无法获得收益')) return res if user: try: update_dict = { "balance": task_earning_money*100 + user.balance, "balance_version": int(time.time()) } db.session.query(EtMember).filter( EtMember.id == task_order['member_id'], EtMember.balance_version == user.balance_version).update(update_dict) db.session.commit() # update user cache Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) Redis.delete(user_task_earnings_key + str(user.id)) #缓存获取分销比例参数 drp_config = Redis.hgetall(redis_key_drp) per_sets = json.loads(drp_config[b'profit_percentage'].decode('utf8')) logger.info(per_sets) # get各级分销比例 profit_percentage_arr=[] for i in range(len(per_sets)): profit_percentage_arr.append (per_sets[i]['per']) logger.info("比例设置:") # logger.info(profit_percentage_arr) # get当前用户关系树 rel_from_relations = db.session.execute(f"SELECT * FROM et_member_relations WHERE member_id={task_order['member_id']}").first() root_id= None if rel_from_relations['parent_id']: root_id= rel_from_relations['parent_id'] if rel_from_relations['top_parent_id']: root_id= rel_from_relations['top_parent_id'] realtion_tree_key_m = realtion_tree_key + str(root_id) logger.info("tree:") tree_node = Redis.hget(realtion_tree_key_m, 0) logger.info(str(tree_node)) realtion_tree_fromuser = json.loads(tree_node) logger.info(str(realtion_tree_fromuser)) importer = DictImporter() parents=[] realtion_tree = importer.import_(realtion_tree_fromuser) cur_node_tuple = realtionlib.findall_by_attr(realtion_tree, task_order['member_id']) cur_node = cur_node_tuple[0] logger.info('ancestors:') logger.info(str(cur_node.ancestors)) if cur_node.ancestors: # async-task: for all parents : drp_earnings for i,k in enumerate(cur_node.ancestors): parents.append(k.name) parentid= k.name drp_level = i+1 logger.info('k-name:'+str(k.name)) logger.info('drp_level:'+str(drp_level)) if drp_level<4: result = async_calculating_earnings.delay(parentid, drp_level, earning_dict, task_id, task_order['id'], type_set=2 ) logger.info(parents) res.update(code=ResponseCode.Success, data={},msg=f'用户交单任务收益更新成功') logger.info(res.data) except Exception as why: res.update(code=ResponseCode.Success, data={},msg=f'用户交单任务收益数据添加失败{why}') logger.info(res.data) else: res.update(code=ResponseCode.Success, data={},msg=f'用户信息异常{user}')
def async_calculating_earnings(parentid: int, level: int, earning_dict: dict, task_id: int, profit_percentage_arr: list, type_set: int = 2): ''' 异步任务 计算该用户 所有上级 收益更新 #type_set 收益来源:2:分销佣金 ''' with current_app.app_context(): res = dict() if earning_dict: fromuser = earning_dict['member_id'] origin_money = earning_dict['amounts'] logger.info(f'ORING收益:{origin_money}') logger.info(profit_percentage_arr) # get drpconfigs from cache drp_config = Redis.hgetall(redis_key_drp) per_set = drp_config[b'profit_percentage'] per_set = str(per_set, encoding="utf-8") logger.info(f'分销比例all:{per_set}') per_set = json.loads(per_set) per_set = per_set[::-1] logger.info(f'reversed分销比例all:{per_set}') profit_percentage = per_set[level - 1]['per'] logger.info(f'分销比例cur:{profit_percentage}') drp_money = origin_money * float(profit_percentage) logger.info(f'分销收益:{drp_money}') drp_earning_dict = { "member_id": parentid, "from_task_id": earning_dict['task_id'], "amounts": drp_money, "from_member_id": fromuser, } new_drp_earning = EtMemberDrp(**drp_earning_dict) db.session.add(new_drp_earning) logger.info(f'edt: {earning_dict}') user = db.session.query(EtMember).filter( EtMember.id == parentid).first() if user.status == 2: res.update( dict(code=ResponseCode.Success, data={}, msg=f'该用户已禁用,无法获得收益')) return res try: update_dict = { "balance": drp_money * 100 + user.balance, "balance_version": int(time.time()) } db.session.query(EtMember).filter( EtMember.id == parentid, EtMember.balance_version == user.balance_version).update(update_dict) db.session.commit() # update user cache Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) Redis.delete(user_task_earnings_key + str(user.id)) Redis.delete(user_appretice_detail_key + str(user.id)) Redis.delete(user_apprentice_key + str(user.id)) res.update( dict(code=ResponseCode.Success, data={}, msg=f'用户{fromuser}to{parentid}分销收益发放成功')) logger.info(res) return res except Exception as why: res.update( dict(code=ResponseCode.Success, data={}, msg=f'用户{fromuser}to{parentid}分销收益发放失败{why}')) logger.info(res) return res
def async_alipay_service(serial_number: int, alipay_account: str, real_name: str, pay_amount: int, mid: int): """ @req: req_data req_data = {'alipay_account': alipay, 'alipay_name': real_name, 'amount': amount, 'serial_number': serial_number} @resp: result_status, error_code :return: """ with current_app.app_context(): res = {} now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) headers = {'content-type': 'application/json;charset=UTF-8'} req_data = { 'alipay_account': alipay_account, 'alipay_name': real_name, 'amount': pay_amount, 'serial_number': serial_number } req_data['secret_key'] = 'FA77E2804734C22F72B22D9B7EDB41A9' wd_record = db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == serial_number).first() if wd_record: if wd_record.pay_status == 3: res.update( dict(code=ResponseCode.Success, data={}, msg=f'该单已发放无法再次提现')) return res user = db.session.query(EtMember).filter(EtMember.id == mid).first() verify_orders = db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == serial_number, EtMemberWithdrawal.member_id == mid).first() if user.status == 2: drp_config = Redis.hgetall(redis_key_drp) handling_fee_s = drp_config[b'handling_fee'] handling_fee = float(str(handling_fee_s, encoding="utf-8")) add_balance = 0 if handling_fee == 0: add_balance = verify_orders.amounts else: handling_fee = (1 - float(handling_fee) / 100) add_balance = round(verify_orders.amounts / handling_fee, 2) if verify_orders.origin_amount: add_balance = verify_orders.origin_amount update_dict = { "balance": user.balance + add_balance * 100, "balance_version": int(time.time()) } db.session.query(EtMember).filter( EtMember.id == mid, EtMember.balance_version == user.balance_version).update(user_update_dict) update_dict = { "id": serial_number, "verify": 1, "pay_status": 4, "end_time": now_timestr, "verify_log": '账号已封禁,无法提现', "pay_log": '账号已封禁,无法提现', } update_dict_ready = helpers.rmnullkeys(update_dict) db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == serial_number).update( update_dict_ready) try: db.session.commit() Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) Redis.delete(user_withdraw_recode_key + str(user.id)) except Exception as why: msg = f'支付失败,请稍后再试{why}' logging.info(str(why)) return msg if user.status == 2: res.update( dict(code=ResponseCode.Success, data={}, msg=f'该用户已禁用,无法提现')) return res res.update( dict(code=ResponseCode.Success, data={}, msg=f'该用户余额已不足,无法提现')) return res try: resp = requests.post( 'http://47.91.142.164/api/alipay/transfer', data=req_data, ) resp_json = resp.json() if resp_json.get('code') == 0: resp_data = resp_json.get('data', {}) result_status, error_code = resp_data.get( 'status'), resp_data.get('error_code') else: result_status, error_code = False, resp_json.get('msg', u'') except Exception as e: result_status, error_code = False, '网络错误' + str(e) logger.info(str(e)) logger.info(result_status) if result_status: # update_db pay_status pay_status = 3 update_dict = { "id": serial_number, "pay_status": pay_status, "end_time": now_timestr, "verify_log": '提现成功,已到账', "pay_log": '提现成功,已到账', } update_dict_ready = helpers.rmnullkeys(update_dict) db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == serial_number).update( update_dict_ready) try: db.session.commit() # update user cache Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) Redis.delete(user_withdraw_recode_key + str(user.id)) # send balance 100 to a parent which is never get the balance from this member new_member_reward(from_user=user.id) except Exception as why: msg = f'修改失败,请稍后再试{why}' return msg # title = '提现成功' # content = '恭喜您提现审核通过成功提现 {0}元'.format('%.2f' % (pay_amount)) # logger.info(result_status) else: remark = '' if error_code in [ '支付宝提现系统升级中!', 'INVALID_PARAMETER', 'PAYCARD_UNABLE_PAYMENT', 'PAYER_DATA_INCOMPLETE', 'PERMIT_CHECK_PERM_LIMITED', 'PAYER_STATUS_ERROR', 'PAYER_STATUS_ERROR', 'PAYER_DATA_INCOMPLETE', 'PAYMENT_INFO_INCONSISTENCY', 'CERT_MISS_TRANS_LIMIT', 'CERT_MISS_ACC_LIMIT', 'PAYEE_ACC_OCUPIED', 'MEMO_REQUIRED_IN_TRANSFER_ERROR', 'PERMIT_PAYER_LOWEST_FORBIDDEN', 'PERMIT_PAYER_FORBIDDEN', 'PERMIT_CHECK_PERM_IDENTITY_THEFT', 'REMARK_HAS_SENSITIVE_WORD', 'ACCOUNT_NOT_EXIST', 'PAYER_CERT_EXPIRED', 'SYNC_SECURITY_CHECK_FAILED', 'TRANSFER_ERROR' ]: remark = '支付宝提现系统升级中!请销后尝试' elif error_code in [ 'PERM_AML_NOT_REALNAME_REV', 'PERM_AML_NOT_REALNAME_REV', 'PERMIT_NON_BANK_LIMIT_PAYEE' ]: remark = '请登录支付宝站内或手机客户端完善身份信息后,重试!' elif error_code in [ 'PAYEE_NOT_EXIST', 'PERMIT_NON_BANK_LIMIT_PAYEE' ]: remark = '支付宝账号不存在!请检查之后重试' elif error_code == 'PAYEE_USER_INFO_ERROR': remark = '支付宝账号和姓名不匹配,请更换成实名信息支付宝账号!' elif error_code in [ '服务暂时不可用!', 'SYSTEM_ERROR', 'PAYER_BALANCE_NOT_ENOUGH' ]: remark = '服务暂时不可用' elif error_code == 'BLOCK_USER_FORBBIDEN_RECIEVE': remark = '账户异常被冻结,无法收款,请咨询支付宝客服95188' else: remark = '支付失败,请稍后再试' + str(error_code) now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) pay_status = 4 update_dict = { "id": serial_number, "verify": 1, "pay_status": pay_status, "verify_log": str(remark), "pay_log": str(remark) + ':' + str(error_code), # "end_time": now_timestr } update_dict_ready = helpers.rmnullkeys(update_dict) db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == serial_number).update( update_dict_ready) drp_config = Redis.hgetall(redis_key_drp) handling_fee_s = drp_config[b'handling_fee'] handling_fee = float(str(handling_fee_s, encoding="utf-8")) logging.info('+提现失败金额:') logging.info(str(verify_orders.amounts)) add_balance = 0 if handling_fee == 0: add_balance = verify_orders.amounts else: handling_fee = (1 - float(handling_fee) / 100) add_balance = round(verify_orders.amounts / handling_fee, 2) if verify_orders.origin_amount: add_balance = verify_orders.origin_amount user_update_dict = { "balance": user.balance + add_balance * 100, "balance_version": int(time.time()) } db.session.query(EtMember).filter( EtMember.id == mid, EtMember.balance_version == user.balance_version).update(user_update_dict) try: db.session.commit() Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) Redis.delete(user_withdraw_recode_key + str(user.id)) except Exception as why: msg = f'支付失败,请稍后再试{why}' logging.info(str(why)) return msg logging.info(error_code + remark) return error_code + remark
def new_member_reward(from_user: int = 1): # 拉新邀请奖励 from_user_id = from_user is_new_member = Redis.hget(is_new_member_key, from_user_id) if is_new_member: logger.info('parentid: is_new_member:' + is_new_member) parent_id = is_new_member is_sendbalance_redis = is_sendbalance_key + str(parent_id) is_send_balance = Redis.sismember(is_sendbalance_redis, from_user_id) # not in the set that means the mid not send balance to the parent_id if not is_send_balance: user = db.session.query(EtMember).filter( EtMember.id == parent_id).first() logger.info(f'{is_sendbalance_redis}:' + str(is_send_balance)) drp_send = db.session.query(EtMemberDrp).filter( EtMemberDrp.member_id == parent_id, EtMemberDrp.from_task_id == 9999_9999, EtMemberDrp.from_member_id == from_user_id).first() logger.info(drp_send) if not drp_send: # from_task_id give a max value # add drp records drp_earning_dict = { "member_id": parent_id, "from_task_id": 9999_9999, "amounts": 1, "from_member_id": from_user_id, } new_drp_earning = EtMemberDrp(**drp_earning_dict) db.session.add(new_drp_earning) update_dict = { "balance": 100 + user.balance, "balance_version": int(time.time()) } # update member balance db.session.query(EtMember).filter( EtMember.id == user.id, EtMember.balance_version == user.balance_version).update(update_dict) try: db.session.commit() # update user cache Redis.delete(user_center_key + str(user.id)) Redis.delete(user_info_key + str(user.mobile)) Redis.delete(user_task_earnings_key + str(user.id)) Redis.delete(user_appretice_detail_key + str(user.id)) Redis.delete(user_apprentice_key + str(user.id)) # update set of the send mids under the parentid Redis.sadd(is_sendbalance_redis, from_user_id) logger.info(f'from {from_user_id} to {parent_id} 发放邀请奖励成功') except Exception as why: logger.info(str(why))
def create_token(user, db_conn): ''' 功能: 获得前端的user数据,返回用户信息 参数: user { code: data.code, username: userResult.encryptedData, password: userResult.iv, grant_type: 'password', auth_approach: 'wxapp' } db_conn 数据库操作对象 返回格式: 非正常返回 False, {} 正常返回 True, {'access_token': token, 'nickname': account['nickName'], 'openid': str(account['openId']), 'avatarUrl':account['avatarUrl']} ''' # verify basic token print(user) approach = user["auth_approach"] username = user["username"] password = user["password"] code = user['code'] if approach == 'wxapp': account, session_key = verify_wxapp(username, password, code, db_conn) if not account: return False, {} payload = { "iss": 'wxapp', "iat": int(time.time()), "exp": int(time.time()) + 86400 * 7, "aud": 'flask', "openid": str(account['openId']), "nickname": account['nickName'], "scopes": ['open'] } token = jwt.encode(payload, current_app.config['SECRET_KEY'], algorithm='HS256') # save token openid session_key # sql_body = UserWXModel(id=token, openid=account['openId'], # session_key=session_key,created_time=datetime.now(), # updated_time=datetime.now()) # db.session.add(sql_body) # db.session.commit() # 将session_key 缓存至redis中,有效期为一个半小时,微信官方现在是两个小时有效期。 Redis.write(str(account['openId']), session_key, 90 * 60) return True, { 'access_token': token, 'nickname': account['nickName'], 'openid': str(account['openId']), 'avatarUrl': account['avatarUrl'] }
def company_list(): ''' 功能: 公司搜索,模糊匹配 参数: "search":"上海思华" 返回格式: { "code": 0, "data": [ { "base": "上海", "companyType": 1, "estiblishTime": "2000-08-15 00:00:00.0", "id": 1032774619, "legalPersonName": "孙逸浪", "name": "<em>上海思华</em>科技股份有限公司", "regCapital": "10750万人民币", "type": 1 }, { "base": "上海", "companyType": 1, "estiblishTime": "1994-05-05 00:00:00.0", "id": 1136050774, "legalPersonName": "陈愉", "name": "<em>上海思华</em>咨询有限公司", "regCapital": "15万美元", "type": 1 },...], "lang": "zh_CN", "msg": "成功" } ''' # 创建返回内容模板 res = ResMsg() # 获取公司名称关键字 word = request.args.get("search") if not word: code = ResponseCode.InvalidParameter res.update(code=code, data='请输入公司名称关键字') return res.data # 从Redis获取 req = Redis.read(word + "company_list") # 如果Redis中有记录,转换类型。如果没有历史记录,请求天眼查获取,并写入Redis。 if req: req = json.loads(req) else: # 头部内容,包括天眼查token header = { "Authorization": current_app.config.get('tianyancha_token'), "Content-Type": "application/x-www-form-urlencoded" } # 天眼查api地址 url = current_app.config.get('tianyancha_search_company_url') + word # 请求返回 req = requests.get(url, headers=header) # 错误内容提示稍后再试 if req.status_code != 200: code = ResponseCode.InvalidParameter res.update(code=code, data="请稍安勿躁,休息片刻再试。") return res.data req = req.json() Redis.write(word + "company_list", json.dumps(req), 86400) # 制作返回内容 code = ResponseCode.Success res.update(code=code, data=req["result"]["items"]) return res.data
def handle_edittask(): """ 任务修改编辑接口 :return: json """ res = ResMsg() req = request.get_json(force=True) now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) taskid= int(req.get("id", 1)) taskname= req.get("name",'tasktest1-new') status= int(req.get("status", 1)) task_class= int(req.get("task_class", 1)) end_time= req.get("end_time", '') begin_task_time= req.get("begin_task_time",'') poster_img= req.get("poster_img", 'https://qiniu.staticfile.org/user_avatar.jpg') count_tasks= req.get("count_tasks",'') allow_nums= req.get("allow_nums", '') allow_member_nums= req.get("allow_member_nums", '') virtual_nums= req.get("virtual_nums", '') tasks_counts= req.get("tasks_counts", '') task_reward= req.get("task_reward", '') task_info= req.get("task_info", '请根据任务步骤完成任务') task_steps= req.get("task_steps", '') tags= req.get("tags", '') sys_tags = req.get("sys_tags", '') task_cats= req.get("task_cats", '') recommend= req.get("recommend", 1) deadline_time = req.get("deadline_time", '') check_router = req.get("check_router", '') end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(end_time)/1000)) begin_task_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(begin_task_time)/1000)) account_name= session.get("user_name") update_dict = { "name": taskname, "status": status, "task_class": task_class, "end_time": end_time, "begin_task_time": begin_task_time, "count_tasks": count_tasks, "allow_nums": allow_nums, "allow_member_nums": allow_member_nums, "virtual_nums": virtual_nums, "tasks_counts": tasks_counts, "task_reward": task_reward, "task_info": task_info, "task_steps": task_steps, "tags": tags, "poster_img":poster_img, "sys_tags": sys_tags, "task_cats": task_cats, "recommend": recommend, "deadline_time": deadline_time, "check_router": check_router, } update_dict_ready = helpers.rmnullkeys( update_dict ) db.session.query(EtTask).filter(EtTask.id == taskid).update(update_dict_ready) try: db.session.commit() Redis.delete(task_info_key) Redis.delete(task_detail_key+str(taskid)) Redis.delete(tasks_high_info_key) res_data= dict() res.update(code=ResponseCode.Success, data=res_data, msg=f'任务修改成功') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={},msg=f'修改失败,数据异常{why}') return res.data
def test_redis_read(): """ 测试redis获取 """ data = Redis.read("test_key") return data
def handle_withdrawals_verify(): """ 用户提现审核接口 @logic 审核完成 异步发送任务至redis队列执行支付宝付款任务 :return: json """ res = ResMsg() req = request.get_json(force=True) wd_id = int(req.get("id", 1)) member_id = int(req.get("member_id", 1)) status = int(req.get("status", 1)) verify_log = str(req.get("verify_log", '数据真实有效,情节感人,通过')) account_name = session.get("user_name") now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) verify_orders = db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == wd_id, EtMemberWithdrawal.member_id == member_id).first() if not account_name or not verify_orders: res.update(code=ResponseCode.Success, data={}, msg=f'账户{account_name}数据异常') return res.data if not status: res.update(code=ResponseCode.Success, data={}, msg='未提交审核数据,操作已经撤销') return res.data pay_status = 1 if status == 2: pay_status = 2 update_dict = { "verify": status, "verify_log": verify_log, "account": account_name, "check_time": now_timestr, "pay_status": pay_status } update_dict_ready = helpers.rmnullkeys(update_dict) db.session.query(EtMemberWithdrawal).filter( EtMemberWithdrawal.id == wd_id).update(update_dict_ready) res_data = dict() ret = '' try: user = db.session.query( EtMember.id, EtMember.nickname, EtMember.status, EtMember.m_class, EtMember.realname, EtMember.mobile, EtMember.IIUV, EtMember.balance, EtMember.balance_version, EtMember.setreal, EtMember.alipayid).filter(EtMember.id == member_id).first() user_info = (dict(zip(user.keys(), user))) drp_config = Redis.hgetall(redis_key_drp) handling_fee_s = drp_config[b'handling_fee'] handling_fee = float(str(handling_fee_s, encoding="utf-8")) logger.info("handling_fee:") logger.info(handling_fee) # verify reject if status == 1: if handling_fee == 0: add_balance = verify_orders.amounts else: handling_fee = (1 - float(handling_fee) / 100) add_balance = round(verify_orders.amounts / handling_fee, 2) if verify_orders.origin_amount: add_balance = verify_orders.origin_amount logger.info("add_balance:") logger.info(add_balance) update_dict = { "balance": user_info['balance'] + add_balance * 100, "balance_version": int(time.time()) } logger.info(update_dict) db.session.query(EtMember).filter( EtMember.id == member_id, EtMember.balance_version == user_info['balance_version']).update(update_dict) try: db.session.commit() Redis.delete(user_center_key + str(user_info['id'])) Redis.delete(user_info_key + str(user_info['mobile'])) res.update(code=ResponseCode.Success, data={}, msg='该单未通过审核') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'审核拒绝操作数据异常{why}') return res.data db.session.commit() # verify pass go alipay if status == 2: if user: ret = async_alipay_service.delay( serial_number=wd_id, alipay_account=user_info['alipayid'], real_name=user_info['realname'], pay_amount=verify_orders.amounts, mid=member_id) logger.info(ret) res.update(code=ResponseCode.Success, data=res_data, msg=f'提现审核成功,系统将发放收益到用户收款账户,请留意支付返回消息') return res.data except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'用户提现订单审核失败,数据异常{why}') return res.data
def check_logout(): res = ResMsg() user_id = session["user_name"] Redis.delete(user_id) res.update(data={"result": "yes"}) return res.data
def handle_verifytaskorder(): """ 用户提交任务审核接口(交单) @todo 审核流程优化 :return: json """ res = ResMsg() req = request.get_json(force=True) taskorder_id= int(req.get("id", 1)) status= int(req.get("status", 1)) verify_log = req.get("verify_log", '') account_name= session.get("user_name") if not account_name: res.update(code=ResponseCode.Success, data={},msg=f'账户{account_name}数据异常') return res.data user = db.session.query(EtAccount.id).filter(EtAccount.name == account_name).first() if not status: res.update(code=ResponseCode.Success, data={},msg='未提交审核数据,操作已经撤销') return res.data update_dict = { "status": status, "account_id": user.id, "verify_log":verify_log } task_order= db.session.query(EtTaskOrder.id,EtTaskOrder.task_id,EtTaskOrder.member_id).filter(EtTaskOrder.id == taskorder_id).first() user = db.session.query(EtMember.id, EtMember.nickname, EtMember.status, EtMember.m_class, EtMember.realname, EtMember.mobile, EtMember.IIUV,EtMember.balance,EtMember.balance_version, EtMember.setreal, EtMember.alipayid).filter(EtMember.id == EtTaskOrder.member_id).first() user_info = (dict(zip(user.keys(), user))) if task_order: db.session.query(EtTaskOrder).filter(EtTaskOrder.id == taskorder_id).update(update_dict) task_order_dict= dict(zip(task_order.keys(), task_order)) if status == 4: up_sql= f"UPDATE et_tasks SET tasks_fulfil = tasks_fulfil+1 WHERE id ={task_order_dict['task_id']}" up_num= db.session.execute(up_sql) try: db.session.commit() res_data= dict() res_data.update(task_order_dict) u_task_key=f"user_tasks_:{task_order_dict['member_id']}" Redis.delete(u_task_key) if status == 5: Redis.sadd(f"{task_complete_key}{task_order.task_id}", task_order.member_id) Redis.sadd(f"{complete_tasks_uid_key}{task_order.member_id}", task_order.task_id) Redis.expire(f"{task_complete_key}{task_order.task_id}", 60 * 60 * 10) res.update(code=ResponseCode.Success, data={}, msg='该单未通过审核') if status == 4: task_limit=20 counts = db.session.execute(f"SELECT count(id) FROM et_task_orders WHERE status=4 AND member_id={task_order_dict['member_id']}").first() # update member status 2 if int(counts[0]) == task_limit: update_dict = { "m_class": 2, } update_dict_ready = helpers.rmnullkeys( update_dict ) db.session.query(EtMember).filter(EtMember.id == memberid).update(update_dict_ready) try: db.session.commit() Redis.delete(user_center_key + str(user_info['id'])) Redis.delete(user_info_key + str(user_info['mobile'])) except Exception as why: res.update(code=ResponseCode.Success, data={}, msg=f'修改失败,请稍后再试{why}') return res.data Redis.sadd(f"{task_verifyed_key}{task_order.task_id}", task_order.member_id) Redis.expire(f"{task_verifyed_key}{task_order.task_id}", 60 * 60 * 10) Redis.sadd(f"{task_complete_key}{task_order.task_id}", task_order.member_id) Redis.expire(f"{task_complete_key}{task_order.task_id}", 60 * 60 * 10) calculating_earnings(task_order_dict, task_order.task_id, type_set=1 ) res.update(code=ResponseCode.Success, data=res_data, msg=f'任务订单审核成功,对该用户发放收益') update_dict_com = { "status": 4, "account_id": user.id, "verify_log":verify_log } db.session.query(EtTaskOrder).filter(EtTaskOrder.id == taskorder_id).update(update_dict_com) return res.data except Exception as why: res.update(code=ResponseCode.Success, data={},msg=f'任务订单审核失败,{why}') return res.data