controls.py 132 KB

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