xjconline 2 jaren geleden
bovenliggende
commit
55e149388f

+ 4 - 4
src/common/common_control.py

@@ -201,10 +201,10 @@ def get_today_record(user_id,match_id,match_group,today):
     today_record = 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=user_id,match_id=match_id,stock_date=today)
-        today_record = today_record.values().first()
+    #if match_id and not match_id==get_cur_match().id and not today_record:
+    #    #记得这里上线后要注释掉
+    #    today_record = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id,stock_date=today)
+    #    today_record = today_record.values().first()
 
     try:
         if today_record:

+ 28 - 27
src/common/models.py

@@ -117,8 +117,8 @@ class PlayerRecord(models.Model):
     #    verbose_name = u"参数选手"
     #    app_label = "common"
 
-    def __str__(self):
-        return u"{}){}".format(self.id, self.username)
+    #def __str__(self):
+    #    return u"{}){}".format(self.id, self.username)
 
     @classmethod
     def get_db_model(cls,match_id):
@@ -304,7 +304,8 @@ class test(models.Model):
 class UserFollows(models.Model):
     """用户关注表
     """
-    user_id = models.IntegerField(u"选手id", blank=True,null=True)
+    player_id = models.IntegerField(u"选手id", blank=True,null=True)
+    user_id = models.IntegerField(u"用户id", blank=True,null=True)
     follow_id = models.IntegerField(u"被关注选手id", blank=True,null=True)
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
@@ -537,31 +538,31 @@ class UserMatch(models.Model):
         return u"{}){}".format(self.id, self.signup_name)
 
 
-class PlayerRecordBase(models.Model):
-    """参数选手数据
-    """
-    user_id = models.IntegerField(u"用户id", blank=True,null=True)
-    player_id = models.IntegerField(u"用户id", blank=True,null=True)
-
-    @classmethod
-    def get_db_model(cls,match_id):
-        table_name = "player_record_%s" % match_id
-        if table_name in cls._db_model_dict:
-            return cls._db_model_dict[table_name]
-        class Meta:
-            db_table = table_name
-
-        attrs = {
-            "__module__":cls.__module__,     
-            "Meta":Meta
-        }
-        db_model = type(table_name,(cls,),attrs)
-        cls._db_model_dict[table_name] = db_model
-        return db_model
-    _db_model_dict = {}
+#class PlayerRecordBase(models.Model):
+#    """参数选手数据
+#    """
+#    user_id = models.IntegerField(u"用户id", blank=True,null=True)
+#    player_id = models.IntegerField(u"用户id", blank=True,null=True)
+#
+#    @classmethod
+#    def get_db_model(cls,match_id):
+#        table_name = "player_record_%s" % match_id
+#        if table_name in cls._db_model_dict:
+#            return cls._db_model_dict[table_name]
+#        class Meta:
+#            db_table = table_name
+#
+#        attrs = {
+#            "__module__":cls.__module__,     
+#            "Meta":Meta
+#        }
+#        db_model = type(table_name,(cls,),attrs)
+#        cls._db_model_dict[table_name] = db_model
+#        return db_model
+#    _db_model_dict = {}
     
-    class Meta:
-        abstract = True
+#    class Meta:
+#        abstract = True
 
 
 

+ 61 - 23
src/manage/controls.py

@@ -149,8 +149,8 @@ def add_model(cls,**kwargs):
         obj.is_markt = is_markt
         obj.yesterday_is_markt = yesterday_is_markt
         #计算今日和昨日盈亏
-        today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
-        total_income = (today_fund - init_fund)/float(init_fund)
+        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
         obj.today_income = round(today_income,4)
         obj.total_income = round(total_income,4)
         if not flag:
@@ -221,6 +221,7 @@ def update_model(cls,**kwargs):
 
     if model_name == "PlayerRecord":
         match_id = kwargs.get("match_id")
+        user_id = kwargs.get("user_id")
         obj = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=id).first()
         today_fund = obj.today_fund
         yesterday_fund = obj.yesterday_fund
