| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854 |
- #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
- 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
- )
- 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() and flag:
- fundinout = cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).first()
- fundin = fundinout.fundin
- fundout = fundinout.fundout
- #入资金
- 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)
- 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
- 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.6:
- raise ce.TipException(u"今日盈利已超过60%,请仔细核对数据或直接联系顽主!")
- if float(total_income)>8:
- raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
- obj.today_income = round(today_income,4)
- obj.total_income = round(total_income,4)
- 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__gte=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:
- 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()
- 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"])
- 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,
- "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")
- qset = cm.Article.objects.filter(status=2).order_by("-id")
- if _type:
- qset = qset.filter(type=_type)
- if isbanner:
- qset = qset.filter(isbanner=isbanner)
- 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")
- #init_fund = kwargs.pop("init_fund")
- #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
-
- 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())
- 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")
- print(qdata)
- 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")
- qset = cm.WanzhuConsult.objects.filter(user_id=player_id)
- data = list(qset.values())
- for item in data:
- if cm.WanzhuConsult.objects.filter(pid=item["id"]):
- data.extend(cm.WanzhuConsult.objects.filter(Q(pid=item["id"])|Q(reply_user_id=player_id)).values())
- 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)
- 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)
- 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"])
- 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()
- 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"]
- 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"牛人专访"]
- return rst
- def get_wanzhu_consult_list(**kwargs):
- """
- """
- qset = cm.Consult.objects.all().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())
- for item in data:
- user_id = item["user_id"]
- userinfo = get_user_info(user_id)
- if userinfo:
- item["user_code"] = userinfo.get("usercode")
- #分页
- 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_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
|