xjc 1 år sedan
förälder
incheckning
df3d7ce4fc

+ 3 - 0
src/common/common_control.py

@@ -174,6 +174,7 @@ def get_user_info(uid):
             user["style"].append(user["cw"])
         if user["df"]:
             user["style"].append(user["df"])
+        del user["phone"]
     return user
 
 
@@ -224,6 +225,8 @@ def get_today_record(user_id,match_id,match_group,today):
                         print e
             today_record["cangwei"] = "{}%".format(round(today_stock_total/today_record["today_fund"],4)*100)
             today_record["today_stock_total"] = today_stock_total
+            if today_record.get("phone"):
+                del today_record["phone"]
     except Exception as e:
         import traceback
         traceback.print_exc()

+ 1 - 1
src/common/constant.py

@@ -1,3 +1,3 @@
 #coding=utf-8
 
-ARTICLE_TYPE_LIST = [u"游资专场",u"冠军交割",u"牛人专场",u"妖股列传"]
+ARTICLE_TYPE_LIST = [u"每日点评",u"冠军交割",u"牛人专场",u"妖股列传"]

+ 2 - 1
src/common/models.py

@@ -29,6 +29,7 @@ class UserInfo(models.Model):
     comment_status = models.SmallIntegerField(u"1/正常,0/拉黑",default=1)
     unionid = models.CharField(u"微信unionid", max_length=64, blank=True,null=True)
     app_openid = models.CharField(u"微信openid", max_length=64, blank=True,null=True)
+    intro = models.TextField(u"用户简介", blank=True, null=True)
 
     ctime = models.DateTimeField(u"创建时间", auto_now_add=True)
 
@@ -212,7 +213,7 @@ class Stock(models.Model):
         app_label = "common"
 
     def __str__(self):
-        return u"{}){}".format(self.id, self.username)
+        return u"{}){}".format(self.id, self.name)
 
 
 class SysUserInfo(models.Model):

+ 53 - 4
src/manage/controls.py

@@ -5,7 +5,7 @@ import os,re,random
 import json,time,datetime
 import shutil
 import tempfile
-import zipfile
+import zipfile,requests
 from docxtpl import DocxTemplate,InlineImage
 from docx.shared import Mm
 from django.db import transaction
@@ -29,7 +29,7 @@ from django.db import connection
 from utils.wxSubscribeMessage import send_consult_reply_message
 from utils.aliyunpush import aliyunpush
 from tools.article_spider import startSpider
-from utils.plottool import plot_records
+from utils.plottool import plot_records,get_zipfile
 
 import xlrd
 import xlwt
@@ -770,11 +770,11 @@ def download_records_image(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"]+str(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 x['fund'] != '0.0']) 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"]+str(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 x['fund'] != '0.0']) if yesterday_stock else ""
 
             #空仓、开超市、请假判断
             if item["auto_complete"] > 0:
@@ -1357,4 +1357,53 @@ def baike_detail_top(**kwargs):
         cm.BaikeDetail.objects.filter(id=_id).update(istop=0)
 
 
+def download_top3_imgs(request):
+    """
+    """
+    kwargs = request.json
+    match_id = kwargs.get("match_id",0)
+
+    qset = cm.PlayerRecord.get_db_model(match_id).objects.all()
+
+    if kwargs.get("match_id"):
+        qset = qset.filter(match_id=kwargs.get("match_id"))
+    #if kwargs.get("groupId"):
+    #    qset = qset.filter(match_group=kwargs.get("groupId"))
+    if kwargs.get("stock_date"):
+        qset = qset.filter(stock_date=kwargs.get("stock_date"))
+
+    group_ids = list(cm.MatchGroup.objects.filter(match_id=match_id).values_list("id",flat=True))
+    imgData = []
+    for group_id in group_ids:
+        data = list(qset.filter(match_group=group_id).order_by("group_rank").values())
+        for item in data[:3]:
+            today_stock_img = json.loads(item["today_stock_img"]) if item["today_stock_img"] else []
+            ilist = []
+            for img in today_stock_img:
+                nlist = img.split('?')
+                if len(nlist) > 0:
+                    ilist.append(nlist[0])
+            match_group = item["match_group"]
+            match_group_name = cm.MatchGroup.objects.filter(id=match_group).first().name
+            group_rank = item["group_rank"]
+            username = item["username"]
+            imgName = u"%s-%s-%s" % (match_group_name,group_rank,username)
+
+            imgData.append({"imgName":imgName,"imgList":ilist})
+    #下载截图
+    zip_files = []
+    for imgInfo in imgData:
+        imgName = imgInfo["imgName"]
+        imgList = imgInfo["imgList"]
+        for i,url in enumerate(imgList):
+            tmpFile = "/tmp/%s-%s%s" % (imgName,i+1,os.path.splitext(url)[-1])
+            res = requests.get(url)
+            if res.status_code == 200:
+                with open(tmpFile,"wb+") as f:
+                    f.write(res.content)
+                zip_files.append(tmpFile)
+    #生成zip文件
+    tmpzip = get_zipfile(zip_files)
+    return tmpzip
+    #return imgData
 