@@ -230,7 +231,7 @@ def update_model(cls,**kwargs):
         obj.today_income = round(today_income,4)
         obj.total_income = round(total_income,4)
         #
-        player = cm.Player.objects.filter(id=obj.player_id).first()
+        player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
         if player:
             obj.match_group = player.match_group
             obj.username = player.username
@@ -238,7 +239,7 @@ def update_model(cls,**kwargs):
         obj.save()
 
         #更新player的init_fund
-        player_id = obj.player_id
+        player_id = player.id
         cm.Player.objects.filter(id=player_id).update(fund=init_fund)
 
         ##更新group_rank
@@ -290,14 +291,13 @@ def get_search_list(cls,**kwargs):
     model = getattr(cm,model_name)
     qset = model.objects.all().order_by("-id")
     if model_name == "Player":
-        data = list(qset.values("id","user_id","username","usercode"))
-        for item in data:
-            #user = cm.UserInfo.objects.filter(id=item["user_id"]).first()
-            #if user:
-            #    item["username"] = user.username
-            #    item["usercode"] = user.usercode
-            #    item["label"] = "%s(%s)" % (item["username"],item["usercode"])
-            item["label"] = "%s(%s)" % (item["username"],item["usercode"])
+        if kwargs.get("usercode"):
+            qset = qset.filter(usercode__icontains=kwargs.get("usercode"))
+            data = list(qset.values("id","user_id","username","usercode"))
+            for item in data:
+                item["label"] = "%s(%s)" % (item["username"],item["usercode"])
+        else:
+            data = []
     elif model_name == "Stock":
         data = list(qset.values("id","name","code"))
         for item in data:
@@ -401,6 +401,7 @@ def get_list_info(cls,**kwargs):
         if kwargs.get("match_id"):
             qset = qset.filter(match_id=kwargs.get("match_id"))
         if kwargs.get("username"):
+            #qset = qset.filter(Q(user_name__icontains=kwargs.get("username"))|Q(phone__icontains=kwargs.get("username"))|Q(transaction_id__icontains=kwargs.get("username")))
             qset = qset.filter(Q(user_name__icontains=kwargs.get("username"))|Q(phone__icontains=kwargs.get("username")))
         if kwargs.get("signup_type"):
             qset = qset.filter(signup_type=kwargs.get("signup_type"))
@@ -444,8 +445,8 @@ def get_list_info(cls,**kwargs):
             for item in data:
                 user = cm.UserInfo.objects.filter(id=item["user_id"]).first()
 
-                item["username"] = user.username
-                item["usercode"] = user.usercode
+                item["username"] = user.username if user else ""
+                item["usercode"] = user.usercode if user else ""
 
                 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 [])
@@ -459,9 +460,10 @@ def get_list_info(cls,**kwargs):
 
                 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)
+                if item["today_income"]:
+                    item["today_income"] = "{}%".format(item["today_income"]*100)
+                if item["total_income"]:
+                    item["total_income"] = "{}%".format(item["total_income"]*100)
                 item["is_markt"] = bool(item["is_markt"]) 
                 #资金出入
                 if cm.FundInOut.objects.filter(user_id=item["user_id"],stock_date=item["stock_date"]).exists():
@@ -644,6 +646,10 @@ def update_group_rank(stock_date=None,match_id=None,group_id=None):
     else:
         stock_date = datetime.datetime.now().strftime("%Y-%m-%d")
 
+    del_keys = ccc.cache.keys("*_%s_%s_%s" % (match_id,group_id,stock_date))
+    if del_keys:
+        ccc.cache.delete(*del_keys)
+
     groups = cm.MatchGroup.objects.filter(id=group_id)
     for gp in groups:
         match_id = gp.match_id
@@ -666,11 +672,13 @@ def update_group_rank(stock_date=None,match_id=None,group_id=None):
             ccc.pl.execute()
 
             winset = cm.PlayerRecord.get_db_model(match_id).objects.filter(
-                match_id=match_id,match_group=match_group,today_income__gte=0)\
+                match_id=match_id,match_group=match_group)\
                 .values("user_id").annotate(wincnt=Count("user_id")).values("user_id","match_id","match_group","wincnt")
