#coding=utf-8 ''' ''' import os,re,random import json,time,datetime import shutil import tempfile import zipfile 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 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 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 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 #import logging #log = logging.getLogger("myerror") 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 user_id = request.user.get("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=request.user.get("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) 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":get_user_info(cur_user_id), "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)) } 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 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 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)) item["players_num"] = len(players) item["win_count"] = win_count item["loss_count"] = loss_count item["players"] = new_players_sort[:3] 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"]) 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"]) 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_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 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(): #记录持股情况 new_stock_list = [] today_stock_list = json.loads(today_stock) for ts in today_stock_list: if ts["name"]: try: stock,flag = cm.Stock.objects.get_or_create( name = ts["name"] ) stock_id = stock.id usobj,flag = cm.UserStock.objects.get_or_create( user_id = user_id, stock_id = stock_id, stock_name = ts["name"], player_id = player.id, stock_date = stock_date ) if ts.get("fund"): usobj.fund = ts["fund"] 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) 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.username = username obj.usercode = usercode obj.match_group = match_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万元,请仔细核对数据!") #有资金出入 if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists(): 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 total_income = (today_fund-init_fund-fundin)/(init_fund+fundin) obj.today_income = round(today_income,4) obj.total_income = round(total_income,4) if flag: cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=init_fund+fundin) obj.init_fund = init_fund + fundin #出资金 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 total_income = (today_fund+fundout-init_fund)/init_fund if init_fund else 0.0 obj.today_income = round(today_income,4) obj.total_income = round(total_income,4) if flag: 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) if float(today_income)>0.4: raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!") if float(total_income)>8: 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.4: raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!") if float(total_income)>8: 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)) 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) 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")) 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) 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) 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() 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 return stock def get_hot_stock_buy(**kwargs): """ """ stock_date = kwargs.get("stock_date") qset = cm.UserStock.objects.filter(stock_date=stock_date) if kwargs.get("name"): qset = cm.UserStock.objects.filter(stock_name__icontains=kwargs.get("name")) 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) 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() return data def get_hot_stock_sell_players(**kwargs): """ """ _id = kwargs.get("id") 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_players = list(cm.UserStock.objects.filter(stock_date=yesterday,stock_id=_id).values_list("player_id",flat=True)) td_players = list(cm.UserStock.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() 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 def get_champion_articles_list(request): """ """ 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("-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()) 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) if kwargs.get("name"): qset = qset.filter(username__icontains=kwargs.get("name")) 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") 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()) data = [] user_stocks = cm.UserStock.objects.filter(stock_id=stock_id,stock_date=stock_date) for us in user_stocks: player_id = us.player_id player = cm.Player.objects.filter(id=player_id).first() 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_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) 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") match_id = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_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") import random 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 user_id = request.user.get("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") if not signup_name: signup_name = user_name orgcode = ccc.cache.get(phone) 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 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 ) #支付 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 ) 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() 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.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 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") if record_id: 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) 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") 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.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.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") 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") ip = ccf.get_ip(request) location = ccf.get_city_from_ip(ip) 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 ) 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 def get_experience_list(request): """ """ #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"] except: item["user_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() del userinfo["phone"] if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists(): userinfo["is_follow"] = 1 else: userinfo["is_follow"] = 0 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://www.hunanwanzhu.com/topic/article.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"]) 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"游资列传",u"妖股列传"] 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_baike_list_by_category(**kwargs): category_id = kwargs.get("category_id") qset = cm.BaikeDetail.objects.filter(category_id=category_id) data = list(qset.values("id","name")) 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()) 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 obj,flag = cm.Consult.objects.get_or_create( user_id = user_id, ) obj.user_name = user_name obj.user_avatar = user_avatar #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.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()