+ 1 - 0
src/manage/urls_backstage.py

@@ -70,6 +70,7 @@ urlpatterns = [
     url(r'^user/famous/list$', views.UserArticleRelationListView.as_view()),
     url(r'^baike/detail/top$', views.BaikeDetailTopView.as_view()),
     url(r'^article/spider$', views.ArticleSpiderView.as_view()),
+    url(r'^player/record/download/top3img$', views.DownloadTop3ImageView.as_view()),
 
 ]
 

+ 19 - 2
src/manage/views.py

@@ -93,7 +93,7 @@ class UserInfoView(cv.AdminView):
         if mse:
             raise ce.TipException(mse)
         try:
-            need_params.extend(["usercode","badge","zq","cw","df","avatar","player_type","phone"])
+            need_params.extend(["usercode","badge","zq","cw","df","avatar","player_type","phone","intro"])
             vals = ccf.get_need_params(*need_params,**qdata)
             if not vals.get("usercode"):
                 vals["usercode"] = self.gen_code()
@@ -116,7 +116,7 @@ class UserInfoView(cv.AdminView):
         if mse:
             raise ce.TipException(mse)
         try:
-            need_params.extend(["is_bind","badge","zq","cw","df","avatar","player_type","phone"])
+            need_params.extend(["is_bind","badge","zq","cw","df","avatar","player_type","phone","intro"])
             vals = ccf.get_need_params(*need_params,**qdata)
             rst = ctl.update_model(self,**vals)
             return cv.to_suc(rst)
@@ -1942,3 +1942,20 @@ class BaikeDetailTopView(cv.AdminView):
         except Exception as e:
             cv.tracefail()
             return cv.to_fail(e)
+
+
+class DownloadTop3ImageView(cv.BaseView):
+    def get(self, request):
+        """download player record as image
+        """
+        try:
+            zipfile = ctl.download_top3_imgs(request)
+            #return cv.to_suc(zipfile)
+            wrapper = FileWrapper(zipfile)
+            response = HttpResponse(wrapper, content_type='application/zip')    
+            response['Content-Disposition'] = 'attachment;filename={}'\
+                 .format(ccf.datetime_to_str(datetime.datetime.now(),"%Y%m%d%H%M%S")+".zip")
+            return response                                                     
+        except Exception as e:
+            cv.tracefail()
+            return cv.to_fail(e)

+ 119 - 51
src/utils/ocrmanage.py

@@ -61,28 +61,31 @@ class OcrManage:
     @classmethod
     def parse(self,result,source):
         list  = result['words_result']
+        words = []
+        for dic in list:
+            word = dic['words']
+            word = self.deleteWords(word)
+            if len(word) > 0:
+                words.append(word)
+        wlist = self.wordsSeperate(words)
+        
         if source == 'pc': #电脑截图
-            words = []
-            for dic in list:
-                word = dic['words']
-                word = self.deleteWords(word)
-                if len(word) > 0:
-                    words.append(word)
-            wlist = self.wordsSeperate(words)
             return self.lookCPAsset(wlist,list)
         else:
-            return self.lookAsset(list)
+            return self.lookAsset(wlist,list)
     
     @classmethod
-    def lookAsset(self,list):
+    def lookAsset(self,wlist,list):
         dic   = {}
         asset = ''
         if self.indexObject('净资产',list) > 0:
             asset = self.caculateAsset(list,'净资产')
         else:
             asset = self.caculateAsset(list,'总资产')
-
-
+            if(self.floatValue(asset) == 0):
+                asset = self.caculateAsset(list,'账户资产')
+            if(self.floatValue(asset) == 0):
+                asset = self.assetWords(wlist)
         
         dic['today'] = self.wangWord(asset)
         dic['list']  = self.lookMarket(list)
@@ -93,14 +96,44 @@ class OcrManage:
     def lookMarket(self,list):
         flist = []
         index = self.indexObject('市值',list)
-        i = index
-        for i in range(len(list)):
+        beforeLoc = 0
+
+        for i in range(index,len(list)):
             dic = list[i]
             words = dic['words']
             codeName = self.codeName(words)
             if len(codeName['name']) > 0:
                 fund = 0
                 market = '0'