+
             totalset = cm.PlayerRecord.get_db_model(match_id).objects.filter(
                 match_id=match_id,match_group=match_group)\
                 .values("user_id").annotate(totalcnt=Count("user_id")).values("user_id","totalcnt")
+
             totallist = list(totalset)
             for item in winset:
                 item["stock_date"] = stock_date
@@ -681,13 +689,17 @@ def update_group_rank(stock_date=None,match_id=None,group_id=None):
                 else:
                     item.update({"totalcnt":0})
 
-                #更新最后一次数据
-                update_player_latest(item)
+                if total:
+                    #更新最后一次数据
+                    update_player_latest(item)
+
+
+
 
             if cases and where:
                 case = case_id + " ".join(cases)
                 where = ",".join(where)
-                sql = "update player_record set group_rank = %s ELSE 0 END where id in (%s)" % (case,where)
+                sql = "update player_record_%s set group_rank = %s ELSE 0 END where id in (%s)" % (match_id,case,where)
                 cursor = connection.cursor()
                 cursor.execute(sql)
                 cursor.close()
@@ -700,8 +712,9 @@ def update_comment(**kwargs):
     """
     """
     id = kwargs.get("id")
+    match_id = kwargs.get("match_id")
     wanzhu_comment = kwargs.get("wanzhu_comment")
-    cm.PlayerRecord.objects.filter(id=id).update(wanzhu_comment=wanzhu_comment)
+    cm.PlayerRecord.get_db_model(match_id).objects.filter(id=id).update(wanzhu_comment=wanzhu_comment)
 
 
 def reset_initfund(**kwargs):
@@ -733,12 +746,13 @@ def get_stock_comments_list(**kwargs):
 def get_record_comments_list(**kwargs):
     """
     """
+    match_id = kwargs.get("match_id")
     qset = cm.Comments.objects.filter(record_id__isnull=False).order_by(*["-istop","-id"])
     if kwargs.get("user_name"):
         qset = qset.filter(user_name__icontains=kwargs.get("name"))
     data = list(qset.values())
     for item in data:
-        item["record_info"] = cm.PlayerRecord.objects.filter(id=item["record_id"]).values().first()
+        item["record_info"] = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=item["record_id"]).values().first()
     #分页
     page = int(kwargs.get("page",1))
     page_size = int(kwargs.get("page_size",20))
@@ -930,3 +944,27 @@ def delete_consult(**kwargs):
     user_id = kwargs.get("id")
     cm.Consult.objects.filter(user_id=user_id).delete()
     cm.WanzhuConsult.objects.filter(Q(user_id=user_id)|Q(reply_user_id=user_id)).delete()
+
+
+def batch_update_player_latest(record):
+    """更新选手最后一次数据
+    """
+    user_id = record["user_id"]
+    match_id = record["match_id"]
+    stock_date = record["stock_date"]
+    match_group = record["match_group"]
+    #wincnt = record["wincnt"]
+    #total = record["totalcnt"]
+
+    key = "PLAYER_LATEST_{}".format(user_id)
+    if record and match_group:
+        ccc.cache.hset(key,"stock_date",stock_date)
+        ccc.cache.hset(key,"match_id",match_id)
+        ccc.cache.hset(key,"match_group",match_group)
+
+        ##更新胜率
+        #qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_id)
+        ##win_rate = qset.filter(today_income__gte=0).count()/float(qset.count()) if qset else 0.0
+        #win_rate = wincnt/float(total) if total else 0.0
+        #win_rate = round(win_rate,3)
+        #ccc.cache.hset(key,"win_rate",win_rate)

+ 2 - 2
src/manage/views.py

@@ -491,7 +491,7 @@ class PlayerRecordView(cv.AdminView):
         @name:"分组名称"
         """
         qdata = request.json
-        need_params = ["id","player_id","match_id","today_fund"]
+        need_params = ["id","user_id","match_id","today_fund"]
         mse = ccf.check_params(*need_params,**qdata)
         if mse:
             raise ce.TipException(mse)
@@ -859,7 +859,7 @@ class PlayerRecordCommentView(cv.AdminView):
         @wanzhu_comment:"顽主点评"
         """
         qdata = request.json
