xjc 3 gadi atpakaļ
vecāks
revīzija
3b271d1bfc

+ 11 - 0
src/common/common_control.py

@@ -10,10 +10,14 @@ from django_redis import get_redis_connection
 
 import common.models as cm
 import common.common_functions as ccf
+from utils.upload_to_oss import hnoss
+import redis_lock
 
 cache = get_redis_connection('data')
 pl = cache.pipeline() 
 
+#redis_lock.reset_all(cache)
+
 class CusJSONEncoder(json.JSONEncoder):
     """
     JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
@@ -107,6 +111,13 @@ def upload_file(request):
     ext = os.path.splitext(upload_file.name)[-1]
     timestamp = str(int(time.time()*1000))
     #dest = settings.STATIC_ROOT + "/upload/"+str(int(time.time()*1000)) + upload_file.name
+    
+    ossfile = timestamp + ext
+    content = upload_file.read()
+    url = hnoss.upload_from_str(content,ossfile)
+    rst = {"url":url,"type":request.POST.get("type"),"name":upload_file.name}
+    return rst
+
     dest = settings.STATIC_ROOT + "/upload/"+ timestamp + ext
     with open(dest,"wb+") as f:
         for chunk in upload_file.chunks():

+ 11 - 5
src/common/models.py

@@ -22,7 +22,7 @@ class UserInfo(models.Model):
     pz = models.CharField(u"品种", max_length=255, blank=True, null=True)
     account_img = models.TextField(u"账号截图", max_length=255, blank=True, null=True)
     join_time = models.CharField(u"入市时间", max_length=255, blank=True, null=True)
-    badge = models.CharField(u"选手标识", max_length=255,blank=False,null=False,default=u"选手")
+    badge = models.CharField(u"选手标识", max_length=255,blank=True,null=True,default=u"选手")
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -50,9 +50,9 @@ class Player(models.Model):
     match_id = models.IntegerField(u"比赛id", blank=True,null=True)
     match_name = models.CharField(u"比赛名称", max_length=255,blank=True,null=True)
     match_group = models.CharField(u"比赛分组", max_length=255,blank=True,null=True)
-    fund = models.FloatField(u"资金",blank=True,null=True)
+    fund = models.FloatField(u"资金",default=0.0)
     match_status = models.SmallIntegerField(u"比赛状态,退赛/暂停/比赛中-1/0/1",default=0)
-    badge = models.CharField(u"选手标识", max_length=255,blank=False,null=False,default=u"选手")
+    badge = models.CharField(u"选手标识", max_length=255,blank=True,null=True,default=u"选手")
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -97,7 +97,7 @@ class PlayerRecord(models.Model):
     cw = models.CharField(u"仓位", max_length=255, blank=True, null=True)
     df = models.CharField(u"打法", max_length=255, blank=True, null=True)
     pz = models.CharField(u"品种", max_length=255, blank=True, null=True)
-    badge = models.CharField(u"选手标识", max_length=255,blank=False,null=False,default=u"选手")
+    badge = models.CharField(u"选手标识", max_length=255,blank=True,null=True,default=u"选手")
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -117,6 +117,8 @@ class Match(models.Model):
     start_time = models.CharField(u"开始时间", max_length=255, blank=True,null=True)
     end_time = models.CharField(u"结束时间", max_length=255, blank=True,null=True)
     groups = models.TextField(u"结束时间", max_length=255, blank=True,null=True)
+    calendar = models.TextField(u"报单日历", max_length=255, blank=True,null=True)
+    valid_dates = models.TextField(u"有效报单时间", max_length=255, blank=True,null=True)
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -135,6 +137,7 @@ class MatchGroup(models.Model):
     match_id = models.IntegerField(u"比赛id", blank=True,null=True)
     name = models.CharField(u"名称", max_length=255, blank=True,null=True)
     is_active = models.SmallIntegerField(u"是否显示",default=1)
+    order = models.IntegerField(u"排序字段",default=1)
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -281,6 +284,7 @@ class UserStock(models.Model):
     player_id = models.IntegerField(u"选手id", blank=True,null=True)
     stock_id = models.IntegerField(u"股票id", blank=True,null=True)
     stock_date = models.CharField(u"持股日期", max_length=255,blank=True,null=True)
+    stock_name = models.CharField(u"股票名称", max_length=255,blank=True,null=True)
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -290,7 +294,7 @@ class UserStock(models.Model):
         app_label = "common"
 
     def __str__(self):
-        return u"{}){}".format(self.id, self.username)
+        return u"{}){}".format(self.id, self.stock_name)
 
 
 class WinDefendRank(models.Model):
@@ -309,6 +313,8 @@ class WinDefendRank(models.Model):
     cw = models.CharField(u"仓位", max_length=255, blank=True, null=True)
     df = models.CharField(u"打法", max_length=255, blank=True, null=True)
     pz = models.CharField(u"品种", max_length=255, blank=True, null=True)
+    auto_complete = models.SmallIntegerField(u"请假次数",default=0)
+    match_status = models.SmallIntegerField(u"比赛状态,退赛/暂停/比赛中-1/0/1",default=1)
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 

+ 46 - 12
src/manage/controls.py

@@ -40,7 +40,7 @@ def async(f):
 
 def update_group_rank_day(match_id,match_group,stock_date):
     #return
-    ccc.cache.delete("*_"+stock_date)
+    #ccc.cache.delete("*_"+stock_date)
     prset = cm.PlayerRecord.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 "
@@ -49,7 +49,7 @@ def update_group_rank_day(match_id,match_group,stock_date):
     #
     delkey = "*_%s_%s_%s" % (match_id,match_group,stock_date)
     del_keys = ccc.cache.keys(delkey)
-    ccc.cache.delete(*del_keys)
+    #ccc.cache.delete(*del_keys)
     for index,pr in enumerate(prset):
         case = "WHEN %s THEN %s" % (pr.id,index+1)
         cases.append(case)
@@ -225,8 +225,8 @@ def update_model(cls,**kwargs):
         player_id = obj.player_id
         cm.Player.objects.filter(id=player_id).update(fund=init_fund)
 
-        #更新group_rank
-        update_group_rank_day(obj.match_id,obj.match_group,obj.stock_date)
+        ##更新group_rank
+        #update_group_rank_day(obj.match_id,obj.match_group,obj.stock_date)
     if model_name == "UserInfo":
         ccc.del_cache("cdata_get_user_info_(%s,)"%id)
 
@@ -379,6 +379,7 @@ def get_list_info(cls,**kwargs):
                 match = cm.Match.objects.filter(id=item["match_id"]).first()
                 item["username"] = user.username
                 item["usercode"] = user.usercode
+                item["nickname"] = user.nickname
                 item["match_name"] = match.name if match else ""
                 item["match_group"] = int(item["match_group"])
                 item["match_group_name"] = cm.MatchGroup.objects.filter(id=int(item["match_group"])).first().name
@@ -460,11 +461,11 @@ def download_records(request):
 
         today_stock = json.loads(item["today_stock"]) if item["today_stock"] else []
         today_stock = list(filter(lambda x:x["name"],today_stock if today_stock else []))
-        today_stock = ",".join([x["name"]+x["fund"] for x in today_stock]) if today_stock else ""
+        today_stock = ",".join([x["name"]+str(x["fund"]) for x in today_stock]) if today_stock else ""
 
         yesterday_stock = json.loads(item["yesterday_stock"]) if item["yesterday_stock"] else []
         yesterday_stock = list(filter(lambda x:x["name"],yesterday_stock if yesterday_stock else []))
-        yesterday_stock = ",".join([x["name"]+x["fund"] for x in yesterday_stock]) if yesterday_stock else ""
+        yesterday_stock = ",".join([x["name"]+str(x["fund"]) for x in yesterday_stock]) if yesterday_stock else ""
 
         #空仓、开超市、请假判断
         if item["auto_complete"] > 0:
@@ -520,23 +521,47 @@ def fast_save_player(**kwargs):
     cm.Player.objects.create(**kwargs)
 
 
-def update_group_rank(stock_date=None):
+def update_player_latest(record):
+    """更新选手最后一次数据
+    """
+    player_id=record["player_id"]
+    match_id = record["match_id"]
+
+    latest = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date").first()
+    if latest:
+        key = "PLAYER_LATEST_{}".format(player_id)
+        ccc.cache.hset(key,"stock_date",latest.stock_date)
+        ccc.cache.hset(key,"match_id",latest.match_id)
+        ccc.cache.hset(key,"match_group",latest.match_group)
+        #更新胜率
+        qset = cm.PlayerRecord.objects.filter(match_id=latest.match_id,player_id=latest.player_id)
+        win_rate = qset.filter(today_income__gte=0).count()/float(qset.count()) if qset else 0.0
+        win_rate = round(win_rate,3)
+        ccc.cache.hset(key,"win_rate",win_rate)
+    badest = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-today_income").first()
+    if badest:
+        key = "PLAYER_LATEST_{}".format(player_id)
+        ccc.cache.hset(key,"badest_income",latest.today_income)
+
+
+def update_group_rank(stock_date=None,match_id=None,group_id=None):
     """
     """
-    ccc.cache.delete("cdata_*")
+    #ccc.cache.delete("cdata_*")
     if stock_date:
         stock_date = stock_date
     else:
         stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
-    ccc.cache.delete("*_"+stock_date)
-    groups = cm.MatchGroup.objects.all()
+    #ccc.cache.delete("*_"+stock_date)
+    #groups = cm.MatchGroup.objects.filter(match_id=match_id)
+    groups = cm.MatchGroup.objects.filter(id=group_id)
     for gp in groups:
         match_id = gp.match_id
         match_group = gp.id
         delkey = "*_%s_%s_%s" % (match_id,match_group,stock_date)
         del_keys = ccc.cache.keys(delkey)
-        if del_keys:
-            ccc.cache.delete(*del_keys)
+        #if del_keys:
+        #    ccc.cache.delete(*del_keys)
         prset = cm.PlayerRecord.objects.filter(match_id=match_id,match_group=match_group,stock_date=stock_date).order_by("-total_income")
         if prset:
             records = prset.values()
@@ -552,6 +577,8 @@ def update_group_rank(stock_date=None):
                 record = records[index]
                 record.update({"group_rank":index+1})
                 ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder))
+                #更新最后一次数据
+                #update_player_latest(record)
             ccc.pl.execute()
             if cases and where:
                 case = case_id + " ".join(cases)
@@ -569,3 +596,10 @@ def update_comment(**kwargs):
     wanzhu_comment = kwargs.get("wanzhu_comment")
     cm.PlayerRecord.objects.filter(id=id).update(wanzhu_comment=wanzhu_comment)
 
+
+def reset_initfund(**kwargs):
+    """
+    """
+    match_id = kwargs.get("match_id")
+    cm.Player.objects.filter(match_id=match_id).update(fund=1)
+    #cm.Player.objects.filter(match_id=match_id,id=3011).update(fund=None)

+ 1 - 3
src/manage/urls_backstage.py

@@ -31,9 +31,7 @@ urlpatterns = [
     url(r'^stock$', views.StockView.as_view()),
     url(r'^stock/list$', views.StockListView.as_view()),
     url(r'^player/record/comment$', views.PlayerRecordCommentView.as_view()),
-
-    url(r'^wxtest$', views.WxTestView.as_view()),
-    url(r'^wxtest/(?P<appid>\w+)/callback$', views.WxTestCallbackView.as_view()),
+    url(r'^reset/initfund$', views.ResetInitFundView.as_view()),
 
 ]
 

+ 30 - 82
src/manage/views.py

@@ -192,7 +192,7 @@ class PlayerView(cv.AdminView):
         try:
             need_params.extend(["match_status","fund"])
             vals = ccf.get_need_params(*need_params,**qdata)
-            vals["fund"] = round(float(vals["fund"]),4)
+            vals["fund"] = round(float(vals.get("fund",0)),4)
             rst = ctl.add_model(self,**vals)
             return cv.to_suc(rst)
         except Exception as e:
@@ -214,7 +214,7 @@ class PlayerView(cv.AdminView):
         try:
             need_params.extend(["match_status","fund"])
             vals = ccf.get_need_params(*need_params,**qdata)
-            vals["fund"] = round(float(vals["fund"]),4)
+            vals["fund"] = round(float(vals.get("fund",0)),4)
             rst = ctl.update_model(self,**vals)
             return cv.to_suc(rst)
         except Exception as e:
@@ -285,7 +285,9 @@ class MatchView(cv.AdminView):
         if mse:
             raise ce.TipException(mse)
         try:
+            need_params.extend(["calendar","valid_dates"])
             vals = ccf.get_need_params(*need_params,**qdata)
+            vals["valid_dates"] = json.dumps(vals["valid_dates"])
             rst = ctl.add_model(self,**vals)
             return cv.to_suc(rst)
         except Exception as e:
@@ -305,7 +307,9 @@ class MatchView(cv.AdminView):
         if mse:
             raise ce.TipException(mse)
         try:
+            need_params.extend(["calendar","valid_dates"])
             vals = ccf.get_need_params(*need_params,**qdata)
+            vals["valid_dates"] = json.dumps(vals["valid_dates"])
             rst = ctl.update_model(self,**vals)
             return cv.to_suc(rst)
         except Exception as e:
@@ -630,12 +634,12 @@ class PlayerFastSaveView(cv.AdminView):
         @match_status:"比赛状态"
         """
         qdata = request.json