+                money  = 0
+            
+                if beforeLoc == 0:
+                    for n in range(i,index,-1):
+                        ndic = list[n]
+                        nstr = ndic['words']
+                        nstr = self.replaceWords(nstr)
+                        if('当日盈亏' in nstr or '比' in nstr):
+                            continue
+
+                        if '持仓盈' in nstr or '浮动盈亏' in nstr or '参考盈亏' in nstr or '盈亏/盈亏率' in nstr or '总盈亏' in nstr or '盈亏' in nstr:
+                            bnloc = list[n-1]['location']
+                            beforeLoc = float(bnloc['left']) + float(bnloc['width'])
+                            break
+
+                if beforeLoc > 0:
+                    for m in range(i+1,len(list)):
+                        mdic = list[m]
+                        mloc = mdic['location']
+                        mstr = mdic['words']
+
+                        if mloc['left'] > beforeLoc:
+                            mstr = self.replaceWords(mstr)
+                            mstr = self.replaceDot(mstr)
+                            mstr = self.wangWord(mstr)
+                            money = float(mstr)
+                            
+                            break
+
                 for m in range(i+1,len(list)):
                     mdic = list[m]
                     mloc = mdic['location']
@@ -108,29 +141,25 @@ class OcrManage:
                     nstr = mdic['words']
                     if len(nstr) == 6 and ((',' not in nstr) or ('.' not in nstr)) and self.isNumber(nstr):
                         continue
-                    if float(mloc['left']) < (float(loc['left']) + float(loc['width'])):
+                    if float(mloc['left']) < (float(loc['left']) + float(loc['width'])/2.0):
                         market = mdic['words']
                         break
                 
                 
                 fund = self.wangWord(market)
 
-                if fund > 0:
-                    ndic = {}
-                    ndic['name'] = codeName['name']
-                    ndic['code'] = codeName['code']
-                    ndic['fund'] = str(round(fund,2))
-                    flist.append(ndic)
+                ndic = {}
+                ndic['name'] = codeName['name']
+                ndic['code'] = codeName['code']
+                ndic['fund'] = str(round(fund,2))
+                ndic['money'] = str(round(money,3))
+                flist.append(ndic)
 
         return flist
     
     @classmethod
     def lookCPAsset(self,wlist,list):
         dic   = {}
-
-        # print(str(wlist))
-
-
         asset = self.assetWords(wlist)
         if self.floatValue(asset) >= 0:
             today = self.floatValue(asset)/10000.0
@@ -138,29 +167,30 @@ class OcrManage:
 
         dic['list'] = self.lookCPMarket(list)
 
-        print(str(dic))
 
         return dic
 
     @classmethod
     def lookCPMarket(self,list):
         flist = []
-        index = self.indexEquel('市值',list)
+        mindex = self.indexObject('名称',list)
+       
+        index = self.indexEquel('市值',list,mindex)
         if index == 0:
-            index = self.indexEquel('最新市值',list)
+            index = self.indexEquel('最新市值',list,mindex)
 
         if index == 0:
-            index = self.indexEquel('最新沛值',list)
+            index = self.indexEquel('最新沛值',list,mindex)
         
         before = 0.0
 
         if index - 1 > 0:
             sdic = list[index-1]
             sloc = sdic['location']
-           
+            print(sdic)
             before = float(sloc['left']) + float(sloc['width'])
             
-        
+        beforeLoc = 0
         
         for i in range(index,len(list)):
             dic = list[i]
@@ -175,6 +205,37 @@ class OcrManage:
             if len(codeName['name']) > 0:
                 fund = 0
                 market = '0'
+                money = 0
+
+                if beforeLoc == 0:
+                    for n in range(len(list)-1,-1,-1):
+                        ndic = list[n]
+                        nstr = ndic['words']
+                        nstr = self.replaceWords(nstr)
+                        if('当日盈亏' in nstr or '比例' in nstr):
+                            continue
+                        if '持仓盈亏' == nstr or '浮动盈亏' == nstr or '参考盈亏' == nstr or '盈亏/盈亏率' in nstr or '总盈亏' == nstr or '盈亏' == nstr:
+                            bnloc = list[n-1]['location']
+                            beforeLoc = float(bnloc['left']) + float(bnloc['width'])
+                            break
+                  
+
+
+                if beforeLoc > 0:
+                    for m in range(i+1,len(list)):
+                        mdic = list[m]
+                        mloc = mdic['location']
+                        mstr = mdic['words']
+
+                        if mloc['left'] > beforeLoc:
+                            mstr = self.replaceWords(mstr)
+                            mstr = self.replaceDot(mstr)
+                            mstr = self.wangWord(mstr)
+                            money = float(mstr)
+                            
+                            break
+
+
                 for m in range(i+1,len(list)):
                     mdic = list[m]
                     mloc = mdic['location']