-        need_params = ["id","wanzhu_comment"]
+        need_params = ["id","wanzhu_comment","match_id"]
         mse = ccf.check_params(*need_params,**qdata)
         if mse:
             raise ce.TipException(mse)

+ 1 - 1
src/settings/__init__.py

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

+ 1 - 1
src/settings/base.py

@@ -56,7 +56,7 @@ MIDDLEWARE = [
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
-    'oplog.OpLogMiddleware.OpLogMiddleware'
+    #'oplog.OpLogMiddleware.OpLogMiddleware'
 ]
 
 ROOT_URLCONF = 'urls'

+ 65 - 0
src/tools/batch_build_cache.py

@@ -0,0 +1,65 @@
+#coding:utf-8
+import os
+import time
+import datetime
+import sys
+import django
+from django.core.cache import cache
+from django.db import connection
+from django.db.models import Count
+
+sys.path.append('/mnt/wzbapi/src')
+os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
+django.setup()
+
+import common.models as cm
+import common.common_control as ccc
+import common.common_functions as ccf
+import manage.controls as mc
+
+
+def build_cache():
+    for match_id in [7,8,9,10,11,12,13]:
+    #for match_id in [13]:
+
+        qset = cm.PlayerRecord.get_db_model(match_id).objects.all()
+        qset = qset.values("stock_date").annotate(count=Count("stock_date")).order_by("stock_date")
+        for item in qset:
+            stock_date = item["stock_date"]
+            print(stock_date)
+
+            qqset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=stock_date)
+            qqset = qqset.values("match_id","match_group").annotate(count=Count("match_group"))
+            for iitem in qqset:
+                match_id = iitem["match_id"]
+                match_group = iitem["match_group"]
+                print(iitem)
+                if match_id and match_group:
+                    mc.update_group_rank(stock_date,match_id,match_group)
+            #break
+
+def update_latest():
+    for match_id in [7,8,9,10,11,12,13]:
+        qset = cm.PlayerRecord.get_db_model(match_id).objects.all()
+        qset = qset.values("stock_date").annotate(count=Count("stock_date")).order_by("stock_date")
+        for item in qset:
+            stock_date = item["stock_date"]
+            print(stock_date)
+
+            qqset = cm.PlayerRecord.get_db_model(match_id).objects.filter(stock_date=stock_date).values()
+            for iitem in qqset:
+                mc.batch_update_player_latest(iitem)
+
+
+
+if __name__ == "__main__":
+    print "start build cache..."
+    st = time.time()
+    #build_cache()
+    update_latest()
+    print "time cost:",time.time()-st
+
+
+
+
+

+ 16 - 1
src/tools/player_to_usermatch.py

@@ -37,10 +37,25 @@ def player_to_usermatch():
         obj.match_status = match_status
         obj.save()
 
+
+def user_follow():
+    """选手转用户赛事关联
+    """
+    players = cm.UserFollows.objects.all()
+    for item in players:
+        player_id = item.user_id
+        player = cm.Player.objects.filter(id=player_id).first()
+        if player:
+            user_id = player.user_id
+
+            item.user_id = user_id
+            item.save()
+
 if __name__ == "__main__":
     print "start update group rank..."
     st = time.time()
-    player_to_usermatch()
+    #player_to_usermatch()
+    user_follow()
     print "time cost:",time.time()-st
 
 

+ 10 - 8
src/tools/rank_server.py

