controls.py 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374
  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. opmode_group = player.opmode_group
  578. zq = user.zq
  579. cw = user.cw
  580. df = user.df
  581. match = cm.Match.objects.filter(id=match_id).first()
  582. if player.match_status < 1:
  583. raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
  584. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  585. if not user_id in [9600,6209,5709]:
  586. if match.end_time < now_date:
  587. raise ce.TipException(u"该比赛已结束或您未参加此次比赛不能提交数据!")
  588. validdates = get_match_validdates(match_id)
  589. today_index = validdates.index(stock_date)
  590. yesterday_index = today_index -1 if today_index >=1 else 0
  591. yesterday_date = validdates[yesterday_index]
  592. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  593. match_id=match_id,user_id=user_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
  594. if yesterday:
  595. yesterday_fund = yesterday.today_fund
  596. yesterday_stock = yesterday.today_stock
  597. yesterday_stock_img = yesterday.today_stock_img
  598. yesterday_is_markt = yesterday.is_markt
  599. else:
  600. yesterday_fund = today_fund
  601. yesterday_stock = ""
  602. yesterday_stock_img = ""
  603. yesterday_is_markt = 0
  604. if kwargs.get("id"):
  605. if cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).count()==1:
  606. init_fund = today_fund
  607. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund)
  608. else:
  609. if not cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).exists():
  610. init_fund = today_fund
  611. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund)
  612. with transaction.atomic():
  613. #记录持股情况
  614. new_stock_list = []
  615. today_stock_list = json.loads(today_stock)
  616. for ts in today_stock_list:
  617. if ts["name"]:
  618. try:
  619. stock,flag = cm.Stock.objects.get_or_create(
  620. name = ts["name"]
  621. )
  622. stock_id = stock.id
  623. usobj,flag = cm.UserStock.objects.get_or_create(
  624. user_id = user_id,
  625. stock_id = stock_id,
  626. stock_name = ts["name"],
  627. player_id = player.id,
  628. stock_date = stock_date,
  629. match_group = match_group,
  630. opmode_group = opmode_group
  631. )
  632. if ts.get("fund"):
  633. usobj.fund = ts["fund"]
  634. usobj.save()
  635. ts["stock_id"] = stock_id
  636. new_stock_list.append(ts)
  637. except Exception as e:
  638. print(e)
  639. today_stock = json.dumps(new_stock_list)
  640. obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
  641. user_id=user_id,
  642. match_id=match_id,
  643. stock_date=stock_date)
  644. obj.init_fund = init_fund
  645. obj.yesterday_fund = yesterday_fund
  646. obj.yesterday_stock = yesterday_stock
  647. obj.yesterday_stock_img = yesterday_stock_img
  648. obj.today_fund = today_fund
  649. obj.today_stock = today_stock
  650. obj.today_stock_img = today_stock_img
  651. obj.username = username
  652. obj.usercode = usercode
  653. obj.match_group = match_group
  654. obj.opmode_group = opmode_group
  655. obj.is_markt = is_markt
  656. obj.yesterday_is_markt = yesterday_is_markt
  657. obj.zq = zq
  658. obj.cw = cw
  659. obj.df = df
  660. obj.experience = experience
  661. #计算今日收益和总收益
  662. if float(today_fund)>9999 or float(today_fund)<=0:
  663. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  664. #有资金出入
  665. if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists():
  666. fundinout = cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).first()
  667. fundin = fundinout.fundin
  668. fundout = fundinout.fundout
  669. today_income = 0.0
  670. total_income = 0.0
  671. #入资金
  672. if fundin > fundout:
  673. fundin = fundin - fundout
  674. if yesterday:
  675. today_income = (today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin)
  676. obj.yesterday_fund = obj.yesterday_fund + fundin
  677. else:
  678. today_income = 0.0
  679. obj.today_income = round(today_income,4)
  680. if flag:
  681. total_income = (today_fund-init_fund-fundin)/(init_fund+fundin)
  682. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=init_fund+fundin)
  683. obj.init_fund = init_fund + fundin
  684. else:
  685. total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
  686. obj.total_income = round(total_income,4)
  687. #出资金
  688. else:
  689. fundout = fundout - fundin
  690. if yesterday:
  691. today_income = (today_fund-(yesterday_fund-fundout))/float(yesterday_fund)
  692. obj.yesterday_fund = round(today_fund/(1+today_income),4)
  693. else:
  694. today_income = 0.0
  695. obj.today_income = round(today_income,4)
  696. if flag:
  697. total_income = (today_fund+fundout-init_fund)/init_fund if init_fund else 0.0
  698. cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=round(today_fund/(1+total_income),4))
  699. obj.init_fund = round(today_fund/(1+total_income),4)
  700. else:
  701. total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
  702. obj.total_income = round(total_income,4)
  703. if float(today_income)>0.4:
  704. raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
  705. if float(total_income)>8:
  706. raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
  707. else:
  708. today_income = (today_fund - yesterday_fund)/float(yesterday_fund) if yesterday_fund else 0.0
  709. total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
  710. if float(today_income)>0.4:
  711. raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
  712. if float(total_income)>8:
  713. raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
  714. obj.today_income = round(today_income,4)
  715. obj.total_income = round(total_income,4)
  716. if not flag:
  717. obj.ctime = datetime.datetime.now()
  718. obj.save()
  719. #更新group_rank
  720. #ccc.cache.lpush(settings.RANK_LIST,obj.id)
  721. ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(obj.match_id,obj.id))
  722. return obj.id
  723. obj = model.objects.create(**kwargs)
  724. return obj.id
  725. def update_model(cls,**kwargs):
  726. """
  727. """
  728. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  729. model = getattr(cm,model_name)
  730. id = kwargs.pop("id")
  731. rst = model.objects.filter(id=id).update(**kwargs)
  732. if model_name == "Match":
  733. for item in kwargs.get("groups").split(","):
  734. cm.MatchGroup.objects.get_or_create(match_id=obj.id,name=item)
  735. return rst
  736. def delete_model(cls,**kwargs):
  737. """
  738. """
  739. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  740. model = getattr(cm,model_name)
  741. ids = str(kwargs.get("id")).split(",")
  742. rst = model.objects.filter(id__in=ids).delete()
  743. if model_name == "Comments":
  744. cm.Comments.objects.filter(pid__in=ids).delete()
  745. return ids
  746. def get_search_list(cls,**kwargs):
  747. """
  748. """
  749. model_name = re.search(r'.*\.(\w+)SearchView',str(cls.__class__)).groups()[0]
  750. model = getattr(cm,model_name)
  751. qset = model.objects.all()
  752. if model_name == "Stock":
  753. if kwargs.get("name"):
  754. qset = qset.filter(Q(name__icontains=kwargs.get("name"))|Q(code__icontains=kwargs.get("name")))
  755. else:
  756. if kwargs.get("name"):
  757. qset = qset.filter(name__icontains=kwargs.get("name"))
  758. if model_name == "Player":
  759. data = list(qset.values("id","username"))
  760. if model_name == "Stock":
  761. qset = qset.filter(code__isnull=False)
  762. data = list(qset.values("id","name","code"))
  763. for item in data:
  764. if item["code"]:
  765. item["label"] = "%s(%s)" % (item["name"],item["code"])
  766. else:
  767. item["label"] = "%s" % item["name"]
  768. else:
  769. data = list(qset.values("id","name"))
  770. return data
  771. def get_detail_info(cls,**kwargs):
  772. """
  773. """
  774. model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
  775. model = getattr(cm,model_name)
  776. id = kwargs.get("id")
  777. rst = list(model.objects.filter(id=id).values())
  778. rst = rst[0] if rst else {}
  779. if model_name == "Article":
  780. rst["ctime"] = ccf.datetime_to_str(rst["ctime"],"%Y-%m-%d")
  781. if model_name == "Stock":
  782. rst["choiced"] = ccc.cache.get("%s_choices" % id)
  783. rst["user_num"] = ccc.cache.get("%s_choices" % id)
  784. if model_name == "UserArticleRelation":
  785. article_ids = rst["article_ids"].split(",")
  786. articles = list(cm.Article.objects.filter(id__in=article_ids).values())
  787. rst["articles"] = articles
  788. return rst
  789. #@ccc.cache_data()
  790. def get_record_info(rcid):
  791. """
  792. """
  793. rst = cm.PlayerRecord.objects.filter(id=rcid).values().first()
  794. if rst:
  795. rst["match_group"] = cm.MatchGroup.objects.filter(id=rst["match_group"]).first().name
  796. today_stock = json.loads(rst["today_stock"]) if rst["today_stock"] else []
  797. today_stock = filter(lambda x:x["fund"] and x["name"],today_stock if today_stock else [])
  798. rst["today_stock"] = today_stock
  799. today_stock_img = json.loads(rst["today_stock_img"]) if rst["today_stock_img"] else []
  800. rst["today_stock_img"] = today_stock_img
  801. yesterday_stock = json.loads(rst["yesterday_stock"]) if rst["yesterday_stock"] else []
  802. yesterday_stock = filter(lambda x:x["fund"] and x["name"],yesterday_stock if yesterday_stock else [])
  803. rst["yesterday_stock"] = yesterday_stock
  804. yesterday_stock_img = json.loads(rst["yesterday_stock_img"]) if rst["yesterday_stock_img"] else []
  805. rst["yesterday_stock_img"] = yesterday_stock_img
  806. rst["today_income"] = "{}%".format(rst["today_income"]*100)
  807. rst["total_income"] = "{}%".format(rst["total_income"]*100)
  808. return rst
  809. def get_list_info(cls,**kwargs):
  810. """
  811. """
  812. model_name = re.search(r'.*\.(\w+)ListView',str(cls.__class__)).groups()[0]
  813. model = getattr(cm,model_name)
  814. qset = model.objects.all()
  815. if kwargs.get("name"):
  816. qset = qset.filter(name__icontains=kwargs.get("name"))
  817. if model_name == "UserInfo":
  818. if kwargs.get("username"):
  819. qset = qset.filter(username__icontains=kwargs.get("username"))
  820. if kwargs.get("usercode"):
  821. qset = qset.filter(usercode=kwargs.get("usercode"))
  822. if model_name == "StockComments":
  823. if kwargs.get("stock_id"):
  824. qset = qset.filter(stock_id=kwargs.get("stock_id"))
  825. if model_name == "UserArticleRelation":
  826. data = list(qset.order_by("-id").values("id","user_id","user_name","user_avatar"))
  827. else:
  828. data = list(qset.order_by("-id").values())
  829. page = int(kwargs.get("page",0))
  830. page_size = int(kwargs.get("page_size",20))
  831. if page and page_size:
  832. total,data = ccf.get_page_list(data,page,page_size)
  833. if model_name == "Player":
  834. for item in data:
  835. user = cm.UserInfo.objects.filter(id=item["user_id"]).first()
  836. match = cm.Match.objects.filter(id=item["match_id"]).first()
  837. item["username"] = user.username
  838. item["usercode"] = user.usercode
  839. item["match_name"] = match.name if match else ""
  840. return (total,data)
  841. else:
  842. return len(data),data
  843. return rst
  844. def add_player_record_single(**kwargs):
  845. """用户单独上传数据
  846. """
  847. return None
  848. now = datetime.datetime.now()
  849. if now.weekday() in [5,6] or now.strftime("%Y-%m-%d") in MISS_DATES:
  850. raise ce.TipException(u"今日不能提交数据!")
  851. now_time = datetime.datetime.now().strftime("%H:%S")
  852. if now_time<"15:00" or now_time > "23:50":
  853. raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
  854. usercode = kwargs.get("usercode")
  855. match_id = kwargs.get("match_id")
  856. if not cm.Player.objects.filter(usercode=usercode,match_id=match_id).exists():
  857. raise ce.TipException(u"用户代码错误")
  858. stock_date = kwargs.get("stock_date")
  859. #stock_date = "2022-04-26"
  860. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  861. today_stock = json.dumps(kwargs.get("today_stock"))
  862. today_stock_img = json.dumps(kwargs.get("today_stock_img"))
  863. today_fund = float(kwargs.get("today_fund"))
  864. is_markt = int(kwargs.get("is_markt",0))
  865. if int(today_fund)>9999 or int(today_fund)<0:
  866. raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  867. player = cm.Player.objects.filter(usercode=usercode,match_id=match_id).first()
  868. #if player.fund <=0 :
  869. # raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
  870. player_id = player.id
  871. user_id = player.user_id
  872. init_fund = player.fund
  873. user = cm.UserInfo.objects.filter(id=user_id).first()
  874. username = user.username
  875. usercode = user.usercode
  876. match_group = player.match_group
  877. match = cm.Match.objects.filter(id=match_id).first()
  878. if player.match_status < 1:
  879. raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
  880. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  881. if match.end_time < now_date:
  882. raise ce.TipException(u"该比赛已结束!")
  883. #yesterday = cm.PlayerRecord.objects.filter(
  884. # match_id=match_id,player_id=player_id).order_by("-id").first()
  885. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  886. match_id=match_id,player_id=player_id).order_by("-stock_date").first()
  887. if yesterday:
  888. yesterday_fund = yesterday.today_fund
  889. yesterday_stock = yesterday.today_stock
  890. yesterday_stock_img = yesterday.today_stock_img
  891. else:
  892. #yesterday_fund = init_fund
  893. yesterday_fund = today_fund
  894. init_fund = today_fund
  895. yesterday_stock = ""
  896. yesterday_stock_img = ""
  897. cm.Player.objects.filter(id=player_id).update(fund=today_fund)
  898. #记录持股情况
  899. new_stock_list = []
  900. today_stock_list = json.loads(today_stock)
  901. for ts in today_stock_list:
  902. if ts["name"]:
  903. stock,flag = cm.Stock.objects.get_or_create(
  904. name = ts["stock"]
  905. )
  906. stock_id = stock.id
  907. usobj,flag = cm.UserStock.objects.get_or_create(
  908. player_id = player_id,
  909. stock_id = stock_id,
  910. stock_name = ts["name"],
  911. stock_date = stock_date
  912. )
  913. ts["stock_id"] = stock_id
  914. new_stock_list.append(ts)
  915. today_stock = json.dumps(new_stock_list)
  916. obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
  917. player_id=player_id,
  918. match_id=match_id,
  919. stock_date=stock_date)
  920. obj.init_fund = init_fund
  921. obj.yesterday_fund = yesterday_fund
  922. obj.yesterday_stock = yesterday_stock
  923. obj.yesterday_stock_img = yesterday_stock_img
  924. obj.today_fund = today_fund
  925. obj.today_stock = today_stock
  926. obj.today_stock_img = today_stock_img
  927. obj.user_id = user_id
  928. obj.username = username
  929. obj.usercode = usercode
  930. obj.match_group = match_group
  931. obj.is_markt = is_markt
  932. #计算今日和昨日盈亏
  933. today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
  934. total_income = (today_fund - init_fund)/float(init_fund)
  935. #if int(today_fund)>9999 or int(today_fund)<0:
  936. # raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
  937. if int(today_income)>2:
  938. raise ce.TipException(u"数据错误,今日盈利已超过2倍,请仔细核对数据!")
  939. obj.today_income = round(today_income,4)
  940. obj.total_income = round(total_income,4)
  941. if not flag:
  942. obj.ctime = datetime.datetime.now()
  943. obj.save()
  944. #更新股票持股人数
  945. for stock in new_stock_list:
  946. cm.Stock.objects.filter(id=stock["id"]).update(user_num=F("user_num")+1)
  947. #更新group_rank
  948. #update_group_rank(match_id,match_group,obj.stock_date)
  949. ccc.cache.lpush(settings.RANK_LIST,obj.id)
  950. return obj.id
  951. def get_single_match_info(match_id):
  952. """
  953. """
  954. if not match_id:
  955. match = cm.Match.objects.all().order_by("-id").values().first()
  956. else:
  957. match = cm.Match.objects.filter(id=match_id).values().first()
  958. now_date = datetime.datetime.now().strftime("%Y-%m-%d")
  959. return now_date,match
  960. def get_cur_record(request):
  961. """
  962. """
  963. user_id = request.user.get("id")
  964. match_id = ccc.get_cur_match().id
  965. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  966. 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")
  967. data = qset.values().first() if qset else {}
  968. if data:
  969. data["today_stock_img"] = json.loads(data["today_stock_img"]) if data["today_stock_img"] else []
  970. data["today_stock"] = json.loads(data["today_stock"]) if data["today_stock"] else []
  971. return data
  972. def follow_player(**kwargs):
  973. """
  974. """
  975. user_id = kwargs.get("user_id")
  976. follow_id = kwargs.get("follow_id")
  977. if kwargs.get("action") == "cancel":
  978. cm.UserFollows.objects.filter(user_id=user_id,follow_id=follow_id).delete()
  979. return True
  980. else:
  981. obj,flag = cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=follow_id)
  982. return obj.id
  983. def calc_win_rate(player_id,match_id):
  984. """计算胜率
  985. """
  986. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=player_id)
  987. win_rate = qset.filter(today_income__gt=0).count()/float(qset.count()) if qset else 0.0
  988. win_rate = round(win_rate,3)
  989. win_rate = "{}%".format(win_rate*100)
  990. return win_rate
  991. def get_user_follower(request):
  992. """获取用户列表
  993. """
  994. user_id = request.user.get("id")
  995. match_id = ccc.get_cur_match().id
  996. qdata = request.json
  997. if qdata.get("user_id"):
  998. user_id = int(qdata.get("user_id"))
  999. _today = get_today_date()
  1000. data = []
  1001. qset = cm.UserFollows.objects.filter(follow_id=user_id)
  1002. follow_ids = list(qset.values_list("user_id",flat=True))
  1003. userset = cm.UserInfo.objects.filter(id__in=follow_ids)
  1004. data = list(userset.values())
  1005. page = int(qdata.get("page",1))
  1006. page_size = int(qdata.get("page_size",20))
  1007. if page and page_size:
  1008. total,data = ccf.get_page_list(data,page,page_size)
  1009. return total,data
  1010. else:
  1011. return len(data),data
  1012. #
  1013. for player_id in follow_ids:
  1014. latest_key = "PLAYER_LATEST_%d"%player_id
  1015. _match_id = ccc.cache.hget(latest_key,"match_id")
  1016. _today = ccc.cache.hget(latest_key,"stock_date")
  1017. _match_group = ccc.cache.hget(latest_key,"match_group")
  1018. today_record = ccc.get_today_record(player_id,_match_id,_match_group,_today)
  1019. if today_record:
  1020. data.append(today_record)
  1021. #data.append(today_record)
  1022. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  1023. _today = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"stock_date")
  1024. cur_user_latest = "PLAYER_LATEST_%d" % user_id
  1025. _match_group = ccc.cache.hget(cur_user_latest,"match_group")
  1026. cur_today_record = ccc.get_today_record(user_id,match_id,_match_group,_today)
  1027. if cur_today_record:
  1028. data.insert(0,cur_today_record)
  1029. page = int(qdata.get("page",1))
  1030. page_size = int(qdata.get("page_size",20))
  1031. if page and page_size:
  1032. total,data = ccf.get_page_list(data,page,page_size)
  1033. for item in data:
  1034. if item:
  1035. today_stock = json.loads(item["today_stock"])
  1036. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  1037. item["today_stock"] = today_stock
  1038. item["today_stock_img"] = json.loads(item["today_stock_img"])
  1039. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
  1040. if win_rate:
  1041. item["win_rate"] = str(float(win_rate)*100)+"%"
  1042. else:
  1043. item["win_rate"] = "0.0%"
  1044. item["today_income"] = "{}%".format(item["today_income"]*100)
  1045. item["total_income"] = "{}%".format(item["total_income"]*100)
  1046. return total,data
  1047. else:
  1048. return len(data),data
  1049. def get_user_follows(request):
  1050. """获取用户关注的选手列表
  1051. """
  1052. user_id = request.user.get("id",0)
  1053. qdata = request.json
  1054. if qdata.get("user_id"):
  1055. user_id = qdata.get("user_id")
  1056. qset = cm.UserFollows.objects.filter(user_id=user_id)
  1057. follow_ids = list(qset.values_list("follow_id",flat=True))
  1058. userset = cm.UserInfo.objects.filter(id__in=follow_ids)
  1059. data = list(userset.values())
  1060. page = int(qdata.get("page",1))
  1061. page_size = int(qdata.get("page_size",20))
  1062. if page and page_size:
  1063. total,data = ccf.get_page_list(data,page,page_size)
  1064. return total,data
  1065. else:
  1066. return len(data),data
  1067. today = get_today_date()
  1068. _today = today
  1069. data = []
  1070. for user_id in follow_ids:
  1071. latest_key = "PLAYER_LATEST_%d"%user_id
  1072. _match_id = ccc.cache.hget(latest_key,"match_id")
  1073. _today = ccc.cache.hget(latest_key,"stock_date")
  1074. _match_group = ccc.cache.hget(latest_key,"match_group")
  1075. today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
  1076. if today_record:
  1077. today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
  1078. today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
  1079. data.append(today_record)
  1080. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  1081. page = int(qdata.get("page",1))
  1082. page_size = int(qdata.get("page_size",20))
  1083. if page and page_size:
  1084. total,data = ccf.get_page_list(data,page,page_size)
  1085. for item in data:
  1086. if item:
  1087. try:
  1088. user_id = item["user_id"]
  1089. latest_key = "PLAYER_LATEST_%d"%user_id
  1090. today_stock = json.loads(item["today_stock"])
  1091. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  1092. item["today_stock"] = today_stock
  1093. item["today_stock_img"] = json.loads(item["today_stock_img"])
  1094. win_rate = ccc.cache.hget(latest_key,"win_rate")
  1095. if win_rate:
  1096. item["win_rate"] = str(float(win_rate)*100)+"%"
  1097. else:
  1098. item["win_rate"] = "0.0%"
  1099. item["today_income"] = "{}%".format(item["today_income"]*100)
  1100. item["total_income"] = "{}%".format(item["total_income"]*100)
  1101. item["zans_count"] = item.get("zans",0)
  1102. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  1103. except Exception as e:
  1104. print(e)
  1105. return total,data
  1106. else:
  1107. return len(data),data
  1108. def get_hot_stock_rank(**kwargs):
  1109. """
  1110. """
  1111. data = {
  1112. "hot_buy":[
  1113. {"stock_name":u"创业黑马","count":12}
  1114. ],
  1115. "hot_sell":[
  1116. {"stock_name":u"创业黑马","count":12}
  1117. ]
  1118. }
  1119. return data
  1120. #@ccc.cache_data()
  1121. def get_stock_info(stock_id):
  1122. """
  1123. """
  1124. stock = cm.Stock.objects.filter(id=stock_id).values().first()
  1125. stock["choiced"] = 1
  1126. nbc = cm.StockComments.objects.filter(stock_id=stock_id).order_by("-id").values().first()
  1127. if nbc:
  1128. stock["last_nb_comments"] = nbc
  1129. return stock
  1130. def get_hot_stock_buy(**kwargs):
  1131. """
  1132. """
  1133. stock_date = kwargs.get("stock_date")
  1134. qset = cm.UserStock.objects.filter(stock_date=stock_date)
  1135. if kwargs.get("name"):
  1136. qset = cm.UserStock.objects.filter(stock_name__icontains=kwargs.get("name"),stock_date=stock_date)
  1137. qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-count")
  1138. data = []
  1139. for q in qset:
  1140. stock_id = q["stock_id"]
  1141. count = q["count"]
  1142. stock_name = q.get("stock_name")
  1143. total_fund = q["total_fund"]
  1144. comments_count = ccc.cache.get("%s_comments" % stock_id)
  1145. choice_count = ccc.cache.get("%s_choices" % stock_id)
  1146. comments_count = comments_count if comments_count else 0
  1147. choice_count = choice_count if choice_count else 0
  1148. data.append({"stock_name":stock_name,"id":stock_id,"count":count,"comments_count":comments_count,"choice_count":choice_count,"total_fund":total_fund})
  1149. page = int(kwargs.get("page",1))
  1150. page_size = int(kwargs.get("page_size",20))
  1151. if page and page_size:
  1152. total,data = ccf.get_page_list(data,page,page_size)
  1153. return total,data
  1154. else:
  1155. return len(data),data
  1156. return data
  1157. def get_hot_follow(**kwargs):
  1158. """
  1159. """
  1160. stock_date = kwargs.get("stock_date")
  1161. match_id = kwargs.get("match_id")
  1162. if not match_id:
  1163. match_id = ccc.get_cur_match().id
  1164. #player_ids = list(cm.Player.objects.filter(match_id=cur_match_id,match_status=1).values_list("id",flat=True))
  1165. player_ids = list(cm.Player.objects.filter(match_id=match_id).values_list("user_id",flat=True))
  1166. qset = cm.UserFollows.objects.filter(follow_id__in=player_ids)
  1167. qset = qset.values("follow_id").annotate(count=Count("follow_id")).order_by("-count")
  1168. data = []
  1169. for q in qset:
  1170. player_id = q["follow_id"]
  1171. count = q["count"]
  1172. today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1173. match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
  1174. match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
  1175. badest_income = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"badest_income")
  1176. today_record = get_today_record(player_id,match_id,match_group,today)
  1177. if today_record:
  1178. userinfo = get_user_info(today_record["user_id"])
  1179. user_id = today_record["user_id"]
  1180. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"win_rate")
  1181. try:
  1182. win_rate = str(float(win_rate)*100)+"%"
  1183. except:
  1184. pass
  1185. if userinfo:
  1186. data.append(
  1187. {
  1188. "player_name":userinfo.get("username"),
  1189. "count":count,
  1190. "id":player_id,
  1191. "user_id":user_id,
  1192. "today_fund":today_record["today_fund"],
  1193. "total_income":"{}%".format(today_record["total_income"]*100),
  1194. "today_income":"{}%".format(today_record["today_income"]*100),
  1195. "badest_income":"{}%".format(badest_income*100) if badest_income else "0.0%",
  1196. "style":userinfo.get("style"),
  1197. "badge":userinfo.get("badge"),
  1198. "match_id":match_id,
  1199. "win_rate":win_rate
  1200. }
  1201. )
  1202. if kwargs.get("name"):
  1203. data = filter(lambda x:kwargs.get("name") in x["player_name"],data)
  1204. page = int(kwargs.get("page",1))
  1205. page_size = int(kwargs.get("page_size",20))
  1206. if page and page_size:
  1207. total,data = ccf.get_page_list(data,page,page_size)
  1208. return total,data
  1209. else:
  1210. return len(data),data
  1211. return data
  1212. def get_hot_stock_sell(**kwargs):
  1213. """
  1214. """
  1215. stock_date = kwargs.get("stock_date")
  1216. stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
  1217. yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  1218. ##昨天所有股票
  1219. #yes_stock_ids = list(cm.UserStock.objects.filter(stock_date=yesterday).values_list("stock_id",flat=True))
  1220. #yes_stock_ids = list(set(yes_stock_ids))
  1221. #data = []
  1222. #for ysi in yes_stock_ids:
  1223. # yes_count = cm.UserStock.objects.filter(stock_date=yesterday,stock_id=ysi).count()
  1224. # td_count = cm.UserStock.objects.filter(stock_date=stock_date,stock_id=ysi).count()
  1225. # if td_count < yes_count:
  1226. # stock_name = cm.Stock.objects.filter(id=ysi).first().name
  1227. # data.append({"stock_name":stock_name,"count":yes_count-td_count,"id":ysi})
  1228. qset = cm.HotStockSellCount.objects.filter(stock_date=stock_date)
  1229. if kwargs.get("name"):
  1230. qset = qset.filter(stock_name__icontains=kwargs.get("name"))
  1231. qset = qset.order_by("-count")
  1232. data = list(qset.values("stock_name","stock_id","count"))
  1233. for item in data:
  1234. item["id"] = item["stock_id"]
  1235. page = int(kwargs.get("page",0))
  1236. page_size = int(kwargs.get("page_size",20))
  1237. if page and page_size:
  1238. total,data = ccf.get_page_list(data,page,page_size)
  1239. return total,data
  1240. else:
  1241. return len(data),data
  1242. return data
  1243. def get_stock_info(_id):
  1244. """
  1245. """
  1246. data = cm.Stock.objects.filter(id=_id).values().first()
  1247. nbc = cm.StockComments.objects.filter(stock_id=_id).order_by("-id").values().first()
  1248. if nbc:
  1249. data["last_nb_comments"] = nbc
  1250. return data
  1251. def get_hot_stock_sell_players(**kwargs):
  1252. """
  1253. """
  1254. _id = kwargs.get("id")
  1255. stock_date = kwargs.get("stock_date")
  1256. stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
  1257. yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
  1258. #昨天持股选手
  1259. yes_players = list(cm.UserStock.objects.filter(stock_date=yesterday,stock_id=_id).values_list("player_id",flat=True))
  1260. td_players = list(cm.UserStock.objects.filter(stock_date=stock_date,stock_id=_id).values_list("player_id",flat=True))
  1261. sell_players = list(set(yes_players)-set(td_players))
  1262. data = []
  1263. for player_id in sell_players:
  1264. player = cm.Player.objects.filter(id=player_id).first()
  1265. if player:
  1266. match_id = player.match_id
  1267. match_group = player.match_group
  1268. today_record = get_today_record(player_id,match_id,match_group,stock_date)
  1269. if today_record:
  1270. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  1271. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  1272. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  1273. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  1274. data.append(today_record)
  1275. data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
  1276. page = int(kwargs.get("page",0))
  1277. page_size = int(kwargs.get("page_size",20))
  1278. if page and page_size:
  1279. total,data = ccf.get_page_list(data,page,page_size)
  1280. return total,data
  1281. else:
  1282. return len(data),data
  1283. return data
  1284. def get_win_rate_rank(request):
  1285. """
  1286. """
  1287. player_id = request.player.id
  1288. match_id = request.player.match_id
  1289. match_group = request.player.match_group
  1290. kwargs = request.json
  1291. match_id = ccc.get_cur_match().id
  1292. qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lt=5,match_status=1).order_by("-win_rate")
  1293. data = list(qset.values())
  1294. page = int(kwargs.get("page",1))
  1295. page_size = int(kwargs.get("page_size",20))
  1296. if page and page_size:
  1297. total,data = ccf.get_page_list(data,page,page_size)
  1298. else:
  1299. total = len(data)
  1300. for item in data:
  1301. item["win_rate"] = "{}%".format(item["win_rate"]*100)
  1302. item["badest_income"] = "{}%".format(item["badest_income"]*100)
  1303. item["total_income"] = "{}%".format(item["total_income"]*100)
  1304. userinfo = get_user_info(item["user_id"])
  1305. if userinfo:
  1306. item["badge"] = userinfo.get("badge")
  1307. item["style"] = userinfo.get("style")
  1308. item["username"] = userinfo.get("username")
  1309. return total,data
  1310. def get_defend_rank(request):
  1311. """
  1312. """
  1313. player_id = request.player.id
  1314. match_id = request.player.match_id
  1315. match_group = request.player.match_group
  1316. kwargs = request.json
  1317. qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lte=5,match_status=1).order_by("-badest_income")
  1318. data = list(qset.values())
  1319. #data = []
  1320. #for item in datas:
  1321. # player = cm.Player.objects.filter(id=item["player_id"]).first()
  1322. # item["match_status"] = player.match_status if player else -1
  1323. # if item["match_status"] > -1:
  1324. # data.append(item)
  1325. page = int(kwargs.get("page",1))
  1326. page_size = int(kwargs.get("page_size",20))
  1327. if page and page_size:
  1328. total,data = ccf.get_page_list(data,page,page_size)
  1329. else:
  1330. total = len(data)
  1331. for item in data:
  1332. item["win_rate"] = "{}%".format(item["win_rate"]*100)
  1333. item["badest_income"] = "{}%".format(item["badest_income"]*100)
  1334. item["total_income"] = "{}%".format(item["total_income"]*100)
  1335. userinfo = get_user_info(item["user_id"])
  1336. if userinfo:
  1337. item["badge"] = userinfo.get("badge")
  1338. item["style"] = userinfo.get("style")
  1339. item["username"] = userinfo.get("username")
  1340. return total,data
  1341. def get_champion_articles_list(request):
  1342. """
  1343. """
  1344. kwargs = request.json
  1345. _type = kwargs.get("type")
  1346. isbanner = kwargs.get("isbanner")
  1347. category = kwargs.get("category")
  1348. qset = cm.Article.objects.filter(status=2).exclude(type="notice").order_by("-id")
  1349. if _type:
  1350. qset = qset.filter(type=_type)
  1351. if isbanner:
  1352. qset = qset.filter(isbanner=isbanner)
  1353. if category:
  1354. qset = qset.filter(category=category)
  1355. page = int(kwargs.get("page",0))
  1356. page_size = int(kwargs.get("page_size",20))
  1357. if page and page_size:
  1358. total,qset = ccc.get_page_qset(qset,page,page_size)
  1359. else:
  1360. total = qset.count()
  1361. data = list(qset.values("name","ctime","id","img"))
  1362. for item in data:
  1363. item["ctime"] = ccf.datetime_to_str(item["ctime"],"%Y-%m-%d")
  1364. return total,data
  1365. def get_wanzhu_comment(**kwargs):
  1366. """
  1367. """
  1368. match_id = kwargs.get("match_id")
  1369. group_id = kwargs.get("group_id")
  1370. today = get_today_date()
  1371. players = get_match_group_players(match_id,group_id)
  1372. new_players = []
  1373. for player in players:
  1374. user_id = player["user_id"]
  1375. user = get_user_info(user_id)
  1376. username = user["username"] if user else ""
  1377. player_id = player["id"]
  1378. match_group = group_id
  1379. today_record = get_today_record(player_id,match_id,int(match_group),today)
  1380. if today_record and today_record.get("wanzhu_comment"):
  1381. player.update(today_record)
  1382. player["username"] = username
  1383. player["total_income"] = "{}%".format(player["total_income"]*100)
  1384. player["fund"] = round(player["fund"],4)
  1385. player["init_fund"] = round(player["init_fund"],4)
  1386. player["today_fund"] = round(player["today_fund"],4)
  1387. player["today_stock"] = json.loads(player["today_stock"]) if player["today_stock"] else []
  1388. new_players.append(player)
  1389. new_players = sorted(new_players,key=lambda x:x["group_rank"])
  1390. data = new_players
  1391. page = int(kwargs.get("page",0))
  1392. page_size = int(kwargs.get("page_size",20))
  1393. if page and page_size:
  1394. total,data = ccf.get_page_list(data,page,page_size)
  1395. else:
  1396. total = len(data)
  1397. return total,data
  1398. def get_enum_list(request):
  1399. """
  1400. """
  1401. data = {
  1402. "zq":[
  1403. u"短线博弈",
  1404. u"长线价投",
  1405. u"长短兼备"
  1406. ],
  1407. "cw":[
  1408. u"分仓开超市",
  1409. u"重仓押注",
  1410. u"全仓单钓",
  1411. u"融资加倍"
  1412. ],
  1413. "df":[
  1414. u"低吸",
  1415. u"半路",
  1416. u"首板",
  1417. u"接力",
  1418. u"撬板",
  1419. u"T加0",
  1420. u"隔夜卖",
  1421. u"格局锁仓",
  1422. u"核按钮"
  1423. ],
  1424. "pz":[
  1425. u"10厘米",
  1426. u"20厘米",
  1427. u"30厘米",
  1428. u"N/C新股",
  1429. u"次新股",
  1430. u"可转债",
  1431. u"港股",
  1432. u"基金",
  1433. u"逆回购"
  1434. ]
  1435. }
  1436. return data
  1437. def get_player_list(**kwargs):
  1438. """选手列表
  1439. """
  1440. match_id = kwargs.get("match_id")
  1441. today = get_today_date()
  1442. #qset = cm.Player.objects.filter(match_id=match_id,match_status=1)
  1443. qset = cm.Player.objects.filter(match_status=1)
  1444. if kwargs.get("name"):
  1445. qset = qset.filter(username__icontains=kwargs.get("name"))
  1446. qset = qset.values("username").distinct().order_by("-id")
  1447. page = int(kwargs.get("page",0))
  1448. page_size = int(kwargs.get("page_size",20))
  1449. if page and page_size:
  1450. total,qset = ccc.get_page_qset(qset,page,page_size)
  1451. else:
  1452. total = qset.count()
  1453. data = list(qset.values())
  1454. for item in data:
  1455. #print(item)
  1456. match_id = item["match_id"]
  1457. match_group = item["match_group"]
  1458. user_id = item["user_id"]
  1459. player_id = item["id"]
  1460. #user = cm.UserInfo.objects.filter(id=user_id).first()
  1461. today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
  1462. match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
  1463. match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
  1464. today_record = get_today_record(player_id,match_id,match_group,today)
  1465. if today_record:
  1466. today_record.pop("id")
  1467. item.update(today_record)
  1468. user_info = get_user_info(user_id)
  1469. if user_info:
  1470. user_info.pop("id")
  1471. item.update(user_info)
  1472. if item.get("today_income"):
  1473. item["today_income"] = "{}%".format(item["today_income"]*100)
  1474. item["total_income"] = "{}%".format(item["total_income"]*100)
  1475. if kwargs.get("zq"):
  1476. data = filter(lambda x:kwargs.get("zq") == x.get("zq"),data)
  1477. if kwargs.get("cw"):
  1478. data = filter(lambda x:kwargs.get("cw") == x.get("cw"),data)
  1479. if kwargs.get("df"):
  1480. data = filter(lambda x:kwargs.get("df") == x.get("df"),data)
  1481. return total,data
  1482. def get_mine_style(request):
  1483. """
  1484. """
  1485. user = request.user
  1486. #player = request.player
  1487. user = cm.UserInfo.objects.filter(id=user["id"]).first()
  1488. match_id = ccc.get_cur_match().id
  1489. player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first()
  1490. data = {
  1491. "zq":user.zq,
  1492. "cw":user.cw,
  1493. "df":user.df,
  1494. "pz":user.pz,
  1495. "join_time":user.join_time,
  1496. "username":user.username,
  1497. "account_img":user.account_img,
  1498. "avatar":user.avatar
  1499. }
  1500. if player:
  1501. data["is_player"] = 1
  1502. data["init_fund"] = player.fund if player.fund else 0
  1503. else:
  1504. data["is_player"] = 0
  1505. data["init_fund"] = None
  1506. return data
  1507. def update_user_style(**kwargs):
  1508. """
  1509. """
  1510. user_id = kwargs.pop("user_id")
  1511. #player_id = kwargs.pop("player_id")
  1512. if kwargs.get("init_fund"):
  1513. init_fund = kwargs.pop("init_fund")
  1514. try:
  1515. init_fund = kwargs.pop("init_fund")
  1516. except Exception as e:
  1517. print(e)
  1518. #avatar = kwargs.pop("avatar")
  1519. cm.UserInfo.objects.filter(id=user_id).update(**kwargs)
  1520. #if player_id and init_fund:
  1521. # cm.Player.objects.filter(id=player_id).update(fund=init_fund)
  1522. if kwargs.get("username"):
  1523. cm.Player.objects.filter(user_id=user_id).update(username=kwargs.get("username"))
  1524. match_id = ccc.get_cur_match().id
  1525. upset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id)
  1526. upset.update(username=kwargs.get("username"))
  1527. record_ids = list(upset.values_list("id",flat=True))
  1528. for _id in record_ids:
  1529. ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(match_id,_id))
  1530. if kwargs.get("avatar"):
  1531. cm.UserInfo.objects.filter(id=user_id).update(avatar=kwargs.get("avatar"))
  1532. ccc.cache.delete("cdata_get_user_info_(%sL,)"%user_id)
  1533. return True
  1534. def get_stock_players(**kwargs):
  1535. """
  1536. """
  1537. stock_id = kwargs.get("stock_id")
  1538. stock_date = kwargs.get("stock_date",get_today_date())
  1539. data = []
  1540. user_stocks = cm.UserStock.objects.filter(stock_id=stock_id,stock_date=stock_date)
  1541. for us in user_stocks:
  1542. player_id = us.player_id
  1543. player = cm.Player.objects.filter(id=player_id).first()
  1544. if player:
  1545. match_id = player.match_id
  1546. match_group = player.match_group
  1547. user_id = player.user_id
  1548. if stock_date:
  1549. today_record = get_today_record(user_id,match_id,match_group,stock_date)
  1550. else:
  1551. today_record = get_today_record(user_id,match_id,match_group,us.stock_date)
  1552. if today_record:
  1553. today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
  1554. today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
  1555. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  1556. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  1557. data.append(today_record)
  1558. data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
  1559. #分页
  1560. page = int(kwargs.get("page",0))
  1561. page_size = int(kwargs.get("page_size",20))
  1562. if page and page_size:
  1563. total,data = ccf.get_page_list(data,page,page_size)
  1564. else:
  1565. total = len(data)
  1566. #return total,data
  1567. #return data
  1568. if kwargs.get("v3"):
  1569. return total,data
  1570. else:
  1571. return data
  1572. def update_user_fund(**kwargs):
  1573. """
  1574. """
  1575. user_id = kwargs.pop("user_id")
  1576. player_id = kwargs.pop("player_id")
  1577. init_fund = kwargs.pop("init_fund")
  1578. if player_id and init_fund:
  1579. cm.Player.objects.filter(id=player_id).update(fund=init_fund)
  1580. return True
  1581. def get_player_match_calendar(**kwargs):
  1582. """
  1583. """
  1584. match_id = kwargs.get("match_id")
  1585. month = kwargs.get("month")
  1586. user_id = kwargs.get("user_id")
  1587. week,eday = calendar.monthrange(int(month.split("-")[0]),int(month.split("-")[1]))
  1588. sday = "01"
  1589. eday = str(eday).zfill(2)
  1590. sdate = month + "-" + sday
  1591. edate = month + "-" + eday
  1592. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id)\
  1593. .filter(stock_date__gte=sdate,stock_date__lte=edate)
  1594. data = list(qset.values())
  1595. dct = {}
  1596. for item in data:
  1597. item["today_income"] = "{}%".format(item["today_income"]*100)
  1598. #dct[item["stock_date"]] = item["today_income"]
  1599. dct[item["stock_date"]] = [item["today_income"],item["id"]]
  1600. newdata = []
  1601. for i in range(1,int(eday)+1):
  1602. stock_date = month + "-" + str(i).zfill(2)
  1603. today_tpl = dct.get(stock_date,[])
  1604. today_income = today_tpl[0] if today_tpl else None
  1605. record_id = today_tpl[1] if today_tpl else None
  1606. newdata.append({
  1607. "stock_date":stock_date,
  1608. "today_income":today_income,
  1609. "record_id":record_id
  1610. })
  1611. return newdata
  1612. def get_all_match(request):
  1613. """
  1614. """
  1615. now = datetime.datetime.now().strftime("%Y-%m-%d")
  1616. #qset = cm.Match.objects.filter(start_time__lte=now).order_by("id")
  1617. qset = cm.Match.objects.filter(match_status__in=[3,4]).order_by("-id")
  1618. data = list(qset.values())
  1619. for item in data:
  1620. valid_dates = json.loads(item["valid_dates"]) if item["valid_dates"] else []
  1621. valid_dates.sort()
  1622. item["valid_dates"] = valid_dates
  1623. return data
  1624. def get_default_date(**kwargs):
  1625. """
  1626. """
  1627. match_id = kwargs.get("match_id")
  1628. if not match_id:
  1629. match_id = ccc.get_cur_match().id
  1630. record = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).order_by("-stock_date").first()
  1631. if record:
  1632. return record.stock_date
  1633. else:
  1634. return get_today_date()
  1635. @ccc.cache_data()
  1636. def get_stock_search(**kwargs):
  1637. """
  1638. """
  1639. qset = cm.Stock.objects.all()
  1640. data = list(qset.values("id","name","code"))
  1641. for item in data:
  1642. if item["code"]:
  1643. item["label"] = "%s(%s)" % (item["name"],item["code"])
  1644. else:
  1645. item["label"] = "%s" % item["name"]
  1646. return data
  1647. def get_mine_latest(request):
  1648. """
  1649. """
  1650. try:
  1651. user_id = request.user.get("id")
  1652. match_id = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_id")
  1653. match_group = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_group")
  1654. _today = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"stock_date")
  1655. if _today:
  1656. rst = ccc.get_today_record(int(user_id),int(match_id),int(match_group),_today)
  1657. if rst:
  1658. rst["today_income_fund"] = round((rst["today_fund"] - rst["yesterday_fund"])*10000,2) if rst["yesterday_fund"] else 0.00
  1659. rst["today_income"] = "{}%".format(rst["today_income"]*100)
  1660. rst["total_income"] = "{}%".format(rst["total_income"]*100)
  1661. rst["zan_count"] = rst.get("zans",0)
  1662. rst["comments_count"] = cm.Comments.objects.filter(record_id=rst.get("id",0)).count()
  1663. return rst
  1664. except Exception as e:
  1665. print(e)
  1666. return {"player_id":user_id,"match_id":match_id,"user_id":user_id}
  1667. #@ccc.cache_data()
  1668. def get_match_validdates(match_id):
  1669. """
  1670. """
  1671. #qdata = request.json
  1672. #match_id = qdata.get("match_id")
  1673. match = cm.Match.objects.filter(id=match_id).first()
  1674. if match:
  1675. validdates = json.loads(match.valid_dates) if match.valid_dates else []
  1676. validdates.sort()
  1677. return validdates
  1678. return []
  1679. def send_phcode(request):
  1680. """
  1681. """
  1682. qdata = request.json
  1683. phone = qdata.get("phone")
  1684. code = "%s%s%s%s" % (random.randint(0,9),random.randint(0,9),random.randint(0,9),random.randint(0,9))
  1685. send_verify_code(phone,code)
  1686. ccc.cache.set(phone,code,120)
  1687. pass
  1688. def get_signup_info(request):
  1689. """
  1690. """
  1691. qdata = request.json
  1692. try:
  1693. user_id = request.user.get("id",0)
  1694. except:
  1695. user_id = 0
  1696. try:
  1697. match_id = ccc.get_signup_match().id
  1698. match = cm.Match.objects.filter(id=match_id).values().first()
  1699. #
  1700. match_groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).values())
  1701. match["groups"] = match_groups
  1702. #报名状态
  1703. now = datetime.datetime.now().strftime("%Y-%m-%d")
  1704. signup_start_time = match["signup_start_time"]
  1705. signup_end_time = match["signup_end_time"]
  1706. if signup_start_time <= now and signup_end_time >= now:
  1707. match["signup_status"] = 1
  1708. else:
  1709. match["signup_status"] = 0
  1710. if cm.Player.objects.filter(match_id=match_id,user_id=user_id,match_group__isnull=False).filter(role__in=[1,2]).exists():
  1711. match["signup_done"] = 1
  1712. else:
  1713. match["signup_done"] = 0
  1714. return match
  1715. except Exception as e:
  1716. print(e)
  1717. return {}
  1718. def do_wx_pay(request):
  1719. """
  1720. """
  1721. user = request.user
  1722. user_id = request.user.get("id",0)
  1723. user_name = request.user.get("username","")
  1724. openid = request.user.get("openid","")
  1725. qdata = request.json
  1726. match_id = qdata.get("match_id")
  1727. match_name = qdata.get("match_name")
  1728. signup_type = qdata.get("signup_type")
  1729. total_fee = str(qdata.get("total_fee"))
  1730. phone = qdata.get("phone")
  1731. phcode = qdata.get("phcode")
  1732. match_group = qdata.get("match_group")
  1733. signup_name = qdata.get("signup_name")
  1734. pay_type = qdata.get("pay_type")
  1735. opmode_group = qdata.get("opmode_group")
  1736. if not signup_name:
  1737. signup_name = user_name
  1738. orgcode = ccc.cache.get(phone)
  1739. if not phone == "13883187629":
  1740. if not phcode == orgcode:
  1741. raise ce.TipException(u"验证码不正确!")
  1742. if int(signup_type) == 1:
  1743. if not match_group:
  1744. match_group = cm.MatchGroup.objects.filter(match_id=match_id,charge=0).first().id
  1745. if pay_type == "wxapppay":
  1746. out_trade_no = "WXAPP"+datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
  1747. else:
  1748. out_trade_no = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
  1749. #游客和普通选手付费报名
  1750. #gt_time = datetime.timedelta(days=-365)+datetime.datetime.now()
  1751. #old_player = cm.Player.objects.filter(user_id=user_id,match_status=1,ctime__gte=gt_time).exists()
  1752. #if user["player_type"] in [0,1] and not phone=="13883187629":
  1753. if user["player_type"] in [0,1] and not phone=="13883187629":
  1754. #生成订单
  1755. order = cm.SignupOrder.objects.create(
  1756. user_id = user_id,
  1757. user_name = signup_name,
  1758. match_id = match_id,
  1759. match_name = match_name,
  1760. signup_type = signup_type,
  1761. total_fee = total_fee,
  1762. out_trade_no = out_trade_no,
  1763. phone = phone,
  1764. match_group = match_group,
  1765. signup_name = signup_name,
  1766. opmode_group = opmode_group
  1767. )
  1768. #支付
  1769. if pay_type == "wxapppay":
  1770. total_fee = str(int(float(order.total_fee)*100))
  1771. notify_url = "https://api.hunanwanzhu.com/api/wx/v3/signup/notify"
  1772. #notify_url = "https://test.hunanwanzhu.com"
  1773. data = {"subject":u"%s报名费" % match_name,"price":total_fee,"out_trade_no":out_trade_no}
  1774. wxapppay = WechatPayDAL()
  1775. prepayinfo = wxapppay.create_order_info(data,notify_url)
  1776. return prepayinfo
  1777. else:
  1778. total_fee = str(int(float(order.total_fee)*100))
  1779. prepayinfo = wxpay.get_wx_unifiedorder(out_trade_no,total_fee,openid)
  1780. prepayinfo["key"] = wxpay.WxPayConf_pub.KEY
  1781. return prepayinfo
  1782. #种子选手和开户选手免费报名
  1783. else:
  1784. if signup_type == 1:
  1785. signup_name = user_name
  1786. #生成订单
  1787. order = cm.SignupOrder.objects.create(
  1788. user_id = user_id,
  1789. user_name = signup_name,
  1790. match_id = match_id,
  1791. match_name = match_name,
  1792. signup_type = signup_type,
  1793. total_fee = total_fee,
  1794. out_trade_no = out_trade_no,
  1795. phone = phone,
  1796. match_group = match_group,
  1797. signup_name = signup_name,
  1798. opmode_group = opmode_group
  1799. )
  1800. user = cm.UserInfo.objects.filter(id=user_id).first()
  1801. #生成选手信息
  1802. cur_match = cm.Match.objects.filter(id=match_id).first()
  1803. visit_group = cm.MatchGroup.objects.filter(id=match_group).first()
  1804. opmode_group_obj = cm.OpModelGroup.objects.filter(id=opmode_group).first()
  1805. player,flag = cm.Player.objects.get_or_create(
  1806. user_id = user.id,
  1807. match_id = cur_match.id
  1808. )
  1809. player.match_name = cur_match.name
  1810. player.match_group = visit_group.id
  1811. player.match_group_name = visit_group.name
  1812. player.opmode_group = opmode_group_obj.id
  1813. player.opmode_group_name = opmode_group_obj.name
  1814. player.username = signup_name
  1815. player.usercode = request.user.get("usercode")
  1816. player.role = 2
  1817. player.match_status = 1
  1818. player.save()
  1819. #
  1820. order.player_id = player.id
  1821. order.save()
  1822. user.username = signup_name
  1823. user.phone = phone
  1824. user.role = 2
  1825. user.save()
  1826. #发送报名成功信息
  1827. #send_signup_success(phone,signup_name)
  1828. if phone == "13883187629":
  1829. for i in [5001,4762,5173,5141]:
  1830. cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=i)
  1831. return {"free":1}
  1832. def do_wxpay_notify(request):
  1833. qdata = request.json
  1834. if qdata.get("resource_type") == "encrypt-resource":
  1835. wxapppay = WechatPayDAL()
  1836. res = wxapppay.decrypt_nofify_v3(qdata)
  1837. res = json.loads(res)
  1838. flag = True
  1839. else:
  1840. flag,res = wxpay.check_notify_valid(request.body)
  1841. if flag:
  1842. out_trade_no = res.get("out_trade_no")
  1843. transaction_id = res.get("transaction_id")
  1844. pay_time = res.get("time_end")
  1845. try:
  1846. sorder = cm.SignupOrder.objects.filter(out_trade_no=out_trade_no).first()
  1847. if sorder and not sorder.transaction_id:
  1848. now = datetime.datetime.now()
  1849. sorder.order_status = 1
  1850. sorder.pay_status = 1
  1851. sorder.pay_time = now
  1852. sorder.transaction_id = transaction_id
  1853. sorder.save()
  1854. #生成选手信息
  1855. user = cm.UserInfo.objects.filter(id=sorder.user_id).first()
  1856. visit_group = cm.MatchGroup.objects.filter(id=sorder.match_group).first()
  1857. player,flag = cm.Player.objects.get_or_create(
  1858. user_id = sorder.user_id,
  1859. match_id = sorder.match_id
  1860. )
  1861. player.match_name = sorder.match_name
  1862. player.match_group = visit_group.id
  1863. player.match_group_name = visit_group.name
  1864. player.username = sorder.user_name
  1865. player.usercode = user.usercode if user else ""
  1866. if sorder.signup_type == 2:
  1867. player.role = 2
  1868. else:
  1869. player.role = 1
  1870. #
  1871. sorder.player_id = player.id
  1872. sorder.save()
  1873. player.save()
  1874. if sorder.signup_type == 2:
  1875. player_id = sorder.player_id
  1876. user_id = sorder.user_id
  1877. match_group = sorder.match_group
  1878. match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name
  1879. 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)
  1880. cm.UserInfo.objects.filter(id=user_id).update(role=2,phone=sorder.phone,username=sorder.user_name)
  1881. if sorder.signup_type == 1:
  1882. player_id = sorder.player_id
  1883. user_id = sorder.user_id
  1884. cm.Player.objects.filter(id=player_id).update(role=1,match_status=1)
  1885. cm.UserInfo.objects.filter(id=user_id).update(role=1,phone=sorder.phone,username=sorder.user_name)
  1886. #发送报名成功信息
  1887. #send_signup_success(sorder.phone,sorder.signup_name)
  1888. return True
  1889. except Exception as e:
  1890. import traceback
  1891. traceback.print_exc()
  1892. print(e,111111111111)
  1893. return False
  1894. def get_user_comments(request):
  1895. """
  1896. """
  1897. kwargs = request.json
  1898. stock_id = kwargs.get("stock_id")
  1899. record_id = kwargs.get("record_id")
  1900. match_id = kwargs.get("match_id")
  1901. if record_id:
  1902. if match_id:
  1903. qset = cm.Comments.objects.filter(record_id=record_id,match_id=match_id,pid__isnull=True).order_by(*["-istop","-id"])
  1904. else:
  1905. qset = cm.Comments.objects.filter(record_id=record_id,pid__isnull=True).order_by(*["-istop","-id"])
  1906. else:
  1907. qset = cm.Comments.objects.filter(stock_id=stock_id,pid__isnull=True).order_by(*["-istop","-id"])
  1908. data = list(qset.values())
  1909. for item in data:
  1910. if record_id:
  1911. subcomments = cm.Comments.objects.filter(record_id=record_id,pid=item["id"])
  1912. else:
  1913. subcomments = cm.Comments.objects.filter(stock_id=stock_id,pid=item["id"])
  1914. item["children"] = list(subcomments.values())
  1915. #分页
  1916. page = int(kwargs.get("page",1))
  1917. page_size = int(kwargs.get("page_size",20))
  1918. if page and page_size:
  1919. total,data = ccf.get_page_list(data,page,page_size)
  1920. else:
  1921. total = len(data)
  1922. return total,data
  1923. def get_user_choices(request):
  1924. """
  1925. """
  1926. user_id = request.user.get("id",0)
  1927. #match_id = request.player.match_id
  1928. kwargs = request.json
  1929. stock_id = kwargs.get("stock_id")
  1930. if stock_id:
  1931. qset = cm.UserChoice.objects.filter(stock_id=stock_id)
  1932. else:
  1933. qset = cm.UserChoice.objects.filter(user_id=user_id)
  1934. data = list(qset.values())
  1935. for item in data:
  1936. stock_id = item["stock_id"]
  1937. comments_count = ccc.cache.get("%s_comments" % stock_id)
  1938. choice_count = ccc.cache.get("%s_choices" % stock_id)
  1939. comments_count = comments_count if comments_count else 0
  1940. choice_count = choice_count if choice_count else 0
  1941. item["count"] = choice_count
  1942. item["comments_count"] = comments_count
  1943. item["choice_count"] = choice_count
  1944. #item["match_id"] = match_id
  1945. #分页
  1946. page = int(kwargs.get("page",1))
  1947. page_size = int(kwargs.get("page_size",20))
  1948. if page and page_size:
  1949. total,data = ccf.get_page_list(data,page,page_size)
  1950. else:
  1951. total = len(data)
  1952. return total,data
  1953. def get_user_consult_list(request):
  1954. """
  1955. """
  1956. player_id = request.user.get("id") if request.user else 0
  1957. if not player_id:
  1958. return 0,[]
  1959. kwargs = request.json
  1960. record_id = kwargs.get("record_id")
  1961. if kwargs.get("user_id"):
  1962. player_id = kwargs.get("user_id")
  1963. qset = cm.WanzhuConsult.objects.filter(user_id=player_id,user_id__gt=0)
  1964. qdata = list(qset.values())
  1965. data = []
  1966. for item in qdata:
  1967. data.append(item)
  1968. if cm.WanzhuConsult.objects.filter(pid=item["id"]).exists():
  1969. reply_list = cm.WanzhuConsult.objects.filter(Q(pid=item["id"])).values()
  1970. for iitem in reply_list:
  1971. data.append(iitem)
  1972. data = sorted(data,key=lambda x:x["id"])
  1973. #分页
  1974. page = int(kwargs.get("page",1))
  1975. page_size = int(kwargs.get("page_size",1000))
  1976. if page and page_size:
  1977. total,data = ccf.get_page_list(data,page,page_size)
  1978. else:
  1979. total = len(data)
  1980. for item in data:
  1981. user_id = item["user_id"]
  1982. user = cm.UserInfo.objects.filter(id=user_id).first()
  1983. if user:
  1984. item["usercode"] = user.usercode
  1985. return total,data
  1986. def get_user_zans(request):
  1987. """
  1988. """
  1989. qdata = request.json
  1990. record_id = qdata.get("record_id")
  1991. match_id = qdata.get("match_id")
  1992. zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
  1993. return zans
  1994. def get_user_comments_count(request):
  1995. """
  1996. """
  1997. qdata = request.json
  1998. record_id = qdata.get("record_id")
  1999. count = cm.Comments.objects.filter(record_id=record_id).count()
  2000. return count
  2001. def add_wanzhu_consult(request):
  2002. """咨询顽主
  2003. """
  2004. user_id = request.user.get("id",0)
  2005. user_name = request.user.get("username")
  2006. user_avatar = request.user.get("avatar")
  2007. openid = request.user.get("openid")
  2008. qdata = request.json
  2009. content = qdata.get("cotent")
  2010. width = qdata.get("width")
  2011. height = qdata.get("height")
  2012. pid = qdata.get("pid")
  2013. wanzhu_obj = cm.WanzhuConsult.objects.create(
  2014. user_id = user_id,
  2015. user_name = user_name,
  2016. user_avatar = user_avatar,
  2017. content = content,
  2018. pid = pid
  2019. )
  2020. wanzhu_obj.width = width
  2021. wanzhu_obj.height = height
  2022. wanzhu_obj.save()
  2023. obj,flag = cm.Consult.objects.get_or_create(
  2024. user_id = user_id,
  2025. )
  2026. obj.user_name = user_name
  2027. obj.user_avatar = user_avatar
  2028. obj.content = content
  2029. obj.view_status = 0
  2030. obj.reply_status = 0
  2031. obj.width = width
  2032. obj.height = height
  2033. obj.ctime = datetime.datetime.now()
  2034. obj.save()
  2035. #自动回复
  2036. if cm.WanzhuConsult.objects.filter(user_id=user_id).count() <=1:
  2037. content = u"您好,后台消息一般三小时内回复,如果超出时间请加微信destination8888"
  2038. cm.WanzhuConsult.objects.create(
  2039. pid = pid,
  2040. reply_content = content,
  2041. user_id = 0,
  2042. player_id = 0,
  2043. reply_user_id = user_id
  2044. )
  2045. #发送消息提醒
  2046. if cm.UserInfo.objects.filter(id=user_id).exists():
  2047. user = cm.UserInfo.objects.filter(id=user_id).first()
  2048. send_consult_reply_message(openid,user_name)
  2049. #发送app推送消息
  2050. title = u"顽主杯"
  2051. body = u"你收到一条顽主的消息"
  2052. params = {"type":"message","id":str(user_id)}
  2053. aliyunpush.push_notice_by_userid(0,title,body,params,"ios")
  2054. aliyunpush.push_notice_by_userid(0,title,body,params,"android")
  2055. #退款短信通知
  2056. if '退款' in content:
  2057. send_verify_code('18397565872','0000')
  2058. def add_comments(request):
  2059. """
  2060. """
  2061. #if request.user.comment_status == 0:
  2062. # raise ce.TipException(u"对不起,暂无法评论/留言!")
  2063. user_id = request.user.get("id")
  2064. user_name = request.user.get("username")
  2065. user_avatar = request.user.get("avatar")
  2066. qdata = request.json
  2067. content = qdata.get("cotent")
  2068. record_id = qdata.get("record_id")
  2069. stock_id = qdata.get("stock_id")
  2070. pid = qdata.get("pid")
  2071. match_id = qdata.get("match_id")
  2072. target_user_id = qdata.get("target_user_id")
  2073. ip = ccf.get_ip(request)
  2074. location = ccf.get_city_from_ip(ip)
  2075. if record_id and target_user_id:
  2076. if cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=target_user_id).exists():
  2077. raise ce.TipException(u"对不起,暂无法评论/留言!")
  2078. obj = cm.Comments.objects.create(
  2079. user_id = user_id,
  2080. user_name = user_name,
  2081. user_avatar = user_avatar,
  2082. content = content,
  2083. record_id = record_id,
  2084. pid = pid,
  2085. ip = ip,
  2086. location = location,
  2087. stock_id = stock_id,
  2088. match_id = match_id
  2089. )
  2090. if record_id:
  2091. cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(comments_count=F("comments_count")+1)
  2092. if stock_id:
  2093. ccc.cache.incr("%s_comments" % stock_id,1)
  2094. def add_choice(request):
  2095. """
  2096. """
  2097. user_id = request.user.get("id")
  2098. user_name = request.user.get("username")
  2099. user_avatar = request.user.get("avatar")
  2100. qdata = request.json
  2101. stock_id = qdata.get("stock_id")
  2102. stock_name = cm.Stock.objects.filter(id=stock_id).first().name
  2103. obj = cm.UserChoice.objects.create(
  2104. user_id = user_id,
  2105. user_name = user_name,
  2106. user_avatar = user_avatar,
  2107. stock_id = stock_id,
  2108. stock_name = stock_name
  2109. )
  2110. if stock_id:
  2111. ccc.cache.incr("%s_choices" % stock_id,1)
  2112. def add_zan(request):
  2113. """
  2114. """
  2115. qdata = request.json
  2116. record_id = qdata.get("record_id")
  2117. match_id = qdata.get("match_id")
  2118. cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(zans=F("zans")+1)
  2119. zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
  2120. return zans
  2121. def get_experience_list(request):
  2122. """
  2123. """
  2124. #return 0,[]
  2125. kwargs = request.json
  2126. today = get_today_date()
  2127. match_id = ccc.get_cur_match().id
  2128. match_group = kwargs.get("match_group")
  2129. #冠军组、千万组、百万组
  2130. grpset = cm.MatchGroup.objects.filter(match_id=match_id).filter(Q(name__icontains=u"千万组")|Q(name__icontains=u"百万组")|Q(name__icontains=u"冠军组"))
  2131. if match_group:
  2132. grpset = grpset.filter(id=match_group)
  2133. qbw_ids = list(grpset.values_list("id",flat=True))
  2134. 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")
  2135. 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"))
  2136. for item in data:
  2137. record_id = item["id"]
  2138. user_id = item["user_id"]
  2139. try:
  2140. item["user_avatar"] = get_user_info(user_id)["avatar"]
  2141. item["avatar"] = get_user_info(user_id)["avatar"]
  2142. except:
  2143. item["user_avatar"] = ""
  2144. item["avatar"] = ""
  2145. item["zans_count"] = item["zans"]
  2146. item["today_stock_img"] = json.loads(item["today_stock_img"])
  2147. win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
  2148. if win_rate:
  2149. item["win_rate"] = str(float(win_rate)*100)+"%"
  2150. else:
  2151. item["win_rate"] = "0.0%"
  2152. item["today_income"] = "{}%".format(item["today_income"]*100)
  2153. item["total_income"] = "{}%".format(item["total_income"]*100)
  2154. #分页
  2155. page = int(kwargs.get("page",1))
  2156. page_size = int(kwargs.get("page_size",20))
  2157. if page and page_size:
  2158. total,data = ccf.get_page_list(data,page,page_size)
  2159. else:
  2160. total = len(data)
  2161. return total,data
  2162. def delete_choice(request):
  2163. """
  2164. """
  2165. user_id = request.user.get("id")
  2166. user_name = request.user.get("username")
  2167. user_avatar = request.user.get("avatar")
  2168. qdata = request.json
  2169. stock_id = qdata.get("stock_id")
  2170. cm.UserChoice.objects.filter(stock_id=stock_id,user_id=user_id).delete()
  2171. if ccc.cache.get("%s_choices" % stock_id) and int(ccc.cache.get("%s_choices" % stock_id)) >= 1:
  2172. ccc.cache.decr("%s_choices" % stock_id)
  2173. def delete_comments(request):
  2174. """
  2175. """
  2176. qdata = request.json
  2177. id = qdata.get("id")
  2178. if cm.Comments.objects.filter(id=id,stock_id__isnull=False).exists():
  2179. stock_id = cm.Comments.objects.filter(id=id).first().stock_id
  2180. if ccc.cache.get("%s_comments" % stock_id) and int(ccc.cache.get("%s_comments" % stock_id)) >= 1:
  2181. ccc.cache.decr("%s_comments" % stock_id)
  2182. cm.Comments.objects.filter(id=id).delete()
  2183. def modify_user_fund(request):
  2184. """
  2185. """
  2186. user_id = request.user.get("id")
  2187. #player = request.player
  2188. match_id = ccc.get_cur_match().id
  2189. player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
  2190. player_id = player.id
  2191. match_id = player.match_id
  2192. qdata = request.json
  2193. fundin = qdata.get("in_fund")
  2194. fundout = qdata.get("out_fund")
  2195. fundin = float(fundin) if fundin else 0.0
  2196. fundout = float(fundout) if fundout else 0.0
  2197. account_img = qdata.get("account_img")
  2198. init_fund = player.fund
  2199. trycalc = qdata.get("trycalc")
  2200. today_fund = qdata.get("today_fund")
  2201. today_fund = float(today_fund) if today_fund else 0.0
  2202. if trycalc:
  2203. stock_date = get_today_date()
  2204. validdates = get_match_validdates(match_id)
  2205. today_index = validdates.index(stock_date)
  2206. yesterday_index = today_index -1 if today_index >=1 else 0
  2207. yesterday_date = validdates[yesterday_index]
  2208. yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
  2209. match_id=match_id,player_id=player_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
  2210. if yesterday:
  2211. yesterday_fund = yesterday.today_fund
  2212. yesterday_stock = yesterday.today_stock
  2213. yesterday_stock_img = yesterday.today_stock_img
  2214. yesterday_is_markt = yesterday.is_markt
  2215. else:
  2216. yesterday_fund = today_fund
  2217. yesterday_stock = ""
  2218. yesterday_stock_img = ""
  2219. yesterday_is_markt = 0
  2220. #入资金
  2221. if fundin > fundout:
  2222. fundin = fundin - fundout
  2223. if yesterday:
  2224. today_income = round((today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin),4)
  2225. yesterday_fund = yesterday_fund + fundin
  2226. else:
  2227. today_income = 0.0
  2228. total_income = round((today_fund-init_fund-fundin)/(init_fund+fundin),4)
  2229. init_fund = init_fund + fundin
  2230. #出资金
  2231. else:
  2232. fundout = fundout - fundin
  2233. if yesterday:
  2234. today_income = round((today_fund-(yesterday_fund-fundout))/float(yesterday_fund),4)
  2235. yesterday_fund = round(today_fund/(1+today_income),4)
  2236. else:
  2237. today_income = 0.0
  2238. total_income = round((today_fund+fundout-init_fund)/init_fund,4)
  2239. init_fund = round(today_fund/(1+total_income),4)
  2240. today_income = "{}%".format(today_income*100)
  2241. total_income = "{}%".format(total_income*100)
  2242. return {"yesterday_fund":yesterday_fund,
  2243. "today_fund":today_fund,
  2244. "today_income":today_income,
  2245. "total_income":total_income,
  2246. "init_fund":init_fund}
  2247. stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
  2248. if cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).exists():
  2249. raise ce.TipException(u"资金出入须在提交作业之前提交,今日作业已提交,不能提交资金出入!")
  2250. if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists():
  2251. raise ce.TipException(u"今日已有资金出入,一天只能提交一次资金出入!")
  2252. fundinout,flag = cm.FundInOut.objects.get_or_create(
  2253. user_id = user_id,
  2254. fundin = fundin,
  2255. fundout = fundout,
  2256. stock_date = stock_date,
  2257. account_img = account_img
  2258. )
  2259. def get_user_match_list(request):
  2260. kwargs = request.json
  2261. user_id = kwargs.get("user_id")
  2262. if not user_id:
  2263. user_id = request.user.get("id")
  2264. qset = cm.Player.objects.filter(user_id=user_id).filter(match_group__isnull=False).order_by("-id")
  2265. qset = qset.values("user_id","match_id","match_group").annotate(cnt=Count("match_id"))
  2266. page = int(kwargs.get("page",0))
  2267. page_size = int(kwargs.get("page_size",20))
  2268. if page and page_size:
  2269. total,qset = ccc.get_page_qset(qset,page,page_size)
  2270. else:
  2271. total = qset.count()
  2272. #today = get_today_date(user_id=user_id)
  2273. data = list(qset.values("user_id","match_id","match_group"))
  2274. new_data = []
  2275. for item in data:
  2276. match_id = item["match_id"]
  2277. match_group = item["match_group"]
  2278. user_id = item["user_id"]
  2279. today = get_today_date(match_id=match_id,user_id=user_id)
  2280. item["match_info"] = get_match_info(match_id)
  2281. item["match_group_info"] = get_group_info(match_group)
  2282. if match_id and match_group:
  2283. today_record = ccc.get_today_record(user_id,int(match_id),int(match_group),today)
  2284. today_record = format_today_record(today_record)
  2285. if today_record:
  2286. if today_record.get("today_income"):
  2287. today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
  2288. if today_record.get("total_income"):
  2289. today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
  2290. item["today_record"] = today_record
  2291. new_data.append(item)
  2292. #return total,data
  2293. return total,new_data
  2294. def get_format_user_info(request):
  2295. user_id = request.user.get("id")
  2296. cur_user_id = request.user.get("id")
  2297. kwargs = request.json
  2298. q_user_id = kwargs.get("user_id")
  2299. if q_user_id:
  2300. user_id = q_user_id
  2301. userinfo = get_user_info_actual(q_user_id)
  2302. userinfo["fans"] = cm.UserFollows.objects.filter(follow_id=user_id).count()
  2303. userinfo["followers"] = cm.UserFollows.objects.filter(user_id=user_id).count()
  2304. del userinfo["phone"]
  2305. if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists():
  2306. userinfo["is_follow"] = 1
  2307. else:
  2308. userinfo["is_follow"] = 0
  2309. if cm.UserBlacks.objects.filter(user_id=cur_user_id,black_user_id=user_id).exists():
  2310. userinfo["is_black"] = 1
  2311. else:
  2312. userinfo["is_black"] = 0
  2313. return userinfo
  2314. def get_day_inout_rank_list(request):
  2315. """
  2316. """
  2317. kwargs = request.json
  2318. stock_date = kwargs.get("stock_date")
  2319. match_id = kwargs.get("match_id")
  2320. _type = kwargs.get("type")
  2321. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date)
  2322. if _type == "in":
  2323. qset = qset.order_by("-today_income")
  2324. else:
  2325. qset = qset.order_by("today_income")
  2326. page = int(kwargs.get("page",0))
  2327. page_size = int(kwargs.get("page_size",20))
  2328. if page and page_size:
  2329. total,qset = ccc.get_page_qset(qset,page,page_size)
  2330. else:
  2331. total = qset.count()
  2332. data = list(qset.values())
  2333. return total,data
  2334. def get_user_follows_v3(request):
  2335. """获取用户关注的选手列表
  2336. """
  2337. user_id = request.user.get("id",0)
  2338. qdata = request.json
  2339. if qdata.get("user_id"):
  2340. user_id = qdata.get("user_id")
  2341. qset = cm.UserFollows.objects.filter(user_id=user_id)
  2342. follow_ids = list(qset.values_list("follow_id",flat=True))
  2343. today = get_today_date()
  2344. _today = today
  2345. data = []
  2346. for user_id in follow_ids:
  2347. latest_key = "PLAYER_LATEST_%d"%user_id
  2348. _match_id = ccc.cache.hget(latest_key,"match_id")
  2349. _today = ccc.cache.hget(latest_key,"stock_date")
  2350. _match_group = ccc.cache.hget(latest_key,"match_group")
  2351. today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
  2352. if today_record:
  2353. today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
  2354. today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
  2355. data.append(today_record)
  2356. data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
  2357. page = int(qdata.get("page",1))
  2358. page_size = int(qdata.get("page_size",20))
  2359. if page and page_size:
  2360. total,data = ccf.get_page_list(data,page,page_size)
  2361. for item in data:
  2362. if item:
  2363. user_id = item["user_id"]
  2364. latest_key = "PLAYER_LATEST_%d"%user_id
  2365. today_stock = json.loads(item["today_stock"]) if item.get("today_stock") else []
  2366. today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
  2367. item["today_stock"] = today_stock
  2368. item["today_stock_img"] = json.loads(item["today_stock_img"]) if item.get("today_stock_img") else []
  2369. win_rate = ccc.cache.hget(latest_key,"win_rate")
  2370. if win_rate:
  2371. item["win_rate"] = str(float(win_rate)*100)+"%"
  2372. else:
  2373. item["win_rate"] = "0.0%"
  2374. item["today_income"] = "{}%".format(item["today_income"]*100)
  2375. item["total_income"] = "{}%".format(item["total_income"]*100)
  2376. item["zans_count"] = item.get("zans",0)
  2377. item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
  2378. return total,data
  2379. else:
  2380. return len(data),data
  2381. def get_latest_match_info(request):
  2382. """
  2383. """
  2384. cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").values().first()
  2385. cur_match_id = cur_match.get("id")
  2386. groups = list(cm.MatchGroup.objects.filter(match_id=cur_match_id,is_active=1).order_by("order").values())
  2387. cur_match["groups"] = groups
  2388. return cur_match
  2389. def get_article_info(**kwargs):
  2390. """
  2391. """
  2392. _id = kwargs.get("id")
  2393. rst = cm.Article.objects.filter(id=_id).values().first()
  2394. rst["url"] = "https://www.hunanwanzhu.com/topic/article.html?id="+str(_id)
  2395. return rst
  2396. def get_profit_list(**kwargs):
  2397. """盈亏列表
  2398. """
  2399. stock_date = kwargs.get("stock_date")
  2400. match_id = kwargs.get("match_id")
  2401. _type = kwargs.get("type")
  2402. if not stock_date:
  2403. stock_date = get_today_date()
  2404. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=stock_date)
  2405. #if _type == "win":
  2406. # qset = qset.filter(today_income__gte=0).order_by("-today_income")
  2407. #if _type == "loss":
  2408. # qset = qset.filter(today_income__lt=0).order_by("today_income")
  2409. data = list(qset.values())
  2410. for item in data:
  2411. item["win_loss"] = item["today_fund"] - item["yesterday_fund"]
  2412. item["total_win_loss"] = item["today_fund"] - item["init_fund"]
  2413. item["win_loss"] = round(item["win_loss"],4)
  2414. item["total_win_loss"] = round(item["total_win_loss"],4)
  2415. if _type == "win":
  2416. data = sorted(data,key=lambda x:x["win_loss"],reverse=True)
  2417. if _type == "loss":
  2418. data = sorted(data,key=lambda x:x["win_loss"])
  2419. if _type == "total_win":
  2420. data = sorted(data,key=lambda x:x["total_win_loss"],reverse=True)
  2421. if _type == "total_loss":
  2422. data = sorted(data,key=lambda x:x["total_win_loss"])
  2423. if _type == "total_income_win":
  2424. data = sorted(data,key=lambda x:x["total_income"],reverse=True)
  2425. if _type == "total_income_loss":
  2426. data = sorted(data,key=lambda x:x["total_income"])
  2427. page = int(kwargs.get("page",0))
  2428. page_size = int(kwargs.get("page_size",20))
  2429. if page and page_size:
  2430. total,data = ccf.get_page_list(data,page,page_size)
  2431. else:
  2432. total = len(data)
  2433. #data = list(qset.values())
  2434. return total,data
  2435. def get_group_rank_list_v3(request):
  2436. """排名列表
  2437. """
  2438. qdata = request.json
  2439. kwargs = qdata
  2440. group_id = qdata.get("id")
  2441. match_id = qdata.get("match_id")
  2442. match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id
  2443. today = qdata.get("stock_date")
  2444. if not today:
  2445. today = get_today_date()
  2446. match = get_match_info(match_id)
  2447. group = get_group_info(group_id)
  2448. players = get_match_group_users(match_id,group_id)
  2449. new_players = []
  2450. for player in players:
  2451. user_id = player["user_id"]
  2452. username = player["username"]
  2453. match_group = group_id
  2454. today_record = ccc.get_today_record(user_id,match_id,match_group,today)
  2455. if today_record:
  2456. player.update(today_record)
  2457. player["username"] = username
  2458. player["org_today_income"] = player["today_income"]
  2459. player["org_total_income"] = player["total_income"]
  2460. player["total_income"] = "{}%".format(player["total_income"]*100)
  2461. player["today_income"] = "{}%".format(player["today_income"]*100)
  2462. player["fund"] = round(player["fund"],4)
  2463. player["init_fund"] = round(player["init_fund"],4)
  2464. player["today_fund"] = round(player["today_fund"],4)
  2465. player["today_stock_img"] = json.loads(player["today_stock_img"]) if player["today_stock_img"] else []
  2466. #player["win_rate"] = calc_win_rate(user_id,match_id)
  2467. player["zan_count"] = player["zans"]
  2468. new_players.append(player)
  2469. if kwargs.get("order_by") == "today_income__asc":
  2470. new_players = sorted(new_players,key=lambda x:x["org_today_income"])
  2471. elif kwargs.get("order_by") == "today_income__desc" :
  2472. new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True)
  2473. elif kwargs.get("order_by") == "total_income__asc":
  2474. new_players = sorted(new_players,key=lambda x:x["org_total_income"])
  2475. elif kwargs.get("order_by") == "total_income__desc":
  2476. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  2477. else:
  2478. new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
  2479. #分页
  2480. page = int(kwargs.get("page",0))
  2481. page_size = int(kwargs.get("page_size",50))
  2482. if page and page_size:
  2483. total,new_players = ccf.get_page_list(new_players,page,page_size)
  2484. else:
  2485. total = len(new_players)
  2486. return total,new_players
  2487. def get_article_type_list(**kwargs):
  2488. rst = [u"游资专场",u"冠军交割",u"牛人专场",u"妖股列传"]
  2489. rst = const.ARTICLE_TYPE_LIST
  2490. return rst
  2491. def get_wanzhu_consult_list(**kwargs):
  2492. """
  2493. """
  2494. qset = cm.Consult.objects.filter(user_id__gt=0).order_by("-ctime")
  2495. if kwargs.get("username"):
  2496. qset = qset.filter(user_name__icontains=kwargs.get("username"))
  2497. if kwargs.get("reply_status"):
  2498. qset = qset.filter(reply_status=kwargs.get("reply_status"))
  2499. if kwargs.get("content"):
  2500. qset = qset.filter(Q(content__icontains=kwargs.get("content"))|Q(reply_content__icontains=kwargs.get("content")))
  2501. data = list(qset.values())
  2502. #分页
  2503. page = int(kwargs.get("page",1))
  2504. page_size = int(kwargs.get("page_size",20))
  2505. if page and page_size:
  2506. total,data = ccf.get_page_list(data,page,page_size)
  2507. else:
  2508. total = len(data)
  2509. for item in data:
  2510. user_id = item["user_id"]
  2511. userinfo = get_user_info(user_id)
  2512. if userinfo:
  2513. item["user_code"] = userinfo.get("usercode")
  2514. return total,data
  2515. def get_sub_category(pid):
  2516. """
  2517. """
  2518. qset = cm.BaikeCategory.objects.filter(parent_id=pid)
  2519. qdata = list(qset.values())
  2520. if qdata:
  2521. for subitem in qdata:
  2522. subitem["type"] = "ent"
  2523. subitem["children"] = get_sub_category(subitem["id"])
  2524. return qdata
  2525. def get_baike_category_tree(**kwargs):
  2526. """
  2527. """
  2528. parents = list(cm.BaikeCategory.objects.filter(parent_id__isnull=True).values())
  2529. for item in parents:
  2530. item["children"] = get_sub_category(item["id"])
  2531. return parents
  2532. def get_sub_catids(pid,data):
  2533. """
  2534. """
  2535. data = data if data else []
  2536. qset = cm.BaikeCategory.objects.filter(parent_id=pid)
  2537. ids = list(qset.values_list("id",flat=True))
  2538. if ids:
  2539. data.extend(ids)
  2540. for _id in ids:
  2541. get_sub_catids(_id,data)
  2542. return data
  2543. def get_baike_list_by_category(**kwargs):
  2544. category_id = kwargs.get("category_id")
  2545. sub_catids = get_sub_catids(category_id,[])
  2546. qset = cm.BaikeDetail.objects.filter(category_id__in=sub_catids)
  2547. qset = qset.order_by("-istop","-ctime")
  2548. data = list(qset.values("id","img","intro","ctime","name","category_id"))
  2549. page = int(kwargs.get("page",1))
  2550. page_size = int(kwargs.get("page_size",20))
  2551. if page and page_size:
  2552. total,data = ccf.get_page_list(data,page,page_size)
  2553. return total,data
  2554. else:
  2555. return len(data),data
  2556. return data
  2557. def get_baike_detail(**kwargs):
  2558. #_id = kwargs.get("id")
  2559. category_id = kwargs.get("category_id")
  2560. data = list(cm.BaikeDetail.objects.filter(category_id=category_id).values())
  2561. data = data[0] if data else {}
  2562. return data
  2563. def get_app_version(request):
  2564. rst = cm.APPVersion.objects.all().order_by("-id").values().first()
  2565. return rst
  2566. def reply_wanzhu_consult(**kwargs):
  2567. """
  2568. """
  2569. pid = kwargs.get("pid")
  2570. content = kwargs.get("reply_content")
  2571. user_id = kwargs.get("user_id")
  2572. action = kwargs.get("action")
  2573. width = kwargs.get("width")
  2574. height = kwargs.get("height")
  2575. if action == "send":
  2576. user = cm.UserInfo.objects.filter(id=user_id).first()
  2577. user_name = user.username
  2578. user_avatar = user.avatar
  2579. obj,flag = cm.Consult.objects.get_or_create(
  2580. user_id = user_id,
  2581. )
  2582. obj.user_name = user_name
  2583. obj.user_avatar = user_avatar
  2584. #obj.reply_content = content
  2585. obj.view_status = 1
  2586. obj.reply_status = 0
  2587. obj.ctime = datetime.datetime.now()
  2588. obj.save()
  2589. wanzhu_obj = cm.WanzhuConsult.objects.create(
  2590. user_id = user_id,
  2591. user_name = user_name,
  2592. user_avatar = user_avatar
  2593. )
  2594. wanzhu_obj.width = width
  2595. wanzhu_obj.height = height
  2596. wanzhu_obj.save()
  2597. wanzhu_obj_1 = cm.WanzhuConsult.objects.create(
  2598. reply_content = content,
  2599. user_id = 0,
  2600. player_id = 0,
  2601. reply_user_id = user_id,
  2602. pid = wanzhu_obj.id
  2603. )
  2604. wanzhu_obj_1.width = width
  2605. wanzhu_obj_1.height = height
  2606. wanzhu_obj_1.save()
  2607. cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now())
  2608. else:
  2609. wanzhu_obj = cm.WanzhuConsult.objects.create(
  2610. pid = pid,
  2611. reply_content = content,
  2612. user_id = 0,
  2613. player_id = 0,
  2614. reply_user_id = user_id
  2615. )
  2616. wanzhu_obj.width = width
  2617. wanzhu_obj.height = height
  2618. wanzhu_obj.save()
  2619. cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now())
  2620. #发送消息提醒
  2621. if cm.UserInfo.objects.filter(id=user_id).exists():
  2622. user = cm.UserInfo.objects.filter(id=user_id).first()
  2623. openid = user.openid
  2624. username = user.username
  2625. try:
  2626. send_consult_reply_message(openid,username)
  2627. except Exception as e:
  2628. print(e)
  2629. #发送app推送消息
  2630. title = u"顽主杯"
  2631. body = u"你收到一条顽主的消息"
  2632. params = {"type":"message","id":str(user_id)}
  2633. aliyunpush.push_notice_by_userid(user_id,title,body,params,"ios")
  2634. aliyunpush.push_notice_by_userid(user_id,title,body,params,"android")
  2635. def delete_user_info(request):
  2636. """
  2637. """
  2638. uid = request.user.get("id",0)
  2639. cm.UserInfo.objects.filter(id=uid).delete()
  2640. cm.Player.objects.filter(user_id=uid).delete()
  2641. #cm.PlayerRecord.objects.filter(user_id=uid).delete()
  2642. def get_random_bake_list(**kwargs):
  2643. """
  2644. """
  2645. baikes = list(cm.BaikeDetail.objects.all().values("id","name","intro","img","category_id"))
  2646. randomi = []
  2647. while len(randomi) < 5:
  2648. num = random.randint(0,len(baikes)-1)
  2649. if not num in randomi:
  2650. randomi.append(num)
  2651. rst = [baikes[x] for x in randomi]
  2652. return rst
  2653. def articles_top5_by_type(**kwargs):
  2654. """
  2655. """
  2656. cats = const.ARTICLE_TYPE_LIST
  2657. data = []
  2658. for cat in cats:
  2659. articles = list(cm.Article.objects.filter(category=cat).order_by("-id").values("id","name","ctime","img")[:5])
  2660. data.append({"category":cat,"articles":articles})
  2661. return data
  2662. def get_match_winlost_top5(**kwargs):
  2663. """
  2664. """
  2665. data = []
  2666. cur_match_id = ccc.get_cur_match().id
  2667. matchs = cm.Match.objects.filter(id__gte=8,match_status__in=[3,4]).order_by("-id")
  2668. for match in matchs:
  2669. match_id = match.id
  2670. match_name = match.name
  2671. end_time = match.end_time
  2672. if cur_match_id == match_id:
  2673. end_time = get_today_date()
  2674. records = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=end_time)
  2675. total_income_up = copy.copy(records)
  2676. total_income_up = total_income_up.order_by("-total_income")
  2677. total_income_up = list(total_income_up.values()[:5])
  2678. get_user_avatar(total_income_up)
  2679. total_income_down = copy.copy(records)
  2680. total_income_down = total_income_down.order_by("total_income")
  2681. total_income_down = list(total_income_down.values()[:5])
  2682. get_user_avatar(total_income_down)
  2683. records = list(records.values())
  2684. for item in records:
  2685. item["total_win"] = item["today_fund"] - item["init_fund"]
  2686. total_win_up = copy.copy(records)
  2687. total_win_up = sorted(total_win_up,key=lambda x:x["total_win"],reverse=True)
  2688. total_win_up = total_win_up[:5]
  2689. get_user_avatar(total_win_up)
  2690. total_win_down = copy.copy(records)
  2691. total_win_down = sorted(total_win_down,key=lambda x:x["total_win"])
  2692. total_win_down = total_win_down[:5]
  2693. get_user_avatar(total_win_down)
  2694. 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})
  2695. if int(kwargs.get("new",0)) == 1:
  2696. break
  2697. return data
  2698. def get_user_avatar(records):
  2699. for item in records:
  2700. userinfo = get_user_info_actual(item["user_id"])
  2701. if userinfo:
  2702. item["avatar"] = userinfo.get("avatar")
  2703. else:
  2704. item["avatar"] = ""
  2705. def black_user(request):
  2706. """
  2707. """
  2708. qdata = request.json
  2709. user_id = request.user.get("id",0)
  2710. black_user_id = qdata.get("black_user_id")
  2711. cm.UserBlacks.objects.get_or_create(
  2712. user_id = user_id,
  2713. black_user_id = black_user_id
  2714. )
  2715. def delete_black_user(request):
  2716. """
  2717. """
  2718. qdata = request.json
  2719. user_id = request.user.get("id",0)
  2720. black_user_id = qdata.get("black_user_id")
  2721. cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=black_user_id).delete()
  2722. def get_user_black_user_list(request):
  2723. """
  2724. """
  2725. #user_id = 5709
  2726. user_id = request.user.get("id",0)
  2727. kwargs = request.json
  2728. qset = cm.UserBlacks.objects.filter(user_id=user_id)
  2729. page = int(kwargs.get("page",0))
  2730. page_size = int(kwargs.get("page_size",20))
  2731. if page and page_size:
  2732. total,qset = ccc.get_page_qset(qset,page,page_size)
  2733. else:
  2734. total = qset.count()
  2735. data = list(qset.values("black_user__id","black_user__username","black_user__avatar"))
  2736. datas = []
  2737. for item in data:
  2738. item['id'] = item["black_user__id"]
  2739. item['username'] = item["black_user__username"]
  2740. item['avatar'] = item["black_user__avatar"]
  2741. return total,data
  2742. def get_stock_nb_comments(request):
  2743. """
  2744. """
  2745. kwargs = request.json
  2746. comment_date = kwargs.get("date")
  2747. qset = cm.StockComments.objects.all().order_by("-ctime")
  2748. if comment_date:
  2749. st = comment_date + " 00:00:00"
  2750. et = comment_date + " 23:59:59"
  2751. qset = qset.filter(ctime__gte=st,ctime__lte=et)
  2752. page = int(kwargs.get("page",0))
  2753. page_size = int(kwargs.get("page_size",20))
  2754. if page and page_size:
  2755. total,qset = ccc.get_page_qset(qset,page,page_size)
  2756. else:
  2757. total = qset.count()
  2758. data = list(qset.values())
  2759. return total,data
  2760. def get_opmode_group_rank_list(**kwargs):
  2761. """
  2762. """
  2763. #today = get_today_date()
  2764. #match_id = ccc.get_cur_match().id
  2765. today = "2023-08-25"
  2766. match_id = 16
  2767. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today).order_by("-total_income")
  2768. qdata = list(qset.values())
  2769. #按操作模式分组并排序
  2770. tmp_dct = {}
  2771. for item in qdata:
  2772. opmode_group = item["opmode_group"]
  2773. opmode_group_name = item["opmode_group_name"]
  2774. key = "%s_%s" % (opmode_group,opmode_group_name)
  2775. if not tmp_dct.get(key):
  2776. tmp_dct[key] = [item]
  2777. else:
  2778. tmp_dct[key].append(item)
  2779. if len(tmp_dct[key]) > 5:
  2780. break
  2781. data = []
  2782. for k,v in tmp_dct.items():
  2783. opmode_id,opmode_name = k.split("_")
  2784. #盈利与亏损
  2785. win_5 = qset.filter(today_income__gte=0.05).count()
  2786. loss_5 = qset.filter(today_income__lte=0.05).count()
  2787. item = {
  2788. "opmode_name":opmode_name,
  2789. "opmode_id":opmode_id,
  2790. "list":v,
  2791. "win_5":win_5,
  2792. "loss_5":loss_5
  2793. }
  2794. data.append(item)
  2795. return data
  2796. def get_opmode_group_statistic(**kwargs):
  2797. """
  2798. """
  2799. opmode_id = kwargs.get("opmode_id")
  2800. #today = get_today_date()
  2801. #match_id = ccc.get_cur_match().id
  2802. today = "2023-08-25"
  2803. match_id = 16
  2804. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today,opmode_group=opmode_id)
  2805. qset_user_stock = cm.UserStock.objects.filter(stock_date=today,opmode_group=opmode_id)
  2806. total = qset.count()
  2807. #今日均收益
  2808. today_total_income = qset.aggregate(total=Sum("today_income"))
  2809. today_income_avg = today_total_income["total"]/total
  2810. #总资产
  2811. today_fund_total = qset.aggregate(total=Sum("today_fund"))["total"]
  2812. #初始资产
  2813. init_fund_total = qset.aggregate(total=Sum("init_fund"))["total"]
  2814. #持股前10
  2815. user_stock_top10 = list(qset_user_stock.values("stock_id","stock_name")\
  2816. .annotate(cnt=Count("stock_id")).order_by("-cnt").values("stock_id","stock_name","cnt"))[:10]
  2817. statistic = {
  2818. "total_man":total,
  2819. "today_income_avg":today_income_avg,
  2820. "today_fund_total":today_fund_total,
  2821. "today_init_total":init_fund_total,
  2822. "user_stock_top10":user_stock_top10
  2823. }
  2824. return statistic
  2825. def get_opmode_group_rank_info_list(**kwargs):
  2826. """
  2827. """
  2828. opmode_id = kwargs.get("opmode_id")
  2829. order_by = kwargs.get("order_by")
  2830. #today = get_today_date()
  2831. #match_id = ccc.get_cur_match().id
  2832. today = "2023-08-25"
  2833. match_id = 16
  2834. qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today,opmode_group=opmode_id)
  2835. #今日收益
  2836. if order_by == "today_income":
  2837. qset = qset.order_by("-today_income")
  2838. #总收益
  2839. if order_by == "total_income":
  2840. qset = qset.order_by("-total_income")
  2841. page = int(kwargs.get("page",0))
  2842. page_size = int(kwargs.get("page_size",10))
  2843. if page and page_size:
  2844. total,qset = ccc.get_page_qset(qset,page,page_size)
  2845. else:
  2846. total = qset.count()
  2847. data = list(qset.values())
  2848. return total,data