| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919 |
- #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():
- #记录持股情况
- 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"]
- 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)
- 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.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万元,请仔细核对数据!")
- #有资金出入
- 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.4:
- raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
-
- if float(total_income)>8:
- 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.4:
- raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系顽主!")
- if float(total_income)>8:
- 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")
- 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)
- 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)
- 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")
- 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.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.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
- obj,flag = cm.Consult.objects.get_or_create(
- user_id = user_id,
- )
- obj.user_name = user_name
- obj.user_avatar = user_avatar
- #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.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 {}
|