@@ -20,8 +20,10 @@ def rank_server():
     """
     rcid = ccc.cache.rpop(settings.RANK_LIST)
     if rcid:
+        match_id = rcid.split("_")[0]
+        rcid = rcid.split("_")[1]
         django.db.close_old_connections()
-        record = cm.PlayerRecord.objects.filter(id=rcid).first()
+        record = cm.PlayerRecord.get_db_model(match_id).objects.filter(id=rcid).first()
         if record:
             match_id = int(record.match_id)
             match_group = int(record.match_group)
@@ -58,7 +60,7 @@ def update_win_defend_rank(record):
     player = cm.Player.objects.filter(id=player_id).first()
     if player:
         #胜率
-        qset = cm.PlayerRecord.objects.filter(match_id=match_id,player_id=player_id)
+        qset = cm.PlayerRecord.get_db_model(match_id).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)
         #最大回撤
@@ -89,10 +91,10 @@ def update_cache_rank(match_id,match_group,stock_date):
     """更新redis排名数据
     """
     print "update cache rank..."
-    prset = cm.PlayerRecord.objects.filter(match_id=match_id,match_group=match_group,stock_date=stock_date).order_by("-total_income")
+    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()
     for index,pr in enumerate(records):
-        key = "%s_%s_%s" % (pr["user_id"],match_id,stock_date)
+        key = "%s_%s_%s_%s" % (pr["user_id"],match_id,match_group,stock_date)
         pr.update({"group_rank":index+1})
         ccc.pl.set(key,json.dumps(pr,cls=ccc.CusJSONEncoder))
     ccc.pl.execute()
@@ -101,7 +103,7 @@ def sync_group_rank(match_id,match_group,stock_date):
     """更新数据库排名数据
     """
     print "sync group rank..."
-    prset = cm.PlayerRecord.objects.filter(match_id=match_id,match_group=match_group,stock_date=stock_date).order_by("-total_income")
+    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 = []
@@ -111,7 +113,7 @@ def sync_group_rank(match_id,match_group,stock_date):
         cases.append(case)
         where.append(str(pr["id"]))
         #
-        key = "%s_%s_%s" % (pr["user_id"],match_id,stock_date)
+        key = "%s_%s_%s_%s" % (pr["user_id"],match_id,match_group,stock_date)
         pr.update({"group_rank":index+1})
         ccc.pl.set(key,json.dumps(pr,cls=ccc.CusJSONEncoder))
     ccc.pl.execute()
@@ -119,7 +121,7 @@ def sync_group_rank(match_id,match_group,stock_date):
     if cases and where:
         case = case_id + " ".join(cases)
         where = ",".join(where)
-        sql = "update player_record set group_rank = %s ELSE 0 END where id in (%s)" % (case,where)
+        sql = "update player_record_%s set group_rank = %s ELSE 0 END where id in (%s)" % (match_id,case,where)
         cursor = connection.cursor()
         cursor.execute(sql)
         cursor.close()
@@ -138,7 +140,7 @@ def update_player_latest(record):
         ccc.cache.hset(key,"match_id",match_id)
         ccc.cache.hset(key,"match_group",match_group)
         #更新胜率
-        qset = cm.PlayerRecord.objects.filter(match_id=match_id,user_id=user_id)
+        qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,user_id=user_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)

+ 6 - 5
src/tools/split_table.py

@@ -6,7 +6,7 @@ import sys
 import django
 from django.core.cache import cache
 from django.db import connection
-import pymysql
+#import pymysql
 import torndb
 import json
 
@@ -63,10 +63,10 @@ def create_table(match_id):
     """ % (match_id,match_id)
 
     db = torndb.Connection(
-                '127.0.0.1:3306',
+                '172.29.110.52:3306',
                 'wanzb',
-                user='root',
-                password='xjc890*()',
+                user='wanzb',
+                password='wanzb890*()',
                 charset='utf8mb4')
     try:
         db.execute(sql)
@@ -205,7 +205,8 @@ def insert_data(record):
 def split_table():
     """
     """
-    qset = cm.Match.objects.filter(id=13)
+    qset = cm.Match.objects.filter(id=14)
+    #qset = cm.Match.objects.all()
     for obj in qset:
         match_id = obj.id
         create_table(match_id)

File diff suppressed because it is too large
+ 2506 - 0
src/weixin/2


+ 13 - 1
src/weixin/control_auth.py