-        need_params = ["username","fund","match_id","match_group"]
+        need_params = ["username","match_id","match_group"]
         mse = ccf.check_params(*need_params,**qdata)
         if mse:
             raise ce.TipException(mse)
         try:
-            need_params.extend(["usercode","match_status"])
+            need_params.extend(["usercode","match_status","fund"])
             vals = ccf.get_need_params(*need_params,**qdata)
             if not vals.get("usercode"):
                 vals["usercode"] = self.gen_code()
@@ -651,8 +655,10 @@ class PlayerAutoRecordView(cv.AdminView):
     def post(self,request):
         """#自动补全数据(平台管理后台)
         """
+        qdata = request.json
+        stock_date = qdata.get("stock_date")
         from tools.autocomplete_record import auto_gen_record
-        auto_gen_record()
+        auto_gen_record(stock_date)
         return cv.to_suc()
 
 
@@ -754,9 +760,15 @@ class FlushRankView(cv.AdminView):
         @page_size:20
         """
         qdata = request.json
+        need_params = ["stock_date","match_id","groupId"]
+        mse = ccf.check_params(*need_params,**qdata)
+        if mse:
+            raise ce.TipException(mse)
         try:
             stock_date = qdata.get("stock_date")
-            ctl.update_group_rank(stock_date)
+            match_id = qdata.get("match_id")
+            groupId = qdata.get("groupId")
+            ctl.update_group_rank(stock_date,match_id,groupId)
             return cv.to_suc()
         except Exception as e:
             cv.tracefail()
@@ -873,84 +885,20 @@ class StockListView(cv.AdminView):
             return cv.to_fail(e)
 
 
-class WxTestView(cv.BaseView):
-    def get(self,request):
-        """
-        """
-        return HttpResponse("success")
-
-
-    def get_wx_auth_ticket(self,xml,timestamp,nonce,msg_signature):
-        """获取微信通过授权URL推送的票据
-        """
-        import xml.etree.cElementTree as ET
-        from WXBizMsgCrypt import WXBizMsgCrypt
-        encodingAESKey = "NBFPgHxUIlQ628bYwDJOZQNMp7T1YGykpzzYklo9tmY"
-        token = "1234567890987654321"
-        APPID = "wx02753c07bbfce783"
-
-        decrypt_test = WXBizMsgCrypt(token,encodingAESKey,APPID)
-
-        ret,decryp_xml = decrypt_test.DecryptMsg(xml,msg_signature,timestamp, nonce)
-        if decryp_xml: 
-            xml_tree = ET.fromstring(decryp_xml)
-            print xml_tree,999999999999999
-            ComponentVerifyTicket  = xml_tree.find("ComponentVerifyTicket")
-            return ComponentVerifyTicket
-        return None
-
-    def post(self, request):
-        """#更新排名(平台管理后台)
-        @name:""
-        @page:1
-        @page_size:20
-        """
-        print request.body
-        qdata = request.GET
-        try:
-            postxml = request.body
-            timestamp = request.GET.get("timestamp")
-            nonce = request.GET.get("nonce")
-            msg_signature = request.GET.get("msg_signature")
-            ticket = self.get_wx_auth_ticket(postxml,timestamp,nonce,msg_signature)
-            print "ticket:",ticket
-            return HttpResponse("success")
-        except Exception as e:
-            cv.tracefail()
-            return cv.to_fail(e)
-
-
-class WxTestCallbackView(cv.BaseView):
-    def get(self,request):
-        """
-        """
-        print request.GET
-        print request.REQUEST
-        print request.body
-        return HttpResponse("success")
-
-    def post(self, request,appid):
-        """#更新排名(平台管理后台)
-        @name:""
-        @page:1
-        @page_size:20
+class ResetInitFundView(cv.AdminView):
+    def post(self,request):
+        """#重置初始资金(平台管理后台)
+        @match_id:"1"
         """
-        print request.POST
-        print 11111111111
-        print request.body
-        print 22222222222222
-        print request.json
-        qdata = request.GET
+        qdata = request.json
+        need_params = ["match_id"]
+        mse = ccf.check_params(*need_params,**qdata)
+        if mse:
+            raise ce.TipException(mse)
         try:
