#coding=utf-8 ''' ''' import os,re,random import json,time,datetime import shutil import tempfile import zipfile,requests from docxtpl import DocxTemplate,InlineImage from docx.shared import Mm from django.db import transaction from django.conf import settings import common.models as cm import common.error_info as ce import common.common_functions as ccf import common.common_control as ccc import common.constant as const import account.password_handle as ph from utils.exceltool import ExcelTool from utils.jgpush import send_notification_by_registration_ids import wzhifuSDK as wxpay from utils.exceltool import ExcelTool from utils.qrcodetool import gen_general_qrcode from django.db.models import Q,Sum,Count,F,Avg from PIL import Image from PIL import Image,ImageDraw,ImageFont from django.db import transaction from threading import Thread #from django.core.cache import cache from django.db import connection import calendar import xlrd import xlwt # from xlutils.copy import copy import copy from xltpl.writer import BookWriter from django_redis import get_redis_connection from constants import * from utils.aliyun_sms import send_verify_code,send_signup_success from utils.wxSubscribeMessage import send_consult_reply_message from utils.aliyunpush import aliyunpush from utils.wxpay.pay import WechatPayDAL #import logging #log = logging.getLogger("myerror") from utils.upload_to_oss import get_signature from weixin.wzhifuSDK_V3 import refund_order def async(f): def wrapper(*args, **kwargs): thr = Thread(target=f, args=args, kwargs=kwargs) thr.start() return wrapper def get_today_date(match_id=None,user_id=None): if not match_id: match_id = ccc.get_cur_match().id #if datetime.datetime.now().strftime("%H:%M") < "15:00": # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES: # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date # else: # if datetime.datetime.now().weekday()==0: # today = (datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d") # else: # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d") #else: # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES: # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date # else: # today = datetime.datetime.now().strftime("%Y-%m-%d") try: if user_id: today = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id).order_by("-stock_date").first().stock_date else: today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date except: today = datetime.datetime.now().strftime("%Y-%m-%d") return today #@async def update_group_rank(match_id,match_group,stock_date): #return prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,match_group=match_group,stock_date=stock_date).order_by("-total_income") records = prset.values() case_id = " case id " cases = [] where = [] for index,pr in enumerate(prset): key = "%s_%s_%s_%s" % (pr.player_id,match_id,match_group,stock_date) record = records[index] record.update({"group_rank":index+1}) ccc.cache.delete(key) ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder)) ccc.pl.execute() #@ccc.cache_data() def get_notices(): """ """ notices = list(cm.Article.objects.filter(status=2,type="notice").values()) return notices def get_index_data(request): """首页数据 """ player = request.player if not player: raise ce.TipException(u"该账号未参加任何赛事!") player_id = player.id match_id = player.match_id match_group = player.match_group #if datetime.datetime.now().hour < 15: # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d") #else: # today = datetime.datetime.now().strftime("%Y-%m-%d") today = get_today_date() match_name = get_match_info(match_id).get("name") records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(player_id=player_id,match_id=match_id) if records_set: try: cur_rank = get_today_record(player_id,match_id,match_group,today).get("group_rank","") records = list(records_set.order_by("-stock_date").values()) except: cur_rank = 0 records = [] else: cur_rank = 0 records = [] for item in records: today_stock = json.loads(item["today_stock"]) if item["today_stock"] else [] today_stock = filter(lambda x:x["name"],today_stock) item["today_stock"] = today_stock item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else [] yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else [] yesterday_stock = filter(lambda x:x["name"],yesterday_stock) item["yesterday_stock"] = yesterday_stock item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else [] item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) #通知 notices = get_notices() ret = {"match_name":match_name,"cur_rank":cur_rank,"records":records,"notices":notices} return ret def get_player_match_list(request): """选手参赛列表数据 """ uid = request.user.get("id",0) now_str = datetime.datetime.now().strftime("%Y-%m-%d") cur_match_id = ccc.get_cur_match().id match_ids = list(cm.Player.objects.filter(user_id=uid).values_list("match_id",flat=True)) matchs = list(cm.Match.objects.filter(id__in=match_ids).values()) for item in matchs: player = cm.Player.objects.filter(user_id=uid,match_id=item["id"]).first() item["player_id"] = player.id if player else 0 return matchs def get_group_income(match_id,match_group): """ """ data = [] today = datetime.datetime.now().strftime("%Y-%m-%d") player_ids = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values_list("id",flat=True)) for player_id in player_ids: today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,match_group=match_group,player_id=player_id,stock_date=today).first() if today_record: data.append(today_record.total_income) data = list(set(data)) data = sorted(data,key=lambda x:x,reverse=True) return data def get_player_match_detail(request): """选手参赛详情数据 """ qdata = request.json try: user_id = request.user.get("id",0) except: user_id = 0 match_id = qdata.get("id") record_id = qdata.get("record_id") userinfo = {} cur_user_id = user_id if qdata.get("user_id"): cur_user_id = qdata.get("user_id") today = get_today_date() ismine = True if int(cur_user_id) == user_id else False if not match_id: player = cm.Player.objects.filter(user_id=cur_user_id,match_id=match_id).first() match_id =player.match_id cur_user_id = player.user_id if record_id: records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id) if records_set: match_id = records_set.first().match_id else: records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("-stock_date") match = cm.Match.objects.filter(id=match_id).values().first() groups = list(cm.MatchGroup.objects.filter(match_id=match_id).values_list("name",flat=True)) match["groups"] = groups all_records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("-stock_date") if all_records_set: records = list(all_records_set.values()) else: records = [] for item in records: item["today_stock"] = json.loads(item["today_stock"]) if item["today_stock"] else [] item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else [] item["yesterday_stock"] = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else [] item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else [] item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) item["avatar"] = get_user_info(item["user_id"])["avatar"] today_record = {} if records_set: today = records_set.first().stock_date if record_id: today_record = records_set.values().first() today_record = format_today_record(today_record) else: match_group = records_set.first().match_group today_record = ccc.get_today_record(cur_user_id,int(match_id),match_group,today) if today_record: today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else [] today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else [] today_record["today_income"] = "{}%".format(today_record["today_income"]*100) today_record["total_income"] = "{}%".format(today_record["total_income"]*100) today_record["match_group_name"] = cm.MatchGroup.objects.filter(id=today_record["match_group"]).first().name today_record["players_num"] = cm.Player.objects.filter(match_group=today_record["match_group"]).count() today_record["win_rate"] = calc_win_rate(cur_user_id,today_record["match_id"]) badest = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("today_income").first() if badest: today_record["badest_income"] = "{}%".format(badest.today_income*100) today_record["today_stock_total"] = round(today_record.get("today_stock_total",0.0),4) userinfo = get_user_info(today_record["user_id"]) today_record["style"] = userinfo.get("style") else: player_info = get_user_info(cur_user_id) today_record = {} today_record["stock_date"] = today today_record.update(player_info) today_record["player_id"] = player_info["id"] today_record["avatar"] = get_user_info(cur_user_id)["avatar"] userinfo = get_user_info(cur_user_id) today_record["style"] = userinfo.get("style") today_record["user_id"] = player_info["id"] match["groups"] = [today_record.get("match_group_name","")] if today_record else [] records = sorted(records,key=lambda x:x["stock_date"],reverse=True) if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=cur_user_id).exists(): is_follow = 1 else: is_follow = 0 if today_record and today_record.get("today_fund"): today_record["today_income_fund"] = round((today_record["today_fund"] - today_record["yesterday_fund"])*10000,2) if today_record["yesterday_fund"] else 0.00 today_record["zan_count"] = today_record.get("zans",0) user_info = get_user_info(cur_user_id) if user_info.get("phone"): del user_info["phone"] #查询出入资金 fund_inout_list = [] if cm.FundInOut.objects.filter(user_id = cur_user_id,stock_date=today_record["stock_date"]).exists(): fund_inout_list = list(cm.FundInOut.objects.filter(user_id=cur_user_id,stock_date=today_record["stock_date"]).values()) ret = { "match":match, "today_record":today_record, "match_group_info":get_group_info(today_record.get("match_group")) if today_record.get("match_group") else {}, "userinfo":user_info, "records":records, "is_follow":is_follow, "fans":cm.UserFollows.objects.filter(follow_id=cur_user_id).count(), "followers":cm.UserFollows.objects.filter(user_id=cur_user_id).count(), "stock_age":datetime.datetime.now().year - int(userinfo.get("join_time")) if userinfo.get("join_time") else 0, "stock_follow":list(cm.UserChoice.objects.filter(user_id=cur_user_id).values_list("stock_name",flat=True)), "fund_inout":fund_inout_list[0] if len(fund_inout_list) > 0 else {} } return ret def get_today_record(player_id,match_id,match_group,today): """ """ key = "%s_%s_%s_%s" % (player_id,match_id,match_group,today) #key = "%s_%s_%s" % (player_id,match_id,today) today_record = ccc.cache.get(key) today_record = json.loads(today_record) if today_record else {} #if match_id: # #记得这里上线后要注释掉 # today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=player_id,match_id=match_id,stock_date=today) # today_record = today_record.values().first() try: if today_record: user_info = get_user_info(today_record["user_id"]) if user_info: user_info.pop("id") today_record.update(user_info) #仓位 today_stock_total = 0 today_stock = json.loads(today_record["today_stock"]) for ts in today_stock: if ts["fund"]: try: today_stock_total += float(ts["fund"]) except Exception as e: print e today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100) today_record["today_stock_total"] = today_stock_total except Exception as e: import traceback traceback.print_exc() return today_record def format_today_record(today_record): try: if today_record: user_info = get_user_info(today_record["user_id"]) if user_info: #user_info.pop("id") today_record.update(user_info) #仓位 today_stock_total = 0 today_stock = json.loads(today_record["today_stock"]) for ts in today_stock: if ts["fund"]: try: today_stock_total += float(ts["fund"]) except Exception as e: print e today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100) today_record["today_stock_total"] = today_stock_total # win_rate = ccc.cache.hget("PLAYER_LATEST_%d" % today_record["user_id"],"win_rate") # if win_rate: # today_record["win_rate"] = str(float(win_rate)*100)+"%" # else: # today_record["win_rate"] = "0.0%" win_rate = calc_win_rate(today_record["user_id"],today_record["match_id"]) today_record["win_rate"] = win_rate except Exception as e: import traceback traceback.print_exc() today_record = today_record if today_record else {} return today_record def get_today_record_actual(player_id,match_id,match_group,today=None): """ """ if today: qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,match_group=match_group,player_id=player_id,stock_date=today) else: qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,match_group=match_group,player_id=player_id).order_by("-stock_date") today_record = qset.values().first() if today_record: user_info = get_user_info(today_record["user_id"]) if user_info: user_info.pop("id") today_record.update(user_info) #仓位 today_stock_total = 0 today_stock = json.loads(today_record["today_stock"]) for ts in today_stock: if ts["fund"]: try: today_stock_total += float(ts["fund"]) except Exception as e: print e today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100) today_record["today_stock_total"] = today_stock_total return today_record @ccc.cache_data() def get_match_group_players(match_id,match_group): players = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values()) return players #@ccc.cache_data() def get_match_group_users(match_id,match_group): #users = list(cm.UserMatch.objects.filter(match_id=match_id,match_group=match_group).values()) users = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values()) return users #@ccc.cache_data() def get_match_groups(match_id): """ """ match = cm.Match.objects.filter(id=match_id).values().first() groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).order_by("-order").values()) return match,groups def get_cache_rank_list(match_id,today): """ """ match,groups = get_match_groups(match_id) data = [] for item in groups: new_players = [] players = get_match_group_users(match_id,item["id"]) win_count = 0 loss_count = 0 total_income_win = 0 total_income_lose = 0 today_income_win = 0 today_income_lose = 0 for player in players: user_id = player["user_id"] #username = player["signup_name"] username = player["username"] match_group = player["match_group"] today_record = ccc.get_today_record(user_id,match_id,match_group,today) if today_record: player.update(today_record) player["username"] = username player["org_today_income"] = player["today_income"] player["org_total_income"] = player["total_income"] player["total_income"] = "{}%".format(today_record["total_income"]*100) player["today_income"] = "{}%".format(today_record["today_income"]*100) if player["org_today_income"] >= 0.05: win_count += 1 if player["org_today_income"] <= -0.05: loss_count += 1 if today_record["total_income"] >= 0: total_income_win += 1 else: total_income_lose += 1 if today_record["today_income"] >= 0: today_income_win += 1 else: today_income_lose += 1 try: player["fund"] = round(player["fund"],4) if player["fund"] else 0.0 player["init_fund"] = round(player["init_fund"],4) player["fund"] = round(player["init_fund"],4) player["today_fund"] = round(player["today_fund"],4) new_players.append(player) except Exception as e: print player pass new_players_sort = list(sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)) #计算退赛率 group_id = item["id"] player_total = cm.Player.objects.filter(match_id=match_id,match_group=group_id).count() player_post_total = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today).count() out_rate = (player_total-player_post_total)/float(player_total) if player_total else 0.0 item["players_num"] = len(players) item["win_count"] = win_count item["loss_count"] = loss_count item["players"] = new_players_sort[:3] try: ntotal_income_win = float(total_income_win)/(total_income_win+total_income_lose)*10 ntotal_income_lose = float(total_income_lose)/(total_income_win+total_income_lose)*10 except: ntotal_income_win = 0.0 ntotal_income_lose = 0.0 total_income_win = int(round(ntotal_income_win)) total_income_lose = int(round(ntotal_income_lose)) item["total_income_win"] = total_income_win item["total_income_lose"] = total_income_lose try: ntoday_income_win = float(today_income_win)/(today_income_win+today_income_lose)*10 ntoday_income_lose = float(today_income_lose)/(today_income_win+today_income_lose)*10 except: ntoday_income_win = 0.0 ntoday_income_lose = 0.0 today_income_win = int(round(ntoday_income_win)) today_income_lose = int(round(ntoday_income_lose)) item["today_income_win"] = today_income_win item["today_income_lose"] = today_income_lose item["out_rate"] = "{}%".format(round(out_rate*100,2)) data.append(item) return match,data def get_rank_list(request): """排名列表 """ qdata = request.json #user_id = request.user.get("id",0) match_id = qdata.get("match_id") today = qdata.get("stock_date") if not today: today = get_today_date() match,groups = get_cache_rank_list(match_id,today) ret = {"match":match,"groups":groups} return ret @ccc.cache_data() def get_user_info(uid): user = cm.UserInfo.objects.filter(id=uid).values().first() if user: user["style"] = [] if user["zq"]: user["style"].append(user["zq"]) if user["cw"]: user["style"].append(user["cw"]) if user["df"]: user["style"].append(user["df"]) if user.get("phone"): del user["phone"] return user def get_user_info_actual(uid): user = cm.UserInfo.objects.filter(id=uid).values().first() if user: user["style"] = [] if user["zq"]: user["style"].append(user["zq"]) if user["cw"]: user["style"].append(user["cw"]) if user["df"]: user["style"].append(user["df"]) if user.get("phone"): del user["phone"] return user #@ccc.cache_data() def get_player_info(player_id): player = cm.Player.objects.filter(id=player_id).values().first() return player @ccc.cache_data() def get_player_info_cache(player_id): player = cm.Player.objects.filter(id=player_id).values().first() return player @ccc.cache_data() def get_match_info(match_id): match = cm.Match.objects.filter(id=match_id).values().first() return match @ccc.cache_data() def get_group_info(group_id): group = cm.MatchGroup.objects.filter(id=group_id).values().first() if group: group["players_num"] = cm.Player.objects.filter(match_group=group["id"]).count() return group else: return {} def get_group_rank_list(request): """排名列表 """ qdata = request.json kwargs = qdata group_id = qdata.get("id") match_id = qdata.get("match_id") match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id today = qdata.get("stock_date") if not today: today = get_today_date() match = get_match_info(match_id) group = get_group_info(group_id) players = get_match_group_users(match_id,group_id) new_players = [] for player in players: user_id = player["user_id"] #user = get_user_info(user_id) #username = user["username"] if user else "" #username = player["signup_name"] username = player["username"] match_group = group_id today_record = ccc.get_today_record(user_id,match_id,match_group,today) if today_record: player.update(today_record) player["username"] = username player["org_today_income"] = player["today_income"] player["org_total_income"] = player["total_income"] player["total_income"] = "{}%".format(player["total_income"]*100) player["today_income"] = "{}%".format(player["today_income"]*100) player["fund"] = round(player["fund"],4) player["init_fund"] = round(player["init_fund"],4) player["today_fund"] = round(player["today_fund"],4) new_players.append(player) if kwargs.get("order_by") == "today_income__asc": new_players = sorted(new_players,key=lambda x:x["org_today_income"]) elif kwargs.get("order_by") == "today_income__desc" : new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True) elif kwargs.get("order_by") == "total_income__asc": new_players = sorted(new_players,key=lambda x:x["org_total_income"]) elif kwargs.get("order_by") == "total_income__desc": new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True) else: new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True) #分页 page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",50)) #page_size = 50 if page and page_size: total,new_players = ccf.get_page_list(new_players,page,page_size) else: total = len(new_players) #应到、实到、请假人数 total_person = cm.Player.objects.filter(match_group=group_id,match_status=1).count() actual_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today).count() leave_person = total_person - actual_person win_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__gte=0).count() loss_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__lt=0).count() ret = {"group":group,"players":new_players,"total":total,"total_person":total_person, "actual_person":actual_person,"leave_person":leave_person,"win_person":win_person,"loss_person":loss_person} return ret def get_player_match_records(request): """选手参赛每日持股 """ qdata = request.json match_id = qdata.get("id") user_id = qdata.get("user_id") page = int(qdata.get("page",0)) page_size = int(qdata.get("page_size",20)) records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).order_by("-stock_date") data = list(records_set.values()) for item in data: today_stock = json.loads(item["today_stock"]) if item["today_stock"] else [] today_stock = filter(lambda x:x["name"],today_stock if today_stock else []) item["today_stock"] = today_stock item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else [] yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else [] yesterday_stock = filter(lambda x:x["name"],yesterday_stock if yesterday_stock else []) item["yesterday_stock"] = yesterday_stock item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else [] item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) item["zans_count"] = item.get("zans",0) item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count() if page and page_size: total,data = ccf.get_page_list(data,page,page_size) return total,data else: return len(data),data def add_model(cls,**kwargs): """ """ model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0] model = getattr(cm,model_name) if model_name == "PlayerRecord": user_id = kwargs.get("user_id") match_id = kwargs.get("match_id") stock_date = kwargs.get("stock_date") now = datetime.datetime.now() if not cm.Player.objects.filter(user_id=user_id,match_id=match_id).exists(): raise ce.TipException(u"比赛未开赛/未报名") if now.weekday() in [5,6] or not now.strftime("%Y-%m-%d") in get_match_validdates(match_id): raise ce.TipException(u"今日不能提交数据!") now_time = datetime.datetime.now().strftime("%H:%S") if not user_id in [9600,6209,5709,25953]: if now_time<"15:00" or now_time > "23:50": raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!") stock_date = datetime.datetime.now().strftime("%Y-%m-%d") today_stock = json.dumps(kwargs.get("today_stock")) today_stock_img = json.dumps(kwargs.get("today_stock_img")) today_fund = float(kwargs.get("today_fund",0)) is_markt = int(kwargs.get("is_markt",0)) experience = kwargs.get("experience") if not ccc.get_cur_match().id == match_id: raise ce.TipException(u"非当前赛事参赛选手不能提交作业!") #计算今日和昨日盈亏 if float(today_fund)>9999 or float(today_fund)<=0: raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!") player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first() user_id = player.user_id init_fund = player.fund user = cm.UserInfo.objects.filter(id=user_id).first() username = user.username usercode = user.usercode match_group = player.match_group opmode_group = player.opmode_group zq = user.zq cw = user.cw df = user.df match = cm.Match.objects.filter(id=match_id).first() if player.match_status < 1: raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!") now_date = datetime.datetime.now().strftime("%Y-%m-%d") if not user_id in [9600,6209,5709]: if match.end_time < now_date: raise ce.TipException(u"该比赛已结束或您未参加此次比赛不能提交数据!") validdates = get_match_validdates(match_id) today_index = validdates.index(stock_date) yesterday_index = today_index -1 if today_index >=1 else 0 yesterday_date = validdates[yesterday_index] yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter( match_id=match_id,user_id=user_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first() if yesterday: yesterday_fund = yesterday.today_fund yesterday_stock = yesterday.today_stock yesterday_stock_img = yesterday.today_stock_img yesterday_is_markt = yesterday.is_markt else: yesterday_fund = today_fund yesterday_stock = "" yesterday_stock_img = "" yesterday_is_markt = 0 if kwargs.get("id"): if cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).count()==1: init_fund = today_fund cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund) else: if not cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).exists(): init_fund = today_fund cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund) with transaction.atomic(): #记录持股情况 today_stock_fund = 0 new_stock_list = [] today_stock_list = json.loads(today_stock) month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1]) for ts in today_stock_list: if ts["name"] and ts["fund"]: try: stock,flag = cm.Stock.objects.get_or_create( name = ts["name"] ) stock_id = stock.id usobj,flag = cm.UserStock.get_db_model(month).objects.get_or_create( stock_id = stock_id, player_id = player.id, stock_date = stock_date ) if ts.get("fund"): usobj.fund = ts["fund"] try: today_stock_fund += float(ts["fund"]) except: pass if ts.get("name"): usobj.stock_name = ts.get("name") if match_group: usobj.match_group = match_group if opmode_group: usobj.opmode_group = opmode_group usobj.save() ts["stock_id"] = stock_id new_stock_list.append(ts) except Exception as e: print(e) today_stock = json.dumps(new_stock_list) obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create( user_id=user_id, match_id=match_id, stock_date=stock_date) #计算仓位 today_cangwei = round(today_stock_fund/today_fund,4)*100 obj.init_fund = init_fund obj.yesterday_fund = yesterday_fund obj.yesterday_stock = yesterday_stock obj.yesterday_stock_img = yesterday_stock_img obj.today_fund = today_fund obj.today_stock_total = today_stock_fund obj.today_cangwei = today_cangwei obj.today_stock = today_stock obj.today_stock_img = today_stock_img obj.username = username obj.usercode = usercode obj.match_group = match_group obj.opmode_group = opmode_group obj.is_markt = is_markt obj.yesterday_is_markt = yesterday_is_markt obj.zq = zq obj.cw = cw obj.df = df obj.experience = experience #计算今日收益和总收益 if float(today_fund)>9999 or float(today_fund)<=0: raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!") #如果今日持仓金额大于总资产的10倍,则提示数据有问题 if today_stock_fund > float(today_fund)*10: raise ce.TipException(u"今日持仓金额有误,请修改持仓金额!") #有资金出入 if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists() and player.fund>0: fundinout = cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).first() fundin = fundinout.fundin fundout = fundinout.fundout today_income = 0.0 total_income = 0.0 #入资金 if fundin > fundout: fundin = fundin - fundout if yesterday: today_income = (today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin) obj.yesterday_fund = obj.yesterday_fund + fundin else: today_income = 0.0 obj.today_income = round(today_income,4) if flag: total_income = (today_fund-init_fund-fundin)/(init_fund+fundin) cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=init_fund+fundin) obj.init_fund = init_fund + fundin else: total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0 obj.total_income = round(total_income,4) #出资金 else: fundout = fundout - fundin if yesterday: today_income = (today_fund-(yesterday_fund-fundout))/float(yesterday_fund) obj.yesterday_fund = round(today_fund/(1+today_income),4) else: today_income = 0.0 obj.today_income = round(today_income,4) if flag: total_income = (today_fund+fundout-init_fund)/init_fund if init_fund else 0.0 cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=round(today_fund/(1+total_income),4)) obj.init_fund = round(today_fund/(1+total_income),4) else: total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0 obj.total_income = round(total_income,4) if float(today_income)>0.6: raise ce.TipException(u"今日盈利已超过60%,请仔细核对数据或直接联系顽主!") if float(total_income)>20: raise ce.TipException(u"请仔细核对数据或直接联系顽主!") else: today_income = (today_fund - yesterday_fund)/float(yesterday_fund) if yesterday_fund else 0.0 total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0 if float(today_income)>0.6: raise ce.TipException(u"今日盈利已超过60%,请仔细核对数据或直接联系顽主!") if float(total_income)>20: raise ce.TipException(u"请仔细核对数据或直接联系顽主!") obj.today_income = round(today_income,4) obj.total_income = round(total_income,4) if not flag: obj.ctime = datetime.datetime.now() obj.save() #更新group_rank #ccc.cache.lpush(settings.RANK_LIST,obj.id) ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(obj.match_id,obj.id)) if model_name == "PlayerRecord": rst = {"id":obj.id,"user_id":obj.user_id,"match_id":match_id} return rst else: return obj.id obj = model.objects.create(**kwargs) return obj.id def update_model(cls,**kwargs): """ """ model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0] model = getattr(cm,model_name) id = kwargs.pop("id") rst = model.objects.filter(id=id).update(**kwargs) if model_name == "Match": for item in kwargs.get("groups").split(","): cm.MatchGroup.objects.get_or_create(match_id=obj.id,name=item) return rst def delete_model(cls,**kwargs): """ """ model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0] model = getattr(cm,model_name) ids = str(kwargs.get("id")).split(",") rst = model.objects.filter(id__in=ids).delete() if model_name == "Comments": cm.Comments.objects.filter(pid__in=ids).delete() return ids def get_search_list(cls,**kwargs): """ """ model_name = re.search(r'.*\.(\w+)SearchView',str(cls.__class__)).groups()[0] model = getattr(cm,model_name) qset = model.objects.all() if model_name == "Stock": if kwargs.get("name"): qset = qset.filter(Q(name__icontains=kwargs.get("name"))|Q(code__icontains=kwargs.get("name"))) else: if kwargs.get("name"): qset = qset.filter(name__icontains=kwargs.get("name")) if model_name == "Player": data = list(qset.values("id","username")) if model_name == "Stock": qset = qset.filter(code__isnull=False) data = list(qset.values("id","name","code")) for item in data: if item["code"]: item["label"] = "%s(%s)" % (item["name"],item["code"]) else: item["label"] = "%s" % item["name"] else: data = list(qset.values("id","name")) return data def get_detail_info(cls,**kwargs): """ """ model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0] model = getattr(cm,model_name) id = kwargs.get("id") rst = list(model.objects.filter(id=id).values()) rst = rst[0] if rst else {} if model_name == "Article": rst["ctime"] = ccf.datetime_to_str(rst["ctime"],"%Y-%m-%d") if model_name == "Stock": rst["choiced"] = ccc.cache.get("%s_choices" % id) rst["user_num"] = ccc.cache.get("%s_choices" % id) if model_name == "UserArticleRelation": article_ids = rst["article_ids"].split(",") articles = list(cm.Article.objects.filter(id__in=article_ids).values()) rst["articles"] = articles return rst #@ccc.cache_data() def get_record_info(rcid): """ """ rst = cm.PlayerRecord.objects.filter(id=rcid).values().first() if rst: rst["match_group"] = cm.MatchGroup.objects.filter(id=rst["match_group"]).first().name today_stock = json.loads(rst["today_stock"]) if rst["today_stock"] else [] today_stock = filter(lambda x:x["fund"] and x["name"],today_stock if today_stock else []) rst["today_stock"] = today_stock today_stock_img = json.loads(rst["today_stock_img"]) if rst["today_stock_img"] else [] rst["today_stock_img"] = today_stock_img yesterday_stock = json.loads(rst["yesterday_stock"]) if rst["yesterday_stock"] else [] yesterday_stock = filter(lambda x:x["fund"] and x["name"],yesterday_stock if yesterday_stock else []) rst["yesterday_stock"] = yesterday_stock yesterday_stock_img = json.loads(rst["yesterday_stock_img"]) if rst["yesterday_stock_img"] else [] rst["yesterday_stock_img"] = yesterday_stock_img rst["today_income"] = "{}%".format(rst["today_income"]*100) rst["total_income"] = "{}%".format(rst["total_income"]*100) return rst def get_list_info(cls,**kwargs): """ """ model_name = re.search(r'.*\.(\w+)ListView',str(cls.__class__)).groups()[0] model = getattr(cm,model_name) qset = model.objects.all() if kwargs.get("name"): qset = qset.filter(name__icontains=kwargs.get("name")) if model_name == "UserInfo": if kwargs.get("username"): qset = qset.filter(username__icontains=kwargs.get("username")) if kwargs.get("usercode"): qset = qset.filter(usercode=kwargs.get("usercode")) if model_name == "StockComments": if kwargs.get("stock_id"): qset = qset.filter(stock_id=kwargs.get("stock_id")) if model_name == "UserArticleRelation": data = list(qset.order_by("-id").values("id","user_id","user_name","user_avatar")) else: data = list(qset.order_by("-id").values()) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) if model_name == "Player": for item in data: user = cm.UserInfo.objects.filter(id=item["user_id"]).first() match = cm.Match.objects.filter(id=item["match_id"]).first() item["username"] = user.username item["usercode"] = user.usercode item["match_name"] = match.name if match else "" return (total,data) else: return len(data),data return rst def add_player_record_single(**kwargs): """用户单独上传数据 """ return None now = datetime.datetime.now() if now.weekday() in [5,6] or now.strftime("%Y-%m-%d") in MISS_DATES: raise ce.TipException(u"今日不能提交数据!") now_time = datetime.datetime.now().strftime("%H:%S") if now_time<"15:00" or now_time > "23:50": raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!") usercode = kwargs.get("usercode") match_id = kwargs.get("match_id") if not cm.Player.objects.filter(usercode=usercode,match_id=match_id).exists(): raise ce.TipException(u"用户代码错误") stock_date = kwargs.get("stock_date") #stock_date = "2022-04-26" stock_date = datetime.datetime.now().strftime("%Y-%m-%d") today_stock = json.dumps(kwargs.get("today_stock")) today_stock_img = json.dumps(kwargs.get("today_stock_img")) today_fund = float(kwargs.get("today_fund")) is_markt = int(kwargs.get("is_markt",0)) if int(today_fund)>9999 or int(today_fund)<0: raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!") player = cm.Player.objects.filter(usercode=usercode,match_id=match_id).first() #if player.fund <=0 : # raise ce.TipException(u"请先输入您的初始资金后再提交数据!") player_id = player.id user_id = player.user_id init_fund = player.fund user = cm.UserInfo.objects.filter(id=user_id).first() username = user.username usercode = user.usercode match_group = player.match_group match = cm.Match.objects.filter(id=match_id).first() if player.match_status < 1: raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!") now_date = datetime.datetime.now().strftime("%Y-%m-%d") if match.end_time < now_date: raise ce.TipException(u"该比赛已结束!") #yesterday = cm.PlayerRecord.objects.filter( # match_id=match_id,player_id=player_id).order_by("-id").first() yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter( match_id=match_id,player_id=player_id).order_by("-stock_date").first() if yesterday: yesterday_fund = yesterday.today_fund yesterday_stock = yesterday.today_stock yesterday_stock_img = yesterday.today_stock_img else: #yesterday_fund = init_fund yesterday_fund = today_fund init_fund = today_fund yesterday_stock = "" yesterday_stock_img = "" cm.Player.objects.filter(id=player_id).update(fund=today_fund) #记录持股情况 new_stock_list = [] today_stock_list = json.loads(today_stock) for ts in today_stock_list: if ts["name"]: stock,flag = cm.Stock.objects.get_or_create( name = ts["stock"] ) stock_id = stock.id usobj,flag = cm.UserStock.objects.get_or_create( player_id = player_id, stock_id = stock_id, stock_name = ts["name"], stock_date = stock_date ) ts["stock_id"] = stock_id new_stock_list.append(ts) today_stock = json.dumps(new_stock_list) obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create( player_id=player_id, match_id=match_id, stock_date=stock_date) obj.init_fund = init_fund obj.yesterday_fund = yesterday_fund obj.yesterday_stock = yesterday_stock obj.yesterday_stock_img = yesterday_stock_img obj.today_fund = today_fund obj.today_stock = today_stock obj.today_stock_img = today_stock_img obj.user_id = user_id obj.username = username obj.usercode = usercode obj.match_group = match_group obj.is_markt = is_markt #计算今日和昨日盈亏 today_income = (today_fund - yesterday_fund)/float(yesterday_fund) total_income = (today_fund - init_fund)/float(init_fund) #if int(today_fund)>9999 or int(today_fund)<0: # raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!") if int(today_income)>2: raise ce.TipException(u"数据错误,今日盈利已超过2倍,请仔细核对数据!") obj.today_income = round(today_income,4) obj.total_income = round(total_income,4) if not flag: obj.ctime = datetime.datetime.now() obj.save() #更新股票持股人数 for stock in new_stock_list: cm.Stock.objects.filter(id=stock["id"]).update(user_num=F("user_num")+1) #更新group_rank #update_group_rank(match_id,match_group,obj.stock_date) ccc.cache.lpush(settings.RANK_LIST,obj.id) return obj.id def get_single_match_info(match_id): """ """ if not match_id: match = cm.Match.objects.all().order_by("-id").values().first() else: match = cm.Match.objects.filter(id=match_id).values().first() now_date = datetime.datetime.now().strftime("%Y-%m-%d") return now_date,match def get_cur_record(request): """ """ user_id = request.user.get("id") match_id = ccc.get_cur_match().id stock_date = datetime.datetime.now().strftime("%Y-%m-%d") qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id,stock_date=stock_date).order_by("-stock_date") data = qset.values().first() if qset else {} if data: data["today_stock_img"] = json.loads(data["today_stock_img"]) if data["today_stock_img"] else [] data["today_stock"] = json.loads(data["today_stock"]) if data["today_stock"] else [] return data def follow_player(**kwargs): """ """ user_id = kwargs.get("user_id") follow_id = kwargs.get("follow_id") if kwargs.get("action") == "cancel": cm.UserFollows.objects.filter(user_id=user_id,follow_id=follow_id).delete() return True else: obj,flag = cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=follow_id) return obj.id def calc_win_rate(player_id,match_id): """计算胜率 """ qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=player_id) win_rate = qset.filter(today_income__gt=0).count()/float(qset.count()) if qset else 0.0 win_rate = round(win_rate,3) win_rate = "{}%".format(win_rate*100) return win_rate def get_user_follower(request): """获取用户列表 """ user_id = request.user.get("id") match_id = ccc.get_cur_match().id qdata = request.json if qdata.get("user_id"): user_id = int(qdata.get("user_id")) _today = get_today_date() data = [] qset = cm.UserFollows.objects.filter(follow_id=user_id) follow_ids = list(qset.values_list("user_id",flat=True)) userset = cm.UserInfo.objects.filter(id__in=follow_ids) data = list(userset.values()) page = int(qdata.get("page",1)) page_size = int(qdata.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) return total,data else: return len(data),data # for player_id in follow_ids: latest_key = "PLAYER_LATEST_%d"%player_id _match_id = ccc.cache.hget(latest_key,"match_id") _today = ccc.cache.hget(latest_key,"stock_date") _match_group = ccc.cache.hget(latest_key,"match_group") today_record = ccc.get_today_record(player_id,_match_id,_match_group,_today) if today_record: data.append(today_record) #data.append(today_record) data = sorted(data,key=lambda x:x["stock_date"],reverse=True) _today = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"stock_date") cur_user_latest = "PLAYER_LATEST_%d" % user_id _match_group = ccc.cache.hget(cur_user_latest,"match_group") cur_today_record = ccc.get_today_record(user_id,match_id,_match_group,_today) if cur_today_record: data.insert(0,cur_today_record) page = int(qdata.get("page",1)) page_size = int(qdata.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) for item in data: if item: today_stock = json.loads(item["today_stock"]) today_stock = filter(lambda x:x["name"] and x["fund"],today_stock) item["today_stock"] = today_stock item["today_stock_img"] = json.loads(item["today_stock_img"]) win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate") if win_rate: item["win_rate"] = str(float(win_rate)*100)+"%" else: item["win_rate"] = "0.0%" item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) if item.get("phone"): del item["phone"] return total,data else: return len(data),data def get_user_follows(request): """获取用户关注的选手列表 """ user_id = request.user.get("id",0) qdata = request.json if qdata.get("user_id"): user_id = qdata.get("user_id") qset = cm.UserFollows.objects.filter(user_id=user_id) follow_ids = list(qset.values_list("follow_id",flat=True)) userset = cm.UserInfo.objects.filter(id__in=follow_ids) data = list(userset.values()) page = int(qdata.get("page",1)) page_size = int(qdata.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) for item in data: if item.get("phone"): del item["phone"] return total,data else: return len(data),data today = get_today_date() _today = today data = [] for user_id in follow_ids: latest_key = "PLAYER_LATEST_%d"%user_id _match_id = ccc.cache.hget(latest_key,"match_id") _today = ccc.cache.hget(latest_key,"stock_date") _match_group = ccc.cache.hget(latest_key,"match_group") today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today) if today_record: today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0 today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count() data.append(today_record) data = sorted(data,key=lambda x:x["stock_date"],reverse=True) page = int(qdata.get("page",1)) page_size = int(qdata.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) for item in data: if item: try: user_id = item["user_id"] latest_key = "PLAYER_LATEST_%d"%user_id today_stock = json.loads(item["today_stock"]) today_stock = filter(lambda x:x["name"] and x["fund"],today_stock) item["today_stock"] = today_stock item["today_stock_img"] = json.loads(item["today_stock_img"]) win_rate = ccc.cache.hget(latest_key,"win_rate") if win_rate: item["win_rate"] = str(float(win_rate)*100)+"%" else: item["win_rate"] = "0.0%" item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) item["zans_count"] = item.get("zans",0) item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count() del item["phone"] except Exception as e: print(e) return total,data else: return len(data),data def get_hot_stock_rank(**kwargs): """ """ data = { "hot_buy":[ {"stock_name":u"创业黑马","count":12} ], "hot_sell":[ {"stock_name":u"创业黑马","count":12} ] } return data #@ccc.cache_data() def get_stock_info(stock_id): """ """ stock = cm.Stock.objects.filter(id=stock_id).values().first() stock["choiced"] = 1 nbc = cm.StockComments.objects.filter(stock_id=stock_id).order_by("-id").values().first() if nbc: stock["last_nb_comments"] = nbc return stock @ccc.cache_data() def get_stock_cache(stock_id): stock = cm.Stock.objects.filter(id=stock_id).values().first() return stock def get_hot_stock_buy(**kwargs): """ """ stock_date = kwargs.get("stock_date") month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1]) qset = cm.UserStock.get_db_model(month).objects.filter(stock_date=stock_date,fund__gt=0) if kwargs.get("name"): qset = qset.filter(stock_name__icontains=kwargs.get("name"),stock_date=stock_date) if int(kwargs.get("fund_rank",0)) == 1: qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-total_fund") else: qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-count") data = [] for q in qset: stock_id = q["stock_id"] count = q["count"] stock_name = q.get("stock_name") total_fund = q["total_fund"] comments_count = ccc.cache.get("%s_comments" % stock_id) choice_count = ccc.cache.get("%s_choices" % stock_id) comments_count = comments_count if comments_count else 0 choice_count = choice_count if choice_count else 0 data.append({"stock_name":stock_name,"id":stock_id,"count":count,"comments_count":comments_count,"choice_count":choice_count,"total_fund":total_fund}) page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) for item in data: #stock = cm.Stock.objects.filter(id=item["id"]).first() stock = get_stock_cache(item["id"]) if stock: item["stock_code"] = stock.get("code","") item["stock_desc"] = stock.get("desc","") return total,data else: return len(data),data return data def get_hot_follow(**kwargs): """ """ stock_date = kwargs.get("stock_date") match_id = kwargs.get("match_id") if not match_id: match_id = ccc.get_cur_match().id #player_ids = list(cm.Player.objects.filter(match_id=cur_match_id,match_status=1).values_list("id",flat=True)) player_ids = list(cm.Player.objects.filter(match_id=match_id).values_list("user_id",flat=True)) qset = cm.UserFollows.objects.filter(follow_id__in=player_ids) qset = qset.values("follow_id").annotate(count=Count("follow_id")).order_by("-count") data = [] for q in qset: player_id = q["follow_id"] count = q["count"] today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date") match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id") match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group") badest_income = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"badest_income") today_record = get_today_record(player_id,match_id,match_group,today) if today_record: userinfo = get_user_info(today_record["user_id"]) user_id = today_record["user_id"] win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"win_rate") try: win_rate = str(float(win_rate)*100)+"%" except: pass if userinfo: data.append( { "player_name":userinfo.get("username"), "count":count, "id":player_id, "user_id":user_id, "today_fund":today_record["today_fund"], "total_income":"{}%".format(today_record["total_income"]*100), "today_income":"{}%".format(today_record["today_income"]*100), "badest_income":"{}%".format(badest_income*100) if badest_income else "0.0%", "style":userinfo.get("style"), "badge":userinfo.get("badge"), "match_id":match_id, "win_rate":win_rate } ) if kwargs.get("name"): data = filter(lambda x:kwargs.get("name") in x["player_name"],data) page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) return total,data else: return len(data),data return data def get_hot_stock_sell(**kwargs): """ """ stock_date = kwargs.get("stock_date") stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d") yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d") ##昨天所有股票 #yes_stock_ids = list(cm.UserStock.objects.filter(stock_date=yesterday).values_list("stock_id",flat=True)) #yes_stock_ids = list(set(yes_stock_ids)) #data = [] #for ysi in yes_stock_ids: # yes_count = cm.UserStock.objects.filter(stock_date=yesterday,stock_id=ysi).count() # td_count = cm.UserStock.objects.filter(stock_date=stock_date,stock_id=ysi).count() # if td_count < yes_count: # stock_name = cm.Stock.objects.filter(id=ysi).first().name # data.append({"stock_name":stock_name,"count":yes_count-td_count,"id":ysi}) qset = cm.HotStockSellCount.objects.filter(stock_date=stock_date) if kwargs.get("name"): qset = qset.filter(stock_name__icontains=kwargs.get("name")) qset = qset.order_by("-count") data = list(qset.values("stock_name","stock_id","count")) for item in data: item["id"] = item["stock_id"] page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) return total,data else: return len(data),data return data def get_stock_info(_id): """ """ data = cm.Stock.objects.filter(id=_id).values().first() nbc = cm.StockComments.objects.filter(stock_id=_id).order_by("-id").values().first() if nbc: data["last_nb_comments"] = nbc return data def get_hot_stock_sell_players(**kwargs): """ """ _id = kwargs.get("id") stock_date = kwargs.get("stock_date") month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1]) stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d") yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d") #昨天持股选手 yes_players = list(cm.UserStock.get_db_model(month).objects.filter(stock_date=yesterday,stock_id=_id).values_list("player_id",flat=True)) td_players = list(cm.UserStock.get_db_model(month).objects.filter(stock_date=stock_date,stock_id=_id).values_list("player_id",flat=True)) sell_players = list(set(yes_players)-set(td_players)) data = [] for player_id in sell_players: #player = cm.Player.objects.filter(id=player_id).first() player = get_player_info_cache(player_id) if player: match_id = player["match_id"] match_group = player["match_group"] today_record = get_today_record(player_id,match_id,match_group,stock_date) if today_record: today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else [] today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else [] today_record["today_income"] = "{}%".format(today_record["today_income"]*100) today_record["total_income"] = "{}%".format(today_record["total_income"]*100) data.append(today_record) data = sorted(data,key=lambda x:x["today_fund"],reverse=True) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) return total,data else: return len(data),data return data def get_win_rate_rank(request): """ """ player_id = request.player.id match_id = request.player.match_id match_group = request.player.match_group kwargs = request.json match_id = ccc.get_cur_match().id qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lt=5,match_status=1).order_by("-win_rate") data = list(qset.values()) page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) for item in data: item["win_rate"] = "{}%".format(item["win_rate"]*100) item["badest_income"] = "{}%".format(item["badest_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) userinfo = get_user_info(item["user_id"]) if userinfo: item["badge"] = userinfo.get("badge") item["style"] = userinfo.get("style") item["username"] = userinfo.get("username") return total,data def get_defend_rank(request): """ """ player_id = request.player.id match_id = request.player.match_id match_group = request.player.match_group kwargs = request.json qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lte=5,match_status=1).order_by("-badest_income") data = list(qset.values()) #data = [] #for item in datas: # player = cm.Player.objects.filter(id=item["player_id"]).first() # item["match_status"] = player.match_status if player else -1 # if item["match_status"] > -1: # data.append(item) page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) for item in data: item["win_rate"] = "{}%".format(item["win_rate"]*100) item["badest_income"] = "{}%".format(item["badest_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) userinfo = get_user_info(item["user_id"]) if userinfo: item["badge"] = userinfo.get("badge") item["style"] = userinfo.get("style") item["username"] = userinfo.get("username") return total,data @ccc.cache_data_kw(10*60) def get_champion_articles_list(**kwargs): """ """ #kwargs = request.json _type = kwargs.get("type") isbanner = kwargs.get("isbanner") category = kwargs.get("category") qset = cm.Article.objects.filter(status=2).exclude(type="notice").order_by("-isbanner","-ishot","-id") if _type: qset = qset.filter(type=_type) if isbanner: qset = qset.filter(isbanner=isbanner) if category: qset = qset.filter(category=category) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() data = list(qset.values("name","ctime","id","img")) for item in data: item["ctime"] = ccf.datetime_to_str(item["ctime"],"%Y-%m-%d") return total,data def get_wanzhu_comment(**kwargs): """ """ match_id = kwargs.get("match_id") group_id = kwargs.get("group_id") today = get_today_date() players = get_match_group_players(match_id,group_id) new_players = [] for player in players: user_id = player["user_id"] user = get_user_info(user_id) username = user["username"] if user else "" player_id = player["id"] match_group = group_id today_record = get_today_record(player_id,match_id,int(match_group),today) if today_record and today_record.get("wanzhu_comment"): player.update(today_record) player["username"] = username player["total_income"] = "{}%".format(player["total_income"]*100) player["fund"] = round(player["fund"],4) player["init_fund"] = round(player["init_fund"],4) player["today_fund"] = round(player["today_fund"],4) player["today_stock"] = json.loads(player["today_stock"]) if player["today_stock"] else [] new_players.append(player) new_players = sorted(new_players,key=lambda x:x["group_rank"]) data = new_players page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) return total,data def get_enum_list(request): """ """ data = { "zq":[ u"短线博弈", u"长线价投", u"长短兼备" ], "cw":[ u"分仓开超市", u"重仓押注", u"全仓单钓", u"融资加倍" ], "df":[ u"低吸", u"半路", u"首板", u"接力", u"撬板", u"T加0", u"隔夜卖", u"格局锁仓", u"核按钮" ], "pz":[ u"10厘米", u"20厘米", u"30厘米", u"N/C新股", u"次新股", u"可转债", u"港股", u"基金", u"逆回购" ] } return data def get_player_list(**kwargs): """选手列表 """ match_id = kwargs.get("match_id") today = get_today_date() #qset = cm.Player.objects.filter(match_id=match_id,match_status=1) qset = cm.Player.objects.filter(match_status=1) if kwargs.get("name"): qset = qset.filter(username__icontains=kwargs.get("name")) qset = qset.values("username").distinct().order_by("-id") page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() data = list(qset.values()) for item in data: #print(item) match_id = item["match_id"] match_group = item["match_group"] user_id = item["user_id"] player_id = item["id"] #user = cm.UserInfo.objects.filter(id=user_id).first() today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date") match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id") match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group") today_record = get_today_record(player_id,match_id,match_group,today) if today_record: today_record.pop("id") item.update(today_record) user_info = get_user_info(user_id) if user_info: user_info.pop("id") item.update(user_info) if item.get("today_income"): item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) if kwargs.get("zq"): data = filter(lambda x:kwargs.get("zq") == x.get("zq"),data) if kwargs.get("cw"): data = filter(lambda x:kwargs.get("cw") == x.get("cw"),data) if kwargs.get("df"): data = filter(lambda x:kwargs.get("df") == x.get("df"),data) return total,data def get_mine_style(request): """ """ user = request.user #player = request.player user = cm.UserInfo.objects.filter(id=user["id"]).first() match_id = ccc.get_cur_match().id player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first() data = { "zq":user.zq, "cw":user.cw, "df":user.df, "pz":user.pz, "join_time":user.join_time, "username":user.username, "account_img":user.account_img, "avatar":user.avatar } if player: data["is_player"] = 1 data["init_fund"] = player.fund if player.fund else 0 else: data["is_player"] = 0 data["init_fund"] = None return data def update_user_style(**kwargs): """ """ user_id = kwargs.pop("user_id") #player_id = kwargs.pop("player_id") if kwargs.get("init_fund"): init_fund = kwargs.pop("init_fund") try: init_fund = kwargs.pop("init_fund") except Exception as e: print(e) #avatar = kwargs.pop("avatar") if re.search(settings.FORBID_NAME,kwargs.get("username")): raise ce.TipException(u"名字中包含特殊关键字,请更换名称后重试!") cm.UserInfo.objects.filter(id=user_id).update(**kwargs) #if player_id and init_fund: # cm.Player.objects.filter(id=player_id).update(fund=init_fund) if kwargs.get("username"): cm.Player.objects.filter(user_id=user_id).update(username=kwargs.get("username")) match_id = ccc.get_cur_match().id upset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id) upset.update(username=kwargs.get("username")) record_ids = list(upset.values_list("id",flat=True)) for _id in record_ids: ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(match_id,_id)) if kwargs.get("avatar"): cm.UserInfo.objects.filter(id=user_id).update(avatar=kwargs.get("avatar")) ccc.cache.delete("cdata_get_user_info_(%sL,)"%user_id) return True def get_stock_players(**kwargs): """ """ stock_id = kwargs.get("stock_id") stock_date = kwargs.get("stock_date",get_today_date()) month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1]) print(month) data = [] user_stocks = cm.UserStock.get_db_model(month).objects.filter(stock_id=stock_id,stock_date=stock_date,fund__gt=0.0) for us in user_stocks: player_id = us.player_id #player = cm.Player.objects.filter(id=player_id).first() player = get_player_info_cache(player_id) if player: match_id = player["match_id"] match_group = player["match_group"] user_id = player["user_id"] if stock_date: today_record = get_today_record(user_id,match_id,match_group,stock_date) else: today_record = get_today_record(user_id,match_id,match_group,us.stock_date) if today_record: today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else [] today_stock = json.loads(today_record["today_stock"]) if today_record["today_stock"] else [] today_stock = list(filter(lambda x:float(x.get("fund",0) if x.get('fund') else 0)>0.0,today_stock)) today_record["today_stock"] = today_stock today_record["today_income"] = "{}%".format(today_record["today_income"]*100) today_record["total_income"] = "{}%".format(today_record["total_income"]*100) #today_record["cur_stock_fund"] = 0.0 for item in today_record["today_stock"]: if 'stock_id' not in item: today_record["cur_stock_fund"] = 0.0 continue if int(item["stock_id"]) == int(stock_id): today_record["cur_stock_fund"] = float(item["fund"]) if item["fund"] else 0.0 else: today_record["cur_stock_fund"] = 0.0 data.append(today_record) #data = sorted(data,key=lambda x:x["today_fund"],reverse=True) data = sorted(data,key=lambda x:x.get("cur_stock_fund",0),reverse=True) #分页 page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) #return total,data #return data if kwargs.get("v3"): return total,data else: return data def update_user_fund(**kwargs): """ """ user_id = kwargs.pop("user_id") player_id = kwargs.pop("player_id") init_fund = kwargs.pop("init_fund") if player_id and init_fund: cm.Player.objects.filter(id=player_id).update(fund=init_fund) return True def get_player_match_calendar(**kwargs): """ """ match_id = kwargs.get("match_id") month = kwargs.get("month") user_id = kwargs.get("user_id") week,eday = calendar.monthrange(int(month.split("-")[0]),int(month.split("-")[1])) sday = "01" eday = str(eday).zfill(2) sdate = month + "-" + sday edate = month + "-" + eday qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id)\ .filter(stock_date__gte=sdate,stock_date__lte=edate) data = list(qset.values()) dct = {} for item in data: item["today_income"] = "{}%".format(item["today_income"]*100) #dct[item["stock_date"]] = item["today_income"] dct[item["stock_date"]] = [item["today_income"],item["id"]] newdata = [] for i in range(1,int(eday)+1): stock_date = month + "-" + str(i).zfill(2) today_tpl = dct.get(stock_date,[]) today_income = today_tpl[0] if today_tpl else None record_id = today_tpl[1] if today_tpl else None newdata.append({ "stock_date":stock_date, "today_income":today_income, "record_id":record_id }) return newdata def get_all_match(request): """ """ now = datetime.datetime.now().strftime("%Y-%m-%d") #qset = cm.Match.objects.filter(start_time__lte=now).order_by("id") qset = cm.Match.objects.filter(match_status__in=[3,4]).order_by("-id") data = list(qset.values()) for item in data: valid_dates = json.loads(item["valid_dates"]) if item["valid_dates"] else [] valid_dates.sort() item["valid_dates"] = valid_dates return data def get_default_date(**kwargs): """ """ match_id = kwargs.get("match_id") if not match_id: match_id = ccc.get_cur_match().id record = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).order_by("-stock_date").first() if record: return record.stock_date else: return get_today_date() @ccc.cache_data() def get_stock_search(**kwargs): """ """ qset = cm.Stock.objects.all() data = list(qset.values("id","name","code")) for item in data: if item["code"]: item["label"] = "%s(%s)" % (item["name"],item["code"]) else: item["label"] = "%s" % item["name"] return data def get_mine_latest(request): """ """ try: user_id = request.user.get("id") cur_match_id = ccc.get_cur_match().id match_id = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_id") if cur_match_id != int(match_id): return {"player_id":user_id,"match_id":match_id,"user_id":user_id} match_group = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_group") _today = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"stock_date") if _today: rst = ccc.get_today_record(int(user_id),int(match_id),int(match_group),_today) if rst: rst["today_income_fund"] = round((rst["today_fund"] - rst["yesterday_fund"])*10000,2) if rst["yesterday_fund"] else 0.00 rst["today_income"] = "{}%".format(rst["today_income"]*100) rst["total_income"] = "{}%".format(rst["total_income"]*100) rst["zan_count"] = rst.get("zans",0) rst["comments_count"] = cm.Comments.objects.filter(record_id=rst.get("id",0)).count() return rst except Exception as e: print(e) return {"player_id":user_id,"match_id":match_id,"user_id":user_id} #@ccc.cache_data() def get_match_validdates(match_id): """ """ #qdata = request.json #match_id = qdata.get("match_id") match = cm.Match.objects.filter(id=match_id).first() if match: validdates = json.loads(match.valid_dates) if match.valid_dates else [] validdates.sort() return validdates return [] def send_phcode(request): """ """ qdata = request.json phone = qdata.get("phone") code = "%s%s%s%s" % (random.randint(0,9),random.randint(0,9),random.randint(0,9),random.randint(0,9)) send_verify_code(phone,code) ccc.cache.set(phone,code,120) pass def get_signup_info(request): """ """ qdata = request.json try: user_id = request.user.get("id",0) except: user_id = 0 try: match_id = ccc.get_signup_match().id match = cm.Match.objects.filter(id=match_id).values().first() # match_groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).values()) match["groups"] = match_groups #报名状态 now = datetime.datetime.now().strftime("%Y-%m-%d") signup_start_time = match["signup_start_time"] signup_end_time = match["signup_end_time"] if signup_start_time <= now and signup_end_time >= now: match["signup_status"] = 1 else: match["signup_status"] = 0 if cm.Player.objects.filter(match_id=match_id,user_id=user_id,match_group__isnull=False).filter(role__in=[1,2]).exists(): match["signup_done"] = 1 else: match["signup_done"] = 0 return match except Exception as e: print(e) return {} def do_wx_pay(request): """ """ user = request.user user_id = request.user.get("id",0) user_name = request.user.get("username","") openid = request.user.get("openid","") qdata = request.json match_id = qdata.get("match_id") match_name = qdata.get("match_name") signup_type = qdata.get("signup_type") total_fee = str(qdata.get("total_fee")) phone = qdata.get("phone") phcode = qdata.get("phcode") match_group = qdata.get("match_group") signup_name = qdata.get("signup_name") pay_type = qdata.get("pay_type") opmode_group = qdata.get("opmode_group") if user.get("forbid_status") == 1: raise ce.TipException(u"您暂时不能报名,请联系客服!") if not signup_name: signup_name = user_name orgcode = ccc.cache.get(phone) print(signup_name) if re.search(settings.FORBID_NAME,signup_name): raise ce.TipException(u"名字中包含特殊关键字,请更换名称后重试!") if not phone == "13883187629": if not phcode == orgcode: raise ce.TipException(u"验证码不正确!") if int(signup_type) == 1: if not match_group: match_group = cm.MatchGroup.objects.filter(match_id=match_id,charge=0).first().id if pay_type == "wxapppay": out_trade_no = "WXAPP"+datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000)) else: out_trade_no = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000)) #游客和普通选手付费报名 #gt_time = datetime.timedelta(days=-365)+datetime.datetime.now() #old_player = cm.Player.objects.filter(user_id=user_id,match_status=1,ctime__gte=gt_time).exists() #if user["player_type"] in [0,1] and not phone=="13883187629": if user["player_type"] in [0,1] and not phone=="13883187629": #生成订单 order = cm.SignupOrder.objects.create( user_id = user_id, user_name = signup_name, match_id = match_id, match_name = match_name, signup_type = signup_type, total_fee = total_fee, out_trade_no = out_trade_no, phone = phone, match_group = match_group, signup_name = signup_name, opmode_group = opmode_group ) #支付 if pay_type == "wxapppay": total_fee = str(int(float(order.total_fee)*100)) notify_url = "https://api.hunanwanzhu.com/api/wx/v3/signup/notify" #notify_url = "https://test.hunanwanzhu.com" data = {"subject":u"%s报名费" % match_name,"price":total_fee,"out_trade_no":out_trade_no} wxapppay = WechatPayDAL() prepayinfo = wxapppay.create_order_info(data,notify_url) return prepayinfo else: total_fee = str(int(float(order.total_fee)*100)) prepayinfo = wxpay.get_wx_unifiedorder(out_trade_no,total_fee,openid) prepayinfo["key"] = wxpay.WxPayConf_pub.KEY return prepayinfo #种子选手和开户选手免费报名 else: if signup_type == 1: signup_name = user_name #生成订单 order = cm.SignupOrder.objects.create( user_id = user_id, user_name = signup_name, match_id = match_id, match_name = match_name, signup_type = signup_type, total_fee = total_fee, out_trade_no = out_trade_no, phone = phone, match_group = match_group, signup_name = signup_name, opmode_group = opmode_group ) user = cm.UserInfo.objects.filter(id=user_id).first() #生成选手信息 cur_match = cm.Match.objects.filter(id=match_id).first() visit_group = cm.MatchGroup.objects.filter(id=match_group).first() #opmode_group_obj = cm.OpModelGroup.objects.filter(id=opmode_group).first() player,flag = cm.Player.objects.get_or_create( user_id = user.id, match_id = cur_match.id ) player.match_name = cur_match.name player.match_group = visit_group.id player.match_group_name = visit_group.name #player.opmode_group = opmode_group_obj.id #player.opmode_group_name = opmode_group_obj.name player.username = signup_name player.usercode = request.user.get("usercode") player.role = 2 player.match_status = 1 player.save() # order.player_id = player.id order.save() user.username = signup_name user.phone = phone user.role = 2 user.save() #发送报名成功信息 #send_signup_success(phone,signup_name) if phone == "13883187629": for i in [5001,4762,5173,5141]: cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=i) return {"free":1} def do_wxpay_notify(request): qdata = request.json if qdata.get("resource_type") == "encrypt-resource": wxapppay = WechatPayDAL() res = wxapppay.decrypt_nofify_v3(qdata) res = json.loads(res) flag = True else: flag,res = wxpay.check_notify_valid(request.body) if flag: out_trade_no = res.get("out_trade_no") transaction_id = res.get("transaction_id") pay_time = res.get("time_end") try: sorder = cm.SignupOrder.objects.filter(out_trade_no=out_trade_no).first() if sorder and not sorder.transaction_id: now = datetime.datetime.now() sorder.order_status = 1 sorder.pay_status = 1 sorder.pay_time = now sorder.transaction_id = transaction_id sorder.save() #生成选手信息 user = cm.UserInfo.objects.filter(id=sorder.user_id).first() visit_group = cm.MatchGroup.objects.filter(id=sorder.match_group).first() player,flag = cm.Player.objects.get_or_create( user_id = sorder.user_id, match_id = sorder.match_id ) player.match_name = sorder.match_name player.match_group = visit_group.id player.match_group_name = visit_group.name player.username = sorder.user_name player.usercode = user.usercode if user else "" if sorder.signup_type == 2: player.role = 2 else: player.role = 1 # sorder.player_id = player.id sorder.save() player.save() if sorder.signup_type == 2: player_id = sorder.player_id user_id = sorder.user_id match_group = sorder.match_group match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name cm.Player.objects.filter(id=player_id).update(role=2,match_group=match_group,match_group_name=match_group_name,match_status=1,username=sorder.signup_name) cm.UserInfo.objects.filter(id=user_id).update(role=2,phone=sorder.phone,username=sorder.user_name) if sorder.signup_type == 1: player_id = sorder.player_id user_id = sorder.user_id cm.Player.objects.filter(id=player_id).update(role=1,match_status=1) cm.UserInfo.objects.filter(id=user_id).update(role=1,phone=sorder.phone,username=sorder.user_name) #发送报名成功信息 #send_signup_success(sorder.phone,sorder.signup_name) return True except Exception as e: import traceback traceback.print_exc() print(e,111111111111) return False def get_user_comments(request): """ """ kwargs = request.json stock_id = kwargs.get("stock_id") record_id = kwargs.get("record_id") match_id = kwargs.get("match_id") if record_id: if match_id: qset = cm.Comments.objects.filter(record_id=record_id,match_id=match_id,pid__isnull=True).order_by(*["-istop","-id"]) else: qset = cm.Comments.objects.filter(record_id=record_id,pid__isnull=True).order_by(*["-istop","-id"]) else: qset = cm.Comments.objects.filter(stock_id=stock_id,pid__isnull=True).order_by(*["-istop","-id"]) data = list(qset.values()) for item in data: if record_id: subcomments = cm.Comments.objects.filter(record_id=record_id,pid=item["id"]) else: subcomments = cm.Comments.objects.filter(stock_id=stock_id,pid=item["id"]) item["children"] = list(subcomments.values()) #分页 page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) return total,data def get_user_choices(request): """ """ user_id = request.user.get("id",0) #match_id = request.player.match_id kwargs = request.json stock_id = kwargs.get("stock_id") if stock_id: qset = cm.UserChoice.objects.filter(stock_id=stock_id) else: qset = cm.UserChoice.objects.filter(user_id=user_id) data = list(qset.values()) for item in data: stock_id = item["stock_id"] comments_count = ccc.cache.get("%s_comments" % stock_id) choice_count = ccc.cache.get("%s_choices" % stock_id) comments_count = comments_count if comments_count else 0 choice_count = choice_count if choice_count else 0 item["count"] = choice_count item["comments_count"] = comments_count item["choice_count"] = choice_count #item["match_id"] = match_id #分页 page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) return total,data def get_user_consult_list(request): """ """ player_id = request.user.get("id") if request.user else 0 if not player_id: return 0,[] kwargs = request.json record_id = kwargs.get("record_id") if kwargs.get("user_id"): player_id = kwargs.get("user_id") qset = cm.WanzhuConsult.objects.filter(user_id=player_id,user_id__gt=0) qdata = list(qset.values()) data = [] for item in qdata: data.append(item) if cm.WanzhuConsult.objects.filter(pid=item["id"]).exists(): reply_list = cm.WanzhuConsult.objects.filter(Q(pid=item["id"])).values() for iitem in reply_list: data.append(iitem) if kwargs.get("sort") == "desc": data = sorted(data,key=lambda x:x["id"],reverse=True) else: data = sorted(data,key=lambda x:x["id"]) #分页 page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",1000)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) for item in data: user_id = item["user_id"] user = cm.UserInfo.objects.filter(id=user_id).first() if user: item["usercode"] = user.usercode return total,data def get_user_zans(request): """ """ qdata = request.json record_id = qdata.get("record_id") match_id = qdata.get("match_id") zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans return zans def get_user_comments_count(request): """ """ qdata = request.json record_id = qdata.get("record_id") count = cm.Comments.objects.filter(record_id=record_id).count() return count def add_wanzhu_consult(request): """咨询顽主 """ user_id = request.user.get("id",0) user_name = request.user.get("username") user_avatar = request.user.get("avatar") user_code = request.user.get("usercode") phone = request.user.get("phone") openid = request.user.get("openid") qdata = request.json content = qdata.get("cotent") width = qdata.get("width") height = qdata.get("height") pid = qdata.get("pid") wanzhu_obj = cm.WanzhuConsult.objects.create( user_id = user_id, user_name = user_name, user_avatar = user_avatar, content = content, pid = pid ) wanzhu_obj.user_code = user_code wanzhu_obj.phone = phone wanzhu_obj.width = width wanzhu_obj.height = height wanzhu_obj.save() obj,flag = cm.Consult.objects.get_or_create( user_id = user_id, ) obj.user_name = user_name obj.user_avatar = user_avatar obj.user_code = user_code obj.phone = phone obj.content = content obj.view_status = 0 obj.reply_status = 0 obj.width = width obj.height = height obj.ctime = datetime.datetime.now() obj.save() #自动回复 if cm.WanzhuConsult.objects.filter(user_id=user_id).count() <=1: content = u"您好,后台消息一般三小时内回复,如果超出时间请加微信destination8888" cm.WanzhuConsult.objects.create( pid = pid, reply_content = content, user_id = 0, player_id = 0, reply_user_id = user_id ) #发送消息提醒 if cm.UserInfo.objects.filter(id=user_id).exists(): user = cm.UserInfo.objects.filter(id=user_id).first() send_consult_reply_message(openid,user_name) #发送app推送消息 title = u"顽主杯" body = u"你收到一条顽主的消息" params = {"type":"message","id":str(user_id)} aliyunpush.push_notice_by_userid(0,title,body,params,"ios") aliyunpush.push_notice_by_userid(0,title,body,params,"android") #退款短信通知 # if '退款' in content: # send_verify_code('18397565872','0000') def add_comments(request): """ """ #if request.user.comment_status == 0: # raise ce.TipException(u"对不起,暂无法评论/留言!") user_id = request.user.get("id") user_name = request.user.get("username") user_avatar = request.user.get("avatar") qdata = request.json content = qdata.get("cotent") record_id = qdata.get("record_id") stock_id = qdata.get("stock_id") pid = qdata.get("pid") match_id = qdata.get("match_id") target_user_id = qdata.get("target_user_id") ip = ccf.get_ip(request) location = ccf.get_city_from_ip(ip) if record_id and target_user_id: if cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=target_user_id).exists(): raise ce.TipException(u"对不起,暂无法评论/留言!") obj = cm.Comments.objects.create( user_id = user_id, user_name = user_name, user_avatar = user_avatar, content = content, record_id = record_id, pid = pid, ip = ip, location = location, stock_id = stock_id, match_id = match_id ) if record_id: cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(comments_count=F("comments_count")+1) if stock_id: ccc.cache.incr("%s_comments" % stock_id,1) def add_choice(request): """ """ user_id = request.user.get("id") user_name = request.user.get("username") user_avatar = request.user.get("avatar") qdata = request.json stock_id = qdata.get("stock_id") stock_name = cm.Stock.objects.filter(id=stock_id).first().name obj = cm.UserChoice.objects.create( user_id = user_id, user_name = user_name, user_avatar = user_avatar, stock_id = stock_id, stock_name = stock_name ) if stock_id: ccc.cache.incr("%s_choices" % stock_id,1) def add_zan(request): """ """ qdata = request.json record_id = qdata.get("record_id") match_id = qdata.get("match_id") cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(zans=F("zans")+1) zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans return zans @ccc.cache_data_kw(10*60) def get_experience_list(**kwargs): """ """ #return 0,[] #kwargs = request.json today = get_today_date() match_id = ccc.get_cur_match().id match_group = kwargs.get("match_group") #冠军组、千万组、百万组 grpset = cm.MatchGroup.objects.filter(match_id=match_id).filter(Q(name__icontains=u"千万组")|Q(name__icontains=u"百万组")|Q(name__icontains=u"冠军组")) if match_group: grpset = grpset.filter(id=match_group) qbw_ids = list(grpset.values_list("id",flat=True)) qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=today,match_group__in=qbw_ids).filter(Q(experience__isnull=False)&~Q(experience="")).order_by("-total_income") data = list(qset.values("id","user_id","username","today_fund","today_income","total_income","experience","match_id","today_stock_img","zans","comments_count","stock_date")) for item in data: record_id = item["id"] user_id = item["user_id"] try: item["user_avatar"] = get_user_info(user_id)["avatar"] item["avatar"] = get_user_info(user_id)["avatar"] except: item["user_avatar"] = "" item["avatar"] = "" item["zans_count"] = item["zans"] item["today_stock_img"] = json.loads(item["today_stock_img"]) win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate") if win_rate: item["win_rate"] = str(float(win_rate)*100)+"%" else: item["win_rate"] = "0.0%" item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) #分页 page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) return total,data def delete_choice(request): """ """ user_id = request.user.get("id") user_name = request.user.get("username") user_avatar = request.user.get("avatar") qdata = request.json stock_id = qdata.get("stock_id") cm.UserChoice.objects.filter(stock_id=stock_id,user_id=user_id).delete() if ccc.cache.get("%s_choices" % stock_id) and int(ccc.cache.get("%s_choices" % stock_id)) >= 1: ccc.cache.decr("%s_choices" % stock_id) def delete_comments(request): """ """ qdata = request.json id = qdata.get("id") if cm.Comments.objects.filter(id=id,stock_id__isnull=False).exists(): stock_id = cm.Comments.objects.filter(id=id).first().stock_id if ccc.cache.get("%s_comments" % stock_id) and int(ccc.cache.get("%s_comments" % stock_id)) >= 1: ccc.cache.decr("%s_comments" % stock_id) cm.Comments.objects.filter(id=id).delete() def modify_user_fund(request): """ """ user_id = request.user.get("id") #player = request.player match_id = ccc.get_cur_match().id player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first() player_id = player.id match_id = player.match_id qdata = request.json fundin = qdata.get("in_fund") fundout = qdata.get("out_fund") fundin = float(fundin) if fundin else 0.0 fundout = float(fundout) if fundout else 0.0 account_img = qdata.get("account_img") init_fund = player.fund trycalc = qdata.get("trycalc") today_fund = qdata.get("today_fund") today_fund = float(today_fund) if today_fund else 0.0 if trycalc: stock_date = get_today_date() validdates = get_match_validdates(match_id) today_index = validdates.index(stock_date) yesterday_index = today_index -1 if today_index >=1 else 0 yesterday_date = validdates[yesterday_index] yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter( match_id=match_id,player_id=player_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first() if yesterday: yesterday_fund = yesterday.today_fund yesterday_stock = yesterday.today_stock yesterday_stock_img = yesterday.today_stock_img yesterday_is_markt = yesterday.is_markt else: yesterday_fund = today_fund yesterday_stock = "" yesterday_stock_img = "" yesterday_is_markt = 0 #入资金 if fundin > fundout: fundin = fundin - fundout if yesterday: today_income = round((today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin),4) yesterday_fund = yesterday_fund + fundin else: today_income = 0.0 total_income = round((today_fund-init_fund-fundin)/(init_fund+fundin),4) init_fund = init_fund + fundin #出资金 else: fundout = fundout - fundin if yesterday: today_income = round((today_fund-(yesterday_fund-fundout))/float(yesterday_fund),4) yesterday_fund = round(today_fund/(1+today_income),4) else: today_income = 0.0 total_income = round((today_fund+fundout-init_fund)/init_fund,4) init_fund = round(today_fund/(1+total_income),4) today_income = "{}%".format(today_income*100) total_income = "{}%".format(total_income*100) return {"yesterday_fund":yesterday_fund, "today_fund":today_fund, "today_income":today_income, "total_income":total_income, "init_fund":init_fund} stock_date = datetime.datetime.now().strftime("%Y-%m-%d") if cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).exists(): raise ce.TipException(u"资金出入须在提交作业之前提交,今日作业已提交,不能提交资金出入!") if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists(): raise ce.TipException(u"今日已有资金出入,一天只能提交一次资金出入!") fundinout,flag = cm.FundInOut.objects.get_or_create( user_id = user_id, fundin = fundin, fundout = fundout, stock_date = stock_date, account_img = account_img ) def get_user_match_list(request): kwargs = request.json user_id = kwargs.get("user_id") if not user_id: user_id = request.user.get("id") qset = cm.Player.objects.filter(user_id=user_id).filter(match_group__isnull=False).order_by("-id") qset = qset.values("user_id","match_id","match_group").annotate(cnt=Count("match_id")) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() #today = get_today_date(user_id=user_id) data = list(qset.values("user_id","match_id","match_group")) new_data = [] for item in data: match_id = item["match_id"] match_group = item["match_group"] user_id = item["user_id"] today = get_today_date(match_id=match_id,user_id=user_id) item["match_info"] = get_match_info(match_id) item["match_group_info"] = get_group_info(match_group) if match_id and match_group: today_record = ccc.get_today_record(user_id,int(match_id),int(match_group),today) today_record = format_today_record(today_record) if today_record: if today_record.get("today_income"): today_record["today_income"] = "{}%".format(today_record["today_income"]*100) if today_record.get("total_income"): today_record["total_income"] = "{}%".format(today_record["total_income"]*100) item["today_record"] = today_record new_data.append(item) #return total,data return total,new_data def get_format_user_info(request): user_id = request.user.get("id") cur_user_id = request.user.get("id") kwargs = request.json q_user_id = kwargs.get("user_id") if q_user_id: user_id = q_user_id userinfo = get_user_info_actual(q_user_id) userinfo["fans"] = cm.UserFollows.objects.filter(follow_id=user_id).count() userinfo["followers"] = cm.UserFollows.objects.filter(user_id=user_id).count() if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists(): userinfo["is_follow"] = 1 else: userinfo["is_follow"] = 0 if cm.UserBlacks.objects.filter(user_id=cur_user_id,black_user_id=user_id).exists(): userinfo["is_black"] = 1 else: userinfo["is_black"] = 0 if userinfo.get("phone"): del userinfo["phone"] return userinfo def get_day_inout_rank_list(request): """ """ kwargs = request.json stock_date = kwargs.get("stock_date") match_id = kwargs.get("match_id") _type = kwargs.get("type") qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date) if _type == "in": qset = qset.order_by("-today_income") else: qset = qset.order_by("today_income") page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() data = list(qset.values()) return total,data def get_user_follows_v3(request): """获取用户关注的选手列表 """ user_id = request.user.get("id",0) qdata = request.json if qdata.get("user_id"): user_id = qdata.get("user_id") qset = cm.UserFollows.objects.filter(user_id=user_id) follow_ids = list(qset.values_list("follow_id",flat=True)) today = get_today_date() _today = today data = [] for user_id in follow_ids: latest_key = "PLAYER_LATEST_%d"%user_id _match_id = ccc.cache.hget(latest_key,"match_id") _today = ccc.cache.hget(latest_key,"stock_date") _match_group = ccc.cache.hget(latest_key,"match_group") today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today) if today_record: today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0 today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count() data.append(today_record) data = sorted(data,key=lambda x:x["stock_date"],reverse=True) page = int(qdata.get("page",1)) page_size = int(qdata.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) for item in data: if item: user_id = item["user_id"] latest_key = "PLAYER_LATEST_%d"%user_id today_stock = json.loads(item["today_stock"]) if item.get("today_stock") else [] today_stock = filter(lambda x:x["name"] and x["fund"],today_stock) item["today_stock"] = today_stock item["today_stock_img"] = json.loads(item["today_stock_img"]) if item.get("today_stock_img") else [] win_rate = ccc.cache.hget(latest_key,"win_rate") if win_rate: item["win_rate"] = str(float(win_rate)*100)+"%" else: item["win_rate"] = "0.0%" item["today_income"] = "{}%".format(item["today_income"]*100) item["total_income"] = "{}%".format(item["total_income"]*100) item["zans_count"] = item.get("zans",0) item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count() return total,data else: return len(data),data def get_latest_match_info(request): """ """ cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").values().first() cur_match_id = cur_match.get("id") groups = list(cm.MatchGroup.objects.filter(match_id=cur_match_id,is_active=1).order_by("order").values()) cur_match["groups"] = groups return cur_match def get_article_info(**kwargs): """ """ _id = kwargs.get("id") rst = cm.Article.objects.filter(id=_id).values().first() rst["url"] = "https://api.hunanwanzhu.com/topic/share/article.html?id="+str(_id) rst["web"] = "https://api.hunanwanzhu.com/topic/share/articleweb.html?id="+str(_id) return rst def get_profit_list(**kwargs): """盈亏列表 """ stock_date = kwargs.get("stock_date") match_id = kwargs.get("match_id") _type = kwargs.get("type") if not stock_date: stock_date = get_today_date() qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=stock_date) #if _type == "win": # qset = qset.filter(today_income__gte=0).order_by("-today_income") #if _type == "loss": # qset = qset.filter(today_income__lt=0).order_by("today_income") data = list(qset.values()) for item in data: item["win_loss"] = item["today_fund"] - item["yesterday_fund"] item["total_win_loss"] = item["today_fund"] - item["init_fund"] item["win_loss"] = round(item["win_loss"],4) item["total_win_loss"] = round(item["total_win_loss"],4) if _type == "win": data = sorted(data,key=lambda x:x["win_loss"],reverse=True) if _type == "loss": data = sorted(data,key=lambda x:x["win_loss"]) if _type == "total_win": data = sorted(data,key=lambda x:x["total_win_loss"],reverse=True) if _type == "total_loss": data = sorted(data,key=lambda x:x["total_win_loss"]) if _type == "total_income_win": data = sorted(data,key=lambda x:x["total_income"],reverse=True) if _type == "total_income_loss": data = sorted(data,key=lambda x:x["total_income"]) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) #data = list(qset.values()) return total,data def get_group_rank_list_v3(request): """排名列表 """ qdata = request.json kwargs = qdata group_id = qdata.get("id") match_id = qdata.get("match_id") match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id today = qdata.get("stock_date") if not today: today = get_today_date() match = get_match_info(match_id) group = get_group_info(group_id) players = get_match_group_users(match_id,group_id) new_players = [] for player in players: user_id = player["user_id"] username = player["username"] match_group = group_id today_record = ccc.get_today_record(user_id,match_id,match_group,today) if today_record: player.update(today_record) player["username"] = username player["org_today_income"] = player["today_income"] player["org_total_income"] = player["total_income"] player["total_income"] = "{}%".format(player["total_income"]*100) player["today_income"] = "{}%".format(player["today_income"]*100) player["fund"] = round(player["fund"],4) player["init_fund"] = round(player["init_fund"],4) player["today_fund"] = round(player["today_fund"],4) player["today_stock_img"] = json.loads(player["today_stock_img"]) if player["today_stock_img"] else [] #player["win_rate"] = calc_win_rate(user_id,match_id) player["zan_count"] = player["zans"] new_players.append(player) if kwargs.get("order_by") == "today_income__asc": new_players = sorted(new_players,key=lambda x:x["org_today_income"]) elif kwargs.get("order_by") == "today_income__desc" : new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True) elif kwargs.get("order_by") == "total_income__asc": new_players = sorted(new_players,key=lambda x:x["org_total_income"]) elif kwargs.get("order_by") == "total_income__desc": new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True) else: new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True) #分页 page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",50)) if page and page_size: total,new_players = ccf.get_page_list(new_players,page,page_size) else: total = len(new_players) return total,new_players def get_article_type_list(**kwargs): rst = [u"游资专场",u"冠军交割",u"牛人专场",u"妖股列传"] rst = const.ARTICLE_TYPE_LIST return rst def get_wanzhu_consult_list(**kwargs): """ """ qset = cm.Consult.objects.filter(user_id__gt=0).order_by("-ctime") if kwargs.get("username"): qset = qset.filter(user_name__icontains=kwargs.get("username")) if kwargs.get("reply_status"): qset = qset.filter(reply_status=kwargs.get("reply_status")) if kwargs.get("content"): qset = qset.filter(Q(content__icontains=kwargs.get("content"))|Q(reply_content__icontains=kwargs.get("content"))) data = list(qset.values()) #分页 page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) else: total = len(data) for item in data: user_id = item["user_id"] userinfo = get_user_info(user_id) if userinfo: item["user_code"] = userinfo.get("usercode") return total,data def get_sub_category(pid): """ """ qset = cm.BaikeCategory.objects.filter(parent_id=pid) qdata = list(qset.values()) if qdata: for subitem in qdata: subitem["type"] = "ent" subitem["children"] = get_sub_category(subitem["id"]) return qdata def get_baike_category_tree(**kwargs): """ """ parents = list(cm.BaikeCategory.objects.filter(parent_id__isnull=True).values()) for item in parents: item["children"] = get_sub_category(item["id"]) return parents def get_sub_catids(pid,data): """ """ data = data if data else [] qset = cm.BaikeCategory.objects.filter(parent_id=pid) ids = list(qset.values_list("id",flat=True)) if ids: data.extend(ids) for _id in ids: get_sub_catids(_id,data) return data def get_baike_list_by_category(**kwargs): category_id = kwargs.get("category_id") sub_catids = get_sub_catids(category_id,[]) qset = cm.BaikeDetail.objects.filter(category_id__in=sub_catids) qset = qset.order_by("-istop","-ctime") data = list(qset.values("id","img","intro","ctime","name","category_id")) page = int(kwargs.get("page",1)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,data = ccf.get_page_list(data,page,page_size) return total,data else: return len(data),data return data def get_baike_detail(**kwargs): #_id = kwargs.get("id") category_id = kwargs.get("category_id") data = list(cm.BaikeDetail.objects.filter(category_id=category_id).values()) data = data[0] if data else {} return data def get_app_version(request): rst = cm.APPVersion.objects.all().order_by("-id").values().first() return rst def reply_wanzhu_consult(**kwargs): """ """ pid = kwargs.get("pid") content = kwargs.get("reply_content") user_id = kwargs.get("user_id") action = kwargs.get("action") width = kwargs.get("width") height = kwargs.get("height") if action == "send": user = cm.UserInfo.objects.filter(id=user_id).first() user_name = user.username user_avatar = user.avatar user_code = user.usercode phone = user.phone obj,flag = cm.Consult.objects.get_or_create( user_id = user_id, ) obj.user_name = user_name obj.user_avatar = user_avatar obj.user_code = user_code obj.phone = phone #obj.reply_content = content obj.view_status = 1 obj.reply_status = 0 obj.ctime = datetime.datetime.now() obj.save() wanzhu_obj = cm.WanzhuConsult.objects.create( user_id = user_id, user_name = user_name, user_avatar = user_avatar ) wanzhu_obj.user_code = user_code wanzhu_obj.phone = phone wanzhu_obj.width = width wanzhu_obj.height = height wanzhu_obj.save() wanzhu_obj_1 = cm.WanzhuConsult.objects.create( reply_content = content, user_id = 0, player_id = 0, reply_user_id = user_id, pid = wanzhu_obj.id ) wanzhu_obj_1.width = width wanzhu_obj_1.height = height wanzhu_obj_1.save() cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now()) else: wanzhu_obj = cm.WanzhuConsult.objects.create( pid = pid, reply_content = content, user_id = 0, player_id = 0, reply_user_id = user_id ) wanzhu_obj.width = width wanzhu_obj.height = height wanzhu_obj.save() cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now()) #发送消息提醒 if cm.UserInfo.objects.filter(id=user_id).exists(): user = cm.UserInfo.objects.filter(id=user_id).first() openid = user.openid username = user.username try: send_consult_reply_message(openid,username) except Exception as e: print(e) #发送app推送消息 title = u"顽主杯" body = u"你收到一条顽主的消息" params = {"type":"message","id":str(user_id)} aliyunpush.push_notice_by_userid(user_id,title,body,params,"ios") aliyunpush.push_notice_by_userid(user_id,title,body,params,"android") def delete_user_info(request): """ """ uid = request.user.get("id",0) cm.UserInfo.objects.filter(id=uid).delete() cm.Player.objects.filter(user_id=uid).delete() #cm.PlayerRecord.objects.filter(user_id=uid).delete() def get_random_bake_list(**kwargs): """ """ baikes = list(cm.BaikeDetail.objects.all().values("id","name","intro","img","category_id")) randomi = [] while len(randomi) < 5: num = random.randint(0,len(baikes)-1) if not num in randomi: randomi.append(num) rst = [baikes[x] for x in randomi] return rst def articles_top5_by_type(**kwargs): """ """ cats = const.ARTICLE_TYPE_LIST data = [] for cat in cats: articles = list(cm.Article.objects.filter(category=cat).order_by("-id").values("id","name","ctime","img")[:5]) data.append({"category":cat,"articles":articles}) return data @ccc.cache_data_kw(5*60) def get_match_winlost_top5(**kwargs): """ """ data = [] cur_match_id = ccc.get_cur_match().id matchs = cm.Match.objects.filter(id__gte=19,match_status__in=[3,4]).order_by("-id") for match in matchs: match_id = match.id match_name = match.name end_time = match.end_time if cur_match_id == match_id: end_time = get_today_date() records = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=end_time) total_income_up = copy.copy(records) total_income_up = total_income_up.order_by("-total_income") total_income_up = list(total_income_up.values()[:10]) get_user_avatar(total_income_up) total_income_down = copy.copy(records) total_income_down = total_income_down.order_by("total_income") total_income_down = list(total_income_down.values()[:10]) get_user_avatar(total_income_down) records = list(records.values()) for item in records: item["total_win"] = item["today_fund"] - item["init_fund"] total_win_up = copy.copy(records) total_win_up = sorted(total_win_up,key=lambda x:x["total_win"],reverse=True) total_win_up = total_win_up[:10] get_user_avatar(total_win_up) total_win_down = copy.copy(records) total_win_down = sorted(total_win_down,key=lambda x:x["total_win"]) total_win_down = total_win_down[:10] get_user_avatar(total_win_down) valid_dates = json.loads(match.valid_dates) if match.valid_dates else [] data.append({"valid_dates":valid_dates,"date":end_time,"start_time":match.start_time,"end_time":match.end_time,"match_id":match_id,"match_name":match_name,"total_income_up":total_income_up,"total_income_down":total_income_down,"total_win_up":total_win_up,"total_win_down":total_win_down}) if int(kwargs.get("new",0)) == 1: break return data def get_user_avatar(records): for item in records: userinfo = get_user_info_actual(item["user_id"]) if userinfo: item["avatar"] = userinfo.get("avatar") else: item["avatar"] = "" def black_user(request): """ """ qdata = request.json user_id = request.user.get("id",0) black_user_id = qdata.get("black_user_id") cm.UserBlacks.objects.get_or_create( user_id = user_id, black_user_id = black_user_id ) def delete_black_user(request): """ """ qdata = request.json user_id = request.user.get("id",0) black_user_id = qdata.get("black_user_id") cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=black_user_id).delete() def get_user_black_user_list(request): """ """ #user_id = 5709 user_id = request.user.get("id",0) kwargs = request.json qset = cm.UserBlacks.objects.filter(user_id=user_id) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() data = list(qset.values("black_user__id","black_user__username","black_user__avatar")) datas = [] for item in data: item['id'] = item["black_user__id"] item['username'] = item["black_user__username"] item['avatar'] = item["black_user__avatar"] return total,data def get_stock_nb_comments(request): """ """ kwargs = request.json comment_date = kwargs.get("date") qset = cm.StockComments.objects.all().order_by("-ctime") if comment_date: st = comment_date + " 00:00:00" et = comment_date + " 23:59:59" qset = qset.filter(ctime__gte=st,ctime__lte=et) page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",20)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() data = list(qset.values()) return total,data def get_opmode_group_rank_list(**kwargs): """ """ today = get_today_date() match_id = ccc.get_cur_match().id qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today).order_by("-total_income") qdata = list(qset.values()) #按操作模式分组并排序 tmp_dct = {} for item in qdata: opmode_group = item["opmode_group"] opmode_group_name = item["opmode_group_name"] key = "%s_%s" % (opmode_group,opmode_group_name) if not tmp_dct.get(key): tmp_dct[key] = [item] else: tmp_dct[key].append(item) if len(tmp_dct[key]) > 2: break data = [] for k,v in tmp_dct.items(): opmode_id,opmode_name = k.split("_") #盈利与亏损 win_5 = qset.filter(today_income__gte=0.05).count() loss_5 = qset.filter(today_income__lte=0.05).count() item = { "name":opmode_name, "id":opmode_id, "players":v, "win_count":win_5, "loss_count":loss_5, "opmodel":1, } data.append(item) return data def get_opmode_group_statistic(**kwargs): """ """ opmode_id = kwargs.get("opmode_id") #today = get_today_date() #match_id = ccc.get_cur_match().id today = "2023-08-25" match_id = 16 qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today,opmode_group=opmode_id) qset_user_stock = cm.UserStock.objects.filter(stock_date=today,opmode_group=opmode_id) total = qset.count() #今日均收益 today_total_income = qset.aggregate(total=Sum("today_income")) today_income_avg = today_total_income["total"]/total #总资产 today_fund_total = qset.aggregate(total=Sum("today_fund"))["total"] #初始资产 init_fund_total = qset.aggregate(total=Sum("init_fund"))["total"] total_income = (today_fund_total - init_fund_total)/init_fund_total #持股前10 user_stock_top10 = list(qset_user_stock.values("stock_id","stock_name")\ .annotate(cnt=Count("stock_id")).order_by("-cnt").values("stock_id","stock_name","cnt"))[:10] statistic = { "total_man":total, "today_income_avg":"{}%".format(round(today_income_avg*100,2)), "today_fund_total":round(today_fund_total,2), "today_init_total":round(init_fund_total,2), "total_income":"{}%".format(round(total_income*100,2)), "user_stock_top10":user_stock_top10 } return statistic def get_opmode_group_rank_info_list(**kwargs): """ """ opmode_id = kwargs.get("opmode_id") order_by = kwargs.get("order_by") #today = get_today_date() #match_id = ccc.get_cur_match().id today = "2023-08-25" match_id = 16 qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today,opmode_group=opmode_id) #今日收益 if order_by == "today_income": qset = qset.order_by("-today_income") #总收益 if order_by == "total_income": qset = qset.order_by("-total_income") page = int(kwargs.get("page",0)) page_size = int(kwargs.get("page_size",10)) if page and page_size: total,qset = ccc.get_page_qset(qset,page,page_size) else: total = qset.count() data = list(qset.values()) return total,data @ccc.cache_data_kw(5*60) def get_match_group_winlose_statistic(**qdata): """ """ match_id = qdata.get("match_id") today = qdata.get("stock_date") if not today: today = get_today_date() match_group_dct = {} match_group_status_dct = {} matchGroup = cm.MatchGroup.objects.filter(match_id=match_id).order_by("-order") for item in matchGroup: match_group_dct[item.id] = item.name match_group_status_dct[item.id] = item.is_active prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=today) group_win_lose_list = [] #今日总资产,总收益,平均收益 prdata = prset.values("match_group").annotate(today_fund=Sum("today_fund"), today_income=Sum("today_income"),cnt=Count("today_income")).order_by("match_group") match_name = get_match_info(match_id).get("name") for item in prdata: group_id = int(item["match_group"]) if match_group_status_dct.get(group_id)>0: group_win_lose_list.append({ "match_id":match_id, "match_name":match_name, "match_group":group_id, "name":match_group_dct.get(group_id), "today_fund":"{}".format(round(item["today_fund"],2)), "today_income":"{}%".format(round(item["today_income"]*100,2)), "today_income_avg":"{}%".format(round(item["today_income"]/item["cnt"]*100,2)) if item["cnt"] else 0.0 }) group_win_lose_list = sorted(group_win_lose_list,key=lambda x:x["match_group"],reverse=True) #今日盈亏人数比 win_cnt = prset.filter(today_income__gte=0).count() lose_cnt = prset.filter(today_income__lt=0).count() nwin_cnt = float(win_cnt)/(win_cnt+lose_cnt)*10 if (win_cnt+lose_cnt) >0 else 0.0 nlose_cnt = float(lose_cnt)/(win_cnt+lose_cnt)*10 if (win_cnt+lose_cnt) >0 else 0.0 win_cnt = int(round(nwin_cnt)) lose_cnt = int(round(nlose_cnt)) #今日全部人均收益率 total = prset.aggregate(total=Sum("today_income")).get("total") today_win_lose_avg = "{}%".format(round(total/prset.count()*100,2)) if prset.count()>0 else 0.0 total_fund = prset.aggregate(total=Sum("today_fund")).get("total") rst = {"group_win_lose_list":group_win_lose_list, "win_cnt":win_cnt,"lose_cnt":lose_cnt, "total_fund":total_fund, "date":today, "today_win_lose_avg":today_win_lose_avg} return rst def user_mark_score(**kwargs): """ """ user_id = kwargs.get("user_id") stock_date = kwargs.get("stock_date") score = kwargs.get("score") obj,flag = cm.UserMarkScore.objects.get_or_create( user_id = user_id, stock_date = stock_date, ) obj.score = score obj.save() return obj.score def get_user_markscore_list(**kwargs): """ """ today = kwargs.get("stock_date") user_id = kwargs.get("user_id") if not today: today = get_today_date() qset = cm.UserMarkScore.objects.filter(stock_date=today) qdata = list(qset.values("score").annotate(cnt=Count("score"))) for item in qdata: if item["user_id"] == user_id: item["mark_status"] = 1 else: item["mark_status"] = 0 rst = {"total":qset.count(),"list":qdata} return rst def check_user_markscore(**kwargs): """ """ user_id = kwargs.get("user_id") stock_date = kwargs.get("stock_date") if cm.UserMarkScore.objects.filter(user_id=user_id,stock_date=stock_date): return 1 else: return 0 def get_match_group_winlose_allday(**qdata): """ """ match_id = qdata.get("match_id") group_id = qdata.get("group_id") today = qdata.get("stock_date") if not today: today = get_today_date() match_group_dct = {} matchGroup = cm.MatchGroup.objects.filter(match_id=match_id).order_by("-order") for item in matchGroup: match_group_dct[item.id] = item.name prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,match_group=group_id) group_win_lose_list = [] prdata = prset.values("match_group","stock_date").annotate(today_fund=Sum("today_fund"), today_income=Sum("today_income"),cnt=Count("today_income")).order_by("match_group").order_by("stock_date") money = 10000.0 for item in prdata: group_id = int(item["match_group"]) stock_date = item["stock_date"] money += money * (item["today_income"]/item["cnt"] if item["cnt"] else 0) total_income = (money-10000.0)/10000.0 total_avg = "{}%".format(round(total_income*100,2)) group_win_lose_list.append({ "stock_date":stock_date, "match_group":group_id, "name":match_group_dct.get(group_id), "today_fund":"{}".format(round(item["today_fund"],2)), "total_income":total_avg, "today_income":"{}%".format(round(item["today_income"]/item["cnt"]*100,2)) if item["cnt"] else 0.0 }) group_win_lose_list = sorted(group_win_lose_list,key=lambda x:x["stock_date"],reverse=True) rst = {"list":group_win_lose_list} return rst @ccc.cache_data_kw(5*60) def get_match_group_winlose_avg_allday(**qdata): """ """ match_id = qdata.get("match_id") group_id = qdata.get("group_id") #prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id) #all_day = list(set(prset.values_list("stock_date",flat=True))) #nall_day = sorted(all_day,reverse=False) allday_winlose_avg_list = [] money = 10000.0 prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).values("stock_date")\ .annotate(cnt=Count("stock_date"),total=Sum("today_income")) for item in prset: stock_date = item["stock_date"] cnt = item["cnt"] total = item["total"] today_win_lose_avg = "{}%".format(round(total/cnt*100,2)) if cnt>0 else 0.0 money += money * (total/cnt if cnt > 0 else 0) total_income = (money-10000.0)/10000.0 total_avg = "{}%".format(round(total_income*100,2)) allday_winlose_avg_list.append({ "stock_date":stock_date, "today_income":today_win_lose_avg, "total_income":total_avg, }) #for stock_date in nall_day: # #今日全部人均收益率 # prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date) # total = prset.aggregate(total=Sum("today_income")).get("total") # today_win_lose_avg = "{}%".format(round(total/prset.count()*100,2)) if prset.count()>0 else 0.0 # money += money * (total/prset.count() if prset.count() > 0 else 0) # total_income = (money-10000.0)/10000.0 # total_avg = "{}%".format(round(total_income*100,2)) # allday_winlose_avg_list.append({ # "stock_date":stock_date, # "today_income":today_win_lose_avg, # "total_income":total_avg, # }) allday_winlose_avg_list = sorted(allday_winlose_avg_list,key=lambda x:x["stock_date"],reverse=True) rst = {"list":allday_winlose_avg_list} return rst def get_user_match_stock_winloss_rank_list(**kwargs): """ """ user_id = kwargs.get("user_id") match_id = kwargs.get("match_id") rank_type = kwargs.get("rank_type") data = [] qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).exclude(today_stock="[]").order_by("-stock_date") for index,qitem in enumerate(qset): today_stock = qitem.today_stock today_stock = json.loads(today_stock) if today_stock else [] stock_date = qitem.stock_date if index == 0: for sitem in today_stock: sitem["stock_date"] = stock_date sitem['id'] = qitem.id sitem['match_id'] = qitem.match_id sitem['user_id'] = qitem.user_id data.append(sitem) else: for sitem in today_stock: if sitem["fund"] in ["0.0","0",""]: sitem["stock_date"] = stock_date sitem['id'] = qitem.id sitem['match_id'] = qitem.match_id sitem['user_id'] = qitem.user_id data.append(sitem) if rank_type == "win": data = filter(lambda x:float(x.get("money",0))>0,data) data = sorted(data,key=lambda x:float(x.get("money",0)),reverse=True) else: data = filter(lambda x:float(x.get("money",0))<0,data) data = sorted(data,key=lambda x:float(x.get("money",0))) return data def get_oss2_policy_sign(request): """ """ qdata = request.json policy = qdata.get("policy") rst = get_signature(policy) return rst def get_match_group_list(**kwargs): """ """ match_id = kwargs.get("match_id") match,groups = get_match_groups(match_id) return groups def get_user_markscore_week_avg(request): """ """ pass # now = datetime.datetime.now().date() data = [] msret = cm.UserMarkScore.objects.all().order_by('-stock_date').values() msret = msret.values("stock_date").distinct() for item in msret: qset = cm.UserMarkScore.objects.filter(stock_date=item['stock_date']).aggregate(avg_score=Avg("score")) avg_score = "{}".format(round(qset.get("avg_score",0),1)) data.append({"stock_date":item['stock_date'],"avg_score":avg_score}) # for i in range(1,5): # item_list = [] # for j in range(1,8): # now = now + datetime.timedelta(days=-1) # now_str = ccf.datetime_to_str(now,"%Y-%m-%d") # qset = cm.UserMarkScore.objects.filter(stock_date=now_str).aggregate(avg_score=Avg("score")) # item_list.append({"stock_date":now_str,"avg_score":qset.get("avg_score",0)}) # data.append(item_list) count = (len(data)%5) + 30 return data[:count] def refund_out_trade_order(**kwargs): """ """ _id = kwargs.get("id") signup_order = cm.SignupOrder.objects.filter(id=_id).first() if signup_order: out_trade_no = signup_order.out_trade_no transaction_id = signup_order.transaction_id total_fee = signup_order.total_fee amount = str(int(total_fee*100)) print(amount) result = refund_order(transaction_id,out_trade_no,out_trade_no,amount) if result.get("result_code") == "SUCCESS": signup_order.order_status = -1 signup_order.save() #删除选手信息 user_id = signup_order.user_id match_id = signup_order.match_id cm.Player.objects.filter(user_id=user_id,match_id=match_id).delete() return "success" else: raise ce.TipException(result.get("err_code_des")) else: raise ce.TipException(u"该订单不存在退款失败!") def signup_old_user(**kwargs): """ """ order_id = kwargs.get("id") signup_type = kwargs.get("signup_type") match_group = kwargs.get("match_group") player_type = kwargs.get("player_type") role_type = kwargs.get("role_type") order = cm.SignupOrder.objects.filter(id=order_id).first() if order: user_id = order.user_id match_id = order.match_id signup_name = order.signup_name user = cm.UserInfo.objects.filter(id=user_id).first() match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name match = cm.Match.objects.filter(id=match_id).first() user.player_type = player_type user.phone = order.phone user.username = signup_name user.save() order.signup_type = signup_type order.match_group = match_group order.match_group_name = match_group_name order.order_status = 1 order.save() #生产选手信息 player,flag = cm.Player.objects.get_or_create( user_id = user_id, match_id = match_id ) player.match_name = match.name player.match_group = match_group player.match_group_name = match_group_name player.username = signup_name player.usercode = user.usercode player.role = role_type player.match_status = 1 player.save() def get_user_signup_order(request): """#获取用户订单号 """ try: user_id = request.user.get("id",0) except: user_id = 0 qdata = request.json pay_status = qdata.get("pay_status") if not user_id: user_id = qdata.get("user_id") match_id = ccc.get_signup_match().id qset = cm.SignupOrder.objects.filter(user_id=user_id,match_id=match_id,pay_status=pay_status,order_status=pay_status) qdata = qset.values().first() return qdata def check_msg_content(request): """ """ qdata = request.json APPID = "wxb299e10e65157301" APPSECRET = "20e278a60d52ad63822a07e49931435c" token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (APPID,APPSECRET) res = requests.get(token_url,verify=False) access_token = res.json().get("access_token") #check msg content check_url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s" % access_token print(access_token) openid = qdata.get('openid') if openid: #params = { # "content":qdata.get("content"), # "version":2, # "scene":2, # "openid":openid # } #rest = requests.post(check_url,data=json.dumps(params),verify=False) cmdStr = u""" curl -X POST -H "Content-Type:application/json" -d '{"content":"%s","version":2,"scene":2,"openid":"%s"}' %s """ % (qdata.get("content"),openid,check_url) rst = json.loads(os.popen(cmdStr).read()) return rst return {} def delete_user_stock(request): """ """ qdata = request.json stock_date = qdata.get("stock_date") user_id = qdata.get("user_id") match_id = qdata.get("match_id") player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first() if player: player_id = player.id #删除今日作业数据 cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).delete() #删除今日持仓数据 month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1]) cm.UserStock.get_db_model(month).objects.filter( player_id = player.id, stock_date = stock_date ).delete() #删除今日出入资金数据 if cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).exists(): cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).delete() #用前一天数据重置选手初始资金 yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter( match_id=match_id,player_id=player_id).order_by("-stock_date").first() if yesterday: player.fund = yesterday.init_fund player.save() def get_user_fundinout(request): """ """ try: user_id = request.user.get("id",0) except: user_id = 0 if not user_id: user_id = qdata.get("user_id") qdata = request.json stock_date = qdata.get("stock_date") rst = cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).values().first() return rst def delete_user_fundinout(request): try: user_id = request.user.get("id",0) except: user_id = 0 if not user_id: user_id = qdata.get("user_id") match_id = ccc.get_cur_match().id qdata = request.json stock_date = qdata.get("stock_date") #删除出入资金 if cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).exists(): cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).delete() #player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first() #if player: # player_id = player.id # #用前一天数据重置选手初始资金 # yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter( # match_id=match_id,stock_date=stock_date).order_by("-stock_date").first() # #if yesterday: # # player.fund = yesterday.init_fund # # player.save() #@ccc.cache_data_kw(5*60) def get_match_cangwei_avg_allday(**qdata): """每天人均仓位情况 """ match_id = qdata.get("match_id") allday_cangwei_avg_list = [] prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).values("stock_date")\ .annotate(cnt=Count("stock_date"),total=Sum("today_cangwei")) for item in prset: stock_date = item["stock_date"] cnt = item["cnt"] total = item["total"] if cnt and total: today_cangwei_avg = "{}%".format(round(total/cnt,2)) if cnt>0 else 0.0 allday_cangwei_avg_list.append({ "stock_date":stock_date, "today_cangwei_avg":today_cangwei_avg }) allday_cangwei_avg_list = sorted(allday_cangwei_avg_list,key=lambda x:x["stock_date"],reverse=True) rst = {"list":allday_cangwei_avg_list} return rst