| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062 |
- #coding=utf-8
- '''
- '''
- import os,re,random
- import json,time,datetime
- import shutil
- import tempfile
- import zipfile,requests
- from docxtpl import DocxTemplate,InlineImage
- from docx.shared import Mm
- from django.db import transaction
- from django.conf import settings
- import common.models as cm
- import common.error_info as ce
- import common.common_functions as ccf
- import common.common_control as ccc
- import common.constant as const
- import account.password_handle as ph
- from utils.exceltool import ExcelTool
- from utils.jgpush import send_notification_by_registration_ids
- import wzhifuSDK as wxpay
- from utils.exceltool import ExcelTool
- from utils.qrcodetool import gen_general_qrcode
- from django.db.models import Q,Sum,Count,F,Avg
- from PIL import Image
- from PIL import Image,ImageDraw,ImageFont
- from django.db import transaction
- from threading import Thread
- #from django.core.cache import cache
- from django.db import connection
- import calendar
- import xlrd
- import xlwt
- # from xlutils.copy import copy
- import copy
- from xltpl.writer import BookWriter
- from django_redis import get_redis_connection
- from constants import *
- from utils.aliyun_sms import send_verify_code,send_signup_success
- from utils.wxSubscribeMessage import send_consult_reply_message
- from utils.aliyunpush import aliyunpush
- from utils.wxpay.pay import WechatPayDAL
- #import logging
- #log = logging.getLogger("myerror")
- from utils.upload_to_oss import get_signature
- from weixin.wzhifuSDK_V3 import refund_order
- def async(f):
- def wrapper(*args, **kwargs):
- thr = Thread(target=f, args=args, kwargs=kwargs)
- thr.start()
- return wrapper
- def get_today_date(match_id=None,user_id=None):
- if not match_id:
- match_id = ccc.get_cur_match().id
- #if datetime.datetime.now().strftime("%H:%M") < "15:00":
- # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES:
- # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
- # else:
- # if datetime.datetime.now().weekday()==0:
- # today = (datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d")
- # else:
- # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
- #else:
- # if datetime.datetime.now().weekday() in [5,6] or datetime.datetime.now().strftime("%Y-%m-%d") in MISS_DATES:
- # today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
- # else:
- # today = datetime.datetime.now().strftime("%Y-%m-%d")
- try:
- if user_id:
- today = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id).order_by("-stock_date").first().stock_date
- else:
- today = cm.PlayerRecord.get_db_model(match_id).objects.all().order_by("-stock_date").first().stock_date
- except:
- today = datetime.datetime.now().strftime("%Y-%m-%d")
- return today
- #@async
- def update_group_rank(match_id,match_group,stock_date):
- #return
- 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")
- records = prset.values()
- case_id = " case id "
- cases = []
- where = []
- for index,pr in enumerate(prset):
- key = "%s_%s_%s_%s" % (pr.player_id,match_id,match_group,stock_date)
- record = records[index]
- record.update({"group_rank":index+1})
- ccc.cache.delete(key)
- ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder))
- ccc.pl.execute()
- #@ccc.cache_data()
- def get_notices():
- """
- """
- notices = list(cm.Article.objects.filter(status=2,type="notice").values())
- return notices
- def get_index_data(request):
- """首页数据
- """
- player = request.player
- if not player:
- raise ce.TipException(u"该账号未参加任何赛事!")
- player_id = player.id
- match_id = player.match_id
- match_group = player.match_group
- #if datetime.datetime.now().hour < 15:
- # today = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
- #else:
- # today = datetime.datetime.now().strftime("%Y-%m-%d")
- today = get_today_date()
- match_name = get_match_info(match_id).get("name")
- records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(player_id=player_id,match_id=match_id)
- if records_set:
- try:
- cur_rank = get_today_record(player_id,match_id,match_group,today).get("group_rank","")
- records = list(records_set.order_by("-stock_date").values())
- except:
- cur_rank = 0
- records = []
- else:
- cur_rank = 0
- records = []
- for item in records:
- today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
- today_stock = filter(lambda x:x["name"],today_stock)
- item["today_stock"] = today_stock
- item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
- yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
- yesterday_stock = filter(lambda x:x["name"],yesterday_stock)
- item["yesterday_stock"] = yesterday_stock
- item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- #通知
- notices = get_notices()
- ret = {"match_name":match_name,"cur_rank":cur_rank,"records":records,"notices":notices}
- return ret
- def get_player_match_list(request):
- """选手参赛列表数据
- """
- uid = request.user.get("id",0)
- now_str = datetime.datetime.now().strftime("%Y-%m-%d")
- cur_match_id = ccc.get_cur_match().id
- match_ids = list(cm.Player.objects.filter(user_id=uid).values_list("match_id",flat=True))
- matchs = list(cm.Match.objects.filter(id__in=match_ids).values())
- for item in matchs:
- player = cm.Player.objects.filter(user_id=uid,match_id=item["id"]).first()
- item["player_id"] = player.id if player else 0
- return matchs
- def get_group_income(match_id,match_group):
- """
- """
- data = []
- today = datetime.datetime.now().strftime("%Y-%m-%d")
- player_ids = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values_list("id",flat=True))
- for player_id in player_ids:
- 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()
- if today_record:
- data.append(today_record.total_income)
- data = list(set(data))
- data = sorted(data,key=lambda x:x,reverse=True)
- return data
- def get_player_match_detail(request):
- """选手参赛详情数据
- """
- qdata = request.json
- try:
- user_id = request.user.get("id",0)
- except:
- user_id = 0
- match_id = qdata.get("id")
- record_id = qdata.get("record_id")
- userinfo = {}
- cur_user_id = user_id
- if qdata.get("user_id"):
- cur_user_id = qdata.get("user_id")
- today = get_today_date()
- ismine = True if int(cur_user_id) == user_id else False
- if not match_id:
- player = cm.Player.objects.filter(user_id=cur_user_id,match_id=match_id).first()
- match_id =player.match_id
- cur_user_id = player.user_id
- if record_id:
- records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id)
- if records_set:
- match_id = records_set.first().match_id
- else:
- records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("-stock_date")
- match = cm.Match.objects.filter(id=match_id).values().first()
- groups = list(cm.MatchGroup.objects.filter(match_id=match_id).values_list("name",flat=True))
- match["groups"] = groups
- 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")
- if all_records_set:
- records = list(all_records_set.values())
- else:
- records = []
- for item in records:
- item["today_stock"] = json.loads(item["today_stock"]) if item["today_stock"] else []
- item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
- item["yesterday_stock"] = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
- item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- item["avatar"] = get_user_info(item["user_id"])["avatar"]
- today_record = {}
- if records_set:
- today = records_set.first().stock_date
- if record_id:
- today_record = records_set.values().first()
- today_record = format_today_record(today_record)
- else:
- match_group = records_set.first().match_group
- today_record = ccc.get_today_record(cur_user_id,int(match_id),match_group,today)
- if today_record:
- today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
- today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
- today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
- today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
- today_record["match_group_name"] = cm.MatchGroup.objects.filter(id=today_record["match_group"]).first().name
- today_record["players_num"] = cm.Player.objects.filter(match_group=today_record["match_group"]).count()
- today_record["win_rate"] = calc_win_rate(cur_user_id,today_record["match_id"])
- badest = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=cur_user_id,match_id=match_id).order_by("today_income").first()
- if badest:
- today_record["badest_income"] = "{}%".format(badest.today_income*100)
- today_record["today_stock_total"] = round(today_record.get("today_stock_total",0.0),4)
- userinfo = get_user_info(today_record["user_id"])
- today_record["style"] = userinfo.get("style")
- else:
- player_info = get_user_info(cur_user_id)
- today_record = {}
- today_record["stock_date"] = today
- today_record.update(player_info)
- today_record["player_id"] = player_info["id"]
- today_record["avatar"] = get_user_info(cur_user_id)["avatar"]
- userinfo = get_user_info(cur_user_id)
- today_record["style"] = userinfo.get("style")
- today_record["user_id"] = player_info["id"]
- match["groups"] = [today_record.get("match_group_name","")] if today_record else []
- records = sorted(records,key=lambda x:x["stock_date"],reverse=True)
- if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=cur_user_id).exists():
- is_follow = 1
- else:
- is_follow = 0
- if today_record and today_record.get("today_fund"):
- today_record["today_income_fund"] = round((today_record["today_fund"] - today_record["yesterday_fund"])*10000,2) if today_record["yesterday_fund"] else 0.00
- today_record["zan_count"] = today_record.get("zans",0)
- user_info = get_user_info(cur_user_id)
- if user_info.get("phone"):
- del user_info["phone"]
- #查询出入资金
- fund_inout_list = []
- if cm.FundInOut.objects.filter(user_id = cur_user_id,stock_date=today_record["stock_date"]).exists():
- fund_inout_list = list(cm.FundInOut.objects.filter(user_id=cur_user_id,stock_date=today_record["stock_date"]).values())
- ret = {
- "match":match,
- "today_record":today_record,
- "match_group_info":get_group_info(today_record.get("match_group")) if today_record.get("match_group") else {},
- "userinfo":user_info,
- "records":records,
- "is_follow":is_follow,
- "fans":cm.UserFollows.objects.filter(follow_id=cur_user_id).count(),
- "followers":cm.UserFollows.objects.filter(user_id=cur_user_id).count(),
- "stock_age":datetime.datetime.now().year - int(userinfo.get("join_time")) if userinfo.get("join_time") else 0,
- "stock_follow":list(cm.UserChoice.objects.filter(user_id=cur_user_id).values_list("stock_name",flat=True)),
- "fund_inout":fund_inout_list[0] if len(fund_inout_list) > 0 else {}
- }
- return ret
- def get_today_record(player_id,match_id,match_group,today):
- """
- """
- key = "%s_%s_%s_%s" % (player_id,match_id,match_group,today)
- #key = "%s_%s_%s" % (player_id,match_id,today)
- today_record = ccc.cache.get(key)
- today_record = json.loads(today_record) if today_record else {}
- #if match_id:
- # #记得这里上线后要注释掉
- # today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=player_id,match_id=match_id,stock_date=today)
- # today_record = today_record.values().first()
- try:
- if today_record:
- user_info = get_user_info(today_record["user_id"])
- if user_info:
- user_info.pop("id")
- today_record.update(user_info)
- #仓位
- today_stock_total = 0
- today_stock = json.loads(today_record["today_stock"])
- for ts in today_stock:
- if ts["fund"]:
- try:
- today_stock_total += float(ts["fund"])
- except Exception as e:
- print e
- today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
- today_record["today_stock_total"] = today_stock_total
- except Exception as e:
- import traceback
- traceback.print_exc()
- return today_record
- def format_today_record(today_record):
- try:
- if today_record:
- user_info = get_user_info(today_record["user_id"])
- if user_info:
- #user_info.pop("id")
- today_record.update(user_info)
- #仓位
- today_stock_total = 0
- today_stock = json.loads(today_record["today_stock"])
- for ts in today_stock:
- if ts["fund"]:
- try:
- today_stock_total += float(ts["fund"])
- except Exception as e:
- print e
- today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
- today_record["today_stock_total"] = today_stock_total
- # win_rate = ccc.cache.hget("PLAYER_LATEST_%d" % today_record["user_id"],"win_rate")
- # if win_rate:
- # today_record["win_rate"] = str(float(win_rate)*100)+"%"
- # else:
- # today_record["win_rate"] = "0.0%"
-
- win_rate = calc_win_rate(today_record["user_id"],today_record["match_id"])
- today_record["win_rate"] = win_rate
- except Exception as e:
- import traceback
- traceback.print_exc()
- today_record = today_record if today_record else {}
- return today_record
-
- def get_today_record_actual(player_id,match_id,match_group,today=None):
- """
- """
- if today:
- 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)
- else:
- 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")
- today_record = qset.values().first()
- if today_record:
- user_info = get_user_info(today_record["user_id"])
- if user_info:
- user_info.pop("id")
- today_record.update(user_info)
- #仓位
- today_stock_total = 0
- today_stock = json.loads(today_record["today_stock"])
- for ts in today_stock:
- if ts["fund"]:
- try:
- today_stock_total += float(ts["fund"])
- except Exception as e:
- print e
- today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
- today_record["today_stock_total"] = today_stock_total
- return today_record
- @ccc.cache_data()
- def get_match_group_players(match_id,match_group):
- players = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values())
- return players
- #@ccc.cache_data()
- def get_match_group_users(match_id,match_group):
- #users = list(cm.UserMatch.objects.filter(match_id=match_id,match_group=match_group).values())
- users = list(cm.Player.objects.filter(match_id=match_id,match_group=match_group).values())
- return users
- #@ccc.cache_data()
- def get_match_groups(match_id):
- """
- """
- match = cm.Match.objects.filter(id=match_id).values().first()
- groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).order_by("-order").values())
- return match,groups
- def get_cache_rank_list(match_id,today):
- """
- """
- match,groups = get_match_groups(match_id)
- data = []
- for item in groups:
- new_players = []
- players = get_match_group_users(match_id,item["id"])
- win_count = 0
- loss_count = 0
- total_income_win = 0
- total_income_lose = 0
- today_income_win = 0
- today_income_lose = 0
- for player in players:
- user_id = player["user_id"]
- #username = player["signup_name"]
- username = player["username"]
- match_group = player["match_group"]
- today_record = ccc.get_today_record(user_id,match_id,match_group,today)
- if today_record:
- player.update(today_record)
- player["username"] = username
- player["org_today_income"] = player["today_income"]
- player["org_total_income"] = player["total_income"]
- player["total_income"] = "{}%".format(today_record["total_income"]*100)
- player["today_income"] = "{}%".format(today_record["today_income"]*100)
- if player["org_today_income"] >= 0.05:
- win_count += 1
- if player["org_today_income"] <= -0.05:
- loss_count += 1
- if today_record["total_income"] >= 0:
- total_income_win += 1
- else:
- total_income_lose += 1
-
- if today_record["today_income"] >= 0:
- today_income_win += 1
- else:
- today_income_lose += 1
- try:
- player["fund"] = round(player["fund"],4) if player["fund"] else 0.0
- player["init_fund"] = round(player["init_fund"],4)
- player["fund"] = round(player["init_fund"],4)
- player["today_fund"] = round(player["today_fund"],4)
- new_players.append(player)
- except Exception as e:
- print player
- pass
- new_players_sort = list(sorted(new_players,key=lambda x:x["org_total_income"],reverse=True))
- #计算退赛率
- group_id = item["id"]
- player_total = cm.Player.objects.filter(match_id=match_id,match_group=group_id).count()
- player_post_total = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today).count()
- out_rate = (player_total-player_post_total)/float(player_total) if player_total else 0.0
- item["players_num"] = len(players)
- item["win_count"] = win_count
- item["loss_count"] = loss_count
- item["players"] = new_players_sort[:3]
-
-
- try:
- ntotal_income_win = float(total_income_win)/(total_income_win+total_income_lose)*10
- ntotal_income_lose = float(total_income_lose)/(total_income_win+total_income_lose)*10
- except:
- ntotal_income_win = 0.0
- ntotal_income_lose = 0.0
- total_income_win = int(round(ntotal_income_win))
- total_income_lose = int(round(ntotal_income_lose))
-
- item["total_income_win"] = total_income_win
- item["total_income_lose"] = total_income_lose
-
- try:
- ntoday_income_win = float(today_income_win)/(today_income_win+today_income_lose)*10
- ntoday_income_lose = float(today_income_lose)/(today_income_win+today_income_lose)*10
- except:
- ntoday_income_win = 0.0
- ntoday_income_lose = 0.0
- today_income_win = int(round(ntoday_income_win))
- today_income_lose = int(round(ntoday_income_lose))
- item["today_income_win"] = today_income_win
- item["today_income_lose"] = today_income_lose
- item["out_rate"] = "{}%".format(round(out_rate*100,2))
- data.append(item)
- return match,data
- def get_rank_list(request):
- """排名列表
- """
- qdata = request.json
- #user_id = request.user.get("id",0)
- match_id = qdata.get("match_id")
- today = qdata.get("stock_date")
- if not today:
- today = get_today_date()
- match,groups = get_cache_rank_list(match_id,today)
- ret = {"match":match,"groups":groups}
- return ret
- @ccc.cache_data()
- def get_user_info(uid):
- user = cm.UserInfo.objects.filter(id=uid).values().first()
- if user:
- user["style"] = []
- if user["zq"]:
- user["style"].append(user["zq"])
- if user["cw"]:
- user["style"].append(user["cw"])
- if user["df"]:
- user["style"].append(user["df"])
- if user.get("phone"):
- del user["phone"]
- return user
- def get_user_info_actual(uid):
- user = cm.UserInfo.objects.filter(id=uid).values().first()
- if user:
- user["style"] = []
- if user["zq"]:
- user["style"].append(user["zq"])
- if user["cw"]:
- user["style"].append(user["cw"])
- if user["df"]:
- user["style"].append(user["df"])
- if user.get("phone"):
- del user["phone"]
- return user
- #@ccc.cache_data()
- def get_player_info(player_id):
- player = cm.Player.objects.filter(id=player_id).values().first()
- return player
- @ccc.cache_data()
- def get_player_info_cache(player_id):
- player = cm.Player.objects.filter(id=player_id).values().first()
- return player
- @ccc.cache_data()
- def get_match_info(match_id):
- match = cm.Match.objects.filter(id=match_id).values().first()
- return match
- @ccc.cache_data()
- def get_group_info(group_id):
- group = cm.MatchGroup.objects.filter(id=group_id).values().first()
- if group:
- group["players_num"] = cm.Player.objects.filter(match_group=group["id"]).count()
- return group
- else:
- return {}
- def get_group_rank_list(request):
- """排名列表
- """
- qdata = request.json
- kwargs = qdata
- group_id = qdata.get("id")
- match_id = qdata.get("match_id")
- match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id
- today = qdata.get("stock_date")
- if not today:
- today = get_today_date()
- match = get_match_info(match_id)
- group = get_group_info(group_id)
- players = get_match_group_users(match_id,group_id)
- new_players = []
- for player in players:
- user_id = player["user_id"]
- #user = get_user_info(user_id)
- #username = user["username"] if user else ""
- #username = player["signup_name"]
- username = player["username"]
- match_group = group_id
- today_record = ccc.get_today_record(user_id,match_id,match_group,today)
- if today_record:
- player.update(today_record)
- player["username"] = username
- player["org_today_income"] = player["today_income"]
- player["org_total_income"] = player["total_income"]
- player["total_income"] = "{}%".format(player["total_income"]*100)
- player["today_income"] = "{}%".format(player["today_income"]*100)
- player["fund"] = round(player["fund"],4)
- player["init_fund"] = round(player["init_fund"],4)
- player["today_fund"] = round(player["today_fund"],4)
- new_players.append(player)
- if kwargs.get("order_by") == "today_income__asc":
- new_players = sorted(new_players,key=lambda x:x["org_today_income"])
- elif kwargs.get("order_by") == "today_income__desc" :
- new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True)
- elif kwargs.get("order_by") == "total_income__asc":
- new_players = sorted(new_players,key=lambda x:x["org_total_income"])
- elif kwargs.get("order_by") == "total_income__desc":
- new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
- else:
- new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
- #分页
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",50))
- #page_size = 50
- if page and page_size:
- total,new_players = ccf.get_page_list(new_players,page,page_size)
- else:
- total = len(new_players)
- #应到、实到、请假人数
- total_person = cm.Player.objects.filter(match_group=group_id,match_status=1).count()
- actual_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today).count()
- leave_person = total_person - actual_person
- win_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__gte=0).count()
- loss_person = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_group=group_id,stock_date=today,total_income__lt=0).count()
- ret = {"group":group,"players":new_players,"total":total,"total_person":total_person,
- "actual_person":actual_person,"leave_person":leave_person,"win_person":win_person,"loss_person":loss_person}
- return ret
- def get_player_match_records(request):
- """选手参赛每日持股
- """
- qdata = request.json
- match_id = qdata.get("id")
- user_id = qdata.get("user_id")
- page = int(qdata.get("page",0))
- page_size = int(qdata.get("page_size",20))
- records_set = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).order_by("-stock_date")
- data = list(records_set.values())
- for item in data:
- today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
- today_stock = filter(lambda x:x["name"],today_stock if today_stock else [])
- item["today_stock"] = today_stock
- item["today_stock_img"] = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
- yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
- yesterday_stock = filter(lambda x:x["name"],yesterday_stock if yesterday_stock else [])
- item["yesterday_stock"] = yesterday_stock
- item["yesterday_stock_img"] = json.loads(item["yesterday_stock_img"]) if item["yesterday_stock_img"] else []
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- item["zans_count"] = item.get("zans",0)
- item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- return total,data
- else:
- return len(data),data
- def add_model(cls,**kwargs):
- """
- """
- model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
- model = getattr(cm,model_name)
- if model_name == "PlayerRecord":
- user_id = kwargs.get("user_id")
- match_id = kwargs.get("match_id")
- stock_date = kwargs.get("stock_date")
- now = datetime.datetime.now()
- if not cm.Player.objects.filter(user_id=user_id,match_id=match_id).exists():
- raise ce.TipException(u"比赛未开赛/未报名")
- if now.weekday() in [5,6] or not now.strftime("%Y-%m-%d") in get_match_validdates(match_id):
- raise ce.TipException(u"今日不能提交数据!")
- now_time = datetime.datetime.now().strftime("%H:%S")
- if not user_id in [9600,6209,5709,25953]:
- if now_time<"15:00" or now_time > "23:50":
- raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
- stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
- today_stock = json.dumps(kwargs.get("today_stock"))
- today_stock_img = json.dumps(kwargs.get("today_stock_img"))
- today_fund = float(kwargs.get("today_fund",0))
- is_markt = int(kwargs.get("is_markt",0))
- experience = kwargs.get("experience")
- if not ccc.get_cur_match().id == match_id:
- raise ce.TipException(u"非当前赛事参赛选手不能提交作业!")
- #计算今日和昨日盈亏
- if float(today_fund)>9999 or float(today_fund)<=0:
- raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
- player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
- user_id = player.user_id
- init_fund = player.fund
- user = cm.UserInfo.objects.filter(id=user_id).first()
- username = user.username
- usercode = user.usercode
- match_group = player.match_group
- opmode_group = player.opmode_group
- zq = user.zq
- cw = user.cw
- df = user.df
- match = cm.Match.objects.filter(id=match_id).first()
- if player.match_status < 1:
- raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
- now_date = datetime.datetime.now().strftime("%Y-%m-%d")
- if not user_id in [9600,6209,5709]:
- if match.end_time < now_date:
- raise ce.TipException(u"该比赛已结束或您未参加此次比赛不能提交数据!")
- validdates = get_match_validdates(match_id)
- today_index = validdates.index(stock_date)
- yesterday_index = today_index -1 if today_index >=1 else 0
- yesterday_date = validdates[yesterday_index]
- yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
- match_id=match_id,user_id=user_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
- if yesterday:
- yesterday_fund = yesterday.today_fund
- yesterday_stock = yesterday.today_stock
- yesterday_stock_img = yesterday.today_stock_img
- yesterday_is_markt = yesterday.is_markt
- else:
- yesterday_fund = today_fund
- yesterday_stock = ""
- yesterday_stock_img = ""
- yesterday_is_markt = 0
- if kwargs.get("id"):
- if cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).count()==1:
- init_fund = today_fund
- cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund)
- else:
- if not cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id).exists():
- init_fund = today_fund
- cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=today_fund)
- with transaction.atomic():
- #记录持股情况
- today_stock_fund = 0
- new_stock_list = []
- today_stock_list = json.loads(today_stock)
- month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1])
- for ts in today_stock_list:
- if ts["name"] and ts["fund"]:
- try:
- stock,flag = cm.Stock.objects.get_or_create(
- name = ts["name"]
- )
- stock_id = stock.id
- usobj,flag = cm.UserStock.get_db_model(month).objects.get_or_create(
- stock_id = stock_id,
- player_id = player.id,
- stock_date = stock_date
- )
- if ts.get("fund"):
- usobj.fund = ts["fund"]
- try:
- today_stock_fund += float(ts["fund"])
- except:
- pass
- if ts.get("name"):
- usobj.stock_name = ts.get("name")
- if match_group:
- usobj.match_group = match_group
- if opmode_group:
- usobj.opmode_group = opmode_group
- usobj.save()
- ts["stock_id"] = stock_id
- new_stock_list.append(ts)
- except Exception as e:
- print(e)
- today_stock = json.dumps(new_stock_list)
- obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
- user_id=user_id,
- match_id=match_id,
- stock_date=stock_date)
- #计算仓位
- today_cangwei = round(today_stock_fund/today_fund,4)*100
- obj.init_fund = init_fund
- obj.yesterday_fund = yesterday_fund
- obj.yesterday_stock = yesterday_stock
- obj.yesterday_stock_img = yesterday_stock_img
- obj.today_fund = today_fund
- obj.today_stock_total = today_stock_fund
- obj.today_cangwei = today_cangwei
- obj.today_stock = today_stock
- obj.today_stock_img = today_stock_img
- obj.username = username
- obj.usercode = usercode
- obj.match_group = match_group
- obj.opmode_group = opmode_group
- obj.is_markt = is_markt
- obj.yesterday_is_markt = yesterday_is_markt
- obj.zq = zq
- obj.cw = cw
- obj.df = df
- obj.experience = experience
- #计算今日收益和总收益
- if float(today_fund)>9999 or float(today_fund)<=0:
- raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
-
- #如果今日持仓金额大于总资产的10倍,则提示数据有问题
- if today_stock_fund > float(today_fund)*10:
- raise ce.TipException(u"今日持仓金额有误,请修改持仓金额!")
- #有资金出入
- if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists() and player.fund>0:
- fundinout = cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).first()
- fundin = fundinout.fundin
- fundout = fundinout.fundout
- today_income = 0.0
- total_income = 0.0
-
- #入资金
- if fundin > fundout:
- fundin = fundin - fundout
- if yesterday:
- today_income = (today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin)
- obj.yesterday_fund = obj.yesterday_fund + fundin
- else:
- today_income = 0.0
-
- obj.today_income = round(today_income,4)
-
-
- if flag:
- total_income = (today_fund-init_fund-fundin)/(init_fund+fundin)
- cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=init_fund+fundin)
- obj.init_fund = init_fund + fundin
- else:
- total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
-
- obj.total_income = round(total_income,4)
-
- #出资金
- else:
- fundout = fundout - fundin
- if yesterday:
- today_income = (today_fund-(yesterday_fund-fundout))/float(yesterday_fund)
- obj.yesterday_fund = round(today_fund/(1+today_income),4)
- else:
- today_income = 0.0
-
- obj.today_income = round(today_income,4)
-
- if flag:
- total_income = (today_fund+fundout-init_fund)/init_fund if init_fund else 0.0
- cm.Player.objects.filter(user_id=user_id,match_id=match_id).update(fund=round(today_fund/(1+total_income),4))
- obj.init_fund = round(today_fund/(1+total_income),4)
- else:
- total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
- obj.total_income = round(total_income,4)
-
- if float(today_income)>0.6:
- raise ce.TipException(u"今日盈利已超过60%,请仔细核对数据或直接联系顽主!")
-
- if float(total_income)>20:
- raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
-
- else:
- today_income = (today_fund - yesterday_fund)/float(yesterday_fund) if yesterday_fund else 0.0
- total_income = (today_fund - init_fund)/float(init_fund) if init_fund else 0.0
- if float(today_income)>0.6:
- raise ce.TipException(u"今日盈利已超过60%,请仔细核对数据或直接联系顽主!")
- if float(total_income)>20:
- raise ce.TipException(u"请仔细核对数据或直接联系顽主!")
- obj.today_income = round(today_income,4)
- obj.total_income = round(total_income,4)
- if not flag:
- obj.ctime = datetime.datetime.now()
- obj.save()
- #更新group_rank
- #ccc.cache.lpush(settings.RANK_LIST,obj.id)
- ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(obj.match_id,obj.id))
- if model_name == "PlayerRecord":
- rst = {"id":obj.id,"user_id":obj.user_id,"match_id":match_id}
- return rst
- else:
- return obj.id
- obj = model.objects.create(**kwargs)
- return obj.id
- def update_model(cls,**kwargs):
- """
- """
- model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
- model = getattr(cm,model_name)
- id = kwargs.pop("id")
- rst = model.objects.filter(id=id).update(**kwargs)
- if model_name == "Match":
- for item in kwargs.get("groups").split(","):
- cm.MatchGroup.objects.get_or_create(match_id=obj.id,name=item)
- return rst
- def delete_model(cls,**kwargs):
- """
- """
- model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
- model = getattr(cm,model_name)
- ids = str(kwargs.get("id")).split(",")
- rst = model.objects.filter(id__in=ids).delete()
- if model_name == "Comments":
- cm.Comments.objects.filter(pid__in=ids).delete()
- return ids
- def get_search_list(cls,**kwargs):
- """
- """
- model_name = re.search(r'.*\.(\w+)SearchView',str(cls.__class__)).groups()[0]
- model = getattr(cm,model_name)
- qset = model.objects.all()
- if model_name == "Stock":
- if kwargs.get("name"):
- qset = qset.filter(Q(name__icontains=kwargs.get("name"))|Q(code__icontains=kwargs.get("name")))
- else:
- if kwargs.get("name"):
- qset = qset.filter(name__icontains=kwargs.get("name"))
- if model_name == "Player":
- data = list(qset.values("id","username"))
- if model_name == "Stock":
- qset = qset.filter(code__isnull=False)
- data = list(qset.values("id","name","code"))
- for item in data:
- if item["code"]:
- item["label"] = "%s(%s)" % (item["name"],item["code"])
- else:
- item["label"] = "%s" % item["name"]
- else:
- data = list(qset.values("id","name"))
- return data
- def get_detail_info(cls,**kwargs):
- """
- """
- model_name = re.search(r'.*\.(\w+)View',str(cls.__class__)).groups()[0]
- model = getattr(cm,model_name)
- id = kwargs.get("id")
- rst = list(model.objects.filter(id=id).values())
- rst = rst[0] if rst else {}
- if model_name == "Article":
- rst["ctime"] = ccf.datetime_to_str(rst["ctime"],"%Y-%m-%d")
- if model_name == "Stock":
- rst["choiced"] = ccc.cache.get("%s_choices" % id)
- rst["user_num"] = ccc.cache.get("%s_choices" % id)
- if model_name == "UserArticleRelation":
- article_ids = rst["article_ids"].split(",")
- articles = list(cm.Article.objects.filter(id__in=article_ids).values())
- rst["articles"] = articles
- return rst
- #@ccc.cache_data()
- def get_record_info(rcid):
- """
- """
- rst = cm.PlayerRecord.objects.filter(id=rcid).values().first()
- if rst:
- rst["match_group"] = cm.MatchGroup.objects.filter(id=rst["match_group"]).first().name
- today_stock = json.loads(rst["today_stock"]) if rst["today_stock"] else []
- today_stock = filter(lambda x:x["fund"] and x["name"],today_stock if today_stock else [])
- rst["today_stock"] = today_stock
- today_stock_img = json.loads(rst["today_stock_img"]) if rst["today_stock_img"] else []
- rst["today_stock_img"] = today_stock_img
- yesterday_stock = json.loads(rst["yesterday_stock"]) if rst["yesterday_stock"] else []
- yesterday_stock = filter(lambda x:x["fund"] and x["name"],yesterday_stock if yesterday_stock else [])
- rst["yesterday_stock"] = yesterday_stock
-
- yesterday_stock_img = json.loads(rst["yesterday_stock_img"]) if rst["yesterday_stock_img"] else []
- rst["yesterday_stock_img"] = yesterday_stock_img
- rst["today_income"] = "{}%".format(rst["today_income"]*100)
- rst["total_income"] = "{}%".format(rst["total_income"]*100)
- return rst
- def get_list_info(cls,**kwargs):
- """
- """
- model_name = re.search(r'.*\.(\w+)ListView',str(cls.__class__)).groups()[0]
- model = getattr(cm,model_name)
- qset = model.objects.all()
- if kwargs.get("name"):
- qset = qset.filter(name__icontains=kwargs.get("name"))
- if model_name == "UserInfo":
- if kwargs.get("username"):
- qset = qset.filter(username__icontains=kwargs.get("username"))
- if kwargs.get("usercode"):
- qset = qset.filter(usercode=kwargs.get("usercode"))
- if model_name == "StockComments":
- if kwargs.get("stock_id"):
- qset = qset.filter(stock_id=kwargs.get("stock_id"))
- if model_name == "UserArticleRelation":
- data = list(qset.order_by("-id").values("id","user_id","user_name","user_avatar"))
- else:
- data = list(qset.order_by("-id").values())
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- if model_name == "Player":
- for item in data:
- user = cm.UserInfo.objects.filter(id=item["user_id"]).first()
- match = cm.Match.objects.filter(id=item["match_id"]).first()
- item["username"] = user.username
- item["usercode"] = user.usercode
- item["match_name"] = match.name if match else ""
- return (total,data)
- else:
- return len(data),data
- return rst
- def add_player_record_single(**kwargs):
- """用户单独上传数据
- """
- return None
- now = datetime.datetime.now()
- if now.weekday() in [5,6] or now.strftime("%Y-%m-%d") in MISS_DATES:
- raise ce.TipException(u"今日不能提交数据!")
- now_time = datetime.datetime.now().strftime("%H:%S")
- if now_time<"15:00" or now_time > "23:50":
- raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
- usercode = kwargs.get("usercode")
- match_id = kwargs.get("match_id")
- if not cm.Player.objects.filter(usercode=usercode,match_id=match_id).exists():
- raise ce.TipException(u"用户代码错误")
- stock_date = kwargs.get("stock_date")
- #stock_date = "2022-04-26"
- stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
- today_stock = json.dumps(kwargs.get("today_stock"))
- today_stock_img = json.dumps(kwargs.get("today_stock_img"))
- today_fund = float(kwargs.get("today_fund"))
- is_markt = int(kwargs.get("is_markt",0))
- if int(today_fund)>9999 or int(today_fund)<0:
- raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
- player = cm.Player.objects.filter(usercode=usercode,match_id=match_id).first()
- #if player.fund <=0 :
- # raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
- player_id = player.id
- user_id = player.user_id
- init_fund = player.fund
- user = cm.UserInfo.objects.filter(id=user_id).first()
- username = user.username
- usercode = user.usercode
- match_group = player.match_group
- match = cm.Match.objects.filter(id=match_id).first()
- if player.match_status < 1:
- raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
- now_date = datetime.datetime.now().strftime("%Y-%m-%d")
- if match.end_time < now_date:
- raise ce.TipException(u"该比赛已结束!")
- #yesterday = cm.PlayerRecord.objects.filter(
- # match_id=match_id,player_id=player_id).order_by("-id").first()
- yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
- match_id=match_id,player_id=player_id).order_by("-stock_date").first()
- if yesterday:
- yesterday_fund = yesterday.today_fund
- yesterday_stock = yesterday.today_stock
- yesterday_stock_img = yesterday.today_stock_img
- else:
- #yesterday_fund = init_fund
- yesterday_fund = today_fund
- init_fund = today_fund
- yesterday_stock = ""
- yesterday_stock_img = ""
- cm.Player.objects.filter(id=player_id).update(fund=today_fund)
- #记录持股情况
- new_stock_list = []
- today_stock_list = json.loads(today_stock)
- for ts in today_stock_list:
- if ts["name"]:
- stock,flag = cm.Stock.objects.get_or_create(
- name = ts["stock"]
- )
- stock_id = stock.id
- usobj,flag = cm.UserStock.objects.get_or_create(
- player_id = player_id,
- stock_id = stock_id,
- stock_name = ts["name"],
- stock_date = stock_date
- )
- ts["stock_id"] = stock_id
- new_stock_list.append(ts)
- today_stock = json.dumps(new_stock_list)
- obj,flag = cm.PlayerRecord.get_db_model(match_id).objects.get_or_create(
- player_id=player_id,
- match_id=match_id,
- stock_date=stock_date)
- obj.init_fund = init_fund
- obj.yesterday_fund = yesterday_fund
- obj.yesterday_stock = yesterday_stock
- obj.yesterday_stock_img = yesterday_stock_img
- obj.today_fund = today_fund
- obj.today_stock = today_stock
- obj.today_stock_img = today_stock_img
- obj.user_id = user_id
- obj.username = username
- obj.usercode = usercode
- obj.match_group = match_group
- obj.is_markt = is_markt
- #计算今日和昨日盈亏
- today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
- total_income = (today_fund - init_fund)/float(init_fund)
- #if int(today_fund)>9999 or int(today_fund)<0:
- # raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")
- if int(today_income)>2:
- raise ce.TipException(u"数据错误,今日盈利已超过2倍,请仔细核对数据!")
- obj.today_income = round(today_income,4)
- obj.total_income = round(total_income,4)
- if not flag:
- obj.ctime = datetime.datetime.now()
- obj.save()
- #更新股票持股人数
- for stock in new_stock_list:
- cm.Stock.objects.filter(id=stock["id"]).update(user_num=F("user_num")+1)
- #更新group_rank
- #update_group_rank(match_id,match_group,obj.stock_date)
- ccc.cache.lpush(settings.RANK_LIST,obj.id)
- return obj.id
- def get_single_match_info(match_id):
- """
- """
- if not match_id:
- match = cm.Match.objects.all().order_by("-id").values().first()
- else:
- match = cm.Match.objects.filter(id=match_id).values().first()
- now_date = datetime.datetime.now().strftime("%Y-%m-%d")
- return now_date,match
- def get_cur_record(request):
- """
- """
- user_id = request.user.get("id")
- match_id = ccc.get_cur_match().id
- stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
- 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")
- data = qset.values().first() if qset else {}
- if data:
- data["today_stock_img"] = json.loads(data["today_stock_img"]) if data["today_stock_img"] else []
- data["today_stock"] = json.loads(data["today_stock"]) if data["today_stock"] else []
- return data
- def follow_player(**kwargs):
- """
- """
- user_id = kwargs.get("user_id")
- follow_id = kwargs.get("follow_id")
- if kwargs.get("action") == "cancel":
- cm.UserFollows.objects.filter(user_id=user_id,follow_id=follow_id).delete()
- return True
- else:
- obj,flag = cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=follow_id)
- return obj.id
- def calc_win_rate(player_id,match_id):
- """计算胜率
- """
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=player_id)
- win_rate = qset.filter(today_income__gt=0).count()/float(qset.count()) if qset else 0.0
- win_rate = round(win_rate,3)
- win_rate = "{}%".format(win_rate*100)
- return win_rate
- def get_user_follower(request):
- """获取用户列表
- """
- user_id = request.user.get("id")
- match_id = ccc.get_cur_match().id
- qdata = request.json
- if qdata.get("user_id"):
- user_id = int(qdata.get("user_id"))
- _today = get_today_date()
- data = []
- qset = cm.UserFollows.objects.filter(follow_id=user_id)
- follow_ids = list(qset.values_list("user_id",flat=True))
-
- userset = cm.UserInfo.objects.filter(id__in=follow_ids)
- data = list(userset.values())
- page = int(qdata.get("page",1))
- page_size = int(qdata.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- return total,data
- else:
- return len(data),data
-
- #
- for player_id in follow_ids:
- latest_key = "PLAYER_LATEST_%d"%player_id
- _match_id = ccc.cache.hget(latest_key,"match_id")
- _today = ccc.cache.hget(latest_key,"stock_date")
- _match_group = ccc.cache.hget(latest_key,"match_group")
- today_record = ccc.get_today_record(player_id,_match_id,_match_group,_today)
- if today_record:
- data.append(today_record)
- #data.append(today_record)
- data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
- _today = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"stock_date")
- cur_user_latest = "PLAYER_LATEST_%d" % user_id
- _match_group = ccc.cache.hget(cur_user_latest,"match_group")
- cur_today_record = ccc.get_today_record(user_id,match_id,_match_group,_today)
- if cur_today_record:
- data.insert(0,cur_today_record)
- page = int(qdata.get("page",1))
- page_size = int(qdata.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- for item in data:
- if item:
- today_stock = json.loads(item["today_stock"])
- today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
- item["today_stock"] = today_stock
- item["today_stock_img"] = json.loads(item["today_stock_img"])
- win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
- if win_rate:
- item["win_rate"] = str(float(win_rate)*100)+"%"
- else:
- item["win_rate"] = "0.0%"
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- if item.get("phone"):
- del item["phone"]
- return total,data
- else:
- return len(data),data
- def get_user_follows(request):
- """获取用户关注的选手列表
- """
- user_id = request.user.get("id",0)
- qdata = request.json
- if qdata.get("user_id"):
- user_id = qdata.get("user_id")
- qset = cm.UserFollows.objects.filter(user_id=user_id)
- follow_ids = list(qset.values_list("follow_id",flat=True))
- userset = cm.UserInfo.objects.filter(id__in=follow_ids)
- data = list(userset.values())
- page = int(qdata.get("page",1))
- page_size = int(qdata.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- for item in data:
- if item.get("phone"):
- del item["phone"]
- return total,data
- else:
- return len(data),data
- today = get_today_date()
- _today = today
- data = []
- for user_id in follow_ids:
- latest_key = "PLAYER_LATEST_%d"%user_id
- _match_id = ccc.cache.hget(latest_key,"match_id")
- _today = ccc.cache.hget(latest_key,"stock_date")
- _match_group = ccc.cache.hget(latest_key,"match_group")
- today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
- if today_record:
- today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
- today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
- data.append(today_record)
- data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
- page = int(qdata.get("page",1))
- page_size = int(qdata.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- for item in data:
- if item:
- try:
- user_id = item["user_id"]
- latest_key = "PLAYER_LATEST_%d"%user_id
- today_stock = json.loads(item["today_stock"])
- today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
- item["today_stock"] = today_stock
- item["today_stock_img"] = json.loads(item["today_stock_img"])
- win_rate = ccc.cache.hget(latest_key,"win_rate")
- if win_rate:
- item["win_rate"] = str(float(win_rate)*100)+"%"
- else:
- item["win_rate"] = "0.0%"
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- item["zans_count"] = item.get("zans",0)
- item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
- del item["phone"]
- except Exception as e:
- print(e)
- return total,data
- else:
- return len(data),data
- def get_hot_stock_rank(**kwargs):
- """
- """
- data = {
- "hot_buy":[
- {"stock_name":u"创业黑马","count":12}
- ],
- "hot_sell":[
- {"stock_name":u"创业黑马","count":12}
- ]
- }
- return data
- #@ccc.cache_data()
- def get_stock_info(stock_id):
- """
- """
- stock = cm.Stock.objects.filter(id=stock_id).values().first()
- stock["choiced"] = 1
- nbc = cm.StockComments.objects.filter(stock_id=stock_id).order_by("-id").values().first()
- if nbc:
- stock["last_nb_comments"] = nbc
- return stock
-
- @ccc.cache_data()
- def get_stock_cache(stock_id):
- stock = cm.Stock.objects.filter(id=stock_id).values().first()
- return stock
- def get_hot_stock_buy(**kwargs):
- """
- """
- stock_date = kwargs.get("stock_date")
- month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1])
- qset = cm.UserStock.get_db_model(month).objects.filter(stock_date=stock_date,fund__gt=0)
- if kwargs.get("name"):
- qset = qset.filter(stock_name__icontains=kwargs.get("name"),stock_date=stock_date)
-
- if int(kwargs.get("fund_rank",0)) == 1:
- qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-total_fund")
- else:
- qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-count")
- data = []
- for q in qset:
- stock_id = q["stock_id"]
- count = q["count"]
- stock_name = q.get("stock_name")
- total_fund = q["total_fund"]
- comments_count = ccc.cache.get("%s_comments" % stock_id)
- choice_count = ccc.cache.get("%s_choices" % stock_id)
- comments_count = comments_count if comments_count else 0
- choice_count = choice_count if choice_count else 0
- data.append({"stock_name":stock_name,"id":stock_id,"count":count,"comments_count":comments_count,"choice_count":choice_count,"total_fund":total_fund})
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- for item in data:
- #stock = cm.Stock.objects.filter(id=item["id"]).first()
- stock = get_stock_cache(item["id"])
- if stock:
- item["stock_code"] = stock.get("code","")
- item["stock_desc"] = stock.get("desc","")
- return total,data
- else:
- return len(data),data
- return data
- def get_hot_follow(**kwargs):
- """
- """
- stock_date = kwargs.get("stock_date")
- match_id = kwargs.get("match_id")
- if not match_id:
- match_id = ccc.get_cur_match().id
- #player_ids = list(cm.Player.objects.filter(match_id=cur_match_id,match_status=1).values_list("id",flat=True))
- player_ids = list(cm.Player.objects.filter(match_id=match_id).values_list("user_id",flat=True))
- qset = cm.UserFollows.objects.filter(follow_id__in=player_ids)
- qset = qset.values("follow_id").annotate(count=Count("follow_id")).order_by("-count")
- data = []
- for q in qset:
- player_id = q["follow_id"]
- count = q["count"]
- today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
- match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
- match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
- badest_income = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"badest_income")
- today_record = get_today_record(player_id,match_id,match_group,today)
- if today_record:
- userinfo = get_user_info(today_record["user_id"])
- user_id = today_record["user_id"]
- win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"win_rate")
- try:
- win_rate = str(float(win_rate)*100)+"%"
- except:
- pass
- if userinfo:
- data.append(
- {
- "player_name":userinfo.get("username"),
- "count":count,
- "id":player_id,
- "user_id":user_id,
- "today_fund":today_record["today_fund"],
- "total_income":"{}%".format(today_record["total_income"]*100),
- "today_income":"{}%".format(today_record["today_income"]*100),
- "badest_income":"{}%".format(badest_income*100) if badest_income else "0.0%",
- "style":userinfo.get("style"),
- "badge":userinfo.get("badge"),
- "match_id":match_id,
- "win_rate":win_rate
- }
- )
- if kwargs.get("name"):
- data = filter(lambda x:kwargs.get("name") in x["player_name"],data)
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- return total,data
- else:
- return len(data),data
- return data
- def get_hot_stock_sell(**kwargs):
- """
- """
- stock_date = kwargs.get("stock_date")
- stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
- yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
- ##昨天所有股票
- #yes_stock_ids = list(cm.UserStock.objects.filter(stock_date=yesterday).values_list("stock_id",flat=True))
- #yes_stock_ids = list(set(yes_stock_ids))
- #data = []
- #for ysi in yes_stock_ids:
- # yes_count = cm.UserStock.objects.filter(stock_date=yesterday,stock_id=ysi).count()
- # td_count = cm.UserStock.objects.filter(stock_date=stock_date,stock_id=ysi).count()
- # if td_count < yes_count:
- # stock_name = cm.Stock.objects.filter(id=ysi).first().name
- # data.append({"stock_name":stock_name,"count":yes_count-td_count,"id":ysi})
- qset = cm.HotStockSellCount.objects.filter(stock_date=stock_date)
- if kwargs.get("name"):
- qset = qset.filter(stock_name__icontains=kwargs.get("name"))
- qset = qset.order_by("-count")
- data = list(qset.values("stock_name","stock_id","count"))
- for item in data:
- item["id"] = item["stock_id"]
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- return total,data
- else:
- return len(data),data
- return data
- def get_stock_info(_id):
- """
- """
- data = cm.Stock.objects.filter(id=_id).values().first()
- nbc = cm.StockComments.objects.filter(stock_id=_id).order_by("-id").values().first()
- if nbc:
- data["last_nb_comments"] = nbc
- return data
- def get_hot_stock_sell_players(**kwargs):
- """
- """
- _id = kwargs.get("id")
- stock_date = kwargs.get("stock_date")
- month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1])
- stock_date_time = ccf.str_to_datetime(kwargs.get("stock_date"),"%Y-%m-%d")
- yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
- #昨天持股选手
- yes_players = list(cm.UserStock.get_db_model(month).objects.filter(stock_date=yesterday,stock_id=_id).values_list("player_id",flat=True))
- td_players = list(cm.UserStock.get_db_model(month).objects.filter(stock_date=stock_date,stock_id=_id).values_list("player_id",flat=True))
- sell_players = list(set(yes_players)-set(td_players))
- data = []
- for player_id in sell_players:
- #player = cm.Player.objects.filter(id=player_id).first()
- player = get_player_info_cache(player_id)
- if player:
- match_id = player["match_id"]
- match_group = player["match_group"]
- today_record = get_today_record(player_id,match_id,match_group,stock_date)
- if today_record:
- today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
- today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
- today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
- today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
- data.append(today_record)
- data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- return total,data
- else:
- return len(data),data
- return data
- def get_win_rate_rank(request):
- """
- """
- player_id = request.player.id
- match_id = request.player.match_id
- match_group = request.player.match_group
- kwargs = request.json
- match_id = ccc.get_cur_match().id
- qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lt=5,match_status=1).order_by("-win_rate")
- data = list(qset.values())
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- for item in data:
- item["win_rate"] = "{}%".format(item["win_rate"]*100)
- item["badest_income"] = "{}%".format(item["badest_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- userinfo = get_user_info(item["user_id"])
- if userinfo:
- item["badge"] = userinfo.get("badge")
- item["style"] = userinfo.get("style")
- item["username"] = userinfo.get("username")
- return total,data
- def get_defend_rank(request):
- """
- """
- player_id = request.player.id
- match_id = request.player.match_id
- match_group = request.player.match_group
- kwargs = request.json
- qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lte=5,match_status=1).order_by("-badest_income")
- data = list(qset.values())
- #data = []
- #for item in datas:
- # player = cm.Player.objects.filter(id=item["player_id"]).first()
- # item["match_status"] = player.match_status if player else -1
- # if item["match_status"] > -1:
- # data.append(item)
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- for item in data:
- item["win_rate"] = "{}%".format(item["win_rate"]*100)
- item["badest_income"] = "{}%".format(item["badest_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- userinfo = get_user_info(item["user_id"])
- if userinfo:
- item["badge"] = userinfo.get("badge")
- item["style"] = userinfo.get("style")
- item["username"] = userinfo.get("username")
- return total,data
- @ccc.cache_data_kw(10*60)
- def get_champion_articles_list(**kwargs):
- """
- """
- #kwargs = request.json
- _type = kwargs.get("type")
- isbanner = kwargs.get("isbanner")
- category = kwargs.get("category")
- qset = cm.Article.objects.filter(status=2).exclude(type="notice").order_by("-isbanner","-ishot","-id")
- if _type:
- qset = qset.filter(type=_type)
- if isbanner:
- qset = qset.filter(isbanner=isbanner)
- if category:
- qset = qset.filter(category=category)
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- data = list(qset.values("name","ctime","id","img"))
- for item in data:
- item["ctime"] = ccf.datetime_to_str(item["ctime"],"%Y-%m-%d")
- return total,data
- def get_wanzhu_comment(**kwargs):
- """
- """
- match_id = kwargs.get("match_id")
- group_id = kwargs.get("group_id")
- today = get_today_date()
- players = get_match_group_players(match_id,group_id)
- new_players = []
- for player in players:
- user_id = player["user_id"]
- user = get_user_info(user_id)
- username = user["username"] if user else ""
- player_id = player["id"]
- match_group = group_id
- today_record = get_today_record(player_id,match_id,int(match_group),today)
- if today_record and today_record.get("wanzhu_comment"):
- player.update(today_record)
- player["username"] = username
- player["total_income"] = "{}%".format(player["total_income"]*100)
- player["fund"] = round(player["fund"],4)
- player["init_fund"] = round(player["init_fund"],4)
- player["today_fund"] = round(player["today_fund"],4)
- player["today_stock"] = json.loads(player["today_stock"]) if player["today_stock"] else []
- new_players.append(player)
- new_players = sorted(new_players,key=lambda x:x["group_rank"])
- data = new_players
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- return total,data
- def get_enum_list(request):
- """
- """
- data = {
- "zq":[
- u"短线博弈",
- u"长线价投",
- u"长短兼备"
- ],
- "cw":[
- u"分仓开超市",
- u"重仓押注",
- u"全仓单钓",
- u"融资加倍"
- ],
- "df":[
- u"低吸",
- u"半路",
- u"首板",
- u"接力",
- u"撬板",
- u"T加0",
- u"隔夜卖",
- u"格局锁仓",
- u"核按钮"
- ],
- "pz":[
- u"10厘米",
- u"20厘米",
- u"30厘米",
- u"N/C新股",
- u"次新股",
- u"可转债",
- u"港股",
- u"基金",
- u"逆回购"
- ]
- }
- return data
- def get_player_list(**kwargs):
- """选手列表
- """
- match_id = kwargs.get("match_id")
- today = get_today_date()
- #qset = cm.Player.objects.filter(match_id=match_id,match_status=1)
- qset = cm.Player.objects.filter(match_status=1)
- if kwargs.get("name"):
- qset = qset.filter(username__icontains=kwargs.get("name"))
- qset = qset.values("username").distinct().order_by("-id")
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- data = list(qset.values())
- for item in data:
- #print(item)
- match_id = item["match_id"]
- match_group = item["match_group"]
- user_id = item["user_id"]
- player_id = item["id"]
- #user = cm.UserInfo.objects.filter(id=user_id).first()
- today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
- match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
- match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
- today_record = get_today_record(player_id,match_id,match_group,today)
- if today_record:
- today_record.pop("id")
- item.update(today_record)
- user_info = get_user_info(user_id)
- if user_info:
- user_info.pop("id")
- item.update(user_info)
- if item.get("today_income"):
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- if kwargs.get("zq"):
- data = filter(lambda x:kwargs.get("zq") == x.get("zq"),data)
- if kwargs.get("cw"):
- data = filter(lambda x:kwargs.get("cw") == x.get("cw"),data)
- if kwargs.get("df"):
- data = filter(lambda x:kwargs.get("df") == x.get("df"),data)
- return total,data
- def get_mine_style(request):
- """
- """
- user = request.user
- #player = request.player
- user = cm.UserInfo.objects.filter(id=user["id"]).first()
- match_id = ccc.get_cur_match().id
- player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first()
- data = {
- "zq":user.zq,
- "cw":user.cw,
- "df":user.df,
- "pz":user.pz,
- "join_time":user.join_time,
- "username":user.username,
- "account_img":user.account_img,
- "avatar":user.avatar
- }
- if player:
- data["is_player"] = 1
- data["init_fund"] = player.fund if player.fund else 0
- else:
- data["is_player"] = 0
- data["init_fund"] = None
- return data
- def update_user_style(**kwargs):
- """
- """
- user_id = kwargs.pop("user_id")
- #player_id = kwargs.pop("player_id")
- if kwargs.get("init_fund"):
- init_fund = kwargs.pop("init_fund")
- try:
- init_fund = kwargs.pop("init_fund")
- except Exception as e:
- print(e)
- #avatar = kwargs.pop("avatar")
- if re.search(settings.FORBID_NAME,kwargs.get("username")):
- raise ce.TipException(u"名字中包含特殊关键字,请更换名称后重试!")
- cm.UserInfo.objects.filter(id=user_id).update(**kwargs)
- #if player_id and init_fund:
- # cm.Player.objects.filter(id=player_id).update(fund=init_fund)
- if kwargs.get("username"):
- cm.Player.objects.filter(user_id=user_id).update(username=kwargs.get("username"))
- match_id = ccc.get_cur_match().id
- upset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id)
- upset.update(username=kwargs.get("username"))
- record_ids = list(upset.values_list("id",flat=True))
- for _id in record_ids:
- ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(match_id,_id))
- if kwargs.get("avatar"):
- cm.UserInfo.objects.filter(id=user_id).update(avatar=kwargs.get("avatar"))
- ccc.cache.delete("cdata_get_user_info_(%sL,)"%user_id)
- return True
- def get_stock_players(**kwargs):
- """
- """
- stock_id = kwargs.get("stock_id")
- stock_date = kwargs.get("stock_date",get_today_date())
- month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1])
- print(month)
- data = []
- user_stocks = cm.UserStock.get_db_model(month).objects.filter(stock_id=stock_id,stock_date=stock_date,fund__gt=0.0)
- for us in user_stocks:
- player_id = us.player_id
- #player = cm.Player.objects.filter(id=player_id).first()
- player = get_player_info_cache(player_id)
- if player:
- match_id = player["match_id"]
- match_group = player["match_group"]
- user_id = player["user_id"]
- if stock_date:
- today_record = get_today_record(user_id,match_id,match_group,stock_date)
- else:
- today_record = get_today_record(user_id,match_id,match_group,us.stock_date)
- if today_record:
- today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
- today_stock = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
- today_stock = list(filter(lambda x:float(x.get("fund",0) if x.get('fund') else 0)>0.0,today_stock))
- today_record["today_stock"] = today_stock
- today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
- today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
- #today_record["cur_stock_fund"] = 0.0
- for item in today_record["today_stock"]:
- if 'stock_id' not in item:
- today_record["cur_stock_fund"] = 0.0
- continue
- if int(item["stock_id"]) == int(stock_id):
- today_record["cur_stock_fund"] = float(item["fund"]) if item["fund"] else 0.0
- else:
- today_record["cur_stock_fund"] = 0.0
- data.append(today_record)
- #data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
- data = sorted(data,key=lambda x:x.get("cur_stock_fund",0),reverse=True)
- #分页
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- #return total,data
- #return data
- if kwargs.get("v3"):
- return total,data
- else:
- return data
-
- def update_user_fund(**kwargs):
- """
- """
- user_id = kwargs.pop("user_id")
- player_id = kwargs.pop("player_id")
- init_fund = kwargs.pop("init_fund")
- if player_id and init_fund:
- cm.Player.objects.filter(id=player_id).update(fund=init_fund)
- return True
- def get_player_match_calendar(**kwargs):
- """
- """
- match_id = kwargs.get("match_id")
- month = kwargs.get("month")
- user_id = kwargs.get("user_id")
- week,eday = calendar.monthrange(int(month.split("-")[0]),int(month.split("-")[1]))
- sday = "01"
- eday = str(eday).zfill(2)
- sdate = month + "-" + sday
- edate = month + "-" + eday
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id)\
- .filter(stock_date__gte=sdate,stock_date__lte=edate)
- data = list(qset.values())
- dct = {}
- for item in data:
- item["today_income"] = "{}%".format(item["today_income"]*100)
- #dct[item["stock_date"]] = item["today_income"]
- dct[item["stock_date"]] = [item["today_income"],item["id"]]
- newdata = []
- for i in range(1,int(eday)+1):
- stock_date = month + "-" + str(i).zfill(2)
- today_tpl = dct.get(stock_date,[])
- today_income = today_tpl[0] if today_tpl else None
- record_id = today_tpl[1] if today_tpl else None
- newdata.append({
- "stock_date":stock_date,
- "today_income":today_income,
- "record_id":record_id
- })
- return newdata
- def get_all_match(request):
- """
- """
- now = datetime.datetime.now().strftime("%Y-%m-%d")
- #qset = cm.Match.objects.filter(start_time__lte=now).order_by("id")
- qset = cm.Match.objects.filter(match_status__in=[3,4]).order_by("-id")
- data = list(qset.values())
- for item in data:
- valid_dates = json.loads(item["valid_dates"]) if item["valid_dates"] else []
- valid_dates.sort()
- item["valid_dates"] = valid_dates
- return data
- def get_default_date(**kwargs):
- """
- """
- match_id = kwargs.get("match_id")
- if not match_id:
- match_id = ccc.get_cur_match().id
- record = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).order_by("-stock_date").first()
- if record:
- return record.stock_date
- else:
- return get_today_date()
- @ccc.cache_data()
- def get_stock_search(**kwargs):
- """
- """
- qset = cm.Stock.objects.all()
- data = list(qset.values("id","name","code"))
- for item in data:
- if item["code"]:
- item["label"] = "%s(%s)" % (item["name"],item["code"])
- else:
- item["label"] = "%s" % item["name"]
- return data
- def get_mine_latest(request):
- """
- """
- try:
- user_id = request.user.get("id")
- cur_match_id = ccc.get_cur_match().id
- match_id = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_id")
- if cur_match_id != int(match_id):
- return {"player_id":user_id,"match_id":match_id,"user_id":user_id}
- match_group = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_group")
- _today = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"stock_date")
- if _today:
- rst = ccc.get_today_record(int(user_id),int(match_id),int(match_group),_today)
- if rst:
- rst["today_income_fund"] = round((rst["today_fund"] - rst["yesterday_fund"])*10000,2) if rst["yesterday_fund"] else 0.00
- rst["today_income"] = "{}%".format(rst["today_income"]*100)
- rst["total_income"] = "{}%".format(rst["total_income"]*100)
- rst["zan_count"] = rst.get("zans",0)
- rst["comments_count"] = cm.Comments.objects.filter(record_id=rst.get("id",0)).count()
- return rst
- except Exception as e:
- print(e)
- return {"player_id":user_id,"match_id":match_id,"user_id":user_id}
- #@ccc.cache_data()
- def get_match_validdates(match_id):
- """
- """
- #qdata = request.json
- #match_id = qdata.get("match_id")
- match = cm.Match.objects.filter(id=match_id).first()
- if match:
- validdates = json.loads(match.valid_dates) if match.valid_dates else []
- validdates.sort()
- return validdates
- return []
- def send_phcode(request):
- """
- """
- qdata = request.json
- phone = qdata.get("phone")
- code = "%s%s%s%s" % (random.randint(0,9),random.randint(0,9),random.randint(0,9),random.randint(0,9))
- send_verify_code(phone,code)
- ccc.cache.set(phone,code,120)
- pass
- def get_signup_info(request):
- """
- """
- qdata = request.json
- try:
- user_id = request.user.get("id",0)
- except:
- user_id = 0
- try:
- match_id = ccc.get_signup_match().id
- match = cm.Match.objects.filter(id=match_id).values().first()
- #
- match_groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).values())
- match["groups"] = match_groups
- #报名状态
- now = datetime.datetime.now().strftime("%Y-%m-%d")
- signup_start_time = match["signup_start_time"]
- signup_end_time = match["signup_end_time"]
- if signup_start_time <= now and signup_end_time >= now:
- match["signup_status"] = 1
- else:
- match["signup_status"] = 0
- if cm.Player.objects.filter(match_id=match_id,user_id=user_id,match_group__isnull=False).filter(role__in=[1,2]).exists():
- match["signup_done"] = 1
- else:
- match["signup_done"] = 0
-
- return match
- except Exception as e:
- print(e)
- return {}
- def do_wx_pay(request):
- """
- """
- user = request.user
- user_id = request.user.get("id",0)
- user_name = request.user.get("username","")
- openid = request.user.get("openid","")
- qdata = request.json
- match_id = qdata.get("match_id")
- match_name = qdata.get("match_name")
- signup_type = qdata.get("signup_type")
- total_fee = str(qdata.get("total_fee"))
- phone = qdata.get("phone")
- phcode = qdata.get("phcode")
- match_group = qdata.get("match_group")
- signup_name = qdata.get("signup_name")
- pay_type = qdata.get("pay_type")
- opmode_group = qdata.get("opmode_group")
- if user.get("forbid_status") == 1:
- raise ce.TipException(u"您暂时不能报名,请联系客服!")
- if not signup_name:
- signup_name = user_name
- orgcode = ccc.cache.get(phone)
- print(signup_name)
- if re.search(settings.FORBID_NAME,signup_name):
- raise ce.TipException(u"名字中包含特殊关键字,请更换名称后重试!")
- if not phone == "13883187629":
- if not phcode == orgcode:
- raise ce.TipException(u"验证码不正确!")
- if int(signup_type) == 1:
- if not match_group:
- match_group = cm.MatchGroup.objects.filter(match_id=match_id,charge=0).first().id
- if pay_type == "wxapppay":
- out_trade_no = "WXAPP"+datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
- else:
- out_trade_no = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(int(time.time()*1000))
- #游客和普通选手付费报名
- #gt_time = datetime.timedelta(days=-365)+datetime.datetime.now()
- #old_player = cm.Player.objects.filter(user_id=user_id,match_status=1,ctime__gte=gt_time).exists()
- #if user["player_type"] in [0,1] and not phone=="13883187629":
- if user["player_type"] in [0,1] and not phone=="13883187629":
- #生成订单
- order = cm.SignupOrder.objects.create(
- user_id = user_id,
- user_name = signup_name,
- match_id = match_id,
- match_name = match_name,
- signup_type = signup_type,
- total_fee = total_fee,
- out_trade_no = out_trade_no,
- phone = phone,
- match_group = match_group,
- signup_name = signup_name,
- opmode_group = opmode_group
- )
- #支付
- if pay_type == "wxapppay":
- total_fee = str(int(float(order.total_fee)*100))
- notify_url = "https://api.hunanwanzhu.com/api/wx/v3/signup/notify"
- #notify_url = "https://test.hunanwanzhu.com"
- data = {"subject":u"%s报名费" % match_name,"price":total_fee,"out_trade_no":out_trade_no}
- wxapppay = WechatPayDAL()
- prepayinfo = wxapppay.create_order_info(data,notify_url)
- return prepayinfo
- else:
- total_fee = str(int(float(order.total_fee)*100))
- prepayinfo = wxpay.get_wx_unifiedorder(out_trade_no,total_fee,openid)
- prepayinfo["key"] = wxpay.WxPayConf_pub.KEY
- return prepayinfo
- #种子选手和开户选手免费报名
- else:
- if signup_type == 1:
- signup_name = user_name
- #生成订单
- order = cm.SignupOrder.objects.create(
- user_id = user_id,
- user_name = signup_name,
- match_id = match_id,
- match_name = match_name,
- signup_type = signup_type,
- total_fee = total_fee,
- out_trade_no = out_trade_no,
- phone = phone,
- match_group = match_group,
- signup_name = signup_name,
- opmode_group = opmode_group
- )
- user = cm.UserInfo.objects.filter(id=user_id).first()
- #生成选手信息
- cur_match = cm.Match.objects.filter(id=match_id).first()
- visit_group = cm.MatchGroup.objects.filter(id=match_group).first()
- #opmode_group_obj = cm.OpModelGroup.objects.filter(id=opmode_group).first()
- player,flag = cm.Player.objects.get_or_create(
- user_id = user.id,
- match_id = cur_match.id
- )
- player.match_name = cur_match.name
- player.match_group = visit_group.id
- player.match_group_name = visit_group.name
- #player.opmode_group = opmode_group_obj.id
- #player.opmode_group_name = opmode_group_obj.name
- player.username = signup_name
- player.usercode = request.user.get("usercode")
- player.role = 2
- player.match_status = 1
- player.save()
- #
- order.player_id = player.id
- order.save()
- user.username = signup_name
- user.phone = phone
- user.role = 2
- user.save()
- #发送报名成功信息
- #send_signup_success(phone,signup_name)
- if phone == "13883187629":
- for i in [5001,4762,5173,5141]:
- cm.UserFollows.objects.get_or_create(user_id=user_id,follow_id=i)
- return {"free":1}
- def do_wxpay_notify(request):
- qdata = request.json
- if qdata.get("resource_type") == "encrypt-resource":
- wxapppay = WechatPayDAL()
- res = wxapppay.decrypt_nofify_v3(qdata)
- res = json.loads(res)
- flag = True
- else:
- flag,res = wxpay.check_notify_valid(request.body)
- if flag:
- out_trade_no = res.get("out_trade_no")
- transaction_id = res.get("transaction_id")
- pay_time = res.get("time_end")
- try:
- sorder = cm.SignupOrder.objects.filter(out_trade_no=out_trade_no).first()
- if sorder and not sorder.transaction_id:
- now = datetime.datetime.now()
- sorder.order_status = 1
- sorder.pay_status = 1
- sorder.pay_time = now
- sorder.transaction_id = transaction_id
- sorder.save()
- #生成选手信息
- user = cm.UserInfo.objects.filter(id=sorder.user_id).first()
- visit_group = cm.MatchGroup.objects.filter(id=sorder.match_group).first()
- player,flag = cm.Player.objects.get_or_create(
- user_id = sorder.user_id,
- match_id = sorder.match_id
- )
- player.match_name = sorder.match_name
- player.match_group = visit_group.id
- player.match_group_name = visit_group.name
- player.username = sorder.user_name
- player.usercode = user.usercode if user else ""
- if sorder.signup_type == 2:
- player.role = 2
- else:
- player.role = 1
- #
- sorder.player_id = player.id
- sorder.save()
- player.save()
- if sorder.signup_type == 2:
- player_id = sorder.player_id
- user_id = sorder.user_id
- match_group = sorder.match_group
- match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name
- 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)
- cm.UserInfo.objects.filter(id=user_id).update(role=2,phone=sorder.phone,username=sorder.user_name)
- if sorder.signup_type == 1:
- player_id = sorder.player_id
- user_id = sorder.user_id
- cm.Player.objects.filter(id=player_id).update(role=1,match_status=1)
- cm.UserInfo.objects.filter(id=user_id).update(role=1,phone=sorder.phone,username=sorder.user_name)
- #发送报名成功信息
- #send_signup_success(sorder.phone,sorder.signup_name)
- return True
- except Exception as e:
- import traceback
- traceback.print_exc()
- print(e,111111111111)
- return False
- def get_user_comments(request):
- """
- """
- kwargs = request.json
- stock_id = kwargs.get("stock_id")
- record_id = kwargs.get("record_id")
- match_id = kwargs.get("match_id")
- if record_id:
- if match_id:
- qset = cm.Comments.objects.filter(record_id=record_id,match_id=match_id,pid__isnull=True).order_by(*["-istop","-id"])
- else:
- qset = cm.Comments.objects.filter(record_id=record_id,pid__isnull=True).order_by(*["-istop","-id"])
- else:
- qset = cm.Comments.objects.filter(stock_id=stock_id,pid__isnull=True).order_by(*["-istop","-id"])
- data = list(qset.values())
- for item in data:
- if record_id:
- subcomments = cm.Comments.objects.filter(record_id=record_id,pid=item["id"])
- else:
- subcomments = cm.Comments.objects.filter(stock_id=stock_id,pid=item["id"])
- item["children"] = list(subcomments.values())
- #分页
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- return total,data
- def get_user_choices(request):
- """
- """
- user_id = request.user.get("id",0)
- #match_id = request.player.match_id
- kwargs = request.json
- stock_id = kwargs.get("stock_id")
- if stock_id:
- qset = cm.UserChoice.objects.filter(stock_id=stock_id)
- else:
- qset = cm.UserChoice.objects.filter(user_id=user_id)
- data = list(qset.values())
- for item in data:
- stock_id = item["stock_id"]
- comments_count = ccc.cache.get("%s_comments" % stock_id)
- choice_count = ccc.cache.get("%s_choices" % stock_id)
- comments_count = comments_count if comments_count else 0
- choice_count = choice_count if choice_count else 0
- item["count"] = choice_count
- item["comments_count"] = comments_count
- item["choice_count"] = choice_count
- #item["match_id"] = match_id
- #分页
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- return total,data
- def get_user_consult_list(request):
- """
- """
- player_id = request.user.get("id") if request.user else 0
- if not player_id:
- return 0,[]
- kwargs = request.json
- record_id = kwargs.get("record_id")
- if kwargs.get("user_id"):
- player_id = kwargs.get("user_id")
- qset = cm.WanzhuConsult.objects.filter(user_id=player_id,user_id__gt=0)
- qdata = list(qset.values())
- data = []
- for item in qdata:
- data.append(item)
- if cm.WanzhuConsult.objects.filter(pid=item["id"]).exists():
- reply_list = cm.WanzhuConsult.objects.filter(Q(pid=item["id"])).values()
- for iitem in reply_list:
- data.append(iitem)
- if kwargs.get("sort") == "desc":
- data = sorted(data,key=lambda x:x["id"],reverse=True)
- else:
- data = sorted(data,key=lambda x:x["id"])
- #分页
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",1000))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- for item in data:
- user_id = item["user_id"]
- user = cm.UserInfo.objects.filter(id=user_id).first()
- if user:
- item["usercode"] = user.usercode
- return total,data
- def get_user_zans(request):
- """
- """
- qdata = request.json
- record_id = qdata.get("record_id")
- match_id = qdata.get("match_id")
- zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
- return zans
- def get_user_comments_count(request):
- """
- """
- qdata = request.json
- record_id = qdata.get("record_id")
- count = cm.Comments.objects.filter(record_id=record_id).count()
- return count
- def add_wanzhu_consult(request):
- """咨询顽主
- """
- user_id = request.user.get("id",0)
- user_name = request.user.get("username")
- user_avatar = request.user.get("avatar")
- user_code = request.user.get("usercode")
- phone = request.user.get("phone")
- openid = request.user.get("openid")
- qdata = request.json
- content = qdata.get("cotent")
- width = qdata.get("width")
- height = qdata.get("height")
- pid = qdata.get("pid")
- wanzhu_obj = cm.WanzhuConsult.objects.create(
- user_id = user_id,
- user_name = user_name,
- user_avatar = user_avatar,
- content = content,
- pid = pid
- )
- wanzhu_obj.user_code = user_code
- wanzhu_obj.phone = phone
- wanzhu_obj.width = width
- wanzhu_obj.height = height
- wanzhu_obj.save()
- obj,flag = cm.Consult.objects.get_or_create(
- user_id = user_id,
- )
- obj.user_name = user_name
- obj.user_avatar = user_avatar
- obj.user_code = user_code
- obj.phone = phone
- obj.content = content
- obj.view_status = 0
- obj.reply_status = 0
- obj.width = width
- obj.height = height
- obj.ctime = datetime.datetime.now()
- obj.save()
- #自动回复
- if cm.WanzhuConsult.objects.filter(user_id=user_id).count() <=1:
- content = u"您好,后台消息一般三小时内回复,如果超出时间请加微信destination8888"
- cm.WanzhuConsult.objects.create(
- pid = pid,
- reply_content = content,
- user_id = 0,
- player_id = 0,
- reply_user_id = user_id
- )
- #发送消息提醒
- if cm.UserInfo.objects.filter(id=user_id).exists():
- user = cm.UserInfo.objects.filter(id=user_id).first()
- send_consult_reply_message(openid,user_name)
- #发送app推送消息
- title = u"顽主杯"
- body = u"你收到一条顽主的消息"
- params = {"type":"message","id":str(user_id)}
- aliyunpush.push_notice_by_userid(0,title,body,params,"ios")
- aliyunpush.push_notice_by_userid(0,title,body,params,"android")
- #退款短信通知
- # if '退款' in content:
- # send_verify_code('18397565872','0000')
- def add_comments(request):
- """
- """
- #if request.user.comment_status == 0:
- # raise ce.TipException(u"对不起,暂无法评论/留言!")
- user_id = request.user.get("id")
- user_name = request.user.get("username")
- user_avatar = request.user.get("avatar")
- qdata = request.json
- content = qdata.get("cotent")
- record_id = qdata.get("record_id")
- stock_id = qdata.get("stock_id")
- pid = qdata.get("pid")
- match_id = qdata.get("match_id")
- target_user_id = qdata.get("target_user_id")
- ip = ccf.get_ip(request)
- location = ccf.get_city_from_ip(ip)
- if record_id and target_user_id:
- if cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=target_user_id).exists():
- raise ce.TipException(u"对不起,暂无法评论/留言!")
- obj = cm.Comments.objects.create(
- user_id = user_id,
- user_name = user_name,
- user_avatar = user_avatar,
- content = content,
- record_id = record_id,
- pid = pid,
- ip = ip,
- location = location,
- stock_id = stock_id,
- match_id = match_id
- )
- if record_id:
- cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(comments_count=F("comments_count")+1)
- if stock_id:
- ccc.cache.incr("%s_comments" % stock_id,1)
- def add_choice(request):
- """
- """
- user_id = request.user.get("id")
- user_name = request.user.get("username")
- user_avatar = request.user.get("avatar")
- qdata = request.json
- stock_id = qdata.get("stock_id")
- stock_name = cm.Stock.objects.filter(id=stock_id).first().name
- obj = cm.UserChoice.objects.create(
- user_id = user_id,
- user_name = user_name,
- user_avatar = user_avatar,
- stock_id = stock_id,
- stock_name = stock_name
- )
- if stock_id:
- ccc.cache.incr("%s_choices" % stock_id,1)
- def add_zan(request):
- """
- """
- qdata = request.json
- record_id = qdata.get("record_id")
- match_id = qdata.get("match_id")
- cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).update(zans=F("zans")+1)
- zans = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=record_id).first().zans
- return zans
- @ccc.cache_data_kw(10*60)
- def get_experience_list(**kwargs):
- """
- """
- #return 0,[]
- #kwargs = request.json
- today = get_today_date()
- match_id = ccc.get_cur_match().id
- match_group = kwargs.get("match_group")
- #冠军组、千万组、百万组
- grpset = cm.MatchGroup.objects.filter(match_id=match_id).filter(Q(name__icontains=u"千万组")|Q(name__icontains=u"百万组")|Q(name__icontains=u"冠军组"))
- if match_group:
- grpset = grpset.filter(id=match_group)
- qbw_ids = list(grpset.values_list("id",flat=True))
- 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")
- 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"))
- for item in data:
- record_id = item["id"]
- user_id = item["user_id"]
- try:
- item["user_avatar"] = get_user_info(user_id)["avatar"]
- item["avatar"] = get_user_info(user_id)["avatar"]
- except:
- item["user_avatar"] = ""
- item["avatar"] = ""
- item["zans_count"] = item["zans"]
- item["today_stock_img"] = json.loads(item["today_stock_img"])
- win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["user_id"],"win_rate")
- if win_rate:
- item["win_rate"] = str(float(win_rate)*100)+"%"
- else:
- item["win_rate"] = "0.0%"
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- #分页
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- return total,data
- def delete_choice(request):
- """
- """
- user_id = request.user.get("id")
- user_name = request.user.get("username")
- user_avatar = request.user.get("avatar")
- qdata = request.json
- stock_id = qdata.get("stock_id")
- cm.UserChoice.objects.filter(stock_id=stock_id,user_id=user_id).delete()
- if ccc.cache.get("%s_choices" % stock_id) and int(ccc.cache.get("%s_choices" % stock_id)) >= 1:
- ccc.cache.decr("%s_choices" % stock_id)
- def delete_comments(request):
- """
- """
- qdata = request.json
- id = qdata.get("id")
- if cm.Comments.objects.filter(id=id,stock_id__isnull=False).exists():
- stock_id = cm.Comments.objects.filter(id=id).first().stock_id
- if ccc.cache.get("%s_comments" % stock_id) and int(ccc.cache.get("%s_comments" % stock_id)) >= 1:
- ccc.cache.decr("%s_comments" % stock_id)
- cm.Comments.objects.filter(id=id).delete()
- def modify_user_fund(request):
- """
- """
- user_id = request.user.get("id")
- #player = request.player
- match_id = ccc.get_cur_match().id
- player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
- player_id = player.id
- match_id = player.match_id
- qdata = request.json
- fundin = qdata.get("in_fund")
- fundout = qdata.get("out_fund")
- fundin = float(fundin) if fundin else 0.0
- fundout = float(fundout) if fundout else 0.0
- account_img = qdata.get("account_img")
- init_fund = player.fund
- trycalc = qdata.get("trycalc")
- today_fund = qdata.get("today_fund")
- today_fund = float(today_fund) if today_fund else 0.0
- if trycalc:
- stock_date = get_today_date()
- validdates = get_match_validdates(match_id)
- today_index = validdates.index(stock_date)
- yesterday_index = today_index -1 if today_index >=1 else 0
- yesterday_date = validdates[yesterday_index]
- yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
- match_id=match_id,player_id=player_id,stock_date=yesterday_date).exclude(stock_date=stock_date).first()
- if yesterday:
- yesterday_fund = yesterday.today_fund
- yesterday_stock = yesterday.today_stock
- yesterday_stock_img = yesterday.today_stock_img
- yesterday_is_markt = yesterday.is_markt
- else:
- yesterday_fund = today_fund
- yesterday_stock = ""
- yesterday_stock_img = ""
- yesterday_is_markt = 0
- #入资金
- if fundin > fundout:
- fundin = fundin - fundout
- if yesterday:
- today_income = round((today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin),4)
- yesterday_fund = yesterday_fund + fundin
- else:
- today_income = 0.0
- total_income = round((today_fund-init_fund-fundin)/(init_fund+fundin),4)
- init_fund = init_fund + fundin
- #出资金
- else:
- fundout = fundout - fundin
- if yesterday:
- today_income = round((today_fund-(yesterday_fund-fundout))/float(yesterday_fund),4)
- yesterday_fund = round(today_fund/(1+today_income),4)
- else:
- today_income = 0.0
- total_income = round((today_fund+fundout-init_fund)/init_fund,4)
- init_fund = round(today_fund/(1+total_income),4)
- today_income = "{}%".format(today_income*100)
- total_income = "{}%".format(total_income*100)
- return {"yesterday_fund":yesterday_fund,
- "today_fund":today_fund,
- "today_income":today_income,
- "total_income":total_income,
- "init_fund":init_fund}
- stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
- if cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).exists():
- raise ce.TipException(u"资金出入须在提交作业之前提交,今日作业已提交,不能提交资金出入!")
- if cm.FundInOut.objects.filter(user_id=user_id,stock_date=stock_date).exists():
- raise ce.TipException(u"今日已有资金出入,一天只能提交一次资金出入!")
- fundinout,flag = cm.FundInOut.objects.get_or_create(
- user_id = user_id,
- fundin = fundin,
- fundout = fundout,
- stock_date = stock_date,
- account_img = account_img
- )
- def get_user_match_list(request):
- kwargs = request.json
- user_id = kwargs.get("user_id")
- if not user_id:
- user_id = request.user.get("id")
- qset = cm.Player.objects.filter(user_id=user_id).filter(match_group__isnull=False).order_by("-id")
- qset = qset.values("user_id","match_id","match_group").annotate(cnt=Count("match_id"))
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- #today = get_today_date(user_id=user_id)
- data = list(qset.values("user_id","match_id","match_group"))
- new_data = []
- for item in data:
- match_id = item["match_id"]
- match_group = item["match_group"]
- user_id = item["user_id"]
- today = get_today_date(match_id=match_id,user_id=user_id)
- item["match_info"] = get_match_info(match_id)
- item["match_group_info"] = get_group_info(match_group)
- if match_id and match_group:
- today_record = ccc.get_today_record(user_id,int(match_id),int(match_group),today)
- today_record = format_today_record(today_record)
- if today_record:
- if today_record.get("today_income"):
- today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
- if today_record.get("total_income"):
- today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
- item["today_record"] = today_record
- new_data.append(item)
- #return total,data
- return total,new_data
- def get_format_user_info(request):
- user_id = request.user.get("id")
- cur_user_id = request.user.get("id")
- kwargs = request.json
- q_user_id = kwargs.get("user_id")
- if q_user_id:
- user_id = q_user_id
- userinfo = get_user_info_actual(q_user_id)
- userinfo["fans"] = cm.UserFollows.objects.filter(follow_id=user_id).count()
- userinfo["followers"] = cm.UserFollows.objects.filter(user_id=user_id).count()
- if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists():
- userinfo["is_follow"] = 1
- else:
- userinfo["is_follow"] = 0
- if cm.UserBlacks.objects.filter(user_id=cur_user_id,black_user_id=user_id).exists():
- userinfo["is_black"] = 1
- else:
- userinfo["is_black"] = 0
- if userinfo.get("phone"):
- del userinfo["phone"]
- return userinfo
- def get_day_inout_rank_list(request):
- """
- """
- kwargs = request.json
- stock_date = kwargs.get("stock_date")
- match_id = kwargs.get("match_id")
- _type = kwargs.get("type")
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date)
- if _type == "in":
- qset = qset.order_by("-today_income")
- else:
- qset = qset.order_by("today_income")
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- data = list(qset.values())
- return total,data
- def get_user_follows_v3(request):
- """获取用户关注的选手列表
- """
- user_id = request.user.get("id",0)
- qdata = request.json
- if qdata.get("user_id"):
- user_id = qdata.get("user_id")
- qset = cm.UserFollows.objects.filter(user_id=user_id)
- follow_ids = list(qset.values_list("follow_id",flat=True))
- today = get_today_date()
- _today = today
- data = []
- for user_id in follow_ids:
- latest_key = "PLAYER_LATEST_%d"%user_id
- _match_id = ccc.cache.hget(latest_key,"match_id")
- _today = ccc.cache.hget(latest_key,"stock_date")
- _match_group = ccc.cache.hget(latest_key,"match_group")
- today_record = ccc.get_today_record(user_id,_match_id,_match_group,_today)
- if today_record:
- today_record["zan_count"] = today_record.get("zans",0) if today_record.get("zans") else 0
- today_record["comments_count"] = cm.Comments.objects.filter(record_id=today_record.get("id",0)).count()
- data.append(today_record)
- data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
- page = int(qdata.get("page",1))
- page_size = int(qdata.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- for item in data:
- if item:
- user_id = item["user_id"]
- latest_key = "PLAYER_LATEST_%d"%user_id
- today_stock = json.loads(item["today_stock"]) if item.get("today_stock") else []
- today_stock = filter(lambda x:x["name"] and x["fund"],today_stock)
- item["today_stock"] = today_stock
- item["today_stock_img"] = json.loads(item["today_stock_img"]) if item.get("today_stock_img") else []
- win_rate = ccc.cache.hget(latest_key,"win_rate")
- if win_rate:
- item["win_rate"] = str(float(win_rate)*100)+"%"
- else:
- item["win_rate"] = "0.0%"
- item["today_income"] = "{}%".format(item["today_income"]*100)
- item["total_income"] = "{}%".format(item["total_income"]*100)
- item["zans_count"] = item.get("zans",0)
- item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
- return total,data
- else:
- return len(data),data
- def get_latest_match_info(request):
- """
- """
- cur_match = cm.Match.objects.filter(match_status=3).order_by("-id").values().first()
- cur_match_id = cur_match.get("id")
- groups = list(cm.MatchGroup.objects.filter(match_id=cur_match_id,is_active=1).order_by("order").values())
- cur_match["groups"] = groups
- return cur_match
- def get_article_info(**kwargs):
- """
- """
- _id = kwargs.get("id")
- rst = cm.Article.objects.filter(id=_id).values().first()
- rst["url"] = "https://api.hunanwanzhu.com/topic/share/article.html?id="+str(_id)
- rst["web"] = "https://api.hunanwanzhu.com/topic/share/articleweb.html?id="+str(_id)
- return rst
- def get_profit_list(**kwargs):
- """盈亏列表
- """
- stock_date = kwargs.get("stock_date")
- match_id = kwargs.get("match_id")
- _type = kwargs.get("type")
- if not stock_date:
- stock_date = get_today_date()
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=stock_date)
- #if _type == "win":
- # qset = qset.filter(today_income__gte=0).order_by("-today_income")
- #if _type == "loss":
- # qset = qset.filter(today_income__lt=0).order_by("today_income")
- data = list(qset.values())
- for item in data:
- item["win_loss"] = item["today_fund"] - item["yesterday_fund"]
- item["total_win_loss"] = item["today_fund"] - item["init_fund"]
- item["win_loss"] = round(item["win_loss"],4)
- item["total_win_loss"] = round(item["total_win_loss"],4)
- if _type == "win":
- data = sorted(data,key=lambda x:x["win_loss"],reverse=True)
- if _type == "loss":
- data = sorted(data,key=lambda x:x["win_loss"])
- if _type == "total_win":
- data = sorted(data,key=lambda x:x["total_win_loss"],reverse=True)
- if _type == "total_loss":
- data = sorted(data,key=lambda x:x["total_win_loss"])
- if _type == "total_income_win":
- data = sorted(data,key=lambda x:x["total_income"],reverse=True)
- if _type == "total_income_loss":
- data = sorted(data,key=lambda x:x["total_income"])
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- #data = list(qset.values())
- return total,data
- def get_group_rank_list_v3(request):
- """排名列表
- """
- qdata = request.json
- kwargs = qdata
- group_id = qdata.get("id")
- match_id = qdata.get("match_id")
- match_id = cm.MatchGroup.objects.filter(id=group_id).first().match_id
- today = qdata.get("stock_date")
- if not today:
- today = get_today_date()
- match = get_match_info(match_id)
- group = get_group_info(group_id)
- players = get_match_group_users(match_id,group_id)
- new_players = []
- for player in players:
- user_id = player["user_id"]
- username = player["username"]
- match_group = group_id
- today_record = ccc.get_today_record(user_id,match_id,match_group,today)
- if today_record:
- player.update(today_record)
- player["username"] = username
- player["org_today_income"] = player["today_income"]
- player["org_total_income"] = player["total_income"]
- player["total_income"] = "{}%".format(player["total_income"]*100)
- player["today_income"] = "{}%".format(player["today_income"]*100)
- player["fund"] = round(player["fund"],4)
- player["init_fund"] = round(player["init_fund"],4)
- player["today_fund"] = round(player["today_fund"],4)
- player["today_stock_img"] = json.loads(player["today_stock_img"]) if player["today_stock_img"] else []
- #player["win_rate"] = calc_win_rate(user_id,match_id)
- player["zan_count"] = player["zans"]
- new_players.append(player)
- if kwargs.get("order_by") == "today_income__asc":
- new_players = sorted(new_players,key=lambda x:x["org_today_income"])
- elif kwargs.get("order_by") == "today_income__desc" :
- new_players = sorted(new_players,key=lambda x:x["org_today_income"],reverse=True)
- elif kwargs.get("order_by") == "total_income__asc":
- new_players = sorted(new_players,key=lambda x:x["org_total_income"])
- elif kwargs.get("order_by") == "total_income__desc":
- new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
- else:
- new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
- #分页
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",50))
- if page and page_size:
- total,new_players = ccf.get_page_list(new_players,page,page_size)
- else:
- total = len(new_players)
- return total,new_players
- def get_article_type_list(**kwargs):
- rst = [u"游资专场",u"冠军交割",u"牛人专场",u"妖股列传"]
- rst = const.ARTICLE_TYPE_LIST
- return rst
- def get_wanzhu_consult_list(**kwargs):
- """
- """
- qset = cm.Consult.objects.filter(user_id__gt=0).order_by("-ctime")
- if kwargs.get("username"):
- qset = qset.filter(user_name__icontains=kwargs.get("username"))
- if kwargs.get("reply_status"):
- qset = qset.filter(reply_status=kwargs.get("reply_status"))
- if kwargs.get("content"):
- qset = qset.filter(Q(content__icontains=kwargs.get("content"))|Q(reply_content__icontains=kwargs.get("content")))
- data = list(qset.values())
- #分页
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- else:
- total = len(data)
- for item in data:
- user_id = item["user_id"]
- userinfo = get_user_info(user_id)
- if userinfo:
- item["user_code"] = userinfo.get("usercode")
- return total,data
- def get_sub_category(pid):
- """
- """
- qset = cm.BaikeCategory.objects.filter(parent_id=pid)
- qdata = list(qset.values())
- if qdata:
- for subitem in qdata:
- subitem["type"] = "ent"
- subitem["children"] = get_sub_category(subitem["id"])
- return qdata
- def get_baike_category_tree(**kwargs):
- """
- """
- parents = list(cm.BaikeCategory.objects.filter(parent_id__isnull=True).values())
- for item in parents:
- item["children"] = get_sub_category(item["id"])
- return parents
- def get_sub_catids(pid,data):
- """
- """
- data = data if data else []
- qset = cm.BaikeCategory.objects.filter(parent_id=pid)
- ids = list(qset.values_list("id",flat=True))
- if ids:
- data.extend(ids)
- for _id in ids:
- get_sub_catids(_id,data)
- return data
- def get_baike_list_by_category(**kwargs):
- category_id = kwargs.get("category_id")
- sub_catids = get_sub_catids(category_id,[])
- qset = cm.BaikeDetail.objects.filter(category_id__in=sub_catids)
- qset = qset.order_by("-istop","-ctime")
- data = list(qset.values("id","img","intro","ctime","name","category_id"))
-
- page = int(kwargs.get("page",1))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,data = ccf.get_page_list(data,page,page_size)
- return total,data
- else:
- return len(data),data
-
- return data
- def get_baike_detail(**kwargs):
- #_id = kwargs.get("id")
- category_id = kwargs.get("category_id")
- data = list(cm.BaikeDetail.objects.filter(category_id=category_id).values())
- data = data[0] if data else {}
- return data
- def get_app_version(request):
- rst = cm.APPVersion.objects.all().order_by("-id").values().first()
- return rst
- def reply_wanzhu_consult(**kwargs):
- """
- """
- pid = kwargs.get("pid")
- content = kwargs.get("reply_content")
- user_id = kwargs.get("user_id")
- action = kwargs.get("action")
- width = kwargs.get("width")
- height = kwargs.get("height")
- if action == "send":
- user = cm.UserInfo.objects.filter(id=user_id).first()
- user_name = user.username
- user_avatar = user.avatar
- user_code = user.usercode
- phone = user.phone
- obj,flag = cm.Consult.objects.get_or_create(
- user_id = user_id,
- )
- obj.user_name = user_name
- obj.user_avatar = user_avatar
- obj.user_code = user_code
- obj.phone = phone
- #obj.reply_content = content
- obj.view_status = 1
- obj.reply_status = 0
- obj.ctime = datetime.datetime.now()
- obj.save()
- wanzhu_obj = cm.WanzhuConsult.objects.create(
- user_id = user_id,
- user_name = user_name,
- user_avatar = user_avatar
- )
- wanzhu_obj.user_code = user_code
- wanzhu_obj.phone = phone
- wanzhu_obj.width = width
- wanzhu_obj.height = height
- wanzhu_obj.save()
- wanzhu_obj_1 = cm.WanzhuConsult.objects.create(
- reply_content = content,
- user_id = 0,
- player_id = 0,
- reply_user_id = user_id,
- pid = wanzhu_obj.id
- )
- wanzhu_obj_1.width = width
- wanzhu_obj_1.height = height
- wanzhu_obj_1.save()
- cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now())
- else:
- wanzhu_obj = cm.WanzhuConsult.objects.create(
- pid = pid,
- reply_content = content,
- user_id = 0,
- player_id = 0,
- reply_user_id = user_id
- )
- wanzhu_obj.width = width
- wanzhu_obj.height = height
- wanzhu_obj.save()
- cm.Consult.objects.filter(user_id=user_id).update(reply_status=1,view_status=1,reply_content=content,ctime=datetime.datetime.now())
- #发送消息提醒
- if cm.UserInfo.objects.filter(id=user_id).exists():
- user = cm.UserInfo.objects.filter(id=user_id).first()
- openid = user.openid
- username = user.username
- try:
- send_consult_reply_message(openid,username)
- except Exception as e:
- print(e)
- #发送app推送消息
- title = u"顽主杯"
- body = u"你收到一条顽主的消息"
- params = {"type":"message","id":str(user_id)}
- aliyunpush.push_notice_by_userid(user_id,title,body,params,"ios")
- aliyunpush.push_notice_by_userid(user_id,title,body,params,"android")
- def delete_user_info(request):
- """
- """
- uid = request.user.get("id",0)
- cm.UserInfo.objects.filter(id=uid).delete()
- cm.Player.objects.filter(user_id=uid).delete()
- #cm.PlayerRecord.objects.filter(user_id=uid).delete()
- def get_random_bake_list(**kwargs):
- """
- """
- baikes = list(cm.BaikeDetail.objects.all().values("id","name","intro","img","category_id"))
- randomi = []
- while len(randomi) < 5:
- num = random.randint(0,len(baikes)-1)
- if not num in randomi:
- randomi.append(num)
- rst = [baikes[x] for x in randomi]
- return rst
- def articles_top5_by_type(**kwargs):
- """
- """
- cats = const.ARTICLE_TYPE_LIST
- data = []
- for cat in cats:
- articles = list(cm.Article.objects.filter(category=cat).order_by("-id").values("id","name","ctime","img")[:5])
- data.append({"category":cat,"articles":articles})
- return data
- @ccc.cache_data_kw(5*60)
- def get_match_winlost_top5(**kwargs):
- """
- """
- data = []
- cur_match_id = ccc.get_cur_match().id
- matchs = cm.Match.objects.filter(id__gte=19,match_status__in=[3,4]).order_by("-id")
- for match in matchs:
- match_id = match.id
- match_name = match.name
- end_time = match.end_time
- if cur_match_id == match_id:
- end_time = get_today_date()
- records = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=end_time)
- total_income_up = copy.copy(records)
- total_income_up = total_income_up.order_by("-total_income")
- total_income_up = list(total_income_up.values()[:10])
- get_user_avatar(total_income_up)
- total_income_down = copy.copy(records)
- total_income_down = total_income_down.order_by("total_income")
- total_income_down = list(total_income_down.values()[:10])
- get_user_avatar(total_income_down)
- records = list(records.values())
- for item in records:
- item["total_win"] = item["today_fund"] - item["init_fund"]
- total_win_up = copy.copy(records)
- total_win_up = sorted(total_win_up,key=lambda x:x["total_win"],reverse=True)
- total_win_up = total_win_up[:10]
- get_user_avatar(total_win_up)
- total_win_down = copy.copy(records)
- total_win_down = sorted(total_win_down,key=lambda x:x["total_win"])
- total_win_down = total_win_down[:10]
- get_user_avatar(total_win_down)
- valid_dates = json.loads(match.valid_dates) if match.valid_dates else []
- data.append({"valid_dates":valid_dates,"date":end_time,"start_time":match.start_time,"end_time":match.end_time,"match_id":match_id,"match_name":match_name,"total_income_up":total_income_up,"total_income_down":total_income_down,"total_win_up":total_win_up,"total_win_down":total_win_down})
- if int(kwargs.get("new",0)) == 1:
- break
- return data
- def get_user_avatar(records):
- for item in records:
- userinfo = get_user_info_actual(item["user_id"])
- if userinfo:
- item["avatar"] = userinfo.get("avatar")
- else:
- item["avatar"] = ""
- def black_user(request):
- """
- """
- qdata = request.json
- user_id = request.user.get("id",0)
- black_user_id = qdata.get("black_user_id")
- cm.UserBlacks.objects.get_or_create(
- user_id = user_id,
- black_user_id = black_user_id
- )
- def delete_black_user(request):
- """
- """
- qdata = request.json
- user_id = request.user.get("id",0)
- black_user_id = qdata.get("black_user_id")
- cm.UserBlacks.objects.filter(user_id=user_id,black_user_id=black_user_id).delete()
-
- def get_user_black_user_list(request):
- """
- """
- #user_id = 5709
- user_id = request.user.get("id",0)
- kwargs = request.json
- qset = cm.UserBlacks.objects.filter(user_id=user_id)
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- data = list(qset.values("black_user__id","black_user__username","black_user__avatar"))
- datas = []
- for item in data:
- item['id'] = item["black_user__id"]
- item['username'] = item["black_user__username"]
- item['avatar'] = item["black_user__avatar"]
- return total,data
- def get_stock_nb_comments(request):
- """
- """
- kwargs = request.json
- comment_date = kwargs.get("date")
- qset = cm.StockComments.objects.all().order_by("-ctime")
- if comment_date:
- st = comment_date + " 00:00:00"
- et = comment_date + " 23:59:59"
- qset = qset.filter(ctime__gte=st,ctime__lte=et)
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",20))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- data = list(qset.values())
- return total,data
- def get_opmode_group_rank_list(**kwargs):
- """
- """
- today = get_today_date()
- match_id = ccc.get_cur_match().id
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today).order_by("-total_income")
- qdata = list(qset.values())
- #按操作模式分组并排序
- tmp_dct = {}
- for item in qdata:
- opmode_group = item["opmode_group"]
- opmode_group_name = item["opmode_group_name"]
- key = "%s_%s" % (opmode_group,opmode_group_name)
- if not tmp_dct.get(key):
- tmp_dct[key] = [item]
- else:
- tmp_dct[key].append(item)
- if len(tmp_dct[key]) > 2:
- break
- data = []
- for k,v in tmp_dct.items():
- opmode_id,opmode_name = k.split("_")
- #盈利与亏损
- win_5 = qset.filter(today_income__gte=0.05).count()
- loss_5 = qset.filter(today_income__lte=0.05).count()
- item = {
- "name":opmode_name,
- "id":opmode_id,
- "players":v,
- "win_count":win_5,
- "loss_count":loss_5,
- "opmodel":1,
- }
- data.append(item)
- return data
- def get_opmode_group_statistic(**kwargs):
- """
- """
- opmode_id = kwargs.get("opmode_id")
- #today = get_today_date()
- #match_id = ccc.get_cur_match().id
- today = "2023-08-25"
- match_id = 16
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today,opmode_group=opmode_id)
- qset_user_stock = cm.UserStock.objects.filter(stock_date=today,opmode_group=opmode_id)
- total = qset.count()
- #今日均收益
- today_total_income = qset.aggregate(total=Sum("today_income"))
- today_income_avg = today_total_income["total"]/total
- #总资产
- today_fund_total = qset.aggregate(total=Sum("today_fund"))["total"]
- #初始资产
- init_fund_total = qset.aggregate(total=Sum("init_fund"))["total"]
- total_income = (today_fund_total - init_fund_total)/init_fund_total
-
- #持股前10
- user_stock_top10 = list(qset_user_stock.values("stock_id","stock_name")\
- .annotate(cnt=Count("stock_id")).order_by("-cnt").values("stock_id","stock_name","cnt"))[:10]
- statistic = {
- "total_man":total,
- "today_income_avg":"{}%".format(round(today_income_avg*100,2)),
- "today_fund_total":round(today_fund_total,2),
- "today_init_total":round(init_fund_total,2),
- "total_income":"{}%".format(round(total_income*100,2)),
- "user_stock_top10":user_stock_top10
- }
- return statistic
- def get_opmode_group_rank_info_list(**kwargs):
- """
- """
- opmode_id = kwargs.get("opmode_id")
- order_by = kwargs.get("order_by")
- #today = get_today_date()
- #match_id = ccc.get_cur_match().id
- today = "2023-08-25"
- match_id = 16
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=today,opmode_group=opmode_id)
- #今日收益
- if order_by == "today_income":
- qset = qset.order_by("-today_income")
- #总收益
- if order_by == "total_income":
- qset = qset.order_by("-total_income")
- page = int(kwargs.get("page",0))
- page_size = int(kwargs.get("page_size",10))
- if page and page_size:
- total,qset = ccc.get_page_qset(qset,page,page_size)
- else:
- total = qset.count()
- data = list(qset.values())
- return total,data
- @ccc.cache_data_kw(5*60)
- def get_match_group_winlose_statistic(**qdata):
- """
- """
- match_id = qdata.get("match_id")
- today = qdata.get("stock_date")
- if not today:
- today = get_today_date()
- match_group_dct = {}
- match_group_status_dct = {}
- matchGroup = cm.MatchGroup.objects.filter(match_id=match_id).order_by("-order")
- for item in matchGroup:
- match_group_dct[item.id] = item.name
- match_group_status_dct[item.id] = item.is_active
- prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=today)
- group_win_lose_list = []
- #今日总资产,总收益,平均收益
- prdata = prset.values("match_group").annotate(today_fund=Sum("today_fund"),
- today_income=Sum("today_income"),cnt=Count("today_income")).order_by("match_group")
- match_name = get_match_info(match_id).get("name")
-
- for item in prdata:
- group_id = int(item["match_group"])
- if match_group_status_dct.get(group_id)>0:
- group_win_lose_list.append({
- "match_id":match_id,
- "match_name":match_name,
- "match_group":group_id,
- "name":match_group_dct.get(group_id),
- "today_fund":"{}".format(round(item["today_fund"],2)),
- "today_income":"{}%".format(round(item["today_income"]*100,2)),
- "today_income_avg":"{}%".format(round(item["today_income"]/item["cnt"]*100,2)) if item["cnt"] else 0.0
- })
- group_win_lose_list = sorted(group_win_lose_list,key=lambda x:x["match_group"],reverse=True)
- #今日盈亏人数比
- win_cnt = prset.filter(today_income__gte=0).count()
- lose_cnt = prset.filter(today_income__lt=0).count()
- nwin_cnt = float(win_cnt)/(win_cnt+lose_cnt)*10 if (win_cnt+lose_cnt) >0 else 0.0
- nlose_cnt = float(lose_cnt)/(win_cnt+lose_cnt)*10 if (win_cnt+lose_cnt) >0 else 0.0
- win_cnt = int(round(nwin_cnt))
- lose_cnt = int(round(nlose_cnt))
- #今日全部人均收益率
- total = prset.aggregate(total=Sum("today_income")).get("total")
- today_win_lose_avg = "{}%".format(round(total/prset.count()*100,2)) if prset.count()>0 else 0.0
- total_fund = prset.aggregate(total=Sum("today_fund")).get("total")
- rst = {"group_win_lose_list":group_win_lose_list,
- "win_cnt":win_cnt,"lose_cnt":lose_cnt,
- "total_fund":total_fund,
- "date":today,
- "today_win_lose_avg":today_win_lose_avg}
- return rst
- def user_mark_score(**kwargs):
- """
- """
- user_id = kwargs.get("user_id")
- stock_date = kwargs.get("stock_date")
- score = kwargs.get("score")
- obj,flag = cm.UserMarkScore.objects.get_or_create(
- user_id = user_id,
- stock_date = stock_date,
- )
- obj.score = score
- obj.save()
-
- return obj.score
- def get_user_markscore_list(**kwargs):
- """
- """
- today = kwargs.get("stock_date")
- user_id = kwargs.get("user_id")
- if not today:
- today = get_today_date()
- qset = cm.UserMarkScore.objects.filter(stock_date=today)
- qdata = list(qset.values("score").annotate(cnt=Count("score")))
- for item in qdata:
- if item["user_id"] == user_id:
- item["mark_status"] = 1
- else:
- item["mark_status"] = 0
- rst = {"total":qset.count(),"list":qdata}
- return rst
- def check_user_markscore(**kwargs):
- """
- """
- user_id = kwargs.get("user_id")
- stock_date = kwargs.get("stock_date")
- if cm.UserMarkScore.objects.filter(user_id=user_id,stock_date=stock_date):
- return 1
- else:
- return 0
- def get_match_group_winlose_allday(**qdata):
- """
- """
- match_id = qdata.get("match_id")
- group_id = qdata.get("group_id")
- today = qdata.get("stock_date")
- if not today:
- today = get_today_date()
- match_group_dct = {}
- matchGroup = cm.MatchGroup.objects.filter(match_id=match_id).order_by("-order")
- for item in matchGroup:
- match_group_dct[item.id] = item.name
- prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,match_group=group_id)
- group_win_lose_list = []
- prdata = prset.values("match_group","stock_date").annotate(today_fund=Sum("today_fund"),
- today_income=Sum("today_income"),cnt=Count("today_income")).order_by("match_group").order_by("stock_date")
- money = 10000.0
- for item in prdata:
- group_id = int(item["match_group"])
- stock_date = item["stock_date"]
-
- money += money * (item["today_income"]/item["cnt"] if item["cnt"] else 0)
- total_income = (money-10000.0)/10000.0
- total_avg = "{}%".format(round(total_income*100,2))
- group_win_lose_list.append({
- "stock_date":stock_date,
- "match_group":group_id,
- "name":match_group_dct.get(group_id),
- "today_fund":"{}".format(round(item["today_fund"],2)),
- "total_income":total_avg,
- "today_income":"{}%".format(round(item["today_income"]/item["cnt"]*100,2)) if item["cnt"] else 0.0
- })
- group_win_lose_list = sorted(group_win_lose_list,key=lambda x:x["stock_date"],reverse=True)
- rst = {"list":group_win_lose_list}
- return rst
- @ccc.cache_data_kw(5*60)
- def get_match_group_winlose_avg_allday(**qdata):
- """
- """
- match_id = qdata.get("match_id")
- group_id = qdata.get("group_id")
- #prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id)
- #all_day = list(set(prset.values_list("stock_date",flat=True)))
- #nall_day = sorted(all_day,reverse=False)
- allday_winlose_avg_list = []
- money = 10000.0
- prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).values("stock_date")\
- .annotate(cnt=Count("stock_date"),total=Sum("today_income"))
- for item in prset:
- stock_date = item["stock_date"]
- cnt = item["cnt"]
- total = item["total"]
- today_win_lose_avg = "{}%".format(round(total/cnt*100,2)) if cnt>0 else 0.0
- money += money * (total/cnt if cnt > 0 else 0)
- total_income = (money-10000.0)/10000.0
- total_avg = "{}%".format(round(total_income*100,2))
- allday_winlose_avg_list.append({
- "stock_date":stock_date,
- "today_income":today_win_lose_avg,
- "total_income":total_avg,
- })
- #for stock_date in nall_day:
- # #今日全部人均收益率
- # prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date)
- # total = prset.aggregate(total=Sum("today_income")).get("total")
- # today_win_lose_avg = "{}%".format(round(total/prset.count()*100,2)) if prset.count()>0 else 0.0
- # money += money * (total/prset.count() if prset.count() > 0 else 0)
- # total_income = (money-10000.0)/10000.0
- # total_avg = "{}%".format(round(total_income*100,2))
- # allday_winlose_avg_list.append({
- # "stock_date":stock_date,
- # "today_income":today_win_lose_avg,
- # "total_income":total_avg,
- # })
- allday_winlose_avg_list = sorted(allday_winlose_avg_list,key=lambda x:x["stock_date"],reverse=True)
- rst = {"list":allday_winlose_avg_list}
- return rst
- def get_user_match_stock_winloss_rank_list(**kwargs):
- """
- """
- user_id = kwargs.get("user_id")
- match_id = kwargs.get("match_id")
- rank_type = kwargs.get("rank_type")
- data = []
- qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).exclude(today_stock="[]").order_by("-stock_date")
- for index,qitem in enumerate(qset):
- today_stock = qitem.today_stock
- today_stock = json.loads(today_stock) if today_stock else []
- stock_date = qitem.stock_date
- if index == 0:
- for sitem in today_stock:
- sitem["stock_date"] = stock_date
- sitem['id'] = qitem.id
- sitem['match_id'] = qitem.match_id
- sitem['user_id'] = qitem.user_id
- data.append(sitem)
- else:
- for sitem in today_stock:
- if sitem["fund"] in ["0.0","0",""]:
- sitem["stock_date"] = stock_date
- sitem['id'] = qitem.id
- sitem['match_id'] = qitem.match_id
- sitem['user_id'] = qitem.user_id
- data.append(sitem)
-
- if rank_type == "win":
- data = filter(lambda x:float(x.get("money",0))>0,data)
- data = sorted(data,key=lambda x:float(x.get("money",0)),reverse=True)
- else:
- data = filter(lambda x:float(x.get("money",0))<0,data)
- data = sorted(data,key=lambda x:float(x.get("money",0)))
- return data
- def get_oss2_policy_sign(request):
- """
- """
- qdata = request.json
- policy = qdata.get("policy")
- rst = get_signature(policy)
- return rst
- def get_match_group_list(**kwargs):
- """
- """
- match_id = kwargs.get("match_id")
- match,groups = get_match_groups(match_id)
- return groups
-
- def get_user_markscore_week_avg(request):
- """
- """
- pass
- # now = datetime.datetime.now().date()
- data = []
- msret = cm.UserMarkScore.objects.all().order_by('-stock_date').values()
- msret = msret.values("stock_date").distinct()
- for item in msret:
- qset = cm.UserMarkScore.objects.filter(stock_date=item['stock_date']).aggregate(avg_score=Avg("score"))
- avg_score = "{}".format(round(qset.get("avg_score",0),1))
- data.append({"stock_date":item['stock_date'],"avg_score":avg_score})
- # for i in range(1,5):
- # item_list = []
- # for j in range(1,8):
- # now = now + datetime.timedelta(days=-1)
- # now_str = ccf.datetime_to_str(now,"%Y-%m-%d")
- # qset = cm.UserMarkScore.objects.filter(stock_date=now_str).aggregate(avg_score=Avg("score"))
- # item_list.append({"stock_date":now_str,"avg_score":qset.get("avg_score",0)})
- # data.append(item_list)
- count = (len(data)%5) + 30
- return data[:count]
-
- def refund_out_trade_order(**kwargs):
- """
- """
- _id = kwargs.get("id")
- signup_order = cm.SignupOrder.objects.filter(id=_id).first()
- if signup_order:
- out_trade_no = signup_order.out_trade_no
- transaction_id = signup_order.transaction_id
- total_fee = signup_order.total_fee
- amount = str(int(total_fee*100))
- print(amount)
- result = refund_order(transaction_id,out_trade_no,out_trade_no,amount)
- if result.get("result_code") == "SUCCESS":
- signup_order.order_status = -1
- signup_order.save()
- #删除选手信息
- user_id = signup_order.user_id
- match_id = signup_order.match_id
- cm.Player.objects.filter(user_id=user_id,match_id=match_id).delete()
- return "success"
- else:
- raise ce.TipException(result.get("err_code_des"))
- else:
- raise ce.TipException(u"该订单不存在退款失败!")
- def signup_old_user(**kwargs):
- """
- """
- order_id = kwargs.get("id")
- signup_type = kwargs.get("signup_type")
- match_group = kwargs.get("match_group")
- player_type = kwargs.get("player_type")
- role_type = kwargs.get("role_type")
- order = cm.SignupOrder.objects.filter(id=order_id).first()
- if order:
- user_id = order.user_id
- match_id = order.match_id
- signup_name = order.signup_name
- user = cm.UserInfo.objects.filter(id=user_id).first()
- match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name
- match = cm.Match.objects.filter(id=match_id).first()
- user.player_type = player_type
- user.phone = order.phone
- user.username = signup_name
- user.save()
- order.signup_type = signup_type
- order.match_group = match_group
- order.match_group_name = match_group_name
- order.order_status = 1
- order.save()
-
- #生产选手信息
- player,flag = cm.Player.objects.get_or_create(
- user_id = user_id,
- match_id = match_id
- )
- player.match_name = match.name
- player.match_group = match_group
- player.match_group_name = match_group_name
- player.username = signup_name
- player.usercode = user.usercode
- player.role = role_type
- player.match_status = 1
- player.save()
- def get_user_signup_order(request):
- """#获取用户订单号
- """
- try:
- user_id = request.user.get("id",0)
- except:
- user_id = 0
- qdata = request.json
- pay_status = qdata.get("pay_status")
- if not user_id:
- user_id = qdata.get("user_id")
- match_id = ccc.get_signup_match().id
- qset = cm.SignupOrder.objects.filter(user_id=user_id,match_id=match_id,pay_status=pay_status,order_status=pay_status)
- qdata = qset.values().first()
- return qdata
- def check_msg_content(request):
- """
- """
- qdata = request.json
- APPID = "wxb299e10e65157301"
- APPSECRET = "20e278a60d52ad63822a07e49931435c"
- token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (APPID,APPSECRET)
- res = requests.get(token_url,verify=False)
- access_token = res.json().get("access_token")
- #check msg content
- check_url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=%s" % access_token
- print(access_token)
-
- openid = qdata.get('openid')
- if openid:
- #params = {
- # "content":qdata.get("content"),
- # "version":2,
- # "scene":2,
- # "openid":openid
- # }
- #rest = requests.post(check_url,data=json.dumps(params),verify=False)
- cmdStr = u"""
- curl -X POST -H "Content-Type:application/json" -d '{"content":"%s","version":2,"scene":2,"openid":"%s"}' %s
- """ % (qdata.get("content"),openid,check_url)
- rst = json.loads(os.popen(cmdStr).read())
- return rst
- return {}
- def delete_user_stock(request):
- """
- """
- qdata = request.json
- stock_date = qdata.get("stock_date")
- user_id = qdata.get("user_id")
- match_id = qdata.get("match_id")
- player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
- if player:
- player_id = player.id
- #删除今日作业数据
- cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,stock_date=stock_date).delete()
- #删除今日持仓数据
- month = "%s%s" % (stock_date.split("-")[0],stock_date.split("-")[1])
- cm.UserStock.get_db_model(month).objects.filter(
- player_id = player.id,
- stock_date = stock_date
- ).delete()
- #删除今日出入资金数据
- if cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).exists():
- cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).delete()
- #用前一天数据重置选手初始资金
- yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
- match_id=match_id,player_id=player_id).order_by("-stock_date").first()
- if yesterday:
- player.fund = yesterday.init_fund
- player.save()
- def get_user_fundinout(request):
- """
- """
- try:
- user_id = request.user.get("id",0)
- except:
- user_id = 0
- if not user_id:
- user_id = qdata.get("user_id")
- qdata = request.json
- stock_date = qdata.get("stock_date")
- rst = cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).values().first()
- return rst
- def delete_user_fundinout(request):
- try:
- user_id = request.user.get("id",0)
- except:
- user_id = 0
- if not user_id:
- user_id = qdata.get("user_id")
- match_id = ccc.get_cur_match().id
- qdata = request.json
- stock_date = qdata.get("stock_date")
- #删除出入资金
- if cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).exists():
- cm.FundInOut.objects.filter(user_id = user_id,stock_date=stock_date).delete()
- #player = cm.Player.objects.filter(user_id=user.id,match_id=match_id).first()
- #if player:
- # player_id = player.id
- # #用前一天数据重置选手初始资金
- # yesterday = cm.PlayerRecord.get_db_model(match_id).objects.filter(
- # match_id=match_id,stock_date=stock_date).order_by("-stock_date").first()
- # #if yesterday:
- # # player.fund = yesterday.init_fund
- # # player.save()
- #@ccc.cache_data_kw(5*60)
- def get_match_cangwei_avg_allday(**qdata):
- """每天人均仓位情况
- """
- match_id = qdata.get("match_id")
- allday_cangwei_avg_list = []
- prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id).values("stock_date")\
- .annotate(cnt=Count("stock_date"),total=Sum("today_cangwei"))
- for item in prset:
- stock_date = item["stock_date"]
- cnt = item["cnt"]
- total = item["total"]
- if cnt and total:
- today_cangwei_avg = "{}%".format(round(total/cnt,2)) if cnt>0 else 0.0
- allday_cangwei_avg_list.append({
- "stock_date":stock_date,
- "today_cangwei_avg":today_cangwei_avg
- })
- allday_cangwei_avg_list = sorted(allday_cangwei_avg_list,key=lambda x:x["stock_date"],reverse=True)
- rst = {"list":allday_cangwei_avg_list}
- return rst
|