controls.py 141 KB

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