@@ -1,7 +1,7 @@
 #coding=utf-8
 '''
 '''
-import json,time,random
+import json,time,random,datetime
 from django.db import transaction
 from django.db.models import Q
 import common.models as cm
@@ -44,6 +44,18 @@ def get_wxauth_info(request):
     user = request.user
     uid = user.get("id")
     user = cm.UserInfo.objects.filter(id=uid).values().first()
+
+    cur_match_id = ccc.get_signup_match().id
+    #player = cm.Player.objects.filter(user_id=uid,match_id=cur_match_id).order_by("-id").first()
+    gt_time = datetime.timedelta(days=-365)+datetime.datetime.now()
+    player = cm.Player.objects.filter(user_id=uid,match_status=1,ctime__gte=gt_time).order_by("-id").first()
+    #print(uid,cur_match_id)
+    if player:
+        user["role"] = player.role
+    else:
+        user["role"] = 0
+    if user["comment_status"]==0:
+        user["role"] = 0
     return user
 
 def update_wxauth_info(request):

+ 200 - 64
src/weixin/controls.py

@@ -205,8 +205,10 @@ def get_player_match_detail(request):
     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
-    if records_set:
-        records = list(records_set.values())
+
+    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 = []
 
@@ -239,7 +241,7 @@ def get_player_match_detail(request):
             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["today_stock_total"],4)
+            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")
 
@@ -287,10 +289,10 @@ def get_today_record(player_id,match_id,match_group,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()
+    #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:
@@ -335,11 +337,18 @@ def format_today_record(today_record):
             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 = 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()
@@ -355,8 +364,6 @@ def get_today_record_actual(player_id,match_id,match_group,today=None):
     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()
-    print(player_id,match_id,match_group,today,4444444444444444444)
-    print(today_record,1111111111)
 
     if today_record:
         user_info = get_user_info(today_record["user_id"])
@@ -384,9 +391,10 @@ def get_match_group_players(match_id,match_group):
     return players
 
 
-@ccc.cache_data()
+#@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.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()
@@ -409,7 +417,8 @@ def get_cache_rank_list(match_id,today):
         loss_count = 0
         for player in players:
             user_id = player["user_id"]
-            username = player["signup_name"]
+            #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)
@@ -477,6 +486,19 @@ def get_user_info(uid):
     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"])
+    return user
+
+
 #@ccc.cache_data()
 def get_player_info(player_id):
     player = cm.Player.objects.filter(id=player_id).values().first()
@@ -490,8 +512,11 @@ def get_match_info(match_id):
 @ccc.cache_data()
 def get_group_info(group_id):
     group = cm.MatchGroup.objects.filter(id=group_id).values().first()
-    group["players_num"] = cm.Player.objects.filter(match_group=group["id"]).count()
-    return group
+    if group:
+        group["players_num"] = cm.Player.objects.filter(match_group=group["id"]).count()
+        return group
+    else:
+        return {}
 
 
 def get_group_rank_list(request):
@@ -517,7 +542,8 @@ def get_group_rank_list(request):
         user_id = player["user_id"]
         #user = get_user_info(user_id) 
         #username = user["username"] if user else ""
-        username = player["signup_name"]
+        #username = player["signup_name"]
+        username = player["username"]
 
         match_group = group_id
         today_record = ccc.get_today_record(user_id,match_id,match_group,today)
@@ -613,8 +639,7 @@ def add_model(cls,**kwargs):
         stock_date = kwargs.get("stock_date")
 
         now = datetime.datetime.now()
-        print(user_id,match_id)
-        if not cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).exists():
+        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):
@@ -622,7 +647,7 @@ def add_model(cls,**kwargs):
 
         now_time = datetime.datetime.now().strftime("%H:%S")
 
-        if not user_id in [9600,6209,5709]:
+        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以前提交数据!")
 
@@ -641,7 +666,7 @@ def add_model(cls,**kwargs):
         if float(today_fund)>9999 or float(today_fund)<=0:                              
             raise ce.TipException(u"数据错误,今日净资产不能超过9999万元,不能低于0万元,请仔细核对数据!")                                                                                                                                                                       
 