-            openid = qdata.get("openid")
-            from wechatpy import WeChatClient
-            client = WeChatClient("wx84a42c807ed07198", "e2de849dfef826b1854c0b18407a6be2")
-            #client.message.send_mass_text(None,u"欢迎关注四川环宇星创科技有限公司公众号!",True)
-            client.message.send_text(openid,u"点击绑定手机号查看您的电子证书:http://testcaos.tederen.com/zs.jpg")
-
-            return HttpResponse(qdata.get("timestamp"))
-
-            return HttpResponse("success")
+            vals = ccf.get_need_params(*need_params,**qdata)
+            rst = ctl.reset_initfund(**vals)
+            return cv.to_suc(rst)
         except Exception as e:
             cv.tracefail()
             return cv.to_fail(e)

+ 1 - 1
src/settings/__init__.py

@@ -1,3 +1,3 @@
 #coding=utf-8
-from settings_dev import *
+from .settings_online import *
 

+ 13 - 11
src/settings/settings_online.py

@@ -1,11 +1,20 @@
 # coding=utf-8
-from base import *
+from .base import *
 
 # redis配置
 CACHES = {
     'default': {
         'BACKEND': 'django_redis.cache.RedisCache',
         'LOCATION': 'redis://127.0.0.1:6379/0',
+        'TIMEOUT': 60*10,
+        "OPTIONS": {
+            "CLIENT_CLASS": "django_redis.client.default.DefaultClient",
+        },
+    },
+    'data': {
+        'BACKEND': 'django_redis.cache.RedisCache',
+        'LOCATION': 'redis://127.0.0.1:6379/1',
+        'TIMEOUT': 60*60*24,
         "OPTIONS": {
             "CLIENT_CLASS": "django_redis.client.default.DefaultClient",
         },
@@ -60,14 +69,7 @@ LOGGING = {
     },
 }
 
+RANK_LIST = "RANK_LIST"
 
-#channels                                                                          
-CHANNEL_LAYERS = {                                                                 
-    "default": {                                                                   
-        "BACKEND": "asgi_redis.RedisChannelLayer",                                     
-        "CONFIG": {                                                                    
-                    "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],          
-                },                                                                             
-            "ROUTING": "dashboard.routings.channel_routing",                         
-        },                                                                             
-} 
+HOST = "https://www.hunanwanzhu.com"
+PROJECT_NAME = u"顽主杯"

+ 0 - 0
src/sync_stock_data.py


+ 39 - 25
src/tools/autocomplete_record.py

@@ -1,9 +1,10 @@
 #coding:utf-8
-import os
+import os,json
 import time
 import datetime
 import sys
 import django
+from threading import Thread
 
 sys.path.append('/mnt/wzbapi/src')
 os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
@@ -11,27 +12,42 @@ django.setup()
 
 import common.models as cm
 
+def get_valid_dates():
+    """
+    """
+    match_id = 8
+    valid_dates = cm.Match.objects.filter(id=match_id).first().valid_dates
+    valid_dates = json.loads(valid_dates)
+    valid_dates.sort()
+    return valid_dates
 
-def auto_gen_record():
+def auto_gen_record(stock_date=None):
     """每天15:30以后如果选手没有填报数据则,自动为其生产一天数据
     今日资产等于昨日资产,今日收益为0,总收益不变.自动生产一次则
     标识一次请假,请假超过5次则将该选手表示为退赛状态
     """
+    print stock_date
     now_time = datetime.datetime.now().strftime("%H:%S")
 
-    if "16:00"<now_time<"23:59":
-        now_stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
-        plaset = cm.Player.objects.filter(match_status=1)
+    if "23:00"<now_time<"23:59" or stock_date:
+        if not stock_date:
+            now_stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
+        else:
+            now_stock_date = stock_date
+        cur_match_id = cm.Match.objects.all().order_by("-id").first().id
+        plaset = cm.Player.objects.filter(match_status=1,match_id=cur_match_id)
         for pla in plaset:
             player_id = pla.id
             match_id = pla.match_id
             match_group = pla.match_group
             user = cm.UserInfo.objects.filter(id=pla.user_id).first()
+
             if not cm.PlayerRecord.objects.filter(
                     player_id=player_id,
                     match_id=match_id,
                     stock_date=now_stock_date
                     ).exists():
+                print "start autocomplete:",player_id,match_id,stock_date
                 #昨日数据
                 yesterday = cm.PlayerRecord.objects.filter(player_id=player_id,
                     match_id=match_id).filter(stock_date__lt=now_stock_date).order_by("-stock_date").first()
@@ -74,29 +90,27 @@ def auto_gen_record():
                         total_income=0,
                         auto_complete=1
                     )
-                #更新排名与请假标识
-                records_set = cm.PlayerRecord.objects.filter(match_id=match_id,match_group=match_group,stock_date=now_stock_date).order_by("-total_income")
-                for index,item in enumerate(records_set):
-                    item.rank = index+1
-                    item.save()
-                #更新请假标识
-                records_set = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id,match_group=match_group,stock_date=now_stock_date,auto_complete__gt=0).order_by("-stock_date")
-                for index,item in enumerate(records_set):
-                    item.auto_complete = index+1
-                    item.save()
-                if records_set.count()>5:
-                    pla.match_status = -1
-                    pla.save()
-                print u"complete add{} data:{}".format(now_stock_date,pla.usercode)
+
+            #统计请假标识
+            records_set = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id,match_group=match_group,auto_complete__gt=0)
+            print "player_id=",player_id,"match_id=",match_id,"stock_date=",stock_date,"auto_complete=",records_set.count()
+            #更新胜率榜的请假标识
+            cm.WinDefendRank.objects.filter(player_id=player_id,match_id=match_id).update(auto_complete=records_set.count())
+
+            #退赛
+            #if records_set.count()>5:
+            #    pla.match_status = -1
+            #    pla.save()
 
 if __name__ == "__main__":
     auto_gen_record()
-    #while True:
-    #    try:
-    #        auto_gen_record()
-    #        time.sleep(300)
-    #    except KeyboardInterrupt:
-    #        sys.exit(0)
+    #valid_dates = get_valid_dates()
+    #for stock_date in valid_dates:
+    #    now_stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
+    #    if stock_date < now_stock_date:
+    #        print stock_date
+    #        t = Thread(target=auto_gen_record,args=(stock_date,))
+    #        t.start()
 
 
 

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 4684 - 0
src/tools/code.csv


+ 24 - 0
src/tools/loadcode.py

@@ -0,0 +1,24 @@
+#import tushare as ts
+import csv
+import os
+
+def get_stock_list():
+    """
+    """
+    #ts.set_token('56cda41c39cfd949e9e11211a6b46ac700f2df2684fa74bd23e3ce4c')
+    #pro = ts.pro_api()
+    #
+    #df = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,fullname,enname,cnspell,market,list_date')
+    #data = df.to_records()
+    #df.to_json("test.json")
+    data = []
+    with open("/mnt/wzbapi/src/tools/code.csv","r") as f:
+        rows = csv.reader(f)
+        for row in rows:
+            data.append(row)
+    return data
+
+
+
+
+

+ 60 - 26
src/tools/rank_server.py

@@ -19,7 +19,8 @@ def rank_server():
     """
     """
     rcid = ccc.cache.rpop(settings.RANK_LIST)
-    print rcid
+    #rcid = 117904
+    print rcid,99999999999999999
     record = cm.PlayerRecord.objects.filter(id=rcid).first()
     if record:
         match_id = int(record.match_id)
@@ -31,9 +32,11 @@ def rank_server():
         else:
             update_cache_rank(match_id,match_group,stock_date)
             sync_group_rank(match_id,match_group,stock_date)
-            update_hot_seller(record)
+            #update_hot_seller(record)
         #更新胜率榜
         update_win_defend_rank(record)