@@ -186,12 +247,13 @@ class OcrManage:
                 
                 fund = self.wangWord(market)
                 
-                if fund > 0:
-                    ndic = {}
-                    ndic['name'] = codeName['name']
-                    ndic['code'] = codeName['code']
-                    ndic['fund'] = str(round(fund,2))
-                    flist.append(ndic)
+  
+                ndic = {}
+                ndic['name'] = codeName['name']
+                ndic['code'] = codeName['code']
+                ndic['fund'] = str(round(fund,2))
+                ndic['money'] = str(round(money,3))
+                flist.append(ndic)
 
         return flist
 
@@ -213,6 +275,10 @@ class OcrManage:
                     width = float(jdic['width'])
                     if jx < ix and ix < (jx + width):
                         strAsset = ndic['words']
+                        if(self.isChinese(strAsset)):
+                            if ('万' not in strAsset):
+                                clist    = self.seperateChinense(strAsset)
+                                strAsset = clist[0]
                         break
                 
                 if self.wangWord(strAsset) == 0:
@@ -260,7 +326,7 @@ class OcrManage:
                     if len(cword) > 0:
                         list.append(cword)
                         cword = ''
-                if strw == '-' or strw == ':':
+                if strw == ':':
                     if len(nword) > 0:
                         list.append(nword)
                         nword = ''
@@ -425,6 +491,9 @@ class OcrManage:
         words = words.replace(':','')
         words = words.replace(':','')
         words = words.replace('A','')
+        words = words.replace('▲','')
+        words = words.replace('◆','')
+        words = words.replace('+','')
         words = words.upper()
 
         return words
@@ -462,6 +531,7 @@ class OcrManage:
         for i in range(len(list)):
             dic = list[i]
             nword = dic['words']
+            nword = self.replaceWords(nword)
             if words in nword:
                 index = i
                 break
@@ -469,13 +539,14 @@ class OcrManage:
         return index
     
     @classmethod
-    def indexEquel(self,words,list):
+    def indexEquel(self,words,list,m):
         index = -1
         i=0
-        for i in range(len(list)):
+        for i in range(m,len(list)):
             dic = list[i]
             nword = dic['words']
-            if words == nword:
+            nword = self.replaceWords(nword)
+            if words in nword:
                 index = i
                 break
 
@@ -488,6 +559,10 @@ class OcrManage:
             # print('ischinese:' + number)
             return False
 
+        fushu = r'-\w*'
+        if re.match(fushu, str(number)):
+            return True
+        
         zhengshu = r'^([1-9][\d]*|0)(\.[\d]+)?$'
         if re.match(zhengshu, str(number)):
             return True
@@ -512,14 +587,10 @@ class OcrManage:
         if word == '':
             return 0
 
-        # print('floatValue:' + word)
-
         return float(word)
     
     @classmethod
     def wangWord(self,word):
-        print(word)
-
         isWang = 0
         if '万' in word:
             wlist = self.seperateChinense(word)
@@ -528,14 +599,11 @@ class OcrManage:
                 isWang = 1
 
         
-        if self.floatValue(word) >= 0:
-            if isWang == 1:
-                nvalue = self.floatValue(word)
-            else:
-                nvalue = self.floatValue(word)/10000.0
-            word = round(nvalue,2)
+        if isWang == 1:
+            nvalue = self.floatValue(word)
         else:
-            word = 0
+            nvalue = self.floatValue(word)/10000.0
+        word = round(nvalue,3)
 
         return word
 

+ 8 - 4
src/utils/upload_to_oss.py

@@ -95,15 +95,19 @@ class MyOSS:
 hnoss = MyOSS()
 
 
-def get_signature(policy, access_key_secret):
+def get_signature(policy):
     """
     获取上传签名
     """
+    AccessKeyID = "LTAI5t8bioQxGXB1jtVugJcU"
+    access_key_secret = "OdGWSBRjkJxaPjgmE38eQ8nzkI6nRk"
+
     policy_str = json.dumps(policy).replace('\n', '').replace('\r', '')
-    policy_encode = base64.b64encode(policy).rstrip('=').decode('utf-8')
+    policy_encode = base64.b64encode(policy_str).rstrip('=').decode('utf-8')
     h = hmac.new(access_key_secret.encode('utf-8'), policy_encode.encode('utf-8'), hashlib.sha1)
