controls.py 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200
  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 common.constant as const
  18. import account.password_handle as ph
  19. from utils.exceltool import ExcelTool
  20. from utils.jgpush import send_notification_by_registration_ids
  21. import wzhifuSDK as wxpay
  22. from utils.exceltool import ExcelTool
  23. from utils.qrcodetool import gen_general_qrcode
  24. from django.db.models import Q,Sum,Count,F
  25. from PIL import Image
  26. from PIL import Image,ImageDraw,ImageFont
  27. from django.db import transaction
  28. from threading import Thread
  29. #from django.core.cache import cache
  30. from django.db import connection
  31. import calendar
  32. import xlrd
  33. import xlwt
  34. # from xlutils.copy import copy
  35. import copy
  36. from xltpl.writer import BookWriter
  37. from django_redis import get_redis_connection
  38. from constants import *
  39. from utils.aliyun_sms import send_verify_code,send_signup_success
  40. from utils.wxSubscribeMessage import send_consult_reply_message
  41. from utils.aliyunpush import aliyunpush
  42. from utils.wxpay.pay import WechatPayDAL
  43. #import logging
  44. #log = logging.getLogger("myerror")
  45. def async(f):
  46. def wrapper(*args, **kwargs):
  47. thr = Thread(target=f, args=args, kwargs=kwargs)
  48. thr.start()
  49. return wrapper
  50. def get_today_date(match_id=None,user_id=None):
  51. if not match_id:
  52. match_id = ccc.get_cur_match().id
  53. #if datetime.datetime.now().strftime("%H:%M") < "15:00":
  54. # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES:
  55. # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
  56. # else:
  57. # if datetime.datetime.now().weekday()==0:
  58. # today = (datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d")
  59. # else:
  60. # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  61. #else:
  62. # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES:
  63. # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
  64. # else:
  65. # today = datetime.datetime.now().strftime("%Y-%m-%d")
  66. try:
  67. if user_id:
  68. today = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id).order_by("-stock_date").first().stock_date
  69. else:
  70. today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
  71. except:
  72. today = datetime.datetime.now().strftime("%Y-%m-%d")
  73. return today
  74. #@async
  75. def update_group_rank(match_id,match_group,stock_date):
  76. #return
  77. 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")
  78. records = prset.values()
  79. case_id = " case id "
  80. cases = []
  81. where = []
  82. for index,pr in enumerate(prset):
  83. key = "%s_%s_%s_%s" % (pr.player_id,match_id,match_group,stock_date)
  84. record = records[index]
  85. record.update({"group_rank":index+1})
  86. ccc.cache.delete(key)
  87. ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder))
  88. ccc.pl.execute()
  89. #@ccc.cache_data()
  90. def get_notices():
  91. """
  92. """
  93. notices = list(cm.Article.objects.filter(status=2,type="notice").values())
  94. return notices
  95. def get_index_data(request):
  96. """首页数据
  97. """
  98. player = request.player
  99. if not player:
  100. raise ce.TipException(u"该账号未参加任何赛事!")
  101. player_id = player.id
  102. match_id = player.match_id
  103. match_group = player.match_group
  104. #if datetime.datetime.now().hour < 15:
  105. # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  106. #else:
  107. # today = datetime.datetime.now().strftime("%Y-%m-%d")
  108. today = get_today_date()
  109. match_name = get_match_info(match_id).get("name")
  110. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(player_id=player_id,match_id=match_id)
  111. if records_set:
  112. try:
  113. cur_rank = get_today_record(player_id,match_id,match_group,today).get("group_rank","")
  114. records = list(records_set.order_by("-stock_date").values())
  115. except:
  116. cur_rank = 0
  117. records = []
  118. else:
  119. cur_rank = 0
  120. records = []
  121. for item in records:
  122. today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
  123. today_stock = filter(lambda x:x["name"],today_stock)
  124. item["today_stock"] = today_stock
  125. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
  126. yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
  127. yesterday_stock = filter(lambda x:x["name"],yesterday_stock)
  128. item["yesterday_stock"] = yesterday_stock
  129. item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
  130. item["today_income"] = "{}%".format(item["today_income"]*100)
  131. item["total_income"] = "{}%".format(item["total_income"]*100)
  132. #通知
  133. notices = get_notices()
  134. ret = {"match_name":match_name,"cur_rank":cur_rank,"records":records,"notices":notices}
  135. return ret
  136. def get_player_match_list(request):
  137. """选手参赛列表数据
  138. """
  139. uid = request.user.get("id",0)
  140. now_str = datetime.datetime.now().strftime("%Y-%m-%d")
  141. cur_match_id = ccc.get_cur_match().id
  142. match_ids = list(cm.Player.objects.filter(user_id=uid).values_list("match_id",flat=True))
  143. matchs = list(cm.Match.objects.filter(id__in=match_ids).values())
  144. for item in matchs:
  145. player = cm.Player.objects.filter(user_id=uid,match_id=item["id"]).first()
  146. item["player_id"] = player.id if player else 0
  147. return matchs
  148. def get_group_income(match_id,match_group):
  149. """
  150. """
  151. data = []
  152. today = datetime.datetime.now().strftime("%Y-%m-%d")
  153. player_ids = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values_list("id",flat=True))
  154. for player_id in player_ids:
  155. 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()
  156. if today_record:
  157. data.append(today_record.total_income)
  158. data = list(set(data))
  159. data = sorted(data,key=lambda x:x,reverse=True)
  160. return data
  161. def get_player_match_detail(request):
  162. """选手参赛详情数据
  163. """
  164. qdata = request.json
  165. user_id = request.user.get("id",0)
  166. match_id = qdata.get("id")
  167. record_id = qdata.get("record_id")
  168. userinfo = {}
  169. cur_user_id = user_id
  170. if qdata.get("user_id"):
  171. cur_user_id = qdata.get("user_id")
  172. today = get_today_date()
  173. ismine = True if int(cur_user_id) == user_id else False
  174. if not match_id:
  175. player = cm.Player.objects.filter(user_id=cur_user_id,match_id=match_id).first()
  176. match_id =player.match_id
  177. cur_user_id = player.user_id
  178. if record_id:
  179. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id)
  180. if records_set:
  181. match_id = records_set.first().match_id
  182. else:
  183. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("-stock_date")
  184. match = cm.Match.objects.filter(id=match_id).values().first()
  185. groups = list(cm.MatchGroup.objects.filter(match_id=match_id).values_list("name",flat=True))
  186. match["groups"] = groups
  187. all_records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("-stock_date")
  188. if all_records_set:
  189. records = list(all_records_set.values())
  190. else:
  191. records = []
  192. for item in records:
  193. item["today_stock"] = json.loads(item["today_stock"]) if item["today_stock"] else []
  194. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
  195. item["yesterday_stock"] = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
  196. item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
  197. item["today_income"] = "{}%".format(item["today_income"]*100)
  198. item["total_income"] = "{}%".format(item["total_income"]*100)
  199. item["avatar"] = get_user_info(item["user_id"])["avatar"]
  200. today_record = {}
  201. if records_set:
  202. today = records_set.first().stock_date
  203. if record_id:
  204. today_record = records_set.values().first()
  205. today_record = format_today_record(today_record)
  206. else:
  207. match_group = records_set.first().match_group
  208. today_record = ccc.get_today_record(cur_user_id,int(match_id),match_group,today)
  209. if today_record:
  210. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  211. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  212. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  213. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  214. today_record["match_group_name"] = cm.MatchGroup.objects.filter(id=today_record["match_group"]).first().name
  215. today_record["players_num"] = cm.Player.objects.filter(match_group=today_record["match_group"]).count()
  216. today_record["win_rate"] = calc_win_rate(cur_user_id,today_record["match_id"])
  217. badest = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("today_income").first()
  218. if badest:
  219. today_record["badest_income"] = "{}%".format(badest.today_income*100)
  220. today_record["today_stock_total"] = round(today_record.get("today_stock_total",0.0),4)
  221. userinfo = get_user_info(today_record["user_id"])
  222. today_record["style"] = userinfo.get("style")
  223. else:
  224. player_info = get_user_info(cur_user_id)
  225. today_record = {}
  226. today_record["stock_date"] = today
  227. today_record.update(player_info)
  228. today_record["player_id"] = player_info["id"]
  229. today_record["avatar"] = get_user_info(cur_user_id)["avatar"]
  230. userinfo = get_user_info(cur_user_id)
  231. today_record["style"] = userinfo.get("style")
  232. today_record["user_id"] = player_info["id"]
  233. match["groups"] = [today_record.get("match_group_name","")] if today_record else []
  234. records = sorted(records,key=lambda x:x["stock_date"],reverse=True)
  235. if cm.UserFollows.objects.filter(user_id=request.user.get("id"),follow_id=cur_user_id).exists():
  236. is_follow = 1
  237. else:
  238. is_follow = 0
  239. if today_record and today_record.get("today_fund"):
  240. today_record["today_income_fund"] = round((today_record["today_fund"] - today_record["yesterday_fund"])*10000,2) if today_record["yesterday_fund"] else 0.00
  241. today_record["zan_count"] = today_record.get("zans",0)
  242. ret = {
  243. "match":match,
  244. "today_record":today_record,
  245. "match_group_info":get_group_info(today_record.get("match_group")) if today_record.get("match_group") else {},
  246. "userinfo":get_user_info(cur_user_id),
  247. "records":records,
  248. "is_follow":is_follow,
  249. "fans":cm.UserFollows.objects.filter(follow_id=cur_user_id).count(),
  250. "followers":cm.UserFollows.objects.filter(user_id=cur_user_id).count(),
  251. "stock_age":datetime.datetime.now().year - int(userinfo.get("join_time")) if userinfo.get("join_time") else 0,
  252. "stock_follow":list(cm.UserChoice.objects.filter(user_id=cur_user_id).values_list("stock_name",flat=True))
  253. }
  254. return ret
  255. def get_today_record(player_id,match_id,match_group,today):
  256. """
  257. """
  258. key = "%s_%s_%s_%s" % (player_id,match_id,match_group,today)
  259. #key = "%s_%s_%s" % (player_id,match_id,today)
  260. today_record = ccc.cache.get(key)
  261. today_record = json.loads(today_record) if today_record else {}
  262. #if match_id:
  263. # #记得这里上线后要注释掉
  264. # today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=player_id,match_id=match_id,stock_date=today)
  265. # today_record = today_record.values().first()
  266. try:
  267. if today_record:
  268. user_info = get_user_info(today_record["user_id"])
  269. if user_info:
  270. user_info.pop("id")
  271. today_record.update(user_info)
  272. #仓位
  273. today_stock_total = 0
  274. today_stock = json.loads(today_record["today_stock"])
  275. for ts in today_stock:
  276. if ts["fund"]:
  277. try:
  278. today_stock_total += float(ts["fund"])
  279. except Exception as e:
  280. print e
  281. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  282. today_record["today_stock_total"] = today_stock_total
  283. except Exception as e:
  284. import traceback
  285. traceback.print_exc()
  286. return today_record
  287. def format_today_record(today_record):
  288. try:
  289. if today_record:
  290. user_info = get_user_info(today_record["user_id"])
  291. if user_info:
  292. #user_info.pop("id")
  293. today_record.update(user_info)
  294. #仓位
  295. today_stock_total = 0
  296. today_stock = json.loads(today_record["today_stock"])
  297. for ts in today_stock:
  298. if ts["fund"]:
  299. try:
  300. today_stock_total += float(ts["fund"])
  301. except Exception as e:
  302. print e
  303. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  304. today_record["today_stock_total"] = today_stock_total
  305. # win_rate = ccc.cache.hget("PLAYER_LATEST_%d" % today_record["user_id"],"win_rate")
  306. # if win_rate:
  307. # today_record["win_rate"] = str(float(win_rate)*100)+"%"
  308. # else:
  309. # today_record["win_rate"] = "0.0%"
  310. win_rate = calc_win_rate(today_record["user_id"],today_record["match_id"])
  311. today_record["win_rate"] = win_rate
  312. except Exception as e:
  313. import traceback
  314. traceback.print_exc()
  315. today_record = today_record if today_record else {}
  316. return today_record
  317. def get_today_record_actual(player_id,match_id,match_group,today=None):
  318. """
  319. """
  320. if today:
  321. 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)
  322. else:
  323. 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")
  324. today_record = qset.values().first()
  325. if today_record:
  326. user_info = get_user_info(today_record["user_id"])
  327. if user_info:
  328. user_info.pop("id")
  329. today_record.update(user_info)
  330. #仓位
  331. today_stock_total = 0
  332. today_stock = json.loads(today_record["today_stock"])
  333. for ts in today_stock:
  334. if ts["fund"]:
  335. try:
  336. today_stock_total += float(ts["fund"])
  337. except Exception as e:
  338. print e
  339. today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
  340. today_record["today_stock_total"] = today_stock_total
  341. return today_record
  342. @ccc.cache_data()
  343. def get_match_group_players(match_id,match_group):
  344. players = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values())
  345. return players
  346. #@ccc.cache_data()
  347. def get_match_group_users(match_id,match_group):
  348. #users = list(cm.UserMatch.objects.filter(match_id=match_id,match_group=match_group).values())
  349. users = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values())
  350. return users
  351. #@ccc.cache_data()
  352. def get_match_groups(match_id):
  353. """
  354. """
  355. match = cm.Match.objects.filter(id=match_id).values().first()
  356. groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).order_by("-order").values())
  357. return match,groups
  358. def get_cache_rank_list(match_id,today):
  359. """
  360. """
  361. match,groups = get_match_groups(match_id)
  362. data = []
  363. for item in groups:
  364. new_players = []
  365. players = get_match_group_users(match_id,item["id"])
  366. win_count = 0
  367. loss_count = 0
  368. for player in players:
  369. user_id = player["user_id"]
  370. #username = player["signup_name"]
  371. username = player["username"]
  372. match_group = player["match_group"]
  373. today_record = ccc.get_today_record(user_id,match_id,match_group,today)
  374. if today_record:
  375. player.update(today_record)
  376. player["username"] = username
  377. player["org_today_income"] = player["today_income"]
  378. player["org_total_income"] = player["total_income"]
  379. player["total_income"] = "{}%".format(today_record["total_income"]*100)
  380. player["today_income"] = "{}%".format(today_record["today_income"]*100)
  381. if player["org_today_income"] >= 0.05:
  382. win_count += 1
  383. if player["org_today_income"] <= -0.05:
  384. loss_count += 1
  385. try:
  386. player["fund"] = round(player["fund"],4) if player["fund"] else 0.0
  387. player["init_fund"] = round(player["init_fund"],4)
  388. player["fund"] = round(player["init_fund"],4)
  389. player["today_fund"] = round(player["today_fund"],4)
  390. new_players.append(player)
  391. except Exception as e:
  392. print player
  393. pass
  394. new_players_sort = list(sorted(new_players,key=lambda x:x["org_total_income"],reverse=True))
  395. item["players_num"] = len(players)
  396. item["win_count"] = win_count
  397. item["loss_count"] = loss_count
  398. item["players"] = new_players_sort[:3]
  399. data.append(item)
  400. return match,data
  401. def get_rank_list(request):
  402. """排名列表
  403. """
  404. qdata = request.json
  405. user_id = request.user.get("id",0)
  406. match_id = qdata.get("match_id")
  407. today = qdata.get("stock_date")
  408. if not today:
  409. today = get_today_date()
  410. match,groups = get_cache_rank_list(match_id,today)
  411. ret = {"match":match,"groups":groups}
  412. return ret
  413. @ccc.cache_data()
  414. def get_user_info(uid):
  415. user = cm.UserInfo.objects.filter(id=uid).values().first()
  416. if user:
  417. user["style"] = []
  418. if user["zq"]:
  419. user["style"].append(user["zq"])
  420. if user["cw"]:
  421. user["style"].append(user["cw"])
  422. if user["df"]:
  423. user["style"].append(user["df"])
  424. return user
  425. def get_user_info_actual(uid):
  426. user = cm.UserInfo.objects.filter(id=uid).values().first()
  427. if user:
  428. user["style"] = []
  429. if user["zq"]:
  430. user["style"].append(user["zq"])
  431. if user["cw"]:
  432. user["style"].append(user["cw"])
  433. if user["df"]:
  434. user["style"].append(user["df"])
  435. return user
  436. #@ccc.cache_data()
  437. def get_player_info(player_id):
  438. player = cm.Player.objects.filter(id=player_id).values().first()
  439. return player
  440. @ccc.cache_data()
  441. def get_match_info(match_id):
  442. match = cm.Match.objects.filter(id=match_id).values().first()
  443. return match
  444. @ccc.cache_data()
  445. def get_group_info(group_id):
  446. group = cm.MatchGroup.objects.filter(id=group_id).values().first()
  447. if group:
  448. group["players_num"] = cm.Player.objects.filter(match_group=group["id"]).count()
  449. return group
  450. else:
  451. return {}
  452. def get_group_rank_list(request):
  453. """排名列表
  454. """
  455. qdata = request.json
  456. kwargs = qdata
  457. group_id = qdata.get("id")
  458. match_id = qdata.get("match_id")
  459. match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id
  460. today = qdata.get("stock_date")
  461. if not today:
  462. today = get_today_date()
  463. match = get_match_info(match_id)
  464. group = get_group_info(group_id)
  465. players = get_match_group_users(match_id,group_id)
  466. new_players = []
  467. for player in players:
  468. user_id = player["user_id"]
  469. #user = get_user_info(user_id)
  470. #username = user["username"] if user else ""
  471. #username = player["signup_name"]
  472. username = player["username"]
  473. match_group = group_id
  474. today_record = ccc.get_today_record(user_id,match_id,match_group,today)
  475. if today_record:
  476. player.update(today_record)
  477. player["username"] = username
  478. player["org_today_income"] = player["today_income"]
  479. player["org_total_income"] = player["total_income"]
  480. player["total_income"] = "{}%".format(player["total_income"]*100)
  481. player["today_income"] = "{}%".format(player["today_income"]*100)
  482. player["fund"] = round(player["fund"],4)
  483. player["init_fund"] = round(player["init_fund"],4)
  484. player["today_fund"] = round(player["today_fund"],4)
  485. new_players.append(player)
  486. if kwargs.get("order_by") == "today_income__asc":
  487. new_players = sorted(new_players,key=lambda x:x["org_today_income"])
  488. elif kwargs.get("order_by") == "today_income__desc" :
  489. new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True)
  490. elif kwargs.get("order_by") == "total_income__asc":
  491. new_players = sorted(new_players,key=lambda x:x["org_total_income"])
  492. elif kwargs.get("order_by") == "total_income__desc":
  493. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  494. else:
  495. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  496. #分页
  497. page = int(kwargs.get("page",0))
  498. page_size = int(kwargs.get("page_size",50))
  499. #page_size = 50
  500. if page and page_size:
  501. total,new_players = ccf.get_page_list(new_players,page,page_size)
  502. else:
  503. total = len(new_players)
  504. #应到、实到、请假人数
  505. total_person = cm.Player.objects.filter(match_group=group_id,match_status=1).count()
  506. actual_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today).count()
  507. leave_person = total_person - actual_person
  508. win_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__gte=0).count()
  509. loss_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__lt=0).count()
  510. ret = {"group":group,"players":new_players,"total":total,"total_person":total_person,
  511. "actual_person":actual_person,"leave_person":leave_person,"win_person":win_person,"loss_person":loss_person}
  512. return ret
  513. def get_player_match_records(request):
  514. """选手参赛每日持股
  515. """
  516. qdata = request.json
  517. match_id = qdata.get("id")
  518. user_id = qdata.get("user_id")
  519. page = int(qdata.get("page",0))
  520. page_size = int(qdata.get("page_size",20))
  521. records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).order_by("-stock_date")
  522. data = list(records_set.values())
  523. for item in data:
  524. today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
  525. today_stock = filter(lambda x:x["name"],today_stock if today_stock else [])
  526. item["today_stock"] = today_stock
  527. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
  528. yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
  529. yesterday_stock = filter(lambda x:x["name"],yesterday_stock if yesterday_stock else [])
  530. item["yesterday_stock"] = yesterday_stock
  531. item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
  532. item["today_income"] = "{}%".format(item["today_income"]*100)
  533. item["total_income"] = "{}%".format(item["total_income"]*100)
  534. item["zans_count"] = item.get("zans",0)
  535. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  536. if page and page_size:
  537. total,data = ccf.get_page_list(data,page,page_size)
  538. return total,data
  539. else:
  540. return len(data),data
  541. def add_model(cls,**kwargs):
  542. """
  543. """
  544. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  545. model = getattr(cm,model_name)
  546. if model_name == "PlayerRecord":
  547. user_id = kwargs.get("user_id")
  548. match_id = kwargs.get("match_id")
  549. stock_date = kwargs.get("stock_date")
  550. now = datetime.datetime.now()
  551. if not cm.Player.objects.filter(user_id=user_id,match_id=match_id).exists():
  552. raise ce.TipException(u"请先完成报名再提交数据!")
  553. if now.weekday() in [5,6] or not now.strftime("%Y-%m-%d") in get_match_validdates(match_id):
  554. raise ce.TipException(u"今日不能提交数据!")
  555. now_time = datetime.datetime.now().strftime("%H:%S")
  556. if not user_id in [9600,6209,5709,25953]:
  557. if now_time<"15:00" or now_time > "23:50":
  558. raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
  559. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  560. today_stock = json.dumps(kwargs.get("today_stock"))
  561. today_stock_img = json.dumps(kwargs.get("today_stock_img"))
  562. today_fund = float(kwargs.get("today_fund",0))
  563. is_markt = int(kwargs.get("is_markt",0))
  564. experience = kwargs.get("experience")
  565. if not ccc.get_cur_match().id == match_id:
  566. raise ce.TipException(u"非当前赛事参赛选手不能提交作业!")
  567. #计算今日和昨日盈亏
  568. if float(today_fund)>9999 or float(today_fund)<=0:
  569. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  570. player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
  571. user_id = player.user_id
  572. init_fund = player.fund
  573. user = cm.UserInfo.objects.filter(id=user_id).first()
  574. username = user.username
  575. usercode = user.usercode
  576. match_group = player.match_group
  577. zq = user.zq
  578. cw = user.cw
  579. df = user.df
  580. match = cm.Match.objects.filter(id=match_id).first()
  581. if player.match_status < 1:
  582. raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
  583. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  584. if not user_id in [9600,6209,5709]:
  585. if match.end_time < now_date:
  586. raise ce.TipException(u"该比赛已结束或您未参加此次比赛不能提交数据!")
  587. validdates = get_match_validdates(match_id)
  588. today_index = validdates.index(stock_date)
  589. yesterday_index = today_index -1 if today_index >=1 else 0
  590. yesterday_date = validdates[yesterday_index]
  591. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  592. match_id=match_id,user_id=user_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
  593. if yesterday:
  594. yesterday_fund = yesterday.today_fund
  595. yesterday_stock = yesterday.today_stock
  596. yesterday_stock_img = yesterday.today_stock_img
  597. yesterday_is_markt = yesterday.is_markt
  598. else:
  599. yesterday_fund = today_fund
  600. yesterday_stock = ""
  601. yesterday_stock_img = ""
  602. yesterday_is_markt = 0
  603. if kwargs.get("id"):
  604. if cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).count()==1:
  605. init_fund = today_fund
  606. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund)
  607. else:
  608. if not cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).exists():
  609. init_fund = today_fund
  610. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund)
  611. with transaction.atomic():
  612. #记录持股情况
  613. new_stock_list = []
  614. today_stock_list = json.loads(today_stock)
  615. for ts in today_stock_list:
  616. if ts["name"]:
  617. try:
  618. stock,flag = cm.Stock.objects.get_or_create(
  619. name = ts["name"]
  620. )
  621. stock_id = stock.id
  622. usobj,flag = cm.UserStock.objects.get_or_create(
  623. user_id = user_id,
  624. stock_id = stock_id,
  625. stock_name = ts["name"],
  626. player_id = player.id,
  627. stock_date = stock_date
  628. )
  629. if ts.get("fund"):
  630. usobj.fund = ts["fund"]
  631. usobj.save()
  632. ts["stock_id"] = stock_id
  633. new_stock_list.append(ts)
  634. except Exception as e:
  635. print(e)
  636. today_stock = json.dumps(new_stock_list)
  637. obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
  638. user_id=user_id,
  639. match_id=match_id,
  640. stock_date=stock_date)
  641. obj.init_fund = init_fund
  642. obj.yesterday_fund = yesterday_fund
  643. obj.yesterday_stock = yesterday_stock
  644. obj.yesterday_stock_img = yesterday_stock_img
  645. obj.today_fund = today_fund
  646. obj.today_stock = today_stock
  647. obj.today_stock_img = today_stock_img
  648. obj.username = username
  649. obj.usercode = usercode
  650. obj.match_group = match_group
  651. obj.is_markt = is_markt
  652. obj.yesterday_is_markt = yesterday_is_markt
  653. obj.zq = zq
  654. obj.cw = cw
  655. obj.df = df
  656. obj.experience = experience
  657. #计算今日收益和总收益
  658. if float(today_fund)>9999 or float(today_fund)<=0:
  659. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  660. #有资金出入
  661. if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists():
  662. fundinout = cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).first()
  663. fundin = fundinout.fundin
  664. fundout = fundinout.fundout
  665. today_income = 0.0
  666. total_income = 0.0
  667. #入资金
  668. if fundin > fundout:
  669. fundin = fundin - fundout
  670. if yesterday:
  671. today_income = (today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin)
  672. obj.yesterday_fund = obj.yesterday_fund + fundin
  673. else:
  674. today_income = 0.0
  675. obj.today_income = round(today_income,4)
  676. if flag:
  677. total_income = (today_fund-init_fund-fundin)/(init_fund+fundin)
  678. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=init_fund+fundin)
  679. obj.init_fund = init_fund + fundin
  680. else:
  681. total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
  682. obj.total_income = round(total_income,4)
  683. #出资金
  684. else:
  685. fundout = fundout - fundin
  686. if yesterday:
  687. today_income = (today_fund-(yesterday_fund-fundout))/float(yesterday_fund)
  688. obj.yesterday_fund = round(today_fund/(1+today_income),4)
  689. else:
  690. today_income = 0.0
  691. obj.today_income = round(today_income,4)
  692. if flag:
  693. total_income = (today_fund+fundout-init_fund)/init_fund if init_fund else 0.0
  694. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=round(today_fund/(1+total_income),4))
  695. obj.init_fund = round(today_fund/(1+total_income),4)
  696. else:
  697. total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
  698. obj.total_income = round(total_income,4)
  699. if float(today_income)>0.4:
  700. raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
  701. if float(total_income)>8:
  702. raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
  703. else:
  704. today_income = (today_fund - yesterday_fund)/float(yesterday_fund) if yesterday_fund else 0.0
  705. total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
  706. if float(today_income)>0.4:
  707. raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
  708. if float(total_income)>8:
  709. raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
  710. obj.today_income = round(today_income,4)
  711. obj.total_income = round(total_income,4)
  712. if not flag:
  713. obj.ctime = datetime.datetime.now()
  714. obj.save()
  715. #更新group_rank
  716. #ccc.cache.lpush(settings.RANK_LIST,obj.id)
  717. ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(obj.match_id,obj.id))
  718. return obj.id
  719. obj = model.objects.create(**kwargs)
  720. return obj.id
  721. def update_model(cls,**kwargs):
  722. """
  723. """
  724. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  725. model = getattr(cm,model_name)
  726. id = kwargs.pop("id")
  727. rst = model.objects.filter(id=id).update(**kwargs)
  728. if model_name == "Match":
  729. for item in kwargs.get("groups").split(","):
  730. cm.MatchGroup.objects.get_or_create(match_id=obj.id,name=item)
  731. return rst
  732. def delete_model(cls,**kwargs):
  733. """
  734. """
  735. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  736. model = getattr(cm,model_name)
  737. ids = str(kwargs.get("id")).split(",")
  738. rst = model.objects.filter(id__in=ids).delete()
  739. if model_name == "Comments":
  740. cm.Comments.objects.filter(pid__in=ids).delete()
  741. return ids
  742. def get_search_list(cls,**kwargs):
  743. """
  744. """
  745. model_name = re.search(r'.*\.(\w+)SearchView',str(cls.__class__)).groups()[0]
  746. model = getattr(cm,model_name)
  747. qset = model.objects.all()
  748. if model_name == "Stock":
  749. if kwargs.get("name"):
  750. qset = qset.filter(Q(name__icontains=kwargs.get("name"))|Q(code__icontains=kwargs.get("name")))
  751. else:
  752. if kwargs.get("name"):
  753. qset = qset.filter(name__icontains=kwargs.get("name"))
  754. if model_name == "Player":
  755. data = list(qset.values("id","username"))
  756. if model_name == "Stock":
  757. qset = qset.filter(code__isnull=False)
  758. data = list(qset.values("id","name","code"))
  759. for item in data:
  760. if item["code"]:
  761. item["label"] = "%s(%s)" % (item["name"],item["code"])
  762. else:
  763. item["label"] = "%s" % item["name"]
  764. else:
  765. data = list(qset.values("id","name"))
  766. return data
  767. def get_detail_info(cls,**kwargs):
  768. """
  769. """
  770. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  771. model = getattr(cm,model_name)
  772. id = kwargs.get("id")
  773. rst = list(model.objects.filter(id=id).values())
  774. rst = rst[0] if rst else {}
  775. if model_name == "Article":
  776. rst["ctime"] = ccf.datetime_to_str(rst["ctime"],"%Y-%m-%d")
  777. if model_name == "Stock":
  778. rst["choiced"] = ccc.cache.get("%s_choices" % id)
  779. rst["user_num"] = ccc.cache.get("%s_choices" % id)
  780. if model_name == "UserArticleRelation":
  781. article_ids = rst["article_ids"].split(",")
  782. articles = list(cm.Article.objects.filter(id__in=article_ids).values())
  783. rst["articles"] = articles
  784. return rst
  785. #@ccc.cache_data()
  786. def get_record_info(rcid):
  787. """
  788. """
  789. rst = cm.PlayerRecord.objects.filter(id=rcid).values().first()
  790. if rst:
  791. rst["match_group"] = cm.MatchGroup.objects.filter(id=rst["match_group"]).first().name
  792. today_stock = json.loads(rst["today_stock"]) if rst["today_stock"] else []
  793. today_stock = filter(lambda x:x["fund"] and x["name"],today_stock if today_stock else [])
  794. rst["today_stock"] = today_stock
  795. today_stock_img = json.loads(rst["today_stock_img"]) if rst["today_stock_img"] else []
  796. rst["today_stock_img"] = today_stock_img
  797. yesterday_stock = json.loads(rst["yesterday_stock"]) if rst["yesterday_stock"] else []
  798. yesterday_stock = filter(lambda x:x["fund"] and x["name"],yesterday_stock if yesterday_stock else [])
  799. rst["yesterday_stock"] = yesterday_stock
  800. yesterday_stock_img = json.loads(rst["yesterday_stock_img"]) if rst["yesterday_stock_img"] else []
  801. rst["yesterday_stock_img"] = yesterday_stock_img
  802. rst["today_income"] = "{}%".format(rst["today_income"]*100)
  803. rst["total_income"] = "{}%".format(rst["total_income"]*100)
  804. return rst
  805. def get_list_info(cls,**kwargs):
  806. """
  807. """
  808. model_name = re.search(r'.*\.(\w+)ListView',str(cls.__class__)).groups()[0]
  809. model = getattr(cm,model_name)
  810. qset = model.objects.all()
  811. if kwargs.get("name"):
  812. qset = qset.filter(name__icontains=kwargs.get("name"))
  813. if model_name == "UserInfo":
  814. if kwargs.get("username"):
  815. qset = qset.filter(username__icontains=kwargs.get("username"))
  816. if kwargs.get("usercode"):
  817. qset = qset.filter(usercode=kwargs.get("usercode"))
  818. if model_name == "StockComments":
  819. if kwargs.get("stock_id"):
  820. qset = qset.filter(stock_id=kwargs.get("stock_id"))
  821. if model_name == "UserArticleRelation":
  822. data = list(qset.order_by("-id").values("id","user_id","user_name","user_avatar"))
  823. else:
  824. data = list(qset.order_by("-id").values())
  825. page = int(kwargs.get("page",0))
  826. page_size = int(kwargs.get("page_size",20))
  827. if page and page_size:
  828. total,data = ccf.get_page_list(data,page,page_size)
  829. if model_name == "Player":
  830. for item in data:
  831. user = cm.UserInfo.objects.filter(id=item["user_id"]).first()
  832. match = cm.Match.objects.filter(id=item["match_id"]).first()
  833. item["username"] = user.username
  834. item["usercode"] = user.usercode
  835. item["match_name"] = match.name if match else ""
  836. return (total,data)
  837. else:
  838. return len(data),data
  839. return rst
  840. def add_player_record_single(**kwargs):
  841. """用户单独上传数据
  842. """
  843. return None
  844. now = datetime.datetime.now()
  845. if now.weekday() in [5,6] or now.strftime("%Y-%m-%d") in MISS_DATES:
  846. raise ce.TipException(u"今日不能提交数据!")
  847. now_time = datetime.datetime.now().strftime("%H:%S")
  848. if now_time<"15:00" or now_time > "23:50":
  849. raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
  850. usercode = kwargs.get("usercode")
  851. match_id = kwargs.get("match_id")
  852. if not cm.Player.objects.filter(usercode=usercode,match_id=match_id).exists():
  853. raise ce.TipException(u"用户代码错误")
  854. stock_date = kwargs.get("stock_date")
  855. #stock_date = "2022-04-26"
  856. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  857. today_stock = json.dumps(kwargs.get("today_stock"))
  858. today_stock_img = json.dumps(kwargs.get("today_stock_img"))
  859. today_fund = float(kwargs.get("today_fund"))
  860. is_markt = int(kwargs.get("is_markt",0))
  861. if int(today_fund)>9999 or int(today_fund)<0:
  862. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  863. player = cm.Player.objects.filter(usercode=usercode,match_id=match_id).first()
  864. #if player.fund <=0 :
  865. # raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
  866. player_id = player.id
  867. user_id = player.user_id
  868. init_fund = player.fund
  869. user = cm.UserInfo.objects.filter(id=user_id).first()
  870. username = user.username
  871. usercode = user.usercode
  872. match_group = player.match_group
  873. match = cm.Match.objects.filter(id=match_id).first()
  874. if player.match_status < 1:
  875. raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
  876. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  877. if match.end_time < now_date:
  878. raise ce.TipException(u"该比赛已结束!")
  879. #yesterday = cm.PlayerRecord.objects.filter(
  880. # match_id=match_id,player_id=player_id).order_by("-id").first()
  881. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  882. match_id=match_id,player_id=player_id).order_by("-stock_date").first()
  883. if yesterday:
  884. yesterday_fund = yesterday.today_fund
  885. yesterday_stock = yesterday.today_stock
  886. yesterday_stock_img = yesterday.today_stock_img
  887. else:
  888. #yesterday_fund = init_fund
  889. yesterday_fund = today_fund
  890. init_fund = today_fund
  891. yesterday_stock = ""
  892. yesterday_stock_img = ""
  893. cm.Player.objects.filter(id=player_id).update(fund=today_fund)
  894. #记录持股情况
  895. new_stock_list = []
  896. today_stock_list = json.loads(today_stock)
  897. for ts in today_stock_list:
  898. if ts["name"]:
  899. stock,flag = cm.Stock.objects.get_or_create(
  900. name = ts["stock"]
  901. )
  902. stock_id = stock.id
  903. usobj,flag = cm.UserStock.objects.get_or_create(
  904. player_id = player_id,
  905. stock_id = stock_id,
  906. stock_name = ts["name"],
  907. stock_date = stock_date
  908. )
  909. ts["stock_id"] = stock_id
  910. new_stock_list.append(ts)
  911. today_stock = json.dumps(new_stock_list)
  912. obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
  913. player_id=player_id,
  914. match_id=match_id,
  915. stock_date=stock_date)
  916. obj.init_fund = init_fund
  917. obj.yesterday_fund = yesterday_fund
  918. obj.yesterday_stock = yesterday_stock
  919. obj.yesterday_stock_img = yesterday_stock_img
  920. obj.today_fund = today_fund
  921. obj.today_stock = today_stock
  922. obj.today_stock_img = today_stock_img
  923. obj.user_id = user_id
  924. obj.username = username
  925. obj.usercode = usercode
  926. obj.match_group = match_group
  927. obj.is_markt = is_markt
  928. #计算今日和昨日盈亏
  929. today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
  930. total_income = (today_fund - init_fund)/float(init_fund)
  931. #if int(today_fund)>9999 or int(today_fund)<0:
  932. # raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  933. if int(today_income)>2:
  934. raise ce.TipException(u"数据错误,今日盈利已超过2倍,请仔细核对数据!")
  935. obj.today_income = round(today_income,4)
  936. obj.total_income = round(total_income,4)
  937. if not flag:
  938. obj.ctime = datetime.datetime.now()
  939. obj.save()
  940. #更新股票持股人数
  941. for stock in new_stock_list:
  942. cm.Stock.objects.filter(id=stock["id"]).update(user_num=F("user_num")+1)
  943. #更新group_rank
  944. #update_group_rank(match_id,match_group,obj.stock_date)
  945. ccc.cache.lpush(settings.RANK_LIST,obj.id)
  946. return obj.id
  947. def get_single_match_info(match_id):
  948. """
  949. """
  950. if not match_id:
  951. match = cm.Match.objects.all().order_by("-id").values().first()
  952. else:
  953. match = cm.Match.objects.filter(id=match_id).values().first()
  954. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  955. return now_date,match
  956. def get_cur_record(request):
  957. """
  958. """
  959. user_id = request.user.get("id")
  960. match_id = ccc.get_cur_match().id
  961. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  962. 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")
  963. data = qset.values().first() if qset else {}
  964. if data:
  965. data["today_stock_img"] = json.loads(data["today_stock_img"]) if data["today_stock_img"] else []
  966. data["today_stock"] = json.loads(data["today_stock"]) if data["today_stock"] else []
  967. return data
  968. def follow_player(**kwargs):
  969. """
  970. """
  971. user_id = kwargs.get("user_id")
  972. follow_id = kwargs.get("follow_id")
  973. if kwargs.get("action") == "cancel":
  974. cm.UserFollows.objects.filter(user_id=user_id,follow_id=follow_id).delete()
  975. return True
  976. else:
  977. obj,flag = cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=follow_id)
  978. return obj.id
  979. def calc_win_rate(player_id,match_id):
  980. """计算胜率
  981. """
  982. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=player_id)
  983. win_rate = qset.filter(today_income__gt=0).count()/float(qset.count()) if qset else 0.0
  984. win_rate = round(win_rate,3)
  985. win_rate = "{}%".format(win_rate*100)
  986. return win_rate
  987. def get_user_follower(request):
  988. """获取用户列表
  989. """
  990. user_id = request.user.get("id")
  991. match_id = ccc.get_cur_match().id
  992. qdata = request.json
  993. if qdata.get("user_id"):
  994. user_id = int(qdata.get("user_id"))
  995. _today = get_today_date()
  996. data = []
  997. qset = cm.UserFollows.objects.filter(follow_id=user_id)
  998. follow_ids = list(qset.values_list("user_id",flat=True))
  999. userset = cm.UserInfo.objects.filter(id__in=follow_ids)
  1000. data = list(userset.values())
  1001. page = int(qdata.get("page",1))
  1002. page_size = int(qdata.get("page_size",20))
  1003. if page and page_size:
  1004. total,data = ccf.get_page_list(data,page,page_size)
  1005. return total,data
  1006. else:
  1007. return len(data),data
  1008. #
  1009. for player_id in follow_ids:
  1010. latest_key = "PLAYER_LATEST_%d"%player_id
  1011. _match_id = ccc.cache.hget(latest_key,"match_id")
  1012. _today = ccc.cache.hget(latest_key,"stock_date")
  1013. _match_group = ccc.cache.hget(latest_key,"match_group")
  1014. today_record = ccc.get_today_record(player_id,_match_id,_match_group,_today)
  1015. if today_record:
  1016. data.append(today_record)
  1017. #data.append(today_record)
  1018. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  1019. _today = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"stock_date")
  1020. cur_user_latest = "PLAYER_LATEST_%d" % user_id
  1021. _match_group = ccc.cache.hget(cur_user_latest,"match_group")
  1022. cur_today_record = ccc.get_today_record(user_id,match_id,_match_group,_today)
  1023. if cur_today_record:
  1024. data.insert(0,cur_today_record)
  1025. page = int(qdata.get("page",1))
  1026. page_size = int(qdata.get("page_size",20))
  1027. if page and page_size:
  1028. total,data = ccf.get_page_list(data,page,page_size)
  1029. for item in data:
  1030. if item:
  1031. today_stock = json.loads(item["today_stock"])
  1032. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  1033. item["today_stock"] = today_stock
  1034. item["today_stock_img"] = json.loads(item["today_stock_img"])
  1035. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
  1036. if win_rate:
  1037. item["win_rate"] = str(float(win_rate)*100)+"%"
  1038. else:
  1039. item["win_rate"] = "0.0%"
  1040. item["today_income"] = "{}%".format(item["today_income"]*100)
  1041. item["total_income"] = "{}%".format(item["total_income"]*100)
  1042. return total,data
  1043. else:
  1044. return len(data),data
  1045. def get_user_follows(request):
  1046. """获取用户关注的选手列表
  1047. """
  1048. user_id = request.user.get("id",0)
  1049. qdata = request.json
  1050. if qdata.get("user_id"):
  1051. user_id = qdata.get("user_id")
  1052. qset = cm.UserFollows.objects.filter(user_id=user_id)
  1053. follow_ids = list(qset.values_list("follow_id",flat=True))
  1054. userset = cm.UserInfo.objects.filter(id__in=follow_ids)
  1055. data = list(userset.values())
  1056. page = int(qdata.get("page",1))
  1057. page_size = int(qdata.get("page_size",20))
  1058. if page and page_size:
  1059. total,data = ccf.get_page_list(data,page,page_size)
  1060. return total,data
  1061. else:
  1062. return len(data),data
  1063. today = get_today_date()
  1064. _today = today
  1065. data = []
  1066. for user_id in follow_ids:
  1067. latest_key = "PLAYER_LATEST_%d"%user_id
  1068. _match_id = ccc.cache.hget(latest_key,"match_id")
  1069. _today = ccc.cache.hget(latest_key,"stock_date")
  1070. _match_group = ccc.cache.hget(latest_key,"match_group")
  1071. today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
  1072. if today_record:
  1073. today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
  1074. today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
  1075. data.append(today_record)
  1076. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  1077. page = int(qdata.get("page",1))
  1078. page_size = int(qdata.get("page_size",20))
  1079. if page and page_size:
  1080. total,data = ccf.get_page_list(data,page,page_size)
  1081. for item in data:
  1082. if item:
  1083. try:
  1084. user_id = item["user_id"]
  1085. latest_key = "PLAYER_LATEST_%d"%user_id
  1086. today_stock = json.loads(item["today_stock"])
  1087. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  1088. item["today_stock"] = today_stock
  1089. item["today_stock_img"] = json.loads(item["today_stock_img"])
  1090. win_rate = ccc.cache.hget(latest_key,"win_rate")
  1091. if win_rate:
  1092. item["win_rate"] = str(float(win_rate)*100)+"%"
  1093. else:
  1094. item["win_rate"] = "0.0%"
  1095. item["today_income"] = "{}%".format(item["today_income"]*100)
  1096. item["total_income"] = "{}%".format(item["total_income"]*100)
  1097. item["zans_count"] = item.get("zans",0)
  1098. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  1099. except Exception as e:
  1100. print(e)
  1101. return total,data
  1102. else:
  1103. return len(data),data
  1104. def get_hot_stock_rank(**kwargs):
  1105. """
  1106. """
  1107. data = {
  1108. "hot_buy":[
  1109. {"stock_name":u"创业黑马","count":12}
  1110. ],
  1111. "hot_sell":[
  1112. {"stock_name":u"创业黑马","count":12}
  1113. ]
  1114. }
  1115. return data
  1116. #@ccc.cache_data()
  1117. def get_stock_info(stock_id):
  1118. """
  1119. """
  1120. stock = cm.Stock.objects.filter(id=stock_id).values().first()
  1121. stock["choiced"] = 1
  1122. nbc = cm.StockComments.objects.filter(stock_id=stock_id).order_by("-id").values().first()
  1123. if nbc:
  1124. stock["last_nb_comments"] = nbc
  1125. return stock
  1126. def get_hot_stock_buy(**kwargs):
  1127. """
  1128. """
  1129. stock_date = kwargs.get("stock_date")
  1130. qset = cm.UserStock.objects.filter(stock_date=stock_date)
  1131. if kwargs.get("name"):
  1132. qset = cm.UserStock.objects.filter(stock_name__icontains=kwargs.get("name"),stock_date=stock_date)
  1133. qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-count")
  1134. data = []
  1135. for q in qset:
  1136. stock_id = q["stock_id"]
  1137. count = q["count"]
  1138. stock_name = q.get("stock_name")
  1139. total_fund = q["total_fund"]
  1140. comments_count = ccc.cache.get("%s_comments" % stock_id)
  1141. choice_count = ccc.cache.get("%s_choices" % stock_id)
  1142. comments_count = comments_count if comments_count else 0
  1143. choice_count = choice_count if choice_count else 0
  1144. data.append({"stock_name":stock_name,"id":stock_id,"count":count,"comments_count":comments_count,"choice_count":choice_count,"total_fund":total_fund})
  1145. page = int(kwargs.get("page",1))
  1146. page_size = int(kwargs.get("page_size",20))
  1147. if page and page_size:
  1148. total,data = ccf.get_page_list(data,page,page_size)
  1149. return total,data
  1150. else:
  1151. return len(data),data
  1152. return data
  1153. def get_hot_follow(**kwargs):
  1154. """
  1155. """
  1156. stock_date = kwargs.get("stock_date")
  1157. match_id = kwargs.get("match_id")
  1158. if not match_id:
  1159. match_id = ccc.get_cur_match().id
  1160. #player_ids = list(cm.Player.objects.filter(match_id=cur_match_id,match_status=1).values_list("id",flat=True))
  1161. player_ids = list(cm.Player.objects.filter(match_id=match_id).values_list("user_id",flat=True))
  1162. qset = cm.UserFollows.objects.filter(follow_id__in=player_ids)
  1163. qset = qset.values("follow_id").annotate(count=Count("follow_id")).order_by("-count")
  1164. data = []
  1165. for q in qset:
  1166. player_id = q["follow_id"]
  1167. count = q["count"]
  1168. today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1169. match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
  1170. match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
  1171. badest_income = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"badest_income")
  1172. today_record = get_today_record(player_id,match_id,match_group,today)
  1173. if today_record:
  1174. userinfo = get_user_info(today_record["user_id"])
  1175. user_id = today_record["user_id"]
  1176. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"win_rate")
  1177. try:
  1178. win_rate = str(float(win_rate)*100)+"%"
  1179. except:
  1180. pass
  1181. if userinfo:
  1182. data.append(
  1183. {
  1184. "player_name":userinfo.get("username"),
  1185. "count":count,
  1186. "id":player_id,
  1187. "user_id":user_id,
  1188. "today_fund":today_record["today_fund"],
  1189. "total_income":"{}%".format(today_record["total_income"]*100),
  1190. "today_income":"{}%".format(today_record["today_income"]*100),
  1191. "badest_income":"{}%".format(badest_income*100) if badest_income else "0.0%",
  1192. "style":userinfo.get("style"),
  1193. "badge":userinfo.get("badge"),
  1194. "match_id":match_id,
  1195. "win_rate":win_rate
  1196. }
  1197. )
  1198. if kwargs.get("name"):
  1199. data = filter(lambda x:kwargs.get("name") in x["player_name"],data)
  1200. page = int(kwargs.get("page",1))
  1201. page_size = int(kwargs.get("page_size",20))
  1202. if page and page_size:
  1203. total,data = ccf.get_page_list(data,page,page_size)
  1204. return total,data
  1205. else:
  1206. return len(data),data
  1207. return data
  1208. def get_hot_stock_sell(**kwargs):
  1209. """
  1210. """
  1211. stock_date = kwargs.get("stock_date")
  1212. stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
  1213. yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  1214. ##昨天所有股票
  1215. #yes_stock_ids = list(cm.UserStock.objects.filter(stock_date=yesterday).values_list("stock_id",flat=True))
  1216. #yes_stock_ids = list(set(yes_stock_ids))
  1217. #data = []
  1218. #for ysi in yes_stock_ids:
  1219. # yes_count = cm.UserStock.objects.filter(stock_date=yesterday,stock_id=ysi).count()
  1220. # td_count = cm.UserStock.objects.filter(stock_date=stock_date,stock_id=ysi).count()
  1221. # if td_count < yes_count:
  1222. # stock_name = cm.Stock.objects.filter(id=ysi).first().name
  1223. # data.append({"stock_name":stock_name,"count":yes_count-td_count,"id":ysi})
  1224. qset = cm.HotStockSellCount.objects.filter(stock_date=stock_date)
  1225. if kwargs.get("name"):
  1226. qset = qset.filter(stock_name__icontains=kwargs.get("name"))
  1227. qset = qset.order_by("-count")
  1228. data = list(qset.values("stock_name","stock_id","count"))
  1229. for item in data:
  1230. item["id"] = item["stock_id"]
  1231. page = int(kwargs.get("page",0))
  1232. page_size = int(kwargs.get("page_size",20))
  1233. if page and page_size:
  1234. total,data = ccf.get_page_list(data,page,page_size)
  1235. return total,data
  1236. else:
  1237. return len(data),data
  1238. return data
  1239. def get_stock_info(_id):
  1240. """
  1241. """
  1242. data = cm.Stock.objects.filter(id=_id).values().first()
  1243. nbc = cm.StockComments.objects.filter(stock_id=_id).order_by("-id").values().first()
  1244. if nbc:
  1245. data["last_nb_comments"] = nbc
  1246. return data
  1247. def get_hot_stock_sell_players(**kwargs):
  1248. """
  1249. """
  1250. _id = kwargs.get("id")
  1251. stock_date = kwargs.get("stock_date")
  1252. stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
  1253. yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  1254. #昨天持股选手
  1255. yes_players = list(cm.UserStock.objects.filter(stock_date=yesterday,stock_id=_id).values_list("player_id",flat=True))
  1256. td_players = list(cm.UserStock.objects.filter(stock_date=stock_date,stock_id=_id).values_list("player_id",flat=True))
  1257. sell_players = list(set(yes_players)-set(td_players))
  1258. data = []
  1259. for player_id in sell_players:
  1260. player = cm.Player.objects.filter(id=player_id).first()
  1261. if player:
  1262. match_id = player.match_id
  1263. match_group = player.match_group
  1264. today_record = get_today_record(player_id,match_id,match_group,stock_date)
  1265. if today_record:
  1266. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  1267. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  1268. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  1269. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  1270. data.append(today_record)
  1271. data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
  1272. page = int(kwargs.get("page",0))
  1273. page_size = int(kwargs.get("page_size",20))
  1274. if page and page_size:
  1275. total,data = ccf.get_page_list(data,page,page_size)
  1276. return total,data
  1277. else:
  1278. return len(data),data
  1279. return data
  1280. def get_win_rate_rank(request):
  1281. """
  1282. """
  1283. player_id = request.player.id
  1284. match_id = request.player.match_id
  1285. match_group = request.player.match_group
  1286. kwargs = request.json
  1287. match_id = ccc.get_cur_match().id
  1288. qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lt=5,match_status=1).order_by("-win_rate")
  1289. data = list(qset.values())
  1290. page = int(kwargs.get("page",1))
  1291. page_size = int(kwargs.get("page_size",20))
  1292. if page and page_size:
  1293. total,data = ccf.get_page_list(data,page,page_size)
  1294. else:
  1295. total = len(data)
  1296. for item in data:
  1297. item["win_rate"] = "{}%".format(item["win_rate"]*100)
  1298. item["badest_income"] = "{}%".format(item["badest_income"]*100)
  1299. item["total_income"] = "{}%".format(item["total_income"]*100)
  1300. userinfo = get_user_info(item["user_id"])
  1301. if userinfo:
  1302. item["badge"] = userinfo.get("badge")
  1303. item["style"] = userinfo.get("style")
  1304. item["username"] = userinfo.get("username")
  1305. return total,data
  1306. def get_defend_rank(request):
  1307. """
  1308. """
  1309. player_id = request.player.id
  1310. match_id = request.player.match_id
  1311. match_group = request.player.match_group
  1312. kwargs = request.json
  1313. qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lte=5,match_status=1).order_by("-badest_income")
  1314. data = list(qset.values())
  1315. #data = []
  1316. #for item in datas:
  1317. # player = cm.Player.objects.filter(id=item["player_id"]).first()
  1318. # item["match_status"] = player.match_status if player else -1
  1319. # if item["match_status"] > -1:
  1320. # data.append(item)
  1321. page = int(kwargs.get("page",1))
  1322. page_size = int(kwargs.get("page_size",20))
  1323. if page and page_size:
  1324. total,data = ccf.get_page_list(data,page,page_size)
  1325. else:
  1326. total = len(data)
  1327. for item in data:
  1328. item["win_rate"] = "{}%".format(item["win_rate"]*100)
  1329. item["badest_income"] = "{}%".format(item["badest_income"]*100)
  1330. item["total_income"] = "{}%".format(item["total_income"]*100)
  1331. userinfo = get_user_info(item["user_id"])
  1332. if userinfo:
  1333. item["badge"] = userinfo.get("badge")
  1334. item["style"] = userinfo.get("style")
  1335. item["username"] = userinfo.get("username")
  1336. return total,data
  1337. def get_champion_articles_list(request):
  1338. """
  1339. """
  1340. kwargs = request.json
  1341. _type = kwargs.get("type")
  1342. isbanner = kwargs.get("isbanner")
  1343. category = kwargs.get("category")
  1344. qset = cm.Article.objects.filter(status=2).exclude(type="notice").order_by("-id")
  1345. if _type:
  1346. qset = qset.filter(type=_type)
  1347. if isbanner:
  1348. qset = qset.filter(isbanner=isbanner)
  1349. if category:
  1350. qset = qset.filter(category=category)
  1351. page = int(kwargs.get("page",0))
  1352. page_size = int(kwargs.get("page_size",20))
  1353. if page and page_size:
  1354. total,qset = ccc.get_page_qset(qset,page,page_size)
  1355. else:
  1356. total = qset.count()
  1357. data = list(qset.values())
  1358. for item in data:
  1359. item["ctime"] = ccf.datetime_to_str(item["ctime"],"%Y-%m-%d")
  1360. return total,data
  1361. def get_wanzhu_comment(**kwargs):
  1362. """
  1363. """
  1364. match_id = kwargs.get("match_id")
  1365. group_id = kwargs.get("group_id")
  1366. today = get_today_date()
  1367. players = get_match_group_players(match_id,group_id)
  1368. new_players = []
  1369. for player in players:
  1370. user_id = player["user_id"]
  1371. user = get_user_info(user_id)
  1372. username = user["username"] if user else ""
  1373. player_id = player["id"]
  1374. match_group = group_id
  1375. today_record = get_today_record(player_id,match_id,int(match_group),today)
  1376. if today_record and today_record.get("wanzhu_comment"):
  1377. player.update(today_record)
  1378. player["username"] = username
  1379. player["total_income"] = "{}%".format(player["total_income"]*100)
  1380. player["fund"] = round(player["fund"],4)
  1381. player["init_fund"] = round(player["init_fund"],4)
  1382. player["today_fund"] = round(player["today_fund"],4)
  1383. player["today_stock"] = json.loads(player["today_stock"]) if player["today_stock"] else []
  1384. new_players.append(player)
  1385. new_players = sorted(new_players,key=lambda x:x["group_rank"])
  1386. data = new_players
  1387. page = int(kwargs.get("page",0))
  1388. page_size = int(kwargs.get("page_size",20))
  1389. if page and page_size:
  1390. total,data = ccf.get_page_list(data,page,page_size)
  1391. else:
  1392. total = len(data)
  1393. return total,data
  1394. def get_enum_list(request):
  1395. """
  1396. """
  1397. data = {
  1398. "zq":[
  1399. u"短线博弈",
  1400. u"长线价投",
  1401. u"长短兼备"
  1402. ],
  1403. "cw":[
  1404. u"分仓开超市",
  1405. u"重仓押注",
  1406. u"全仓单钓",
  1407. u"融资加倍"
  1408. ],
  1409. "df":[
  1410. u"低吸",
  1411. u"半路",
  1412. u"首板",
  1413. u"接力",
  1414. u"撬板",
  1415. u"T加0",
  1416. u"隔夜卖",
  1417. u"格局锁仓",
  1418. u"核按钮"
  1419. ],
  1420. "pz":[
  1421. u"10厘米",
  1422. u"20厘米",
  1423. u"30厘米",
  1424. u"N/C新股",
  1425. u"次新股",
  1426. u"可转债",
  1427. u"港股",
  1428. u"基金",
  1429. u"逆回购"
  1430. ]
  1431. }
  1432. return data
  1433. def get_player_list(**kwargs):
  1434. """选手列表
  1435. """
  1436. match_id = kwargs.get("match_id")
  1437. today = get_today_date()
  1438. qset = cm.Player.objects.filter(match_id=match_id,match_status=1)
  1439. if kwargs.get("name"):
  1440. qset = qset.filter(username__icontains=kwargs.get("name"))
  1441. page = int(kwargs.get("page",0))
  1442. page_size = int(kwargs.get("page_size",20))
  1443. if page and page_size:
  1444. total,qset = ccc.get_page_qset(qset,page,page_size)
  1445. else:
  1446. total = qset.count()
  1447. data = list(qset.values())
  1448. for item in data:
  1449. #print(item)
  1450. match_id = item["match_id"]
  1451. match_group = item["match_group"]
  1452. user_id = item["user_id"]
  1453. player_id = item["id"]
  1454. #user = cm.UserInfo.objects.filter(id=user_id).first()
  1455. today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1456. match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
  1457. match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
  1458. today_record = get_today_record(player_id,match_id,match_group,today)
  1459. if today_record:
  1460. today_record.pop("id")
  1461. item.update(today_record)
  1462. user_info = get_user_info(user_id)
  1463. if user_info:
  1464. user_info.pop("id")
  1465. item.update(user_info)
  1466. if item.get("today_income"):
  1467. item["today_income"] = "{}%".format(item["today_income"]*100)
  1468. item["total_income"] = "{}%".format(item["total_income"]*100)
  1469. if kwargs.get("zq"):
  1470. data = filter(lambda x:kwargs.get("zq") == x.get("zq"),data)
  1471. if kwargs.get("cw"):
  1472. data = filter(lambda x:kwargs.get("cw") == x.get("cw"),data)
  1473. if kwargs.get("df"):
  1474. data = filter(lambda x:kwargs.get("df") == x.get("df"),data)
  1475. return total,data
  1476. def get_mine_style(request):
  1477. """
  1478. """
  1479. user = request.user
  1480. #player = request.player
  1481. user = cm.UserInfo.objects.filter(id=user["id"]).first()
  1482. match_id = ccc.get_cur_match().id
  1483. player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first()
  1484. data = {
  1485. "zq":user.zq,
  1486. "cw":user.cw,
  1487. "df":user.df,
  1488. "pz":user.pz,
  1489. "join_time":user.join_time,
  1490. "username":user.username,
  1491. "account_img":user.account_img,
  1492. "avatar":user.avatar
  1493. }
  1494. if player:
  1495. data["is_player"] = 1
  1496. data["init_fund"] = player.fund if player.fund else 0
  1497. else:
  1498. data["is_player"] = 0
  1499. data["init_fund"] = None
  1500. return data
  1501. def update_user_style(**kwargs):
  1502. """
  1503. """
  1504. user_id = kwargs.pop("user_id")
  1505. #player_id = kwargs.pop("player_id")
  1506. if kwargs.get("init_fund"):
  1507. init_fund = kwargs.pop("init_fund")
  1508. try:
  1509. init_fund = kwargs.pop("init_fund")
  1510. except Exception as e:
  1511. print(e)
  1512. #avatar = kwargs.pop("avatar")
  1513. cm.UserInfo.objects.filter(id=user_id).update(**kwargs)
  1514. #if player_id and init_fund:
  1515. # cm.Player.objects.filter(id=player_id).update(fund=init_fund)
  1516. if kwargs.get("username"):
  1517. cm.Player.objects.filter(user_id=user_id).update(username=kwargs.get("username"))
  1518. match_id = ccc.get_cur_match().id
  1519. upset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id)
  1520. upset.update(username=kwargs.get("username"))
  1521. record_ids = list(upset.values_list("id",flat=True))
  1522. for _id in record_ids:
  1523. ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(match_id,_id))
  1524. if kwargs.get("avatar"):
  1525. cm.UserInfo.objects.filter(id=user_id).update(avatar=kwargs.get("avatar"))
  1526. ccc.cache.delete("cdata_get_user_info_(%sL,)"%user_id)
  1527. return True
  1528. def get_stock_players(**kwargs):
  1529. """
  1530. """
  1531. stock_id = kwargs.get("stock_id")
  1532. stock_date = kwargs.get("stock_date",get_today_date())
  1533. data = []
  1534. user_stocks = cm.UserStock.objects.filter(stock_id=stock_id,stock_date=stock_date)
  1535. for us in user_stocks:
  1536. player_id = us.player_id
  1537. player = cm.Player.objects.filter(id=player_id).first()
  1538. if player:
  1539. match_id = player.match_id
  1540. match_group = player.match_group
  1541. user_id = player.user_id
  1542. if stock_date:
  1543. today_record = get_today_record(user_id,match_id,match_group,stock_date)
  1544. else:
  1545. today_record = get_today_record(user_id,match_id,match_group,us.stock_date)
  1546. if today_record:
  1547. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  1548. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  1549. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  1550. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  1551. data.append(today_record)
  1552. data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
  1553. #分页
  1554. page = int(kwargs.get("page",0))
  1555. page_size = int(kwargs.get("page_size",20))
  1556. if page and page_size:
  1557. total,data = ccf.get_page_list(data,page,page_size)
  1558. else:
  1559. total = len(data)
  1560. #return total,data
  1561. #return data
  1562. if kwargs.get("v3"):
  1563. return total,data
  1564. else:
  1565. return data
  1566. def update_user_fund(**kwargs):
  1567. """
  1568. """
  1569. user_id = kwargs.pop("user_id")
  1570. player_id = kwargs.pop("player_id")
  1571. init_fund = kwargs.pop("init_fund")
  1572. if player_id and init_fund:
  1573. cm.Player.objects.filter(id=player_id).update(fund=init_fund)
  1574. return True
  1575. def get_player_match_calendar(**kwargs):
  1576. """
  1577. """
  1578. match_id = kwargs.get("match_id")
  1579. month = kwargs.get("month")
  1580. user_id = kwargs.get("user_id")
  1581. week,eday = calendar.monthrange(int(month.split("-")[0]),int(month.split("-")[1]))
  1582. sday = "01"
  1583. eday = str(eday).zfill(2)
  1584. sdate = month + "-" + sday
  1585. edate = month + "-" + eday
  1586. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id)\
  1587. .filter(stock_date__gte=sdate,stock_date__lte=edate)
  1588. data = list(qset.values())
  1589. dct = {}
  1590. for item in data:
  1591. item["today_income"] = "{}%".format(item["today_income"]*100)
  1592. #dct[item["stock_date"]] = item["today_income"]
  1593. dct[item["stock_date"]] = [item["today_income"],item["id"]]
  1594. newdata = []
  1595. for i in range(1,int(eday)+1):
  1596. stock_date = month + "-" + str(i).zfill(2)
  1597. today_tpl = dct.get(stock_date,[])
  1598. today_income = today_tpl[0] if today_tpl else None
  1599. record_id = today_tpl[1] if today_tpl else None
  1600. newdata.append({
  1601. "stock_date":stock_date,
  1602. "today_income":today_income,
  1603. "record_id":record_id
  1604. })
  1605. return newdata
  1606. def get_all_match(request):
  1607. """
  1608. """
  1609. now = datetime.datetime.now().strftime("%Y-%m-%d")
  1610. #qset = cm.Match.objects.filter(start_time__lte=now).order_by("id")
  1611. qset = cm.Match.objects.filter(match_status__in=[3,4]).order_by("-id")
  1612. data = list(qset.values())
  1613. for item in data:
  1614. valid_dates = json.loads(item["valid_dates"]) if item["valid_dates"] else []
  1615. valid_dates.sort()
  1616. item["valid_dates"] = valid_dates
  1617. return data
  1618. def get_default_date(**kwargs):
  1619. """
  1620. """
  1621. match_id = kwargs.get("match_id")
  1622. if not match_id:
  1623. match_id = ccc.get_cur_match().id
  1624. record = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).order_by("-stock_date").first()
  1625. if record:
  1626. return record.stock_date
  1627. else:
  1628. return get_today_date()
  1629. @ccc.cache_data()
  1630. def get_stock_search(**kwargs):
  1631. """
  1632. """
  1633. qset = cm.Stock.objects.all()
  1634. data = list(qset.values("id","name","code"))
  1635. for item in data:
  1636. if item["code"]:
  1637. item["label"] = "%s(%s)" % (item["name"],item["code"])
  1638. else:
  1639. item["label"] = "%s" % item["name"]
  1640. return data
  1641. def get_mine_latest(request):
  1642. """
  1643. """
  1644. try:
  1645. user_id = request.user.get("id")
  1646. match_id = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_id")
  1647. match_group = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_group")
  1648. _today = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"stock_date")
  1649. if _today:
  1650. rst = ccc.get_today_record(int(user_id),int(match_id),int(match_group),_today)
  1651. if rst:
  1652. rst["today_income_fund"] = round((rst["today_fund"] - rst["yesterday_fund"])*10000,2) if rst["yesterday_fund"] else 0.00
  1653. rst["today_income"] = "{}%".format(rst["today_income"]*100)
  1654. rst["total_income"] = "{}%".format(rst["total_income"]*100)
  1655. rst["zan_count"] = rst.get("zans",0)
  1656. rst["comments_count"] = cm.Comments.objects.filter(record_id=rst.get("id",0)).count()
  1657. return rst
  1658. except Exception as e:
  1659. print(e)
  1660. return {"player_id":user_id,"match_id":match_id,"user_id":user_id}
  1661. #@ccc.cache_data()
  1662. def get_match_validdates(match_id):
  1663. """
  1664. """
  1665. #qdata = request.json
  1666. #match_id = qdata.get("match_id")
  1667. match = cm.Match.objects.filter(id=match_id).first()
  1668. if match:
  1669. validdates = json.loads(match.valid_dates) if match.valid_dates else []
  1670. validdates.sort()
  1671. return validdates
  1672. return []
  1673. def send_phcode(request):
  1674. """
  1675. """
  1676. qdata = request.json
  1677. phone = qdata.get("phone")
  1678. code = "%s%s%s%s" % (random.randint(0,9),random.randint(0,9),random.randint(0,9),random.randint(0,9))
  1679. send_verify_code(phone,code)
  1680. ccc.cache.set(phone,code,120)
  1681. pass
  1682. def get_signup_info(request):
  1683. """
  1684. """
  1685. qdata = request.json
  1686. try:
  1687. user_id = request.user.get("id",0)
  1688. except:
  1689. user_id = 0
  1690. try:
  1691. match_id = ccc.get_signup_match().id
  1692. match = cm.Match.objects.filter(id=match_id).values().first()
  1693. #
  1694. match_groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).values())
  1695. match["groups"] = match_groups
  1696. #报名状态
  1697. now = datetime.datetime.now().strftime("%Y-%m-%d")
  1698. signup_start_time = match["signup_start_time"]
  1699. signup_end_time = match["signup_end_time"]
  1700. if signup_start_time <= now and signup_end_time >= now:
  1701. match["signup_status"] = 1
  1702. else:
  1703. match["signup_status"] = 0
  1704. if cm.Player.objects.filter(match_id=match_id,user_id=user_id,match_group__isnull=False).filter(role__in=[1,2]).exists():
  1705. match["signup_done"] = 1
  1706. else:
  1707. match["signup_done"] = 0
  1708. return match
  1709. except Exception as e:
  1710. print(e)
  1711. return {}
  1712. def do_wx_pay(request):
  1713. """
  1714. """
  1715. user = request.user
  1716. user_id = request.user.get("id",0)
  1717. user_name = request.user.get("username","")
  1718. openid = request.user.get("openid","")
  1719. qdata = request.json
  1720. match_id = qdata.get("match_id")
  1721. match_name = qdata.get("match_name")
  1722. signup_type = qdata.get("signup_type")
  1723. total_fee = str(qdata.get("total_fee"))
  1724. phone = qdata.get("phone")
  1725. phcode = qdata.get("phcode")
  1726. match_group = qdata.get("match_group")
  1727. signup_name = qdata.get("signup_name")
  1728. pay_type = qdata.get("pay_type")
  1729. if not signup_name:
  1730. signup_name = user_name
  1731. orgcode = ccc.cache.get(phone)
  1732. if not phone == "13883187629":
  1733. if not phcode == orgcode:
  1734. raise ce.TipException(u"验证码不正确!")
  1735. if int(signup_type) == 1:
  1736. if not match_group:
  1737. match_group = cm.MatchGroup.objects.filter(match_id=match_id,charge=0).first().id
  1738. if pay_type == "wxapppay":
  1739. out_trade_no = "WXAPP"+datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
  1740. else:
  1741. out_trade_no = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
  1742. #游客和普通选手付费报名
  1743. #gt_time = datetime.timedelta(days=-365)+datetime.datetime.now()
  1744. #old_player = cm.Player.objects.filter(user_id=user_id,match_status=1,ctime__gte=gt_time).exists()
  1745. #if user["player_type"] in [0,1] and not phone=="13883187629":
  1746. if user["player_type"] in [0,1] and not phone=="13883187629":
  1747. #生成订单
  1748. order = cm.SignupOrder.objects.create(
  1749. user_id = user_id,
  1750. user_name = signup_name,
  1751. match_id = match_id,
  1752. match_name = match_name,
  1753. signup_type = signup_type,
  1754. total_fee = total_fee,
  1755. out_trade_no = out_trade_no,
  1756. phone = phone,
  1757. match_group = match_group,
  1758. signup_name = signup_name
  1759. )
  1760. #支付
  1761. if pay_type == "wxapppay":
  1762. total_fee = str(int(float(order.total_fee)*100))
  1763. notify_url = "https://test.hunanwanzhu.com/api/wx/v3/signup/notify"
  1764. #notify_url = "https://test.hunanwanzhu.com"
  1765. data = {"subject":u"%s报名费" % match_name,"price":total_fee,"out_trade_no":out_trade_no}
  1766. wxapppay = WechatPayDAL()
  1767. prepayinfo = wxapppay.create_order_info(data,notify_url)
  1768. return prepayinfo
  1769. else:
  1770. total_fee = str(int(float(order.total_fee)*100))
  1771. prepayinfo = wxpay.get_wx_unifiedorder(out_trade_no,total_fee,openid)
  1772. prepayinfo["key"] = wxpay.WxPayConf_pub.KEY
  1773. return prepayinfo
  1774. #种子选手和开户选手免费报名
  1775. else:
  1776. if signup_type == 1:
  1777. signup_name = user_name
  1778. #生成订单
  1779. order = cm.SignupOrder.objects.create(
  1780. user_id = user_id,
  1781. user_name = signup_name,
  1782. match_id = match_id,
  1783. match_name = match_name,
  1784. signup_type = signup_type,
  1785. total_fee = total_fee,
  1786. out_trade_no = out_trade_no,
  1787. phone = phone,
  1788. match_group = match_group,
  1789. signup_name = signup_name
  1790. )
  1791. user = cm.UserInfo.objects.filter(id=user_id).first()
  1792. #生成选手信息
  1793. cur_match = cm.Match.objects.filter(id=match_id).first()
  1794. visit_group = cm.MatchGroup.objects.filter(id=match_group).first()
  1795. player,flag = cm.Player.objects.get_or_create(
  1796. user_id = user.id,
  1797. match_id = cur_match.id
  1798. )
  1799. player.match_name = cur_match.name
  1800. player.match_group = visit_group.id
  1801. player.match_group_name = visit_group.name
  1802. player.username = signup_name
  1803. player.usercode = request.user.get("usercode")
  1804. player.role = 2
  1805. player.match_status = 1
  1806. player.save()
  1807. #
  1808. order.player_id = player.id
  1809. order.save()
  1810. user.username = signup_name
  1811. user.phone = phone
  1812. user.role = 2
  1813. user.save()
  1814. #发送报名成功信息
  1815. #send_signup_success(phone,signup_name)
  1816. if phone == "13883187629":
  1817. for i in [5001,4762,5173,5141]:
  1818. cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=i)
  1819. return {"free":1}
  1820. def do_wxpay_notify(request):
  1821. qdata = request.json
  1822. if qdata.get("resource_type") == "encrypt-resource":
  1823. wxapppay = WechatPayDAL()
  1824. res = wxapppay.decrypt_nofify_v3(qdata)
  1825. res = json.loads(res)
  1826. flag = True
  1827. else:
  1828. flag,res = wxpay.check_notify_valid(request.body)
  1829. if flag:
  1830. out_trade_no = res.get("out_trade_no")
  1831. transaction_id = res.get("transaction_id")
  1832. pay_time = res.get("time_end")
  1833. try:
  1834. sorder = cm.SignupOrder.objects.filter(out_trade_no=out_trade_no).first()
  1835. if sorder and not sorder.transaction_id:
  1836. now = datetime.datetime.now()
  1837. sorder.order_status = 1
  1838. sorder.pay_status = 1
  1839. sorder.pay_time = now
  1840. sorder.transaction_id = transaction_id
  1841. sorder.save()
  1842. #生成选手信息
  1843. user = cm.UserInfo.objects.filter(id=sorder.user_id).first()
  1844. visit_group = cm.MatchGroup.objects.filter(id=sorder.match_group).first()
  1845. player,flag = cm.Player.objects.get_or_create(
  1846. user_id = sorder.user_id,
  1847. match_id = sorder.match_id
  1848. )
  1849. player.match_name = sorder.match_name
  1850. player.match_group = visit_group.id
  1851. player.match_group_name = visit_group.name
  1852. player.username = sorder.user_name
  1853. player.usercode = user.usercode if user else ""
  1854. if sorder.signup_type == 2:
  1855. player.role = 2
  1856. else:
  1857. player.role = 1
  1858. #
  1859. sorder.player_id = player.id
  1860. sorder.save()
  1861. player.save()
  1862. if sorder.signup_type == 2:
  1863. player_id = sorder.player_id
  1864. user_id = sorder.user_id
  1865. match_group = sorder.match_group
  1866. match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name
  1867. 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)
  1868. cm.UserInfo.objects.filter(id=user_id).update(role=2,phone=sorder.phone,username=sorder.user_name)
  1869. if sorder.signup_type == 1:
  1870. player_id = sorder.player_id
  1871. user_id = sorder.user_id
  1872. cm.Player.objects.filter(id=player_id).update(role=1,match_status=1)
  1873. cm.UserInfo.objects.filter(id=user_id).update(role=1,phone=sorder.phone,username=sorder.user_name)
  1874. #发送报名成功信息
  1875. #send_signup_success(sorder.phone,sorder.signup_name)
  1876. return True
  1877. except Exception as e:
  1878. import traceback
  1879. traceback.print_exc()
  1880. print(e,111111111111)
  1881. return False
  1882. def get_user_comments(request):
  1883. """
  1884. """
  1885. kwargs = request.json
  1886. stock_id = kwargs.get("stock_id")
  1887. record_id = kwargs.get("record_id")
  1888. if record_id:
  1889. qset = cm.Comments.objects.filter(record_id=record_id,pid__isnull=True).order_by(*["-istop","-id"])
  1890. else:
  1891. qset = cm.Comments.objects.filter(stock_id=stock_id,pid__isnull=True).order_by(*["-istop","-id"])
  1892. data = list(qset.values())
  1893. for item in data:
  1894. if record_id:
  1895. subcomments = cm.Comments.objects.filter(record_id=record_id,pid=item["id"])
  1896. else:
  1897. subcomments = cm.Comments.objects.filter(stock_id=stock_id,pid=item["id"])
  1898. item["children"] = list(subcomments.values())
  1899. #分页
  1900. page = int(kwargs.get("page",1))
  1901. page_size = int(kwargs.get("page_size",20))
  1902. if page and page_size:
  1903. total,data = ccf.get_page_list(data,page,page_size)
  1904. else:
  1905. total = len(data)
  1906. return total,data
  1907. def get_user_choices(request):
  1908. """
  1909. """
  1910. user_id = request.user.get("id",0)
  1911. #match_id = request.player.match_id
  1912. kwargs = request.json
  1913. stock_id = kwargs.get("stock_id")
  1914. if stock_id:
  1915. qset = cm.UserChoice.objects.filter(stock_id=stock_id)
  1916. else:
  1917. qset = cm.UserChoice.objects.filter(user_id=user_id)
  1918. data = list(qset.values())
  1919. for item in data:
  1920. stock_id = item["stock_id"]
  1921. comments_count = ccc.cache.get("%s_comments" % stock_id)
  1922. choice_count = ccc.cache.get("%s_choices" % stock_id)
  1923. comments_count = comments_count if comments_count else 0
  1924. choice_count = choice_count if choice_count else 0
  1925. item["count"] = choice_count
  1926. item["comments_count"] = comments_count
  1927. item["choice_count"] = choice_count
  1928. #item["match_id"] = match_id
  1929. #分页
  1930. page = int(kwargs.get("page",1))
  1931. page_size = int(kwargs.get("page_size",20))
  1932. if page and page_size:
  1933. total,data = ccf.get_page_list(data,page,page_size)
  1934. else:
  1935. total = len(data)
  1936. return total,data
  1937. def get_user_consult_list(request):
  1938. """
  1939. """
  1940. player_id = request.user.get("id") if request.user else 0
  1941. if not player_id:
  1942. return 0,[]
  1943. kwargs = request.json
  1944. record_id = kwargs.get("record_id")
  1945. if kwargs.get("user_id"):
  1946. player_id = kwargs.get("user_id")
  1947. qset = cm.WanzhuConsult.objects.filter(user_id=player_id,user_id__gt=0)
  1948. qdata = list(qset.values())
  1949. data = []
  1950. for item in qdata:
  1951. data.append(item)
  1952. if cm.WanzhuConsult.objects.filter(pid=item["id"]).exists():
  1953. reply_list = cm.WanzhuConsult.objects.filter(Q(pid=item["id"])).values()
  1954. for iitem in reply_list:
  1955. data.append(iitem)
  1956. data = sorted(data,key=lambda x:x["id"])
  1957. #分页
  1958. page = int(kwargs.get("page",1))
  1959. page_size = int(kwargs.get("page_size",1000))
  1960. if page and page_size:
  1961. total,data = ccf.get_page_list(data,page,page_size)
  1962. else:
  1963. total = len(data)
  1964. for item in data:
  1965. user_id = item["user_id"]
  1966. user = cm.UserInfo.objects.filter(id=user_id).first()
  1967. if user:
  1968. item["usercode"] = user.usercode
  1969. return total,data
  1970. def get_user_zans(request):
  1971. """
  1972. """
  1973. qdata = request.json
  1974. record_id = qdata.get("record_id")
  1975. match_id = qdata.get("match_id")
  1976. zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
  1977. return zans
  1978. def get_user_comments_count(request):
  1979. """
  1980. """
  1981. qdata = request.json
  1982. record_id = qdata.get("record_id")
  1983. count = cm.Comments.objects.filter(record_id=record_id).count()
  1984. return count
  1985. def add_wanzhu_consult(request):
  1986. """咨询顽主
  1987. """
  1988. user_id = request.user.get("id",0)
  1989. user_name = request.user.get("username")
  1990. user_avatar = request.user.get("avatar")
  1991. openid = request.user.get("openid")
  1992. qdata = request.json
  1993. content = qdata.get("cotent")
  1994. width = qdata.get("width")
  1995. height = qdata.get("height")
  1996. pid = qdata.get("pid")
  1997. wanzhu_obj = cm.WanzhuConsult.objects.create(
  1998. user_id = user_id,
  1999. user_name = user_name,
  2000. user_avatar = user_avatar,
  2001. content = content,
  2002. pid = pid
  2003. )
  2004. wanzhu_obj.width = width
  2005. wanzhu_obj.height = height
  2006. wanzhu_obj.save()
  2007. obj,flag = cm.Consult.objects.get_or_create(
  2008. user_id = user_id,
  2009. )
  2010. obj.user_name = user_name
  2011. obj.user_avatar = user_avatar
  2012. obj.content = content
  2013. obj.view_status = 0
  2014. obj.reply_status = 0
  2015. obj.width = width
  2016. obj.height = height
  2017. obj.ctime = datetime.datetime.now()
  2018. obj.save()
  2019. #自动回复
  2020. if cm.WanzhuConsult.objects.filter(user_id=user_id).count() <=1:
  2021. content = u"您好,后台消息一般三小时内回复,如果超出时间请加微信destination8888"
  2022. cm.WanzhuConsult.objects.create(
  2023. pid = pid,
  2024. reply_content = content,
  2025. user_id = 0,
  2026. player_id = 0,
  2027. reply_user_id = user_id
  2028. )
  2029. #发送消息提醒
  2030. if cm.UserInfo.objects.filter(id=user_id).exists():
  2031. user = cm.UserInfo.objects.filter(id=user_id).first()
  2032. send_consult_reply_message(openid,user_name)
  2033. #发送app推送消息
  2034. title = u"顽主杯"
  2035. body = u"你收到一条顽主的消息"
  2036. params = {"type":"message","id":str(user_id)}
  2037. aliyunpush.push_notice_by_userid(0,title,body,params,"ios")
  2038. aliyunpush.push_notice_by_userid(0,title,body,params,"android")
  2039. def add_comments(request):
  2040. """
  2041. """
  2042. #if request.user.comment_status == 0:
  2043. # raise ce.TipException(u"对不起,暂无法评论/留言!")
  2044. user_id = request.user.get("id")
  2045. user_name = request.user.get("username")
  2046. user_avatar = request.user.get("avatar")
  2047. qdata = request.json
  2048. content = qdata.get("cotent")
  2049. record_id = qdata.get("record_id")
  2050. stock_id = qdata.get("stock_id")
  2051. pid = qdata.get("pid")
  2052. match_id = qdata.get("match_id")
  2053. target_user_id = qdata.get("target_user_id")
  2054. ip = ccf.get_ip(request)
  2055. location = ccf.get_city_from_ip(ip)
  2056. if record_id and target_user_id:
  2057. if cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=target_user_id).exists():
  2058. raise ce.TipException(u"对不起,暂无法评论/留言!")
  2059. obj = cm.Comments.objects.create(
  2060. user_id = user_id,
  2061. user_name = user_name,
  2062. user_avatar = user_avatar,
  2063. content = content,
  2064. record_id = record_id,
  2065. pid = pid,
  2066. ip = ip,
  2067. location = location,
  2068. stock_id = stock_id
  2069. )
  2070. if record_id:
  2071. cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(comments_count=F("comments_count")+1)
  2072. if stock_id:
  2073. ccc.cache.incr("%s_comments" % stock_id,1)
  2074. def add_choice(request):
  2075. """
  2076. """
  2077. user_id = request.user.get("id")
  2078. user_name = request.user.get("username")
  2079. user_avatar = request.user.get("avatar")
  2080. qdata = request.json
  2081. stock_id = qdata.get("stock_id")
  2082. stock_name = cm.Stock.objects.filter(id=stock_id).first().name
  2083. obj = cm.UserChoice.objects.create(
  2084. user_id = user_id,
  2085. user_name = user_name,
  2086. user_avatar = user_avatar,
  2087. stock_id = stock_id,
  2088. stock_name = stock_name
  2089. )
  2090. if stock_id:
  2091. ccc.cache.incr("%s_choices" % stock_id,1)
  2092. def add_zan(request):
  2093. """
  2094. """
  2095. qdata = request.json
  2096. record_id = qdata.get("record_id")
  2097. match_id = qdata.get("match_id")
  2098. cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(zans=F("zans")+1)
  2099. zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
  2100. return zans
  2101. def get_experience_list(request):
  2102. """
  2103. """
  2104. #return 0,[]
  2105. kwargs = request.json
  2106. today = get_today_date()
  2107. match_id = ccc.get_cur_match().id
  2108. match_group = kwargs.get("match_group")
  2109. #冠军组、千万组、百万组
  2110. grpset = cm.MatchGroup.objects.filter(match_id=match_id).filter(Q(name__icontains=u"千万组")|Q(name__icontains=u"百万组")|Q(name__icontains=u"冠军组"))
  2111. if match_group:
  2112. grpset = grpset.filter(id=match_group)
  2113. qbw_ids = list(grpset.values_list("id",flat=True))
  2114. 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")
  2115. 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"))
  2116. for item in data:
  2117. record_id = item["id"]
  2118. user_id = item["user_id"]
  2119. try:
  2120. item["user_avatar"] = get_user_info(user_id)["avatar"]
  2121. except:
  2122. item["user_avatar"] = ""
  2123. item["zans_count"] = item["zans"]
  2124. item["today_stock_img"] = json.loads(item["today_stock_img"])
  2125. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
  2126. if win_rate:
  2127. item["win_rate"] = str(float(win_rate)*100)+"%"
  2128. else:
  2129. item["win_rate"] = "0.0%"
  2130. item["today_income"] = "{}%".format(item["today_income"]*100)
  2131. item["total_income"] = "{}%".format(item["total_income"]*100)
  2132. #分页
  2133. page = int(kwargs.get("page",1))
  2134. page_size = int(kwargs.get("page_size",20))
  2135. if page and page_size:
  2136. total,data = ccf.get_page_list(data,page,page_size)
  2137. else:
  2138. total = len(data)
  2139. return total,data
  2140. def delete_choice(request):
  2141. """
  2142. """
  2143. user_id = request.user.get("id")
  2144. user_name = request.user.get("username")
  2145. user_avatar = request.user.get("avatar")
  2146. qdata = request.json
  2147. stock_id = qdata.get("stock_id")
  2148. cm.UserChoice.objects.filter(stock_id=stock_id,user_id=user_id).delete()
  2149. if ccc.cache.get("%s_choices" % stock_id) and int(ccc.cache.get("%s_choices" % stock_id)) >= 1:
  2150. ccc.cache.decr("%s_choices" % stock_id)
  2151. def delete_comments(request):
  2152. """
  2153. """
  2154. qdata = request.json
  2155. id = qdata.get("id")
  2156. if cm.Comments.objects.filter(id=id,stock_id__isnull=False).exists():
  2157. stock_id = cm.Comments.objects.filter(id=id).first().stock_id
  2158. if ccc.cache.get("%s_comments" % stock_id) and int(ccc.cache.get("%s_comments" % stock_id)) >= 1:
  2159. ccc.cache.decr("%s_comments" % stock_id)
  2160. cm.Comments.objects.filter(id=id).delete()
  2161. def modify_user_fund(request):
  2162. """
  2163. """
  2164. user_id = request.user.get("id")
  2165. #player = request.player
  2166. match_id = ccc.get_cur_match().id
  2167. player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
  2168. player_id = player.id
  2169. match_id = player.match_id
  2170. qdata = request.json
  2171. fundin = qdata.get("in_fund")
  2172. fundout = qdata.get("out_fund")
  2173. fundin = float(fundin) if fundin else 0.0
  2174. fundout = float(fundout) if fundout else 0.0
  2175. account_img = qdata.get("account_img")
  2176. init_fund = player.fund
  2177. trycalc = qdata.get("trycalc")
  2178. today_fund = qdata.get("today_fund")
  2179. today_fund = float(today_fund) if today_fund else 0.0
  2180. if trycalc:
  2181. stock_date = get_today_date()
  2182. validdates = get_match_validdates(match_id)
  2183. today_index = validdates.index(stock_date)
  2184. yesterday_index = today_index -1 if today_index >=1 else 0
  2185. yesterday_date = validdates[yesterday_index]
  2186. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  2187. match_id=match_id,player_id=player_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
  2188. if yesterday:
  2189. yesterday_fund = yesterday.today_fund
  2190. yesterday_stock = yesterday.today_stock
  2191. yesterday_stock_img = yesterday.today_stock_img
  2192. yesterday_is_markt = yesterday.is_markt
  2193. else:
  2194. yesterday_fund = today_fund
  2195. yesterday_stock = ""
  2196. yesterday_stock_img = ""
  2197. yesterday_is_markt = 0
  2198. #入资金
  2199. if fundin > fundout:
  2200. fundin = fundin - fundout
  2201. if yesterday:
  2202. today_income = round((today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin),4)
  2203. yesterday_fund = yesterday_fund + fundin
  2204. else:
  2205. today_income = 0.0
  2206. total_income = round((today_fund-init_fund-fundin)/(init_fund+fundin),4)
  2207. init_fund = init_fund + fundin
  2208. #出资金
  2209. else:
  2210. fundout = fundout - fundin
  2211. if yesterday:
  2212. today_income = round((today_fund-(yesterday_fund-fundout))/float(yesterday_fund),4)
  2213. yesterday_fund = round(today_fund/(1+today_income),4)
  2214. else:
  2215. today_income = 0.0
  2216. total_income = round((today_fund+fundout-init_fund)/init_fund,4)
  2217. init_fund = round(today_fund/(1+total_income),4)
  2218. today_income = "{}%".format(today_income*100)
  2219. total_income = "{}%".format(total_income*100)
  2220. return {"yesterday_fund":yesterday_fund,
  2221. "today_fund":today_fund,
  2222. "today_income":today_income,
  2223. "total_income":total_income,
  2224. "init_fund":init_fund}
  2225. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  2226. if cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).exists():
  2227. raise ce.TipException(u"资金出入须在提交作业之前提交,今日作业已提交,不能提交资金出入!")
  2228. if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists():
  2229. raise ce.TipException(u"今日已有资金出入,一天只能提交一次资金出入!")
  2230. fundinout,flag = cm.FundInOut.objects.get_or_create(
  2231. user_id = user_id,
  2232. fundin = fundin,
  2233. fundout = fundout,
  2234. stock_date = stock_date,
  2235. account_img = account_img
  2236. )
  2237. def get_user_match_list(request):
  2238. kwargs = request.json
  2239. user_id = kwargs.get("user_id")
  2240. if not user_id:
  2241. user_id = request.user.get("id")
  2242. qset = cm.Player.objects.filter(user_id=user_id).filter(match_group__isnull=False).order_by("-id")
  2243. qset = qset.values("user_id","match_id","match_group").annotate(cnt=Count("match_id"))
  2244. page = int(kwargs.get("page",0))
  2245. page_size = int(kwargs.get("page_size",20))
  2246. if page and page_size:
  2247. total,qset = ccc.get_page_qset(qset,page,page_size)
  2248. else:
  2249. total = qset.count()
  2250. #today = get_today_date(user_id=user_id)
  2251. data = list(qset.values("user_id","match_id","match_group"))
  2252. new_data = []
  2253. for item in data:
  2254. match_id = item["match_id"]
  2255. match_group = item["match_group"]
  2256. user_id = item["user_id"]
  2257. today = get_today_date(match_id=match_id,user_id=user_id)
  2258. item["match_info"] = get_match_info(match_id)
  2259. item["match_group_info"] = get_group_info(match_group)
  2260. if match_id and match_group:
  2261. today_record = ccc.get_today_record(user_id,int(match_id),int(match_group),today)
  2262. today_record = format_today_record(today_record)
  2263. if today_record:
  2264. if today_record.get("today_income"):
  2265. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  2266. if today_record.get("total_income"):
  2267. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  2268. item["today_record"] = today_record
  2269. new_data.append(item)
  2270. #return total,data
  2271. return total,new_data
  2272. def get_format_user_info(request):
  2273. user_id = request.user.get("id")
  2274. cur_user_id = request.user.get("id")
  2275. kwargs = request.json
  2276. q_user_id = kwargs.get("user_id")
  2277. if q_user_id:
  2278. user_id = q_user_id
  2279. userinfo = get_user_info_actual(q_user_id)
  2280. userinfo["fans"] = cm.UserFollows.objects.filter(follow_id=user_id).count()
  2281. userinfo["followers"] = cm.UserFollows.objects.filter(user_id=user_id).count()
  2282. del userinfo["phone"]
  2283. if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists():
  2284. userinfo["is_follow"] = 1
  2285. else:
  2286. userinfo["is_follow"] = 0
  2287. if cm.UserBlacks.objects.filter(user_id=cur_user_id,black_user_id=user_id).exists():
  2288. userinfo["is_black"] = 1
  2289. else:
  2290. userinfo["is_black"] = 0
  2291. return userinfo
  2292. def get_day_inout_rank_list(request):
  2293. """
  2294. """
  2295. kwargs = request.json
  2296. stock_date = kwargs.get("stock_date")
  2297. match_id = kwargs.get("match_id")
  2298. _type = kwargs.get("type")
  2299. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date)
  2300. if _type == "in":
  2301. qset = qset.order_by("-today_income")
  2302. else:
  2303. qset = qset.order_by("today_income")
  2304. page = int(kwargs.get("page",0))
  2305. page_size = int(kwargs.get("page_size",20))
  2306. if page and page_size:
  2307. total,qset = ccc.get_page_qset(qset,page,page_size)
  2308. else:
  2309. total = qset.count()
  2310. data = list(qset.values())
  2311. return total,data
  2312. def get_user_follows_v3(request):
  2313. """获取用户关注的选手列表
  2314. """
  2315. user_id = request.user.get("id",0)
  2316. qdata = request.json
  2317. if qdata.get("user_id"):
  2318. user_id = qdata.get("user_id")
  2319. qset = cm.UserFollows.objects.filter(user_id=user_id)
  2320. follow_ids = list(qset.values_list("follow_id",flat=True))
  2321. today = get_today_date()
  2322. _today = today
  2323. data = []
  2324. for user_id in follow_ids:
  2325. latest_key = "PLAYER_LATEST_%d"%user_id
  2326. _match_id = ccc.cache.hget(latest_key,"match_id")
  2327. _today = ccc.cache.hget(latest_key,"stock_date")
  2328. _match_group = ccc.cache.hget(latest_key,"match_group")
  2329. today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
  2330. if today_record:
  2331. today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
  2332. today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
  2333. data.append(today_record)
  2334. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  2335. page = int(qdata.get("page",1))
  2336. page_size = int(qdata.get("page_size",20))
  2337. if page and page_size:
  2338. total,data = ccf.get_page_list(data,page,page_size)
  2339. for item in data:
  2340. if item:
  2341. user_id = item["user_id"]
  2342. latest_key = "PLAYER_LATEST_%d"%user_id
  2343. today_stock = json.loads(item["today_stock"]) if item.get("today_stock") else []
  2344. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  2345. item["today_stock"] = today_stock
  2346. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item.get("today_stock_img") else []
  2347. win_rate = ccc.cache.hget(latest_key,"win_rate")
  2348. if win_rate:
  2349. item["win_rate"] = str(float(win_rate)*100)+"%"
  2350. else:
  2351. item["win_rate"] = "0.0%"
  2352. item["today_income"] = "{}%".format(item["today_income"]*100)
  2353. item["total_income"] = "{}%".format(item["total_income"]*100)
  2354. item["zans_count"] = item.get("zans",0)
  2355. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  2356. return total,data
  2357. else:
  2358. return len(data),data
  2359. def get_latest_match_info(request):
  2360. """
  2361. """
  2362. cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").values().first()
  2363. cur_match_id = cur_match.get("id")
  2364. groups = list(cm.MatchGroup.objects.filter(match_id=cur_match_id,is_active=1).order_by("order").values())
  2365. cur_match["groups"] = groups
  2366. return cur_match
  2367. def get_article_info(**kwargs):
  2368. """
  2369. """
  2370. _id = kwargs.get("id")
  2371. rst = cm.Article.objects.filter(id=_id).values().first()
  2372. rst["url"] = "https://www.hunanwanzhu.com/topic/article.html?id="+str(_id)
  2373. return rst
  2374. def get_profit_list(**kwargs):
  2375. """盈亏列表
  2376. """
  2377. stock_date = kwargs.get("stock_date")
  2378. match_id = kwargs.get("match_id")
  2379. _type = kwargs.get("type")
  2380. if not stock_date:
  2381. stock_date = get_today_date()
  2382. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=stock_date)
  2383. #if _type == "win":
  2384. # qset = qset.filter(today_income__gte=0).order_by("-today_income")
  2385. #if _type == "loss":
  2386. # qset = qset.filter(today_income__lt=0).order_by("today_income")
  2387. data = list(qset.values())
  2388. for item in data:
  2389. item["win_loss"] = item["today_fund"] - item["yesterday_fund"]
  2390. item["total_win_loss"] = item["today_fund"] - item["init_fund"]
  2391. item["win_loss"] = round(item["win_loss"],4)
  2392. item["total_win_loss"] = round(item["total_win_loss"],4)
  2393. if _type == "win":
  2394. data = sorted(data,key=lambda x:x["win_loss"],reverse=True)
  2395. if _type == "loss":
  2396. data = sorted(data,key=lambda x:x["win_loss"])
  2397. if _type == "total_win":
  2398. data = sorted(data,key=lambda x:x["total_win_loss"],reverse=True)
  2399. if _type == "total_loss":
  2400. data = sorted(data,key=lambda x:x["total_win_loss"])
  2401. page = int(kwargs.get("page",0))
  2402. page_size = int(kwargs.get("page_size",20))
  2403. if page and page_size:
  2404. total,data = ccf.get_page_list(data,page,page_size)
  2405. else:
  2406. total = len(data)
  2407. #data = list(qset.values())
  2408. return total,data
  2409. def get_group_rank_list_v3(request):
  2410. """排名列表
  2411. """
  2412. qdata = request.json
  2413. kwargs = qdata
  2414. group_id = qdata.get("id")
  2415. match_id = qdata.get("match_id")
  2416. match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id
  2417. today = qdata.get("stock_date")
  2418. if not today:
  2419. today = get_today_date()
  2420. match = get_match_info(match_id)
  2421. group = get_group_info(group_id)
  2422. players = get_match_group_users(match_id,group_id)
  2423. new_players = []
  2424. for player in players:
  2425. user_id = player["user_id"]
  2426. username = player["username"]
  2427. match_group = group_id
  2428. today_record = ccc.get_today_record(user_id,match_id,match_group,today)
  2429. if today_record:
  2430. player.update(today_record)
  2431. player["username"] = username
  2432. player["org_today_income"] = player["today_income"]
  2433. player["org_total_income"] = player["total_income"]
  2434. player["total_income"] = "{}%".format(player["total_income"]*100)
  2435. player["today_income"] = "{}%".format(player["today_income"]*100)
  2436. player["fund"] = round(player["fund"],4)
  2437. player["init_fund"] = round(player["init_fund"],4)
  2438. player["today_fund"] = round(player["today_fund"],4)
  2439. player["today_stock_img"] = json.loads(player["today_stock_img"]) if player["today_stock_img"] else []
  2440. #player["win_rate"] = calc_win_rate(user_id,match_id)
  2441. player["zan_count"] = player["zans"]
  2442. new_players.append(player)
  2443. if kwargs.get("order_by") == "today_income__asc":
  2444. new_players = sorted(new_players,key=lambda x:x["org_today_income"])
  2445. elif kwargs.get("order_by") == "today_income__desc" :
  2446. new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True)
  2447. elif kwargs.get("order_by") == "total_income__asc":
  2448. new_players = sorted(new_players,key=lambda x:x["org_total_income"])
  2449. elif kwargs.get("order_by") == "total_income__desc":
  2450. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  2451. else:
  2452. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  2453. #分页
  2454. page = int(kwargs.get("page",0))
  2455. page_size = int(kwargs.get("page_size",50))
  2456. if page and page_size:
  2457. total,new_players = ccf.get_page_list(new_players,page,page_size)
  2458. else:
  2459. total = len(new_players)
  2460. return total,new_players
  2461. def get_article_type_list(**kwargs):
  2462. rst = [u"游资专场",u"冠军交割",u"牛人专场",u"妖股列传"]
  2463. rst = const.ARTICLE_TYPE_LIST
  2464. return rst
  2465. def get_wanzhu_consult_list(**kwargs):
  2466. """
  2467. """
  2468. qset = cm.Consult.objects.filter(user_id__gt=0).order_by("-ctime")
  2469. if kwargs.get("username"):
  2470. qset = qset.filter(user_name__icontains=kwargs.get("username"))
  2471. if kwargs.get("reply_status"):
  2472. qset = qset.filter(reply_status=kwargs.get("reply_status"))
  2473. if kwargs.get("content"):
  2474. qset = qset.filter(Q(content__icontains=kwargs.get("content"))|Q(reply_content__icontains=kwargs.get("content")))
  2475. data = list(qset.values())
  2476. #分页
  2477. page = int(kwargs.get("page",1))
  2478. page_size = int(kwargs.get("page_size",20))
  2479. if page and page_size:
  2480. total,data = ccf.get_page_list(data,page,page_size)
  2481. else:
  2482. total = len(data)
  2483. for item in data:
  2484. user_id = item["user_id"]
  2485. userinfo = get_user_info(user_id)
  2486. if userinfo:
  2487. item["user_code"] = userinfo.get("usercode")
  2488. return total,data
  2489. def get_sub_category(pid):
  2490. """
  2491. """
  2492. qset = cm.BaikeCategory.objects.filter(parent_id=pid)
  2493. qdata = list(qset.values())
  2494. if qdata:
  2495. for subitem in qdata:
  2496. subitem["type"] = "ent"
  2497. subitem["children"] = get_sub_category(subitem["id"])
  2498. return qdata
  2499. def get_baike_category_tree(**kwargs):
  2500. """
  2501. """
  2502. parents = list(cm.BaikeCategory.objects.filter(parent_id__isnull=True).values())
  2503. for item in parents:
  2504. item["children"] = get_sub_category(item["id"])
  2505. return parents
  2506. def get_sub_catids(pid,data):
  2507. """
  2508. """
  2509. data = data if data else []
  2510. qset = cm.BaikeCategory.objects.filter(parent_id=pid)
  2511. ids = list(qset.values_list("id",flat=True))
  2512. if ids:
  2513. data.extend(ids)
  2514. for _id in ids:
  2515. get_sub_catids(_id,data)
  2516. return data
  2517. def get_baike_list_by_category(**kwargs):
  2518. category_id = kwargs.get("category_id")
  2519. sub_catids = get_sub_catids(category_id,[])
  2520. qset = cm.BaikeDetail.objects.filter(category_id__in=sub_catids)
  2521. data = list(qset.values())
  2522. page = int(kwargs.get("page",1))
  2523. page_size = int(kwargs.get("page_size",20))
  2524. if page and page_size:
  2525. total,data = ccf.get_page_list(data,page,page_size)
  2526. return total,data
  2527. else:
  2528. return len(data),data
  2529. return data
  2530. def get_baike_detail(**kwargs):
  2531. #_id = kwargs.get("id")
  2532. category_id = kwargs.get("category_id")
  2533. data = list(cm.BaikeDetail.objects.filter(category_id=category_id).values())
  2534. return data
  2535. def get_app_version(request):
  2536. rst = cm.APPVersion.objects.all().order_by("-id").values().first()
  2537. return rst
  2538. def reply_wanzhu_consult(**kwargs):
  2539. """
  2540. """
  2541. pid = kwargs.get("pid")
  2542. content = kwargs.get("reply_content")
  2543. user_id = kwargs.get("user_id")
  2544. action = kwargs.get("action")
  2545. width = kwargs.get("width")
  2546. height = kwargs.get("height")
  2547. if action == "send":
  2548. user = cm.UserInfo.objects.filter(id=user_id).first()
  2549. user_name = user.username
  2550. user_avatar = user.avatar
  2551. obj,flag = cm.Consult.objects.get_or_create(
  2552. user_id = user_id,
  2553. )
  2554. obj.user_name = user_name
  2555. obj.user_avatar = user_avatar
  2556. #obj.reply_content = content
  2557. obj.view_status = 1
  2558. obj.reply_status = 0
  2559. obj.ctime = datetime.datetime.now()
  2560. obj.save()
  2561. wanzhu_obj = cm.WanzhuConsult.objects.create(
  2562. user_id = user_id,
  2563. user_name = user_name,
  2564. user_avatar = user_avatar
  2565. )
  2566. wanzhu_obj.width = width
  2567. wanzhu_obj.height = height
  2568. wanzhu_obj.save()
  2569. wanzhu_obj_1 = cm.WanzhuConsult.objects.create(
  2570. reply_content = content,
  2571. user_id = 0,
  2572. player_id = 0,
  2573. reply_user_id = user_id,
  2574. pid = wanzhu_obj.id
  2575. )
  2576. wanzhu_obj_1.width = width
  2577. wanzhu_obj_1.height = height
  2578. wanzhu_obj_1.save()
  2579. cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now())
  2580. else:
  2581. wanzhu_obj = cm.WanzhuConsult.objects.create(
  2582. pid = pid,
  2583. reply_content = content,
  2584. user_id = 0,
  2585. player_id = 0,
  2586. reply_user_id = user_id
  2587. )
  2588. wanzhu_obj.width = width
  2589. wanzhu_obj.height = height
  2590. wanzhu_obj.save()
  2591. cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now())
  2592. #发送消息提醒
  2593. if cm.UserInfo.objects.filter(id=user_id).exists():
  2594. user = cm.UserInfo.objects.filter(id=user_id).first()
  2595. openid = user.openid
  2596. username = user.username
  2597. try:
  2598. send_consult_reply_message(openid,username)
  2599. except Exception as e:
  2600. print(e)
  2601. #发送app推送消息
  2602. title = u"顽主杯"
  2603. body = u"你收到一条顽主的消息"
  2604. params = {"type":"message","id":str(user_id)}
  2605. aliyunpush.push_notice_by_userid(user_id,title,body,params,"ios")
  2606. aliyunpush.push_notice_by_userid(user_id,title,body,params,"android")
  2607. def delete_user_info(request):
  2608. """
  2609. """
  2610. uid = request.user.get("id",0)
  2611. cm.UserInfo.objects.filter(id=uid).delete()
  2612. cm.Player.objects.filter(user_id=uid).delete()
  2613. #cm.PlayerRecord.objects.filter(user_id=uid).delete()
  2614. def get_random_bake_list(**kwargs):
  2615. """
  2616. """
  2617. baikes = list(cm.BaikeDetail.objects.all().values())
  2618. randomi = []
  2619. while len(randomi) < 5:
  2620. num = random.randint(0,len(baikes)-1)
  2621. if not num in randomi:
  2622. randomi.append(num)
  2623. rst = [baikes[x] for x in randomi]
  2624. return rst
  2625. def articles_top5_by_type(**kwargs):
  2626. """
  2627. """
  2628. cats = const.ARTICLE_TYPE_LIST
  2629. data = []
  2630. for cat in cats:
  2631. articles = list(cm.Article.objects.filter(category=cat).order_by("-id").values()[:5])
  2632. data.append({"category":cat,"articles":articles})
  2633. return data
  2634. def get_match_winlost_top5(**kwargs):
  2635. """
  2636. """
  2637. data = []
  2638. cur_match_id = ccc.get_cur_match().id
  2639. matchs = cm.Match.objects.filter(id__gte=8).order_by("-id")
  2640. for match in matchs:
  2641. match_id = match.id
  2642. match_name = match.name
  2643. end_time = match.end_time
  2644. if cur_match_id == match_id:
  2645. end_time = get_today_date()
  2646. records = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=end_time)
  2647. total_income_up = copy.copy(records)
  2648. total_income_up = total_income_up.order_by("-total_income")
  2649. total_income_up = list(total_income_up.values()[:5])
  2650. get_user_avatar(total_income_up)
  2651. total_income_down = copy.copy(records)
  2652. total_income_down = total_income_down.order_by("total_income")
  2653. total_income_down = list(total_income_down.values()[:5])
  2654. get_user_avatar(total_income_down)
  2655. records = list(records.values())
  2656. for item in records:
  2657. item["total_win"] = item["today_fund"] - item["init_fund"]
  2658. total_win_up = copy.copy(records)
  2659. total_win_up = sorted(total_win_up,key=lambda x:x["total_win"],reverse=True)
  2660. total_win_up = total_win_up[:5]
  2661. get_user_avatar(total_win_up)
  2662. total_win_down = copy.copy(records)
  2663. total_win_down = sorted(total_win_down,key=lambda x:x["total_win"])
  2664. total_win_down = total_win_down[:5]
  2665. get_user_avatar(total_win_down)
  2666. data.append({"match_id":match_id,"match_name":match_name,"total_income_up":total_income_up,"total_income_down":total_income_down,"total_win_up":total_win_up,"total_win_down":total_win_down})
  2667. if int(kwargs.get("new",0)) == 1:
  2668. break
  2669. return data
  2670. def get_user_avatar(records):
  2671. for item in records:
  2672. userinfo = get_user_info_actual(item["user_id"])
  2673. if userinfo:
  2674. item["avatar"] = userinfo.get("avatar")
  2675. else:
  2676. item["avatar"] = ""
  2677. def black_user(request):
  2678. """
  2679. """
  2680. qdata = request.json
  2681. user_id = request.user.get("id",0)
  2682. black_user_id = qdata.get("black_user_id")
  2683. cm.UserBlacks.objects.get_or_create(
  2684. user_id = user_id,
  2685. black_user_id = black_user_id
  2686. )
  2687. def delete_black_user(request):
  2688. """
  2689. """
  2690. qdata = request.json
  2691. user_id = request.user.get("id",0)
  2692. black_user_id = qdata.get("black_user_id")
  2693. cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=black_user_id).delete()
  2694. def get_user_black_user_list(request):
  2695. """
  2696. """
  2697. #user_id = 5709
  2698. user_id = request.user.get("id",0)
  2699. kwargs = request.json
  2700. qset = cm.UserBlacks.objects.filter(user_id=user_id)
  2701. page = int(kwargs.get("page",0))
  2702. page_size = int(kwargs.get("page_size",20))
  2703. if page and page_size:
  2704. total,qset = ccc.get_page_qset(qset,page,page_size)
  2705. else:
  2706. total = qset.count()
  2707. data = list(qset.values("black_user__id","black_user__username","black_user__avatar"))
  2708. datas = []
  2709. for item in data:
  2710. item['id'] = item["black_user__id"]
  2711. item['username'] = item["black_user__username"]
  2712. item['avatar'] = item["black_user__avatar"]
  2713. return total,data