2 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507
  1. #coding=utf-8
  2. '''
  3. '''
  4. import os,re,random
  5. import json,time,datetime
  6. import shutil
  7. import tempfile
  8. import zipfile
  9. from docxtpl import DocxTemplate,InlineImage
  10. from docx.shared import Mm
  11. from django.db import transaction
  12. from django.conf import settings
  13. import common.models as cm
  14. import common.error_info as ce
  15. import common.common_functions as ccf
  16. import common.common_control as ccc
  17. import account.password_handle as ph
  18. from utils.exceltool import ExcelTool
  19. from utils.jgpush import send_notification_by_registration_ids
  20. import wzhifuSDK as wxpay
  21. from utils.exceltool import ExcelTool
  22. from utils.qrcodetool import gen_general_qrcode
  23. from django.db.models import Q,Sum,Count,F
  24. from PIL import Image
  25. from PIL import Image,ImageDraw,ImageFont
  26. from django.db import transaction
  27. from threading import Thread
  28. #from django.core.cache import cache
  29. from django.db import connection
  30. import calendar
  31. import xlrd
  32. import xlwt
  33. from xlutils.copy import copy
  34. from xltpl.writer import BookWriter
  35. from django_redis import get_redis_connection
  36. from constants import *
  37. from utils.aliyun_sms import send_verify_code,send_signup_success
  38. from utils.wxSubscribeMessage import send_consult_reply_message
  39. def async(f):
  40. def wrapper(*args, **kwargs):
  41. thr = Thread(target=f, args=args, kwargs=kwargs)
  42. thr.start()
  43. return wrapper
  44. def get_today_date(match_id=None,user_id=None):
  45. if not match_id:
  46. match_id = ccc.get_cur_match().id
  47. #if datetime.datetime.now().strftime("%H:%M") < "15:00":
  48. # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES:
  49. # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
  50. # else:
  51. # if datetime.datetime.now().weekday()==0:
  52. # today = (datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d")
  53. # else:
  54. # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  55. #else:
  56. # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES:
  57. # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
  58. # else:
  59. # today = datetime.datetime.now().strftime("%Y-%m-%d")
  60. try:
  61. if user_id:
  62. today = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id).order_by("-stock_date").first().stock_date
  63. else:
  64. today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
  65. except:
  66. today = datetime.datetime.now().strftime("%Y-%m-%d")
  67. return today
  68. #@async
  69. def update_group_rank(match_id,match_group,stock_date):
  70. #return
  71. 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")
  72. records = prset.values()
  73. case_id = " case id "
  74. cases = []
  75. where = []
  76. for index,pr in enumerate(prset):
  77. key = "%s_%s_%s_%s" % (pr.player_id,match_id,match_group,stock_date)
  78. record = records[index]
  79. record.update({"group_rank":index+1})
  80. ccc.cache.delete(key)
  81. ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder))
  82. ccc.pl.execute()
  83. #@ccc.cache_data()
  84. def get_notices():
  85. """
  86. """
  87. notices = list(cm.Article.objects.filter(status=2,type="notice").values())
  88. return notices
  89. def get_index_data(request):
  90. """首页数据
  91. """
  92. player = request.player
  93. if not player:
  94. raise ce.TipException(u"该账号未参加任何赛事!")
  95. player_id = player.id
  96. match_id = player.match_id
  97. match_group = player.match_group
  98. #if datetime.datetime.now().hour < 15:
  99. # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  100. #else:
  101. # today = datetime.datetime.now().strftime("%Y-%m-%d")
  102. today = get_today_date()
  103. match_name = get_match_info(match_id).get("name")
  104. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(player_id=player_id,match_id=match_id)
  105. if records_set:
  106. try:
  107. cur_rank = get_today_record(player_id,match_id,match_group,today).get("group_rank","")
  108. records = list(records_set.order_by("-stock_date").values())
  109. except:
  110. cur_rank = 0
  111. records = []
  112. else:
  113. cur_rank = 0
  114. records = []
  115. for item in records:
  116. today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
  117. today_stock = filter(lambda x:x["name"],today_stock)
  118. item["today_stock"] = today_stock
  119. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
  120. yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
  121. yesterday_stock = filter(lambda x:x["name"],yesterday_stock)
  122. item["yesterday_stock"] = yesterday_stock
  123. item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
  124. item["today_income"] = "{}%".format(item["today_income"]*100)
  125. item["total_income"] = "{}%".format(item["total_income"]*100)
  126. #通知
  127. notices = get_notices()
  128. ret = {"match_name":match_name,"cur_rank":cur_rank,"records":records,"notices":notices}
  129. return ret
  130. def get_player_match_list(request):
  131. """选手参赛列表数据
  132. """
  133. uid = request.user.get("id",0)
  134. now_str = datetime.datetime.now().strftime("%Y-%m-%d")
  135. cur_match_id = ccc.get_cur_match().id
  136. match_ids = list(cm.Player.objects.filter(user_id=uid).values_list("match_id",flat=True))
  137. matchs = list(cm.Match.objects.filter(id__in=match_ids).values())
  138. for item in matchs:
  139. player = cm.Player.objects.filter(user_id=uid,match_id=item["id"]).first()
  140. item["player_id"] = player.id if player else 0
  141. return matchs
  142. def get_group_income(match_id,match_group):
  143. """
  144. """
  145. data = []
  146. today = datetime.datetime.now().strftime("%Y-%m-%d")
  147. player_ids = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values_list("id",flat=True))
  148. for player_id in player_ids:
  149. 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()
  150. if today_record:
  151. data.append(today_record.total_income)
  152. data = list(set(data))
  153. data = sorted(data,key=lambda x:x,reverse=True)
  154. return data
  155. def get_player_match_detail(request):
  156. """选手参赛详情数据
  157. """
  158. qdata = request.json
  159. user_id = request.user.get("id",0)
  160. match_id = qdata.get("id")
  161. record_id = qdata.get("record_id")
  162. userinfo = {}
  163. cur_user_id = user_id
  164. if qdata.get("user_id"):
  165. cur_user_id = qdata.get("user_id")
  166. today = get_today_date()
  167. ismine = True if int(cur_user_id) == user_id else False
  168. if not match_id:
  169. player = cm.Player.objects.filter(user_id=cur_user_id,match_id=match_id).first()
  170. match_id =player.match_id
  171. cur_user_id = player.user_id
  172. if record_id:
  173. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id)
  174. if records_set:
  175. match_id = records_set.first().match_id
  176. else:
  177. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("-stock_date")
  178. match = cm.Match.objects.filter(id=match_id).values().first()
  179. groups = list(cm.MatchGroup.objects.filter(match_id=match_id).values_list("name",flat=True))
  180. match["groups"] = groups
  181. if records_set:
  182. records = list(records_set.values())
  183. else:
  184. records = []
  185. for item in records:
  186. item["today_stock"] = json.loads(item["today_stock"]) if item["today_stock"] else []
  187. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
  188. item["yesterday_stock"] = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
  189. item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
  190. item["today_income"] = "{}%".format(item["today_income"]*100)
  191. item["total_income"] = "{}%".format(item["total_income"]*100)
  192. today_record = {}
  193. if records_set:
  194. today = records_set.first().stock_date
  195. if record_id:
  196. today_record = records_set.values().first()
  197. today_record = format_today_record(today_record)
  198. else:
  199. match_group = records_set.first().match_group
  200. today_record = ccc.get_today_record(cur_user_id,int(match_id),match_group,today)
  201. if today_record:
  202. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  203. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  204. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  205. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  206. today_record["match_group_name"] = cm.MatchGroup.objects.filter(id=today_record["match_group"]).first().name
  207. today_record["players_num"] = cm.Player.objects.filter(match_group=today_record["match_group"]).count()
  208. today_record["win_rate"] = calc_win_rate(cur_user_id,today_record["match_id"])
  209. badest = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("today_income").first()
  210. if badest:
  211. today_record["badest_income"] = "{}%".format(badest.today_income*100)
  212. today_record["today_stock_total"] = round(today_record["today_stock_total"],4)
  213. userinfo = get_user_info(today_record["user_id"])
  214. today_record["style"] = userinfo.get("style")
  215. else:
  216. player_info = get_user_info(cur_user_id)
  217. today_record = {}
  218. today_record["stock_date"] = today
  219. today_record.update(player_info)
  220. today_record["player_id"] = player_info["id"]
  221. today_record["avatar"] = get_user_info(cur_user_id)["avatar"]
  222. userinfo = get_user_info(cur_user_id)
  223. today_record["style"] = userinfo.get("style")
  224. today_record["user_id"] = player_info["id"]
  225. match["groups"] = [today_record.get("match_group_name","")] if today_record else []
  226. records = sorted(records,key=lambda x:x["stock_date"],reverse=True)
  227. if cm.UserFollows.objects.filter(user_id=request.user.get("id"),follow_id=cur_user_id).exists():
  228. is_follow = 1
  229. else:
  230. is_follow = 0
  231. if today_record and today_record.get("today_fund"):
  232. today_record["today_income_fund"] = round((today_record["today_fund"] - today_record["yesterday_fund"])*10000,2) if today_record["yesterday_fund"] else 0.00
  233. today_record["zan_count"] = today_record.get("zans",0)
  234. ret = {
  235. "match":match,
  236. "today_record":today_record,
  237. "match_group_info":get_group_info(today_record.get("match_group")) if today_record.get("match_group") else {},
  238. "userinfo":get_user_info(cur_user_id),
  239. "records":records,
  240. "is_follow":is_follow,
  241. "fans":cm.UserFollows.objects.filter(follow_id=cur_user_id).count(),
  242. "followers":cm.UserFollows.objects.filter(user_id=cur_user_id).count(),
  243. "stock_age":datetime.datetime.now().year - int(userinfo.get("join_time")) if userinfo.get("join_time") else 0,
  244. "stock_follow":list(cm.UserChoice.objects.filter(user_id=cur_user_id).values_list("stock_name",flat=True))
  245. }
  246. return ret
  247. def get_today_record(player_id,match_id,match_group,today):
  248. """
  249. """
  250. key = "%s_%s_%s_%s" % (player_id,match_id,match_group,today)
  251. #key = "%s_%s_%s" % (player_id,match_id,today)
  252. today_record = ccc.cache.get(key)
  253. today_record = json.loads(today_record) if today_record else {}
  254. #if match_id:
  255. # #记得这里上线后要注释掉
  256. # today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=player_id,match_id=match_id,stock_date=today)
  257. # today_record = today_record.values().first()
  258. try:
  259. if today_record:
  260. user_info = get_user_info(today_record["user_id"])
  261. if user_info:
  262. user_info.pop("id")
  263. today_record.update(user_info)
  264. #仓位
  265. today_stock_total = 0
  266. today_stock = json.loads(today_record["today_stock"])
  267. for ts in today_stock:
  268. if ts["fund"]:
  269. try:
  270. today_stock_total += float(ts["fund"])
  271. except Exception as e:
  272. print e
  273. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  274. today_record["today_stock_total"] = today_stock_total
  275. except Exception as e:
  276. import traceback
  277. traceback.print_exc()
  278. return today_record
  279. def format_today_record(today_record):
  280. try:
  281. if today_record:
  282. user_info = get_user_info(today_record["user_id"])
  283. if user_info:
  284. #user_info.pop("id")
  285. today_record.update(user_info)
  286. #仓位
  287. today_stock_total = 0
  288. today_stock = json.loads(today_record["today_stock"])
  289. for ts in today_stock:
  290. if ts["fund"]:
  291. try:
  292. today_stock_total += float(ts["fund"])
  293. except Exception as e:
  294. print e
  295. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  296. today_record["today_stock_total"] = today_stock_total
  297. win_rate = ccc.cache.hget("PLAYER_LATEST_%d" % today_record["user_id"],"win_rate")
  298. if win_rate:
  299. today_record["win_rate"] = str(float(win_rate)*100)+"%"
  300. else:
  301. today_record["win_rate"] = "0.0%"
  302. except Exception as e:
  303. import traceback
  304. traceback.print_exc()
  305. today_record = today_record if today_record else {}
  306. return today_record
  307. def get_today_record_actual(player_id,match_id,match_group,today=None):
  308. """
  309. """
  310. if today:
  311. 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)
  312. else:
  313. 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")
  314. today_record = qset.values().first()
  315. print(player_id,match_id,match_group,today,4444444444444444444)
  316. print(today_record,1111111111)
  317. if today_record:
  318. user_info = get_user_info(today_record["user_id"])
  319. if user_info:
  320. user_info.pop("id")
  321. today_record.update(user_info)
  322. #仓位
  323. today_stock_total = 0
  324. today_stock = json.loads(today_record["today_stock"])
  325. for ts in today_stock:
  326. if ts["fund"]:
  327. try:
  328. today_stock_total += float(ts["fund"])
  329. except Exception as e:
  330. print e
  331. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  332. today_record["today_stock_total"] = today_stock_total
  333. return today_record
  334. @ccc.cache_data()
  335. def get_match_group_players(match_id,match_group):
  336. players = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values())
  337. return players
  338. #@ccc.cache_data()
  339. def get_match_group_users(match_id,match_group):
  340. users = list(cm.UserMatch.objects.filter(match_id=match_id,match_group=match_group).values())
  341. return users
  342. @ccc.cache_data()
  343. def get_match_groups(match_id):
  344. """
  345. """
  346. match = cm.Match.objects.filter(id=match_id).values().first()
  347. groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).order_by("order").values())
  348. return match,groups
  349. def get_cache_rank_list(match_id,today):
  350. """
  351. """
  352. match,groups = get_match_groups(match_id)
  353. data = []
  354. for item in groups:
  355. new_players = []
  356. players = get_match_group_users(match_id,item["id"])
  357. win_count = 0
  358. loss_count = 0
  359. for player in players:
  360. user_id = player["user_id"]
  361. username = player["signup_name"]
  362. match_group = player["match_group"]
  363. today_record = ccc.get_today_record(user_id,match_id,match_group,today)
  364. print(today_record,999999999999999999999)
  365. if today_record:
  366. player.update(today_record)
  367. player["username"] = username
  368. player["org_today_income"] = player["today_income"]
  369. player["org_total_income"] = player["total_income"]
  370. player["total_income"] = "{}%".format(today_record["total_income"]*100)
  371. player["today_income"] = "{}%".format(today_record["today_income"]*100)
  372. if player["org_today_income"] >= 0.05:
  373. win_count += 1
  374. if player["org_today_income"] <= -0.05:
  375. loss_count += 1
  376. try:
  377. player["fund"] = round(player["fund"],4) if player["fund"] else 0.0
  378. player["init_fund"] = round(player["init_fund"],4)
  379. player["fund"] = round(player["init_fund"],4)
  380. player["today_fund"] = round(player["today_fund"],4)
  381. new_players.append(player)
  382. except Exception as e:
  383. print player
  384. pass
  385. new_players_sort = list(sorted(new_players,key=lambda x:x["org_total_income"],reverse=True))
  386. item["players_num"] = len(players)
  387. item["win_count"] = win_count
  388. item["loss_count"] = loss_count
  389. item["players"] = new_players_sort[:3]
  390. data.append(item)
  391. return match,data
  392. def get_rank_list(request):
  393. """排名列表
  394. """
  395. qdata = request.json
  396. print(qdata)
  397. user_id = request.user.get("id",0)
  398. match_id = qdata.get("match_id")
  399. today = qdata.get("stock_date")
  400. if not today:
  401. today = get_today_date()
  402. match,groups = get_cache_rank_list(match_id,today)
  403. ret = {"match":match,"groups":groups}
  404. return ret
  405. @ccc.cache_data()
  406. def get_user_info(uid):
  407. user = cm.UserInfo.objects.filter(id=uid).values().first()
  408. if user:
  409. user["style"] = []
  410. if user["zq"]:
  411. user["style"].append(user["zq"])
  412. if user["cw"]:
  413. user["style"].append(user["cw"])
  414. if user["df"]:
  415. user["style"].append(user["df"])
  416. return user
  417. #@ccc.cache_data()
  418. def get_player_info(player_id):
  419. player = cm.Player.objects.filter(id=player_id).values().first()
  420. return player
  421. @ccc.cache_data()
  422. def get_match_info(match_id):
  423. match = cm.Match.objects.filter(id=match_id).values().first()
  424. return match
  425. @ccc.cache_data()
  426. def get_group_info(group_id):
  427. group = cm.MatchGroup.objects.filter(id=group_id).values().first()
  428. group["players_num"] = cm.Player.objects.filter(match_group=group["id"]).count()
  429. return group
  430. def get_group_rank_list(request):
  431. """排名列表
  432. """
  433. qdata = request.json
  434. kwargs = qdata
  435. group_id = qdata.get("id")
  436. match_id = qdata.get("match_id")
  437. match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id
  438. today = qdata.get("stock_date")
  439. if not today:
  440. today = get_today_date()
  441. match = get_match_info(match_id)
  442. group = get_group_info(group_id)
  443. players = get_match_group_users(match_id,group_id)
  444. new_players = []
  445. for player in players:
  446. user_id = player["user_id"]
  447. #user = get_user_info(user_id)
  448. #username = user["username"] if user else ""
  449. username = player["signup_name"]
  450. match_group = group_id
  451. today_record = ccc.get_today_record(user_id,match_id,match_group,today)
  452. if today_record:
  453. player.update(today_record)
  454. player["username"] = username
  455. player["org_today_income"] = player["today_income"]
  456. player["org_total_income"] = player["total_income"]
  457. player["total_income"] = "{}%".format(player["total_income"]*100)
  458. player["today_income"] = "{}%".format(player["today_income"]*100)
  459. player["fund"] = round(player["fund"],4)
  460. player["init_fund"] = round(player["init_fund"],4)
  461. player["today_fund"] = round(player["today_fund"],4)
  462. new_players.append(player)
  463. if kwargs.get("order_by") == "today_income__asc":
  464. new_players = sorted(new_players,key=lambda x:x["org_today_income"])
  465. elif kwargs.get("order_by") == "today_income__desc" :
  466. new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True)
  467. elif kwargs.get("order_by") == "total_income__asc":
  468. new_players = sorted(new_players,key=lambda x:x["org_total_income"])
  469. elif kwargs.get("order_by") == "total_income__desc":
  470. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  471. else:
  472. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  473. #new_players = []
  474. #分页
  475. page = int(kwargs.get("page",0))
  476. page_size = int(kwargs.get("page_size",50))
  477. #page_size = 50
  478. if page and page_size:
  479. total,new_players = ccf.get_page_list(new_players,page,page_size)
  480. else:
  481. total = len(new_players)
  482. #应到、实到、请假人数
  483. total_person = cm.Player.objects.filter(match_group=group_id,match_status=1).count()
  484. actual_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today).count()
  485. leave_person = total_person - actual_person
  486. win_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__gte=0).count()
  487. loss_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__lt=0).count()
  488. ret = {"group":group,"players":new_players,"total":total,"total_person":total_person,
  489. "actual_person":actual_person,"leave_person":leave_person,"win_person":win_person,"loss_person":loss_person}
  490. return ret
  491. def get_player_match_records(request):
  492. """选手参赛每日持股
  493. """
  494. qdata = request.json
  495. match_id = qdata.get("id")
  496. user_id = qdata.get("user_id")
  497. page = int(qdata.get("page",0))
  498. page_size = int(qdata.get("page_size",20))
  499. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).order_by("-stock_date")
  500. data = list(records_set.values())
  501. for item in data:
  502. today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
  503. today_stock = filter(lambda x:x["name"],today_stock if today_stock else [])
  504. item["today_stock"] = today_stock
  505. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
  506. yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
  507. yesterday_stock = filter(lambda x:x["name"],yesterday_stock if yesterday_stock else [])
  508. item["yesterday_stock"] = yesterday_stock
  509. item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
  510. item["today_income"] = "{}%".format(item["today_income"]*100)
  511. item["total_income"] = "{}%".format(item["total_income"]*100)
  512. item["zans_count"] = item.get("zans",0)
  513. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  514. if page and page_size:
  515. total,data = ccf.get_page_list(data,page,page_size)
  516. return total,data
  517. else:
  518. return len(data),data
  519. def add_model(cls,**kwargs):
  520. """
  521. """
  522. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  523. model = getattr(cm,model_name)
  524. if model_name == "PlayerRecord":
  525. user_id = kwargs.get("user_id")
  526. match_id = kwargs.get("match_id")
  527. stock_date = kwargs.get("stock_date")
  528. now = datetime.datetime.now()
  529. print(user_id,match_id)
  530. if not cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).exists():
  531. raise ce.TipException(u"请先完成报名再提交数据!")
  532. if now.weekday() in [5,6] or not now.strftime("%Y-%m-%d") in get_match_validdates(match_id):
  533. raise ce.TipException(u"今日不能提交数据!")
  534. now_time = datetime.datetime.now().strftime("%H:%S")
  535. if not user_id in [9600,6209,5709]:
  536. if now_time<"15:00" or now_time > "23:50":
  537. raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
  538. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  539. today_stock = json.dumps(kwargs.get("today_stock"))
  540. today_stock_img = json.dumps(kwargs.get("today_stock_img"))
  541. today_fund = float(kwargs.get("today_fund",0))
  542. is_markt = int(kwargs.get("is_markt",0))
  543. experience = kwargs.get("experience")
  544. if not ccc.get_cur_match().id == match_id:
  545. raise ce.TipException(u"非当前赛事参赛选手不能提交作业!")
  546. #计算今日和昨日盈亏
  547. if float(today_fund)>9999 or float(today_fund)<=0:
  548. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  549. player = cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).first()
  550. user_id = player.user_id
  551. init_fund = player.fund
  552. user = cm.UserInfo.objects.filter(id=user_id).first()
  553. username = user.username
  554. usercode = user.usercode
  555. match_group = player.match_group
  556. zq = user.zq
  557. cw = user.cw
  558. df = user.df
  559. match = cm.Match.objects.filter(id=match_id).first()
  560. if player.match_status < 1:
  561. raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
  562. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  563. if not user_id in [9600,6209,5709]:
  564. if match.end_time < now_date:
  565. raise ce.TipException(u"该比赛已结束或您未参加此次比赛不能提交数据!")
  566. validdates = get_match_validdates(match_id)
  567. today_index = validdates.index(stock_date)
  568. yesterday_index = today_index -1 if today_index >=1 else 0
  569. yesterday_date = validdates[yesterday_index]
  570. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  571. match_id=match_id,user_id=user_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
  572. if yesterday:
  573. yesterday_fund = yesterday.today_fund
  574. yesterday_stock = yesterday.today_stock
  575. yesterday_stock_img = yesterday.today_stock_img
  576. yesterday_is_markt = yesterday.is_markt
  577. else:
  578. yesterday_fund = today_fund
  579. yesterday_stock = ""
  580. yesterday_stock_img = ""
  581. yesterday_is_markt = 0
  582. if not cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).exists():
  583. init_fund = today_fund
  584. cm.UserMatch.objects.filter(id=user_id,match_id=match_id).update(fund=today_fund)
  585. with transaction.atomic():
  586. #记录持股情况
  587. new_stock_list = []
  588. today_stock_list = json.loads(today_stock)
  589. for ts in today_stock_list:
  590. if ts["name"]:
  591. try:
  592. stock,flag = cm.Stock.objects.get_or_create(
  593. name = ts["name"]
  594. )
  595. stock_id = stock.id
  596. usobj,flag = cm.UserStock.objects.get_or_create(
  597. user_id = user_id,
  598. stock_id = stock_id,
  599. stock_name = ts["name"],
  600. stock_date = stock_date
  601. )
  602. ts["stock_id"] = stock_id
  603. new_stock_list.append(ts)
  604. except Exception as e:
  605. print(e)
  606. today_stock = json.dumps(new_stock_list)
  607. obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
  608. user_id=user_id,
  609. match_id=match_id,
  610. stock_date=stock_date)
  611. obj.init_fund = init_fund
  612. obj.yesterday_fund = yesterday_fund
  613. obj.yesterday_stock = yesterday_stock
  614. obj.yesterday_stock_img = yesterday_stock_img
  615. obj.today_fund = today_fund
  616. obj.today_stock = today_stock
  617. obj.today_stock_img = today_stock_img
  618. obj.username = username
  619. obj.usercode = usercode
  620. obj.match_group = match_group
  621. obj.is_markt = is_markt
  622. obj.yesterday_is_markt = yesterday_is_markt
  623. obj.zq = zq
  624. obj.cw = cw
  625. obj.df = df
  626. obj.experience = experience
  627. #计算今日收益和总收益
  628. if float(today_fund)>9999 or float(today_fund)<=0:
  629. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  630. #有资金出入
  631. if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists() and flag:
  632. fundinout = cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).first()
  633. fundin = fundinout.fundin
  634. fundout = fundinout.fundout
  635. #入资金
  636. if fundin > fundout:
  637. fundin = fundin - fundout
  638. today_income = (today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin)
  639. total_income = (today_fund-init_fund-fundin)/(init_fund+fundin)
  640. cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).update(fund=init_fund+fundin)
  641. obj.init_fund = init_fund + fundin
  642. obj.yesterday_fund = obj.yesterday_fund + fundin
  643. #出资金
  644. else:
  645. fundout = fundout - fundin
  646. today_income = (today_fund-(yesterday_fund-fundout))/float(yesterday_fund)
  647. total_income = (today_fund+fundout-init_fund)/init_fund
  648. cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).update(fund=round(today_fund/(1+total_income),4))
  649. obj.init_fund = round(today_fund/(1+total_income),4)
  650. obj.yesterday_fund = round(today_fund/(1+today_income),4)
  651. if float(today_income)>0.6:
  652. raise ce.TipException(u"今日盈利已超过60%,请仔细核对数据或直接联系顽主!")
  653. if float(total_income)>8:
  654. raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
  655. obj.today_income = round(today_income,4)
  656. obj.total_income = round(total_income,4)
  657. else:
  658. today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
  659. total_income = (today_fund - init_fund)/float(init_fund)
  660. if float(today_income)>0.4:
  661. raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
  662. if float(total_income)>8:
  663. raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
  664. obj.today_income = round(today_income,4)
  665. obj.total_income = round(total_income,4)
  666. if not flag:
  667. obj.ctime = datetime.datetime.now()
  668. obj.save()
  669. #更新group_rank
  670. ccc.cache.lpush(settings.RANK_LIST,obj.id)
  671. return obj.id
  672. obj = model.objects.create(**kwargs)
  673. return obj.id
  674. def update_model(cls,**kwargs):
  675. """
  676. """
  677. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  678. model = getattr(cm,model_name)
  679. id = kwargs.pop("id")
  680. rst = model.objects.filter(id=id).update(**kwargs)
  681. if model_name == "Match":
  682. for item in kwargs.get("groups").split(","):
  683. cm.MatchGroup.objects.get_or_create(match_id=obj.id,name=item)
  684. return rst
  685. def delete_model(cls,**kwargs):
  686. """
  687. """
  688. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  689. model = getattr(cm,model_name)
  690. ids = str(kwargs.get("id")).split(",")
  691. rst = model.objects.filter(id__in=ids).delete()
  692. if model_name == "Comments":
  693. cm.Comments.objects.filter(pid__in=ids).delete()
  694. return ids
  695. def get_search_list(cls,**kwargs):
  696. """
  697. """
  698. model_name = re.search(r'.*\.(\w+)SearchView',str(cls.__class__)).groups()[0]
  699. model = getattr(cm,model_name)
  700. qset = model.objects.all()
  701. if model_name == "Stock":
  702. if kwargs.get("name"):
  703. qset = qset.filter(Q(name__icontains=kwargs.get("name"))|Q(code__icontains=kwargs.get("name")))
  704. else:
  705. if kwargs.get("name"):
  706. qset = qset.filter(name__icontains=kwargs.get("name"))
  707. if model_name == "Player":
  708. data = list(qset.values("id","username"))
  709. if model_name == "Stock":
  710. qset = qset.filter(code__isnull=False)
  711. data = list(qset.values("id","name","code"))
  712. for item in data:
  713. if item["code"]:
  714. item["label"] = "%s(%s)" % (item["name"],item["code"])
  715. else:
  716. item["label"] = "%s" % item["name"]
  717. else:
  718. data = list(qset.values("id","name"))
  719. return data
  720. def get_detail_info(cls,**kwargs):
  721. """
  722. """
  723. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  724. model = getattr(cm,model_name)
  725. id = kwargs.get("id")
  726. rst = list(model.objects.filter(id=id).values())
  727. rst = rst[0] if rst else {}
  728. if model_name == "Article":
  729. rst["ctime"] = ccf.datetime_to_str(rst["ctime"],"%Y-%m-%d")
  730. if model_name == "Stock":
  731. rst["choiced"] = ccc.cache.get("%s_choices" % id)
  732. rst["user_num"] = ccc.cache.get("%s_choices" % id)
  733. return rst
  734. #@ccc.cache_data()
  735. def get_record_info(rcid):
  736. """
  737. """
  738. rst = cm.PlayerRecord.objects.filter(id=rcid).values().first()
  739. if rst:
  740. rst["match_group"] = cm.MatchGroup.objects.filter(id=rst["match_group"]).first().name
  741. today_stock = json.loads(rst["today_stock"]) if rst["today_stock"] else []
  742. today_stock = filter(lambda x:x["fund"] and x["name"],today_stock if today_stock else [])
  743. rst["today_stock"] = today_stock
  744. today_stock_img = json.loads(rst["today_stock_img"]) if rst["today_stock_img"] else []
  745. rst["today_stock_img"] = today_stock_img
  746. yesterday_stock = json.loads(rst["yesterday_stock"]) if rst["yesterday_stock"] else []
  747. yesterday_stock = filter(lambda x:x["fund"] and x["name"],yesterday_stock if yesterday_stock else [])
  748. rst["yesterday_stock"] = yesterday_stock
  749. yesterday_stock_img = json.loads(rst["yesterday_stock_img"]) if rst["yesterday_stock_img"] else []
  750. rst["yesterday_stock_img"] = yesterday_stock_img
  751. rst["today_income"] = "{}%".format(rst["today_income"]*100)
  752. rst["total_income"] = "{}%".format(rst["total_income"]*100)
  753. return rst
  754. def get_list_info(cls,**kwargs):
  755. """
  756. """
  757. model_name = re.search(r'.*\.(\w+)ListView',str(cls.__class__)).groups()[0]
  758. model = getattr(cm,model_name)
  759. qset = model.objects.all()
  760. if kwargs.get("name"):
  761. qset = qset.filter(name__icontains=kwargs.get("name"))
  762. if model_name == "UserInfo":
  763. if kwargs.get("username"):
  764. qset = qset.filter(username__icontains=kwargs.get("username"))
  765. if kwargs.get("usercode"):
  766. qset = qset.filter(usercode=kwargs.get("usercode"))
  767. data = list(qset.order_by("-id").values())
  768. page = int(kwargs.get("page",0))
  769. page_size = int(kwargs.get("page_size",20))
  770. if page and page_size:
  771. total,data = ccf.get_page_list(data,page,page_size)
  772. if model_name == "Player":
  773. for item in data:
  774. user = cm.UserInfo.objects.filter(id=item["user_id"]).first()
  775. match = cm.Match.objects.filter(id=item["match_id"]).first()
  776. item["username"] = user.username
  777. item["usercode"] = user.usercode
  778. item["match_name"] = match.name if match else ""
  779. return (total,data)
  780. else:
  781. return len(data),data
  782. return rst
  783. def add_player_record_single(**kwargs):
  784. """用户单独上传数据
  785. """
  786. return None
  787. now = datetime.datetime.now()
  788. if now.weekday() in [5,6] or now.strftime("%Y-%m-%d") in MISS_DATES:
  789. raise ce.TipException(u"今日不能提交数据!")
  790. now_time = datetime.datetime.now().strftime("%H:%S")
  791. if now_time<"15:00" or now_time > "23:50":
  792. raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
  793. usercode = kwargs.get("usercode")
  794. match_id = kwargs.get("match_id")
  795. if not cm.Player.objects.filter(usercode=usercode,match_id=match_id).exists():
  796. raise ce.TipException(u"用户代码错误")
  797. stock_date = kwargs.get("stock_date")
  798. #stock_date = "2022-04-26"
  799. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  800. today_stock = json.dumps(kwargs.get("today_stock"))
  801. today_stock_img = json.dumps(kwargs.get("today_stock_img"))
  802. today_fund = float(kwargs.get("today_fund"))
  803. is_markt = int(kwargs.get("is_markt",0))
  804. if int(today_fund)>9999 or int(today_fund)<0:
  805. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  806. player = cm.Player.objects.filter(usercode=usercode,match_id=match_id).first()
  807. #if player.fund <=0 :
  808. # raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
  809. player_id = player.id
  810. user_id = player.user_id
  811. init_fund = player.fund
  812. user = cm.UserInfo.objects.filter(id=user_id).first()
  813. username = user.username
  814. usercode = user.usercode
  815. match_group = player.match_group
  816. match = cm.Match.objects.filter(id=match_id).first()
  817. if player.match_status < 1:
  818. raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
  819. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  820. if match.end_time < now_date:
  821. raise ce.TipException(u"该比赛已结束!")
  822. #yesterday = cm.PlayerRecord.objects.filter(
  823. # match_id=match_id,player_id=player_id).order_by("-id").first()
  824. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  825. match_id=match_id,player_id=player_id).order_by("-stock_date").first()
  826. if yesterday:
  827. yesterday_fund = yesterday.today_fund
  828. yesterday_stock = yesterday.today_stock
  829. yesterday_stock_img = yesterday.today_stock_img
  830. else:
  831. #yesterday_fund = init_fund
  832. yesterday_fund = today_fund
  833. init_fund = today_fund
  834. yesterday_stock = ""
  835. yesterday_stock_img = ""
  836. cm.Player.objects.filter(id=player_id).update(fund=today_fund)
  837. #记录持股情况
  838. new_stock_list = []
  839. today_stock_list = json.loads(today_stock)
  840. for ts in today_stock_list:
  841. if ts["name"]:
  842. stock,flag = cm.Stock.objects.get_or_create(
  843. name = ts["stock"]
  844. )
  845. stock_id = stock.id
  846. usobj,flag = cm.UserStock.objects.get_or_create(
  847. player_id = player_id,
  848. stock_id = stock_id,
  849. stock_name = ts["name"],
  850. stock_date = stock_date
  851. )
  852. ts["stock_id"] = stock_id
  853. new_stock_list.append(ts)
  854. today_stock = json.dumps(new_stock_list)
  855. obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
  856. player_id=player_id,
  857. match_id=match_id,
  858. stock_date=stock_date)
  859. obj.init_fund = init_fund
  860. obj.yesterday_fund = yesterday_fund
  861. obj.yesterday_stock = yesterday_stock
  862. obj.yesterday_stock_img = yesterday_stock_img
  863. obj.today_fund = today_fund
  864. obj.today_stock = today_stock
  865. obj.today_stock_img = today_stock_img
  866. obj.user_id = user_id
  867. obj.username = username
  868. obj.usercode = usercode
  869. obj.match_group = match_group
  870. obj.is_markt = is_markt
  871. #计算今日和昨日盈亏
  872. today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
  873. total_income = (today_fund - init_fund)/float(init_fund)
  874. #if int(today_fund)>9999 or int(today_fund)<0:
  875. # raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  876. if int(today_income)>2:
  877. raise ce.TipException(u"数据错误,今日盈利已超过2倍,请仔细核对数据!")
  878. obj.today_income = round(today_income,4)
  879. obj.total_income = round(total_income,4)
  880. if not flag:
  881. obj.ctime = datetime.datetime.now()
  882. obj.save()
  883. #更新股票持股人数
  884. for stock in new_stock_list:
  885. cm.Stock.objects.filter(id=stock["id"]).update(user_num=F("user_num")+1)
  886. #更新group_rank
  887. #update_group_rank(match_id,match_group,obj.stock_date)
  888. ccc.cache.lpush(settings.RANK_LIST,obj.id)
  889. return obj.id
  890. def get_single_match_info(match_id):
  891. """
  892. """
  893. if not match_id:
  894. match = cm.Match.objects.all().order_by("-id").values().first()
  895. else:
  896. match = cm.Match.objects.filter(id=match_id).values().first()
  897. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  898. return now_date,match
  899. def get_cur_record(request):
  900. """
  901. """
  902. user_id = request.user.get("id")
  903. match_id = ccc.get_cur_match().id
  904. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  905. 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")
  906. data = qset.values().first() if qset else {}
  907. if data:
  908. data["today_stock_img"] = json.loads(data["today_stock_img"]) if data["today_stock_img"] else []
  909. data["today_stock"] = json.loads(data["today_stock"]) if data["today_stock"] else []
  910. return data
  911. def follow_player(**kwargs):
  912. """
  913. """
  914. user_id = kwargs.get("user_id")
  915. follow_id = kwargs.get("follow_id")
  916. if kwargs.get("action") == "cancel":
  917. cm.UserFollows.objects.filter(user_id=user_id,follow_id=follow_id).delete()
  918. return True
  919. else:
  920. obj,flag = cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=follow_id)
  921. return obj.id
  922. def calc_win_rate(player_id,match_id):
  923. """计算胜率
  924. """
  925. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=player_id)
  926. win_rate = qset.filter(today_income__gte=0).count()/float(qset.count()) if qset else 0.0
  927. win_rate = round(win_rate,3)
  928. win_rate = "{}%".format(win_rate*100)
  929. return win_rate
  930. def get_user_follower(request):
  931. """获取用户列表
  932. """
  933. user_id = request.user.get("id")
  934. match_id = ccc.get_cur_match().id
  935. qdata = request.json
  936. _today = get_today_date()
  937. data = []
  938. qset = cm.UserFollows.objects.filter(follow_id=user_id)
  939. follow_ids = list(qset.values_list("user_id",flat=True))
  940. for player_id in follow_ids:
  941. latest_key = "PLAYER_LATEST_%d"%player_id
  942. _match_id = ccc.cache.hget(latest_key,"match_id")
  943. _today = ccc.cache.hget(latest_key,"stock_date")
  944. _match_group = ccc.cache.hget(latest_key,"match_group")
  945. today_record = ccc.get_today_record(player_id,_match_id,_match_group,_today)
  946. if today_record:
  947. data.append(today_record)
  948. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  949. _today = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"stock_date")
  950. cur_user_latest = "PLAYER_LATEST_%d" % user_id
  951. _match_group = ccc.cache.hget(cur_user_latest,"match_group")
  952. cur_today_record = ccc.get_today_record(user_id,match_id,_match_group,_today)
  953. if cur_today_record:
  954. data.insert(0,cur_today_record)
  955. page = int(qdata.get("page",1))
  956. page_size = int(qdata.get("page_size",20))
  957. if page and page_size:
  958. total,data = ccf.get_page_list(data,page,page_size)
  959. for item in data:
  960. if item:
  961. today_stock = json.loads(item["today_stock"])
  962. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  963. item["today_stock"] = today_stock
  964. item["today_stock_img"] = json.loads(item["today_stock_img"])
  965. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
  966. if win_rate:
  967. item["win_rate"] = str(float(win_rate)*100)+"%"
  968. else:
  969. item["win_rate"] = "0.0%"
  970. item["today_income"] = "{}%".format(item["today_income"]*100)
  971. item["total_income"] = "{}%".format(item["total_income"]*100)
  972. return total,data
  973. else:
  974. return len(data),data
  975. def get_user_follows(request):
  976. """获取用户关注的选手列表
  977. """
  978. user_id = request.user.get("id",0)
  979. qdata = request.json
  980. qset = cm.UserFollows.objects.filter(user_id=user_id)
  981. follow_ids = list(qset.values_list("follow_id",flat=True))
  982. today = get_today_date()
  983. _today = today
  984. data = []
  985. for user_id in follow_ids:
  986. latest_key = "PLAYER_LATEST_%d"%user_id
  987. _match_id = ccc.cache.hget(latest_key,"match_id")
  988. _today = ccc.cache.hget(latest_key,"stock_date")
  989. _match_group = ccc.cache.hget(latest_key,"match_group")
  990. today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
  991. if today_record:
  992. today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
  993. today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
  994. data.append(today_record)
  995. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  996. page = int(qdata.get("page",1))
  997. page_size = int(qdata.get("page_size",20))
  998. if page and page_size:
  999. total,data = ccf.get_page_list(data,page,page_size)
  1000. for item in data:
  1001. if item:
  1002. user_id = item["user_id"]
  1003. latest_key = "PLAYER_LATEST_%d"%user_id
  1004. today_stock = json.loads(item["today_stock"])
  1005. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  1006. item["today_stock"] = today_stock
  1007. item["today_stock_img"] = json.loads(item["today_stock_img"])
  1008. win_rate = ccc.cache.hget(latest_key,"win_rate")
  1009. if win_rate:
  1010. item["win_rate"] = str(float(win_rate)*100)+"%"
  1011. else:
  1012. item["win_rate"] = "0.0%"
  1013. item["today_income"] = "{}%".format(item["today_income"]*100)
  1014. item["total_income"] = "{}%".format(item["total_income"]*100)
  1015. item["zans_count"] = item.get("zans",0)
  1016. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  1017. return total,data
  1018. else:
  1019. return len(data),data
  1020. def get_hot_stock_rank(**kwargs):
  1021. """
  1022. """
  1023. data = {
  1024. "hot_buy":[
  1025. {"stock_name":u"创业黑马","count":12}
  1026. ],
  1027. "hot_sell":[
  1028. {"stock_name":u"创业黑马","count":12}
  1029. ]
  1030. }
  1031. return data
  1032. #@ccc.cache_data()
  1033. def get_stock_info(stock_id):
  1034. """
  1035. """
  1036. stock = cm.Stock.objects.filter(id=stock_id).values().first()
  1037. stock["choiced"] = 1
  1038. return stock
  1039. def get_hot_stock_buy(**kwargs):
  1040. """
  1041. """
  1042. stock_date = kwargs.get("stock_date")
  1043. qset = cm.UserStock.objects.filter(stock_date=stock_date)
  1044. if kwargs.get("name"):
  1045. qset = cm.UserStock.objects.filter(stock_name__icontains=kwargs.get("name"))
  1046. qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id")).order_by("-count")
  1047. data = []
  1048. for q in qset:
  1049. stock_id = q["stock_id"]
  1050. count = q["count"]
  1051. stock_name = q.get("stock_name")
  1052. comments_count = ccc.cache.get("%s_comments" % stock_id)
  1053. choice_count = ccc.cache.get("%s_choices" % stock_id)
  1054. comments_count = comments_count if comments_count else 0
  1055. choice_count = choice_count if choice_count else 0
  1056. data.append({"stock_name":stock_name,"id":stock_id,"count":count,"comments_count":comments_count,"choice_count":choice_count})
  1057. page = int(kwargs.get("page",1))
  1058. page_size = int(kwargs.get("page_size",20))
  1059. if page and page_size:
  1060. total,data = ccf.get_page_list(data,page,page_size)
  1061. return total,data
  1062. else:
  1063. return len(data),data
  1064. return data
  1065. def get_hot_follow(**kwargs):
  1066. """
  1067. """
  1068. stock_date = kwargs.get("stock_date")
  1069. match_id = kwargs.get("match_id")
  1070. if not match_id:
  1071. match_id = ccc.get_cur_match().id
  1072. #player_ids = list(cm.Player.objects.filter(match_id=cur_match_id,match_status=1).values_list("id",flat=True))
  1073. player_ids = list(cm.Player.objects.filter(match_id=match_id).values_list("user_id",flat=True))
  1074. qset = cm.UserFollows.objects.filter(follow_id__in=player_ids)
  1075. qset = qset.values("follow_id").annotate(count=Count("follow_id")).order_by("-count")
  1076. data = []
  1077. for q in qset:
  1078. player_id = q["follow_id"]
  1079. count = q["count"]
  1080. today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1081. match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
  1082. match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
  1083. badest_income = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"badest_income")
  1084. today_record = get_today_record(player_id,match_id,match_group,today)
  1085. if today_record:
  1086. userinfo = get_user_info(today_record["user_id"])
  1087. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"win_rate")
  1088. try:
  1089. win_rate = str(float(win_rate)*100)+"%"
  1090. except:
  1091. pass
  1092. if userinfo:
  1093. data.append(
  1094. {
  1095. "player_name":userinfo.get("username"),
  1096. "count":count,
  1097. "id":player_id,
  1098. "today_fund":today_record["today_fund"],
  1099. "total_income":"{}%".format(today_record["total_income"]*100),
  1100. "today_income":"{}%".format(today_record["today_income"]*100),
  1101. "badest_income":"{}%".format(badest_income*100) if badest_income else "0.0%",
  1102. "style":userinfo.get("style"),
  1103. "badge":userinfo.get("badge"),
  1104. "match_id":match_id,
  1105. "win_rate":win_rate
  1106. }
  1107. )
  1108. if kwargs.get("name"):
  1109. data = filter(lambda x:kwargs.get("name") in x["player_name"],data)
  1110. page = int(kwargs.get("page",1))
  1111. page_size = int(kwargs.get("page_size",20))
  1112. if page and page_size:
  1113. total,data = ccf.get_page_list(data,page,page_size)
  1114. return total,data
  1115. else:
  1116. return len(data),data
  1117. return data
  1118. def get_hot_stock_sell(**kwargs):
  1119. """
  1120. """
  1121. stock_date = kwargs.get("stock_date")
  1122. stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
  1123. yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  1124. ##昨天所有股票
  1125. #yes_stock_ids = list(cm.UserStock.objects.filter(stock_date=yesterday).values_list("stock_id",flat=True))
  1126. #yes_stock_ids = list(set(yes_stock_ids))
  1127. #data = []
  1128. #for ysi in yes_stock_ids:
  1129. # yes_count = cm.UserStock.objects.filter(stock_date=yesterday,stock_id=ysi).count()
  1130. # td_count = cm.UserStock.objects.filter(stock_date=stock_date,stock_id=ysi).count()
  1131. # if td_count < yes_count:
  1132. # stock_name = cm.Stock.objects.filter(id=ysi).first().name
  1133. # data.append({"stock_name":stock_name,"count":yes_count-td_count,"id":ysi})
  1134. qset = cm.HotStockSellCount.objects.filter(stock_date=stock_date)
  1135. if kwargs.get("name"):
  1136. qset = qset.filter(stock_name__icontains=kwargs.get("name"))
  1137. qset = qset.order_by("-count")
  1138. data = list(qset.values("stock_name","stock_id","count"))
  1139. for item in data:
  1140. item["id"] = item["stock_id"]
  1141. page = int(kwargs.get("page",0))
  1142. page_size = int(kwargs.get("page_size",20))
  1143. if page and page_size:
  1144. total,data = ccf.get_page_list(data,page,page_size)
  1145. return total,data
  1146. else:
  1147. return len(data),data
  1148. return data
  1149. def get_stock_info(_id):
  1150. """
  1151. """
  1152. data = cm.Stock.objects.filter(id=_id).values().first()
  1153. return data
  1154. def get_hot_stock_sell_players(**kwargs):
  1155. """
  1156. """
  1157. _id = kwargs.get("id")
  1158. stock_date = kwargs.get("stock_date")
  1159. stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
  1160. yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  1161. #昨天持股选手
  1162. yes_players = list(cm.UserStock.objects.filter(stock_date=yesterday,stock_id=_id).values_list("player_id",flat=True))
  1163. td_players = list(cm.UserStock.objects.filter(stock_date=stock_date,stock_id=_id).values_list("player_id",flat=True))
  1164. sell_players = list(set(yes_players)-set(td_players))
  1165. data = []
  1166. for player_id in sell_players:
  1167. player = cm.Player.objects.filter(id=player_id).first()
  1168. if player:
  1169. match_id = player.match_id
  1170. match_group = player.match_group
  1171. today_record = get_today_record(player_id,match_id,match_group,stock_date)
  1172. if today_record:
  1173. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  1174. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  1175. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  1176. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  1177. data.append(today_record)
  1178. data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
  1179. page = int(kwargs.get("page",0))
  1180. page_size = int(kwargs.get("page_size",20))
  1181. if page and page_size:
  1182. total,data = ccf.get_page_list(data,page,page_size)
  1183. return total,data
  1184. else:
  1185. return len(data),data
  1186. return data
  1187. def get_win_rate_rank(request):
  1188. """
  1189. """
  1190. player_id = request.player.id
  1191. match_id = request.player.match_id
  1192. match_group = request.player.match_group
  1193. kwargs = request.json
  1194. match_id = ccc.get_cur_match().id
  1195. qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lt=5,match_status=1).order_by("-win_rate")
  1196. data = list(qset.values())
  1197. page = int(kwargs.get("page",1))
  1198. page_size = int(kwargs.get("page_size",20))
  1199. if page and page_size:
  1200. total,data = ccf.get_page_list(data,page,page_size)
  1201. else:
  1202. total = len(data)
  1203. for item in data:
  1204. item["win_rate"] = "{}%".format(item["win_rate"]*100)
  1205. item["badest_income"] = "{}%".format(item["badest_income"]*100)
  1206. item["total_income"] = "{}%".format(item["total_income"]*100)
  1207. userinfo = get_user_info(item["user_id"])
  1208. if userinfo:
  1209. item["badge"] = userinfo.get("badge")
  1210. item["style"] = userinfo.get("style")
  1211. item["username"] = userinfo.get("username")
  1212. return total,data
  1213. def get_defend_rank(request):
  1214. """
  1215. """
  1216. player_id = request.player.id
  1217. match_id = request.player.match_id
  1218. match_group = request.player.match_group
  1219. kwargs = request.json
  1220. qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lte=5,match_status=1).order_by("-badest_income")
  1221. data = list(qset.values())
  1222. #data = []
  1223. #for item in datas:
  1224. # player = cm.Player.objects.filter(id=item["player_id"]).first()
  1225. # item["match_status"] = player.match_status if player else -1
  1226. # if item["match_status"] > -1:
  1227. # data.append(item)
  1228. page = int(kwargs.get("page",1))
  1229. page_size = int(kwargs.get("page_size",20))
  1230. if page and page_size:
  1231. total,data = ccf.get_page_list(data,page,page_size)
  1232. else:
  1233. total = len(data)
  1234. for item in data:
  1235. item["win_rate"] = "{}%".format(item["win_rate"]*100)
  1236. item["badest_income"] = "{}%".format(item["badest_income"]*100)
  1237. item["total_income"] = "{}%".format(item["total_income"]*100)
  1238. userinfo = get_user_info(item["user_id"])
  1239. if userinfo:
  1240. item["badge"] = userinfo.get("badge")
  1241. item["style"] = userinfo.get("style")
  1242. item["username"] = userinfo.get("username")
  1243. return total,data
  1244. def get_champion_articles_list(request):
  1245. """
  1246. """
  1247. kwargs = request.json
  1248. _type = kwargs.get("type")
  1249. isbanner = kwargs.get("isbanner")
  1250. qset = cm.Article.objects.filter(status=2).order_by("-id")
  1251. if _type:
  1252. qset = qset.filter(type=_type)
  1253. if isbanner:
  1254. qset = qset.filter(isbanner=isbanner)
  1255. page = int(kwargs.get("page",0))
  1256. page_size = int(kwargs.get("page_size",20))
  1257. if page and page_size:
  1258. total,qset = ccc.get_page_qset(qset,page,page_size)
  1259. else:
  1260. total = qset.count()
  1261. data = list(qset.values())
  1262. for item in data:
  1263. item["ctime"] = ccf.datetime_to_str(item["ctime"],"%Y-%m-%d")
  1264. return total,data
  1265. def get_wanzhu_comment(**kwargs):
  1266. """
  1267. """
  1268. match_id = kwargs.get("match_id")
  1269. group_id = kwargs.get("group_id")
  1270. today = get_today_date()
  1271. players = get_match_group_players(match_id,group_id)
  1272. new_players = []
  1273. for player in players:
  1274. user_id = player["user_id"]
  1275. user = get_user_info(user_id)
  1276. username = user["username"] if user else ""
  1277. player_id = player["id"]
  1278. match_group = group_id
  1279. today_record = get_today_record(player_id,match_id,int(match_group),today)
  1280. if today_record and today_record.get("wanzhu_comment"):
  1281. player.update(today_record)
  1282. player["username"] = username
  1283. player["total_income"] = "{}%".format(player["total_income"]*100)
  1284. player["fund"] = round(player["fund"],4)
  1285. player["init_fund"] = round(player["init_fund"],4)
  1286. player["today_fund"] = round(player["today_fund"],4)
  1287. player["today_stock"] = json.loads(player["today_stock"]) if player["today_stock"] else []
  1288. new_players.append(player)
  1289. new_players = sorted(new_players,key=lambda x:x["group_rank"])
  1290. data = new_players
  1291. page = int(kwargs.get("page",0))
  1292. page_size = int(kwargs.get("page_size",20))
  1293. if page and page_size:
  1294. total,data = ccf.get_page_list(data,page,page_size)
  1295. else:
  1296. total = len(data)
  1297. return total,data
  1298. def get_enum_list(request):
  1299. """
  1300. """
  1301. data = {
  1302. "zq":[
  1303. u"短线博弈",
  1304. u"长线价投",
  1305. u"长短兼备"
  1306. ],
  1307. "cw":[
  1308. u"分仓开超市",
  1309. u"重仓押注",
  1310. u"全仓单钓",
  1311. u"融资加倍"
  1312. ],
  1313. "df":[
  1314. u"低吸",
  1315. u"半路",
  1316. u"首板",
  1317. u"接力",
  1318. u"撬板",
  1319. u"T加0",
  1320. u"隔夜卖",
  1321. u"格局锁仓",
  1322. u"核按钮"
  1323. ],
  1324. "pz":[
  1325. u"10厘米",
  1326. u"20厘米",
  1327. u"30厘米",
  1328. u"N/C新股",
  1329. u"次新股",
  1330. u"可转债",
  1331. u"港股",
  1332. u"基金",
  1333. u"逆回购"
  1334. ]
  1335. }
  1336. return data
  1337. def get_player_list(**kwargs):
  1338. """选手列表
  1339. """
  1340. match_id = kwargs.get("match_id")
  1341. today = get_today_date()
  1342. qset = cm.Player.objects.filter(match_id=match_id,match_status=1)
  1343. if kwargs.get("name"):
  1344. qset = qset.filter(username__icontains=kwargs.get("name"))
  1345. page = int(kwargs.get("page",0))
  1346. page_size = int(kwargs.get("page_size",20))
  1347. if page and page_size:
  1348. total,qset = ccc.get_page_qset(qset,page,page_size)
  1349. else:
  1350. total = qset.count()
  1351. data = list(qset.values())
  1352. for item in data:
  1353. #print(item)
  1354. match_id = item["match_id"]
  1355. match_group = item["match_group"]
  1356. user_id = item["user_id"]
  1357. player_id = item["id"]
  1358. #user = cm.UserInfo.objects.filter(id=user_id).first()
  1359. today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1360. match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
  1361. match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
  1362. today_record = get_today_record(player_id,match_id,match_group,today)
  1363. if today_record:
  1364. today_record.pop("id")
  1365. item.update(today_record)
  1366. user_info = get_user_info(user_id)
  1367. if user_info:
  1368. user_info.pop("id")
  1369. item.update(user_info)
  1370. if item.get("today_income"):
  1371. item["today_income"] = "{}%".format(item["today_income"]*100)
  1372. item["total_income"] = "{}%".format(item["total_income"]*100)
  1373. if kwargs.get("zq"):
  1374. data = filter(lambda x:kwargs.get("zq") == x.get("zq"),data)
  1375. if kwargs.get("cw"):
  1376. data = filter(lambda x:kwargs.get("cw") == x.get("cw"),data)
  1377. if kwargs.get("df"):
  1378. data = filter(lambda x:kwargs.get("df") == x.get("df"),data)
  1379. return total,data
  1380. def get_mine_style(request):
  1381. """
  1382. """
  1383. user = request.user
  1384. #player = request.player
  1385. user = cm.UserInfo.objects.filter(id=user["id"]).first()
  1386. match_id = ccc.get_cur_match().id
  1387. player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first()
  1388. data = {
  1389. "zq":user.zq,
  1390. "cw":user.cw,
  1391. "df":user.df,
  1392. "pz":user.pz,
  1393. "join_time":user.join_time,
  1394. "username":user.username,
  1395. "account_img":user.account_img,
  1396. "avatar":user.avatar
  1397. }
  1398. if player:
  1399. data["is_player"] = 1
  1400. data["init_fund"] = player.fund if player.fund else 0
  1401. else:
  1402. data["is_player"] = 0
  1403. data["init_fund"] = None
  1404. return data
  1405. def update_user_style(**kwargs):
  1406. """
  1407. """
  1408. user_id = kwargs.pop("user_id")
  1409. #player_id = kwargs.pop("player_id")
  1410. init_fund = kwargs.pop("init_fund")
  1411. #avatar = kwargs.pop("avatar")
  1412. cm.UserInfo.objects.filter(id=user_id).update(**kwargs)
  1413. #if player_id and init_fund:
  1414. # cm.Player.objects.filter(id=player_id).update(fund=init_fund)
  1415. #if kwargs.get("username"):
  1416. # cm.Player.objects.filter(id=player_id).update(username=kwargs.get("username"))
  1417. if kwargs.get("avatar"):
  1418. cm.UserInfo.objects.filter(id=user_id).update(avatar=kwargs.get("avatar"))
  1419. ccc.cache.delete("cdata_get_user_info_(%sL,)"%user_id)
  1420. return True
  1421. def get_stock_players(**kwargs):
  1422. """
  1423. """
  1424. stock_id = kwargs.get("stock_id")
  1425. stock_date = kwargs.get("stock_date",get_today_date())
  1426. data = []
  1427. user_stocks = cm.UserStock.objects.filter(stock_id=stock_id,stock_date=stock_date)
  1428. for us in user_stocks:
  1429. player_id = us.player_id
  1430. player = cm.Player.objects.filter(id=player_id).first()
  1431. if player:
  1432. match_id = player.match_id
  1433. match_group = player.match_group
  1434. user_id = player.user_id
  1435. if stock_date:
  1436. today_record = get_today_record(user_id,match_id,match_group,stock_date)
  1437. else:
  1438. today_record = get_today_record(user_id,match_id,match_group,us.stock_date)
  1439. if today_record:
  1440. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  1441. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  1442. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  1443. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  1444. data.append(today_record)
  1445. data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
  1446. #分页
  1447. page = int(kwargs.get("page",0))
  1448. page_size = int(kwargs.get("page_size",20))
  1449. if page and page_size:
  1450. total,data = ccf.get_page_list(data,page,page_size)
  1451. else:
  1452. total = len(data)
  1453. #return total,data
  1454. return data
  1455. def update_user_fund(**kwargs):
  1456. """
  1457. """
  1458. user_id = kwargs.pop("user_id")
  1459. player_id = kwargs.pop("player_id")
  1460. init_fund = kwargs.pop("init_fund")
  1461. if player_id and init_fund:
  1462. cm.Player.objects.filter(id=player_id).update(fund=init_fund)
  1463. return True
  1464. def get_player_match_calendar(**kwargs):
  1465. """
  1466. """
  1467. match_id = kwargs.get("match_id")
  1468. month = kwargs.get("month")
  1469. user_id = kwargs.get("user_id")
  1470. week,eday = calendar.monthrange(int(month.split("-")[0]),int(month.split("-")[1]))
  1471. sday = "01"
  1472. eday = str(eday).zfill(2)
  1473. sdate = month + "-" + sday
  1474. edate = month + "-" + eday
  1475. print sdate,edate
  1476. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id)\
  1477. .filter(stock_date__gte=sdate,stock_date__lte=edate)
  1478. data = list(qset.values())
  1479. dct = {}
  1480. for item in data:
  1481. item["today_income"] = "{}%".format(item["today_income"]*100)
  1482. dct[item["stock_date"]] = item["today_income"]
  1483. newdata = []
  1484. for i in range(1,int(eday)+1):
  1485. stock_date = month + "-" + str(i).zfill(2)
  1486. newdata.append({
  1487. "stock_date":stock_date,
  1488. "today_income":dct.get(stock_date,""),
  1489. })
  1490. return newdata
  1491. def get_all_match(request):
  1492. """
  1493. """
  1494. now = datetime.datetime.now().strftime("%Y-%m-%d")
  1495. #qset = cm.Match.objects.filter(start_time__lte=now).order_by("id")
  1496. qset = cm.Match.objects.filter(match_status__in=[3,4]).order_by("-id")
  1497. data = list(qset.values())
  1498. return data
  1499. def get_default_date(**kwargs):
  1500. """
  1501. """
  1502. match_id = kwargs.get("match_id")
  1503. if not match_id:
  1504. match_id = ccc.get_cur_match().id
  1505. record = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).order_by("-stock_date").first()
  1506. if record:
  1507. return record.stock_date
  1508. else:
  1509. return get_today_date()
  1510. @ccc.cache_data()
  1511. def get_stock_search(**kwargs):
  1512. """
  1513. """
  1514. qset = cm.Stock.objects.all()
  1515. data = list(qset.values("id","name","code"))
  1516. for item in data:
  1517. if item["code"]:
  1518. item["label"] = "%s(%s)" % (item["name"],item["code"])
  1519. else:
  1520. item["label"] = "%s" % item["name"]
  1521. return data
  1522. def get_mine_latest(request):
  1523. """
  1524. """
  1525. try:
  1526. user_id = request.user.get("id")
  1527. match_id = ccc.get_cur_match().id
  1528. player_id = request.player.id
  1529. match_id = request.player.match_id
  1530. match_group = request.player.match_group
  1531. today = get_today_date()
  1532. _today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1533. if _today:
  1534. today = _today
  1535. rst = get_today_record_actual(player_id,match_id,match_group)
  1536. if rst:
  1537. rst["today_income_fund"] = round((rst["today_fund"] - rst["yesterday_fund"])*10000,2) if rst["yesterday_fund"] else 0.00
  1538. rst["today_income"] = "{}%".format(rst["today_income"]*100)
  1539. rst["total_income"] = "{}%".format(rst["total_income"]*100)
  1540. rst["zan_count"] = rst.get("zans",0)
  1541. rst["comments_count"] = cm.Comments.objects.filter(record_id=rst.get("id",0)).count()
  1542. return rst
  1543. except Exception as e:
  1544. print(e)
  1545. return {"player_id":user_id,"match_id":match_id,"user_id":user_id}
  1546. @ccc.cache_data()
  1547. def get_match_validdates(match_id):
  1548. """
  1549. """
  1550. #qdata = request.json
  1551. #match_id = qdata.get("match_id")
  1552. match = cm.Match.objects.filter(id=match_id).first()
  1553. if match:
  1554. validdates = json.loads(match.valid_dates) if match.valid_dates else []
  1555. validdates.sort()
  1556. return validdates
  1557. return []
  1558. def send_phcode(request):
  1559. """
  1560. """
  1561. qdata = request.json
  1562. phone = qdata.get("phone")
  1563. import random
  1564. code = "%s%s%s%s" % (random.randint(0,9),random.randint(0,9),random.randint(0,9),random.randint(0,9))
  1565. send_verify_code(phone,code)
  1566. ccc.cache.set(phone,code,120)
  1567. pass
  1568. def get_signup_info(request):
  1569. """
  1570. """
  1571. qdata = request.json
  1572. user_id = request.user.get("id",0)
  1573. try:
  1574. match_id = ccc.get_signup_match().id
  1575. match = cm.Match.objects.filter(id=match_id).values().first()
  1576. #
  1577. match_groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).values())
  1578. match["groups"] = match_groups
  1579. #报名状态
  1580. now = datetime.datetime.now().strftime("%Y-%m-%d")
  1581. signup_start_time = match["signup_start_time"]
  1582. signup_end_time = match["signup_end_time"]
  1583. if signup_start_time <= now and signup_end_time >= now:
  1584. match["signup_status"] = 1
  1585. else:
  1586. match["signup_status"] = 0
  1587. if cm.Player.objects.filter(match_id=match_id,user_id=user_id,match_group__isnull=False).filter(role__in=[1,2]).exists():
  1588. match["signup_done"] = 1
  1589. else:
  1590. match["signup_done"] = 0
  1591. return match
  1592. except Exception as e:
  1593. print(e)
  1594. return {}
  1595. def do_wx_pay(request):
  1596. """
  1597. """
  1598. user = request.user
  1599. user_id = request.user.get("id",0)
  1600. user_name = request.user.get("username","")
  1601. openid = request.user.get("openid","")
  1602. qdata = request.json
  1603. match_id = qdata.get("match_id")
  1604. match_name = qdata.get("match_name")
  1605. signup_type = qdata.get("signup_type")
  1606. total_fee = str(qdata.get("total_fee"))
  1607. phone = qdata.get("phone")
  1608. phcode = qdata.get("phcode")
  1609. match_group = qdata.get("match_group")
  1610. print(qdata)
  1611. signup_name = qdata.get("signup_name")
  1612. if not signup_name:
  1613. signup_name = user_name
  1614. orgcode = ccc.cache.get(phone)
  1615. if not phone == "13883187629":
  1616. if not phcode == orgcode:
  1617. raise ce.TipException(u"验证码不正确!")
  1618. if int(signup_type) == 1:
  1619. if not match_group:
  1620. match_group = cm.MatchGroup.objects.filter(match_id=match_id,charge=0).first().id
  1621. out_trade_no = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
  1622. #游客和普通选手付费报名
  1623. #if user["player_type"] in [0,1] and not phone=="13883187629":
  1624. if user["player_type"] in [0,1]:
  1625. #生成订单
  1626. order = cm.SignupOrder.objects.create(
  1627. user_id = user_id,
  1628. user_name = signup_name,
  1629. match_id = match_id,
  1630. match_name = match_name,
  1631. signup_type = signup_type,
  1632. total_fee = total_fee,
  1633. out_trade_no = out_trade_no,
  1634. phone = phone,
  1635. match_group = match_group,
  1636. signup_name = signup_name
  1637. )
  1638. #支付
  1639. total_fee = str(int(float(order.total_fee)*100))
  1640. prepayinfo = wxpay.get_wx_unifiedorder(out_trade_no,total_fee,openid)
  1641. prepayinfo["key"] = wxpay.WxPayConf_pub.KEY
  1642. return prepayinfo
  1643. #种子选手和开户选手免费报名
  1644. else:
  1645. if signup_type == 1:
  1646. signup_name = user_name
  1647. #生成订单
  1648. order = cm.SignupOrder.objects.create(
  1649. user_id = user_id,
  1650. user_name = signup_name,
  1651. match_id = match_id,
  1652. match_name = match_name,
  1653. signup_type = signup_type,
  1654. total_fee = total_fee,
  1655. out_trade_no = out_trade_no,
  1656. phone = phone,
  1657. match_group = match_group,
  1658. signup_name = signup_name
  1659. )
  1660. user = cm.UserInfo.objects.filter(id=user_id).first()
  1661. #生成选手信息
  1662. cur_match = cm.Match.objects.filter(id=match_id).first()
  1663. visit_group = cm.MatchGroup.objects.filter(id=match_group).first()
  1664. player,flag = cm.Player.objects.get_or_create(
  1665. user_id = user.id,
  1666. match_id = cur_match.id
  1667. )
  1668. player.match_name = cur_match.name
  1669. player.match_group = visit_group.id
  1670. player.match_group_name = visit_group.name
  1671. player.username = signup_name
  1672. player.usercode = request.user.get("usercode")
  1673. player.role = 2
  1674. player.match_status = 1
  1675. player.save()
  1676. #
  1677. order.player_id = player.id
  1678. order.save()
  1679. user.username = signup_name
  1680. user.phone = phone
  1681. user.role = 2
  1682. user.save()
  1683. #发送报名成功信息
  1684. send_signup_success(phone,signup_name)
  1685. if phone == "13883187629":
  1686. for i in [5001,4762,5173,5141]:
  1687. cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=i)
  1688. return {"free":1}
  1689. def do_wxpay_notify(request):
  1690. qdata = request.json
  1691. flag,res = wxpay.check_notify_valid(request.body)
  1692. if flag:
  1693. out_trade_no = res.get("out_trade_no")
  1694. print(out_trade_no)
  1695. transaction_id = res.get("transaction_id")
  1696. pay_time = res.get("time_end")
  1697. try:
  1698. sorder = cm.SignupOrder.objects.filter(out_trade_no=out_trade_no).first()
  1699. if sorder and not sorder.transaction_id:
  1700. now = datetime.datetime.now()
  1701. sorder.order_status = 1
  1702. sorder.pay_status = 1
  1703. sorder.pay_time = now
  1704. sorder.transaction_id = transaction_id
  1705. sorder.save()
  1706. #生成选手信息
  1707. user = cm.UserInfo.objects.filter(id=sorder.user_id).first()
  1708. visit_group = cm.MatchGroup.objects.filter(id=sorder.match_group).first()
  1709. player,flag = cm.Player.objects.get_or_create(
  1710. user_id = sorder.user_id,
  1711. match_id = sorder.match_id
  1712. )
  1713. player.match_name = sorder.match_name
  1714. player.match_group = visit_group.id
  1715. player.match_group_name = visit_group.name
  1716. player.username = sorder.user_name
  1717. player.usercode = user.usercode if user else ""
  1718. if sorder.signup_type == 2:
  1719. player.role = 2
  1720. else:
  1721. player.role = 1
  1722. #
  1723. sorder.player_id = player.id
  1724. sorder.save()
  1725. player.save()
  1726. if sorder.signup_type == 2:
  1727. player_id = sorder.player_id
  1728. user_id = sorder.user_id
  1729. match_group = sorder.match_group
  1730. match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name
  1731. 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)
  1732. cm.UserInfo.objects.filter(id=user_id).update(role=2,phone=sorder.phone,username=sorder.user_name)
  1733. if sorder.signup_type == 1:
  1734. player_id = sorder.player_id
  1735. user_id = sorder.user_id
  1736. cm.Player.objects.filter(id=player_id).update(role=1,match_status=1)
  1737. cm.UserInfo.objects.filter(id=user_id).update(role=1,phone=sorder.phone,username=sorder.user_name)
  1738. #发送报名成功信息
  1739. send_signup_success(sorder.phone,sorder.signup_name)
  1740. return True
  1741. except Exception as e:
  1742. import traceback
  1743. traceback.print_exc()
  1744. print(e,111111111111)
  1745. return False
  1746. def get_user_comments(request):
  1747. """
  1748. """
  1749. kwargs = request.json
  1750. stock_id = kwargs.get("stock_id")
  1751. record_id = kwargs.get("record_id")
  1752. if record_id:
  1753. qset = cm.Comments.objects.filter(record_id=record_id,pid__isnull=True).order_by(*["-istop","-id"])
  1754. else:
  1755. qset = cm.Comments.objects.filter(stock_id=stock_id,pid__isnull=True).order_by(*["-istop","-id"])
  1756. data = list(qset.values())
  1757. for item in data:
  1758. if record_id:
  1759. subcomments = cm.Comments.objects.filter(record_id=record_id,pid=item["id"])
  1760. else:
  1761. subcomments = cm.Comments.objects.filter(stock_id=stock_id,pid=item["id"])
  1762. item["children"] = list(subcomments.values())
  1763. #分页
  1764. page = int(kwargs.get("page",1))
  1765. page_size = int(kwargs.get("page_size",20))
  1766. if page and page_size:
  1767. total,data = ccf.get_page_list(data,page,page_size)
  1768. else:
  1769. total = len(data)
  1770. return total,data
  1771. def get_user_choices(request):
  1772. """
  1773. """
  1774. user_id = request.user.get("id",0)
  1775. #match_id = request.player.match_id
  1776. kwargs = request.json
  1777. stock_id = kwargs.get("stock_id")
  1778. if stock_id:
  1779. qset = cm.UserChoice.objects.filter(stock_id=stock_id)
  1780. else:
  1781. qset = cm.UserChoice.objects.filter(user_id=user_id)
  1782. data = list(qset.values())
  1783. for item in data:
  1784. stock_id = item["stock_id"]
  1785. comments_count = ccc.cache.get("%s_comments" % stock_id)
  1786. choice_count = ccc.cache.get("%s_choices" % stock_id)
  1787. comments_count = comments_count if comments_count else 0
  1788. choice_count = choice_count if choice_count else 0
  1789. item["count"] = choice_count
  1790. item["comments_count"] = comments_count
  1791. item["choice_count"] = choice_count
  1792. #item["match_id"] = match_id
  1793. #分页
  1794. page = int(kwargs.get("page",1))
  1795. page_size = int(kwargs.get("page_size",20))
  1796. if page and page_size:
  1797. total,data = ccf.get_page_list(data,page,page_size)
  1798. else:
  1799. total = len(data)
  1800. return total,data
  1801. def get_user_consult_list(request):
  1802. """
  1803. """
  1804. player_id = request.user.get("id") if request.user else 0
  1805. if not player_id:
  1806. return 0,[]
  1807. kwargs = request.json
  1808. record_id = kwargs.get("record_id")
  1809. qset = cm.WanzhuConsult.objects.filter(user_id=player_id)
  1810. data = list(qset.values())
  1811. for item in data:
  1812. if cm.WanzhuConsult.objects.filter(pid=item["id"]):
  1813. data.extend(cm.WanzhuConsult.objects.filter(Q(pid=item["id"])|Q(reply_user_id=player_id)).values())
  1814. data = sorted(data,key=lambda x:x["id"])
  1815. #分页
  1816. page = int(kwargs.get("page",1))
  1817. page_size = int(kwargs.get("page_size",1000))
  1818. if page and page_size:
  1819. total,data = ccf.get_page_list(data,page,page_size)
  1820. else:
  1821. total = len(data)
  1822. return total,data
  1823. def get_user_zans(request):
  1824. """
  1825. """
  1826. qdata = request.json
  1827. record_id = qdata.get("record_id")
  1828. match_id = qdata.get("match_id")
  1829. zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
  1830. return zans
  1831. def get_user_comments_count(request):
  1832. """
  1833. """
  1834. qdata = request.json
  1835. record_id = qdata.get("record_id")
  1836. count = cm.Comments.objects.filter(record_id=record_id).count()
  1837. return count
  1838. def add_wanzhu_consult(request):
  1839. """咨询顽主
  1840. """
  1841. user_id = request.user.get("id",0)
  1842. user_name = request.user.get("username")
  1843. user_avatar = request.user.get("avatar")
  1844. openid = request.user.get("openid")
  1845. qdata = request.json
  1846. content = qdata.get("cotent")
  1847. pid = qdata.get("pid")
  1848. obj = cm.WanzhuConsult.objects.create(
  1849. user_id = user_id,
  1850. user_name = user_name,
  1851. user_avatar = user_avatar,
  1852. content = content,
  1853. pid = pid
  1854. )
  1855. obj,flag = cm.Consult.objects.get_or_create(
  1856. user_id = user_id,
  1857. )
  1858. obj.user_name = user_name
  1859. obj.user_avatar = user_avatar
  1860. obj.content = content
  1861. obj.view_status = 0
  1862. obj.reply_status = 0
  1863. obj.ctime = datetime.datetime.now()
  1864. obj.save()
  1865. #自动回复
  1866. if cm.WanzhuConsult.objects.filter(user_id=user_id).count() <=1:
  1867. content = u"您好,后台消息一般三小时内回复,如果超出时间请加微信destination8888"
  1868. cm.WanzhuConsult.objects.create(
  1869. pid = pid,
  1870. reply_content = content,
  1871. user_id = 0,
  1872. player_id = 0,
  1873. reply_user_id = user_id
  1874. )
  1875. #发送消息提醒
  1876. if cm.UserInfo.objects.filter(id=user_id).exists():
  1877. user = cm.UserInfo.objects.filter(id=user_id).first()
  1878. send_consult_reply_message(openid,user_name)
  1879. def add_comments(request):
  1880. """
  1881. """
  1882. #if request.user.comment_status == 0:
  1883. # raise ce.TipException(u"对不起,暂无法评论/留言!")
  1884. user_id = request.user.get("id")
  1885. user_name = request.user.get("username")
  1886. user_avatar = request.user.get("avatar")
  1887. qdata = request.json
  1888. content = qdata.get("cotent")
  1889. record_id = qdata.get("record_id")
  1890. stock_id = qdata.get("stock_id")
  1891. pid = qdata.get("pid")
  1892. match_id = qdata.get("match_id")
  1893. ip = ccf.get_ip(request)
  1894. location = ccf.get_city_from_ip(ip)
  1895. obj = cm.Comments.objects.create(
  1896. user_id = user_id,
  1897. user_name = user_name,
  1898. user_avatar = user_avatar,
  1899. content = content,
  1900. record_id = record_id,
  1901. pid = pid,
  1902. ip = ip,
  1903. location = location,
  1904. stock_id = stock_id
  1905. )
  1906. if record_id:
  1907. cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(comments_count=F("comments_count")+1)
  1908. if stock_id:
  1909. ccc.cache.incr("%s_comments" % stock_id,1)
  1910. def add_choice(request):
  1911. """
  1912. """
  1913. user_id = request.user.get("id")
  1914. user_name = request.user.get("username")
  1915. user_avatar = request.user.get("avatar")
  1916. qdata = request.json
  1917. stock_id = qdata.get("stock_id")
  1918. stock_name = cm.Stock.objects.filter(id=stock_id).first().name
  1919. obj = cm.UserChoice.objects.create(
  1920. user_id = user_id,
  1921. user_name = user_name,
  1922. user_avatar = user_avatar,
  1923. stock_id = stock_id,
  1924. stock_name = stock_name
  1925. )
  1926. if stock_id:
  1927. ccc.cache.incr("%s_choices" % stock_id,1)
  1928. def add_zan(request):
  1929. """
  1930. """
  1931. qdata = request.json
  1932. record_id = qdata.get("record_id")
  1933. match_id = qdata.get("match_id")
  1934. cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(zans=F("zans")+1)
  1935. zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
  1936. return zans
  1937. def get_experience_list(request):
  1938. """
  1939. """
  1940. #return 0,[]
  1941. kwargs = request.json
  1942. today = get_today_date()
  1943. match_id = ccc.get_cur_match().id
  1944. match_group = kwargs.get("match_group")
  1945. #冠军组、千万组、百万组
  1946. grpset = cm.MatchGroup.objects.filter(match_id=match_id).filter(Q(name__icontains=u"千万组")|Q(name__icontains=u"百万组")|Q(name__icontains=u"冠军组"))
  1947. if match_group:
  1948. grpset = grpset.filter(id=match_group)
  1949. qbw_ids = list(grpset.values_list("id",flat=True))
  1950. 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")
  1951. 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"))
  1952. for item in data:
  1953. record_id = item["id"]
  1954. user_id = item["user_id"]
  1955. try:
  1956. item["user_avatar"] = get_user_info(user_id)["avatar"]
  1957. except:
  1958. item["user_avatar"] = ""
  1959. item["zans_count"] = item["zans"]
  1960. item["today_stock_img"] = json.loads(item["today_stock_img"])
  1961. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
  1962. if win_rate:
  1963. item["win_rate"] = str(float(win_rate)*100)+"%"
  1964. else:
  1965. item["win_rate"] = "0.0%"
  1966. item["today_income"] = "{}%".format(item["today_income"]*100)
  1967. item["total_income"] = "{}%".format(item["total_income"]*100)
  1968. #分页
  1969. page = int(kwargs.get("page",1))
  1970. page_size = int(kwargs.get("page_size",20))
  1971. if page and page_size:
  1972. total,data = ccf.get_page_list(data,page,page_size)
  1973. else:
  1974. total = len(data)
  1975. return total,data
  1976. def delete_choice(request):
  1977. """
  1978. """
  1979. user_id = request.user.get("id")
  1980. user_name = request.user.get("username")
  1981. user_avatar = request.user.get("avatar")
  1982. qdata = request.json
  1983. stock_id = qdata.get("stock_id")
  1984. cm.UserChoice.objects.filter(stock_id=stock_id,user_id=user_id).delete()
  1985. if ccc.cache.get("%s_choices" % stock_id) and int(ccc.cache.get("%s_choices" % stock_id)) >= 1:
  1986. ccc.cache.decr("%s_choices" % stock_id)
  1987. def delete_comments(request):
  1988. """
  1989. """
  1990. qdata = request.json
  1991. id = qdata.get("id")
  1992. if cm.Comments.objects.filter(id=id,stock_id__isnull=False).exists():
  1993. stock_id = cm.Comments.objects.filter(id=id).first().stock_id
  1994. if ccc.cache.get("%s_comments" % stock_id) and int(ccc.cache.get("%s_comments" % stock_id)) >= 1:
  1995. ccc.cache.decr("%s_comments" % stock_id)
  1996. cm.Comments.objects.filter(id=id).delete()
  1997. def modify_user_fund(request):
  1998. """
  1999. """
  2000. user_id = request.user.get("id")
  2001. #player = request.player
  2002. match_id = ccc.get_cur_match().id
  2003. player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
  2004. player_id = player.id
  2005. match_id = player.match_id
  2006. qdata = request.json
  2007. fundin = qdata.get("in_fund")
  2008. fundout = qdata.get("out_fund")
  2009. fundin = float(fundin) if fundin else 0.0
  2010. fundout = float(fundout) if fundout else 0.0
  2011. account_img = qdata.get("account_img")
  2012. init_fund = player.fund
  2013. trycalc = qdata.get("trycalc")
  2014. today_fund = qdata.get("today_fund")
  2015. today_fund = float(today_fund) if today_fund else 0.0
  2016. if trycalc:
  2017. stock_date = get_today_date()
  2018. validdates = get_match_validdates(match_id)
  2019. today_index = validdates.index(stock_date)
  2020. yesterday_index = today_index -1 if today_index >=1 else 0
  2021. yesterday_date = validdates[yesterday_index]
  2022. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  2023. match_id=match_id,player_id=player_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
  2024. if yesterday:
  2025. yesterday_fund = yesterday.today_fund
  2026. yesterday_stock = yesterday.today_stock
  2027. yesterday_stock_img = yesterday.today_stock_img
  2028. yesterday_is_markt = yesterday.is_markt
  2029. else:
  2030. yesterday_fund = today_fund
  2031. yesterday_stock = ""
  2032. yesterday_stock_img = ""
  2033. yesterday_is_markt = 0
  2034. #入资金
  2035. if fundin > fundout:
  2036. fundin = fundin - fundout
  2037. today_income = round((today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin),4)
  2038. total_income = round((today_fund-init_fund-fundin)/(init_fund+fundin),4)
  2039. init_fund = init_fund + fundin
  2040. yesterday_fund = yesterday_fund + fundin
  2041. #出资金
  2042. else:
  2043. fundout = fundout - fundin
  2044. today_income = round((today_fund-(yesterday_fund-fundout))/float(yesterday_fund),4)
  2045. total_income = round((today_fund+fundout-init_fund)/init_fund,4)
  2046. init_fund = round(today_fund/(1+total_income),4)
  2047. yesterday_fund = round(today_fund/(1+today_income),4)
  2048. today_income = "{}%".format(today_income*100)
  2049. total_income = "{}%".format(total_income*100)
  2050. return {"yesterday_fund":yesterday_fund,
  2051. "today_fund":today_fund,
  2052. "today_income":today_income,
  2053. "total_income":total_income,
  2054. "init_fund":init_fund}
  2055. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  2056. if cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).exists():
  2057. raise ce.TipException(u"资金出入须在提交作业之前提交,今日作业已提交,不能提交资金出入!")
  2058. if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists():
  2059. raise ce.TipException(u"今日已有资金出入,一天只能提交一次资金出入!")
  2060. fundinout,flag = cm.FundInOut.objects.get_or_create(
  2061. user_id = user_id,
  2062. fundin = fundin,
  2063. fundout = fundout,
  2064. stock_date = stock_date,
  2065. account_img = account_img
  2066. )
  2067. def get_user_match_list(request):
  2068. kwargs = request.json
  2069. user_id = kwargs.get("user_id")
  2070. if not user_id:
  2071. user_id = request.user.get("id")
  2072. qset = cm.Player.objects.filter(user_id=user_id).order_by("-id")
  2073. qset = qset.values("user_id","match_id","match_group").annotate(cnt=Count("match_id"))
  2074. page = int(kwargs.get("page",0))
  2075. page_size = int(kwargs.get("page_size",20))
  2076. if page and page_size:
  2077. total,qset = ccc.get_page_qset(qset,page,page_size)
  2078. else:
  2079. total = qset.count()
  2080. today = get_today_date(user_id=user_id)
  2081. data = list(qset.values("user_id","match_id","match_group"))
  2082. for item in data:
  2083. match_id = item["match_id"]
  2084. match_group = item["match_group"]
  2085. user_id = item["user_id"]
  2086. item["match_info"] = get_match_info(match_id)
  2087. item["match_group_info"] = get_group_info(match_group)
  2088. today_record = ccc.get_today_record(user_id,int(match_id),int(match_group),today)
  2089. today_record = format_today_record(today_record)
  2090. if today_record.get("today_income"):
  2091. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  2092. if today_record.get("total_income"):
  2093. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  2094. item["today_record"] = today_record
  2095. return total,data
  2096. def get_format_user_info(request):
  2097. user_id = request.user.get("id")
  2098. cur_user_id = request.user.get("id")
  2099. kwargs = request.json
  2100. q_user_id = kwargs.get("user_id")
  2101. if q_user_id:
  2102. user_id = q_user_id
  2103. userinfo = get_user_info(q_user_id)
  2104. userinfo["fans"] = cm.UserFollows.objects.filter(follow_id=user_id).count()
  2105. userinfo["followers"] = cm.UserFollows.objects.filter(user_id=user_id).count()
  2106. del userinfo["phone"]
  2107. if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists():
  2108. userinfo["is_follow"] = 1
  2109. else:
  2110. userinfo["is_follow"] = 0
  2111. return userinfo
  2112. def get_day_inout_rank_list(request):
  2113. """
  2114. """
  2115. kwargs = request.json
  2116. stock_date = kwargs.get("stock_date")
  2117. match_id = kwargs.get("match_id")
  2118. _type = kwargs.get("type")
  2119. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date)
  2120. if _type == "in":
  2121. qset = qset.order_by("-today_income")
  2122. else:
  2123. qset = qset.order_by("today_income")
  2124. page = int(kwargs.get("page",0))
  2125. page_size = int(kwargs.get("page_size",20))
  2126. if page and page_size:
  2127. total,qset = ccc.get_page_qset(qset,page,page_size)
  2128. else:
  2129. total = qset.count()
  2130. data = list(qset.values())
  2131. return total,data