-        player = cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).first()
+        player = cm.Player.objects.filter(user_id=user_id,match_id=match_id).first()
 
         user_id = player.user_id
         init_fund = player.fund
@@ -681,9 +706,14 @@ def add_model(cls,**kwargs):
             yesterday_stock = ""
             yesterday_stock_img = "" 
             yesterday_is_markt = 0
-            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.UserMatch.objects.filter(id=user_id,match_id=match_id).update(fund=today_fund)
+            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():
             #记录持股情况
@@ -700,6 +730,7 @@ def add_model(cls,**kwargs):
                             user_id = user_id, 
                             stock_id = stock_id,
                             stock_name = ts["name"],
+                            player_id = player.id,
                             stock_date = stock_date
                         )
                         ts["stock_id"] = stock_id
@@ -745,7 +776,7 @@ def add_model(cls,**kwargs):
                     today_income = (today_fund-(yesterday_fund+fundin))/(float(yesterday_fund) + fundin)
                     total_income = (today_fund-init_fund-fundin)/(init_fund+fundin)
 
-                    cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).update(fund=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
                     obj.yesterday_fund = obj.yesterday_fund + fundin
                 #出资金
@@ -754,7 +785,7 @@ def add_model(cls,**kwargs):
                     today_income = (today_fund-(yesterday_fund-fundout))/float(yesterday_fund)
                     total_income = (today_fund+fundout-init_fund)/init_fund
 
-                    cm.UserMatch.objects.filter(user_id=user_id,match_id=match_id).update(fund=round(today_fund/(1+total_income),4))
+                    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)
                     obj.yesterday_fund = round(today_fund/(1+today_income),4)
 
@@ -768,8 +799,8 @@ def add_model(cls,**kwargs):
                 obj.total_income = round(total_income,4)
 
             else:
-                today_income = (today_fund - yesterday_fund)/float(yesterday_fund)
-                total_income = (today_fund - init_fund)/float(init_fund)
+                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%,请仔细核对数据或直接联系顽主!")
@@ -785,7 +816,8 @@ def add_model(cls,**kwargs):
             obj.save()
 
             #更新group_rank
-            ccc.cache.lpush(settings.RANK_LIST,obj.id)
+            #ccc.cache.lpush(settings.RANK_LIST,obj.id)
+            ccc.cache.lpush(settings.RANK_LIST,"%s_%s" %(obj.match_id,obj.id))
             return obj.id
 
 
@@ -1091,13 +1123,28 @@ def get_user_follower(request):
     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")
@@ -1108,6 +1155,7 @@ def get_user_follower(request):
         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)
 
@@ -1148,11 +1196,27 @@ 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)
+        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
@@ -1169,7 +1233,6 @@ def get_user_follows(request):
 
     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))
 
@@ -1669,8 +1732,14 @@ def update_user_style(**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(id=player_id).update(username=kwargs.get("username"))
+    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"))
@@ -1739,8 +1808,6 @@ def get_player_match_calendar(**kwargs):
     sdate = month + "-" + sday
     edate = month + "-" + eday
 
-    print sdate,edate
-
     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())
@@ -1748,14 +1815,21 @@ def get_player_match_calendar(**kwargs):
     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"]
+        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":dct.get(stock_date,""),     
+            "today_income":today_income,     
+            "record_id":record_id    
         })
 
     return newdata
