controls.py 146 KB

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