-    signature = base64.encodebytes(h.digest()).strip().decode('utf-8')
-    return policy_encode, signature
+    signature = base64.b64encode(h.digest()).strip().decode('utf-8')
+    rst = {"AccessKeyID":AccessKeyID,"policy_encode":policy_encode,"signature":signature}
+    return rst
 
 def validate_callback(callback_body, access_key_secret):
     """

+ 10 - 6
src/weixin/control_auth.py

@@ -129,10 +129,12 @@ def login_user_v3(request):
     #else:
     #    if unionid or phone:
     #        user = cm.UserInfo.objects.filter(Q(phone=phone)|Q(unionid=unionid)).order_by("-id").first()
-
+    print('unionid test')
+    print(unionid)
+	
     if unionid:
         user = cm.UserInfo.objects.filter(unionid=unionid).order_by("-id").first()
-
+	
     if not user and openid:
         user = cm.UserInfo.objects.filter(openid=openid).order_by("-id").first()
 
@@ -231,7 +233,9 @@ def get_wxauth_info_v3(request):
         orgcode = ccc.cache.get(phone)
         if not phcode == orgcode and not phone=="13883187629":
             raise ce.TipException(u"验证码不正确!")
-
+    print('unionid test')
+    print(unionid)
+    
     if unionid:
         user = cm.UserInfo.objects.filter(unionid=unionid).values().first()
 
@@ -243,9 +247,9 @@ def get_wxauth_info_v3(request):
 
     if not user:
         return {}
-    else:
-        if xcxflag and user.get("openid") != openid:
-            return {}
+#     else:
+#         if xcxflag and user.get("openid") != openid:
+#             return {}
 
     cur_match_id = ccc.get_signup_match().id
     gt_time = datetime.timedelta(days=-365)+datetime.datetime.now()

+ 105 - 16
src/weixin/controls.py

@@ -43,6 +43,7 @@ from utils.aliyunpush import aliyunpush
 from utils.wxpay.pay import WechatPayDAL
 #import logging
 #log = logging.getLogger("myerror")
+from utils.upload_to_oss import get_signature
 
 def async(f):
     def wrapper(*args, **kwargs):
@@ -182,7 +183,10 @@ def get_player_match_detail(request):
     """选手参赛详情数据
     """
     qdata = request.json
-    user_id = request.user.get("id",0)
+    try:
+        user_id = request.user.get("id",0)
+    except:
+        user_id = 0
 
     match_id = qdata.get("id")
     record_id = qdata.get("record_id")
@@ -265,18 +269,21 @@ def get_player_match_detail(request):
 
     match["groups"] = [today_record.get("match_group_name","")] if today_record else []
     records = sorted(records,key=lambda x:x["stock_date"],reverse=True)
-    if cm.UserFollows.objects.filter(user_id=request.user.get("id"),follow_id=cur_user_id).exists():
+    if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=cur_user_id).exists():
         is_follow = 1
     else:
         is_follow = 0
     if today_record and today_record.get("today_fund"):
         today_record["today_income_fund"] = round((today_record["today_fund"] - today_record["yesterday_fund"])*10000,2) if today_record["yesterday_fund"] else 0.00
     today_record["zan_count"] = today_record.get("zans",0)
+    user_info = get_user_info(cur_user_id)
+    if user_info.get("phone"):
+        del user_info["phone"]
     ret = {
         "match":match,
         "today_record":today_record,
         "match_group_info":get_group_info(today_record.get("match_group")) if today_record.get("match_group") else {},
-        "userinfo":get_user_info(cur_user_id),
+        "userinfo":user_info,
         "records":records,
         "is_follow":is_follow,
         "fans":cm.UserFollows.objects.filter(follow_id=cur_user_id).count(),
@@ -536,6 +543,8 @@ def get_user_info(uid):
             user["style"].append(user["cw"])
         if user["df"]:
             user["style"].append(user["df"])
+        if user.get("phone"):
+            del user["phone"]
     return user
 
 
@@ -549,6 +558,8 @@ def get_user_info_actual(uid):
             user["style"].append(user["cw"])
         if user["df"]:
             user["style"].append(user["df"])
+        if user.get("phone"):
+            del user["phone"]
     return user
 
 
@@ -772,7 +783,7 @@ def add_model(cls,**kwargs):
             new_stock_list = []
             today_stock_list = json.loads(today_stock)
             for ts in today_stock_list:
-                if ts["name"]:
+                if ts["name"] and ts["fund"]:
                     try:
                         stock,flag = cm.Stock.objects.get_or_create(
                             name = ts["name"] 
@@ -904,7 +915,11 @@ def add_model(cls,**kwargs):
 
     obj = model.objects.create(**kwargs)
 
-    return obj.id
+    if model_name == "PlayerRecord":
+        rst = {"id":obj.id,"user_id":obj.user_id,"match_id":match_id}
+        return rst
+    else:
+        return obj.id
 
 def update_model(cls,**kwargs):
     """
