controls.py 104 KB

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