+        #更新最值
+        update_player_latest(record)
 
 def update_win_defend_rank(record):
     """更新胜率防守榜
@@ -49,27 +52,35 @@ def update_win_defend_rank(record):
     cw = record.cw
     df = record.df
     pz = record.pz
-    #胜率
-    qset = cm.PlayerRecord.objects.filter(match_id=match_id,player_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)
-    #最大回撤
-    badest_income = qset.order_by("today_income").first().today_income
-    badest_income = round(badest_income,3)
-
-    obj,flag = cm.WinDefendRank.objects.get_or_create(
-        user_id = user_id, 
-        player_id = player_id, 
-        match_id = match_id, 
-        match_group = match_group 
-    )
-    obj.user_name = user_name
-    obj.today_fund = today_fund
-    obj.total_income = total_income
-    obj.win_rate = win_rate
-    obj.badest_income = badest_income
-    obj.save()
+    
+    player = cm.Player.objects.filter(id=player_id).first()
+    if player:
+        #胜率
+        qset = cm.PlayerRecord.objects.filter(match_id=match_id,player_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)
+        #最大回撤
+        badest_income = qset.order_by("today_income").first().today_income
+        badest_income = round(badest_income,3)
+        #选手状态
+        match_status = player.match_status
+        #请假次数
+        auto_complete = qset.filter(auto_complete__gt=0).count()
+
+        obj,flag = cm.WinDefendRank.objects.get_or_create(
+            user_id = user_id, 
+            player_id = player_id, 
+            match_id = match_id, 
+            match_group = match_group 
+        )
+        obj.user_name = user_name
+        obj.today_fund = today_fund
+        obj.total_income = total_income
+        obj.win_rate = win_rate
+        obj.badest_income = badest_income
+        obj.match_status = match_status
+        obj.auto_complete = auto_complete
+        obj.save()
 
 
 def update_cache_rank(match_id,match_group,stock_date):
@@ -88,9 +99,10 @@ def update_cache_rank(match_id,match_group,stock_date):
     where = []
     for index,pr in enumerate(prset):
         key = "%s_%s_%s_%s" % (pr.player_id,match_id,match_group,stock_date)
+        print(key)
         record = records[index]
         record.update({"group_rank":index+1})
-        ccc.cache.delete(key)
+        #ccc.cache.delete(key)
         ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder))
     ccc.pl.execute()
 
@@ -116,7 +128,7 @@ def sync_group_rank(match_id,match_group,stock_date):
         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.cache.delete(key)
         ccc.pl.set(key,json.dumps(record,cls=ccc.CusJSONEncoder))
     ccc.pl.execute()
     #同步数据库
@@ -162,11 +174,33 @@ def update_hot_seller(record):
                 obj.count = count
                 obj.save()
 
+def update_player_latest(record):
+    """更新选手最后一次数据
+    """
+    player_id=record.player_id
+    match_id = record.match_id
+
+    latest = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date").first()
+    if latest:
+        key = "PLAYER_LATEST_{}".format(player_id)
+        ccc.cache.hset(key,"stock_date",latest.stock_date)
+        ccc.cache.hset(key,"match_id",latest.match_id)
+        ccc.cache.hset(key,"match_group",latest.match_group)
+        #更新胜率
+        qset = cm.PlayerRecord.objects.filter(match_id=latest.match_id,player_id=latest.player_id)
+        win_rate = qset.filter(today_income__gte=0).count()/float(qset.count()) if qset else 0.0
+        win_rate = round(win_rate,3)
+        ccc.cache.hset(key,"win_rate",win_rate)
+    badest = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-today_income").first()
+    if badest:
+        key = "PLAYER_LATEST_{}".format(player_id)
+        ccc.cache.hset(key,"badest_income",latest.today_income)
+
 if __name__ == "__main__":
     print "start update group rank..."
     while True:
         rank_server()
-        time.sleep(0.1)
+        time.sleep(1)
 
 
 

+ 84 - 27
src/tools/sync_data.py

@@ -14,11 +14,12 @@ django.setup()
 
 import common.models as cm
 import common.common_functions as ccf
+import common.common_control as ccc
 
 def sync_stock():
     """同步用户持股和股票仓库数据
     """
-    prset = cm.PlayerRecord.objects.order_by("stock_date")
+    prset = cm.PlayerRecord.objects.filter(match_id=8).order_by("stock_date")
     for index,pr in enumerate(prset):
         player_id = pr.player_id
         match_id = pr.match_id
@@ -60,7 +61,8 @@ def sync_stock():
 def sync_win_defend():
     """更新胜率和最大回撤
     """
-    match_id = 7
+    match_id = 9
+    cm.WinDefendRank.objects.filter(match_id=match_id).delete()
     players = cm.Player.objects.filter(match_id=match_id)
     for pl in players:
         record = cm.PlayerRecord.objects.filter(match_id=match_id,player_id=pl.id).order_by("-stock_date").first()
@@ -75,9 +77,9 @@ def update_win_defend_rank(record):
     """更新胜率防守榜
     """
     player_id = record.player_id
-    user_id = record.user_id
     match_id = record.match_id
     match_group = record.match_group
+    user_id = record.user_id
     user_name = record.username
     today_fund = record.today_fund
     total_income = record.total_income
@@ -85,27 +87,35 @@ def update_win_defend_rank(record):
     cw = record.cw
     df = record.df
     pz = record.pz
-    #胜率
-    qset = cm.PlayerRecord.objects.filter(match_id=match_id,player_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)
-    #最大回撤
-    badest_income = qset.order_by("today_income").first().today_income
-    badest_income = round(badest_income,3)
-
-    obj,flag = cm.WinDefendRank.objects.get_or_create(
-        user_id = user_id, 
-        player_id = player_id, 
-        match_id = match_id, 
-        match_group = match_group 
-    )
-    obj.username = user_name
-    obj.today_fund = today_fund
-    obj.total_income = total_income
-    obj.win_rate = win_rate
-    obj.badest_income = badest_income
-    obj.save()
+    
+    player = cm.Player.objects.filter(id=player_id).first()
+    if player:
+        #胜率
+        qset = cm.PlayerRecord.objects.filter(match_id=match_id,player_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)
+        #最大回撤
+        badest_income = qset.order_by("today_income").first().today_income
+        badest_income = round(badest_income,3)
+        #选手状态
+        match_status = player.match_status
+        #请假次数
+        auto_complete = qset.filter(auto_complete__gt=0).count()
+
+        obj,flag = cm.WinDefendRank.objects.get_or_create(
+            user_id = user_id, 
+            player_id = player_id, 
+            match_id = match_id, 
+            match_group = match_group 
+        )
+        obj.user_name = user_name
+        obj.today_fund = today_fund
+        obj.total_income = total_income
+        obj.win_rate = win_rate
+        obj.badest_income = badest_income
+        obj.match_status = match_status
+        obj.auto_complete = auto_complete
+        obj.save()
 
 def sync_hot_seller():
     """同步热门清仓数据
@@ -113,7 +123,6 @@ def sync_hot_seller():
     all_dates = list(cm.UserStock.objects.order_by("stock_date").values_list("stock_date",flat=True))
     all_dates = list(set(all_dates))
     all_dates.sort()