@@ -1277,6 +1292,8 @@ def get_user_follower(request):
                     item["win_rate"] = "0.0%"
                 item["today_income"] = "{}%".format(item["today_income"]*100)
                 item["total_income"] = "{}%".format(item["total_income"]*100)
+                if item.get("phone"):
+                    del item["phone"]
         return total,data
     else:
         return len(data),data
@@ -1301,6 +1318,9 @@ def get_user_follows(request):
 
     if page and page_size:
         total,data = ccf.get_page_list(data,page,page_size)
+        for item in data:
+            if item.get("phone"):
+                del item["phone"]
         return total,data
     else:
         return len(data),data
@@ -1349,6 +1369,7 @@ def get_user_follows(request):
                     item["total_income"] = "{}%".format(item["total_income"]*100)
                     item["zans_count"] = item.get("zans",0)
                     item["comments_count"] = cm.Comments.objects.filter(record_id=item.get("id",0)).count()
+                    del item["phone"]
                 except Exception as e:
                     print(e)
         return total,data
@@ -1387,7 +1408,7 @@ def get_hot_stock_buy(**kwargs):
     """
     """
     stock_date = kwargs.get("stock_date")
-    qset = cm.UserStock.objects.filter(stock_date=stock_date)
+    qset = cm.UserStock.objects.filter(stock_date=stock_date,fund__gt=0)
     if kwargs.get("name"):
         qset = cm.UserStock.objects.filter(stock_name__icontains=kwargs.get("name"),stock_date=stock_date)
     qset = qset.values("stock_id","stock_name").annotate(count=Count("stock_id"),total_fund=Sum("fund")).order_by("-count")
@@ -1411,6 +1432,11 @@ def get_hot_stock_buy(**kwargs):
 
     if page and page_size:
         total,data = ccf.get_page_list(data,page,page_size)
+        for item in data:
+            stock = cm.Stock.objects.filter(id=item["id"]).first()
+            if stock:
+                item["stock_code"] = stock.code
+                item["stock_desc"] = stock.desc
         return total,data
     else:
         return len(data),data
@@ -1869,7 +1895,7 @@ def get_stock_players(**kwargs):
     stock_id = kwargs.get("stock_id")
     stock_date = kwargs.get("stock_date",get_today_date())
     data = []
-    user_stocks = cm.UserStock.objects.filter(stock_id=stock_id,stock_date=stock_date)
+    user_stocks = cm.UserStock.objects.filter(stock_id=stock_id,stock_date=stock_date,fund__gt=0.0)
     for us in user_stocks:
         player_id = us.player_id
         player = cm.Player.objects.filter(id=player_id).first()
@@ -1883,16 +1909,20 @@ def get_stock_players(**kwargs):
                 today_record = get_today_record(user_id,match_id,match_group,us.stock_date)
             if today_record:
                 today_record["today_stock_img"] = json.loads(today_record["today_stock_img"]) if today_record["today_stock_img"] else []
-                today_record["today_stock"] = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
+                today_stock = json.loads(today_record["today_stock"]) if today_record["today_stock"] else []
+                today_stock = list(filter(lambda x:float(x.get("fund",0))>0.0,today_stock))
+                today_record["today_stock"] = today_stock
                 today_record["today_income"] = "{}%".format(today_record["today_income"]*100)
                 today_record["total_income"] = "{}%".format(today_record["total_income"]*100)
                 #today_record["cur_stock_fund"] = 0.0
                 for item in today_record["today_stock"]:
                     if int(item["stock_id"]) == int(stock_id):
                         today_record["cur_stock_fund"] = float(item["fund"]) if item["fund"] else 0.0
+                    else:
+                        today_record["cur_stock_fund"] = 0.0
                 data.append(today_record)
     #data = sorted(data,key=lambda x:x["today_fund"],reverse=True)
-    data = sorted(data,key=lambda x:x["cur_stock_fund"],reverse=True)
+    data = sorted(data,key=lambda x:x.get("cur_stock_fund",0),reverse=True)
     #分页
     page = int(kwargs.get("page",0))
     page_size = int(kwargs.get("page_size",20))