@@ -1801,17 +1875,12 @@ def get_mine_latest(request):
     """
     try:
         user_id = request.user.get("id")
-        match_id = ccc.get_cur_match().id
 
-        player_id = request.player.id
-        match_id = request.player.match_id
-        match_group = request.player.match_group
-        today = get_today_date()
-
-        _today = ccc.cache.hget("PLAYER_LATEST_%d"%player_id,"stock_date")
+        match_id = ccc.cache.hget("PLAYER_LATEST_%d" % user_id,"match_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:
-            today = _today
-            rst = get_today_record_actual(player_id,match_id,match_group)
+            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
 
@@ -1825,7 +1894,7 @@ def get_mine_latest(request):
         print(e)
         return {"player_id":user_id,"match_id":match_id,"user_id":user_id}
 
-@ccc.cache_data()
+#@ccc.cache_data()
 def get_match_validdates(match_id):
     """
     """
@@ -1914,9 +1983,12 @@ def do_wx_pay(request):
             match_group = cm.MatchGroup.objects.filter(match_id=match_id,charge=0).first().id
 
     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]:
+    if user["player_type"] in [0,1] and not phone=="13883187629":
         #生成订单
         order = cm.SignupOrder.objects.create(
             user_id = user_id, 
@@ -1977,7 +2049,7 @@ def do_wx_pay(request):
         user.role = 2
         user.save()
         #发送报名成功信息
-        send_signup_success(phone,signup_name)
+        #send_signup_success(phone,signup_name)
 
         if phone == "13883187629":
             for i in [5001,4762,5173,5141]:
@@ -1991,7 +2063,6 @@ def do_wxpay_notify(request):
     flag,res = wxpay.check_notify_valid(request.body)                              
     if flag:                                                                       
         out_trade_no = res.get("out_trade_no")                                     
-        print(out_trade_no)
         transaction_id = res.get("transaction_id")                                 
         pay_time = res.get("time_end")                                             
         try:
@@ -2038,7 +2109,7 @@ def do_wxpay_notify(request):
                     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)
+                #send_signup_success(sorder.phone,sorder.signup_name)
                 return True                                                            
         except Exception as e:
             import traceback
@@ -2429,7 +2500,7 @@ def get_user_match_list(request):
     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).order_by("-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))
@@ -2440,24 +2511,31 @@ def get_user_match_list(request):
     else:
         total = qset.count()
 
-    today = get_today_date(user_id=user_id)
+    #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)
-        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.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
 
-    return total,data
+        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):
@@ -2467,7 +2545,7 @@ def get_format_user_info(request):
     q_user_id = kwargs.get("user_id")
     if q_user_id:
         user_id = q_user_id
-    userinfo = get_user_info(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()
     del userinfo["phone"]
@@ -2503,3 +2581,61 @@ def get_day_inout_rank_list(request):
     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"])
+                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()
+        return total,data
+    else:
+        return len(data),data

+ 1 - 0
src/weixin/urls_backstage.py

@@ -72,6 +72,7 @@ urlpatterns = [
     url(r'^v3/user/match/list$', views.UserMatchListView.as_view()),
     url(r'^v3/stock/user/list$', views.StockUserListView.as_view()),
     url(r'^v3/user/inout/list$', views.UserInOutListView.as_view()),
+    url(r'^v3/user/follow/list$', views.V3FollowUserListView.as_view()),
 
 ]
 

+ 13 - 1
src/weixin/views.py

@@ -193,7 +193,7 @@ class PlayerRecordView(cv.AuthView):
         if mse:
             raise ce.TipException(mse)
         try:
-            need_params.extend(["is_markt","today_stock","today_stock_img","experience"])
+            need_params.extend(["is_markt","today_stock","today_stock_img","experience","id"])
             vals = ccf.get_need_params(*need_params,**qdata)
             vals["user_id"] = request.user.get("id",0)
             vals["match_id"] = ccc.get_cur_match().id
@@ -1088,3 +1088,15 @@ class UserInOutListView(cv.AuthView):
         except Exception as e: 
             cv.tracefail()
             return cv.to_fail(e)
+
+
+class V3FollowUserListView(cv.AuthView):                                                    
+    def get(self, request):                                                        
+        """#我的关注(2.0小程序)                                                       
+        """                                                                        
+        try:                                                                       
+            total,rst = ctl.get_user_follows_v3(request)                                 
+            return cv.to_suc({"total":total,"list":rst})
+        except Exception as e:                                                     
+            cv.tracefail()                                                         
+            return cv.to_fail(e)

File diff suppressed because it is too large
+ 1 - 1
templates/index.html