-
     for stock_date in all_dates:
         stock_date_time = ccf.str_to_datetime(stock_date,"%Y-%m-%d")
         yesterday = (stock_date_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
@@ -144,14 +153,62 @@ def sync_hot_seller():
                     obj.count = count
                     obj.save()
 
+def sync_user_stock():
+    """
+    """
+    #qset = cm.UserStock.objects.all()
+    #for obj in qset:
+    #    try:
+    #        print(obj.stock_id)
+    #        obj.stock_name = cm.Stock.objects.filter(id=obj.stock_id).first().name
+    #        obj.save()
+    #    except Exception as e:
+    #        print(e)
+    #        pass
+    stock_ids = list(cm.UserStock.objects.all().values_list("stock_id",flat=True))
+    stock_ids = list(set(stock_ids))
+    for sid in stock_ids:
+        try:
+            stock_name = cm.Stock.objects.filter(id=sid).first().name
+            print stock_name
+            cm.UserStock.objects.filter(stock_id=sid).update(stock_name=stock_name)
+        except Exception as e:
+            pass
+
+def sync_player_latest():
+    """更新选手最后一次数据
+    """
+    match_id = 8
+    qset = cm.Player.objects.filter(match_id=match_id,match_status=1)
+    for obj in qset:
+        latest = cm.PlayerRecord.objects.filter(player_id=obj.id,match_id=match_id).order_by("-stock_date").first()
+        if latest:
+            key = "PLAYER_LATEST_{}".format(obj.id)
+            print "latest:",obj.id,latest.stock_date
+            ccc.cache.hset(key,"stock_date",latest.stock_date)
+            ccc.cache.hset(key,"match_id",latest.match_id)
+            ccc.cache.hset(key,"match_group",latest.match_group)
+
+            #更新胜率
+            qset = cm.PlayerRecord.objects.filter(match_id=latest.match_id,player_id=latest.player_id)
+            win_rate = qset.filter(today_income__gte=0).count()/float(qset.count()) if qset else 0.0
+            win_rate = round(win_rate,3)
+            ccc.cache.hset(key,"win_rate",win_rate)
+
+        badest = cm.PlayerRecord.objects.filter(player_id=obj.id).order_by("-today_income").first()
+        if badest:
+            key = "PLAYER_LATEST_{}".format(obj.id)
+            ccc.cache.hset(key,"badest_income",latest.today_income)
+            print "badest:",obj.id,badest.today_income
 
 
 if __name__ == "__main__":
     print "start sync stock..."
     st = time.time()
-    sync_stock()
     sync_win_defend()
-    sync_hot_seller()
+    #sync_user_stock()
+    #sync_hot_seller()
+    #sync_player_latest()
     print "time cost:",time.time()-st
 
 

+ 45 - 0
src/tools/sync_stock_data.py

@@ -0,0 +1,45 @@
+#coding:utf-8
+import os,json
+import time
+import datetime
+import sys
+import django
+from django.core.cache import cache
+from django.db import connection
+from django.db.models import Q,Sum,Count,F
+
+sys.path.append('/mnt/wzbapi/src')
+os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
+django.setup()
+
+import common.models as cm
+import common.common_functions as ccf
+from .loadcode import get_stock_list
+
+def sync_stock_data():
+    """同步股票数据
+    """
+    stock_list = get_stock_list()
+    for item in stock_list:
+        code = item[2]
+        name = item[3]
+        print(code,name)
+        obj,flag = cm.Stock.objects.get_or_create(
+                    name = name, 
+                )
+        obj.code = code
+        obj.save()
+
+
+
+if __name__ == "__main__":
+    print("start sync stock...")
+    st = time.time()
+    sync_stock_data()
+    #cm.Stock.objects.filter(code__isnull=False).delete()
+    print("time cost:",time.time()-st)
+
+
+
+
+

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1 - 0
src/tools/test.json


+ 64 - 0
src/tools/update_initfund.py

@@ -0,0 +1,64 @@
+#coding:utf-8
+import os
+import time
+import datetime
+import sys
+import django
+from django.core.cache import cache
+from django.db import connection
+
+sys.path.append('/mnt/wzbapi/src')
+os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
+django.setup()
+
+import common.models as cm
+
+def update_initfund():
+    """
+    """
+    prset = cm.PlayerRecord.objects.filter(match_id=10,stock_date="2022-04-26")
+    for index,pr in enumerate(prset):
+        print(pr.id)
+        pr.init_fund = pr.today_fund
+        pr.today_income = 0.0
+        pr.total_income = 0.0
+        pr.yesterday_fund = pr.today_fund
+        pr.save()
+        player_id = pr.player_id
+        cm.Player.objects.filter(id=player_id).update(fund=pr.today_fund)
+
+def update_income():
+    """
+    """
+    prset = cm.PlayerRecord.objects.filter(match_id=10,stock_date="2022-04-27")
+    for index,pr in enumerate(prset):
+        player_id = pr.player_id
+        today_fund = pr.today_fund
+
+        yesterday = cm.PlayerRecord.objects.filter(match_id=10,player_id=player_id,stock_date="2022-04-26")
+        if yesterday:
+            yesterday = yesterday.first()
+            yesterday_fund = yesterday.today_fund
+            init_fund = yesterday.init_fund
+
+            today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
+            total_income = (today_fund - init_fund)/float(init_fund)
+
+
+            pr.init_fund = init_fund
+            pr.today_income = round(today_income,4)
+            pr.total_income = round(total_income,4)
+            pr.save()
+
+
+if __name__ == "__main__":
+    print "start update init_fund..."
+    st = time.time()
+    #update_initfund()
+    update_income()
+    print "time cost:",time.time()-st
+
+
+
+
+

+ 2 - 1
src/tools/update_player_record.py

@@ -16,8 +16,9 @@ import common.models as cm
 def update_player_record():
     """
     """
-    stock_date = "2021-12-15"
+    stock_date = "2022-04-26"
     qset = cm.PlayerRecord.objects.filter(stock_date=stock_date)
+    print(qset.count())
     for obj in qset:
         obj.today_fund = obj.init_fund
         obj.today_income = 0 

+ 2 - 2
src/tools/update_records.py

@@ -16,12 +16,12 @@ import common.models as cm
 def update_records():
     """
     """
-    prset = cm.PlayerRecord.objects.filter(stock_date="2021-10-18")
+    prset = cm.PlayerRecord.objects.filter(stock_date="2022-05-09")
     for index,pr in enumerate(prset):
         player_id = pr.player_id
         match_id = pr.match_id
         match_group = pr.match_group
-        yesterday = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id,match_group=match_group,stock_date="2021-10-15").first()
+        yesterday = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id,match_group=match_group,stock_date="2022-05-06").first()
         if yesterday:
             pr.yesterday_fund = yesterday.today_fund
             pr.yesterday_stock = yesterday.today_stock

+ 12 - 9
src/utils/upload_to_oss.py

@@ -9,14 +9,15 @@ class MyOSS:
     def __init__(self):
         """
         """
-        self.AccessKeyID = 'LTAIbkpKrzQViemJ'
-        self.AccessKeySecret = '9y9mqNFMMDfUEBGvWqHt3wGas2W5ML'
-        self.bucket_name = 'scxjcclub'
-        self.root_name = 'say365'
+        self.AccessKeyID = 'LTAI5t8bioQxGXB1jtVugJcU'
+        self.AccessKeySecret = 'OdGWSBRjkJxaPjgmE38eQ8nzkI6nRk'
+        self.bucket_name = 'hunanwanzhu'
+        self.root_name = 'hnwz'
         self.auth = oss2.Auth(self.AccessKeyID, self.AccessKeySecret)
-        self.endpoint = 'http://oss-cn-beijing.aliyuncs.com'
+        self.endpoint = 'http://oss-cn-shenzhen.aliyuncs.com'
         self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)
-        self.domain = 'http://scxjcclub.oss-cn-beijing.aliyuncs.com'
+        self.domain = 'http://hunanwanzhu.oss-cn-shenzhen.aliyuncs.com'
+        self.watermark = '?x-oss-process=image/auto-orient,1/quality,q_90/watermark,text_6aG95Li75p2v5a6e55uY5aSn6LWb,color_ff0000,size_50,rotate_330,g_center,t_70,x_10,y_10'
 
 
     def upload_from_str(self,content_str=None,filename=None):
@@ -33,7 +34,7 @@ class MyOSS:
         else:
             url = ''
 