@@ -2753,7 +2783,6 @@ def get_format_user_info(request):
     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"]
     if cm.UserFollows.objects.filter(user_id=cur_user_id,follow_id=user_id).exists():
         userinfo["is_follow"] = 1
     else:
@@ -2762,6 +2791,8 @@ def get_format_user_info(request):
         userinfo["is_black"] = 1
     else:
         userinfo["is_black"] = 0
+    if userinfo.get("phone"): 
+        del userinfo["phone"]
     return userinfo
 
 def get_day_inout_rank_list(request):
@@ -3221,7 +3252,7 @@ def get_match_winlost_top5(**kwargs):
         get_user_avatar(total_win_down)
         valid_dates = json.loads(match.valid_dates) if match.valid_dates else []
 
-        data.append({"valid_dates":valid_dates,"date":end_time,"match_id":match_id,"match_name":match_name,"total_income_up":total_income_up,"total_income_down":total_income_down,"total_win_up":total_win_up,"total_win_down":total_win_down})
+        data.append({"valid_dates":valid_dates,"date":end_time,"start_time":match.start_time,"end_time":match.end_time,"match_id":match_id,"match_name":match_name,"total_income_up":total_income_up,"total_income_down":total_income_down,"total_win_up":total_win_up,"total_win_down":total_win_down})
 
         if int(kwargs.get("new",0)) == 1:
             break
@@ -3478,9 +3509,11 @@ def get_match_group_winlose_statistic(**qdata):
     #今日全部人均收益率
     total = prset.aggregate(total=Sum("today_income")).get("total")
     today_win_lose_avg = "{}%".format(round(total/prset.count()*100,2)) if prset.count()>0 else 0.0
+    total_fund = prset.aggregate(total=Sum("today_fund")).get("total")
 
     rst = {"group_win_lose_list":group_win_lose_list,
         "win_cnt":win_cnt,"lose_cnt":lose_cnt,
+        "total_fund":total_fund,
         "today_win_lose_avg":today_win_lose_avg}
 
     return rst
@@ -3549,20 +3582,25 @@ def get_match_group_winlose_allday(**qdata):
 
     group_win_lose_list = []
     prdata = prset.values("match_group","stock_date").annotate(today_fund=Sum("today_fund"),
-        today_income=Sum("today_income"),cnt=Count("today_income")).order_by("match_group").order_by("-stock_date")
-
+        today_income=Sum("today_income"),cnt=Count("today_income")).order_by("match_group").order_by("stock_date")
+    money = 10000.0
     for item in prdata:
         group_id = int(item["match_group"])
         stock_date = item["stock_date"]
+       
+        money += money * (item["today_income"]/item["cnt"] if item["cnt"] else 0)
+        total_income = (money-10000.0)/10000.0
+        total_avg    = "{}%".format(round(total_income*100,2))
         group_win_lose_list.append({
             "stock_date":stock_date,
             "match_group":group_id,
             "name":match_group_dct.get(group_id),
             "today_fund":"{}".format(round(item["today_fund"],2)),
-            "total_income":"{}%".format(round(item["today_income"]/item["cnt"]*100,2)) if item["cnt"] else 0.0,
+            "total_income":total_avg,
             "today_income":"{}%".format(round(item["today_income"]/item["cnt"]*100,2)) if item["cnt"] else 0.0
         })
 
+    group_win_lose_list = sorted(group_win_lose_list,key=lambda x:x["stock_date"],reverse=True)
     rst = {"list":group_win_lose_list}
     return rst
 
@@ -3577,17 +3615,68 @@ def get_match_group_winlose_avg_allday(**qdata):
 
     all_day = list(set(prset.values_list("stock_date",flat=True)))
 
+    nall_day = sorted(all_day,reverse=False)
+
     allday_winlose_avg_list = []
-    for stock_date in all_day: 
+    money = 10000.0
+    for stock_date in nall_day: 
         #今日全部人均收益率
         prset = cm.PlayerRecord.get_db_model(match_id).objects.filter(match_id=match_id,stock_date=stock_date)
         total = prset.aggregate(total=Sum("today_income")).get("total")
         today_win_lose_avg = "{}%".format(round(total/prset.count()*100,2)) if prset.count()>0 else 0.0
+        money += money * (total/prset.count() if prset.count() > 0 else 0)
+        total_income = (money-10000.0)/10000.0
+        total_avg    = "{}%".format(round(total_income*100,2))
         allday_winlose_avg_list.append({
             "stock_date":stock_date,     
             "today_income":today_win_lose_avg,     
-            "total_income":today_win_lose_avg
+            "total_income":total_avg,
         })
     allday_winlose_avg_list = sorted(allday_winlose_avg_list,key=lambda x:x["stock_date"],reverse=True)
     rst = {"list":allday_winlose_avg_list}
     return rst