-        return url
+        return url + self.watermark if url else ""
 
     def upload_from_local(self, localfile=None, ossfile=None):
         '''
@@ -49,7 +50,7 @@ class MyOSS:
         else:
             url = ''
 
-        return url
+        return url + self.watermark if url else ""
 
     def resumable_upload_from_local(self, localfile=None, ossfile=None):
         ossfile = os.path.join(self.root_name, ossfile)
@@ -82,7 +83,9 @@ class MyOSS:
         else:
             url = ''
 
-        return url
+        return url + self.watermark if url else ""
+
+hnoss = MyOSS()
 
 if __name__ == '__main__':
     myoss = MyOSS()

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 876 - 0
src/wanzb.sql.20220427


+ 1 - 1
src/weixin/constants.py

@@ -3,5 +3,5 @@
 #不能提交数据的日期(周六周日可不配置)
 MISS_DATES = [
     "2021-10-30",        
-    "2021-10-31",        
+    "2021-10-31"
 ]

+ 393 - 123
src/weixin/controls.py

@@ -44,6 +44,7 @@ def async(f):
 
 
 def get_today_date():
+    #return '2021-12-31'
     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.objects.all().order_by("-stock_date").first().stock_date
@@ -141,6 +142,9 @@ def get_player_match_list(request):
     #match_ids = list(cm.Player.objects.filter(user_id=uid,match_id=cur_match_id).values_list("match_id",flat=True))
     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
 
@@ -164,22 +168,29 @@ def get_player_match_detail(request):
     """
     qdata = request.json
     player_id = request.player.id
+    user_id = request.player.user_id
     org_player_id = request.player.id
     match_group = request.player.match_group
     match_id = qdata.get("id")
     record_id = qdata.get("record_id")
+    cur_player_id = qdata.get("player_id")
+
+    ismine = True if int(cur_player_id) == player_id else False
 
     if record_id:
         records_set = cm.PlayerRecord.objects.filter(id=record_id)
-        match_id = records_set.first().match_id
-        match_group = records_set.first().match_group
-        player_id = records_set.first().player_id
-        records_set = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date")
+        if records_set:
+            match_id = records_set.first().match_id
+            match_group = records_set.first().match_group
+            player_id = records_set.first().player_id
+            records_set = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date")
     else:
         if qdata.get("player_id"):
             player_id = qdata.get("player_id")
             match_group = cm.Player.objects.filter(id=player_id).first().match_group
-
+        else:
+            #为了兼容老版本没有传player_id要获取用户的某届赛事player_id
+            player_id = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first().id
         records_set = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date")
 
 
@@ -191,11 +202,6 @@ def get_player_match_detail(request):
     else:
         records = []
 
-    today = get_today_date()
-
-    today = records_set.first().stock_date
-    today_record = get_today_record(player_id,int(match_id),int(match_group),today)
-
     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 []
@@ -203,20 +209,36 @@ def get_player_match_detail(request):
         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)
-    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(player_id,today_record["match_id"])
-        badest = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("today_income").first()
-        if badest:
-            today_record["badest_income"] = "{}%".format(badest.today_income*100)
+
+    today = get_today_date()
+    if records_set.first():
+        today = records_set.first().stock_date
+        #today_record = get_today_record(player_id,int(match_id),int(match_group),today)
+        #if not today_record:
+        #    today_record = get_today_record_actual(player_id,match_id,today)
+        if ismine:
+            today_record = get_today_record_actual(player_id,match_id,match_group,today)
+        else:
+            today_record = get_today_record(player_id,int(match_id),int(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(player_id,today_record["match_id"])
+            badest = cm.PlayerRecord.objects.filter(player_id=player_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["today_stock_total"],4)
+            userinfo = get_user_info(today_record["user_id"])
+            today_record["style"] = userinfo.get("style")
+    else:
+        today_record = {}
 
     match["groups"] = [today_record["match_group_name"]] if today_record else []
-    records = sorted(records,key=lambda x:x["stock_date"],reverse=True)[:5]
+    records = sorted(records,key=lambda x:x["stock_date"],reverse=True)
     if cm.UserFollows.objects.filter(user_id=org_player_id,follow_id=player_id).exists():
         is_follow = 1
     else:
@@ -256,17 +278,47 @@ def get_today_record(player_id,match_id,match_group,today):
         traceback.print_exc()
     return today_record
 
+
+def get_today_record_actual(player_id,match_id,match_group,today=None):
+    """
+    """
+    if today:
+        qset = cm.PlayerRecord.objects.filter(match_id=match_id,match_group=match_group,player_id=player_id,stock_date=today)
+    else:
+        qset = cm.PlayerRecord.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()
+@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).values())
+    groups = list(cm.MatchGroup.objects.filter(match_id=match_id,is_active=1).order_by("order").values())
     #groups = list(cm.MatchGroup.objects.filter(match_id=match_id).values())
     return match,groups
 
@@ -275,15 +327,18 @@ def get_cache_rank_list(player_id,match_id,today):
     """
     """
     match,groups = get_match_groups(match_id)
+    #groups = sorted(groups,key=lambda x:x["id"])
 
     #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")
-
+    data = []
     for item in groups:
         new_players = []
         players = get_match_group_players(match_id,item["id"])
+        win_count = 0
+        loss_count = 0
         for player in players:
             user_id = player["user_id"]
             user = get_user_info(user_id) 
@@ -296,9 +351,15 @@ def get_cache_rank_list(player_id,match_id,today):
                 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
+
                 try:
                     player["fund"] = round(player["fund"],4) if player["fund"] else 0.0
                     player["init_fund"] = round(player["init_fund"],4)
@@ -308,15 +369,20 @@ def get_cache_rank_list(player_id,match_id,today):
                 except Exception as e:    
                     print player
                     pass
-        new_players = sorted(new_players,key=lambda x:x["group_rank"])
-        win_count = filter(lambda x:x["org_today_income"]>=0.05,new_players)
-        loss_count = filter(lambda x:x["org_today_income"]<=-0.05,new_players)
-        #item["players_num"] = cm.Player.objects.filter(match_group=item["id"]).count()
+        #win_count = filter(lambda x:x["org_today_income"]>=0.05,new_players)
+        #loss_count = filter(lambda x:x["org_today_income"]<=-0.05,new_players)
+
+        new_players_sort = list(sorted(new_players,key=lambda x:x["org_total_income"],reverse=True))
+        #new_players_sort = new_players
+
         item["players_num"] = len(players)
-        item["win_count"] = len(win_count)
-        item["loss_count"] = len(loss_count)
-        item["players"] = new_players[:3]
-    return match,groups
+        #item["win_count"] = len(win_count)
+        #item["loss_count"] = len(loss_count)
+        item["win_count"] = win_count
+        item["loss_count"] = loss_count
+        item["players"] = new_players_sort[:3]
+        data.append(item)
+    return match,data
 
 
 def get_rank_list(request):
@@ -324,9 +390,12 @@ def get_rank_list(request):
     """
     qdata = request.json
     player_id = request.player.id
-    match_id = request.player.match_id
+
+    match_id = qdata.get("match_id")
 
     today = qdata.get("stock_date")
+    if not today:
+        today = get_today_date()
 
     match,groups = get_cache_rank_list(player_id,match_id,today)
 
@@ -369,20 +438,25 @@ def get_group_rank_list(request):
     group_id = qdata.get("id")
     player_id = request.player.id
     match_id = request.player.match_id
-    today = qdata.get("stock_date")
+    match_id = qdata.get("match_id")
 
-    match_id = 8
+    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_players(match_id,group_id)
+    print(match_id,group_id)
+    print(len(players))
     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)
@@ -408,12 +482,14 @@ def get_group_rank_list(request):
     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["group_rank"])
+        new_players = sorted(new_players,key=lambda x:x["org_total_income"],reverse=True)
+
+    #new_players = []
 
     #分页
     page = int(kwargs.get("page",0))
-    page_size = int(kwargs.get("page_size",20))
-    page_size = 50
+    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:
@@ -444,11 +520,11 @@ def get_player_match_records(request):
     page = int(qdata.get("page",0))
     page_size = int(qdata.get("page_size",20))
 
-    if int(match_id) == 7:
-        player = cm.Player.objects.filter(match_id=match_id,usercode=request.user.usercode).first()
-        if player:
-            player_id = player.id
-            match_group = player.match_group
+    #if int(match_id) == 7:
+    #    player = cm.Player.objects.filter(match_id=match_id,usercode=request.user.usercode).first()
+    #    if player:
+    #        player_id = player.id
+    #        match_group = player.match_group
 
     records_set = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date")
     data = list(records_set.values())
@@ -493,19 +569,34 @@ def add_model(cls,**kwargs):
 
     if model_name == "PlayerRecord":
         now = datetime.datetime.now()
-        if now.weekday() in [5,6] or now.strftime("%Y-%m-%d") in MISS_DATES:
+        match_id = kwargs.get("match_id")
+        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 now_time<"15:00" or now_time > "23:50":
+            raise ce.TipException(u"当日数据请在当日15:00以后23:50以前提交数据!")
+
         match_id = kwargs.get("match_id")
         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"))
         player_id = kwargs.get("player_id")
         today_fund = float(kwargs.get("today_fund",0))
         is_markt = int(kwargs.get("is_markt",0))
+        experience = kwargs.get("experience")
+
+        #计算今日和昨日盈亏
+        if float(today_fund)>9999 or float(today_fund)<=0:                              
+            raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")                                                                                                                                                                       
 
         player = cm.Player.objects.filter(id=player_id).first()
-        if player.fund <= 0:
-            raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
+
+        #if player.fund <= 0:
+        #    raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
+
         user_id = player.user_id
         init_fund = player.fund
         user = cm.UserInfo.objects.filter(id=user_id).first()
@@ -522,22 +613,35 @@ def add_model(cls,**kwargs):
             raise ce.TipException(u"该账号已暂停/退出比赛,如有疑问请联系管理员获取详情信息!")
         now_date = datetime.datetime.now().strftime("%Y-%m-%d")
         if match.end_time < now_date:
-            raise ce.TipException(u"该比赛已结束!")
-        cm.PlayerRecord.objects.filter(match_id=match_id,player_id=player_id,stock_date=stock_date).delete()
+            raise ce.TipException(u"该比赛已结束或您未参加此次比赛不能提交数据!")
 
+        #cm.PlayerRecord.objects.filter(match_id=match_id,player_id=player_id,stock_date=stock_date).delete()
         #yesterday_date = (datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
+        #yesterday = cm.PlayerRecord.objects.filter(
+        #                match_id=match_id,player_id=player_id).exclude(stock_date=stock_date).order_by("-stock_date").first()
+
+        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.objects.filter(
-                        match_id=match_id,player_id=player_id).order_by("-stock_date").first()
+                        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 = init_fund 
+            #yesterday_fund = init_fund  #today_fund 
+            yesterday_fund = today_fund 
             yesterday_stock = ""
             yesterday_stock_img = "" 
             yesterday_is_markt = 0
+            if not cm.PlayerRecord.objects.filter(match_id=match_id,player_id=player_id).exists():
+                init_fund = today_fund
+                cm.Player.objects.filter(id=player_id).update(fund=today_fund)
+
         with transaction.atomic():
             #记录持股情况
             new_stock_list = []
@@ -551,6 +655,7 @@ def add_model(cls,**kwargs):
                     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
@@ -578,6 +683,7 @@ def add_model(cls,**kwargs):
             obj.cw = cw
             obj.df = df
             obj.badge = badge
+            obj.experience = experience
             #计算今日和昨日盈亏
             if float(today_fund)>9999 or float(today_fund)<=0:                              
                 raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")                                                                                                                                                                       
@@ -585,10 +691,15 @@ def add_model(cls,**kwargs):
             total_income = (today_fund - init_fund)/float(init_fund)
 
             if float(today_income)>0.4:                                                    
-                raise ce.TipException(u"今日盈利已超过40%,请仔细核对数据或直接联系副主编!")
+                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)
+            #obj.today_income = 0
+            #obj.total_income = 0
             if not flag:
                 obj.ctime = datetime.datetime.now()
             obj.save()
@@ -643,6 +754,7 @@ def get_search_list(cls,**kwargs):
     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"]:
@@ -743,22 +855,33 @@ def get_list_info(cls,**kwargs):
 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"请先输入您的初始资金后再提交数据!")
+    #if player.fund <=0 :
+    #    raise ce.TipException(u"请先输入您的初始资金后再提交数据!")
     player_id = player.id
     user_id = player.user_id
     init_fund = player.fund
@@ -783,9 +906,12 @@ def add_player_record_single(**kwargs):
         yesterday_stock = yesterday.today_stock
         yesterday_stock_img = yesterday.today_stock_img
     else:
-        yesterday_fund = init_fund 
+        #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 = []
@@ -799,6 +925,7 @@ def add_player_record_single(**kwargs):
             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
@@ -824,8 +951,8 @@ def add_player_record_single(**kwargs):
     #计算今日和昨日盈亏
     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_fund)>9999 or int(today_fund)<0:                              
+    #    raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!") 
     if int(today_income)>2:                                                    
         raise ce.TipException(u"数据错误,今日盈利已超过2倍,请仔细核对数据!")
 
@@ -900,38 +1027,64 @@ def get_user_follows(request):
     """获取用户关注的选手列表
     """
     user_id = request.player.id
-    print user_id
     match_id = request.player.match_id
+    cur_match_id = match_id
     match_group = request.player.match_group
+    cur_match_group = match_group
     qdata = request.json
     today = get_today_date()
-    print today
 
     data = []
 
     qset = cm.UserFollows.objects.filter(user_id=user_id)
     follow_ids = list(qset.values_list("follow_id",flat=True))
 
+    _today = today
     for player_id in follow_ids:
-        last = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=match_id).order_by("-stock_date").first()
-        if last:
-            today = last.stock_date
+        _match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
+
+        #last = cm.PlayerRecord.objects.filter(player_id=player_id,match_id=_match_id).order_by("-stock_date").first()
+        #if last:
+        #    _today = last.stock_date
+
+        _today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
+        _match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
+
+        today_record = get_today_record(player_id,_match_id,_match_group,_today)
+        #today_record = get_today_record_actual(player_id,_match_id,_match_group,_today)
+        if today_record:
+            data.append(today_record)
+
+    data = sorted(data,key=lambda x:x["stock_date"],reverse=True)
+
+
+    _match_id = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"match_id")
+    _today = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"stock_date")
+    _match_group = ccc.cache.hget("PLAYER_LATEST_%d"%user_id,"match_group")
+
+    cur_today_record = get_today_record(user_id,_match_id,_match_group,_today)
+    if cur_today_record:
+        data.insert(0,cur_today_record)
 
-            today_record = get_today_record(player_id,match_id,last.match_group,today)
-            if today_record:
-                data.append(today_record)
-    data = sorted(data,key=lambda x:x["group_rank"])
     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:
-            item["today_stock"] = json.loads(item["today_stock"])
-            item["today_stock_img"] = json.loads(item["today_stock_img"])
-            item["win_rate"] = calc_win_rate(item["player_id"],item["match_id"])
-            item["today_income"] = "{}%".format(item["today_income"]*100)
-            item["total_income"] = "{}%".format(item["total_income"]*100)
+            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"])
+                #item["win_rate"] = calc_win_rate(item["player_id"],item["match_id"])
+                win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%item["player_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)
         return total,data
     else:
         return len(data),data
@@ -950,27 +1103,32 @@ def get_hot_stock_rank(**kwargs):
         }
     return data
 
+@ccc.cache_data()
+def get_stock_info(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")
     qset = cm.UserStock.objects.filter(stock_date=stock_date)
-    qset = qset.values("stock_id").annotate(count=Count("stock_id")).order_by("-count")
+    if kwargs.get("name"):
+        qset = qset.filter(stock_name__icontains=kwargs.get("name"))
+    qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id")).order_by("-count")
     data = []
     for q in qset:
         stock_id = q["stock_id"]
         count = q["count"]
-        data.append(
-            {
-                "stock_name":cm.Stock.objects.filter(id=stock_id).first().name,
-                "count":count,
-                "id":stock_id
-            } 
-        )
+        stock_name = q.get("stock_name")
+        #stock = get_stock_info(stock_id)
+        data.append({"stock_name":stock_name,"id":stock_id,"count":count})
 
-    if kwargs.get("name"):
-        data = filter(lambda x:kwargs.get("name") in x["stock_name"],data)
 
     page = int(kwargs.get("page",1))
     page_size = int(kwargs.get("page_size",20))
@@ -988,33 +1146,44 @@ def get_hot_follow(**kwargs):
     """
     stock_date = kwargs.get("stock_date")
     #qset = cm.UserFollows.objects.filter(stock_date=stock_date)
-    qset = cm.UserFollows.objects.all()
+    cur_match_id = 9
+    player_ids = list(cm.Player.objects.filter(match_id=cur_match_id,match_status=1).values_list("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"]
-        player = cm.Player.objects.filter(id=player_id).first()
-        today = cm.PlayerRecord.objects.filter(player_id=player_id).order_by("-stock_date").first().stock_date
-        badest_income = cm.PlayerRecord.objects.filter(player_id=player_id).order_by("-today_income").first().today_income
-        today_record = get_today_record(player_id,int(player.match_id),int(player.match_group),today)
-        userinfo = get_user_info(today_record["user_id"])
-
-        data.append(
-            {
-                "player_name":player.username,
-                "count":count,
-                "id":player_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),
-                "style":userinfo.get("style"),
-                "badge":userinfo.get("badge"),
-                "match_id":player.match_id,
-                "win_rate":calc_win_rate(player_id,player.match_id)
-            } 
-        )
+
+        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"])
+
+            win_rate = ccc.cache.hget("PLAYER_LATEST_%d"%today_record["player_id"],"win_rate")
+            win_rate = str(float(win_rate)*100)+"%"
+            if userinfo:
+                data.append(
+                    {
+                        "player_name":userinfo.get("username"),
+                        "count":count,
+                        "id":player_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),
+                        "style":userinfo.get("style"),
+                        "badge":userinfo.get("badge"),
+                        "match_id":match_id,
+                        "win_rate":win_rate
+                        #"win_rate":calc_win_rate(player_id,match_id)
+                    } 
+                )
 
     if kwargs.get("name"):
         data = filter(lambda x:kwargs.get("name") in x["player_name"],data)
@@ -1047,7 +1216,10 @@ def get_hot_stock_sell(**kwargs):
     #    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).order_by("-count")
+    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:
@@ -1098,7 +1270,7 @@ def get_hot_stock_sell_players(**kwargs):
                 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))
 
@@ -1117,10 +1289,18 @@ def get_win_rate_rank(request):
     match_id = request.player.match_id
     match_group = request.player.match_group
     kwargs = request.json
+    match_id = 9
 
-    qset = cm.WinDefendRank.objects.filter(match_id=match_id).order_by("-win_rate")
+    qset = cm.WinDefendRank.objects.filter(match_id=match_id,auto_complete__lt=5,match_status=1).order_by("-win_rate")
     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))
 
@@ -1133,8 +1313,10 @@ def get_win_rate_rank(request):
         item["badest_income"] = "{}%".format(item["badest_income"]*100)
         item["total_income"] = "{}%".format(item["total_income"]*100)
         userinfo = get_user_info(item["user_id"])
-        item["badge"] = userinfo.get("badge")
-        item["style"] = userinfo.get("style")
+        if userinfo:
+            item["badge"] = userinfo.get("badge")
+            item["style"] = userinfo.get("style")
+            item["username"] = userinfo.get("username")
 
 
     return total,data
@@ -1148,9 +1330,16 @@ def get_defend_rank(request):
     match_group = request.player.match_group
     kwargs = request.json
 
-    qset = cm.WinDefendRank.objects.filter(match_id=match_id).order_by("-badest_income")
+    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))
 
@@ -1162,14 +1351,12 @@ def get_defend_rank(request):
         item["win_rate"] = "{}%".format(item["win_rate"]*100)
         item["badest_income"] = "{}%".format(item["badest_income"]*100)
         item["total_income"] = "{}%".format(item["total_income"]*100)
-        item["style"] = []
-        if item["zq"]:
-            item["style"].apepnd(item["zq"])
-        if item["cw"]:
-            item["style"].apepnd(item["cw"])
-        if item["df"]:
-            item["style"].apepnd(item["df"])
-        item["badge"] = cm.Player.objects.filter(id=item["player_id"]).first().badge
+
+        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
 
@@ -1178,7 +1365,7 @@ def get_champion_articles_list(request):
     """
     """
     kwargs = request.json
-    qset = cm.Article.objects.filter(status=2,type="champion")
+    qset = cm.Article.objects.filter(status=2,type="champion").order_by("-id")
 
     page = int(kwargs.get("page",0))
     page_size = int(kwargs.get("page_size",20))
@@ -1197,7 +1384,6 @@ def get_wanzhu_comment(**kwargs):
     """
     match_id = kwargs.get("match_id")
     group_id = kwargs.get("group_id")
-    print match_id
     today = get_today_date()
     players = get_match_group_players(match_id,group_id)
     new_players = []
@@ -1259,7 +1445,10 @@ def get_enum_list(request):
             u"核按钮"
         ], 
         "pz":[
-            u"N/C字头新股", 
+            u"10厘米",
+            u"20厘米",
+            u"30厘米",
+            u"N/C新股", 
             u"次新股", 
             u"可转债", 
             u"港股", 
@@ -1286,6 +1475,10 @@ def get_player_list(**kwargs):
         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")
@@ -1294,6 +1487,9 @@ def get_player_list(**kwargs):
         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["zq"],data)
@@ -1328,7 +1524,7 @@ def get_mine_style(request):
     }
     if player:
         data["is_player"] = 1
-        data["init_fund"] = player.fund
+        data["init_fund"] = player.fund if player.fund else 0
     else:
         data["is_player"] = 0
         data["init_fund"] = None
@@ -1370,7 +1566,7 @@ def get_stock_players(**kwargs):
                 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",1))
     page_size = int(kwargs.get("page_size",20))
@@ -1430,3 +1626,77 @@ def get_player_match_calendar(**kwargs):
     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")
+    data = list(qset.values())
+    return data
+
+
+def get_default_date(**kwargs):
+    """
+    """
+    match_id = kwargs.get("match_id")
+    record = cm.PlayerRecord.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):
+    """
+    """
+    player_id = request.player.id
+    match_id = request.player.match_id
+    match_group = request.player.match_group
+
+    today = get_today_date()
+
+    _match_id = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_id")
+    if _match_id:
+        match_id = _match_id
+    _today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
+    if _today:
+        today = _today
+    _match_group = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"match_group")
+    if _match_group:
+        match_group = _match_group
+
+    #rst = get_today_record(player_id,match_id,match_group,today)
+    try:
+        rst = get_today_record_actual(player_id,match_id,match_group)
+
+        rst["today_income"] = "{}%".format(rst["today_income"]*100)
+        rst["total_income"] = "{}%".format(rst["total_income"]*100)
+
+        return rst
+    except:
+        return {}
+
+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 []

+ 4 - 0
src/weixin/urls_backstage.py

@@ -44,6 +44,10 @@ urlpatterns = [
     url(r'^v2/notices/list$', views.NoticesListView.as_view()),
     url(r'^v2/default/date$', views.DefaultDateView.as_view()),
     url(r'^v2/player/match/calendar$', views.PlayerMatchCalendarView.as_view()),
+    url(r'^v2/match/list$', views.MatchListView.as_view()),
+    url(r'^v3/user/follow$', views.FollowUserView.as_view()),
+    url(r'^v2/mine/latest$', views.MineLatestView.as_view()),
+    url(r'^v2/match/validdates$', views.MatchValidDatesView.as_view()),
 
 ]
 

+ 61 - 11
src/weixin/views.py

@@ -15,6 +15,7 @@ import common.common_functions as ccf
 import weixin.control_auth as ca
 import weixin.controls as ctl
 import weixin.wzhifuSDK as wzf
+from utils.upload_to_oss import hnoss
 
 
 class OpenidView(cv.BaseView):
@@ -31,6 +32,7 @@ class OpenidView(cv.BaseView):
             get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code' .format(wzf.WxPayConf_pub.APPID,wzf.WxPayConf_pub.APPSECRET,code)
 
             res = requests.get(get_token_url).json()                                   
+            print res
             if res.has_key('openid'):                                                 
                 open_id = res['openid']                                               
                 cache.set(code,open_id,24*3600)
@@ -50,13 +52,17 @@ class UploadFileView(cv.BaseView):
         """
         import time
         upload_file = request.FILES['file']
-        dest = settings.STATIC_ROOT + "/upload/"+str(int(time.time())) + upload_file.name
-        with open(dest,"wb+") as f:
-            for chunk in upload_file.chunks():
-                f.write(chunk)
-        f.close()
-        url = dest.replace(settings.STATIC_ROOT,settings.HOST)
-        print url
+        ts = str(int(time.time()))
+        dest = settings.STATIC_ROOT + "/upload/"+ ts + upload_file.name
+
+        #with open(dest,"wb+") as f:
+        #    for chunk in upload_file.chunks():
+        #        f.write(chunk)
+        #f.close()
+        #url = dest.replace(settings.STATIC_ROOT,settings.HOST)
+        content = upload_file.read()
+        ossfile = ts + upload_file.name
+        url = hnoss.upload_from_str(content,ossfile)
         return cv.to_suc({"url":url})
 
 
@@ -237,6 +243,10 @@ class StockSearchView(cv.AuthView):
         try:
             qdata = request.json
             rst = ctl.get_search_list(self,**qdata)
+            #rst = ctl.get_stock_search(**qdata)
+            #if qdata.get("name"):
+            #    rst = filter(lambda x:qdata.get("name") in x["name"],rst)
+            #print(rst)
             return cv.to_suc(rst)
         except Exception as e:
             cv.tracefail()
@@ -408,7 +418,7 @@ class HotFollowListView(cv.AuthView):
         if mse:                                                                    
             raise ce.TipException(mse)                                             
         try:                                                                       
-            need_params.extend(["name"])
+            need_params.extend(["name","page","page_size"])
             vals = ccf.get_need_params(*need_params,**qdata)                       
             total,rst = ctl.get_hot_follow(**vals)                                 
             return cv.to_suc({"total":total,"list":rst})
@@ -451,6 +461,7 @@ class HotStockSellListView(cv.AuthView):
         if mse:                                                                    
             raise ce.TipException(mse)                                             
         try:                                                                       
+            need_params.extend(["name"])
             vals = ccf.get_need_params(*need_params,**qdata)                       
             total,rst = ctl.get_hot_stock_sell(**vals)                                 
             return cv.to_suc({"total":total,"list":rst})
@@ -603,12 +614,12 @@ class MineStyleView(cv.AuthView):
         @account_img:"",账号截图
         """
         qdata = request.json                                                       
-        need_params = ["zq","cw","df","pz","join_time","account_img"]                                                       
+        need_params = ["zq","cw","df","pz","join_time"]                                                       
         mse = ccf.check_params(*need_params,**qdata)                               
         if mse:                                                                    
             raise ce.TipException(mse)                                             
         try:                                                                       
-            need_params.extend(["init_fund"])
+            need_params.extend(["init_fund","account_img"])
             vals = ccf.get_need_params(*need_params,**qdata)                       
             vals["user_id"] = request.user.id
             vals["player_id"] = request.player.id if request.player else None
@@ -672,7 +683,8 @@ class DefaultDateView(cv.AuthView):
         @id:1
         """
         try:
-            rst = ctl.get_today_date()
+            qdata = request.json
+            rst = ctl.get_default_date(**qdata)
             return cv.to_suc(rst)
         except Exception as e:
             cv.tracefail()
@@ -711,3 +723,41 @@ class PlayerMatchCalendarView(cv.AuthView):
         except Exception as e:
             cv.tracefail()
             return cv.to_fail(e)
+
+
+class MatchListView(cv.AuthView):
+    def get(self, request):
+        """#获取所有赛事(2.0小程序)
+        """
+        try:
+            rst = ctl.get_all_match(request)
+            return cv.to_suc(rst)
+        except Exception as e:
+            cv.tracefail()
+            return cv.to_fail(e)
+
+
+class MineLatestView(cv.AuthView):                                                    
+    def get(self, request):                                                        
+        """#我的最新(2.0小程序)                                                       
+        """                                                                        
+        try:                                                                       
+            rst = ctl.get_mine_latest(request)                                 
+            return cv.to_suc(rst)
+        except Exception as e:                                                     
+            cv.tracefail()                                                         
+            return cv.to_fail(e)
+
+
+class MatchValidDatesView(cv.AuthView):                                                    
+    def get(self, request):                                                        
+        """#比赛时间(2.0小程序)                                                       
+        """                                                                        
+        try:                                                                       
+            qdata = request.json
+            match_id = qdata.get("match_id")
+            rst = ctl.get_match_validdates(match_id)                                 
+            return cv.to_suc(rst)
+        except Exception as e:                                                     
+            cv.tracefail()                                                         
+            return cv.to_fail(e)

+ 2 - 2
src/weixin/wzhifuSDK.py

@@ -55,9 +55,9 @@ class WxPayConf_pub(object):
 
     ##=======【基本信息设置】=====================================
     #微信公众号身份的唯一标识。审核通过后,在微信发送的邮件中查看
-    APPID = "wxefb72c1e5fb5add2"
+    APPID = "wxb299e10e65157301"
     #JSAPI接口中获取openid,审核后在公众平台开启开发模式后可查看
-    APPSECRET = "a5992b99de94131d738a1ce9da9beb42"
+    APPSECRET = "20e278a60d52ad63822a07e49931435c"
     #受理商ID,身份标识
     MCHID = ""
     #商户支付密钥Key。审核通过后,在微信发送的邮件中查看

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1 - 1
templates/index.html