+
+
+def get_user_match_stock_winloss_rank_list(**kwargs):
+    """
+    """
+    user_id = kwargs.get("user_id")
+    match_id = kwargs.get("match_id")
+    rank_type = kwargs.get("rank_type")
+    data = []
+
+    qset = cm.PlayerRecord.get_db_model(match_id).objects.filter(user_id=user_id,match_id=match_id).exclude(today_stock="[]").order_by("-stock_date")
+    for index,qitem in enumerate(qset):
+        today_stock = qitem.today_stock
+        today_stock = json.loads(today_stock) if today_stock else []
+        stock_date = qitem.stock_date
+        if index == 0:
+            for sitem in today_stock:
+                sitem["stock_date"] = stock_date
+                data.append(sitem)
+        else:
+            for sitem in today_stock:
+                if sitem["fund"] in ["0.0","0",""]:
+                    sitem["stock_date"] = stock_date
+                    data.append(sitem)
+
+    if rank_type == "win":
+        data = filter(lambda x:float(x.get("money",0))>0,data)
+        data = sorted(data,key=lambda x:float(x.get("money",0)),reverse=True)
+    else:
+        data = filter(lambda x:float(x.get("money",0))<0,data)
+        data = sorted(data,key=lambda x:float(x.get("money",0)),reverse=True)
+
+    return data
+
+
+
+def get_oss2_policy_sign(request):
+    """
+    """
+    qdata = request.json
+    policy = qdata.get("policy")
+    rst = get_signature(policy)
+    return rst
+
+

+ 5 - 0
src/weixin/urls_backstage.py

@@ -114,6 +114,11 @@ urlpatterns = [
     url(r'^v3/user/markscore/check$', views.UserMarkScoreCheckView.as_view()),
     url(r'^v3/match/group/winlose/allday$', views.MatchGroupWinloseAllDayView.as_view()),
     url(r'^v3/match/group/winlose/avg/allday$', views.MatchGroupWinloseAvgAllDayView.as_view()),
+
+    url(r'^player/match/external$', views.PlayerMatchExternalView.as_view()),
+    url(r'^v2/player/match/calendar/external$', views.PlayerMatchCalendarExternalView.as_view()),
+    url(r'^v3/user/match/stock/winlossrank/list$', views.UserMatchStockWinLossListView.as_view()),
+    url(r'^oss2/uploadfile/sign$', views.OSS2PolicyAndSignView.as_view()),
     
 ]
 

+ 58 - 0
src/weixin/views.py

@@ -1705,3 +1705,61 @@ class MatchGroupWinloseAvgAllDayView(cv.BaseView):
         except Exception as e:
             cv.tracefail()
             return cv.to_fail(e)
+
+
+class UserMatchStockWinLossListView(cv.BaseView):
+    def get(self, request):
+        """#获取个人股票盈亏排名
+        """
+        qdata = request.json
+        try:
+            rst = ctl.get_user_match_stock_winloss_rank_list(**qdata)
+            return cv.to_suc(rst)
+        except Exception as e:
+            cv.tracefail()
+            return cv.to_fail(e)
+
+
+class PlayerMatchExternalView(cv.BaseView):
+    def get(self, request):
+        """#选手参赛详情(小程序)
+        """
+        try:
+            rst = ctl.get_player_match_detail(request)
+            return cv.to_suc(rst)
+        except Exception as e:
+            cv.tracefail()
+            return cv.to_fail(e)
+
+
+class PlayerMatchCalendarExternalView(cv.BaseView):
+    def get(self, request):
+        """#获取日历收益(2.0小程序)
+        @match_id:1
+        @user_id:1
+        @month:2021-12
+        """
+        qdata = request.json
+        need_params = ["user_id","match_id","month"]
+        mse = ccf.check_params(*need_params,**qdata)
+        if mse:
+            raise ce.TipException(mse)
+        try:
+            vals = ccf.get_need_params(*need_params,**qdata)
+            rst = ctl.get_player_match_calendar(**vals)
+            return cv.to_suc(rst)
+        except Exception as e:
+            cv.tracefail()
+            return cv.to_fail(e)
+
+
+class OSS2PolicyAndSignView(cv.BaseView):
+    def get(self, request):
+        """#获取oss签名和上传策略
+        """
+        try:
+            rst = ctl.get_oss2_policy_sign(request)
+            return cv.to_suc(rst)
+        except Exception as e:
+            cv.tracefail()
+            return cv.to_fail(e)