WH01243 2 éve
szülő
commit
4461b8a8e3
100 módosított fájl, 17658 hozzáadás és 17741 törlés
  1. 2 1
      src/go.mod
  2. 4 2
      src/go.sum
  3. 163 163
      src/jfw/active/live.go
  4. 1 0
      src/jfw/config/config.go
  5. 43 42
      src/jfw/filter/pcUserSalesFilter.go
  6. 10 9
      src/jfw/filter/wxUserSalesFilter.go
  7. 1 1
      src/jfw/front/applysub.go
  8. 503 502
      src/jfw/front/dataExport.go
  9. 1290 1288
      src/jfw/front/front.go
  10. 303 304
      src/jfw/front/login.go
  11. 1 1
      src/jfw/front/pchelper.go
  12. 1 1
      src/jfw/front/search.go
  13. 4 4
      src/jfw/front/shorturl.go
  14. 322 325
      src/jfw/front/structedData.go
  15. 4 3
      src/jfw/front/supsearch.go
  16. 971 987
      src/jfw/front/swordfish.go
  17. 1 1
      src/jfw/front/ws_dataExport.go
  18. 2 2
      src/jfw/front/wxMyOrder.go
  19. 7 24
      src/jfw/front/wxkeyset.go
  20. 157 155
      src/jfw/jyutil/jyutil.go
  21. 50 51
      src/jfw/modules/app/src/app/active/active.go
  22. 191 191
      src/jfw/modules/app/src/app/active/pullnew/pullnew.go
  23. 114 116
      src/jfw/modules/app/src/app/filter/phonefilter.go
  24. 25 28
      src/jfw/modules/app/src/app/front/bigMember.go
  25. 571 597
      src/jfw/modules/app/src/app/front/front.go
  26. 918 919
      src/jfw/modules/app/src/app/front/login.go
  27. 200 199
      src/jfw/modules/app/src/app/front/logoffuser.go
  28. 392 398
      src/jfw/modules/app/src/app/front/me.go
  29. 4 3
      src/jfw/modules/app/src/app/front/myorder.go
  30. 144 144
      src/jfw/modules/app/src/app/front/search.go
  31. 4 4
      src/jfw/modules/app/src/app/front/shorturl.go
  32. 285 284
      src/jfw/modules/app/src/app/front/structedData.go
  33. 481 508
      src/jfw/modules/app/src/app/front/swordfish.go
  34. 19 19
      src/jfw/modules/app/src/app/front/vipsubscribe.go
  35. 2 1
      src/jfw/modules/app/src/app/front/ws_dataExport.go
  36. 299 293
      src/jfw/modules/app/src/app/front/wxkeyset.go
  37. 19 19
      src/jfw/modules/app/src/app/jylabutil/authority.go
  38. 135 133
      src/jfw/modules/app/src/app/jyutil/util.go
  39. 2 1
      src/jfw/modules/app/src/go.mod
  40. 4 2
      src/jfw/modules/app/src/go.sum
  41. 1 1
      src/jfw/modules/app/src/public/rpccall.go
  42. 75 64
      src/jfw/modules/bidfileinter/src/config.json
  43. 89 4
      src/jfw/modules/bidfileinter/src/go.mod
  44. 658 5
      src/jfw/modules/bidfileinter/src/go.sum
  45. 1 1
      src/jfw/modules/bidfileinter/src/service/action/exchange.go
  46. 148 148
      src/jfw/modules/bidfileinter/src/service/action/info.go
  47. 145 119
      src/jfw/modules/bidfileinter/src/service/config/config.go
  48. 430 430
      src/jfw/modules/bidfileinter/src/util/util.go
  49. 2 0
      src/jfw/modules/bigmember/src/config/config.go
  50. 3 0
      src/jfw/modules/bigmember/src/db/db.go
  51. 2 1
      src/jfw/modules/bigmember/src/go.mod
  52. 4 2
      src/jfw/modules/bigmember/src/go.sum
  53. 257 272
      src/jfw/modules/bigmember/src/service/analysis/analysis.go
  54. 1 2
      src/jfw/modules/bigmember/src/service/analysis/decision.go
  55. 27 25
      src/jfw/modules/bigmember/src/service/analysis/forecastproject.go
  56. 75 75
      src/jfw/modules/bigmember/src/service/bidfile/bidfile.go
  57. 1 25
      src/jfw/modules/bigmember/src/service/follow/projectPdf.go
  58. 64 109
      src/jfw/modules/bigmember/src/service/push/push.go
  59. 186 200
      src/jfw/modules/bigmember/src/service/report/marketAnalysis.go
  60. 6 29
      src/jfw/modules/bigmember/src/service/report/report.go
  61. 11 61
      src/jfw/modules/bigmember/src/service/subscribe/subscribe.go
  62. 29 96
      src/jfw/modules/bigmember/src/service/use/use.go
  63. 8 0
      src/jfw/modules/distribution/src/config.json
  64. 4 1
      src/jfw/modules/distribution/src/go.mod
  65. 8 2
      src/jfw/modules/distribution/src/go.sum
  66. 3 3
      src/jfw/modules/distribution/src/service/action/share.go
  67. 143 126
      src/jfw/modules/distribution/src/service/config/config.go
  68. 12 12
      src/jfw/modules/distribution/src/service/filter/phonefilter.go
  69. 1 1
      src/jfw/modules/distribution/src/util/util.go
  70. 4 3
      src/jfw/modules/publicapply/src/active/21yearEndReport.go
  71. 60 58
      src/jfw/modules/publicapply/src/config/config.go
  72. 2 2
      src/jfw/modules/publicapply/src/dataexport/service/action.go
  73. 10 7
      src/jfw/modules/publicapply/src/db/db.go
  74. 2 1
      src/jfw/modules/publicapply/src/go.mod
  75. 4 2
      src/jfw/modules/publicapply/src/go.sum
  76. 3 3
      src/jfw/modules/publicapply/src/shareFission/service/service.go
  77. 198 232
      src/jfw/modules/publicapply/src/subscribe/entity/entity.go
  78. 261 270
      src/jfw/modules/publicapply/src/subscribePush/entity/historyPush.go
  79. 620 1019
      src/jfw/modules/publicapply/src/subscribePush/entity/keyWords.go
  80. 473 509
      src/jfw/modules/publicapply/src/subscribePush/entity/setting.go
  81. 325 325
      src/jfw/modules/publicapply/src/subscribePush/entity/vrew.go
  82. 2 2
      src/jfw/modules/publicapply/src/userbase/entity/entity.go
  83. 207 207
      src/jfw/modules/publicapply/src/util/util.go
  84. 223 237
      src/jfw/modules/subscribepay/src/entity/areaPack.go
  85. 88 88
      src/jfw/modules/subscribepay/src/entity/bidfile.go
  86. 539 539
      src/jfw/modules/subscribepay/src/entity/dataExportPackStruct.go
  87. 852 854
      src/jfw/modules/subscribepay/src/entity/dataexport.go
  88. 65 65
      src/jfw/modules/subscribepay/src/entity/distribution.go
  89. 0 2
      src/jfw/modules/subscribepay/src/entity/order.go
  90. 474 538
      src/jfw/modules/subscribepay/src/entity/subscribeVip.go
  91. 0 1
      src/jfw/modules/subscribepay/src/report/report.go
  92. 596 598
      src/jfw/modules/subscribepay/src/service/afterPay.go
  93. 1 1
      src/jfw/modules/subscribepay/src/service/dataexportPack.go
  94. 2 2
      src/jfw/modules/subscribepay/src/service/exceptionVerification.go
  95. 0 1
      src/jfw/modules/subscribepay/src/service/invoice.go
  96. 876 876
      src/jfw/modules/subscribepay/src/service/orderListDetails.go
  97. 3 3
      src/jfw/modules/subscribepay/src/service/phoneCollent.go
  98. 541 541
      src/jfw/modules/subscribepay/src/service/salesCreateOrder.go
  99. 574 574
      src/jfw/modules/subscribepay/src/service/userAccountInfo.go
  100. 610 642
      src/jfw/modules/subscribepay/src/service/vipSubscribeChange.go

+ 2 - 1
src/go.mod

@@ -4,7 +4,7 @@ go 1.18
 
 require (
 	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
-	app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa
+	app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114
 	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230129060002-f69424aa14ba
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/dchest/captcha v1.0.0
@@ -17,6 +17,7 @@ require (
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
 	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 // indirect
 	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 // indirect
 	bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4 // indirect
 	github.com/BurntSushi/toml v1.1.0 // indirect

+ 4 - 2
src/go.sum

@@ -13,11 +13,13 @@ app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tc
 app.yhyue.com/moapp/jybase v0.0.0-20230109015757-aa3d5e19b196/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a h1:wD4aWPSYdiX1cIP4lzzPD2s7fYhKa3muIf97l9tonJE=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa h1:0/2I4ubgDsRbKm7PeiVSTvYwZCK3anZQaEagsGBbI7E=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa/go.mod h1:0DqPlGxaufZlKaLoRndTWG4j3qUQqJ6MNZCmoPcMqSg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114 h1:89J5Zq4bfnocIpEWBn19PnfaT+8Dh+Rv4X8QoTwxCpg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114/go.mod h1:sa5YRPqTQLOVBmpltjT21EkQ7DfJbUZFARUb4ZJ7U+k=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae h1:6rDDaz6yxvE8viTSzEBwKYOFWq14TMfuBivSazUZMz4=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
 bp.jydev.jianyu360.cn/BP/jynsq v0.0.0-20220222052708-ebc43af90698/go.mod h1:ojo/AUH9Yr1wzarEjOaNMkj1Cet/9r8IgLyba64Z52E=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 h1:cw/PdRypNFcYOk4iWAfHjIFoMzIlXUfl9XAmWujBOPY=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7/go.mod h1:7Xhygw0KBuL4h0G76FnFg4otQcA9bmOO0c8M0FCjAyQ=
 bp.jydev.jianyu360.cn/BaseService/gateway v0.0.0-20220419090715-88ddb32961be/go.mod h1:Yj4oabIGItuMoF0BXYLz2XAnF581kxgXBrvlUtIJrkI=
 bp.jydev.jianyu360.cn/BaseService/gateway v1.3.4/go.mod h1:BMLd/5wb3BIEGhnEgF9y1sJN9P5/Dw9kYsoiE9V8I9g=
 bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 h1:jeItQ6RM1T6yPWc/5i4R6h3kViD+Rm2VnIEsc1gCFJA=

+ 163 - 163
src/jfw/active/live.go

@@ -2,187 +2,187 @@
 package active
 
 import (
-	"fmt"
-	"jy/src/jfw/config"
-	. "jy/src/jfw/front"
-	"net/url"
-	"time"
+    "fmt"
+    "jy/src/jfw/config"
+    . "jy/src/jfw/front"
+    "net/url"
+    "time"
 
-	"jy/src/jfw/jyutil"
+    "jy/src/jfw/jyutil"
 
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/public"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/public"
 
-	util "app.yhyue.com/moapp/jybase/common"
+    util "app.yhyue.com/moapp/jybase/common"
 )
 
 var LiveOrder = "liveorder" //预约表
 //修改直播时间等信息
 func (this *Active) UpdateInfo() {
-	if this.GetString("p") != "51a3b7b4ed3cf140" {
-		return
-	}
-	//直播开始时间
-	liveStart, _ := this.GetInt("ls")
-	if liveStart != 0 {
-		config.ActiveConfig.Live_Ing_Start = liveStart
-	}
-	//直播结束时间
-	liveEnd, _ := this.GetInt("le")
-	if liveEnd != 0 {
-		config.ActiveConfig.Live_Ing_End = liveEnd
-	}
-	this.ServeJson(map[string]interface{}{
-		"直播开始时间:": FormatDateByInt64(&liveStart, Date_Full_Layout),
-		"直播结束时间:": FormatDateByInt64(&liveEnd, Date_Full_Layout),
-	})
+    if this.GetString("p") != "51a3b7b4ed3cf140" {
+        return
+    }
+    //直播开始时间
+    liveStart, _ := this.GetInt("ls")
+    if liveStart != 0 {
+        config.ActiveConfig.Live_Ing_Start = liveStart
+    }
+    //直播结束时间
+    liveEnd, _ := this.GetInt("le")
+    if liveEnd != 0 {
+        config.ActiveConfig.Live_Ing_End = liveEnd
+    }
+    this.ServeJson(map[string]interface{}{
+        "直播开始时间:": FormatDateByInt64(&liveStart, Date_Full_Layout),
+        "直播结束时间:": FormatDateByInt64(&liveEnd, Date_Full_Layout),
+    })
 }
 
 //保存预约信息
 func (this *Active) SubInfo() error {
-	defer util.Catch()
-	var res = map[string]interface{}{
-		"success": false,
-	}
-	userId, _ := this.Session().Get("userId").(string)
-	s_phone := this.GetString("phone")
-	if userId != "" && s_phone != "" {
-		count := public.MQFW.Count(LiveOrder, map[string]interface{}{
-			"s_userid":   userId,
-			"order_type": "wx",
-		})
-		if count == 0 {
-			saveData := map[string]interface{}{
-				"s_userid":     userId,
-				"s_openid":     this.Session().Get("s_m_openid").(string),
-				"s_phone":      s_phone,
-				"order_type":   "wx",
-				"l_createdate": time.Now().Unix(),
-			}
-			id := public.MQFW.Save(LiveOrder, saveData)
-			if id == "" {
-				fmt.Println("直播活动 预约失败--", userId)
-			} else {
-				res["success"] = true
-			}
-		} else {
-			res["success"] = true
-		}
-	}
-	this.ServeJson(res)
-	return nil
+    defer util.Catch()
+    var res = map[string]interface{}{
+        "success": false,
+    }
+    userId, _ := this.Session().Get("userId").(string)
+    s_phone := this.GetString("phone")
+    if userId != "" && s_phone != "" {
+        count := public.MQFW.Count(LiveOrder, map[string]interface{}{
+            "s_userid":   userId,
+            "order_type": "wx",
+        })
+        if count == 0 {
+            saveData := map[string]interface{}{
+                "s_userid":     userId,
+                "s_openid":     this.Session().Get("s_m_openid").(string),
+                "s_phone":      s_phone,
+                "order_type":   "wx",
+                "l_createdate": time.Now().Unix(),
+            }
+            id := public.MQFW.Save(LiveOrder, saveData)
+            if id == "" {
+                fmt.Println("直播活动 预约失败--", userId)
+            } else {
+                res["success"] = true
+            }
+        } else {
+            res["success"] = true
+        }
+    }
+    this.ServeJson(res)
+    return nil
 }
 
 //预约状态等信息
 func (this *Active) SubStatus() error {
-	defer util.Catch()
-	userId, _ := this.Session().Get("userId").(string)
-	var res = map[string]interface{}{
-		"live_Active_Start":  FormatDateByInt64(&config.ActiveConfig.Live_Active_Start, "2006/01/02/15:04"), //直播活动开始时间
-		"live_Active_End":    config.ActiveConfig.Live_Active_End,
-		"live_Preheat_Start": config.ActiveConfig.Live_Preheat_Start,
-		"live_Preheat_End":   config.ActiveConfig.Live_Preheat_End,
-		"liveactiveRTB":      redis.GetInt("other", "liveactiveRTB"), //获取已购买人数
-	}
-	if userId != "" {
-		openId, _ := this.Session().Get("s_m_openid").(string)
-		if CheckUserIsSubscribe(openId) {
-			//是否是vip用户
-			res["userId"] = encrypt.SE.EncodeString(userId)
-			if this.GetString("pageName") == "A" {
-				data, ok := public.MQFW.FindById("user", userId, nil)
-				if ok && data != nil && *data != nil {
-					res["isVip"] = util.IntAll((*data)["i_vip_status"]) > 0
-					res["isOnTail"] = util.IntAll((*data)["i_vip_status"]) == 1
-				}
-			}
-		}
-		var query = map[string]interface{}{
-			"s_userid":   userId,
-			"order_type": "wx", //微信预约
-		}
-		count := public.MQFW.Count(LiveOrder, query)
-		res["order_status"] = count > 0
-	}
-	this.ServeJson(res)
-	return nil
+    defer util.Catch()
+    userId, _ := this.Session().Get("userId").(string)
+    var res = map[string]interface{}{
+        "live_Active_Start":  FormatDateByInt64(&config.ActiveConfig.Live_Active_Start, "2006/01/02/15:04"), //直播活动开始时间
+        "live_Active_End":    config.ActiveConfig.Live_Active_End,
+        "live_Preheat_Start": config.ActiveConfig.Live_Preheat_Start,
+        "live_Preheat_End":   config.ActiveConfig.Live_Preheat_End,
+        "liveactiveRTB":      redis.GetInt("other", "liveactiveRTB"), //获取已购买人数
+    }
+    if userId != "" {
+        openId, _ := this.Session().Get("s_m_openid").(string)
+        if CheckUserIsSubscribe(openId) {
+            //是否是vip用户
+            res["userId"] = encrypt.SE.EncodeString(userId)
+            if this.GetString("pageName") == "A" {
+                data := jyutil.Compatible.Select(userId, `{"i_vip_status":1}`)
+                if data != nil && *data != nil {
+                    res["isVip"] = util.IntAll((*data)["i_vip_status"]) > 0
+                    res["isOnTail"] = util.IntAll((*data)["i_vip_status"]) == 1
+                }
+            }
+        }
+        var query = map[string]interface{}{
+            "s_userid":   userId,
+            "order_type": "wx", //微信预约
+        }
+        count := public.MQFW.Count(LiveOrder, query)
+        res["order_status"] = count > 0
+    }
+    this.ServeJson(res)
+    return nil
 }
 
 //直播和预约活动 跳转分拨逻辑
 func (this *Active) LivePage() error {
-	defer util.Catch()
-	checkIsSubscribeFlag := true
-	openid, _ := this.Session().Get("s_m_openid").(string)
-	if openid == "" {
-		if this.Session().Get("s_m_openid") == nil {
-			if this.GetString("state") == "wx" {
-				//微信跳回来的
-				code := this.GetString("code")
-				if code != "" {
-					openid = jyutil.Getopenid(code)
-					if openid != "" {
-						//是否为关注用户
-						checkIsSubscribeFlag = CheckUserIsSubscribe(openid)
-						if checkIsSubscribeFlag {
-							//关注用户 建session
-							go FindUserAndCreateSess(openid, this.Session(), "wx", false)
-						}
-					}
-				}
-			} else {
-				if public.CheckWxBrowser(this.Request) {
-					//所有参数都不再使用,跳到微信验证用户
-					return this.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(this.Site()+this.Url()), "wx"), 302)
-				}
-			}
-		}
-		if this.Session().Get("s_m_openid") == nil {
-			checkIsSubscribeFlag = false
-		}
-	} else {
-		//是否为关注用户
-		checkIsSubscribeFlag = CheckUserIsSubscribe(openid)
-	}
-	this.T["checkIsSubscribeFlag"] = checkIsSubscribeFlag
-	this.T["Live_Active_Start"] = config.ActiveConfig.Live_Active_Start   //直播活动开始时间
-	this.T["Live_Active_End"] = config.ActiveConfig.Live_Active_End       //直播活动结束时间
-	this.T["Live_Preheat_Start"] = config.ActiveConfig.Live_Preheat_Start //预热活动开始时间
-	this.T["Live_Preheat_End"] = config.ActiveConfig.Live_Preheat_End     //预热活动结束时间
-	this.T["LIVEING"] = false                                             //是否直播中
-	now := time.Now()
-	if now.Unix() > config.ActiveConfig.Live_After_Date { //直播活动结束超过提示时间  跳转到vip介绍页
-		return this.Redirect("/front/vipsubscribe/introducePage")
-	} else if now.Unix() > config.ActiveConfig.Live_Active_End { //直播活动结束 活动结束页
-		this.T["LIVEEND"] = true
-		return this.Render("/active/livePage/live_online_wx.html", &this.T)
-	} else if now.Unix() > config.ActiveConfig.Live_Active_Start { //直播活动进行中
-		if checkIsSubscribeFlag {
-			//是否是vip用户
-			userId, _ := this.Session().Get("userId").(string)
-			data, ok := public.MQFW.FindById("user", userId, nil)
-			if ok && data != nil && *data != nil {
-				this.T["isVip"] = util.IntAll((*data)["i_vip_status"]) > 0
-				this.T["isOnTail"] = util.IntAll((*data)["i_vip_status"]) == 1
-			}
-		}
-		//是否直播进行中
-		if config.ActiveConfig.Live_Ing_End > time.Now().Unix() && time.Now().Unix() > config.ActiveConfig.Live_Ing_Start {
-			this.T["LIVEING"] = true
-		}
-		return this.Render("/active/livePage/live_online_wx.html", &this.T)
-	} else if now.Unix() > config.ActiveConfig.Live_Preheat_Start { //预热活动进行中
-		userId, _ := this.Session().Get("userId").(string)
-		this.T["order_status"] = 0
-		if checkIsSubscribeFlag && userId != "" {
-			var query = map[string]interface{}{
-				"s_userid":   this.Session().Get("userId").(string),
-				"order_type": "wx", //微信预约
-			}
-			this.T["order_status"] = public.MQFW.Count(LiveOrder, query)
-		}
-		return this.Render("/active/livePage/live_preheat_wx.html", &this.T)
-	}
-	return nil
+    defer util.Catch()
+    checkIsSubscribeFlag := true
+    openid, _ := this.Session().Get("s_m_openid").(string)
+    if openid == "" {
+        if this.Session().Get("s_m_openid") == nil {
+            if this.GetString("state") == "wx" {
+                //微信跳回来的
+                code := this.GetString("code")
+                if code != "" {
+                    openid = jyutil.Getopenid(code)
+                    if openid != "" {
+                        //是否为关注用户
+                        checkIsSubscribeFlag = CheckUserIsSubscribe(openid)
+                        if checkIsSubscribeFlag {
+                            //关注用户 建session
+                            go FindUserAndCreateSess(openid, this.Session(), "wx", false)
+                        }
+                    }
+                }
+            } else {
+                if public.CheckWxBrowser(this.Request) {
+                    //所有参数都不再使用,跳到微信验证用户
+                    return this.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(this.Site()+this.Url()), "wx"), 302)
+                }
+            }
+        }
+        if this.Session().Get("s_m_openid") == nil {
+            checkIsSubscribeFlag = false
+        }
+    } else {
+        //是否为关注用户
+        checkIsSubscribeFlag = CheckUserIsSubscribe(openid)
+    }
+    this.T["checkIsSubscribeFlag"] = checkIsSubscribeFlag
+    this.T["Live_Active_Start"] = config.ActiveConfig.Live_Active_Start   //直播活动开始时间
+    this.T["Live_Active_End"] = config.ActiveConfig.Live_Active_End       //直播活动结束时间
+    this.T["Live_Preheat_Start"] = config.ActiveConfig.Live_Preheat_Start //预热活动开始时间
+    this.T["Live_Preheat_End"] = config.ActiveConfig.Live_Preheat_End     //预热活动结束时间
+    this.T["LIVEING"] = false                                             //是否直播中
+    now := time.Now()
+    if now.Unix() > config.ActiveConfig.Live_After_Date { //直播活动结束超过提示时间  跳转到vip介绍页
+        return this.Redirect("/front/vipsubscribe/introducePage")
+    } else if now.Unix() > config.ActiveConfig.Live_Active_End { //直播活动结束 活动结束页
+        this.T["LIVEEND"] = true
+        return this.Render("/active/livePage/live_online_wx.html", &this.T)
+    } else if now.Unix() > config.ActiveConfig.Live_Active_Start { //直播活动进行中
+        if checkIsSubscribeFlag {
+            //是否是vip用户
+            userId, _ := this.Session().Get("userId").(string)
+            data := jyutil.Compatible.Select(userId, `{"i_vip_status":1}`)
+            if data != nil && *data != nil {
+                this.T["isVip"] = util.IntAll((*data)["i_vip_status"]) > 0
+                this.T["isOnTail"] = util.IntAll((*data)["i_vip_status"]) == 1
+            }
+        }
+        //是否直播进行中
+        if config.ActiveConfig.Live_Ing_End > time.Now().Unix() && time.Now().Unix() > config.ActiveConfig.Live_Ing_Start {
+            this.T["LIVEING"] = true
+        }
+        return this.Render("/active/livePage/live_online_wx.html", &this.T)
+    } else if now.Unix() > config.ActiveConfig.Live_Preheat_Start { //预热活动进行中
+        userId, _ := this.Session().Get("userId").(string)
+        this.T["order_status"] = 0
+        if checkIsSubscribeFlag && userId != "" {
+            var query = map[string]interface{}{
+                "s_userid":   this.Session().Get("userId").(string),
+                "order_type": "wx", //微信预约
+            }
+            this.T["order_status"] = public.MQFW.Count(LiveOrder, query)
+        }
+        return this.Render("/active/livePage/live_preheat_wx.html", &this.T)
+    }
+    return nil
 }

+ 1 - 0
src/jfw/config/config.go

@@ -20,6 +20,7 @@ var (
 	GmailAuth            []*mail.GmailAuth
 	EntnichePcConf       *entnichePcConf
 	Middleground         *middleground.Middleground
+
 )
 
 type entnichePcConf struct {

+ 43 - 42
src/jfw/filter/pcUserSalesFilter.go

@@ -1,54 +1,55 @@
 package filter
 
 import (
-	"app.yhyue.com/moapp/jypkg/public"
-	"jy/src/jfw/config"
-	"net/http"
-	"strings"
-	"time"
+    "app.yhyue.com/moapp/jypkg/public"
+    "jy/src/jfw/config"
+    "jy/src/jfw/jyutil"
+    "net/http"
+    "strings"
+    "time"
 
-	qu "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    qu "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
 )
 
 type pcSalesFilter struct {
-	W          http.ResponseWriter
-	R          *http.Request
-	Session    *httpsession.Session
-	GetSession map[string]interface{}
+    W          http.ResponseWriter
+    R          *http.Request
+    Session    *httpsession.Session
+    GetSession map[string]interface{}
 }
 
 // pc新用户判断是否需要留资
 func (l *pcSalesFilter) Do() bool {
-	if !initflag {
-		return true
-	}
-	if flag, _ := config.Sysconfig["phoneFilterFlag"].(bool); !flag {
-		return true
-	}
-	if l.R.Method == "POST" {
-		return true
-	}
-	for _, v := range bindurl {
-		if v.MatchString(l.R.URL.Path) && !strings.Contains(l.R.URL.Path, "bidedoc") && !strings.Contains(l.R.URL.Path, "squeeze") && !strings.Contains(l.R.URL.Path, "partner") {
-			return true
-		}
-	}
-	if userAgent := l.R.UserAgent(); mobileReg.MatchString(userAgent) || public.CheckWxBrowser(l.R) {
-		return true // 移动端 返回
-	}
-	//pc判断是否需要留资
-	href := "/swordfish/frontPage/user/sess/set_favorite" // pc端留资页面地址
-	if uid := l.GetSession["userId"]; uid != nil && uid != "" {
-		data, ok := public.MQFW.FindById("user", qu.InterfaceToStr(uid), `{"l_registedate":1,"app_first_login":1}`)
-		if ok && data != nil && len(*data) > 0 {
-			if qu.Int64All((*data)["l_registedate"]) >= qu.Int64All(config.Seoconfig["appNewUserTime"]) && qu.IntAll((*data)["app_first_login"]) == 0 {
-				//设置cookie 前端跳转
-				SetCookie(l.R.URL.String(), int(time.Hour*24/time.Second), l.W)
-				http.Redirect(l.W, l.R, href, 302)
-				return false
-			}
-		}
-	}
-	return true
+    if !initflag {
+        return true
+    }
+    if flag, _ := config.Sysconfig["phoneFilterFlag"].(bool); !flag {
+        return true
+    }
+    if l.R.Method == "POST" {
+        return true
+    }
+    for _, v := range bindurl {
+        if v.MatchString(l.R.URL.Path) && !strings.Contains(l.R.URL.Path, "bidedoc") && !strings.Contains(l.R.URL.Path, "squeeze") && !strings.Contains(l.R.URL.Path, "partner") {
+            return true
+        }
+    }
+    if userAgent := l.R.UserAgent(); mobileReg.MatchString(userAgent) || public.CheckWxBrowser(l.R) {
+        return true // 移动端 返回
+    }
+    //pc判断是否需要留资
+    href := "/swordfish/frontPage/user/sess/set_favorite" // pc端留资页面地址
+    if uid := l.GetSession["userId"]; uid != nil && uid != "" {
+        data := jyutil.Compatible.Select(qu.InterfaceToStr(uid), `{"l_registedate":1,"app_first_login":1}`)
+        if  data != nil && len(*data) > 0 {
+            if qu.Int64All((*data)["l_registedate"]) >= qu.Int64All(config.Seoconfig["appNewUserTime"]) && qu.IntAll((*data)["app_first_login"]) == 0 {
+                //设置cookie 前端跳转
+                SetCookie(l.R.URL.String(), int(time.Hour*24/time.Second), l.W)
+                http.Redirect(l.W, l.R, href, 302)
+                return false
+            }
+        }
+    }
+    return true
 }

+ 10 - 9
src/jfw/filter/wxUserSalesFilter.go

@@ -1,15 +1,16 @@
 package filter
 
 import (
-	"jy/src/jfw/config"
-	"app.yhyue.com/moapp/jypkg/public"
-	"net/http"
-	"strings"
-	"time"
+    "app.yhyue.com/moapp/jypkg/public"
+    "jy/src/jfw/config"
+    "jy/src/jfw/jyutil"
+    "net/http"
+    "strings"
+    "time"
 
-	qu "app.yhyue.com/moapp/jybase/common"
+    qu "app.yhyue.com/moapp/jybase/common"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
 )
 
 type salesFilter struct {
@@ -38,8 +39,8 @@ func (l *salesFilter) Do() bool {
 	if userAgent := l.R.UserAgent(); mobileReg.MatchString(userAgent) || public.CheckWxBrowser(l.R) {
 		href := "/jy_mobile/uersales/newuser" //wx判断是否需要留资
 		if uid := l.GetSession["userId"]; uid != nil && uid != "" {
-			data, ok := public.MQFW.FindById("user", qu.InterfaceToStr(uid), `{"l_registedate":1,"app_first_login":1}`)
-			if ok && data != nil && len(*data) > 0 {
+			data :=jyutil.Compatible.Select( qu.InterfaceToStr(uid), `{"l_registedate":1,"app_first_login":1}`)
+			if  data != nil && len(*data) > 0 {
 				if qu.Int64All((*data)["l_registedate"]) >= qu.Int64All(config.Seoconfig["appNewUserTime"]) && qu.IntAll((*data)["app_first_login"]) == 0 {
 					//设置cookie 前端跳转
 					SetCookie(l.R.URL.String(), int(time.Hour*24/time.Second), l.W)

+ 1 - 1
src/jfw/front/applysub.go

@@ -70,7 +70,7 @@ func (a *Applysub) SubInfo() error {
 						id := mongodb.Save("applysub_user", applyinfo)
 						if len(id) > 0 {
 							returnMap["flag"] = true
-							mongodb.UpdateById("user", userid, bson.M{"$set": bson.M{"i_applystatus": 1, "o_jy.i_ratemode": 2}})
+                            jyutil.Compatible.Update( userid, bson.M{"$set": bson.M{"i_applystatus": 1, "o_jy.i_ratemode": 2}})
 						}
 					} else {
 						returnMap["msg"] = "请输入正确的手机号"

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 503 - 502
src/jfw/front/dataExport.go


A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 1290 - 1288
src/jfw/front/front.go


+ 303 - 304
src/jfw/front/login.go

@@ -1,361 +1,360 @@
 package front
 
 import (
-	"jy/src/jfw/config"
-	"log"
-	"regexp"
-	"strings"
-	"time"
+    "jy/src/jfw/config"
+    "jy/src/jfw/jyutil"
+    "log"
+    "regexp"
+    "strings"
+    "time"
 
-	"app.yhyue.com/moapp/jybase/usercenter"
+    "app.yhyue.com/moapp/jybase/usercenter"
 
-	"app.yhyue.com/moapp/jypkg/public"
+    "app.yhyue.com/moapp/jypkg/public"
 
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
+    qutil "app.yhyue.com/moapp/jybase/common"
 
-	. "app.yhyue.com/moapp/jybase/mongodb"
+    . "app.yhyue.com/moapp/jybase/mongodb"
 
-	"github.com/dchest/captcha"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"go.mongodb.org/mongo-driver/bson/primitive"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "github.com/dchest/captcha"
+    "go.mongodb.org/mongo-driver/bson/primitive"
 )
 
 type Login struct {
-	*xweb.Action
-	login     xweb.Mapper `xweb:"/phone/login"`     //登录
-	forgetPwd xweb.Mapper `xweb:"/phone/forgetPwd"` //忘记密码
-	register  xweb.Mapper `xweb:"/phone/register"`  //注册
-	phoneBind xweb.Mapper `xweb:"/phone/bind"`      //绑定手机号
+    *xweb.Action
+    login     xweb.Mapper `xweb:"/phone/login"`     //登录
+    forgetPwd xweb.Mapper `xweb:"/phone/forgetPwd"` //忘记密码
+    register  xweb.Mapper `xweb:"/phone/register"`  //注册
+    phoneBind xweb.Mapper `xweb:"/phone/bind"`      //绑定手机号
 }
 
 var (
-	passwordReg = regexp.MustCompile(".{6,}")
+    passwordReg = regexp.MustCompile(".{6,}")
 )
 
 func init() {
-	xweb.AddAction(&Login{})
+    xweb.AddAction(&Login{})
 }
 
 func (l *Login) PhoneBind() error {
-	userId := qutil.ObjToString(l.GetSession("userId"))
-	if userId == "" {
-		return l.Redirect("/notin/page")
-	}
-	return l.Render("/login/phoneBind.html", &l.T)
+    userId := qutil.ObjToString(l.GetSession("userId"))
+    if userId == "" {
+        return l.Redirect("/notin/page")
+    }
+    return l.Render("/login/phoneBind.html", &l.T)
 }
 
 func (l *Login) Login() error {
-	defer qutil.Catch()
-	result := map[string]interface{}{}
-	reqType := l.GetString("reqType")
-	status := func() int {
-		if reqType == "phoneLogin" {
-			phone := l.GetString("phone")
-			password := l.GetString("password")
-			if strings.TrimSpace(phone) == "" {
-				return -1
-			} else if strings.TrimSpace(password) == "" {
-				return -2
-			}
-			user, ok := mongodb.FindOneByField("user", map[string]interface{}{
-				"i_appid": 2,
-				"s_phone": phone,
-			}, `{"s_password":1}`)
-			if ok && user != nil && len(*user) > 0 {
-				if qutil.ObjToString((*user)["s_password"]) == qutil.GetMd5String(password) {
-					ok, _, userInfo := afterLogin(phone, l.Session())
-					if ok {
-						result["userInfo"] = userInfo
-						return 1
-					}
-				} else {
-					return -2
-				}
-			} else {
-				return -1
-			}
-		} else if reqType == "sendIdentCode" {
-			register := l.GetString("register")
-			phone := l.GetString("phone")
-			//注册页面添加校验
-			if register != "" && mongodb.Count("user", map[string]interface{}{
-				"i_appid": 2,
-				"s_phone": phone,
-			}) > 0 {
-				return -3
-			}
-			if !phoneReg.MatchString(phone) {
-				return -1
-			} else if tmp := l.GetSession("CheckCodeId"); tmp == nil || !captcha.VerifyString(tmp.(string), l.GetString("code")) {
-				return -2
-			} else if jy.SendPhoneIdentCode(qutil.ObjToString(config.Sysconfig["smsServiceRpc"]), phone, l.Session()) {
-				return 1
-			}
-			return 0
-		} else if reqType == "identCodeLogin" {
-			phone, _ := l.GetSession("identCodeKey").(string)
-			if phone == "" || l.GetSession("identCodeValue") == nil || l.GetString("identCode") != l.GetSession("identCodeValue") { //验证码不正确
-				return -1
-			} else {
-				//用户不存在
-				datas, _ := mongodb.Find("user", map[string]interface{}{
-					"i_appid": 2,
-					"$or": []map[string]interface{}{
-						{"s_phone": phone},
-						{"s_m_phone": phone},
-					},
-				}, `{"s_phone":-1}`, `{"s_phone":1,"s_m_phone":1}`, false, 0, 1)
-				s_company := l.GetString("s_entname")
-				if datas == nil || len(*datas) == 0 { //不存在
-					data := map[string]interface{}{
-						"i_appid":       2,
-						"s_phone":       phone,
-						"s_password":    "",
-						"l_registedate": time.Now().Unix(),
-						"i_ts_guide":    2,
-						"s_company":     s_company,
-						"o_jy": map[string]interface{}{
-							"i_apppush": 1,
-							// "i_newfree":    1, //新免费用户=>新订阅设置页面 20211122
-							"i_ratemode":   2,
-							"l_modifydate": time.Now().Unix(),
-						},
-						"s_regsource": "pc",
-						"s_platform":  "pc",
-					}
-					//注册邮箱
-					email := l.GetString("email")
-					if jy.IsEmail(email) {
-						data["s_email"] = email
-					}
-					source := l.GetString("source") //用户手机号用户记录百度统计
-					if ck, err := l.GetCookie("source"); err == nil && ck.Value != "" {
-						//cookie中记录用户的来源
-						data["s_newsource"] = ck.Value
-						data["s_module"] = GetModule(ck.Value) //根据cookie中记录的来源获取模块
-					}
-					if source != "" {
-						data["s_tracksource"] = source
-					}
-					_id := mongodb.Save("user", data)
-					if _id != "" {
-						func(phone, userid string) {
-							//用户中台存储  开始
-							formdata := map[string]interface{}{
-								"appid": "10000",
-								"phone": phone,
-							}
-							if s_company != "" {
-								formdata["company"] = s_company
-							}
-							ck, _ := l.GetCookie("SESSIONID")
-							usercenter.AddBaseUser(mongodb, qutil.ObjToString(config.Sysconfig["userCenterApi"]), userid, formdata, ck)
-							//用户中台存储  结束
-						}(phone, _id)
-						jy.ClearPhoneIdentSession(l.Session())
-						ok, _, userInfo := afterLogin(phone, l.Session())
-						nsqPath, _ := config.Sysconfig["nsq"].(string)
-						nsq_topic, _ := config.Sysconfig["nsq_topic"].(string)
-						er := jy.Publish(public.Mgo_Log, nsqPath, nsq_topic, jy.Jypc_phone_register, _id, jy.Jyweb_node2)
-						if er != nil {
-							log.Println("nsq队列写入失败-->", jy.Jypc_phone_register, _id)
-						}
-						if ok {
-							result["userInfo"] = userInfo
-							return 1
-						}
-					}
-				} else {
-					//存在
-					//以s_m_phone登录的 需要把s_m_phone转化为s_phone
-					updataMap := map[string]interface{}{}
-					if s_company != "" {
-						updataMap["s_company"] = s_company
-					}
-					if (*datas)[0]["s_m_phone"] != nil {
-						updataMap["s_phone"] = phone
-					}
-					//注册邮箱
-					email := l.GetString("email")
-					if jy.IsEmail(email) {
-						updataMap["s_email"] = email
-					}
-					if len(updataMap) > 0 {
-						mongodb.UpdateById("user", BsonIdToSId((*datas)[0]["_id"]), map[string]interface{}{
-							"$set":   updataMap,
-							"$unset": map[string]interface{}{"s_m_phone": ""},
-						})
-					}
+    defer qutil.Catch()
+    result := map[string]interface{}{}
+    reqType := l.GetString("reqType")
+    status := func() int {
+        if reqType == "phoneLogin" {
+            phone := l.GetString("phone")
+            password := l.GetString("password")
+            if strings.TrimSpace(phone) == "" {
+                return -1
+            } else if strings.TrimSpace(password) == "" {
+                return -2
+            }
+            user, ok := mongodb.FindOneByField("user", map[string]interface{}{
+                "i_appid": 2,
+                "s_phone": phone,
+            }, `{"s_password":1}`)
+            if user != nil && len(*user) > 0  && ok{
+                if qutil.ObjToString((*user)["s_password"]) == qutil.GetMd5String(password) {
+                    ok, _, userInfo := afterLogin(phone, l.Session())
+                    if ok {
+                        result["userInfo"] = userInfo
+                        return 1
+                    }
+                } else {
+                    return -2
+                }
+            } else {
+                return -1
+            }
+        } else if reqType == "sendIdentCode" {
+            register := l.GetString("register")
+            phone := l.GetString("phone")
+            //注册页面添加校验
+            if register != "" && mongodb.Count("user", map[string]interface{}{
+                "i_appid": 2,
+                "s_phone": phone,
+            }) > 0 {
+                return -3
+            }
+            if !phoneReg.MatchString(phone) {
+                return -1
+            } else if tmp := l.GetSession("CheckCodeId"); tmp == nil || !captcha.VerifyString(tmp.(string), l.GetString("code")) {
+                return -2
+            } else if jy.SendPhoneIdentCode(qutil.ObjToString(config.Sysconfig["smsServiceRpc"]), phone, l.Session()) {
+                return 1
+            }
+            return 0
+        } else if reqType == "identCodeLogin" {
+            phone, _ := l.GetSession("identCodeKey").(string)
+            if phone == "" || l.GetSession("identCodeValue") == nil || l.GetString("identCode") != l.GetSession("identCodeValue") { //验证码不正确
+                return -1
+            } else {
+                //用户不存在
+                datas, _ := mongodb.Find("user", map[string]interface{}{
+                    "i_appid": 2,
+                    "$or": []map[string]interface{}{
+                        {"s_phone": phone},
+                        {"s_m_phone": phone},
+                    },
+                }, `{"s_phone":-1}`, `{"s_phone":1,"s_m_phone":1}`, false, 0, 1)
+                s_company := l.GetString("s_entname")
+                if datas == nil || len(*datas) == 0 { //不存在
+                    data := map[string]interface{}{
+                        "i_appid":       2,
+                        "s_phone":       phone,
+                        "s_password":    "",
+                        "l_registedate": time.Now().Unix(),
+                        "i_ts_guide":    2,
+                        "s_company":     s_company,
+                        "o_jy": map[string]interface{}{
+                            "i_apppush": 1,
+                            // "i_newfree":    1, //新免费用户=>新订阅设置页面 20211122
+                            "i_ratemode":   2,
+                            "l_modifydate": time.Now().Unix(),
+                        },
+                        "s_regsource": "pc",
+                        "s_platform":  "pc",
+                    }
+                    //注册邮箱
+                    email := l.GetString("email")
+                    if jy.IsEmail(email) {
+                        data["s_email"] = email
+                    }
+                    source := l.GetString("source") //用户手机号用户记录百度统计
+                    if ck, err := l.GetCookie("source"); err == nil && ck.Value != "" {
+                        //cookie中记录用户的来源
+                        data["s_newsource"] = ck.Value
+                        data["s_module"] = GetModule(ck.Value) //根据cookie中记录的来源获取模块
+                    }
+                    if source != "" {
+                        data["s_tracksource"] = source
+                    }
+                    _id := mongodb.Save("user", data)
+                    if _id != "" {
+                        func(phone, userid string) {
+                            //用户中台存储  开始
+                            formdata := map[string]interface{}{
+                                "appid": "10000",
+                                "phone": phone,
+                            }
+                            if s_company != "" {
+                                formdata["company"] = s_company
+                            }
+                            ck, _ := l.GetCookie("SESSIONID")
+                            usercenter.AddBaseUser(mongodb, qutil.ObjToString(config.Sysconfig["userCenterApi"]), userid, formdata, ck)
+                            //用户中台存储  结束
+                        }(phone, _id)
+                        jy.ClearPhoneIdentSession(l.Session())
+                        ok, _, userInfo := afterLogin(phone, l.Session())
+                        nsqPath, _ := config.Sysconfig["nsq"].(string)
+                        nsq_topic, _ := config.Sysconfig["nsq_topic"].(string)
+                        er := jy.Publish(public.Mgo_Log, nsqPath, nsq_topic, jy.Jypc_phone_register, _id, jy.Jyweb_node2)
+                        if er != nil {
+                            log.Println("nsq队列写入失败-->", jy.Jypc_phone_register, _id)
+                        }
+                        if ok {
+                            result["userInfo"] = userInfo
+                            return 1
+                        }
+                    }
+                } else {
+                    //存在
+                    //以s_m_phone登录的 需要把s_m_phone转化为s_phone
+                    updataMap := map[string]interface{}{}
+                    if s_company != "" {
+                        updataMap["s_company"] = s_company
+                    }
+                    if (*datas)[0]["s_m_phone"] != nil {
+                        updataMap["s_phone"] = phone
+                    }
+                    //注册邮箱
+                    email := l.GetString("email")
+                    if jy.IsEmail(email) {
+                        updataMap["s_email"] = email
+                    }
+                    if len(updataMap) > 0 {
+                        jyutil.Compatible.Update(BsonIdToSId((*datas)[0]["_id"]), map[string]interface{}{
+                            "$set":   updataMap,
+                            "$unset": map[string]interface{}{"s_m_phone": ""},
+                        })
+                    }
 
-					jy.ClearPhoneIdentSession(l.Session())
-					ok, _, userInfo := afterLogin(phone, l.Session())
-					if ok {
-						result["userInfo"] = userInfo
-						return 1
-					}
-				}
-			}
-		}
-		return 0
-	}()
-	result["status"] = status
-	l.ServeJson(result)
-	return nil
+                    jy.ClearPhoneIdentSession(l.Session())
+                    ok, _, userInfo := afterLogin(phone, l.Session())
+                    if ok {
+                        result["userInfo"] = userInfo
+                        return 1
+                    }
+                }
+            }
+        }
+        return 0
+    }()
+    result["status"] = status
+    l.ServeJson(result)
+    return nil
 }
 
 func (l *Login) Register() error {
-	return l.Render("/login/register.html", &l.T)
+    return l.Render("/login/register.html", &l.T)
 }
 
 // ForgetPwd 忘记密码
 func (l *Login) ForgetPwd() error {
-	defer qutil.Catch()
-	if l.Method() == "GET" {
-		var shareid = l.GetString("id")
-		if len(shareid) == 0 {
-			shareid = "10"
-		}
-		l.T["logid"] = config.Seoconfig["wjmm"].(string)
-		l.T["shareid"] = se.EncodeString(shareid)
-		return l.Render("/login/forgetPwd.html", &l.T)
-	}
-	status := func() string {
-		reqType := l.GetString("reqType")
-		if reqType == "sendIdentCode" { //发短信
-			phone := l.GetString("phone") //手机号
-			//手机号验证不通过
-			if !phoneReg.MatchString(phone) {
-				return "phoneError"
-			}
-			if tmp := l.GetSession("CheckCodeId"); tmp == nil || !captcha.VerifyString(tmp.(string), l.GetString("code")) {
-				return "codeError"
-			}
-			//手机号是否已被注册
-			if !phoneIsExists(phone) {
-				return "phoneNotExists"
-			} else if jy.SendPhoneIdentCode(qutil.ObjToString(config.Sysconfig["smsServiceRpc"]), phone, l.Session()) {
-				return "y"
-			}
-		} else if reqType == "nextStep" {
-			if l.GetSession("identCodeValue") == nil || l.GetString("identCode") != l.GetSession("identCodeValue") { //验证码不正确
-				return "identCodeError"
-			}
-			l.SetSession("forgetPwdStep", "2")
-			return "y"
-		} else if reqType == "save" {
-			if l.GetSession("forgetPwdStep") == nil {
-				return "error"
-			}
-			phone, _ := l.GetSession("identCodeKey").(string)
-			if phone == "" {
-				return "timeout"
-			}
-			password := strings.TrimSpace(l.GetString("password"))
-			if !passwordReg.MatchString(password) {
-				return "passwordError"
-			}
-			ok, user := getPhoneUser(phone)
-			if !ok || user == nil || len(user) == 0 {
-				return "userNotExists"
-			}
-			oldpwd, _ := user["s_password"].(string)
-			if oldpwd == qutil.GetMd5String(password) {
-				return "passwordRepeat"
-			}
-			if mongodb.Update("user", map[string]interface{}{
-				"_id": user["_id"],
-			}, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"s_phone":         phone,
-					"s_password":      qutil.GetMd5String(password),
-					"l_updatepwdtime": time.Now().Unix(),
-				},
-				"$unset": map[string]interface{}{
-					"s_m_phone": "",
-				}}, false, false) {
-				userid := BsonIdToSId(user["_id"])
-				//用户中台存储  开始
-				ck, _ := l.GetCookie("SESSIONID")
-				usercenter.UpdateBaseUser(mongodb, qutil.ObjToString(config.Sysconfig["userCenterApi"]), userid, ck)
+    defer qutil.Catch()
+    if l.Method() == "GET" {
+        var shareid = l.GetString("id")
+        if len(shareid) == 0 {
+            shareid = "10"
+        }
+        l.T["logid"] = config.Seoconfig["wjmm"].(string)
+        l.T["shareid"] = se.EncodeString(shareid)
+        return l.Render("/login/forgetPwd.html", &l.T)
+    }
+    status := func() string {
+        reqType := l.GetString("reqType")
+        if reqType == "sendIdentCode" { //发短信
+            phone := l.GetString("phone") //手机号
+            //手机号验证不通过
+            if !phoneReg.MatchString(phone) {
+                return "phoneError"
+            }
+            if tmp := l.GetSession("CheckCodeId"); tmp == nil || !captcha.VerifyString(tmp.(string), l.GetString("code")) {
+                return "codeError"
+            }
+            //手机号是否已被注册
+            if !phoneIsExists(phone) {
+                return "phoneNotExists"
+            } else if jy.SendPhoneIdentCode(qutil.ObjToString(config.Sysconfig["smsServiceRpc"]), phone, l.Session()) {
+                return "y"
+            }
+        } else if reqType == "nextStep" {
+            if l.GetSession("identCodeValue") == nil || l.GetString("identCode") != l.GetSession("identCodeValue") { //验证码不正确
+                return "identCodeError"
+            }
+            l.SetSession("forgetPwdStep", "2")
+            return "y"
+        } else if reqType == "save" {
+            if l.GetSession("forgetPwdStep") == nil {
+                return "error"
+            }
+            phone, _ := l.GetSession("identCodeKey").(string)
+            if phone == "" {
+                return "timeout"
+            }
+            password := strings.TrimSpace(l.GetString("password"))
+            if !passwordReg.MatchString(password) {
+                return "passwordError"
+            }
+            ok, user := getPhoneUser(phone)
+            if !ok || user == nil || len(user) == 0 {
+                return "userNotExists"
+            }
+            oldpwd, _ := user["s_password"].(string)
+            if oldpwd == qutil.GetMd5String(password) {
+                return "passwordRepeat"
+            }
+            if jyutil.Compatible.Update(qutil.ObjToString(user["_id"]), map[string]interface{}{
+                "$set": map[string]interface{}{
+                    "s_phone":         phone,
+                    "s_password":      qutil.GetMd5String(password),
+                    "l_updatepwdtime": time.Now().Unix(),
+                },
+                "$unset": map[string]interface{}{
+                    "s_m_phone": "",
+                }}) {
+                userid := BsonIdToSId(user["_id"])
+                //用户中台存储  开始
+                ck, _ := l.GetCookie("SESSIONID")
+                usercenter.UpdateBaseUser(mongodb, qutil.ObjToString(config.Sysconfig["userCenterApi"]), userid, ck)
 
-				//用户中台存储  结束
-				l.DelSession("forgetPwdStep")
-				jy.ClearPhoneIdentSession(l.Session())
-				return "y"
-			}
-			return "saveError"
-		}
-		return "n"
-	}()
-	//返回
-	l.ServeJson(map[string]string{
-		"status": status,
-	})
-	return nil
+                //用户中台存储  结束
+                l.DelSession("forgetPwdStep")
+                jy.ClearPhoneIdentSession(l.Session())
+                return "y"
+            }
+            return "saveError"
+        }
+        return "n"
+    }()
+    //返回
+    l.ServeJson(map[string]string{
+        "status": status,
+    })
+    return nil
 }
 
 /**********************************************************************
 ***********************************************************************
 ***********************************************************************/
 func phoneIsExists(phone string) bool {
-	return mongodb.Count("user", map[string]interface{}{
-		"i_appid": 2,
-		"$or": []map[string]interface{}{
-			{"s_phone": phone},
-			{"s_m_phone": phone}},
-	}) > 0
+    return mongodb.Count("user", map[string]interface{}{
+        "i_appid": 2,
+        "$or": []map[string]interface{}{
+            {"s_phone": phone},
+            {"s_m_phone": phone}},
+    }) > 0
 }
 
 func getPhoneUser(phone string) (bool, map[string]interface{}) {
-	datas, ok := mongodb.Find("user", map[string]interface{}{
-		"i_appid": 2,
-		"$or": []map[string]interface{}{
-			{"s_phone": phone},
-			{"s_m_phone": phone},
-		},
-	}, `{"s_phone":-1}`, `{"_id":1,"s_password":1}`, false, 0, 1)
-	if datas != nil && len(*datas) > 0 {
-		return ok, (*datas)[0]
-	}
-	return ok, nil
+    datas, ok := mongodb.Find("user", map[string]interface{}{
+        "i_appid": 2,
+        "$or": []map[string]interface{}{
+            {"s_phone": phone},
+            {"s_m_phone": phone},
+        },
+    }, `{"s_phone":-1}`, `{"_id":1,"s_password":1}`, false, 0, 1)
+    if datas != nil && len(*datas) > 0 {
+        return ok, (*datas)[0]
+    }
+    return ok, nil
 }
 
 // 手机号用户是否存在
 func userIsExists(phoneNum string) bool {
-	query := map[string]interface{}{
-		"s_phone": phoneNum,
-		"i_appid": 2,
-	}
-	return mongodb.Count("user", query) > 0
+    query := map[string]interface{}{
+        "s_phone": phoneNum,
+        "i_appid": 2,
+    }
+    return mongodb.Count("user", query) > 0
 }
 
 func afterLogin(phone string, session *httpsession.Session) (bool, *map[string]interface{}, map[string]interface{}) {
-	ok, user := getPhoneUser(phone)
-	if !ok {
-		return false, nil, nil
-	}
-	if user == nil || len(user) == 0 {
-		return false, nil, nil
-	}
-	return FindUserAndCreateSessById(user["_id"].(primitive.ObjectID), session, true)
+    ok, user := getPhoneUser(phone)
+    if !ok {
+        return false, nil, nil
+    }
+    if user == nil || len(user) == 0 {
+        return false, nil, nil
+    }
+    return FindUserAndCreateSessById(user["_id"].(primitive.ObjectID), session, true)
 }
 
 func GetModule(source string) string {
-	sourceModuleMap, _ := config.Seoconfig["cookieSource"].(map[string]interface{})
-	return qutil.ObjToString(sourceModuleMap[source])
+    sourceModuleMap, _ := config.Seoconfig["cookieSource"].(map[string]interface{})
+    return qutil.ObjToString(sourceModuleMap[source])
 }
 
 // 当前用户是否存在
 func isExistsByPO(phone, openId string) bool {
-	return mongodb.Count("user", map[string]interface{}{
-		"i_appid": 2,
-		"$or": []map[string]interface{}{
-			{"s_phone": phone},
-			{"s_m_phone": phone},
-			{"s_m_openid": openId},
-		},
-	}) > 0
+    return mongodb.Count("user", map[string]interface{}{
+        "i_appid": 2,
+        "$or": []map[string]interface{}{
+            {"s_phone": phone},
+            {"s_m_phone": phone},
+            {"s_m_openid": openId},
+        },
+    }) > 0
 }

+ 1 - 1
src/jfw/front/pchelper.go

@@ -165,7 +165,7 @@ func (l *PcHelper) Login() error {
 							updataMap["s_phone"] = phone
 						}
 						if len(updataMap) > 0 {
-							mongodb.UpdateById("user", BsonIdToSId((*datas)[0]["_id"]), map[string]interface{}{
+                            jyutil.Compatible.Update( BsonIdToSId((*datas)[0]["_id"]), map[string]interface{}{
 								"$set":   updataMap,
 								"$unset": map[string]interface{}{"s_m_phone": ""},
 							})

+ 1 - 1
src/jfw/front/search.go

@@ -130,7 +130,7 @@ func (s *Search) GetHK() error {
 			history = strings.Split(h, ",")
 		}
 		//我的订阅
-		one, _ := mongodb.FindById("user", userid.(string), `{"o_jy":1}`)
+		one:=jyutil.Compatible.Select( userid.(string), `{"o_jy":1}`)
 		if one != nil && len(*one) > 0 {
 			o_jy, _ := (*one)["o_jy"].(map[string]interface{})
 			a_key, _ := o_jy["a_key"].([]interface{})

+ 4 - 4
src/jfw/front/shorturl.go

@@ -224,7 +224,7 @@ func (s *Short) Article(stype, id string) error {
 		}
 	} else if userId != "" {
 		//判断用户是否是vip
-		res, ok = public.MQFW.FindById("user", userId, `{"i_vip_status":1,"i_member_status":1,"s_m_phone":1,"s_phone":1,"l_vip_starttime":1}`)
+		res = jyutil.Compatible.Select( userId, `{"i_vip_status":1,"i_member_status":1,"s_m_phone":1,"s_phone":1,"l_vip_starttime":1}`)
 	}
 	entid := util.Int64All(s.GetSession("entId"))
 	userPower := jy.GetBigVipUserBaseMsg( s.Session(), *config.Middleground)
@@ -237,7 +237,7 @@ func (s *Short) Article(stype, id string) error {
 		privatedata   bool = userPower.PrivateGD          //广东移动DICT 用户
 		isEntService  bool = userPower.IsEntService       //商机管理服务
 	)
-	if ok && res != nil && len(*res) > 0 {
+	if res != nil && len(*res) > 0 {
 		if isVip && util.Int64All((*res)["l_vip_starttime"]) < util.Int64All(config.Sysconfig["contextOldVipLimit"]) {
 			isOldVip = true
 		}
@@ -559,7 +559,7 @@ func CNode(userId string) bool {
 		delete(rM, "createtime")
 		delete(rM, "client")
 	}
-	if userinfo, ok := mongodb.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,"s_myemail":1,"s_company":1,"o_jy":1,"o_vipjy":1}`); userinfo != nil && ok && len(*userinfo) > 0 {
+	if userinfo :=jyutil.Compatible.Select( userId, `{"s_phone":1,"s_m_phone":1,"s_myemail":1,"s_company":1,"o_jy":1,"o_vipjy":1}`); userinfo != nil && len(*userinfo) > 0 {
 		s_phone := util.ObjToString((*userinfo)["s_phone"])
 		phone := util.If(s_phone == "", util.ObjToString((*userinfo)["s_m_phone"]), s_phone)
 		if rM["phone"] == nil || rM["phone"] == "" {
@@ -641,7 +641,7 @@ func UserPermission(userId string, ssOpenid interface{}) (bool, bool, bool) {
 		userId = BsonIdToSId((*res)["_id"])
 	} else {
 		//判断用户是否是vip
-		res, _ = public.MQFW.FindById("user", userId, `{"i_vip_status":1,"i_member_status":1,"s_m_phone":1,"s_phone":1}`)
+		res = jyutil.Compatible.Select( userId, `{"i_vip_status":1,"i_member_status":1,"s_m_phone":1,"s_phone":1}`)
 	}
 
 	isVip = util.IntAll((*res)["i_vip_status"]) == 1 || util.IntAll((*res)["i_vip_status"]) == 2

+ 322 - 325
src/jfw/front/structedData.go

@@ -1,382 +1,379 @@
 package front
 
 import (
-	"fmt"
-	"jy/src/jfw/config"
-	"log"
-	"strings"
-	"time"
+    "fmt"
+    "jy/src/jfw/config"
+    "jy/src/jfw/jyutil"
+    "log"
+    "strings"
+    "time"
 
-	"app.yhyue.com/moapp/jypkg/public"
+    "app.yhyue.com/moapp/jypkg/public"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/redis"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/redis"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"go.mongodb.org/mongo-driver/bson"
-	"go.mongodb.org/mongo-driver/bson/primitive"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type StructedData struct {
-	*xweb.Action
-	index      xweb.Mapper `xweb:"/front/structed/index"`     //数据结构化首页
-	writeInfo  xweb.Mapper `xweb:"/front/structed/writeinfo"` //信息填写
-	checkUser  xweb.Mapper `xweb:"/front/structed/checkuser"`
-	success    xweb.Mapper `xweb:"/front/structed/success"`    //信息填写成功
-	saveData   xweb.Mapper `xweb:"/front/structed/savedata"`   //数据结构化保存用户
-	getPreview xweb.Mapper `xweb:"/front/structed/getpreview"` //数据结构化预览
-	//dev2.10.10
-	pc_index       xweb.Mapper `xweb:"/front/structed/pc_index.html"`  //pc端结构化数据首页
-	pc_info        xweb.Mapper `xweb:"/front/structed/pc_info.html"`   //pc端结构化数据信息页面
-	freeSamples    xweb.Mapper `xweb:"/front/structed/freeSamples"`    //数据结构化保存免费样例数据
-	verifyCode     xweb.Mapper `xweb:"/front/structed/verifyCode"`     //数据结构化验证邮箱验证码
-	sendMailVerify xweb.Mapper `xweb:"/front/structed/sendMailVerify"` //数据结构化发送邮箱验证码
-	verifyEmail    xweb.Mapper `xweb:"/front/structed/verifyEmail"`    //数据结构化验证邮箱是否验证过
+    *xweb.Action
+    index      xweb.Mapper `xweb:"/front/structed/index"`     //数据结构化首页
+    writeInfo  xweb.Mapper `xweb:"/front/structed/writeinfo"` //信息填写
+    checkUser  xweb.Mapper `xweb:"/front/structed/checkuser"`
+    success    xweb.Mapper `xweb:"/front/structed/success"`    //信息填写成功
+    saveData   xweb.Mapper `xweb:"/front/structed/savedata"`   //数据结构化保存用户
+    getPreview xweb.Mapper `xweb:"/front/structed/getpreview"` //数据结构化预览
+    //dev2.10.10
+    pc_index       xweb.Mapper `xweb:"/front/structed/pc_index.html"`  //pc端结构化数据首页
+    pc_info        xweb.Mapper `xweb:"/front/structed/pc_info.html"`   //pc端结构化数据信息页面
+    freeSamples    xweb.Mapper `xweb:"/front/structed/freeSamples"`    //数据结构化保存免费样例数据
+    verifyCode     xweb.Mapper `xweb:"/front/structed/verifyCode"`     //数据结构化验证邮箱验证码
+    sendMailVerify xweb.Mapper `xweb:"/front/structed/sendMailVerify"` //数据结构化发送邮箱验证码
+    verifyEmail    xweb.Mapper `xweb:"/front/structed/verifyEmail"`    //数据结构化验证邮箱是否验证过
 }
 
 func init() {
-	xweb.AddAction(&StructedData{})
+    xweb.AddAction(&StructedData{})
 }
 
 //验证邮箱的正确性
 func (t *StructedData) VerifyEmail() {
-	defer util.Catch()
-	msg := "请求方式有误"
-	status := false
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		email := t.GetString("email")
-		msg = "参数有误"
-		if email != "" {
-			msg = "未登录"
-			if userId != "" {
-				emails := public.Mysql.FindOne("dataexport_order", map[string]interface{}{
-					"user_mail":    email,
-					"user_id":      userId,
-					"product_type": "历史数据",
-				}, "user_mail", "")
-				//是否是绑定邮箱或者是数据导出邮箱  验证过的邮箱
-				if (emails != nil && util.ObjToString((*emails)["user_mail"]) != "") || (t.GetSession("s_myemail") != nil && email == t.GetSession("s_myemail").(string)) || (t.GetSession("SMVerifySucess") != nil && t.GetSession("SMVerifySucess").(bool) && email == t.GetSession("DataSMVerifyEmail")) {
-					status = true
-					msg = "此邮箱已被验证"
-					t.SetSession("SMVerifySucess", true)
-				} else {
-					msg = "未被验证"
-				}
-			}
-		}
-	}
+    defer util.Catch()
+    msg := "请求方式有误"
+    status := false
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        email := t.GetString("email")
+        msg = "参数有误"
+        if email != "" {
+            msg = "未登录"
+            if userId != "" {
+                emails := public.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                    "user_mail":    email,
+                    "user_id":      userId,
+                    "product_type": "历史数据",
+                }, "user_mail", "")
+                //是否是绑定邮箱或者是数据导出邮箱  验证过的邮箱
+                if (emails != nil && util.ObjToString((*emails)["user_mail"]) != "") || (t.GetSession("s_myemail") != nil && email == t.GetSession("s_myemail").(string)) || (t.GetSession("SMVerifySucess") != nil && t.GetSession("SMVerifySucess").(bool) && email == t.GetSession("DataSMVerifyEmail")) {
+                    status = true
+                    msg = "此邮箱已被验证"
+                    t.SetSession("SMVerifySucess", true)
+                } else {
+                    msg = "未被验证"
+                }
+            }
+        }
+    }
 
-	t.ServeJson(map[string]interface{}{
-		"msg":    msg,
-		"status": status,
-	})
+    t.ServeJson(map[string]interface{}{
+        "msg":    msg,
+        "status": status,
+    })
 }
 
 //验证 验证码的正确性
 func (t *StructedData) VerifyCode() {
-	defer util.Catch()
-	msg := "请求方式有误"
-	status := false
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		msg = "未登录"
-		if userId != "" {
-			s_email := t.GetString("s_email")       //邮箱
-			verifyCode := t.GetString("verifyCode") //验证码
-			VerifyEmail := util.ObjToString(t.GetSession("DataSMVerifyEmail"))
-			if verifyCode != "" && s_email != "" && VerifyEmail != "" {
-				if s_email == VerifyEmail {
-					msg = "验证码正确"
-					status = true
-					SMVerifySucess := t.GetSession("SMVerifySucess")
-					//需验证邮箱
-					if SMVerifySucess != nil && !SMVerifySucess.(bool) {
-						//验证码
-						verifyStr := t.GetSession("DataSMVerify")
-						//是否超时
-						lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
-						timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
-						if lastSendDEVerify == 0 || timeSpaceing < 0 {
-							msg = "验证码超时"
-							status = false
-						} else if verifyStr != verifyCode {
-							msg = "验证码有误"
-							status = false
-						} else {
-							t.SetSession("SMVerifySucess", true)
-						}
-					}
-				} else {
-					msg = "验证码有误"
-					status = false
-				}
-			}
-		}
-	}
-	t.ServeJson(map[string]interface{}{
-		"msg":    msg,
-		"status": status,
-	})
+    defer util.Catch()
+    msg := "请求方式有误"
+    status := false
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        msg = "未登录"
+        if userId != "" {
+            s_email := t.GetString("s_email")       //邮箱
+            verifyCode := t.GetString("verifyCode") //验证码
+            VerifyEmail := util.ObjToString(t.GetSession("DataSMVerifyEmail"))
+            if verifyCode != "" && s_email != "" && VerifyEmail != "" {
+                if s_email == VerifyEmail {
+                    msg = "验证码正确"
+                    status = true
+                    SMVerifySucess := t.GetSession("SMVerifySucess")
+                    //需验证邮箱
+                    if SMVerifySucess != nil && !SMVerifySucess.(bool) {
+                        //验证码
+                        verifyStr := t.GetSession("DataSMVerify")
+                        //是否超时
+                        lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
+                        timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
+                        if lastSendDEVerify == 0 || timeSpaceing < 0 {
+                            msg = "验证码超时"
+                            status = false
+                        } else if verifyStr != verifyCode {
+                            msg = "验证码有误"
+                            status = false
+                        } else {
+                            t.SetSession("SMVerifySucess", true)
+                        }
+                    }
+                } else {
+                    msg = "验证码有误"
+                    status = false
+                }
+            }
+        }
+    }
+    t.ServeJson(map[string]interface{}{
+        "msg":    msg,
+        "status": status,
+    })
 }
 
 //保存免费样例数据
 func (t *StructedData) FreeSamples() error {
-	defer util.Catch()
-	msg := "请求方式有误"
-	status := false
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		if userId != "" {
-			name := t.GetString("name")                      //联系人
-			phone_num := t.GetString("phone_num")            //手机号
-			s_email := t.GetString("s_email")                //邮箱
-			SMVerifySucess := t.GetSession("SMVerifySucess") //邮箱是否验证成功
-			if name != "" && phone_num != "" && s_email != "" && SMVerifySucess != nil && SMVerifySucess.(bool) {
-				count := public.Mysql.Count("structed_data", map[string]interface{}{
-					"name":  name,
-					"phone": phone_num,
-					"email": s_email,
-					"type":  1,
-				})
-				if count >= 1 {
-					msg = "用户信息已存在"
-					status = true
-				} else {
-					source := t.GetString("source")
-					insertMap := map[string]interface{}{
-						"name":        name,
-						"phone":       phone_num,
-						"email":       s_email,
-						"submit_time": time.Now().Unix(),
-						"status":      0,
-						"type":        1, //用户来源,0:联系客服,1:免费样例,2:自选购买
-					}
-					if source != "" {
-						insertMap["source"] = source
-					}
-					stu := public.Mysql.Insert("structed_data", insertMap)
-					if stu == 0 {
-						msg = "数据库操作异常"
-						status = false
-					} else {
-						//保存成功后 删除验证成功记录 和 发送验证码时间
-						t.DelSession("SMVerifySucess")
-						t.DelSession("CreatSMVerifyTime")
-						t.DelSession("DataSMVerifyEmail")
-						msg = "保存成功"
-						status = true
-						go public.SendStructedDataByEmail(s_email, config.GmailAuth, config.Sysconfig, config.Seoconfig)
-					}
-				}
-			} else {
-				msg = "缺少参数"
-				status = false
-			}
-		}
-	}
-	t.ServeJson(map[string]interface{}{
-		"msg":    msg,
-		"status": status,
-	})
-	return nil
+    defer util.Catch()
+    msg := "请求方式有误"
+    status := false
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        if userId != "" {
+            name := t.GetString("name")                      //联系人
+            phone_num := t.GetString("phone_num")            //手机号
+            s_email := t.GetString("s_email")                //邮箱
+            SMVerifySucess := t.GetSession("SMVerifySucess") //邮箱是否验证成功
+            if name != "" && phone_num != "" && s_email != "" && SMVerifySucess != nil && SMVerifySucess.(bool) {
+                count := public.Mysql.Count("structed_data", map[string]interface{}{
+                    "name":  name,
+                    "phone": phone_num,
+                    "email": s_email,
+                    "type":  1,
+                })
+                if count >= 1 {
+                    msg = "用户信息已存在"
+                    status = true
+                } else {
+                    source := t.GetString("source")
+                    insertMap := map[string]interface{}{
+                        "name":        name,
+                        "phone":       phone_num,
+                        "email":       s_email,
+                        "submit_time": time.Now().Unix(),
+                        "status":      0,
+                        "type":        1, //用户来源,0:联系客服,1:免费样例,2:自选购买
+                    }
+                    if source != "" {
+                        insertMap["source"] = source
+                    }
+                    stu := public.Mysql.Insert("structed_data", insertMap)
+                    if stu == 0 {
+                        msg = "数据库操作异常"
+                        status = false
+                    } else {
+                        //保存成功后 删除验证成功记录 和 发送验证码时间
+                        t.DelSession("SMVerifySucess")
+                        t.DelSession("CreatSMVerifyTime")
+                        t.DelSession("DataSMVerifyEmail")
+                        msg = "保存成功"
+                        status = true
+                        go public.SendStructedDataByEmail(s_email, config.GmailAuth, config.Sysconfig, config.Seoconfig)
+                    }
+                }
+            } else {
+                msg = "缺少参数"
+                status = false
+            }
+        }
+    }
+    t.ServeJson(map[string]interface{}{
+        "msg":    msg,
+        "status": status,
+    })
+    return nil
 }
 
 //必须登录
 func (t *StructedData) Pc_info() error {
-	defer util.Catch()
-	userId := util.ObjToString(t.GetSession("userId"))
-	if userId != "" {
-		//删除验证成功记录 和 发送验证码时间 邮箱
-		t.DelSession("SMVerifySucess")
-		t.DelSession("CreatSMVerifyTime")
-		t.DelSession("DataSMVerifyEmail")
-		_id, _ := primitive.ObjectIDFromHex(userId)
-		nums, ok := public.MQFW.FindOne("user", bson.M{"_id": _id})
-		if !ok {
-			return t.Redirect("/front/aboutus.html")
-		}
-		if _, ok := (*nums)["s_phone"]; ok {
-			t.T["phone_num"] = (*nums)["s_phone"].(string)
-		}
-		if _, ok := (*nums)["s_myemail"]; ok {
-			t.T["s_myemail"] = (*nums)["s_myemail"].(string)
-			//验证是否是绑定的邮箱
-			t.SetSession("s_myemail", (*nums)["s_myemail"].(string))
-			t.SetSession("DataSMVerifyEmail", (*nums)["s_myemail"].(string))
-			t.SetSession("SMVerifySucess", true)
-		}
-		return t.Render("/structuredata/pc/info.html", &t.T)
-	} else {
-		return t.Redirect("/front/aboutus.html")
-	}
+    defer util.Catch()
+    userId := util.ObjToString(t.GetSession("userId"))
+    if userId != "" {
+        //删除验证成功记录 和 发送验证码时间 邮箱
+        t.DelSession("SMVerifySucess")
+        t.DelSession("CreatSMVerifyTime")
+        t.DelSession("DataSMVerifyEmail")
+        nums := jyutil.Compatible.Select(userId, `{"s_phone":1,"s_myemail":1}`)
+        if nums == nil {
+            return t.Redirect("/front/aboutus.html")
+        }
+        if _, ok := (*nums)["s_phone"]; ok {
+            t.T["phone_num"] = (*nums)["s_phone"].(string)
+        }
+        if _, ok := (*nums)["s_myemail"]; ok {
+            t.T["s_myemail"] = (*nums)["s_myemail"].(string)
+            //验证是否是绑定的邮箱
+            t.SetSession("s_myemail", (*nums)["s_myemail"].(string))
+            t.SetSession("DataSMVerifyEmail", (*nums)["s_myemail"].(string))
+            t.SetSession("SMVerifySucess", true)
+        }
+        return t.Render("/structuredata/pc/info.html", &t.T)
+    } else {
+        return t.Redirect("/front/aboutus.html")
+    }
 }
 
 //可以不登录
 func (t *StructedData) Pc_index() error {
-	t.T["source"] = "wx_sy_dh_4"
-	return t.Render("/structuredata/pc/index.html", &t.T)
+    t.T["source"] = "wx_sy_dh_4"
+    return t.Render("/structuredata/pc/index.html", &t.T)
 }
 func (t *StructedData) Index() error {
-	t.T["source"] = "wx_sy_dh_4"
-	return t.Render("/structuredata/mobile/marketing_wx.html", &t.T)
+    t.T["source"] = "wx_sy_dh_4"
+    return t.Render("/structuredata/mobile/marketing_wx.html", &t.T)
 }
 
 //信息填写
 func (t *StructedData) WriteInfo() error {
-	return t.Render("/structuredata/mobile/write_info.html")
+    return t.Render("/structuredata/mobile/write_info.html")
 }
 
 //结构化数据预览
 func (t *StructedData) GetPreview() error {
-	return t.Render("/structuredata/mobile/preview.html")
+    return t.Render("/structuredata/mobile/preview.html")
 }
 func (t *StructedData) Success() error {
-	//删除验证成功记录 和 发送验证码时间 邮箱
-	t.DelSession("SMVerifySucess")
-	t.DelSession("CreatSMVerifyTime")
-	t.DelSession("DataSMVerifyEmail")
-	return t.Render("/structuredata/mobile/write_result.html")
+    //删除验证成功记录 和 发送验证码时间 邮箱
+    t.DelSession("SMVerifySucess")
+    t.DelSession("CreatSMVerifyTime")
+    t.DelSession("DataSMVerifyEmail")
+    return t.Render("/structuredata/mobile/write_result.html")
 }
 func (t *StructedData) CheckUser() error {
-	userId := util.ObjToString(t.GetSession("userId"))
-	if userId != "" {
-		//删除验证成功记录 和 发送验证码时间 邮箱
-		t.DelSession("SMVerifySucess")
-		t.DelSession("CreatSMVerifyTime")
-		t.DelSession("DataSMVerifyEmail")
-		_id, _ := primitive.ObjectIDFromHex(userId)
-		nums, ok := public.MQFW.FindOne("user", bson.M{"_id": _id})
-		if !ok {
-			return t.Redirect("/swordfish/about?source=open_infocontent&o=-130")
-		}
-		if _, ok := (*nums)["s_phone"]; ok {
-			t.T["phone_num"] = (*nums)["s_phone"].(string)
-		}
-		if _, ok := (*nums)["s_myemail"]; ok {
-			t.T["s_myemail"] = (*nums)["s_myemail"].(string)
-			//验证是否是绑定的邮箱
-			t.SetSession("s_myemail", (*nums)["s_myemail"].(string))
-			t.SetSession("DataSMVerifyEmail", (*nums)["s_myemail"].(string))
-			t.SetSession("SMVerifySucess", true)
-		}
-		return t.Render("/structuredata/mobile/write_infor_wx.html", &t.T)
-	} else {
-		return t.Redirect("/swordfish/about?source=open_infocontent&o=-130")
-	}
+    userId := util.ObjToString(t.GetSession("userId"))
+    if userId != "" {
+        //删除验证成功记录 和 发送验证码时间 邮箱
+        t.DelSession("SMVerifySucess")
+        t.DelSession("CreatSMVerifyTime")
+        t.DelSession("DataSMVerifyEmail")
+        nums := jyutil.Compatible.Select( userId,`{"s_phone":1,"s_phone":1}`)
+        if nums==nil {
+            return t.Redirect("/swordfish/about?source=open_infocontent&o=-130")
+        }
+        if _, ok := (*nums)["s_phone"]; ok {
+            t.T["phone_num"] = (*nums)["s_phone"].(string)
+        }
+        if _, ok := (*nums)["s_myemail"]; ok {
+            t.T["s_myemail"] = (*nums)["s_phone"].(string)
+            //验证是否是绑定的邮箱
+            t.SetSession("s_myemail", (*nums)["s_myemail"].(string))
+            t.SetSession("DataSMVerifyEmail", (*nums)["s_myemail"].(string))
+            t.SetSession("SMVerifySucess", true)
+        }
+        return t.Render("/structuredata/mobile/write_infor_wx.html", &t.T)
+    } else {
+        return t.Redirect("/swordfish/about?source=open_infocontent&o=-130")
+    }
 
 }
 
 func (t *StructedData) SaveData() {
-	name := t.GetString("name")
-	phone_num := t.GetString("phone_num")
-	source := t.GetString("source")
-	if name != "" && phone_num != "" && isPhone(phone_num) {
-		count := public.Mysql.Count("structed_data", map[string]interface{}{
-			"name":  name,
-			"phone": phone_num,
-			"type":  0,
-		})
-		if count >= 1 {
-			t.ServeJson(map[string]interface{}{
-				"error_code": "0",
-				"data": map[string]interface{}{
-					"msg":    "用户信息已存在",
-					"status": true,
-				},
-			})
-		} else {
-			insertMap := map[string]interface{}{
-				"name":        name,
-				"phone":       phone_num,
-				"submit_time": time.Now().Unix(),
-				"status":      0,
-				"type":        0, //用户来源,0:联系客服,1:免费样例,2:自选购买
-			}
-			if source != "" {
-				insertMap["source"] = source
-			}
-			stu := public.Mysql.Insert("structed_data", insertMap)
-			if stu == 0 {
-				t.ServeJson(map[string]interface{}{
-					"error_code": "1",
-					"data": map[string]interface{}{
-						"msg":    "数据库操作异常",
-						"status": false,
-					},
-				})
-			} else {
-				t.ServeJson(map[string]interface{}{
-					"error_code": "0",
-					"data": map[string]interface{}{
-						"msg":    "保存成功",
-						"status": true,
-					},
-				})
-			}
-		}
-	}
+    name := t.GetString("name")
+    phone_num := t.GetString("phone_num")
+    source := t.GetString("source")
+    if name != "" && phone_num != "" && isPhone(phone_num) {
+        count := public.Mysql.Count("structed_data", map[string]interface{}{
+            "name":  name,
+            "phone": phone_num,
+            "type":  0,
+        })
+        if count >= 1 {
+            t.ServeJson(map[string]interface{}{
+                "error_code": "0",
+                "data": map[string]interface{}{
+                    "msg":    "用户信息已存在",
+                    "status": true,
+                },
+            })
+        } else {
+            insertMap := map[string]interface{}{
+                "name":        name,
+                "phone":       phone_num,
+                "submit_time": time.Now().Unix(),
+                "status":      0,
+                "type":        0, //用户来源,0:联系客服,1:免费样例,2:自选购买
+            }
+            if source != "" {
+                insertMap["source"] = source
+            }
+            stu := public.Mysql.Insert("structed_data", insertMap)
+            if stu == 0 {
+                t.ServeJson(map[string]interface{}{
+                    "error_code": "1",
+                    "data": map[string]interface{}{
+                        "msg":    "数据库操作异常",
+                        "status": false,
+                    },
+                })
+            } else {
+                t.ServeJson(map[string]interface{}{
+                    "error_code": "0",
+                    "data": map[string]interface{}{
+                        "msg":    "保存成功",
+                        "status": true,
+                    },
+                })
+            }
+        }
+    }
 }
 
 //发送邮件
 func (t *StructedData) SendMailVerify() {
-	defer util.Catch()
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		if userId != "" {
-			email := t.GetString("email")
-			if isEmail(email) {
-				lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
-				timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
-				incurKey := fmt.Sprintf("SendSMEmail_%s_%d", t.GetSession("userId"), time.Now().Day())
-				if lastSendDEVerify == 0 || timeSpaceing < 0 {
-					//每日限制10次
-					times := util.IntAll(redis.Get("other", incurKey))
-					if times < 10 {
-						if times == 0 {
-							redis.Put("other", incurKey, 1, 24*60*60)
-						} else {
-							redis.Incr("other", incurKey)
-						}
-						//生成随机数
-						verifyStr := strings.ToUpper(util.GetComplexRandom(6, 3, 3))
-						t.SetSession("SMVerifySucess", false)
-						t.SetSession("DataSMVerify", verifyStr)
-						t.SetSession("CreatSMVerifyTime", time.Now().Unix())
-						t.SetSession("DataSMVerifyEmail", email)
-						log.Println("====================", verifyStr, "====================", t.GetSession("CreatSMVerifyTime"), "====================")
-						//发送邮箱验证码
-						go public.SendMailIdentCode(email, verifyStr, config.GmailAuth)
-						t.T["success"] = true
-						t.T["errCode"] = 5
-						t.T["errMsg"] = "已发送邮箱验证码"
-					} else {
-						t.T["success"] = false
-						t.T["errCode"] = 3
-						t.T["time"] = timeSpaceing
-						t.T["errMsg"] = "验证码发送次数已达到今日上限"
-					}
+    defer util.Catch()
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        if userId != "" {
+            email := t.GetString("email")
+            if isEmail(email) {
+                lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
+                timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
+                incurKey := fmt.Sprintf("SendSMEmail_%s_%d", t.GetSession("userId"), time.Now().Day())
+                if lastSendDEVerify == 0 || timeSpaceing < 0 {
+                    //每日限制10次
+                    times := util.IntAll(redis.Get("other", incurKey))
+                    if times < 10 {
+                        if times == 0 {
+                            redis.Put("other", incurKey, 1, 24*60*60)
+                        } else {
+                            redis.Incr("other", incurKey)
+                        }
+                        //生成随机数
+                        verifyStr := strings.ToUpper(util.GetComplexRandom(6, 3, 3))
+                        t.SetSession("SMVerifySucess", false)
+                        t.SetSession("DataSMVerify", verifyStr)
+                        t.SetSession("CreatSMVerifyTime", time.Now().Unix())
+                        t.SetSession("DataSMVerifyEmail", email)
+                        log.Println("====================", verifyStr, "====================", t.GetSession("CreatSMVerifyTime"), "====================")
+                        //发送邮箱验证码
+                        go public.SendMailIdentCode(email, verifyStr, config.GmailAuth)
+                        t.T["success"] = true
+                        t.T["errCode"] = 5
+                        t.T["errMsg"] = "已发送邮箱验证码"
+                    } else {
+                        t.T["success"] = false
+                        t.T["errCode"] = 3
+                        t.T["time"] = timeSpaceing
+                        t.T["errMsg"] = "验证码发送次数已达到今日上限"
+                    }
 
-				} else {
-					t.T["success"] = false
-					t.T["errCode"] = 2
-					t.T["time"] = timeSpaceing
-					t.T["errMsg"] = "已发送,5分钟后再尝试"
-				}
-			} else {
-				t.T["success"] = false
-				t.T["errCode"] = 1
-				t.T["errMsg"] = "邮箱格式不正确"
-			}
-		} else {
-			t.T["success"] = false
-			t.T["errCode"] = 7
-			t.T["errMsg"] = "未登录"
-		}
-	} else {
-		t.T["success"] = false
-		t.T["errCode"] = 6
-		t.T["errMsg"] = "请求方式有误"
-	}
-	t.ServeJson(&t.T)
+                } else {
+                    t.T["success"] = false
+                    t.T["errCode"] = 2
+                    t.T["time"] = timeSpaceing
+                    t.T["errMsg"] = "已发送,5分钟后再尝试"
+                }
+            } else {
+                t.T["success"] = false
+                t.T["errCode"] = 1
+                t.T["errMsg"] = "邮箱格式不正确"
+            }
+        } else {
+            t.T["success"] = false
+            t.T["errCode"] = 7
+            t.T["errMsg"] = "未登录"
+        }
+    } else {
+        t.T["success"] = false
+        t.T["errCode"] = 6
+        t.T["errMsg"] = "请求方式有误"
+    }
+    t.ServeJson(&t.T)
 }

+ 4 - 3
src/jfw/front/supsearch.go

@@ -3,7 +3,8 @@ package front
 import (
 	"fmt"
 	"jy/src/jfw/config"
-	"log"
+    "jy/src/jfw/jyutil"
+    "log"
 	"math/rand"
 	"strconv"
 	"strings"
@@ -220,9 +221,9 @@ func (p *Pcsearch) Getstatus() error {
 	defer util.Catch()
 	var supstatus, entstatus, tablepro, dataexportstatus, portraitpower, followent, smartstatus bool
 	if userid := util.ObjToString(p.GetSession("userId")); userid != "" {
-		user, b := mongodb.FindById("user", userid,
+		user := jyutil.Compatible.Select( userid,
 			`{"i_tablepro":1}`)
-		if len(*user) > 0 && b {
+		if len(*user) > 0 {
 			tablepro = util.Int64All((*user)["i_tablepro"]) == 1
 		}
 	}

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 971 - 987
src/jfw/front/swordfish.go


+ 1 - 1
src/jfw/front/ws_dataExport.go

@@ -307,7 +307,7 @@ func (w *WsDataExport) SubmitOrder() error {
 	if resEmail == "" || resPhone == "" {
 		lastEmail, lastPhone := "", ""
 		if lastPhone, lastEmail = dataexport.GetLastExportPhoneAndMail(public.Mysql, userId, util.ObjToString(w.GetSession("entUserId"))); lastPhone == "" || lastEmail == "" {
-			userData, _ := mongodb.FindById("user", userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
+			userData :=jyutil.Compatible.Select( userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
 			if userData != nil && len(*userData) > 0 {
 				if lastEmail == "" {
 					lastEmail, _ = (*userData)["s_myemail"].(string)

+ 2 - 2
src/jfw/front/wxMyOrder.go

@@ -101,8 +101,8 @@ func (w *WxMyOrder) MyEmail() {
 	if util.ObjToString(w.GetSession("userId")) != "" {
 		w.T["userId"] = util.ObjToString(w.GetSession("userId"))
 	}
-	res, err := mongodb.FindById("user", util.ObjToString(w.GetSession("userId")), nil)
-	if len(*res) > 0 && err {
+	res:= jyutil.Compatible.Select( util.ObjToString(w.GetSession("userId")), `"s_myemail":1`)
+	if len(*res) > 0 {
 		if util.ObjToString((*res)["s_myemail"]) == "" || name != "" {
 			//未绑定邮箱 进入绑定邮箱界面
 			if name != "" && util.ObjToString((*res)["s_myemail"]) != "" {

+ 7 - 24
src/jfw/front/wxkeyset.go

@@ -3,6 +3,7 @@ package front
 import (
     "fmt"
     "jy/src/jfw/config"
+    "jy/src/jfw/jyutil"
     "jy/src/jfw/wx"
     "net/url"
     "regexp"
@@ -277,33 +278,15 @@ func (m *Front) WxKeysetAjaxReq() {
     var flag bool
     if len(saveData) > 0 {
         saveData[types+".l_modifydate"] = time.Now().Unix()
-        query := map[string]interface{}{
-            "i_userid": util.Int64All(m.GetSession("entUserId")),
-            "i_entid":  util.Int64All(m.GetSession("entId")),
-            "i_type":   2,
-        }
         if index == "" {
-            if positionType == 0 {
-                flag = mongodb.UpdateById("user", userId, map[string]interface{}{
-                    "$set": saveData,
-                })
-            } else {
-                flag = mongodb.Update("entniche_rule", query, map[string]interface{}{
-                    "$set": saveData,
-                }, true, false)
-            }
-
+            flag = jyutil.Compatible.Update(userId, map[string]interface{}{
+                "$set": saveData,
+            })
         } else {
             if intIndex, e := strconv.Atoi(index); e == nil && intIndex >= 0 && intIndex < 10 {
-                if positionType == 0 {
-                    flag = mongodb.UpdateById("user", userId, map[string]interface{}{
-                        "$set": saveData,
-                    })
-                } else {
-                    flag = mongodb.Update("entniche_rule", query, map[string]interface{}{
-                        "$set": saveData,
-                    }, true, false)
-                }
+                flag = jyutil.Compatible.Update(userId, map[string]interface{}{
+                    "$set": saveData,
+                })
 
             }
         }

+ 157 - 155
src/jfw/jyutil/jyutil.go

@@ -1,204 +1,206 @@
 package jyutil
 
 import (
-	"encoding/json"
-	"fmt"
-	"io/ioutil"
-	"jy/src/jfw/config"
-	"log"
-	"net/http"
-	"reflect"
-	"regexp"
-	"sort"
-	"strings"
-	"time"
+    "app.yhyue.com/moapp/jypkg/compatible"
+    "encoding/json"
+    "fmt"
+    "io/ioutil"
+    "jy/src/jfw/config"
+    "log"
+    "net/http"
+    "reflect"
+    "regexp"
+    "sort"
+    "strings"
+    "time"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	. "app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/public"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    . "app.yhyue.com/moapp/jybase/mongodb"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/public"
 )
 
 var mongodb = public.MQFW
 var se = &encrypt.SimpleEncrypt{Key: "topnet2015topnet2015"}
 
+var Compatible = compatible.NewCompatible(&mongodb, public.BaseMysql, public.Mysql, config.Middleground)
 var AC = &encrypt.AES_CBC{
-	Key: "mGlAgnIBB8bx2nch",
-	Iv:  "1389461544135476",
+    Key: "mGlAgnIBB8bx2nch",
+    Iv:  "1389461544135476",
 }
 
 //
 func FindMyShareId(activecode, openid string) string {
-	defer util.Catch()
-	ret, bres := mongodb.Find("person_share", "{'s_openid':'"+openid+"','s_businesscode':'"+activecode+"'}", `{"l_timestamp":-1}`, nil, true, -1, -1)
-	var shareid string
-	if bres {
-		var shareData = make(map[string]interface{})
-		var str = ""
-		for _, v := range *ret {
-			str = util.ObjToString(v["i_shareid"])
-		}
-		var tt = `^\d+$`
-		a, _ := regexp.Compile(tt)
-		if str == "" || a.MatchString(str) {
-			data := make(map[string]interface{})
-			data["s_openid"] = openid
-			data["s_businesscode"] = activecode
-			data["i_shareid"] = se.EncodeString(openid + "---" + activecode)
-			data["l_timestamp"] = time.Now().Unix()
-			mongodb.Save("person_share", data)
-			shareid = openid + "---" + activecode
-		} else {
-			shareid = se.DecodeString(str)
-		}
-		odata := redis.Get("sso", "p_shareData_"+shareid)
-		if odata == nil {
-			shareData["action"] = "32"
-			redis.Put("sso", "p_shareData_"+shareid, shareData, 24*60*60)
-		}
-	}
-	return shareid
+    defer util.Catch()
+    ret, bres := mongodb.Find("person_share", "{'s_openid':'"+openid+"','s_businesscode':'"+activecode+"'}", `{"l_timestamp":-1}`, nil, true, -1, -1)
+    var shareid string
+    if bres {
+        var shareData = make(map[string]interface{})
+        var str = ""
+        for _, v := range *ret {
+            str = util.ObjToString(v["i_shareid"])
+        }
+        var tt = `^\d+$`
+        a, _ := regexp.Compile(tt)
+        if str == "" || a.MatchString(str) {
+            data := make(map[string]interface{})
+            data["s_openid"] = openid
+            data["s_businesscode"] = activecode
+            data["i_shareid"] = se.EncodeString(openid + "---" + activecode)
+            data["l_timestamp"] = time.Now().Unix()
+            mongodb.Save("person_share", data)
+            shareid = openid + "---" + activecode
+        } else {
+            shareid = se.DecodeString(str)
+        }
+        odata := redis.Get("sso", "p_shareData_"+shareid)
+        if odata == nil {
+            shareData["action"] = "32"
+            redis.Put("sso", "p_shareData_"+shareid, shareData, 24*60*60)
+        }
+    }
+    return shareid
 }
 
 //获取用户openid
 func Getopenid(code string) (openid string) {
-	defer util.Catch()
-	recturl := fmt.Sprintf(config.Wxoauthinfo, code)
-	resp, err := http.Get(recturl)
-	if err != nil {
-		log.Println(err.Error())
-		return
-	}
-	defer resp.Body.Close()
-	bs, _ := ioutil.ReadAll(resp.Body)
-	data := map[string]interface{}{}
-	json.Unmarshal(bs, &data)
-	openid, _ = data["openid"].(string)
-	return
+    defer util.Catch()
+    recturl := fmt.Sprintf(config.Wxoauthinfo, code)
+    resp, err := http.Get(recturl)
+    if err != nil {
+        log.Println(err.Error())
+        return
+    }
+    defer resp.Body.Close()
+    bs, _ := ioutil.ReadAll(resp.Body)
+    data := map[string]interface{}{}
+    json.Unmarshal(bs, &data)
+    openid, _ = data["openid"].(string)
+    return
 }
 
 //
 func GetSessionVal(q map[string]interface{}) (*map[string]interface{}, map[string]interface{}) {
-	person, ok := public.MQFW.FindOneByField("user", q, `{"_id":1,"i_shareknow":1,"s_m_openid":1,"s_nickname":1,"s_headimage":1,"s_headimageurl":1,"s_phone":1,"s_m_phone":1,"l_registedate":1,"i_ispush":1,"i_unlimited":1,"s_jyname":1,"base_user_id":1}`)
-	sessionVal := make(map[string]interface{})
-	if !ok || person == nil || len(*person) == 0 {
-		return nil, sessionVal
-	}
-	sessionVal["user"] = *person
-	if (*person)["i_shareknow"] != nil {
-		sessionVal["shareknow"] = (*person)["i_shareknow"]
-	}
-	sessionVal["userId"] = BsonIdToSId((*person)["_id"])
-	sessionVal["mgoUserId"] = sessionVal["userId"]
-	nickName, _ := (*person)["s_nickname"].(string)
-	phone := util.ObjToString((*person)["s_phone"])
-	if nickName == "" {
-		if phone != "" && len(phone) > 3 {
-			nickName = string(phone[0:3]) + "****" + string(phone[len(phone)-4:])
-		}
-	}
-	if util.ObjToString((*person)["s_jyname"]) != "" {
-		sessionVal["s_jyname"] = util.ObjToString((*person)["s_jyname"])
-	}
-	sessionVal["s_nickname"] = nickName
-	sessionVal["nickname"] = nickName
-	avatar, _ := (*person)["s_headimageurl"].(string)
-	if avatar == "" {
-		avatar, _ = (*person)["s_headimage"].(string)
-	}
-	sessionVal["s_avatar"] = strings.Replace(avatar, "http://", "https://", 1)
-	sessionVal["s_m_openid"], _ = (*person)["s_m_openid"].(string)
-	sessionVal["openid"] = sessionVal["s_m_openid"]
-	if phone == "" {
-		phone = util.ObjToString((*person)["s_m_phone"])
-	}
-	sessionVal["phone"] = phone
-	sessionVal["i_unlimited"] = util.IntAll((*person)["i_unlimited"])
-	sessionVal["base_user_id"] = util.IntAll((*person)["base_user_id"]) //用户中台的uid
-	return person, sessionVal
+    person, ok := public.MQFW.FindOneByField("user", q, `{"_id":1,"i_shareknow":1,"s_m_openid":1,"s_nickname":1,"s_headimage":1,"s_headimageurl":1,"s_phone":1,"s_m_phone":1,"l_registedate":1,"i_ispush":1,"i_unlimited":1,"s_jyname":1,"base_user_id":1}`)
+    sessionVal := make(map[string]interface{})
+    if !ok || person == nil || len(*person) == 0 {
+        return nil, sessionVal
+    }
+    sessionVal["user"] = *person
+    if (*person)["i_shareknow"] != nil {
+        sessionVal["shareknow"] = (*person)["i_shareknow"]
+    }
+    sessionVal["userId"] = BsonIdToSId((*person)["_id"])
+    sessionVal["mgoUserId"] = sessionVal["userId"]
+    nickName, _ := (*person)["s_nickname"].(string)
+    phone := util.ObjToString((*person)["s_phone"])
+    if nickName == "" {
+        if phone != "" && len(phone) > 3 {
+            nickName = string(phone[0:3]) + "****" + string(phone[len(phone)-4:])
+        }
+    }
+    if util.ObjToString((*person)["s_jyname"]) != "" {
+        sessionVal["s_jyname"] = util.ObjToString((*person)["s_jyname"])
+    }
+    sessionVal["s_nickname"] = nickName
+    sessionVal["nickname"] = nickName
+    avatar, _ := (*person)["s_headimageurl"].(string)
+    if avatar == "" {
+        avatar, _ = (*person)["s_headimage"].(string)
+    }
+    sessionVal["s_avatar"] = strings.Replace(avatar, "http://", "https://", 1)
+    sessionVal["s_m_openid"], _ = (*person)["s_m_openid"].(string)
+    sessionVal["openid"] = sessionVal["s_m_openid"]
+    if phone == "" {
+        phone = util.ObjToString((*person)["s_m_phone"])
+    }
+    sessionVal["phone"] = phone
+    sessionVal["i_unlimited"] = util.IntAll((*person)["i_unlimited"])
+    sessionVal["base_user_id"] = util.IntAll((*person)["base_user_id"]) //用户中台的uid
+    return person, sessionVal
 }
 
 //value 用户sessionid
 func LoginRedisKey(userid string) string {
-	return fmt.Sprintf("login_%s", userid)
+    return fmt.Sprintf("login_%s", userid)
 }
 
 // 排序 排序键必须为数字类型
 type SortBy struct {
-	Data    []map[string]interface{}
-	Sortkey string
+    Data    []map[string]interface{}
+    Sortkey string
 }
 
 func (a SortBy) Len() int { return len(a.Data) }
 
 func (a SortBy) Swap(i, j int) {
-	a.Data[i], a.Data[j] = a.Data[j], a.Data[i]
+    a.Data[i], a.Data[j] = a.Data[j], a.Data[i]
 }
 
 func (a SortBy) Less(i, j int) bool {
-	//return Float64(a.Data[i][a.Sortkey]) < Float64(a.Data[j][a.Sortkey])
-	m := a.Data[i][a.Sortkey]
-	n := a.Data[j][a.Sortkey]
-	w := reflect.ValueOf(m)
-	v := reflect.ValueOf(n)
-	switch v.Kind() {
-	case reflect.String:
-		return w.String() < v.String()
-	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-		return w.Int() < v.Int()
-	case reflect.Float64, reflect.Float32:
-		return w.Float() < v.Float()
-	default:
-		return fmt.Sprintf("%v", w) < fmt.Sprintf("%v", v)
-	}
+    //return Float64(a.Data[i][a.Sortkey]) < Float64(a.Data[j][a.Sortkey])
+    m := a.Data[i][a.Sortkey]
+    n := a.Data[j][a.Sortkey]
+    w := reflect.ValueOf(m)
+    v := reflect.ValueOf(n)
+    switch v.Kind() {
+    case reflect.String:
+        return w.String() < v.String()
+    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+        return w.Int() < v.Int()
+    case reflect.Float64, reflect.Float32:
+        return w.Float() < v.Float()
+    default:
+        return fmt.Sprintf("%v", w) < fmt.Sprintf("%v", v)
+    }
 }
 
 // ture  倒序3, 2, 1
 //fmt.Println(m)
 func SortData(data interface{}, sortkey string, reverse bool) {
-	//func SortData(data interface{}, sortkey string, reverse bool) {
-	var db []map[string]interface{}
-	err := Bind(data, &db)
-	if err != nil {
-		fmt.Println(err)
-		return
-	}
-	stb := SortBy{db, sortkey}
-	if !reverse {
-		sort.Sort(stb)
-	} else {
-		sort.Sort(sort.Reverse(stb))
-	}
-	err = Bind(stb.Data, data)
-	if err != nil {
-		fmt.Println(err)
-	}
+    //func SortData(data interface{}, sortkey string, reverse bool) {
+    var db []map[string]interface{}
+    err := Bind(data, &db)
+    if err != nil {
+        fmt.Println(err)
+        return
+    }
+    stb := SortBy{db, sortkey}
+    if !reverse {
+        sort.Sort(stb)
+    } else {
+        sort.Sort(sort.Reverse(stb))
+    }
+    err = Bind(stb.Data, data)
+    if err != nil {
+        fmt.Println(err)
+    }
 
 }
 
 // data 转换成ret
 func Bind(data interface{}, ret interface{}) error {
-	v := reflect.ValueOf(ret)
-	if v.Kind() != reflect.Ptr {
-		return fmt.Errorf("ptr input ret needed as type as input type %s", v.Kind())
-	}
-	havdata := false
-	var bk interface{}
-	if v.Elem().Kind() == reflect.Slice {
-		t := reflect.Zero(reflect.TypeOf(v.Elem().Interface()))
-		bk = v.Elem().Interface()
-		v.Elem().Set(t)
-		havdata = true
-	}
-	_data, _ := json.MarshalIndent(data, "", "    ")
-	err := json.Unmarshal(_data, ret)
-	if err != nil {
-		fmt.Println(err)
-		if havdata {
-			v.Elem().Set(reflect.ValueOf(bk))
-		}
-		return err
-	}
-	return nil
+    v := reflect.ValueOf(ret)
+    if v.Kind() != reflect.Ptr {
+        return fmt.Errorf("ptr input ret needed as type as input type %s", v.Kind())
+    }
+    havdata := false
+    var bk interface{}
+    if v.Elem().Kind() == reflect.Slice {
+        t := reflect.Zero(reflect.TypeOf(v.Elem().Interface()))
+        bk = v.Elem().Interface()
+        v.Elem().Set(t)
+        havdata = true
+    }
+    _data, _ := json.MarshalIndent(data, "", "    ")
+    err := json.Unmarshal(_data, ret)
+    if err != nil {
+        fmt.Println(err)
+        if havdata {
+            v.Elem().Set(reflect.ValueOf(bk))
+        }
+        return err
+    }
+    return nil
 }

+ 50 - 51
src/jfw/modules/app/src/app/active/active.go

@@ -1,70 +1,69 @@
 package active
 
 import (
-	"jy/src/jfw/modules/app/src/app/active/pullnew"
-	"jy/src/jfw/modules/app/src/app/config"
-	util "app.yhyue.com/moapp/jybase/common"
-	"time"
-
-	"app.yhyue.com/moapp/jypkg/public"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jypkg/public"
+    "jy/src/jfw/modules/app/src/app/active/pullnew"
+    "jy/src/jfw/modules/app/src/app/config"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "time"
 )
 
 type active struct {
-	*xweb.Action
-	explain xweb.Mapper `xweb:"/jyapp/free/active/explain"` //活动说明
-	info    xweb.Mapper `xweb:"/jyapp/free/active/info"`    //超级搜索页面只弹一次输入邀请码
+    *xweb.Action
+    explain xweb.Mapper `xweb:"/jyapp/free/active/explain"` //活动说明
+    info    xweb.Mapper `xweb:"/jyapp/free/active/info"`    //超级搜索页面只弹一次输入邀请码
 }
 
 func Init() {
-	//拉新活动初始化
-	go pullnew.Init()
+    //拉新活动初始化
+    go pullnew.Init()
 }
 
 func init() {
-	xweb.AddAction(&active{})
+    xweb.AddAction(&active{})
 }
 func (a *active) Explain() error {
-	return a.Render("/active/explain.html")
+    return a.Render("/active/explain.html")
 }
 
 //app所有活动信息都可使用该方法获取活动的基本信息
 func (a *active) Info() {
-	userId, _ := a.GetSession("userId").(string)
-	now_unix := time.Now().Unix()
-	/***拉新活动 start ***/
-	pullnewFuc := func() map[string]interface{} {
-		isCodeTip := false
-		isActiveTime := now_unix >= config.Active.Pullnew.StartTime && now_unix <= config.Active.Pullnew.EndTime
-		if isActiveTime && userId != "" {
-			user, ok := public.MQFW.FindById("user", userId, `{"l_registedate":1}`)
-			if ok && user != nil && len(*user) > 0 {
-				registeDate := util.Int64All((*user)["l_registedate"])
-				if registeDate >= config.Active.Pullnew.StartTime {
-					data, ok := public.MQFW.FindOneByField("jyapp_active_pullnew", map[string]interface{}{
-						"uid": userId,
-					}, `{"tip":1}`)
-					if ok {
-						if data != nil && len(*data) > 0 {
-							if util.IntAll((*data)["tip"]) != 1 {
-								isCodeTip = true
-							}
-						} else {
-							isCodeTip = true
-						}
-					}
-				}
-			}
-		}
-		return map[string]interface{}{
-			"isCodeTip":    isCodeTip,
-			"isActiveTime": isActiveTime,
-		}
-	}()
-	/***拉新活动 end ***/
-	a.ServeJson(map[string]interface{}{
-		"pullnew": pullnewFuc,
-		"isLogin": userId != "",
-	})
+    userId, _ := a.GetSession("userId").(string)
+    now_unix := time.Now().Unix()
+    /***拉新活动 start ***/
+    pullnewFuc := func() map[string]interface{} {
+        isCodeTip := false
+        isActiveTime := now_unix >= config.Active.Pullnew.StartTime && now_unix <= config.Active.Pullnew.EndTime
+        if isActiveTime && userId != "" {
+            user := utils.Compatible.Select(userId, `{"l_registedate":1}`)
+            if user != nil && len(*user) > 0 {
+                registeDate := util.Int64All((*user)["l_registedate"])
+                if registeDate >= config.Active.Pullnew.StartTime {
+                    data, ok := public.MQFW.FindOneByField("jyapp_active_pullnew", map[string]interface{}{
+                        "uid": userId,
+                    }, `{"tip":1}`)
+                    if ok {
+                        if data != nil && len(*data) > 0 {
+                            if util.IntAll((*data)["tip"]) != 1 {
+                                isCodeTip = true
+                            }
+                        } else {
+                            isCodeTip = true
+                        }
+                    }
+                }
+            }
+        }
+        return map[string]interface{}{
+            "isCodeTip":    isCodeTip,
+            "isActiveTime": isActiveTime,
+        }
+    }()
+    /***拉新活动 end ***/
+    a.ServeJson(map[string]interface{}{
+        "pullnew": pullnewFuc,
+        "isLogin": userId != "",
+    })
 }

+ 191 - 191
src/jfw/modules/app/src/app/active/pullnew/pullnew.go

@@ -1,232 +1,232 @@
 package pullnew
 
 import (
-	"jy/src/jfw/modules/app/src/app/config"
-	jconfig "jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"regexp"
-	"strings"
-	"sync"
-	"time"
+    "jy/src/jfw/modules/app/src/app/config"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    jconfig "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "regexp"
+    "strings"
+    "sync"
+    "time"
 
-	util "app.yhyue.com/moapp/jybase/common"
-
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"app.yhyue.com/moapp/jypkg/public"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jypkg/public"
 )
 
 type pullnew struct {
-	*xweb.Action
+    *xweb.Action
 
-	index        xweb.Mapper `xweb:"/jyapp/active/pullnew/index"`                  //首页
-	helpFriends  xweb.Mapper `xweb:"/jyapp/active/pullnew/helpfriends"`            //助力好友
-	inviteCode   xweb.Mapper `xweb:"/jyapp/active/pullnew/helpfriends/invitecode"` //好友的邀请码
-	dataPacket   xweb.Mapper `xweb:"/jyapp/active/pullnew/datapacket"`             //领取资料包
-	share        xweb.Mapper `xweb:"/jyapp/active/pullnew/share"`                  //分享统计
-	invite       xweb.Mapper `xweb:"/jyapp/free/active/pullnew/invite"`            //邀请
-	once         xweb.Mapper `xweb:"/jyapp/active/pullnew/once"`                   //超级搜索页面只弹一次输入邀请码
-	mydatapacket xweb.Mapper `xweb:"/jyapp/free/pullnew/mydatapacket"`             //领取资料包
+    index        xweb.Mapper `xweb:"/jyapp/active/pullnew/index"`                  //首页
+    helpFriends  xweb.Mapper `xweb:"/jyapp/active/pullnew/helpfriends"`            //助力好友
+    inviteCode   xweb.Mapper `xweb:"/jyapp/active/pullnew/helpfriends/invitecode"` //好友的邀请码
+    dataPacket   xweb.Mapper `xweb:"/jyapp/active/pullnew/datapacket"`             //领取资料包
+    share        xweb.Mapper `xweb:"/jyapp/active/pullnew/share"`                  //分享统计
+    invite       xweb.Mapper `xweb:"/jyapp/free/active/pullnew/invite"`            //邀请
+    once         xweb.Mapper `xweb:"/jyapp/active/pullnew/once"`                   //超级搜索页面只弹一次输入邀请码
+    mydatapacket xweb.Mapper `xweb:"/jyapp/free/pullnew/mydatapacket"`             //领取资料包
 }
 
 var (
-	hasInviteCode  = make(map[string]bool)
-	size           = 50
-	inviteCodePool = make(chan string, size)
-	lock           = &sync.Mutex{}
-	collection     = "jyapp_active_pullnew"
-	reg            = regexp.MustCompile("^[A-Z]{5}$")
+    hasInviteCode  = make(map[string]bool)
+    size           = 50
+    inviteCodePool = make(chan string, size)
+    lock           = &sync.Mutex{}
+    collection     = "jyapp_active_pullnew"
+    reg            = regexp.MustCompile("^[A-Z]{5}$")
 )
 
 func Init() {
-	//从数据库加载全部邀请码
-	log.Println("开始加载拉新活动全部邀请码。。。")
-	sess := public.MQFW.GetMgoConn()
-	defer public.MQFW.DestoryMongoConn(sess)
-	log.Println("拉新活动邀请码加载结束。。。", len(hasInviteCode))
-	//预先生成邀请码
-	for i := 0; i < size; i++ {
-		createInviteCode()
-	}
-	log.Println("预生成邀请码结束。。。")
+    //从数据库加载全部邀请码
+    log.Println("开始加载拉新活动全部邀请码。。。")
+    sess := public.MQFW.GetMgoConn()
+    defer public.MQFW.DestoryMongoConn(sess)
+    log.Println("拉新活动邀请码加载结束。。。", len(hasInviteCode))
+    //预先生成邀请码
+    for i := 0; i < size; i++ {
+        createInviteCode()
+    }
+    log.Println("预生成邀请码结束。。。")
 }
 
 //生成一个邀请码
 func createInviteCode() {
-	lock.Lock()
-	defer lock.Unlock()
-	for {
-		code := util.GetLetterRandom(5, true)
-		if !hasInviteCode[code] {
-			hasInviteCode[code] = true
-			inviteCodePool <- code
-			break
-		}
-	}
+    lock.Lock()
+    defer lock.Unlock()
+    for {
+        code := util.GetLetterRandom(5, true)
+        if !hasInviteCode[code] {
+            hasInviteCode[code] = true
+            inviteCodePool <- code
+            break
+        }
+    }
 }
 
 func init() {
-	xweb.AddAction(&pullnew{})
+    xweb.AddAction(&pullnew{})
 }
 func (a *pullnew) Index() error {
-	userId, _ := a.GetSession("userId").(string)
-	nickName := util.ObjToString(a.GetSession("s_nickname"))
-	hasHelp := true
-	data, ok := public.MQFW.FindOneByField(collection, map[string]interface{}{
-		"uid": userId,
-	}, `{"invitecode":1,"helpcode":1}`)
-	if ok {
-		inviteCode := ""
-		if data != nil && len(*data) > 0 {
-			inviteCode = util.ObjToString((*data)["invitecode"])
-			if util.ObjToString((*data)["helpcode"]) == "" {
-				hasHelp = false
-			} else {
-				hasHelp = true
-			}
-		} else {
-			hasHelp = false
-		}
-		if inviteCode == "" {
-			inviteCode = <-inviteCodePool
-			if public.MQFW.Update(collection, map[string]interface{}{
-				"uid": userId,
-			}, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"uid":          userId,
-					"invitecode":   inviteCode,
-					"invitetime":   time.Now().Unix(),
-					"nickname":     nickName,
-					"headimageurl": util.ObjToString(a.GetSession("s_headimageurl")),
-				},
-			}, true, false) {
-				a.T["inviteCode"] = inviteCode
-				go createInviteCode()
-			} else {
-				go func() {
-					inviteCodePool <- inviteCode
-				}()
-			}
-		} else {
-			a.T["inviteCode"] = inviteCode
-			//
-			a.T["myInvites"], _ = public.MQFW.Find(collection, map[string]interface{}{
-				"helpcode": inviteCode,
-			}, `{"helptime":1}`, `{"_id":0,"nickname":1,"headimageurl":1}`, false, 0, 3)
-		}
-	} else {
-		hasHelp = true
-	}
-	if !hasHelp {
-		hasHelp = true
-		user, ok := public.MQFW.FindById("user", userId, `{"l_registedate":1}`)
-		if ok && user != nil && len(*user) > 0 {
-			if util.Int64All((*user)["l_registedate"]) >= config.Active.Pullnew.StartTime {
-				hasHelp = false
-			}
-		}
-	}
-	a.T["hasHelp"] = hasHelp
-	a.T["shareNickName"] = encrypt.SE.Encode2Hex(nickName)
-	a.T["shareInviteCode"] = encrypt.SE.Encode2Hex(util.ObjToString(a.T["inviteCode"]))
-	return a.Render("/active/pullnew/index.html")
+    userId, _ := a.GetSession("userId").(string)
+    nickName := util.ObjToString(a.GetSession("s_nickname"))
+    hasHelp := true
+    data, ok := public.MQFW.FindOneByField(collection, map[string]interface{}{
+        "uid": userId,
+    }, `{"invitecode":1,"helpcode":1}`)
+    if ok {
+        inviteCode := ""
+        if data != nil && len(*data) > 0 {
+            inviteCode = util.ObjToString((*data)["invitecode"])
+            if util.ObjToString((*data)["helpcode"]) == "" {
+                hasHelp = false
+            } else {
+                hasHelp = true
+            }
+        } else {
+            hasHelp = false
+        }
+        if inviteCode == "" {
+            inviteCode = <-inviteCodePool
+            if public.MQFW.Update(collection, map[string]interface{}{
+                "uid": userId,
+            }, map[string]interface{}{
+                "$set": map[string]interface{}{
+                    "uid":          userId,
+                    "invitecode":   inviteCode,
+                    "invitetime":   time.Now().Unix(),
+                    "nickname":     nickName,
+                    "headimageurl": util.ObjToString(a.GetSession("s_headimageurl")),
+                },
+            }, true, false) {
+                a.T["inviteCode"] = inviteCode
+                go createInviteCode()
+            } else {
+                go func() {
+                    inviteCodePool <- inviteCode
+                }()
+            }
+        } else {
+            a.T["inviteCode"] = inviteCode
+            //
+            a.T["myInvites"], _ = public.MQFW.Find(collection, map[string]interface{}{
+                "helpcode": inviteCode,
+            }, `{"helptime":1}`, `{"_id":0,"nickname":1,"headimageurl":1}`, false, 0, 3)
+        }
+    } else {
+        hasHelp = true
+    }
+    if !hasHelp {
+        hasHelp = true
+        user := utils.Compatible.Select(userId, `{"l_registedate":1}`)
+        if user != nil && len(*user) > 0 {
+            if util.Int64All((*user)["l_registedate"]) >= config.Active.Pullnew.StartTime {
+                hasHelp = false
+            }
+        }
+    }
+    a.T["hasHelp"] = hasHelp
+    a.T["shareNickName"] = encrypt.SE.Encode2Hex(nickName)
+    a.T["shareInviteCode"] = encrypt.SE.Encode2Hex(util.ObjToString(a.T["inviteCode"]))
+    return a.Render("/active/pullnew/index.html")
 }
 func (a *pullnew) HelpFriends() error {
-	return a.Render("/active/pullnew/helpfriends.html")
+    return a.Render("/active/pullnew/helpfriends.html")
 }
 func (a *pullnew) InviteCode() {
-	status := "n"
-	userId, _ := a.GetSession("userId").(string)
-	code := strings.ToUpper(strings.TrimSpace(a.GetString("code")))
-	if reg.MatchString(code) {
-		data, ok := public.MQFW.FindOneByField(collection, map[string]interface{}{
-			"uid": userId,
-		}, `{"helpcode":1,"invitecode":1}`)
-		if ok {
-			if data != nil && len(*data) > 0 {
-				helpcode, _ := (*data)["helpcode"].(string)
-				if helpcode != "" {
-					status = "o"
-				} else if code == util.ObjToString((*data)["invitecode"]) {
-					status = "m"
-				}
-			}
-			if public.MQFW.Count(collection, map[string]interface{}{"invitecode": code}) == 0 {
-				status = "b"
-			}
-			if status == "n" {
-				if public.MQFW.Update(collection, map[string]interface{}{
-					"uid": userId,
-				}, map[string]interface{}{
-					"$set": map[string]interface{}{
-						"uid":          userId,
-						"helpcode":     code,
-						"helptime":     time.Now().Unix(),
-						"nickname":     util.ObjToString(a.GetSession("s_nickname")),
-						"headimageurl": util.ObjToString(a.GetSession("s_headimageurl")),
-					},
-				}, true, false) {
-					status = "y"
-				}
-			}
-		}
-	}
-	a.ServeJson(map[string]interface{}{
-		"status": status,
-	})
+    status := "n"
+    userId, _ := a.GetSession("userId").(string)
+    code := strings.ToUpper(strings.TrimSpace(a.GetString("code")))
+    if reg.MatchString(code) {
+        data, ok := public.MQFW.FindOneByField(collection, map[string]interface{}{
+            "uid": userId,
+        }, `{"helpcode":1,"invitecode":1}`)
+        if ok {
+            if data != nil && len(*data) > 0 {
+                helpcode, _ := (*data)["helpcode"].(string)
+                if helpcode != "" {
+                    status = "o"
+                } else if code == util.ObjToString((*data)["invitecode"]) {
+                    status = "m"
+                }
+            }
+            if public.MQFW.Count(collection, map[string]interface{}{"invitecode": code}) == 0 {
+                status = "b"
+            }
+            if status == "n" {
+                if public.MQFW.Update(collection, map[string]interface{}{
+                    "uid": userId,
+                }, map[string]interface{}{
+                    "$set": map[string]interface{}{
+                        "uid":          userId,
+                        "helpcode":     code,
+                        "helptime":     time.Now().Unix(),
+                        "nickname":     util.ObjToString(a.GetSession("s_nickname")),
+                        "headimageurl": util.ObjToString(a.GetSession("s_headimageurl")),
+                    },
+                }, true, false) {
+                    status = "y"
+                }
+            }
+        }
+    }
+    a.ServeJson(map[string]interface{}{
+        "status": status,
+    })
 }
 func (a *pullnew) DataPacket() error {
-	userId, _ := a.GetSession("userId").(string)
-	count := 0
-	data, ok := public.MQFW.FindOneByField(collection, map[string]interface{}{"uid": userId}, `{"invitecode":1}`)
-	if ok && data != nil && len(*data) > 0 {
-		inviteCode := util.ObjToString((*data)["invitecode"])
-		count = public.MQFW.Count(collection, map[string]interface{}{"helpcode": inviteCode})
-	}
-	if count >= 3 {
-		a.T["domain"] = jconfig.Sysconfig["webdomain"]
-		a.T["url"] = config.Active.Pullnew.Url
-		a.T["password"] = config.Active.Pullnew.Password
-		return a.Render("/active/pullnew/datapacket.html")
-	} else {
-		return a.Redirect("/jyapp/active/pullnew/index")
-	}
+    userId, _ := a.GetSession("userId").(string)
+    count := 0
+    data, ok := public.MQFW.FindOneByField(collection, map[string]interface{}{"uid": userId}, `{"invitecode":1}`)
+    if ok && data != nil && len(*data) > 0 {
+        inviteCode := util.ObjToString((*data)["invitecode"])
+        count = public.MQFW.Count(collection, map[string]interface{}{"helpcode": inviteCode})
+    }
+    if count >= 3 {
+        a.T["domain"] = jconfig.Sysconfig["webdomain"]
+        a.T["url"] = config.Active.Pullnew.Url
+        a.T["password"] = config.Active.Pullnew.Password
+        return a.Render("/active/pullnew/datapacket.html")
+    } else {
+        return a.Redirect("/jyapp/active/pullnew/index")
+    }
 }
 
 func (a *pullnew) Share() {
-	flag := public.MQFW.Save("jyapp_active_pullnew_share", map[string]interface{}{
-		"type":       a.GetString("type"),
-		"createtime": time.Now().Unix(),
-		"uid":        a.GetSession("userId"),
-		"title":      a.GetString("title"),
-	}) != ""
-	a.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
+    flag := public.MQFW.Save("jyapp_active_pullnew_share", map[string]interface{}{
+        "type":       a.GetString("type"),
+        "createtime": time.Now().Unix(),
+        "uid":        a.GetSession("userId"),
+        "title":      a.GetString("title"),
+    }) != ""
+    a.ServeJson(map[string]interface{}{
+        "flag": flag,
+    })
 }
 
 func (a *pullnew) Invite() error {
-	a.T["nickName"] = encrypt.SE.Decode4Hex(a.GetString("n"))
-	a.T["inviteCode"] = encrypt.SE.Decode4Hex(a.GetString("i"))
-	a.T["source"] = a.GetString("t")
-	return a.Render("/active/pullnew/invite.html")
+    a.T["nickName"] = encrypt.SE.Decode4Hex(a.GetString("n"))
+    a.T["inviteCode"] = encrypt.SE.Decode4Hex(a.GetString("i"))
+    a.T["source"] = a.GetString("t")
+    return a.Render("/active/pullnew/invite.html")
 }
 
 func (a *pullnew) Once() {
-	userId, _ := a.GetSession("userId").(string)
-	flag := public.MQFW.Update(collection, map[string]interface{}{
-		"uid": userId,
-	}, map[string]interface{}{
-		"$set": map[string]interface{}{
-			"tip":     1,
-			"tiptime": time.Now().Unix(),
-			"uid":     userId,
-		},
-	}, true, false)
-	a.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
+    userId, _ := a.GetSession("userId").(string)
+    flag := public.MQFW.Update(collection, map[string]interface{}{
+        "uid": userId,
+    }, map[string]interface{}{
+        "$set": map[string]interface{}{
+            "tip":     1,
+            "tiptime": time.Now().Unix(),
+            "uid":     userId,
+        },
+    }, true, false)
+    a.ServeJson(map[string]interface{}{
+        "flag": flag,
+    })
 }
 func (a *pullnew) Mydatapacket() error {
-	return a.Redirect(config.Active.Pullnew.Url)
+    return a.Redirect(config.Active.Pullnew.Url)
 }

+ 114 - 116
src/jfw/modules/app/src/app/filter/phonefilter.go

@@ -1,28 +1,26 @@
 package filter
 
 import (
-	"fmt"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"net/http"
-	"regexp"
-	"strings"
-	"time"
+    "fmt"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "net/http"
+    "regexp"
+    "strings"
+    "time"
 
-	qu "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/public"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    qu "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jybase/redis"
 )
 
 type phoneFilter struct {
-	W          http.ResponseWriter
-	R          *http.Request
-	Session    *httpsession.Session
-	GetSession map[string]interface{}
+    W          http.ResponseWriter
+    R          *http.Request
+    Session    *httpsession.Session
+    GetSession map[string]interface{}
 }
 
 var articleUrl = regexp.MustCompile("^/jyapp/article/.*")
@@ -30,109 +28,109 @@ var bindurl = []*regexp.Regexp{}
 var initflag = true
 
 func init() {
-	//初始化不需要过滤的地址
-	qu.ReadConfig("./phoneFilter.json", &config.PhoneFilterConfig)
-	for _, v := range config.PhoneFilterConfig["regurl"].([]interface{}) {
-		bindurl = append(bindurl, regexp.MustCompile(qu.ObjToString(v)))
-	}
-	if len(bindurl) == 0 {
-		log.Println("初始化过滤地址失败。。")
-		initflag = false
-	}
+    //初始化不需要过滤的地址
+    qu.ReadConfig("./phoneFilter.json", &config.PhoneFilterConfig)
+    for _, v := range config.PhoneFilterConfig["regurl"].([]interface{}) {
+        bindurl = append(bindurl, regexp.MustCompile(qu.ObjToString(v)))
+    }
+    if len(bindurl) == 0 {
+        log.Println("初始化过滤地址失败。。")
+        initflag = false
+    }
 }
 
 func (l *phoneFilter) Do() bool {
-	if qu.Int64All(l.GetSession["positionType"]) == 1 {
-		return true
-	}
-	userId, _ := l.GetSession["userId"].(string)
-	// 请求过滤
-	pass := func() bool {
-		if !initflag || l.R.Method == "POST" || userId == "" {
-			return true
-		}
-		if flag, _ := config.Sysconfig["phoneFilterFlag"].(bool); !flag {
-			return true
-		}
-		for _, v := range bindurl {
-			if v.MatchString(l.R.URL.Path) && !strings.Contains(l.R.URL.Path, "squeeze") {
-				return true
-			}
-		}
-		return false
-	}()
-	if pass {
-		return true
-	}
-	isNewUser := false
-	//是否需要跳转绑定手机号
-	needBindPhone := func() bool {
-		if phone := l.GetSession["phone"]; phone != nil && phone != "" {
-			return false
-		}
-		if person, ok := public.MQFW.FindById("user", mongodb.BsonIdToSId(qu.ObjToString(userId)), `{"s_phone":1,"s_m_phone":1,"l_registedate":1}`); person != nil && ok {
-			s_phone := qu.ObjToString((*person)["s_phone"])
-			if s_phone == "" {
-				s_phone = qu.ObjToString((*person)["s_m_phone"])
-			}
-			if s_phone != "" {
-				l.Session.Set("phone", s_phone)
-				return false
-			}
-			regtime := qu.Int64All((*person)["l_registedate"])
-			reg := time.Unix(regtime, 0)
-			//新用户时间
-			accountMergeOnline, _ := config.Sysconfig["accountMergeOnline"].(string)
-			onLineTime, _ := time.ParseInLocation(Date_Full_Layout, accountMergeOnline, time.Local)
-			if onLineTime.After(reg) { //老用户
-				dbname, _ := config.Sysconfig["bindPopRedis"].(string)
-				key := fmt.Sprintf("bindPop_new_%s", userId)
-				if redis.GetInt(dbname, key) >= qu.IntAll(config.Sysconfig["maxBindPop"]) {
-					return true
-				}
-				if articleUrl.MatchString(l.R.URL.Path) {
-					bindPopNum := redis.Incr(dbname, key)
-					if bindPopNum == qu.Int64All(config.Sysconfig["firstBindPop"]) ||
-						bindPopNum > qu.Int64All(config.Sysconfig["maxBindPop"]) {
-						return true
-					}
-				}
-				return false
-			} else {
-				isNewUser = true
-			}
-			//设置cookie 前端跳转
-			SetCookie(l.R.URL.String(), int(time.Hour*24/time.Second), l.W)
-			return true
-		}
-		return false
-	}()
-	var href string
-	if needBindPhone {
-		href = "/jyapp/account/phone/bind?mode=mergeBind"
-		if isNewUser {
-			href += "&act=logout"
-		}
-	} else {
-		if exists, _ := redis.Exists("newother", fmt.Sprintf("abnormal_trigger_%s", userId)); exists {
-			href = "/jyapp/frontPage/verify/free/index?mode=phoneCheck"
-		}
-	}
-	if href != "" {
-		http.Redirect(l.W, l.R, href, 302)
-		return false
-	}
-	return true
+    if qu.Int64All(l.GetSession["positionType"]) == 1 {
+        return true
+    }
+    userId, _ := l.GetSession["userId"].(string)
+    // 请求过滤
+    pass := func() bool {
+        if !initflag || l.R.Method == "POST" || userId == "" {
+            return true
+        }
+        if flag, _ := config.Sysconfig["phoneFilterFlag"].(bool); !flag {
+            return true
+        }
+        for _, v := range bindurl {
+            if v.MatchString(l.R.URL.Path) && !strings.Contains(l.R.URL.Path, "squeeze") {
+                return true
+            }
+        }
+        return false
+    }()
+    if pass {
+        return true
+    }
+    isNewUser := false
+    //是否需要跳转绑定手机号
+    needBindPhone := func() bool {
+        if phone := l.GetSession["phone"]; phone != nil && phone != "" {
+            return false
+        }
+        if person := utils.Compatible.Select(userId, `{"s_phone":1,"s_m_phone":1,"l_registedate":1}`); person != nil {
+            s_phone := qu.ObjToString((*person)["s_phone"])
+            if s_phone == "" {
+                s_phone = qu.ObjToString((*person)["s_m_phone"])
+            }
+            if s_phone != "" {
+                l.Session.Set("phone", s_phone)
+                return false
+            }
+            regtime := qu.Int64All((*person)["l_registedate"])
+            reg := time.Unix(regtime, 0)
+            //新用户时间
+            accountMergeOnline, _ := config.Sysconfig["accountMergeOnline"].(string)
+            onLineTime, _ := time.ParseInLocation(Date_Full_Layout, accountMergeOnline, time.Local)
+            if onLineTime.After(reg) { //老用户
+                dbname, _ := config.Sysconfig["bindPopRedis"].(string)
+                key := fmt.Sprintf("bindPop_new_%s", userId)
+                if redis.GetInt(dbname, key) >= qu.IntAll(config.Sysconfig["maxBindPop"]) {
+                    return true
+                }
+                if articleUrl.MatchString(l.R.URL.Path) {
+                    bindPopNum := redis.Incr(dbname, key)
+                    if bindPopNum == qu.Int64All(config.Sysconfig["firstBindPop"]) ||
+                        bindPopNum > qu.Int64All(config.Sysconfig["maxBindPop"]) {
+                        return true
+                    }
+                }
+                return false
+            } else {
+                isNewUser = true
+            }
+            //设置cookie 前端跳转
+            SetCookie(l.R.URL.String(), int(time.Hour*24/time.Second), l.W)
+            return true
+        }
+        return false
+    }()
+    var href string
+    if needBindPhone {
+        href = "/jyapp/account/phone/bind?mode=mergeBind"
+        if isNewUser {
+            href += "&act=logout"
+        }
+    } else {
+        if exists, _ := redis.Exists("newother", fmt.Sprintf("abnormal_trigger_%s", userId)); exists {
+            href = "/jyapp/frontPage/verify/free/index?mode=phoneCheck"
+        }
+    }
+    if href != "" {
+        http.Redirect(l.W, l.R, href, 302)
+        return false
+    }
+    return true
 }
 
 //文章三级页跳转设置cookie
 func SetCookie(value string, timeout int, w http.ResponseWriter) {
-	c := &http.Cookie{
-		Name:     "article",
-		Value:    value,
-		Path:     "/",
-		HttpOnly: true,
-		MaxAge:   timeout,
-	}
-	http.SetCookie(w, c)
+    c := &http.Cookie{
+        Name:     "article",
+        Value:    value,
+        Path:     "/",
+        HttpOnly: true,
+        MaxAge:   timeout,
+    }
+    http.SetCookie(w, c)
 }

+ 25 - 28
src/jfw/modules/app/src/app/front/bigMember.go

@@ -9,43 +9,40 @@ import (
 )
 
 type NewBigMemberAction struct {
-	*xweb.Action
-	vipPageManager xweb.Mapper `xweb:"/jyapp/big/page/(.*)"`        //大会员
-	powerClear     xweb.Mapper `xweb:"/jyapp/bigMember/powerClear"` //大会员清除redis 服务id缓存
+    *xweb.Action
+    vipPageManager xweb.Mapper `xweb:"/jyapp/big/page/(.*)"`        //大会员
+    powerClear     xweb.Mapper `xweb:"/jyapp/bigMember/powerClear"` //大会员清除redis 服务id缓存
 }
 
 var freePageReg = regexp.MustCompile(`full|landingPage|pro_follow_detail|buy_commit|push_setting_detail|land_setting|push_settings|contrast|orderdetail_.*|write_infor|init|set_.*|ontrial_commit|bid_.*|free_.*|ent_portrait|bigvip_subreport_.*|report_detail_.*|analysis_(search|filter)|client_*|pro_follow_list|report_analysis|report_table`)
 
 func init() {
-	jy.InitBigVipService(public.Mysql)
-	xweb.AddAction(&NewBigMemberAction{})
+    jy.InitBigVipService(public.Mysql)
+    xweb.AddAction(&NewBigMemberAction{})
 }
 
 func (s *NewBigMemberAction) PowerClear() {
-	userid := s.GetString("userid")
-	if userid == "" {
-		userid, _ = s.GetSession("userId").(string)
-	}
-	s.ServeJson(map[string]interface{}{
-		"清除大会用用户:": userid,
-		"清除结果":     jy.ClearBigVipUserPower(userid),
-	})
+    positionId, _ := s.GetSession("positionId").(string)
+    s.ServeJson(map[string]interface{}{
+        "清除大会用用户:": positionId,
+        "清除结果":     jy.ClearBigVipUserPower(positionId),
+    })
 }
 
 func (s *NewBigMemberAction) VipPageManager(htmlName string) error {
-	if !freePageReg.MatchString(htmlName) {
-		bigBaseMsg := jy.GetBigVipUserBaseMsg( s.Session(), *config.Middleground)
-		//大会员页面权限判断
-		if !bigBaseMsg.CheckBigVipFrontPower(htmlName) {
-			//main_root页面大会员主页面 只要是大会员都可以进入
-			if !(bigBaseMsg.Status > 0 && htmlName == "main_root") {
-				return s.Redirect("/jyapp/big/page/landingPage")
-			}
-		}
-		//如果没有首次使用
-		if bigBaseMsg.Status > 0 && !bigBaseMsg.Used {
-			return s.Redirect("/jyapp/big/page/init") //跳转至首次初始化页面
-		}
-	}
-	return s.Render("/big-member/page_" + htmlName + ".html")
+    if !freePageReg.MatchString(htmlName) {
+        bigBaseMsg := jy.GetBigVipUserBaseMsg(s.Session(), *config.Middleground)
+        //大会员页面权限判断
+        if !bigBaseMsg.CheckBigVipFrontPower(htmlName) {
+            //main_root页面大会员主页面 只要是大会员都可以进入
+            if !(bigBaseMsg.Status > 0 && htmlName == "main_root") {
+                return s.Redirect("/jyapp/big/page/landingPage")
+            }
+        }
+        //如果没有首次使用
+        if bigBaseMsg.Status > 0 && !bigBaseMsg.Used {
+            return s.Redirect("/jyapp/big/page/init") //跳转至首次初始化页面
+        }
+    }
+    return s.Render("/big-member/page_" + htmlName + ".html")
 }

+ 571 - 597
src/jfw/modules/app/src/app/front/front.go

@@ -1,85 +1,85 @@
 package front
 
 import (
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"fmt"
-	"jy/src/jfw/modules/app/src/app/jylabutil"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"strings"
-	"sync"
-	"time"
-
-	. "jy/src/jfw/modules/app/src/app/jyutil"
-
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jypkg/public"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"github.com/SKatiyar/qr"
-	"github.com/dchest/captcha"
-	"go.mongodb.org/mongo-driver/bson"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "fmt"
+    "jy/src/jfw/modules/app/src/app/jylabutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "strings"
+    "sync"
+    "time"
+
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "app.yhyue.com/moapp/jypkg/public"
+    . "jy/src/jfw/modules/app/src/app/jyutil"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "github.com/SKatiyar/qr"
+    "github.com/dchest/captcha"
+    "go.mongodb.org/mongo-driver/bson"
 )
 
 type Front struct {
-	*xweb.Action
-	feedback           xweb.Mapper `xweb:"/jyapp/swordfish/feedback"` //意见反馈
-	praise             xweb.Mapper `xweb:"/jyapp/swordfish/praise"`
-	myFeedbacks        xweb.Mapper `xweb:"/jyapp/swordfish/myFeedbacks"`
-	ajaxReq            xweb.Mapper `xweb:"/jyapp/member/swordfish/ajaxReq"`
-	wxsearchlistPaging xweb.Mapper `xweb:"/jyapp/swordfish/searchlist/paging"`  //剑鱼标讯微信查询结果展示--分页
-	wxKeyset           xweb.Mapper `xweb:"/jyapp/wxkeyset/keyset/(\\w+)"`       //订阅词设置
-	wxKeysetAjaxReq    xweb.Mapper `xweb:"/jyapp/wxkeyset/ajaxReq"`             //订阅词ajax请求
-	wxpushView         xweb.Mapper `xweb:"/jyapp/wxpush/wxpushview"`            //推送结果预览
-	wxpushViewPaging   xweb.Mapper `xweb:"/jyapp/wxpush/wxpushview/paging"`     //推送结果预览--分页
-	historypush        xweb.Mapper `xweb:"/jyapp/swordfish/historypush"`        //历时推送记录
-	historypushPaging  xweb.Mapper `xweb:"/jyapp/swordfish/historypush/paging"` //历时推送记录--分页
-	tSGuide            xweb.Mapper `xweb:"/jyapp/tenderSubscribe/guide"`        //引导页
-	getRecomKWs        xweb.Mapper `xweb:"/jyapp/member/getRecomKWs"`           //获取推荐关键词
-	behaviorRecord     xweb.Mapper `xweb:"/jyapp/member/behaviorRecord"`        //记录用户点击的关键词
-	wxpushAjaxReq      xweb.Mapper `xweb:"/jyapp/wxpush/bid/ajaxReq"`
-	delWxHistorySearch xweb.Mapper `xweb:"/jyapp/swordfish/delWxHistorySearch"` //剑鱼标讯微信删除历史搜索
-	delOL              xweb.Mapper `xweb:"/jyapp/swordfish/delovertimelist"`    //手动删除30天无更新数据
-	wxpushListInfo     xweb.Mapper `xweb:"/jyapp/wxpush/bidinfo/(.*)"`          //推送列表
-	/*不需要登录*/
-	wxerr              xweb.Mapper `xweb:"/jyapp/free/mob/err"`
-	about              xweb.Mapper `xweb:"/jyapp/free/swordfish/about"`
-	transfer           xweb.Mapper `xweb:"/jyapp/free/transfer"` //原文链接中转
-	captcha            xweb.Mapper `xweb:"/jyapp/free/captcha"`  //生成验证码图片
-	getIndexData       xweb.Mapper `xweb:"/jyapp/free/front/getIndexData"`
-	limitSearchText    xweb.Mapper `xweb:"/jyapp/front/limitSearchText"`
-	index              xweb.Mapper `xweb:"/jyapp/free/index"`  //打开app跳转
-	kicked             xweb.Mapper `xweb:"/jyapp/free/kicked"` //被踢人之后跳转
-	setSeoVersion      xweb.Mapper `xweb:"/jyapp/free/setSeoVersion"`
-	receive            xweb.Mapper `xweb:"/jyapp/free/message/receive"`
-	jylabShareTimeline xweb.Mapper `xweb:"/jyapp/jylabShareTimeline"`
-	//修改强制分享主动分享状态和时间
-	updateShareStatus xweb.Mapper `xweb:"/jyapp/share/updateShareStatus"`
-	changePro         xweb.Mapper `xweb:"/jyapp/jylab/changePro"` //修改提示信息状态
-	hasPushHistory    xweb.Mapper `xweb:"/jyapp/front/hasPushHistory"`
-	showRedSpotOnMenu xweb.Mapper `xweb:"/jyapp/free/showRedSpotOnMenu"`
-	goToUpdate        xweb.Mapper `xweb:"/jyapp/free/goToUpdate"`
-	//许可协议及隐私政策 v2.9.4新增
-	policy          xweb.Mapper `xweb:"/jyapp/free/policy"`
-	pushMsgCallback xweb.Mapper `xweb:"/jyapp/pushmessage/callback"` //app客户端收到消息回调服务端地址
-
-	//静态页面通用地址
-	staticPage xweb.Mapper `xweb:"/jyapp/front/staticPage/(.+)"`
-	//商机管理推送
-	entnichePushList xweb.Mapper `xweb:"/jyapp/entniche/pushlist"`
-	entnichePush     xweb.Mapper `xweb:"/jyapp/entniche/push"`
-	delc             xweb.Mapper `xweb:"/jyapp/free/delcache/(.+)"` //删除模板缓存
-	iosExam          xweb.Mapper `xweb:"/jyapp/free/iosexam"`       //ios审核
-
-	downloadJyAppQrOther xweb.Mapper `xweb:"/jyapp/front/downloadJyApp/qrOther"` //扫码下载
-
-	qRCodePage xweb.Mapper `xweb:"/jyapp/free/qRCodePage"` //二维码页面
-
-	appConfig   xweb.Mapper `xweb:"/jyapp/free/config"`      //app配置项
-	shareDomain xweb.Mapper `xweb:"/jyapp/free/shareDomain"` //app分享 域名配置项
+    *xweb.Action
+    feedback           xweb.Mapper `xweb:"/jyapp/swordfish/feedback"` //意见反馈
+    praise             xweb.Mapper `xweb:"/jyapp/swordfish/praise"`
+    myFeedbacks        xweb.Mapper `xweb:"/jyapp/swordfish/myFeedbacks"`
+    ajaxReq            xweb.Mapper `xweb:"/jyapp/member/swordfish/ajaxReq"`
+    wxsearchlistPaging xweb.Mapper `xweb:"/jyapp/swordfish/searchlist/paging"`  //剑鱼标讯微信查询结果展示--分页
+    wxKeyset           xweb.Mapper `xweb:"/jyapp/wxkeyset/keyset/(\\w+)"`       //订阅词设置
+    wxKeysetAjaxReq    xweb.Mapper `xweb:"/jyapp/wxkeyset/ajaxReq"`             //订阅词ajax请求
+    wxpushView         xweb.Mapper `xweb:"/jyapp/wxpush/wxpushview"`            //推送结果预览
+    wxpushViewPaging   xweb.Mapper `xweb:"/jyapp/wxpush/wxpushview/paging"`     //推送结果预览--分页
+    historypush        xweb.Mapper `xweb:"/jyapp/swordfish/historypush"`        //历时推送记录
+    historypushPaging  xweb.Mapper `xweb:"/jyapp/swordfish/historypush/paging"` //历时推送记录--分页
+    tSGuide            xweb.Mapper `xweb:"/jyapp/tenderSubscribe/guide"`        //引导页
+    getRecomKWs        xweb.Mapper `xweb:"/jyapp/member/getRecomKWs"`           //获取推荐关键词
+    behaviorRecord     xweb.Mapper `xweb:"/jyapp/member/behaviorRecord"`        //记录用户点击的关键词
+    wxpushAjaxReq      xweb.Mapper `xweb:"/jyapp/wxpush/bid/ajaxReq"`
+    delWxHistorySearch xweb.Mapper `xweb:"/jyapp/swordfish/delWxHistorySearch"` //剑鱼标讯微信删除历史搜索
+    delOL              xweb.Mapper `xweb:"/jyapp/swordfish/delovertimelist"`    //手动删除30天无更新数据
+    wxpushListInfo     xweb.Mapper `xweb:"/jyapp/wxpush/bidinfo/(.*)"`          //推送列表
+    /*不需要登录*/
+    wxerr              xweb.Mapper `xweb:"/jyapp/free/mob/err"`
+    about              xweb.Mapper `xweb:"/jyapp/free/swordfish/about"`
+    transfer           xweb.Mapper `xweb:"/jyapp/free/transfer"` //原文链接中转
+    captcha            xweb.Mapper `xweb:"/jyapp/free/captcha"`  //生成验证码图片
+    getIndexData       xweb.Mapper `xweb:"/jyapp/free/front/getIndexData"`
+    limitSearchText    xweb.Mapper `xweb:"/jyapp/front/limitSearchText"`
+    index              xweb.Mapper `xweb:"/jyapp/free/index"`  //打开app跳转
+    kicked             xweb.Mapper `xweb:"/jyapp/free/kicked"` //被踢人之后跳转
+    setSeoVersion      xweb.Mapper `xweb:"/jyapp/free/setSeoVersion"`
+    receive            xweb.Mapper `xweb:"/jyapp/free/message/receive"`
+    jylabShareTimeline xweb.Mapper `xweb:"/jyapp/jylabShareTimeline"`
+    //修改强制分享主动分享状态和时间
+    updateShareStatus xweb.Mapper `xweb:"/jyapp/share/updateShareStatus"`
+    changePro         xweb.Mapper `xweb:"/jyapp/jylab/changePro"` //修改提示信息状态
+    hasPushHistory    xweb.Mapper `xweb:"/jyapp/front/hasPushHistory"`
+    showRedSpotOnMenu xweb.Mapper `xweb:"/jyapp/free/showRedSpotOnMenu"`
+    goToUpdate        xweb.Mapper `xweb:"/jyapp/free/goToUpdate"`
+    //许可协议及隐私政策 v2.9.4新增
+    policy          xweb.Mapper `xweb:"/jyapp/free/policy"`
+    pushMsgCallback xweb.Mapper `xweb:"/jyapp/pushmessage/callback"` //app客户端收到消息回调服务端地址
+
+    //静态页面通用地址
+    staticPage xweb.Mapper `xweb:"/jyapp/front/staticPage/(.+)"`
+    //商机管理推送
+    entnichePushList xweb.Mapper `xweb:"/jyapp/entniche/pushlist"`
+    entnichePush     xweb.Mapper `xweb:"/jyapp/entniche/push"`
+    delc             xweb.Mapper `xweb:"/jyapp/free/delcache/(.+)"` //删除模板缓存
+    iosExam          xweb.Mapper `xweb:"/jyapp/free/iosexam"`       //ios审核
+
+    downloadJyAppQrOther xweb.Mapper `xweb:"/jyapp/front/downloadJyApp/qrOther"` //扫码下载
+
+    qRCodePage xweb.Mapper `xweb:"/jyapp/free/qRCodePage"` //二维码页面
+
+    appConfig   xweb.Mapper `xweb:"/jyapp/free/config"`      //app配置项
+    shareDomain xweb.Mapper `xweb:"/jyapp/free/shareDomain"` //app分享 域名配置项
 }
 
 var sewx encrypt.SimpleEncrypt //微信的加密方法
@@ -90,425 +90,399 @@ var sortArray []string
 var mLock *sync.Mutex
 
 func init() {
-	mLock = new(sync.Mutex)
-	sewx = encrypt.SimpleEncrypt{Key: "topnet"}
-	xweb.AddAction(&Front{})
-	industrylist, sortArray = jy.Getindustrys(util.ObjToString(config.Sysconfig["industry"]), mongodb)
+    mLock = new(sync.Mutex)
+    sewx = encrypt.SimpleEncrypt{Key: "topnet"}
+    xweb.AddAction(&Front{})
+    industrylist, sortArray = jy.Getindustrys(util.ObjToString(config.Sysconfig["industry"]), mongodb)
 }
 
 func (f *Front) PushMsgCallback() {
-	f.ServeJson(map[string]interface{}{})
+    f.ServeJson(map[string]interface{}{})
 }
 
 // Policy 许可协议及隐私政策
 func (f *Front) Policy() {
-	status := 0
-	data := map[string]interface{}{}
-	policy := util.ObjToMap(config.Sysconfig["policy"])
-	title := util.ObjToString((*policy)["title"])
-	content := util.ObjToString((*policy)["content"])
-	href := util.ObjArrToStringArr((*policy)["href"].([]interface{}))
-	name := util.ObjArrToStringArr((*policy)["name"].([]interface{}))
-	if content != "" && title != "" {
-		status = 1
-		data = map[string]interface{}{
-			"title":   title,
-			"content": content,
-			"href":    href,
-			"name":    name,
-		}
-	}
-	//转义
-	f.ServeJson(map[string]interface{}{
-		"status": status,
-		"data":   data,
-	})
+    status := 0
+    data := map[string]interface{}{}
+    policy := util.ObjToMap(config.Sysconfig["policy"])
+    title := util.ObjToString((*policy)["title"])
+    content := util.ObjToString((*policy)["content"])
+    href := util.ObjArrToStringArr((*policy)["href"].([]interface{}))
+    name := util.ObjArrToStringArr((*policy)["name"].([]interface{}))
+    if content != "" && title != "" {
+        status = 1
+        data = map[string]interface{}{
+            "title":   title,
+            "content": content,
+            "href":    href,
+            "name":    name,
+        }
+    }
+    //转义
+    f.ServeJson(map[string]interface{}{
+        "status": status,
+        "data":   data,
+    })
 }
 
 func (m *Front) Receive() error {
-	defer util.Catch()
-	url_mid := m.GetString("url")
-	mid := ""
-	url := ""
-	if len(strings.Split(url_mid, "==")) > 1 {
-		mid = strings.Split(url_mid, "==")[1]
-		url = strings.Split(url_mid, "==")[0]
-	} else {
-		log.Println("非message消息通知")
-		return nil
-	}
-	recType := m.GetString("rectype")
-	//这是客户端发的请求,之前是openid,后来改成userid了,参数名没变还是openid,但值是userid
-	userId := m.GetString("openid")
-	if userId == "" {
-		userId, _ = m.GetSession("userId").(string)
-	}
-	defer mLock.Unlock()
-	mLock.Lock()
-	var ok = false
-	if recType == "D" && mid != "" && len([]rune(mid)) > 12 {
-		field := "i_delivery"
-		ok = mongodb.UpdateById("message_app", mid, map[string]interface{}{"$inc": map[string]interface{}{field: 1}})
-	} else if recType == "C" && mid != "" && len([]rune(mid)) > 12 {
-		field := "i_click"
-		//打开计算一次 是否已经打开过
-		if c := mongodb.Count("jyapp_notice", map[string]interface{}{
-			"s_id":     mid, //信息id
-			"s_userid": userId,
-			"i_unread": 1, //1:未打开;0:已打开
-		}); c == 1 {
-			//更新信息为已读状态
-			mongodb.Update("jyapp_notice", map[string]interface{}{
-				"s_id":     mid, //信息id
-				"s_userid": userId,
-			}, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"i_unread":    0,
-					"l_timestamp": time.Now().Unix(),
-				},
-			}, false, false)
-			//信息总量打开率+1
-			ok = mongodb.UpdateById("message_app", mid, map[string]interface{}{"$inc": map[string]interface{}{field: 1}})
-		}
-	} else if recType == "A" && mid != "" && len([]rune(mid)) > 12 {
-		field := "i_delivery"
-		field1 := "i_click"
-		//打开计算一次 是否已经打开过
-		if c := mongodb.Count("jyapp_notice", map[string]interface{}{
-			"s_id":     mid, //信息id
-			"s_userid": userId,
-			"i_unread": 1, //1:未打开;0:已打开
-		}); c == 1 {
-			ok = mongodb.UpdateById("message_app", mid, map[string]interface{}{"$inc": map[string]interface{}{field: 1, field1: 1}})
-			mongodb.Update("jyapp_notice", map[string]interface{}{
-				"s_id":     mid, //信息id
-				"s_userid": userId,
-			}, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"i_unread":    0,
-					"l_timestamp": time.Now().Unix(),
-				},
-			}, false, false)
-		}
-	}
-	if ok {
-		go mesCaLog(mid, url, userId, recType)
-	} else {
-		log.Println(recType, "--err: $inc")
-	}
-	m.ServeJson(map[string]interface{}{
-		"flag": ok,
-	})
-	return nil
+    defer util.Catch()
+    url_mid := m.GetString("url")
+    mid := ""
+    url := ""
+    if len(strings.Split(url_mid, "==")) > 1 {
+        mid = strings.Split(url_mid, "==")[1]
+        url = strings.Split(url_mid, "==")[0]
+    } else {
+        log.Println("非message消息通知")
+        return nil
+    }
+    recType := m.GetString("rectype")
+    //这是客户端发的请求,之前是openid,后来改成userid了,参数名没变还是openid,但值是userid
+    userId := m.GetString("openid")
+    if userId == "" {
+        userId, _ = m.GetSession("userId").(string)
+    }
+    defer mLock.Unlock()
+    mLock.Lock()
+    var ok = false
+    if recType == "D" && mid != "" && len([]rune(mid)) > 12 {
+        field := "i_delivery"
+        ok = mongodb.UpdateById("message_app", mid, map[string]interface{}{"$inc": map[string]interface{}{field: 1}})
+    } else if recType == "C" && mid != "" && len([]rune(mid)) > 12 {
+        field := "i_click"
+        //打开计算一次 是否已经打开过
+        if c := mongodb.Count("jyapp_notice", map[string]interface{}{
+            "s_id":     mid, //信息id
+            "s_userid": userId,
+            "i_unread": 1, //1:未打开;0:已打开
+        }); c == 1 {
+            //更新信息为已读状态
+            mongodb.Update("jyapp_notice", map[string]interface{}{
+                "s_id":     mid, //信息id
+                "s_userid": userId,
+            }, map[string]interface{}{
+                "$set": map[string]interface{}{
+                    "i_unread":    0,
+                    "l_timestamp": time.Now().Unix(),
+                },
+            }, false, false)
+            //信息总量打开率+1
+            ok = mongodb.UpdateById("message_app", mid, map[string]interface{}{"$inc": map[string]interface{}{field: 1}})
+        }
+    } else if recType == "A" && mid != "" && len([]rune(mid)) > 12 {
+        field := "i_delivery"
+        field1 := "i_click"
+        //打开计算一次 是否已经打开过
+        if c := mongodb.Count("jyapp_notice", map[string]interface{}{
+            "s_id":     mid, //信息id
+            "s_userid": userId,
+            "i_unread": 1, //1:未打开;0:已打开
+        }); c == 1 {
+            ok = mongodb.UpdateById("message_app", mid, map[string]interface{}{"$inc": map[string]interface{}{field: 1, field1: 1}})
+            mongodb.Update("jyapp_notice", map[string]interface{}{
+                "s_id":     mid, //信息id
+                "s_userid": userId,
+            }, map[string]interface{}{
+                "$set": map[string]interface{}{
+                    "i_unread":    0,
+                    "l_timestamp": time.Now().Unix(),
+                },
+            }, false, false)
+        }
+    }
+    if ok {
+        go mesCaLog(mid, url, userId, recType)
+    } else {
+        log.Println(recType, "--err: $inc")
+    }
+    m.ServeJson(map[string]interface{}{
+        "flag": ok,
+    })
+    return nil
 }
 
 func mesCaLog(mid, url, userId, recType string) {
-	defer util.Catch()
-	userData, ok1 := mongodb.FindById("user", userId, `{"s_province":1,"s_city":1,"s_nickname":1}`)
-	mesData, ok2 := mongodb.FindById("message_app", mid, `{"s_title":1,"s_subtitle":1}`)
-	if ok1 && ok2 && *mesData != nil && *userData != nil {
-		public.Mgo_Log.Save("jy_message", map[string]interface{}{
-			"openid":   userId, //之前存的是openid,用户合并以后存的是userid
-			"mid":      mid,
-			"title":    util.ObjToString((*mesData)["s_title"]),
-			"subtitle": util.ObjToString((*mesData)["s_subtitle"]),
-			"province": util.ObjToString((*userData)["s_province"]),
-			"city":     util.ObjToString((*userData)["s_city"]),
-			"nickname": util.ObjToString((*userData)["s_nickname"]),
-			"action":   recType, //S:发送 D:送达 C:打开
-			"date":     time.Now().Unix(),
-			"url":      url,
-		})
-	} else {
-		log.Println(mid, "-", userId, "mongodb 保存报错")
-	}
+    defer util.Catch()
+    userData := utils.Compatible.Select(userId, `{"s_province":1,"s_city":1,"s_nickname":1}`)
+    mesData, ok2 := mongodb.FindById("message_app", mid, `{"s_title":1,"s_subtitle":1}`)
+    if ok2 && *mesData != nil && *userData != nil {
+        public.Mgo_Log.Save("jy_message", map[string]interface{}{
+            "openid":   userId, //之前存的是openid,用户合并以后存的是userid
+            "mid":      mid,
+            "title":    util.ObjToString((*mesData)["s_title"]),
+            "subtitle": util.ObjToString((*mesData)["s_subtitle"]),
+            "province": util.ObjToString((*userData)["s_province"]),
+            "city":     util.ObjToString((*userData)["s_city"]),
+            "nickname": util.ObjToString((*userData)["s_nickname"]),
+            "action":   recType, //S:发送 D:送达 C:打开
+            "date":     time.Now().Unix(),
+            "url":      url,
+        })
+    } else {
+        log.Println(mid, "-", userId, "mongodb 保存报错")
+    }
 }
 
 func (m *Front) Wxerr() error {
-	return m.Render("/_err.html")
+    return m.Render("/_err.html")
 }
 func isInTSguide(userid string, session *httpsession.Session) bool {
-	if userid == "" {
-		return false
-	}
-	data := jy.GetBigVipUserBaseMsg( session,  *config.Middleground)
-	//付费用户无免费订阅,不进入订阅向导页面
-	if data.Data.Vip.Status > 0 || data.Data.Vip.Status > 0 {
-		return false
-	}
-	i_ts_guide := data.Data.Free.TsGuide
-	if i_ts_guide == 2 || (i_ts_guide == 0 && !data.Data.Free.FreeHasKey) {
-		return true
-	}
-	return false
+    if userid == "" {
+        return false
+    }
+    data := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
+    //付费用户无免费订阅,不进入订阅向导页面
+    if data.Data.Vip.Status > 0 || data.Data.Vip.Status > 0 {
+        return false
+    }
+    i_ts_guide := data.Data.Free.TsGuide
+    if i_ts_guide == 2 || (i_ts_guide == 0 && !data.Data.Free.FreeHasKey) {
+        return true
+    }
+    return false
 }
 func (m *Front) Feedback() error {
-	defer util.Catch()
-	userId, _ := m.GetSession("userId").(string)
-	list, _ := mongodb.Find("interaction", bson.M{"s_submitid": userId}, `{"l_submitdate":-1}`, `{"s_remark":1,"l_submitdate":1,"s_opinion":1,"i_status":1}`, false, 0, 200)
-	m.T["list"] = list
-	fkid := m.GetString("fkid")
-	if fkid != "" {
-		fkid = encrypt.DecodeArticleId2ByCheck(fkid)[0]
-	}
-	fromName := m.GetString("fromName")
-	if fromName != "" {
-		if fromName == "zndy" {
-			fromName = "剑鱼标讯实验室-智能订阅"
-		} else if fromName == "sjdc" {
-			fromName = "剑鱼标讯实验室-数据导出"
-		} else if fromName == "cjss" {
-			fromName = "剑鱼标讯实验室-超级搜索"
-		} else if fromName == "zbqy" {
-			fromName = "剑鱼标讯实验室-中标企业"
-		} else if fromName == "gzqy" {
-			fromName = "剑鱼标讯实验室-关注企业"
-		}
-	}
-	_, m.T["advertText"] = getRewardText()
-	m.T["advertImg"] = config.Sysconfig["advertImg"]
-	m.T["advertName"] = config.Sysconfig["advertName"]
-	m.T["advertUrl"] = config.Sysconfig["advertUrl"]
-	m.T["fkid"] = fkid
-	m.T["fromName"] = fromName
-	return m.Render("/weixin/feedback.html", &m.T)
+    defer util.Catch()
+    userId, _ := m.GetSession("userId").(string)
+    list, _ := mongodb.Find("interaction", bson.M{"s_submitid": userId}, `{"l_submitdate":-1}`, `{"s_remark":1,"l_submitdate":1,"s_opinion":1,"i_status":1}`, false, 0, 200)
+    m.T["list"] = list
+    fkid := m.GetString("fkid")
+    if fkid != "" {
+        fkid = encrypt.DecodeArticleId2ByCheck(fkid)[0]
+    }
+    fromName := m.GetString("fromName")
+    if fromName != "" {
+        if fromName == "zndy" {
+            fromName = "剑鱼标讯实验室-智能订阅"
+        } else if fromName == "sjdc" {
+            fromName = "剑鱼标讯实验室-数据导出"
+        } else if fromName == "cjss" {
+            fromName = "剑鱼标讯实验室-超级搜索"
+        } else if fromName == "zbqy" {
+            fromName = "剑鱼标讯实验室-中标企业"
+        } else if fromName == "gzqy" {
+            fromName = "剑鱼标讯实验室-关注企业"
+        }
+    }
+    _, m.T["advertText"] = getRewardText()
+    m.T["advertImg"] = config.Sysconfig["advertImg"]
+    m.T["advertName"] = config.Sysconfig["advertName"]
+    m.T["advertUrl"] = config.Sysconfig["advertUrl"]
+    m.T["fkid"] = fkid
+    m.T["fromName"] = fromName
+    return m.Render("/weixin/feedback.html", &m.T)
 }
 
 // 招标订阅向导
 func (f *Front) TSGuide() error {
-	defer util.Catch()
-	userid := util.ObjToString(f.GetSession("userId"))
-	positionType := util.Int64All(f.GetSession("positionType"))
-	if f.Method() == "GET" {
-		if !isInTSguide(userid, f.Session()) {
-			return f.Redirect("/jyapp/wxkeyset/keyset/index")
-		}
-		return f.Render("/weixin/wxtsguide.html")
-	} else {
-		reqType := f.GetString("reqType")
-		// index, _ := f.GetInteger("index")
-		result := make(bson.M)
-		if reqType == "save" {
-			var keyMaps []map[string]interface{}
-			keyWord := f.GetSlice("keyWord")
-			area := f.GetString("area")
-			if area == "" {
-				result["flag"] = false
-			} else { //20210930增加免费用户必须选择一个地区
-				for _, v := range keyWord {
-					vs := processKeyword(v)
-					if vs == nil {
-						continue
-					}
-					//多个词合并成一个
-					key := ""
-					for _, vkeys := range vs {
-						key += vkeys
-					}
-					keyMaps = append(keyMaps, map[string]interface{}{
-						"key":      []string{key},
-						"infotype": []string{},
-						"notkey":   []string{},
-						"from":     1, //用于记录是否可以选择全国
-					})
-					if len(keyMaps) >= 10 {
-						break
-					}
-				}
-				areas := map[string]interface{}{
-					area: []string{},
-				}
-				saveData := bson.M{}
-				if positionType == 0 {
-					saveData = bson.M{
-						"o_jy.o_area":       areas,
-						"o_jy.a_key":        keyMaps,
-						"o_jy.l_modifydate": time.Now().Unix(),
-						"i_ts_guide":        2,
-						"o_jy.i_newfree":    1,
-					}
-					result["flag"] = mongodb.UpdateById("user", userid, bson.M{"$set": saveData})
-				} else {
-					saveData = bson.M{
-						"o_entniche.o_area":       areas,
-						"o_entniche.a_key":        keyMaps,
-						"o_entniche.l_modifydate": time.Now().Unix(),
-						"i_ts_guide":              2,
-						"o_entniche.i_newfree":    1,
-					}
-					query := map[string]interface{}{
-						"i_userid": util.Int64All(f.GetSession("entUserId")),
-						"i_entid":  util.Int64All(f.GetSession("entId")),
-						"i_type":   2,
-					}
-					result["flag"] = mongodb.Update("entniche_rule", query, map[string]interface{}{"$set": saveData}, true, false)
-				}
-
-			}
-		} else if reqType == "over" {
-			saveData := bson.M{
-				"i_ts_guide": 1,
-			}
-			if positionType == 0 {
-				result["flag"] = mongodb.UpdateById("user", userid, bson.M{"$set": saveData})
-			} else {
-				query := map[string]interface{}{
-					"i_userid": util.Int64All(f.GetSession("entUserId")),
-					"i_entid":  util.Int64All(f.GetSession("entId")),
-					"i_type":   2,
-				}
-				result["flag"] = mongodb.Update("entniche_rule", query, map[string]interface{}{"$set": saveData}, true, false)
-			}
-
-		} else if reqType == "preview" {
-			rlt := elastic.GetByNgram(INDEX, TYPE, strings.Split(f.GetString("key"), " "), "", FINDF, `{"publishtime":-1}`, `"_id","title","publishtime","toptype","subtype","type","area","href","areaval"`, 0, 10)
-			if *rlt != nil && len(*rlt) > 0 {
-				for _, v := range *rlt {
-					v["_id"] = encrypt.EncodeArticleId2ByCheck(util.ObjToString(v["_id"]))
-				}
-			}
-			result["data"] = rlt
-		}
-		if result["flag"] != nil && result["flag"].(bool) {
-			jy.ClearBigVipUserPower(userid)
-		}
-		f.ServeJson(result)
-	}
-	return nil
+    defer util.Catch()
+    userid := util.ObjToString(f.GetSession("userId"))
+    if f.Method() == "GET" {
+        if !isInTSguide(userid, f.Session()) {
+            return f.Redirect("/jyapp/wxkeyset/keyset/index")
+        }
+        return f.Render("/weixin/wxtsguide.html")
+    } else {
+        reqType := f.GetString("reqType")
+        // index, _ := f.GetInteger("index")
+        result := make(bson.M)
+        if reqType == "save" {
+            var keyMaps []map[string]interface{}
+            keyWord := f.GetSlice("keyWord")
+            area := f.GetString("area")
+            if area == "" {
+                result["flag"] = false
+            } else { //20210930增加免费用户必须选择一个地区
+                for _, v := range keyWord {
+                    vs := processKeyword(v)
+                    if vs == nil {
+                        continue
+                    }
+                    //多个词合并成一个
+                    key := ""
+                    for _, vkeys := range vs {
+                        key += vkeys
+                    }
+                    keyMaps = append(keyMaps, map[string]interface{}{
+                        "key":      []string{key},
+                        "infotype": []string{},
+                        "notkey":   []string{},
+                        "from":     1, //用于记录是否可以选择全国
+                    })
+                    if len(keyMaps) >= 10 {
+                        break
+                    }
+                }
+                areas := map[string]interface{}{
+                    area: []string{},
+                }
+                saveData := bson.M{}
+                saveData = bson.M{
+                    "o_jy.o_area":       areas,
+                    "o_jy.a_key":        keyMaps,
+                    "o_jy.l_modifydate": time.Now().Unix(),
+                    "i_ts_guide":        2,
+                    "o_jy.i_newfree":    1,
+                }
+                result["flag"] = utils.Compatible.Update(userid, bson.M{"$set": saveData})
+
+            }
+        } else if reqType == "over" {
+            saveData := bson.M{
+                "i_ts_guide": 1,
+            }
+            result["flag"] = utils.Compatible.Update(userid, bson.M{"$set": saveData})
+        } else if reqType == "preview" {
+            rlt := elastic.GetByNgram(INDEX, TYPE, strings.Split(f.GetString("key"), " "), "", FINDF, `{"publishtime":-1}`, `"_id","title","publishtime","toptype","subtype","type","area","href","areaval"`, 0, 10)
+            if *rlt != nil && len(*rlt) > 0 {
+                for _, v := range *rlt {
+                    v["_id"] = encrypt.EncodeArticleId2ByCheck(util.ObjToString(v["_id"]))
+                }
+            }
+            result["data"] = rlt
+        }
+        if result["flag"] != nil && result["flag"].(bool) {
+            positionId := util.ObjToString(f.GetSession("positionId"))
+            jy.ClearBigVipUserPower(positionId)
+        }
+        f.ServeJson(result)
+    }
+    return nil
 }
 
 // 查看原文中转
 func (f *Front) Transfer() error {
-	return f.Redirect(f.GetString("url"))
+    return f.Redirect(f.GetString("url"))
 }
 func (c *Front) Captcha() error {
-	id := captcha.NewLen(4) //此id为生成验证码的ID,并不是实际显示的数字,在提交校验时,需要根据此ID进行查询。
-	c.SetSession("CheckCodeId", id)
-	//校验时调用以下代码
-	//ccid,_:=c.GetSession("CheckCodeId").(string)
-	//captcha.VerifyString(ccid,"用户输入的校验码")//返回bool
-	w := c.ResponseWriter
-	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
-	w.Header().Set("Pragma", "no-cache")
-	w.Header().Set("Expires", "0")
-	w.Header().Set("Content-Type", "image/png")
-	return captcha.WriteImage(w, id, 90, 30)
+    id := captcha.NewLen(4) //此id为生成验证码的ID,并不是实际显示的数字,在提交校验时,需要根据此ID进行查询。
+    c.SetSession("CheckCodeId", id)
+    //校验时调用以下代码
+    //ccid,_:=c.GetSession("CheckCodeId").(string)
+    //captcha.VerifyString(ccid,"用户输入的校验码")//返回bool
+    w := c.ResponseWriter
+    w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+    w.Header().Set("Pragma", "no-cache")
+    w.Header().Set("Expires", "0")
+    w.Header().Set("Content-Type", "image/png")
+    return captcha.WriteImage(w, id, 90, 30)
 }
 
 func (m *Front) WxpushListInfo(_id string) error {
-	defer util.Catch()
-	return m.Redirect("/jyapp/swordfish/historypush")
+    defer util.Catch()
+    return m.Redirect("/jyapp/swordfish/historypush")
 }
 
 func (f *Front) LimitSearchText() {
-	userId, _ := f.GetSession("userId").(string)
-	if userId == "" || !public.Lst.IsCanLogin(userId) {
-		f.Write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">需要登录!")
-		return
-	}
-	timeout, _ := f.GetInteger("t")
-	if timeout > 0 || timeout == -1 {
-		public.Lst.TimeOut = timeout
-	}
-	count, _ := f.GetInteger("c")
-	if (count > 0 || count == -1 || count == -2) && count != public.Lst.Count && public.Lst.Flag {
-		public.Lst.Count = count
-		public.Lst.Init()
-	}
-	flag, _ := f.GetInteger("f")
-	status := ""
-	if flag == -2 { //重置
-		status = "重置"
-		public.InitLimitSearchText(true, config.Sysconfig)
-	} else if flag == -1 && public.Lst.Flag { //关闭
-		status = "关闭"
-		public.Lst.Flag = false
-		public.Lst.Clear()
-	} else if flag == 1 && !public.Lst.Flag { //打开
-		status = "打开"
-		public.Lst.Flag = true
-		public.Lst.Init()
-	} else {
-		if public.Lst.Flag {
-			status = "打开"
-		} else {
-			status = "关闭"
-		}
-	}
-	totalPage, _ := f.GetInteger("p")
-	if totalPage > 0 && public.Lst.Flag {
-		public.Lst.TotalPage = totalPage
-	}
-	f.Write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">" + fmt.Sprintf(public.Lst.Msg, status, public.Lst.Count, public.Lst.TimeOut, public.Lst.TotalPage))
+    userId, _ := f.GetSession("userId").(string)
+    if userId == "" || !public.Lst.IsCanLogin(userId) {
+        f.Write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">需要登录!")
+        return
+    }
+    timeout, _ := f.GetInteger("t")
+    if timeout > 0 || timeout == -1 {
+        public.Lst.TimeOut = timeout
+    }
+    count, _ := f.GetInteger("c")
+    if (count > 0 || count == -1 || count == -2) && count != public.Lst.Count && public.Lst.Flag {
+        public.Lst.Count = count
+        public.Lst.Init()
+    }
+    flag, _ := f.GetInteger("f")
+    status := ""
+    if flag == -2 { //重置
+        status = "重置"
+        public.InitLimitSearchText(true, config.Sysconfig)
+    } else if flag == -1 && public.Lst.Flag { //关闭
+        status = "关闭"
+        public.Lst.Flag = false
+        public.Lst.Clear()
+    } else if flag == 1 && !public.Lst.Flag { //打开
+        status = "打开"
+        public.Lst.Flag = true
+        public.Lst.Init()
+    } else {
+        if public.Lst.Flag {
+            status = "打开"
+        } else {
+            status = "关闭"
+        }
+    }
+    totalPage, _ := f.GetInteger("p")
+    if totalPage > 0 && public.Lst.Flag {
+        public.Lst.TotalPage = totalPage
+    }
+    f.Write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">" + fmt.Sprintf(public.Lst.Msg, status, public.Lst.Count, public.Lst.TimeOut, public.Lst.TotalPage))
 }
 
 func (f *Front) Index() error {
-	url := f.Url()
-	redirect := "/jyapp/jylab/mainSearch"
-	if strings.Contains(url, "sign=") && strings.Contains(url, "url=") && strings.Contains(url, "from=") {
-		wh := strings.Split(url, "?")
-		redirect = "/jyapp/free/login?" + wh[len(wh)-1]
-	}
-	return f.Redirect(redirect)
+    url := f.Url()
+    redirect := "/jyapp/jylab/mainSearch"
+    if strings.Contains(url, "sign=") && strings.Contains(url, "url=") && strings.Contains(url, "from=") {
+        wh := strings.Split(url, "?")
+        redirect = "/jyapp/free/login?" + wh[len(wh)-1]
+    }
+    return f.Redirect(redirect)
 }
 
 func (f *Front) Kicked() error {
-	return f.Redirect("/jyapp/free/login?back=index")
+    return f.Redirect("/jyapp/free/login?back=index")
 }
 
 // 设置js css 版本号,修改以后记得同步更新seo.json中的值
 func (f *Front) SetSeoVersion() {
-	//!@111qqq@! md5=51a3b7b4ed3cf140
-	if f.GetString("p") != "51a3b7b4ed3cf140" {
-		return
-	}
-	version := ""
-	if f.GetString("v") == "" {
-		version = config.Seoconfig_Version
-		if version == "" {
-			version, _ = config.Seoconfig["version"].(string)
-		}
-	} else {
-		version = f.GetString("v")
-		config.Seoconfig_Version = version
-	}
-	//新的版本号 version作为固定版本号,非大版本不更改,mod_version 作为小版本号 经常变动;
-	mod_version := ""
-	if f.GetString("mv") == "" {
-		mod_version = config.Seoconfig_Mod_Version
-		if mod_version == "" {
-			mod_version, _ = config.Seoconfig["mod_version"].(string)
-		}
-	} else {
-		mod_version = f.GetString("mv")
-		config.Seoconfig_Mod_Version = mod_version
-	}
-	f.Write("当前版本号:" + mod_version + "-固定版本号:" + version)
+    //!@111qqq@! md5=51a3b7b4ed3cf140
+    if f.GetString("p") != "51a3b7b4ed3cf140" {
+        return
+    }
+    version := ""
+    if f.GetString("v") == "" {
+        version = config.Seoconfig_Version
+        if version == "" {
+            version, _ = config.Seoconfig["version"].(string)
+        }
+    } else {
+        version = f.GetString("v")
+        config.Seoconfig_Version = version
+    }
+    //新的版本号 version作为固定版本号,非大版本不更改,mod_version 作为小版本号 经常变动;
+    mod_version := ""
+    if f.GetString("mv") == "" {
+        mod_version = config.Seoconfig_Mod_Version
+        if mod_version == "" {
+            mod_version, _ = config.Seoconfig["mod_version"].(string)
+        }
+    } else {
+        mod_version = f.GetString("mv")
+        config.Seoconfig_Mod_Version = mod_version
+    }
+    f.Write("当前版本号:" + mod_version + "-固定版本号:" + version)
 }
 
 func (f *Front) JylabShareTimeline() {
-	userId, _ := f.GetSession("userId").(string)
-	if userId == "" {
-		f.ServeJson(map[string]interface{}{
-			"status": false,
-		})
-		return
-	}
-	reqType := f.GetString("reqType")
-	if reqType == "update" {
-		public.UpdateShareStatus(userId, "app", 3, 1, 0, false, config.Sysconfig)
-		f.ServeJson(map[string]interface{}{
-			"status": true,
-		})
-	} else {
-		jylabsharetimeline := 1
-		if public.CheckUserNeedForceShare(userId, public.ShareType_lab, config.Sysconfig) {
-			jylabsharetimeline = 0
-		}
-		f.ServeJson(map[string]interface{}{
-			"jylabsharetimeline": jylabsharetimeline,
-		})
-	}
+    userId, _ := f.GetSession("userId").(string)
+    if userId == "" {
+        f.ServeJson(map[string]interface{}{
+            "status": false,
+        })
+        return
+    }
+    reqType := f.GetString("reqType")
+    if reqType == "update" {
+        public.UpdateShareStatus(userId, "app", 3, 1, 0, false, config.Sysconfig)
+        f.ServeJson(map[string]interface{}{
+            "status": true,
+        })
+    } else {
+        jylabsharetimeline := 1
+        if public.CheckUserNeedForceShare(userId, public.ShareType_lab, config.Sysconfig) {
+            jylabsharetimeline = 0
+        }
+        f.ServeJson(map[string]interface{}{
+            "jylabsharetimeline": jylabsharetimeline,
+        })
+    }
 }
 
 /*
@@ -519,196 +493,196 @@ shareType - 分享类型 1-详情页 2-推送列表 3-实验室
 shareProperty - 分享性质 1-被动分享 2-主动分享
 */
 func (s *Front) UpdateShareStatus() error {
-	userId, _ := s.GetSession("userId").(string)
-	shareType, _ := s.GetInt("shareType")
-	shareProperty, _ := s.GetInt("shareProperty")
-	public.UpdateShareStatus(userId, "app", shareType, shareProperty, 0, false, config.Sysconfig)
-	s.ServeJson(map[string]interface{}{})
-	return nil
+    userId, _ := s.GetSession("userId").(string)
+    shareType, _ := s.GetInt("shareType")
+    shareProperty, _ := s.GetInt("shareProperty")
+    public.UpdateShareStatus(userId, "app", shareType, shareProperty, 0, false, config.Sysconfig)
+    s.ServeJson(map[string]interface{}{})
+    return nil
 }
 func (s *Front) ChangePro() {
-	defer util.Catch()
-	userid := util.ObjToString(s.GetSession("userId"))
-	if userid != "" {
-		jylabutil.UpdateAuthory(userid, "i_tablepro", 1)
-	}
+    defer util.Catch()
+    userid := util.ObjToString(s.GetSession("userId"))
+    if userid != "" {
+        jylabutil.UpdateAuthory(userid, "i_tablepro", 1)
+    }
 }
 
 func (s *Front) ShowRedSpotOnMenu() {
-	defer util.Catch()
-	userid := util.ObjToString(s.GetSession("userId"))
-	if userid == "" {
-		token := s.GetString("token")
-		if token != "" {
-			sign, status := analySign("显示小红点", token)
-			if status == 1 {
-				userid = sign.UserId //xxxxx
-			}
-		}
-	}
-	subscribe, project, ent, notice := 0, 0, 0, 0
-	if userid != "" {
-		users, ok := mongodb.FindById("user", userid, `{"s_phone":1,"s_m_phone":1,i_member_status":1,"i_apppushunread":1,"i_member_apppushunread":1,"s_member_mainid":1,"i_member_sub_status":1}`)
-		user := jy.GetBigVipUserBaseMsg( s.Session(),  *config.Middleground)
-		uid := ""
-		isNew := user.Data.Entniche.IsNew > 0
-		if ok && users != nil {
-			if jy.SwitchService.IsMember(s.Session(),   *config.Middleground) {
-				subscribe = util.IntAll((*users)["i_member_apppushunread"])
-			} else if isNew {
-				subscribe = 0
-			} else {
-				subscribe = util.IntAll((*users)["i_apppushunread"])
-			}
-		}
-		memberStatus := user.Data.Member.Status
-		/* if s_member_mainid := util.ObjToString((*user)["s_member_mainid"]); s_member_mainid != "" && util.IntAll((*user)["i_member_sub_status"]) == 1 && memberStatus > 0 {
-		           uid = s_member_mainid
-		   } else {
-		           uid = userid
-		   }*/
-		if user.Data.Member.Pid != "" {
-			uid = user.Data.Member.Pid
-		} else {
-			uid = userid
-		}
-		powerMap := user.PowerMap
-		if memberStatus > 0 && (powerMap[13] || powerMap[16]) {
-			ent = util.IntAll(public.BaseMysql.Count("follow_ent_monitor", map[string]interface{}{
-				"i_apppushunread": 1,
-				"s_userid":        uid,
-			}))
-		}
-		if memberStatus > 0 && powerMap[14] {
-			project = util.IntAll(public.BaseMysql.Count("follow_project_monitor", map[string]interface{}{
-				"i_apppushunread": 1,
-				"s_userid":        uid,
-			}))
-		}
-		notice = mongodb.Count("jyapp_notice", map[string]interface{}{
-			"i_unread": 1,
-			"s_userid": userid,
-		})
-	}
-	s.ServeJson(map[string]interface{}{
-		"subscribe":      subscribe,
-		"my":             project + ent + notice,
-		"notice":         notice,
-		"follow_project": project,
-		"follow_ent":     ent,
-	})
+    defer util.Catch()
+    userid := util.ObjToString(s.GetSession("userId"))
+    if userid == "" {
+        token := s.GetString("token")
+        if token != "" {
+            sign, status := analySign("显示小红点", token)
+            if status == 1 {
+                userid = sign.UserId //xxxxx
+            }
+        }
+    }
+    subscribe, project, ent, notice := 0, 0, 0, 0
+    if userid != "" {
+        users := utils.Compatible.Select(userid, `{"s_phone":1,"s_m_phone":1,i_member_status":1,"i_apppushunread":1,"i_member_apppushunread":1,"s_member_mainid":1,"i_member_sub_status":1}`)
+        user := jy.GetBigVipUserBaseMsg(s.Session(), *config.Middleground)
+        uid := ""
+        isNew := user.Data.Entniche.IsNew > 0
+        if users != nil {
+            if jy.SwitchService.IsMember(s.Session(), *config.Middleground) {
+                subscribe = util.IntAll((*users)["i_member_apppushunread"])
+            } else if isNew {
+                subscribe = 0
+            } else {
+                subscribe = util.IntAll((*users)["i_apppushunread"])
+            }
+        }
+        memberStatus := user.Data.Member.Status
+        /* if s_member_mainid := util.ObjToString((*user)["s_member_mainid"]); s_member_mainid != "" && util.IntAll((*user)["i_member_sub_status"]) == 1 && memberStatus > 0 {
+                   uid = s_member_mainid
+           } else {
+                   uid = userid
+           }*/
+        if user.Data.Member.Pid != "" {
+            uid = user.Data.Member.Pid
+        } else {
+            uid = userid
+        }
+        powerMap := user.PowerMap
+        if memberStatus > 0 && (powerMap[13] || powerMap[16]) {
+            ent = util.IntAll(public.BaseMysql.Count("follow_ent_monitor", map[string]interface{}{
+                "i_apppushunread": 1,
+                "s_userid":        uid,
+            }))
+        }
+        if memberStatus > 0 && powerMap[14] {
+            project = util.IntAll(public.BaseMysql.Count("follow_project_monitor", map[string]interface{}{
+                "i_apppushunread": 1,
+                "s_userid":        uid,
+            }))
+        }
+        notice = mongodb.Count("jyapp_notice", map[string]interface{}{
+            "i_unread": 1,
+            "s_userid": userid,
+        })
+    }
+    s.ServeJson(map[string]interface{}{
+        "subscribe":      subscribe,
+        "my":             project + ent + notice,
+        "notice":         notice,
+        "follow_project": project,
+        "follow_ent":     ent,
+    })
 }
 
 func (s *Front) GoToUpdate() {
-	mustupdate := false
-	updateflag, _ := s.GetInt("mustupdate")
-	if updateflag == 1 {
-		mustupdate = true
-	}
-	s.T["update"] = config.Sysconfig["update"]
-	s.T["mustupdate"] = mustupdate
-	s.Render("/app/update.html")
+    mustupdate := false
+    updateflag, _ := s.GetInt("mustupdate")
+    if updateflag == 1 {
+        mustupdate = true
+    }
+    s.T["update"] = config.Sysconfig["update"]
+    s.T["mustupdate"] = mustupdate
+    s.Render("/app/update.html")
 }
 
 // 静态页面
 func (s *Front) StaticPage(pagename string) error {
-	return s.Render("/staticpage/" + pagename)
+    return s.Render("/staticpage/" + pagename)
 }
 
 // 商机管理推送列表 --- 下个版本删除
 func (s *Front) EntnichePushList() error {
-	pi := s.GetString("pi")
-	pn := s.GetString("pn")
-	if pi != "" && pn != "" {
-		d_pn_s := strings.Split(encrypt.SE.Decode4HexByCheck(pi), "_")
-		if len(d_pn_s) == 3 && util.ObjToString(d_pn_s[0]) == "entniche" {
-			entId := util.IntAll(d_pn_s[1])
-			entUserId := util.IntAll(d_pn_s[2])
-			entName := encrypt.SE.Decode4HexByCheck(pn)
-			s.SetSession("entId", entId)
-			s.SetSession("entName", entName)
-			s.SetSession("entUserId", entUserId)
-		}
-	}
-	return s.Redirect("/page_entniche/home?f=push&selectTime=" + s.GetString("selectTime"))
+    pi := s.GetString("pi")
+    pn := s.GetString("pn")
+    if pi != "" && pn != "" {
+        d_pn_s := strings.Split(encrypt.SE.Decode4HexByCheck(pi), "_")
+        if len(d_pn_s) == 3 && util.ObjToString(d_pn_s[0]) == "entniche" {
+            entId := util.IntAll(d_pn_s[1])
+            entUserId := util.IntAll(d_pn_s[2])
+            entName := encrypt.SE.Decode4HexByCheck(pn)
+            s.SetSession("entId", entId)
+            s.SetSession("entName", entName)
+            s.SetSession("entUserId", entUserId)
+        }
+    }
+    return s.Redirect("/page_entniche/home?f=push&selectTime=" + s.GetString("selectTime"))
 }
 
 // 商机管理推送
 func (s *Front) EntnichePush() error {
-	pi := s.GetString("pi")
-	pn := s.GetString("pn")
-	if pi != "" && pn != "" {
-		d_pn_s := strings.Split(encrypt.SE.Decode4HexByCheck(pi), "_")
-		if len(d_pn_s) == 3 && util.ObjToString(d_pn_s[0]) == "entniche" {
-			entId := util.IntAll(d_pn_s[1])
-			entUserId := util.IntAll(d_pn_s[2])
-			entName := encrypt.SE.Decode4HexByCheck(pn)
-			s.SetSession("entId", entId)
-			s.SetSession("entName", entName)
-			s.SetSession("entUserId", entUserId)
-		}
-	}
-	if s.GetString("type") == "nomsgtip" {
-		return s.Redirect("/page_entniche/page/subsetting/sub_entrance.html")
-	} else if s.GetString("type") == "subscribepush" {
-		return s.Redirect("/jyapp/swordfish/historypush?f=push&t=entniche&pushtime=" + s.GetString("time"))
-	} else if s.GetString("type") == "old_subscribepush" {
-		return s.Redirect("/page_entniche/home?f=push&selectTime=" + s.GetString("time"))
-	}
-	return nil
+    pi := s.GetString("pi")
+    pn := s.GetString("pn")
+    if pi != "" && pn != "" {
+        d_pn_s := strings.Split(encrypt.SE.Decode4HexByCheck(pi), "_")
+        if len(d_pn_s) == 3 && util.ObjToString(d_pn_s[0]) == "entniche" {
+            entId := util.IntAll(d_pn_s[1])
+            entUserId := util.IntAll(d_pn_s[2])
+            entName := encrypt.SE.Decode4HexByCheck(pn)
+            s.SetSession("entId", entId)
+            s.SetSession("entName", entName)
+            s.SetSession("entUserId", entUserId)
+        }
+    }
+    if s.GetString("type") == "nomsgtip" {
+        return s.Redirect("/page_entniche/page/subsetting/sub_entrance.html")
+    } else if s.GetString("type") == "subscribepush" {
+        return s.Redirect("/jyapp/swordfish/historypush?f=push&t=entniche&pushtime=" + s.GetString("time"))
+    } else if s.GetString("type") == "old_subscribepush" {
+        return s.Redirect("/page_entniche/home?f=push&selectTime=" + s.GetString("time"))
+    }
+    return nil
 }
 
 // 删除模板缓存
 func (f *Front) Delc(url string) {
-	f.App.TemplateMgr.CacheDelete(strings.Replace(url, "GG", "/", 1))
-	f.WriteBytes([]byte("清除路径:" + url))
+    f.App.TemplateMgr.CacheDelete(strings.Replace(url, "GG", "/", 1))
+    f.WriteBytes([]byte("清除路径:" + url))
 }
 
 func (f *Front) IosExam() {
-	isIosExam, isIosExamPhone, isVip, isEnt := IosExamInfo(f.Action, true, true)
-	showVip, showEnt := true, true
-	if isIosExam || isIosExamPhone {
-		if !isVip {
-			showVip = false
-		}
-		if !isEnt {
-			showEnt = false
-		}
-	}
-	f.ServeJson(map[string]interface{}{
-		"error_code": 0,
-		"data": map[string]interface{}{
-			"showVip": showVip,
-			"showEnt": showEnt,
-		},
-	})
+    isIosExam, isIosExamPhone, isVip, isEnt := IosExamInfo(f.Action, true, true)
+    showVip, showEnt := true, true
+    if isIosExam || isIosExamPhone {
+        if !isVip {
+            showVip = false
+        }
+        if !isEnt {
+            showEnt = false
+        }
+    }
+    f.ServeJson(map[string]interface{}{
+        "error_code": 0,
+        "data": map[string]interface{}{
+            "showVip": showVip,
+            "showEnt": showEnt,
+        },
+    })
 }
 
 func (f *Front) DownloadJyAppQrOther() error {
-	w := f.ResponseWriter
-	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
-	w.Header().Set("Pragma", "no-cache")
-	w.Header().Set("Expires", "0")
-	w.Header().Set("Content-Type", "image/png")
-	discored := f.GetString("discored")
-	data := config.Seoconfig["jyDomain"].(string) + "/X/" + discored
-	r, _ := qr.Encode(data, qr.M)
-	pngdat := r.PNG()
-	_, err := w.Write(pngdat)
-	return err
+    w := f.ResponseWriter
+    w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
+    w.Header().Set("Pragma", "no-cache")
+    w.Header().Set("Expires", "0")
+    w.Header().Set("Content-Type", "image/png")
+    discored := f.GetString("discored")
+    data := config.Seoconfig["jyDomain"].(string) + "/X/" + discored
+    r, _ := qr.Encode(data, qr.M)
+    pngdat := r.PNG()
+    _, err := w.Write(pngdat)
+    return err
 }
 
 // QRCodePage 静态页面
 func (s *Front) QRCodePage() error {
-	s.T["path"] = s.GetString("path")
-	return s.Render("/weixin/sharePic.html")
+    s.T["path"] = s.GetString("path")
+    return s.Render("/weixin/sharePic.html")
 }
 
 func (s *Front) AppConfig() {
-	s.ServeJson(config.Sysconfig["appConfig"])
+    s.ServeJson(config.Sysconfig["appConfig"])
 }
 
 // app微信分享域名
 func (s *Front) ShareDomain() {
-	s.ServeJson(config.Seoconfig["wxDomain"].(string))
+    s.ServeJson(config.Seoconfig["wxDomain"].(string))
 }

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 918 - 919
src/jfw/modules/app/src/app/front/login.go


+ 200 - 199
src/jfw/modules/app/src/app/front/logoffuser.go

@@ -1,254 +1,255 @@
 package front
 
 import (
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"net/http"
-	"time"
-
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/usercenter"
-	"app.yhyue.com/moapp/jypkg/public"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"go.mongodb.org/mongo-driver/bson"
-	"go.mongodb.org/mongo-driver/bson/primitive"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "net/http"
+    "time"
+
+    . "app.yhyue.com/moapp/jybase/api"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/usercenter"
+    "app.yhyue.com/moapp/jypkg/public"
+
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "go.mongodb.org/mongo-driver/bson"
+    "go.mongodb.org/mongo-driver/bson/primitive"
 )
 
 // Logoffuser APP用户账号注销
 type Logoffuser struct {
-	*xweb.Action
-	outPage xweb.Mapper `xweb:"/jyapp/logoff/outpage/(.+)"` //注销相关页面
-	out     xweb.Mapper `xweb:"/jyapp/logoff/out"`          //注销
+    *xweb.Action
+    outPage xweb.Mapper `xweb:"/jyapp/logoff/outpage/(.+)"` //注销相关页面
+    out     xweb.Mapper `xweb:"/jyapp/logoff/out"`          //注销
 }
 
 func init() {
-	xweb.AddAction(&Logoffuser{})
+    xweb.AddAction(&Logoffuser{})
 }
 
 // OutPage 注销页面
 func (l *Logoffuser) OutPage(pagename string) error {
-	user_id := l.GetSession("userId").(string)
-	l.T["userId"] = user_id
-	return l.Render("/me/logoff/"+pagename, &l.T)
+    user_id := l.GetSession("userId").(string)
+    l.T["userId"] = user_id
+    return l.Render("/me/logoff/"+pagename, &l.T)
 }
 
 // Out 注销
 func (l *Logoffuser) Out() {
-	if !R.CheckReqParam(l.ResponseWriter, l.Request, "cause") {
-		return
-	}
-	user_id := l.GetSession("userId").(string)
-	status := 0
-	msg := ""
-	//获取用户注销原因
-	cause := l.GetString("cause")
-	//查询是否可以注销用户
-	isOk, mess := UserIsOk(user_id)
-	if isOk == 1 {
-		//注销企业
-		if LogOffAppUser(user_id, cause) {
-			status = 1
-		}
-		log.Println("可以注销:", user_id, cause)
-	} else {
-		//
-		status = isOk
-		msg = mess
-	}
-	l.ServeJson(Result{Data: M{"status": status}, Error_msg: msg})
-	return
+    if !R.CheckReqParam(l.ResponseWriter, l.Request, "cause") {
+        return
+    }
+    user_id := l.GetSession("userId").(string)
+    status := 0
+    msg := ""
+    //获取用户注销原因
+    cause := l.GetString("cause")
+    //查询是否可以注销用户
+    isOk, mess := UserIsOk(user_id)
+    if isOk == 1 {
+        //注销企业
+        if LogOffAppUser(user_id, cause) {
+            status = 1
+        }
+        log.Println("可以注销:", user_id, cause)
+    } else {
+        //
+        status = isOk
+        msg = mess
+    }
+    l.ServeJson(Result{Data: M{"status": status}, Error_msg: msg})
+    return
 }
 
 // UserIsOk 是否可以注销
 func UserIsOk(userid string) (int, string) {
-	//判断用户是否进行过用户合并
-	user, _ := mongodb.FindById("user", userid, nil)
-	if user != nil {
-		isEntnicheEnd := false
-		phone := []string{} //获取用户的手机号
-		if (*user)["s_phone"] != nil {
-			phone = append(phone, qutil.ObjToString((*user)["s_phone"]))
-		}
-		if (*user)["s_m_phone"] != nil {
-			phone = append(phone, qutil.ObjToString((*user)["s_m_phone"]))
-		}
-		if len(phone) > 0 {
-			isEntnicheEnd = IsEntnicheEnd(phone) //是否有未完成的商机管理服务
-		}
-		i_vip_status := qutil.IntAll((*user)["i_vip_status"])
-		if i_vip_status == 1 || i_vip_status == 2 || isEntnicheEnd {
-			return 2, "账户内有未完成的订单和服务。"
-		}
-		//修改订阅词操作
-		isojyupdate := false
-		ojy_modify := int64(0)
-		if (*user)["o_jy"] != nil {
-			isojyupdate, ojy_modify = IsOjyGtMonth(*qutil.ObjToMap((*user)["o_jy"]))
-		}
-		//修改密码操作
-		isupdatePwd := false
-		if (*user)["l_updatepwdtime"] != nil {
-			isupdatePwd = IsUpdatePwd(qutil.Int64All((*user)["l_updatepwdtime"]))
-		}
-		isupdateEmail := false
-		if (*user)["l_updatemyemail"] != nil {
-			isupdateEmail = IsUpdateEmail(qutil.Int64All((*user)["l_updatemyemail"]))
-		}
-		//
-		if IsUpdateMeGtMonth(userid) || IsUpdateEntGtMonth(phone) || (isojyupdate && !isNew(qutil.Int64All((*user)["l_registedate"]), ojy_modify)) || isupdatePwd || isupdateEmail {
-			return 3, "在最近一个月内,账户进行过更改密码、更改绑定信息等敏感操作。"
-		}
-		bl := (*user)["s_m_openid"] != nil && ((*user)["a_m_openid"] != nil || (*user)["s_phone"] != nil && (*user)["s_m_openid"] != (*user)["s_phone"])
-		if bl && qutil.IntAll((*user)["i_ispush"]) != 0 {
-			return 4, "“剑鱼标讯”公众号未取消关注。"
-		}
-	}
-	return 1, ""
+    //判断用户是否进行过用户合并
+    user := utils.Compatible.Select(userid, nil)
+    if user != nil {
+        isEntnicheEnd := false
+        phone := []string{} //获取用户的手机号
+        if (*user)["s_phone"] != nil {
+            phone = append(phone, qutil.ObjToString((*user)["s_phone"]))
+        }
+        if (*user)["s_m_phone"] != nil {
+            phone = append(phone, qutil.ObjToString((*user)["s_m_phone"]))
+        }
+        if len(phone) > 0 {
+            isEntnicheEnd = IsEntnicheEnd(phone) //是否有未完成的商机管理服务
+        }
+        i_vip_status := qutil.IntAll((*user)["i_vip_status"])
+        if i_vip_status == 1 || i_vip_status == 2 || isEntnicheEnd {
+            return 2, "账户内有未完成的订单和服务。"
+        }
+        //修改订阅词操作
+        isojyupdate := false
+        ojy_modify := int64(0)
+        if (*user)["o_jy"] != nil {
+            isojyupdate, ojy_modify = IsOjyGtMonth(*qutil.ObjToMap((*user)["o_jy"]))
+        }
+        //修改密码操作
+        isupdatePwd := false
+        if (*user)["l_updatepwdtime"] != nil {
+            isupdatePwd = IsUpdatePwd(qutil.Int64All((*user)["l_updatepwdtime"]))
+        }
+        isupdateEmail := false
+        if (*user)["l_updatemyemail"] != nil {
+            isupdateEmail = IsUpdateEmail(qutil.Int64All((*user)["l_updatemyemail"]))
+        }
+        //
+        if IsUpdateMeGtMonth(userid) || IsUpdateEntGtMonth(phone) || (isojyupdate && !isNew(qutil.Int64All((*user)["l_registedate"]), ojy_modify)) || isupdatePwd || isupdateEmail {
+            return 3, "在最近一个月内,账户进行过更改密码、更改绑定信息等敏感操作。"
+        }
+        bl := (*user)["s_m_openid"] != nil && ((*user)["a_m_openid"] != nil || (*user)["s_phone"] != nil && (*user)["s_m_openid"] != (*user)["s_phone"])
+        if bl && qutil.IntAll((*user)["i_ispush"]) != 0 {
+            return 4, "“剑鱼标讯”公众号未取消关注。"
+        }
+    }
+    return 1, ""
 }
 
 // LogOffAppUser 注销操作
 func LogOffAppUser(user_id, cause string) bool {
-	delete_data := map[string]interface{}{}
-	delete_data["s_cause"] = cause //注销原因
-	user, _ := mongodb.FindById("user", user_id, "")
-	delete_data["o_user"] = *user
-	delete_data["l_createtime"] = time.Now().Unix()
-	//存库
-	ok := mongodb.Save("delete_user", delete_data)
-	if ok != "" {
-		//删除用户中台
-		ck := &http.Cookie{}
-		base_userid_del := usercenter.GetBaseUserId(mongodb, user_id)
-		usercenter.PostUserCenter(qutil.ObjToString(config.Sysconfig["userCenterApi"])+usercenter.UserCenterDelete, usercenter.ContentType_Json, user_id, map[string]interface{}{
-			"appid": "10000",
-			"id":    base_userid_del,
-		}, ck)
-		//删除以前数据
-		_id, _ := primitive.ObjectIDFromHex(user_id)
-		if mongodb.Del("user", map[string]interface{}{
-			"_id": _id,
-		}) {
-			return true
-		}
-	}
-	return false
+    delete_data := map[string]interface{}{}
+    delete_data["s_cause"] = cause //注销原因
+    user:= utils.Compatible.Select( user_id, "")
+    delete_data["o_user"] = *user
+    delete_data["l_createtime"] = time.Now().Unix()
+    //存库
+    ok := mongodb.Save("delete_user", delete_data)
+    if ok != "" {
+        //删除用户中台
+        ck := &http.Cookie{}
+        base_userid_del := usercenter.GetBaseUserId(mongodb, user_id)
+        usercenter.PostUserCenter(qutil.ObjToString(config.Sysconfig["userCenterApi"])+usercenter.UserCenterDelete, usercenter.ContentType_Json, user_id, map[string]interface{}{
+            "appid": "10000",
+            "id":    base_userid_del,
+        }, ck)
+        //删除以前数据
+        _id, _ := primitive.ObjectIDFromHex(user_id)
+        if mongodb.Del("user", map[string]interface{}{
+            "_id": _id,
+        }) {
+            return true
+        }
+    }
+    return false
 }
 
 // IsUpdateMeGtMonth 个人信息修改时间是否超过1个月
 func IsUpdateMeGtMonth(userId string) bool {
-	res, _ := mongodb.FindOneByField("user_auth", bson.M{"s_userid": userId}, `{"l_auditDate":1,"i_status":1}`)
-	if res != nil && len(*res) > 0 {
-		auditdate := qutil.Int64All((*res)["l_auditDate"])
-		now := time.Now().AddDate(0, -1, 0).Unix()
-		if now < auditdate {
-			return true
-		}
-	}
-	return false
+    res, _ := mongodb.FindOneByField("user_auth", bson.M{"s_userid": userId}, `{"l_auditDate":1,"i_status":1}`)
+    if res != nil && len(*res) > 0 {
+        auditdate := qutil.Int64All((*res)["l_auditDate"])
+        now := time.Now().AddDate(0, -1, 0).Unix()
+        if now < auditdate {
+            return true
+        }
+    }
+    return false
 }
 
 // IsUpdateEntGtMonth 企业修改时间及增删员工是否超过1个月
 func IsUpdateEntGtMonth(phone []string) bool {
-	if len(phone) == 0 {
-		return false
-	}
-	sql := "select id,createtime from entniche_info where phone in("
-	args := []interface{}{}
-	for k, v := range phone {
-		if k == (len(phone) - 1) {
-			sql += "?)"
-		} else {
-			sql += "?, "
-		}
-		args = append(args, v)
-	}
-	res := public.Mysql.SelectBySql(sql, args...)
-	month_time := time.Now().AddDate(0, -1, 0)
-	if res != nil {
-		for _, v := range *res {
-			create_time := qutil.ObjToString(v["createtime"])
-			createT, _ := time.ParseInLocation(Date_Full_Layout, create_time, time.Local)
-			if createT.After(month_time) {
-				return true
-			}
-			//是否新增过员工
-			newaddcount := public.Mysql.CountBySql(`select count(1) as count from entniche_user 
+    if len(phone) == 0 {
+        return false
+    }
+    sql := "select id,createtime from entniche_info where phone in("
+    args := []interface{}{}
+    for k, v := range phone {
+        if k == (len(phone) - 1) {
+            sql += "?)"
+        } else {
+            sql += "?, "
+        }
+        args = append(args, v)
+    }
+    res := public.Mysql.SelectBySql(sql, args...)
+    month_time := time.Now().AddDate(0, -1, 0)
+    if res != nil {
+        for _, v := range *res {
+            create_time := qutil.ObjToString(v["createtime"])
+            createT, _ := time.ParseInLocation(Date_Full_Layout, create_time, time.Local)
+            if createT.After(month_time) {
+                return true
+            }
+            //是否新增过员工
+            newaddcount := public.Mysql.CountBySql(`select count(1) as count from entniche_user
 									where ent_id = ? and  createtime between ? and ? `, v["id"], month_time.Format(Date_Full_Layout), time.Now().Format(Date_Full_Layout))
-			if newaddcount > 0 {
-				return true
-			}
-			//是否删除员工
-			if mongodb.Count("entniche_delete", bson.M{
-				"ent_id":    v["id"],
-				"tablename": "entniche_user",
-				"deletetime": bson.M{
-					"$gte": month_time.Unix(),
-					"$lte": time.Now().Unix(),
-				},
-			}) > 0 {
-				return true
-			}
-		}
-	}
-	return false
+            if newaddcount > 0 {
+                return true
+            }
+            //是否删除员工
+            if mongodb.Count("entniche_delete", bson.M{
+                "ent_id":    v["id"],
+                "tablename": "entniche_user",
+                "deletetime": bson.M{
+                    "$gte": month_time.Unix(),
+                    "$lte": time.Now().Unix(),
+                },
+            }) > 0 {
+                return true
+            }
+        }
+    }
+    return false
 }
 
 // IsOjyGtMonth 是否修改过订阅设置
 func IsOjyGtMonth(ojy map[string]interface{}) (bool, int64) {
-	updatetime := qutil.Int64All(ojy["l_modifydate"])
-	now := time.Now().AddDate(0, -1, 0).Unix()
-	if now < updatetime {
-		return true, updatetime
-	}
-	return false, updatetime
+    updatetime := qutil.Int64All(ojy["l_modifydate"])
+    now := time.Now().AddDate(0, -1, 0).Unix()
+    if now < updatetime {
+        return true, updatetime
+    }
+    return false, updatetime
 }
 
 // IsEntnicheEnd 商机管理是否到期
 func IsEntnicheEnd(phone []string) bool {
-	if len(phone) == 0 {
-		return false
-	}
-	sql := "select  count(1) as count from entniche_info where status=? and phone in("
-	args := []interface{}{}
-	args = append(args, 1)
-	for k, v := range phone {
-		if k == (len(phone) - 1) {
-			sql += "?)"
-		} else {
-			sql += "?, "
-		}
-		args = append(args, v)
-	}
-	if public.Mysql.CountBySql(sql, args...) > 0 {
-		return true
-	}
-	return false
+    if len(phone) == 0 {
+        return false
+    }
+    sql := "select  count(1) as count from entniche_info where status=? and phone in("
+    args := []interface{}{}
+    args = append(args, 1)
+    for k, v := range phone {
+        if k == (len(phone) - 1) {
+            sql += "?)"
+        } else {
+            sql += "?, "
+        }
+        args = append(args, v)
+    }
+    if public.Mysql.CountBySql(sql, args...) > 0 {
+        return true
+    }
+    return false
 }
 
 // IsUpdatePwd 是否修改过密码
 func IsUpdatePwd(updatetime int64) bool {
-	now := time.Now().AddDate(0, -1, 0).Unix()
-	if now < updatetime {
-		return true
-	}
-	return false
+    now := time.Now().AddDate(0, -1, 0).Unix()
+    if now < updatetime {
+        return true
+    }
+    return false
 }
 
 // IsUpdateEmail 是否修改过邮箱 l_updatemyemail
 func IsUpdateEmail(updatetime int64) bool {
-	now := time.Now().AddDate(0, -1, 0).Unix()
-	if now < updatetime {
-		return true
-	}
-	return false
+    now := time.Now().AddDate(0, -1, 0).Unix()
+    if now < updatetime {
+        return true
+    }
+    return false
 }
 
 func isNew(l_registedate, l_modifydate int64) bool {
-	if l_modifydate == l_registedate {
-		return true
-	}
-	return false
+    if l_modifydate == l_registedate {
+        return true
+    }
+    return false
 }

+ 392 - 398
src/jfw/modules/app/src/app/front/me.go

@@ -1,277 +1,277 @@
 package front
 
 import (
-	"fmt"
-	. "jy/src/jfw/modules/app/src/app/jyutil"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"strings"
-	"time"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jybase/usercenter"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "app.yhyue.com/moapp/jypkg/public"
+    "fmt"
+    . "jy/src/jfw/modules/app/src/app/jyutil"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "strings"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jybase/usercenter"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jypkg/public"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"go.mongodb.org/mongo-driver/bson"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "go.mongodb.org/mongo-driver/bson"
 )
 
 type Me struct {
-	*xweb.Action
-	meIndex             xweb.Mapper `xweb:"/jyapp/free/me"`
-	meSet               xweb.Mapper `xweb:"/jyapp/free/set"`
-	meSetPhone          xweb.Mapper `xweb:"/jyapp/free/setphone"`
-	meCustomer          xweb.Mapper `xweb:"/jyapp/free/customer"`
-	meset_info          xweb.Mapper `xweb:"/jyapp/free/setinfo"`             //修改页面需要的参数
-	updatepwd           xweb.Mapper `xweb:"/jyapp/updatepwd"`                //修改密码
-	pushMsgSet          xweb.Mapper `xweb:"/jyapp/free/pushMsgSet"`          //推送消息设置
-	iframe              xweb.Mapper `xweb:"/jyapp/free/iframe"`              //使用帮助
-	solveWay            xweb.Mapper `xweb:"/jyapp/free/solveWay"`            //android收不到推送的解决办法
-	notice              xweb.Mapper `xweb:"/jyapp/free/notice"`              //通知
-	noticeList          xweb.Mapper `xweb:"/jyapp/free/notice/list"`         //获取通知
-	checkUpdate         xweb.Mapper `xweb:"/jyapp/free/checkUpdate"`         //检查是否更新
-	newVersionUpdateLog xweb.Mapper `xweb:"/jyapp/free/newVersionUpdateLog"` //检查是否更新
-	download            xweb.Mapper `xweb:"/jyapp/free/download/(weixin|normal)"`
-	controlGrayUpdate   xweb.Mapper `xweb:"/jyapp/free/controlGrayUpdate/(user|channel)"` //app灰度更新
-	accountSafe         xweb.Mapper `xweb:"/jyapp/free/accountSafe"`                      //账号安全
-	getAccountInfo      xweb.Mapper `xweb:"/jyapp/free/getAccountInfo"`                   //账号安全获取信息
-	appVersion          xweb.Mapper `xweb:"/jyapp/free/appVersion"`                       //app版本号检测
+    *xweb.Action
+    meIndex             xweb.Mapper `xweb:"/jyapp/free/me"`
+    meSet               xweb.Mapper `xweb:"/jyapp/free/set"`
+    meSetPhone          xweb.Mapper `xweb:"/jyapp/free/setphone"`
+    meCustomer          xweb.Mapper `xweb:"/jyapp/free/customer"`
+    meset_info          xweb.Mapper `xweb:"/jyapp/free/setinfo"`             //修改页面需要的参数
+    updatepwd           xweb.Mapper `xweb:"/jyapp/updatepwd"`                //修改密码
+    pushMsgSet          xweb.Mapper `xweb:"/jyapp/free/pushMsgSet"`          //推送消息设置
+    iframe              xweb.Mapper `xweb:"/jyapp/free/iframe"`              //使用帮助
+    solveWay            xweb.Mapper `xweb:"/jyapp/free/solveWay"`            //android收不到推送的解决办法
+    notice              xweb.Mapper `xweb:"/jyapp/free/notice"`              //通知
+    noticeList          xweb.Mapper `xweb:"/jyapp/free/notice/list"`         //获取通知
+    checkUpdate         xweb.Mapper `xweb:"/jyapp/free/checkUpdate"`         //检查是否更新
+    newVersionUpdateLog xweb.Mapper `xweb:"/jyapp/free/newVersionUpdateLog"` //检查是否更新
+    download            xweb.Mapper `xweb:"/jyapp/free/download/(weixin|normal)"`
+    controlGrayUpdate   xweb.Mapper `xweb:"/jyapp/free/controlGrayUpdate/(user|channel)"` //app灰度更新
+    accountSafe         xweb.Mapper `xweb:"/jyapp/free/accountSafe"`                      //账号安全
+    getAccountInfo      xweb.Mapper `xweb:"/jyapp/free/getAccountInfo"`                   //账号安全获取信息
+    appVersion          xweb.Mapper `xweb:"/jyapp/free/appVersion"`                       //app版本号检测
 
-	//静态页面通用地址-未登录
-	staticPage xweb.Mapper `xweb:"/jyapp/free/staticPage/(.+)"`
-	myInfo     xweb.Mapper `xweb:"/jyapp/myinfo"`
+    //静态页面通用地址-未登录
+    staticPage xweb.Mapper `xweb:"/jyapp/free/staticPage/(.+)"`
+    myInfo     xweb.Mapper `xweb:"/jyapp/myinfo"`
 }
 
 func init() {
-	xweb.AddAction(&Me{})
+    xweb.AddAction(&Me{})
 }
 
 func (m *Me) AppVersion() {
-	m.Render("/me/appVersion.html", &m.T)
+    m.Render("/me/appVersion.html", &m.T)
 }
 
 // StaticPage 静态页面
 func (m *Me) StaticPage(pagename string) error {
-	return m.Render("/staticpage/" + pagename)
+    return m.Render("/staticpage/" + pagename)
 }
 func (m *Me) MeIndex() error {
-	userid := qutil.ObjToString(m.GetSession("mgoUserId"))
-	//检测用户是否绑定邮箱
-	if userid != "" {
-		b := jy.GetBigVipUserBaseMsg(m.Session(), *config.Middleground)
-		if b.Email == "" {
-			m.T["isNoEmail"] = true
-		}
-		if b.VipStatus > 0 {
-			m.T["isVip"] = true
-		}
-		m.T["member_status"] = b.Status
-		power := []int{} //GetNewPower(userid)
-		for k := range b.PowerMap {
-			power = append(power, k)
-		}
-		m.T["power"] = power
-	} else {
-		return m.Redirect("/jyapp/free/login?back=index&flag=quit")
-	}
-	m.T["isIosExam"], m.T["isIosExamPhone"], _, m.T["isEnt"] = IosExamInfo(m.Action, false, true)
-	return m.Render("/me/mine.html", &m.T)
+    userid := qutil.ObjToString(m.GetSession("mgoUserId"))
+    //检测用户是否绑定邮箱
+    if userid != "" {
+        b := jy.GetBigVipUserBaseMsg(m.Session(), *config.Middleground)
+        if b.Email == "" {
+            m.T["isNoEmail"] = true
+        }
+        if b.VipStatus > 0 {
+            m.T["isVip"] = true
+        }
+        m.T["member_status"] = b.Status
+        power := []int{} //GetNewPower(userid)
+        for k := range b.PowerMap {
+            power = append(power, k)
+        }
+        m.T["power"] = power
+    } else {
+        return m.Redirect("/jyapp/free/login?back=index&flag=quit")
+    }
+    m.T["isIosExam"], m.T["isIosExamPhone"], _, m.T["isEnt"] = IosExamInfo(m.Action, false, true)
+    return m.Render("/me/mine.html", &m.T)
 }
 func (m *Me) MeSet() error {
-	return m.Render("/me/setting.html")
+    return m.Render("/me/setting.html")
 }
 func (m *Me) MeSetPhone() error {
-	return m.Render("/me/setphone.html")
+    return m.Render("/me/setphone.html")
 }
 func (m *Me) MeCustomer() error {
-	return m.Render("/me/customer.html")
+    return m.Render("/me/customer.html")
 }
 
 func (m *Me) Meset_info() {
-	userid := qutil.ObjToString(m.GetSession("mgoUserId"))
-	hasPwd := false
-	isVip := false
-	if userid != "" {
-		user, ok := mongodb.FindById("user", userid, `{"s_password":1}`)
-		if ok && user != nil {
-			if qutil.ObjToString((*user)["s_password"]) != "" {
-				hasPwd = true
-			}
-			b := jy.GetBigVipUserBaseMsg(m.Session(), *config.Middleground)
-			if b.VipStatus > 0 {
-				isVip = true
-			}
-		}
+    userid := qutil.ObjToString(m.GetSession("mgoUserId"))
+    hasPwd := false
+    isVip := false
+    if userid != "" {
+        user := utils.Compatible.Select(userid, `{"s_password":1}`)
+        if user != nil {
+            if qutil.ObjToString((*user)["s_password"]) != "" {
+                hasPwd = true
+            }
+            b := jy.GetBigVipUserBaseMsg(m.Session(), *config.Middleground)
+            if b.VipStatus > 0 {
+                isVip = true
+            }
+        }
 
-	}
-	m.ServeJson(map[string]interface{}{
-		"isVip":  isVip,
-		"hasPwd": hasPwd,
-	})
+    }
+    m.ServeJson(map[string]interface{}{
+        "isVip":  isVip,
+        "hasPwd": hasPwd,
+    })
 }
 func (m *Me) PushMsgSet() error {
-	return m.Render("/me/pushMsgSet.html")
+    return m.Render("/me/pushMsgSet.html")
 }
 func (m *Me) Iframe() error {
-	return m.Render("/me/iframe.html")
+    return m.Render("/me/iframe.html")
 }
 func (m *Me) SolveWay() error {
-	return m.Render("/me/solveWay.html")
+    return m.Render("/me/solveWay.html")
 }
 func (m *Me) Notice() error {
-	userId, _ := m.GetSession("userId").(string)
-	if userId != "" {
-		mongodb.Update("jyapp_notice", map[string]interface{}{
-			"s_userid": userId,
-			"i_unread": 1,
-			"$and":     []bson.M{{"s_type": bson.M{"$ne": "message"}}, {"s_type": bson.M{"$ne": "titleMessage"}}},
-		}, map[string]interface{}{
-			"$set": map[string]interface{}{
-				"i_unread":    0,
-				"l_timestamp": time.Now().Unix(),
-			},
-		}, false, true)
-	}
-	return m.Render("/me/notice.html")
+    userId, _ := m.GetSession("userId").(string)
+    if userId != "" {
+        mongodb.Update("jyapp_notice", map[string]interface{}{
+            "s_userid": userId,
+            "i_unread": 1,
+            "$and":     []bson.M{{"s_type": bson.M{"$ne": "message"}}, {"s_type": bson.M{"$ne": "titleMessage"}}},
+        }, map[string]interface{}{
+            "$set": map[string]interface{}{
+                "i_unread":    0,
+                "l_timestamp": time.Now().Unix(),
+            },
+        }, false, true)
+    }
+    return m.Render("/me/notice.html")
 }
 func (m *Me) NoticeList() {
-	userId, _ := m.GetSession("userId").(string)
-	pageNum, _ := m.GetInteger("pageNum")
-	var list *[]map[string]interface{}
-	if userId != "" {
-		list, _ = mongodb.Find("jyapp_notice", map[string]interface{}{
-			"s_userid": userId,
-		}, `{"l_comeintime":-1}`, nil, false, pageNum*100, 100)
-	}
-	if public.Mysql.CountBySql("select count(*) from dis_partner where uid=? and type!=3 ", userId) > 0 {
-		for key := range *list {
-			(*list)[key]["isExhibition"] = false
-		}
-	} else {
-		for key := range *list {
-			(*list)[key]["isExhibition"] = true
-		}
-	}
-	m.ServeJson(map[string]interface{}{
-		"list": list,
-	})
+    userId, _ := m.GetSession("userId").(string)
+    pageNum, _ := m.GetInteger("pageNum")
+    var list *[]map[string]interface{}
+    if userId != "" {
+        list, _ = mongodb.Find("jyapp_notice", map[string]interface{}{
+            "s_userid": userId,
+        }, `{"l_comeintime":-1}`, nil, false, pageNum*100, 100)
+    }
+    if public.Mysql.CountBySql("select count(*) from dis_partner where uid=? and type!=3 ", userId) > 0 {
+        for key := range *list {
+            (*list)[key]["isExhibition"] = false
+        }
+    } else {
+        for key := range *list {
+            (*list)[key]["isExhibition"] = true
+        }
+    }
+    m.ServeJson(map[string]interface{}{
+        "list": list,
+    })
 }
 func (m *Me) Download(from string) error {
-	m.T["from"] = from
-	m.T["source"] = m.GetString("source")
-	m.T["code"] = m.GetString("code")
-	return m.Render("/me/download.html", &m.T)
+    m.T["from"] = from
+    m.T["source"] = m.GetString("source")
+    m.T["code"] = m.GetString("code")
+    return m.Render("/me/download.html", &m.T)
 }
 func (l *Me) Updatepwd() error {
-	defer qutil.Catch()
-	if l.Method() == "GET" {
-		return l.Render("/me/updatepwd.html")
-	}
-	status := func() string {
-		userid := qutil.ObjToString(l.GetSession("mgoUserId"))
-		if userid == "" {
-			return "timeout"
-		}
-		user, ok := mongodb.FindById("user", userid, `{"s_password":1}`)
-		if !ok || user == nil || len(*user) == 0 {
-			return ""
-		}
-		oldpwd := l.GetString("oldpwd")
-		newpwd := l.GetString("newpwd")
-		if !passwordReg.MatchString(strings.TrimSpace(oldpwd)) || !passwordReg.MatchString(strings.TrimSpace(newpwd)) {
-			return "pwdFormatError"
-		}
-		password, _ := (*user)["s_password"].(string)
-		if password != qutil.GetMd5String(oldpwd) {
-			return "pwdError"
-		}
-		if mongodb.UpdateById("user", userid, map[string]interface{}{
-			"$set": map[string]interface{}{
-				"s_password":      qutil.GetMd5String(newpwd),
-				"l_updatepwdtime": time.Now().Unix(), //增加修改密码时间
-			},
-		}) {
-			//调用用户中台
-			ck, _ := l.GetCookie("SESSIONID")
-			usercenter.UpdateBaseUser(mongodb, qutil.ObjToString(config.Sysconfig["userCenterApi"]), userid, ck)
-			return "y"
-		} else {
-			return "saveError"
-		}
-	}()
-	l.ServeJson(map[string]interface{}{
-		"status": status,
-	})
-	return nil
+    defer qutil.Catch()
+    if l.Method() == "GET" {
+        return l.Render("/me/updatepwd.html")
+    }
+    status := func() string {
+        userid := qutil.ObjToString(l.GetSession("mgoUserId"))
+        if userid == "" {
+            return "timeout"
+        }
+        user:=utils.Compatible.Select( userid, `{"s_password":1}`)
+        if  user == nil || len(*user) == 0 {
+            return ""
+        }
+        oldpwd := l.GetString("oldpwd")
+        newpwd := l.GetString("newpwd")
+        if !passwordReg.MatchString(strings.TrimSpace(oldpwd)) || !passwordReg.MatchString(strings.TrimSpace(newpwd)) {
+            return "pwdFormatError"
+        }
+        password, _ := (*user)["s_password"].(string)
+        if password != qutil.GetMd5String(oldpwd) {
+            return "pwdError"
+        }
+        if utils.Compatible.Update(userid, map[string]interface{}{
+            "$set": map[string]interface{}{
+                "s_password":      qutil.GetMd5String(newpwd),
+                "l_updatepwdtime": time.Now().Unix(), //增加修改密码时间
+            },
+        }) {
+            //调用用户中台
+            ck, _ := l.GetCookie("SESSIONID")
+            usercenter.UpdateBaseUser(mongodb, qutil.ObjToString(config.Sysconfig["userCenterApi"]), userid, ck)
+            return "y"
+        } else {
+            return "saveError"
+        }
+    }()
+    l.ServeJson(map[string]interface{}{
+        "status": status,
+    })
+    return nil
 }
 
 //
 func (l *Me) CheckUpdate() error {
-	defer qutil.Catch()
-	channel := l.GetString("channel")
-	u, s := analySign("", l.GetString("token"))
-	userId := ""
-	if s == 1 {
-		userId = u.UserId
-	}
-	if userId == "" {
-		userId, _ = l.GetSession("mgoUserId").(string)
-	}
-	isNeedUpdate := 0
-	update, _ := config.Sysconfig["update"].(map[string]interface{})
-	grayUpdate, _ := update["grayupdate"].(bool)
-	newChannel := channel
-	newSystem := -1
-	if strings.HasPrefix(l.GetString("from"), "server-") {
-		system, err := l.GetInt("system")
-		if err == nil && system >= 11 {
-			newSystem = int(system)
-		}
-	}
-	version := l.GetString("version")
-	updateFlag := ClientUpdate.IsNeedUpdate(userId, version, qutil.ObjToString(update["version"]), newChannel, newSystem, grayUpdate)
-	if updateFlag {
-		if mustupdate, _ := update["mustupdate"].(bool); mustupdate {
-			isNeedUpdate = 2
-		} else {
-			isNeedUpdate = 1
-		}
-	}
-	isBrowserUpdate := qutil.IntAll(update["isBrowserUpdate"])
-	if grayUpdate {
-		isBrowserUpdate = 4
-	}
-	result := map[string]interface{}{
-		"isNeedUpdate":    isNeedUpdate,       //0:不需要更新 1:提示更新 2:强制更新
-		"isBrowserUpdate": isBrowserUpdate,    //0:只走app内部更新 1:先app内部更新,再走应用市场,再走浏览器更新 2:只走浏览器更新 3:先app内部更新,再走应用市场 4:先app内部更新,再走浏览器更新
-		"version":         update["version"],  //新版本号
-		"tipspace":        update["tipspace"], //提示间隔时间
-		"apkurl":          ClientUpdate.ApkUrl(channel, qutil.ObjToString(update["apkurl"])),
-	}
-	if version == "" { //3.0.3及以前版本
-		exists := false
-		if userId != "" {
-			exists, _ = redis.Exists(ClientUpdate.RedisCode, "app_clientupdate_"+userId)
-			if exists {
-				redis.Del(ClientUpdate.RedisCode, "app_clientupdate_"+userId)
-			}
-		}
-		if exists {
-			result["mustupdate"] = update["mustupdate"]
-			result["userflag"] = updateFlag
-		} else {
-			result["mustupdate"] = false
-			result["userflag"] = false
-			result["version"] = "3.0.3"
-		}
-	}
-	if userId != "" && (l.GetString("from") == "server-appVersion-2" || l.GetString("from") == "server-mainSearch") {
-		redis.Put(ClientUpdate.RedisCode, "app_clientupdate_"+userId, 1, 5)
-	}
-	l.ServeJson(result)
-	return nil
+    defer qutil.Catch()
+    channel := l.GetString("channel")
+    u, s := analySign("", l.GetString("token"))
+    userId := ""
+    if s == 1 {
+        userId = u.UserId
+    }
+    if userId == "" {
+        userId, _ = l.GetSession("mgoUserId").(string)
+    }
+    isNeedUpdate := 0
+    update, _ := config.Sysconfig["update"].(map[string]interface{})
+    grayUpdate, _ := update["grayupdate"].(bool)
+    newChannel := channel
+    newSystem := -1
+    if strings.HasPrefix(l.GetString("from"), "server-") {
+        system, err := l.GetInt("system")
+        if err == nil && system >= 11 {
+            newSystem = int(system)
+        }
+    }
+    version := l.GetString("version")
+    updateFlag := ClientUpdate.IsNeedUpdate(userId, version, qutil.ObjToString(update["version"]), newChannel, newSystem, grayUpdate)
+    if updateFlag {
+        if mustupdate, _ := update["mustupdate"].(bool); mustupdate {
+            isNeedUpdate = 2
+        } else {
+            isNeedUpdate = 1
+        }
+    }
+    isBrowserUpdate := qutil.IntAll(update["isBrowserUpdate"])
+    if grayUpdate {
+        isBrowserUpdate = 4
+    }
+    result := map[string]interface{}{
+        "isNeedUpdate":    isNeedUpdate,       //0:不需要更新 1:提示更新 2:强制更新
+        "isBrowserUpdate": isBrowserUpdate,    //0:只走app内部更新 1:先app内部更新,再走应用市场,再走浏览器更新 2:只走浏览器更新 3:先app内部更新,再走应用市场 4:先app内部更新,再走浏览器更新
+        "version":         update["version"],  //新版本号
+        "tipspace":        update["tipspace"], //提示间隔时间
+        "apkurl":          ClientUpdate.ApkUrl(channel, qutil.ObjToString(update["apkurl"])),
+    }
+    if version == "" { //3.0.3及以前版本
+        exists := false
+        if userId != "" {
+            exists, _ = redis.Exists(ClientUpdate.RedisCode, "app_clientupdate_"+userId)
+            if exists {
+                redis.Del(ClientUpdate.RedisCode, "app_clientupdate_"+userId)
+            }
+        }
+        if exists {
+            result["mustupdate"] = update["mustupdate"]
+            result["userflag"] = updateFlag
+        } else {
+            result["mustupdate"] = false
+            result["userflag"] = false
+            result["version"] = "3.0.3"
+        }
+    }
+    if userId != "" && (l.GetString("from") == "server-appVersion-2" || l.GetString("from") == "server-mainSearch") {
+        redis.Put(ClientUpdate.RedisCode, "app_clientupdate_"+userId, 1, 5)
+    }
+    l.ServeJson(result)
+    return nil
 }
 
 /*
@@ -294,193 +294,187 @@ func (l *Me) CheckUpdate() error {
     error           //下载失败的异常信息
 */
 func (l *Me) NewVersionUpdateLog() {
-	u, s := analySign("", l.GetString("token"))
-	userId := ""
-	if u != nil && s == 1 {
-		userId = u.UserId
-	}
-	if l.GetString("event") == "server_tip" && userId != "" {
-		redis.Del(ClientUpdate.RedisCode, "app_clientupdate_"+userId)
-	}
-	public.Mgo_Log.Save("jyapp_newversion_updatelog", map[string]interface{}{
-		"createtime":      time.Now().Unix(),
-		"userid":          userId,
-		"event":           l.GetString("event"),
-		"current_version": l.GetString("current_version"),
-		"new_version":     l.GetString("new_version"),
-		"channel":         l.GetString("channel"),
-		"phonetype":       l.GetString("phonetype"),
-		"system":          l.GetString("system"),
-		"ip":              l.IP(),
-		"proxy":           l.Proxy(),
-		"user-agent":      l.Header("User-Agent"),
-		"error":           l.GetString("error"),
-	})
-	l.ServeJson(map[string]interface{}{})
+    u, s := analySign("", l.GetString("token"))
+    userId := ""
+    if u != nil && s == 1 {
+        userId = u.UserId
+    }
+    if l.GetString("event") == "server_tip" && userId != "" {
+        redis.Del(ClientUpdate.RedisCode, "app_clientupdate_"+userId)
+    }
+    public.Mgo_Log.Save("jyapp_newversion_updatelog", map[string]interface{}{
+        "createtime":      time.Now().Unix(),
+        "userid":          userId,
+        "event":           l.GetString("event"),
+        "current_version": l.GetString("current_version"),
+        "new_version":     l.GetString("new_version"),
+        "channel":         l.GetString("channel"),
+        "phonetype":       l.GetString("phonetype"),
+        "system":          l.GetString("system"),
+        "ip":              l.IP(),
+        "proxy":           l.Proxy(),
+        "user-agent":      l.Header("User-Agent"),
+        "error":           l.GetString("error"),
+    })
+    l.ServeJson(map[string]interface{}{})
 }
 
 //
 func (l *Me) MyInfo() {
-	r := map[string]interface{}{
-		"userType": "free",
-	}
-	userId, _ := l.GetSession("userId").(string)
-	positionType := qutil.Int64All(l.GetSession("positionType"))
-	user, ok := &map[string]interface{}{}, false
-	if positionType == 0 {
-		user, ok = mongodb.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,"o_jy":1,"i_vip_status":1,"l_vip_endtime":1,"o_vipjy":1,"i_vip_subtips":1,"i_entniche_first":1}`)
-	} else {
-
-	}
-	if ok && user != nil {
-		isExpire := -1
-		isPassCount := false
-		hasKeyFlag := false
-		tedayNum := time.Unix(time.Now().Unix(), 1).Format("20060102")
-		if qutil.IntAll((*user)["i_vip_status"]) > 0 {
-			r["userType"] = "vip"
-			var threeRemind = int64(3 * 24 * 60 * 60)
-			var twoRemind = int64(2 * 24 * 60 * 60)
-			var oneRemind = int64(1 * 24 * 60 * 60)
-			_endtime := qutil.Int64All((*user)["l_vip_endtime"])
-			now_unix := time.Now().Unix()
-			//是否到期
-			if _endtime-now_unix < threeRemind && _endtime-now_unix >= twoRemind {
-				isExpire = 3 //即将到期
-			} else if _endtime-now_unix < twoRemind && _endtime-now_unix >= oneRemind {
-				isExpire = 2 //即将到期
-			} else if _endtime-now_unix < oneRemind && _endtime-now_unix >= 0 {
-				isExpire = 1 //即将到期
-			}
-			isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+tedayNum+"_"+userId) >= 2000
-			o_vipjy, _ := (*user)["o_vipjy"].(map[string]interface{})
-			if o_vipjy["a_items"] != nil {
-				a_itmes := qutil.ObjArrToMapArr(o_vipjy["a_items"].([]interface{}))
-				hasKeyFlag = len(a_itmes) > 0
-			}
-		} else {
-			isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+tedayNum+"_"+userId) >= 150
-			o_jy, _ := (*user)["o_jy"].(map[string]interface{})
-			if o_jy != nil || len(o_jy) == 0 {
-				a_key, _ := o_jy["a_key"].([]interface{})
-				hasKeyFlag = len(a_key) > 0
-			}
-		}
-		//商机管理处理
-		phone := ""
-		if s_phone, _ := (*user)["s_phone"].(string); s_phone != "" {
-			phone = s_phone
-		} else if s_m_phone, _ := (*user)["s_m_phone"].(string); s_m_phone != "" {
-			phone = s_m_phone
-		}
-		isEnt := false
-		if phone != "" {
-			//已购买企业未过期
-			log.Println("SELECT status FROM entniche_info WHERE id  IN (SELECT ent_id FROM entniche_user where phone = ? and power =1", phone)
-			if entInfo := public.Mysql.SelectBySql(`SELECT status,isNew FROM entniche_info WHERE id  IN (SELECT ent_id FROM entniche_user where phone = ? and power =1)`, phone); len((*entInfo)) > 0 {
-				for _, v := range *entInfo {
-					//&& qutil.IntAll(v["isNew"]
-					if qutil.IntAll(v["status"]) == 1 {
-						isEnt = true
-						break
-					}
+    r := map[string]interface{}{
+        "userType": "free",
+    }
+    userId, _ := l.GetSession("userId").(string)
+    user := utils.Compatible.Select(userId, `{"s_phone":1,"s_m_phone":1,"o_jy":1,"i_vip_status":1,"l_vip_endtime":1,"o_vipjy":1,"i_vip_subtips":1,"i_entniche_first":1}`)
+    if user != nil {
+        isExpire := -1
+        isPassCount := false
+        hasKeyFlag := false
+        tedayNum := time.Unix(time.Now().Unix(), 1).Format("20060102")
+        if qutil.IntAll((*user)["i_vip_status"]) > 0 {
+            r["userType"] = "vip"
+            var threeRemind = int64(3 * 24 * 60 * 60)
+            var twoRemind = int64(2 * 24 * 60 * 60)
+            var oneRemind = int64(1 * 24 * 60 * 60)
+            _endtime := qutil.Int64All((*user)["l_vip_endtime"])
+            now_unix := time.Now().Unix()
+            //是否到期
+            if _endtime-now_unix < threeRemind && _endtime-now_unix >= twoRemind {
+                isExpire = 3 //即将到期
+            } else if _endtime-now_unix < twoRemind && _endtime-now_unix >= oneRemind {
+                isExpire = 2 //即将到期
+            } else if _endtime-now_unix < oneRemind && _endtime-now_unix >= 0 {
+                isExpire = 1 //即将到期
+            }
+            isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+tedayNum+"_"+userId) >= 2000
+            o_vipjy, _ := (*user)["o_vipjy"].(map[string]interface{})
+            if o_vipjy["a_items"] != nil {
+                a_itmes := qutil.ObjArrToMapArr(o_vipjy["a_items"].([]interface{}))
+                hasKeyFlag = len(a_itmes) > 0
+            }
+        } else {
+            isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+tedayNum+"_"+userId) >= 150
+            o_jy, _ := (*user)["o_jy"].(map[string]interface{})
+            if o_jy != nil || len(o_jy) == 0 {
+                a_key, _ := o_jy["a_key"].([]interface{})
+                hasKeyFlag = len(a_key) > 0
+            }
+        }
+        //商机管理处理
+        phone := ""
+        if s_phone, _ := (*user)["s_phone"].(string); s_phone != "" {
+            phone = s_phone
+        } else if s_m_phone, _ := (*user)["s_m_phone"].(string); s_m_phone != "" {
+            phone = s_m_phone
+        }
+        isEnt := false
+        if phone != "" {
+            //已购买企业未过期
+            log.Println("SELECT status FROM entniche_info WHERE id  IN (SELECT ent_id FROM entniche_user where phone = ? and power =1", phone)
+            if entInfo := public.Mysql.SelectBySql(`SELECT status,isNew FROM entniche_info WHERE id  IN (SELECT ent_id FROM entniche_user where phone = ? and power =1)`, phone); len((*entInfo)) > 0 {
+                for _, v := range *entInfo {
+                    //&& qutil.IntAll(v["isNew"]
+                    if qutil.IntAll(v["status"]) == 1 {
+                        isEnt = true
+                        break
+                    }
 
-				}
-			}
-		}
-		if isEnt {
-			r["userType"] = "entniche"
-		}
-		r["isExpire"] = isExpire
-		r["vipStatus"] = qutil.IntAll((*user)["i_vip_status"])
-		r["isPassCount"] = isPassCount
-		r["haskey"] = hasKeyFlag
-	}
-	l.ServeJson(r)
+                }
+            }
+        }
+        if isEnt {
+            r["userType"] = "entniche"
+        }
+        r["isExpire"] = isExpire
+        r["vipStatus"] = qutil.IntAll((*user)["i_vip_status"])
+        r["isPassCount"] = isPassCount
+        r["haskey"] = hasKeyFlag
+    }
+    l.ServeJson(r)
 }
 
 //
 func (l *Me) AccountSafe() error {
-	return l.Render("/me/account.html")
+    return l.Render("/me/account.html")
 }
 
 func (l *Me) GetAccountInfo() {
-	userid := l.GetSession("mgoUserId").(string)
-	info := map[string]interface{}{}
+    userid := l.GetSession("mgoUserId").(string)
+    info := map[string]interface{}{}
 
-	res, _ := public.MQFW.FindById("user", userid, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
-	delete(*res, "_id")
-	if len(*res) > 0 {
-		if (*res)["s_myemail"] != nil {
-			info["email"] = (*res)["s_myemail"]
-		}
-		if s_phone, _ := (*res)["s_phone"].(string); s_phone != "" {
-			info["phone"] = s_phone
-		} else if s_m_phone, _ := (*res)["s_m_phone"].(string); s_m_phone != "" {
-			info["phone"] = s_m_phone
-		}
-	}
-	l.ServeJson(map[string]interface{}{
-		"data": info,
-	})
-	return
+    res := utils.Compatible.Select( userid, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
+    delete(*res, "_id")
+    if len(*res) > 0 {
+        if (*res)["s_myemail"] != nil {
+            info["email"] = (*res)["s_myemail"]
+        }
+        if s_phone, _ := (*res)["s_phone"].(string); s_phone != "" {
+            info["phone"] = s_phone
+        } else if s_m_phone, _ := (*res)["s_m_phone"].(string); s_m_phone != "" {
+            info["phone"] = s_m_phone
+        }
+    }
+    l.ServeJson(map[string]interface{}{
+        "data": info,
+    })
+    return
 }
 
 //
 func (l *Me) ControlGrayUpdate(t string) {
-	if l.GetString("pwd") != "lHJ5agM3eiKczOPk3IVj" {
-		l.Write("密码错误!")
-		return
-	}
-	value := l.GetForm()["v"]
-	redisAddr := map[string]string{}
-	for _, v := range strings.Split(public.DbConf.Redis.Main.Address, ",") {
-		rs := strings.Split(v, "=")
-		if len(rs) == 2 {
-			redisAddr[rs[0]] = rs[1]
-		}
-	}
-	if t == "user" {
-		if len(value) == 0 {
-			l.Write("请连redis %s 使用命令 keys app_grayupdate_appoint_user_* 查看具体灰度更新人员名单", redisAddr[ClientUpdate.RedisCode])
-		} else {
-			redis.DelByCodePattern(ClientUpdate.RedisCode, "app_grayupdate_appoint_user_*")
-			if value[0] == "" {
-				l.Write("已清除灰度更新人员名单")
-			} else {
-				for _, v := range strings.Split(value[0], ",") {
-					redis.PutCKV(ClientUpdate.RedisCode, "app_grayupdate_appoint_user_"+v, 1)
-				}
-				l.Write("灰度发布人员名单:<br>&nbsp;&nbsp;&nbsp;%s", strings.ReplaceAll(value[0], ",", "<br>&nbsp;&nbsp;&nbsp;"))
-			}
-		}
-	} else if t == "channel" {
-		if len(value) == 0 {
-			msg := fmt.Sprintf("请连redis %s 使用命令 keys app_grayupdate_channel_user_* 查看渠道内灰度更新人员名单", redisAddr[ClientUpdate.RedisCode])
-			msg += "<br><br>渠道灰度更新配置详情:"
-			for _, v := range redis.GetKeysByPattern(ClientUpdate.RedisCode, "app_grayupdate_channel_max_*") {
-				vv := string(v.([]uint8))
-				msg += fmt.Sprintf("<br>&nbsp;&nbsp;&nbsp;渠道名:%s,最大数:%d,当前数:%d", strings.TrimPrefix(vv, "app_grayupdate_channel_max_"), qutil.IntAll(redis.Get(ClientUpdate.RedisCode, vv)), qutil.IntAll(redis.Get(ClientUpdate.RedisCode, strings.ReplaceAll(vv, "_max_", "_count_"))))
-			}
-			l.Write(msg)
-		} else {
-			if value[0] == "" {
-				redis.DelByCodePattern(ClientUpdate.RedisCode, "app_grayupdate_channel_*")
-				l.Write("已清除渠道灰度更新配置")
-			} else {
-				redis.DelByCodePattern(ClientUpdate.RedisCode, "app_grayupdate_channel_max_*")
-				msg := "增量的渠道灰度更新,如需全量请先清除,配置详情:"
-				for _, v := range strings.Split(value[0], ",") {
-					vs := strings.Split(v, ":")
-					if len(vs) != 2 {
-						continue
-					}
-					if redis.PutCKV(ClientUpdate.RedisCode, "app_grayupdate_channel_max_"+vs[0], qutil.IntAll(vs[1])) {
-						msg += fmt.Sprintf("<br>&nbsp;&nbsp;&nbsp;渠道名:%s,最大数:%s", vs[0], vs[1])
-					}
-				}
-				l.Write(msg)
-			}
-		}
-	}
+    if l.GetString("pwd") != "lHJ5agM3eiKczOPk3IVj" {
+        l.Write("密码错误!")
+        return
+    }
+    value := l.GetForm()["v"]
+    redisAddr := map[string]string{}
+    for _, v := range strings.Split(public.DbConf.Redis.Main.Address, ",") {
+        rs := strings.Split(v, "=")
+        if len(rs) == 2 {
+            redisAddr[rs[0]] = rs[1]
+        }
+    }
+    if t == "user" {
+        if len(value) == 0 {
+            l.Write("请连redis %s 使用命令 keys app_grayupdate_appoint_user_* 查看具体灰度更新人员名单", redisAddr[ClientUpdate.RedisCode])
+        } else {
+            redis.DelByCodePattern(ClientUpdate.RedisCode, "app_grayupdate_appoint_user_*")
+            if value[0] == "" {
+                l.Write("已清除灰度更新人员名单")
+            } else {
+                for _, v := range strings.Split(value[0], ",") {
+                    redis.PutCKV(ClientUpdate.RedisCode, "app_grayupdate_appoint_user_"+v, 1)
+                }
+                l.Write("灰度发布人员名单:<br>&nbsp;&nbsp;&nbsp;%s", strings.ReplaceAll(value[0], ",", "<br>&nbsp;&nbsp;&nbsp;"))
+            }
+        }
+    } else if t == "channel" {
+        if len(value) == 0 {
+            msg := fmt.Sprintf("请连redis %s 使用命令 keys app_grayupdate_channel_user_* 查看渠道内灰度更新人员名单", redisAddr[ClientUpdate.RedisCode])
+            msg += "<br><br>渠道灰度更新配置详情:"
+            for _, v := range redis.GetKeysByPattern(ClientUpdate.RedisCode, "app_grayupdate_channel_max_*") {
+                vv := string(v.([]uint8))
+                msg += fmt.Sprintf("<br>&nbsp;&nbsp;&nbsp;渠道名:%s,最大数:%d,当前数:%d", strings.TrimPrefix(vv, "app_grayupdate_channel_max_"), qutil.IntAll(redis.Get(ClientUpdate.RedisCode, vv)), qutil.IntAll(redis.Get(ClientUpdate.RedisCode, strings.ReplaceAll(vv, "_max_", "_count_"))))
+            }
+            l.Write(msg)
+        } else {
+            if value[0] == "" {
+                redis.DelByCodePattern(ClientUpdate.RedisCode, "app_grayupdate_channel_*")
+                l.Write("已清除渠道灰度更新配置")
+            } else {
+                redis.DelByCodePattern(ClientUpdate.RedisCode, "app_grayupdate_channel_max_*")
+                msg := "增量的渠道灰度更新,如需全量请先清除,配置详情:"
+                for _, v := range strings.Split(value[0], ",") {
+                    vs := strings.Split(v, ":")
+                    if len(vs) != 2 {
+                        continue
+                    }
+                    if redis.PutCKV(ClientUpdate.RedisCode, "app_grayupdate_channel_max_"+vs[0], qutil.IntAll(vs[1])) {
+                        msg += fmt.Sprintf("<br>&nbsp;&nbsp;&nbsp;渠道名:%s,最大数:%s", vs[0], vs[1])
+                    }
+                }
+                l.Write(msg)
+            }
+        }
+    }
 }

+ 4 - 3
src/jfw/modules/app/src/app/front/myorder.go

@@ -1,7 +1,8 @@
 package front
 
 import (
-	"strconv"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "strconv"
 	"strings"
 
 	util "app.yhyue.com/moapp/jybase/common"
@@ -118,8 +119,8 @@ func (m *MyOrder) MyEmail() {
 	if util.ObjToString(m.GetSession("userId")) != "" {
 		m.T["userId"] = util.ObjToString(m.GetSession("userId"))
 	}
-	res, err := mongodb.FindById("user", util.ObjToString(m.GetSession("userId")), nil)
-	if len(*res) > 0 && err {
+	res := utils.Compatible.Select( util.ObjToString(m.GetSession("userId")), nil)
+	if len(*res) > 0  {
 		if util.ObjToString((*res)["s_myemail"]) == "" || name != "" {
 			//未绑定邮箱 进入绑定邮箱界面
 			if name != "" && util.ObjToString((*res)["s_myemail"]) != "" {

+ 144 - 144
src/jfw/modules/app/src/app/front/search.go

@@ -1,171 +1,171 @@
 package front
 
 import (
-	"fmt"
-	"jy/src/jfw/modules/app/src/app/jylabutil"
-	"jy/src/jfw/modules/app/src/app/tag"
-	. "jy/src/jfw/modules/app/src/jfw/config"
-	"strings"
+    "fmt"
+    "jy/src/jfw/modules/app/src/app/jylabutil"
+    . "jy/src/jfw/modules/app/src/app/jyutil"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/app/tag"
+    . "jy/src/jfw/modules/app/src/jfw/config"
+    "strings"
 
-	. "jy/src/jfw/modules/app/src/app/jyutil"
-
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"app.yhyue.com/moapp/jybase/redis"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jybase/redis"
 )
 
 type Search struct {
-	*xweb.Action
-	mainSearch          xweb.Mapper `xweb:"/jyapp/jylab/mainSearch"` //剑鱼标讯搜索主页面
-	searchIndex         xweb.Mapper `xweb:"/jyapp/free/searchIndex"`
-	getstatus           xweb.Mapper `xweb:"/jyapp/jylab/supsearch/getstatus"`
-	getHK               xweb.Mapper `xweb:"/jyapp/jylab/mainSearch/getHK"` //获取历史记录,订阅关键词
-	updateSearchHistory xweb.Mapper `xweb:"/jyapp/jylab/updateSearchHistory"`
-	site                xweb.Mapper `xweb:"/jyapp/free/site"`
+    *xweb.Action
+    mainSearch          xweb.Mapper `xweb:"/jyapp/jylab/mainSearch"` //剑鱼标讯搜索主页面
+    searchIndex         xweb.Mapper `xweb:"/jyapp/free/searchIndex"`
+    getstatus           xweb.Mapper `xweb:"/jyapp/jylab/supsearch/getstatus"`
+    getHK               xweb.Mapper `xweb:"/jyapp/jylab/mainSearch/getHK"` //获取历史记录,订阅关键词
+    updateSearchHistory xweb.Mapper `xweb:"/jyapp/jylab/updateSearchHistory"`
+    site                xweb.Mapper `xweb:"/jyapp/free/site"`
 }
 
 func init() {
-	xweb.AddAction(&Search{})
+    xweb.AddAction(&Search{})
 }
 
 //
 func (s *Search) Site() error {
-	//l:是否需要登录访问 0:不需要登录;1、2:需要登录(1:内部链接;2:外部链接)
-	l, _ := s.GetInteger("l")
-	//u:访问地址
-	userid := util.ObjToString(s.GetSession("userId"))
-	u := s.GetString("u")
-	if l > -1 && u != "" {
-		if l > 0 && userid == "" {
-			//需要登录 且 未登录状态
-			switch l { //内部链接
-			case 1:
-				u = fmt.Sprintf("/jyapp/free/login?url=%s", u)
-			case 2: //外部链接
-				u = fmt.Sprintf("/jyapp/free/login?out=%s", u)
-			}
-		}
-		return s.Redirect(u)
-	} else if userid == "" {
-		s.Redirect("/jyapp/free/login?back=index")
-	}
-	return s.Redirect("/jyapp/jylab/mainSearch")
+    //l:是否需要登录访问 0:不需要登录;1、2:需要登录(1:内部链接;2:外部链接)
+    l, _ := s.GetInteger("l")
+    //u:访问地址
+    userid := util.ObjToString(s.GetSession("userId"))
+    u := s.GetString("u")
+    if l > -1 && u != "" {
+        if l > 0 && userid == "" {
+            //需要登录 且 未登录状态
+            switch l { //内部链接
+            case 1:
+                u = fmt.Sprintf("/jyapp/free/login?url=%s", u)
+            case 2: //外部链接
+                u = fmt.Sprintf("/jyapp/free/login?out=%s", u)
+            }
+        }
+        return s.Redirect(u)
+    } else if userid == "" {
+        s.Redirect("/jyapp/free/login?back=index")
+    }
+    return s.Redirect("/jyapp/jylab/mainSearch")
 }
 
 //
 func (s *Search) MainSearch() error {
-	return s.Redirect("/jy_mobile/tabbar/home")
-	// 	if len(industrylist) > 0 {
-	// 		s.T["industry"] = industrylist
-	// 		s.T["sortArray"] = sortArray
-	// 	} else {
-	// 		industry, sortA := jy.Getindustrys(util.ObjToString(Sysconfig["industry"]), public.MQFW)
-	// 		s.T["industry"] = industry
-	// 		s.T["sortArray"] = sortA
-	// 	}
-	// 	s.T["pageSize"] = bidsearch.SearchPageSize_APP
-	// 	//搜索列表增加分享
-	// 	s.T["searchWord"] = s.GetString("searchWord")
-	// 	if now_unix := time.Now().Unix(); now_unix >= app_config.Active.Pullnew.StartTime && now_unix <= app_config.Active.Pullnew.EndTime {
-	// 		s.T["pullnew"] = true
-	// 	} else {
-	// 		s.T["pullnew"] = false
-	// 	}
-	// 	s.T["isIosExam"], s.T["isIosExamPhone"], _, _ = IosExamInfo(s.Action, false, false)
-	// 	return s.Render("/weixin/search/mainSearch.html", &s.T)
+    return s.Redirect("/jy_mobile/tabbar/home")
+    // 	if len(industrylist) > 0 {
+    // 		s.T["industry"] = industrylist
+    // 		s.T["sortArray"] = sortArray
+    // 	} else {
+    // 		industry, sortA := jy.Getindustrys(util.ObjToString(Sysconfig["industry"]), public.MQFW)
+    // 		s.T["industry"] = industry
+    // 		s.T["sortArray"] = sortA
+    // 	}
+    // 	s.T["pageSize"] = bidsearch.SearchPageSize_APP
+    // 	//搜索列表增加分享
+    // 	s.T["searchWord"] = s.GetString("searchWord")
+    // 	if now_unix := time.Now().Unix(); now_unix >= app_config.Active.Pullnew.StartTime && now_unix <= app_config.Active.Pullnew.EndTime {
+    // 		s.T["pullnew"] = true
+    // 	} else {
+    // 		s.T["pullnew"] = false
+    // 	}
+    // 	s.T["isIosExam"], s.T["isIosExamPhone"], _, _ = IosExamInfo(s.Action, false, false)
+    // 	return s.Render("/weixin/search/mainSearch.html", &s.T)
 }
 func (p *Search) SearchIndex() {
-	isIosExam, isIosExamPhone, _, _ := IosExamInfo(p.Action, false, false)
-	data, ok := mongodb.FindById("user", util.ObjToString(p.GetSession("userId")), `{"i_member_status":1}`)
-	member := 0
-	if len(*data) > 0 && ok {
-		member = util.IntAll((*data)["i_member_status"])
-	}
-	m := map[string]interface{}{
-		"userId":         encrypt.EncodeArticleId(util.ObjToString(p.GetSession("userId"))),
-		"isIosExam":      isIosExam,
-		"isIosExamPhone": isIosExamPhone,
-		"member":         member,
-	}
-	if ad_name := p.GetString("ad_name"); ad_name != "" {
-		ad_names := strings.Split(ad_name, ",")
-		iosExam, _ := Seoconfig["IosExam"].(map[string]interface{})
-		ad_indexs := strings.Split(p.GetString("ad_index"), ",")
-		for k, v := range ad_names {
-			if isIosExam || isIosExamPhone {
-				iosExam_adv, _ := iosExam["adv"].(map[string]interface{})
-				if iosExam_adv[v] != nil {
-					m[v] = iosExam_adv[v]
-				}
-			} else {
-				index := -1
-				if k < len(ad_indexs) {
-					index = util.IntAll(ad_indexs[k])
-				}
-				m[v] = tag.Ad(v, index, p.Request.Host)
-			}
-		}
-	}
-	p.ServeJson(m)
+    isIosExam, isIosExamPhone, _, _ := IosExamInfo(p.Action, false, false)
+    data := utils.Compatible.Select(util.ObjToString(p.GetSession("userId")), `{"i_member_status":1}`)
+    member := 0
+    if len(*data) > 0  {
+        member = util.IntAll((*data)["i_member_status"])
+    }
+    m := map[string]interface{}{
+        "userId":         encrypt.EncodeArticleId(util.ObjToString(p.GetSession("userId"))),
+        "isIosExam":      isIosExam,
+        "isIosExamPhone": isIosExamPhone,
+        "member":         member,
+    }
+    if ad_name := p.GetString("ad_name"); ad_name != "" {
+        ad_names := strings.Split(ad_name, ",")
+        iosExam, _ := Seoconfig["IosExam"].(map[string]interface{})
+        ad_indexs := strings.Split(p.GetString("ad_index"), ",")
+        for k, v := range ad_names {
+            if isIosExam || isIosExamPhone {
+                iosExam_adv, _ := iosExam["adv"].(map[string]interface{})
+                if iosExam_adv[v] != nil {
+                    m[v] = iosExam_adv[v]
+                }
+            } else {
+                index := -1
+                if k < len(ad_indexs) {
+                    index = util.IntAll(ad_indexs[k])
+                }
+                m[v] = tag.Ad(v, index, p.Request.Host)
+            }
+        }
+    }
+    p.ServeJson(m)
 }
 func (p *Search) Getstatus() error {
-	defer util.Catch()
-	var tablepro bool
-	userid := util.ObjToString(p.GetSession("userId"))
-	if userid != "" {
-		tablepro = jylabutil.IsAuthorized(userid, "i_tablepro")
-	}
-	p.ServeJson(map[string]interface{}{
-		"tablepro": tablepro,
-		"userId":   userid,
-	})
-	return nil
+    defer util.Catch()
+    var tablepro bool
+    userid := util.ObjToString(p.GetSession("userId"))
+    if userid != "" {
+        tablepro = jylabutil.IsAuthorized(userid, "i_tablepro")
+    }
+    p.ServeJson(map[string]interface{}{
+        "tablepro": tablepro,
+        "userId":   userid,
+    })
+    return nil
 }
 
 //获取历史记录和关键词
 func (s *Search) GetHK() error {
-	defer util.Catch()
-	userid, _ := s.GetSession("userId").(string)
-	keys := []interface{}{}
-	arrs := []string{}
-	words := s.GetString("words")
-	if userid != "" {
-		arrs = strings.Split(redis.GetStr("other", "s_"+userid), ",")
-		if words != "" {
-			wordsArr := strings.Split(words, ",")
-			for _, word := range wordsArr {
-				for k, v := range arrs {
-					if v == strings.TrimSpace(word) {
-						arrs = append(arrs[:k], arrs[k+1:]...)
-						break
-					}
-				}
-				arrs = append(arrs, word)
-			}
-		}
-		if len(arrs) > 10 {
-			arrs = arrs[1:11]
-		}
-		redis.Del("other", "s_"+userid)
-		redis.Put("other", "s_"+userid, strings.Join(arrs, ","), -1)
-		//我的订阅
-		one, _ := mongodb.FindById("user", userid, `{"o_jy":1}`)
-		if one != nil && len(*one) > 0 {
-			o_jy, _ := (*one)["o_jy"].(map[string]interface{})
-			a_key, _ := o_jy["a_key"].([]interface{})
-			for _, v := range a_key {
-				keyMap, _ := v.(map[string]interface{})
-				key, _ := keyMap["key"].([]interface{})
-				keys = append(keys, key)
-			}
-		}
-	} else if words != "" {
-		arrs = strings.Split(words, ",")
-	}
-	s.ServeJson(map[string]interface{}{
-		"msgset":  keys,
-		"history": arrs,
-	})
-	return nil
+    defer util.Catch()
+    userid, _ := s.GetSession("userId").(string)
+    keys := []interface{}{}
+    arrs := []string{}
+    words := s.GetString("words")
+    if userid != "" {
+        arrs = strings.Split(redis.GetStr("other", "s_"+userid), ",")
+        if words != "" {
+            wordsArr := strings.Split(words, ",")
+            for _, word := range wordsArr {
+                for k, v := range arrs {
+                    if v == strings.TrimSpace(word) {
+                        arrs = append(arrs[:k], arrs[k+1:]...)
+                        break
+                    }
+                }
+                arrs = append(arrs, word)
+            }
+        }
+        if len(arrs) > 10 {
+            arrs = arrs[1:11]
+        }
+        redis.Del("other", "s_"+userid)
+        redis.Put("other", "s_"+userid, strings.Join(arrs, ","), -1)
+        //我的订阅
+        one := utils.Compatible.Select(userid, `{"o_jy":1}`)
+        if one != nil && len(*one) > 0 {
+            o_jy, _ := (*one)["o_jy"].(map[string]interface{})
+            a_key, _ := o_jy["a_key"].([]interface{})
+            for _, v := range a_key {
+                keyMap, _ := v.(map[string]interface{})
+                key, _ := keyMap["key"].([]interface{})
+                keys = append(keys, key)
+            }
+        }
+    } else if words != "" {
+        arrs = strings.Split(words, ",")
+    }
+    s.ServeJson(map[string]interface{}{
+        "msgset":  keys,
+        "history": arrs,
+    })
+    return nil
 }

+ 4 - 4
src/jfw/modules/app/src/app/front/shorturl.go

@@ -10,7 +10,7 @@ import (
 	"time"
 
 	"app.yhyue.com/moapp/jybase/encrypt"
-
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
 	//"math/rand"
 	"log"
 
@@ -283,7 +283,7 @@ func CNode(userId string) bool {
 		delete(rM, "createtime")
 		delete(rM, "client")
 	}
-	if userinfo, ok := mongodb.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,"s_myemail":1,"s_company":1,"o_jy":1,"o_vipjy":1}`); userinfo != nil && ok && len(*userinfo) > 0 {
+	if userinfo := utils.Compatible.Select( userId, `{"s_phone":1,"s_m_phone":1,"s_myemail":1,"s_company":1,"o_jy":1,"o_vipjy":1}`); userinfo != nil && ok && len(*userinfo) > 0 {
 		s_phone := util.ObjToString((*userinfo)["s_phone"])
 		phone := util.If(s_phone == "", util.ObjToString((*userinfo)["s_m_phone"]), s_phone)
 		if rM["phone"] == nil || rM["phone"] == "" {
@@ -384,8 +384,8 @@ func getwinnertel(company interface{}) string {
 
 func UserPermission(userId string) (isVip, isOldVip, isEntniche bool, i_member_status int, email string) {
 	var phone string
-	data, ok := mongodb.FindById("user", userId, `{"i_vip_status":1,"i_member_status":1,"s_myemail":1,"s_phone":1,"s_m_phone":1,"l_vip_starttime":1}`)
-	if ok && data != nil && len(*data) > 0 {
+	data :=utils.Compatible.Select( userId, `{"i_vip_status":1,"i_member_status":1,"s_myemail":1,"s_phone":1,"s_m_phone":1,"l_vip_starttime":1}`)
+	if  data != nil && len(*data) > 0 {
 		i_vip_status := util.IntAll((*data)["i_vip_status"])
 		if i_vip_status > 0 {
 			isVip = true

+ 285 - 284
src/jfw/modules/app/src/app/front/structedData.go

@@ -1,332 +1,333 @@
 package front
 
 import (
-	"fmt"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"strings"
-	"time"
+    "fmt"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "strings"
+    "time"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/public"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/public"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type StructedData struct {
-	*xweb.Action
-	index      xweb.Mapper `xweb:"/jyapp/structed/index"`     //数据结构化首页
-	writeInfo  xweb.Mapper `xweb:"/jyapp/structed/writeinfo"` //信息填写
-	saveData   xweb.Mapper `xweb:"/jyapp/structed/savedata"`
-	success    xweb.Mapper `xweb:"/jyapp/structed/success"`    //信息填写成功
-	getPreview xweb.Mapper `xweb:"/jyapp/structed/getpreview"` //数据结构化预览
-	//dev2.10.10
-	freeSamples    xweb.Mapper `xweb:"/jyapp/structed/freeSamples"`    //数据结构化保存免费样例数据
-	verifyCode     xweb.Mapper `xweb:"/jyapp/structed/verifyCode"`     //数据结构化验证邮箱验证码
-	sendMailVerify xweb.Mapper `xweb:"/jyapp/structed/sendMailVerify"` //数据结构化发送邮箱验证码
-	verifyEmail    xweb.Mapper `xweb:"/jyapp/structed/verifyEmail"`    //数据结构化验证邮箱是否验证过
+    *xweb.Action
+    index      xweb.Mapper `xweb:"/jyapp/structed/index"`     //数据结构化首页
+    writeInfo  xweb.Mapper `xweb:"/jyapp/structed/writeinfo"` //信息填写
+    saveData   xweb.Mapper `xweb:"/jyapp/structed/savedata"`
+    success    xweb.Mapper `xweb:"/jyapp/structed/success"`    //信息填写成功
+    getPreview xweb.Mapper `xweb:"/jyapp/structed/getpreview"` //数据结构化预览
+    //dev2.10.10
+    freeSamples    xweb.Mapper `xweb:"/jyapp/structed/freeSamples"`    //数据结构化保存免费样例数据
+    verifyCode     xweb.Mapper `xweb:"/jyapp/structed/verifyCode"`     //数据结构化验证邮箱验证码
+    sendMailVerify xweb.Mapper `xweb:"/jyapp/structed/sendMailVerify"` //数据结构化发送邮箱验证码
+    verifyEmail    xweb.Mapper `xweb:"/jyapp/structed/verifyEmail"`    //数据结构化验证邮箱是否验证过
 
 }
 
 func init() {
-	xweb.AddAction(&StructedData{})
+    xweb.AddAction(&StructedData{})
 }
 
 // VerifyEmail 验证邮箱的正确性
 func (t *StructedData) VerifyEmail() {
-	defer util.Catch()
-	msg := "请求方式有误"
-	status := false
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		email := t.GetString("email")
-		msg = "参数有误"
-		if email != "" {
-			msg = "未登录"
-			if userId != "" {
-				emails := public.Mysql.FindOne("dataexport_order", map[string]interface{}{
-					"user_mail":    email,
-					"user_id":      userId,
-					"product_type": "历史数据",
-				}, "user_mail", "")
-				//是否是绑定邮箱或者是数据导出邮箱  已验证过的邮箱
-				if (emails != nil && util.ObjToString((*emails)["user_mail"]) != "") || (t.GetSession("s_myemail") != nil && email == t.GetSession("s_myemail").(string)) || (t.GetSession("SMVerifySucess") != nil && t.GetSession("SMVerifySucess").(bool) && email == t.GetSession("DataSMVerifyEmail")) {
-					status = true
-					msg = "此邮箱已被验证"
-					t.SetSession("SMVerifySucess", true)
-				} else {
-					msg = "未被验证"
-				}
-			}
-		}
-	}
+    defer util.Catch()
+    msg := "请求方式有误"
+    status := false
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        email := t.GetString("email")
+        msg = "参数有误"
+        if email != "" {
+            msg = "未登录"
+            if userId != "" {
+                emails := public.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                    "user_mail":    email,
+                    "user_id":      userId,
+                    "product_type": "历史数据",
+                }, "user_mail", "")
+                //是否是绑定邮箱或者是数据导出邮箱  已验证过的邮箱
+                if (emails != nil && util.ObjToString((*emails)["user_mail"]) != "") || (t.GetSession("s_myemail") != nil && email == t.GetSession("s_myemail").(string)) || (t.GetSession("SMVerifySucess") != nil && t.GetSession("SMVerifySucess").(bool) && email == t.GetSession("DataSMVerifyEmail")) {
+                    status = true
+                    msg = "此邮箱已被验证"
+                    t.SetSession("SMVerifySucess", true)
+                } else {
+                    msg = "未被验证"
+                }
+            }
+        }
+    }
 
-	t.ServeJson(map[string]interface{}{
-		"msg":    msg,
-		"status": status,
-	})
+    t.ServeJson(map[string]interface{}{
+        "msg":    msg,
+        "status": status,
+    })
 }
 
 // VerifyCode 验证 验证码的正确性
 func (t *StructedData) VerifyCode() {
-	defer util.Catch()
-	msg := "请求方式有误"
-	status := false
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		msg = "未登录"
-		if userId != "" {
-			s_email := t.GetString("s_email")       //邮箱
-			verifyCode := t.GetString("verifyCode") //验证码
-			VerifyEmail := util.ObjToString(t.GetSession("DataSMVerifyEmail"))
-			if verifyCode != "" && s_email != "" && VerifyEmail != "" {
-				if s_email == VerifyEmail {
-					msg = "验证码正确"
-					status = true
-					SMVerifySucess := t.GetSession("SMVerifySucess")
-					//需验证邮箱
-					if SMVerifySucess != nil && !SMVerifySucess.(bool) {
-						//验证码
-						verifyStr := t.GetSession("DataSMVerify")
-						//是否超时
-						lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
-						timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
-						if lastSendDEVerify == 0 || timeSpaceing < 0 {
-							msg = "验证码超时"
-							status = false
-						} else if verifyStr != verifyCode {
-							msg = "验证码有误"
-							status = false
-						} else {
-							t.SetSession("SMVerifySucess", true)
-						}
-					}
-				} else {
-					msg = "邮箱有误"
-					status = false
-				}
-			}
-		}
-	}
-	t.ServeJson(map[string]interface{}{
-		"msg":    msg,
-		"status": status,
-	})
+    defer util.Catch()
+    msg := "请求方式有误"
+    status := false
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        msg = "未登录"
+        if userId != "" {
+            s_email := t.GetString("s_email")       //邮箱
+            verifyCode := t.GetString("verifyCode") //验证码
+            VerifyEmail := util.ObjToString(t.GetSession("DataSMVerifyEmail"))
+            if verifyCode != "" && s_email != "" && VerifyEmail != "" {
+                if s_email == VerifyEmail {
+                    msg = "验证码正确"
+                    status = true
+                    SMVerifySucess := t.GetSession("SMVerifySucess")
+                    //需验证邮箱
+                    if SMVerifySucess != nil && !SMVerifySucess.(bool) {
+                        //验证码
+                        verifyStr := t.GetSession("DataSMVerify")
+                        //是否超时
+                        lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
+                        timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
+                        if lastSendDEVerify == 0 || timeSpaceing < 0 {
+                            msg = "验证码超时"
+                            status = false
+                        } else if verifyStr != verifyCode {
+                            msg = "验证码有误"
+                            status = false
+                        } else {
+                            t.SetSession("SMVerifySucess", true)
+                        }
+                    }
+                } else {
+                    msg = "邮箱有误"
+                    status = false
+                }
+            }
+        }
+    }
+    t.ServeJson(map[string]interface{}{
+        "msg":    msg,
+        "status": status,
+    })
 }
 
 // FreeSamples 保存免费样例数据
 func (t *StructedData) FreeSamples() error {
-	defer util.Catch()
-	msg := "请求方式有误"
-	status := false
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		if userId != "" {
-			name := t.GetString("name")                      //联系人
-			phone_num := t.GetString("phone_num")            //手机号
-			s_email := t.GetString("s_email")                //邮箱
-			SMVerifySucess := t.GetSession("SMVerifySucess") //邮箱是否验证成功
-			if name != "" && phone_num != "" && s_email != "" && SMVerifySucess != nil && SMVerifySucess.(bool) {
-				count := public.Mysql.Count("structed_data", map[string]interface{}{
-					"name":  name,
-					"phone": phone_num,
-					"email": s_email,
-					"type":  1,
-				})
-				if count >= 1 {
-					msg = "用户信息已存在"
-					status = true
-				} else {
-					stu := public.Mysql.Insert("structed_data", map[string]interface{}{
-						"name":        name,
-						"phone":       phone_num,
-						"email":       s_email,
-						"submit_time": time.Now().Unix(),
-						"status":      0,
-						"type":        1, //用户来源,0:联系客服,1:免费样例,2:自选购买
-					})
-					if stu == 0 {
-						msg = "数据库操作异常"
-						status = false
-					} else {
-						//删除验证成功记录 和 发送验证码时间 邮箱
-						t.DelSession("SMVerifySucess")
-						t.DelSession("CreatSMVerifyTime")
-						t.DelSession("DataSMVerifyEmail")
-						msg = "保存成功"
-						status = true
-						go public.SendStructedDataByEmail(s_email, config.GmailAuth, config.Sysconfig, config.Seoconfig)
-					}
-				}
-			} else {
-				msg = "缺少参数"
-				status = false
-			}
-		}
-	}
-	t.ServeJson(map[string]interface{}{
-		"msg":    msg,
-		"status": status,
-	})
-	return nil
+    defer util.Catch()
+    msg := "请求方式有误"
+    status := false
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        if userId != "" {
+            name := t.GetString("name")                      //联系人
+            phone_num := t.GetString("phone_num")            //手机号
+            s_email := t.GetString("s_email")                //邮箱
+            SMVerifySucess := t.GetSession("SMVerifySucess") //邮箱是否验证成功
+            if name != "" && phone_num != "" && s_email != "" && SMVerifySucess != nil && SMVerifySucess.(bool) {
+                count := public.Mysql.Count("structed_data", map[string]interface{}{
+                    "name":  name,
+                    "phone": phone_num,
+                    "email": s_email,
+                    "type":  1,
+                })
+                if count >= 1 {
+                    msg = "用户信息已存在"
+                    status = true
+                } else {
+                    stu := public.Mysql.Insert("structed_data", map[string]interface{}{
+                        "name":        name,
+                        "phone":       phone_num,
+                        "email":       s_email,
+                        "submit_time": time.Now().Unix(),
+                        "status":      0,
+                        "type":        1, //用户来源,0:联系客服,1:免费样例,2:自选购买
+                    })
+                    if stu == 0 {
+                        msg = "数据库操作异常"
+                        status = false
+                    } else {
+                        //删除验证成功记录 和 发送验证码时间 邮箱
+                        t.DelSession("SMVerifySucess")
+                        t.DelSession("CreatSMVerifyTime")
+                        t.DelSession("DataSMVerifyEmail")
+                        msg = "保存成功"
+                        status = true
+                        go public.SendStructedDataByEmail(s_email, config.GmailAuth, config.Sysconfig, config.Seoconfig)
+                    }
+                }
+            } else {
+                msg = "缺少参数"
+                status = false
+            }
+        }
+    }
+    t.ServeJson(map[string]interface{}{
+        "msg":    msg,
+        "status": status,
+    })
+    return nil
 }
 
 // SendMailVerify 发送邮件
 func (t *StructedData) SendMailVerify() {
-	defer util.Catch()
-	if t.Method() == "POST" {
-		userId := util.ObjToString(t.GetSession("userId"))
-		if userId != "" {
-			email := t.GetString("email")
-			if isEmail(email) {
-				lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
-				timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
-				incurKey := fmt.Sprintf("SendSMEmail_%s_%d", t.GetSession("userId"), time.Now().Day())
-				if lastSendDEVerify == 0 || timeSpaceing < 0 {
-					//每日限制10次
-					times := util.IntAll(redis.Get("other", incurKey))
-					if times < 10 {
-						if times == 0 {
-							redis.Put("other", incurKey, 1, 24*60*60)
-						} else {
-							redis.Incr("other", incurKey)
-						}
-						//生成随机数
-						verifyStr := strings.ToUpper(util.GetComplexRandom(6, 3, 3))
-						t.SetSession("SMVerifySucess", false)
-						t.SetSession("DataSMVerify", verifyStr)
-						t.SetSession("CreatSMVerifyTime", time.Now().Unix())
-						t.SetSession("DataSMVerifyEmail", email)
-						log.Println("====================", verifyStr, "====================", t.GetSession("CreatSMVerifyTime"), "====================")
-						//发送邮箱验证码
-						go public.SendMailIdentCode(email, verifyStr, config.GmailAuth)
-						t.T["success"] = true
-						t.T["errCode"] = 5
-						t.T["errMsg"] = "已发送邮箱验证码"
-					} else {
-						t.T["success"] = false
-						t.T["errCode"] = 3
-						t.T["time"] = timeSpaceing
-						t.T["errMsg"] = "验证码发送次数已达到今日上限"
-					}
+    defer util.Catch()
+    if t.Method() == "POST" {
+        userId := util.ObjToString(t.GetSession("userId"))
+        if userId != "" {
+            email := t.GetString("email")
+            if isEmail(email) {
+                lastSendDEVerify := util.Int64All(t.GetSession("CreatSMVerifyTime"))
+                timeSpaceing := lastSendDEVerify - time.Now().Unix() + 60*5
+                incurKey := fmt.Sprintf("SendSMEmail_%s_%d", t.GetSession("userId"), time.Now().Day())
+                if lastSendDEVerify == 0 || timeSpaceing < 0 {
+                    //每日限制10次
+                    times := util.IntAll(redis.Get("other", incurKey))
+                    if times < 10 {
+                        if times == 0 {
+                            redis.Put("other", incurKey, 1, 24*60*60)
+                        } else {
+                            redis.Incr("other", incurKey)
+                        }
+                        //生成随机数
+                        verifyStr := strings.ToUpper(util.GetComplexRandom(6, 3, 3))
+                        t.SetSession("SMVerifySucess", false)
+                        t.SetSession("DataSMVerify", verifyStr)
+                        t.SetSession("CreatSMVerifyTime", time.Now().Unix())
+                        t.SetSession("DataSMVerifyEmail", email)
+                        log.Println("====================", verifyStr, "====================", t.GetSession("CreatSMVerifyTime"), "====================")
+                        //发送邮箱验证码
+                        go public.SendMailIdentCode(email, verifyStr, config.GmailAuth)
+                        t.T["success"] = true
+                        t.T["errCode"] = 5
+                        t.T["errMsg"] = "已发送邮箱验证码"
+                    } else {
+                        t.T["success"] = false
+                        t.T["errCode"] = 3
+                        t.T["time"] = timeSpaceing
+                        t.T["errMsg"] = "验证码发送次数已达到今日上限"
+                    }
 
-				} else {
-					t.T["success"] = false
-					t.T["errCode"] = 2
-					t.T["time"] = timeSpaceing
-					t.T["errMsg"] = "已发送,5分钟后再尝试"
-				}
-			} else {
-				t.T["success"] = false
-				t.T["errCode"] = 1
-				t.T["errMsg"] = "邮箱格式不正确"
-			}
-		} else {
-			t.T["success"] = false
-			t.T["errCode"] = 7
-			t.T["errMsg"] = "未登录"
-		}
-	} else {
-		t.T["success"] = false
-		t.T["errCode"] = 6
-		t.T["errMsg"] = "请求方式有误"
-	}
-	t.ServeJson(&t.T)
+                } else {
+                    t.T["success"] = false
+                    t.T["errCode"] = 2
+                    t.T["time"] = timeSpaceing
+                    t.T["errMsg"] = "已发送,5分钟后再尝试"
+                }
+            } else {
+                t.T["success"] = false
+                t.T["errCode"] = 1
+                t.T["errMsg"] = "邮箱格式不正确"
+            }
+        } else {
+            t.T["success"] = false
+            t.T["errCode"] = 7
+            t.T["errMsg"] = "未登录"
+        }
+    } else {
+        t.T["success"] = false
+        t.T["errCode"] = 6
+        t.T["errMsg"] = "请求方式有误"
+    }
+    t.ServeJson(&t.T)
 }
 
 func (t *StructedData) Index() error {
-	userId := util.ObjToString(t.GetSession("userId"))
-	t.T["source"] = "app_sy_dh_5"
-	t.T["loginFlag"] = false
-	if userId != "" {
-		t.T["loginFlag"] = true
-	}
-	return t.Render("/structeddata/marketing.html", &t.T)
+    userId := util.ObjToString(t.GetSession("userId"))
+    t.T["source"] = "app_sy_dh_5"
+    t.T["loginFlag"] = false
+    if userId != "" {
+        t.T["loginFlag"] = true
+    }
+    return t.Render("/structeddata/marketing.html", &t.T)
 }
 
 // WriteInfo 信息填写
 func (t *StructedData) WriteInfo() error {
-	userId := util.ObjToString(t.GetSession("userId"))
-	if userId != "" {
-		//删除验证成功记录 和 发送验证码时间 邮箱
-		t.DelSession("SMVerifySucess")
-		t.DelSession("CreatSMVerifyTime")
-		t.DelSession("DataSMVerifyEmail")
-		nums, ok := public.MQFW.FindById("user", userId, nil)
-		if !ok {
-			return t.Redirect("/jyapp/free/swordfish/about", 302)
-		}
-		if _, ok := (*nums)["s_phone"]; ok {
-			t.T["phone_num"] = (*nums)["s_phone"].(string)
-		}
-		if _, ok := (*nums)["s_myemail"]; ok {
-			t.T["s_myemail"] = (*nums)["s_myemail"].(string)
-			//验证是否是绑定的邮箱
-			t.SetSession("DataSMVerifyEmail", (*nums)["s_myemail"].(string))
-			t.SetSession("SMVerifySucess", true)
-		}
-		return t.Render("/structeddata/write_infor.html", &t.T)
-	} else {
-		return t.Redirect("/jyapp/free/swordfish/about", 302)
-	}
+    userId := util.ObjToString(t.GetSession("userId"))
+    if userId != "" {
+        //删除验证成功记录 和 发送验证码时间 邮箱
+        t.DelSession("SMVerifySucess")
+        t.DelSession("CreatSMVerifyTime")
+        t.DelSession("DataSMVerifyEmail")
+        nums := utils.Compatible.Select(userId, nil)
+        if nums == nil || len(*nums) <= 0 {
+            return t.Redirect("/jyapp/free/swordfish/about", 302)
+        }
+        if _, ok := (*nums)["s_phone"]; ok {
+            t.T["phone_num"] = (*nums)["s_phone"].(string)
+        }
+        if _, ok := (*nums)["s_myemail"]; ok {
+            t.T["s_myemail"] = (*nums)["s_myemail"].(string)
+            //验证是否是绑定的邮箱
+            t.SetSession("DataSMVerifyEmail", (*nums)["s_myemail"].(string))
+            t.SetSession("SMVerifySucess", true)
+        }
+        return t.Render("/structeddata/write_infor.html", &t.T)
+    } else {
+        return t.Redirect("/jyapp/free/swordfish/about", 302)
+    }
 }
 
 func (t *StructedData) Success() error {
-	//删除验证成功记录 和 发送验证码时间 邮箱
-	t.DelSession("SMVerifySucess")
-	t.DelSession("CreatSMVerifyTime")
-	t.DelSession("DataSMVerifyEmail")
-	return t.Render("/structeddata/write_result.html")
+    //删除验证成功记录 和 发送验证码时间 邮箱
+    t.DelSession("SMVerifySucess")
+    t.DelSession("CreatSMVerifyTime")
+    t.DelSession("DataSMVerifyEmail")
+    return t.Render("/structeddata/write_result.html")
 }
 
 // GetPreview 结构化数据预览
 func (t *StructedData) GetPreview() error {
-	return t.Render("/structeddata/preview.html")
+    return t.Render("/structeddata/preview.html")
 }
 
 func (t *StructedData) SaveData() {
-	name := t.GetString("name")
-	phone_num := t.GetString("phone_num")
-	if name != "" && phone_num != "" {
-		count := public.Mysql.Count("structed_data", map[string]interface{}{
-			"name":  name,
-			"phone": phone_num,
-			"type":  0,
-		})
-		if count >= 1 {
-			t.ServeJson(map[string]interface{}{
-				"error_code": "0",
-				"data": map[string]interface{}{
-					"msg":    "用户信息已存在",
-					"status": true,
-				},
-			})
-		} else {
-			stu := public.Mysql.Insert("structed_data", map[string]interface{}{
-				"name":        name,
-				"phone":       phone_num,
-				"submit_time": time.Now().Unix(),
-				"status":      0,
-				"type":        0, //用户来源,0:联系客服,1:免费样例,2:自选购买
-			})
-			if stu == 0 {
-				t.ServeJson(map[string]interface{}{
-					"error_code": "1",
-					"data": map[string]interface{}{
-						"msg":    "数据库操作异常",
-						"status": false,
-					},
-				})
-			} else {
-				t.ServeJson(map[string]interface{}{
-					"error_code": "0",
-					"data": map[string]interface{}{
-						"msg":    "保存成功",
-						"status": true,
-					},
-				})
-			}
-		}
-	}
+    name := t.GetString("name")
+    phone_num := t.GetString("phone_num")
+    if name != "" && phone_num != "" {
+        count := public.Mysql.Count("structed_data", map[string]interface{}{
+            "name":  name,
+            "phone": phone_num,
+            "type":  0,
+        })
+        if count >= 1 {
+            t.ServeJson(map[string]interface{}{
+                "error_code": "0",
+                "data": map[string]interface{}{
+                    "msg":    "用户信息已存在",
+                    "status": true,
+                },
+            })
+        } else {
+            stu := public.Mysql.Insert("structed_data", map[string]interface{}{
+                "name":        name,
+                "phone":       phone_num,
+                "submit_time": time.Now().Unix(),
+                "status":      0,
+                "type":        0, //用户来源,0:联系客服,1:免费样例,2:自选购买
+            })
+            if stu == 0 {
+                t.ServeJson(map[string]interface{}{
+                    "error_code": "1",
+                    "data": map[string]interface{}{
+                        "msg":    "数据库操作异常",
+                        "status": false,
+                    },
+                })
+            } else {
+                t.ServeJson(map[string]interface{}{
+                    "error_code": "0",
+                    "data": map[string]interface{}{
+                        "msg":    "保存成功",
+                        "status": true,
+                    },
+                })
+            }
+        }
+    }
 }

+ 481 - 508
src/jfw/modules/app/src/app/front/swordfish.go

@@ -1,380 +1,353 @@
 package front
 
 import (
-	"fmt"
-	_ "jy/src/jfw/modules/app/src/app/filter"
-	. "jy/src/jfw/modules/app/src/app/jyutil"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"math/rand"
-	"strings"
-	"time"
+    "fmt"
+    _ "jy/src/jfw/modules/app/src/app/filter"
+    . "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "log"
+    "math/rand"
+    "strings"
+    "time"
 
-	. "app.yhyue.com/moapp/jybase/date"
+    util "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    . "app.yhyue.com/moapp/jybase/mongodb"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "app.yhyue.com/moapp/jypkg/public"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	. "app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jypkg/public"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/bidsearch"
 
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/bidsearch"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"go.mongodb.org/mongo-driver/bson"
-	"go.mongodb.org/mongo-driver/bson/primitive"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "go.mongodb.org/mongo-driver/bson"
+    "go.mongodb.org/mongo-driver/bson/primitive"
 )
 
 const (
-	INDEX             = "bidding"
-	TYPE              = "bidding"
-	FINDF             = `"title"`
-	bidSearch_field_1 = `"_id","title","publishtime","toptype","subtype","type","area","s_subscopeclass","buyerclass","bidamount","budget","spidercode","site"`
-	bidSearch_field   = bidSearch_field_1 + `,"bidopentime","winner","buyer","projectname","projectcode","projectinfo"`
+    INDEX             = "bidding"
+    TYPE              = "bidding"
+    FINDF             = `"title"`
+    bidSearch_field_1 = `"_id","title","publishtime","toptype","subtype","type","area","s_subscopeclass","buyerclass","bidamount","budget","spidercode","site"`
+    bidSearch_field   = bidSearch_field_1 + `,"bidopentime","winner","buyer","projectname","projectcode","projectinfo"`
 )
 
 // 剑鱼标讯推送三级页点赞暂弃 改成剑鱼标讯实验室点赞功能
 func (m *Front) Praise() error {
-	defer util.Catch()
-	var flag = "F"
-	var praiseflag = true
-	thistype := m.GetString("type")
-	uod := m.GetString("uod")
-	util.Try(func() {
-		pdata, _ := mongodb.FindOneByField("praise", `{"s_type":"`+thistype+`"}`, `{"s_no":1}`)
-		if len(*pdata) != 0 {
-			if uod == "U" {
-				praiseflag = mongodb.Update("praise", `{"s_type":"`+thistype+`"}`, `{ "$inc" : { "s_no" : 1 }}`, false, false)
-			} else {
-				praiseflag = mongodb.Update("praise", `{"s_type":"`+thistype+`"}`, `{ "$inc" : { "s_no" : -1 }}`, false, false)
-			}
-			if praiseflag {
-				flag = "T"
-			}
-		}
-	}, func(e interface{}) {
-		log.Println("剑鱼标讯实验室点赞出错", e)
-	})
-	m.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
-	return nil
+    defer util.Catch()
+    var flag = "F"
+    var praiseflag = true
+    thistype := m.GetString("type")
+    uod := m.GetString("uod")
+    util.Try(func() {
+        pdata, _ := mongodb.FindOneByField("praise", `{"s_type":"`+thistype+`"}`, `{"s_no":1}`)
+        if len(*pdata) != 0 {
+            if uod == "U" {
+                praiseflag = mongodb.Update("praise", `{"s_type":"`+thistype+`"}`, `{ "$inc" : { "s_no" : 1 }}`, false, false)
+            } else {
+                praiseflag = mongodb.Update("praise", `{"s_type":"`+thistype+`"}`, `{ "$inc" : { "s_no" : -1 }}`, false, false)
+            }
+            if praiseflag {
+                flag = "T"
+            }
+        }
+    }, func(e interface{}) {
+        log.Println("剑鱼标讯实验室点赞出错", e)
+    })
+    m.ServeJson(map[string]interface{}{
+        "flag": flag,
+    })
+    return nil
 }
 
 // 剑鱼标讯保存
 func (m *Front) AjaxReq() error {
-	defer util.Catch()
-	reqType := m.GetString("reqType")
-	var flag = "n"
-	switch reqType {
-	case "feedback": //意见反馈
-		data := make(map[string]interface{})
-		userId, ok := m.GetSession("userId").(string)
-		if !ok || userId == "" {
-			break
-		}
-		userInfo, ok := mongodb.FindById("user", userId, nil)
-		if !ok {
-			break
-		}
-		data["i_type"] = 8
-		data["s_fromName"] = m.GetString("fromName")
-		value := m.GetString("value")
-		if len([]rune(value)) > 200 {
-			value = util.SubString(value, 0, 200)
-		}
-		data["s_remark"] = value
-		//
-		s_name := ""
-		if (*userInfo)["s_name"] != nil {
-			s_name, _ = (*userInfo)["s_name"].(string)
-		}
-		s_nickname := ""
-		if (*userInfo)["s_nickname"] != nil {
-			s_nickname, _ = (*userInfo)["s_nickname"].(string)
-		}
-		s_phone, _ := (*userInfo)["s_phone"].(string)
-		if s_name != "" {
-			data["s_submitname"] = s_name
-		} else if s_nickname != "" {
-			data["s_submitname"] = s_nickname
-		} else if s_phone != "" {
-			data["s_submitname"] = s_phone
-		} else {
-			data["s_submitname"] = userId
-		}
-		//
-		if s_nickname != "" { //昵称
-			data["s_username"] = s_nickname
-		} else if s_name != "" { //s_name
-			data["s_username"] = s_name
-		} else if s_phone != "" {
-			data["s_username"] = s_phone
-		} else { //userId
-			data["s_username"] = userId
-		}
-		//
-		data["s_submitid"] = userId
-		data["s_title"] = m.GetString("title")
-		data["i_status"] = 0
-		data["l_submitdate"] = time.Now().Unix()
-		data["s_source"] = m.GetString("source")
-		data["s_fkid"] = m.GetString("fkid")
-		data["s_from"] = "app"
-		if len(mongodb.Save("interaction", data)) > 0 {
-			flag = "y"
-		}
-		break
-	case "subscribe": //直接订阅
-		if userid := util.ObjToString(m.GetSession("userId")); userid != "" {
-			//r, _ := mongodb.FindById("user", userid, `{"o_jy":1}`)
-			o_jy := jy.GetSubScribeInfo(m.Session(), mongodb, "f", "10000")
-			//o_jy, _ := (*r)["o_jy"].(map[string]interface{})
-			a_key, _ := (*o_jy)["a_key"].([]interface{})
-			keysArray := processKeyword(m.GetString("keys"))
-			if keysArray == nil {
-				break
-			}
-			var isExists bool
-			for _, v := range a_key {
-				//count := 0
-				//for _, kay := range keysArray {
-				keyMap, _ := v.(map[string]interface{})
-				key, _ := keyMap["key"].([]interface{})
-				kystr := ""
-				for _, ky := range key {
-					kystr = kystr + " " + ky.(string)
-				}
-				if strings.TrimSpace(m.GetString("keys")) == strings.TrimSpace(kystr) {
-					isExists = true
-					flag = "y"
-					break
-				}
-			}
-			positionType := util.Int64All(m.GetSession("positionType"))
-			//如果不存在
-			ok := false
-			if !isExists {
-				if len(a_key) >= 10 {
-					flag = "o"
-				} else {
+    defer util.Catch()
+    reqType := m.GetString("reqType")
+    var flag = "n"
+    switch reqType {
+    case "feedback": //意见反馈
+        data := make(map[string]interface{})
+        userId, ok := m.GetSession("userId").(string)
+        if !ok || userId == "" {
+            break
+        }
+        userInfo := utils.Compatible.Select(userId, nil)
+        if userInfo == nil || len(*userInfo) <= 0 {
+            break
+        }
+        data["i_type"] = 8
+        data["s_fromName"] = m.GetString("fromName")
+        value := m.GetString("value")
+        if len([]rune(value)) > 200 {
+            value = util.SubString(value, 0, 200)
+        }
+        data["s_remark"] = value
+        //
+        s_name := ""
+        if (*userInfo)["s_name"] != nil {
+            s_name, _ = (*userInfo)["s_name"].(string)
+        }
+        s_nickname := ""
+        if (*userInfo)["s_nickname"] != nil {
+            s_nickname, _ = (*userInfo)["s_nickname"].(string)
+        }
+        s_phone, _ := (*userInfo)["s_phone"].(string)
+        if s_name != "" {
+            data["s_submitname"] = s_name
+        } else if s_nickname != "" {
+            data["s_submitname"] = s_nickname
+        } else if s_phone != "" {
+            data["s_submitname"] = s_phone
+        } else {
+            data["s_submitname"] = userId
+        }
+        //
+        if s_nickname != "" { //昵称
+            data["s_username"] = s_nickname
+        } else if s_name != "" { //s_name
+            data["s_username"] = s_name
+        } else if s_phone != "" {
+            data["s_username"] = s_phone
+        } else { //userId
+            data["s_username"] = userId
+        }
+        //
+        data["s_submitid"] = userId
+        data["s_title"] = m.GetString("title")
+        data["i_status"] = 0
+        data["l_submitdate"] = time.Now().Unix()
+        data["s_source"] = m.GetString("source")
+        data["s_fkid"] = m.GetString("fkid")
+        data["s_from"] = "app"
+        if len(mongodb.Save("interaction", data)) > 0 {
+            flag = "y"
+        }
+        break
+    case "subscribe": //直接订阅
+        if userid := util.ObjToString(m.GetSession("userId")); userid != "" {
+            r := utils.Compatible.Select(userid, `{"o_jy":1}`)
+            o_jy, _ := (*r)["o_jy"].(map[string]interface{})
+            a_key, _ := o_jy["a_key"].([]interface{})
+            keysArray := processKeyword(m.GetString("keys"))
+            if keysArray == nil {
+                break
+            }
+            var isExists bool
+            for _, v := range a_key {
+                //count := 0
+                //for _, kay := range keysArray {
+                keyMap, _ := v.(map[string]interface{})
+                key, _ := keyMap["key"].([]interface{})
+                kystr := ""
+                for _, ky := range key {
+                    kystr = kystr + " " + ky.(string)
+                }
+                if strings.TrimSpace(m.GetString("keys")) == strings.TrimSpace(kystr) {
+                    isExists = true
+                    flag = "y"
+                    break
+                }
+            }
+            //如果不存在
+            if !isExists {
+                if len(a_key) >= 10 {
+                    flag = "o"
+                } else {
+                    ok := utils.Compatible.Update(userid,
+                        bson.M{
+                            "$push": bson.M{"o_jy.a_key": bson.M{"key": keysArray, "area": []string{}, "infotype": []string{}, "notkey": []string{}, "from": 1}},
+                            "$set":  bson.M{"i_ts_guide": 1, "o_jy.l_modifydate": time.Now().Unix()},
+                        })
 
-					if positionType == 0 {
-						ok = mongodb.UpdateById("user", userid,
-							bson.M{
-								"$push": bson.M{"o_jy.a_key": bson.M{"key": keysArray, "area": []string{}, "infotype": []string{}, "notkey": []string{}, "from": 1}},
-								"$set":  bson.M{"i_ts_guide": 1, "o_jy.l_modifydate": time.Now().Unix()},
-							})
-					} else {
-						query := map[string]interface{}{
-							"i_userid": util.Int64All(m.GetSession("entUserId")),
-							"i_entid":  util.Int64All(m.GetSession("entId")),
-							"i_type":   2,
-						}
-						if mongodb.Update("entniche_rule", query, bson.M{
-							"$push": bson.M{"o_entniche.a_key": bson.M{"key": keysArray, "area": []string{}, "infotype": []string{}, "notkey": []string{}, "from": 1}},
-							"$set":  bson.M{"i_ts_guide": 1, "o_entniche.l_modifydate": time.Now().Unix()},
-						}, true, false) {
-							ok = true
-						}
-					}
-					if ok {
-						flag = "y"
-					}
-				}
-			} else {
-				/* if mongodb.UpdateById("user", userid,
-				        bson.M{
-				                "$set": bson.M{"i_ts_guide": 1},
-				        }) {
-				        flag = "y"
-				}*/
-				query := map[string]interface{}{
-					"i_userid": util.Int64All(m.GetSession("entUserId")),
-					"i_entid":  util.Int64All(m.GetSession("entId")),
-					"i_type":   2,
-				}
-				if mongodb.Update("entniche_rule", query, bson.M{
-					"$push": bson.M{"o_entniche.a_key": bson.M{"key": keysArray, "area": []string{}, "infotype": []string{}, "notkey": []string{}, "from": 1}},
-					"$set":  bson.M{"i_ts_guide": 1, "o_entniche.l_modifydate": time.Now().Unix()},
-				}, true, false) {
-					flag = "y"
-				}
-			}
-		}
-		break
-	}
-	m.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
-	return nil
+                    if ok {
+                        flag = "y"
+                    }
+                }
+            } else {
+                if utils.Compatible.Update(userid,
+                    bson.M{
+                        "$set": bson.M{"i_ts_guide": 1},
+                    }) {
+                    flag = "y"
+                }
+
+            }
+        }
+        break
+    }
+    m.ServeJson(map[string]interface{}{
+        "flag": flag,
+    })
+    return nil
 }
 
 // 获取我的反馈列表
 func (f *Front) MyFeedbacks() error {
-	userId, _ := f.GetSession("userId").(string)
-	if userId == "" {
-		return f.Redirect("/jyapp/free/mob/err")
-	}
-	list, ok := mongodb.Find("interaction", bson.M{"s_submitid": userId}, `{"l_submitdate":-1}`, `{"s_remark":1,"l_submitdate":1,"s_opinion":1,"i_status":1}`, false, 0, 200)
-	if !ok {
-		return f.Redirect("/jyapp/free/mob/err")
-	}
-	mongodb.Update("jyapp_notice", map[string]interface{}{
-		"s_userid": util.ObjToString(f.GetSession("userId")),
-		"s_type":   "feedback",
-	}, map[string]interface{}{
-		"$set": map[string]interface{}{
-			"i_unread":    0,
-			"l_timestamp": time.Now().Unix(),
-		},
-	}, false, true)
-	if f.Method() == "GET" {
-		f.T["list"] = list
-		f.T["flag"] = true
-		return f.Render("/weixin/feedback.html")
-	}
-	f.ServeJson(map[string]interface{}{
-		"list": list,
-	})
-	return nil
+    userId, _ := f.GetSession("userId").(string)
+    if userId == "" {
+        return f.Redirect("/jyapp/free/mob/err")
+    }
+    list, ok := mongodb.Find("interaction", bson.M{"s_submitid": userId}, `{"l_submitdate":-1}`, `{"s_remark":1,"l_submitdate":1,"s_opinion":1,"i_status":1}`, false, 0, 200)
+    if !ok {
+        return f.Redirect("/jyapp/free/mob/err")
+    }
+    mongodb.Update("jyapp_notice", map[string]interface{}{
+        "s_userid": util.ObjToString(f.GetSession("userId")),
+        "s_type":   "feedback",
+    }, map[string]interface{}{
+        "$set": map[string]interface{}{
+            "i_unread":    0,
+            "l_timestamp": time.Now().Unix(),
+        },
+    }, false, true)
+    if f.Method() == "GET" {
+        f.T["list"] = list
+        f.T["flag"] = true
+        return f.Render("/weixin/feedback.html")
+    }
+    f.ServeJson(map[string]interface{}{
+        "list": list,
+    })
+    return nil
 }
 
 func getRewardText() (string, string) {
-	rewardText, _ := config.Sysconfig["rewardText"].([]interface{})
-	advertText, _ := config.Sysconfig["advertText"].([]interface{})
-	randVal := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(rewardText))
-	if len(advertText) != 0 {
-		advVal := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(advertText))
-		return util.ObjToString(rewardText[randVal]), util.ObjToString(advertText[advVal])
-	} else {
-		return util.ObjToString(rewardText[randVal]), ""
-	}
+    rewardText, _ := config.Sysconfig["rewardText"].([]interface{})
+    advertText, _ := config.Sysconfig["advertText"].([]interface{})
+    randVal := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(rewardText))
+    if len(advertText) != 0 {
+        advVal := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(advertText))
+        return util.ObjToString(rewardText[randVal]), util.ObjToString(advertText[advVal])
+    } else {
+        return util.ObjToString(rewardText[randVal]), ""
+    }
 }
 func (m *Front) About() error {
-	return m.Render("/weixin/about.html")
+    return m.Render("/weixin/about.html")
 }
 func (m *Front) WxsearchlistPaging() {
-	defer util.Catch()
-	var list *[]map[string]interface{}
+    defer util.Catch()
+    var list *[]map[string]interface{}
 
-	pageNum, _ := m.GetInteger("pageNum")
-	searchvalue := strings.TrimSpace(m.GetString("searchvalue"))
-	userid := util.ObjToString(m.GetSession("userId"))
-	if userid != "" {
-		//历史记录
-		history := redis.GetStr("other", "s_"+userid)
-		arrs := bidsearch.AddHistory(history, searchvalue)
-		redis.Del("other", "s_"+userid)
-		redis.Put("other", "s_"+userid, strings.Join(arrs, ","), -1)
-		m.T["history"] = arrs
-	}
+    pageNum, _ := m.GetInteger("pageNum")
+    searchvalue := strings.TrimSpace(m.GetString("searchvalue"))
+    userid := util.ObjToString(m.GetSession("userId"))
+    if userid != "" {
+        //历史记录
+        history := redis.GetStr("other", "s_"+userid)
+        arrs := bidsearch.AddHistory(history, searchvalue)
+        redis.Del("other", "s_"+userid)
+        redis.Put("other", "s_"+userid, strings.Join(arrs, ","), -1)
+        m.T["history"] = arrs
+    }
 
-	isLimit := 1
-	var (
-		b_word, a_word string
-		secondKWS      = ""
-		secondFlag     = ""
-		queryItems     []string
-		isPayedUser    bool
-		hasNextPage    bool
-		secondList     []map[string]interface{}
-		fileExists     = ""
-		city           = ""
-	)
+    isLimit := 1
+    var (
+        b_word, a_word string
+        secondKWS      = ""
+        secondFlag     = ""
+        queryItems     []string
+        isPayedUser    bool
+        hasNextPage    bool
+        secondList     []map[string]interface{}
+        fileExists     = ""
+        city           = ""
+    )
 
-	if searchvalue != "" {
-		selectType := m.GetString("selectType")
-		subtype := m.GetString("subtype")
-		scope := m.GetString("scope")
-		publishtime := m.GetString("publishtime")
-		industry := strings.TrimSpace(m.GetString("industry"))
-		minprice := m.GetString("minprice")
-		maxprice := m.GetString("maxprice")
-		winner := "" //仅大会员用户可以查询中标企业
-		//高级筛选 仅vip用户可查询
-		var hasBuyerTel, hasWinnerTel string = "", "" //是否有采购单位电话、是否有中标单位电话 y:有 n:没有
-		buyerclass := ""                              //采购单位类别
-		var notkey string = ""                        //排除词
-		fileExists = m.GetString("fileExists")        //是否有附件--所有用户都可用此功能 0:全部;1:有附件;-1:无附件
+    if searchvalue != "" {
+        selectType := m.GetString("selectType")
+        subtype := m.GetString("subtype")
+        scope := m.GetString("scope")
+        publishtime := m.GetString("publishtime")
+        industry := strings.TrimSpace(m.GetString("industry"))
+        minprice := m.GetString("minprice")
+        maxprice := m.GetString("maxprice")
+        winner := "" //仅大会员用户可以查询中标企业
+        //高级筛选 仅vip用户可查询
+        var hasBuyerTel, hasWinnerTel string = "", "" //是否有采购单位电话、是否有中标单位电话 y:有 n:没有
+        buyerclass := ""                              //采购单位类别
+        var notkey string = ""                        //排除词
+        fileExists = m.GetString("fileExists")        //是否有附件--所有用户都可用此功能 0:全部;1:有附件;-1:无附件
 
-		isPayedUser, publishtime, queryItems, pageNum, _ = bidsearch.PublicSearch(userid, selectType, publishtime, util.Int64All(config.Sysconfig["bidSearchOldUserLimit"]), pageNum, 50,  m.Session(),  *config.Middleground)
-		if isPayedUser {
-			buyerclass = m.GetString("buyerclass")
-			hasBuyerTel, hasWinnerTel = m.GetString("buyertel"), m.GetString("winnertel")
-			notkey = m.GetString("notkey")
-			city = m.GetString("city")
-		}
-		//校验是否有大会员中标企业查询权限
-		bigBaseMsg := jy.GetBigVipUserBaseMsg( m.Session(),  *config.Middleground)
-		if bigBaseMsg.CheckBigVipBackPower("search") {
-			winner = m.GetString("winner")
-		}
-		//全文检索限制
-		searchLimit := public.IsSearchLimit(queryItems)
-		if searchLimit {
-			//limitFlag = public.Lst.Flag
-			isLimit = public.Lst.IsLimited(m.Request, m.ResponseWriter, m.Session(), isPayedUser)
-			if isLimit == 1 { //没有被限制
-				defer public.Lst.Limit()
-			}
-		}
-		//第一页数据展示多字段(table表格需要)
-		filed := bidSearch_field_1
-		if pageNum == 1 {
-			filed = bidSearch_field
-		}
-		if isLimit == 1 {
-			secondKWS, b_word, a_word, _, secondFlag, _, _, list = bidsearch.SearchData("app", m.Request, pageNum, util.ObjToString(m.GetSession("userId")), secondKWS, searchvalue, scope, city, publishtime, subtype, industry, minprice, maxprice, winner, buyerclass, hasBuyerTel, hasWinnerTel, fileExists, pageNum, true, queryItems, filed, notkey, isPayedUser, false, "", bidsearch.SearchPageSize_APP, config.Sysconfig)
-		}
-	}
+        isPayedUser, publishtime, queryItems, pageNum, _ = bidsearch.PublicSearch(userid, selectType, publishtime, util.Int64All(config.Sysconfig["bidSearchOldUserLimit"]), pageNum, 50, m.Session(), *config.Middleground)
+        if isPayedUser {
+            buyerclass = m.GetString("buyerclass")
+            hasBuyerTel, hasWinnerTel = m.GetString("buyertel"), m.GetString("winnertel")
+            notkey = m.GetString("notkey")
+            city = m.GetString("city")
+        }
+        //校验是否有大会员中标企业查询权限
+        bigBaseMsg := jy.GetBigVipUserBaseMsg(m.Session(), *config.Middleground)
+        if bigBaseMsg.CheckBigVipBackPower("search") {
+            winner = m.GetString("winner")
+        }
+        //全文检索限制
+        searchLimit := public.IsSearchLimit(queryItems)
+        if searchLimit {
+            //limitFlag = public.Lst.Flag
+            isLimit = public.Lst.IsLimited(m.Request, m.ResponseWriter, m.Session(), isPayedUser)
+            if isLimit == 1 { //没有被限制
+                defer public.Lst.Limit()
+            }
+        }
+        //第一页数据展示多字段(table表格需要)
+        filed := bidSearch_field_1
+        if pageNum == 1 {
+            filed = bidSearch_field
+        }
+        if isLimit == 1 {
+            secondKWS, b_word, a_word, _, secondFlag, _, _, list = bidsearch.SearchData("app", m.Request, pageNum, util.ObjToString(m.GetSession("userId")), secondKWS, searchvalue, scope, city, publishtime, subtype, industry, minprice, maxprice, winner, buyerclass, hasBuyerTel, hasWinnerTel, fileExists, pageNum, true, queryItems, filed, notkey, isPayedUser, false, "", bidsearch.SearchPageSize_APP, config.Sysconfig)
+        }
+    }
 
-	secondList, _, hasNextPage = bidsearch.LisetData(3, pageNum, list, secondFlag, config.Seoconfig, isPayedUser, 50, userid)
-	m.ServeJson(map[string]interface{}{
-		"limitFlag":     false,
-		"status":        isLimit,
-		"list":          list,
-		"hasNextPage":   hasNextPage,
-		"history":       m.T["history"],
-		"msgset":        m.T["msgset"],
-		"interceptWord": a_word,
-		"keyWord":       b_word,
-		"isLogin":       m.GetSession("userId") != nil,
-		"secondFlag":    secondFlag,
-		"secondList":    secondList,
-		"secondKWS":     secondKWS,
-	})
+    secondList, _, hasNextPage = bidsearch.LisetData(3, pageNum, list, secondFlag, config.Seoconfig, isPayedUser, 50, userid)
+    m.ServeJson(map[string]interface{}{
+        "limitFlag":     false,
+        "status":        isLimit,
+        "list":          list,
+        "hasNextPage":   hasNextPage,
+        "history":       m.T["history"],
+        "msgset":        m.T["msgset"],
+        "interceptWord": a_word,
+        "keyWord":       b_word,
+        "isLogin":       m.GetSession("userId") != nil,
+        "secondFlag":    secondFlag,
+        "secondList":    secondList,
+        "secondKWS":     secondKWS,
+    })
 
 }
 
 // 预览结果
 func (m *Front) WxpushView() error {
-	defer util.Catch()
-	userid := util.ObjToString(m.GetSession("userId"))
-	if userid == "" {
-		return m.Redirect("/jyapp/login")
-	}
-	a_key, list := public.PushViewDatas(userid, "", bidSearch_field_1, 1, bidsearch.SearchPageSize_APP)
-	public.BidListConvert("", list)
-	m.T["firstPage"] = list
-	m.T["hasNextPage"] = list != nil && len(*list) == bidsearch.SearchPageSize_APP
-	m.T["pageSize"] = bidsearch.SearchPageSize_APP
-	m.T["a_key"] = a_key
-	return m.Render("/weixin/resultpreview.html", &m.T)
+    defer util.Catch()
+    userid := util.ObjToString(m.GetSession("userId"))
+    if userid == "" {
+        return m.Redirect("/jyapp/login")
+    }
+    a_key, list := public.PushViewDatas(userid, "", bidSearch_field_1, 1, bidsearch.SearchPageSize_APP)
+    public.BidListConvert("", list)
+    m.T["firstPage"] = list
+    m.T["hasNextPage"] = list != nil && len(*list) == bidsearch.SearchPageSize_APP
+    m.T["pageSize"] = bidsearch.SearchPageSize_APP
+    m.T["a_key"] = a_key
+    return m.Render("/weixin/resultpreview.html", &m.T)
 }
 func (m *Front) WxpushViewPaging() {
-	defer util.Catch()
-	var list *[]map[string]interface{}
-	pageNum, _ := m.GetInteger("pageNum")
-	if userid := util.ObjToString(m.GetSession("userId")); userid != "" && pageNum <= bidsearch.SearchMaxPageNum_APP {
-		_, list = public.PushViewDatas(userid, "", bidSearch_field_1, pageNum, bidsearch.SearchPageSize_APP)
-	}
-	public.BidListConvert("", list)
-	m.ServeJson(map[string]interface{}{
-		"list":        list,
-		"hasNextPage": list != nil && len(*list) == bidsearch.SearchPageSize_APP && pageNum < bidsearch.SearchMaxPageNum_APP,
-	})
+    defer util.Catch()
+    var list *[]map[string]interface{}
+    pageNum, _ := m.GetInteger("pageNum")
+    if userid := util.ObjToString(m.GetSession("userId")); userid != "" && pageNum <= bidsearch.SearchMaxPageNum_APP {
+        _, list = public.PushViewDatas(userid, "", bidSearch_field_1, pageNum, bidsearch.SearchPageSize_APP)
+    }
+    public.BidListConvert("", list)
+    m.ServeJson(map[string]interface{}{
+        "list":        list,
+        "hasNextPage": list != nil && len(*list) == bidsearch.SearchPageSize_APP && pageNum < bidsearch.SearchMaxPageNum_APP,
+    })
 }
 
 /*func (f *Front) HasPushHistory() {
@@ -468,126 +441,126 @@ func (m *Front) WxpushViewPaging() {
 
 // 历史推送
 func (f *Front) Historypush() error {
-	if f.GetString("f") == "push" {
-		if f.GetString("t") == "member" {
-			f.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Member)
-		} else if f.GetString("t") == "entniche" {
-			f.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Entniche)
-		} else {
-			f.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Vip)
-		}
-	}
-	userId, _ := f.GetSession("userId").(string)
-	if userId != "" {
-		vipSubtips := 1
-		// 打开推送
-		data, ok := mongodb.FindById("user", userId, `{"i_vip_subtips":1,"isread":1}`)
-		if ok && data != nil && len(*data) > 0 {
-			//VIP服务到期
-			i_vip_subtips := (*data)["i_vip_subtips"]
-			if i_vip_subtips == 0 {
-				if mongodb.UpdateById("user", userId, bson.M{"$set": bson.M{"i_vip_subtips": 1}}) {
-					vipSubtips = 0
-				}
-			}
-		}
-		f.T["isread"] = (*data)["isread"]
-		f.T["vipSubtips"] = vipSubtips
-		f.T["userId"] = userId
-		f.T["isIosExam"], f.T["isIosExamPhone"], f.T["isVip"], _ = IosExamInfo(f.Action, true, false)
-	}
-	return f.Render("/weixin/historypush.html", &f.T)
+    if f.GetString("f") == "push" {
+        if f.GetString("t") == "member" {
+            f.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Member)
+        } else if f.GetString("t") == "entniche" {
+            f.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Entniche)
+        } else {
+            f.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Vip)
+        }
+    }
+    userId, _ := f.GetSession("userId").(string)
+    if userId != "" {
+        vipSubtips := 1
+        // 打开推送
+        data := utils.Compatible.Select(userId, `{"i_vip_subtips":1,"isread":1}`)
+        if data != nil && len(*data) > 0 {
+            //VIP服务到期
+            i_vip_subtips := (*data)["i_vip_subtips"]
+            if i_vip_subtips == 0 {
+                if utils.Compatible.Update(userId, bson.M{"$set": bson.M{"i_vip_subtips": 1}}) {
+                    vipSubtips = 0
+                }
+            }
+        }
+        f.T["isread"] = (*data)["isread"]
+        f.T["vipSubtips"] = vipSubtips
+        f.T["userId"] = userId
+        f.T["isIosExam"], f.T["isIosExamPhone"], f.T["isVip"], _ = IosExamInfo(f.Action, true, false)
+    }
+    return f.Render("/weixin/historypush.html", &f.T)
 }
 
 func MFollow(userId, sid string) (bool, string) {
-	defer util.Catch()
-	var followId string
-	followFlag := false
-	follows := public.BaseMysql.FindOne("follow_project_monitor", map[string]interface{}{"s_userid": userId, "s_id": sid}, "id", "")
-	if follows != nil && len(*follows) > 0 {
-		followId = encrypt.EncodeArticleId2ByCheck(util.InterfaceToStr((*follows)["id"]))
-		followFlag = true
-	}
-	return followFlag, followId
+    defer util.Catch()
+    var followId string
+    followFlag := false
+    follows := public.BaseMysql.FindOne("follow_project_monitor", map[string]interface{}{"s_userid": userId, "s_id": sid}, "id", "")
+    if follows != nil && len(*follows) > 0 {
+        followId = encrypt.EncodeArticleId2ByCheck(util.InterfaceToStr((*follows)["id"]))
+        followFlag = true
+    }
+    return followFlag, followId
 }
 func wxvisitD(sid, userId string, isPayUser bool) (objdata map[string]interface{}) {
-	defer util.Catch()
-	var obj map[string]interface{}
-	if len(sid) > 5 {
-		aobj, ok := public.Mgo_Bidding.FindById(public.DbConf.Mongodb.Bidding.Collection, sid, public.MgoBiddingFields)
-		if ok && (aobj == nil || *aobj == nil || len(*aobj) == 0) {
-			aobj, ok = public.Mgo_Bidding.FindById(public.DbConf.Mongodb.Bidding.Collection_back, sid, public.MgoBiddingFields)
-		}
-		//aobj, ok := elastic.GetByIdField("bidding", "bidding", sid, ""), true
-		obj = *aobj
-		if ok && obj != nil && len(obj) >= 3 {
-			if !isPayUser && (util.ObjToString(obj["subtype"]) == "拟建" || util.ObjToString(obj["subtype"]) == "采购意向") {
-				for k, _ := range obj {
-					if k != "title" && k != "area" && k != "subtype" && k != "toptype" && k != "publishtime" && k != "budget" && k != "bidamount" && k != "site" && k != "spidercode" && k != "recommended_service" &&
-						k != "owner" && k != "total_investment" && k != "projectaddr" && k != "projectperiod" && k != "approvedept" && k != "approvecontent" && k != "approvecode" && k != "approvenumber" && k != "approvetime" && k != "approvestatus" && k != "project_scale" && k != "projectname" {
-						delete(obj, k)
-					}
-				}
-			}
-			obj["_id"] = encrypt.EncodeArticleId2ByCheck(sid)
-			// obj["url"] = obj["href"]
-			pt := obj["publishtime"]
-			obj["l_publishtime"] = pt
-			obj["publishtime"] = FormatDateWithObj(&pt, Date_Full_Layout)
-			//查询是否关注
-			obj["followFlag"] = false
-			obj["hasSession"] = false
-			var infoformat = util.IntAllDef(obj["infoformat"], 1)
-			obj["infoformat"] = infoformat
-			//精准字段(竞争对手的地址) 或  拟建项目
-			if obj["competehref"] != nil || infoformat == 2 {
-				delete(obj, "href")
-			}
-			if userId != "" {
-				//pcode, _ := obj["projectcode"].(string)
-				//pname, _ := obj["projectname"].(string)
-				titleTmp := util.ObjToString(obj["title"])
-				obj["followFlag"], obj["followId"] = MFollow(userId, sid)
-				if len([]rune(titleTmp)) > 100 {
-					titleTmp = string([]rune(titleTmp)[:100]) + "..."
-				}
-				titleTmp = public.ClearHtml.ReplaceAllString(titleTmp, "")
-				obj["title"] = titleTmp
-				obj["hasSession"] = true
+    defer util.Catch()
+    var obj map[string]interface{}
+    if len(sid) > 5 {
+        aobj, ok := public.Mgo_Bidding.FindById(public.DbConf.Mongodb.Bidding.Collection, sid, public.MgoBiddingFields)
+        if ok && (aobj == nil || *aobj == nil || len(*aobj) == 0) {
+            aobj, ok = public.Mgo_Bidding.FindById(public.DbConf.Mongodb.Bidding.Collection_back, sid, public.MgoBiddingFields)
+        }
+        //aobj, ok := elastic.GetByIdField("bidding", "bidding", sid, ""), true
+        obj = *aobj
+        if ok && obj != nil && len(obj) >= 3 {
+            if !isPayUser && (util.ObjToString(obj["subtype"]) == "拟建" || util.ObjToString(obj["subtype"]) == "采购意向") {
+                for k, _ := range obj {
+                    if k != "title" && k != "area" && k != "subtype" && k != "toptype" && k != "publishtime" && k != "budget" && k != "bidamount" && k != "site" && k != "spidercode" && k != "recommended_service" &&
+                        k != "owner" && k != "total_investment" && k != "projectaddr" && k != "projectperiod" && k != "approvedept" && k != "approvecontent" && k != "approvecode" && k != "approvenumber" && k != "approvetime" && k != "approvestatus" && k != "project_scale" && k != "projectname" {
+                        delete(obj, k)
+                    }
+                }
+            }
+            obj["_id"] = encrypt.EncodeArticleId2ByCheck(sid)
+            // obj["url"] = obj["href"]
+            pt := obj["publishtime"]
+            obj["l_publishtime"] = pt
+            obj["publishtime"] = FormatDateWithObj(&pt, Date_Full_Layout)
+            //查询是否关注
+            obj["followFlag"] = false
+            obj["hasSession"] = false
+            var infoformat = util.IntAllDef(obj["infoformat"], 1)
+            obj["infoformat"] = infoformat
+            //精准字段(竞争对手的地址) 或  拟建项目
+            if obj["competehref"] != nil || infoformat == 2 {
+                delete(obj, "href")
+            }
+            if userId != "" {
+                //pcode, _ := obj["projectcode"].(string)
+                //pname, _ := obj["projectname"].(string)
+                titleTmp := util.ObjToString(obj["title"])
+                obj["followFlag"], obj["followId"] = MFollow(userId, sid)
+                if len([]rune(titleTmp)) > 100 {
+                    titleTmp = string([]rune(titleTmp)[:100]) + "..."
+                }
+                titleTmp = public.ClearHtml.ReplaceAllString(titleTmp, "")
+                obj["title"] = titleTmp
+                obj["hasSession"] = true
 
-				//obj["title"] = util.If(len([]rune(titleTmp)) > 100, string([]rune(titleTmp)[:100])+"...", string(titleTmp)).(string)
-			}
-			if strings.Trim(util.ObjToString(obj["detail"]), " ") == "" {
-				obj["detail"] = ""
-			}
-		}
-	}
-	return obj
+                //obj["title"] = util.If(len([]rune(titleTmp)) > 100, string([]rune(titleTmp)[:100])+"...", string(titleTmp)).(string)
+            }
+            if strings.Trim(util.ObjToString(obj["detail"]), " ") == "" {
+                obj["detail"] = ""
+            }
+        }
+    }
+    return obj
 }
 func (f *Front) GetRecomKWs() {
-	count, _ := f.GetInteger("count")
-	f.ServeJson(public.RecomKws.GetRecomKws(f.GetString("value"), count, float32(config.Sysconfig["recommendThreshold"].(float64))))
+    count, _ := f.GetInteger("count")
+    f.ServeJson(public.RecomKws.GetRecomKws(f.GetString("value"), count, float32(config.Sysconfig["recommendThreshold"].(float64))))
 }
 
 // 记录用户行为--推荐关键词
 func (f *Front) BehaviorRecord() {
-	flag := saveBehaviorRecord(f.Session(),
-		bson.M{
-			"s_word":   f.GetString("value"),
-			"s_type":   f.GetString("type"),
-			"s_source": f.GetString("source"),
-		})
-	f.ServeJson(bson.M{"flag": flag})
+    flag := saveBehaviorRecord(f.Session(),
+        bson.M{
+            "s_word":   f.GetString("value"),
+            "s_type":   f.GetString("type"),
+            "s_source": f.GetString("source"),
+        })
+    f.ServeJson(bson.M{"flag": flag})
 }
 
 // 记录用户行为
 func saveBehaviorRecord(sess *httpsession.Session, data bson.M) bool {
-	userId, _ := sess.Get("userId").(string)
-	nickName, _ := sess.Get("s_nickname").(string)
-	data["s_userid"] = userId
-	data["s_nickname"] = nickName
-	data["l_createtime"] = time.Now().Unix()
-	return len(mongodb.Save("behavior", data)) > 0
+    userId, _ := sess.Get("userId").(string)
+    nickName, _ := sess.Get("s_nickname").(string)
+    data["s_userid"] = userId
+    data["s_nickname"] = nickName
+    data["l_createtime"] = time.Now().Unix()
+    return len(mongodb.Save("behavior", data)) > 0
 }
 
 /*
@@ -605,80 +578,80 @@ func saveBehaviorRecord(sess *httpsession.Session, data bson.M) bool {
 	}
 */
 func (m *Front) DelWxHistorySearch() {
-	defer util.Catch()
-	//定义一个无用参数作为返回值
-	var rt string = "rt"
-	userId := m.GetSession("userId")
-	history := redis.GetStr("other", "s_"+userId.(string))
-	if len(history) > 0 || history != "" {
-		redis.Del("other", "s_"+userId.(string))
-	}
-	m.ServeJson(map[string]interface{}{
-		"rt": rt,
-	})
+    defer util.Catch()
+    //定义一个无用参数作为返回值
+    var rt string = "rt"
+    userId := m.GetSession("userId")
+    history := redis.GetStr("other", "s_"+userId.(string))
+    if len(history) > 0 || history != "" {
+        redis.Del("other", "s_"+userId.(string))
+    }
+    m.ServeJson(map[string]interface{}{
+        "rt": rt,
+    })
 }
 func (m *Front) GetIndexData() {
-	defer util.Catch()
-	redis_obj := redis.Get("other", "sw_index")
-	var one map[string]interface{}
-	if redis_obj != nil {
-		one = redis_obj.(map[string]interface{})
-		log.Println("newpage from the cache...")
-	} else {
-		rs, err := mongodb.Find("swordfish_index", nil, `{"_id":-1}`, nil, false, 0, 1)
-		if err {
-			one = (*rs)[0]
-			one["i_site"] = util.IntAll(one["i_entsite"]) + util.IntAll(one["i_govsite"])
-			avg := util.IntAll(one["i_bidmonth"])/21 + util.IntAll(one["i_bidmonth"])%21
-			one["i_avg"] = avg
-			one["i_my"] = util.IntAll(one["i_entsite"]) * 35 / 100
-			one["i_hy"] = util.IntAll(one["i_entsite"]) * 15 / 100
-			one["i_zb"] = util.IntAll(one["i_entsite"]) - util.IntAll(one["i_my"]) - util.IntAll(one["i_hy"])
-			redis.Put("other", "sw_index", one, 60*60*2)
-		} else {
-			m.ServeJson("n")
-		}
-	}
-	m.ServeJson(one)
+    defer util.Catch()
+    redis_obj := redis.Get("other", "sw_index")
+    var one map[string]interface{}
+    if redis_obj != nil {
+        one = redis_obj.(map[string]interface{})
+        log.Println("newpage from the cache...")
+    } else {
+        rs, err := mongodb.Find("swordfish_index", nil, `{"_id":-1}`, nil, false, 0, 1)
+        if err {
+            one = (*rs)[0]
+            one["i_site"] = util.IntAll(one["i_entsite"]) + util.IntAll(one["i_govsite"])
+            avg := util.IntAll(one["i_bidmonth"])/21 + util.IntAll(one["i_bidmonth"])%21
+            one["i_avg"] = avg
+            one["i_my"] = util.IntAll(one["i_entsite"]) * 35 / 100
+            one["i_hy"] = util.IntAll(one["i_entsite"]) * 15 / 100
+            one["i_zb"] = util.IntAll(one["i_entsite"]) - util.IntAll(one["i_my"]) - util.IntAll(one["i_hy"])
+            redis.Put("other", "sw_index", one, 60*60*2)
+        } else {
+            m.ServeJson("n")
+        }
+    }
+    m.ServeJson(one)
 }
 
 // 手动删除30天无更新数据
 func (m *Front) DelOL() error {
-	defer util.Catch()
-	var ids []primitive.ObjectID
-	var flag = "F"
-	var arrid = strings.Split(m.GetString("arrid"), ",")
-	log.Println("---->", arrid)
+    defer util.Catch()
+    var ids []primitive.ObjectID
+    var flag = "F"
+    var arrid = strings.Split(m.GetString("arrid"), ",")
+    log.Println("---->", arrid)
 
-	userId, ok := m.GetSession("userId").(string)
-	log.Println("sss", ids)
-	if !ok || userId == "" || len(ids) < 1 {
-		m.ServeJson(map[string]interface{}{
-			"flag": flag,
-		})
-		return nil
-	}
-	arrStr := []string{}
-	for _, v := range arrid {
-		arrStr = append(arrStr, fmt.Sprintf(`"%s"`, v))
-	}
-	idStr := fmt.Sprintf(`SELECT * FROM follow_project_monitor WHERE s_userid ="%s" and id in (%s)`, userId, strings.Join(arrStr, ","))
+    userId, ok := m.GetSession("userId").(string)
+    log.Println("sss", ids)
+    if !ok || userId == "" || len(ids) < 1 {
+        m.ServeJson(map[string]interface{}{
+            "flag": flag,
+        })
+        return nil
+    }
+    arrStr := []string{}
+    for _, v := range arrid {
+        arrStr = append(arrStr, fmt.Sprintf(`"%s"`, v))
+    }
+    idStr := fmt.Sprintf(`SELECT * FROM follow_project_monitor WHERE s_userid ="%s" and id in (%s)`, userId, strings.Join(arrStr, ","))
 
-	if datas := public.BaseMysql.SelectBySql(idStr); datas != nil {
-		for _, v := range *datas {
-			relation := []interface{}{v["s_id"]}
-			go delRelRedis(v["s_userid"], relation)
-			v["s_followid"] = BsonIdToSId(v["id"])
-			delete(v, "id")
-			v["i_status"] = 2
-			mongodb.Save("follow_project_monitor_back", v)
-		}
-	}
-	delIdStr := fmt.Sprintf(`delete FROM follow_project_monitor WHERE s_userid ="%s" and id in (%s)`, userId, strings.Join(arrStr, ","))
-	public.BaseMysql.SelectBySql(delIdStr)
-	flag = "T"
-	m.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
-	return nil
+    if datas := public.BaseMysql.SelectBySql(idStr); datas != nil {
+        for _, v := range *datas {
+            relation := []interface{}{v["s_id"]}
+            go delRelRedis(v["s_userid"], relation)
+            v["s_followid"] = BsonIdToSId(v["id"])
+            delete(v, "id")
+            v["i_status"] = 2
+            mongodb.Save("follow_project_monitor_back", v)
+        }
+    }
+    delIdStr := fmt.Sprintf(`delete FROM follow_project_monitor WHERE s_userid ="%s" and id in (%s)`, userId, strings.Join(arrStr, ","))
+    public.BaseMysql.SelectBySql(delIdStr)
+    flag = "T"
+    m.ServeJson(map[string]interface{}{
+        "flag": flag,
+    })
+    return nil
 }

+ 19 - 19
src/jfw/modules/app/src/app/front/vipsubscribe.go

@@ -1,18 +1,18 @@
 package front
 
 import (
-	"encoding/hex"
-	"jy/src/jfw/modules/app/src/app/jyutil"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"net/url"
-	"strings"
-	"time"
-
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jypkg/public"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "app.yhyue.com/moapp/jypkg/public"
+    "encoding/hex"
+    "jy/src/jfw/modules/app/src/app/jyutil"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "net/url"
+    "strings"
+    "time"
+
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Subscribepay struct {
@@ -152,7 +152,7 @@ func (s *Subscribepay) Introduce() error {
 	if userId == "" {
 		return s.Render("/vipsubscribe/vip_introduce.html")
 	}
-	m, _ := public.MQFW.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1}`)
+	m := utils.Compatible.Select( userId, `{"o_vipjy":1,"i_vip_status":1}`)
 	if len(*m) == 0 {
 		return s.Redirect("/jyapp/login")
 	}
@@ -180,8 +180,8 @@ func (s *Subscribepay) TrialInfo() error {
 	if userId == "" {
 		return s.Redirect("/jyapp/login")
 	}
-	m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1}`)
-	if !ok || len(*m) == 0 {
+	m := utils.Compatible.Select( userId, `{"o_vipjy":1}`)
+	if  len(*m) == 0 {
 		return s.Redirect("/jyapp/login")
 	}
 	obj := util.ObjToMap((*m)["o_vipjy"])
@@ -201,8 +201,8 @@ func (s *Subscribepay) ToPurchasePage(flag string) {
 			s.Redirect("/jyapp/login")
 			return
 		}
-		m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1}`)
-		if !ok {
+		m := utils.Compatible.Select(  userId, `{"o_vipjy":1,"i_vip_status":1}`)
+		if m==nil||len(*m)<=0 {
 			s.Redirect("/jyapp/login")
 			return
 		}
@@ -299,8 +299,8 @@ func (f *Subscribepay) Msgremind() error {
 	if userId == "" {
 		return f.Render("_error.html")
 	}
-	user, ok := public.MQFW.FindById("user", userId, `{"i_vip_status":1,"l_vip_endtime":1,"i_member_status":1,"i_member_endtime":1}`)
-	if !ok || user == nil || len(*user) == 0 {
+	user := utils.Compatible.Select( userId, `{"i_vip_status":1,"l_vip_endtime":1,"i_member_status":1,"i_member_endtime":1}`)
+	if  user == nil || len(*user) == 0 {
 		return f.Render("_error.html")
 	}
 	myLastOrderCode := func(user_id string) string {

+ 2 - 1
src/jfw/modules/app/src/app/front/ws_dataExport.go

@@ -4,6 +4,7 @@ import (
     "encoding/json"
     "errors"
     "fmt"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
     "jy/src/jfw/modules/app/src/jfw/config"
     "log"
     "regexp"
@@ -280,7 +281,7 @@ func (w *WsDataExport) ToCreateOrderPage() error {
     if resEmail == "" || resPhone == "" {
         lastEmail, lastPhone := "", ""
         if lastPhone, lastEmail = dataexport.GetLastExportPhoneAndMail(public.Mysql, userId, util.ObjToString(w.GetSession("entUserId"))); lastPhone == "" || lastEmail == "" {
-            userData, _ := mongodb.FindById("user", userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
+            userData:= utils.Compatible.Select( userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
             if userData != nil && len(*userData) > 0 {
                 if lastEmail == "" {
                     lastEmail, _ = (*userData)["s_myemail"].(string)

+ 299 - 293
src/jfw/modules/app/src/app/front/wxkeyset.go

@@ -2,327 +2,333 @@
 package front
 
 import (
-	"fmt"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"net/url"
-	"regexp"
-	"strconv"
-	"strings"
+    "fmt"
+    . "jy/src/jfw/modules/app/src/app/jyutil"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
+    "jy/src/jfw/modules/app/src/jfw/config"
+    "net/url"
+    "regexp"
+    "strconv"
+    "strings"
 
-	. "jy/src/jfw/modules/app/src/app/jyutil"
-
-	util "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	//	"sync"
-	"time"
+    util "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    //	"sync"
+    "time"
 )
 
 // WxKeyset 进入订阅词设置
 func (m *Front) WxKeyset(tpl string) error {
-	defer util.Catch()
-	userid := util.ObjToString(m.GetSession("userId"))
-	surprise := m.GetSession("surprise")
-	if tpl == "index" && isInTSguide(userid, m.Session()) { //仅免费用户跳转向导页面
-		return m.Redirect("/jyapp/tenderSubscribe/guide?url=" + url.QueryEscape(m.Request.RequestURI))
-	}
-	//到新订阅设置
-	vipMsg := jy.GetBigVipUserBaseMsg( m.Session(),  *config.Middleground)
-	if vipMsg.IsUpgrade {
-		return m.Redirect("/jyapp/vipsubscribe/toSubVipSetPage")
-	}
-	if tpl == "seniorset" {
-		/*data, ok := mongodb.FindById("user", userid, `{"o_jy":1}`)*/
-		m.T["haskeyword"] = vipMsg.Data.Free.FreeHasKey
+    defer util.Catch()
+    userid := util.ObjToString(m.GetSession("userId"))
+    surprise := m.GetSession("surprise")
+    if tpl == "index" && isInTSguide(userid, m.Session()) { //仅免费用户跳转向导页面
+        return m.Redirect("/jyapp/tenderSubscribe/guide?url=" + url.QueryEscape(m.Request.RequestURI))
+    }
+    //到新订阅设置
+    vipMsg := jy.GetBigVipUserBaseMsg(m.Session(), *config.Middleground)
+    if vipMsg.IsUpgrade {
+        return m.Redirect("/jyapp/vipsubscribe/toSubVipSetPage")
+    }
+    if tpl == "seniorset" {
+        data := utils.Compatible.Select(userid, `{"o_jy":1}`)
+        if data != nil && len(*data) > 0 {
+            o_jy, _ := (*data)["o_jy"].(map[string]interface{})
+            a_key, _ := o_jy["a_key"].([]interface{})
+            if len(a_key) > 0 {
+                m.T["haskeyword"] = true
+            }
+        }
 
-	}
-	userId, _ := m.GetSession("userId").(string)
-	s_surprise := ""
-	if tpl == "index" || tpl == "filterset" {
-		data, ok := mongodb.FindById("user", userId, `{"o_jy":1}`)
-		var o_jy map[string]interface{}
-		if ok && data != nil && len(*data) > 0 {
-			o_jy, _ = (*data)["o_jy"].(map[string]interface{})
-			s_surprise = util.ObjToString(o_jy["s_surprise"])
-		}
-	}
-	m.T["s_surprise"] = s_surprise
-	m.T["surprise"] = surprise
-	if tpl == "index" {
-		m.T["isIosExam"], m.T["isIosExamPhone"], _, _ = IosExamInfo(m.Action, false, false)
-	}
-	return m.Render("/weixin/wxkeyset/"+tpl+".html", &m.T)
+    }
+    userId, _ := m.GetSession("userId").(string)
+    s_surprise := ""
+    if tpl == "index" || tpl == "filterset" {
+        data := utils.Compatible.Select(userId, `{"o_jy":1}`)
+        var o_jy map[string]interface{}
+        if data != nil && len(*data) > 0 {
+            o_jy, _ = (*data)["o_jy"].(map[string]interface{})
+            s_surprise = util.ObjToString(o_jy["s_surprise"])
+        }
+    }
+    m.T["s_surprise"] = s_surprise
+    m.T["surprise"] = surprise
+    if tpl == "index" {
+        m.T["isIosExam"], m.T["isIosExamPhone"], _, _ = IosExamInfo(m.Action, false, false)
+    }
+    return m.Render("/weixin/wxkeyset/"+tpl+".html", &m.T)
 }
 
 //ajax各种请求
 func (m *Front) WxKeysetAjaxReq() {
-	defer util.Catch()
-	userId, _ := m.GetSession("userId").(string)
-	if userId == "" {
-		m.ServeJson(map[string]interface{}{
-			"flag": false,
-		})
-		return
-	}
-	//增加锁,防止map读写
-	//	lock, _ := m.Session().Get("Lock").(*sync.Mutex)
-	//	lock.Lock()
-	//	defer lock.Unlock()
-	reqType := m.GetString("reqType")
-	if reqType == "getKeyset" { //获取高级设置
-		data, ok := mongodb.FindById("user", userId, `{"o_jy":1,"l_registedate":1}`)
-		var o_jy map[string]interface{}
-		if ok && data != nil && len(*data) > 0 {
-			o_jy, _ = (*data)["o_jy"].(map[string]interface{})
-			o_jy["i_new"] = NewUserByVIP(data)
-			a_key, _ := o_jy["a_key"].([]interface{})
-			m.SetSession("o_jy_a_key", a_key)
-		}
-		m.ServeJson(o_jy)
-		return
-	}
-	/*******************以下是修改操作******************/
-	index := ""
-	saveData := make(map[string]interface{})
-	if reqType == "saveKeyWords" { //保存关键词
-		a_key, _ := m.GetSession("o_jy_a_key").([]interface{})
-		keyWords := m.GetSlice("keyWords")
-		indexs := m.GetSlice("indexs")
-		var keyMaps []map[string]interface{}
-		//给删除的关键词加上标识
-		a_keycopy := make([]map[string]interface{}, len(a_key))
-		//复制
-		for k, v := range a_key {
-			key := v.(map[string]interface{})
-			keycopy := map[string]interface{}{}
-			for k1, v1 := range key {
-				keycopy[k1] = v1
-			}
-			isExists := false
-			for _, i := range indexs {
-				if k == util.IntAll(i) {
-					isExists = true
-					break
-				}
-			}
-			//isExists =false已经被删除
-			keycopy["flag"] = !isExists
-			a_keycopy[k] = keycopy
-		}
-		for k, v := range keyWords {
-			if strings.Trim(v, " ") == "" {
-				continue
-			}
-			if k >= 10 {
-				break
-			}
-			index := util.IntAll(indexs[k])
-			key := map[string]interface{}{}
-			if index < len(a_keycopy) {
-				key = a_keycopy[index]
-				flag, _ := key["flag"].(bool)
-				if flag {
-					key = map[string]interface{}{}
-				} else {
-					delete(key, "flag")
-				}
-			}
-			keys := processKeyword(v)
-			if keys != nil {
-				key["key"] = keys
-				if len(key) > 0 {
-					keyMaps = append(keyMaps, key)
-				}
-			}
-		}
-		saveData["o_jy.a_key"] = keyMaps
-	} else if reqType == "saveArea" { //保存信息范围
-		index = m.GetString("index")
-		saveData["o_jy.a_key."+index+".area"] = m.GetSlice("area")
-	} else if reqType == "saveInfotype" { //保存信息类型
-		index = m.GetString("index")
-		saveData["o_jy.a_key."+index+".infotype"] = m.GetSlice("infotype")
-	} else if reqType == "saveNotkey" { //保存排除关键词
-		index = m.GetString("index")
-		notkey := m.GetSlice("notkey")
-		if len(notkey) > 10 {
-			notkey = notkey[0:10]
-		}
-		for k, v := range notkey {
-			notkey[k] = strings.Replace(v, " ", "", -1)
-		}
-		saveData["o_jy.a_key."+index+".notkey"] = notkey
-	} else if reqType == "saveSeniorset" { //保存高级设置
-		//推送频率:1实时 2每日一推 3自定义时间
-		ratemode, _ := m.GetInteger("ratemode")
-		if ratemode != 2 && ratemode != 3 {
-			ratemode = 1
-		}
-		saveData["o_jy.i_ratemode"] = ratemode
-		apppush, _ := m.GetInteger("apppush")
-		mailpush, _ := m.GetInteger("mailpush")
-		if apppush == 0 && mailpush == 0 {
-			apppush = 1
-		}
-		if ratemode == 3 {
-			saveData["o_jy.i_rmstart"], _ = m.GetInteger("rmstart")
-			saveData["o_jy.i_rmend"], _ = m.GetInteger("rmend")
-		}
-		saveData["o_jy.s_email"] = strings.Trim(m.GetString("email"), " ")
-		saveData["o_jy.i_apppush"] = apppush
-		saveData["o_jy.i_mailpush"] = mailpush
-	} else if reqType == "delKeysWord" { //
-		index = m.GetString("index")
-		var keyMaps = []map[string]interface{}{}
-		a_key, _ := m.GetSession("o_jy_a_key").([]interface{})
-		for k, v := range a_key {
-			if k != util.IntAll(index) {
-				keyMaps = append(keyMaps, v.(map[string]interface{}))
-			}
-		}
-		saveData["o_jy.a_key"] = keyMaps
-	} else if reqType == "setSurp" {
-		saveData["o_jy.s_surprise"] = "A"
-		m.SetSession("surprise", "A")
-	} else if reqType == "saveKeyWordsNew" { //保存 or 修改 整个订阅词接口
-		index = m.GetString("index")
-		indexInt := util.IntAll(index)
-		area := m.GetSlice("area")
-		infotype := m.GetSlice("infotype")
-		notkey := m.GetSlice("notkey")
-		keyWords := m.GetString("keyWords")
-		a_key, a_key_ok := m.GetSession("o_jy_a_key").([]interface{})
-		if len(notkey) > 10 {
-			notkey = notkey[0:10]
-		}
-		for k, v := range notkey {
-			notkey[k] = strings.Replace(v, " ", "", -1)
-		}
-		keys := processKeyword(keyWords)
-		if keys == nil || indexInt >= 10 {
-			m.ServeJson(map[string]interface{}{
-				"flag": false,
-			})
-			return
-		}
-		saveKey := map[string]interface{}{
-			"key":      []string{keys[0]},
-			"area":     fliterEmptyArr(area),
-			"notkey":   fliterEmptyArr(notkey),
-			"infotype": fliterEmptyArr(infotype),
-		}
-		var optime time.Time
-		var regtime int64
-		if rd, ok := mongodb.FindById("user", userId, `{"o_jy":1,"l_registedate":1}`); rd != nil && ok && len(*rd) > 0 {
-			//获取活动上线时间
-			optimalTime, _ := config.Sysconfig["optimalTime"].(string)
-			optime, _ = time.ParseInLocation(Date_Full_Layout, optimalTime, time.Local)
-			regtime, _ = (*rd)["l_registedate"].(int64)
-			if ojy, _ := (*rd)["o_jy"].(map[string]interface{}); len(ojy) > 0 {
-				if ojy["i_new"] == nil {
-					if time.Unix(regtime, 0).After(optime) {
-						saveData["o_jy.i_new"] = 1
-					} else {
-						saveData["o_jy.i_new"] = 0
-					}
-				}
-				if ojy["a_key"] != nil {
-					ak, _ := ojy["a_key"].([]interface{})
-					if len(ak) > indexInt {
-						if akmap, _ := ak[indexInt].(map[string]interface{}); akmap["from"] != nil {
-							saveKey["from"] = akmap["from"]
-						}
-					}
-				}
-			}
-		}
-		if !a_key_ok && indexInt == 0 { //第一次新增
-			index = ""
-			saveData["o_jy.a_key"] = []map[string]interface{}{saveKey}
-			if time.Unix(regtime, 0).Before(optime) {
-				saveData["o_jy.i_new"] = 1
-			}
-		} else { //修改新增
-			if indexInt > len(a_key) {
-				indexInt = len(a_key)
-			}
-			saveData[fmt.Sprintf("o_jy.a_key.%d", indexInt)] = saveKey
-		}
-	}
-	//修改操作
-	var flag bool
-	if len(saveData) > 0 {
-		saveData["o_jy.l_modifydate"] = time.Now().Unix()
-		if index == "" {
-			flag = mongodb.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-		} else {
-			if intIndex, e := strconv.Atoi(index); e == nil && intIndex >= 0 && intIndex < 10 {
-				flag = mongodb.UpdateById("user", userId, map[string]interface{}{
-					"$set": saveData,
-				})
-			}
-		}
-	}
-	m.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
-	return
+    defer util.Catch()
+    userId, _ := m.GetSession("userId").(string)
+    if userId == "" {
+        m.ServeJson(map[string]interface{}{
+            "flag": false,
+        })
+        return
+    }
+    //增加锁,防止map读写
+    //	lock, _ := m.Session().Get("Lock").(*sync.Mutex)
+    //	lock.Lock()
+    //	defer lock.Unlock()
+    reqType := m.GetString("reqType")
+    if reqType == "getKeyset" { //获取高级设置
+        data := utils.Compatible.Select(userId, `{"o_jy":1,"l_registedate":1}`)
+        var o_jy map[string]interface{}
+        if data != nil && len(*data) > 0 {
+            o_jy, _ = (*data)["o_jy"].(map[string]interface{})
+            o_jy["i_new"] = NewUserByVIP(data)
+            a_key, _ := o_jy["a_key"].([]interface{})
+            m.SetSession("o_jy_a_key", a_key)
+        }
+        m.ServeJson(o_jy)
+        return
+    }
+    /*******************以下是修改操作******************/
+    index := ""
+    saveData := make(map[string]interface{})
+    if reqType == "saveKeyWords" { //保存关键词
+        a_key, _ := m.GetSession("o_jy_a_key").([]interface{})
+        keyWords := m.GetSlice("keyWords")
+        indexs := m.GetSlice("indexs")
+        var keyMaps []map[string]interface{}
+        //给删除的关键词加上标识
+        a_keycopy := make([]map[string]interface{}, len(a_key))
+        //复制
+        for k, v := range a_key {
+            key := v.(map[string]interface{})
+            keycopy := map[string]interface{}{}
+            for k1, v1 := range key {
+                keycopy[k1] = v1
+            }
+            isExists := false
+            for _, i := range indexs {
+                if k == util.IntAll(i) {
+                    isExists = true
+                    break
+                }
+            }
+            //isExists =false已经被删除
+            keycopy["flag"] = !isExists
+            a_keycopy[k] = keycopy
+        }
+        for k, v := range keyWords {
+            if strings.Trim(v, " ") == "" {
+                continue
+            }
+            if k >= 10 {
+                break
+            }
+            index := util.IntAll(indexs[k])
+            key := map[string]interface{}{}
+            if index < len(a_keycopy) {
+                key = a_keycopy[index]
+                flag, _ := key["flag"].(bool)
+                if flag {
+                    key = map[string]interface{}{}
+                } else {
+                    delete(key, "flag")
+                }
+            }
+            keys := processKeyword(v)
+            if keys != nil {
+                key["key"] = keys
+                if len(key) > 0 {
+                    keyMaps = append(keyMaps, key)
+                }
+            }
+        }
+        saveData["o_jy.a_key"] = keyMaps
+    } else if reqType == "saveArea" { //保存信息范围
+        index = m.GetString("index")
+        saveData["o_jy.a_key."+index+".area"] = m.GetSlice("area")
+    } else if reqType == "saveInfotype" { //保存信息类型
+        index = m.GetString("index")
+        saveData["o_jy.a_key."+index+".infotype"] = m.GetSlice("infotype")
+    } else if reqType == "saveNotkey" { //保存排除关键词
+        index = m.GetString("index")
+        notkey := m.GetSlice("notkey")
+        if len(notkey) > 10 {
+            notkey = notkey[0:10]
+        }
+        for k, v := range notkey {
+            notkey[k] = strings.Replace(v, " ", "", -1)
+        }
+        saveData["o_jy.a_key."+index+".notkey"] = notkey
+    } else if reqType == "saveSeniorset" { //保存高级设置
+        //推送频率:1实时 2每日一推 3自定义时间
+        ratemode, _ := m.GetInteger("ratemode")
+        if ratemode != 2 && ratemode != 3 {
+            ratemode = 1
+        }
+        saveData["o_jy.i_ratemode"] = ratemode
+        apppush, _ := m.GetInteger("apppush")
+        mailpush, _ := m.GetInteger("mailpush")
+        if apppush == 0 && mailpush == 0 {
+            apppush = 1
+        }
+        if ratemode == 3 {
+            saveData["o_jy.i_rmstart"], _ = m.GetInteger("rmstart")
+            saveData["o_jy.i_rmend"], _ = m.GetInteger("rmend")
+        }
+        saveData["o_jy.s_email"] = strings.Trim(m.GetString("email"), " ")
+        saveData["o_jy.i_apppush"] = apppush
+        saveData["o_jy.i_mailpush"] = mailpush
+    } else if reqType == "delKeysWord" { //
+        index = m.GetString("index")
+        var keyMaps = []map[string]interface{}{}
+        a_key, _ := m.GetSession("o_jy_a_key").([]interface{})
+        for k, v := range a_key {
+            if k != util.IntAll(index) {
+                keyMaps = append(keyMaps, v.(map[string]interface{}))
+            }
+        }
+        saveData["o_jy.a_key"] = keyMaps
+    } else if reqType == "setSurp" {
+        saveData["o_jy.s_surprise"] = "A"
+        m.SetSession("surprise", "A")
+    } else if reqType == "saveKeyWordsNew" { //保存 or 修改 整个订阅词接口
+        index = m.GetString("index")
+        indexInt := util.IntAll(index)
+        area := m.GetSlice("area")
+        infotype := m.GetSlice("infotype")
+        notkey := m.GetSlice("notkey")
+        keyWords := m.GetString("keyWords")
+        a_key, a_key_ok := m.GetSession("o_jy_a_key").([]interface{})
+        if len(notkey) > 10 {
+            notkey = notkey[0:10]
+        }
+        for k, v := range notkey {
+            notkey[k] = strings.Replace(v, " ", "", -1)
+        }
+        keys := processKeyword(keyWords)
+        if keys == nil || indexInt >= 10 {
+            m.ServeJson(map[string]interface{}{
+                "flag": false,
+            })
+            return
+        }
+        saveKey := map[string]interface{}{
+            "key":      []string{keys[0]},
+            "area":     fliterEmptyArr(area),
+            "notkey":   fliterEmptyArr(notkey),
+            "infotype": fliterEmptyArr(infotype),
+        }
+        var optime time.Time
+        var regtime int64
+        if rd := utils.Compatible.Select(userId, `{"o_jy":1,"l_registedate":1}`); rd != nil && len(*rd) > 0 {
+            //获取活动上线时间
+            optimalTime, _ := config.Sysconfig["optimalTime"].(string)
+            optime, _ = time.ParseInLocation(Date_Full_Layout, optimalTime, time.Local)
+            regtime, _ = (*rd)["l_registedate"].(int64)
+            if ojy, _ := (*rd)["o_jy"].(map[string]interface{}); len(ojy) > 0 {
+                if ojy["i_new"] == nil {
+                    if time.Unix(regtime, 0).After(optime) {
+                        saveData["o_jy.i_new"] = 1
+                    } else {
+                        saveData["o_jy.i_new"] = 0
+                    }
+                }
+                if ojy["a_key"] != nil {
+                    ak, _ := ojy["a_key"].([]interface{})
+                    if len(ak) > indexInt {
+                        if akmap, _ := ak[indexInt].(map[string]interface{}); akmap["from"] != nil {
+                            saveKey["from"] = akmap["from"]
+                        }
+                    }
+                }
+            }
+        }
+        if !a_key_ok && indexInt == 0 { //第一次新增
+            index = ""
+            saveData["o_jy.a_key"] = []map[string]interface{}{saveKey}
+            if time.Unix(regtime, 0).Before(optime) {
+                saveData["o_jy.i_new"] = 1
+            }
+        } else { //修改新增
+            if indexInt > len(a_key) {
+                indexInt = len(a_key)
+            }
+            saveData[fmt.Sprintf("o_jy.a_key.%d", indexInt)] = saveKey
+        }
+    }
+    //修改操作
+    var flag bool
+    if len(saveData) > 0 {
+        saveData["o_jy.l_modifydate"] = time.Now().Unix()
+        if index == "" {
+            flag = utils.Compatible.Update(userId, map[string]interface{}{
+                "$set": saveData,
+            })
+        } else {
+            if intIndex, e := strconv.Atoi(index); e == nil && intIndex >= 0 && intIndex < 10 {
+                flag = utils.Compatible.Update(userId, map[string]interface{}{
+                    "$set": saveData,
+                })
+            }
+        }
+    }
+    m.ServeJson(map[string]interface{}{
+        "flag": flag,
+    })
+    return
 }
 
 //过滤[""]数组
 func fliterEmptyArr(beforeArr []string) []string {
-	afterArr := []string{}
-	for _, v := range beforeArr {
-		if v == "" {
-			continue
-		}
-		afterArr = append(afterArr, v)
-	}
-	return afterArr
+    afterArr := []string{}
+    for _, v := range beforeArr {
+        if v == "" {
+            continue
+        }
+        afterArr = append(afterArr, v)
+    }
+    return afterArr
 }
 
 //高级设置
 func (m *Front) WxKeysetSeniorset() error {
-	return m.Render("/weixin/wxkeyset/seniorset.html")
+    return m.Render("/weixin/wxkeyset/seniorset.html")
 }
 
 //高级设置
 func (m *Front) WxKeysetFilterset() error {
-	return m.Render("/weixin/wxkeyset/filterset.html")
+    return m.Render("/weixin/wxkeyset/filterset.html")
 }
 
 //保存入库之前,处理订阅的关键词
 func processKeyword(keyword string) []string {
-	keywordReg := regexp.MustCompile("([\\s\u3000\u2003\u00a0+,,])+")
-	spaceReg := regexp.MustCompile("\\s+")
-	keyword = keywordReg.ReplaceAllString(keyword, " ")
-	keyword = spaceReg.ReplaceAllString(keyword, " ")
-	keyword = strings.Trim(keyword, " ")
-	if keyword == "" {
-		return nil
-	}
-	return strings.Split(keyword, " ")
+    keywordReg := regexp.MustCompile("([\\s\u3000\u2003\u00a0+,,])+")
+    spaceReg := regexp.MustCompile("\\s+")
+    keyword = keywordReg.ReplaceAllString(keyword, " ")
+    keyword = spaceReg.ReplaceAllString(keyword, " ")
+    keyword = strings.Trim(keyword, " ")
+    if keyword == "" {
+        return nil
+    }
+    return strings.Split(keyword, " ")
 }
 
 //超级订阅优化,免费订阅判断新老用户  1:新用户 0:老用户
 func NewUserByVIP(mData *map[string]interface{}) int {
-	if len(*mData) == 0 || mData == nil {
-		return 1
-	}
-	ojy, _ := (*mData)["o_jy"].(map[string]interface{})
-	if len(ojy) > 0 {
-		if ojy["i_new"] != nil {
-			return util.IntAllDef(ojy["i_new"], 1)
-		}
-		optimalTime, _ := config.Sysconfig["optimalTime"].(string)
-		optime, _ := time.ParseInLocation(Date_Full_Layout, optimalTime, time.Local)
-		regtime, _ := (*mData)["l_registedate"].(int64)
-		//如果a_key 存在 即为老用户
-		if (ojy["a_key"] == nil && time.Unix(regtime, 0).Before(optime)) || (time.Unix(regtime, 0).After(optime)) {
-			return 1
-		}
-	}
-	return 0
+    if len(*mData) == 0 || mData == nil {
+        return 1
+    }
+    ojy, _ := (*mData)["o_jy"].(map[string]interface{})
+    if len(ojy) > 0 {
+        if ojy["i_new"] != nil {
+            return util.IntAllDef(ojy["i_new"], 1)
+        }
+        optimalTime, _ := config.Sysconfig["optimalTime"].(string)
+        optime, _ := time.ParseInLocation(Date_Full_Layout, optimalTime, time.Local)
+        regtime, _ := (*mData)["l_registedate"].(int64)
+        //如果a_key 存在 即为老用户
+        if (ojy["a_key"] == nil && time.Unix(regtime, 0).Before(optime)) || (time.Unix(regtime, 0).After(optime)) {
+            return 1
+        }
+    }
+    return 0
 }

+ 19 - 19
src/jfw/modules/app/src/app/jylabutil/authority.go

@@ -2,8 +2,8 @@
 package jylabutil
 
 import (
-	"app.yhyue.com/moapp/jypkg/public"
-	qu "app.yhyue.com/moapp/jybase/common"
+    qu "app.yhyue.com/moapp/jybase/common"
+    utils "jy/src/jfw/modules/app/src/app/jyutil"
 )
 
 //UpdateAuthory 设置用户权限
@@ -11,27 +11,27 @@ import (
 //field  用户权限属性字段
 //value  用户权限值
 func UpdateAuthory(userid, field string, value int) bool {
-	b := public.MQFW.UpdateById("user", userid,
-		map[string]interface{}{
-			"$set": map[string]interface{}{
-				field: value,
-			},
-		})
-	return b
+    b := utils.Compatible.Update(userid,
+        map[string]interface{}{
+            "$set": map[string]interface{}{
+                field: value,
+            },
+        })
+    return b
 }
 
 //IsAuthorized 获取当前模块是否有权限
 //userid 用户_id
 //field  用户权限属性字段
 func IsAuthorized(userid, field string) bool {
-	user, b := public.MQFW.FindById("user", userid, nil)
-	if len(*user) > 0 && b {
-		if qu.Int64All((*user)[field]) == 1 {
-			return true
-		} else {
-			return false
-		}
-	} else {
-		return false
-	}
+    user := utils.Compatible.Select(userid, nil)
+    if len(*user) > 0 {
+        if qu.Int64All((*user)[field]) == 1 {
+            return true
+        } else {
+            return false
+        }
+    } else {
+        return false
+    }
 }

+ 135 - 133
src/jfw/modules/app/src/app/jyutil/util.go

@@ -1,181 +1,183 @@
 package jyutil
 
 import (
-	"encoding/json"
-	. "jy/src/jfw/modules/app/src/jfw/config"
-	"app.yhyue.com/moapp/jypkg/public"
-	util "app.yhyue.com/moapp/jybase/common"
-	"reflect"
-	"regexp"
-	"sort"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-
-	"fmt"
-	"sync"
-	"time"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jypkg/compatible"
+    "app.yhyue.com/moapp/jypkg/public"
+    "encoding/json"
+    . "jy/src/jfw/modules/app/src/jfw/config"
+    "reflect"
+    "regexp"
+    "sort"
+
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "fmt"
+    "sync"
+    "time"
 )
 
+var Compatible = compatible.NewCompatible(&mongodb, public.BaseMysql, public.Mysql, Middleground)
+
 func init() {
-	VarOrderCode = &orderCode{
-		pool: make(chan string, 20),
-		all:  &sync.Map{},
-		lock: &sync.Mutex{},
-	}
-	VarOrderCode.gc()
-	for i := 0; i < 10; i++ {
-		go func() {
-			for {
-				o := fmt.Sprintf("%d%s", time.Now().Unix(), util.GetRandom(6))
-				VarOrderCode.lock.Lock()
-				if _, ok := VarOrderCode.all.Load(o); ok {
-					VarOrderCode.lock.Unlock()
-					continue
-				}
-				VarOrderCode.all.Store(o, time.Now().Day())
-				VarOrderCode.lock.Unlock()
-				VarOrderCode.pool <- o
-			}
-		}()
-	}
+    VarOrderCode = &orderCode{
+        pool: make(chan string, 20),
+        all:  &sync.Map{},
+        lock: &sync.Mutex{},
+    }
+    VarOrderCode.gc()
+    for i := 0; i < 10; i++ {
+        go func() {
+            for {
+                o := fmt.Sprintf("%d%s", time.Now().Unix(), util.GetRandom(6))
+                VarOrderCode.lock.Lock()
+                if _, ok := VarOrderCode.all.Load(o); ok {
+                    VarOrderCode.lock.Unlock()
+                    continue
+                }
+                VarOrderCode.all.Store(o, time.Now().Day())
+                VarOrderCode.lock.Unlock()
+                VarOrderCode.pool <- o
+            }
+        }()
+    }
 }
 
 //生成订单号
 var VarOrderCode *orderCode
 
 type orderCode struct {
-	pool chan string
-	all  *sync.Map
-	lock *sync.Mutex
+    pool chan string
+    all  *sync.Map
+    lock *sync.Mutex
 }
 
 func (o *orderCode) gc() {
-	VarOrderCode.all.Range(func(key, value interface{}) bool {
-		if time.Now().Day() != value.(int) {
-			VarOrderCode.all.Delete(key)
-		}
-		return true
-	})
-	time.AfterFunc(24*time.Hour, o.gc)
+    VarOrderCode.all.Range(func(key, value interface{}) bool {
+        if time.Now().Day() != value.(int) {
+            VarOrderCode.all.Delete(key)
+        }
+        return true
+    })
+    time.AfterFunc(24*time.Hour, o.gc)
 }
 
 //创建订单号
 func (o *orderCode) Get() string {
-	return <-VarOrderCode.pool
+    return <-VarOrderCode.pool
 }
 
 var IosReg = regexp.MustCompile(`\(i[^;]+;( U;)? CPU.+Mac OS X`)
 var IosIpadReg = regexp.MustCompile(`\(M[^;]+; Intel Mac OS X`)
 
 func IosExamInfo(a *xweb.Action, vip, ent bool) (bool, bool, bool, bool) {
-	if !IosReg.MatchString(a.Header("User-Agent")) && !IosIpadReg.MatchString(a.Header("User-Agent")) {
-		return false, false, false, false
-	}
-	iosExam, _ := Seoconfig["IosExam"].(map[string]interface{})
-	iosExam_flag, _ := iosExam["flag"].(bool)
-	//
-	iosExam_phone, _ := iosExam["phone"].(string)
-	isExamPhone := false
-	if phone, _ := a.GetSession("s_phone").(string); phone != "" && phone == iosExam_phone {
-		isExamPhone = true
-	}
-	//
-	isVip := false
-	isEnt := false
-	if iosExam_flag && (vip || ent) {
-		if userId, _ := a.GetSession("userId").(string); userId != "" {
-			user, ok := mongodb.FindById("user", userId, `{"i_vip_status":1,"s_phone":1,"s_m_phone":1}`)
-			if ok && user != nil {
-				i_vip_status := util.IntAll((*user)["i_vip_status"])
-				isVip = i_vip_status == 1 || i_vip_status == 2
-			}
-			s_phone, _ := (*user)["s_phone"].(string)
-			if s_phone == "" {
-				s_phone, _ = (*user)["s_m_phone"].(string)
-			}
-			if ent && public.Mysql.CountBySql(`select count(1) as count from entniche_info where phone=? and status=1`, s_phone) > 0 {
-				isEnt = true
-			}
-		}
-	}
-	return iosExam_flag, isExamPhone, isVip, isEnt
+    if !IosReg.MatchString(a.Header("User-Agent")) && !IosIpadReg.MatchString(a.Header("User-Agent")) {
+        return false, false, false, false
+    }
+    iosExam, _ := Seoconfig["IosExam"].(map[string]interface{})
+    iosExam_flag, _ := iosExam["flag"].(bool)
+    //
+    iosExam_phone, _ := iosExam["phone"].(string)
+    isExamPhone := false
+    if phone, _ := a.GetSession("s_phone").(string); phone != "" && phone == iosExam_phone {
+        isExamPhone = true
+    }
+    //
+    isVip := false
+    isEnt := false
+    if iosExam_flag && (vip || ent) {
+        if userId, _ := a.GetSession("userId").(string); userId != "" {
+            user := Compatible.Select(  userId, `{"i_vip_status":1,"s_phone":1,"s_m_phone":1}`)
+            if user != nil {
+                i_vip_status := util.IntAll((*user)["i_vip_status"])
+                isVip = i_vip_status == 1 || i_vip_status == 2
+            }
+            s_phone, _ := (*user)["s_phone"].(string)
+            if s_phone == "" {
+                s_phone, _ = (*user)["s_m_phone"].(string)
+            }
+            if ent && public.Mysql.CountBySql(`select count(1) as count from entniche_info where phone=? and status=1`, s_phone) > 0 {
+                isEnt = true
+            }
+        }
+    }
+    return iosExam_flag, isExamPhone, isVip, isEnt
 }
 
 // 排序 排序键必须为数字类型
 type SortBy struct {
-	Data    []map[string]interface{}
-	Sortkey string
+    Data    []map[string]interface{}
+    Sortkey string
 }
 
 func (a SortBy) Len() int { return len(a.Data) }
 
 func (a SortBy) Swap(i, j int) {
-	a.Data[i], a.Data[j] = a.Data[j], a.Data[i]
+    a.Data[i], a.Data[j] = a.Data[j], a.Data[i]
 }
 
 func (a SortBy) Less(i, j int) bool {
-	//return Float64(a.Data[i][a.Sortkey]) < Float64(a.Data[j][a.Sortkey])
-	m := a.Data[i][a.Sortkey]
-	n := a.Data[j][a.Sortkey]
-	w := reflect.ValueOf(m)
-	v := reflect.ValueOf(n)
-	switch v.Kind() {
-	case reflect.String:
-		return w.String() < v.String()
-	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-		return w.Int() < v.Int()
-	case reflect.Float64, reflect.Float32:
-		return w.Float() < v.Float()
-	default:
-		return fmt.Sprintf("%v", w) < fmt.Sprintf("%v", v)
-	}
+    //return Float64(a.Data[i][a.Sortkey]) < Float64(a.Data[j][a.Sortkey])
+    m := a.Data[i][a.Sortkey]
+    n := a.Data[j][a.Sortkey]
+    w := reflect.ValueOf(m)
+    v := reflect.ValueOf(n)
+    switch v.Kind() {
+    case reflect.String:
+        return w.String() < v.String()
+    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+        return w.Int() < v.Int()
+    case reflect.Float64, reflect.Float32:
+        return w.Float() < v.Float()
+    default:
+        return fmt.Sprintf("%v", w) < fmt.Sprintf("%v", v)
+    }
 }
 
 // ture  倒序3, 2, 1
 //fmt.Println(m)
 func SortData(data interface{}, sortkey string, reverse bool) {
-	//func SortData(data interface{}, sortkey string, reverse bool) {
-	var db []map[string]interface{}
-	err := Bind(data, &db)
-	if err != nil {
-		fmt.Println(err)
-		return
-	}
-	stb := SortBy{db, sortkey}
-	if !reverse {
-		sort.Sort(stb)
-	} else {
-		sort.Sort(sort.Reverse(stb))
-	}
-	err = Bind(stb.Data, data)
-	if err != nil {
-		fmt.Println(err)
-	}
+    //func SortData(data interface{}, sortkey string, reverse bool) {
+    var db []map[string]interface{}
+    err := Bind(data, &db)
+    if err != nil {
+        fmt.Println(err)
+        return
+    }
+    stb := SortBy{db, sortkey}
+    if !reverse {
+        sort.Sort(stb)
+    } else {
+        sort.Sort(sort.Reverse(stb))
+    }
+    err = Bind(stb.Data, data)
+    if err != nil {
+        fmt.Println(err)
+    }
 
 }
 
 // data 转换成ret
 func Bind(data interface{}, ret interface{}) error {
-	v := reflect.ValueOf(ret)
-	if v.Kind() != reflect.Ptr {
-		return fmt.Errorf("ptr input ret needed as type as input type %s", v.Kind())
-	}
-	havdata := false
-	var bk interface{}
-	if v.Elem().Kind() == reflect.Slice {
-		t := reflect.Zero(reflect.TypeOf(v.Elem().Interface()))
-		bk = v.Elem().Interface()
-		v.Elem().Set(t)
-		havdata = true
-	}
-	_data, _ := json.MarshalIndent(data, "", "    ")
-	err := json.Unmarshal(_data, ret)
-	if err != nil {
-		fmt.Println(err)
-		if havdata {
-			v.Elem().Set(reflect.ValueOf(bk))
-		}
-		return err
-	}
-	return nil
+    v := reflect.ValueOf(ret)
+    if v.Kind() != reflect.Ptr {
+        return fmt.Errorf("ptr input ret needed as type as input type %s", v.Kind())
+    }
+    havdata := false
+    var bk interface{}
+    if v.Elem().Kind() == reflect.Slice {
+        t := reflect.Zero(reflect.TypeOf(v.Elem().Interface()))
+        bk = v.Elem().Interface()
+        v.Elem().Set(t)
+        havdata = true
+    }
+    _data, _ := json.MarshalIndent(data, "", "    ")
+    err := json.Unmarshal(_data, ret)
+    if err != nil {
+        fmt.Println(err)
+        if havdata {
+            v.Elem().Set(reflect.ValueOf(bk))
+        }
+        return err
+    }
+    return nil
 }

+ 2 - 1
src/jfw/modules/app/src/go.mod

@@ -4,7 +4,7 @@ go 1.18
 
 require (
 	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
-	app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa
+	app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114
 	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230209030331-362833655274
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/dchest/captcha v1.0.0
@@ -16,6 +16,7 @@ require (
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
 	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 // indirect
 	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230209005453-ef0d34675e8d // indirect
 	bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4 // indirect
 	github.com/BurntSushi/toml v0.4.1 // indirect

+ 4 - 2
src/jfw/modules/app/src/go.sum

@@ -13,11 +13,13 @@ app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tc
 app.yhyue.com/moapp/jybase v0.0.0-20221229065928-e4ba75127ac9/go.mod h1:efAeRPDpJ13JuNODuqtfLlKQSQgCbnUcwGPzhFU5krY=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a h1:wD4aWPSYdiX1cIP4lzzPD2s7fYhKa3muIf97l9tonJE=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa h1:0/2I4ubgDsRbKm7PeiVSTvYwZCK3anZQaEagsGBbI7E=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa/go.mod h1:0DqPlGxaufZlKaLoRndTWG4j3qUQqJ6MNZCmoPcMqSg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114 h1:89J5Zq4bfnocIpEWBn19PnfaT+8Dh+Rv4X8QoTwxCpg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114/go.mod h1:sa5YRPqTQLOVBmpltjT21EkQ7DfJbUZFARUb4ZJ7U+k=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae h1:6rDDaz6yxvE8viTSzEBwKYOFWq14TMfuBivSazUZMz4=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
 bp.jydev.jianyu360.cn/BP/jynsq v0.0.0-20220222052708-ebc43af90698/go.mod h1:ojo/AUH9Yr1wzarEjOaNMkj1Cet/9r8IgLyba64Z52E=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 h1:cw/PdRypNFcYOk4iWAfHjIFoMzIlXUfl9XAmWujBOPY=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7/go.mod h1:7Xhygw0KBuL4h0G76FnFg4otQcA9bmOO0c8M0FCjAyQ=
 bp.jydev.jianyu360.cn/BaseService/gateway v0.0.0-20220419090715-88ddb32961be/go.mod h1:Yj4oabIGItuMoF0BXYLz2XAnF581kxgXBrvlUtIJrkI=
 bp.jydev.jianyu360.cn/BaseService/gateway v1.3.4/go.mod h1:BMLd/5wb3BIEGhnEgF9y1sJN9P5/Dw9kYsoiE9V8I9g=
 bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230209005453-ef0d34675e8d h1:72TRQQikWIbu0T5WVsq3CI5HCqFDKsE63wRPMc9r5CE=

+ 1 - 1
src/jfw/modules/app/src/public/rpccall.go

@@ -1,7 +1,7 @@
 package public
 
 import (
-	"encoding/json"
+    "encoding/json"
 	config "jy/src/jfw/modules/app/src/jfw/config"
 	"log"
 	"net/rpc"

+ 75 - 64
src/jfw/modules/bidfileinter/src/config.json

@@ -1,69 +1,80 @@
 {
-	"webport": "92",
-	"webdomain":"https://web-jydev-zxl.jianyu360.cn",
-	"mongodb": {
-		"main": {
-			"address": "192.168.3.128:27080",
-	 		"size": 5,
-	 		"dbName": "qfw"
-		},
-		"log": {
-			"address": "192.168.3.128:27080",
-	 		"size": 5,
-	 		"dbName": "qfw",
-			"userName": "admin",
-			"password": "123456"
-		}
-	},
-    "redis": {
-    		"main": {
-			"address": "other=192.168.3.128:1712,session=192.168.3.128:1712"
-		}
+  "webport": "92",
+  "webdomain": "https://web-jydev-zxl.jianyu360.cn",
+  "mongodb": {
+    "main": {
+      "address": "192.168.3.128:27080",
+      "size": 5,
+      "dbName": "qfw"
     },
-    "mysql": {
-	    "main": {
-	         "dbName": "jianyu",
-	        "address": "192.168.3.11:3366",
-	        "userName": "root",
-	        "passWord": "Topnet123",
-			"maxOpenConns": 2,
-			"maxIdleConns": 2
-	    }
+    "log": {
+      "address": "192.168.3.128:27080",
+      "size": 5,
+      "dbName": "qfw",
+      "userName": "admin",
+      "password": "123456"
+    }
+  },
+  "redis": {
+    "main": {
+      "address": "other=192.168.3.128:1712,session=192.168.3.128:1712"
+    }
+  },
+  "mysql": {
+    "main": {
+      "dbName": "jianyu",
+      "address": "192.168.3.11:3366",
+      "userName": "root",
+      "passWord": "Topnet123",
+      "maxOpenConns": 2,
+      "maxIdleConns": 2
     },
-    "elasticsearch": {
-		"main": {
-			"address": "http://192.168.3.128:9800",
-	    	"size": 2
-		}
+    "base": {
+      "dbName": "base_service",
+      "address": "192.168.3.217:4000",
+      "userName": "root",
+      "passWord": "=PDT49#80Z!RVv52_z",
+      "maxOpenConns": 5,
+      "maxIdleConns": 5
+    }
+  },
+  "elasticsearch": {
+    "main": {
+      "address": "http://192.168.3.128:9800",
+      "size": 2
+    }
+  },
+  "mail": [
+    {
+      "addr": "smtp.exmail.qq.com",
+      "port": 465,
+      "pwd": "ue9Rg9Sf4CVtdm5a",
+      "user": "public03@topnet.net.cn"
     },
-    "mail": [
-        {
-            "addr": "smtp.exmail.qq.com",
-            "port": 465,
-            "pwd": "ue9Rg9Sf4CVtdm5a",
-            "user": "public03@topnet.net.cn"
-        },
-        {
-            "addr": "smtp.exmail.qq.com",
-            "port": 465,
-            "pwd": "ue9Rg9Sf4CVtdm5a",
-            "user": "public03@topnet.net.cn"
-        }
-    ],
-	"uploadPath": "./web/staticres/upload/res/",
-	"untoken":"dV2Q7TIlsHoDmY1dz9YBbfMfovTK8CT1l2CJc9yEaGmKPLzad8EneHb/5tX2Ipl/g3xl+BCyZ0SSf/KjJLWhLR/a9jisEI8mIxQdwSNU+TIeo9PAqDwgZ1FnrPr0qAw9bEctflJ4w2EWSo9qOvErqsbCtqiHT3H+ZdPYgr1EFWM=",
-	"downloadZbZipTask":"0 */3 * * * ?",
-	"taskIsRun":false,
-	"alarmMail":["zhangxinlei@topnet.net.cn","745811385@qq.com"],
-	"fileMaxSize":30,
-	"checkFailTask":"0 */1 * * * ?",
-	"failTime":5,
-	"integralUrl":{
-		"balance":"http://0.0.0.0:8888/integralBalanceCheck",
-		"consume":"http://0.0.0.0:8888/integralConsume"
-	},
-	"appids":{
-		"jianyu":"10000"
-	},
-	"pointCount":500
+    {
+      "addr": "smtp.exmail.qq.com",
+      "port": 465,
+      "pwd": "ue9Rg9Sf4CVtdm5a",
+      "user": "public03@topnet.net.cn"
+    }
+  ],
+  "uploadPath": "./web/staticres/upload/res/",
+  "untoken": "dV2Q7TIlsHoDmY1dz9YBbfMfovTK8CT1l2CJc9yEaGmKPLzad8EneHb/5tX2Ipl/g3xl+BCyZ0SSf/KjJLWhLR/a9jisEI8mIxQdwSNU+TIeo9PAqDwgZ1FnrPr0qAw9bEctflJ4w2EWSo9qOvErqsbCtqiHT3H+ZdPYgr1EFWM=",
+  "downloadZbZipTask": "0 */3 * * * ?",
+  "taskIsRun": false,
+  "alarmMail": [
+    "zhangxinlei@topnet.net.cn",
+    "745811385@qq.com"
+  ],
+  "fileMaxSize": 30,
+  "checkFailTask": "0 */1 * * * ?",
+  "failTime": 5,
+  "integralUrl": {
+    "balance": "http://0.0.0.0:8888/integralBalanceCheck",
+    "consume": "http://0.0.0.0:8888/integralConsume"
+  },
+  "appids": {
+    "jianyu": "10000"
+  },
+  "pointCount": 500
 }

+ 89 - 4
src/jfw/modules/bidfileinter/src/go.mod

@@ -3,7 +3,9 @@ module jy/src/jfw/modules/bidfileinter/src
 go 1.18
 
 require (
-	app.yhyue.com/moapp/jybase v0.0.0-20230110071808-0c8ff7f798c6
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg v0.0.0-20230210020312-75e22a7a7be4
+	github.com/gogf/gf/v2 v2.3.1
 	github.com/robfig/cron v1.2.0
 	github.com/tealeg/xlsx v1.0.5
 	go.mongodb.org/mongo-driver v1.11.1
@@ -11,26 +13,109 @@ require (
 
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
+	bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 // indirect
+	bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4 // indirect
+	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230129060002-f69424aa14ba // indirect
+	github.com/BurntSushi/toml v1.1.0 // indirect
+	github.com/beorn7/perks v1.0.1 // indirect
+	github.com/cenkalti/backoff/v4 v4.1.3 // indirect
+	github.com/cespare/xxhash/v2 v2.1.2 // indirect
+	github.com/clbanning/mxj/v2 v2.5.5 // indirect
+	github.com/coreos/go-semver v0.3.0 // indirect
+	github.com/coreos/go-systemd/v22 v22.3.2 // indirect
+	github.com/davecgh/go-spew v1.1.1 // indirect
 	github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f // indirect
+	github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+	github.com/fatih/color v1.13.0 // indirect
+	github.com/felixge/fgprof v0.9.3 // indirect
+	github.com/fsnotify/fsnotify v1.5.4 // indirect
 	github.com/garyburd/redigo v1.6.2 // indirect
-	github.com/go-sql-driver/mysql v1.6.0 // indirect
+	github.com/go-logr/logr v1.2.3 // indirect
+	github.com/go-logr/stdr v1.2.2 // indirect
+	github.com/go-redis/redis/v8 v8.11.5 // indirect
+	github.com/go-sql-driver/mysql v1.7.0 // indirect
+	github.com/gogo/protobuf v1.3.2 // indirect
+	github.com/golang/mock v1.6.0 // indirect
+	github.com/golang/protobuf v1.5.2 // indirect
 	github.com/golang/snappy v0.0.4 // indirect
 	github.com/gomodule/redigo v1.8.9 // indirect
+	github.com/google/go-cmp v0.5.9 // indirect
+	github.com/google/gofuzz v1.2.0 // indirect
+	github.com/google/pprof v0.0.0-20211214055906-6f57359322fd // indirect
+	github.com/googleapis/gnostic v0.5.5 // indirect
+	github.com/gorilla/websocket v1.5.0 // indirect
+	github.com/grokify/html-strip-tags-go v0.0.1 // indirect
+	github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 // indirect
 	github.com/howeyc/fsnotify v0.9.0 // indirect
 	github.com/jinzhu/inflection v1.0.0 // indirect
 	github.com/jinzhu/now v1.1.1 // indirect
+	github.com/json-iterator/go v1.1.12 // indirect
 	github.com/klauspost/compress v1.13.6 // indirect
+	github.com/magiconair/properties v1.8.6 // indirect
+	github.com/mattn/go-colorable v0.1.9 // indirect
+	github.com/mattn/go-isatty v0.0.14 // indirect
+	github.com/mattn/go-runewidth v0.0.13 // indirect
+	github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
+	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
+	github.com/modern-go/reflect2 v1.0.2 // indirect
 	github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
+	github.com/olekukonko/tablewriter v0.0.5 // indirect
 	github.com/olivere/elastic v6.2.37+incompatible // indirect
+	github.com/openzipkin/zipkin-go v0.4.0 // indirect
+	github.com/pelletier/go-toml/v2 v2.0.6 // indirect
 	github.com/pkg/errors v0.9.1 // indirect
+	github.com/prometheus/client_golang v1.13.0 // indirect
+	github.com/prometheus/client_model v0.2.0 // indirect
+	github.com/prometheus/common v0.37.0 // indirect
+	github.com/prometheus/procfs v0.8.0 // indirect
+	github.com/rivo/uniseg v0.2.0 // indirect
+	github.com/spaolacci/murmur3 v1.1.0 // indirect
 	github.com/xdg-go/pbkdf2 v1.0.0 // indirect
 	github.com/xdg-go/scram v1.1.1 // indirect
 	github.com/xdg-go/stringprep v1.0.3 // indirect
 	github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
+	github.com/zeromicro/go-zero v1.4.4 // indirect
+	go.etcd.io/etcd/api/v3 v3.5.5 // indirect
+	go.etcd.io/etcd/client/pkg/v3 v3.5.5 // indirect
+	go.etcd.io/etcd/client/v3 v3.5.5 // indirect
+	go.opentelemetry.io/otel v1.11.0 // indirect
+	go.opentelemetry.io/otel/exporters/jaeger v1.11.0 // indirect
+	go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0 // indirect
+	go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0 // indirect
+	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0 // indirect
+	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 // indirect
+	go.opentelemetry.io/otel/exporters/zipkin v1.11.0 // indirect
+	go.opentelemetry.io/otel/sdk v1.11.0 // indirect
+	go.opentelemetry.io/otel/trace v1.11.0 // indirect
+	go.opentelemetry.io/proto/otlp v0.19.0 // indirect
+	go.uber.org/atomic v1.9.0 // indirect
+	go.uber.org/automaxprocs v1.5.1 // indirect
+	go.uber.org/multierr v1.8.0 // indirect
+	go.uber.org/zap v1.21.0 // indirect
 	golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
-	golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
-	golang.org/x/text v0.3.7 // indirect
+	golang.org/x/net v0.0.0-20221014081412-f15817d10f9b // indirect
+	golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 // indirect
+	golang.org/x/sync v0.1.0 // indirect
+	golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 // indirect
+	golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
+	golang.org/x/text v0.4.0 // indirect
+	golang.org/x/time v0.3.0 // indirect
+	google.golang.org/appengine v1.6.7 // indirect
+	google.golang.org/genproto v0.0.0-20221111202108-142d8a6fa32e // indirect
+	google.golang.org/grpc v1.51.0 // indirect
+	google.golang.org/protobuf v1.28.1 // indirect
 	gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
+	gopkg.in/inf.v0 v0.9.1 // indirect
+	gopkg.in/yaml.v2 v2.4.0 // indirect
+	gopkg.in/yaml.v3 v3.0.1 // indirect
 	gorm.io/driver/mysql v1.0.5 // indirect
 	gorm.io/gorm v1.21.3 // indirect
+	k8s.io/api v0.22.9 // indirect
+	k8s.io/apimachinery v0.22.9 // indirect
+	k8s.io/client-go v0.22.9 // indirect
+	k8s.io/klog/v2 v2.80.1 // indirect
+	k8s.io/utils v0.0.0-20221108210102-8e77b1f39fe2 // indirect
+	sigs.k8s.io/structured-merge-diff/v4 v4.2.1 // indirect
+	sigs.k8s.io/yaml v1.2.0 // indirect
 )

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 658 - 5
src/jfw/modules/bidfileinter/src/go.sum


+ 1 - 1
src/jfw/modules/bidfileinter/src/service/action/exchange.go

@@ -45,7 +45,7 @@ func (e *Exchange) Bidcount() {
 		name := fmt.Sprintf("兑换%d次", count)
 		if util.Consume(userid, name, "", 2006, needIntegral) {
 			//增加次数
-			if MQFW.UpdateById("user", userid, map[string]interface{}{
+			if jyutil.Compatible.Update( userid, map[string]interface{}{
 				"$inc": map[string]interface{}{
 					"i_bidfileCount": count,
 				},

+ 148 - 148
src/jfw/modules/bidfileinter/src/service/action/info.go

@@ -1,187 +1,187 @@
 package action
 
 import (
-	. "jy/src/jfw/modules/bidfileinter/src/service/config"
-	"jy/src/jfw/modules/bidfileinter/src/util"
+    . "jy/src/jfw/modules/bidfileinter/src/service/config"
+    "jy/src/jfw/modules/bidfileinter/src/util"
 
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/api"
+    qutil "app.yhyue.com/moapp/jybase/common"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Info struct {
-	*xweb.Action
-	list      xweb.Mapper `xweb:"/info/list"`      //列表页
-	deleteOne xweb.Mapper `xweb:"/info/deleteOne"` //删除某条招标文件解读
-	detail    xweb.Mapper `xweb:"/info/detail"`    //招标文件解读详情页
-	power     xweb.Mapper `xweb:"/info/power"`     //是否有权限
-	belong    xweb.Mapper `xweb:"/info/belong"`    //将未登录状态上传文件归属个人
+    *xweb.Action
+    list      xweb.Mapper `xweb:"/info/list"`      //列表页
+    deleteOne xweb.Mapper `xweb:"/info/deleteOne"` //删除某条招标文件解读
+    detail    xweb.Mapper `xweb:"/info/detail"`    //招标文件解读详情页
+    power     xweb.Mapper `xweb:"/info/power"`     //是否有权限
+    belong    xweb.Mapper `xweb:"/info/belong"`    //将未登录状态上传文件归属个人
 }
 
 func init() {
-	xweb.AddAction(&Info{})
+    xweb.AddAction(&Info{})
 }
 
 var (
-	pagesize_max = 10
-	table        = "bidfile_history"
+    pagesize_max = 10
+    table        = "bidfile_history"
 )
 
 func (i *Info) List() {
-	if !R.CheckReqParam(i.ResponseWriter, i.Request, "pageNum") {
-		return
-	}
-	//总数
-	data := map[string]interface{}{}
-	pageNum := qutil.IntAll(i.GetString("pageNum"))
-	pageNum = qutil.If(pageNum == 0, 1, pageNum).(int)
-	userid, _ := i.GetSession("userId").(string)
-	if userid == "" {
-		data["res"] = []map[string]interface{}{}
-		data["count"] = 0
-		data["haveNextPage"] = false
-		i.ServeJson(Result{Data: data})
-	}
-	//res := *Mysql.Find(table, query, "id,project_name,project_md5,explain_time,explain_status,upload_url,buyer,upload_filename", "create_time desc", -1, 0)
-	sql := `
+    if !R.CheckReqParam(i.ResponseWriter, i.Request, "pageNum") {
+        return
+    }
+    //总数
+    data := map[string]interface{}{}
+    pageNum := qutil.IntAll(i.GetString("pageNum"))
+    pageNum = qutil.If(pageNum == 0, 1, pageNum).(int)
+    userid, _ := i.GetSession("userId").(string)
+    if userid == "" {
+        data["res"] = []map[string]interface{}{}
+        data["count"] = 0
+        data["haveNextPage"] = false
+        i.ServeJson(Result{Data: data})
+    }
+    //res := *Mysql.Find(table, query, "id,project_name,project_md5,explain_time,explain_status,upload_url,buyer,upload_filename", "create_time desc", -1, 0)
+    sql := `
 	select id,project_name projectName,project_md5 projectMd5,
 	explain_time explainTime,explain_status explainStatus,
 	upload_url uploadUrl,buyer,upload_filename uploadFilename,user_id
 	from bidfile_history where (user_id =? or main_id =?)and is_delete=? order by create_time desc`
 
-	res := *Mysql.SelectBySql(sql, userid, userid, 0)
-	removal_res := []map[string]interface{}{}
-	projectM := map[string]map[string]interface{}{}
-	for _, v := range res {
-		projectMd5 := qutil.ObjToString(v["projectMd5"])
-		explainStatus := v["explainStatus"]
-		if projectM[projectMd5] != nil {
-			explain_status := qutil.IntAll(projectM[projectMd5]["explainStatus"])
-			index := qutil.IntAll(projectM[projectMd5]["index"])
-			//之前数据已经解读过
-			if explain_status == 1 {
-				continue
-			}
-			//之前数据未解读过、本次解读过
-			if qutil.IntAll(explainStatus) > 0 {
-				removal_res[index] = v
-				continue
-			}
-			//均没解读过
-			myself, _ := projectM[projectMd5]["myself"].(bool)
-			if myself {
-				continue
-			} else {
-				removal_res[index] = v
-				projectM[projectMd5]["myself"] = true
-				continue
-			}
-		}
-		projectM[projectMd5] = map[string]interface{}{
-			"explainStatus": explainStatus,                                                    //是否解读过
-			"index":         len(removal_res),                                                 //该条记录的索引
-			"myself":        qutil.If(qutil.ObjToString(v["user_id"]) == userid, true, false), //是否是自己解读的
-		}
-		removal_res = append(removal_res, v)
-	}
-	//
-	result := []map[string]interface{}{}
-	if len(removal_res) > 0 {
-		start := (pageNum - 1) * pagesize_max
-		end := pageNum * pagesize_max
-		if end > len(removal_res) {
-			end = len(removal_res)
-		}
-		if start < len(removal_res) {
-			result = removal_res[start:end]
-		}
-	}
-	count := len(removal_res)
-	haveNextPage := len(result) >= pagesize_max
-	data["res"] = result
-	data["count"] = count
-	data["haveNextPage"] = haveNextPage
-	i.ServeJson(Result{Data: data})
+    res := *Mysql.SelectBySql(sql, userid, userid, 0)
+    removal_res := []map[string]interface{}{}
+    projectM := map[string]map[string]interface{}{}
+    for _, v := range res {
+        projectMd5 := qutil.ObjToString(v["projectMd5"])
+        explainStatus := v["explainStatus"]
+        if projectM[projectMd5] != nil {
+            explain_status := qutil.IntAll(projectM[projectMd5]["explainStatus"])
+            index := qutil.IntAll(projectM[projectMd5]["index"])
+            //之前数据已经解读过
+            if explain_status == 1 {
+                continue
+            }
+            //之前数据未解读过、本次解读过
+            if qutil.IntAll(explainStatus) > 0 {
+                removal_res[index] = v
+                continue
+            }
+            //均没解读过
+            myself, _ := projectM[projectMd5]["myself"].(bool)
+            if myself {
+                continue
+            } else {
+                removal_res[index] = v
+                projectM[projectMd5]["myself"] = true
+                continue
+            }
+        }
+        projectM[projectMd5] = map[string]interface{}{
+            "explainStatus": explainStatus,                                                    //是否解读过
+            "index":         len(removal_res),                                                 //该条记录的索引
+            "myself":        qutil.If(qutil.ObjToString(v["user_id"]) == userid, true, false), //是否是自己解读的
+        }
+        removal_res = append(removal_res, v)
+    }
+    //
+    result := []map[string]interface{}{}
+    if len(removal_res) > 0 {
+        start := (pageNum - 1) * pagesize_max
+        end := pageNum * pagesize_max
+        if end > len(removal_res) {
+            end = len(removal_res)
+        }
+        if start < len(removal_res) {
+            result = removal_res[start:end]
+        }
+    }
+    count := len(removal_res)
+    haveNextPage := len(result) >= pagesize_max
+    data["res"] = result
+    data["count"] = count
+    data["haveNextPage"] = haveNextPage
+    i.ServeJson(Result{Data: data})
 }
 
 func (i *Info) DeleteOne() {
-	if !R.CheckReqParam(i.ResponseWriter, i.Request, "id") {
-		return
-	}
-	id, _ := i.GetInteger("id")
-	userid, _ := i.GetSession("userId").(string)
-	mainid, _ := util.MainId(userid)
-	bl := true
-	if mainid == userid {
-		sql := `UPDATE bidfile_history SET is_delete=?
+    if !R.CheckReqParam(i.ResponseWriter, i.Request, "id") {
+        return
+    }
+    id, _ := i.GetInteger("id")
+    userid, _ := i.GetSession("userId").(string)
+    mainid, _ := util.MainId(userid)
+    bl := true
+    if mainid == userid {
+        sql := `UPDATE bidfile_history SET is_delete=?
 			where id =? and (main_id=? or user_id =?)`
-		bl = Mysql.UpdateOrDeleteBySql(sql, 1, id, userid, userid) > -1
-	} else {
-		sql := `UPDATE bidfile_history SET is_delete=?
+        bl = Mysql.UpdateOrDeleteBySql(sql, 1, id, userid, userid) > -1
+    } else {
+        sql := `UPDATE bidfile_history SET is_delete=?
 			where id =? and user_id =?`
-		bl = Mysql.UpdateOrDeleteBySql(sql, 1, id, userid) > 0
-	}
-	i.ServeJson(Result{Data: M{"status": bl}})
+        bl = Mysql.UpdateOrDeleteBySql(sql, 1, id, userid) > 0
+    }
+    i.ServeJson(Result{Data: M{"status": bl}})
 }
 
 func (i *Info) Detail() {
-	if !R.CheckReqParam(i.ResponseWriter, i.Request, "md5") {
-		return
-	}
-	md5Str := i.GetString("md5")
-	r := func() Result {
-		userid := qutil.ObjToString(i.GetSession("userId"))
-		data, ok := MQFW.FindOne("bidfile_project", map[string]interface{}{
-			"project_md5": md5Str,
-			"status":      2,
-		})
-		countbl := Mysql.CountBySql(`select count(1) from bidfile_history 
+    if !R.CheckReqParam(i.ResponseWriter, i.Request, "md5") {
+        return
+    }
+    md5Str := i.GetString("md5")
+    r := func() Result {
+        userid := qutil.ObjToString(i.GetSession("userId"))
+        data, ok := MQFW.FindOne("bidfile_project", map[string]interface{}{
+            "project_md5": md5Str,
+            "status":      2,
+        })
+        countbl := Mysql.CountBySql(`select count(1) from bidfile_history
 		where ( user_id = ? or main_id = ? ) and project_md5 =? and explain_status =1 and is_delete=0`, userid, userid, md5Str) > 0
-		if ok && (*data) != nil && len(*data) > 0 && countbl {
-			return Result{Data: (*data)["analysis_info"]}
-		}
-		return Result{Data: nil, Error_msg: "未找到文件"}
-	}()
-	i.ServeJson(r)
+        if ok && (*data) != nil && len(*data) > 0 && countbl {
+            return Result{Data: (*data)["analysis_info"]}
+        }
+        return Result{Data: nil, Error_msg: "未找到文件"}
+    }()
+    i.ServeJson(r)
 }
 
 func (i *Info) Power() {
-	r := func() Result {
-		count := 0
-		userid, _ := i.GetSession("userId").(string)
-		mainid, _ := util.MainId(userid)
-		count = util.BigmemberBidfileCount(mainid)
-		data, ok := MQFW.FindById("user", userid, `{"i_bidfileCount":1}`)
-		if ok && (*data) != nil && len(*data) > 0 {
-			bidfile_count := qutil.If((*data)["i_bidfileCount"] == nil, 0, (*data)["i_bidfileCount"])
-			count += qutil.IntAll(bidfile_count)
-		}
-		points := util.Integral(userid)
-		return Result{Data: M{"bidfile_count": count, "integral": points}}
-	}()
-	i.ServeJson(r)
+    r := func() Result {
+        count := 0
+        userid, _ := i.GetSession("userId").(string)
+        mainid, _ := util.MainId(userid)
+        count = util.BigmemberBidfileCount(mainid)
+        data := Compatible.Select(userid, `{"i_bidfileCount":1}`)
+        if (*data) != nil && len(*data) > 0 {
+            bidfile_count := qutil.If((*data)["i_bidfileCount"] == nil, 0, (*data)["i_bidfileCount"])
+            count += qutil.IntAll(bidfile_count)
+        }
+        points := util.Integral(userid)
+        return Result{Data: M{"bidfile_count": count, "integral": points}}
+    }()
+    i.ServeJson(r)
 }
 
 func (i *Info) Belong() {
-	if !R.CheckReqParam(i.ResponseWriter, i.Request, "id") {
-		return
-	}
-	id, _ := i.GetInteger("id")
-	r := func() Result {
-		userid, _ := i.GetSession("userId").(string)
-		//该用户已经上传过该文件
-		if Mysql.CountBySql(`select count(1) from bidfile_history 
-		where user_id =? and is_delete =0 
+    if !R.CheckReqParam(i.ResponseWriter, i.Request, "id") {
+        return
+    }
+    id, _ := i.GetInteger("id")
+    r := func() Result {
+        userid, _ := i.GetSession("userId").(string)
+        //该用户已经上传过该文件
+        if Mysql.CountBySql(`select count(1) from bidfile_history
+		where user_id =? and is_delete =0
 		and project_md5 =(select project_md5 from bidfile_history where id =?)`, userid, id) > 0 {
-			return Result{Data: M{"status": true}, Error_msg: ""}
-		}
-		bl := Mysql.Update(table, map[string]interface{}{
-			"id": id,
-		}, map[string]interface{}{
-			"user_id": userid,
-		})
-		return Result{Data: M{"status": bl}, Error_msg: ""}
-	}()
-	i.ServeJson(r)
+            return Result{Data: M{"status": true}, Error_msg: ""}
+        }
+        bl := Mysql.Update(table, map[string]interface{}{
+            "id": id,
+        }, map[string]interface{}{
+            "user_id": userid,
+        })
+        return Result{Data: M{"status": bl}, Error_msg: ""}
+    }()
+    i.ServeJson(r)
 }

+ 145 - 119
src/jfw/modules/bidfileinter/src/service/config/config.go

@@ -1,145 +1,171 @@
 package config
 
 import (
-	"log"
+    "app.yhyue.com/moapp/jypkg/compatible"
+    "log"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"app.yhyue.com/moapp/jybase/mail"
-	mg "app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jybase/mysql"
-	"app.yhyue.com/moapp/jybase/redis"
+    util "app.yhyue.com/moapp/jybase/common"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
+    "app.yhyue.com/moapp/jybase/mail"
+    mg "app.yhyue.com/moapp/jybase/mongodb"
+    "app.yhyue.com/moapp/jybase/mysql"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/middleground"
+    "github.com/gogf/gf/v2/frame/g"
+    "github.com/gogf/gf/v2/os/gcfg"
+    "github.com/gogf/gf/v2/os/gctx"
 )
 
 type config struct {
-	Webport   string
-	Webdomain string
-	Mail      *[]mailConf
-	Mongodb   struct {
-		Main *mgoConf
-		Log  *mgoConf
-	}
-	Elasticsearch struct {
-		Main *esConf
-	}
-	Redis struct {
-		Main  *redisConf
-		Login *redisConf
-	}
-	Mysql struct {
-		Main *mysqlConf
-		Push *mysqlConf
-	}
-	UploadPath        string
-	Untoken           string //盈标秘书接口-密钥
-	TaskIsRun         bool
-	DownloadZbZipTask string
-	AlarmMail         []string
-	FileMaxSize       int
-	CheckFailTask     string
-	FailTime          int
-	IntegralUrl       map[string]interface{}
-	Appids            map[string]interface{}
-	PointCount        int
+    Webport   string
+    Webdomain string
+    Mail      *[]mailConf
+    Mongodb   struct {
+        Main *mgoConf
+        Log  *mgoConf
+    }
+    Elasticsearch struct {
+        Main *esConf
+    }
+    Redis struct {
+        Main  *redisConf
+        Login *redisConf
+    }
+    Mysql struct {
+        Main *mysqlConf
+        Push *mysqlConf
+        Base *mysqlConf
+    }
+    UploadPath        string
+    Untoken           string //盈标秘书接口-密钥
+    TaskIsRun         bool
+    DownloadZbZipTask string
+    AlarmMail         []string
+    FileMaxSize       int
+    CheckFailTask     string
+    FailTime          int
+    IntegralUrl       map[string]interface{}
+    Appids            map[string]interface{}
+    PointCount        int
 }
 
 type mgoConf struct {
-	Address         string
-	Size            int
-	DbName          string
-	UserName        string
-	Password        string
-	Collection      string
-	Collection_back string
+    Address         string
+    Size            int
+    DbName          string
+    UserName        string
+    Password        string
+    Collection      string
+    Collection_back string
 }
 
 type esConf struct {
-	Address string
-	Size    int
+    Address string
+    Size    int
 }
 type redisConf struct {
-	Address string
+    Address string
 }
 type mysqlConf struct {
-	DbName       string
-	Address      string
-	UserName     string
-	PassWord     string
-	MaxOpenConns int
-	MaxIdleConns int
+    DbName       string
+    Address      string
+    UserName     string
+    PassWord     string
+    MaxOpenConns int
+    MaxIdleConns int
 }
 type mailConf struct {
-	Addr string
-	Port int
-	Pwd  string
-	User string
+    Addr string
+    Port int
+    Pwd  string
+    User string
 }
 
 var (
-	Sysconfig *config
-	Mysql     *mysql.Mysql
-	MQFW      mg.MongodbSim
-	Mgo_Log   mg.MongodbSim
-	Mgo_Bid   mg.MongodbSim
-	GmailAuth []*mail.GmailAuth
+    Sysconfig    *config
+    Mysql        *mysql.Mysql
+    Base         *mysql.Mysql
+    MQFW         mg.MongodbSim
+    Mgo_Log      mg.MongodbSim
+    Mgo_Bid      mg.MongodbSim
+    GmailAuth    []*mail.GmailAuth
+    Middleground *middleground.Middleground
+    Compatible   *compatible.Compatible
 )
 
 func init() {
-	util.ReadConfig(&Sysconfig)
-	if Sysconfig != nil {
-		//初始化redis
-		if Sysconfig.Redis.Main != nil {
-			log.Println("初始化 redis")
-			redis.InitRedisBySize(Sysconfig.Redis.Main.Address, 100, 30, 300)
-		}
-		//
-		if Sysconfig.Mongodb.Main != nil {
-			log.Println("初始化 mongodb main")
-			MQFW = mg.MongodbSim{
-				MongodbAddr: Sysconfig.Mongodb.Main.Address,
-				Size:        Sysconfig.Mongodb.Main.Size,
-				DbName:      Sysconfig.Mongodb.Main.DbName,
-			}
-			MQFW.InitPool()
-		}
-		if Sysconfig.Mongodb.Log != nil {
-			log.Println("初始化 mongodb log")
-			Mgo_Log = mg.MongodbSim{
-				MongodbAddr: Sysconfig.Mongodb.Log.Address,
-				Size:        Sysconfig.Mongodb.Log.Size,
-				DbName:      Sysconfig.Mongodb.Log.DbName,
-				UserName:    Sysconfig.Mongodb.Log.UserName,
-				Password:    Sysconfig.Mongodb.Log.Password,
-			}
-			Mgo_Log.InitPool()
-		}
-		if Sysconfig.Mysql.Main != nil {
-			log.Println("初始化 mysql")
-			Mysql = &mysql.Mysql{
-				Address:      Sysconfig.Mysql.Main.Address,
-				UserName:     Sysconfig.Mysql.Main.UserName,
-				PassWord:     Sysconfig.Mysql.Main.PassWord,
-				DBName:       Sysconfig.Mysql.Main.DbName,
-				MaxOpenConns: Sysconfig.Mysql.Main.MaxOpenConns,
-				MaxIdleConns: Sysconfig.Mysql.Main.MaxIdleConns,
-			}
-			Mysql.Init()
-		}
-		elastic.InitElasticSize(Sysconfig.Elasticsearch.Main.Address, Sysconfig.Elasticsearch.Main.Size)
-		log.Println("初始化 Elasticsearch")
-		//
-		if Sysconfig.Mail != nil {
-			log.Println("初始化 Mail")
-			mailConfigArrMap := Sysconfig.Mail
-			for _, v := range *mailConfigArrMap {
-				mail := &mail.GmailAuth{
-					SmtpHost: v.Addr,
-					SmtpPort: v.Port,
-					User:     v.User,
-					Pwd:      v.Pwd,
-				}
-				GmailAuth = append(GmailAuth, mail)
-			}
-		}
-	}
+    util.ReadConfig(&Sysconfig)
+    if Sysconfig != nil {
+        //初始化redis
+        if Sysconfig.Redis.Main != nil {
+            log.Println("初始化 redis")
+            redis.InitRedisBySize(Sysconfig.Redis.Main.Address, 100, 30, 300)
+        }
+        //
+        if Sysconfig.Mongodb.Main != nil {
+            log.Println("初始化 mongodb main")
+            MQFW = mg.MongodbSim{
+                MongodbAddr: Sysconfig.Mongodb.Main.Address,
+                Size:        Sysconfig.Mongodb.Main.Size,
+                DbName:      Sysconfig.Mongodb.Main.DbName,
+            }
+            MQFW.InitPool()
+        }
+        if Sysconfig.Mongodb.Log != nil {
+            log.Println("初始化 mongodb log")
+            Mgo_Log = mg.MongodbSim{
+                MongodbAddr: Sysconfig.Mongodb.Log.Address,
+                Size:        Sysconfig.Mongodb.Log.Size,
+                DbName:      Sysconfig.Mongodb.Log.DbName,
+                UserName:    Sysconfig.Mongodb.Log.UserName,
+                Password:    Sysconfig.Mongodb.Log.Password,
+            }
+            Mgo_Log.InitPool()
+        }
+        if Sysconfig.Mysql.Base != nil {
+            log.Println("初始化 mysql")
+            Base = &mysql.Mysql{
+                Address:      Sysconfig.Mysql.Base.Address,
+                UserName:     Sysconfig.Mysql.Base.UserName,
+                PassWord:     Sysconfig.Mysql.Base.PassWord,
+                DBName:       Sysconfig.Mysql.Base.DbName,
+                MaxOpenConns: Sysconfig.Mysql.Base.MaxOpenConns,
+                MaxIdleConns: Sysconfig.Mysql.Base.MaxIdleConns,
+            }
+            Base.Init()
+        }
+        if Sysconfig.Ba.Main != nil {
+            log.Println("初始化 mysql")
+            Mysql = &mysql.Mysql{
+                Address:      Sysconfig.Mysql.Main.Address,
+                UserName:     Sysconfig.Mysql.Main.UserName,
+                PassWord:     Sysconfig.Mysql.Main.PassWord,
+                DBName:       Sysconfig.Mysql.Main.DbName,
+                MaxOpenConns: Sysconfig.Mysql.Main.MaxOpenConns,
+                MaxIdleConns: Sysconfig.Mysql.Main.MaxIdleConns,
+            }
+            Mysql.Init()
+        }
+        elastic.InitElasticSize(Sysconfig.Elasticsearch.Main.Address, Sysconfig.Elasticsearch.Main.Size)
+        log.Println("初始化 Elasticsearch")
+        //
+        if Sysconfig.Mail != nil {
+            log.Println("初始化 Mail")
+            mailConfigArrMap := Sysconfig.Mail
+            for _, v := range *mailConfigArrMap {
+                mail := &mail.GmailAuth{
+                    SmtpHost: v.Addr,
+                    SmtpPort: v.Port,
+                    User:     v.User,
+                    Pwd:      v.Pwd,
+                }
+                GmailAuth = append(GmailAuth, mail)
+            }
+        }
+    }
+    g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetFileName("config.yaml")
+    var ctx = gctx.New()
+    Middleground = middleground.NewMiddleground(g.Cfg().MustGet(ctx, "etcd.hosts").Strings()).RegPowerCheckCenter(g.Cfg().MustGet(ctx, "powerCheckCenterKey").String()).RegResourceCenter(g.Cfg().MustGet(ctx, "resourceCenterKey").String())
+    Compatible = compatible.NewCompatible(&MQFW, Base, Mysql, Middleground)
+
 }

+ 430 - 430
src/jfw/modules/bidfileinter/src/util/util.go

@@ -1,130 +1,130 @@
 package util
 
 import (
-	"archive/zip"
-	"encoding/json"
-	"fmt"
-	"io"
-	"io/ioutil"
-	"jy/src/jfw/modules/bidfileinter/src/service/config"
-	"log"
-	"net/http"
-	"net/url"
-	"os"
-	"path/filepath"
-	"strconv"
-	"strings"
-	"time"
+    "archive/zip"
+    "encoding/json"
+    "fmt"
+    "io"
+    "io/ioutil"
+    "jy/src/jfw/modules/bidfileinter/src/service/config"
+    "log"
+    "net/http"
+    "net/url"
+    "os"
+    "path/filepath"
+    "strconv"
+    "strings"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
 
-	"go.mongodb.org/mongo-driver/bson/primitive"
+    "go.mongodb.org/mongo-driver/bson/primitive"
 
-	"github.com/tealeg/xlsx"
+    "github.com/tealeg/xlsx"
 )
 
 //解压
 // zipFile--文件地址 dest_path--解压位置
 func DeCompress_zip(zipFile, dest_path string) (arr []string) {
-	reader, err := zip.OpenReader(zipFile)
-	if err != nil {
-		return arr
-	}
-	defer reader.Close()
-	DeCompress_to_dest := func(f *zip.File) error {
-		rc, err := f.Open()
-		if err != nil {
-			log.Println("err", err)
-			return err
-		}
-		defer rc.Close()
-		filename := dest_path + f.Name
-		if !strings.HasSuffix(filename, "/") {
-			arr = append(arr, filename)
-		}
-		if err = os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
-			return err
-		}
-		w, _ := os.Create(filename)
-		defer w.Close()
-		_, err = io.Copy(w, rc)
-		return err
-	}
-	for _, file := range reader.File {
-		err := DeCompress_to_dest(file)
-		if err != nil {
-			return arr
-		}
-	}
-	return arr
+    reader, err := zip.OpenReader(zipFile)
+    if err != nil {
+        return arr
+    }
+    defer reader.Close()
+    DeCompress_to_dest := func(f *zip.File) error {
+        rc, err := f.Open()
+        if err != nil {
+            log.Println("err", err)
+            return err
+        }
+        defer rc.Close()
+        filename := dest_path + f.Name
+        if !strings.HasSuffix(filename, "/") {
+            arr = append(arr, filename)
+        }
+        if err = os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
+            return err
+        }
+        w, _ := os.Create(filename)
+        defer w.Close()
+        _, err = io.Copy(w, rc)
+        return err
+    }
+    for _, file := range reader.File {
+        err := DeCompress_to_dest(file)
+        if err != nil {
+            return arr
+        }
+    }
+    return arr
 }
 
 func getDir(path string) string {
-	return subString(path, 0, strings.LastIndex(path, "/"))
+    return subString(path, 0, strings.LastIndex(path, "/"))
 }
 
 func subString(str string, start, end int) string {
-	rs := []rune(str)
-	length := len(rs)
+    rs := []rune(str)
+    length := len(rs)
 
-	if start < 0 || start > length {
-		panic("start is wrong")
-	}
+    if start < 0 || start > length {
+        panic("start is wrong")
+    }
 
-	if end < start || end > length {
-		panic("end is wrong")
-	}
+    if end < start || end > length {
+        panic("end is wrong")
+    }
 
-	return string(rs[start:end])
+    return string(rs[start:end])
 }
 
 // xlsx文件解析获取excel中相关数据
 //filePath--文件地址
 func ExcelParse(filePath string) map[string]interface{} {
-	//filePath = `D:\work\project\test\files\6522831606973535034.xlsx`
-	xlFile, err := xlsx.OpenFile(filePath)
-	if err != nil {
-		log.Println("解析excel 报错", err)
-		return map[string]interface{}{}
-	}
-	projectname, buyer, agency, bidopentime := "", "", "", ""
-	// 遍历sheet页读取
-	for _, sheet := range xlFile.Sheets {
-		/*遍历行读取
-		第一行第二列:项目名称 projectname
-		第二行第二列:采购单位 buyer
-		第三行第二列:代理机构 agency
-		第七行第二列:开标时间 bidopentime
-		*/
-		for i := 0; i < len(sheet.Rows); i++ {
-			row := sheet.Rows[i]
-			for j := 0; j < len(row.Cells); j++ {
-				if i == 0 && j == 1 {
-					projectname = row.Cells[j].String()
-				}
-				if i == 1 && j == 1 {
-					buyer = row.Cells[j].String()
-				}
-				if i == 2 && j == 1 {
-					agency = row.Cells[j].String()
-				}
-				if i == 6 && j == 1 {
-					bidopentime = row.Cells[j].String()
-				}
-			}
-		}
-		if sheet.Name == "项目基本信息" {
-			break
-		}
-	}
-	return map[string]interface{}{
-		"projectname": projectname,
-		"buyer":       buyer,
-		"agency":      agency,
-		"bidopentime": bidopentime,
-	}
+    //filePath = `D:\work\project\test\files\6522831606973535034.xlsx`
+    xlFile, err := xlsx.OpenFile(filePath)
+    if err != nil {
+        log.Println("解析excel 报错", err)
+        return map[string]interface{}{}
+    }
+    projectname, buyer, agency, bidopentime := "", "", "", ""
+    // 遍历sheet页读取
+    for _, sheet := range xlFile.Sheets {
+        /*遍历行读取
+          第一行第二列:项目名称 projectname
+          第二行第二列:采购单位 buyer
+          第三行第二列:代理机构 agency
+          第七行第二列:开标时间 bidopentime
+        */
+        for i := 0; i < len(sheet.Rows); i++ {
+            row := sheet.Rows[i]
+            for j := 0; j < len(row.Cells); j++ {
+                if i == 0 && j == 1 {
+                    projectname = row.Cells[j].String()
+                }
+                if i == 1 && j == 1 {
+                    buyer = row.Cells[j].String()
+                }
+                if i == 2 && j == 1 {
+                    agency = row.Cells[j].String()
+                }
+                if i == 6 && j == 1 {
+                    bidopentime = row.Cells[j].String()
+                }
+            }
+        }
+        if sheet.Name == "项目基本信息" {
+            break
+        }
+    }
+    return map[string]interface{}{
+        "projectname": projectname,
+        "buyer":       buyer,
+        "agency":      agency,
+        "bidopentime": bidopentime,
+    }
 }
 
 /*
@@ -147,373 +147,373 @@ func ExcelParse(filePath string) map[string]interface{} {
 当结果有多个时,以开标时间相等、项目名称长度最相近为准
 */
 func GetInfoFromBidding(m map[string]interface{}) map[string]interface{} {
-	projectname := qutil.ObjToString(m["projectname"])
-	if projectname == "" {
-		return nil
-	}
-	buyer_n := qutil.ObjToString(m["buyer"])
-	bidopentime_n := qutil.ObjToString(m["bidopentime"])
-	agency_n := qutil.ObjToString(m["agency"])
-	if buyer_n == "" && agency_n == "" {
-		return nil
-	}
-	pronameLen := len([]rune(projectname))
-	//对比相关项目
-	sql := ""
-	var before int64
-	var after int64
-	switch {
-	case pronameLen <= 6: //项目名称包含关系 至少一个相等【采购单位、代理机构】 开标时间相等,精确到天。
-		before, after = getOpenTime(1, bidopentime_n)
-	case pronameLen > 6 && pronameLen <= 14: //项目名称包含关系 至少一个相等【采购单位、代理机构】 开标时间相等或(开标时间-15天<=招标时间<开标时间),精确到天
-		before, after = getOpenTime(1, bidopentime_n)
-	case pronameLen > 14: //项目名称包含关系 至少一个相等【采购单位、代理机构、开标时间】 开标时间-30天<=招标时间<开标时间
-		before, after = getOpenTime(1, bidopentime_n)
-	}
-	if before > 0 && after > 0 {
-		sql = getEsSql(projectname, buyer_n, agency_n, before, after)
-		data := elastic.Get("projectset", "projectset", sql)
-		if data != nil && len(*data) > 0 {
-			dataOne := (*data)[0]
-			area := qutil.If(dataOne["area"] != nil, dataOne["area"], nil)
-			city := qutil.If(dataOne["city"] != nil, dataOne["city"], nil)
-			if area != nil || city != nil {
-				dataOne["area"] = qutil.ObjToString(area) + qutil.ObjToString(city)
-			}
-			if qutil.Int64All(dataOne["zbtime"]) == 0 {
-				delete(dataOne, "zbtime")
-			}
-			return dataOne
-		}
-	}
-	return nil
+    projectname := qutil.ObjToString(m["projectname"])
+    if projectname == "" {
+        return nil
+    }
+    buyer_n := qutil.ObjToString(m["buyer"])
+    bidopentime_n := qutil.ObjToString(m["bidopentime"])
+    agency_n := qutil.ObjToString(m["agency"])
+    if buyer_n == "" && agency_n == "" {
+        return nil
+    }
+    pronameLen := len([]rune(projectname))
+    //对比相关项目
+    sql := ""
+    var before int64
+    var after int64
+    switch {
+    case pronameLen <= 6: //项目名称包含关系 至少一个相等【采购单位、代理机构】 开标时间相等,精确到天。
+        before, after = getOpenTime(1, bidopentime_n)
+    case pronameLen > 6 && pronameLen <= 14: //项目名称包含关系 至少一个相等【采购单位、代理机构】 开标时间相等或(开标时间-15天<=招标时间<开标时间),精确到天
+        before, after = getOpenTime(1, bidopentime_n)
+    case pronameLen > 14: //项目名称包含关系 至少一个相等【采购单位、代理机构、开标时间】 开标时间-30天<=招标时间<开标时间
+        before, after = getOpenTime(1, bidopentime_n)
+    }
+    if before > 0 && after > 0 {
+        sql = getEsSql(projectname, buyer_n, agency_n, before, after)
+        data := elastic.Get("projectset", "projectset", sql)
+        if data != nil && len(*data) > 0 {
+            dataOne := (*data)[0]
+            area := qutil.If(dataOne["area"] != nil, dataOne["area"], nil)
+            city := qutil.If(dataOne["city"] != nil, dataOne["city"], nil)
+            if area != nil || city != nil {
+                dataOne["area"] = qutil.ObjToString(area) + qutil.ObjToString(city)
+            }
+            if qutil.Int64All(dataOne["zbtime"]) == 0 {
+                delete(dataOne, "zbtime")
+            }
+            return dataOne
+        }
+    }
+    return nil
 }
 
 //
 func getEsSql(projectname, buyer, agency string, openBefer, openAfter int64) string {
-	query := `{"query": {"filtered": {"filter": {"bool": {"should": [%s]}},"query": {"bool": {"should": [{"bool": {"must": [{"multi_match": {"query": "%s","type": "phrase","fields": ["projectname.pname"]}}]}}],"minimum_should_match": 1}}}},"sort": [{"firsttime": "desc"}], "_source": ["agency","buyer","bidopentime","bidendtime","area","city","zbtime","projectname"],"from": 0,"size": 10}`
-	where := ""
-	if openBefer > 0 && openAfter > 0 {
-		where += ` {"range": {"bidopentime": {"gte":%d ,"lt": %d}}}`
-		where = fmt.Sprintf(where, openBefer, openAfter)
-	}
-	if buyer != "" {
-		if where != "" {
-			where += ","
-		}
-		where += ` {"term": {"buyer": "%s" }}`
-		where = fmt.Sprintf(where, buyer)
-	}
-	if agency != "" {
-		if where != "" {
-			where += ","
-		}
-		where += ` {"term": {"agency": "%s"}}`
-		where = fmt.Sprintf(where, agency)
-	}
-	sql := fmt.Sprintf(query, where, projectname)
-	log.Println("---sql:", sql)
-	return sql
+    query := `{"query": {"filtered": {"filter": {"bool": {"should": [%s]}},"query": {"bool": {"should": [{"bool": {"must": [{"multi_match": {"query": "%s","type": "phrase","fields": ["projectname.pname"]}}]}}],"minimum_should_match": 1}}}},"sort": [{"firsttime": "desc"}], "_source": ["agency","buyer","bidopentime","bidendtime","area","city","zbtime","projectname"],"from": 0,"size": 10}`
+    where := ""
+    if openBefer > 0 && openAfter > 0 {
+        where += ` {"range": {"bidopentime": {"gte":%d ,"lt": %d}}}`
+        where = fmt.Sprintf(where, openBefer, openAfter)
+    }
+    if buyer != "" {
+        if where != "" {
+            where += ","
+        }
+        where += ` {"term": {"buyer": "%s" }}`
+        where = fmt.Sprintf(where, buyer)
+    }
+    if agency != "" {
+        if where != "" {
+            where += ","
+        }
+        where += ` {"term": {"agency": "%s"}}`
+        where = fmt.Sprintf(where, agency)
+    }
+    sql := fmt.Sprintf(query, where, projectname)
+    log.Println("---sql:", sql)
+    return sql
 }
 
 //根据参数获取开标时间
 func getOpenTime(typ int, date string) (before, after int64) {
-	year, month, day, t := "", "", "", ""
-	var stamp time.Time
-	//年月日
-	if strings.Index(date, "年") > 0 && strings.Index(date, "月") > 0 && strings.Index(date, "日") > 0 {
-		if dateSplit_y := strings.Split(date, "年"); len(dateSplit_y) > 1 {
-			year = dateSplit_y[0]
-			date = dateSplit_y[1]
-			if dateSplit_m := strings.Split(date, "月"); len(dateSplit_m) > 1 {
-				month = dateSplit_m[0]
-				date = dateSplit_m[1]
-				if dateSplit_d := strings.Split(date, "日"); len(dateSplit_d) > 1 {
-					day = dateSplit_d[0]
-				}
-			}
-		}
-		if len([]rune(day)) == 1 {
-			day = "0" + day
-		}
-		if len([]rune(month)) == 1 {
-			month = "0" + month
-		}
-		t = fmt.Sprintf("%s-%s-%s", year, month, day)
-	}
-	//
-	if strings.Count(date, ".") == 2 {
-		dateSplit := strings.Split(date, ".")
-		if len(dateSplit) == 3 {
-			year = dateSplit[0]
-			month = dateSplit[1]
-			day = dateSplit[2]
-			if len([]rune(day)) == 1 {
-				day = "0" + day
-			}
-			if len([]rune(month)) == 1 {
-				month = "0" + month
-			}
-			t = fmt.Sprintf("%s-%s-%s", year, month, day)
-		}
-	} else if strings.Count(date, "-") == 2 {
-		dateSplit := strings.Split(date, "-")
-		if len(dateSplit) == 3 {
-			year = dateSplit[0]
-			month = dateSplit[1]
-			day = dateSplit[2]
-			if len([]rune(day)) == 1 {
-				day = "0" + day
-			}
-			if len([]rune(month)) == 1 {
-				month = "0" + month
-			}
-			t = fmt.Sprintf("%s-%s-%s", year, month, day)
-		}
-	}
-	stamp, _ = time.ParseInLocation(Date_Short_Layout, t, time.Local)
-	after = stamp.AddDate(0, 0, 1).Unix() - 1
-	if typ == 1 {
-		before = stamp.Unix()
-	} else if typ == 2 {
-		before = stamp.AddDate(0, 0, -15).Unix()
-	} else if typ == 3 {
-		before = stamp.AddDate(0, 0, -30).Unix()
-	}
-	return
+    year, month, day, t := "", "", "", ""
+    var stamp time.Time
+    //年月日
+    if strings.Index(date, "年") > 0 && strings.Index(date, "月") > 0 && strings.Index(date, "日") > 0 {
+        if dateSplit_y := strings.Split(date, "年"); len(dateSplit_y) > 1 {
+            year = dateSplit_y[0]
+            date = dateSplit_y[1]
+            if dateSplit_m := strings.Split(date, "月"); len(dateSplit_m) > 1 {
+                month = dateSplit_m[0]
+                date = dateSplit_m[1]
+                if dateSplit_d := strings.Split(date, "日"); len(dateSplit_d) > 1 {
+                    day = dateSplit_d[0]
+                }
+            }
+        }
+        if len([]rune(day)) == 1 {
+            day = "0" + day
+        }
+        if len([]rune(month)) == 1 {
+            month = "0" + month
+        }
+        t = fmt.Sprintf("%s-%s-%s", year, month, day)
+    }
+    //
+    if strings.Count(date, ".") == 2 {
+        dateSplit := strings.Split(date, ".")
+        if len(dateSplit) == 3 {
+            year = dateSplit[0]
+            month = dateSplit[1]
+            day = dateSplit[2]
+            if len([]rune(day)) == 1 {
+                day = "0" + day
+            }
+            if len([]rune(month)) == 1 {
+                month = "0" + month
+            }
+            t = fmt.Sprintf("%s-%s-%s", year, month, day)
+        }
+    } else if strings.Count(date, "-") == 2 {
+        dateSplit := strings.Split(date, "-")
+        if len(dateSplit) == 3 {
+            year = dateSplit[0]
+            month = dateSplit[1]
+            day = dateSplit[2]
+            if len([]rune(day)) == 1 {
+                day = "0" + day
+            }
+            if len([]rune(month)) == 1 {
+                month = "0" + month
+            }
+            t = fmt.Sprintf("%s-%s-%s", year, month, day)
+        }
+    }
+    stamp, _ = time.ParseInLocation(Date_Short_Layout, t, time.Local)
+    after = stamp.AddDate(0, 0, 1).Unix() - 1
+    if typ == 1 {
+        before = stamp.Unix()
+    } else if typ == 2 {
+        before = stamp.AddDate(0, 0, -15).Unix()
+    } else if typ == 3 {
+        before = stamp.AddDate(0, 0, -30).Unix()
+    }
+    return
 }
 
 //
 func GetbidKey(md5str, zipname string) string {
-	return fmt.Sprintf("bid_%s_%s", md5str, zipname)
+    return fmt.Sprintf("bid_%s_%s", md5str, zipname)
 }
 
 //解读成功后、修改bidfile_history
 func UpdateBidHistory(project_md5 string, project *map[string]interface{}) bool {
-	buyer := qutil.If((*project)["buyer"] == nil, nil, (*project)["buyer"])
-	projectname := qutil.If((*project)["projectname"] == nil, nil, (*project)["projectname"])
-	now := NowFormat(Date_Full_Layout)
-	return config.Mysql.UpdateOrDeleteBySql(`UPDATE bidfile_history 
+    buyer := qutil.If((*project)["buyer"] == nil, nil, (*project)["buyer"])
+    projectname := qutil.If((*project)["projectname"] == nil, nil, (*project)["projectname"])
+    now := NowFormat(Date_Full_Layout)
+    return config.Mysql.UpdateOrDeleteBySql(`UPDATE bidfile_history
 						SET explain_status=1,buyer=?,project_name=?,update_time=?
-						WHERE project_md5=? AND is_delete=0 AND explain_status=2 
+						WHERE project_md5=? AND is_delete=0 AND explain_status=2
 						AND explain_time IS NOT NULL`, buyer, projectname, now, project_md5) != -1
 }
 
 //开始解读 修改解读时间 并扣费
 func UpdateBidHistoryStart(userid, md5Str string) bool {
-	mainid, member_status := MainId(userid)      //大会员主账号id 大会员等级
-	memberCount := BigmemberBidfileCount(mainid) //大会员剩余招标文件解读次数
-	isunread := !IsRead(md5Str, mainid)          //大会员是否解读过该文件
-	isreadByMyself := config.Mysql.CountBySql(`select count(1) from bidfile_history 
-						where project_md5=? and user_id =? AND is_delete=0  
+    mainid, member_status := MainId(userid)                                                                                                                                                                                             //大会员主账号id 大会员等级
+    memberCount := BigmemberBidfileCount(mainid)                                                                                                                                                                                        //大会员剩余招标文件解读次数
+    isunread := !IsRead(md5Str, mainid)                                                                                                                                                                                                 //大会员是否解读过该文件
+    isreadByMyself := config.Mysql.CountBySql(`select count(1) from bidfile_history
+						where project_md5=? and user_id =? AND is_delete=0
 						AND explain_time IS NOT NULL`, md5Str, userid) > 0 //个人是否解读过
 
-	if (memberCount > 0 || !isunread) && member_status > 0 {
-		if bidcount := getBAmountInfo(mainid, 11); bidcount > 0 {
-			//插入历史记录
-			config.Mysql.Insert("bigmember_consume", map[string]interface{}{
-				"s_userid":             userid,
-				"s_master_userid":      mainid,
-				"s_serviceid":          11,
-				"l_createtime":         time.Now().Format(Date_Full_Layout),
-				"i_updatecount_before": bidcount,
-				"i_updatecount_after":  qutil.If((isunread && !isreadByMyself), bidcount-1, bidcount),
-				"s_phone":              Phone(userid),
-			})
-		}
-	}
-	//已经解读过
-	if isreadByMyself {
-		return true
-	}
-	//未解读
-	updateBidMap := map[string]interface{}{
-		"explain_time":   NowFormat(Date_Full_Layout),
-		"update_time":    NowFormat(Date_Full_Layout),
-		"explain_status": 2,
-	}
-	if memberCount > 0 && member_status > 0 { //增加主账号id
-		updateBidMap["main_id"] = mainid
-	}
-	up1 := config.Mysql.Update("bidfile_history", map[string]interface{}{
-		"user_id":        userid,
-		"project_md5":    md5Str,
-		"explain_status": 0,
-		"is_delete":      0,
-	}, updateBidMap)
-	up2 := true
-	if (memberCount > 0 || !isunread) && member_status > 0 {
-		//更改大会员次数
-		if isunread {
-			up2 = config.Mysql.UpdateOrDeleteBySql(`UPDATE bigmember_service_user a 
-						SET a.i_frequency= IF(a.i_frequency<1,0,a.i_frequency-1) 
+    if (memberCount > 0 || !isunread) && member_status > 0 {
+        if bidcount := getBAmountInfo(mainid, 11); bidcount > 0 {
+            //插入历史记录
+            config.Mysql.Insert("bigmember_consume", map[string]interface{}{
+                "s_userid":             userid,
+                "s_master_userid":      mainid,
+                "s_serviceid":          11,
+                "l_createtime":         time.Now().Format(Date_Full_Layout),
+                "i_updatecount_before": bidcount,
+                "i_updatecount_after":  qutil.If((isunread && !isreadByMyself), bidcount-1, bidcount),
+                "s_phone":              Phone(userid),
+            })
+        }
+    }
+    //已经解读过
+    if isreadByMyself {
+        return true
+    }
+    //未解读
+    updateBidMap := map[string]interface{}{
+        "explain_time":   NowFormat(Date_Full_Layout),
+        "update_time":    NowFormat(Date_Full_Layout),
+        "explain_status": 2,
+    }
+    if memberCount > 0 && member_status > 0 { //增加主账号id
+        updateBidMap["main_id"] = mainid
+    }
+    up1 := config.Mysql.Update("bidfile_history", map[string]interface{}{
+        "user_id":        userid,
+        "project_md5":    md5Str,
+        "explain_status": 0,
+        "is_delete":      0,
+    }, updateBidMap)
+    up2 := true
+    if (memberCount > 0 || !isunread) && member_status > 0 {
+        //更改大会员次数
+        if isunread {
+            up2 = config.Mysql.UpdateOrDeleteBySql(`UPDATE bigmember_service_user a
+						SET a.i_frequency= IF(a.i_frequency<1,0,a.i_frequency-1)
 						WHERE a.s_userid = ? AND a.s_serviceid = ? `, mainid, 11) > 0
-		}
-		//
-	} else {
-		r, ok := config.MQFW.FindById("user", userid, `{"i_bidfileCount":1}`)
-		if r != nil && len(*r) > 0 && ok {
-			i_bidfileCount := qutil.IntAll((*r)["i_bidfileCount"])
-			if i_bidfileCount > 0 {
-				//更改个人次数
-				up2 = config.MQFW.UpdateById("user", userid, map[string]interface{}{
-					"$inc": map[string]interface{}{
-						"i_bidfileCount": -1,
-					},
-				})
-			} else {
-				rdata := config.Mysql.FindOne("bidfile_history", map[string]interface{}{
-					"project_md5": md5Str,
-					"user_id":     userid,
-					"is_delete":   0,
-				}, "upload_filename", "")
-				filename := ""
-				if rdata != nil {
-					filename = qutil.ObjToString((*rdata)["upload_filename"])
-				}
-				//积分扣除
-				up2 = Consume(userid, filename, md5Str, 2005, config.Sysconfig.PointCount)
-			}
-		}
-	}
-	return up1 && up2
+        }
+        //
+    } else {
+        r := config.Compatible.Select(userid, `{"i_bidfileCount":1}`)
+        if r != nil && len(*r) > 0 {
+            i_bidfileCount := qutil.IntAll((*r)["i_bidfileCount"])
+            if i_bidfileCount > 0 {
+                //更改个人次数
+                up2 = config.Compatible.Update(userid, map[string]interface{}{
+                    "$inc": map[string]interface{}{
+                        "i_bidfileCount": -1,
+                    },
+                })
+            } else {
+                rdata := config.Mysql.FindOne("bidfile_history", map[string]interface{}{
+                    "project_md5": md5Str,
+                    "user_id":     userid,
+                    "is_delete":   0,
+                }, "upload_filename", "")
+                filename := ""
+                if rdata != nil {
+                    filename = qutil.ObjToString((*rdata)["upload_filename"])
+                }
+                //积分扣除
+                up2 = Consume(userid, filename, md5Str, 2005, config.Sysconfig.PointCount)
+            }
+        }
+    }
+    return up1 && up2
 }
 
 //解析失败 并发送邮件
 func FileFailSendMail(userId, href, md5Str string, status int, err string) {
-	for _, v := range config.Sysconfig.AlarmMail {
-		a := `用户userid:%s</br>
+    for _, v := range config.Sysconfig.AlarmMail {
+        a := `用户userid:%s</br>
 			  请求接口:%s</br>
 			  请求接口错误码:%d</br>
 			  请求时间:%s</br>
 			  文件md5:%s</br>
 			  错误日志:%s
 			`
-		now := NowFormat(Date_Full_Layout)
-		content := fmt.Sprintf(a, userId, href, status, now, md5Str, err)
-		SendRetryMail(3, v, "招标文件解读告警", content, "", nil, config.GmailAuth)
-	}
+        now := NowFormat(Date_Full_Layout)
+        content := fmt.Sprintf(a, userId, href, status, now, md5Str, err)
+        SendRetryMail(3, v, "招标文件解读告警", content, "", nil, config.GmailAuth)
+    }
 }
 
 //判断用户是否有大会员-招标文件解读次数 -serviceid:11(招标文件解读)
 func BigmemberBidfileCount(userid string) (count int) {
-	if userid == "" {
-		return 0
-	}
-	res := config.Mysql.SelectBySql(`select i_frequency from bigmember_service_user 
+    if userid == "" {
+        return 0
+    }
+    res := config.Mysql.SelectBySql(`select i_frequency from bigmember_service_user
 			where s_userid =? and s_serviceid=?  and i_status=0`, userid, 11)
-	if res != nil && len(*res) > 0 {
-		count = qutil.IntAll((*res)[0]["i_frequency"])
-	}
-	return count
+    if res != nil && len(*res) > 0 {
+        count = qutil.IntAll((*res)[0]["i_frequency"])
+    }
+    return count
 }
 
 //判断普通用户没有招标文件解读权力 true:没 fasle 有
 func BidFilePower(userid, md5 string) bool {
-	_id, _ := primitive.ObjectIDFromHex(userid)
-	return config.Mysql.CountBySql(`select count(1) from bidfile_history
+    _id, _ := primitive.ObjectIDFromHex(userid)
+    return config.Mysql.CountBySql(`select count(1) from bidfile_history
 						where project_md5=? and user_id =? AND is_delete=0
 						AND explain_time IS NOT NULL`, md5, userid) <= 0 &&
-		config.MQFW.Count("user", map[string]interface{}{ //判断用户没有上传过且没有次数
-			"_id": _id,
-			"i_bidfileCount": map[string]interface{}{
-				"$gt": 0,
-			}}) <= 0
+        config.MQFW.Count("user", map[string]interface{}{ //判断用户没有上传过且没有次数
+            "_id": _id,
+            "i_bidfileCount": map[string]interface{}{
+                "$gt": 0,
+            }}) <= 0
 }
 
 //判断大会员用户没有招标文件解读权力 true:没 fasle 有
 func MemberBidFilePower(userid, md5 string) bool {
-	userid, _ = MainId(userid)
-	if userid == "" {
-		return true
-	}
-	return config.Mysql.CountBySql(`select count(1) from bidfile_history
+    userid, _ = MainId(userid)
+    if userid == "" {
+        return true
+    }
+    return config.Mysql.CountBySql(`select count(1) from bidfile_history
 						where project_md5=? and user_id =? AND is_delete=0
 						AND explain_time IS NOT NULL`, md5, userid) <= 0 &&
-		config.Mysql.CountBySql(`select count(1) from 
-		bigmember_service_user where s_userid=? and s_serviceid =11 
+        config.Mysql.CountBySql(`select count(1) from
+		bigmember_service_user where s_userid=? and s_serviceid =11
 		and i_frequency >0 and i_status=0`, userid) == 0
 }
 
 //判断用户积分是否可以进行招标文件解读 true:不行 false可以
 func JyPointBidFilePower(userid string) bool {
-	if integral := Integral(userid); integral >= config.Sysconfig.PointCount {
-		return false
-	}
-	return true
+    if integral := Integral(userid); integral >= config.Sysconfig.PointCount {
+        return false
+    }
+    return true
 }
 
 //return 主账号id、大会员等级
 func MainId(userid string) (string, int) {
-	member_status := 0
-	data, ok := config.MQFW.FindById("user", userid, `{"s_member_mainid":1,,"i_member_status":1,"i_member_sub_status":1}`)
-	if ok && *data != nil && len(*data) > 0 {
-		if (*data)["s_member_mainid"] != nil && qutil.IntAllDef((*data)["i_member_sub_status"], 0) == 1 {
-			userid = qutil.ObjToString((*data)["s_member_mainid"])
-		}
-		member_status = qutil.IntAll((*data)["i_member_status"])
-	}
-	if member_status <= 0 {
-		userid = ""
-	}
-	return userid, member_status
+    member_status := 0
+    data := config.Compatible.Select(userid, `{"s_member_mainid":1,,"i_member_status":1,"i_member_sub_status":1}`)
+    if *data != nil && len(*data) > 0 {
+        if (*data)["s_member_mainid"] != nil && qutil.IntAllDef((*data)["i_member_sub_status"], 0) == 1 {
+            userid = qutil.ObjToString((*data)["s_member_mainid"])
+        }
+        member_status = qutil.IntAll((*data)["i_member_status"])
+    }
+    if member_status <= 0 {
+        userid = ""
+    }
+    return userid, member_status
 }
 
 //判断用户是否解读过该文件
 func IsRead(md5Str, userid string) bool {
-	if userid == "" {
-		return false
-	}
-	return config.Mysql.CountBySql(`select count(1) from bidfile_history 
+    if userid == "" {
+        return false
+    }
+    return config.Mysql.CountBySql(`select count(1) from bidfile_history
 	where main_id=? and is_delete=0 and project_md5=? and explain_time IS NOT NULL`, userid, md5Str) > 0
 }
 
 //获取mysql 大会员权限信息
 func getBAmountInfo(userId string, serviceId int) int {
-	// info := db.Mysql.SelectBySql("SELECT * FROM bigmember_amount a WHERE a.user_id = '" + userId + "' AND a.is_ing = 1")
-	info := config.Mysql.SelectBySql(`SELECT a.i_frequency FROM bigmember_service_user a WHERE a.s_userid = ? AND a.i_status = 0 AND a.s_serviceid = ?`, userId, serviceId)
-	if info != nil && len(*info) > 0 {
-		amount := (*info)[0]
-		count := qutil.IntAll(amount["i_frequency"])
-		return count
-	}
-	return 0
+    // info := db.Mysql.SelectBySql("SELECT * FROM bigmember_amount a WHERE a.user_id = '" + userId + "' AND a.is_ing = 1")
+    info := config.Mysql.SelectBySql(`SELECT a.i_frequency FROM bigmember_service_user a WHERE a.s_userid = ? AND a.i_status = 0 AND a.s_serviceid = ?`, userId, serviceId)
+    if info != nil && len(*info) > 0 {
+        amount := (*info)[0]
+        count := qutil.IntAll(amount["i_frequency"])
+        return count
+    }
+    return 0
 }
 
 func Phone(userid string) string {
-	u, ok := config.MQFW.FindById("user", userid, `{"s_phone":1,"s_m_phone":1}`)
-	if ok && u != nil {
-		if s_phone, _ := (*u)["s_phone"].(string); s_phone != "" {
-			return s_phone
-		} else if s_m_phone, _ := (*u)["s_m_phone"].(string); s_m_phone != "" {
-			return s_m_phone
-		}
-	}
-	return ""
+    u := config.Compatible.Select(userid, `{"s_phone":1,"s_m_phone":1}`)
+    if u != nil {
+        if s_phone, _ := (*u)["s_phone"].(string); s_phone != "" {
+            return s_phone
+        } else if s_m_phone, _ := (*u)["s_m_phone"].(string); s_m_phone != "" {
+            return s_m_phone
+        }
+    }
+    return ""
 }
 
 //获取用户积分
 func Integral(userid string) int {
-	appid, _ := config.Sysconfig.Appids["jianyu"].(string)
-	value := fmt.Sprintf("?userId=%s&appId=%s", userid, appid)
-	href, _ := config.Sysconfig.IntegralUrl["balance"].(string)
-	res, err := http.Get(href + value)
-	if err != nil {
-		log.Println(err.Error())
-		return -1
-	}
-	defer res.Body.Close()
-	bs, _ := ioutil.ReadAll(res.Body)
-	resMap := map[string]interface{}{}
-	err = json.Unmarshal([]byte(bs), &resMap)
-	if err != nil {
-		log.Println("json.unmarshal err", resMap)
-		return -1
-	}
-	if qutil.IntAll(resMap["Code"]) == 1 {
-		return qutil.IntAll(resMap["Data"])
-	}
-	return -1
+    appid, _ := config.Sysconfig.Appids["jianyu"].(string)
+    value := fmt.Sprintf("?userId=%s&appId=%s", userid, appid)
+    href, _ := config.Sysconfig.IntegralUrl["balance"].(string)
+    res, err := http.Get(href + value)
+    if err != nil {
+        log.Println(err.Error())
+        return -1
+    }
+    defer res.Body.Close()
+    bs, _ := ioutil.ReadAll(res.Body)
+    resMap := map[string]interface{}{}
+    err = json.Unmarshal([]byte(bs), &resMap)
+    if err != nil {
+        log.Println("json.unmarshal err", resMap)
+        return -1
+    }
+    if qutil.IntAll(resMap["Code"]) == 1 {
+        return qutil.IntAll(resMap["Data"])
+    }
+    return -1
 }
 
 //消耗剑鱼币接口
@@ -523,42 +523,42 @@ md5Str :文件md5值 如果是剑鱼币兑换则传""
 pointType :2005招标文件解读消耗剑鱼币 2006招标文件解读兑换次数
 */
 func Consume(userid, name, md5Str string, pointType, pointCount int) bool {
-	abstract := ""
-	bytes := []byte{}
-	if name != "" {
-		bytes, _ = json.Marshal(map[string]interface{}{
-			"name": name,
-		})
-		abstract = string(bytes)
-	}
-	href, _ := config.Sysconfig.IntegralUrl["consume"].(string)
-	appid, _ := config.Sysconfig.Appids["jianyu"].(string)
-	data := url.Values{
-		"userId":     []string{userid},
-		"appId":      []string{appid},                    //剑鱼标识
-		"pointType":  []string{strconv.Itoa(pointType)},  //招标文件解读
-		"sourceType": []string{"积分消耗"},                   //业务类型
-		"sourceId":   []string{md5Str},                   //订单号
-		"point":      []string{strconv.Itoa(pointCount)}, //积分
-		"endDate":    []string{""},                       //积分类型永久:true、时效:false
-		"abstract":   []string{abstract},                 //
-	}
-	//
-	res, err := http.PostForm(href, data)
-	if err != nil {
-		log.Println(err.Error())
-	}
-	defer res.Body.Close()
-	bs, _ := ioutil.ReadAll(res.Body)
-	log.Println("返回内容:" + string(bs))
-	resMap := map[string]interface{}{}
-	err = json.Unmarshal([]byte(bs), &resMap)
-	if err != nil {
-		log.Println("json.unmarshal err", resMap)
-	} else {
-		if qutil.IntAll(resMap["Code"]) == 1 {
-			return true
-		}
-	}
-	return false
+    abstract := ""
+    bytes := []byte{}
+    if name != "" {
+        bytes, _ = json.Marshal(map[string]interface{}{
+            "name": name,
+        })
+        abstract = string(bytes)
+    }
+    href, _ := config.Sysconfig.IntegralUrl["consume"].(string)
+    appid, _ := config.Sysconfig.Appids["jianyu"].(string)
+    data := url.Values{
+        "userId":     []string{userid},
+        "appId":      []string{appid},                    //剑鱼标识
+        "pointType":  []string{strconv.Itoa(pointType)},  //招标文件解读
+        "sourceType": []string{"积分消耗"},                   //业务类型
+        "sourceId":   []string{md5Str},                   //订单号
+        "point":      []string{strconv.Itoa(pointCount)}, //积分
+        "endDate":    []string{""},                       //积分类型永久:true、时效:false
+        "abstract":   []string{abstract},                 //
+    }
+    //
+    res, err := http.PostForm(href, data)
+    if err != nil {
+        log.Println(err.Error())
+    }
+    defer res.Body.Close()
+    bs, _ := ioutil.ReadAll(res.Body)
+    log.Println("返回内容:" + string(bs))
+    resMap := map[string]interface{}{}
+    err = json.Unmarshal([]byte(bs), &resMap)
+    if err != nil {
+        log.Println("json.unmarshal err", resMap)
+    } else {
+        if qutil.IntAll(resMap["Code"]) == 1 {
+            return true
+        }
+    }
+    return false
 }

+ 2 - 0
src/jfw/modules/bigmember/src/config/config.go

@@ -4,6 +4,7 @@ import (
 	qutil "app.yhyue.com/moapp/jybase/common"
 	"app.yhyue.com/moapp/jybase/mail"
 	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/middleGround"
+	"app.yhyue.com/moapp/jypkg/compatible"
 	"app.yhyue.com/moapp/jypkg/middleground"
 	"github.com/gogf/gf/v2/frame/g"
 	"github.com/gogf/gf/v2/os/gcfg"
@@ -79,6 +80,7 @@ type followConfig struct {
 var Config *config
 var GmailAuth []*mail.GmailAuth
 var Middleground *middleground.Middleground
+var Compatible *compatible.Compatible
 
 func init() {
 	//程序配置文件

+ 3 - 0
src/jfw/modules/bigmember/src/db/db.go

@@ -7,6 +7,8 @@ import (
 	"app.yhyue.com/moapp/jybase/mysql"
 	"app.yhyue.com/moapp/jybase/redis"
 	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+	"app.yhyue.com/moapp/jypkg/compatible"
+	"jy/src/jfw/modules/bigmember/src/config"
 	"log"
 )
 
@@ -194,5 +196,6 @@ func init() {
 			}
 			MysqlSubject.Init()
 		}
+		config.Compatible = compatible.NewCompatible(&Mgo, Base, Mysql, config.Middleground)
 	}
 }

+ 2 - 1
src/jfw/modules/bigmember/src/go.mod

@@ -5,7 +5,7 @@ go 1.18
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d
 	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
-	app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa
+	app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114
 	github.com/donnie4w/go-logger v0.0.0-20170827050443-4740c51383f4
 	github.com/gogf/gf/v2 v2.0.6
 	go.mongodb.org/mongo-driver v1.11.1
@@ -13,6 +13,7 @@ require (
 
 require (
 	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 // indirect
 	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 // indirect
 	bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4 // indirect
 	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230129060002-f69424aa14ba // indirect

+ 4 - 2
src/jfw/modules/bigmember/src/go.sum

@@ -13,11 +13,13 @@ app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tc
 app.yhyue.com/moapp/jybase v0.0.0-20230109015757-aa3d5e19b196/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a h1:wD4aWPSYdiX1cIP4lzzPD2s7fYhKa3muIf97l9tonJE=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa h1:0/2I4ubgDsRbKm7PeiVSTvYwZCK3anZQaEagsGBbI7E=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa/go.mod h1:0DqPlGxaufZlKaLoRndTWG4j3qUQqJ6MNZCmoPcMqSg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114 h1:89J5Zq4bfnocIpEWBn19PnfaT+8Dh+Rv4X8QoTwxCpg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114/go.mod h1:sa5YRPqTQLOVBmpltjT21EkQ7DfJbUZFARUb4ZJ7U+k=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae h1:6rDDaz6yxvE8viTSzEBwKYOFWq14TMfuBivSazUZMz4=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
 bp.jydev.jianyu360.cn/BP/jynsq v0.0.0-20220222052708-ebc43af90698/go.mod h1:ojo/AUH9Yr1wzarEjOaNMkj1Cet/9r8IgLyba64Z52E=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 h1:cw/PdRypNFcYOk4iWAfHjIFoMzIlXUfl9XAmWujBOPY=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7/go.mod h1:7Xhygw0KBuL4h0G76FnFg4otQcA9bmOO0c8M0FCjAyQ=
 bp.jydev.jianyu360.cn/BaseService/gateway v0.0.0-20220419090715-88ddb32961be/go.mod h1:Yj4oabIGItuMoF0BXYLz2XAnF581kxgXBrvlUtIJrkI=
 bp.jydev.jianyu360.cn/BaseService/gateway v1.3.4/go.mod h1:BMLd/5wb3BIEGhnEgF9y1sJN9P5/Dw9kYsoiE9V8I9g=
 bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 h1:jeItQ6RM1T6yPWc/5i4R6h3kViD+Rm2VnIEsc1gCFJA=

+ 257 - 272
src/jfw/modules/bigmember/src/service/analysis/analysis.go

@@ -2,295 +2,280 @@
 package analysis
 
 import (
-        . "jy/src/jfw/modules/bigmember/src/config"
-        "jy/src/jfw/modules/bigmember/src/db"
-        "jy/src/jfw/modules/bigmember/src/entity"
-        "jy/src/jfw/modules/bigmember/src/util"
-        "regexp"
-        "strconv"
-        "strings"
-        "time"
+	. "jy/src/jfw/modules/bigmember/src/config"
+	"jy/src/jfw/modules/bigmember/src/entity"
+	"jy/src/jfw/modules/bigmember/src/util"
+	"regexp"
+	"strconv"
+	"strings"
+	"time"
 
-        . "app.yhyue.com/moapp/jybase/api"
-        qutil "app.yhyue.com/moapp/jybase/common"
-        . "app.yhyue.com/moapp/jybase/date"
-        "app.yhyue.com/moapp/jybase/encrypt"
-        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+	. "app.yhyue.com/moapp/jybase/api"
+	qutil "app.yhyue.com/moapp/jybase/common"
+	. "app.yhyue.com/moapp/jybase/date"
+	"app.yhyue.com/moapp/jybase/encrypt"
+	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Analysis struct {
-        *xweb.Action
-        pName           xweb.Mapper `xweb:"/analysis/projectName"`     //根据项目名称关键词连带项目名称
-        pInfo           xweb.Mapper `xweb:"/analysis/projectInfo"`     //根据项目名称获取项目信息
-        csORRsList      xweb.Mapper `xweb:"/potential/corList"`        //潜在客户customers or 潜在竞争对手rivals
-        rMyRivals       xweb.Mapper `xweb:"/potential/rMyRivals"`      //移除我的潜在竞争对手rivals
-        decInfo         xweb.Mapper `xweb:"/decision/decInfo"`         //投标决策分析
-        trialInfo       xweb.Mapper `xweb:"/decision/trialInfo"`       //投标决策分析-使用用户 剩余次数
-        forPList        xweb.Mapper `xweb:"/forecast/forPList"`        //新项目预测结果list
-        forPContent     xweb.Mapper `xweb:"/forecast/forPContent"`     //新项目预测结果详情
-        fWData          xweb.Mapper `xweb:"/forecast/forWData"`        //中标预测分析
-        fWStatus        xweb.Mapper `xweb:"/forecast/forWStatus"`      //查看中标预测状态
-        fWResult        xweb.Mapper `xweb:"/forecast/forWResult"`      //中标预测结果
-        fWOvertime      xweb.Mapper `xweb:"/forecast/forWOvertime"`    //中标预测超时处理
-        bdInfoStatus    xweb.Mapper `xweb:"/forecast/bdInfoStatus"`    //中标预测-项目是否已完成招标
-        freeDecInfo     xweb.Mapper `xweb:"/decision/freeDecInfo"`     //投标决策分析-免费用户
-        potIndex        xweb.Mapper `xweb:"/potential/index"`          //潜在客户customers or 潜在竞争对手rivals 首页接口
-        projectInfoByBW xweb.Mapper `xweb:"/decision/projectInfoByBW"` //投标决策分析-采购单位和中标企业 其他项目明细/类似项目明细
+	*xweb.Action
+	pName           xweb.Mapper `xweb:"/analysis/projectName"`     //根据项目名称关键词连带项目名称
+	pInfo           xweb.Mapper `xweb:"/analysis/projectInfo"`     //根据项目名称获取项目信息
+	csORRsList      xweb.Mapper `xweb:"/potential/corList"`        //潜在客户customers or 潜在竞争对手rivals
+	rMyRivals       xweb.Mapper `xweb:"/potential/rMyRivals"`      //移除我的潜在竞争对手rivals
+	decInfo         xweb.Mapper `xweb:"/decision/decInfo"`         //投标决策分析
+	trialInfo       xweb.Mapper `xweb:"/decision/trialInfo"`       //投标决策分析-使用用户 剩余次数
+	forPList        xweb.Mapper `xweb:"/forecast/forPList"`        //新项目预测结果list
+	forPContent     xweb.Mapper `xweb:"/forecast/forPContent"`     //新项目预测结果详情
+	fWData          xweb.Mapper `xweb:"/forecast/forWData"`        //中标预测分析
+	fWStatus        xweb.Mapper `xweb:"/forecast/forWStatus"`      //查看中标预测状态
+	fWResult        xweb.Mapper `xweb:"/forecast/forWResult"`      //中标预测结果
+	fWOvertime      xweb.Mapper `xweb:"/forecast/forWOvertime"`    //中标预测超时处理
+	bdInfoStatus    xweb.Mapper `xweb:"/forecast/bdInfoStatus"`    //中标预测-项目是否已完成招标
+	freeDecInfo     xweb.Mapper `xweb:"/decision/freeDecInfo"`     //投标决策分析-免费用户
+	potIndex        xweb.Mapper `xweb:"/potential/index"`          //潜在客户customers or 潜在竞争对手rivals 首页接口
+	projectInfoByBW xweb.Mapper `xweb:"/decision/projectInfoByBW"` //投标决策分析-采购单位和中标企业 其他项目明细/类似项目明细
 
 }
 
 const (
-        C_FW_qyxy       = "qyxy_std"            //中标预测-企业信息
-        C_FPContent     = "project_forecast"    //新项目预测表
-        C_FPList        = "pushprojectforecast" //新项目预测
-        FP_Limit        = 10                    //每页10条
-        C_ForecastData  = "forecast_info"       //中标预测数据
-        C_ForecastLog   = "forecast_log"        //中标预测日志
-        C_PTLog         = "potential_search"    //潜在竞争对手或客户日志表
-        C_FEnt          = "follow_ent_monitor"  //企业情报
-        C_Member        = "member"
-        C_User          = "user"
-        C_Entniche_Rule = "entniche_rule"
-        P_INDEX         = "projectset"
-        P_TYPE          = "projectset"
-        PSearch_PCount  = 500 //潜在客户和潜在竞争对手数量
-        PSearch_field   = `buyer`
-        P_limit         = 2000              //查询两千个客户
-        P_redis_time    = 15 * 24 * 60 * 60 //redis存15天
-        METHOD          = "POST"
+	C_FW_qyxy       = "qyxy_std"            //中标预测-企业信息
+	C_FPContent     = "project_forecast"    //新项目预测表
+	C_FPList        = "pushprojectforecast" //新项目预测
+	FP_Limit        = 10                    //每页10条
+	C_ForecastData  = "forecast_info"       //中标预测数据
+	C_ForecastLog   = "forecast_log"        //中标预测日志
+	C_PTLog         = "potential_search"    //潜在竞争对手或客户日志表
+	C_FEnt          = "follow_ent_monitor"  //企业情报
+	C_Member        = "member"
+	C_User          = "user"
+	C_Entniche_Rule = "entniche_rule"
+	P_INDEX         = "projectset"
+	P_TYPE          = "projectset"
+	PSearch_PCount  = 500 //潜在客户和潜在竞争对手数量
+	PSearch_field   = `buyer`
+	P_limit         = 2000              //查询两千个客户
+	P_redis_time    = 15 * 24 * 60 * 60 //redis存15天
+	METHOD          = "POST"
 )
 
 func init() {
-        now := time.Now()
-        newDate := time.Date(now.Year()-Config.TimeSpan, 1, 1, 0, 0, 0, 0, time.Local).Unix()
-        entity.P_Starttime = strconv.FormatInt(newDate, 10)
-        if Config.RegWinner != "" {
-                entity.RegWinner = regexp.MustCompile(Config.RegWinner)
-        }
-        entity.UIL = entity.NewUserInfoLock()
+	now := time.Now()
+	newDate := time.Date(now.Year()-Config.TimeSpan, 1, 1, 0, 0, 0, 0, time.Local).Unix()
+	entity.P_Starttime = strconv.FormatInt(newDate, 10)
+	if Config.RegWinner != "" {
+		entity.RegWinner = regexp.MustCompile(Config.RegWinner)
+	}
+	entity.UIL = entity.NewUserInfoLock()
 }
 
 // 根据项目名称获取项目信息
 func (this *Analysis) PInfo() {
-        defer qutil.Catch()
-        var regMap = Result{
-                Data:       []map[string]interface{}{},
-                Error_code: Error_code,
-                Error_msg:  "",
-        }
-        if this.Method() == METHOD {
-                userId, _ := this.GetSession("userId").(string)
-                var ptids = []string{}
-                if this.GetString("ptid") != "" {
-                        ptids = encrypt.DecodeArticleId2ByCheck(this.GetString("ptid"))
-                }
-                var sourceinfoids = []string{}
-                if this.GetString("sourceinfoid") != "" {
-                        sourceinfoids = encrypt.DecodeArticleId2ByCheck(this.GetString("sourceinfoid"))
-                }
-                // log.Println(ptids, "-----", sourceinfoids)
-                if len(ptids) > 0 || len(sourceinfoids) > 0 {
-                        ptdatas := entity.GetProInfoById(ptids, sourceinfoids)
-                        ArrPS := map[string]interface{}{}
-                        if ptdatas != nil && len(ptdatas) > 0 {
-                                ptdata := ptdatas[0]
-                                projectname := qutil.ObjToString(ptdata["projectname"])
-                                buyerclass := qutil.ObjToString(ptdata["buyerclass"])
-                                purchasing := qutil.ObjToString(ptdata["purchasing"])
-                                area := qutil.ObjToString(ptdata["area"])
-                                city := qutil.ObjToString(ptdata["city"])
-                                buyer := qutil.ObjToString(ptdata["buyer"]) //采购单位
-                                ids := qutil.ObjArrToStringArr(ptdata["ids"].([]interface{}))
-                                s_subscopeclass := qutil.ObjToString(ptdata["s_subscopeclass"]) //项目行业
-                                buyerperson := qutil.ObjToString(ptdata["buyerperson"])         //采购联系人
-                                buyertel := qutil.ObjToString(ptdata["buyertel"])               //采购联系方式
-                                if this.GetString("D") == "" {
-                                        var keyArr = []map[string]interface{}{}
-                                        var a_key = []map[string]interface{}{}
-                                        //查库获得大会员用户的信息
-                                        positionType := qutil.Int64All(this.GetSession("positionType"))
-                                        o_mb, ok := &map[string]interface{}{}, false
-                                        if positionType == 0 {
-                                                o_mb, ok = db.Mgo.FindById(C_User, userId, `{"o_member_jy":1,"s_member_mainid":1,"i_member_sub_status":1}`)
-                                                if ok && o_mb != nil && (*o_mb) != nil && (*o_mb)["s_member_mainid"] != nil && qutil.IntAllDef((*o_mb)["i_member_sub_status"], 0) == 1 { //如果是子账号 查询主账号信息
-                                                        mainId := qutil.ObjToString((*o_mb)["s_member_mainid"])
-                                                        o_mb, ok = db.Mgo.FindById(C_User, mainId, `{"o_member_jy":1}`)
-                                                }
-                                        } else {
-                                                o_mb, ok = db.Mgo.FindById(C_Entniche_Rule, userId, `{"o_member_jy":1,"s_member_mainid":1,"i_member_sub_status":1}`)
-                                                query := map[string]interface{}{
-                                                        "i_userid": qutil.Int64All(this.GetSession("entUserId")),
-                                                        "i_entid":  qutil.Int64All(this.GetSession("entId")),
-                                                        "i_type":   1,
-                                                }
-                                                o_mb, ok = db.Mgo.FindOne(C_User, query)
-                                                if (*o_mb) != nil && (*o_mb)["o_member_jy"] != nil {
-                                                        (*o_mb)["o_member_jy"] = (*o_mb)["o_entniche"]
-                                                }
-                                        }
-                                        if ok && o_mb != nil && (*o_mb) != nil && (*o_mb)["o_member_jy"] != nil {
-                                                o_member_jy := qutil.ObjToMap((*o_mb)["o_member_jy"])
-                                                if (*o_member_jy)["a_items"] != nil {
-                                                        a_items := qutil.ObjArrToMapArr((*o_member_jy)["a_items"].([]interface{}))
-                                                        if len(a_items) > 0 {
-                                                                for _, v := range a_items {
-                                                                        a_key = qutil.ObjArrToMapArr(v["a_key"].([]interface{}))
-                                                                L:
-                                                                        for _, vv := range a_key {
-                                                                                keys := qutil.ObjArrToStringArr(vv["key"].([]interface{}))
-                                                                                for _, kv := range keys {
-                                                                                        if strings.Contains(projectname, kv) || strings.Contains(purchasing, kv) {
-                                                                                                keyArr = append(keyArr, vv)
-                                                                                                break L
-                                                                                        }
-                                                                                }
-                                                                        }
-                                                                }
-                                                        }
-                                                }
-                                        }
-                                        if len(keyArr) == 0 {
-                                                if purchasing != "" {
-                                                        if len(strings.Split(purchasing, ",")) > 0 {
-                                                                for _, v := range strings.Split(purchasing, ",") {
-                                                                        keyArr = append(keyArr, map[string]interface{}{
-                                                                                "key": []string{v},
-                                                                        })
-                                                                }
-                                                        }
-                                                }
-                                        }
-                                        ArrPS["buyerContent"] = keyArr
-                                        var industry_arr = []string{}
-                                        if s_subscopeclass != "" {
-                                                for _, v := range strings.Split(s_subscopeclass, ",") {
-                                                        if v == "" {
-                                                                continue
-                                                        }
-                                                        industry_arr = append(industry_arr, v)
-                                                }
-                                        }
-                                        ArrPS["industry"] = industry_arr
-                                        if purchasing != "" && len(strings.Split(purchasing, ",")) > 0 {
-                                                if len(strings.Split(purchasing, ",")) > 5 {
-                                                        ArrPS["purchasing"] = strings.Split(purchasing, ",")[:5]
-                                                } else {
-                                                        ArrPS["purchasing"] = strings.Split(purchasing, ",")
-                                                }
-                                        } else {
-                                                ArrPS["purchasing"] = []string{}
-                                        }
-                                        if area == "全国" {
-                                                ArrPS["area"] = map[string]interface{}{}
-                                        } else {
-                                                ArrPS["area"] = map[string]interface{}{
-                                                        area: strings.Split(city, ","),
-                                                }
-                                        }
-                                } else {
-                                        if s_subscopeclass != "" {
-                                                ArrPS["s_subscopeclass"] = s_subscopeclass
-                                        } else {
-                                                ArrPS["s_subscopeclass"] = ""
-                                        }
-                                        ArrPS["bidamount"] = qutil.Float64All(ptdata["bidamount"]) //中标金额
-                                        ArrPS["agency"] = qutil.ObjToString(ptdata["agency"])      //招标代理机构
-                                        zbtime := ptdata["zbtime"]
-                                        if zbtime != nil {
-                                                ArrPS["zbtime"] = FormatDateWithObj(&zbtime, "2006/01/02") //招标时间
-                                        }
-                                        bidopentime := ptdata["bidopentime"]
-                                        if bidopentime != nil {
-                                                ArrPS["bidopentime"] = FormatDateWithObj(&bidopentime, "2006/01/02") //开标时间
-                                        }
-                                        ArrPS["area"] = area
-                                        ArrPS["city"] = city
-                                        ArrPS["bidcycle"] = ptdata["bidcycle"] //标书周期
-                                }
-                                var buyerclass_arr = []string{}
-                                if buyerclass != "" {
-                                        for _, v := range strings.Split(buyerclass, ",") {
-                                                if v == "其它" || v == "" {
-                                                        continue
-                                                }
-                                                buyerclass_arr = append(buyerclass_arr, v)
-                                        }
-                                }
-                                ArrPS["buyerclass"] = buyerclass_arr
-                                ArrPS["projectname"] = projectname
-                                if len(sourceinfoids) > 0 {
-                                        ArrPS["infoid"] = this.GetString("sourceinfoid")
-                                } else if len(ids) > 0 && ids[0] != "" {
-                                        ArrPS["infoid"] = util.EncodeId(ids[0])
-                                }
-                                ArrPS["id"] = util.EncodeId(ptdata["_id"].(string))
-                                ArrPS["buyer"] = buyer
-                                ArrPS["budget"] = qutil.Float64All(ptdata["budget"]) //预算
-                                ArrPS["buyerperson"] = buyerperson
-                                ArrPS["buyertel"] = buyertel
-                        }
-                        regMap.Data = ArrPS
-                } else {
-                        regMap.Error_code = Error_code_1002
-                        regMap.Error_msg = Error_msg_1002
-                }
-        } else {
-                regMap.Error_code = Error_code_1005
-                regMap.Error_msg = Error_msg_1005
-        }
-        this.ServeJson(regMap)
+	defer qutil.Catch()
+	var regMap = Result{
+		Data:       []map[string]interface{}{},
+		Error_code: Error_code,
+		Error_msg:  "",
+	}
+	if this.Method() == METHOD {
+		userId, _ := this.GetSession("userId").(string)
+		var ptids = []string{}
+		if this.GetString("ptid") != "" {
+			ptids = encrypt.DecodeArticleId2ByCheck(this.GetString("ptid"))
+		}
+		var sourceinfoids = []string{}
+		if this.GetString("sourceinfoid") != "" {
+			sourceinfoids = encrypt.DecodeArticleId2ByCheck(this.GetString("sourceinfoid"))
+		}
+		// log.Println(ptids, "-----", sourceinfoids)
+		if len(ptids) > 0 || len(sourceinfoids) > 0 {
+			ptdatas := entity.GetProInfoById(ptids, sourceinfoids)
+			ArrPS := map[string]interface{}{}
+			if ptdatas != nil && len(ptdatas) > 0 {
+				ptdata := ptdatas[0]
+				projectname := qutil.ObjToString(ptdata["projectname"])
+				buyerclass := qutil.ObjToString(ptdata["buyerclass"])
+				purchasing := qutil.ObjToString(ptdata["purchasing"])
+				area := qutil.ObjToString(ptdata["area"])
+				city := qutil.ObjToString(ptdata["city"])
+				buyer := qutil.ObjToString(ptdata["buyer"]) //采购单位
+				ids := qutil.ObjArrToStringArr(ptdata["ids"].([]interface{}))
+				s_subscopeclass := qutil.ObjToString(ptdata["s_subscopeclass"]) //项目行业
+				buyerperson := qutil.ObjToString(ptdata["buyerperson"])         //采购联系人
+				buyertel := qutil.ObjToString(ptdata["buyertel"])               //采购联系方式
+				if this.GetString("D") == "" {
+					var keyArr = []map[string]interface{}{}
+					var a_key = []map[string]interface{}{}
+					//查库获得大会员用户的信息
+					o_mb, ok := &map[string]interface{}{}, false
+					o_mb = Compatible.Select(userId, `{"o_member_jy":1,"s_member_mainid":1,"i_member_sub_status":1}`)
+					if o_mb != nil && (*o_mb) != nil && (*o_mb)["s_member_mainid"] != nil && qutil.IntAllDef((*o_mb)["i_member_sub_status"], 0) == 1 { //如果是子账号 查询主账号信息
+						mainId := qutil.ObjToString((*o_mb)["s_member_mainid"])
+						o_mb = Compatible.Select(mainId, `{"o_member_jy":1}`)
+					}
+					if ok && o_mb != nil && (*o_mb) != nil && (*o_mb)["o_member_jy"] != nil {
+						o_member_jy := qutil.ObjToMap((*o_mb)["o_member_jy"])
+						if (*o_member_jy)["a_items"] != nil {
+							a_items := qutil.ObjArrToMapArr((*o_member_jy)["a_items"].([]interface{}))
+							if len(a_items) > 0 {
+								for _, v := range a_items {
+									a_key = qutil.ObjArrToMapArr(v["a_key"].([]interface{}))
+								L:
+									for _, vv := range a_key {
+										keys := qutil.ObjArrToStringArr(vv["key"].([]interface{}))
+										for _, kv := range keys {
+											if strings.Contains(projectname, kv) || strings.Contains(purchasing, kv) {
+												keyArr = append(keyArr, vv)
+												break L
+											}
+										}
+									}
+								}
+							}
+						}
+					}
+					if len(keyArr) == 0 {
+						if purchasing != "" {
+							if len(strings.Split(purchasing, ",")) > 0 {
+								for _, v := range strings.Split(purchasing, ",") {
+									keyArr = append(keyArr, map[string]interface{}{
+										"key": []string{v},
+									})
+								}
+							}
+						}
+					}
+					ArrPS["buyerContent"] = keyArr
+					var industry_arr = []string{}
+					if s_subscopeclass != "" {
+						for _, v := range strings.Split(s_subscopeclass, ",") {
+							if v == "" {
+								continue
+							}
+							industry_arr = append(industry_arr, v)
+						}
+					}
+					ArrPS["industry"] = industry_arr
+					if purchasing != "" && len(strings.Split(purchasing, ",")) > 0 {
+						if len(strings.Split(purchasing, ",")) > 5 {
+							ArrPS["purchasing"] = strings.Split(purchasing, ",")[:5]
+						} else {
+							ArrPS["purchasing"] = strings.Split(purchasing, ",")
+						}
+					} else {
+						ArrPS["purchasing"] = []string{}
+					}
+					if area == "全国" {
+						ArrPS["area"] = map[string]interface{}{}
+					} else {
+						ArrPS["area"] = map[string]interface{}{
+							area: strings.Split(city, ","),
+						}
+					}
+				} else {
+					if s_subscopeclass != "" {
+						ArrPS["s_subscopeclass"] = s_subscopeclass
+					} else {
+						ArrPS["s_subscopeclass"] = ""
+					}
+					ArrPS["bidamount"] = qutil.Float64All(ptdata["bidamount"]) //中标金额
+					ArrPS["agency"] = qutil.ObjToString(ptdata["agency"])      //招标代理机构
+					zbtime := ptdata["zbtime"]
+					if zbtime != nil {
+						ArrPS["zbtime"] = FormatDateWithObj(&zbtime, "2006/01/02") //招标时间
+					}
+					bidopentime := ptdata["bidopentime"]
+					if bidopentime != nil {
+						ArrPS["bidopentime"] = FormatDateWithObj(&bidopentime, "2006/01/02") //开标时间
+					}
+					ArrPS["area"] = area
+					ArrPS["city"] = city
+					ArrPS["bidcycle"] = ptdata["bidcycle"] //标书周期
+				}
+				var buyerclass_arr = []string{}
+				if buyerclass != "" {
+					for _, v := range strings.Split(buyerclass, ",") {
+						if v == "其它" || v == "" {
+							continue
+						}
+						buyerclass_arr = append(buyerclass_arr, v)
+					}
+				}
+				ArrPS["buyerclass"] = buyerclass_arr
+				ArrPS["projectname"] = projectname
+				if len(sourceinfoids) > 0 {
+					ArrPS["infoid"] = this.GetString("sourceinfoid")
+				} else if len(ids) > 0 && ids[0] != "" {
+					ArrPS["infoid"] = util.EncodeId(ids[0])
+				}
+				ArrPS["id"] = util.EncodeId(ptdata["_id"].(string))
+				ArrPS["buyer"] = buyer
+				ArrPS["budget"] = qutil.Float64All(ptdata["budget"]) //预算
+				ArrPS["buyerperson"] = buyerperson
+				ArrPS["buyertel"] = buyertel
+			}
+			regMap.Data = ArrPS
+		} else {
+			regMap.Error_code = Error_code_1002
+			regMap.Error_msg = Error_msg_1002
+		}
+	} else {
+		regMap.Error_code = Error_code_1005
+		regMap.Error_msg = Error_msg_1005
+	}
+	this.ServeJson(regMap)
 }
 
 // 根据项目名称获取项目名称
 func (this *Analysis) PName() {
-        defer qutil.Catch()
-        var regMap = Result{
-                Data:       []map[string]interface{}{},
-                Error_code: Error_code,
-                Error_msg:  "",
-        }
-        if this.Method() == METHOD {
-                var pName = this.GetString("pName")
-                limit := Config.RdProLimit //匹配项目数量
-                if limit == 0 {
-                        limit = 10
-                }
-                if pName != "" {
-                        if len([]rune(pName)) > 2 {
-                                pName = strings.ReplaceAll(pName, "\"", "")
-                                data := entity.GetProNameImmediate(pName, limit)
-                                ArrPS := []map[string]interface{}{}
-                                if data != nil && len(data) > 0 {
-                                        var pjtMap = map[string]bool{}
-                                        for _, v := range data {
-                                                r_data := qutil.ObjToMap(v)
-                                                //过滤重复名称的项目
-                                                if pjtMap[(*r_data)["projectname"].(string)] {
-                                                        continue
-                                                }
-                                                if (*r_data)["firsttime"] != nil {
-                                                        firsttime := (*r_data)["firsttime"]
-                                                        (*r_data)["firsttime"] = FormatDateWithObj(&firsttime, Date_Short_Layout)
-                                                }
-                                                (*r_data)["s_id"] = util.EncodeId((*r_data)["_id"].(string))
-                                                (*r_data)["sourceinfoid"] = util.EncodeId((*r_data)["sourceinfoid"].(string))
-                                                delete(v, "_id")
-                                                pjtMap[(*r_data)["projectname"].(string)] = true
-                                                ArrPS = append(ArrPS, v)
-                                        }
-                                }
-                                regMap.Data = ArrPS
-                        } else {
-                                regMap.Error_code = Error_code_1003
-                                regMap.Error_msg = Error_msg_1003
-                        }
-                } else {
-                        regMap.Error_code = Error_code_1002
-                        regMap.Error_msg = Error_msg_1002
-                }
-        } else {
-                regMap.Error_code = Error_code_1005
-                regMap.Error_msg = Error_msg_1005
-        }
-        this.ServeJson(regMap)
+	defer qutil.Catch()
+	var regMap = Result{
+		Data:       []map[string]interface{}{},
+		Error_code: Error_code,
+		Error_msg:  "",
+	}
+	if this.Method() == METHOD {
+		var pName = this.GetString("pName")
+		limit := Config.RdProLimit //匹配项目数量
+		if limit == 0 {
+			limit = 10
+		}
+		if pName != "" {
+			if len([]rune(pName)) > 2 {
+				pName = strings.ReplaceAll(pName, "\"", "")
+				data := entity.GetProNameImmediate(pName, limit)
+				ArrPS := []map[string]interface{}{}
+				if data != nil && len(data) > 0 {
+					var pjtMap = map[string]bool{}
+					for _, v := range data {
+						r_data := qutil.ObjToMap(v)
+						//过滤重复名称的项目
+						if pjtMap[(*r_data)["projectname"].(string)] {
+							continue
+						}
+						if (*r_data)["firsttime"] != nil {
+							firsttime := (*r_data)["firsttime"]
+							(*r_data)["firsttime"] = FormatDateWithObj(&firsttime, Date_Short_Layout)
+						}
+						(*r_data)["s_id"] = util.EncodeId((*r_data)["_id"].(string))
+						(*r_data)["sourceinfoid"] = util.EncodeId((*r_data)["sourceinfoid"].(string))
+						delete(v, "_id")
+						pjtMap[(*r_data)["projectname"].(string)] = true
+						ArrPS = append(ArrPS, v)
+					}
+				}
+				regMap.Data = ArrPS
+			} else {
+				regMap.Error_code = Error_code_1003
+				regMap.Error_msg = Error_msg_1003
+			}
+		} else {
+			regMap.Error_code = Error_code_1002
+			regMap.Error_msg = Error_msg_1002
+		}
+	} else {
+		regMap.Error_code = Error_code_1005
+		regMap.Error_msg = Error_msg_1005
+	}
+	this.ServeJson(regMap)
 }

+ 1 - 2
src/jfw/modules/bigmember/src/service/analysis/decision.go

@@ -78,8 +78,7 @@ func (this *Analysis) TrialInfo() {
 	defer qutil.Catch()
 	userId, _ := this.GetSession("userId").(string)
 	rData, errMsg := func() (interface{}, error) {
-		//userInfo, ok := db.Mgo.FindById(C_User, userId, nil)
-		baseMsg := jy.GetBigVipUserBaseMsg( this.Session(),*config.Middleground)
+		baseMsg := jy.GetBigVipUserBaseMsg(this.Session(), *config.Middleground)
 		if baseMsg == nil {
 			return -2, nil
 		}

+ 27 - 25
src/jfw/modules/bigmember/src/service/analysis/forecastproject.go

@@ -7,19 +7,18 @@ import (
 	"jy/src/jfw/modules/bigmember/src/config"
 	"jy/src/jfw/modules/bigmember/src/db"
 	"jy/src/jfw/modules/bigmember/src/util"
+	"sort"
+	"strconv"
 
 	. "app.yhyue.com/moapp/jybase/api"
 	. "app.yhyue.com/moapp/jybase/date"
 
-	"log"
-
 	qutil "app.yhyue.com/moapp/jybase/common"
 	dfa "app.yhyue.com/moapp/jybase/dfa"
 	elastic "app.yhyue.com/moapp/jybase/esv1"
 	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+	"log"
 
-	"sort"
-	"strconv"
 	"strings"
 	"time"
 )
@@ -187,7 +186,7 @@ func (this *Analysis) ForPContent() {
 				}
 			}
 			power := []int{}
-			powerMap := jy.GetBigVipUserBaseMsg( this.Session(),*config.Middleground).PowerMap
+			powerMap := jy.GetBigVipUserBaseMsg(this.Session(), *config.Middleground).PowerMap
 			for k, _ := range powerMap {
 				power = append(power, k)
 			}
@@ -234,32 +233,35 @@ func (this *Analysis) ForPList() {
 		if pageSize == 0 {
 			pageSize = 10
 		}
+		o_member_jy := &map[string]interface{}{}
 		//查库获得大会员用户的信息
-		//ao_mb, ok := db.Mgo.FindById(C_User, main_userId, `{"o_member_jy":1}`)
-		o_member_jy := jy.GetSubScribeInfo(this.Session(), db.Mgo, "m", "10000")
-		if o_member_jy != nil {
-			// list, count = getNewProjects(main_userId, pageNum)
-			//项目预测检索库
-			flist, fcount = getNewForecast(main_userId, pageNum, *o_member_jy, pageSize)
-			if pageNum == 1 {
-				if (*o_member_jy)["a_items"] != nil {
-					a_items := qutil.ObjArrToMapArr((*o_member_jy)["a_items"].([]interface{}))
-					if len(a_items) == 0 || a_items[0]["a_key"] == nil || len(a_items[0]["a_key"].([]interface{})) == 0 {
+		o_mb := config.Compatible.Select(main_userId, `{"o_member_jy":1}`)
+		if o_mb != nil && (*o_mb) != nil {
+			if (*o_mb)["o_member_jy"] != nil {
+				o_member_jy = qutil.ObjToMap((*o_mb)["o_member_jy"])
+				//项目预测检索库
+				flist, fcount = getNewForecast(main_userId, pageNum, *o_member_jy, pageSize)
+				if pageNum == 1 {
+					if (*o_member_jy)["a_items"] != nil {
+						a_items := qutil.ObjArrToMapArr((*o_member_jy)["a_items"].([]interface{}))
+						if len(a_items) == 0 || a_items[0]["a_key"] == nil || len(a_items[0]["a_key"].([]interface{})) == 0 {
+							msg = "暂无设置订阅关键词,无法进行预测"
+							code = 1
+						} else if (list == nil || len(list) == 0) && len(flist) == 0 {
+							msg = "您设置的订阅关键词无法进行预测"
+							code = 2
+						}
+					} else {
 						msg = "暂无设置订阅关键词,无法进行预测"
 						code = 1
-					} else if (list == nil || len(list) == 0) && len(flist) == 0 {
-						msg = "您设置的订阅关键词无法进行预测"
-						code = 2
 					}
-				} else {
-					msg = "暂无设置订阅关键词,无法进行预测"
-					code = 1
 				}
+
+			} else {
+				//PC端大会员 没有进行初始化
+				msg = "暂无设置订阅关键词,无法进行预测"
+				code = 1
 			}
-		} else {
-			//PC端大会员 没有进行初始化
-			msg = "暂无设置订阅关键词,无法进行预测"
-			code = 1
 		}
 		regMap.Data = map[string]interface{}{
 			"msg":        msg,

+ 75 - 75
src/jfw/modules/bigmember/src/service/bidfile/bidfile.go

@@ -1,97 +1,97 @@
 package bidfile
 
 import (
-        "jy/src/jfw/modules/bigmember/src/config"
-        "jy/src/jfw/modules/bigmember/src/db"
-        "jy/src/jfw/modules/bigmember/src/util"
-        "time"
+	"jy/src/jfw/modules/bigmember/src/config"
+	"jy/src/jfw/modules/bigmember/src/db"
+	"jy/src/jfw/modules/bigmember/src/util"
+	"time"
 
-        . "app.yhyue.com/moapp/jybase/api"
-        qu "app.yhyue.com/moapp/jybase/common"
-        . "app.yhyue.com/moapp/jybase/date"
-        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
-        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+	. "app.yhyue.com/moapp/jybase/api"
+	qu "app.yhyue.com/moapp/jybase/common"
+	. "app.yhyue.com/moapp/jybase/date"
+	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 type Bidfile struct {
-        *xweb.Action
-        history xweb.Mapper `xweb:"/bidfile/history"`
+	*xweb.Action
+	history xweb.Mapper `xweb:"/bidfile/history"`
 }
 
 // History AI中标预测历史记录
 func (b *Bidfile) History() {
-        r := func() Result {
-                userid := qu.ObjToString(b.GetSession("userId"))
-                if userid == "" {
-                        return Result{Data: nil, Error_msg: "未登录"}
-                }
-                isSub := true
-                bidfileCount := 0
-                mainid, _, member_status := util.MainUserId(b.Session())
-                if mainid == userid {
-                        isSub = false
-                }
-                //获取用户权限详情
-                power := []int{}
-                bigPower := jy.GetBigVipUserBaseMsg( b.Session(),*config.Middleground)
-                for k, _ := range bigPower.PowerMap {
-                        power = append(power, k)
-                }
-                res := db.Mysql.SelectBySql(`select explain_time,user_id from bidfile_history
+	r := func() Result {
+		userid := qu.ObjToString(b.GetSession("userId"))
+		if userid == "" {
+			return Result{Data: nil, Error_msg: "未登录"}
+		}
+		isSub := true
+		bidfileCount := 0
+		mainid, _, member_status := util.MainUserId(b.Session())
+		if mainid == userid {
+			isSub = false
+		}
+		//获取用户权限详情
+		power := []int{}
+		bigPower := jy.GetBigVipUserBaseMsg(b.Session(), *config.Middleground)
+		for k, _ := range bigPower.PowerMap {
+			power = append(power, k)
+		}
+		res := db.Mysql.SelectBySql(`select explain_time,user_id from bidfile_history
 		where main_id=?
 		and is_delete =0 and explain_time is not null order by explain_time desc`, userid)
-                userPhoneMap := map[string]string{}
-                for _, v := range *res {
-                        phone := ""
-                        use_id := qu.ObjToString(v["user_id"]) //使用人的userid
-                        if userPhoneMap[use_id] == "" {
-                                phone = GetUserPhone(use_id)
-                                userPhoneMap[use_id] = phone
-                        }
-                        v["phone"] = userPhoneMap[use_id]
-                        delete(v, "user_id")
-                }
-                bidfileCount, _ = util.IsBidfilePower(b.Session())
-                bidfileCount += 0
-                bidfile_endtime := "2021年11月15日" //目前招标文件解读到11/15到期
-                bed := GetTime("2006年01月02日", bidfile_endtime)
-                d := db.Mysql.SelectBySql(`SELECT l_endtime AS endtime FROM bigmember_service_user
+		userPhoneMap := map[string]string{}
+		for _, v := range *res {
+			phone := ""
+			use_id := qu.ObjToString(v["user_id"]) //使用人的userid
+			if userPhoneMap[use_id] == "" {
+				phone = GetUserPhone(use_id)
+				userPhoneMap[use_id] = phone
+			}
+			v["phone"] = userPhoneMap[use_id]
+			delete(v, "user_id")
+		}
+		bidfileCount, _ = util.IsBidfilePower(b.Session())
+		bidfileCount += 0
+		bidfile_endtime := "2021年11月15日" //目前招标文件解读到11/15到期
+		bed := GetTime("2006年01月02日", bidfile_endtime)
+		d := db.Mysql.SelectBySql(`SELECT l_endtime AS endtime FROM bigmember_service_user
 				WHERE s_serviceid =11 AND s_userid =? AND i_status = 0`, mainid)
-                if d != nil && len(*d) > 0 {
-                        endtime := qu.ObjToString((*d)[0]["endtime"])
-                        et := GetTime(Date_Full_Layout, endtime)
-                        if bed.After(et) {
-                                bidfile_endtime = et.Format("2006年01月02日")
-                        }
-                }
-                return Result{Data: M{
-                        "used_count":      len(*res),
-                        "surplus":         bidfileCount,
-                        "history_list":    res,
-                        "isSubCount":      isSub,
-                        "member_status":   member_status,
-                        "power":           power,
-                        "bidfile_endtime": bidfile_endtime,
-                }}
-        }()
-        b.ServeJson(r)
+		if d != nil && len(*d) > 0 {
+			endtime := qu.ObjToString((*d)[0]["endtime"])
+			et := GetTime(Date_Full_Layout, endtime)
+			if bed.After(et) {
+				bidfile_endtime = et.Format("2006年01月02日")
+			}
+		}
+		return Result{Data: M{
+			"used_count":      len(*res),
+			"surplus":         bidfileCount,
+			"history_list":    res,
+			"isSubCount":      isSub,
+			"member_status":   member_status,
+			"power":           power,
+			"bidfile_endtime": bidfile_endtime,
+		}}
+	}()
+	b.ServeJson(r)
 }
 
 //获取用户手机号
 func GetUserPhone(userid string) string {
-        data, ok := db.Mgo.FindById("user", userid, `{"s_phone":1,"s_m_phone":1}`)
-        if data != nil && len(*data) > 0 && ok {
-                s_phone := qu.ObjToString((*data)["s_phone"])
-                s_m_phone := qu.ObjToString((*data)["s_m_phone"])
-                phone := qu.If(s_phone == "", s_m_phone, s_phone)
-                if phone_str := qu.ObjToString(phone); phone_str != "" {
-                        return phone_str
-                }
-        }
-        return ""
+	data := config.Compatible.Select(userid, `{"s_phone":1,"s_m_phone":1}`)
+	if data != nil && len(*data) > 0 {
+		s_phone := qu.ObjToString((*data)["s_phone"])
+		s_m_phone := qu.ObjToString((*data)["s_m_phone"])
+		phone := qu.If(s_phone == "", s_m_phone, s_phone)
+		if phone_str := qu.ObjToString(phone); phone_str != "" {
+			return phone_str
+		}
+	}
+	return ""
 }
 
 func GetTime(layout, t string) time.Time {
-        times, _ := time.ParseInLocation(layout, t, time.Local)
-        return times
+	times, _ := time.ParseInLocation(layout, t, time.Local)
+	return times
 }

+ 1 - 25
src/jfw/modules/bigmember/src/service/follow/projectPdf.go

@@ -123,35 +123,11 @@ func (this *FollowProject) GetPdfDetail() {
 
 //校验是否是付费用户
 func checkPay(session *httpsession.Session) bool {
-	bigPower := jy.GetBigVipUserBaseMsg( session,*config.Middleground)
+	bigPower := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
 	//userId := qutil.InterfaceToStr(session.Get("userId"))
 	if bigPower.Status > 0 || bigPower.VipStatus > 0 {
 		return true
 	}
-	//校验是否为商机管理用户
-	/*phone := ""
-	u, ok := db.Mgo.FindById(C_User, userId, `{"s_phone":1,"s_m_phone":1}`)
-	if ok && u != nil {
-		if s_phone, _ := (*u)["s_phone"].(string); s_phone != "" {
-			phone = s_phone
-		} else if s_m_phone, _ := (*u)["s_m_phone"].(string); s_m_phone != "" {
-			phone = s_m_phone
-		}
-	}
-	if phone == "" {
-		return false
-	}
-	res := db.Mysql.SelectBySql(`SELECT i.name,i.phone,i.status,i.auth_status,u.power FROM entniche_user u LEFT JOIN entniche_info i
-			ON u.ent_id=i.id
-			WHERE u.phone=?
-			ORDER BY  i.status DESC,i.auth_status DESC, CASE WHEN i.phone=? THEN 0  ELSE 1 END  ASC`, phone, phone)
-	if res != nil && len(*res) > 0 {
-		for _, v := range *res {
-			if qutil.IntAll(v["status"]) == 1 && qutil.IntAll(v["power"]) == 1 {
-				return true
-			}
-		}
-	}*/
 	return bigPower.IsEntService
 }
 

+ 64 - 109
src/jfw/modules/bigmember/src/service/push/push.go

@@ -38,7 +38,7 @@ type pushSet struct {
 //后期
 //4.6.0修改 只把有权益的存入map返给前端, k:权益 v:是否开启
 func (a *Action) Items() {
-	bigMsg := jy.GetBigVipUserBaseMsg( a.Session(), *config.Middleground)
+	bigMsg := jy.GetBigVipUserBaseMsg(a.Session(), *config.Middleground)
 	subScribeInfo := jy.GetSubScribeInfo(a.Session(), Mgo, "m", "10000")
 	data := M{}
 	data["super_subscribe"] = true //超级订阅
@@ -58,14 +58,11 @@ func (a *Action) Items() {
 }
 func (a *Action) Detail() {
 	userId, _ := a.GetSession("userId").(string)
-	entId := util.Int64All(a.GetSession("entId"))
-	entUserId := util.Int64All(a.GetSession("entUserId "))
-	positionType := util.Int64All(a.GetSession("positionType "))
 	if !R.CheckReqParam(a.ResponseWriter, a.Request, "item") {
 		return
 	}
 	var data M
-	bigMsg := jy.GetBigVipUserBaseMsg( a.Session(), *config.Middleground)
+	bigMsg := jy.GetBigVipUserBaseMsg(a.Session(), *config.Middleground)
 	switch a.GetString("item") {
 	case "member_subscribe":
 		o_member_jy := jy.GetSubScribeInfo(a.Session(), Mgo, "m", "10000")
@@ -84,8 +81,8 @@ func (a *Action) Detail() {
 			"wxpush":         util.IntAll((*o_member_jy)["i_wxpush"]),
 		}
 		power := []int{}
-		BigMsg := jy.GetBigVipUserBaseMsg( a.Session(),*config.Middleground)
-		for k,_ := range BigMsg.PowerMap {
+		BigMsg := jy.GetBigVipUserBaseMsg(a.Session(), *config.Middleground)
+		for k, _ := range BigMsg.PowerMap {
 			power = append(power, k)
 		}
 		data["power"] = power
@@ -140,17 +137,7 @@ func (a *Action) Detail() {
 			"mail":     mail,
 		}
 	case "follow_ent":
-		user := &map[string]interface{}{}
-		if positionType == 0 {
-			user, _ = Mgo.FindById("user", userId, `{"s_myemail":1,"o_follow_ent":1}`)
-		} else {
-			query := map[string]interface{}{
-				"i_userid": entUserId,
-				"i_entid":  entId,
-				"i_type":   1,
-			}
-			user, _ = Mgo.FindOneByField("entniche_rule", query, `{"s_myemail":1,"o_follow_ent":1}`)
-		}
+		user := config.Compatible.Select(userId, `{"s_myemail":1,"o_follow_ent":1}`)
 		o_follow_ent, _ := (*user)["o_follow_ent"].(map[string]interface{})
 		apppush := util.IntAll(o_follow_ent["i_apppush"])
 		mailpush := util.IntAll(o_follow_ent["i_mailpush"])
@@ -167,18 +154,7 @@ func (a *Action) Detail() {
 			"mail":     mail,
 		}
 	case "follow_project":
-		user := &map[string]interface{}{}
-		if positionType == 0 {
-			user, _ = Mgo.FindById("user", userId, `{"s_myemail":1,"o_follow_project":1}`)
-		} else {
-			query := map[string]interface{}{
-				"i_userid": entUserId,
-				"i_entid":  entId,
-				"i_type":   1,
-			}
-			user, _ = Mgo.FindOneByField("entniche_rule", query, `{"s_myemail":1,"o_follow_project":1}`)
-		}
-		//user, _ := Mgo.FindById("user", userId, `{"s_myemail":1,"o_follow_project":1}`)
+		user := config.Compatible.Select(userId, `{"s_myemail":1,"o_follow_project":1}`)
 		o_follow_project, _ := (*user)["o_follow_project"].(map[string]interface{})
 		apppush := util.IntAll(o_follow_project["i_apppush"])
 		mailpush := util.IntAll(o_follow_project["i_mailpush"])
@@ -195,62 +171,62 @@ func (a *Action) Detail() {
 			"mail":     mail,
 		}
 		/* case "entniche":
-		                //user, _ := Mgo.FindById("user", userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1,"o_entniche":1}`)
-		                //o_entniche, _ := (*user)["o_entniche"].(map[string]interface{})
-		                o_entniche := jy.GetSubScribeInfo(a.Session(), Mgo, "f", "10000")
-		                ratemode, apppush, mailpush := 0, 0, 0
-		                mail := ""
-		                flag := true
-		                if len(*o_entniche) == 0&&  {
-		                        //phone:=bigMsg.Data.Free. 后期
-		                        phone := ""
-		                        entniche_user := Mysql.SelectBySql(`select a.id,a.ent_id,a.mail,b.model,c.dept_id from entniche_user a
-						inner join entniche_info b on (a.phone=? and b.status=1 and a.ent_id=b.id)
-						inner join entniche_department_user c on (a.id=c.user_id)`, phone)
-		                        if len(*entniche_user) == 1 {
-		                                if model := util.IntAll((*entniche_user)[0]["model"]); model > 0 {
-		                                        mail, _ = (*entniche_user)[0]["mail"].(string)
-		                                        var query map[string]interface{}
-		                                        query = map[string]interface{}{
-		                                                "i_entid":  entId,
-		                                                "i_userid": entUserId,
-		                                        }
-		                                        if query != nil {
-		                                                entniche_rule, _ := Mgo.FindOneByField("entniche_rule", query, `{"o_entniche":1}`)
-		                                                if entniche_rule != nil && len(*entniche_rule) > 0 {
-		                                                        flag = false
-		                                                        obj, _ := (*entniche_rule)["o_entniche"].(map[string]interface{})
-		                                                        ratemode = util.IntAll(obj["i_ratemode"])
-		                                                        apppush = util.IntAll(obj["i_apppush"])
-		                                                        mailpush = util.IntAll(obj["i_mailpush"])
-		                                                }
-		                                        }
-		                                }
-		                        }
-		                }
-		                if mail == "" {
-		                        mail, _ = (*o_entniche)["s_email"].(string)
-		                }
-		                if mail == "" {
-		                        mail = bigMsg.Data.Free.Mail
-		                }
-		                if flag {
-		                        ratemode = util.IntAll((*o_entniche)["i_ratemode"])
-		                        apppush = util.IntAll((*o_entniche)["i_apppush"])
-		                        mailpush = util.IntAll((*o_entniche)["i_mailpush"])
-		                }
-		                if ratemode == 0 {
-		                        ratemode = 2
-		                }
-		                if apppush == 0 && mailpush == 0 {
-		                        apppush = 1
-		                }
-		                data = M{
-		                        "ratemode": ratemode,
-		                        "apppush":  apppush,
-		                        "mailpush": mailpush,
-		                        "mail":     mail,
-		                }*/
+		                   //user, _ := Mgo.FindById("user", userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1,"o_entniche":1}`)
+		                   //o_entniche, _ := (*user)["o_entniche"].(map[string]interface{})
+		                   o_entniche := jy.GetSubScribeInfo(a.Session(), Mgo, "f", "10000")
+		                   ratemode, apppush, mailpush := 0, 0, 0
+		                   mail := ""
+		                   flag := true
+		                   if len(*o_entniche) == 0&&  {
+		                           //phone:=bigMsg.Data.Free. 后期
+		                           phone := ""
+		                           entniche_user := Mysql.SelectBySql(`select a.id,a.ent_id,a.mail,b.model,c.dept_id from entniche_user a
+		   				inner join entniche_info b on (a.phone=? and b.status=1 and a.ent_id=b.id)
+		   				inner join entniche_department_user c on (a.id=c.user_id)`, phone)
+		                           if len(*entniche_user) == 1 {
+		                                   if model := util.IntAll((*entniche_user)[0]["model"]); model > 0 {
+		                                           mail, _ = (*entniche_user)[0]["mail"].(string)
+		                                           var query map[string]interface{}
+		                                           query = map[string]interface{}{
+		                                                   "i_entid":  entId,
+		                                                   "i_userid": entUserId,
+		                                           }
+		                                           if query != nil {
+		                                                   entniche_rule, _ := Mgo.FindOneByField("entniche_rule", query, `{"o_entniche":1}`)
+		                                                   if entniche_rule != nil && len(*entniche_rule) > 0 {
+		                                                           flag = false
+		                                                           obj, _ := (*entniche_rule)["o_entniche"].(map[string]interface{})
+		                                                           ratemode = util.IntAll(obj["i_ratemode"])
+		                                                           apppush = util.IntAll(obj["i_apppush"])
+		                                                           mailpush = util.IntAll(obj["i_mailpush"])
+		                                                   }
+		                                           }
+		                                   }
+		                           }
+		                   }
+		                   if mail == "" {
+		                           mail, _ = (*o_entniche)["s_email"].(string)
+		                   }
+		                   if mail == "" {
+		                           mail = bigMsg.Data.Free.Mail
+		                   }
+		                   if flag {
+		                           ratemode = util.IntAll((*o_entniche)["i_ratemode"])
+		                           apppush = util.IntAll((*o_entniche)["i_apppush"])
+		                           mailpush = util.IntAll((*o_entniche)["i_mailpush"])
+		                   }
+		                   if ratemode == 0 {
+		                           ratemode = 2
+		                   }
+		                   if apppush == 0 && mailpush == 0 {
+		                           apppush = 1
+		                   }
+		                   data = M{
+		                           "ratemode": ratemode,
+		                           "apppush":  apppush,
+		                           "mailpush": mailpush,
+		                           "mail":     mail,
+		                   }*/
 	default:
 		R.InvalidReqParam(a.ResponseWriter, a.Request, "item")
 		return
@@ -260,7 +236,6 @@ func (a *Action) Detail() {
 
 func (a *Action) Update() {
 	userId, _ := a.GetSession("userId").(string)
-	positionType := util.Int64All(a.GetSession("positionType"))
 	ps := pushSet{
 		Subscribe:           -1,
 		Follow_project:      -1,
@@ -283,9 +258,6 @@ func (a *Action) Update() {
 		switch ps.Item {
 		case "member_subscribe":
 			mType := "o_member_jy"
-			if positionType == 1 {
-				mType = "o_entniche"
-			}
 			set = map[string]interface{}{
 				fmt.Sprintf("%s.i_ratemode", mType):   ps.Ratemode,
 				fmt.Sprintf("%s.i_ratemode", mType):   ps.Apppush,
@@ -314,9 +286,6 @@ func (a *Action) Update() {
 			}
 		case "super_subscribe":
 			vType := "o_vipjy"
-			if positionType == 1 {
-				vType = "o_entniche"
-			}
 			set = map[string]interface{}{
 				fmt.Sprintf("%s.i_subscribe", vType):      ps.Subscribe,      //订阅开关
 				fmt.Sprintf("%s.i_follow_ent", vType):     ps.Follow_ent,     //关注企业推送开关
@@ -330,9 +299,6 @@ func (a *Action) Update() {
 			}
 		case "free_subscribe":
 			ftype := "o_jy"
-			if positionType == 1 {
-				ftype = "o_entniche"
-			}
 			set = map[string]interface{}{
 				fmt.Sprintf("%s.i_apppush", ftype):    ps.Apppush,
 				fmt.Sprintf("%s.i_mailpush", ftype):   ps.Mailpush,
@@ -357,19 +323,8 @@ func (a *Action) Update() {
 			R.InvalidReqParam(a.ResponseWriter, a.Request, "item")
 			return
 		}
-		if positionType == 0 {
-			if set != nil && Mgo.UpdateById("user", userId, map[string]interface{}{"$set": set}) {
-				status = 1
-			}
-		} else {
-			query := map[string]interface{}{
-				"i_userid": util.Int64All(a.GetSession("entUserId")),
-				"i_entid":  util.Int64All(a.GetSession("entId")),
-				"i_type":   1,
-			}
-			if set != nil && Mgo.Update("entniche_rule", query, map[string]interface{}{"$set": set}, true, false) {
-				status = 1
-			}
+		if set != nil && config.Compatible.Update(userId, map[string]interface{}{"$set": set}) {
+			status = 1
 		}
 	} else {
 		log.Println("修改推送设置 json.Unmarshal 出错:", err)

+ 186 - 200
src/jfw/modules/bigmember/src/service/report/marketAnalysis.go

@@ -1,232 +1,218 @@
 package report
 
 import (
-        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-        "fmt"
-        "jy/src/jfw/modules/bigmember/src/config"
-        "jy/src/jfw/modules/bigmember/src/db"
-        "jy/src/jfw/modules/bigmember/src/entity/marketAnalysis"
-        "jy/src/jfw/modules/bigmember/src/util"
-        "log"
-        "time"
+	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+	"fmt"
+	"jy/src/jfw/modules/bigmember/src/config"
+	"jy/src/jfw/modules/bigmember/src/entity/marketAnalysis"
+	"jy/src/jfw/modules/bigmember/src/util"
+	"log"
+	"time"
 
-        . "app.yhyue.com/moapp/jybase/api"
-        qutil "app.yhyue.com/moapp/jybase/common"
-        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
-        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+	. "app.yhyue.com/moapp/jybase/api"
+	qutil "app.yhyue.com/moapp/jybase/common"
+	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 // MarketAnalysis 市场分析报告路由定义
 type MarketAnalysis struct {
-        *xweb.Action
-        doAnalysis        xweb.Mapper `xweb:"/marketAnalysis/doAnalysis"`        //市场分析分析查询(此接口只做为保存查询条件,返回记录id)
-        getAnalysisResult xweb.Mapper `xweb:"/marketAnalysis/getAnalysisResult"` //获取分析报告结果(根据记录id查询报告结果)
-        analysisHistory   xweb.Mapper `xweb:"/marketAnalysis/analysisHistory"`   //市场分析报告历史记录
-        analysisKeyWord   xweb.Mapper `xweb:"/marketAnalysis/analysisKeyWord"`   //市场分析报告订阅词
+	*xweb.Action
+	doAnalysis        xweb.Mapper `xweb:"/marketAnalysis/doAnalysis"`        //市场分析分析查询(此接口只做为保存查询条件,返回记录id)
+	getAnalysisResult xweb.Mapper `xweb:"/marketAnalysis/getAnalysisResult"` //获取分析报告结果(根据记录id查询报告结果)
+	analysisHistory   xweb.Mapper `xweb:"/marketAnalysis/analysisHistory"`   //市场分析报告历史记录
+	analysisKeyWord   xweb.Mapper `xweb:"/marketAnalysis/analysisKeyWord"`   //市场分析报告订阅词
 }
 
 // checkPower 权限校验
 func checkPower(session *httpsession.Session) (string, error) {
-        userId := qutil.InterfaceToStr(session.Get("base_user_id"))
-        if userId == "" {
-                return "", fmt.Errorf("未登录")
-        }
-        //仅购买《周报/月报/定制化市场分析报告》的大会员有权限
-        bigMeg := jy.GetBigVipUserBaseMsg( session,*config.Middleground)
-        return bigMeg.Pid, nil
+	userId := qutil.InterfaceToStr(session.Get("base_user_id"))
+	if userId == "" {
+		return "", fmt.Errorf("未登录")
+	}
+	//仅购买《周报/月报/定制化市场分析报告》的大会员有权限
+	bigMeg := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
+	return bigMeg.Pid, nil
 }
 
 // DoAnalysis 开始分析报告
 func (this *MarketAnalysis) DoAnalysis() {
-        userId := qutil.ObjToString(this.GetSession("userId"))
-        rData, errMsg := func() (interface{}, error) {
-                pid, powerErr := checkPower(this.Session())
-                if powerErr != nil {
-                        return nil, powerErr
-                }
-                //接受参数
-                bParam := marketAnalysis.AnalysisRequestParam{
-                        KeysItemsStr:   this.GetString("keysItems"),      //分析内容【字符串】结构和o_member_jy.a_items保持一致
-                        RangeTime:      this.GetString("rangeTime"),      //时间【字符串】 时间戳开始-结束时间戳
-                        RangeTimeExtra: this.GetString("rangeTimeExtra"), //时间【字符串】 时间戳开始-结束时间戳
-                        Area:           this.GetString("area"),           //省份【字符串】多个省份用逗号拼接
-                        Industry:       this.GetString("industry"),       //行业【字符串】多个行业用逗号拼接
-                        BuyerClass:     this.GetString("buyerclass"),     //采购单位类型【字符串】多个采购单位类型用逗号拼接
-                }
-                mae := &marketAnalysis.MarketAnalysisEntity{BaseParam: bParam, UId: userId, Pid: pid}
-                if err := mae.ForMatData(); err != nil {
-                        return nil, err
-                }
-                //存储分析记录
-                if err := mae.SaveAnalysisRecord(); err != nil {
-                        return nil, err
-                }
-                return util.EncodeId(mae.MgoRecordId), nil
-        }()
-        if errMsg != nil {
-                log.Printf("%s MarketAnalysis DoAnalysis Error:%s\n", userId, errMsg.Error())
-        }
-        this.ServeJson(NewResult(rData, errMsg))
+	userId := qutil.ObjToString(this.GetSession("userId"))
+	rData, errMsg := func() (interface{}, error) {
+		pid, powerErr := checkPower(this.Session())
+		if powerErr != nil {
+			return nil, powerErr
+		}
+		//接受参数
+		bParam := marketAnalysis.AnalysisRequestParam{
+			KeysItemsStr:   this.GetString("keysItems"),      //分析内容【字符串】结构和o_member_jy.a_items保持一致
+			RangeTime:      this.GetString("rangeTime"),      //时间【字符串】 时间戳开始-结束时间戳
+			RangeTimeExtra: this.GetString("rangeTimeExtra"), //时间【字符串】 时间戳开始-结束时间戳
+			Area:           this.GetString("area"),           //省份【字符串】多个省份用逗号拼接
+			Industry:       this.GetString("industry"),       //行业【字符串】多个行业用逗号拼接
+			BuyerClass:     this.GetString("buyerclass"),     //采购单位类型【字符串】多个采购单位类型用逗号拼接
+		}
+		mae := &marketAnalysis.MarketAnalysisEntity{BaseParam: bParam, UId: userId, Pid: pid}
+		if err := mae.ForMatData(); err != nil {
+			return nil, err
+		}
+		//存储分析记录
+		if err := mae.SaveAnalysisRecord(); err != nil {
+			return nil, err
+		}
+		return util.EncodeId(mae.MgoRecordId), nil
+	}()
+	if errMsg != nil {
+		log.Printf("%s MarketAnalysis DoAnalysis Error:%s\n", userId, errMsg.Error())
+	}
+	this.ServeJson(NewResult(rData, errMsg))
 }
 
 // GetAnalysisResult 获取分析结果
 func (this *MarketAnalysis) GetAnalysisResult() {
-        userId := qutil.ObjToString(this.GetSession("userId"))
-        rData, errMsg := func() (interface{}, error) {
-                pid, powerErr := checkPower(this.Session())
-                if powerErr != nil {
-                        return nil, powerErr
-                }
-                mae := &marketAnalysis.MarketAnalysisEntity{MgoRecordId: util.DecodeId(this.GetString("rid")), UId: userId, Pid: pid}
-                if err := mae.GetAnalysisFromMgoDb(); err != nil {
-                        return nil, err
-                }
-                //二次校验数据
-                if err := mae.ForMatData(); err != nil {
-                        return nil, err
-                }
-                //查询
-                flag, _ := this.GetInteger("flag")
-                rData, err := mae.GetPartResult(flag)
-                if err != nil {
-                        return nil, err
-                }
-                return rData, nil
-        }()
-        if errMsg != nil {
-                log.Printf("%s MarketAnalysis GetAnalysisResult Error:%s\n", userId, errMsg.Error())
-        }
-        this.ServeJson(NewResult(rData, errMsg))
+	userId := qutil.ObjToString(this.GetSession("userId"))
+	rData, errMsg := func() (interface{}, error) {
+		pid, powerErr := checkPower(this.Session())
+		if powerErr != nil {
+			return nil, powerErr
+		}
+		mae := &marketAnalysis.MarketAnalysisEntity{MgoRecordId: util.DecodeId(this.GetString("rid")), UId: userId, Pid: pid}
+		if err := mae.GetAnalysisFromMgoDb(); err != nil {
+			return nil, err
+		}
+		//二次校验数据
+		if err := mae.ForMatData(); err != nil {
+			return nil, err
+		}
+		//查询
+		flag, _ := this.GetInteger("flag")
+		rData, err := mae.GetPartResult(flag)
+		if err != nil {
+			return nil, err
+		}
+		return rData, nil
+	}()
+	if errMsg != nil {
+		log.Printf("%s MarketAnalysis GetAnalysisResult Error:%s\n", userId, errMsg.Error())
+	}
+	this.ServeJson(NewResult(rData, errMsg))
 }
 
 // AnalysisHistory 分析报告历史
 func (this *MarketAnalysis) AnalysisHistory() {
-        userId := qutil.ObjToString(this.GetSession("userId"))
-        rData, errMsg := func() (interface{}, error) {
-                pid, powerErr := checkPower(this.Session())
-                if powerErr != nil {
-                        return nil, powerErr
-                }
-                //接受参数
-                pageNum, pageNumErr := this.GetInteger("pageNum") //页码
-                if pageNumErr != nil {
-                        pageNum = 1
-                }
-                pageSize, pageSizeErr := this.GetInteger("pageSize") //每页数量
-                if pageSizeErr != nil {
-                        pageSize = 10
-                }
-                mae := &marketAnalysis.MarketAnalysisEntity{UId: userId, Pid: pid}
-                total, list := mae.GetRecordList(pageNum, pageSize)
-                return map[string]interface{}{
-                        "total": total,
-                        "list":  list,
-                }, nil
-        }()
-        if errMsg != nil {
-                log.Printf("%s MarketAnalysis AnalysisHistory Error:%s\n", userId, errMsg.Error())
-        }
-        this.ServeJson(NewResult(rData, errMsg))
+	userId := qutil.ObjToString(this.GetSession("userId"))
+	rData, errMsg := func() (interface{}, error) {
+		pid, powerErr := checkPower(this.Session())
+		if powerErr != nil {
+			return nil, powerErr
+		}
+		//接受参数
+		pageNum, pageNumErr := this.GetInteger("pageNum") //页码
+		if pageNumErr != nil {
+			pageNum = 1
+		}
+		pageSize, pageSizeErr := this.GetInteger("pageSize") //每页数量
+		if pageSizeErr != nil {
+			pageSize = 10
+		}
+		mae := &marketAnalysis.MarketAnalysisEntity{UId: userId, Pid: pid}
+		total, list := mae.GetRecordList(pageNum, pageSize)
+		return map[string]interface{}{
+			"total": total,
+			"list":  list,
+		}, nil
+	}()
+	if errMsg != nil {
+		log.Printf("%s MarketAnalysis AnalysisHistory Error:%s\n", userId, errMsg.Error())
+	}
+	this.ServeJson(NewResult(rData, errMsg))
 }
 
 func (this *MarketAnalysis) AnalysisKeyWord() {
-        r := func() Result {
-                userid := qutil.ObjToString(this.GetSession("userId"))
-                if userid == "" {
-                        return Result{Data: M{"status": -1}, Error_msg: "未登录"}
-                }
-                mainid, _, _ := util.MainUserId(this.Session())
-                d := map[string]interface{}{
-                        "member_status": 0,
-                }
-                i_member_status := int64(0)
-                i_vip_status := int64(0)
-                o_member_jy := &map[string]interface{}{}
-                oJy := &map[string]interface{}{}
-                vipJy := &map[string]interface{}{}
-                i_member_starttime := int(0)
-                i_member_endtime := int(0)
-                l_vip_starttime := int(0)
-                l_vip_endtime := int(0)
-                registedate := int64(0)
-                positionType := qutil.IntAll(this.GetSession("positionType "))
-                if positionType == 0 {
-                        data, _ := db.Mgo.FindById(C_User, mainid, `{"o_jy":1,"o_vipjy":1,"i_member_starttime":1,"i_member_endtime":1,"i_member_status":1,"l_vip_endtime":1,"l_vip_starttime":1,"o_member_jy":1,"i_vip_status":1,:1,"l_registedate":1}`)
-                        i_member_status = qutil.Int64All((*data)["i_member_status"])
-                        i_vip_status = qutil.Int64All((*data)["i_vip_status"])
-                        o_member_jy = qutil.ObjToMap((*data)["o_member_jy"])
-                        oJy = qutil.ObjToMap((*data)["o_jy"])      //免费用户关键词
-                        vipJy = qutil.ObjToMap((*data)["o_vipjy"]) //超级订阅关键词
-                        i_member_starttime = qutil.IntAll((*data)["i_member_starttime"])
-                        i_member_endtime = qutil.IntAll((*data)["i_member_endtime"])
-                        registedate = (*data)["l_registedate"].(int64)
-                } else {
-                        bigVipBaseMsg := jy.GetBigVipUserBaseMsg( this.Session(), *config.Middleground)
-                        i_member_status = bigVipBaseMsg.Data.Member.Status
-                        i_vip_status = bigVipBaseMsg.Data.Member.Status
-                        o_member_jy = jy.GetSubScribeInfo(this.Session(), db.Mgo, "m", "10000")
-                        oJy = jy.GetSubScribeInfo(this.Session(), db.Mgo, "f", "10000")   //免费用户关键词
-                        vipJy = jy.GetSubScribeInfo(this.Session(), db.Mgo, "v", "10000") //超级订阅关键词
-                        l_vip_starttime = qutil.IntAll(bigVipBaseMsg.Data.Vip.StartTime)
-                        l_vip_endtime = qutil.IntAll(bigVipBaseMsg.Data.Vip.EndTime)
-                        registedate = bigVipBaseMsg.Registedate
-                }
-                if i_member_status > 0 {
-                        btip, _ := (*o_member_jy)["b_keytip"].(bool)
-                        KeyWord(btip, i_member_status, i_member_starttime, i_member_endtime, registedate, *o_member_jy, d)
-                } else if i_vip_status > 0 {
-                        btip, _ := (*vipJy)["b_keytip"].(bool)
-                        KeyWord(btip, i_vip_status, l_vip_starttime, l_vip_endtime, registedate, (*vipJy), d)
-                } else {
-                        a_key, _ := (*oJy)["a_key"].([]interface{})
-                        if a_key != nil && len(a_key) > 0 {
-                                //免费用户关键词格式统一
-                                arrMap := map[string]interface{}{
-                                        "s_item": "未分类",
-                                        "a_key":  (*oJy)["a_key"],
-                                }
-                                (*oJy)["a_items"] = []map[string]interface{}{arrMap}
-                                d["member_jy"] = oJy
-                                d["key_max_length"] = config.Config.KeyMaxLength
-                        }
-                }
-                return Result{Data: d}
-        }()
-        this.ServeJson(r)
+	r := func() Result {
+		userid := qutil.ObjToString(this.GetSession("userId"))
+		if userid == "" {
+			return Result{Data: M{"status": -1}, Error_msg: "未登录"}
+		}
+		mainid, _, _ := util.MainUserId(this.Session())
+		d := map[string]interface{}{
+			"member_status": 0,
+		}
+		i_member_status := int64(0)
+		i_vip_status := int64(0)
+		o_member_jy := &map[string]interface{}{}
+		oJy := &map[string]interface{}{}
+		vipJy := &map[string]interface{}{}
+		i_member_starttime := int(0)
+		i_member_endtime := int(0)
+		l_vip_starttime := int(0)
+		l_vip_endtime := int(0)
+		registedate := int64(0)
+		data := config.Compatible.Select(mainid, `{"o_jy":1,"o_vipjy":1,"i_member_starttime":1,"i_member_endtime":1,"i_member_status":1,"l_vip_endtime":1,"l_vip_starttime":1,"o_member_jy":1,"i_vip_status":1,:1,"l_registedate":1}`)
+		i_member_status = qutil.Int64All((*data)["i_member_status"])
+		i_vip_status = qutil.Int64All((*data)["i_vip_status"])
+		o_member_jy = qutil.ObjToMap((*data)["o_member_jy"])
+		oJy = qutil.ObjToMap((*data)["o_jy"])      //免费用户关键词
+		vipJy = qutil.ObjToMap((*data)["o_vipjy"]) //超级订阅关键词
+		i_member_starttime = qutil.IntAll((*data)["i_member_starttime"])
+		i_member_endtime = qutil.IntAll((*data)["i_member_endtime"])
+		registedate = (*data)["l_registedate"].(int64)
+		if i_member_status > 0 {
+			btip, _ := (*o_member_jy)["b_keytip"].(bool)
+			KeyWord(btip, i_member_status, i_member_starttime, i_member_endtime, registedate, *o_member_jy, d)
+		} else if i_vip_status > 0 {
+			btip, _ := (*vipJy)["b_keytip"].(bool)
+			KeyWord(btip, i_vip_status, l_vip_starttime, l_vip_endtime, registedate, (*vipJy), d)
+		} else {
+			a_key, _ := (*oJy)["a_key"].([]interface{})
+			if a_key != nil && len(a_key) > 0 {
+				//免费用户关键词格式统一
+				arrMap := map[string]interface{}{
+					"s_item": "未分类",
+					"a_key":  (*oJy)["a_key"],
+				}
+				(*oJy)["a_items"] = []map[string]interface{}{arrMap}
+				d["member_jy"] = oJy
+				d["key_max_length"] = config.Config.KeyMaxLength
+			}
+		}
+		return Result{Data: d}
+	}()
+	this.ServeJson(r)
 }
 
 func KeyWord(btip bool, status int64, i_member_starttime, i_member_endtime int, regtime int64, o_member_jy, d map[string]interface{}) {
-        //是否展示附加词合并
-        appendK_bl := false
-        if !btip && status > 0 && o_member_jy != nil && len(o_member_jy) > 0 {
-                if o_member_jy["a_items"] != nil {
-                        for _, v := range o_member_jy["a_items"].([]interface{}) {
-                                tmp := qutil.ObjToMap(v.(map[string]interface{}))
-                                a_key, _ := (*tmp)["a_key"].([]interface{})
-                                for _, n := range a_key {
-                                        ntmp := qutil.ObjToMap(n.(interface{}))
-                                        if (*ntmp)["appendkey"] != nil && (*ntmp)["updatetime"] == nil {
-                                                appendkey := qutil.ObjArrToStringArr((*ntmp)["appendkey"].([]interface{}))
-                                                if len(appendkey) > 0 {
-                                                        appendK_bl = true
-                                                }
-                                        }
-                                }
-                        }
-                }
+	//是否展示附加词合并
+	appendK_bl := false
+	if !btip && status > 0 && o_member_jy != nil && len(o_member_jy) > 0 {
+		if o_member_jy["a_items"] != nil {
+			for _, v := range o_member_jy["a_items"].([]interface{}) {
+				tmp := qutil.ObjToMap(v.(map[string]interface{}))
+				a_key, _ := (*tmp)["a_key"].([]interface{})
+				for _, n := range a_key {
+					ntmp := qutil.ObjToMap(n.(interface{}))
+					if (*ntmp)["appendkey"] != nil && (*ntmp)["updatetime"] == nil {
+						appendkey := qutil.ObjArrToStringArr((*ntmp)["appendkey"].([]interface{}))
+						if len(appendkey) > 0 {
+							appendK_bl = true
+						}
+					}
+				}
+			}
+		}
 
-                //订阅设置优化版本上线之前的用户弹窗提醒
-                optime := time.Unix(config.Config.OldSubscribeMoveTip, 0)
-                if time.Unix(regtime, 0).Before(optime) && appendK_bl {
-                        o_member_jy["b_keytip"] = false
-                } else {
-                        o_member_jy["b_keytip"] = true
-                }
-        }
-        d["member_jy"] = o_member_jy
-        d["member_status"] = status
-        d["member_starttime"] = i_member_starttime
-        d["member_endtime"] = i_member_endtime
-        //d["member_jy"] = qu.ObjToMap((*data)["o_member_jy"])
-        d["key_max_length"] = config.Config.KeyMaxLength
+		//订阅设置优化版本上线之前的用户弹窗提醒
+		optime := time.Unix(config.Config.OldSubscribeMoveTip, 0)
+		if time.Unix(regtime, 0).Before(optime) && appendK_bl {
+			o_member_jy["b_keytip"] = false
+		} else {
+			o_member_jy["b_keytip"] = true
+		}
+	}
+	d["member_jy"] = o_member_jy
+	d["member_status"] = status
+	d["member_starttime"] = i_member_starttime
+	d["member_endtime"] = i_member_endtime
+	//d["member_jy"] = qu.ObjToMap((*data)["o_member_jy"])
+	d["key_max_length"] = config.Config.KeyMaxLength
 }

+ 6 - 29
src/jfw/modules/bigmember/src/service/report/report.go

@@ -106,36 +106,13 @@ func (r *Report) Index() {
 	}
 	result["list"] = array
 	result["subscribe"] = false
-	positionType := qutil.Int64All(r.GetSession("positionType"))
 	o_mb := &map[string]interface{}{}
-	if positionType == 0 {
-		data := jy.GetBigVipUserBaseMsg(r.Session(), *config.Middleground)
-		if data.Data.Member.Pid == "" {
-			//没有父级
-			o_mb := jy.GetSubScribeInfo(r.Session(), Mgo, "m", "10000")
-			if o_mb != nil && (*o_mb)["o_member_jy"] != nil {
-				(*o_mb)["o_member_jy"] = o_mb
-			}
-		} else {
-			o_mb, ok = Mgo.FindById(C_User, userId, `{"o_member_jy":1,"s_member_mainid":1,"i_member_sub_status":1}`)
-			if ok && o_mb != nil && (*o_mb) != nil && (*o_mb)["s_member_mainid"] != nil && qutil.IntAllDef((*o_mb)["i_member_sub_status"], 0) == 1 { //如果是子账号 查询主账号信息
-				mainId := qutil.ObjToString((*o_mb)["s_member_mainid"])
-				o_mb, ok = Mgo.FindById(C_User, mainId, `{"o_member_jy":1}`)
-			}
-		}
-	} else {
-		o_mb, ok = Mgo.FindById(C_Entniche_Rule, userId, `{"o_member_jy":1,"s_member_mainid":1,"i_member_sub_status":1}`)
-		query := map[string]interface{}{
-			"i_userid": qutil.Int64All(r.GetSession("entUserId")),
-			"i_entid":  qutil.Int64All(r.GetSession("entId")),
-			"i_type":   1,
-		}
-		o_mb, ok = Mgo.FindOne(C_User, query)
-		if (*o_mb) != nil && (*o_mb)["o_member_jy"] != nil {
-			(*o_mb)["o_member_jy"] = (*o_mb)["o_entniche"]
+	user := config.Compatible.Select(userId, `{"o_member_jy":1,"i_member_status":1,"s_member_mainid":1,"i_member_sub_status":1}`)
+	if user != nil {
+		if s_member_mainid := qutil.ObjToString((*user)["s_member_mainid"]); s_member_mainid != "" && qutil.IntAll((*user)["i_member_sub_status"]) == 1 && qutil.IntAll((*user)["i_member_status"]) > 0 {
+			user, ok = Mgo.FindById("user", s_member_mainid, `{"o_member_jy":1}`)
 		}
 	}
-
 	if ok && o_mb != nil {
 		o_member_jy, _ := (*o_mb)["o_member_jy"].(map[string]interface{})
 		if o_member_jy["a_infotype"] != nil || o_member_jy["o_area"] != nil || o_member_jy["a_buyerclass"] != nil {
@@ -598,8 +575,8 @@ func isFree(userId string, positionType int64, session *httpsession.Session) boo
 func getQuery(sess *httpsession.Session) (string, string, interface{}) {
 	sessMap := sess.GetMultiple()
 	userId := qutil.ObjToString(sessMap["userId"])
-	user, ok := Mgo.FindById(C_User, userId, `{"s_phone":1,"s_m_phone":1}`)
-	if !ok || user == nil {
+	user := config.Compatible.Select(userId, `{"s_phone":1,"s_m_phone":1}`)
+	if user == nil {
 		return "", "", nil
 	}
 	phone := qutil.ObjToString((*user)["s_phone"])

+ 11 - 61
src/jfw/modules/bigmember/src/service/subscribe/subscribe.go

@@ -3,7 +3,6 @@ package subscribe
 import (
 	. "app.yhyue.com/moapp/jybase/api"
 	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/mongodb"
 	"app.yhyue.com/moapp/jybase/redis"
 	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 	"encoding/json"
@@ -49,7 +48,7 @@ func (s *Subscribe) FreeUserSubscribe() {
 	}
 	t := time.Now()
 	redisKey := fmt.Sprintf("%d_%s_%d_freeSubscription_%s", t.Year(), t.Month(), t.Day(), userId)
-	bigMsg := jy.GetBigVipUserBaseMsg( s.Session(), *config.Middleground)
+	bigMsg := jy.GetBigVipUserBaseMsg(s.Session(), *config.Middleground)
 	oJy := jy.GetSubScribeInfo(s.Session(), db.Mgo, "f", "10000")
 	//oJy, _ := (*res)["o_jy"].(map[string]interface{})
 	freeArea := true
@@ -104,7 +103,6 @@ func (s *Subscribe) SubscribeSearch() {
 	subsequentPrompt := s.GetString("subsequentPrompt")
 	key := s.GetString("key")
 	userId := s.GetSession("userId").(string)
-	positionType := qutil.Int64All(s.GetSession("positionType"))
 	if userId == "" {
 		s.ServeJson(Result{Data: nil, Error_msg: "未登录"})
 		return
@@ -119,37 +117,16 @@ func (s *Subscribe) SubscribeSearch() {
 	//暂不订阅修改
 	if isNoSubscribe == "N" {
 		aa := false
-		if positionType == 0 {
-			aa = db.Mgo.UpdateById("user", userId, bson.M{"$set": bson.M{"o_jy.l_search_prompt": search_prompt}})
-		} else {
-			query := map[string]interface{}{
-				"i_userid": qutil.Int64All(s.GetSession("entUserId")),
-				"i_entid":  qutil.Int64All(s.GetSession("entId")),
-				"i_type":   1,
-			}
-			aa = db.Mgo.Update("entniche_rule", query, bson.M{"$set": bson.M{"o_entniche.l_search_prompt": search_prompt}}, true, false)
-		}
+		aa = config.Compatible.Update(userId, bson.M{"$set": bson.M{"o_jy.l_search_prompt": search_prompt}})
 		s.ServeJson(Result{Data: M{"status": aa}})
 		return
 	}
 
 	//一键订阅修改
-	res := &map[string]interface{}{}
 	oJy := map[string]interface{}{}
 	fType := "o_jy"
-	if positionType == 0 {
-		res, _ = db.Mgo.FindById("user", userId, `{"o_jy":1,"i_ts_guide":1}`)
-		oJy, _ = (*res)["o_jy"].(map[string]interface{})
-	} else {
-		query := map[string]interface{}{
-			"i_userid": qutil.Int64All(s.GetSession("entUserId")),
-			"i_entid":  qutil.Int64All(s.GetSession("entId")),
-			"i_type":   2,
-		}
-		res, _ = db.Mgo.FindOne("entniche_rule", query)
-		oJy, _ = (*res)["o_entniche"].(map[string]interface{})
-		fType = "o_entniche"
-	}
+	res := config.Compatible.Select(userId, `{"o_jy":1,"i_ts_guide":1}`)
+	oJy, _ = (*res)["o_jy"].(map[string]interface{})
 	//获取原有订阅词
 	aKey, _ := oJy["a_key"].([]interface{})
 	if key != "" {
@@ -178,16 +155,7 @@ func (s *Subscribe) SubscribeSearch() {
 		"$set": data,
 	}
 	status := false
-	if positionType == 0 {
-		status = db.Mgo.UpdateById("user", userId, UpData)
-	} else {
-		query := map[string]interface{}{
-			"i_userid": qutil.Int64All(s.GetSession("entUserId")),
-			"i_entid":  qutil.Int64All(s.GetSession("entId")),
-			"i_type":   1,
-		}
-		status = db.Mgo.Update("entniche_rule", query, UpData, true, false)
-	}
+	status = config.Compatible.Update(userId, UpData)
 	if status && newFree == 0 {
 		if !redis.Del("other", "bigmember_power_3_"+userId) {
 			log.Println("redis delete bigmember_power ", userId)
@@ -440,31 +408,13 @@ func isRepeat(slice1 []string) bool {
 
 //修改订阅信息  parameter_name参数名  parameter参数
 func (s *Subscribe) UpdateSub(parameter_name string, parameter interface{}) bool {
-	userid := mongodb.StringTOBsonId(qutil.ObjToString(s.GetSession("userId")))
-	positionType := qutil.Int64All(s.GetSession("positionType"))
 	ok := false
-	if positionType == 0 {
-		ok = db.Mgo.Update("user", map[string]interface{}{"_id": userid}, map[string]interface{}{
-			"$set": map[string]interface{}{
-				"o_member_jy.l_modifydate":      time.Now().Unix(),
-				"o_member_jy." + parameter_name: parameter,
-			},
-		}, true, false)
-	} else {
-		entUserId := qutil.IntAll(s.GetSession("entUserId"))
-		entId := qutil.IntAll(s.GetSession("entId"))
-		query := map[string]interface{}{
-			"i_userid": entUserId,
-			"i_entid":  entId,
-			"i_type":   1,
-		}
-		ok = db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-			"$set": map[string]interface{}{
-				"o_entniche.l_modifydate":      time.Now().Unix(),
-				"o_entniche." + parameter_name: parameter,
-			},
-		}, true, false)
-	}
+	ok = config.Compatible.Update(qutil.ObjToString(s.GetSession("userId")), map[string]interface{}{
+		"$set": map[string]interface{}{
+			"o_member_jy.l_modifydate":      time.Now().Unix(),
+			"o_member_jy." + parameter_name: parameter,
+		},
+	})
 	if ok {
 		go func() {
 			db.Mgo_Log.Save("bigmember_sub_logs", map[string]interface{}{

+ 29 - 96
src/jfw/modules/bigmember/src/service/use/use.go

@@ -16,7 +16,6 @@ import (
 	qu "app.yhyue.com/moapp/jybase/common"
 	elastic "app.yhyue.com/moapp/jybase/esv1"
 	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jybase/mongodb"
 	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 
 	elastic1 "app.yhyue.com/moapp/esv1/gopkg.in/olivere/elastic.v1"
@@ -42,27 +41,11 @@ func (u *Use) SubPageMoveTip() {
 	flag := false
 	if userId := qu.ObjToString(u.GetSession("userId")); userId != "" {
 		if u.GetString("doType") == "know" { //我知道了 更新
-			positionType := qu.IntAll(u.GetSession("positionType"))
-			if positionType == 0 {
-				flag = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-					"$set": map[string]interface{}{
-						"o_member_jy.i_moveTip": 1,
-					},
-				})
-			} else {
-				entUserId := qu.IntAll(u.GetSession("entUserId"))
-				entId := qu.IntAll(u.GetSession("entId"))
-				query := map[string]interface{}{
-					"i_userid": entUserId,
-					"i_entid":  entId,
-					"i_type":   1,
-				}
-				flag = db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-					"$set": map[string]interface{}{
-						"o_entniche.i_moveTip": 1,
-					},
-				}, true, false)
-			}
+			config.Compatible.Update(userId, map[string]interface{}{
+				"$set": map[string]interface{}{
+					"o_member_jy.i_moveTip": 1,
+				},
+			})
 		} else { //查询是否提示弹框
 			bigMsg := jy.GetBigVipUserBaseMsg(u.Session(), *config.Middleground)
 			//后期需要更改
@@ -122,11 +105,6 @@ func (u *Use) Add() {
 					items[0]["s_item"] = "未分类"
 				}
 				set["business_scope"] = items //业务范围
-				/* if r, ok := db.Mgo.FindById("user", userid, `{"o_member_jy":1}`); r != nil && len(*r) > 0 && ok {
-				        rdata := qu.ObjToMap((*r)["o_member_jy"])
-				        a_items_old, _ := (*rdata)["a_items"].([]interface{}) //获取已经设置的关键词
-				        items = MergeMemberKw(qu.ObjArrToMapArr(a_items_old), items)
-				}*/
 				rdata := jy.GetSubScribeInfo(u.Session(), db.Mgo, "m", "10000")
 				if rdata != nil && len(*rdata) > 0 {
 					member_jy["a_items"] = items
@@ -178,32 +156,17 @@ func (u *Use) Add() {
 			update1 := db.Mgo.Update("member", map[string]interface{}{"userid": userid}, map[string]interface{}{
 				"$set": set,
 			}, true, false)
-			positionType := qu.Int64All(u.GetSession("positionType"))
 			update2 := false
-			if positionType == 0 {
-				update2 = db.Mgo.Update("user", map[string]interface{}{"_id": mongodb.StringTOBsonId(userid)}, map[string]interface{}{
-					"$set": map[string]interface{}{
-						"o_member_jy": member_jy,
-					},
-				}, true, false)
-			} else {
-				entUserId := qu.IntAll(u.GetSession("entUserId"))
-				entId := qu.IntAll(u.GetSession("entId"))
-				query := map[string]interface{}{
-					"i_userid": entUserId,
-					"i_entid":  entId,
-					"i_type":   1,
-				}
-				update2 = db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-					"$set": map[string]interface{}{
-						"o_entniche": member_jy,
-					},
-				}, true, false)
-			}
+			config.Compatible.Update(userid, map[string]interface{}{
+				"$set": map[string]interface{}{
+					"o_member_jy": member_jy,
+				},
+			})
 			// log.Println("use/add:", update1, update2)
 			if update1 && update2 {
 				entity.FirstInitFollowProject(userid)
-				jy.ClearBigVipUserPower(userid)
+				positionId := qu.InterfaceToStr(u.GetSession("positionId"))
+				jy.ClearBigVipUserPower(positionId)
 				return Result{Data: M{"status": 1}}
 			}
 		}
@@ -216,7 +179,6 @@ func (u *Use) Add() {
 func (u *Use) Info() {
 	r := func() Result {
 		userid := qu.ObjToString(u.GetSession("userId"))
-		positionType := qu.IntAll(u.GetSession("positionType"))
 		if userid == "" {
 			return Result{Data: M{"status": -1}, Error_msg: "未登录"}
 		}
@@ -232,21 +194,12 @@ func (u *Use) Info() {
 		regtime := int64(0)
 		i_member_starttime := int64(0)
 		i_member_endtime := int64(0)
-		if positionType == 0 {
-			data, _ := db.Mgo.FindById("user", mainid, `{"i_member_starttime":1,"i_member_endtime":1,"i_member_status":1,"o_member_jy":1,"l_registedate":1}`)
-			i_member_status = qu.Int64All((*data)["i_member_status"])
-			o_member_jy = qu.ObjToMap((*data)["o_member_jy"])
-			regtime, _ = (*data)["l_registedate"].(int64)
-			i_member_starttime = qu.Int64All((*data)["i_member_starttime"])
-			i_member_endtime = qu.Int64All((*data)["i_member_endtime"])
-		} else {
-			bigVipBaseMsg := jy.GetBigVipUserBaseMsg(u.Session(), *config.Middleground)
-			i_member_status = bigVipBaseMsg.Data.Member.Status
-			o_member_jy = jy.GetSubScribeInfo(u.Session(), db.Mgo, "m", "10000")
-			regtime = bigVipBaseMsg.Registedate
-			i_member_starttime = bigVipBaseMsg.Data.Member.StartTime
-			i_member_endtime = bigVipBaseMsg.Data.Member.EndTime
-		}
+		data := config.Compatible.Select(mainid, `{"i_member_starttime":1,"i_member_endtime":1,"i_member_status":1,"o_member_jy":1,"l_registedate":1}`)
+		i_member_status = qu.Int64All((*data)["i_member_status"])
+		o_member_jy = qu.ObjToMap((*data)["o_member_jy"])
+		regtime, _ = (*data)["l_registedate"].(int64)
+		i_member_starttime = qu.Int64All((*data)["i_member_starttime"])
+		i_member_endtime = qu.Int64All((*data)["i_member_endtime"])
 		if i_member_status != 0 {
 			//是否展示附加词合并
 			appendK_bl := false
@@ -531,21 +484,16 @@ func (u *Use) Equity() {
 				"customers": config.Config.Customers,
 			}, Error_msg: "未登录"}
 		}
-		person, ok := db.Mgo.FindOneByField("user", map[string]interface{}{
-			"_id": mongodb.StringTOBsonId(userid),
-		}, `{"s_nickname":1,"s_headimageurl":1,"s_phone":1,"i_member_sub_status":1,"i_bidfileCount":1}`)
+		person := config.Compatible.Select(userid, `{"s_nickname":1,"s_headimageurl":1,"s_phone":1,"i_member_sub_status":1,"i_bidfileCount":1}`)
 		data := jy.GetBigVipUserBaseMsg(u.Session(), *config.Middleground)
 		isSubCount := false
-		if ok && person != nil && len(*person) > 0 {
+		if person != nil && len(*person) > 0 {
 			//有父级id 且 子账号是激活状态
 			//if (*person)["s_member_mainid"] != nil && (*person)["i_member_sub_status"] != nil && qu.IntAllDef((*person)["i_member_sub_status"], 0) == 1 {
 			if data.Data.Member.Pid != "" {
 				userid = data.Data.Member.Pid //如果是子账号 则根据主账号id查询
 				isSubCount = true
-				o_member_jy := &map[string]interface{}{}
-				o_member_jy, _ = db.Mgo.FindOneByField("user", map[string]interface{}{
-					"_id": mongodb.StringTOBsonId(userid),
-				}, `{"o_member_jy":1}`)
+				o_member_jy := config.Compatible.Select(userid, `{"o_member_jy":1}`)
 				if o_member_jy != nil && len(*o_member_jy) > 0 {
 					(*person)["o_member_jy"] = o_member_jy
 				}
@@ -631,25 +579,11 @@ func (u *Use) Update() {
 				return Result{Data: M{"status": -1}, Error_msg: "企业名称不能为空"}
 			}
 			if industry := set_map["industry"]; industry != nil {
-				positionType := qu.Int64All(u.GetSession("positionType"))
-				if positionType == 0 {
-					ok2 = db.Mgo.Update("user", map[string]interface{}{"_id": mongodb.StringTOBsonId(userid)}, map[string]interface{}{
-						"$set": map[string]interface{}{
-							"o_member_jy.o_industry": qu.ObjToMap(industry),
-						},
-					}, true, false)
-				} else {
-					query := map[string]interface{}{
-						"i_userid": qu.Int64All(u.GetSession("entUserId")),
-						"i_entid":  qu.Int64All(u.GetSession("entId")),
-						"i_type":   1,
-					}
-					ok2 = db.Mgo.Update("entniche_rule", query, map[string]interface{}{"$set": map[string]interface{}{
-						"$set": map[string]interface{}{
-							"o_entniche.o_industry": qu.ObjToMap(industry),
-						}}}, true, false)
-
-				}
+				config.Compatible.Update(userid, map[string]interface{}{
+					"$set": map[string]interface{}{
+						"o_member_jy.o_industry": qu.ObjToMap(industry),
+					},
+				})
 			}
 			if ok1 && ok2 {
 				return Result{Data: M{"status": 1}}
@@ -809,8 +743,8 @@ func (u *Use) Aiused_history() {
 
 //获取当前登录用户的手机号
 func Phone(userId string) (string, string) {
-	u, ok := db.Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1}`)
-	if ok && u != nil {
+	u := config.Compatible.Select(userId, `{"s_phone":1,"s_m_phone":1}`)
+	if u != nil {
 		if s_phone, _ := (*u)["s_phone"].(string); s_phone != "" {
 			return s_phone, "s_phone"
 		} else if s_m_phone, _ := (*u)["s_m_phone"].(string); s_m_phone != "" {
@@ -861,9 +795,8 @@ func Merge(echo_map map[string]interface{}, userid string, session *httpsession.
 		m[v] = []string{}
 	}
 	//获取用户订阅信息
-	//data, _ := db.Mgo.FindById("user", userid, `{"o_jy":1,"o_vipjy":1,"i_vip_status":1}`)
 	o_vipjy := jy.GetSubScribeInfo(session, db.Mgo, "v", "10000")
-	o_jy := jy.GetSubScribeInfo(session, db.Mgo, "v", "10000")
+	o_jy := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
 	if (*o_vipjy) != nil {
 		//o_vipjy := *qu.ObjToMap((*data)["o_vipjy"])
 		//区域

+ 8 - 0
src/jfw/modules/distribution/src/config.json

@@ -28,6 +28,14 @@
       "passWord": "Topnet123",
       "maxOpenConns": 20,
       "maxIdleConns": 20
+    },
+    "base": {
+      "dbName": "base_service",
+      "address": "192.168.3.217:4000",
+      "userName": "root",
+      "passWord": "=PDT49#80Z!RVv52_z",
+      "maxOpenConns": 5,
+      "maxIdleConns": 5
     }
   },
   "mail": [

+ 4 - 1
src/jfw/modules/distribution/src/go.mod

@@ -4,7 +4,7 @@ go 1.18
 
 require (
 	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
-	app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa
+	app.yhyue.com/moapp/jypkg v0.0.0-20230210020312-75e22a7a7be4
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/gogf/gf/v2 v2.0.6
 	github.com/tealeg/xlsx v1.0.5
@@ -13,6 +13,7 @@ require (
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
 	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 // indirect
 	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 // indirect
 	bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4 // indirect
 	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230129060002-f69424aa14ba // indirect
@@ -72,11 +73,13 @@ require (
 	github.com/prometheus/procfs v0.8.0 // indirect
 	github.com/rivo/uniseg v0.2.0 // indirect
 	github.com/spaolacci/murmur3 v1.1.0 // indirect
+	github.com/thinxer/go-word2vec v0.0.0-20150917053916-5c19ec7379ed // indirect
 	github.com/xdg-go/pbkdf2 v1.0.0 // indirect
 	github.com/xdg-go/scram v1.1.1 // indirect
 	github.com/xdg-go/stringprep v1.0.3 // indirect
 	github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
 	github.com/zeromicro/go-zero v1.4.4 // indirect
+	github.com/ziutek/blas v0.0.0-20190227122918-da4ca23e90bb // indirect
 	go.etcd.io/etcd/api/v3 v3.5.5 // indirect
 	go.etcd.io/etcd/client/pkg/v3 v3.5.5 // indirect
 	go.etcd.io/etcd/client/v3 v3.5.5 // indirect

+ 8 - 2
src/jfw/modules/distribution/src/go.sum

@@ -13,11 +13,13 @@ app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tc
 app.yhyue.com/moapp/jybase v0.0.0-20230109015757-aa3d5e19b196/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a h1:wD4aWPSYdiX1cIP4lzzPD2s7fYhKa3muIf97l9tonJE=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa h1:0/2I4ubgDsRbKm7PeiVSTvYwZCK3anZQaEagsGBbI7E=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa/go.mod h1:0DqPlGxaufZlKaLoRndTWG4j3qUQqJ6MNZCmoPcMqSg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230210020312-75e22a7a7be4 h1:bzZsVBu3XOef3dDkfR3+01h8JBG1LchE+ClhUiAA9HQ=
+app.yhyue.com/moapp/jypkg v0.0.0-20230210020312-75e22a7a7be4/go.mod h1:sa5YRPqTQLOVBmpltjT21EkQ7DfJbUZFARUb4ZJ7U+k=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae h1:6rDDaz6yxvE8viTSzEBwKYOFWq14TMfuBivSazUZMz4=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
 bp.jydev.jianyu360.cn/BP/jynsq v0.0.0-20220222052708-ebc43af90698/go.mod h1:ojo/AUH9Yr1wzarEjOaNMkj1Cet/9r8IgLyba64Z52E=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 h1:cw/PdRypNFcYOk4iWAfHjIFoMzIlXUfl9XAmWujBOPY=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7/go.mod h1:7Xhygw0KBuL4h0G76FnFg4otQcA9bmOO0c8M0FCjAyQ=
 bp.jydev.jianyu360.cn/BaseService/gateway v0.0.0-20220419090715-88ddb32961be/go.mod h1:Yj4oabIGItuMoF0BXYLz2XAnF581kxgXBrvlUtIJrkI=
 bp.jydev.jianyu360.cn/BaseService/gateway v1.3.4/go.mod h1:BMLd/5wb3BIEGhnEgF9y1sJN9P5/Dw9kYsoiE9V8I9g=
 bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 h1:jeItQ6RM1T6yPWc/5i4R6h3kViD+Rm2VnIEsc1gCFJA=
@@ -1071,6 +1073,8 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
 github.com/tal-tech/go-zero v1.1.5/go.mod h1:LbN0C7/rbl2+LUWTSUYx5leXmgedeMWjt1jc3/8/zFA=
 github.com/tealeg/xlsx v1.0.5 h1:+f8oFmvY8Gw1iUXzPk+kz+4GpbDZPK1FhPiQRd+ypgE=
 github.com/tealeg/xlsx v1.0.5/go.mod h1:btRS8dz54TDnvKNosuAqxrM1QgN1udgk9O34bDCnORM=
+github.com/thinxer/go-word2vec v0.0.0-20150917053916-5c19ec7379ed h1:1+oKuPuDQ4AbN1WRMFxl9WQClH80GuZ81X/4FsOshjI=
+github.com/thinxer/go-word2vec v0.0.0-20150917053916-5c19ec7379ed/go.mod h1:WE5pZgSp3RwicfhHQmOJOexA0n4AKTzBqmnSu7R8Nbk=
 github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
 github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
 github.com/tklauser/go-sysconf v0.3.10/go.mod h1:C8XykCvCb+Gn0oNCWPIlcb0RuglQTYaQ2hGm7jmxEFk=
@@ -1113,6 +1117,8 @@ github.com/zeromicro/go-zero v1.4.0/go.mod h1:1amLn98K7c6FLntb9f8hdmq26ajtolOg4D
 github.com/zeromicro/go-zero v1.4.3/go.mod h1:UmDjuW7LHd9j7+nnnPBcXF0HLNmjJw6OjHPTlSp7X7Y=
 github.com/zeromicro/go-zero v1.4.4 h1:J8M768EVFNtIQJ/GCEsoIQPanxbx2HHT0it7r69U76Y=
 github.com/zeromicro/go-zero v1.4.4/go.mod h1:5WSUwtJm0bYdDZ69GlckigcT6D0EyAPbDaX3unbSY/4=
+github.com/ziutek/blas v0.0.0-20190227122918-da4ca23e90bb h1:uWiILQloLUVdtPYr1ZZo2zqtlpzo4G8vUpglo/Fs2H8=
+github.com/ziutek/blas v0.0.0-20190227122918-da4ca23e90bb/go.mod h1:J3xKssoVdrwZ2E29fIox/EKxOZWimS7AZ4fOTCFkOLo=
 github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0=
 go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
 go.etcd.io/etcd v0.0.0-20200402134248-51bdeb39e698/go.mod h1:YoUyTScD3Vcv2RBm3eGVOq7i1ULiz3OuXoQFWOirmAM=

+ 3 - 3
src/jfw/modules/distribution/src/service/action/share.go

@@ -454,8 +454,8 @@ func (this *Share) GetWordShare() {
                 }
                 word := redis.GetStr("other", "DIS_"+userId)
                 if word == "" {
-                    userData, ok := MQFW.FindById("user", userId, `{"s_disword":1}`)
-                    if ok && (*userData)["s_disword"] != nil && util.ObjToString((*userData)["s_disword"]) != "" {
+                    userData := Compatible.Select(userId, `{"s_disword":1}`)
+                    if (*userData)["s_disword"] != nil && util.ObjToString((*userData)["s_disword"]) != "" {
                         word = util.ObjToString((*userData)["s_disword"])
                     } else {
                         word = VarLSCPool.GetJob()
@@ -463,7 +463,7 @@ func (this *Share) GetWordShare() {
                         redis.Put("other", "DIS_"+word, s_nickname+"##"+userId, -1)
                         //用户信息绑定分享口令
                         redis.Put("other", "DIS_"+userId, word, -1)
-                        ok := MQFW.UpdateById("user", userId, map[string]interface{}{
+                        ok := Compatible.Update(userId, map[string]interface{}{
                             "$set": map[string]interface{}{
                                 "s_disword": word,
                             },

+ 143 - 126
src/jfw/modules/distribution/src/service/config/config.go

@@ -1,155 +1,172 @@
 package config
 
 import (
-	"log"
+    "app.yhyue.com/moapp/jypkg/compatible"
+    "log"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/mail"
-	m "app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jybase/mysql"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/middleground"
-	"github.com/gogf/gf/v2/frame/g"
-	"github.com/gogf/gf/v2/os/gcfg"
-	"github.com/gogf/gf/v2/os/gctx"
+    util "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/mail"
+    m "app.yhyue.com/moapp/jybase/mongodb"
+    "app.yhyue.com/moapp/jybase/mysql"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/middleground"
+    "github.com/gogf/gf/v2/frame/g"
+    "github.com/gogf/gf/v2/os/gcfg"
+    "github.com/gogf/gf/v2/os/gctx"
 )
 
 type config struct {
-	Webport   string
-	Webdomain string
-	Mail      *[]mailConf
-	Mongodb   struct {
-		Main *mgoConf
-		Log  *mgoConf
-		Ent  *mgoConf
-	}
-	Elasticsearch struct {
-		Main *esConf
-	}
-	Redis struct {
-		Main  *redisConf
-		Login *redisConf
-	}
-	Mysql struct {
-		Main *mysqlConf
-		Push *mysqlConf
-	}
-	WorkerNum          int
-	JobNum             int
-	Modular            map[string]interface{}
-	UploadPath         string
-	CatchoutTimesMonth int64
-	AuthCost           float64
-	TermValidity       int
-	SourceCenter       string
-	PhoneFilterFlag    bool
-	AccountMergeOnline string
-	Regurl             []string
-	SmsServiceRpc      string
+    Webport   string
+    Webdomain string
+    Mail      *[]mailConf
+    Mongodb   struct {
+        Main *mgoConf
+        Log  *mgoConf
+        Ent  *mgoConf
+    }
+    Elasticsearch struct {
+        Main *esConf
+    }
+    Redis struct {
+        Main  *redisConf
+        Login *redisConf
+    }
+    Mysql struct {
+        Main *mysqlConf
+        Push *mysqlConf
+        Base *mysqlConf
+    }
+    WorkerNum          int
+    JobNum             int
+    Modular            map[string]interface{}
+    UploadPath         string
+    CatchoutTimesMonth int64
+    AuthCost           float64
+    TermValidity       int
+    SourceCenter       string
+    PhoneFilterFlag    bool
+    AccountMergeOnline string
+    Regurl             []string
+    SmsServiceRpc      string
 }
 
 type BalanceRes struct {
-	Code    int64                    `json:"code"`
-	Message string                   `json:"message"`
-	Data    []map[string]interface{} `json:"data"`
+    Code    int64                    `json:"code"`
+    Message string                   `json:"message"`
+    Data    []map[string]interface{} `json:"data"`
 }
 
 type mgoConf struct {
-	Address  string
-	Size     int
-	DbName   string
-	UserName string
-	Password string
+    Address  string
+    Size     int
+    DbName   string
+    UserName string
+    Password string
 }
 
 type esConf struct {
-	Address string
-	Size    int
+    Address string
+    Size    int
 }
 type redisConf struct {
-	Address string
+    Address string
 }
 type mysqlConf struct {
-	DbName       string
-	Address      string
-	UserName     string
-	PassWord     string
-	MaxOpenConns int
-	MaxIdleConns int
+    DbName       string
+    Address      string
+    UserName     string
+    PassWord     string
+    MaxOpenConns int
+    MaxIdleConns int
 }
 type mailConf struct {
-	Addr string
-	Port int
-	Pwd  string
-	User string
+    Addr string
+    Port int
+    Pwd  string
+    User string
 }
 
 var (
-	Sysconfig    *config
-	Mysql        *mysql.Mysql
-	MQFW         m.MongodbSim
-	Mgo_Log      m.MongodbSim
-	GmailAuth    []*mail.GmailAuth
-	Middleground *middleground.Middleground
+    Sysconfig    *config
+    Mysql        *mysql.Mysql
+    Base         *mysql.Mysql
+    MQFW         m.MongodbSim
+    Mgo_Log      m.MongodbSim
+    GmailAuth    []*mail.GmailAuth
+    Middleground *middleground.Middleground
+    Compatible   *compatible.Compatible
 )
 
 func init() {
-	util.ReadConfig(&Sysconfig)
-	if Sysconfig != nil {
-		//初始化redis
-		if Sysconfig.Redis.Main != nil {
-			log.Println("初始化 redis")
-			redis.InitRedisBySize(Sysconfig.Redis.Main.Address, 100, 30, 300)
-		}
-		//
-		if Sysconfig.Mongodb.Main != nil {
-			log.Println("初始化 mongodb main")
-			MQFW = m.MongodbSim{
-				MongodbAddr: Sysconfig.Mongodb.Main.Address,
-				Size:        Sysconfig.Mongodb.Main.Size,
-				DbName:      Sysconfig.Mongodb.Main.DbName,
-			}
-			MQFW.InitPool()
-		}
-		if Sysconfig.Mongodb.Log != nil {
-			log.Println("初始化 mongodb log")
-			Mgo_Log = m.MongodbSim{
-				MongodbAddr: Sysconfig.Mongodb.Log.Address,
-				Size:        Sysconfig.Mongodb.Log.Size,
-				DbName:      Sysconfig.Mongodb.Log.DbName,
-				UserName:    Sysconfig.Mongodb.Log.UserName,
-				Password:    Sysconfig.Mongodb.Log.Password,
-			}
-			Mgo_Log.InitPool()
-		}
-		if Sysconfig.Mysql.Main != nil {
-			log.Println("初始化 mysql")
-			Mysql = &mysql.Mysql{
-				Address:      Sysconfig.Mysql.Main.Address,
-				UserName:     Sysconfig.Mysql.Main.UserName,
-				PassWord:     Sysconfig.Mysql.Main.PassWord,
-				DBName:       Sysconfig.Mysql.Main.DbName,
-				MaxOpenConns: Sysconfig.Mysql.Main.MaxOpenConns,
-				MaxIdleConns: Sysconfig.Mysql.Main.MaxIdleConns,
-			}
-			Mysql.Init()
-		}
-		//
-		if Sysconfig.Mail != nil {
-			log.Println("初始化 Mail")
-			mailConfigArrMap := Sysconfig.Mail
-			for _, v := range *mailConfigArrMap {
-				mail := &mail.GmailAuth{
-					SmtpHost: v.Addr,
-					SmtpPort: v.Port,
-					User:     v.User,
-					Pwd:      v.Pwd,
-				}
-				GmailAuth = append(GmailAuth, mail)
-			}
-		}
-		g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetFileName("config.yaml")
-		var ctx = gctx.New()
-		Middleground = middleground.NewMiddleground(g.Cfg().MustGet(ctx, "etcd.hosts").Strings()).RegPowerCheckCenter(g.Cfg().MustGet(ctx, "powerCheckCenterKey").String())
-	}
+    util.ReadConfig(&Sysconfig)
+    if Sysconfig != nil {
+        //初始化redis
+        if Sysconfig.Redis.Main != nil {
+            log.Println("初始化 redis")
+            redis.InitRedisBySize(Sysconfig.Redis.Main.Address, 100, 30, 300)
+        }
+        //
+        if Sysconfig.Mongodb.Main != nil {
+            log.Println("初始化 mongodb main")
+            MQFW = m.MongodbSim{
+                MongodbAddr: Sysconfig.Mongodb.Main.Address,
+                Size:        Sysconfig.Mongodb.Main.Size,
+                DbName:      Sysconfig.Mongodb.Main.DbName,
+            }
+            MQFW.InitPool()
+        }
+        if Sysconfig.Mongodb.Log != nil {
+            log.Println("初始化 mongodb log")
+            Mgo_Log = m.MongodbSim{
+                MongodbAddr: Sysconfig.Mongodb.Log.Address,
+                Size:        Sysconfig.Mongodb.Log.Size,
+                DbName:      Sysconfig.Mongodb.Log.DbName,
+                UserName:    Sysconfig.Mongodb.Log.UserName,
+                Password:    Sysconfig.Mongodb.Log.Password,
+            }
+            Mgo_Log.InitPool()
+        }
+        if Sysconfig.Mysql.Main != nil {
+            log.Println("初始化 mysql")
+            Mysql = &mysql.Mysql{
+                Address:      Sysconfig.Mysql.Main.Address,
+                UserName:     Sysconfig.Mysql.Main.UserName,
+                PassWord:     Sysconfig.Mysql.Main.PassWord,
+                DBName:       Sysconfig.Mysql.Main.DbName,
+                MaxOpenConns: Sysconfig.Mysql.Main.MaxOpenConns,
+                MaxIdleConns: Sysconfig.Mysql.Main.MaxIdleConns,
+            }
+            Mysql.Init()
+        }
+        if Sysconfig.Mysql.Base != nil {
+            log.Println("初始化 mysql")
+            Base = &mysql.Mysql{
+                Address:      Sysconfig.Mysql.Base.Address,
+                UserName:     Sysconfig.Mysql.Base.UserName,
+                PassWord:     Sysconfig.Mysql.Base.PassWord,
+                DBName:       Sysconfig.Mysql.Base.DbName,
+                MaxOpenConns: Sysconfig.Mysql.Base.MaxOpenConns,
+                MaxIdleConns: Sysconfig.Mysql.Base.MaxIdleConns,
+            }
+            Base.Init()
+        }
+        //
+        if Sysconfig.Mail != nil {
+            log.Println("初始化 Mail")
+            mailConfigArrMap := Sysconfig.Mail
+            for _, v := range *mailConfigArrMap {
+                mail := &mail.GmailAuth{
+                    SmtpHost: v.Addr,
+                    SmtpPort: v.Port,
+                    User:     v.User,
+                    Pwd:      v.Pwd,
+                }
+                GmailAuth = append(GmailAuth, mail)
+            }
+        }
+        g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetFileName("config.yaml")
+        var ctx = gctx.New()
+        Middleground = middleground.NewMiddleground(g.Cfg().MustGet(ctx, "etcd.hosts").Strings()).RegPowerCheckCenter(g.Cfg().MustGet(ctx, "powerCheckCenterKey").String())
+        Compatible = compatible.NewCompatible(&MQFW, Base, Mysql, Middleground)
+    }
 }

+ 12 - 12
src/jfw/modules/distribution/src/service/filter/phonefilter.go

@@ -1,17 +1,17 @@
 package filter
 
 import (
-	. "jy/src/jfw/modules/distribution/src/service/config"
-	"log"
-	"net/http"
-	"net/url"
-	"regexp"
-	"strings"
-	"time"
-	qu "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jybase/mongodb"
+    qu "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jybase/mongodb"
+    . "jy/src/jfw/modules/distribution/src/service/config"
+    "log"
+    "net/http"
+    "net/url"
+    "regexp"
+    "strings"
+    "time"
 )
 
 type phoneFilter struct {
@@ -70,7 +70,7 @@ func (l *phoneFilter) Do() bool {
 	}
 	href := Sysconfig.Webdomain + "/front/account/phone/bind?mode=mergeBind&redirectTo=" + encodeURIComponent(l.R.URL.String()) //wx 加密 前端用于返回
 	if uid := l.GetSession["userId"]; uid != nil && uid != "" {
-		if person, ok := MQFW.FindById("user", mongodb.BsonIdToSId(qu.ObjToString(uid)), `{"s_phone":1,"s_m_phone":1,"l_registedate":1,"i_ispush":1}`); person != nil && ok {
+		if person :=Compatible.Select( mongodb.BsonIdToSId(qu.ObjToString(uid)), `{"s_phone":1,"s_m_phone":1,"l_registedate":1,"i_ispush":1}`); person != nil  {
 			s_phone := qu.ObjToString((*person)["s_phone"])
 			if s_phone == "" {
 				s_phone = qu.ObjToString((*person)["s_m_phone"])

+ 1 - 1
src/jfw/modules/distribution/src/util/util.go

@@ -1,7 +1,7 @@
 package pay
 
 import (
-	"fmt"
+    "fmt"
 	. "jy/src/jfw/modules/distribution/src/service/config"
 	"log"
 	"sync"

+ 4 - 3
src/jfw/modules/publicapply/src/active/21yearEndReport.go

@@ -2,7 +2,8 @@ package active
 
 import (
 	"fmt"
-	"jy/src/jfw/modules/publicapply/src/db"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
 	"math"
 	"strconv"
 	"strings"
@@ -64,7 +65,7 @@ type YearEndReportData struct {
 }
 
 func (this *YearEndReport) YearEndReportApi() {
-	userId, _ := this.GetSession("userId").(string)
+	userId, _ := this.GetSession("mgoUserId").(string)
 	rData, errMsg := func() (interface{}, error) {
 		if userId == "" {
 			return nil, fmt.Errorf("未登录")
@@ -97,7 +98,7 @@ func (this *YearEndReport) YearEndReportApi() {
 				yerd.ExpList = strings.Split(expListStr, ",")
 			}
 		}
-		if baseRes, _ := db.Mgo.FindById("user", userId, `{"s_nickname":1,"s_headimage":1,"s_headimageurl":1,"l_registedate":1,"s_phone":1}`); baseRes != nil && len(*baseRes) > 0 {
+		if baseRes :=config.Compatible.Select( userId, `{"s_nickname":1,"s_headimage":1,"s_headimageurl":1,"l_registedate":1,"s_phone":1}`); baseRes != nil && len(*baseRes) > 0 {
 			if head, _ := (*baseRes)["s_headimage"].(string); head != "" {
 				yerd.UserHead = head
 			} else if head, _ := (*baseRes)["s_headimageurl"].(string); head != "" {

+ 60 - 58
src/jfw/modules/publicapply/src/config/config.go

@@ -1,79 +1,81 @@
 package config
 
 import (
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jypkg/middleground"
-	"github.com/gogf/gf/v2/frame/g"
-	"github.com/gogf/gf/v2/os/gcfg"
-	"github.com/gogf/gf/v2/os/gctx"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jypkg/compatible"
+    "app.yhyue.com/moapp/jypkg/middleground"
+    "github.com/gogf/gf/v2/frame/g"
+    "github.com/gogf/gf/v2/os/gcfg"
+    "github.com/gogf/gf/v2/os/gctx"
 )
 
 type config struct {
-	WebPort string
-	Mail    []struct {
-		Addr string
-		Port int
-		Pwd  string
-		User string
-	}
-	Industry              string
-	Frequency             string
-	HotWords              []string
-	DefaultEntList        []string //企业查询默认展示企业
-	BidSearchOldUserLimit int64
-	File_number           int
-	AttachmentRPC         string
-	FollowPushRpc         string
-	SmsServiceRpc         string
-	FileSignBool          bool
-	FollowCustomer        struct {
-		CustomerNumb   int
-		EnterpriseNumb int
-	}
-	ExhibitionLog string
-	TipInfo       map[string]int64
+    WebPort string
+    Mail    []struct {
+        Addr string
+        Port int
+        Pwd  string
+        User string
+    }
+    Industry              string
+    Frequency             string
+    HotWords              []string
+    DefaultEntList        []string //企业查询默认展示企业
+    BidSearchOldUserLimit int64
+    File_number           int
+    AttachmentRPC         string
+    FollowPushRpc         string
+    SmsServiceRpc         string
+    FileSignBool          bool
+    FollowCustomer        struct {
+        CustomerNumb   int
+        EnterpriseNumb int
+    }
+    ExhibitionLog string
+    TipInfo       map[string]int64
 }
 type BidColl struct {
-	PayUserCollLimit      int    //付费用户收藏数量最大限制
-	FreeUserCollLimit     int    //免费用户收藏数量最大限制
-	Pagesize              int    //付费用户收藏列表每页展示数量
-	FreePageSize          int    //免费用户收藏列表展示数量
-	LabelMaxCount         int    //标签数量最大限制
-	CollRedisDb           string //收藏的bid redis key
-	IsCollRedisTime       int    //是否收藏redis过期时间
-	CollListRedisTime     int    //收藏列表redis过期时间
-	CollListRedisMaxCount int    //收藏列表redis最大条数限制
+    PayUserCollLimit      int    //付费用户收藏数量最大限制
+    FreeUserCollLimit     int    //免费用户收藏数量最大限制
+    Pagesize              int    //付费用户收藏列表每页展示数量
+    FreePageSize          int    //免费用户收藏列表展示数量
+    LabelMaxCount         int    //标签数量最大限制
+    CollRedisDb           string //收藏的bid redis key
+    IsCollRedisTime       int    //是否收藏redis过期时间
+    CollListRedisTime     int    //收藏列表redis过期时间
+    CollListRedisMaxCount int    //收藏列表redis最大条数限制
 }
 
 type AdLeague struct {
-	Exposure string //广告曝光记录接口
-	Click    string //点击接口
+    Exposure string //广告曝光记录接口
+    Click    string //点击接口
 }
 
 type ShareF struct {
-	JobNum     int
-	WorkerNum  int
-	ShareRedis string
-	Webdomain  string
-	SaveTime   int
-	MayActive  string //活动标识
+    JobNum     int
+    WorkerNum  int
+    ShareRedis string
+    Webdomain  string
+    SaveTime   int
+    MayActive  string //活动标识
 }
 
 var (
-	Config        *config
-	BidCollConfig *BidColl
-	AdLeaguefig   *AdLeague
-	ShareConfig   *ShareF
-	Middleground  *middleground.Middleground
+    Config        *config
+    BidCollConfig *BidColl
+    AdLeaguefig   *AdLeague
+    ShareConfig   *ShareF
+    Middleground  *middleground.Middleground
+    Compatible    *compatible.Compatible
 )
 
 func init() {
-	g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetFileName("config.yaml")
-	//程序配置文件
-	qutil.ReadConfig(&Config)
-	qutil.ReadConfig("./bidcollection.json", &BidCollConfig)
-	qutil.ReadConfig("./adLeague.json", &AdLeaguefig)
-	qutil.ReadConfig("./shareFission.json", &ShareConfig)
-	var ctx = gctx.New()
-	Middleground = middleground.NewMiddleground(g.Cfg().MustGet(ctx, "etcd.hosts").Strings()).RegUserCenter(g.Cfg().MustGet(ctx, "userCenterKey").String()).RegPowerCheckCenter(g.Cfg().MustGet(ctx, "powerCheckCenterKey").String())
+    g.Cfg().GetAdapter().(*gcfg.AdapterFile).SetFileName("config.yaml")
+    //程序配置文件
+    qutil.ReadConfig(&Config)
+    qutil.ReadConfig("./bidcollection.json", &BidCollConfig)
+    qutil.ReadConfig("./adLeague.json", &AdLeaguefig)
+    qutil.ReadConfig("./shareFission.json", &ShareConfig)
+    var ctx = gctx.New()
+    Middleground = middleground.NewMiddleground(g.Cfg().MustGet(ctx, "etcd.hosts").Strings()).RegUserCenter(g.Cfg().MustGet(ctx, "userCenterKey").String()).RegPowerCheckCenter(g.Cfg().MustGet(ctx, "powerCheckCenterKey").String())
 }

+ 2 - 2
src/jfw/modules/publicapply/src/dataexport/service/action.go

@@ -31,7 +31,7 @@ type DataExportStruct struct {
 }
 
 func (des *DataExportStruct) PayPageParams() {
-	userId, _ := des.GetSession("userId").(string)
+	userId, _ := des.GetSession("mgoUserId").(string)
 	rData, errMsg := func() (interface{}, error) {
 		defer util.Catch()
 		if userId == "" {
@@ -64,7 +64,7 @@ func (des *DataExportStruct) PayPageParams() {
 		if resEmail == "" || resPhone == "" {
 			lastEmail, lastPhone := "", ""
 			if lastPhone, lastEmail = dataexport.GetLastExportPhoneAndMail(db.Mysql, userId, util.ObjToString(des.GetSession("entUserId"))); lastPhone == "" || lastEmail == "" {
-				userData, _ := db.Mgo.FindById("user", userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
+				userData := config.Compatible.Select( userId, `{"s_myemail":1,"s_phone":1,"s_m_phone":1}`)
 				if userData != nil && len(*userData) > 0 {
 					if lastEmail == "" {
 						lastEmail, _ = (*userData)["s_myemail"].(string)

+ 10 - 7
src/jfw/modules/publicapply/src/db/db.go

@@ -1,14 +1,16 @@
 package db
 
 import (
-	"log"
-	m "app.yhyue.com/moapp/jybase/mongodb"
-	util "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
+    util "app.yhyue.com/moapp/jybase/common"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
+    m "app.yhyue.com/moapp/jybase/mongodb"
+    "app.yhyue.com/moapp/jypkg/compatible"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "log"
 
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jybase/mysql"
-	"app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jybase/mysql"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 type dbConf struct {
@@ -217,5 +219,6 @@ func init() {
 			}
 			MysqlMedical.Init()
 		}
+       config.Compatible = compatible.NewCompatible(&Mgo, MysqlSupplyInfo, Mysql, config.Middleground)
 	}
 }

+ 2 - 1
src/jfw/modules/publicapply/src/go.mod

@@ -4,7 +4,7 @@ go 1.18
 
 require (
 	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
-	app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa
+	app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114
 	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230129060002-f69424aa14ba
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/gogf/gf/v2 v2.0.6
@@ -15,6 +15,7 @@ require (
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
 	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 // indirect
 	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 // indirect
 	bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4 // indirect
 	github.com/BurntSushi/toml v0.4.1 // indirect

+ 4 - 2
src/jfw/modules/publicapply/src/go.sum

@@ -13,11 +13,13 @@ app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tc
 app.yhyue.com/moapp/jybase v0.0.0-20230109015757-aa3d5e19b196/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a h1:wD4aWPSYdiX1cIP4lzzPD2s7fYhKa3muIf97l9tonJE=
 app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa h1:0/2I4ubgDsRbKm7PeiVSTvYwZCK3anZQaEagsGBbI7E=
-app.yhyue.com/moapp/jypkg v0.0.0-20230209022443-283a80f1b7fa/go.mod h1:0DqPlGxaufZlKaLoRndTWG4j3qUQqJ6MNZCmoPcMqSg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114 h1:89J5Zq4bfnocIpEWBn19PnfaT+8Dh+Rv4X8QoTwxCpg=
+app.yhyue.com/moapp/jypkg v0.0.0-20230209055147-4cf703ace114/go.mod h1:sa5YRPqTQLOVBmpltjT21EkQ7DfJbUZFARUb4ZJ7U+k=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae h1:6rDDaz6yxvE8viTSzEBwKYOFWq14TMfuBivSazUZMz4=
 app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
 bp.jydev.jianyu360.cn/BP/jynsq v0.0.0-20220222052708-ebc43af90698/go.mod h1:ojo/AUH9Yr1wzarEjOaNMkj1Cet/9r8IgLyba64Z52E=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7 h1:cw/PdRypNFcYOk4iWAfHjIFoMzIlXUfl9XAmWujBOPY=
+bp.jydev.jianyu360.cn/BaseService/entManageApplication v0.0.0-20230209051900-1e7dcb8f83b7/go.mod h1:7Xhygw0KBuL4h0G76FnFg4otQcA9bmOO0c8M0FCjAyQ=
 bp.jydev.jianyu360.cn/BaseService/gateway v0.0.0-20220419090715-88ddb32961be/go.mod h1:Yj4oabIGItuMoF0BXYLz2XAnF581kxgXBrvlUtIJrkI=
 bp.jydev.jianyu360.cn/BaseService/gateway v1.3.4/go.mod h1:BMLd/5wb3BIEGhnEgF9y1sJN9P5/Dw9kYsoiE9V8I9g=
 bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230207054315-b05f3dd4c4d3 h1:jeItQ6RM1T6yPWc/5i4R6h3kViD+Rm2VnIEsc1gCFJA=

+ 3 - 3
src/jfw/modules/publicapply/src/shareFission/service/service.go

@@ -35,7 +35,7 @@ func (this *Share) Qwe() {
 
 func (this *Share) Info() {
     defer qu.Catch()
-    userid, _ := this.GetSession("userId").(string)
+    userid, _ := this.GetSession("mgoUserId").(string)
     r := func() map[string]interface{} {
         res := map[string]interface{}{}
         keyUser := fmt.Sprintf("SF_%s", userid)
@@ -184,8 +184,8 @@ func timeOut() int {
 
 //获取用户头像,手机号
 func GetInfo(userid string) map[string]interface{} {
-    rdata, ok := db.Mgo.FindById("user", userid, `{"s_headimageurl":1,"s_headimage":1,"s_phone":1,"s_m_phone":1,"s_nickname":1,"l_registedate":1}`)
-    if ok && len(*rdata) > 0 && rdata != nil {
+    rdata:= config.Compatible.Select(userid, `{"s_headimageurl":1,"s_headimage":1,"s_phone":1,"s_m_phone":1,"s_nickname":1,"l_registedate":1}`)
+    if  len(*rdata) > 0 && rdata != nil {
         nickname, headimageurl := "", ""
         if s_phone, _ := (*rdata)["s_phone"].(string); s_phone != "" {
             nickname = s_phone

+ 198 - 232
src/jfw/modules/publicapply/src/subscribe/entity/entity.go

@@ -1,234 +1,217 @@
 package entity
 
 import (
-        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-        "fmt"
-        "jy/src/jfw/modules/publicapply/src/db"
-        "log"
-        "time"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "fmt"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
+    "log"
+    "time"
 
-        qutil "app.yhyue.com/moapp/jybase/common"
-        "app.yhyue.com/moapp/jybase/encrypt"
-        elastic "app.yhyue.com/moapp/jybase/esv1"
-        "app.yhyue.com/moapp/jybase/redis"
-        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 
-        // "reflect"
-        //"strconv"
-        . "jy/src/jfw/modules/publicapply/src/subscribePush/entity"
-        "strings"
+    // "reflect"
+    //"strconv"
+    . "jy/src/jfw/modules/publicapply/src/subscribePush/entity"
+    "strings"
 )
 
 const (
-        bidSearch_sort = `{"publishtime":-1}`
-        findfields     = `"title"`
+    bidSearch_sort = `{"publishtime":-1}`
+    findfields     = `"title"`
 
-        view_maxPageNum = 20
-        view_pageSize   = 50
-        bidSearch_field = `"_id","title","publishtime","toptype","subtype","type","area","buyerclass","budget","bidamount"`
+    view_maxPageNum = 20
+    view_pageSize   = 50
+    bidSearch_field = `"_id","title","publishtime","toptype","subtype","type","area","buyerclass","budget","bidamount"`
 )
 
 var stringArr = []string{}
 
 //
 type ParamInfo struct {
-        UserId  string
-        Session *httpsession.Session
+    UserId  string
+    Session *httpsession.Session
 }
 
 //
 func NewParamInfo(userId string, session *httpsession.Session) *ParamInfo {
-        return &ParamInfo{userId, session}
+    return &ParamInfo{userId, session}
 }
 
 //dev4.6.3.21 暂不调用
 func (this *ParamInfo) SetAreaByOneProvince() (b bool) {
-        b = true
-        /*mData, ok := db.Mgo.FindById("user", this.UserId, `{"o_jy":1}`)*/
-        o_jy := jy.GetSubScribeInfo(this.Session, db.Mgo, "f", "10000")
-        if o_jy != nil && len(*o_jy) != 0 {
-                if (*o_jy)["o_area"] != nil {
-                        return b
-                }
-                a_key, _ := (*o_jy)["a_key"].([]interface{})
-                areas := []string{}
-                for _, v := range a_key {
-                        keyMap, _ := v.(map[string]interface{})
-                        area, _ := keyMap["area"].([]interface{})
-                        if len(area) > 1 {
-                                continue
-                        }
-                        areas = append(areas, qutil.ObjArrToStringArr(area)...)
-                }
-                setMap := map[string]interface{}{
-                        // "o_jy.i_newfree": 1, //老免费用户=>新订阅设置页面 20211122
-                }
-                positionType := qutil.Int64All(this.Session.Get("positionType"))
-                if len(areas) == 1 {
-                        //设置地区
-                        if positionType == 0 {
-                                setMap["o_jy.o_area"] = map[string]interface{}{
-                                        areas[0]: []string{},
-                                }
-                        } else {
-                                setMap["o_entniche.o_area"] = map[string]interface{}{
-                                        areas[0]: []string{},
-                                }
-                        }
-                }
-                ok := false
-                if positionType == 0 {
-                        ok = db.Mgo.UpdateById("user", this.UserId, map[string]interface{}{"$set": setMap})
-                } else {
-                        entId := qutil.Int64All(this.Session.Get("entId"))
-                        entUserId := qutil.IntAll(this.Session.Get("entUserId"))
-                        query := map[string]interface{}{
-                                "i_userid": entUserId,
-                                "i_entid":  entId,
-                                "i_type":   2,
-                        }
-                        ok = db.Mgo.Update("entniche_rule", query, map[string]interface{}{"$set": setMap}, true, false)
-                }
-                if ok {
-                        jy.ClearBigVipUserPower(this.UserId)
+    b = true
+    o_jy := jy.GetSubScribeInfo(this.Session, db.Mgo, "f", "10000")
+    if o_jy != nil && len(*o_jy) != 0 {
+        if (*o_jy)["o_area"] != nil {
+            return b
+        }
+        a_key, _ := (*o_jy)["a_key"].([]interface{})
+        areas := []string{}
+        for _, v := range a_key {
+            keyMap, _ := v.(map[string]interface{})
+            area, _ := keyMap["area"].([]interface{})
+            if len(area) > 1 {
+                continue
+            }
+            areas = append(areas, qutil.ObjArrToStringArr(area)...)
+        }
+        setMap := map[string]interface{}{
+            // "o_jy.i_newfree": 1, //老免费用户=>新订阅设置页面 20211122
+        }
+
+        if len(areas) == 1 {
+            //设置地区
+                setMap["o_jy.o_area"] = map[string]interface{}{
+                    areas[0]: []string{},
                 }
         }
-        return b
+        ok := false
+        ok = config.Compatible.Update(this.UserId, map[string]interface{}{"$set": setMap})
+        if ok {
+            positionId := qutil.ObjToString(this.Session.Get("positionId"))
+            jy.ClearBigVipUserPower(positionId)
+        }
+    }
+    return b
 }
 
 //
 type UserSubMsg struct {
-        Area        map[string]interface{} `json:"area"`        //地区
-        Infotype    []interface{}          `json:"infotype"`    //信息类型
-        Matchway    int                    `json:"imatchway"`   //关键词匹配方式
-        Keys        []ViewKeyWord          `json:"keys"`        //关键词
-        Areanum     int                    `json:"areanum"`     //可修改地区次数
-        Basenum     int                    `json:"basenum"`     //基础修改次数
-        Provincenum int                    `json:"provincenum"` //省份流量包购买省份数量
-        Ppstarttime int64                  `json:"ppstart"`     //省份订阅包开始时间
-        Ppendtime   int64                  `json:"ppend"`       //省份订阅包结束时间
+    Area        map[string]interface{} `json:"area"`        //地区
+    Infotype    []interface{}          `json:"infotype"`    //信息类型
+    Matchway    int                    `json:"imatchway"`   //关键词匹配方式
+    Keys        []ViewKeyWord          `json:"keys"`        //关键词
+    Areanum     int                    `json:"areanum"`     //可修改地区次数
+    Basenum     int                    `json:"basenum"`     //基础修改次数
+    Provincenum int                    `json:"provincenum"` //省份流量包购买省份数量
+    Ppstarttime int64                  `json:"ppstart"`     //省份订阅包开始时间
+    Ppendtime   int64                  `json:"ppend"`       //省份订阅包结束时间
 }
 
 //推送预览总数
 func DataCount(uid, item string, index int) int64 {
-        sql := GetSqlObjFromFreeId(uid, item, index)
-        if item != "" && index >= 0 && (sql.Keyword == nil || len(sql.Keyword) == 0) {
-                log.Println("推送结果预览总数参数异常,没有找到改组订阅词", item, index)
-                return 0
-        }
-        qstr := GetVIPViewSql(uid, sql)
-        return elastic.Count(INDEX, TYPE, qstr)
+    sql := GetSqlObjFromFreeId(uid, item, index)
+    if item != "" && index >= 0 && (sql.Keyword == nil || len(sql.Keyword) == 0) {
+        log.Println("推送结果预览总数参数异常,没有找到改组订阅词", item, index)
+        return 0
+    }
+    qstr := GetVIPViewSql(uid, sql)
+    return elastic.Count(INDEX, TYPE, qstr)
 }
 
 //match 默认精准 0
 func KeysetDataCount(userId, key, notkey string, matchway int) int64 {
-        key = strings.TrimSpace(key)
-        notkey = strings.TrimSpace(notkey)
-        if key == "" {
-                return 0
-        }
-        sql := GetSqlObjFromFreeId(userId, "", -1)
-        viewKeyWords := []ViewKeyWord{}
-        viewKeyWords = append(viewKeyWords, ViewKeyWord{
-                Keyword:  strings.Split(key, " "),
-                Exclude:  strings.Split(notkey, " "),
-                MatchWay: matchway,
-        })
-        sql.Keyword = viewKeyWords
-        qstr := GetVIPViewSql(userId, sql)
-        return elastic.Count(INDEX, TYPE, qstr)
+    key = strings.TrimSpace(key)
+    notkey = strings.TrimSpace(notkey)
+    if key == "" {
+        return 0
+    }
+    sql := GetSqlObjFromFreeId(userId, "", -1)
+    viewKeyWords := []ViewKeyWord{}
+    viewKeyWords = append(viewKeyWords, ViewKeyWord{
+        Keyword:  strings.Split(key, " "),
+        Exclude:  strings.Split(notkey, " "),
+        MatchWay: matchway,
+    })
+    sql.Keyword = viewKeyWords
+    qstr := GetVIPViewSql(userId, sql)
+    return elastic.Count(INDEX, TYPE, qstr)
 }
 
 func SubViewDatas(userId, allquery string, pageNum int) (keys []interface{}, list *[]map[string]interface{}, hasNextPage bool) {
-        if userId == "" {
-                return
+    if userId == "" {
+        return
+    }
+    sql := GetSqlObjFromFreeId(userId, "", -1)
+    for _, v := range sql.Keyword {
+        var keys_one []string
+        for _, k := range v.Keyword {
+            keys_one = append(keys_one, k)
         }
-        sql := GetSqlObjFromFreeId(userId, "", -1)
-        for _, v := range sql.Keyword {
-                var keys_one []string
-                for _, k := range v.Keyword {
-                        keys_one = append(keys_one, k)
-                }
-                //dev3.5 附加词也要高亮
-                for _, k := range v.Appended {
-                        keys_one = append(keys_one, k)
-                }
-                keys = append(keys, strings.Join(keys_one, "++"))
+        //dev3.5 附加词也要高亮
+        for _, k := range v.Appended {
+            keys_one = append(keys_one, k)
         }
-        qstr := GetVIPViewSql(userId, sql)
-        list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSearch_sort, bidSearch_field, (pageNum-1)*view_pageSize, view_pageSize, 0, false)
-        if list != nil {
-                for _, v := range *list {
-                        v["_id"] = encrypt.EncodeArticleId2ByCheck(qutil.ObjToString(v["_id"]))
-                }
+        keys = append(keys, strings.Join(keys_one, "++"))
+    }
+    qstr := GetVIPViewSql(userId, sql)
+    list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSearch_sort, bidSearch_field, (pageNum-1)*view_pageSize, view_pageSize, 0, false)
+    if list != nil {
+        for _, v := range *list {
+            v["_id"] = encrypt.EncodeArticleId2ByCheck(qutil.ObjToString(v["_id"]))
         }
-        hasNextPage = list != nil && len(*list) == view_pageSize && pageNum < view_maxPageNum
-        return
+    }
+    hasNextPage = list != nil && len(*list) == view_pageSize && pageNum < view_maxPageNum
+    return
 }
 
 //
 func (pi *ParamInfo) GetSubMsg() UserSubMsg {
-        // mData, ok := db.Mgo.FindById("user", pi.UserId, `{"o_jy":1}`)
-        var res = UserSubMsg{
-                Basenum: jy.BaseAreaNum,
+    var res = UserSubMsg{
+        Basenum: jy.BaseAreaNum,
+    }
+    o_jy := jy.GetSubScribeInfo(pi.Session, db.Mgo, "f", "10000")
+    if o_jy != nil && len(*o_jy) != 0 {
+        if _, ok := (*o_jy)["o_area"]; ok && (*o_jy)["o_area"] != nil {
+            res.Area, _ = (*o_jy)["o_area"].(map[string]interface{})
         }
-        o_jy := jy.GetSubScribeInfo(pi.Session, db.Mgo, "f", "10000")
-        if o_jy != nil && len(*o_jy) != 0 {
-                if _, ok := (*o_jy)["o_area"]; ok && (*o_jy)["o_area"] != nil {
-                        res.Area, _ = (*o_jy)["o_area"].(map[string]interface{})
-                }
-                res.Infotype, _ = (*o_jy)["a_infotype"].([]interface{})
+        res.Infotype, _ = (*o_jy)["a_infotype"].([]interface{})
 
-                //免费用户未购买省份订阅包 按年算
-                year := fmt.Sprint(time.Now().Year())
-                //免费用户未购买省份订阅包 已调整地区次数(年)
-                fpnum := redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, pi.UserId, year))
-                //免费用户未购买省份订阅包 地区调整可用次数(默认值)
-                res.Areanum = qutil.If(fpnum > 0, jy.BaseAreaNum-fpnum, jy.BaseAreaNum).(int)
-                //免费用户已购买省份订阅包
-                if (*o_jy)["i_ppstatus"] != nil && qutil.IntAll((*o_jy)["i_ppstatus"]) > 0 {
-                        o_buyset_p, _ := (*o_jy)["o_buyset_p"].(map[string]interface{})
-                        res.Provincenum = qutil.IntAll(o_buyset_p["areacount"]) //-1 全国无限制
-                        res.Areanum = res.Provincenum
-                        if res.Provincenum > 0 {
-                                //按月算
-                                ym := fmt.Sprint(time.Now().Year()) + "-" + fmt.Sprint(time.Now().Month())
-                                //已调整地区次数(月)
-                                ppnum := redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, pi.UserId, ym))
-                                //可调整次数(月)
-                                res.Areanum = res.Provincenum + jy.BaseAreaNum - ppnum //- fpnum
-                        }
-                        res.Ppstarttime = qutil.Int64All((*o_jy)["l_areaStart_p"])
-                        res.Ppendtime = qutil.Int64All((*o_jy)["l_areaEnd_p"])
-                        res.Area, _ = (*o_jy)["o_area_p"].(map[string]interface{})
-                } else if res.Area != nil && len(res.Area) == 0 {
-                        res.Area = nil
+        //免费用户未购买省份订阅包 按年算
+        year := fmt.Sprint(time.Now().Year())
+        //免费用户未购买省份订阅包 已调整地区次数(年)
+        fpnum := redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, pi.UserId, year))
+        //免费用户未购买省份订阅包 地区调整可用次数(默认值)
+        res.Areanum = qutil.If(fpnum > 0, jy.BaseAreaNum-fpnum, jy.BaseAreaNum).(int)
+        //免费用户已购买省份订阅包
+        if (*o_jy)["i_ppstatus"] != nil && qutil.IntAll((*o_jy)["i_ppstatus"]) > 0 {
+            o_buyset_p, _ := (*o_jy)["o_buyset_p"].(map[string]interface{})
+            res.Provincenum = qutil.IntAll(o_buyset_p["areacount"]) //-1 全国无限制
+            res.Areanum = res.Provincenum
+            if res.Provincenum > 0 {
+                //按月算
+                ym := fmt.Sprint(time.Now().Year()) + "-" + fmt.Sprint(time.Now().Month())
+                //已调整地区次数(月)
+                ppnum := redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, pi.UserId, ym))
+                //可调整次数(月)
+                res.Areanum = res.Provincenum + jy.BaseAreaNum - ppnum //- fpnum
+            }
+            res.Ppstarttime = qutil.Int64All((*o_jy)["l_areaStart_p"])
+            res.Ppendtime = qutil.Int64All((*o_jy)["l_areaEnd_p"])
+            res.Area, _ = (*o_jy)["o_area_p"].(map[string]interface{})
+        } else if res.Area != nil && len(res.Area) == 0 {
+            res.Area = nil
+        }
+        //关键词
+        a_key, _ := (*o_jy)["a_key"].([]interface{})
+        if len(a_key) > 0 {
+            for _, v := range a_key {
+                keyMap, _ := v.(map[string]interface{})
+                key := qutil.ObjArrToStringArr(keyMap["key"].([]interface{}))
+                appendkey := stringArr
+                if keyMap["appendkey"] != nil {
+                    appendkey = qutil.ObjArrToStringArr(keyMap["appendkey"].([]interface{}))
                 }
-                //关键词
-                a_key, _ := (*o_jy)["a_key"].([]interface{})
-                if len(a_key) > 0 {
-                        for _, v := range a_key {
-                                keyMap, _ := v.(map[string]interface{})
-                                key := qutil.ObjArrToStringArr(keyMap["key"].([]interface{}))
-                                appendkey := stringArr
-                                if keyMap["appendkey"] != nil {
-                                        appendkey = qutil.ObjArrToStringArr(keyMap["appendkey"].([]interface{}))
-                                }
-                                notkey := stringArr
-                                if keyMap["notkey"] != nil {
-                                        notkey = qutil.ObjArrToStringArr(keyMap["notkey"].([]interface{}))
-                                }
-                                res.Keys = append(res.Keys, ViewKeyWord{
-                                        Keyword:  key,
-                                        Appended: appendkey,
-                                        Exclude:  notkey,
-                                        MatchWay: 0,
-                                })
-                        }
+                notkey := stringArr
+                if keyMap["notkey"] != nil {
+                    notkey = qutil.ObjArrToStringArr(keyMap["notkey"].([]interface{}))
                 }
-                res.Matchway = 1 //匹配方式 1:标题 2:正文  免费默认1
+                res.Keys = append(res.Keys, ViewKeyWord{
+                    Keyword:  key,
+                    Appended: appendkey,
+                    Exclude:  notkey,
+                    MatchWay: 0,
+                })
+            }
         }
-        return res
+        res.Matchway = 1 //匹配方式 1:标题 2:正文  免费默认1
+    }
+    return res
 }
 
 /*是否需要到期弹窗提醒
@@ -236,68 +219,51 @@ tip : true需要 false不需要
 area : 免费订阅的地区
 */
 func (pi *ParamInfo) AreaPackTip() map[string]interface{} {
-        m := map[string]interface{}{
-                "tip":  false,
-                "area": "",
+    m := map[string]interface{}{
+        "tip":  false,
+        "area": "",
+    }
+    o_jy := jy.GetSubScribeInfo(pi.Session, db.Mgo, "f", "10000")
+    if o_jy != nil && len(*o_jy) != 0 {
+        if (*o_jy)["i_areapackTip"] != nil {
+            if i_tip := qutil.IntAll((*o_jy)["i_areapackTip"]); i_tip == 1 {
+                m["tip"] = true
+            }
         }
-        /*mData, ok := db.Mgo.FindById("user", pi.UserId, `{"o_jy":1}`)*/
-        o_jy := jy.GetSubScribeInfo(pi.Session, db.Mgo, "f", "10000")
-        if o_jy != nil && len(*o_jy) != 0 {
-                if (*o_jy)["i_areapackTip"] != nil {
-                        if i_tip := qutil.IntAll((*o_jy)["i_areapackTip"]); i_tip == 1 {
-                                m["tip"] = true
-                        }
-                }
-                if (*o_jy)["o_area"] != nil {
-                        oarea, _ := (*o_jy)["o_area"].(map[string]interface{})
-                        if len(oarea) > 0 {
-                                for k, _ := range oarea {
-                                        m["area"] = k
-                                        break
-                                }
-                        }
+        if (*o_jy)["o_area"] != nil {
+            oarea, _ := (*o_jy)["o_area"].(map[string]interface{})
+            if len(oarea) > 0 {
+                for k, _ := range oarea {
+                    m["area"] = k
+                    break
                 }
+            }
         }
-        return m
+    }
+    return m
 }
 
 //修改到期提醒状态
 func (pi *ParamInfo) UpdateAreaPackTip() bool {
-        positionType := qutil.Int64All(pi.Session.Get("positionType"))
-        ok := false
-        setMap := map[string]interface{}{}
-        if positionType == 0 {
-                setMap = map[string]interface{}{
-                        "o_jy.i_areapackTip": 0,
-                }
-                ok = db.Mgo.UpdateById("user", pi.UserId, map[string]interface{}{"$set": setMap})
-        } else {
-                setMap = map[string]interface{}{
-                        "o_entniche.i_areapackTip": 0,
-                }
-                entId := qutil.Int64All(pi.Session.Get("entId"))
-                entUserId := qutil.IntAll(pi.Session.Get("entUserId"))
-                query := map[string]interface{}{
-                        "i_userid": entUserId,
-                        "i_entid":  entId,
-                        "i_type":   2,
-                }
-                ok = db.Mgo.Update("entniche_rule", query, map[string]interface{}{"$set": setMap}, true, false)
-        }
-        return ok
+    ok := false
+    setMap := map[string]interface{}{
+        "o_jy.i_areapackTip": 0,
+    }
+    ok = config.Compatible.Update(pi.UserId, map[string]interface{}{"$set": setMap})
+    return ok
 }
 
 //
 func getstype(stype string) string {
-        switch stype {
-        case "招标":
-                stype = "招标,邀标,询价,竞谈,单一,竞价,变更"
-        case "结果":
-                stype = "中标,成交,废标,流标,结果变更"
-        case "其它":
-                stype = "合同,验收,违规"
-        case "预告":
-                stype = "预告,需求公示,预审,论证意见,预审结果"
-        }
-        return stype
+    switch stype {
+    case "招标":
+        stype = "招标,邀标,询价,竞谈,单一,竞价,变更"
+    case "结果":
+        stype = "中标,成交,废标,流标,结果变更"
+    case "其它":
+        stype = "合同,验收,违规"
+    case "预告":
+        stype = "预告,需求公示,预审,论证意见,预审结果"
+    }
+    return stype
 }

+ 261 - 270
src/jfw/modules/publicapply/src/subscribePush/entity/historyPush.go

@@ -1,19 +1,19 @@
 package entity
 
 import (
-	util "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/publicapply/src/config"
-	"jy/src/jfw/modules/publicapply/src/db"
-	es "jy/src/jfw/modules/publicapply/src/subscribePush/entity/service"
-	"log"
-	"strconv"
-	"strings"
-	"time"
+    util "app.yhyue.com/moapp/jybase/common"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "encoding/json"
+    "fmt"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
+    es "jy/src/jfw/modules/publicapply/src/subscribePush/entity/service"
+    "log"
+    "strconv"
+    "strings"
+    "time"
 )
 
 type historyPush struct {
@@ -23,291 +23,282 @@ var HistoryPush = &historyPush{}
 
 //UpdateUserPushUnread 更新app未读标识为已读
 func (hp *historyPush) UpdateUserPushUnread(userid string, vt string) {
-	if vt == jy.MemberFlag {
-		db.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
-	} else if vt == jy.EntnicheFlag {
-		db.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
-	} else {
-		db.Mgo.UpdateById("user", userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
-
-	}
+    if vt == jy.MemberFlag {
+        config.Compatible.Update(userid, map[string]interface{}{"$set": map[string]interface{}{"i_member_apppushunread": 0}})
+    } else if vt == jy.EntnicheFlag {
+        config.Compatible.Update(userid, map[string]interface{}{"$set": map[string]interface{}{"i_entniche_apppushunread": 0}})
+    } else {
+        config.Compatible.Update(userid, map[string]interface{}{"$set": map[string]interface{}{"i_apppushunread": 0}})
+    }
 }
 
 //IsInTsGuide 是否进入向导
 func (hp *historyPush) IsInTsGuide(session *httpsession.Session) bool {
-	data := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
-	if data.Data.Member.Status > 0 || data.Data.Vip.Status > 0 {
-		return false
-	}
-	return false
+    data := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
+    if data.Data.Member.Status > 0 || data.Data.Vip.Status > 0 {
+        return false
+    }
+    return false
 }
 
 func PushView(userid, allquery, field string, pageNum, pageSize int, session *httpsession.Session) (keys []interface{}, list *[]map[string]interface{}) {
-	if userid == "" {
-		return
-	}
-	/*tmp, ok := db.Mgo.FindById("user", userid, `{"_id":1,"o_jy":1}`)
-	  if !ok || tmp == nil || len(*tmp) == 0 {
-	          return
-	  }
-	  o_jy := (*tmp)["o_jy"].(map[string]interface{})
-	  a_key, _ := o_jy["a_key"].([]interface{})
-	  if len(a_key) == 0 {
-	          return
-	  }*/
-	data := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
-	if data == nil || len(*data) == 0 {
-		return
-	}
-	a_key, _ := (*data)["a_key"].([]interface{})
-	if len(a_key) == 0 {
-		return
-	}
-	for _, v := range a_key {
-		keyMap, _ := v.(map[string]interface{})
-		key, _ := keyMap["key"].([]interface{})
-		keys = append(keys, key)
-	}
-	var allkeys []elastic.KeyConfig //用户配置
-	_bs, err := json.Marshal(a_key)
-	if err == nil {
-		json.Unmarshal(_bs, &allkeys)
-	}
-	list = elastic.GetResForJY(INDEX, TYPE, allkeys, allquery, `"title"`, `{"publishtime":"desc"}`, field, (pageNum-1)*pageSize, pageSize)
-	return
+    if userid == "" {
+        return
+    }
+    tmp := config.Compatible.Select(userid, `{"_id":1,"o_jy":1}`)
+    if tmp == nil || len(*tmp) == 0 {
+        return
+    }
+    o_jy := (*tmp)["o_jy"].(map[string]interface{})
+    a_key, _ := o_jy["a_key"].([]interface{})
+    if len(a_key) == 0 {
+        return
+    }
+    for _, v := range a_key {
+        keyMap, _ := v.(map[string]interface{})
+        key, _ := keyMap["key"].([]interface{})
+        keys = append(keys, key)
+    }
+    var allkeys []elastic.KeyConfig //用户配置
+    _bs, err := json.Marshal(a_key)
+    if err == nil {
+        json.Unmarshal(_bs, &allkeys)
+    }
+    list = elastic.GetResForJY(INDEX, TYPE, allkeys, allquery, `"title"`, `{"publishtime":"desc"}`, field, (pageNum-1)*pageSize, pageSize)
+    return
 }
 
 const (
-	bidField   = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","isValidFile","spidercode","site"`
-	bidTime    = `{"range":{"publishtime":{"gt":%d}}}`
-	bidSort    = `{"publishtime":"desc"}`
-	findfields = `"title"`
+    bidField   = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","buyerclass","budget","bidamount","isValidFile","spidercode","site"`
+    bidTime    = `{"range":{"publishtime":{"gt":%d}}}`
+    bidSort    = `{"publishtime":"desc"}`
+    findfields = `"title"`
 )
 
 type defaultPush struct {
-	UserId     string
-	EntId      int
-	Size       int
-	ModuleFlag string
-	Session    *httpsession.Session
+    UserId     string
+    EntId      int
+    Size       int
+    ModuleFlag string
+    Session    *httpsession.Session
 }
 
 func DefaultPushList(userId, moduleFlag string, entId int) (keyword []byte, list *[]map[string]interface{}, deptId int) {
-	if userId == "" {
-		return
-	}
-	dp := defaultPush{
-		UserId:     userId,
-		EntId:      entId,
-		Size:       50,
-		ModuleFlag: moduleFlag,
-	}
-	scd, deptid := dp.getUserInfo()
-	if len(scd.Keyword) > 0 {
-		deptId = deptid
-		keyword, _ = json.Marshal(scd.Keyword)
-		//获取查询语句
-		qstr := dp.getDefaultDatasSQL(scd)
-		list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, dp.Size, 0, false)
-	}
-	return
+    if userId == "" {
+        return
+    }
+    dp := defaultPush{
+        UserId:     userId,
+        EntId:      entId,
+        Size:       50,
+        ModuleFlag: moduleFlag,
+    }
+    scd, deptid := dp.getUserInfo()
+    if len(scd.Keyword) > 0 {
+        deptId = deptid
+        keyword, _ = json.Marshal(scd.Keyword)
+        //获取查询语句
+        qstr := dp.getDefaultDatasSQL(scd)
+        list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSort, bidField, 0, dp.Size, 0, false)
+    }
+    return
 }
 
 //获取用户信息
 func (d *defaultPush) getUserInfo() (vc *ViewCondition, deptId int) {
-	t1 := time.Now()
-	var isPayBool = false
-	var tmpInfo = struct {
-		Items      []interface{}
-		BuyerClass []interface{}
-		SubType    []interface{}
-		Area       map[string]interface{}
-		SelectType string
-	}{}
-	data := jy.GetBigVipUserBaseMsg(d.Session, *config.Middleground)
-	switch d.ModuleFlag {
-	case "m":
-		//大会员
-		if data.Data.Member.Status > 0 {
-			//订阅词获取
-			o_member_jy := jy.GetSubScribeInfo(d.Session, db.Mgo, "m", "10000")
-			isPayBool = true
-			tmpInfo.Items, _ = (*o_member_jy)["a_items"].([]interface{})
-			tmpInfo.BuyerClass, _ = (*o_member_jy)["a_buyerclass"].([]interface{})
-			tmpInfo.SubType, _ = (*o_member_jy)["a_infotype"].([]interface{})
-			tmpInfo.Area, _ = (*o_member_jy)["o_area"].(map[string]interface{})
-		}
-	case "v":
-		//超级订阅
-		if data.Data.Member.Status > 0 {
-			//订阅词获取
-			o_vipjy := jy.GetSubScribeInfo(d.Session, db.Mgo, "v", "10000")
-			isPayBool = true
-			tmpInfo.Items, _ = (*o_vipjy)["a_items"].([]interface{})
-			tmpInfo.BuyerClass, _ = (*o_vipjy)["a_buyerclass"].([]interface{})
-			tmpInfo.SubType, _ = (*o_vipjy)["a_infotype"].([]interface{})
-			tmpInfo.Area, _ = (*o_vipjy)["o_area"].(map[string]interface{})
-		}
-	case "s":
-		//商机管理
-		entUserId, _ := strconv.Atoi(d.UserId)
-		if d.UserId == "" || d.EntId == 0 {
-			return &ViewCondition{}, 0
-		}
-		var entInfo map[string]interface{}
-		entInfo, deptId = (&es.MatchJob{}).Start(d.EntId, entUserId)
-		if entInfo != nil && len(entInfo) > 0 {
-			isPayBool = true
-			tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
-			tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
-			tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
-			tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
-		}
-	default:
-		//免费用户
-		//订阅词获取
-		o_jy := jy.GetSubScribeInfo(d.Session, db.Mgo, "f", "10000")
-		if (*o_jy)["a_key"] != nil {
-			tmpInfo.Items, _ = (*o_jy)["a_key"].([]interface{})
-			//信息类型
-			tmpInfo.SubType, _ = (*o_jy)["a_infotype"].([]interface{})
-			//省份
-			tmpInfo.Area, _ = (*o_jy)["o_area"].(map[string]interface{})
-			if util.IntAllDef((*o_jy)["i_ppstatus"], 0) == 1 && (*o_jy)["o_area_p"] != nil {
-				tmpInfo.Area, _ = (*o_jy)["o_area_p"].(map[string]interface{})
-			}
-		}
-	}
-	vc = &ViewCondition{
-		Buyerclass: util.ObjArrToStringArr(tmpInfo.BuyerClass),
-		Subtype:    util.ObjArrToStringArr(tmpInfo.SubType),
-		Area:       getStringArrFromDbResult(tmpInfo.Area, 1),
-		City:       getStringArrFromDbResult(tmpInfo.Area, 2),
-		SelectType: "1",
-	}
-	//付费用户
-	if isPayBool {
-		d.Size = 1000
-		vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
-	} else {
-		vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
-	}
-	log.Println("获取用户信息耗时:", time.Since(t1).Seconds())
-	return
+    t1 := time.Now()
+    var isPayBool = false
+    var tmpInfo = struct {
+        Items      []interface{}
+        BuyerClass []interface{}
+        SubType    []interface{}
+        Area       map[string]interface{}
+        SelectType string
+    }{}
+    data := jy.GetBigVipUserBaseMsg(d.Session, *config.Middleground)
+    switch d.ModuleFlag {
+    case "m":
+        //大会员
+        if data.Data.Member.Status > 0 {
+            //订阅词获取
+            o_member_jy := jy.GetSubScribeInfo(d.Session, db.Mgo, "m", "10000")
+            isPayBool = true
+            tmpInfo.Items, _ = (*o_member_jy)["a_items"].([]interface{})
+            tmpInfo.BuyerClass, _ = (*o_member_jy)["a_buyerclass"].([]interface{})
+            tmpInfo.SubType, _ = (*o_member_jy)["a_infotype"].([]interface{})
+            tmpInfo.Area, _ = (*o_member_jy)["o_area"].(map[string]interface{})
+        }
+    case "v":
+        //超级订阅
+        if data.Data.Member.Status > 0 {
+            //订阅词获取
+            o_vipjy := jy.GetSubScribeInfo(d.Session, db.Mgo, "v", "10000")
+            isPayBool = true
+            tmpInfo.Items, _ = (*o_vipjy)["a_items"].([]interface{})
+            tmpInfo.BuyerClass, _ = (*o_vipjy)["a_buyerclass"].([]interface{})
+            tmpInfo.SubType, _ = (*o_vipjy)["a_infotype"].([]interface{})
+            tmpInfo.Area, _ = (*o_vipjy)["o_area"].(map[string]interface{})
+        }
+    case "s":
+        //商机管理
+        entUserId, _ := strconv.Atoi(d.UserId)
+        if d.UserId == "" || d.EntId == 0 {
+            return &ViewCondition{}, 0
+        }
+        var entInfo map[string]interface{}
+        entInfo, deptId = (&es.MatchJob{}).Start(d.EntId, entUserId)
+        if entInfo != nil && len(entInfo) > 0 {
+            isPayBool = true
+            tmpInfo.Items, _ = entInfo["a_items"].([]interface{})
+            tmpInfo.BuyerClass, _ = entInfo["a_buyerclass"].([]interface{})
+            tmpInfo.SubType, _ = entInfo["a_infotype"].([]interface{})
+            tmpInfo.Area, _ = entInfo["o_area"].(map[string]interface{})
+        }
+    default:
+        //免费用户
+        //订阅词获取
+        o_jy := jy.GetSubScribeInfo(d.Session, db.Mgo, "f", "10000")
+        if (*o_jy)["a_key"] != nil {
+            tmpInfo.Items, _ = (*o_jy)["a_key"].([]interface{})
+            //信息类型
+            tmpInfo.SubType, _ = (*o_jy)["a_infotype"].([]interface{})
+            //省份
+            tmpInfo.Area, _ = (*o_jy)["o_area"].(map[string]interface{})
+            if util.IntAllDef((*o_jy)["i_ppstatus"], 0) == 1 && (*o_jy)["o_area_p"] != nil {
+                tmpInfo.Area, _ = (*o_jy)["o_area_p"].(map[string]interface{})
+            }
+        }
+    }
+    vc = &ViewCondition{
+        Buyerclass: util.ObjArrToStringArr(tmpInfo.BuyerClass),
+        Subtype:    util.ObjArrToStringArr(tmpInfo.SubType),
+        Area:       getStringArrFromDbResult(tmpInfo.Area, 1),
+        City:       getStringArrFromDbResult(tmpInfo.Area, 2),
+        SelectType: "1",
+    }
+    //付费用户
+    if isPayBool {
+        d.Size = 1000
+        vc.Keyword = getKeyWordArrFromDbResult(tmpInfo.Items, "", -1)
+    } else {
+        vc.Keyword = getKeyWordArrFromDbResultByFree(tmpInfo.Items, "", -1)
+    }
+    log.Println("获取用户信息耗时:", time.Since(t1).Seconds())
+    return
 }
 
 //获取查询语句
 func (d *defaultPush) getDefaultDatasSQL(scd *ViewCondition) (str string) {
-	query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
-	query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
-	multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
-	query_bool_must_and := `{"bool":{"must":[%s]%s}}`
-	bools := []string{}
-	musts := []string{}
-	//发布时间最新7天
-	musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -7).Unix()))
-	//省份
-	areaCity := []string{}
-	if len(scd.Area) > 0 {
-		areaquery := `{"terms":{"area":[`
-		for k, v := range scd.Area {
-			if k > 0 {
-				areaquery += `,`
-			}
-			areaquery += `"` + v + `"`
-		}
-		areaquery += `]}}`
-		areaCity = append(areaCity, areaquery)
-	}
+    query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
+    query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
+    multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
+    query_bool_must_and := `{"bool":{"must":[%s]%s}}`
+    bools := []string{}
+    musts := []string{}
+    //发布时间最新7天
+    musts = append(musts, fmt.Sprintf(bidTime, time.Now().AddDate(0, 0, -7).Unix()))
+    //省份
+    areaCity := []string{}
+    if len(scd.Area) > 0 {
+        areaquery := `{"terms":{"area":[`
+        for k, v := range scd.Area {
+            if k > 0 {
+                areaquery += `,`
+            }
+            areaquery += `"` + v + `"`
+        }
+        areaquery += `]}}`
+        areaCity = append(areaCity, areaquery)
+    }
 
-	//城市
-	if len(scd.City) > 0 {
-		areaquery := `{"terms":{"city":[`
-		for k, v := range scd.City {
-			if k > 0 {
-				areaquery += `,`
-			}
-			areaquery += `"` + v + `"`
-		}
-		areaquery += `]}}`
-		areaCity = append(areaCity, areaquery)
-	}
-	if len(areaCity) > 0 {
-		musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
-	}
-	if len(scd.Subtype) > 0 {
-		subquery := `{"terms":{"subtype":[`
-		for k, v := range scd.Subtype {
-			if k > 0 {
-				subquery += `,`
-			}
-			subquery += `"` + v + `"`
-		}
-		subquery += `]}}`
-		musts = append(musts, subquery)
-	}
-	if len(scd.Buyerclass) > 0 {
-		Buyerclass := `{"terms":{"buyerclass":[`
-		for k, v := range scd.Buyerclass {
-			if k > 0 {
-				Buyerclass += `,`
-			}
-			Buyerclass += `"` + v + `"`
-		}
-		Buyerclass += `]}}`
-		musts = append(musts, Buyerclass)
-	}
-	boolsNum := 0 //should
-	if len(scd.Keyword) > 0 {
-		boolsNum = 1
-		if scd.SelectType == "" || scd.SelectType == "2" {
-			scd.SelectType = "detail\", \"title"
-		} else {
-			scd.SelectType = "title"
-		}
-		multi_match = fmt.Sprintf(multi_match, "%s", "\""+scd.SelectType+"\"")
+    //城市
+    if len(scd.City) > 0 {
+        areaquery := `{"terms":{"city":[`
+        for k, v := range scd.City {
+            if k > 0 {
+                areaquery += `,`
+            }
+            areaquery += `"` + v + `"`
+        }
+        areaquery += `]}}`
+        areaCity = append(areaCity, areaquery)
+    }
+    if len(areaCity) > 0 {
+        musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
+    }
+    if len(scd.Subtype) > 0 {
+        subquery := `{"terms":{"subtype":[`
+        for k, v := range scd.Subtype {
+            if k > 0 {
+                subquery += `,`
+            }
+            subquery += `"` + v + `"`
+        }
+        subquery += `]}}`
+        musts = append(musts, subquery)
+    }
+    if len(scd.Buyerclass) > 0 {
+        Buyerclass := `{"terms":{"buyerclass":[`
+        for k, v := range scd.Buyerclass {
+            if k > 0 {
+                Buyerclass += `,`
+            }
+            Buyerclass += `"` + v + `"`
+        }
+        Buyerclass += `]}}`
+        musts = append(musts, Buyerclass)
+    }
+    boolsNum := 0 //should
+    if len(scd.Keyword) > 0 {
+        boolsNum = 1
+        if scd.SelectType == "" || scd.SelectType == "2" {
+            scd.SelectType = "detail\", \"title"
+        } else {
+            scd.SelectType = "title"
+        }
+        multi_match = fmt.Sprintf(multi_match, "%s", "\""+scd.SelectType+"\"")
 
-		for _, v := range scd.Keyword {
-			shoulds := []string{}
-			must_not := []string{}
-			//附加词
-			for _, vv := range v.Keyword {
-				vv = strings.TrimSpace(vv)
-				if vv == "" {
-					continue
-				}
-				shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
+        for _, v := range scd.Keyword {
+            shoulds := []string{}
+            must_not := []string{}
+            //附加词
+            for _, vv := range v.Keyword {
+                vv = strings.TrimSpace(vv)
+                if vv == "" {
+                    continue
+                }
+                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+            }
 
-			for _, vv := range v.Appended {
-				vv = strings.TrimSpace(vv)
-				if vv == "" {
-					continue
-				}
-				shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
+            for _, vv := range v.Appended {
+                vv = strings.TrimSpace(vv)
+                if vv == "" {
+                    continue
+                }
+                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+            }
 
-			//排除词
-			for _, vv := range v.Exclude {
-				vv = strings.TrimSpace(vv)
-				if vv == "" {
-					continue
-				}
-				must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
+            //排除词
+            for _, vv := range v.Exclude {
+                vv = strings.TrimSpace(vv)
+                if vv == "" {
+                    continue
+                }
+                must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
+            }
 
-			//添加
-			if len(shoulds) > 0 {
-				notStr := ""
-				if len(must_not) > 0 {
-					notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
-				}
-				bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
-			}
-		}
-	}
+            //添加
+            if len(shoulds) > 0 {
+                notStr := ""
+                if len(must_not) > 0 {
+                    notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
+                }
+                bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
+            }
+        }
+    }
 
-	qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
-	log.Println("----", qstr)
-	return qstr
+    qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
+    log.Println("----", qstr)
+    return qstr
 }

+ 620 - 1019
src/jfw/modules/publicapply/src/subscribePush/entity/keyWords.go

@@ -1,1095 +1,696 @@
 package entity
 
 import (
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"fmt"
-	"jy/src/jfw/modules/publicapply/src/config"
-	"jy/src/jfw/modules/publicapply/src/db"
-	"jy/src/jfw/modules/publicapply/src/util"
-	"strconv"
-	"strings"
-	"time"
-
-	"go.mongodb.org/mongo-driver/bson"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "fmt"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
+    "jy/src/jfw/modules/publicapply/src/util"
+    "strconv"
+    "strings"
+    "time"
+
+    "go.mongodb.org/mongo-driver/bson"
 )
 
 type KeyWordsSet struct {
-	ClassifyIndex string   //分类索引
-	ClassifyName  string   //分类名称
-	KeyWordIndex  string   //关键词索引
-	KeyWordName   string   //关键词名称
-	ActionType    string   //操作类型 SK:保存/修改关键词; DK:删除关键词; SC:保存/修改分类  DC:删除分类
-	AppendKeyWord []string //附加词
-	NotKeyWord    []string //排除词
-	MatchWay      int      // 单个关键词匹配方事 0:精准匹配 1:模糊匹配
-	KeyWordsCount string   //是否是首次添加关键词
-	Type          string   // 大会员/超级订阅
-	UserId        string   //用户id
-	DeleteKey     string   //删除的关键词 json字符串{"0":"1,2","2":"0,3"} key:分类名称索引  value:分类名称下的关键词索引
-	Power         int
-	EntId         int
-	EntUserId     int
-	Session       *httpsession.Session
+    ClassifyIndex string   //分类索引
+    ClassifyName  string   //分类名称
+    KeyWordIndex  string   //关键词索引
+    KeyWordName   string   //关键词名称
+    ActionType    string   //操作类型 SK:保存/修改关键词; DK:删除关键词; SC:保存/修改分类  DC:删除分类
+    AppendKeyWord []string //附加词
+    NotKeyWord    []string //排除词
+    MatchWay      int      // 单个关键词匹配方事 0:精准匹配 1:模糊匹配
+    KeyWordsCount string   //是否是首次添加关键词
+    Type          string   // 大会员/超级订阅
+    UserId        string   //用户id
+    DeleteKey     string   //删除的关键词 json字符串{"0":"1,2","2":"0,3"} key:分类名称索引  value:分类名称下的关键词索引
+    Power         int
+    EntId         int
+    EntUserId     int
+    Session       *httpsession.Session
 }
 
 func (this *KeyWordsSet) UpdateKeyWords() map[string]interface{} {
-	power := jy.GetBigVipUserBaseMsg(this.Session, *config.Middleground)
-	if this.Type == "m" && power.Status < 0 {
-		return map[string]interface{}{"flag": false, "msg": "暂无权限"}
-	}
-	types := "o_jy"
-	if this.Type == "m" {
-		types = "o_member_jy"
-	} else if this.Type == "v" {
-		types = "o_vipjy"
-	}
-	//付费用户
-	if this.Type != "f" && (power.Status > 0 || power.VipStatus > 0) {
-		switch this.ActionType {
-		case "SK": //保存/修改关键词
-			return AddKeyWords(types, this.UserId, this.ClassifyIndex, this.ClassifyName, this.KeyWordIndex, this.KeyWordName, this.KeyWordsCount, this.NotKeyWord, this.AppendKeyWord, this.MatchWay, this.Session)
-		case "DK": //删除关键词
-			return DeleteKeyWords(types, this.DeleteKey, this.UserId, this.Session)
-		case "SC": //保存/修改分类
-			return AddClass(types, this.ClassifyIndex, this.ClassifyName, this.UserId, this.Session)
-		case "DC": //删除分类
-			return DeleteClass(types, this.ClassifyIndex, this.UserId, this.Session)
-		case "directSubKWS": //搜索列表直接订阅关键词
-			return directSubKWS(types, this.KeyWordName, this.UserId, this.Session)
-		}
-	} else {
-		this.ClassifyIndex = "0"
-		this.ClassifyName = "未分类"
-		switch this.ActionType {
-		case "SK": //保存/修改关键词
-			return AddKeyWordsFree(types, this.UserId, this.ClassifyIndex, this.ClassifyName, this.KeyWordIndex, this.KeyWordName, this.KeyWordsCount, this.NotKeyWord, this.AppendKeyWord, this.MatchWay, this.Session)
-		case "DK": //删除关键词
-			return DeleteKeyWordsFree(types, this.DeleteKey, this.Session)
-		case "directSubKWS": //搜索列表直接订阅关键词
-			return directSubKWSFree(types, this.KeyWordName, this.Session)
-		}
-	}
-	return map[string]interface{}{"flag": true, "msg": ""}
+    power := jy.GetBigVipUserBaseMsg(this.Session, *config.Middleground)
+    if this.Type == "m" && power.Status < 0 {
+        return map[string]interface{}{"flag": false, "msg": "暂无权限"}
+    }
+    types := "o_jy"
+    if this.Type == "m" {
+        types = "o_member_jy"
+    } else if this.Type == "v" {
+        types = "o_vipjy"
+    }
+    //付费用户
+    if this.Type != "f" && (power.Status > 0 || power.VipStatus > 0) {
+        switch this.ActionType {
+        case "SK": //保存/修改关键词
+            return AddKeyWords(types, this.UserId, this.ClassifyIndex, this.ClassifyName, this.KeyWordIndex, this.KeyWordName, this.KeyWordsCount, this.NotKeyWord, this.AppendKeyWord, this.MatchWay, this.Session)
+        case "DK": //删除关键词
+            return DeleteKeyWords(types, this.DeleteKey, this.UserId, this.Session)
+        case "SC": //保存/修改分类
+            return AddClass(types, this.ClassifyIndex, this.ClassifyName, this.UserId, this.Session)
+        case "DC": //删除分类
+            return DeleteClass(types, this.ClassifyIndex, this.UserId, this.Session)
+        case "directSubKWS": //搜索列表直接订阅关键词
+            return directSubKWS(types, this.KeyWordName, this.UserId, this.Session)
+        }
+    } else {
+        this.ClassifyIndex = "0"
+        this.ClassifyName = "未分类"
+        switch this.ActionType {
+        case "SK": //保存/修改关键词
+            return AddKeyWordsFree(types, this.UserId, this.ClassifyIndex, this.ClassifyName, this.KeyWordIndex, this.KeyWordName, this.KeyWordsCount, this.NotKeyWord, this.AppendKeyWord, this.MatchWay, this.Session)
+        case "DK": //删除关键词
+            return DeleteKeyWordsFree(types, this.DeleteKey, this.Session)
+        case "directSubKWS": //搜索列表直接订阅关键词
+            return directSubKWSFree(types, this.KeyWordName, this.Session)
+        }
+    }
+    return map[string]interface{}{"flag": true, "msg": ""}
 }
 
 //
 func directSubKWSFree(types string, keys string, session *httpsession.Session) map[string]interface{} {
-	userId := qutil.ObjToString(session.Get("userId"))
-	var repleat = false
-	var kwsCount = 0
-	if len([]rune(keys)) > 20 {
-		keys = qutil.SubString(keys, 0, 20)
-	}
-	positionType := qutil.Int64All(session.Get("positionType"))
-	query := map[string]interface{}{
-		"i_userid": qutil.Int64All(session.Get("entUserId")),
-		"i_entid":  qutil.Int64All(session.Get("entId")),
-		"i_type":   1,
-	}
-	flag := "n"
-	updateObj := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
-	if updateObj != nil && len(*updateObj) > 0 && keys != "" {
-		if (*updateObj)["a_key"] != nil && len(qutil.ObjArrToMapArr((*updateObj)["a_key"].([]interface{}))) > 0 {
-			a_key := (*updateObj)["a_key"].([]interface{})
-			for _, n := range a_key {
-				ntmp := qutil.ObjToMap(n.(interface{}))
-				nkey := qutil.ObjArrToStringArr((*ntmp)["key"].([]interface{}))
-				if strings.Join(nkey, " ") == keys {
-					repleat = true
-					break
-				}
-			}
-		} else {
-			//无关键词 直接添加
-			if positionType == 0 {
-				if ok := db.Mgo.UpdateById("user", userId, bson.M{"$set": bson.M{
-					fmt.Sprintf("%s.a_key", types): bson.A{
-						bson.M{
-							"key":        bson.A{keys},
-							"appendkey":  bson.A{},
-							"notkey":     bson.A{},
-							"updatetime": time.Now().Unix(),
-						},
-					},
-					types + ".l_modifydate": time.Now().Unix(),
-					// types + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
-				},
-				}); ok {
-					flag = "y"
-				}
-			} else {
-				if ok := db.Mgo.Update("entniche_rule", query, bson.M{"$set": bson.M{
-					fmt.Sprintf("%s.a_key", types): bson.A{
-						bson.M{
-							"key":        bson.A{keys},
-							"appendkey":  bson.A{},
-							"notkey":     bson.A{},
-							"updatetime": time.Now().Unix(),
-						},
-					},
-					types + ".l_modifydate": time.Now().Unix(),
-					// types + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
-				},
-				}, true, false); ok {
-					flag = "y"
-				}
-			}
-
-			return map[string]interface{}{"flag": flag}
-		}
-		if repleat {
-			flag = "o"
-		} else if kwsCount >= 10 {
-			flag = "m"
-		} else {
-			var _key = make(map[string]interface{})
-			var a_key = make([]map[string]interface{}, 1)
-			classify_name := "未分类"
-			_key["key"] = strings.Split(strings.ReplaceAll(keys, " ", ""), " ")
-			_key["appendkey"] = []string{}
-			_key["notkey"] = []string{}
-			_key["updatetime"] = time.Now().Unix()
-			a_key[0] = _key
-			if len(a_key) > 0 {
-				ok := false
-				if positionType == 0 {
-					ok = db.Mgo.UpdateById("user", userId, bson.M{
-						"$push": bson.M{
-							types + ".a_key": bson.M{
-								"$each": a_key,
-							},
-						},
-						"$set": bson.M{
-							types + ".l_modifydate": time.Now().Unix(),
-							types + ".s_item":       classify_name,
-							// updateItems + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
-						},
-					})
-				} else {
-					ok = db.Mgo.Update("entniche_rule", query, bson.M{
-						"$push": bson.M{
-							types + ".a_key": bson.M{
-								"$each": a_key,
-							},
-						},
-						"$set": bson.M{
-							types + ".l_modifydate": time.Now().Unix(),
-							types + ".s_item":       classify_name,
-							// updateItems + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
-						},
-					}, true, false)
-				}
-				if ok {
-					flag = "y"
-				}
-			}
-		}
-	}
-	if flag == "y" {
-		//清楚缓存
-		jy.ClearBigVipUserPower(userId)
-	}
-	return map[string]interface{}{"flag": flag}
+    userId := qutil.ObjToString(session.Get("userId"))
+    var repleat = false
+    var kwsCount = 0
+    if len([]rune(keys)) > 20 {
+        keys = qutil.SubString(keys, 0, 20)
+    }
+    flag := "n"
+    updateObj := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
+    if updateObj != nil && len(*updateObj) > 0 && keys != "" {
+        if (*updateObj)["a_key"] != nil && len(qutil.ObjArrToMapArr((*updateObj)["a_key"].([]interface{}))) > 0 {
+            a_key := (*updateObj)["a_key"].([]interface{})
+            for _, n := range a_key {
+                ntmp := qutil.ObjToMap(n.(interface{}))
+                nkey := qutil.ObjArrToStringArr((*ntmp)["key"].([]interface{}))
+                if strings.Join(nkey, " ") == keys {
+                    repleat = true
+                    break
+                }
+            }
+        } else {
+            //无关键词 直接添加
+            if ok := config.Compatible.Update(userId, bson.M{"$set": bson.M{
+                fmt.Sprintf("%s.a_key", types): bson.A{
+                    bson.M{
+                        "key":        bson.A{keys},
+                        "appendkey":  bson.A{},
+                        "notkey":     bson.A{},
+                        "updatetime": time.Now().Unix(),
+                    },
+                },
+                types + ".l_modifydate": time.Now().Unix(),
+            },
+            }); ok {
+                flag = "y"
+            }
+            return map[string]interface{}{"flag": flag}
+        }
+        if repleat {
+            flag = "o"
+        } else if kwsCount >= 10 {
+            flag = "m"
+        } else {
+            var _key = make(map[string]interface{})
+            var a_key = make([]map[string]interface{}, 1)
+            classify_name := "未分类"
+            _key["key"] = strings.Split(strings.ReplaceAll(keys, " ", ""), " ")
+            _key["appendkey"] = []string{}
+            _key["notkey"] = []string{}
+            _key["updatetime"] = time.Now().Unix()
+            a_key[0] = _key
+            if len(a_key) > 0 {
+                ok := false
+                ok = config.Compatible.Update(userId, bson.M{
+                    "$push": bson.M{
+                        types + ".a_key": bson.M{
+                            "$each": a_key,
+                        },
+                    },
+                    "$set": bson.M{
+                        types + ".l_modifydate": time.Now().Unix(),
+                        types + ".s_item":       classify_name,
+                        // updateItems + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
+                    },
+                })
+                if ok {
+                    flag = "y"
+                }
+            }
+        }
+    }
+    if flag == "y" {
+        //清楚缓存
+        positionId := qutil.InterfaceToStr(session.Get("positionId"))
+        jy.ClearBigVipUserPower(positionId)
+    }
+    return map[string]interface{}{"flag": flag}
 }
 
 //免费用户删除关键词
 func DeleteKeyWordsFree(types, deletekey string, session *httpsession.Session) map[string]interface{} {
-	//免费用户只有一个分类
-	var index = "0"
-	userId := qutil.ObjToString(session.Get("userId"))
-	dMap, err := util.JsonToMap(deletekey)
-	newMap, saveData := []interface{}{}, map[string]interface{}{}
-	if err == nil && len(dMap) > 0 {
-		data := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
-		if data != nil && len(*data) > 0 {
-			ojy, _ := (*data)[types].(map[string]interface{})
-			a_key, _ := ojy["a_key"].([]interface{})
-			if dMap[index] != nil {
-				keyarrs := qutil.ObjArrToMapArr(a_key)
-				for kk, vk := range keyarrs {
-					if util.IsContain(strings.Split(dMap[index].(string), ","), strconv.Itoa(kk)) {
-						continue
-					}
-					newMap = append(newMap, vk)
-				}
-				saveData[types+".a_key"] = newMap
-			}
-		}
-	}
-	flag := true
-	if len(saveData) > 0 {
-		positionType := qutil.Int64All(session.Get("positionType"))
-		if positionType == 0 {
-			flag = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-		} else {
-			query := map[string]interface{}{
-				"i_userid": qutil.Int64All(session.Get("entUserId")),
-				"i_entid":  qutil.Int64All(session.Get("entId")),
-				"i_type":   1,
-			}
-			flag = db.Mgo.Update("entniche_rule", query, map[string]interface{}{"$set": saveData}, true, false)
-
-		}
-		SetLog(userId, types, 0, session)
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    //免费用户只有一个分类
+    var index = "0"
+    userId := qutil.ObjToString(session.Get("userId"))
+    dMap, err := util.JsonToMap(deletekey)
+    newMap, saveData := []interface{}{}, map[string]interface{}{}
+    if err == nil && len(dMap) > 0 {
+        data := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
+        if data != nil && len(*data) > 0 {
+            ojy, _ := (*data)[types].(map[string]interface{})
+            a_key, _ := ojy["a_key"].([]interface{})
+            if dMap[index] != nil {
+                keyarrs := qutil.ObjArrToMapArr(a_key)
+                for kk, vk := range keyarrs {
+                    if util.IsContain(strings.Split(dMap[index].(string), ","), strconv.Itoa(kk)) {
+                        continue
+                    }
+                    newMap = append(newMap, vk)
+                }
+                saveData[types+".a_key"] = newMap
+            }
+        }
+    }
+    flag := true
+    if len(saveData) > 0 {
+        flag = config.Compatible.Update(userId, map[string]interface{}{
+            "$set": saveData,
+        })
+        SetLog(userId, types, 0, session)
+    }
+    return map[string]interface{}{"flag": flag, "msg": ""}
 }
 
 //免费用户修改 保存关键词
 func AddKeyWordsFree(types, userId, classIndex, className, keywordsIndex, keywordName, keywordCount string, notKeyword, appendKeyword []string, matchWay int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	data := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
-	saveData := map[string]interface{}{}
-	positionType := qutil.Int64All(session.Get("positionType"))
-	query := map[string]interface{}{
-		"i_userid": qutil.Int64All(session.Get("entUserId")),
-		"i_entid":  qutil.Int64All(session.Get("entId")),
-		"i_type":   1,
-	}
-	if data != nil && len(*data) > 0 {
-		a_items := make([]interface{}, 0)
-		ojy, _ := (*data)[types].(map[string]interface{})
-		a_key, errs := (*data)["a_key"].([]interface{})
-		if !errs {
-
-			if positionType == 0 {
-				db.Mgo.UpdateById("user", userId, map[string]interface{}{
-					"$set": map[string]interface{}{
-						types + ".a_key": []map[string]interface{}{},
-						// types + ".i_newfree": 1, //老免费用户=>新订阅设置页面 20211122
-					},
-				})
-			} else {
-
-				db.Mgo.Update("entniche_rule", query, map[string]interface{}{"$set": map[string]interface{}{
-					"o_entniche.a_key": []map[string]interface{}{},
-				}}, true, false)
-			}
-
-		}
-		if ki, _ := strconv.Atoi(keywordsIndex); ki > len(a_key) {
-			keywordsIndex = strconv.Itoa(len(a_key))
-		} else if ki == 0 {
-			keywordsIndex = strconv.Itoa(ki)
-		}
-		a_items = append(a_items, ojy)
-		//排除词处理 词过长或者为空的情况
-		if len(notKeyword) > 0 {
-			for i, notval := range notKeyword {
-				if len([]rune(notval)) > 20 {
-					notval = qutil.SubString(notval, 0, 20)
-				}
-				if notval == "" {
-					notKeyword = append(notKeyword[:i], notKeyword[i+1:]...)
-				}
-			}
-		}
-		var _kws []string //关键词
-		for _, kn := range strings.Split(keywordName, " ") {
-			if kn != "" {
-				_kws = append(_kws, kn)
-			}
-		}
-		var _key = make(map[string]interface{})
-		newKws := []string{_kws[0]} //第一个关键词在key中 后边的存入appendkey
-		_key["key"] = newKws
-		_key["appendkey"] = append(appendKeyword, _kws[1:]...)
-		_key["notkey"] = notKeyword
-		_key["matchway"] = matchWay //matchway 0:精准匹配 1:模糊匹配
-		if KeyWordsRepeat(_key, a_items) {
-			return map[string]interface{}{"flag": false, "msg": "关键词已存在"}
-		} else {
-			//修改关键词
-			saveData[types+".s_item"] = className
-			// saveData[types+".i_newfree"] = 1 //老免费用户=>新订阅设置页面 20211122
-			saveData[types+".a_key."+keywordsIndex+".key"] = newKws
-			saveData[types+".a_key."+keywordsIndex+".appendkey"] = append(appendKeyword, _kws[1:]...)
-			saveData[types+".a_key."+keywordsIndex+".notkey"] = notKeyword
-			saveData[types+".a_key."+keywordsIndex+".matchway"] = matchWay
-			saveData[types+".a_key."+keywordsIndex+".updatetime"] = time.Now().Unix()
-		}
-	}
-	if len(saveData) > 0 {
-		ok := false
-		if positionType == 0 {
-			ok = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-		} else {
-			ok = db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-				"$set": saveData,
-			}, true, false)
-		}
-		if ok {
-			flag = true
-			//清楚缓存
-			jy.ClearBigVipUserPower(userId)
-		}
-		SetLog(userId, types, 0, session)
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    flag := true
+    data := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
+    saveData := map[string]interface{}{}
+    if data != nil && len(*data) > 0 {
+        a_items := make([]interface{}, 0)
+        ojy, _ := (*data)[types].(map[string]interface{})
+        a_key, errs := (*data)["a_key"].([]interface{})
+        if !errs {
+            config.Compatible.Update(userId, map[string]interface{}{
+                "$set": map[string]interface{}{
+                    types + ".a_key": []map[string]interface{}{},
+                    // types + ".i_newfree": 1, //老免费用户=>新订阅设置页面 20211122
+                },
+            })
+        }
+        if ki, _ := strconv.Atoi(keywordsIndex); ki > len(a_key) {
+            keywordsIndex = strconv.Itoa(len(a_key))
+        } else if ki == 0 {
+            keywordsIndex = strconv.Itoa(ki)
+        }
+        a_items = append(a_items, ojy)
+        //排除词处理 词过长或者为空的情况
+        if len(notKeyword) > 0 {
+            for i, notval := range notKeyword {
+                if len([]rune(notval)) > 20 {
+                    notval = qutil.SubString(notval, 0, 20)
+                }
+                if notval == "" {
+                    notKeyword = append(notKeyword[:i], notKeyword[i+1:]...)
+                }
+            }
+        }
+        var _kws []string //关键词
+        for _, kn := range strings.Split(keywordName, " ") {
+            if kn != "" {
+                _kws = append(_kws, kn)
+            }
+        }
+        var _key = make(map[string]interface{})
+        newKws := []string{_kws[0]} //第一个关键词在key中 后边的存入appendkey
+        _key["key"] = newKws
+        _key["appendkey"] = append(appendKeyword, _kws[1:]...)
+        _key["notkey"] = notKeyword
+        _key["matchway"] = matchWay //matchway 0:精准匹配 1:模糊匹配
+        if KeyWordsRepeat(_key, a_items) {
+            return map[string]interface{}{"flag": false, "msg": "关键词已存在"}
+        } else {
+            //修改关键词
+            saveData[types+".s_item"] = className
+            // saveData[types+".i_newfree"] = 1 //老免费用户=>新订阅设置页面 20211122
+            saveData[types+".a_key."+keywordsIndex+".key"] = newKws
+            saveData[types+".a_key."+keywordsIndex+".appendkey"] = append(appendKeyword, _kws[1:]...)
+            saveData[types+".a_key."+keywordsIndex+".notkey"] = notKeyword
+            saveData[types+".a_key."+keywordsIndex+".matchway"] = matchWay
+            saveData[types+".a_key."+keywordsIndex+".updatetime"] = time.Now().Unix()
+        }
+    }
+    if len(saveData) > 0 {
+        ok := false
+        ok = config.Compatible.Update(userId, map[string]interface{}{
+            "$set": saveData,
+        })
+
+        if ok {
+            flag = true
+            //清楚缓存
+            positionId := qutil.InterfaceToStr(session.Get("positionId"))
+            jy.ClearBigVipUserPower(positionId)
+        }
+        SetLog(userId, types, 0, session)
+    }
+    return map[string]interface{}{"flag": flag, "msg": ""}
 }
 
 //保存/修改关键词
 func AddKeyWords(types, userId, classIndex, className, keywordsIndex, keywordName, keywordCount string, notKeyword, appendKeyword []string, matchWay int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 0 {
-		//个人版
-		data, ok := db.Mgo.FindById("user", userId, `{"`+types+`.a_items":1}`)
-		saveData := map[string]interface{}{}
-		if ok && data != nil && len(*data) > 0 {
-			ojy, _ := (*data)[types].(map[string]interface{})
-			a_items, errs := ojy["a_items"].([]interface{})
-			if !errs {
-				db.Mgo.UpdateById("user", userId, map[string]interface{}{
-					"$set": map[string]interface{}{
-						types + ".a_items": []map[string]interface{}{},
-					},
-				})
-			}
-			//附加词处理
-			if len(appendKeyword) > 0 {
-				for i, addval := range appendKeyword {
-					if len([]rune(addval)) > 20 {
-						addval = qutil.SubString(addval, 0, 20)
-					}
-					if addval == "" {
-						appendKeyword = append(appendKeyword[:i], appendKeyword[i+1:]...)
-					}
-				}
-			}
-			//排除词处理 词过长或者为空的情况
-			if len(notKeyword) > 0 {
-				for i, notval := range notKeyword {
-					if len([]rune(notval)) > 20 {
-						notval = qutil.SubString(notval, 0, 20)
-					}
-					if notval == "" {
-						notKeyword = append(notKeyword[:i], notKeyword[i+1:]...)
-					}
-				}
-			}
-			var _kws []string //关键词
-			for _, kn := range strings.Split(keywordName, " ") {
-				if kn != "" {
-					_kws = append(_kws, kn)
-				}
-			}
-			var _key = make(map[string]interface{})
-			newKws := []string{_kws[0]} //第一个关键词在key中 后边的存入appendkey
-			_key["key"] = newKws
-			_key["appendkey"] = append(appendKeyword, _kws[1:]...)
-			_key["notkey"] = notKeyword
-			_key["matchway"] = matchWay //matchway 0:精准匹配 1:模糊匹配
-			if KeyWordsRepeat(_key, a_items) {
-				return map[string]interface{}{"flag": false, "msg": "关键词已存在"}
-			} else {
-				//修改关键词
-				saveData[types+".a_items."+classIndex+".s_item"] = className
-				saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".key"] = newKws
-				saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".appendkey"] = append(appendKeyword, _kws[1:]...)
-				saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".notkey"] = notKeyword
-				saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".matchway"] = matchWay
-				saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".updatetime"] = time.Now().Unix()
-			}
-		}
-
-		if len(saveData) > 0 {
-			flag = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-			SetLog(userId, types, positionType, session)
-		}
-	} else {
-		//企业个人版
-		//先查看有没有关键词
-		types := "o_entniche"
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		data, ok := db.Mgo.Find("entniche_rule", query, `{"`+types+`.a_items":1}`, nil, false, -1, -1)
-		saveData := map[string]interface{}{}
-		if !ok || data == nil || len(*data) == 0 {
-			db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"o_entniche.a_items": []map[string]interface{}{},
-					"l_updatetime":       time.Now().Unix(),
-				}}, true, false)
-		}
-		//entniche_rule有数据
-		ojy, _ := (*data)[0][types].(map[string]interface{})
-		a_items, errs := ojy["a_items"].([]interface{})
-		if !errs {
-			db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"o_entniche.a_items": []map[string]interface{}{},
-				}}, true, false)
-		}
-		//附加词处理
-		if len(appendKeyword) > 0 {
-			for i, addval := range appendKeyword {
-				if len([]rune(addval)) > 20 {
-					addval = qutil.SubString(addval, 0, 20)
-				}
-				if addval == "" {
-					appendKeyword = append(appendKeyword[:i], appendKeyword[i+1:]...)
-				}
-			}
-		}
-		//排除词处理 词过长或者为空的情况
-		if len(notKeyword) > 0 {
-			for i, notval := range notKeyword {
-				if len([]rune(notval)) > 20 {
-					notval = qutil.SubString(notval, 0, 20)
-				}
-				if notval == "" {
-					notKeyword = append(notKeyword[:i], notKeyword[i+1:]...)
-				}
-			}
-		}
-		var _kws []string //关键词
-		for _, kn := range strings.Split(keywordName, " ") {
-			if kn != "" {
-				_kws = append(_kws, kn)
-			}
-		}
-		var _key = make(map[string]interface{})
-		newKws := []string{_kws[0]} //第一个关键词在key中 后边的存入appendkey
-		_key["key"] = newKws
-		_key["appendkey"] = append(appendKeyword, _kws[1:]...)
-		_key["notkey"] = notKeyword
-		_key["updatetime"] = time.Now().Unix()
-		_key["matchway"] = matchWay //matchway 0:精准匹配 1:模糊匹配
-		if KeyWordsRepeat(_key, a_items) {
-			return map[string]interface{}{"flag": false, "msg": "关键词已存在"}
-		} else {
-			//修改关键词
-			saveData[types+".a_items."+classIndex+".s_item"] = className
-			saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".key"] = newKws
-			saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".appendkey"] = append(appendKeyword, _kws[1:]...)
-			saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".notkey"] = notKeyword
-			saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".matchway"] = matchWay
-			saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".updatetime"] = time.Now().Unix()
-		}
-
-		saveData["l_updatetime"] = time.Now().Unix()
-		flag = db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-			"$set": saveData,
-		}, true, false)
-		SetLog(userId, types, positionType, session)
-	}
-
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    flag := true
+    positionType := qutil.Int64All(session.Get("positionType"))
+    data := config.Compatible.Select(userId, `{"`+types+`.a_items":1}`)
+    saveData := map[string]interface{}{}
+    if data != nil && len(*data) > 0 {
+        ojy, _ := (*data)[types].(map[string]interface{})
+        a_items, errs := ojy["a_items"].([]interface{})
+        if !errs {
+            config.Compatible.Update(userId, map[string]interface{}{
+                "$set": map[string]interface{}{
+                    types + ".a_items": []map[string]interface{}{},
+                },
+            })
+        }
+        //附加词处理
+        if len(appendKeyword) > 0 {
+            for i, addval := range appendKeyword {
+                if len([]rune(addval)) > 20 {
+                    addval = qutil.SubString(addval, 0, 20)
+                }
+                if addval == "" {
+                    appendKeyword = append(appendKeyword[:i], appendKeyword[i+1:]...)
+                }
+            }
+        }
+        //排除词处理 词过长或者为空的情况
+        if len(notKeyword) > 0 {
+            for i, notval := range notKeyword {
+                if len([]rune(notval)) > 20 {
+                    notval = qutil.SubString(notval, 0, 20)
+                }
+                if notval == "" {
+                    notKeyword = append(notKeyword[:i], notKeyword[i+1:]...)
+                }
+            }
+        }
+        var _kws []string //关键词
+        for _, kn := range strings.Split(keywordName, " ") {
+            if kn != "" {
+                _kws = append(_kws, kn)
+            }
+        }
+        var _key = make(map[string]interface{})
+        newKws := []string{_kws[0]} //第一个关键词在key中 后边的存入appendkey
+        _key["key"] = newKws
+        _key["appendkey"] = append(appendKeyword, _kws[1:]...)
+        _key["notkey"] = notKeyword
+        _key["matchway"] = matchWay //matchway 0:精准匹配 1:模糊匹配
+        if KeyWordsRepeat(_key, a_items) {
+            return map[string]interface{}{"flag": false, "msg": "关键词已存在"}
+        } else {
+            //修改关键词
+            saveData[types+".a_items."+classIndex+".s_item"] = className
+            saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".key"] = newKws
+            saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".appendkey"] = append(appendKeyword, _kws[1:]...)
+            saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".notkey"] = notKeyword
+            saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".matchway"] = matchWay
+            saveData[types+".a_items."+classIndex+".a_key."+keywordsIndex+".updatetime"] = time.Now().Unix()
+        }
+    }
+
+    if len(saveData) > 0 {
+        flag = config.Compatible.Update(userId, map[string]interface{}{
+            "$set": saveData,
+        })
+        SetLog(userId, types, positionType, session)
+    }
+    return map[string]interface{}{"flag": flag, "msg": ""}
 }
 
 //删除关键词可以批量
 func DeleteKeyWords(types, deletekey, userId string, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 0 {
-		dMap, err := util.JsonToMap(deletekey)
-		newMap, saveData := []interface{}{}, map[string]interface{}{}
-		if err == nil && len(dMap) > 0 {
-			data, ok := db.Mgo.FindById("user", userId, `{"`+types+`.a_items":1}`)
-			if data != nil && ok && len(*data) > 0 {
-				ojy, _ := (*data)[types].(map[string]interface{})
-				a_items, _ := ojy["a_items"].([]interface{})
-				for k, v := range a_items {
-					newItems := map[string]interface{}{}
-					if dMap[strconv.Itoa(k)] != nil {
-						if items, ok := v.(map[string]interface{}); ok && len(items) > 0 {
-							for kk, vv := range items {
-								new_vv := vv
-								new_m := []map[string]interface{}{}
-								if kk == "a_key" {
-									keyarrs := qutil.ObjArrToMapArr(vv.([]interface{}))
-									for kk, vk := range keyarrs {
-										if util.IsContain(strings.Split(dMap[strconv.Itoa(k)].(string), ","), strconv.Itoa(kk)) {
-											continue
-										}
-										new_m = append(new_m, vk)
-									}
-									new_vv = new_m
-								}
-								newItems[kk] = new_vv
-							}
-						}
-						newMap = append(newMap, newItems)
-					} else {
-						newMap = append(newMap, v)
-					}
-				}
-			}
-			saveData[types+".a_items"] = newMap
-		}
-		if len(saveData) > 0 {
-			flag = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-			SetLog(userId, types, 0, session)
-		}
-	} else {
-		types := "o_entniche"
-		dMap, err := util.JsonToMap(deletekey)
-		newMap := []interface{}{}
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		if err == nil && len(dMap) > 0 {
-			data, ok := db.Mgo.Find("entniche_rule", query, `{"o_entniche.a_items":1}`, nil, false, -1, -1)
-			if data == nil || !ok || len(*data) == 0 {
-				return map[string]interface{}{"flag": flag, "msg": ""}
-			}
-			ojy, _ := (*data)[0][types].(map[string]interface{})
-			a_items, _ := ojy["a_items"].([]interface{})
-			for k, v := range a_items {
-				newItems := map[string]interface{}{}
-				if dMap[strconv.Itoa(k)] != nil {
-					if items, ok := v.(map[string]interface{}); ok && len(items) > 0 {
-						for kk, vv := range items {
-							new_vv := vv
-							new_m := []map[string]interface{}{}
-							if kk == "a_key" {
-								keyarrs := qutil.ObjArrToMapArr(vv.([]interface{}))
-								for kk, vk := range keyarrs {
-									if util.IsContain(strings.Split(dMap[strconv.Itoa(k)].(string), ","), strconv.Itoa(kk)) {
-										continue
-									}
-									new_m = append(new_m, vk)
-								}
-								new_vv = new_m
-							}
-							newItems[kk] = new_vv
-						}
-					}
-					newMap = append(newMap, newItems)
-				} else {
-					newMap = append(newMap, v)
-				}
-			}
-		}
-
-		if len(newMap) > 0 {
-			flag = db.Mgo.Update("entniche_rule", query, bson.M{"$set": bson.M{
-				"l_updatetime":       time.Now().Unix(),
-				"o_entniche.a_items": newMap,
-			}}, true, false)
-			SetLog(userId, types, positionType, session)
-		}
-
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    flag := true
+    dMap, err := util.JsonToMap(deletekey)
+    newMap, saveData := []interface{}{}, map[string]interface{}{}
+    if err == nil && len(dMap) > 0 {
+        data := config.Compatible.Select(userId, `{"`+types+`.a_items":1}`)
+        if data != nil && len(*data) > 0 {
+            ojy, _ := (*data)[types].(map[string]interface{})
+            a_items, _ := ojy["a_items"].([]interface{})
+            for k, v := range a_items {
+                newItems := map[string]interface{}{}
+                if dMap[strconv.Itoa(k)] != nil {
+                    if items, ok := v.(map[string]interface{}); ok && len(items) > 0 {
+                        for kk, vv := range items {
+                            new_vv := vv
+                            new_m := []map[string]interface{}{}
+                            if kk == "a_key" {
+                                keyarrs := qutil.ObjArrToMapArr(vv.([]interface{}))
+                                for kk, vk := range keyarrs {
+                                    if util.IsContain(strings.Split(dMap[strconv.Itoa(k)].(string), ","), strconv.Itoa(kk)) {
+                                        continue
+                                    }
+                                    new_m = append(new_m, vk)
+                                }
+                                new_vv = new_m
+                            }
+                            newItems[kk] = new_vv
+                        }
+                    }
+                    newMap = append(newMap, newItems)
+                } else {
+                    newMap = append(newMap, v)
+                }
+            }
+        }
+        saveData[types+".a_items"] = newMap
+    }
+    if len(saveData) > 0 {
+        flag = config.Compatible.Update(userId, map[string]interface{}{
+            "$set": saveData,
+        })
+        SetLog(userId, types, 0, session)
+    }
+    return map[string]interface{}{"flag": flag, "msg": ""}
 }
 
 //删除分类【可以批量删除】
 func DeleteClass(types, classIndex, userId string, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 0 {
-		items, saveData := []interface{}{}, map[string]interface{}{}
-		m := map[string]bool{}
-		for _, v := range strings.Split(classIndex, ",") {
-			m[v] = true
-		}
-		data, ok := db.Mgo.FindById("user", userId, `{"`+types+`.a_items":1}`)
-		if data != nil && ok && len(*data) > 0 {
-			ojy, _ := (*data)[types].(map[string]interface{})
-			a_items, _ := ojy["a_items"].([]interface{})
-			for k, v := range a_items {
-				if !m[strconv.Itoa(k)] {
-					items = append(items, v)
-				}
-			}
-		}
-		saveData[types+".a_items"] = items
-
-		if len(saveData) > 0 {
-			flag = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-			SetLog(userId, types, 0, session)
-		}
-	} else {
-		types := "o_entniche"
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		items := []interface{}{}
-		m := map[string]bool{}
-		for _, v := range strings.Split(classIndex, ",") {
-			m[v] = true
-		}
-		data, ok := db.Mgo.Find("entniche_rule", query, `{"o_entniche.a_items":1}`, nil, false, -1, -1)
-		if data == nil || !ok || len(*data) == 0 {
-			return map[string]interface{}{"flag": flag, "msg": ""}
-		}
-		ojy, _ := (*data)[0][types].(map[string]interface{})
-		a_items, _ := ojy["a_items"].([]interface{})
-		for k, v := range a_items {
-			if !m[strconv.Itoa(k)] {
-				items = append(items, v)
-			}
-		}
-
-		if len(items) > 0 {
-			flag = db.Mgo.Update("entniche_rule", query, bson.M{"$set": bson.M{
-				"l_updatetime":       time.Now().Unix(),
-				"o_entniche.a_items": items,
-			}}, true, false)
-			SetLog(userId, types, positionType, session)
-		}
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    flag := true
+    items, saveData := []interface{}{}, map[string]interface{}{}
+    m := map[string]bool{}
+    for _, v := range strings.Split(classIndex, ",") {
+        m[v] = true
+    }
+    data := config.Compatible.Select(userId, `{"`+types+`.a_items":1}`)
+    if data != nil && len(*data) > 0 {
+        ojy, _ := (*data)[types].(map[string]interface{})
+        a_items, _ := ojy["a_items"].([]interface{})
+        for k, v := range a_items {
+            if !m[strconv.Itoa(k)] {
+                items = append(items, v)
+            }
+        }
+    }
+    saveData[types+".a_items"] = items
+
+    if len(saveData) > 0 {
+        flag = config.Compatible.Update(userId, map[string]interface{}{
+            "$set": saveData,
+        })
+        SetLog(userId, types, 0, session)
+    }
+    return map[string]interface{}{"flag": flag, "msg": ""}
 }
 
 //创建分类名
 func AddClass(types, classIndex, className, userId string, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 0 {
-		saveData := map[string]interface{}{}
-		data, ok := db.Mgo.FindById("user", userId, `{"`+types+`.a_items":1}`)
-		if data != nil && ok && len(*data) > 0 {
-			ojy, _ := (*data)[types].(map[string]interface{})
-			a_items, errs := ojy["a_items"].([]interface{})
-			//没有该字段创建
-			if !errs {
-				db.Mgo.UpdateById("user", userId, map[string]interface{}{
-					"$set": map[string]interface{}{
-						"" + types + ".a_items": []map[string]interface{}{},
-					},
-				})
-			}
-			sitemsArr := []string{} //分类名称数组
-			for _, av := range a_items {
-				_av := qutil.ObjToMap(av)
-				sitemsArr = append(sitemsArr, qutil.ObjToString((*_av)["s_item"]))
-			}
-			if util.IsRepeat(append(sitemsArr, className)) {
-				return map[string]interface{}{"flag": false, "msg": "分类名称重复"}
-			}
-			c_lens := strconv.Itoa(len(a_items))
-			if ci, _ := strconv.Atoi(classIndex); ci < len(a_items)+1 {
-				if classIndex == "" || c_lens == classIndex { //新增
-					classIndex = strconv.Itoa(len(a_items)) //索引
-					saveData[types+".a_items."+classIndex+".a_key"] = []map[string]interface{}{}
-				}
-				saveData[types+".a_items."+classIndex+".s_item"] = className
-				saveData[types+".a_items."+classIndex+".updatetime"] = time.Now().Unix()
-			}
-		}
-
-		if len(saveData) > 0 {
-			flag = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-				"$set": saveData,
-			})
-			SetLog(userId, types, 0, session)
-		}
-	} else {
-		types := "o_entniche"
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		saveData := map[string]interface{}{}
-		data, ok := db.Mgo.Find("entniche_rule", query, `{"o_entniche.a_items":1}`, nil, false, -1, -1)
-		a_items := []interface{}{}
-		if data == nil || !ok || len(*data) == 0 {
-			db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-				"$set": map[string]interface{}{
-					"o_entniche.a_items": []map[string]interface{}{},
-					"l_updatetime":       time.Now().Unix(),
-				}}, true, false)
-
-		} else {
-			ojy, _ := (*data)[0][types].(map[string]interface{})
-			a_items, _ = ojy["a_items"].([]interface{})
-		}
-
-		sitemsArr := []string{} //分类名称数组
-		for _, av := range a_items {
-			_av := qutil.ObjToMap(av)
-			sitemsArr = append(sitemsArr, qutil.ObjToString((*_av)["s_item"]))
-		}
-		if util.IsRepeat(append(sitemsArr, className)) {
-			return map[string]interface{}{"flag": false, "msg": "分类名称重复"}
-		}
-		c_lens := strconv.Itoa(len(a_items))
-		if ci, _ := strconv.Atoi(classIndex); ci < len(a_items)+1 {
-			if classIndex == "" || c_lens == classIndex { //新增
-				classIndex = strconv.Itoa(len(a_items)) //索引
-				saveData[types+".a_items."+classIndex+".a_key"] = []map[string]interface{}{}
-			}
-			saveData[types+".a_items."+classIndex+".s_item"] = className
-			saveData[types+".a_items."+classIndex+".updatetime"] = time.Now().Unix()
-
-		}
-		saveData["l_updatetime"] = time.Now().Unix()
-		if len(saveData) > 0 {
-			flag = db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-				"$set": saveData,
-			}, true, false)
-			SetLog(userId, types, positionType, session)
-		}
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    flag := true
+    saveData := map[string]interface{}{}
+    data := config.Compatible.Select(userId, `{"`+types+`.a_items":1}`)
+    if data != nil && len(*data) > 0 {
+        ojy, _ := (*data)[types].(map[string]interface{})
+        a_items, errs := ojy["a_items"].([]interface{})
+        //没有该字段创建
+        if !errs {
+            config.Compatible.Update(userId, map[string]interface{}{
+                "$set": map[string]interface{}{
+                    "" + types + ".a_items": []map[string]interface{}{},
+                },
+            })
+        }
+        sitemsArr := []string{} //分类名称数组
+        for _, av := range a_items {
+            _av := qutil.ObjToMap(av)
+            sitemsArr = append(sitemsArr, qutil.ObjToString((*_av)["s_item"]))
+        }
+        if util.IsRepeat(append(sitemsArr, className)) {
+            return map[string]interface{}{"flag": false, "msg": "分类名称重复"}
+        }
+        c_lens := strconv.Itoa(len(a_items))
+        if ci, _ := strconv.Atoi(classIndex); ci < len(a_items)+1 {
+            if classIndex == "" || c_lens == classIndex { //新增
+                classIndex = strconv.Itoa(len(a_items)) //索引
+                saveData[types+".a_items."+classIndex+".a_key"] = []map[string]interface{}{}
+            }
+            saveData[types+".a_items."+classIndex+".s_item"] = className
+            saveData[types+".a_items."+classIndex+".updatetime"] = time.Now().Unix()
+        }
+    }
+
+    if len(saveData) > 0 {
+        flag = config.Compatible.Update(userId, map[string]interface{}{
+            "$set": saveData,
+        })
+        SetLog(userId, types, 0, session)
+    }
+    return map[string]interface{}{"flag": flag, "msg": ""}
 
 }
 
 //关键词判重
 func KeyWordsRepeat(obj map[string]interface{}, aitems []interface{}) bool {
-	// 录入的关键词
-	key, _ := obj["key"].([]string)
-	notkey, _ := obj["notkey"].([]string)
-	matchway, _ := obj["matchway"].(int) //matchway 0:精准匹配 1:模糊匹配
-	appendkey, _ := obj["appendkey"].([]string)
-	if util.IsRepeat(key) || util.IsRepeat(appendkey) {
-		return true
-	}
-	// 录入的关键词
-	for _, v := range aitems {
-		if items, ok := v.(map[string]interface{}); ok && len(items) > 0 {
-			for kk, vv := range items {
-				if kk == "a_key" {
-					for _, n := range qutil.ObjArrToMapArr(vv.([]interface{})) {
-						db_not := []string{}
-						db_key := []string{}
-						db_append := []string{}
-						if n["key"] != nil {
-							db_key = qutil.ObjArrToStringArr(n["key"].([]interface{}))
-						}
-						if n["notkey"] != nil {
-							db_not = qutil.ObjArrToStringArr(n["notkey"].([]interface{}))
-						}
-						if n["appendkey"] != nil {
-							db_append = qutil.ObjArrToStringArr(n["appendkey"].([]interface{}))
-						}
-						if util.StringArrEqual(key, db_key) && util.StringArrEqual(notkey, db_not) && qutil.IntAllDef(n["matchway"], 0) == matchway && util.StringArrEqual(appendkey, db_append) {
-							return true
-						}
-					}
-				}
-			}
-		}
-	}
-	return false
+    // 录入的关键词
+    key, _ := obj["key"].([]string)
+    notkey, _ := obj["notkey"].([]string)
+    matchway, _ := obj["matchway"].(int) //matchway 0:精准匹配 1:模糊匹配
+    appendkey, _ := obj["appendkey"].([]string)
+    if util.IsRepeat(key) || util.IsRepeat(appendkey) {
+        return true
+    }
+    // 录入的关键词
+    for _, v := range aitems {
+        if items, ok := v.(map[string]interface{}); ok && len(items) > 0 {
+            for kk, vv := range items {
+                if kk == "a_key" {
+                    for _, n := range qutil.ObjArrToMapArr(vv.([]interface{})) {
+                        db_not := []string{}
+                        db_key := []string{}
+                        db_append := []string{}
+                        if n["key"] != nil {
+                            db_key = qutil.ObjArrToStringArr(n["key"].([]interface{}))
+                        }
+                        if n["notkey"] != nil {
+                            db_not = qutil.ObjArrToStringArr(n["notkey"].([]interface{}))
+                        }
+                        if n["appendkey"] != nil {
+                            db_append = qutil.ObjArrToStringArr(n["appendkey"].([]interface{}))
+                        }
+                        if util.StringArrEqual(key, db_key) && util.StringArrEqual(notkey, db_not) && qutil.IntAllDef(n["matchway"], 0) == matchway && util.StringArrEqual(appendkey, db_append) {
+                            return true
+                        }
+                    }
+                }
+            }
+        }
+    }
+    return false
 }
 
 type UpdateOther struct {
-	PageType        string //projectMatch项目匹配  saveSeniorset关键词匹配方式  infoType信息类型
-	Pmindex         int    //1项目匹配开启 0项目匹配关闭
-	InfoTypeArr     string //信息类型
-	Matchtype       int    //1标题匹配 2项目匹配
-	UserId          string
-	Type            string
-	OtherBuyerclass int //其它采购单位
-	EntId           int
-	EntUserId       int
-	Session         *httpsession.Session
+    PageType        string //projectMatch项目匹配  saveSeniorset关键词匹配方式  infoType信息类型
+    Pmindex         int    //1项目匹配开启 0项目匹配关闭
+    InfoTypeArr     string //信息类型
+    Matchtype       int    //1标题匹配 2项目匹配
+    UserId          string
+    Type            string
+    OtherBuyerclass int //其它采购单位
+    EntId           int
+    EntUserId       int
+    Session         *httpsession.Session
 }
 
 func (this *UpdateOther) UpdateOther() map[string]interface{} {
-	power := jy.GetBigVipUserBaseMsg(this.Session, *config.Middleground)
-	positionType := qutil.Int64All(this.Session.Get("positionType"))
-	if this.Type == "m" && power.Status < 0 {
-		return map[string]interface{}{"flag": false, "msg": "暂无权限"}
-	}
-	types := "o_jy"
-	if this.Type == "m" {
-		types = "o_member_jy"
-	} else if this.Type == "v" {
-		types = "o_vipjy"
-	}
-	if positionType == 1 {
-		types = "o_entniche"
-	}
-	setMap := func() map[string]interface{} {
-		switch this.PageType {
-		case "projectMatch": //项目匹配
-			return UpdateProjectMatch(types, this.Pmindex)
-		case "saveSeniorset": //关键词匹配方式
-			return UpdateSaveSeniorset(types, this.Matchtype)
-		case "infoType": //信息类型
-			return UpdateInfoType(types, this.InfoTypeArr)
-		case "other_buyerclass":
-			return UpdateOtherBuyerClass(types, this.OtherBuyerclass)
-		case "keytip": //关键词升级弹窗提示(一个用户只提示一次)
-			return UpdateKeyTip(types)
-		}
-		return nil
-	}()
-	flag := true
-	if types == "o_jy" {
-		// setMap["o_jy.i_newfree"] = 1 //老免费用户=>新订阅设置页面 20211122
-	}
-	if setMap != nil {
-		if positionType == 1 {
-			query := map[string]interface{}{
-				"i_userid": this.EntUserId,
-				"i_entid":  this.EntId,
-				"i_type":   1,
-			}
-			if db.Mgo.Update("entniche_rule", query, map[string]interface{}{
-				"$set": setMap,
-			}, true, false) {
-				flag = true
-				//清楚缓存
-				jy.ClearBigVipUserPower(this.UserId)
-			}
-			SetLog(this.UserId, types, positionType, this.Session)
-		} else {
-			query := map[string]interface{}{
-				"i_userid": this.EntUserId,
-				"i_entid":  this.EntId,
-			}
-			setMap["l_updatetime"] = time.Now().Unix()
-			flag = db.Mgo.Update("entniche_rule", query, bson.M{"$set": setMap}, true, false)
-			if flag {
-				flag = true
-				//清楚缓存
-				jy.ClearBigVipUserPower(this.UserId)
-			}
-			SetLog(this.UserId, types, positionType, this.Session)
-
-		}
-
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+    power := jy.GetBigVipUserBaseMsg(this.Session, *config.Middleground)
+    if this.Type == "m" && power.Status < 0 {
+        return map[string]interface{}{"flag": false, "msg": "暂无权限"}
+    }
+    positionType := qutil.Int64All(this.Session.Get("positionType"))
+    types := "o_jy"
+    if this.Type == "m" {
+        types = "o_member_jy"
+    } else if this.Type == "v" {
+        types = "o_vipjy"
+    }
+    setMap := func() map[string]interface{} {
+        switch this.PageType {
+        case "projectMatch": //项目匹配
+            return UpdateProjectMatch(types, this.Pmindex)
+        case "saveSeniorset": //关键词匹配方式
+            return UpdateSaveSeniorset(types, this.Matchtype)
+        case "infoType": //信息类型
+            return UpdateInfoType(types, this.InfoTypeArr)
+        case "other_buyerclass":
+            return UpdateOtherBuyerClass(types, this.OtherBuyerclass)
+        case "keytip": //关键词升级弹窗提示(一个用户只提示一次)
+            return UpdateKeyTip(types)
+        }
+        return nil
+    }()
+    flag := true
+    if types == "o_jy" {
+        // setMap["o_jy.i_newfree"] = 1 //老免费用户=>新订阅设置页面 20211122
+    }
+    if setMap != nil {
+        if config.Compatible.Update(this.UserId, map[string]interface{}{
+            "$set": setMap,
+        }) {
+            flag = true
+            //清楚缓存
+            jy.ClearBigVipUserPower(this.UserId)
+        }
+        SetLog(this.UserId, types, positionType, this.Session)
+    }
+
+    return map[string]interface{}{"flag": flag, "msg": ""}
 }
 
 //
 func UpdateProjectMatch(types string, pmindex int) map[string]interface{} {
-	return map[string]interface{}{
-		types + ".i_projectmatch": pmindex,
-	}
+    return map[string]interface{}{
+        types + ".i_projectmatch": pmindex,
+    }
 }
 
 //
 func UpdateSaveSeniorset(types string, matchtype int) map[string]interface{} {
-	return map[string]interface{}{
-		types + ".i_matchway": matchtype,
-	}
+    return map[string]interface{}{
+        types + ".i_matchway": matchtype,
+    }
 }
 
 //
 func UpdateInfoType(types string, infotype string) map[string]interface{} {
-	if infotype != "" {
-		return map[string]interface{}{
-			types + ".a_infotype": strings.Split(infotype, ","),
-		}
-	} else {
-		return map[string]interface{}{
-			types + ".a_infotype": []string{},
-		}
-	}
+    if infotype != "" {
+        return map[string]interface{}{
+            types + ".a_infotype": strings.Split(infotype, ","),
+        }
+    } else {
+        return map[string]interface{}{
+            types + ".a_infotype": []string{},
+        }
+    }
 }
 
 //
 func UpdateOtherBuyerClass(types string, other int) map[string]interface{} {
-	return map[string]interface{}{
-		types + ".i_matchbuyerclass_other": other,
-	}
+    return map[string]interface{}{
+        types + ".i_matchbuyerclass_other": other,
+    }
 }
 
 //UpdateKeyTip 关键词升级提示
 func UpdateKeyTip(types string) map[string]interface{} {
-	return map[string]interface{}{
-		types + ".b_keytip": true,
-	}
+    return map[string]interface{}{
+        types + ".b_keytip": true,
+    }
 }
 
 func directSubKWS(updateItems string, keys string, userId string, session *httpsession.Session) map[string]interface{} {
-	flag := "n"
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 0 {
-		data, ok := db.Mgo.FindById("user", userId, fmt.Sprintf(`{"%s":1}`, updateItems))
-		var repleat = false
-		var classify_index = -1
-		var kwsCount = 0
-		if len([]rune(keys)) > 20 {
-			keys = qutil.SubString(keys, 0, 20)
-		}
-		if ok && data != nil && len(*data) > 0 && keys != "" {
-			updateObj, _ := (*data)[updateItems].(map[string]interface{})
-			if updateObj["a_items"] != nil {
-				a_items := updateObj["a_items"].([]interface{})
-				for k, v := range a_items {
-					tmp := qutil.ObjToMap(v.(map[string]interface{}))
-					a_key := (*tmp)["a_key"].([]interface{})
-					kwsCount = kwsCount + len(a_key)
-					if (*tmp)["s_item"] == "未分类" {
-						classify_index = k
-					}
-					for _, n := range a_key {
-						ntmp := qutil.ObjToMap(n.(interface{}))
-						nkey := qutil.ObjArrToStringArr((*ntmp)["key"].([]interface{}))
-						if strings.Join(nkey, " ") == keys {
-							repleat = true
-							break
-						}
-					}
-					if repleat {
-						break
-					}
-				}
-				if classify_index == -1 {
-					classify_index = len(a_items)
-				}
-			} else {
-				//无关键词 直接添加
-				if ok := db.Mgo.UpdateById("user", userId, bson.M{"$set": bson.M{fmt.Sprintf("%s.a_items", updateItems): bson.A{bson.M{"s_item": "未分类",
-					"a_key":        bson.A{bson.M{"key": bson.A{keys}}},
-					"l_modifydate": time.Now().Unix()}}}}); ok {
-					flag = "y"
-				}
-				return map[string]interface{}{"flag": flag}
-			}
-			if repleat {
-				flag = "o"
-			} else if kwsCount >= 300 {
-				flag = "m"
-			} else {
-				var _key = make(map[string]interface{})
-				var a_key = make([]map[string]interface{}, 1)
-				classify_name := "未分类"
-				_key["key"] = strings.Split(keys, " ")
-				a_key[0] = _key
-				if len(a_key) > 0 {
-					ok := db.Mgo.UpdateById("user", userId, bson.M{
-						"$push": bson.M{
-							updateItems + ".a_items." + strconv.Itoa(classify_index) + ".a_key": bson.M{
-								"$each": a_key,
-							},
-						},
-						"$set": bson.M{
-							updateItems + ".l_modifydate":                                        time.Now().Unix(),
-							updateItems + ".a_items." + strconv.Itoa(classify_index) + ".s_item": classify_name,
-						},
-					})
-					if ok {
-						flag = "y"
-					}
-				}
-			}
-		}
-	} else {
-		updateItems = "o_entniche"
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		data, ok := db.Mgo.Find("entniche_rule", query, `{"o_entniche.a_items":1}`, nil, false, -1, -1)
-		var repleat = false
-		var classify_index = -1
-		var kwsCount = 0
-		if len([]rune(keys)) > 20 {
-			keys = qutil.SubString(keys, 0, 20)
-		}
-		if ok && data != nil && len(*data) > 0 && keys != "" {
-			updateObj, _ := (*data)[0]["o_entniche"].(map[string]interface{})
-			if updateObj["a_items"] != nil {
-				a_items := updateObj["a_items"].([]interface{})
-				for k, v := range a_items {
-					tmp := qutil.ObjToMap(v.(map[string]interface{}))
-					a_key := (*tmp)["a_key"].([]interface{})
-					kwsCount = kwsCount + len(a_key)
-					if (*tmp)["s_item"] == "未分类" {
-						classify_index = k
-					}
-					for _, n := range a_key {
-						ntmp := qutil.ObjToMap(n.(interface{}))
-						nkey := qutil.ObjArrToStringArr((*ntmp)["key"].([]interface{}))
-						if strings.Join(nkey, " ") == keys {
-							repleat = true
-							break
-						}
-					}
-					if repleat {
-						break
-					}
-				}
-				if classify_index == -1 {
-					classify_index = len(a_items)
-				}
-			} else {
-				//无关键词 直接添加
-				if ok := db.Mgo.Update("entniche_rule", query, bson.M{"$set": bson.M{"o_entniche.a_items": bson.A{bson.M{"s_item": "未分类",
-					"a_key":      bson.A{bson.M{"key": bson.A{keys}}},
-					"updatetime": time.Now().Unix()}},
-					"l_updatetime": time.Now().Unix(),
-				}}, true, false); ok {
-					flag = "y"
-				}
-				return map[string]interface{}{"flag": flag}
-			}
-			if repleat {
-				flag = "o"
-			} else if kwsCount >= 300 {
-				flag = "m"
-			} else {
-				var _key = make(map[string]interface{})
-				var a_key = make([]map[string]interface{}, 1)
-				classify_name := "未分类"
-				_key["key"] = strings.Split(keys, " ")
-				a_key[0] = _key
-				if len(a_key) > 0 {
-					ok := db.Mgo.Update("entniche_rule", query, bson.M{
-
-						"$push": bson.M{
-							updateItems + ".a_items." + strconv.Itoa(classify_index) + ".a_key": bson.M{
-								"$each": a_key,
-							},
-						},
-						"$set": bson.M{
-							"l_updatetime": time.Now().Unix(),
-							updateItems + ".a_items." + strconv.Itoa(classify_index) + ".s_item":     classify_name,
-							updateItems + ".a_items." + strconv.Itoa(classify_index) + ".updatetime": time.Now().Unix(),
-						},
-					}, true, false)
-					if ok {
-						flag = "y"
-					}
-				}
-			}
-		}
-	}
-	return map[string]interface{}{"flag": flag}
+    flag := "n"
+    data := config.Compatible.Select(userId, fmt.Sprintf(`{"%s":1}`, updateItems))
+    var repleat = false
+    var classify_index = -1
+    var kwsCount = 0
+    if len([]rune(keys)) > 20 {
+        keys = qutil.SubString(keys, 0, 20)
+    }
+    if data != nil && len(*data) > 0 && keys != "" {
+        updateObj, _ := (*data)[updateItems].(map[string]interface{})
+        if updateObj["a_items"] != nil {
+            a_items := updateObj["a_items"].([]interface{})
+            for k, v := range a_items {
+                tmp := qutil.ObjToMap(v.(map[string]interface{}))
+                a_key := (*tmp)["a_key"].([]interface{})
+                kwsCount = kwsCount + len(a_key)
+                if (*tmp)["s_item"] == "未分类" {
+                    classify_index = k
+                }
+                for _, n := range a_key {
+                    ntmp := qutil.ObjToMap(n.(interface{}))
+                    nkey := qutil.ObjArrToStringArr((*ntmp)["key"].([]interface{}))
+                    if strings.Join(nkey, " ") == keys {
+                        repleat = true
+                        break
+                    }
+                }
+                if repleat {
+                    break
+                }
+            }
+            if classify_index == -1 {
+                classify_index = len(a_items)
+            }
+        } else {
+            //无关键词 直接添加
+            if ok := config.Compatible.Update(userId, bson.M{"$set": bson.M{fmt.Sprintf("%s.a_items", updateItems): bson.A{bson.M{"s_item": "未分类",
+                "a_key":        bson.A{bson.M{"key": bson.A{keys}}},
+                "l_modifydate": time.Now().Unix()}}}}); ok {
+                flag = "y"
+            }
+            return map[string]interface{}{"flag": flag}
+        }
+        if repleat {
+            flag = "o"
+        } else if kwsCount >= 300 {
+            flag = "m"
+        } else {
+            var _key = make(map[string]interface{})
+            var a_key = make([]map[string]interface{}, 1)
+            classify_name := "未分类"
+            _key["key"] = strings.Split(keys, " ")
+            a_key[0] = _key
+            if len(a_key) > 0 {
+                ok := config.Compatible.Update(userId, bson.M{
+                    "$push": bson.M{
+                        updateItems + ".a_items." + strconv.Itoa(classify_index) + ".a_key": bson.M{
+                            "$each": a_key,
+                        },
+                    },
+                    "$set": bson.M{
+                        updateItems + ".l_modifydate":                                        time.Now().Unix(),
+                        updateItems + ".a_items." + strconv.Itoa(classify_index) + ".s_item": classify_name,
+                    },
+                })
+                if ok {
+                    flag = "y"
+                }
+            }
+        }
+    }
+    return map[string]interface{}{"flag": flag}
 }
 
 //订阅设置记录
 func SetLog(userid, types string, power int64, session *httpsession.Session) {
-	if power == 1 {
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		res, _ := db.Mgo.FindOne("entniche_rule", query)
-		if res != nil && len(*res) > 0 {
-			(*res)["userid"] = userid
-			(*res)["type"] = types
-			(*res)["createtime"] = time.Now().Unix()
-			db.Mgo_Log.Save("ovipjy_log", res)
-		}
-	} else {
-		if data, ok := db.Mgo.FindById("user", userid, `{"o_vipjy":1,"o_member_jy":1,"o_jy":1}`); len(*data) > 0 && ok && data != nil {
-			(*data)["userid"] = userid
-			(*data)["type"] = types
-			(*data)["createtime"] = time.Now().Unix()
-			db.Mgo_Log.Save("ovipjy_log", data)
-		}
-	}
+    if power == 1 {
+        query := map[string]interface{}{
+            "i_userid": qutil.IntAll(session.Get("entUserId")),
+            "i_entid":  qutil.IntAll(session.Get("entId")),
+            "i_type":   1,
+        }
+        res, _ := db.Mgo.FindOne("entniche_rule", query)
+        if res != nil && len(*res) > 0 {
+            (*res)["userid"] = userid
+            (*res)["type"] = types
+            (*res)["createtime"] = time.Now().Unix()
+            db.Mgo_Log.Save("ovipjy_log", res)
+        }
+    } else {
+        if data:= config.Compatible.Select( userid, `{"o_vipjy":1,"o_member_jy":1,"o_jy":1}`); len(*data) > 0  && data != nil {
+            (*data)["userid"] = userid
+            (*data)["type"] = types
+            (*data)["createtime"] = time.Now().Unix()
+            db.Mgo_Log.Save("ovipjy_log", data)
+        }
+    }
 }

+ 473 - 509
src/jfw/modules/publicapply/src/subscribePush/entity/setting.go

@@ -1,587 +1,551 @@
 package entity
 
 import (
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/publicapply/src/config"
-	"jy/src/jfw/modules/publicapply/src/db"
-	"jy/src/jfw/modules/publicapply/src/util"
-	"log"
-	"sort"
-	"strings"
-	"time"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "errors"
+    "fmt"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
+    "jy/src/jfw/modules/publicapply/src/util"
+    "log"
+    "sort"
+    "strings"
+    "time"
 )
 
 //订阅设置设置修改
 type SubscribeSet struct {
-	Area      map[string]interface{} //地区
-	Industry  []string               //行业
-	UserId    string                 //用户id
-	Type      string                 //类型
-	EntId     int
-	EntUserId int
-	Session   *httpsession.Session
+    Area      map[string]interface{} //地区
+    Industry  []string               //行业
+    UserId    string                 //用户id
+    Type      string                 //类型
+    EntId     int
+    EntUserId int
+    Session   *httpsession.Session
 }
 
 func (this *SubscribeSet) SetAreaAndIndustry() *FuncResult {
-	area := this.Area
-	industry := this.Industry
-	userId := this.UserId
-	typ := this.Type
-	if typ == "m" {
-		return memberSet(area, industry, userId, this.Session)
-	} else if typ == "v" {
-		return vipSet(area, industry, userId, this.Session)
-	} else {
-		return freeSet(area, industry, userId, this.Session)
-	}
+    area := this.Area
+    industry := this.Industry
+    userId := this.UserId
+    typ := this.Type
+    if typ == "m" {
+        return memberSet(area, industry, userId, this.Session)
+    } else if typ == "v" {
+        return vipSet(area, industry, userId, this.Session)
+    } else {
+        return freeSet(area, industry, userId, this.Session)
+    }
 }
 
 //
 func freeSet(area map[string]interface{}, industry []string, userId string, session *httpsession.Session) *FuncResult {
-	//isfirst:是否第一次设置地区;ppb:是否购买省级订阅包; areacount:省份订阅包购买的省份数量-1:全国 无限制调整
-	isfirst, ppb, areacount := IsCanSet(userId, area, session)
-	//购买省份订阅包 已调整地区次数
-	ppnum := 0
-	//免费用户购买省份订阅包 按月算
-	ym := fmt.Sprint(time.Now().Year()) + "-" + fmt.Sprint(time.Now().Month())
-	if ppb {
-		ppnum = redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, ym))
-	} else if len(area) == 0 {
-		return &FuncResult{false, errors.New("地区参数异常"), nil}
-	}
-	//免费用户未购买省份订阅包 按年算
-	year := fmt.Sprint(time.Now().Year())
-	//免费用户 已调整地区次数
-	fpnum := redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, year))
-	// log.Println(len(area), "fpnum:", fpnum, "ppnum:", ppnum)
-	//第一次设置地区 || 购买全国  不扣次数
-	var issetredis = areacount > -1 && !isfirst
-	if issetredis {
-		//地区范围判断
-		if areacount+jy.BaseAreaNum < len(area) {
-			return &FuncResult{false, errors.New("超出地区可设置范围"), nil}
-		}
-		//地区调整次数判断
-		if areacount+jy.BaseAreaNum <= ppnum { //+fpnum
-			return &FuncResult{false, errors.New(fmt.Sprintf("订阅地区调整次数(%d)已用完", areacount+jy.BaseAreaNum)), nil}
-		}
-	}
-	//清楚缓存
-	jy.ClearBigVipUserPower(userId)
-	if !FreeSubChange(userId, &area, industry, ppb, isfirst) {
-		return &FuncResult{false, errors.New("保存修改出错"), nil}
-	} else if issetredis { //更新调整次数 非全国(第一次 不消耗次数)
-		//优先使用省份订阅包次数
-		// log.Println(areacount, "---", ppnum)
-		// log.Println(jy.BaseAreaNum, "---", fpnum)
-		if ppb {
-			if areacount+jy.BaseAreaNum > ppnum {
-				redis.Put(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, ym), ppnum+1, 31*24*60*60)
-			} else {
-				log.Println(fmt.Sprintf("免费用户购买省份订阅包设置地区 扣除次数异常  userId:%s", userId))
-			}
-		} else if jy.BaseAreaNum > fpnum {
-			redis.Put(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, year), fpnum+1, 365*24*60*60)
-		} else {
-			log.Println(fmt.Sprintf("免费用户设置地区 扣除次数异常  userId:%s", userId))
-		}
-	}
-	SetLog(userId, "o_jy", 0, session)
-	return &FuncResult{true, nil, map[string]interface{}{
-		"doSuccess": true,
-	}}
+    //isfirst:是否第一次设置地区;ppb:是否购买省级订阅包; areacount:省份订阅包购买的省份数量-1:全国 无限制调整
+    isfirst, ppb, areacount := IsCanSet(userId, area, session)
+    //购买省份订阅包 已调整地区次数
+    ppnum := 0
+    //免费用户购买省份订阅包 按月算
+    ym := fmt.Sprint(time.Now().Year()) + "-" + fmt.Sprint(time.Now().Month())
+    if ppb {
+        ppnum = redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, ym))
+    } else if len(area) == 0 {
+        return &FuncResult{false, errors.New("地区参数异常"), nil}
+    }
+    //免费用户未购买省份订阅包 按年算
+    year := fmt.Sprint(time.Now().Year())
+    //免费用户 已调整地区次数
+    fpnum := redis.GetInt(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, year))
+    // log.Println(len(area), "fpnum:", fpnum, "ppnum:", ppnum)
+    //第一次设置地区 || 购买全国  不扣次数
+    var issetredis = areacount > -1 && !isfirst
+    if issetredis {
+        //地区范围判断
+        if areacount+jy.BaseAreaNum < len(area) {
+            return &FuncResult{false, errors.New("超出地区可设置范围"), nil}
+        }
+        //地区调整次数判断
+        if areacount+jy.BaseAreaNum <= ppnum { //+fpnum
+            return &FuncResult{false, errors.New(fmt.Sprintf("订阅地区调整次数(%d)已用完", areacount+jy.BaseAreaNum)), nil}
+        }
+    }
+    //清楚缓存
+    positionId := qutil.InterfaceToStr(session.Get("positionId"))
+    jy.ClearBigVipUserPower(positionId)
+    if !FreeSubChange(userId, &area, industry, ppb, isfirst) {
+        return &FuncResult{false, errors.New("保存修改出错"), nil}
+    } else if issetredis { //更新调整次数 非全国(第一次 不消耗次数)
+        //优先使用省份订阅包次数
+        // log.Println(areacount, "---", ppnum)
+        // log.Println(jy.BaseAreaNum, "---", fpnum)
+        if ppb {
+            if areacount+jy.BaseAreaNum > ppnum {
+                redis.Put(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, ym), ppnum+1, 31*24*60*60)
+            } else {
+                log.Println(fmt.Sprintf("免费用户购买省份订阅包设置地区 扣除次数异常  userId:%s", userId))
+            }
+        } else if jy.BaseAreaNum > fpnum {
+            redis.Put(jy.PowerCacheDb, fmt.Sprintf(jy.UserUpdateAreaKey, userId, year), fpnum+1, 365*24*60*60)
+        } else {
+            log.Println(fmt.Sprintf("免费用户设置地区 扣除次数异常  userId:%s", userId))
+        }
+    }
+    SetLog(userId, "o_jy", 0, session)
+    return &FuncResult{true, nil, map[string]interface{}{
+        "doSuccess": true,
+    }}
 }
 
 //免费用户地区调整
 func FreeSubChange(userId string, area *map[string]interface{}, industry []string, ppb, isfirst bool) bool {
-	setMap := map[string]interface{}{"$set": map[string]interface{}{
-		"o_jy.o_area":    area, //设置地区
-		"o_jy.i_newfree": 1,    //老免费用户=>新订阅设置页面 20211122
-	}}
-	if ppb {
-		setMap = map[string]interface{}{"$set": map[string]interface{}{
-			"o_jy.o_area_p":  area, //设置地区
-			"o_jy.i_newfree": 1,    //老免费用户=>新订阅设置页面 20211122
-		}}
-	}
-	updateOk := db.Mgo.UpdateById("user", userId, setMap)
-	if !updateOk {
-		return false
-	}
-	return true
+    setMap := map[string]interface{}{"$set": map[string]interface{}{
+        "o_jy.o_area":    area, //设置地区
+        "o_jy.i_newfree": 1,    //老免费用户=>新订阅设置页面 20211122
+    }}
+    if ppb {
+        setMap = map[string]interface{}{"$set": map[string]interface{}{
+            "o_jy.o_area_p":  area, //设置地区
+            "o_jy.i_newfree": 1,    //老免费用户=>新订阅设置页面 20211122
+        }}
+    }
+    updateOk := config.Compatible.Update(userId, setMap)
+    if !updateOk {
+        return false
+    }
+    return true
 }
 
 //是否可进行地区调整
 func IsCanSet(userId string, areamap map[string]interface{}, session *httpsession.Session) (bool, bool, int) {
-	areacount := 0
-	myarea := []string{}
-	setarea := []string{}
-	myareamap := map[string]interface{}{}
-	o_jy := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
-	//地区是否完全一致
-	if (*o_jy)["o_area"] != nil {
-		myareamap = *qutil.ObjToMap((*o_jy)["o_area"])
+    areacount := 0
+    myarea := []string{}
+    setarea := []string{}
+    myareamap := map[string]interface{}{}
+    o_jy := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
+    //地区是否完全一致
+    if (*o_jy)["o_area"] != nil {
+        myareamap = *qutil.ObjToMap((*o_jy)["o_area"])
 
-	}
-	//是否购买省份订阅包
-	if (*o_jy)["i_ppstatus"] != nil && qutil.IntAll((*o_jy)["i_ppstatus"]) > 0 {
-		o_buyset_p, _ := (*o_jy)["o_buyset_p"].(map[string]interface{})
-		areacount = qutil.IntAll(o_buyset_p["areacount"]) //-1 全国无限制
-		myareamap = *qutil.ObjToMap((*o_jy)["o_area_p"])
-	}
-	myareabool := map[string]bool{}
-	areasize := 0
-	//库中地区
-	for oak, _ := range myareamap {
-		myareabool[oak] = true
-		myarea = append(myarea, oak)
-	}
-	//参数地区
-	for sak, _ := range areamap {
-		if myareabool[sak] {
-			areasize += 1
-		}
-		setarea = append(setarea, sak)
-	}
-	if areaSort(setarea) == areaSort(myarea) || areasize == len(setarea) {
-		log.Println(setarea, "-地区选择前后一致或地区调整在已选择地区范围内-", myarea)
-		return true, qutil.IntAll((*o_jy)["i_ppstatus"]) > 0, areacount
-	}
-	// log.Println(areaSort(setarea) == areaSort(myarea), "---areacount:", areacount)
-	return (*o_jy)["o_area"] == nil, qutil.IntAll((*o_jy)["i_ppstatus"]) > 0, areacount
+    }
+    //是否购买省份订阅包
+    if (*o_jy)["i_ppstatus"] != nil && qutil.IntAll((*o_jy)["i_ppstatus"]) > 0 {
+        o_buyset_p, _ := (*o_jy)["o_buyset_p"].(map[string]interface{})
+        areacount = qutil.IntAll(o_buyset_p["areacount"]) //-1 全国无限制
+        myareamap = *qutil.ObjToMap((*o_jy)["o_area_p"])
+    }
+    myareabool := map[string]bool{}
+    areasize := 0
+    //库中地区
+    for oak, _ := range myareamap {
+        myareabool[oak] = true
+        myarea = append(myarea, oak)
+    }
+    //参数地区
+    for sak, _ := range areamap {
+        if myareabool[sak] {
+            areasize += 1
+        }
+        setarea = append(setarea, sak)
+    }
+    if areaSort(setarea) == areaSort(myarea) || areasize == len(setarea) {
+        log.Println(setarea, "-地区选择前后一致或地区调整在已选择地区范围内-", myarea)
+        return true, qutil.IntAll((*o_jy)["i_ppstatus"]) > 0, areacount
+    }
+    // log.Println(areaSort(setarea) == areaSort(myarea), "---areacount:", areacount)
+    return (*o_jy)["o_area"] == nil, qutil.IntAll((*o_jy)["i_ppstatus"]) > 0, areacount
 }
 
 //
 func areaSort(area []string) string {
-	sort.Slice(area, func(i, j int) bool {
-		return area[i] < area[j]
-	})
-	return strings.Join(area, ",")
+    sort.Slice(area, func(i, j int) bool {
+        return area[i] < area[j]
+    })
+    return strings.Join(area, ",")
 }
 
 //
 func vipSet(area map[string]interface{}, industry []string, userId string, session *httpsession.Session) *FuncResult {
-	if len(industry) == 1 && industry[0] == "" {
-		industry = []string{}
-	}
-	positionType := qutil.Int64All(session.Get("positionType"))
-	rData, oldBuyset, isVip := GetVipDetail(session)
-	if !isVip {
-		return &FuncResult{false, errors.New("请求异常,非vip状态"), nil}
-	}
-	if rData == nil || len(*rData) == 0 {
-		return &FuncResult{false, errors.New("获取信息失败"), nil}
-	}
-	newBuyset := NewBuySet(&area, industry, oldBuyset.Upgrade == 1)
+    if len(industry) == 1 && industry[0] == "" {
+        industry = []string{}
+    }
+    positionType := qutil.Int64All(session.Get("positionType"))
+    rData, oldBuyset, isVip := GetVipDetail(session)
+    if !isVip {
+        return &FuncResult{false, errors.New("请求异常,非vip状态"), nil}
+    }
+    if rData == nil || len(*rData) == 0 {
+        return &FuncResult{false, errors.New("获取信息失败"), nil}
+    }
+    newBuyset := NewBuySet(&area, industry, oldBuyset.Upgrade == 1)
 
-	if needUpgrade := needUpgrade(newBuyset, oldBuyset); needUpgrade {
-		log.Printf("%s 订阅内容超出套餐 %+v area:%v industry:%v", userId, oldBuyset, area, industry)
-		return &FuncResult{false, errors.New("订阅内容超出套餐"), nil}
-	}
-	if positionType == 1 {
-		if !VipSubChange(userId, qutil.ObjToMap((*rData)["o_entniche"]), &area, industry, session) {
-			return &FuncResult{false, errors.New("保存修改出错"), nil}
-		}
-	} else {
-		if !VipSubChange(userId, qutil.ObjToMap((*rData)["o_vipjy"]), &area, industry, session) {
-			return &FuncResult{false, errors.New("保存修改出错"), nil}
-		}
-	}
+    if needUpgrade := needUpgrade(newBuyset, oldBuyset); needUpgrade {
+        log.Printf("%s 订阅内容超出套餐 %+v area:%v industry:%v", userId, oldBuyset, area, industry)
+        return &FuncResult{false, errors.New("订阅内容超出套餐"), nil}
+    }
+    if !VipSubChange(userId, qutil.ObjToMap((*rData)["o_vipjy"]), &area, industry, session) {
+        return &FuncResult{false, errors.New("保存修改出错"), nil}
+    }
 
-	SetLog(userId, "o_vipjy", positionType, session)
-	return &FuncResult{true, nil, map[string]interface{}{
-		"doSuccess": true,
-	}}
+    SetLog(userId, "o_vipjy", positionType, session)
+    return &FuncResult{true, nil, map[string]interface{}{
+        "doSuccess": true,
+    }}
 }
 
 //大会员订阅设置
 func memberSet(area map[string]interface{}, industry []string, userId string, session *httpsession.Session) *FuncResult {
-	if data := jy.GetBigVipUserBaseMsg(session, *config.Middleground); data.Status <= 0 {
-		return &FuncResult{false, errors.New("请求异常,非大会员状态"), nil}
-	}
-	if len(industry) == 1 && industry[0] == "" {
-		industry = []string{}
-	}
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if !MemberSubChange(userId, &area, industry, session) {
-		return &FuncResult{false, errors.New("保存修改出错"), nil}
-	}
-	SetLog(userId, "o_member_jy", positionType, session)
-	return &FuncResult{true, nil, map[string]interface{}{
-		"doSuccess": true,
-	}}
+    if data := jy.GetBigVipUserBaseMsg(session, *config.Middleground); data.Status <= 0 {
+        return &FuncResult{false, errors.New("请求异常,非大会员状态"), nil}
+    }
+    if len(industry) == 1 && industry[0] == "" {
+        industry = []string{}
+    }
+    positionType := qutil.Int64All(session.Get("positionType"))
+    if !MemberSubChange(userId, &area, industry, session) {
+        return &FuncResult{false, errors.New("保存修改出错"), nil}
+    }
+    SetLog(userId, "o_member_jy", positionType, session)
+    return &FuncResult{true, nil, map[string]interface{}{
+        "doSuccess": true,
+    }}
 }
 
 //购买内容
 type SubvipBuySet struct {
-	Upgrade         int   `json:"upgrade"`         //是否是升级版;1是 其他不是
-	AreaCount       int   `json:"areacount"`       //-1 全国  >0 省份数量
-	NewCitys        []int `json:"newcitys"`        //城市数量(新)
-	BuyerclassCount int   `json:"buyerclasscount"` //行业数
+    Upgrade         int   `json:"upgrade"`         //是否是升级版;1是 其他不是
+    AreaCount       int   `json:"areacount"`       //-1 全国  >0 省份数量
+    NewCitys        []int `json:"newcitys"`        //城市数量(新)
+    BuyerclassCount int   `json:"buyerclasscount"` //行业数
 }
 
 //获取省份,城市,行业购买内容
 //[省份,城市,行业]
 func GetVipDetail(session *httpsession.Session) (*map[string]interface{}, *SubvipBuySet, bool) {
-	data := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
-	//是否处于vip状态
-	vipStatus := data.Data.Vip.Status
-	o_jy := jy.GetSubScribeInfo(session, db.Mgo, "v", "10000")
-	tmp := qutil.ObjToMap((*o_jy)["o_buyset"])
-	newCity, _ := (*tmp)["newcitys"].([]interface{})
-	return o_jy, &SubvipBuySet{
-		qutil.IntAll((*tmp)["upgrade"]),
-		qutil.IntAll((*tmp)["areacount"]),
-		util.ConfirmIntArr(newCity),
-		qutil.IntAll((*tmp)["buyerclasscount"]),
-	}, vipStatus > 0
+    data := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
+    //是否处于vip状态
+    vipStatus := data.Data.Vip.Status
+    o_jy := jy.GetSubScribeInfo(session, db.Mgo, "v", "10000")
+    tmp := qutil.ObjToMap((*o_jy)["o_buyset"])
+    newCity, _ := (*tmp)["newcitys"].([]interface{})
+    return o_jy, &SubvipBuySet{
+        qutil.IntAll((*tmp)["upgrade"]),
+        qutil.IntAll((*tmp)["areacount"]),
+        util.ConfirmIntArr(newCity),
+        qutil.IntAll((*tmp)["buyerclasscount"]),
+    }, vipStatus > 0
 }
 
 var SubVipPrice subVipPrice
 
 func init() {
-	qutil.ReadConfig("./subvip_price.json", &SubVipPrice)
+    qutil.ReadConfig("./subvip_price.json", &SubVipPrice)
 }
 
 //价格表
 type subVipPrice struct {
-	Old struct {
-		Month struct {
-			OneCity_oneBuyerClass     int `json:"oneCity_oneBuyerClass"`     //一个城市一个行业
-			OneCity_allBuyerClass     int `json:"oneCity_allBuyerClass"`     //一个城市全部行业
-			OneProvince_oneBuyerClass int `json:"oneProvince_oneBuyerClass"` //一个省份一个行业
-			OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-			AllProvince_oneBuyerClass int `json:"allProvince_oneBuyerClass"` //全国一个行业
-			AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-		} `json:"month"`
-		Year struct {
-			OneCity_oneBuyerClass     int `json:"oneCity_oneBuyerClass"`     //一个城市一个行业
-			OneCity_allBuyerClass     int `json:"oneCity_allBuyerClass"`     //一个城市全部行业
-			OneProvince_oneBuyerClass int `json:"oneProvince_oneBuyerClass"` //一个省份一个行业
-			OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-			AllProvince_oneBuyerClass int `json:"allProvince_oneBuyerClass"` //全国一个行业
-			AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-		} `json:"year"`
-		CityPrice          int `json:"cityPrice"`          //单个城市价格
-		ProvincePrice      int `json:"provincePrice"`      //单个省份价格
-		BuyerClassPrice    int `json:"buyerClassPrice"`    //单个行业价格
-		CityMaxCount       int `json:"cityMaxCount"`       //单个省份城市可计价最大数量
-		ProvinceMaxCount   int `json:"provinceMaxCount"`   //所有地区中省份可计价最大数量
-		BuyerClassMaxCount int `json:"buyerClassMaxCount"` //行业价格可计价最大数量
-		MonthMaxCount      int `json:"monthMaxCount"`      //月份可计价最大数量
-	} `json:"old"`
-	New struct {
-		Month struct {
-			OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-			AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-		} `json:"month"`
-		Quarter struct {
-			OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-			AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-		} `json:"quarter"`
-		Year struct {
-			OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-			AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-		} `json:"year"`
-		ProvincePrice    int `json:"provincePrice"`    //单个省份价格
-		ProvinceMaxCount int `json:"provinceMaxCount"` //所有地区中省份可计价最大数量
-		MonthMaxCount    int `json:"monthMaxCount"`    //月份可计价最大数量
-	} `json:"new"`
-	Discount float64 `json:"discount"` //折扣(测试使用)
+    Old struct {
+        Month struct {
+            OneCity_oneBuyerClass     int `json:"oneCity_oneBuyerClass"`     //一个城市一个行业
+            OneCity_allBuyerClass     int `json:"oneCity_allBuyerClass"`     //一个城市全部行业
+            OneProvince_oneBuyerClass int `json:"oneProvince_oneBuyerClass"` //一个省份一个行业
+            OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+            AllProvince_oneBuyerClass int `json:"allProvince_oneBuyerClass"` //全国一个行业
+            AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+        } `json:"month"`
+        Year struct {
+            OneCity_oneBuyerClass     int `json:"oneCity_oneBuyerClass"`     //一个城市一个行业
+            OneCity_allBuyerClass     int `json:"oneCity_allBuyerClass"`     //一个城市全部行业
+            OneProvince_oneBuyerClass int `json:"oneProvince_oneBuyerClass"` //一个省份一个行业
+            OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+            AllProvince_oneBuyerClass int `json:"allProvince_oneBuyerClass"` //全国一个行业
+            AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+        } `json:"year"`
+        CityPrice          int `json:"cityPrice"`          //单个城市价格
+        ProvincePrice      int `json:"provincePrice"`      //单个省份价格
+        BuyerClassPrice    int `json:"buyerClassPrice"`    //单个行业价格
+        CityMaxCount       int `json:"cityMaxCount"`       //单个省份城市可计价最大数量
+        ProvinceMaxCount   int `json:"provinceMaxCount"`   //所有地区中省份可计价最大数量
+        BuyerClassMaxCount int `json:"buyerClassMaxCount"` //行业价格可计价最大数量
+        MonthMaxCount      int `json:"monthMaxCount"`      //月份可计价最大数量
+    } `json:"old"`
+    New struct {
+        Month struct {
+            OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+            AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+        } `json:"month"`
+        Quarter struct {
+            OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+            AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+        } `json:"quarter"`
+        Year struct {
+            OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+            AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+        } `json:"year"`
+        ProvincePrice    int `json:"provincePrice"`    //单个省份价格
+        ProvinceMaxCount int `json:"provinceMaxCount"` //所有地区中省份可计价最大数量
+        MonthMaxCount    int `json:"monthMaxCount"`    //月份可计价最大数量
+    } `json:"new"`
+    Discount float64 `json:"discount"` //折扣(测试使用)
 }
 
 //超级订阅获取购买项
 func NewBuySet(area *map[string]interface{}, industry []string, isUpgrade bool) *SubvipBuySet {
-	pCount := -1
-	citys := []int{}
-	if area != nil {
-		if (*area)["全国"] != nil {
-			area = &map[string]interface{}{}
-		} else if pCount_tmp := qutil.IntAll((*area)["areacount"]); pCount_tmp > 0 {
-			pCount = pCount_tmp
-		}
-	}
-	buyset := SubvipBuySet{}
-	if !isUpgrade {
-		buyset.Upgrade = 0 //升级版超级订阅标识
-		if len(*area) > 0 {
-			pCount = 0
-			for _, v := range *area {
-				tmp := v.([]interface{})
-				if len(tmp) == 0 || len(tmp) > SubVipPrice.Old.CityMaxCount { //省份
-					pCount++
-				} else { //城市
-					citys = append(citys, len(tmp))
-				}
-			}
-			//省份数量自动转换全国
-			if pCount > SubVipPrice.Old.ProvinceMaxCount {
-				pCount = -1
-				citys = []int{}
-			}
-		}
-		buyset.NewCitys = citys
-		buyset.AreaCount = pCount //地区
-		//行业数量自动转换全行业
-		buyset.BuyerclassCount = len(industry)
-		if len(industry) > SubVipPrice.Old.BuyerClassMaxCount || len(industry) == 0 {
-			buyset.BuyerclassCount = -1
-		}
-	} else {
-		buyset.Upgrade = 1 //升级版超级订阅标识
-		if len(*area) > 0 {
-			pCount = len(*area)
-			//省份数量自动转换全国
-			if pCount > SubVipPrice.New.ProvinceMaxCount {
-				pCount = -1
-			}
-		} else {
-			buyset.AreaCount = -1 //全国
-		}
-		buyset.AreaCount = pCount   //地区
-		buyset.NewCitys = citys     //城市,4.4改版不支持购买城市
-		buyset.BuyerclassCount = -1 //行业,4.4改版只能购买全行业
-	}
-	return &buyset
+    pCount := -1
+    citys := []int{}
+    if area != nil {
+        if (*area)["全国"] != nil {
+            area = &map[string]interface{}{}
+        } else if pCount_tmp := qutil.IntAll((*area)["areacount"]); pCount_tmp > 0 {
+            pCount = pCount_tmp
+        }
+    }
+    buyset := SubvipBuySet{}
+    if !isUpgrade {
+        buyset.Upgrade = 0 //升级版超级订阅标识
+        if len(*area) > 0 {
+            pCount = 0
+            for _, v := range *area {
+                tmp := v.([]interface{})
+                if len(tmp) == 0 || len(tmp) > SubVipPrice.Old.CityMaxCount { //省份
+                    pCount++
+                } else { //城市
+                    citys = append(citys, len(tmp))
+                }
+            }
+            //省份数量自动转换全国
+            if pCount > SubVipPrice.Old.ProvinceMaxCount {
+                pCount = -1
+                citys = []int{}
+            }
+        }
+        buyset.NewCitys = citys
+        buyset.AreaCount = pCount //地区
+        //行业数量自动转换全行业
+        buyset.BuyerclassCount = len(industry)
+        if len(industry) > SubVipPrice.Old.BuyerClassMaxCount || len(industry) == 0 {
+            buyset.BuyerclassCount = -1
+        }
+    } else {
+        buyset.Upgrade = 1 //升级版超级订阅标识
+        if len(*area) > 0 {
+            pCount = len(*area)
+            //省份数量自动转换全国
+            if pCount > SubVipPrice.New.ProvinceMaxCount {
+                pCount = -1
+            }
+        } else {
+            buyset.AreaCount = -1 //全国
+        }
+        buyset.AreaCount = pCount   //地区
+        buyset.NewCitys = citys     //城市,4.4改版不支持购买城市
+        buyset.BuyerclassCount = -1 //行业,4.4改版只能购买全行业
+    }
+    return &buyset
 }
 
 //是否需要升级
 func needUpgrade(newBuySet, oldBuySet *SubvipBuySet) bool {
-	if newBuySet.Upgrade != 1 { //旧版本订阅是否需要升级校验
-		BuyerclassUpgrade, AreaNeedUpgrade := false, false
-		UpgradeBuyset := &SubvipBuySet{
-			oldBuySet.Upgrade,
-			oldBuySet.AreaCount,
-			oldBuySet.NewCitys,
-			oldBuySet.BuyerclassCount,
-		}
-		//比较行业
-		if oldBuySet.BuyerclassCount != -1 {
-			//若当前买的不是全行业,并且当前行业数量小于新行业数量时
-			if oldBuySet.BuyerclassCount < newBuySet.BuyerclassCount || newBuySet.BuyerclassCount == -1 {
-				BuyerclassUpgrade = true
-				//计算升级后的buySet
-				UpgradeBuyset.BuyerclassCount = newBuySet.BuyerclassCount
-			}
-		}
-		//比较地区
-		if oldBuySet.AreaCount != -1 {
-			if newBuySet.AreaCount == -1 { //升级为全国
-				UpgradeBuyset.AreaCount = newBuySet.AreaCount
-				UpgradeBuyset.NewCitys = newBuySet.NewCitys
-				AreaNeedUpgrade = true
-			} else {
-				oldCitysBuyOne, oldCitysBuyTwo := 0, 0
-				newCitysBuyOne, newCitysBuyTwo := 0, 0
-				oldCopy := []int{} //复制(防止影响原数组)
-				for _, v := range oldBuySet.NewCitys {
-					if v == 1 {
-						oldCitysBuyOne++
-					} else {
-						oldCitysBuyTwo++
-					}
-					oldCopy = append(oldCopy, v)
-				}
-				UpgradeBuyset.NewCitys = oldCopy
-				for _, v := range newBuySet.NewCitys {
-					if v == 1 {
-						newCitysBuyOne++
-					} else {
-						newCitysBuyTwo++
-					}
-				}
+    if newBuySet.Upgrade != 1 { //旧版本订阅是否需要升级校验
+        BuyerclassUpgrade, AreaNeedUpgrade := false, false
+        UpgradeBuyset := &SubvipBuySet{
+            oldBuySet.Upgrade,
+            oldBuySet.AreaCount,
+            oldBuySet.NewCitys,
+            oldBuySet.BuyerclassCount,
+        }
+        //比较行业
+        if oldBuySet.BuyerclassCount != -1 {
+            //若当前买的不是全行业,并且当前行业数量小于新行业数量时
+            if oldBuySet.BuyerclassCount < newBuySet.BuyerclassCount || newBuySet.BuyerclassCount == -1 {
+                BuyerclassUpgrade = true
+                //计算升级后的buySet
+                UpgradeBuyset.BuyerclassCount = newBuySet.BuyerclassCount
+            }
+        }
+        //比较地区
+        if oldBuySet.AreaCount != -1 {
+            if newBuySet.AreaCount == -1 { //升级为全国
+                UpgradeBuyset.AreaCount = newBuySet.AreaCount
+                UpgradeBuyset.NewCitys = newBuySet.NewCitys
+                AreaNeedUpgrade = true
+            } else {
+                oldCitysBuyOne, oldCitysBuyTwo := 0, 0
+                newCitysBuyOne, newCitysBuyTwo := 0, 0
+                oldCopy := []int{} //复制(防止影响原数组)
+                for _, v := range oldBuySet.NewCitys {
+                    if v == 1 {
+                        oldCitysBuyOne++
+                    } else {
+                        oldCitysBuyTwo++
+                    }
+                    oldCopy = append(oldCopy, v)
+                }
+                UpgradeBuyset.NewCitys = oldCopy
+                for _, v := range newBuySet.NewCitys {
+                    if v == 1 {
+                        newCitysBuyOne++
+                    } else {
+                        newCitysBuyTwo++
+                    }
+                }
 
-				p_Diff := newBuySet.AreaCount - oldBuySet.AreaCount
-				c_1_diff := newCitysBuyOne - oldCitysBuyOne
-				c_2_diff := newCitysBuyTwo - oldCitysBuyTwo
+                p_Diff := newBuySet.AreaCount - oldBuySet.AreaCount
+                c_1_diff := newCitysBuyOne - oldCitysBuyOne
+                c_2_diff := newCitysBuyTwo - oldCitysBuyTwo
 
-				if p_Diff > 0 {
-					UpgradeBuyset.AreaCount = newBuySet.AreaCount
-				}
+                if p_Diff > 0 {
+                    UpgradeBuyset.AreaCount = newBuySet.AreaCount
+                }
 
-				if p_Diff > 0 || p_Diff+c_2_diff > 0 || p_Diff+c_2_diff+c_1_diff > 0 {
-					//有多余未使用名额保留
-					if p_Diff+c_2_diff+c_1_diff < 0 {
-						if c_1_diff < 0 && p_Diff+c_2_diff >= 0 {
-							c_1_diff = -(p_Diff + c_2_diff)
-						}
-						if c_2_diff < 0 && p_Diff+c_1_diff >= 0 {
-							c_2_diff = -(p_Diff + c_1_diff)
-						}
-					}
+                if p_Diff > 0 || p_Diff+c_2_diff > 0 || p_Diff+c_2_diff+c_1_diff > 0 {
+                    //有多余未使用名额保留
+                    if p_Diff+c_2_diff+c_1_diff < 0 {
+                        if c_1_diff < 0 && p_Diff+c_2_diff >= 0 {
+                            c_1_diff = -(p_Diff + c_2_diff)
+                        }
+                        if c_2_diff < 0 && p_Diff+c_1_diff >= 0 {
+                            c_2_diff = -(p_Diff + c_1_diff)
+                        }
+                    }
 
-					//需要升级
-					AreaNeedUpgrade = true
-					//计算升级后的buySet
-					if p_Diff < 0 { //有剩余省份未使用
-						if c_2_diff > 0 {
-							c_2_diff += p_Diff //转移给两个市使用
-						} else {
-							c_1_diff += p_Diff //转移给一个市使用
-						}
-					} else { //省份数量增加
-						UpgradeBuyset.AreaCount = newBuySet.AreaCount
-					}
-					del_2_flag, del_1_flag := 0, 0 //被占用
-					if c_2_diff < 0 {              //有两个城市的名额未使用完
-						if p_Diff > 0 {
-							//转移给一个省使用
-							if c_2_diff+p_Diff > 0 {
-								del_2_flag += -c_2_diff
-								c_2_diff = 0
-								//p_Diff -= -c_2_diff;
-							} else {
-								c_2_diff += p_Diff
-								del_2_flag += p_Diff
-								//p_Diff = 0
-							}
-						}
-						if c_1_diff > 0 && c_2_diff < 0 { //转移给一个市使用
-							c_1_diff += c_2_diff
-						}
-					}
-					if c_1_diff < 0 { //有一个城市的名额未使用完
-						if p_Diff > 0 {
-							if c_1_diff+p_Diff > 0 {
-								del_1_flag += -c_1_diff
-								c_1_diff = 0
-								//p_Diff -= -c_1_diff
-							} else {
-								c_1_diff += p_Diff
-								del_1_flag += p_Diff
-								//p_Diff = 0
-							}
-						}
-						if c_2_diff > 0 && c_1_diff < 0 {
-							if c_1_diff+c_2_diff > 0 {
-								del_1_flag += -c_1_diff
-								c_1_diff = 0
-								//c_2_diff -= -c_1_diff;
-							} else {
-								c_1_diff += c_2_diff
-								del_1_flag += c_2_diff
-								//c_2_diff = 0
-							}
-						}
-					}
-					//删除顶替
-					log.Println("start", UpgradeBuyset.NewCitys, del_2_flag, del_1_flag)
-					index_flag := 0
-					for del_2_flag > 0 || del_1_flag > 0 {
-						valueFlag := UpgradeBuyset.NewCitys[index_flag]
-						if del_2_flag > 0 && valueFlag == 2 {
-							UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
-							del_2_flag--
-							continue
-						} else if del_1_flag > 0 && valueFlag == 1 {
-							UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
-							del_1_flag--
-							continue
-						}
-						index_flag++
-					}
-					log.Println("end", UpgradeBuyset.NewCitys, c_2_diff, c_1_diff)
-					//增加新增
-					for i := c_2_diff; i > 0; i-- { //添加购买两个市数量
-						UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 2)
-					}
+                    //需要升级
+                    AreaNeedUpgrade = true
+                    //计算升级后的buySet
+                    if p_Diff < 0 { //有剩余省份未使用
+                        if c_2_diff > 0 {
+                            c_2_diff += p_Diff //转移给两个市使用
+                        } else {
+                            c_1_diff += p_Diff //转移给一个市使用
+                        }
+                    } else { //省份数量增加
+                        UpgradeBuyset.AreaCount = newBuySet.AreaCount
+                    }
+                    del_2_flag, del_1_flag := 0, 0 //被占用
+                    if c_2_diff < 0 {              //有两个城市的名额未使用完
+                        if p_Diff > 0 {
+                            //转移给一个省使用
+                            if c_2_diff+p_Diff > 0 {
+                                del_2_flag += -c_2_diff
+                                c_2_diff = 0
+                                //p_Diff -= -c_2_diff;
+                            } else {
+                                c_2_diff += p_Diff
+                                del_2_flag += p_Diff
+                                //p_Diff = 0
+                            }
+                        }
+                        if c_1_diff > 0 && c_2_diff < 0 { //转移给一个市使用
+                            c_1_diff += c_2_diff
+                        }
+                    }
+                    if c_1_diff < 0 { //有一个城市的名额未使用完
+                        if p_Diff > 0 {
+                            if c_1_diff+p_Diff > 0 {
+                                del_1_flag += -c_1_diff
+                                c_1_diff = 0
+                                //p_Diff -= -c_1_diff
+                            } else {
+                                c_1_diff += p_Diff
+                                del_1_flag += p_Diff
+                                //p_Diff = 0
+                            }
+                        }
+                        if c_2_diff > 0 && c_1_diff < 0 {
+                            if c_1_diff+c_2_diff > 0 {
+                                del_1_flag += -c_1_diff
+                                c_1_diff = 0
+                                //c_2_diff -= -c_1_diff;
+                            } else {
+                                c_1_diff += c_2_diff
+                                del_1_flag += c_2_diff
+                                //c_2_diff = 0
+                            }
+                        }
+                    }
+                    //删除顶替
+                    log.Println("start", UpgradeBuyset.NewCitys, del_2_flag, del_1_flag)
+                    index_flag := 0
+                    for del_2_flag > 0 || del_1_flag > 0 {
+                        valueFlag := UpgradeBuyset.NewCitys[index_flag]
+                        if del_2_flag > 0 && valueFlag == 2 {
+                            UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
+                            del_2_flag--
+                            continue
+                        } else if del_1_flag > 0 && valueFlag == 1 {
+                            UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
+                            del_1_flag--
+                            continue
+                        }
+                        index_flag++
+                    }
+                    log.Println("end", UpgradeBuyset.NewCitys, c_2_diff, c_1_diff)
+                    //增加新增
+                    for i := c_2_diff; i > 0; i-- { //添加购买两个市数量
+                        UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 2)
+                    }
 
-					for i := c_1_diff; i > 0; i-- { //添加购买一个市数量
-						UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 1)
-					}
-				} else {
-					//不需要升级
-					AreaNeedUpgrade = false
-				}
-			}
-		}
-		if BuyerclassUpgrade || AreaNeedUpgrade {
-			return true
-		} else {
-			return false
-		}
-	} else {
-		//return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
-		if oldBuySet.AreaCount != -1 {
-			return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
-		} else {
-			return false
-		}
-	}
+                    for i := c_1_diff; i > 0; i-- { //添加购买一个市数量
+                        UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 1)
+                    }
+                } else {
+                    //不需要升级
+                    AreaNeedUpgrade = false
+                }
+            }
+        }
+        if BuyerclassUpgrade || AreaNeedUpgrade {
+            return true
+        } else {
+            return false
+        }
+    } else {
+        //return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
+        if oldBuySet.AreaCount != -1 {
+            return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
+        } else {
+            return false
+        }
+    }
 }
 
 //超级订阅 订阅修改
 func VipSubChange(userId string, oldVip, areaNew *map[string]interface{}, industryNew []string, session *httpsession.Session) bool {
-	updateOk := false
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 1 {
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		updateOk = db.Mgo.Update("entniche_rule", query,
-			map[string]interface{}{"$set": map[string]interface{}{
-				"o_entniche.o_area":       areaNew,     //设置地区
-				"o_entniche.a_buyerclass": industryNew, //设置行业
-				"l_updatetime":            time.Now().Unix(),
-			}}, true, false)
-	} else {
-		updateOk = db.Mgo.UpdateById("user", userId,
-			map[string]interface{}{"$set": map[string]interface{}{
-				"o_vipjy.o_area":       areaNew,     //设置地区
-				"o_vipjy.a_buyerclass": industryNew, //设置行业
-			}})
-	}
-	if !updateOk {
-		return false
-	} else {
-		//保存修改日志
-		go func() {
-			db.Mgo_Log.Save("subvip_edit_log", map[string]interface{}{
-				"s_userid":         userId,
-				"o_area_old":       (*oldVip)["o_area"],
-				"a_buyerclass_old": (*oldVip)["a_buyerclass"],
-				"o_area":           areaNew,
-				"a_buyerclass":     industryNew,
-				"l_changeTime":     time.Now().Unix(),
-			})
-		}()
-	}
-	return true
+    updateOk := false
+    updateOk = config.Compatible.Update(userId,
+        map[string]interface{}{"$set": map[string]interface{}{
+            "o_vipjy.o_area":       areaNew,     //设置地区
+            "o_vipjy.a_buyerclass": industryNew, //设置行业
+        }})
+
+    if !updateOk {
+        return false
+    } else {
+        //保存修改日志
+        go func() {
+            db.Mgo_Log.Save("subvip_edit_log", map[string]interface{}{
+                "s_userid":         userId,
+                "o_area_old":       (*oldVip)["o_area"],
+                "a_buyerclass_old": (*oldVip)["a_buyerclass"],
+                "o_area":           areaNew,
+                "a_buyerclass":     industryNew,
+                "l_changeTime":     time.Now().Unix(),
+            })
+        }()
+    }
+    return true
 }
 
 //超级订阅 订阅修改
 func MemberSubChange(userId string, areaNew *map[string]interface{}, industryNew []string, session *httpsession.Session) bool {
-	positionType := qutil.Int64All(session.Get("positionType"))
-	if positionType == 1 {
-		query := map[string]interface{}{
-			"i_userid": qutil.IntAll(session.Get("entUserId")),
-			"i_entid":  qutil.IntAll(session.Get("entId")),
-			"i_type":   1,
-		}
-		if updateOk := db.Mgo.Update("entniche_rule", query,
-			map[string]interface{}{"$set": map[string]interface{}{
-				"o_entniche.o_area":       areaNew,     //设置地区
-				"o_entniche.a_buyerclass": industryNew, //设置行业
-				"l_updatetime":            time.Now().Unix(),
-			}}, true, false); !updateOk {
-			return false
-		}
-	} else {
-		if updateOk := db.Mgo.UpdateById("user", userId,
-			map[string]interface{}{"$set": map[string]interface{}{
-				"o_member_jy.o_area":       areaNew,     //设置地区
-				"o_member_jy.a_buyerclass": industryNew, //设置行业
-			}}); !updateOk {
-			return false
-		}
-	}
+    if updateOk := config.Compatible.Update(userId,
+        map[string]interface{}{"$set": map[string]interface{}{
+            "o_member_jy.o_area":       areaNew,     //设置地区
+            "o_member_jy.a_buyerclass": industryNew, //设置行业
+        }}); !updateOk {
+        return false
+    }
 
-	return true
+    return true
 }

+ 325 - 325
src/jfw/modules/publicapply/src/subscribePush/entity/vrew.go

@@ -1,40 +1,41 @@
 package entity
 
 import (
-        qutil "app.yhyue.com/moapp/jybase/common"
-        elastic "app.yhyue.com/moapp/jybase/esv1"
-        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-        "encoding/json"
-        "fmt"
-        "jy/src/jfw/modules/publicapply/src/db"
-        "log"
-        "strconv"
-        "strings"
-        "time"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    elastic "app.yhyue.com/moapp/jybase/esv1"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "encoding/json"
+    "fmt"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
+    "log"
+    "strconv"
+    "strings"
+    "time"
 )
 
 /*已选条件--关键词*/
 type ViewKeyWord struct {
-        Keyword  []string `json:"key"`       //关键词
-        Appended []string `json:"appendkey"` //附加词
-        Exclude  []string `json:"notkey"`    //排除词
-        MatchWay int      `json:"matchway"`  //匹配模式
+    Keyword  []string `json:"key"`       //关键词
+    Appended []string `json:"appendkey"` //附加词
+    Exclude  []string `json:"notkey"`    //排除词
+    MatchWay int      `json:"matchway"`  //匹配模式
 }
 
 /*已选条件*/
 type ViewCondition struct {
-        Area       []string      //地区-省份
-        City       []string      //地区-城市
-        Buyerclass []string      //采购行业
-        Keyword    []ViewKeyWord //关键词
-        SelectType string        //筛选(正文 or 标题)
-        Subtype    []string      //信息类型
+    Area       []string      //地区-省份
+    City       []string      //地区-城市
+    Buyerclass []string      //采购行业
+    Keyword    []ViewKeyWord //关键词
+    SelectType string        //筛选(正文 or 标题)
+    Subtype    []string      //信息类型
 }
 
 const (
-        INDEX = "bidding"
-        TYPE  = "bidding"
+    INDEX = "bidding"
+    TYPE  = "bidding"
 )
 
 /*某组关键词-推送结果预览总数
@@ -43,38 +44,38 @@ const (
  *@param notkey 排除词
  *@param matchway 0:精准 1:模糊
  */
-func KeysetViewDatasCount(userId, vType, key, notkey string, matchway int,session *httpsession.Session) int64 {
-        key = strings.TrimSpace(key)
-        notkey = strings.TrimSpace(notkey)
-        if key == "" {
-                return 0
-        }
-        sql := &ViewCondition{}
-        if vType == "" {
-                sql = GetSqlObjFromFreeId(userId, "", -1)
-        } else {
-                sql = GetSqlObjFromId(userId, vType, "", -1,session)
-        }
+func KeysetViewDatasCount(userId, vType, key, notkey string, matchway int, session *httpsession.Session) int64 {
+    key = strings.TrimSpace(key)
+    notkey = strings.TrimSpace(notkey)
+    if key == "" {
+        return 0
+    }
+    sql := &ViewCondition{}
+    if vType == "" {
+        sql = GetSqlObjFromFreeId(userId, "", -1)
+    } else {
+        sql = GetSqlObjFromId(userId, vType, "", -1, session)
+    }
 
-        viewKeyWords := []ViewKeyWord{}
-        if matchway == 0 {
-                viewKeyWords = append(viewKeyWords, ViewKeyWord{
-                        Keyword:  strings.Split(key, " "),
-                        Exclude:  strings.Split(notkey, " "),
-                        MatchWay: matchway,
-                })
-        } else {
-                for _, v := range strings.Split(key, " ") {
-                        viewKeyWords = append(viewKeyWords, ViewKeyWord{
-                                Keyword:  []string{v},
-                                Exclude:  strings.Split(notkey, " "),
-                                MatchWay: matchway,
-                        })
-                }
+    viewKeyWords := []ViewKeyWord{}
+    if matchway == 0 {
+        viewKeyWords = append(viewKeyWords, ViewKeyWord{
+            Keyword:  strings.Split(key, " "),
+            Exclude:  strings.Split(notkey, " "),
+            MatchWay: matchway,
+        })
+    } else {
+        for _, v := range strings.Split(key, " ") {
+            viewKeyWords = append(viewKeyWords, ViewKeyWord{
+                Keyword:  []string{v},
+                Exclude:  strings.Split(notkey, " "),
+                MatchWay: matchway,
+            })
         }
-        sql.Keyword = viewKeyWords
-        qstr := GetVIPViewSql(userId, sql)
-        return elastic.Count(INDEX, TYPE, qstr)
+    }
+    sql.Keyword = viewKeyWords
+    qstr := GetVIPViewSql(userId, sql)
+    return elastic.Count(INDEX, TYPE, qstr)
 }
 
 /*推送结果预览总数
@@ -82,330 +83,329 @@ func KeysetViewDatasCount(userId, vType, key, notkey string, matchway int,sessio
  *@param item 分类名称
  *@param index 关键词在分类下的索引位置
  */
-func SubViewDatasCount(userId, vType, item string, index int,session *httpsession.Session) int64 {
-        sql := GetSqlObjFromId(userId, vType, item, index,session)
-        if item != "" && index >= 0 && (sql.Keyword == nil || len(sql.Keyword) == 0) {
-                log.Println("推送结果预览总数参数异常,没有找到改组订阅词", item, index)
-                return 0
-        }
-        qstr := GetVIPViewSql(userId, sql)
-        return elastic.Count(INDEX, TYPE, qstr)
+func SubViewDatasCount(userId, vType, item string, index int, session *httpsession.Session) int64 {
+    sql := GetSqlObjFromId(userId, vType, item, index, session)
+    if item != "" && index >= 0 && (sql.Keyword == nil || len(sql.Keyword) == 0) {
+        log.Println("推送结果预览总数参数异常,没有找到改组订阅词", item, index)
+        return 0
+    }
+    qstr := GetVIPViewSql(userId, sql)
+    return elastic.Count(INDEX, TYPE, qstr)
 }
 
 //获取vip订阅预览的查询语句
 func GetVIPViewSql(userId string, scd *ViewCondition) string {
-        query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
-        query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
-        multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
-        query_bool_must_and := `{"bool":{"must":[%s]%s}}`
+    query := `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": %d}}}`
+    query_bool_should := `{"bool":{"should":[%s],"minimum_should_match": 1}}`
+    multi_match := `{"multi_match": {"query": %s,"type": "phrase", "fields": [%s]}}`
+    query_bool_must_and := `{"bool":{"must":[%s]%s}}`
 
-        bools := []string{}
-        musts := []string{}
-        //发布时间最新三个月
-        musts = append(musts, fmt.Sprintf(`{"range":{"publishtime":{"gte":%d}}}`, time.Now().AddDate(0, -3, 0).Unix()))
-        //省份
-        areaCity := []string{}
-        if len(scd.Area) > 0 {
-                areaquery := `{"terms":{"area":[`
-                for k, v := range scd.Area {
-                        if k > 0 {
-                                areaquery += `,`
-                        }
-                        areaquery += `"` + v + `"`
-                }
-                areaquery += `]}}`
-                areaCity = append(areaCity, areaquery)
+    bools := []string{}
+    musts := []string{}
+    //发布时间最新三个月
+    musts = append(musts, fmt.Sprintf(`{"range":{"publishtime":{"gte":%d}}}`, time.Now().AddDate(0, -3, 0).Unix()))
+    //省份
+    areaCity := []string{}
+    if len(scd.Area) > 0 {
+        areaquery := `{"terms":{"area":[`
+        for k, v := range scd.Area {
+            if k > 0 {
+                areaquery += `,`
+            }
+            areaquery += `"` + v + `"`
         }
+        areaquery += `]}}`
+        areaCity = append(areaCity, areaquery)
+    }
 
-        //城市
-        if len(scd.City) > 0 {
-                areaquery := `{"terms":{"city":[`
-                for k, v := range scd.City {
-                        if k > 0 {
-                                areaquery += `,`
-                        }
-                        areaquery += `"` + v + `"`
-                }
-                areaquery += `]}}`
-                areaCity = append(areaCity, areaquery)
+    //城市
+    if len(scd.City) > 0 {
+        areaquery := `{"terms":{"city":[`
+        for k, v := range scd.City {
+            if k > 0 {
+                areaquery += `,`
+            }
+            areaquery += `"` + v + `"`
         }
-        if len(areaCity) > 0 {
-                musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
+        areaquery += `]}}`
+        areaCity = append(areaCity, areaquery)
+    }
+    if len(areaCity) > 0 {
+        musts = append(musts, fmt.Sprintf(query_bool_should, strings.Join(areaCity, ",")))
+    }
+    if len(scd.Subtype) > 0 {
+        subquery := `{"terms":{"subtype":[`
+        for k, v := range scd.Subtype {
+            if k > 0 {
+                subquery += `,`
+            }
+            subquery += `"` + v + `"`
         }
-        if len(scd.Subtype) > 0 {
-                subquery := `{"terms":{"subtype":[`
-                for k, v := range scd.Subtype {
-                        if k > 0 {
-                                subquery += `,`
-                        }
-                        subquery += `"` + v + `"`
-                }
-                subquery += `]}}`
-                musts = append(musts, subquery)
+        subquery += `]}}`
+        musts = append(musts, subquery)
+    }
+    if len(scd.Buyerclass) > 0 {
+        Buyerclass := `{"terms":{"buyerclass":[`
+        for k, v := range scd.Buyerclass {
+            if k > 0 {
+                Buyerclass += `,`
+            }
+            Buyerclass += `"` + v + `"`
         }
-        if len(scd.Buyerclass) > 0 {
-                Buyerclass := `{"terms":{"buyerclass":[`
-                for k, v := range scd.Buyerclass {
-                        if k > 0 {
-                                Buyerclass += `,`
-                        }
-                        Buyerclass += `"` + v + `"`
-                }
-                Buyerclass += `]}}`
-                musts = append(musts, Buyerclass)
+        Buyerclass += `]}}`
+        musts = append(musts, Buyerclass)
+    }
+    boolsNum := 0 //should
+    if len(scd.Keyword) > 0 {
+        boolsNum = 1
+        if scd.SelectType == "" || scd.SelectType == "2" {
+            scd.SelectType = "detail\", \"title"
+        } else {
+            scd.SelectType = "title"
         }
-        boolsNum := 0 //should
-        if len(scd.Keyword) > 0 {
-                boolsNum = 1
-                if scd.SelectType == "" || scd.SelectType == "2" {
-                        scd.SelectType = "detail\", \"title"
-                } else {
-                        scd.SelectType = "title"
-                }
-                multi_match = fmt.Sprintf(multi_match, "%s", "\""+scd.SelectType+"\"")
+        multi_match = fmt.Sprintf(multi_match, "%s", "\""+scd.SelectType+"\"")
 
-                for _, v := range scd.Keyword {
-                        shoulds := []string{}
-                        must_not := []string{}
-                        //附加词
-                        for _, vv := range v.Keyword {
-                                vv = strings.TrimSpace(vv)
-                                if vv == "" {
-                                        continue
-                                }
-                                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-                        }
+        for _, v := range scd.Keyword {
+            shoulds := []string{}
+            must_not := []string{}
+            //附加词
+            for _, vv := range v.Keyword {
+                vv = strings.TrimSpace(vv)
+                if vv == "" {
+                    continue
+                }
+                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+            }
 
-                        for _, vv := range v.Appended {
-                                vv = strings.TrimSpace(vv)
-                                if vv == "" {
-                                        continue
-                                }
-                                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-                        }
+            for _, vv := range v.Appended {
+                vv = strings.TrimSpace(vv)
+                if vv == "" {
+                    continue
+                }
+                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+            }
 
-                        //排除词
-                        for _, vv := range v.Exclude {
-                                vv = strings.TrimSpace(vv)
-                                if vv == "" {
-                                        continue
-                                }
-                                must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
-                        }
+            //排除词
+            for _, vv := range v.Exclude {
+                vv = strings.TrimSpace(vv)
+                if vv == "" {
+                    continue
+                }
+                must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
+            }
 
-                        //添加
-                        if len(shoulds) > 0 {
-                                notStr := ""
-                                if len(must_not) > 0 {
-                                        notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
-                                }
-                                bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
-                        }
+            //添加
+            if len(shoulds) > 0 {
+                notStr := ""
+                if len(must_not) > 0 {
+                    notStr = fmt.Sprintf(`,"must_not":[%s]`, strings.Join(must_not, ","))
                 }
+                bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(shoulds, ","), notStr))
+            }
         }
+    }
 
-        qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
-        log.Println(userId, "推送结果预览", qstr)
-        return qstr
+    qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
+    log.Println(userId, "推送结果预览", qstr)
+    return qstr
 }
 
 //
 func GetSqlObjFromId(_id, vType, item string, index int, session *httpsession.Session) *ViewCondition {
-        o_vipjy := map[string]interface{}{}
-        types := ""
-        if vType == jy.MemberFlag {
-                types = "v"
-        } else {
-                types = "m"
-        }
-        data := jy.GetSubScribeInfo(session, db.Mgo, types, "10000")
-        a_items, _ := (*data)["a_items"].([]interface{})
-        a_buyerclass, _ := o_vipjy["a_buyerclass"].([]interface{})
-        if len(a_buyerclass) > 0 && qutil.IntAllDef(o_vipjy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
-                a_buyerclass = append(a_buyerclass, "其它")
-        }
-        a_infotype, _ := o_vipjy["a_infotype"].([]interface{})
-        o_area, _ := o_vipjy["o_area"].(map[string]interface{})
-        return &ViewCondition{
-                Keyword:    getKeyWordArrFromDbResult(a_items, item, index),
-                Buyerclass: qutil.ObjArrToStringArr(a_buyerclass),
-                Subtype:    qutil.ObjArrToStringArr(a_infotype),
-                Area:       getStringArrFromDbResult(o_area, 1),
-                City:       getStringArrFromDbResult(o_area, 2),
-                SelectType: strconv.Itoa(qutil.IntAll(o_vipjy["i_matchway"])),
-        }
+    o_vipjy := map[string]interface{}{}
+    types := ""
+    if vType == jy.MemberFlag {
+        types = "v"
+    } else {
+        types = "m"
+    }
+    data := jy.GetSubScribeInfo(session, db.Mgo, types, "10000")
+    a_items, _ := (*data)["a_items"].([]interface{})
+    a_buyerclass, _ := o_vipjy["a_buyerclass"].([]interface{})
+    if len(a_buyerclass) > 0 && qutil.IntAllDef(o_vipjy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
+        a_buyerclass = append(a_buyerclass, "其它")
+    }
+    a_infotype, _ := o_vipjy["a_infotype"].([]interface{})
+    o_area, _ := o_vipjy["o_area"].(map[string]interface{})
+    return &ViewCondition{
+        Keyword:    getKeyWordArrFromDbResult(a_items, item, index),
+        Buyerclass: qutil.ObjArrToStringArr(a_buyerclass),
+        Subtype:    qutil.ObjArrToStringArr(a_infotype),
+        Area:       getStringArrFromDbResult(o_area, 1),
+        City:       getStringArrFromDbResult(o_area, 2),
+        SelectType: strconv.Itoa(qutil.IntAll(o_vipjy["i_matchway"])),
+    }
 }
 
 //
 func getStringArrFromDbResult(area map[string]interface{}, i int) (arr []string) {
-        if area == nil {
-                return
-        }
-        var eareArr []string
-        var cityArr []string
-        for k, v := range area {
-                if len(v.([]interface{})) > 0 {
-                        cityArr = append(cityArr, qutil.ObjArrToStringArr(v.([]interface{}))...)
-                } else {
-                        eareArr = append(eareArr, k)
-                }
-        }
-        if i == 1 {
-                arr = eareArr
+    if area == nil {
+        return
+    }
+    var eareArr []string
+    var cityArr []string
+    for k, v := range area {
+        if len(v.([]interface{})) > 0 {
+            cityArr = append(cityArr, qutil.ObjArrToStringArr(v.([]interface{}))...)
         } else {
-                arr = cityArr
+            eareArr = append(eareArr, k)
         }
-        return
+    }
+    if i == 1 {
+        arr = eareArr
+    } else {
+        arr = cityArr
+    }
+    return
 }
 
 //关键词 附加词 排除词
 func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
-        if a_items == nil {
-                return
+    if a_items == nil {
+        return
+    }
+    for _, v := range a_items {
+        vm, _ := v.(map[string]interface{})
+        if item != "" && index >= 0 && item != qutil.ObjToString(vm["s_item"]) {
+            continue
         }
-        for _, v := range a_items {
-                vm, _ := v.(map[string]interface{})
-                if item != "" && index >= 0 && item != qutil.ObjToString(vm["s_item"]) {
-                        continue
+        kwsArr := vm["a_key"]
+        for i, k := range kwsArr.([]interface{}) {
+            if item != "" && index >= 0 && i != index {
+                continue
+            }
+            kw := ViewKeyWord{}
+            b, e := json.Marshal(k)
+            if e != nil {
+                log.Println(e.Error())
+            }
+            json.Unmarshal(b, &kw)
+            if kw.MatchWay == 1 {
+                for _, kk := range kw.Keyword {
+                    arr = append(arr, ViewKeyWord{
+                        Keyword: []string{kk},
+                        Exclude: kw.Exclude,
+                    })
                 }
-                kwsArr := vm["a_key"]
-                for i, k := range kwsArr.([]interface{}) {
-                        if item != "" && index >= 0 && i != index {
-                                continue
-                        }
-                        kw := ViewKeyWord{}
-                        b, e := json.Marshal(k)
-                        if e != nil {
-                                log.Println(e.Error())
-                        }
-                        json.Unmarshal(b, &kw)
-                        if kw.MatchWay == 1 {
-                                for _, kk := range kw.Keyword {
-                                        arr = append(arr, ViewKeyWord{
-                                                Keyword: []string{kk},
-                                                Exclude: kw.Exclude,
-                                        })
-                                }
-                                for _, kk := range kw.Appended {
-                                        arr = append(arr, ViewKeyWord{
-                                                Keyword: []string{kk},
-                                                Exclude: kw.Exclude,
-                                        })
-                                }
-                        } else {
-                                arr = append(arr, kw)
-                        }
+                for _, kk := range kw.Appended {
+                    arr = append(arr, ViewKeyWord{
+                        Keyword: []string{kk},
+                        Exclude: kw.Exclude,
+                    })
                 }
+            } else {
+                arr = append(arr, kw)
+            }
         }
-        return
+    }
+    return
 }
 
 //免费用户对象
 func GetSqlObjFromFreeId(_id, item string, index int) *ViewCondition {
-        var (
-                query *map[string]interface{}
-                ok    bool
-        )
-        if query, ok = db.Mgo.FindById("user", _id, `{"o_jy":1}`); !ok && (*query)["o_jy"] == nil {
-                return nil
-        }
-        o_jy, _ := (*query)["o_jy"].(map[string]interface{})
+    var (
+        query *map[string]interface{}
+    )
+    if query = config.Compatible.Select(_id, `{"o_jy":1}`);  (*query)["o_jy"] == nil {
+        return nil
+    }
+    o_jy, _ := (*query)["o_jy"].(map[string]interface{})
 
-        if o_jy["a_key"] == nil {
-                return nil
-        }
-        //关键词组
-        a_items := []interface{}{}
-        a_items = append(a_items, o_jy["a_key"])
-        //采购单位类型
-        a_buyerclass := []interface{}{}
-        //信息类型
-        a_infotype := []string{}
-        infotypeArr := ""
-        if o_jy["a_infotype"] != nil {
-                a_infotype = qutil.ObjArrToStringArr(o_jy["a_infotype"].([]interface{}))
-                for k, v := range a_infotype {
-                        infotype := v
-                        infotypeArr += getstype(infotype)
-                        if k != len(a_infotype)-1 {
-                                infotypeArr += ","
-                        }
-                }
-        }
-        if infotypeArr != "" {
-                a_infotype = strings.Split(infotypeArr, ",")
-        }
-        //省份
-        o_area := qutil.ObjToMap(o_jy["o_area"])
-        if qutil.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
-                o_area = qutil.ObjToMap(o_jy["o_area_p"])
-        }
-        return &ViewCondition{
-                Keyword:    getKeyWordArrFromDbResultByFree(a_items, item, index), //关键词
-                Buyerclass: qutil.ObjArrToStringArr(a_buyerclass),                 //采购单位类型
-                Subtype:    a_infotype,                                            //信息类型
-                Area:       getStringArrFromDbResult(*o_area, 1),                  //省份
-                SelectType: strconv.Itoa(qutil.IntAll(o_jy["i_matchway"])),        //匹配方式
+    if o_jy["a_key"] == nil {
+        return nil
+    }
+    //关键词组
+    a_items := []interface{}{}
+    a_items = append(a_items, o_jy["a_key"])
+    //采购单位类型
+    a_buyerclass := []interface{}{}
+    //信息类型
+    a_infotype := []string{}
+    infotypeArr := ""
+    if o_jy["a_infotype"] != nil {
+        a_infotype = qutil.ObjArrToStringArr(o_jy["a_infotype"].([]interface{}))
+        for k, v := range a_infotype {
+            infotype := v
+            infotypeArr += getstype(infotype)
+            if k != len(a_infotype)-1 {
+                infotypeArr += ","
+            }
         }
+    }
+    if infotypeArr != "" {
+        a_infotype = strings.Split(infotypeArr, ",")
+    }
+    //省份
+    o_area := qutil.ObjToMap(o_jy["o_area"])
+    if qutil.IntAllDef(o_jy["i_ppstatus"], 0) == 1 && o_jy["o_area_p"] != nil {
+        o_area = qutil.ObjToMap(o_jy["o_area_p"])
+    }
+    return &ViewCondition{
+        Keyword:    getKeyWordArrFromDbResultByFree(a_items, item, index), //关键词
+        Buyerclass: qutil.ObjArrToStringArr(a_buyerclass),                 //采购单位类型
+        Subtype:    a_infotype,                                            //信息类型
+        Area:       getStringArrFromDbResult(*o_area, 1),                  //省份
+        SelectType: strconv.Itoa(qutil.IntAll(o_jy["i_matchway"])),        //匹配方式
+    }
 }
 
 //
 func getstype(stype string) string {
-        switch stype {
-        case "招标":
-                stype = "招标,邀标,询价,竞谈,单一,竞价,变更"
-        case "结果":
-                stype = "中标,成交,废标,流标,结果变更"
-        case "其它":
-                stype = "合同,验收,违规"
-        case "预告":
-                stype = "预告,需求公示,预审,论证意见,预审结果"
-        }
-        return stype
+    switch stype {
+    case "招标":
+        stype = "招标,邀标,询价,竞谈,单一,竞价,变更"
+    case "结果":
+        stype = "中标,成交,废标,流标,结果变更"
+    case "其它":
+        stype = "合同,验收,违规"
+    case "预告":
+        stype = "预告,需求公示,预审,论证意见,预审结果"
+    }
+    return stype
 }
 
 // //关键词 附加词 排除词  省份订阅包
 func getKeyWordArrFromDbResultByFree(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
-        if a_items == nil || len(a_items) == 0 {
-                return
+    if a_items == nil || len(a_items) == 0 {
+        return
+    }
+    for _, v := range a_items {
+        vmr, _ := v.([]interface{})
+        if len(vmr) == 0 {
+            continue
         }
-        for _, v := range a_items {
-                vmr, _ := v.([]interface{})
-                if len(vmr) == 0 {
-                        continue
-                }
-                vm, _ := vmr[0].(map[string]interface{})
-                if item != "" && index >= 0 && item != qutil.ObjToString(vm["s_item"]) {
-                        continue
+        vm, _ := vmr[0].(map[string]interface{})
+        if item != "" && index >= 0 && item != qutil.ObjToString(vm["s_item"]) {
+            continue
+        }
+        kwsArr := vmr
+        for i, k := range kwsArr {
+            if item != "" && index >= 0 && i != index {
+                continue
+            }
+            kw := ViewKeyWord{}
+            b, e := json.Marshal(k)
+            if e != nil {
+                log.Println(e.Error())
+            }
+            json.Unmarshal(b, &kw)
+            if kw.MatchWay == 1 {
+                for _, kk := range kw.Keyword {
+                    arr = append(arr, ViewKeyWord{
+                        Keyword: []string{kk},
+                        Exclude: kw.Exclude,
+                    })
                 }
-                kwsArr := vmr
-                for i, k := range kwsArr {
-                        if item != "" && index >= 0 && i != index {
-                                continue
-                        }
-                        kw := ViewKeyWord{}
-                        b, e := json.Marshal(k)
-                        if e != nil {
-                                log.Println(e.Error())
-                        }
-                        json.Unmarshal(b, &kw)
-                        if kw.MatchWay == 1 {
-                                for _, kk := range kw.Keyword {
-                                        arr = append(arr, ViewKeyWord{
-                                                Keyword: []string{kk},
-                                                Exclude: kw.Exclude,
-                                        })
-                                }
-                                for _, kk := range kw.Appended {
-                                        arr = append(arr, ViewKeyWord{
-                                                Keyword: []string{kk},
-                                                Exclude: kw.Exclude,
-                                        })
-                                }
-                        } else {
-                                arr = append(arr, kw)
-                        }
+                for _, kk := range kw.Appended {
+                    arr = append(arr, ViewKeyWord{
+                        Keyword: []string{kk},
+                        Exclude: kw.Exclude,
+                    })
                 }
+            } else {
+                arr = append(arr, kw)
+            }
         }
-        return
+    }
+    return
 }

+ 2 - 2
src/jfw/modules/publicapply/src/userbase/entity/entity.go

@@ -199,8 +199,8 @@ func HasIndustryTag(session *httpsession.Session, userId string) bool {
 		return hasTag
 	}
 	// 查免费用户订阅的关键词
-	rs, b := db.Mgo.FindById("user", userId, `"o_jy":1`)
-	if !b || rs == nil || len(*rs) == 0 || (*rs)["o_jy"] == nil {
+	rs:= config.Compatible.Select( userId, `"o_jy":1`)
+	if  rs == nil || len(*rs) == 0 || (*rs)["o_jy"] == nil {
 		// 没查到关键词
 		redis.Put("newother", cacheKey, hasTag, cacheTimeout)
 		return hasTag

+ 207 - 207
src/jfw/modules/publicapply/src/util/util.go

@@ -1,37 +1,37 @@
 package util
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/publicapply/src/config"
-	"jy/src/jfw/modules/publicapply/src/db"
-	"regexp"
-	"strconv"
-	"strings"
-	"time"
+    "encoding/json"
+    "fmt"
+    "jy/src/jfw/modules/publicapply/src/config"
+    "jy/src/jfw/modules/publicapply/src/db"
+    "regexp"
+    "strconv"
+    "strings"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 var ClearHtml = regexp.MustCompile("<[^>]*>")
 
 //加密
 func EncodeId(sid string) string {
-	if sid == "" {
-		return ""
-	}
-	return encrypt.EncodeArticleId2ByCheck(sid)
+    if sid == "" {
+        return ""
+    }
+    return encrypt.EncodeArticleId2ByCheck(sid)
 }
 
 //解密
 func DecodeId(eid string) string {
-	if eid == "" {
-		return ""
-	}
-	return encrypt.CommonDecodeArticle("content", eid)[0]
+    if eid == "" {
+        return ""
+    }
+    return encrypt.CommonDecodeArticle("content", eid)[0]
 }
 
 //收藏列表
@@ -43,231 +43,231 @@ func DecodeId(eid string) string {
 	   开始时间-结束时间:1622476800-1623859200
 */
 type CollList struct {
-	Pagenum     int    `json:"pagenum"`     //页数
-	Label       string `json:"label"`       //标签 用,分隔开
-	SelectTime  string `json:"selectTime"`  //收藏时间
-	Buyerclass  string `json:"buyerclass"`  //采购单位 用,分隔开
-	BuyerPhone  int    `json:"buyerPhone"`  //是否需要采购单位联系方式 1:需要 -1:不需要 0:未选中
-	WinnerPhone int    `json:"winnerPhone"` //是否需要中标单位联系方式 1:需要 -1:不需要 0:未选中
-	Pagesize    int    `json:"pagesize"`    //每页展示数量
+    Pagenum     int    `json:"pagenum"`     //页数
+    Label       string `json:"label"`       //标签 用,分隔开
+    SelectTime  string `json:"selectTime"`  //收藏时间
+    Buyerclass  string `json:"buyerclass"`  //采购单位 用,分隔开
+    BuyerPhone  int    `json:"buyerPhone"`  //是否需要采购单位联系方式 1:需要 -1:不需要 0:未选中
+    WinnerPhone int    `json:"winnerPhone"` //是否需要中标单位联系方式 1:需要 -1:不需要 0:未选中
+    Pagesize    int    `json:"pagesize"`    //每页展示数量
 }
 
 //搜藏列表
 func CollListSql(c *CollList, isPay bool, userid string) string {
-	sql := fmt.Sprintf(`select bid from %s where userid ='%s'`, db.DbConf.Bdcollection, userid)
-	limit := config.BidCollConfig.FreeUserCollLimit
-	//个人标签
-	if c.Label != "" {
-		i := 0
-		sql += ` and `
-		if labelArr := strings.Split(c.Label, ","); len(labelArr) > 0 {
-			sql += `(`
-			for _, v := range labelArr {
-				i++
-				labid := encrypt.SE.DecodeString(v)
-				if i == len(labelArr) {
-					sql += fmt.Sprintf(`FIND_IN_SET(%s,labelid)`, labid)
-				} else {
-					sql += fmt.Sprintf(`FIND_IN_SET(%s,labelid) or `, labid)
-				}
-			}
-			sql += `)`
-		}
-	}
-	now := time.Now()
-	start, end := "", ""
-	//收藏时间
-	if c.SelectTime == "lately-7" { //最近7天
-		start = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-7, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
-	} else if c.SelectTime == "lately-30" { //最近30天
-		start = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-30, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
-	} else if c.SelectTime == "thisyear" { //去年
-		start = fmt.Sprint(time.Date(now.Year()-1, 1, 1, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
-		end = fmt.Sprint(time.Date(now.Year()-1, 12, 31, 23, 59, 59, 0, time.Local).Format(Date_Full_Layout))
-	} else if len(strings.Split(c.SelectTime, "_")) == 2 {
-		if c.SelectTime != "0_0" {
-			starttime := strings.Split(c.SelectTime, "_")[0]
-			startstamp, _ := strconv.Atoi(starttime)
-			start = time.Unix(int64(startstamp), 0).Format(Date_Full_Layout)
-			endtime := strings.Split(c.SelectTime, "_")[1]
-			et, _ := strconv.ParseInt(endtime, 0, 64)
-			etTime := time.Unix(et, 0)
-			end = fmt.Sprint(time.Date(etTime.Year(), etTime.Month(), etTime.Day()+1, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
-		}
-	}
-	if start != "" && end != "" {
-		sql += ` and createdate >= '` + start + `' and createdate < '` + end + `'`
-	} else if start != "" && end == "" {
-		sql += ` and createdate >= '` + start + `'`
-	} else if start == "" && end != "" {
-		sql += ` and createdate < '` + end + `'`
-	}
-	if isPay {
+    sql := fmt.Sprintf(`select bid from %s where userid ='%s'`, db.DbConf.Bdcollection, userid)
+    limit := config.BidCollConfig.FreeUserCollLimit
+    //个人标签
+    if c.Label != "" {
+        i := 0
+        sql += ` and `
+        if labelArr := strings.Split(c.Label, ","); len(labelArr) > 0 {
+            sql += `(`
+            for _, v := range labelArr {
+                i++
+                labid := encrypt.SE.DecodeString(v)
+                if i == len(labelArr) {
+                    sql += fmt.Sprintf(`FIND_IN_SET(%s,labelid)`, labid)
+                } else {
+                    sql += fmt.Sprintf(`FIND_IN_SET(%s,labelid) or `, labid)
+                }
+            }
+            sql += `)`
+        }
+    }
+    now := time.Now()
+    start, end := "", ""
+    //收藏时间
+    if c.SelectTime == "lately-7" { //最近7天
+        start = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-7, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
+    } else if c.SelectTime == "lately-30" { //最近30天
+        start = fmt.Sprint(time.Date(now.Year(), now.Month(), now.Day()-30, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
+    } else if c.SelectTime == "thisyear" { //去年
+        start = fmt.Sprint(time.Date(now.Year()-1, 1, 1, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
+        end = fmt.Sprint(time.Date(now.Year()-1, 12, 31, 23, 59, 59, 0, time.Local).Format(Date_Full_Layout))
+    } else if len(strings.Split(c.SelectTime, "_")) == 2 {
+        if c.SelectTime != "0_0" {
+            starttime := strings.Split(c.SelectTime, "_")[0]
+            startstamp, _ := strconv.Atoi(starttime)
+            start = time.Unix(int64(startstamp), 0).Format(Date_Full_Layout)
+            endtime := strings.Split(c.SelectTime, "_")[1]
+            et, _ := strconv.ParseInt(endtime, 0, 64)
+            etTime := time.Unix(et, 0)
+            end = fmt.Sprint(time.Date(etTime.Year(), etTime.Month(), etTime.Day()+1, 0, 0, 0, 0, time.Local).Format(Date_Full_Layout))
+        }
+    }
+    if start != "" && end != "" {
+        sql += ` and createdate >= '` + start + `' and createdate < '` + end + `'`
+    } else if start != "" && end == "" {
+        sql += ` and createdate >= '` + start + `'`
+    } else if start == "" && end != "" {
+        sql += ` and createdate < '` + end + `'`
+    }
+    if isPay {
 
-		//采购单位 用,分隔开
-		if c.Buyerclass != "" {
-			i := 0
-			sql += ` and buyerclass in (`
-			if buyClassArr := strings.Split(c.Buyerclass, ","); len(buyClassArr) > 0 {
-				for _, v := range buyClassArr {
-					i++
-					buyerclassid := fmt.Sprint(jy.PushMapping.Buyerclass[v])
-					if i == len(buyClassArr) {
-						sql += buyerclassid + `)`
-					} else {
-						sql += buyerclassid + ","
-					}
-				}
-			}
-		}
-		//是否存在采购单位电话
-		if c.BuyerPhone == 1 {
-			sql += ` and buyerinfo = 1`
-		} else if c.BuyerPhone == -1 {
-			sql += ` and buyerinfo = 0`
-		}
-		//是否存在中标单位电话
-		if c.WinnerPhone == 1 {
-			sql += ` and winnerinfo = 1`
-		} else if c.WinnerPhone == -1 {
-			sql += ` and winnerinfo = 0`
-		}
-		limit = config.BidCollConfig.PayUserCollLimit
-	}
-	sql += fmt.Sprintf(` order by createdate desc limit %v`, limit)
-	return sql
+        //采购单位 用,分隔开
+        if c.Buyerclass != "" {
+            i := 0
+            sql += ` and buyerclass in (`
+            if buyClassArr := strings.Split(c.Buyerclass, ","); len(buyClassArr) > 0 {
+                for _, v := range buyClassArr {
+                    i++
+                    buyerclassid := fmt.Sprint(jy.PushMapping.Buyerclass[v])
+                    if i == len(buyClassArr) {
+                        sql += buyerclassid + `)`
+                    } else {
+                        sql += buyerclassid + ","
+                    }
+                }
+            }
+        }
+        //是否存在采购单位电话
+        if c.BuyerPhone == 1 {
+            sql += ` and buyerinfo = 1`
+        } else if c.BuyerPhone == -1 {
+            sql += ` and buyerinfo = 0`
+        }
+        //是否存在中标单位电话
+        if c.WinnerPhone == 1 {
+            sql += ` and winnerinfo = 1`
+        } else if c.WinnerPhone == -1 {
+            sql += ` and winnerinfo = 0`
+        }
+        limit = config.BidCollConfig.PayUserCollLimit
+    }
+    sql += fmt.Sprintf(` order by createdate desc limit %v`, limit)
+    return sql
 }
 
 func ConfirmIntArr(arr []interface{}) []int {
-	tmp := make([]int, 0)
-	for _, v := range arr {
-		tmp = append(tmp, qutil.IntAll(v))
-	}
-	return tmp
+    tmp := make([]int, 0)
+    for _, v := range arr {
+        tmp = append(tmp, qutil.IntAll(v))
+    }
+    return tmp
 }
 
 //判断同一个数组是否重复
 func IsRepeat(slice1 []string) bool {
-	m := make(map[string]int)
-	for _, v := range slice1 {
-		m[v]++
-		if m[v] > 1 {
-			return true
-		}
-	}
-	return false
+    m := make(map[string]int)
+    for _, v := range slice1 {
+        m[v]++
+        if m[v] > 1 {
+            return true
+        }
+    }
+    return false
 }
 
 //判断数组是否包含
 func IsContain(slice []string, s string) bool {
-	for _, qq := range slice {
-		if qq == s {
-			return true
-		}
-	}
-	return false
+    for _, qq := range slice {
+        if qq == s {
+            return true
+        }
+    }
+    return false
 }
 
 // jsonStr转map
 func JsonToMap(jsonStr string) (map[string]interface{}, error) {
-	m := map[string]interface{}{}
-	err := json.Unmarshal([]byte(jsonStr), &m)
-	if err != nil {
-		fmt.Printf("Unmarshal with error: %+v\n", err)
-		return nil, err
-	}
-	return m, nil
+    m := map[string]interface{}{}
+    err := json.Unmarshal([]byte(jsonStr), &m)
+    if err != nil {
+        fmt.Printf("Unmarshal with error: %+v\n", err)
+        return nil, err
+    }
+    return m, nil
 }
 
 //判断stringArr相等方法
 func StringArrEqual(a, b []string) bool {
-	if (len(a) == 0) != (len(b) == 0) {
-		return false
-	}
-	if len(a) != len(b) {
-		return false
-	}
-	for i := range a {
-		if a[i] != b[i] {
-			return false
-		}
-	}
-	return true
+    if (len(a) == 0) != (len(b) == 0) {
+        return false
+    }
+    if len(a) != len(b) {
+        return false
+    }
+    for i := range a {
+        if a[i] != b[i] {
+            return false
+        }
+    }
+    return true
 }
 
 //获取频次信息:fre="周-1"(每周周一);"天-3":每三天一个周期;"日-3":每天三点;
 func GetFrequencyInfo(fre string) (string, bool, int) {
-	if fre != "" && len(strings.Split(fre, "-")) > 1 {
-		f := strings.Split(fre, "-")[0]
-		d, _ := strconv.Atoi(strings.Split(fre, "-")[1])
-		switch f {
-		case "月":
-			day := time.Now().Day()
-			return fmt.Sprintf("nps_%s", time.Now().Month().String()), day == d, 31 * 24 * 60 * 60
-		case "周":
-			mi := ConvertWeekday(time.Now().Weekday().String())
-			return fmt.Sprintf("nps_%s", WeekByDate(time.Now())), mi == d, 7 * 24 * 60 * 60
-		case "日":
-			day := time.Now().Day()
-			hour := time.Now().Hour()
-			return fmt.Sprintf("nps_%s", strconv.Itoa(day)), hour == d, 24 * 60 * 60
-		case "天":
-			return fmt.Sprintf("nps_%s", strings.Split(fre, "-")[1]), true, d * 24 * 60 * 60
-		}
-	}
-	return "", false, 0
+    if fre != "" && len(strings.Split(fre, "-")) > 1 {
+        f := strings.Split(fre, "-")[0]
+        d, _ := strconv.Atoi(strings.Split(fre, "-")[1])
+        switch f {
+        case "月":
+            day := time.Now().Day()
+            return fmt.Sprintf("nps_%s", time.Now().Month().String()), day == d, 31 * 24 * 60 * 60
+        case "周":
+            mi := ConvertWeekday(time.Now().Weekday().String())
+            return fmt.Sprintf("nps_%s", WeekByDate(time.Now())), mi == d, 7 * 24 * 60 * 60
+        case "日":
+            day := time.Now().Day()
+            hour := time.Now().Hour()
+            return fmt.Sprintf("nps_%s", strconv.Itoa(day)), hour == d, 24 * 60 * 60
+        case "天":
+            return fmt.Sprintf("nps_%s", strings.Split(fre, "-")[1]), true, d * 24 * 60 * 60
+        }
+    }
+    return "", false, 0
 }
 
 //获取当年第几周
 func WeekByDate(t time.Time) string {
-	yearDay := t.YearDay()
-	yearFirstDay := t.AddDate(0, 0, -yearDay+1)
-	firstDayInWeek := int(yearFirstDay.Weekday())
+    yearDay := t.YearDay()
+    yearFirstDay := t.AddDate(0, 0, -yearDay+1)
+    firstDayInWeek := int(yearFirstDay.Weekday())
 
-	//今年第一周有几天
-	firstWeekDays := 1
-	if firstDayInWeek != 0 {
-		firstWeekDays = 7 - firstDayInWeek + 1
-	}
-	var week int
-	if yearDay <= firstWeekDays {
-		week = 1
-	} else {
-		week = (yearDay-firstWeekDays)/7 + 2
-	}
-	return fmt.Sprintf("%d-%d", t.Year(), week)
+    //今年第一周有几天
+    firstWeekDays := 1
+    if firstDayInWeek != 0 {
+        firstWeekDays = 7 - firstDayInWeek + 1
+    }
+    var week int
+    if yearDay <= firstWeekDays {
+        week = 1
+    } else {
+        week = (yearDay-firstWeekDays)/7 + 2
+    }
+    return fmt.Sprintf("%d-%d", t.Year(), week)
 }
 
 func ConvertWeekday(weekday string) int {
-	_weekday := 0
-	if weekday == "Sunday" {
-		_weekday = 7
-	} else if weekday == "Monday" {
-		_weekday = 1
-	} else if weekday == "Tuesday" {
-		_weekday = 2
-	} else if weekday == "Wednesday" {
-		_weekday = 3
-	} else if weekday == "Thursday" {
-		_weekday = 4
-	} else if weekday == "Friday" {
-		_weekday = 5
-	} else if weekday == "Saturday" {
-		_weekday = 6
-	}
-	return _weekday
+    _weekday := 0
+    if weekday == "Sunday" {
+        _weekday = 7
+    } else if weekday == "Monday" {
+        _weekday = 1
+    } else if weekday == "Tuesday" {
+        _weekday = 2
+    } else if weekday == "Wednesday" {
+        _weekday = 3
+    } else if weekday == "Thursday" {
+        _weekday = 4
+    } else if weekday == "Friday" {
+        _weekday = 5
+    } else if weekday == "Saturday" {
+        _weekday = 6
+    }
+    return _weekday
 }
 
 //map转结构体
 func JsonUnmarshal(m interface{}, s interface{}) interface{} {
-	var b []byte
-	if v, ok := m.(string); ok {
-		b = []byte(v)
-	} else if v, ok := m.([]byte); ok {
-		b = v
-	} else {
-		b, _ = json.Marshal(m)
-	}
-	json.Unmarshal(b, &s)
-	return s
+    var b []byte
+    if v, ok := m.(string); ok {
+        b = []byte(v)
+    } else if v, ok := m.([]byte); ok {
+        b = v
+    } else {
+        b, _ = json.Marshal(m)
+    }
+    json.Unmarshal(b, &s)
+    return s
 }

+ 223 - 237
src/jfw/modules/subscribepay/src/entity/areaPack.go

@@ -1,272 +1,258 @@
 package entity
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"time"
+    "encoding/json"
+    "fmt"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 var AreaPackPrice areaPackPrice
 
 // 价格表
 type areaPackPrice struct {
-	Month struct {
-		OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-		AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-	} `json:"month"`
-	Quarter struct {
-		OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-		AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-	} `json:"quarter"`
-	Year struct {
-		OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
-		AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
-	} `json:"year"`
-	ProvinceMaxCount  int `json:"provinceMaxCount"`  //所有地区中省份可计价最大数量
-	ProvinceFreeCount int `json:"provinceFreeCount"` //免费省份数量
+    Month struct {
+        OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+        AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+    } `json:"month"`
+    Quarter struct {
+        OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+        AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+    } `json:"quarter"`
+    Year struct {
+        OneProvince_allBuyerClass int `json:"oneProvince_allBuyerClass"` //一个省份全部行业
+        AllProvince_allBuyerClass int `json:"allProvince_allBuyerClass"` //全国全行业
+    } `json:"year"`
+    ProvinceMaxCount  int `json:"provinceMaxCount"`  //所有地区中省份可计价最大数量
+    ProvinceFreeCount int `json:"provinceFreeCount"` //免费省份数量
 }
 
 func init() {
-	qutil.ReadConfig("./areaPack.json", &AreaPackPrice)
+    qutil.ReadConfig("./areaPack.json", &AreaPackPrice)
 }
 
 type AreaPackFilter struct {
-	Area          *map[string]interface{} `json:"area"`                     //购买的省份
-	Num           int                     `json:"num"`                      //购买的省份数量
-	OrderType     int                     `json:"ordertype"`                //订单类型 1购买 2升级 3续费
-	Cycleunit     int                     `json:"cycleunit"`                //日期单位 1月 2季 3年
-	OldNum        int                     `json:"OldNum,omitempty"`         //升级前购买的省份
-	GiveCycle     int                     `json:"give_cycle,omitempty"`     //赠送周期
-	OriginalPrice int                     `json:"original_price,omitempty"` //活动原价价格
-	GiveType      int                     `json:"give_type,omitempty"`      //赠送周期 类型 1天 2月
-	DisCountId    int                     `json:"discountId,omitempty"`     //赠送的id
-	Badge         string                  `json:"badge,omitempty"`          //活动标识
-	Source        string                  `json:"source,omitempty"`         //订单来源
+    Area          *map[string]interface{} `json:"area"`                     //购买的省份
+    Num           int                     `json:"num"`                      //购买的省份数量
+    OrderType     int                     `json:"ordertype"`                //订单类型 1购买 2升级 3续费
+    Cycleunit     int                     `json:"cycleunit"`                //日期单位 1月 2季 3年
+    OldNum        int                     `json:"OldNum,omitempty"`         //升级前购买的省份
+    GiveCycle     int                     `json:"give_cycle,omitempty"`     //赠送周期
+    OriginalPrice int                     `json:"original_price,omitempty"` //活动原价价格
+    GiveType      int                     `json:"give_type,omitempty"`      //赠送周期 类型 1天 2月
+    DisCountId    int                     `json:"discountId,omitempty"`     //赠送的id
+    Badge         string                  `json:"badge,omitempty"`          //活动标识
+    Source        string                  `json:"source,omitempty"`         //订单来源
 }
 
 /*
 获取价格
 */
 func (this *AreaPackFilter) Price() int {
-	switch this.Cycleunit {
-	case 1: //月
-		if this.Num == -1 {
-			return AreaPackPrice.Month.AllProvince_allBuyerClass
-		} else {
-			return AreaPackPrice.Month.OneProvince_allBuyerClass * this.Num
-		}
-	case 2: //季
-		if this.Num == -1 {
-			return AreaPackPrice.Quarter.AllProvince_allBuyerClass
-		} else {
-			return AreaPackPrice.Quarter.OneProvince_allBuyerClass * this.Num
-		}
-	case 3: //年
-		if this.Num == -1 {
-			return AreaPackPrice.Year.AllProvince_allBuyerClass
-		} else {
-			return AreaPackPrice.Year.OneProvince_allBuyerClass * this.Num
-		}
-	}
-	return -1
+    switch this.Cycleunit {
+    case 1: //月
+        if this.Num == -1 {
+            return AreaPackPrice.Month.AllProvince_allBuyerClass
+        } else {
+            return AreaPackPrice.Month.OneProvince_allBuyerClass * this.Num
+        }
+    case 2: //季
+        if this.Num == -1 {
+            return AreaPackPrice.Quarter.AllProvince_allBuyerClass
+        } else {
+            return AreaPackPrice.Quarter.OneProvince_allBuyerClass * this.Num
+        }
+    case 3: //年
+        if this.Num == -1 {
+            return AreaPackPrice.Year.AllProvince_allBuyerClass
+        } else {
+            return AreaPackPrice.Year.OneProvince_allBuyerClass * this.Num
+        }
+    }
+    return -1
 }
 
 func (this *AreaPackFilter) UpgradePrice(userId string, positionType, entId, entUserId int64) int {
-	beforePrice, newPrice := 0, 0
-	data := util.Compatible.Select(userId, `{"o_vipjy"}`)
-	if data != nil && len(*data) > 0 {
-		ojy := qutil.ObjToMap((*data)["o_jy"])
-		o_buyset_p := qutil.ObjToMap((*ojy)["o_buyset_p"])
-		count := qutil.IntAllDef((*o_buyset_p)["areacount"], 0)
-		if (*ojy)["l_areaEnd_p"] != nil {
-			//获取剩余周期
-			yearNum, monthNum := util.GetDateSub(time.Now().Unix(), qutil.Int64All((*ojy)["l_areaEnd_p"]))
-			// //计算差价
-			if monthNum != 0 {
-				old := AreaPackFilter{
-					Cycleunit: 1,
-					Num:       count,
-				}
-				new := AreaPackFilter{
-					Cycleunit: 1,
-					Num:       this.Num,
-				}
-				beforePrice += old.Price() * monthNum
-				newPrice += new.Price() * monthNum
-			}
-			if yearNum != 0 {
-				old := AreaPackFilter{
-					Cycleunit: 3,
-					Num:       count,
-				}
-				new := AreaPackFilter{
-					Cycleunit: 3,
-					Num:       this.Num,
-				}
-				beforePrice += old.Price() * yearNum
-				newPrice += new.Price() * yearNum
-			}
-		}
-		return newPrice - beforePrice
-	}
-	return -1
+    beforePrice, newPrice := 0, 0
+    data := util.Compatible.Select(userId, `{"o_vipjy"}`)
+    if data != nil && len(*data) > 0 {
+        ojy := qutil.ObjToMap((*data)["o_jy"])
+        o_buyset_p := qutil.ObjToMap((*ojy)["o_buyset_p"])
+        count := qutil.IntAllDef((*o_buyset_p)["areacount"], 0)
+        if (*ojy)["l_areaEnd_p"] != nil {
+            //获取剩余周期
+            yearNum, monthNum := util.GetDateSub(time.Now().Unix(), qutil.Int64All((*ojy)["l_areaEnd_p"]))
+            // //计算差价
+            if monthNum != 0 {
+                old := AreaPackFilter{
+                    Cycleunit: 1,
+                    Num:       count,
+                }
+                new := AreaPackFilter{
+                    Cycleunit: 1,
+                    Num:       this.Num,
+                }
+                beforePrice += old.Price() * monthNum
+                newPrice += new.Price() * monthNum
+            }
+            if yearNum != 0 {
+                old := AreaPackFilter{
+                    Cycleunit: 3,
+                    Num:       count,
+                }
+                new := AreaPackFilter{
+                    Cycleunit: 3,
+                    Num:       this.Num,
+                }
+                beforePrice += old.Price() * yearNum
+                newPrice += new.Price() * yearNum
+            }
+        }
+        return newPrice - beforePrice
+    }
+    return -1
 }
 
 // PayCallBack 支付完成回调
 func (this *areaPackPrice) PayCallBack(param *CallBackParam) bool {
-	orderData := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(map[string]interface{}{"product_type": "省份订阅包"}),
-		"user_phone,ent_id,id,order_status,order_code,filter,user_id,d_relation_id,dis_word,order_money,vip_starttime,vip_endtime", "")
-	if orderData != nil {
-		userId := qutil.ObjToString((*orderData)["user_id"])
-		now := time.Now()
-		payTime := FormatDate(&now, Date_Full_Layout)
-		updateMap := map[string]interface{}{
-			"pay_money":    param.CashFee,
-			"pay_time":     payTime,
-			"order_status": 1,
-			//支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
-			"out_trade_no": param.OutTradeno,
-		}
-		if order_status := qutil.IntAll((*orderData)["order_status"]); order_status == 0 {
-			st := qutil.ObjToString((*orderData)["vip_starttime"])
-			et := qutil.ObjToString((*orderData)["vip_endtime"])
-			filter := qutil.ObjToString((*orderData)["filter"])
-			areaPack := new(AreaPackFilter)
-			if err := json.Unmarshal([]byte(filter), &areaPack); err != nil {
-				log.Printf("获取用户%s已购买省份订阅包内容异常:%v", userId, err)
-				return false
-			}
-			//计算周期
-			if areaPack.OrderType == 1 { //新订单 计算开始时间 结束时间
-				endTime := util.GetDATE(areaPack.ForGetDATE(), 1, now.Unix()) //该方法  1:年 2:月 4:季度 需要转化
-				if areaPack.GiveType == 1 {
-					endTime = endTime.AddDate(0, 0, areaPack.GiveCycle)
-				} else if areaPack.GiveType == 2 {
-					endTime = endTime.AddDate(0, areaPack.GiveCycle, 0)
-				}
-				updateMap["vip_starttime"] = FormatDate(&now, Date_Full_Layout)
-				updateMap["vip_endtime"] = FormatDate(&endTime, Date_Full_Layout)
-				st = FormatDate(&now, Date_Full_Layout)
-				et = FormatDate(&endTime, Date_Full_Layout)
-			}
-			update := util.Mysql.Update("dataexport_order", map[string]interface{}{
-				"id": (*orderData)["id"],
-			}, updateMap)
-			if !update {
-				log.Printf("用户%s更新省份订阅包订单状态出错:%v", userId, (*orderData)["order_code"])
-				return false
-			}
-			go PayCancel(userId, "省份订阅包", "")
-			//修改权益
-			start, _ := time.ParseInLocation(Date_Full_Layout, st, time.Local)
-			end, _ := time.ParseInLocation(Date_Full_Layout, et, time.Local)
-			entId := qutil.Int64All((*orderData)["ent_id"])
-			positionType := int64(1)
-			entUserId := int64(0)
-			//企业类型
-			user_phone := qutil.IntAll((*orderData)["user_phone"])
-			//查找entUserId
-			entniche_user := util.Mysql.FindOne("entniche_user", map[string]interface{}{
-				"phone":  user_phone,
-				"ent_id": entId,
-			}, "id", "")
-			if entniche_user != nil {
-				entUserId = qutil.Int64All((*entniche_user)["id"])
-			}
-			if !areaPack.Power(userId, start, end, positionType, entId, entUserId) {
-				log.Printf("用户%s更新省份订阅包用户状态出错:%v", userId, areaPack)
-				return false
-			}
-			//卡卷使用
-			userLotteryId := qutil.ObjToString((*orderData)["d_relation_id"])
-			order_code := qutil.ObjToString((*orderData)["order_code"])
-			if userLotteryId != "" {
-				go func(userId, userLotteryId, order_code string) {
-					phone, name := util.GetMyPhoneAndName(userId)
-					if !util.UpdateCouponState(userId, userLotteryId, name, phone, order_code, "省份订阅包", "0", 1, 0) {
-						log.Println(fmt.Sprintf("单号%s-消费失败-卡卷%s", order_code, userLotteryId))
-					}
-				}(userId, userLotteryId, order_code)
-			}
-			return true
-		} else {
-			return true
-		}
-	}
-	return false
+    orderData := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(map[string]interface{}{"product_type": "省份订阅包"}),
+        "user_phone,ent_id,id,order_status,order_code,filter,user_id,d_relation_id,dis_word,order_money,vip_starttime,vip_endtime", "")
+    if orderData != nil {
+        userId := qutil.ObjToString((*orderData)["user_id"])
+        now := time.Now()
+        payTime := FormatDate(&now, Date_Full_Layout)
+        updateMap := map[string]interface{}{
+            "pay_money":    param.CashFee,
+            "pay_time":     payTime,
+            "order_status": 1,
+            //支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
+            "out_trade_no": param.OutTradeno,
+        }
+        if order_status := qutil.IntAll((*orderData)["order_status"]); order_status == 0 {
+            st := qutil.ObjToString((*orderData)["vip_starttime"])
+            et := qutil.ObjToString((*orderData)["vip_endtime"])
+            filter := qutil.ObjToString((*orderData)["filter"])
+            areaPack := new(AreaPackFilter)
+            if err := json.Unmarshal([]byte(filter), &areaPack); err != nil {
+                log.Printf("获取用户%s已购买省份订阅包内容异常:%v", userId, err)
+                return false
+            }
+            //计算周期
+            if areaPack.OrderType == 1 { //新订单 计算开始时间 结束时间
+                endTime := util.GetDATE(areaPack.ForGetDATE(), 1, now.Unix()) //该方法  1:年 2:月 4:季度 需要转化
+                if areaPack.GiveType == 1 {
+                    endTime = endTime.AddDate(0, 0, areaPack.GiveCycle)
+                } else if areaPack.GiveType == 2 {
+                    endTime = endTime.AddDate(0, areaPack.GiveCycle, 0)
+                }
+                updateMap["vip_starttime"] = FormatDate(&now, Date_Full_Layout)
+                updateMap["vip_endtime"] = FormatDate(&endTime, Date_Full_Layout)
+                st = FormatDate(&now, Date_Full_Layout)
+                et = FormatDate(&endTime, Date_Full_Layout)
+            }
+            update := util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "id": (*orderData)["id"],
+            }, updateMap)
+            if !update {
+                log.Printf("用户%s更新省份订阅包订单状态出错:%v", userId, (*orderData)["order_code"])
+                return false
+            }
+            go PayCancel(userId, "省份订阅包", "")
+            //修改权益
+            start, _ := time.ParseInLocation(Date_Full_Layout, st, time.Local)
+            end, _ := time.ParseInLocation(Date_Full_Layout, et, time.Local)
+            entId := qutil.Int64All((*orderData)["ent_id"])
+            positionType := int64(1)
+            entUserId := int64(0)
+            //企业类型
+            user_phone := qutil.IntAll((*orderData)["user_phone"])
+            //查找entUserId
+            entniche_user := util.Mysql.FindOne("entniche_user", map[string]interface{}{
+                "phone":  user_phone,
+                "ent_id": entId,
+            }, "id", "")
+            if entniche_user != nil {
+                entUserId = qutil.Int64All((*entniche_user)["id"])
+            }
+            if !areaPack.Power(userId, start, end, positionType, entId, entUserId) {
+                log.Printf("用户%s更新省份订阅包用户状态出错:%v", userId, areaPack)
+                return false
+            }
+            //卡卷使用
+            userLotteryId := qutil.ObjToString((*orderData)["d_relation_id"])
+            order_code := qutil.ObjToString((*orderData)["order_code"])
+            if userLotteryId != "" {
+                go func(userId, userLotteryId, order_code string) {
+                    phone, name := util.GetMyPhoneAndName(userId)
+                    if !util.UpdateCouponState(userId, userLotteryId, name, phone, order_code, "省份订阅包", "0", 1, 0) {
+                        log.Println(fmt.Sprintf("单号%s-消费失败-卡卷%s", order_code, userLotteryId))
+                    }
+                }(userId, userLotteryId, order_code)
+            }
+            return true
+        } else {
+            return true
+        }
+    }
+    return false
 }
 
 // 修改用户权益
 func (this *AreaPackFilter) Power(userid string, startime, endtime time.Time, positionType, entId, entUserId int64) bool {
-	ok := false
-	o_jy := "o_jy"
-	if positionType == 1 {
-		o_jy = "o_entniche"
-	}
-	setMap := map[string]interface{}{
-		fmt.Sprintf("%s.o_buyset_p", o_jy):  map[string]interface{}{"areacount": this.Num},
-		fmt.Sprintf("%s.l_areaEnd_p", o_jy): endtime.Unix(),
-		fmt.Sprintf("%s.i_ppstatus", o_jy):  1,
-		fmt.Sprintf("%s.i_newfree", o_jy):   1, //新免费用户=>新订阅设置页面 20211122
-	}
-	if this.OrderType == 1 || this.OrderType == 2 {
-		setMap[fmt.Sprintf("%s.l_areaStart_p", o_jy)] = startime.Unix()
-		setMap[fmt.Sprintf("%s.o_area_p", o_jy)] = this.Area
-	}
-	if positionType == 0 {
-		ok = util.MQFW.UpdateById("user", userid, map[string]interface{}{
-			"$set": setMap,
-		})
-	} else {
-		query := map[string]interface{}{
-			"i_userid": entUserId,
-			"i_entid":  entId,
-			"i_type":   2,
-		}
-		ok = util.MQFW.Update("entniche_rule", query, map[string]interface{}{
-			"$set": setMap,
-		}, true, false)
-	}
-	if ok {
-		{
-			//清除 用户权限缓存
-			jy.ClearBigVipUserPower(userid)
-			return true
-		}
-	}
-	return false
+    ok := false
+    o_jy := "o_jy"
+    setMap := map[string]interface{}{
+        fmt.Sprintf("%s.o_buyset_p", o_jy):  map[string]interface{}{"areacount": this.Num},
+        fmt.Sprintf("%s.l_areaEnd_p", o_jy): endtime.Unix(),
+        fmt.Sprintf("%s.i_ppstatus", o_jy):  1,
+        fmt.Sprintf("%s.i_newfree", o_jy):   1, //新免费用户=>新订阅设置页面 20211122
+    }
+    if this.OrderType == 1 || this.OrderType == 2 {
+        setMap[fmt.Sprintf("%s.l_areaStart_p", o_jy)] = startime.Unix()
+        setMap[fmt.Sprintf("%s.o_area_p", o_jy)] = this.Area
+    }
+    ok = util.Compatible.Update(userid, map[string]interface{}{
+        "$set": setMap,
+    })
+    if ok {
+        {
+            //清除 用户权限缓存
+            jy.ClearBigVipUserPower(userid)
+            return true
+        }
+    }
+    return false
 }
 
 // 获取产品id
 func (this *AreaPackFilter) ProductId() string {
-	switch this.Cycleunit {
-	case 1:
-		return "省份订阅包1个月"
-	case 2:
-		return "省份订阅包3个月"
-	case 3:
-		return "省份订阅包12个月"
-	} //1月 2季 3年
-	return "省份订阅包"
+    switch this.Cycleunit {
+    case 1:
+        return "省份订阅包1个月"
+    case 2:
+        return "省份订阅包3个月"
+    case 3:
+        return "省份订阅包12个月"
+    } //1月 2季 3年
+    return "省份订阅包"
 }
 
 // 月份转化 1月 2季 3年
 func (this *AreaPackFilter) ToMonth() int {
-	switch this.Cycleunit {
-	case 1:
-		return 1
-	case 2:
-		return 3
-	case 3:
-		return 12
-	}
-	return -1
+    switch this.Cycleunit {
+    case 1:
+        return 1
+    case 2:
+        return 3
+    case 3:
+        return 12
+    }
+    return -1
 }
 
 /*
@@ -275,13 +261,13 @@ getDate方法的参数1:年 2:月 4:季度
 i:日期单位 1月 2季 3年
 */
 func (this *AreaPackFilter) ForGetDATE() int {
-	switch this.Cycleunit {
-	case 1:
-		return 2
-	case 2:
-		return 4
-	case 3:
-		return 1
-	}
-	return this.Cycleunit
+    switch this.Cycleunit {
+    case 1:
+        return 2
+    case 2:
+        return 4
+    case 3:
+        return 1
+    }
+    return this.Cycleunit
 }

+ 88 - 88
src/jfw/modules/subscribepay/src/entity/bidfile.go

@@ -1,15 +1,15 @@
 package entity
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"time"
+    "encoding/json"
+    "fmt"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 type bidfile struct{}
@@ -19,95 +19,95 @@ var bidfileServiceId = 11
 
 // 招标文件解读支付完成回调方法
 func (b *bidfile) PayCallBack(param *CallBackParam) bool {
-	orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,filter,order_status,user_id,product_type", "")
-	if orderdata == nil {
-		return false
-	}
-	userId := qutil.ObjToString((*orderdata)["user_id"])
-	if qutil.IntAll((*orderdata)["order_status"]) == 0 {
-		now := time.Now()
-		nowFormat := FormatDate(&now, Date_Full_Layout)
-		product_type := qutil.ObjToString((*orderdata)["product_type"])
-		var filter map[string]interface{}
-		if err := json.Unmarshal([]byte(qutil.ObjToString((*orderdata)["filter"])), &filter); err != nil {
-			log.Println("招标文件解读支付成功json.Unmarshal出错", err)
-		} else {
-			count := qutil.IntAll(filter["count"])
-			endtime := qutil.ObjToString(filter["effective_date"])
-			isBig, _ := qutil.If(product_type == "大会员-招标文件解读", true, false).(bool)
-			//更新招标文件解读次数
-			if !UpdateCount(count, userId, endtime, isBig) {
-				log.Println("更新招标解读文件次数失败,", orderdata)
-			}
-			//
-			update := util.Mysql.Update("dataexport_order", map[string]interface{}{
-				"id": (*orderdata)["id"],
-			}, map[string]interface{}{
-				"pay_money":    param.CashFee,
-				"pay_time":     nowFormat,
-				"order_status": 1,
-				//支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
-				"out_trade_no": param.OutTradeno,
-			})
-			if update {
-				//取消其他订单
-				go PayCancel(userId, "招标文件解读", "")
-				go PayCancel(userId, "大会员-招标文件解读", "")
-			}
-		}
-	}
-	return true
+    orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,filter,order_status,user_id,product_type", "")
+    if orderdata == nil {
+        return false
+    }
+    userId := qutil.ObjToString((*orderdata)["user_id"])
+    if qutil.IntAll((*orderdata)["order_status"]) == 0 {
+        now := time.Now()
+        nowFormat := FormatDate(&now, Date_Full_Layout)
+        product_type := qutil.ObjToString((*orderdata)["product_type"])
+        var filter map[string]interface{}
+        if err := json.Unmarshal([]byte(qutil.ObjToString((*orderdata)["filter"])), &filter); err != nil {
+            log.Println("招标文件解读支付成功json.Unmarshal出错", err)
+        } else {
+            count := qutil.IntAll(filter["count"])
+            endtime := qutil.ObjToString(filter["effective_date"])
+            isBig, _ := qutil.If(product_type == "大会员-招标文件解读", true, false).(bool)
+            //更新招标文件解读次数
+            if !UpdateCount(count, userId, endtime, isBig) {
+                log.Println("更新招标解读文件次数失败,", orderdata)
+            }
+            //
+            update := util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "id": (*orderdata)["id"],
+            }, map[string]interface{}{
+                "pay_money":    param.CashFee,
+                "pay_time":     nowFormat,
+                "order_status": 1,
+                //支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
+                "out_trade_no": param.OutTradeno,
+            })
+            if update {
+                //取消其他订单
+                go PayCancel(userId, "招标文件解读", "")
+                go PayCancel(userId, "大会员-招标文件解读", "")
+            }
+        }
+    }
+    return true
 }
 
 // count 使用次数, isBig是否是大会员订单
 func UpdateCount(count int, userId, endtime string, isBig bool) bool {
-	now := time.Now()
-	nowFormat := FormatDate(&now, Date_Full_Layout)
-	if !isBig {
-		return util.MQFW.UpdateById("user", userId, map[string]interface{}{
-			"$inc": map[string]interface{}{
-				"i_bidfileCount": count,
-			},
-		})
-	} else {
-		dt := fmt.Sprintf("%s23:59:59", endtime)
-		l_endtime := GetTime("2006年01月02日15:04:05", dt).Format(Date_Full_Layout)
-		servcieInfos := util.Mysql.SelectBySql(`SELECT * FROM `+jy.BigmemberUserPowerTable+` a WHERE a.s_userid = ? AND a.i_status = 0 AND a.s_serviceid = ?;`, userId, bidfileServiceId)
-		if len(*servcieInfos) <= 0 {
-			util.Mysql.InsertBySql(`INSERT INTO bigmember_service_user
+    now := time.Now()
+    nowFormat := FormatDate(&now, Date_Full_Layout)
+    if !isBig {
+        return util.Compatible.Update(userId, map[string]interface{}{
+            "$inc": map[string]interface{}{
+                "i_bidfileCount": count,
+            },
+        })
+    } else {
+        dt := fmt.Sprintf("%s23:59:59", endtime)
+        l_endtime := GetTime("2006年01月02日15:04:05", dt).Format(Date_Full_Layout)
+        servcieInfos := util.Mysql.SelectBySql(`SELECT * FROM `+jy.BigmemberUserPowerTable+` a WHERE a.s_userid = ? AND a.i_status = 0 AND a.s_serviceid = ?;`, userId, bidfileServiceId)
+        if len(*servcieInfos) <= 0 {
+            util.Mysql.InsertBySql(`INSERT INTO bigmember_service_user
 					  (s_userid,s_serviceid,i_frequency,l_starttime,l_endtime,i_status,l_createtime,l_updatetime)
                        VALUES
                        (?,?,?,?,?,?,?,?);`, userId, 11, 0, nowFormat, l_endtime, 0, nowFormat, nowFormat)
-			servcieInfos = util.Mysql.SelectBySql(`SELECT * FROM `+jy.BigmemberUserPowerTable+` a WHERE a.s_userid = ? AND a.i_status = 0 AND a.s_serviceid = ?;`, userId, bidfileServiceId)
-		}
-		if util.Mysql.UpdateOrDeleteBySql(`UPDATE `+jy.BigmemberUserPowerTable+` SET
+            servcieInfos = util.Mysql.SelectBySql(`SELECT * FROM `+jy.BigmemberUserPowerTable+` a WHERE a.s_userid = ? AND a.i_status = 0 AND a.s_serviceid = ?;`, userId, bidfileServiceId)
+        }
+        if util.Mysql.UpdateOrDeleteBySql(`UPDATE `+jy.BigmemberUserPowerTable+` SET
 	 i_frequency=i_frequency+?,l_updatetime=? WHERE s_userid = ? and s_serviceid = ?`, count, nowFormat, userId, bidfileServiceId) < 0 {
-			log.Println("大会员补充包-招标文件解读更新出错:userid:", userId, " count:", count)
-		}
-		if len(*servcieInfos) > 0 {
-			servcieInfo := (*servcieInfos)[0]
-			i_frequency := qutil.IntAll(servcieInfo["i_frequency"])
-			insert := map[string]interface{}{
-				"s_userid":             userId,
-				"s_serviceid":          bidfileServiceId,
-				"l_updatetime_before":  servcieInfo["l_endtime"],
-				"l_updatetime_after":   servcieInfo["l_endtime"],
-				"i_updatecount_before": i_frequency - count,
-				"i_updatecount_after":  i_frequency,
-				"l_createtime":         NowFormat(Date_Full_Layout),
-			}
-			order_id := util.Mysql.Insert("bigmember_recharge", insert)
-			if order_id == 0 {
-				log.Println("招标文件解读-充值记录保存出错:", userId, "---", bidfileServiceId)
-			}
-		} else {
-			log.Println("未查询到此"+userId+"服务id:", bidfileServiceId)
-		}
-		return true
-	}
+            log.Println("大会员补充包-招标文件解读更新出错:userid:", userId, " count:", count)
+        }
+        if len(*servcieInfos) > 0 {
+            servcieInfo := (*servcieInfos)[0]
+            i_frequency := qutil.IntAll(servcieInfo["i_frequency"])
+            insert := map[string]interface{}{
+                "s_userid":             userId,
+                "s_serviceid":          bidfileServiceId,
+                "l_updatetime_before":  servcieInfo["l_endtime"],
+                "l_updatetime_after":   servcieInfo["l_endtime"],
+                "i_updatecount_before": i_frequency - count,
+                "i_updatecount_after":  i_frequency,
+                "l_createtime":         NowFormat(Date_Full_Layout),
+            }
+            order_id := util.Mysql.Insert("bigmember_recharge", insert)
+            if order_id == 0 {
+                log.Println("招标文件解读-充值记录保存出错:", userId, "---", bidfileServiceId)
+            }
+        } else {
+            log.Println("未查询到此"+userId+"服务id:", bidfileServiceId)
+        }
+        return true
+    }
 }
 
 func GetTime(layout, t string) time.Time {
-	times, _ := time.ParseInLocation(layout, t, time.Local)
-	return times
+    times, _ := time.ParseInLocation(layout, t, time.Local)
+    return times
 }

+ 539 - 539
src/jfw/modules/subscribepay/src/entity/dataExportPackStruct.go

@@ -1,26 +1,26 @@
 package entity
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"strings"
-	"sync"
-	"time"
-
-	"app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/middleGround"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "encoding/json"
+    "fmt"
+    "jy/src/jfw/modules/subscribepay/src/config"
+    "jy/src/jfw/modules/subscribepay/src/pay"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "strings"
+    "sync"
+    "time"
+
+    "app.yhyue.com/moapp/jybase/api"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/encrypt"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/middleGround"
+
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
 )
 
 // 剑鱼数据流量包
@@ -29,614 +29,614 @@ type dataExportPackStruct struct{}
 var JyDataExportPack dataExportPackStruct
 
 type PackDetail struct {
-	PackType      int    `json:"pType"`                    //数据包类型 1标准,2高级
-	PackNum       int    `json:"pNum"`                     //数据包数量
-	ValidYear     int    `json:"validYear"`                //有效年份 「账户合并过来的资源为-1」
-	Price         int    `json:"price"`                    //数据包价格 「账户合并过来的资源为-1」
-	GiveCycle     int    `json:"give_cycle,omitempty"`     //赠送条数
-	OriginalPrice int    `json:"original_price,omitempty"` //双十一活动原价价格
-	DisCountId    int    `json:"discountId,omitempty"`     //赠送的id
-	Badge         string `json:"badge,omitempty"`          //活动标识
-	Source        string `json:"source,omitempty"`         //来源
+    PackType      int    `json:"pType"`                    //数据包类型 1标准,2高级
+    PackNum       int    `json:"pNum"`                     //数据包数量
+    ValidYear     int    `json:"validYear"`                //有效年份 「账户合并过来的资源为-1」
+    Price         int    `json:"price"`                    //数据包价格 「账户合并过来的资源为-1」
+    GiveCycle     int    `json:"give_cycle,omitempty"`     //赠送条数
+    OriginalPrice int    `json:"original_price,omitempty"` //双十一活动原价价格
+    DisCountId    int    `json:"discountId,omitempty"`     //赠送的id
+    Badge         string `json:"badge,omitempty"`          //活动标识
+    Source        string `json:"source,omitempty"`         //来源
 }
 type PackDetailReturn struct { //因账户合并,中台返回的字段会有差异
-	*PackDetail
-	EndTime int64 `json:"endTime"` //仅通过账户合并后的有此字段
+    *PackDetail
+    EndTime int64 `json:"endTime"` //仅通过账户合并后的有此字段
 }
 
 var packPriceMap map[string]*PackDetail
 
 func init() {
-	packPriceMap = make(map[string]*PackDetail)
-	for _, pack := range config.ExConf.Packs_showList {
-		packPriceMap[fmt.Sprintf("%s_%d", "normal", pack.PackNum)] = &PackDetail{
-			PackType:  1,
-			PackNum:   pack.PackNum,
-			ValidYear: 2, //默认全为两年
-			Price:     int(config.ExConf.UnitPrice_normal*config.ExConf.Discount*pack.Normal_discount*100) * pack.PackNum,
-		}
-		packPriceMap[fmt.Sprintf("%s_%d", "senior", pack.PackNum)] = &PackDetail{
-			PackType:  2,
-			PackNum:   pack.PackNum,
-			ValidYear: 2, //默认全为两年
-			Price:     int(config.ExConf.UnitPrice_senior*config.ExConf.Discount*pack.Senior_discount*100) * pack.PackNum,
-		}
-	}
+    packPriceMap = make(map[string]*PackDetail)
+    for _, pack := range config.ExConf.Packs_showList {
+        packPriceMap[fmt.Sprintf("%s_%d", "normal", pack.PackNum)] = &PackDetail{
+            PackType:  1,
+            PackNum:   pack.PackNum,
+            ValidYear: 2, //默认全为两年
+            Price:     int(config.ExConf.UnitPrice_normal*config.ExConf.Discount*pack.Normal_discount*100) * pack.PackNum,
+        }
+        packPriceMap[fmt.Sprintf("%s_%d", "senior", pack.PackNum)] = &PackDetail{
+            PackType:  2,
+            PackNum:   pack.PackNum,
+            ValidYear: 2, //默认全为两年
+            Price:     int(config.ExConf.UnitPrice_senior*config.ExConf.Discount*pack.Senior_discount*100) * pack.PackNum,
+        }
+    }
 }
 
 // PayCallBack 支付完成回调
 func (this *dataExportPackStruct) PayCallBack(param *CallBackParam) bool {
-	orderData := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(map[string]interface{}{"product_type": "数据流量包"}),
-		"id,order_status,order_code,filter,user_id,d_relation_id,dis_word,order_money", "")
-	if orderData != nil {
-		now := time.Now()
-		if order_status := qutil.IntAll((*orderData)["order_status"]); order_status == 0 {
-			payTime := FormatDate(&now, Date_Full_Layout)
-			update := util.Mysql.Update("dataexport_order", map[string]interface{}{
-				"id": (*orderData)["id"],
-			}, map[string]interface{}{
-				"pay_money":    param.CashFee,
-				"pay_time":     payTime,
-				"order_status": 1,
-				//支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
-				"out_trade_no": param.OutTradeno,
-			})
-			if update {
-				filter := qutil.ObjToString((*orderData)["filter"])
-				orderCode := qutil.ObjToString((*orderData)["order_code"])
-				userId := qutil.ObjToString((*orderData)["user_id"])
-				packDetail := new(PackDetail)
-				if err := json.Unmarshal([]byte(filter), &packDetail); err != nil {
-					log.Printf("获取用户%s已购买数据包内容异常:%v", userId, err)
-					return false
-				}
-				if packDetail.GiveCycle > 0 { //赠品
-					packDetail.PackNum += packDetail.GiveCycle
-				}
-				//卡卷使用
-				userLotteryId := qutil.ObjToString((*orderData)["d_relation_id"])
-				if userLotteryId != "" {
-					go func(userId, userLotteryId, order_code string) {
-						phone, name := util.GetMyPhoneAndName(userId)
-						if !util.UpdateCouponState(userId, userLotteryId, name, phone, order_code, "数据流量包", "", 1, 0) {
-							log.Println(fmt.Sprintf("单号 %s-消费失败-卡卷%s", order_code, userLotteryId))
-						}
-					}(userId, userLotteryId, orderCode)
-				}
-				//调用中台 增加数据包
-				entTime := time.Now().AddDate(2, 0, 0) //有效期
-
-				if _, err := perRechargePack(userId, entTime.Format(Date_Short_Layout), packDetail); err != nil {
-					log.Println(fmt.Sprintf("%s 资源账户更改异常 %v", userId, err))
-					return false
-				}
-				dis_word := qutil.ObjToString((*orderData)["dis_word"])
-				//userId := qutil.ObjToString((*orderData)["user_id"])
-				if dis_word != "" {
-					/*	//分销系统 分销记录
-						go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "超级订阅", dis_word)*/
-					//分销系统 分销记录
-					suffix := dis_word[len(dis_word)-3:]
-					if suffix == suffix_msgt {
-						//go OtherDisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "超级订阅", dis_word, qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["create_time"]))
-					} else if suffix == "_GX" {
-						go DisWordRecode(qutil.IntAll((*orderData)["id"]), qutil.IntAll((*orderData)["order_money"]), "数据流量包", dis_word, userId)
-					} else {
-						//go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "超级订阅", dis_word)
-					}
-				}
-				return true
-			}
-		} else {
-			return true
-		}
-	}
-	return false
+    orderData := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(map[string]interface{}{"product_type": "数据流量包"}),
+        "id,order_status,order_code,filter,user_id,d_relation_id,dis_word,order_money", "")
+    if orderData != nil {
+        now := time.Now()
+        if order_status := qutil.IntAll((*orderData)["order_status"]); order_status == 0 {
+            payTime := FormatDate(&now, Date_Full_Layout)
+            update := util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "id": (*orderData)["id"],
+            }, map[string]interface{}{
+                "pay_money":    param.CashFee,
+                "pay_time":     payTime,
+                "order_status": 1,
+                //支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
+                "out_trade_no": param.OutTradeno,
+            })
+            if update {
+                filter := qutil.ObjToString((*orderData)["filter"])
+                orderCode := qutil.ObjToString((*orderData)["order_code"])
+                userId := qutil.ObjToString((*orderData)["user_id"])
+                packDetail := new(PackDetail)
+                if err := json.Unmarshal([]byte(filter), &packDetail); err != nil {
+                    log.Printf("获取用户%s已购买数据包内容异常:%v", userId, err)
+                    return false
+                }
+                if packDetail.GiveCycle > 0 { //赠品
+                    packDetail.PackNum += packDetail.GiveCycle
+                }
+                //卡卷使用
+                userLotteryId := qutil.ObjToString((*orderData)["d_relation_id"])
+                if userLotteryId != "" {
+                    go func(userId, userLotteryId, order_code string) {
+                        phone, name := util.GetMyPhoneAndName(userId)
+                        if !util.UpdateCouponState(userId, userLotteryId, name, phone, order_code, "数据流量包", "", 1, 0) {
+                            log.Println(fmt.Sprintf("单号 %s-消费失败-卡卷%s", order_code, userLotteryId))
+                        }
+                    }(userId, userLotteryId, orderCode)
+                }
+                //调用中台 增加数据包
+                entTime := time.Now().AddDate(2, 0, 0) //有效期
+
+                if _, err := perRechargePack(userId, entTime.Format(Date_Short_Layout), packDetail); err != nil {
+                    log.Println(fmt.Sprintf("%s 资源账户更改异常 %v", userId, err))
+                    return false
+                }
+                dis_word := qutil.ObjToString((*orderData)["dis_word"])
+                //userId := qutil.ObjToString((*orderData)["user_id"])
+                if dis_word != "" {
+                    /*	//分销系统 分销记录
+                    	go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "超级订阅", dis_word)*/
+                    //分销系统 分销记录
+                    suffix := dis_word[len(dis_word)-3:]
+                    if suffix == suffix_msgt {
+                        //go OtherDisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "超级订阅", dis_word, qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["create_time"]))
+                    } else if suffix == "_GX" {
+                        go DisWordRecode(qutil.IntAll((*orderData)["id"]), qutil.IntAll((*orderData)["order_money"]), "数据流量包", dis_word, userId)
+                    } else {
+                        //go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "超级订阅", dis_word)
+                    }
+                }
+                return true
+            }
+        } else {
+            return true
+        }
+    }
+    return false
 }
 
 // GetPackPriceList 获取数据流量包价格
 func (this *dataExportPackStruct) GetPackPriceList() (interface{}, error) {
-	return map[string]interface{}{
-		"unitPrice_normal":   config.ExConf.UnitPrice_normal,
-		"unitPrice_senior":   config.ExConf.UnitPrice_senior,
-		"discount":           config.ExConf.Discount,
-		"packs_validityYear": config.ExConf.Packs_validityYear,
-		"packs_showList":     config.ExConf.Packs_showList,
-	}, nil
+    return map[string]interface{}{
+        "unitPrice_normal":   config.ExConf.UnitPrice_normal,
+        "unitPrice_senior":   config.ExConf.UnitPrice_senior,
+        "discount":           config.ExConf.Discount,
+        "packs_validityYear": config.ExConf.Packs_validityYear,
+        "packs_showList":     config.ExConf.Packs_showList,
+    }, nil
 }
 
 // GetPackDetailById 中台交互-获取单个数据流量包价格
 func (this *dataExportPackStruct) GetPackDetailById(packId string) (*PackDetail, error) {
-	packDetail, ok := packPriceMap[packId]
-	log.Println(packPriceMap)
-	if !ok {
-		return nil, fmt.Errorf("未知规格数据包")
-	}
-	return packDetail, nil
+    packDetail, ok := packPriceMap[packId]
+    log.Println(packPriceMap)
+    if !ok {
+        return nil, fmt.Errorf("未知规格数据包")
+    }
+    return packDetail, nil
 }
 
 // GetAccountMsg 查询账户和企业数据包情况
 func (this *dataExportPackStruct) GetAccountMsg(sess *httpsession.Session, userId string) (map[string]interface{}, error) {
-	//每日限量包
-	packDetail := map[string]interface{}{}
-	vipStatus := jy.GetBigVipUserBaseMsg(sess, *config.Middleground)
-	if vipStatus.Status > 0 && vipStatus.DailyNum > 0 {
-		packetMsg := dataexport.GetDataPacketMsg(vipStatus.GetUseId(), vipStatus.DailyNum)
-		packDetail["dailyPack"] = map[string]interface{}{
-			"limitToday": vipStatus.DailyNum,      //每日限量
-			"usedToday":  packetMsg.GetUsed(true), //已使用
-		}
-	}
-	//个人线上数据包
-	if senior, normal, seniorThirty, normalThirty, err := JyDataExportPack.GetPersonalAccount(userId); err == nil {
-		packDetail["personalPack"] = map[string]interface{}{
-			"seniorTotal":  senior,
-			"normalTotal":  normal,
-			"seniorThirty": seniorThirty,
-			"normalThirty": normalThirty,
-		}
-	}
-
-	//企业数据导出
-	if phone := getAndCacheUserPhone(sess, userId); phone != "" {
-		if entId := qutil.IntAll(sess.Get("entId")); entId != 0 {
-			var entPack []map[string]interface{}
-			var entAllCount int
-			res := util.Mysql.FindOne("entniche_info", map[string]interface{}{"id": entId}, "id,phone,name", "")
-			if res != nil && len(*res) != 0 {
-				entUserId := qutil.IntAll(sess.Get("entUserId"))
-				entName, _ := (*res)["name"].(string)
-				entPhone, _ := (*res)["phone"].(string)
-				if entUserId > 0 && entName != "" && entPhone != "" {
-					entAllCount = getCurrEntCount(entName, entPhone) //查询所属企业及账户余额
-					limit := util.Mysql.FindOne("entniche_export_limit", map[string]interface{}{"ent_id": entId, "user_id": entUserId}, "data_limit,remain_nums,export_nums", "")
-					if limit != nil && len(*limit) > 0 {
-						entPack = append(entPack, map[string]interface{}{
-							"entId":        entId,                                 //企业id
-							"entName":      entName,                               //企业名字
-							"entAllCount":  entAllCount,                           //企业总条数
-							"limitToday":   qutil.IntAll((*limit)["data_limit"]),  //个人今日限额
-							"surplusToday": qutil.IntAll((*limit)["remain_nums"]), //今日剩余
-							"usedToday":    qutil.IntAll((*limit)["export_nums"]), //今日使用
-						})
-					}
-				}
-			}
-			if entPack != nil {
-				packDetail["entPack"] = entPack
-			}
-		}
-	}
-	return packDetail, nil
+    //每日限量包
+    packDetail := map[string]interface{}{}
+    vipStatus := jy.GetBigVipUserBaseMsg(sess, *config.Middleground)
+    if vipStatus.Status > 0 && vipStatus.DailyNum > 0 {
+        packetMsg := dataexport.GetDataPacketMsg(vipStatus.GetUseId(), vipStatus.DailyNum)
+        packDetail["dailyPack"] = map[string]interface{}{
+            "limitToday": vipStatus.DailyNum,      //每日限量
+            "usedToday":  packetMsg.GetUsed(true), //已使用
+        }
+    }
+    //个人线上数据包
+    if senior, normal, seniorThirty, normalThirty, err := JyDataExportPack.GetPersonalAccount(userId); err == nil {
+        packDetail["personalPack"] = map[string]interface{}{
+            "seniorTotal":  senior,
+            "normalTotal":  normal,
+            "seniorThirty": seniorThirty,
+            "normalThirty": normalThirty,
+        }
+    }
+
+    //企业数据导出
+    if phone := getAndCacheUserPhone(sess, userId); phone != "" {
+        if entId := qutil.IntAll(sess.Get("entId")); entId != 0 {
+            var entPack []map[string]interface{}
+            var entAllCount int
+            res := util.Mysql.FindOne("entniche_info", map[string]interface{}{"id": entId}, "id,phone,name", "")
+            if res != nil && len(*res) != 0 {
+                entUserId := qutil.IntAll(sess.Get("entUserId"))
+                entName, _ := (*res)["name"].(string)
+                entPhone, _ := (*res)["phone"].(string)
+                if entUserId > 0 && entName != "" && entPhone != "" {
+                    entAllCount = getCurrEntCount(entName, entPhone) //查询所属企业及账户余额
+                    limit := util.Mysql.FindOne("entniche_export_limit", map[string]interface{}{"ent_id": entId, "user_id": entUserId}, "data_limit,remain_nums,export_nums", "")
+                    if limit != nil && len(*limit) > 0 {
+                        entPack = append(entPack, map[string]interface{}{
+                            "entId":        entId,                                 //企业id
+                            "entName":      entName,                               //企业名字
+                            "entAllCount":  entAllCount,                           //企业总条数
+                            "limitToday":   qutil.IntAll((*limit)["data_limit"]),  //个人今日限额
+                            "surplusToday": qutil.IntAll((*limit)["remain_nums"]), //今日剩余
+                            "usedToday":    qutil.IntAll((*limit)["export_nums"]), //今日使用
+                        })
+                    }
+                }
+            }
+            if entPack != nil {
+                packDetail["entPack"] = entPack
+            }
+        }
+    }
+    return packDetail, nil
 }
 
 // GetPersonalAccount 中台交互-查询个人数据包账户信息
 func (this *dataExportPackStruct) GetPersonalAccount(userId string) (senior, normal, seniorThirty, normalThirty int, err error) {
-	//调用中台 查询
-	var account *AccountPack
-	account, err = packAccountQuery(userId)
-	if err != nil {
-		return
-	}
-	return account.SeniorTotal, account.NormalTotal, account.SeniorThirty, account.NormalThirty, nil
+    //调用中台 查询
+    var account *AccountPack
+    account, err = packAccountQuery(userId)
+    if err != nil {
+        return
+    }
+    return account.SeniorTotal, account.NormalTotal, account.SeniorThirty, account.NormalThirty, nil
 }
 
 // GetDataExportRecordList 数据导出记录(包含商机管理导出、每日流量包导出、数据包导出及用户付费直接导出)
 func (this *dataExportPackStruct) GetDataExportRecordList(userId, memberPid string, entId, entUserId, pageNum, pageSize int) (list []map[string]interface{}, total int, err error) {
-	if pageSize == 0 {
-		pageSize = 10
-	}
+    if pageSize == 0 {
+        pageSize = 10
+    }
 
-	var searchSql []string
-	var searchValue []interface{}
+    var searchSql []string
+    var searchValue []interface{}
 
-	//个人直接支付数据导出
-	if userId != "" {
-		searchSql = append(searchSql, `(SELECT '' AS queryObj,filter_id AS queryId,user_id AS user_id,'' AS user_name,UNIX_TIMESTAMP( create_time ) AS exportDate,
+    //个人直接支付数据导出
+    if userId != "" {
+        searchSql = append(searchSql, `(SELECT '' AS queryObj,filter_id AS queryId,user_id AS user_id,'' AS user_name,UNIX_TIMESTAMP( create_time ) AS exportDate,
 		2 AS data_from,data_count AS export_num,-1 AS deduct_num,download_url AS down_url FROM dataexport_order WHERE user_id =? AND order_status =1 AND product_type ='历史数据')`)
-		searchValue = append(searchValue, userId)
-	}
+        searchValue = append(searchValue, userId)
+    }
 
-	//数据包导出及每日限量包导出
-	if userId != "" || memberPid != "" {
-		if memberPid == "" { //主账号查询
-			searchSql = append(searchSql, `(SELECT '' AS queryObj,query_id AS queryId,useid AS user_id,'' AS user_name,date AS exportDate,2 AS data_from,export_num AS
+    //数据包导出及每日限量包导出
+    if userId != "" || memberPid != "" {
+        if memberPid == "" { //主账号查询
+            searchSql = append(searchSql, `(SELECT '' AS queryObj,query_id AS queryId,useid AS user_id,'' AS user_name,date AS exportDate,2 AS data_from,export_num AS
 			export_num,deduct_num AS deduct_num,path AS down_url FROM datapacket_record WHERE master_id = ? )`)
-			searchValue = append(searchValue, userId)
-		} else { //子账号查询
-			searchSql = append(searchSql, `(SELECT '' AS queryObj,query_id AS queryId,useid AS user_id,'' AS user_name,date AS exportDate,2 AS data_from,export_num AS
+            searchValue = append(searchValue, userId)
+        } else { //子账号查询
+            searchSql = append(searchSql, `(SELECT '' AS queryObj,query_id AS queryId,useid AS user_id,'' AS user_name,date AS exportDate,2 AS data_from,export_num AS
 			export_num,deduct_num AS deduct_num,path AS down_url FROM datapacket_record WHERE useid = ? )`)
-			searchValue = append(searchValue, userId)
-		}
-	}
-
-	//企业数据导出
-	if entId > 0 && entUserId != 0 {
-		if util.Mysql.Count("entniche_user_role", map[string]interface{}{"user_id": entUserId, "role_id": 1}) > 0 {
-			//管理员查询
-			searchSql = append(searchSql, `(SELECT filter AS queryObj,'' AS queryId,'' AS user_id,user_name AS user_name,UNIX_TIMESTAMP( export_time ) AS exportDate,
+            searchValue = append(searchValue, userId)
+        }
+    }
+
+    //企业数据导出
+    if entId > 0 && entUserId != 0 {
+        if util.Mysql.Count("entniche_user_role", map[string]interface{}{"user_id": entUserId, "role_id": 1}) > 0 {
+            //管理员查询
+            searchSql = append(searchSql, `(SELECT filter AS queryObj,'' AS queryId,'' AS user_id,user_name AS user_name,UNIX_TIMESTAMP( export_time ) AS exportDate,
 			data_source AS data_from,export_num AS export_num,deduct_num AS deduct_num,download_url AS down_url FROM entniche_export_log WHERE ent_id = ? )`)
-			searchValue = append(searchValue, entId)
-		} else {
-			//子账号查询
-			searchSql = append(searchSql, `(SELECT filter AS queryObj,'' AS queryId,'' AS user_id,user_name AS user_name,UNIX_TIMESTAMP( export_time ) AS exportDate,
+            searchValue = append(searchValue, entId)
+        } else {
+            //子账号查询
+            searchSql = append(searchSql, `(SELECT filter AS queryObj,'' AS queryId,'' AS user_id,user_name AS user_name,UNIX_TIMESTAMP( export_time ) AS exportDate,
 			data_source AS data_from,export_num AS export_num,deduct_num AS deduct_num,download_url AS down_url FROM entniche_export_log WHERE user_id = ? )`)
-			searchValue = append(searchValue, entUserId)
-		}
-	}
-
-	finalSearch := strings.Join(searchSql, ` UNION ALL `)
-
-	//log.Printf("sql xxx %s\n", fmt.Sprintf(`SELECT * FROM ( %s ) AS allData ORDER BY exportDate DESC limit ?,? `, finalSearch))
-	//log.Printf("values xxx :")
-	//for k, v := range append(searchValue, pageNum*pageSize, pageSize) {
-	//	log.Printf(" [%d]=%v ", k, v)
-	//}
-	//log.Println()
-
-	//第一页返回总条数
-	if pageNum == 0 {
-		//log.Printf(`SELECT COUNT(*) FROM ( %s ) AS allData`, finalSearch)
-		if total = util.Mysql.QueryCount(fmt.Sprintf(`SELECT COUNT(*) FROM ( %s ) AS allData`, finalSearch), searchValue...); total == 0 {
-			return
-		}
-	} else {
-		total = -1
-	}
-
-	//查询列表
-	searchList := util.Mysql.Query(fmt.Sprintf(`SELECT * FROM ( %s ) AS allData ORDER BY exportDate DESC limit ?,? `, finalSearch), append(searchValue, pageNum*pageSize, pageSize)...)
-	if searchList == nil || len(*searchList) == 0 {
-		return
-	}
-
-	//格式化返回内容
-	list = make([]map[string]interface{}, 0, pageSize)
-	cacheName := map[string]string{}
-	for _, row := range *searchList {
-		//筛选内容
-		returnRow := make(map[string]interface{})
-		if queryId, _ := row["queryId"].(string); queryId != "" {
-			returnRow["search"] = getSearchValueById(queryId)
-		} else if queryStr, _ := row["queryObj"].(string); queryStr != "" {
-			filterMap := map[string]interface{}{}
-			if err := json.Unmarshal([]byte(queryStr), &filterMap); err == nil {
-				if filterId, _ := filterMap["FilterId"].(string); filterId != "" {
-					returnRow["search"] = getSearchValueById(filterId)
-				} else {
-					filterMap["area"] = filterMap["Area"]
-					t, _ := filterMap["Time"].(string)
-					if strings.Contains(t, "_") {
-						t1 := strings.Split(t, "_")[0]
-						t2 := strings.Split(t, "_")[1]
-						if len([]rune(t1)) > 10 {
-							t1 = string([]rune(t)[:10])
-						}
-						if len([]rune(t2)) > 10 {
-							t2 = string([]rune(t2)[:10])
-						}
-						t = t1 + "_" + t2
-					} else {
-						if len([]rune(t)) > 10 {
-							t = string([]rune(t)[:10])
-						}
-					}
-					filterMap["publishtime"] = t
-					filterMap["buyerclass"] = filterMap["Buyerclass"]
-					delete(filterMap, "Area")
-					delete(filterMap, "Time")
-					delete(filterMap, "Buyerclass")
-					returnRow["search"] = filterMap
-				}
-			}
-		}
-		//查询用户
-		if personalName, _ := row["user_name"].(string); personalName != "" {
-			returnRow["personal_name"] = personalName
-		} else if searchUserId, _ := row["user_id"].(string); searchUserId != "" {
-			if _, exists := cacheName[searchUserId]; !exists {
-				cacheName[searchUserId] = getUserName(searchUserId)
-			}
-			returnRow["personal_name"] = cacheName[searchUserId]
-		}
-		//导出时间
-		returnRow["export_timestamp"] = row["exportDate"]
-		//数据来源
-		if qutil.IntAll(row["data_from"]) == 1 {
-			returnRow["data_from"] = "统一订阅"
-		} else {
-			returnRow["data_from"] = "用户搜索"
-		}
-		//导出条数
-		returnRow["export_num"] = qutil.Int64All(row["export_num"])
-		returnRow["deduct_num"] = qutil.Int64All(row["deduct_num"])
-		//下载地址
-		returnRow["down_url"] = config.Config.WebDomain + qutil.ObjToString(row["down_url"])
-
-		list = append(list, returnRow)
-	}
-	return
+            searchValue = append(searchValue, entUserId)
+        }
+    }
+
+    finalSearch := strings.Join(searchSql, ` UNION ALL `)
+
+    //log.Printf("sql xxx %s\n", fmt.Sprintf(`SELECT * FROM ( %s ) AS allData ORDER BY exportDate DESC limit ?,? `, finalSearch))
+    //log.Printf("values xxx :")
+    //for k, v := range append(searchValue, pageNum*pageSize, pageSize) {
+    //	log.Printf(" [%d]=%v ", k, v)
+    //}
+    //log.Println()
+
+    //第一页返回总条数
+    if pageNum == 0 {
+        //log.Printf(`SELECT COUNT(*) FROM ( %s ) AS allData`, finalSearch)
+        if total = util.Mysql.QueryCount(fmt.Sprintf(`SELECT COUNT(*) FROM ( %s ) AS allData`, finalSearch), searchValue...); total == 0 {
+            return
+        }
+    } else {
+        total = -1
+    }
+
+    //查询列表
+    searchList := util.Mysql.Query(fmt.Sprintf(`SELECT * FROM ( %s ) AS allData ORDER BY exportDate DESC limit ?,? `, finalSearch), append(searchValue, pageNum*pageSize, pageSize)...)
+    if searchList == nil || len(*searchList) == 0 {
+        return
+    }
+
+    //格式化返回内容
+    list = make([]map[string]interface{}, 0, pageSize)
+    cacheName := map[string]string{}
+    for _, row := range *searchList {
+        //筛选内容
+        returnRow := make(map[string]interface{})
+        if queryId, _ := row["queryId"].(string); queryId != "" {
+            returnRow["search"] = getSearchValueById(queryId)
+        } else if queryStr, _ := row["queryObj"].(string); queryStr != "" {
+            filterMap := map[string]interface{}{}
+            if err := json.Unmarshal([]byte(queryStr), &filterMap); err == nil {
+                if filterId, _ := filterMap["FilterId"].(string); filterId != "" {
+                    returnRow["search"] = getSearchValueById(filterId)
+                } else {
+                    filterMap["area"] = filterMap["Area"]
+                    t, _ := filterMap["Time"].(string)
+                    if strings.Contains(t, "_") {
+                        t1 := strings.Split(t, "_")[0]
+                        t2 := strings.Split(t, "_")[1]
+                        if len([]rune(t1)) > 10 {
+                            t1 = string([]rune(t)[:10])
+                        }
+                        if len([]rune(t2)) > 10 {
+                            t2 = string([]rune(t2)[:10])
+                        }
+                        t = t1 + "_" + t2
+                    } else {
+                        if len([]rune(t)) > 10 {
+                            t = string([]rune(t)[:10])
+                        }
+                    }
+                    filterMap["publishtime"] = t
+                    filterMap["buyerclass"] = filterMap["Buyerclass"]
+                    delete(filterMap, "Area")
+                    delete(filterMap, "Time")
+                    delete(filterMap, "Buyerclass")
+                    returnRow["search"] = filterMap
+                }
+            }
+        }
+        //查询用户
+        if personalName, _ := row["user_name"].(string); personalName != "" {
+            returnRow["personal_name"] = personalName
+        } else if searchUserId, _ := row["user_id"].(string); searchUserId != "" {
+            if _, exists := cacheName[searchUserId]; !exists {
+                cacheName[searchUserId] = getUserName(searchUserId)
+            }
+            returnRow["personal_name"] = cacheName[searchUserId]
+        }
+        //导出时间
+        returnRow["export_timestamp"] = row["exportDate"]
+        //数据来源
+        if qutil.IntAll(row["data_from"]) == 1 {
+            returnRow["data_from"] = "统一订阅"
+        } else {
+            returnRow["data_from"] = "用户搜索"
+        }
+        //导出条数
+        returnRow["export_num"] = qutil.Int64All(row["export_num"])
+        returnRow["deduct_num"] = qutil.Int64All(row["deduct_num"])
+        //下载地址
+        returnRow["down_url"] = config.Config.WebDomain + qutil.ObjToString(row["down_url"])
+
+        list = append(list, returnRow)
+    }
+    return
 }
 
 // DoEntPackRepeatCheck 查询企业去重(旧企业导出逻辑)
 func (this *dataExportPackStruct) DoEntPackRepeatCheck(sess *httpsession.Session, userId, entId, selectId string, selectCount int) (deduct int, err error) {
-	//校验当前用户是否所属此企业
-	if phone := getAndCacheUserPhone(sess, userId); phone != "" {
-		res := util.Mysql.FindOne("entniche_user", map[string]interface{}{"phone": phone, "ent_id": entId}, "id,ent_id", "")
-		if res == nil || len(*res) == 0 {
-			return -1, fmt.Errorf("企业校验异常")
-		}
-
-		entUserId := qutil.IntAll((*res)["id"])
-		entIdInt := qutil.IntAll((*res)["ent_id"])
-
-		exportLock.Lock()
-		exportLockMap[entIdInt] = &sync.Mutex{}
-		entLock := exportLockMap[entIdInt]
-		exportLock.Unlock()
-		entLock.Lock()
-		//开始去重
-		_, newCount, _ := dataexport.GetEntDataExportCount(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch,
-			selectId, entIdInt, entUserId, true, middleGround.JyApiConfig.ApiList.EntDedupUrl, config.ExConf.MsgMaxCount)
-		entLock.Unlock()
-		return newCount, err
-	}
-	return -1, fmt.Errorf("未查询所属企业")
+    //校验当前用户是否所属此企业
+    if phone := getAndCacheUserPhone(sess, userId); phone != "" {
+        res := util.Mysql.FindOne("entniche_user", map[string]interface{}{"phone": phone, "ent_id": entId}, "id,ent_id", "")
+        if res == nil || len(*res) == 0 {
+            return -1, fmt.Errorf("企业校验异常")
+        }
+
+        entUserId := qutil.IntAll((*res)["id"])
+        entIdInt := qutil.IntAll((*res)["ent_id"])
+
+        exportLock.Lock()
+        exportLockMap[entIdInt] = &sync.Mutex{}
+        entLock := exportLockMap[entIdInt]
+        exportLock.Unlock()
+        entLock.Lock()
+        //开始去重
+        _, newCount, _ := dataexport.GetEntDataExportCount(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch,
+            selectId, entIdInt, entUserId, true, middleGround.JyApiConfig.ApiList.EntDedupUrl, config.ExConf.MsgMaxCount)
+        entLock.Unlock()
+        return newCount, err
+    }
+    return -1, fmt.Errorf("未查询所属企业")
 }
 
 // DoPerPackRepeatCheck 查询个人数据包去重
 func (this *dataExportPackStruct) DoPerPackRepeatCheck(userId string, isSenior bool, ids []string) (repeat, deduct int, err error) {
-	return doRepeatCheck(userId, isSenior, ids)
+    return doRepeatCheck(userId, isSenior, ids)
 }
 
 // GetExcelFile 数据包生成excel文件
 func GetExcelFile(selectId string, checkCount int, isSenior bool, success func(excelPath string, exportIds []string), fail func(error)) {
-	list, err := dataexport.GetDataExportSearchResultByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, selectId, qutil.If(isSenior, "2", "1").(string), checkCount)
-	url := util.GetExcelFilePath(pay.GetOrderCode(selectId))
-	if err == nil && list != nil && len(*list) > 0 {
-		list = dataexport.FormatExportData(util.MQFWENT, list, config.Config.WebDomain, "2")
-		err = util.CreateDataExportExcelFile(list, isSenior, config.ExConf.ExcelPayedPath+url) //创建excel文件
-	}
-	if err == nil {
-		ids := make([]string, 0, checkCount)
-		for _, item := range *list {
-			ids = append(ids, item["_id"].(string))
-		}
-		success(url, ids)
-	} else {
-		fail(err)
-	}
+    list, err := dataexport.GetDataExportSearchResultByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, selectId, qutil.If(isSenior, "2", "1").(string), checkCount)
+    url := util.GetExcelFilePath(pay.GetOrderCode(selectId))
+    if err == nil && list != nil && len(*list) > 0 {
+        list = dataexport.FormatExportData(util.MQFWENT, list, config.Config.WebDomain, "2")
+        err = util.CreateDataExportExcelFile(list, isSenior, config.ExConf.ExcelPayedPath+url) //创建excel文件
+    }
+    if err == nil {
+        ids := make([]string, 0, checkCount)
+        for _, item := range *list {
+            ids = append(ids, item["_id"].(string))
+        }
+        success(url, ids)
+    } else {
+        fail(err)
+    }
 }
 
 var (
-	exportLock    = sync.Mutex{}
-	exportLockMap = map[int]*sync.Mutex{}
+    exportLock    = sync.Mutex{}
+    exportLockMap = map[int]*sync.Mutex{}
 )
 
 // UseEntPack 企业数据包扣除
 func (this *dataExportPackStruct) UseEntPack(sess *httpsession.Session, userId, entId string, selectId string, exportPhone, exportEmail string) error {
-	if phone := getAndCacheUserPhone(sess, userId); phone != "" {
-		res := util.Mysql.FindOne("entniche_user", map[string]interface{}{"phone": phone, "ent_id": entId}, "id,ent_id", "")
-		if res == nil || len(*res) == 0 {
-			return fmt.Errorf("企业校验异常")
-		}
-		entUserId := qutil.IntAll((*res)["id"])
-		entIdInt := qutil.IntAll((*res)["ent_id"])
-
-		exportLock.Lock()
-		exportLockMap[entIdInt] = &sync.Mutex{}
-		entLock := exportLockMap[entIdInt]
-		exportLock.Unlock()
-		entLock.Lock()
-
-		query := map[string]interface{}{"ent_id": entId, "user_id": entUserId}
-		remain_nums, export_nums := 0, 0
-		limit := util.Mysql.FindOne("entniche_export_limit", query, "data_limit,remain_nums,export_nums", "")
-		if limit != nil {
-			remain_nums = qutil.IntAll((*limit)["remain_nums"])
-			export_nums = qutil.IntAll((*limit)["export_nums"])
-		}
-
-		count := 0
-		newCount := 0
-		data := &[]map[string]interface{}{}
-
-		current := dataexport.GetCurrentCount(util.Mysql, util.Mgo_Qyfw, entIdInt)
-		log.Println("企业总条数", current)
-		//开始去重
-		count, newCount, data = dataexport.GetEntDataExportCount(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch,
-			selectId, entIdInt, entUserId, false, middleGround.JyApiConfig.ApiList.EntDedupUrl, config.ExConf.MsgMaxCount)
-
-		if newCount > current {
-			return fmt.Errorf("企业账户余额不足")
-		}
-		if newCount > remain_nums {
-			return fmt.Errorf("已超出进入导出上限")
-		}
-		go func() {
-			data = dataexport.FormatExportDatas(util.MQFWENT, data, config.Config.WebDomain, "2", entIdInt)
-			xlsxUrl := dataexport.GetXlsx(*data, entIdInt, entUserId, config.ExConf.ExcelEntPath)
-			if xlsxUrl != "" {
-				filter := dataexport.Filters{
-					FilterId: selectId,
-				}
-				filterStr, _ := json.Marshal(filter)
-				dataexport.SaveExportLog(util.Mysql, entIdInt, entUserId, count, newCount, remain_nums, export_nums, xlsxUrl, "2", string(filterStr), exportPhone, exportEmail)
-				dataexport.DeductNum(util.Mysql, util.Mgo_Qyfw, entIdInt, newCount)
-				cacheResult(nil, xlsxUrl, fmt.Sprintf("entPackResult_%s_%s", userId, selectId))
-				sendPackExportMail(userId, selectId, exportEmail, xlsxUrl)
-				for _, v := range *data {
-					util.MQFW.Save("entdataexport", v)
-				}
-			}
-		}()
-		entLock.Unlock()
-	}
-	return nil
+    if phone := getAndCacheUserPhone(sess, userId); phone != "" {
+        res := util.Mysql.FindOne("entniche_user", map[string]interface{}{"phone": phone, "ent_id": entId}, "id,ent_id", "")
+        if res == nil || len(*res) == 0 {
+            return fmt.Errorf("企业校验异常")
+        }
+        entUserId := qutil.IntAll((*res)["id"])
+        entIdInt := qutil.IntAll((*res)["ent_id"])
+
+        exportLock.Lock()
+        exportLockMap[entIdInt] = &sync.Mutex{}
+        entLock := exportLockMap[entIdInt]
+        exportLock.Unlock()
+        entLock.Lock()
+
+        query := map[string]interface{}{"ent_id": entId, "user_id": entUserId}
+        remain_nums, export_nums := 0, 0
+        limit := util.Mysql.FindOne("entniche_export_limit", query, "data_limit,remain_nums,export_nums", "")
+        if limit != nil {
+            remain_nums = qutil.IntAll((*limit)["remain_nums"])
+            export_nums = qutil.IntAll((*limit)["export_nums"])
+        }
+
+        count := 0
+        newCount := 0
+        data := &[]map[string]interface{}{}
+
+        current := dataexport.GetCurrentCount(util.Mysql, util.Mgo_Qyfw, entIdInt)
+        log.Println("企业总条数", current)
+        //开始去重
+        count, newCount, data = dataexport.GetEntDataExportCount(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch,
+            selectId, entIdInt, entUserId, false, middleGround.JyApiConfig.ApiList.EntDedupUrl, config.ExConf.MsgMaxCount)
+
+        if newCount > current {
+            return fmt.Errorf("企业账户余额不足")
+        }
+        if newCount > remain_nums {
+            return fmt.Errorf("已超出进入导出上限")
+        }
+        go func() {
+            data = dataexport.FormatExportDatas(util.MQFWENT, data, config.Config.WebDomain, "2", entIdInt)
+            xlsxUrl := dataexport.GetXlsx(*data, entIdInt, entUserId, config.ExConf.ExcelEntPath)
+            if xlsxUrl != "" {
+                filter := dataexport.Filters{
+                    FilterId: selectId,
+                }
+                filterStr, _ := json.Marshal(filter)
+                dataexport.SaveExportLog(util.Mysql, entIdInt, entUserId, count, newCount, remain_nums, export_nums, xlsxUrl, "2", string(filterStr), exportPhone, exportEmail)
+                dataexport.DeductNum(util.Mysql, util.Mgo_Qyfw, entIdInt, newCount)
+                cacheResult(nil, xlsxUrl, fmt.Sprintf("entPackResult_%s_%s", userId, selectId))
+                sendPackExportMail(userId, selectId, exportEmail, xlsxUrl)
+                for _, v := range *data {
+                    util.MQFW.Save("entdataexport", v)
+                }
+            }
+        }()
+        entLock.Unlock()
+    }
+    return nil
 }
 
 // UsePersonalPack 个人数据包扣除
 func (this *dataExportPackStruct) UsePersonalPack(userId, selectId, phone, email string, isSenior bool, checkCount int) error {
-	go GetExcelFile(selectId, checkCount, isSenior, func(excelPath string, exportIds []string) {
-		deduct, err := usePerPack(userId, checkCount, isSenior, &PersonalUsePackRemark{
-			QueryId:         selectId,
-			ExcelUrl:        excelPath,
-			ExportNum:       checkCount,
-			ExportTimeStamp: time.Now().Unix(),
-			Phone:           phone,
-			Email:           email,
-		}, exportIds)
-		if err == nil {
-			go util.Mysql.Insert("datapacket_record", map[string]interface{}{
-				"infoids":    strings.Join(exportIds, ","),
-				"type":       2,
-				"master_id":  userId,
-				"useid":      userId,
-				"query_id":   selectId,
-				"date":       time.Now().Unix(),
-				"path":       excelPath,
-				"deduct_num": deduct,
-				"export_num": checkCount,
-				"phone":      phone,
-				"mail":       email,
-				"isSenior":   qutil.If(isSenior, 2, 1),
-			})
-			//发送邮件
-			go sendPackExportMail(userId, selectId, email, excelPath)
-		}
-		cacheResult(err, excelPath, fmt.Sprintf("personalPackResult_%s_%s_%v", userId, selectId, isSenior))
-	}, func(err error) {
-		cacheResult(err, "", fmt.Sprintf("personalPackResult_%s_%s_%v", userId, selectId, isSenior))
-		errMeg := fmt.Sprintf("数据包导出异常\n用户id:%s\n数据导出筛选id:%s\n异常信息:%v:", userId, selectId, err)
-		util.SendErrNoteToMail(errMeg)
-	})
-	return nil
+    go GetExcelFile(selectId, checkCount, isSenior, func(excelPath string, exportIds []string) {
+        deduct, err := usePerPack(userId, checkCount, isSenior, &PersonalUsePackRemark{
+            QueryId:         selectId,
+            ExcelUrl:        excelPath,
+            ExportNum:       checkCount,
+            ExportTimeStamp: time.Now().Unix(),
+            Phone:           phone,
+            Email:           email,
+        }, exportIds)
+        if err == nil {
+            go util.Mysql.Insert("datapacket_record", map[string]interface{}{
+                "infoids":    strings.Join(exportIds, ","),
+                "type":       2,
+                "master_id":  userId,
+                "useid":      userId,
+                "query_id":   selectId,
+                "date":       time.Now().Unix(),
+                "path":       excelPath,
+                "deduct_num": deduct,
+                "export_num": checkCount,
+                "phone":      phone,
+                "mail":       email,
+                "isSenior":   qutil.If(isSenior, 2, 1),
+            })
+            //发送邮件
+            go sendPackExportMail(userId, selectId, email, excelPath)
+        }
+        cacheResult(err, excelPath, fmt.Sprintf("personalPackResult_%s_%s_%v", userId, selectId, isSenior))
+    }, func(err error) {
+        cacheResult(err, "", fmt.Sprintf("personalPackResult_%s_%s_%v", userId, selectId, isSenior))
+        errMeg := fmt.Sprintf("数据包导出异常\n用户id:%s\n数据导出筛选id:%s\n异常信息:%v:", userId, selectId, err)
+        util.SendErrNoteToMail(errMeg)
+    })
+    return nil
 }
 
 func cacheResult(err error, filePath, key string) {
-	var returnData api.Result
-	if err != nil {
-		returnData = api.NewResult(nil, err)
-	} else {
-		returnData = api.NewResult(filePath, nil)
-	}
-	bytes, _ := json.Marshal(returnData)
-	redis.Put("other", key, string(bytes), 60*5)
+    var returnData api.Result
+    if err != nil {
+        returnData = api.NewResult(nil, err)
+    } else {
+        returnData = api.NewResult(filePath, nil)
+    }
+    bytes, _ := json.Marshal(returnData)
+    redis.Put("other", key, string(bytes), 60*5)
 }
 
 // UseDailyPack 每日限量包
 func (this *dataExportPackStruct) UseDailyPack(userId, selectId, phone, email string, selectCount int, session *httpsession.Session) error {
-	vipStatus := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
-	if vipStatus.Status <= 0 || vipStatus.DailyNum == 0 {
-		return fmt.Errorf("非法请求")
-	}
-	go GetExcelFile(selectId, selectCount, true, func(excelPath string, exportIds []string) {
-		packetMsg := dataexport.GetDataPacketMsg(vipStatus.GetUseId(), vipStatus.DailyNum)
-		//余额扣除
-		err := func() error {
-			if err := packetMsg.AddNum(selectCount); err != nil {
-				return err
-			}
-			//保存导出记录
-			packetMsg.SaveRecord(util.Mysql, userId, selectId, dataexport.BigMemberDaily, exportIds, excelPath, phone, email)
-			//发送邮件
-			go sendPackExportMail(userId, selectId, email, excelPath)
-			return nil
-		}()
-		cacheResult(err, excelPath, fmt.Sprintf("dailyPackResult_%s_%s", userId, selectId))
-	}, func(err error) {
-		cacheResult(err, "", fmt.Sprintf("dailyPackResult_%s_%s", userId, selectId))
-		errMeg := fmt.Sprintf("数据包导出异常\n用户id:%s\n数据导出筛选id:%s\n异常信息:%v:", userId, selectId, err)
-		util.SendErrNoteToMail(errMeg)
-	})
-	return nil
+    vipStatus := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
+    if vipStatus.Status <= 0 || vipStatus.DailyNum == 0 {
+        return fmt.Errorf("非法请求")
+    }
+    go GetExcelFile(selectId, selectCount, true, func(excelPath string, exportIds []string) {
+        packetMsg := dataexport.GetDataPacketMsg(vipStatus.GetUseId(), vipStatus.DailyNum)
+        //余额扣除
+        err := func() error {
+            if err := packetMsg.AddNum(selectCount); err != nil {
+                return err
+            }
+            //保存导出记录
+            packetMsg.SaveRecord(util.Mysql, userId, selectId, dataexport.BigMemberDaily, exportIds, excelPath, phone, email)
+            //发送邮件
+            go sendPackExportMail(userId, selectId, email, excelPath)
+            return nil
+        }()
+        cacheResult(err, excelPath, fmt.Sprintf("dailyPackResult_%s_%s", userId, selectId))
+    }, func(err error) {
+        cacheResult(err, "", fmt.Sprintf("dailyPackResult_%s_%s", userId, selectId))
+        errMeg := fmt.Sprintf("数据包导出异常\n用户id:%s\n数据导出筛选id:%s\n异常信息:%v:", userId, selectId, err)
+        util.SendErrNoteToMail(errMeg)
+    })
+    return nil
 }
 
 // PerRechargeList 个人数据包充值记录
 func (this *dataExportPackStruct) PerRechargeList(userId string, pageNum, pageSize int) (int, []map[string]interface{}, error) {
-	if pageSize == 0 {
-		pageSize = 10
-	}
-	pageNum += 1
-	return perPackRecharge(userId, pageNum, pageSize)
+    if pageSize == 0 {
+        pageSize = 10
+    }
+    pageNum += 1
+    return perPackRecharge(userId, pageNum, pageSize)
 }
 
 // 查询企业账户余额
 func getCurrEntCount(entName, entPhone string) int {
-	current, ok := util.Mgo_Qyfw.FindOne("user", map[string]interface{}{"phone": entPhone, "username": entName})
-	if current == nil || !ok {
-		return 0
-	}
-	plan, planOk := (*current)["plan"].(map[string]interface{})
-	if !planOk {
-		return 0
-	}
-	return qutil.IntAll(plan["current"])
+    current, ok := util.Mgo_Qyfw.FindOne("user", map[string]interface{}{"phone": entPhone, "username": entName})
+    if current == nil || !ok {
+        return 0
+    }
+    plan, planOk := (*current)["plan"].(map[string]interface{})
+    if !planOk {
+        return 0
+    }
+    return qutil.IntAll(plan["current"])
 }
 
 // 根据筛选id获取筛选条件
 func getSearchValueById(filterId string) (searchMap map[string]interface{}) {
-	filter, _ := util.MQFW.FindById("export_search", filterId, `{"buyerclass":1,"publishtime":1,"area":1,"comeinfrom":1}`)
-	if filter != nil && len(*filter) > 0 {
-		searchMap = make(map[string]interface{})
-		searchMap["buyerclass"] = (*filter)["buyerclass"]
-		searchMap["publishtime"] = (*filter)["publishtime"]
-		searchMap["area"] = (*filter)["area"]
-		searchMap["id"] = encrypt.SE.Encode2Hex(filterId)
-		searchMap["comeinfrom"] = (*filter)["comeinfrom"]
-	}
-	return
+    filter, _ := util.MQFW.FindById("export_search", filterId, `{"buyerclass":1,"publishtime":1,"area":1,"comeinfrom":1}`)
+    if filter != nil && len(*filter) > 0 {
+        searchMap = make(map[string]interface{})
+        searchMap["buyerclass"] = (*filter)["buyerclass"]
+        searchMap["publishtime"] = (*filter)["publishtime"]
+        searchMap["area"] = (*filter)["area"]
+        searchMap["id"] = encrypt.SE.Encode2Hex(filterId)
+        searchMap["comeinfrom"] = (*filter)["comeinfrom"]
+    }
+    return
 }
 
 // 根据用户id查询用户名
 func getUserName(userId string) string {
-	userRow, _ := util.MQFW.FindById("user", userId, `{"s_nickname":1,"s_phone":1,"s_jyname":1}`)
-	if userRow != nil && len(*userRow) > 0 {
-		if name, ok := (*userRow)["s_nickname"].(string); ok && name != "" {
-			return name
-		} else if s_phone, ok := (*userRow)["s_phone"].(string); ok && len(s_phone) == 11 {
-			return fmt.Sprintf("%s***%s", s_phone[:3], s_phone[7:])
-		} else if jyName, ok := (*userRow)["s_jyname"].(string); ok && jyName != "" {
-			return jyName
-		}
-	}
-	return ""
+    userRow := util.Compatible.Select(userId, `{"s_nickname":1,"s_phone":1,"s_jyname":1}`)
+    if userRow != nil && len(*userRow) > 0 {
+        if name, ok := (*userRow)["s_nickname"].(string); ok && name != "" {
+            return name
+        } else if s_phone, ok := (*userRow)["s_phone"].(string); ok && len(s_phone) == 11 {
+            return fmt.Sprintf("%s***%s", s_phone[:3], s_phone[7:])
+        } else if jyName, ok := (*userRow)["s_jyname"].(string); ok && jyName != "" {
+            return jyName
+        }
+    }
+    return ""
 }
 
 func getAndCacheUserPhone(sess *httpsession.Session, userId string) string {
-	phone, _ := sess.Get("phone").(string)
-	if phone == "" {
-		user, _ := util.MQFW.FindById("user", userId, `{"s_phone":1,"s_m_phone":1}`)
-		if user != nil && len(*user) > 0 {
-			if phone1, ok := (*user)["s_m_phone"]; ok && phone1 != "" {
-				phone, _ = phone1.(string)
-			} else if phone2, ok := (*user)["s_phone"]; ok && phone2 != "" {
-				phone, _ = phone2.(string)
-			}
-		}
-		if phone != "" {
-			sess.Set("phone", phone)
-		}
-	}
-	return phone
+    phone, _ := sess.Get("phone").(string)
+    if phone == "" {
+        user := util.Compatible.Select(userId, `{"s_phone":1,"s_m_phone":1}`)
+        if user != nil && len(*user) > 0 {
+            if phone1, ok := (*user)["s_m_phone"]; ok && phone1 != "" {
+                phone, _ = phone1.(string)
+            } else if phone2, ok := (*user)["s_phone"]; ok && phone2 != "" {
+                phone, _ = phone2.(string)
+            }
+        }
+        if phone != "" {
+            sess.Set("phone", phone)
+        }
+    }
+    return phone
 }
 
 func sendPackExportMail(userId, selectId, userMail, excelPath string) {
-	if userId == "" || selectId == "" || userMail == "" || excelPath == "" {
-		return
-	}
-	mailContent, err := GetPackDataExportMailContent(selectId, config.Config.WebDomain+excelPath)
-	if err != nil {
-		log.Printf("SendDataExportMailForPayed SendMailToPayUser 订单号%s获取邮件内容异常%v\n", selectId, err)
-	}
-	//用户发送邮件
-	if userMail != "" {
-		if util.SendRetryMail(config.ExConf.Mail_retry, userMail, "历史数据", mailContent, "", nil, config.GmailAuth) {
-			log.Printf("SendDataExportMailForPayed SendMailToPayUser 订单号%s:邮箱%s数据导出邮件发送成功!", selectId, userMail)
-		} else {
-			sendErr := fmt.Sprintf("SendDataExportMailForPayed SendMailToPayUser 订单号%s:邮箱%s数据导出邮件发送失败", selectId, userMail)
-			log.Printf("%s sendPackExportMail 发送邮件失败 %v\n", userId, sendErr)
-			return
-		}
-	}
+    if userId == "" || selectId == "" || userMail == "" || excelPath == "" {
+        return
+    }
+    mailContent, err := GetPackDataExportMailContent(selectId, config.Config.WebDomain+excelPath)
+    if err != nil {
+        log.Printf("SendDataExportMailForPayed SendMailToPayUser 订单号%s获取邮件内容异常%v\n", selectId, err)
+    }
+    //用户发送邮件
+    if userMail != "" {
+        if util.SendRetryMail(config.ExConf.Mail_retry, userMail, "历史数据", mailContent, "", nil, config.GmailAuth) {
+            log.Printf("SendDataExportMailForPayed SendMailToPayUser 订单号%s:邮箱%s数据导出邮件发送成功!", selectId, userMail)
+        } else {
+            sendErr := fmt.Sprintf("SendDataExportMailForPayed SendMailToPayUser 订单号%s:邮箱%s数据导出邮件发送失败", selectId, userMail)
+            log.Printf("%s sendPackExportMail 发送邮件失败 %v\n", userId, sendErr)
+            return
+        }
+    }
 }

+ 852 - 854
src/jfw/modules/subscribepay/src/entity/dataexport.go

@@ -1,918 +1,916 @@
 package entity
 
 import (
-	"bytes"
-	"encoding/json"
-	"fmt"
-	"io/ioutil"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"os"
-	"regexp"
-	"strconv"
-	"strings"
-	"sync"
-	"time"
+    "bytes"
+    "encoding/json"
+    "fmt"
+    "io/ioutil"
+    "jy/src/jfw/modules/subscribepay/src/config"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "os"
+    "regexp"
+    "strconv"
+    "strings"
+    "sync"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/mail"
-	. "app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
-	"go.mongodb.org/mongo-driver/bson"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/mail"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
 )
 
 var (
-	reportEmailHtml string
+    reportEmailHtml string
 )
 
 var suffix_msgt = "_SX"
 
 func init() {
-	r, err := os.Open("./reportEmailTemplate.html")
-	if err != nil {
-		log.Println("MailHtmlError", err)
-	}
-	defer r.Close()
-	bs, _ := ioutil.ReadAll(r)
-	reportEmailHtml = string(bs)
+    r, err := os.Open("./reportEmailTemplate.html")
+    if err != nil {
+        log.Println("MailHtmlError", err)
+    }
+    defer r.Close()
+    bs, _ := ioutil.ReadAll(r)
+    reportEmailHtml = string(bs)
 }
 
 type dataExportStruct struct{}
 
 // VIP订单
 type VipFilter struct {
-	Area               map[string]interface{} `json:"area"`     //地区
-	Industry           []string               `json:"industry"` //
-	Cyclecount         int                    `json:"cyclecount"`
-	Cycleunit          int                    `json:"cycleunit"`
-	Ordertype          int                    `json:"ordertype"`
-	Addarea            map[string]interface{} `json:"addarea"`            //新增地区
-	Addindustry        []string               `json:"addindustry"`        //新增行业
-	Addareacount       map[string]interface{} `json:"addareacount"`       //新增地区数量
-	Addbuyerclasscount int                    `json:"addbuyerclasscount"` //新增地区数量
-	Buyset             map[string]interface{} `json:"buyset"`
-	NewBuyset          map[string]interface{} `json:"newBuyset"` //逻辑重写后的判断条件
+    Area               map[string]interface{} `json:"area"`     //地区
+    Industry           []string               `json:"industry"` //
+    Cyclecount         int                    `json:"cyclecount"`
+    Cycleunit          int                    `json:"cycleunit"`
+    Ordertype          int                    `json:"ordertype"`
+    Addarea            map[string]interface{} `json:"addarea"`            //新增地区
+    Addindustry        []string               `json:"addindustry"`        //新增行业
+    Addareacount       map[string]interface{} `json:"addareacount"`       //新增地区数量
+    Addbuyerclasscount int                    `json:"addbuyerclasscount"` //新增地区数量
+    Buyset             map[string]interface{} `json:"buyset"`
+    NewBuyset          map[string]interface{} `json:"newBuyset"` //逻辑重写后的判断条件
 }
 
 var JyDataExportStruct dataExportStruct
 
 // 数据导出支付完成回调方法
 func (d *dataExportStruct) PayCallBack(param *CallBackParam) bool {
-	now := time.Now()
-	update := false
-	orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,filter,user_mail,product_type,data_spec,user_phone,filter_id,order_code,data_count,order_status,order_money,out_trade_no,create_time,pay_way,dis_word,user_id,download_url,d_relation_id", "")
-	pay_time := FormatDate(&now, Date_Full_Layout)
-	if orderdata != nil {
-		order_code := qutil.ObjToString((*orderdata)["order_code"])
-		userId := qutil.ObjToString((*orderdata)["user_id"])
-		order_status := qutil.IntAll((*orderdata)["order_status"])
-		//dis_word := qutil.ObjToString((*orderdata)["dis_word"])
-		filter := qutil.ObjToString((*orderdata)["filter"])
-		user_phone := qutil.ObjToString((*orderdata)["user_phone"])
-		sc := new(dataexport.SieveCondition)
-		err := json.Unmarshal([]byte(filter), &sc)
-		if err != nil {
-			log.Println(" 数据导出获取分销系统口令 有误")
-		}
-		if order_status == 0 {
-			updateMap := map[string]interface{}{
-				"pay_money":    param.CashFee,
-				"pay_time":     pay_time,
-				"order_status": 1,
-				//支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
-				"out_trade_no": param.OutTradeno,
-			}
-			orderCode := qutil.ObjToString((*orderdata)["order_code"])
-			download_url := qutil.ObjToString((*orderdata)["download_url"])
-			if download_url == "" { //若未生成execl
-				download_url = util.GetExcelFilePath(orderCode)
-				updateMap["download_url"] = download_url
-			}
+    now := time.Now()
+    update := false
+    orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,filter,user_mail,product_type,data_spec,user_phone,filter_id,order_code,data_count,order_status,order_money,out_trade_no,create_time,pay_way,dis_word,user_id,download_url,d_relation_id", "")
+    pay_time := FormatDate(&now, Date_Full_Layout)
+    if orderdata != nil {
+        order_code := qutil.ObjToString((*orderdata)["order_code"])
+        userId := qutil.ObjToString((*orderdata)["user_id"])
+        order_status := qutil.IntAll((*orderdata)["order_status"])
+        //dis_word := qutil.ObjToString((*orderdata)["dis_word"])
+        filter := qutil.ObjToString((*orderdata)["filter"])
+        user_phone := qutil.ObjToString((*orderdata)["user_phone"])
+        sc := new(dataexport.SieveCondition)
+        err := json.Unmarshal([]byte(filter), &sc)
+        if err != nil {
+            log.Println(" 数据导出获取分销系统口令 有误")
+        }
+        if order_status == 0 {
+            updateMap := map[string]interface{}{
+                "pay_money":    param.CashFee,
+                "pay_time":     pay_time,
+                "order_status": 1,
+                //支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
+                "out_trade_no": param.OutTradeno,
+            }
+            orderCode := qutil.ObjToString((*orderdata)["order_code"])
+            download_url := qutil.ObjToString((*orderdata)["download_url"])
+            if download_url == "" { //若未生成execl
+                download_url = util.GetExcelFilePath(orderCode)
+                updateMap["download_url"] = download_url
+            }
 
-			update = util.Mysql.Update("dataexport_order", map[string]interface{}{
-				"id": (*orderdata)["id"],
-			}, updateMap)
-			if update {
-				//先发个通知
-				go SendMailToBJFinance(orderdata, pay_time, param.TransactionId, 1, config.GmailAuth)
+            update = util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "id": (*orderdata)["id"],
+            }, updateMap)
+            if update {
+                //先发个通知
+                go SendMailToBJFinance(orderdata, pay_time, param.TransactionId, 1, config.GmailAuth)
 
-				//发送邮件移至定时任务
-				//go SendMailToPayUser(orderdata, float64(param.CashFee)/100, pay_time, download_url, config.GmailAuth)
+                //发送邮件移至定时任务
+                //go SendMailToPayUser(orderdata, float64(param.CashFee)/100, pay_time, download_url, config.GmailAuth)
 
-				/*if dis_word != "" {
-					//分销系统 分销记录
-					suffix := dis_word[len(dis_word)-3 : len(dis_word)]
-					if suffix == suffix_msgt {
-						go OtherDisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据导出", dis_word, qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["create_time"]))
-					} else {
-						go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据导出", dis_word)
-					}
-				}*/
-				//取消其他订单
-				go PayCancel(userId, "历史数据", "")
-				//卡卷使用
-				userLotteryId := qutil.ObjToString((*orderdata)["d_relation_id"])
-				if userLotteryId != "" {
-					go func(userId, userLotteryId, order_code string) {
-						_, name := util.GetMyPhoneAndName(userId)
-						if !util.UpdateCouponState(userId, userLotteryId, name, user_phone, order_code, "数据导出", "", 1, 0) {
-							log.Println(fmt.Sprintf("单号%s-消费失败-卡卷%s", order_code, userLotteryId))
-						}
-					}(userId, userLotteryId, order_code)
-				}
-			} else {
-				log.Printf("PayCallBack %s修改订单状态失败\n", orderCode)
-			}
-		} else {
-			update = true
-		}
-	}
-	return update
+                /*if dis_word != "" {
+                	//分销系统 分销记录
+                	suffix := dis_word[len(dis_word)-3 : len(dis_word)]
+                	if suffix == suffix_msgt {
+                		go OtherDisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据导出", dis_word, qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["create_time"]))
+                	} else {
+                		go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据导出", dis_word)
+                	}
+                }*/
+                //取消其他订单
+                go PayCancel(userId, "历史数据", "")
+                //卡卷使用
+                userLotteryId := qutil.ObjToString((*orderdata)["d_relation_id"])
+                if userLotteryId != "" {
+                    go func(userId, userLotteryId, order_code string) {
+                        _, name := util.GetMyPhoneAndName(userId)
+                        if !util.UpdateCouponState(userId, userLotteryId, name, user_phone, order_code, "数据导出", "", 1, 0) {
+                            log.Println(fmt.Sprintf("单号%s-消费失败-卡卷%s", order_code, userLotteryId))
+                        }
+                    }(userId, userLotteryId, order_code)
+                }
+            } else {
+                log.Printf("PayCallBack %s修改订单状态失败\n", orderCode)
+            }
+        } else {
+            update = true
+        }
+    }
+    return update
 }
 
 var finaceLock *sync.Mutex = &sync.Mutex{}
 
 // 给北京财务人员发邮件
 func SendMailToBJFinance(order *map[string]interface{}, pay_time, transaction_id string, mailType int, auth []*mail.GmailAuth) {
-	defer qutil.Catch()
-	finaceLock.Lock()
-	defer finaceLock.Unlock()
-	order_code := qutil.ObjToString((*order)["order_code"])
-	user_mail := qutil.ObjToString((*order)["user_mail"])
-	user_phone := qutil.ObjToString((*order)["user_phone"])
-	data_spec := qutil.ObjToString((*order)["data_spec"])
-	data_count := qutil.IntAll((*order)["data_count"])
-	pay_way := qutil.ObjToString((*order)["pay_way"])
-	pay_money := float64(qutil.IntAll((*order)["pay_money"])) / 100
-	if strings.Contains(pay_way, "wx") {
-		pay_way = "微信"
-	} else if strings.Contains(pay_way, "ali") {
-		pay_way = "支付宝"
-	}
+    defer qutil.Catch()
+    finaceLock.Lock()
+    defer finaceLock.Unlock()
+    order_code := qutil.ObjToString((*order)["order_code"])
+    user_mail := qutil.ObjToString((*order)["user_mail"])
+    user_phone := qutil.ObjToString((*order)["user_phone"])
+    data_spec := qutil.ObjToString((*order)["data_spec"])
+    data_count := qutil.IntAll((*order)["data_count"])
+    pay_way := qutil.ObjToString((*order)["pay_way"])
+    pay_money := float64(qutil.IntAll((*order)["pay_money"])) / 100
+    if strings.Contains(pay_way, "wx") {
+        pay_way = "微信"
+    } else if strings.Contains(pay_way, "ali") {
+        pay_way = "支付宝"
+    }
 
-	create_time := qutil.ObjToString((*order)["create_time"])
-	if create_time != "" {
-		create_time = strings.Replace(create_time, "-", ".", -1)
-		create_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(create_time, "")
-	}
-	//
-	product_type := qutil.ObjToString((*order)["product_type"]) + "导出"
-	//
-	order_money := float64(qutil.IntAll((*order)["order_money"])) / 100
+    create_time := qutil.ObjToString((*order)["create_time"])
+    if create_time != "" {
+        create_time = strings.Replace(create_time, "-", ".", -1)
+        create_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(create_time, "")
+    }
+    //
+    product_type := qutil.ObjToString((*order)["product_type"]) + "导出"
+    //
+    order_money := float64(qutil.IntAll((*order)["order_money"])) / 100
 
-	if transaction_id == "" {
-		transaction_id = func() string {
-			table := ""
-			if pay_way == "微信" {
-				table = "weixin_pay"
-			} else if pay_way == "支付宝" {
-				table = "ali_pay"
-			} else {
-				return ""
-			}
-			out_trade_no := qutil.ObjToString((*order)["out_trade_no"])
-			wxpaydata := util.Mysql.FindOne(table, map[string]interface{}{
-				"out_trade_no": out_trade_no,
-			}, "transaction_id", "")
-			if wxpaydata != nil && len(*wxpaydata) > 0 { //线下支付没有微信订单编号
-				return qutil.ObjToString((*wxpaydata)["transaction_id"])
-			}
-			return ""
-		}()
-	}
-	isShowTransaction := "" //支付订单号为空,邮件不显示此字段
-	if transaction_id == "" {
-		isShowTransaction = "none"
-	}
-	mailcontent := ""
-	var mail_title = ""
-	selectType := ""
-	if mailType == 1 { //支付完成后给北京财务发送导出数据接口信息的邮件
-		filter := qutil.ObjToString((*order)["filter"])
-		// buyer, buyerclass, winner, subtype := "", "", "", ""
-		// publishtime, region, industry, keys := "", "", "", ""
-		buyer, buyerclass, winner, subtype := "-", "全部", "-", "全部"
-		publishtime, region, industry, keys := "-", "全国", "全部", "-"
-		sc_money := ""
-		sc := new(dataexport.SieveCondition)
-		err := json.Unmarshal([]byte(filter), &sc)
-		if err == nil && sc != nil {
-			var keywordsMatchItemShowArr []string
-			for _, item := range strings.Split(sc.SelectType, ",") {
-				if item == "all" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "全部")
-				} else if item == "title" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "标题")
-				} else if item == "detail" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "正文")
-				} else if item == "mbuyer" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "采购单位")
-				} else if item == "mwinner" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "中标企业")
-				} else if item == "magency" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "招标代理机构")
-				} else if item == "filetext" {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "附件")
-				} else if strings.Contains(item, "purchasing") {
-					keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "项目名称/标的物")
-				}
-			}
-			if keywordsMatchItemShowArr != nil {
-				selectType = strings.Join(keywordsMatchItemShowArr, " ")
-			} else {
-				selectType = "标题"
-			}
-			//
-			if pay_time != "" {
-				pay_time = strings.Replace(pay_time, "-", ".", -1)
-				pay_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(pay_time, "")
-			}
-			sc_money = GetPriceDes_SieveCondition(sc.MinPrice, sc.MaxPrice)
-			pts := strings.Split(sc.PublishTime, "_")
-			if len(pts) == 2 {
-				startTime, endTime := qutil.Int64All(pts[0]), qutil.Int64All(pts[1])
-				if startTime != 0 && endTime != 0 {
-					publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
-				} else if startTime == 0 && endTime != 0 {
-					publishtime = fmt.Sprintf("%s前全部", FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
-				} else if startTime != 0 && endTime == 0 {
-					publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), create_time[:10])
-				}
-			}
-			//超级搜索页面 筛选区域为 area           没有region    移动端数据导出改
-			if sc.Region == nil {
-				showAll := append(sc.Area, sc.City...)
-				region = strings.Join(showAll, " ")
-			} else {
-				region = strings.Join(sc.Region, " ")
-			}
-			if region == "" {
-				region = "全国"
-			}
-			var industryBuffer bytes.Buffer
-			for k, v := range sc.Industry {
-				if k > 0 {
-					industryBuffer.WriteString(" ")
-				}
-				vs := strings.Split(v, "_")
-				if len(vs) == 1 {
-					industryBuffer.WriteString(vs[0])
-				} else {
-					industryBuffer.WriteString(vs[1])
-				}
-			}
-			if len(sc.Industry) > 0 {
-				industry = industryBuffer.String()
-			}
-			var keysBuffer bytes.Buffer
-			for _, v := range sc.Keyword {
-				keysBuffer.WriteString(fmt.Sprintf(config.ExConf.Mail_attach_content_key, v.Keyword, strings.Join(v.Appended, " "), strings.Join(v.Exclude, " ")))
-			}
-			if keysBuffer.String() != "" {
-				keys = keysBuffer.String()
-			}
-			if len(sc.Buyer) > 0 {
-				buyer = strings.Join(sc.Buyer, " ")
-			}
-			if len(sc.Buyerclass) > 0 {
-				buyerclass = strings.Join(sc.Buyerclass, " ")
-			}
-			if len(sc.Winner) > 0 {
-				winner = strings.Join(sc.Winner, " ")
-			}
-			if sc.Subtype != "" {
-				subtype = strings.Replace(sc.Subtype, ",", " ", -1)
-			}
-		} else {
-			log.Println("用户筛选条件错误", err, sc)
-		}
-		mail_title = "剑鱼标讯历史数据订单【" + order_code + "】,请查收"
-		mailcontent = fmt.Sprintf(config.ExConf.Mail_order_finance_content, order_code, create_time, pay_time, product_type, isShowTransaction, pay_way, transaction_id, data_spec, data_count, order_money, user_mail, user_phone, publishtime, region, industry, buyerclass, keys, selectType, sc_money, subtype, buyer, winner)
-	} else {
-		//申请发票
-		pay_time = qutil.ObjToString((*order)["pay_time"])
-		if pay_time != "" {
-			pay_time = strings.Replace(pay_time, "-", ".", -1)
-			pay_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(pay_time, "")
-		}
-		applybill_type := qutil.IntAll((*order)["applybill_type"])
-		bill_title := "个人"
-		bill_company := ""
-		bill_taxnum := ""
-		company_flag := "none"
-		taxnum_flag := "none"
-		if applybill_type != 0 {
-			bill_title = "单位"
-			bill_company = qutil.ObjToString((*order)["applybill_company"])
-			bill_taxnum = qutil.ObjToString((*order)["applybill_taxnum"])
-			company_flag = "flex"
-			taxnum_flag = "flex"
-		}
-		//线下支付获取凭证照片
-		offlineImgSrc := ""
-		if (*order)["pay_way"] == "线下支付" {
-			offlinePayMap := map[string]interface{}{}
-			offlinePayMap["out_trade_no"] = (*order)["out_trade_no"]
-			offlinePay := util.Mysql.FindOne("offline_pay", offlinePayMap, "", "create_time desc")
-			if imgs := qutil.ObjToString((*offlinePay)["img_src"]); imgs != "" {
-				ImgArr := strings.Split(imgs, ",")
-				offlineImgSrc = "<p style='margin: 0px 0px 1px; font-size: 14px; color: rgb(29, 29, 29);'>线下支付凭证:%s</p>"
-				for k, v := range ImgArr {
-					var add = ",%s"
-					if k == len(ImgArr)-1 {
-						add = ""
-					}
-					pz := fmt.Sprintf("<a href='%s'>凭证%d</a>%s", config.ExConf.Qmxdomain+v, k+1, add)
-					offlineImgSrc = fmt.Sprintf(offlineImgSrc, pz)
-				}
-			}
-		}
-		//历史数据导出
-		if product_type == "历史数据导出" {
-			mail_title = "电子发票申请,剑鱼标讯历史数据订单【" + order_code + "】,请查收"
-			mailcontent = fmt.Sprintf(config.ExConf.Mail_invoice_finance_content, bill_title, company_flag, bill_company, taxnum_flag, bill_taxnum, order_code, create_time, pay_time, product_type, isShowTransaction, pay_way, transaction_id, offlineImgSrc, data_spec, data_count, order_money, user_mail, user_phone)
-		} else if product_type == "VIP订阅导出" {
-			user_email := ""
-			user_id := qutil.ObjToString((*order)["user_id"])
-			res, _ := util.MQFW.FindOne("user", bson.M{"_id": StringTOBsonId(user_id)})
-			if len(*res) > 0 {
-				if qutil.ObjToString((*res)["s_myemail"]) != "" {
-					user_email = qutil.ObjToString((*res)["s_myemail"])
-				}
-			}
-			//vip开发票内容
-			subscription_area, industry, subscription_cycle, effective_date, payment_number := "", "", "", "", ""
-			display_a, display_b, display_c := "none", "none", "none" //a:正常购买 b:续费 c:升级
-			city_count, province_count := 0, 0
-			filter := qutil.ObjToString((*order)["filter"])
-			vip_starttime := qutil.ObjToString((*order)["vip_starttime"])
-			vip_endtime := qutil.ObjToString((*order)["vip_endtime"])
-			payment_number = getPayTransactionId(qutil.ObjToString((*order)["pay_way"]), qutil.ObjToString((*order)["out_trade_no"]))
-			vip_type := qutil.Int64All((*order)["vip_type"]) //判断 续费 升级订单
-			vf := new(VipFilter)
-			err := json.Unmarshal([]byte(filter), &vf)
-			if err == nil && vf != nil {
-				newbuyset := vf.NewBuyset //如果newBuyset存在  则为<续费升级逻辑更新>之后的订单 (否则为老订单)
-				if vip_type == 2 {        //升级查新订单
-					if newbuyset != nil {
-						subscription_area, industry = newbuysetConversion(newbuyset)
-					} else {
-						addareacount := vf.Addareacount             //区域数量
-						addbuyerclasscount := vf.Addbuyerclasscount //行业数量
-						if len(addareacount) != 0 {
-							province_count = qutil.IntAll((addareacount)["province"])
-							city_count = qutil.IntAll((addareacount)["city"])
-							//升级区域显示
-							if city_count != 0 && province_count == 0 {
-								subscription_area = fmt.Sprintf("%d个地市", city_count)
-							} else if city_count == 0 && province_count != 0 {
-								subscription_area = fmt.Sprintf("%d个省级区域", province_count)
-							} else if city_count != 0 && province_count != 0 {
-								subscription_area = fmt.Sprintf("%d个省级区域、%d个地市", province_count, city_count)
-							} else if city_count == 0 && province_count == 0 {
-								subscription_area = "全国"
-							}
-						} else {
-							subscription_area = "无"
-						}
-						//升级行业显示
-						industry = fmt.Sprintf("%d个行业", addbuyerclasscount)
-						if addbuyerclasscount == 0 {
-							industry = "无"
-						}
-						if addbuyerclasscount == -1 {
-							industry = "全行业"
-						}
-					}
-				} else if vip_type == 1 { //续费
-					if newbuyset != nil {
-						subscription_area, industry = newbuysetConversion(newbuyset)
-					} else {
-						buyset_r := vf.Buyset
-						if buyset_r != nil {
-							province_count = qutil.IntAll(buyset_r["areacount"])
-							buyerclasscount := qutil.IntAll(buyset_r["buyerclasscount"])
-							citys := qutil.ObjToMap(buyset_r["citys"])
-							if citys != nil {
-								for _, v := range *citys {
-									city_count += qutil.IntAll(v)
-								}
-							}
-							if city_count != 0 && province_count != 0 {
-								subscription_area = fmt.Sprintf("%d个省级区域、%d个地市", province_count, city_count)
-							} else if city_count == 0 && province_count != 0 {
-								subscription_area = fmt.Sprintf("%d个省级区域", province_count)
-							} else if city_count != 0 && province_count == 0 {
-								subscription_area = fmt.Sprintf("%d个地市", city_count)
-							}
-							if province_count == -1 {
-								subscription_area = "全国"
-							}
-							if buyerclasscount == -1 {
-								industry = "全行业"
-							} else {
-								industry = fmt.Sprintf("%d个行业", buyerclasscount)
-							}
-						}
-					}
-				} else { //非升级
-					if newbuyset != nil {
-						subscription_area, industry = newbuysetConversion(newbuyset)
-					} else {
-						vip_area := vf.Area    //区域
-						vip_ind := vf.Industry //行业
-						nbs := JyVipSubStruct.NewBuySet(&vip_area, vip_ind, qutil.IntAll(vf.NewBuyset["upgrade"]) == 1)
-						if nbs != nil {
-							if nbs.NewCitys != nil {
-								for _, v := range nbs.NewCitys {
-									city_count += v
-								}
-							}
-							//订阅区域
-							if nbs.AreaCount == -1 {
-								subscription_area = "全国"
-							} else {
-								if city_count != 0 && nbs.AreaCount == 0 {
-									subscription_area = fmt.Sprintf("%d个地市", city_count)
-								} else if city_count == 0 && nbs.AreaCount != 0 {
-									subscription_area = fmt.Sprintf("%d个省级区域", nbs.AreaCount)
-								} else if city_count != 0 && nbs.AreaCount != 0 {
-									subscription_area = fmt.Sprintf("%d个省级区域、%d个地市", nbs.AreaCount, city_count)
-								}
-							}
-							//行业
-							if nbs.BuyerclassCount != -1 {
-								industry = fmt.Sprintf("%d个行业", nbs.BuyerclassCount)
-							} else {
-								industry = "全行业"
-							}
-						}
-					}
-				}
+    if transaction_id == "" {
+        transaction_id = func() string {
+            table := ""
+            if pay_way == "微信" {
+                table = "weixin_pay"
+            } else if pay_way == "支付宝" {
+                table = "ali_pay"
+            } else {
+                return ""
+            }
+            out_trade_no := qutil.ObjToString((*order)["out_trade_no"])
+            wxpaydata := util.Mysql.FindOne(table, map[string]interface{}{
+                "out_trade_no": out_trade_no,
+            }, "transaction_id", "")
+            if wxpaydata != nil && len(*wxpaydata) > 0 { //线下支付没有微信订单编号
+                return qutil.ObjToString((*wxpaydata)["transaction_id"])
+            }
+            return ""
+        }()
+    }
+    isShowTransaction := "" //支付订单号为空,邮件不显示此字段
+    if transaction_id == "" {
+        isShowTransaction = "none"
+    }
+    mailcontent := ""
+    var mail_title = ""
+    selectType := ""
+    if mailType == 1 { //支付完成后给北京财务发送导出数据接口信息的邮件
+        filter := qutil.ObjToString((*order)["filter"])
+        // buyer, buyerclass, winner, subtype := "", "", "", ""
+        // publishtime, region, industry, keys := "", "", "", ""
+        buyer, buyerclass, winner, subtype := "-", "全部", "-", "全部"
+        publishtime, region, industry, keys := "-", "全国", "全部", "-"
+        sc_money := ""
+        sc := new(dataexport.SieveCondition)
+        err := json.Unmarshal([]byte(filter), &sc)
+        if err == nil && sc != nil {
+            var keywordsMatchItemShowArr []string
+            for _, item := range strings.Split(sc.SelectType, ",") {
+                if item == "all" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "全部")
+                } else if item == "title" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "标题")
+                } else if item == "detail" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "正文")
+                } else if item == "mbuyer" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "采购单位")
+                } else if item == "mwinner" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "中标企业")
+                } else if item == "magency" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "招标代理机构")
+                } else if item == "filetext" {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "附件")
+                } else if strings.Contains(item, "purchasing") {
+                    keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "项目名称/标的物")
+                }
+            }
+            if keywordsMatchItemShowArr != nil {
+                selectType = strings.Join(keywordsMatchItemShowArr, " ")
+            } else {
+                selectType = "标题"
+            }
+            //
+            if pay_time != "" {
+                pay_time = strings.Replace(pay_time, "-", ".", -1)
+                pay_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(pay_time, "")
+            }
+            sc_money = GetPriceDes_SieveCondition(sc.MinPrice, sc.MaxPrice)
+            pts := strings.Split(sc.PublishTime, "_")
+            if len(pts) == 2 {
+                startTime, endTime := qutil.Int64All(pts[0]), qutil.Int64All(pts[1])
+                if startTime != 0 && endTime != 0 {
+                    publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
+                } else if startTime == 0 && endTime != 0 {
+                    publishtime = fmt.Sprintf("%s前全部", FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
+                } else if startTime != 0 && endTime == 0 {
+                    publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), create_time[:10])
+                }
+            }
+            //超级搜索页面 筛选区域为 area           没有region    移动端数据导出改
+            if sc.Region == nil {
+                showAll := append(sc.Area, sc.City...)
+                region = strings.Join(showAll, " ")
+            } else {
+                region = strings.Join(sc.Region, " ")
+            }
+            if region == "" {
+                region = "全国"
+            }
+            var industryBuffer bytes.Buffer
+            for k, v := range sc.Industry {
+                if k > 0 {
+                    industryBuffer.WriteString(" ")
+                }
+                vs := strings.Split(v, "_")
+                if len(vs) == 1 {
+                    industryBuffer.WriteString(vs[0])
+                } else {
+                    industryBuffer.WriteString(vs[1])
+                }
+            }
+            if len(sc.Industry) > 0 {
+                industry = industryBuffer.String()
+            }
+            var keysBuffer bytes.Buffer
+            for _, v := range sc.Keyword {
+                keysBuffer.WriteString(fmt.Sprintf(config.ExConf.Mail_attach_content_key, v.Keyword, strings.Join(v.Appended, " "), strings.Join(v.Exclude, " ")))
+            }
+            if keysBuffer.String() != "" {
+                keys = keysBuffer.String()
+            }
+            if len(sc.Buyer) > 0 {
+                buyer = strings.Join(sc.Buyer, " ")
+            }
+            if len(sc.Buyerclass) > 0 {
+                buyerclass = strings.Join(sc.Buyerclass, " ")
+            }
+            if len(sc.Winner) > 0 {
+                winner = strings.Join(sc.Winner, " ")
+            }
+            if sc.Subtype != "" {
+                subtype = strings.Replace(sc.Subtype, ",", " ", -1)
+            }
+        } else {
+            log.Println("用户筛选条件错误", err, sc)
+        }
+        mail_title = "剑鱼标讯历史数据订单【" + order_code + "】,请查收"
+        mailcontent = fmt.Sprintf(config.ExConf.Mail_order_finance_content, order_code, create_time, pay_time, product_type, isShowTransaction, pay_way, transaction_id, data_spec, data_count, order_money, user_mail, user_phone, publishtime, region, industry, buyerclass, keys, selectType, sc_money, subtype, buyer, winner)
+    } else {
+        //申请发票
+        pay_time = qutil.ObjToString((*order)["pay_time"])
+        if pay_time != "" {
+            pay_time = strings.Replace(pay_time, "-", ".", -1)
+            pay_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(pay_time, "")
+        }
+        applybill_type := qutil.IntAll((*order)["applybill_type"])
+        bill_title := "个人"
+        bill_company := ""
+        bill_taxnum := ""
+        company_flag := "none"
+        taxnum_flag := "none"
+        if applybill_type != 0 {
+            bill_title = "单位"
+            bill_company = qutil.ObjToString((*order)["applybill_company"])
+            bill_taxnum = qutil.ObjToString((*order)["applybill_taxnum"])
+            company_flag = "flex"
+            taxnum_flag = "flex"
+        }
+        //线下支付获取凭证照片
+        offlineImgSrc := ""
+        if (*order)["pay_way"] == "线下支付" {
+            offlinePayMap := map[string]interface{}{}
+            offlinePayMap["out_trade_no"] = (*order)["out_trade_no"]
+            offlinePay := util.Mysql.FindOne("offline_pay", offlinePayMap, "", "create_time desc")
+            if imgs := qutil.ObjToString((*offlinePay)["img_src"]); imgs != "" {
+                ImgArr := strings.Split(imgs, ",")
+                offlineImgSrc = "<p style='margin: 0px 0px 1px; font-size: 14px; color: rgb(29, 29, 29);'>线下支付凭证:%s</p>"
+                for k, v := range ImgArr {
+                    var add = ",%s"
+                    if k == len(ImgArr)-1 {
+                        add = ""
+                    }
+                    pz := fmt.Sprintf("<a href='%s'>凭证%d</a>%s", config.ExConf.Qmxdomain+v, k+1, add)
+                    offlineImgSrc = fmt.Sprintf(offlineImgSrc, pz)
+                }
+            }
+        }
+        //历史数据导出
+        if product_type == "历史数据导出" {
+            mail_title = "电子发票申请,剑鱼标讯历史数据订单【" + order_code + "】,请查收"
+            mailcontent = fmt.Sprintf(config.ExConf.Mail_invoice_finance_content, bill_title, company_flag, bill_company, taxnum_flag, bill_taxnum, order_code, create_time, pay_time, product_type, isShowTransaction, pay_way, transaction_id, offlineImgSrc, data_spec, data_count, order_money, user_mail, user_phone)
+        } else if product_type == "VIP订阅导出" {
+            user_email := ""
+            user_id := qutil.ObjToString((*order)["user_id"])
+            res := util.Compatible.Select(user_id, `{"s_myemail":1}`)
+            if len(*res) > 0 {
+                if qutil.ObjToString((*res)["s_myemail"]) != "" {
+                    user_email = qutil.ObjToString((*res)["s_myemail"])
+                }
+            }
+            //vip开发票内容
+            subscription_area, industry, subscription_cycle, effective_date, payment_number := "", "", "", "", ""
+            display_a, display_b, display_c := "none", "none", "none" //a:正常购买 b:续费 c:升级
+            city_count, province_count := 0, 0
+            filter := qutil.ObjToString((*order)["filter"])
+            vip_starttime := qutil.ObjToString((*order)["vip_starttime"])
+            vip_endtime := qutil.ObjToString((*order)["vip_endtime"])
+            payment_number = getPayTransactionId(qutil.ObjToString((*order)["pay_way"]), qutil.ObjToString((*order)["out_trade_no"]))
+            vip_type := qutil.Int64All((*order)["vip_type"]) //判断 续费 升级订单
+            vf := new(VipFilter)
+            err := json.Unmarshal([]byte(filter), &vf)
+            if err == nil && vf != nil {
+                newbuyset := vf.NewBuyset //如果newBuyset存在  则为<续费升级逻辑更新>之后的订单 (否则为老订单)
+                if vip_type == 2 {        //升级查新订单
+                    if newbuyset != nil {
+                        subscription_area, industry = newbuysetConversion(newbuyset)
+                    } else {
+                        addareacount := vf.Addareacount             //区域数量
+                        addbuyerclasscount := vf.Addbuyerclasscount //行业数量
+                        if len(addareacount) != 0 {
+                            province_count = qutil.IntAll((addareacount)["province"])
+                            city_count = qutil.IntAll((addareacount)["city"])
+                            //升级区域显示
+                            if city_count != 0 && province_count == 0 {
+                                subscription_area = fmt.Sprintf("%d个地市", city_count)
+                            } else if city_count == 0 && province_count != 0 {
+                                subscription_area = fmt.Sprintf("%d个省级区域", province_count)
+                            } else if city_count != 0 && province_count != 0 {
+                                subscription_area = fmt.Sprintf("%d个省级区域、%d个地市", province_count, city_count)
+                            } else if city_count == 0 && province_count == 0 {
+                                subscription_area = "全国"
+                            }
+                        } else {
+                            subscription_area = "无"
+                        }
+                        //升级行业显示
+                        industry = fmt.Sprintf("%d个行业", addbuyerclasscount)
+                        if addbuyerclasscount == 0 {
+                            industry = "无"
+                        }
+                        if addbuyerclasscount == -1 {
+                            industry = "全行业"
+                        }
+                    }
+                } else if vip_type == 1 { //续费
+                    if newbuyset != nil {
+                        subscription_area, industry = newbuysetConversion(newbuyset)
+                    } else {
+                        buyset_r := vf.Buyset
+                        if buyset_r != nil {
+                            province_count = qutil.IntAll(buyset_r["areacount"])
+                            buyerclasscount := qutil.IntAll(buyset_r["buyerclasscount"])
+                            citys := qutil.ObjToMap(buyset_r["citys"])
+                            if citys != nil {
+                                for _, v := range *citys {
+                                    city_count += qutil.IntAll(v)
+                                }
+                            }
+                            if city_count != 0 && province_count != 0 {
+                                subscription_area = fmt.Sprintf("%d个省级区域、%d个地市", province_count, city_count)
+                            } else if city_count == 0 && province_count != 0 {
+                                subscription_area = fmt.Sprintf("%d个省级区域", province_count)
+                            } else if city_count != 0 && province_count == 0 {
+                                subscription_area = fmt.Sprintf("%d个地市", city_count)
+                            }
+                            if province_count == -1 {
+                                subscription_area = "全国"
+                            }
+                            if buyerclasscount == -1 {
+                                industry = "全行业"
+                            } else {
+                                industry = fmt.Sprintf("%d个行业", buyerclasscount)
+                            }
+                        }
+                    }
+                } else { //非升级
+                    if newbuyset != nil {
+                        subscription_area, industry = newbuysetConversion(newbuyset)
+                    } else {
+                        vip_area := vf.Area    //区域
+                        vip_ind := vf.Industry //行业
+                        nbs := JyVipSubStruct.NewBuySet(&vip_area, vip_ind, qutil.IntAll(vf.NewBuyset["upgrade"]) == 1)
+                        if nbs != nil {
+                            if nbs.NewCitys != nil {
+                                for _, v := range nbs.NewCitys {
+                                    city_count += v
+                                }
+                            }
+                            //订阅区域
+                            if nbs.AreaCount == -1 {
+                                subscription_area = "全国"
+                            } else {
+                                if city_count != 0 && nbs.AreaCount == 0 {
+                                    subscription_area = fmt.Sprintf("%d个地市", city_count)
+                                } else if city_count == 0 && nbs.AreaCount != 0 {
+                                    subscription_area = fmt.Sprintf("%d个省级区域", nbs.AreaCount)
+                                } else if city_count != 0 && nbs.AreaCount != 0 {
+                                    subscription_area = fmt.Sprintf("%d个省级区域、%d个地市", nbs.AreaCount, city_count)
+                                }
+                            }
+                            //行业
+                            if nbs.BuyerclassCount != -1 {
+                                industry = fmt.Sprintf("%d个行业", nbs.BuyerclassCount)
+                            } else {
+                                industry = "全行业"
+                            }
+                        }
+                    }
+                }
 
-				// 订阅周期 有效日期
-				if vip_endtime != "" && vip_starttime != "" {
-					year := 0
-					month := 0
-					//订阅周期
-					vip_starttime_stamp, _ := time.ParseInLocation(Date_Full_Layout, vip_starttime, time.Local)
-					vip_endtime_stamp, _ := time.ParseInLocation(Date_Full_Layout, vip_endtime, time.Local)
-					start_year := time.Unix(qutil.Int64All(vip_starttime_stamp.Unix()), 0).Year()
-					end_year := time.Unix(qutil.Int64All(vip_endtime_stamp.Unix()), 0).Year()
-					start_month := int(time.Unix(qutil.Int64All(vip_starttime_stamp.Unix()), 0).Month())
-					end_month := int(time.Unix(qutil.Int64All(vip_endtime_stamp.Unix()), 0).Month())
-					if end_year > start_year {
-						if end_month > start_month {
-							year = end_year - start_year
-							month = end_month - start_month
-						} else {
-							year = end_year - start_year - 1
-							month = 12 + end_month - start_month
-							if month == 12 {
-								year++
-								month = 0
-							}
-						}
-					} else if end_year == start_year {
-						month = end_month - start_month
-					}
-					if vip_type != 2 {
-						if year == 0 && month > 0 {
-							subscription_cycle = fmt.Sprintf("%d个月", month)
-						} else if year > 0 && month > 0 {
-							subscription_cycle = fmt.Sprintf("%d年%d个月", year, month)
-						} else if year > 0 && month == 0 {
-							subscription_cycle = fmt.Sprintf("%d年", year)
-						}
-					} else {
-						if vf.Cycleunit == 1 {
-							subscription_cycle = fmt.Sprintf("%d年", vf.Cyclecount)
-						} else if vf.Cycleunit == 2 {
-							subscription_cycle = fmt.Sprintf("%d个月", vf.Cyclecount)
-						} else if vf.Cycleunit == -1 {
-							subscription_cycle = "不延期"
-						} else {
-							if year == 0 && month > 0 {
-								subscription_cycle = fmt.Sprintf("%d个月", month)
-							} else if year > 0 && month > 0 {
-								subscription_cycle = fmt.Sprintf("%d年%d个月", year, month)
-							} else if year > 0 && month == 0 {
-								subscription_cycle = fmt.Sprintf("%d年", year)
-							}
-						}
-						//升级续费后的根据 不延期 cycleunit,cyclecount=0,0
-						if vf.Cyclecount == 0 && vf.Cycleunit == 0 {
-							subscription_cycle = "不延期"
-						}
-					}
-					//有效日期
-					vip_starttime = strings.Replace(vip_starttime[0:10], "-", ".", -1)
-					vip_endtime = strings.Replace(vip_endtime[0:10], "-", ".", -1)
-					effective_date = fmt.Sprintf("%v-%v", vip_starttime, vip_endtime)
-				}
-			}
-			if vip_type == 1 {
-				product_type = "超级订阅(续费)"
-				display_b = "block"
-			} else if vip_type == 2 {
-				product_type = "超级订阅(升级)"
-				display_c = "block"
-			} else {
-				product_type = "超级订阅"
-				display_a = "block"
-			}
-			mail_title = "电子发票申请-[剑鱼标讯]VIP订阅(" + order_code + ")"
-			mailcontent = fmt.Sprintf(config.ExConf.Mail_vip_invoice_finance_content, bill_title, company_flag, bill_company, taxnum_flag, bill_taxnum, user_email, order_code, create_time, payment_number, pay_time, pay_way, product_type, pay_money, display_a, subscription_area, industry, subscription_cycle, display_b, subscription_area, industry, subscription_cycle, display_c, subscription_area, industry, subscription_cycle, effective_date)
-		} else if product_type == "企业商机管理导出" {
-			//邮箱
-			user_email := ""
-			user_id := qutil.ObjToString((*order)["user_id"])
-			res, _ := util.MQFW.FindOne("user", bson.M{"_id": StringTOBsonId(user_id)})
-			if len(*res) > 0 {
-				if qutil.ObjToString((*res)["s_myemail"]) != "" {
-					user_email = qutil.ObjToString((*res)["s_myemail"])
-				}
-			}
-			filter := qutil.ObjToString((*order)["filter"])
-			ent_filter := map[string]interface{}{}
-			err := json.Unmarshal([]byte(filter), &ent_filter)
-			entname, personnum, cycle := "", "", ""
-			if err == nil && ent_filter != nil {
-				entname = qutil.ObjToString(ent_filter["entname"])
-				personnum = strconv.Itoa(qutil.IntAll(ent_filter["personnum"])) + "人"
-				cycle = strconv.Itoa(qutil.IntAll(ent_filter["cycle"])) + "年"
-			}
-			display_a, display_b := "", ""
-			vip_type := qutil.Int64All((*order)["vip_type"]) //判断 续费
-			if vip_type == 1 {                               //续费
-				display_a = "none"
-			} else {
-				display_b = "none"
-			}
-			product_type = "企业商机管理"
-			payment_number := getPayTransactionId(qutil.ObjToString((*order)["pay_way"]), qutil.ObjToString((*order)["out_trade_no"]))
-			mail_title = "电子发票申请-[剑鱼标讯]企业商机管理(" + order_code + ")"
-			mailcontent = fmt.Sprintf(config.ExConf.Mail_ent_invoice_finance_content, bill_title, company_flag, bill_company, taxnum_flag, bill_taxnum, user_email, order_code, create_time, payment_number, pay_time, pay_way, product_type, pay_money, entname, personnum, display_a, cycle, display_b, cycle)
-		}
-	}
-	//发送邮件
-	for _, finance_mail := range config.ExConf.Finance_emails {
-		if regexp.MustCompile("^\\d+$").MatchString(finance_mail) {
-			continue
-		}
-		if finance_mail != "" {
-			finance_remark := "剑鱼标讯历史数据订单支付邮件"
-			if mailType == 2 {
-				finance_remark = "剑鱼标讯历史数据订单发票申请邮件"
-			}
-			if util.SendRetryMail(config.ExConf.Mail_retry, finance_mail, mail_title, mailcontent, "", nil, auth) {
-				log.Println(finance_mail, "北京财务:"+finance_remark+"发送成功!")
-			} else {
-				log.Println(finance_mail, "北京财务:"+finance_remark+"发送失败!")
-			}
+                // 订阅周期 有效日期
+                if vip_endtime != "" && vip_starttime != "" {
+                    year := 0
+                    month := 0
+                    //订阅周期
+                    vip_starttime_stamp, _ := time.ParseInLocation(Date_Full_Layout, vip_starttime, time.Local)
+                    vip_endtime_stamp, _ := time.ParseInLocation(Date_Full_Layout, vip_endtime, time.Local)
+                    start_year := time.Unix(qutil.Int64All(vip_starttime_stamp.Unix()), 0).Year()
+                    end_year := time.Unix(qutil.Int64All(vip_endtime_stamp.Unix()), 0).Year()
+                    start_month := int(time.Unix(qutil.Int64All(vip_starttime_stamp.Unix()), 0).Month())
+                    end_month := int(time.Unix(qutil.Int64All(vip_endtime_stamp.Unix()), 0).Month())
+                    if end_year > start_year {
+                        if end_month > start_month {
+                            year = end_year - start_year
+                            month = end_month - start_month
+                        } else {
+                            year = end_year - start_year - 1
+                            month = 12 + end_month - start_month
+                            if month == 12 {
+                                year++
+                                month = 0
+                            }
+                        }
+                    } else if end_year == start_year {
+                        month = end_month - start_month
+                    }
+                    if vip_type != 2 {
+                        if year == 0 && month > 0 {
+                            subscription_cycle = fmt.Sprintf("%d个月", month)
+                        } else if year > 0 && month > 0 {
+                            subscription_cycle = fmt.Sprintf("%d年%d个月", year, month)
+                        } else if year > 0 && month == 0 {
+                            subscription_cycle = fmt.Sprintf("%d年", year)
+                        }
+                    } else {
+                        if vf.Cycleunit == 1 {
+                            subscription_cycle = fmt.Sprintf("%d年", vf.Cyclecount)
+                        } else if vf.Cycleunit == 2 {
+                            subscription_cycle = fmt.Sprintf("%d个月", vf.Cyclecount)
+                        } else if vf.Cycleunit == -1 {
+                            subscription_cycle = "不延期"
+                        } else {
+                            if year == 0 && month > 0 {
+                                subscription_cycle = fmt.Sprintf("%d个月", month)
+                            } else if year > 0 && month > 0 {
+                                subscription_cycle = fmt.Sprintf("%d年%d个月", year, month)
+                            } else if year > 0 && month == 0 {
+                                subscription_cycle = fmt.Sprintf("%d年", year)
+                            }
+                        }
+                        //升级续费后的根据 不延期 cycleunit,cyclecount=0,0
+                        if vf.Cyclecount == 0 && vf.Cycleunit == 0 {
+                            subscription_cycle = "不延期"
+                        }
+                    }
+                    //有效日期
+                    vip_starttime = strings.Replace(vip_starttime[0:10], "-", ".", -1)
+                    vip_endtime = strings.Replace(vip_endtime[0:10], "-", ".", -1)
+                    effective_date = fmt.Sprintf("%v-%v", vip_starttime, vip_endtime)
+                }
+            }
+            if vip_type == 1 {
+                product_type = "超级订阅(续费)"
+                display_b = "block"
+            } else if vip_type == 2 {
+                product_type = "超级订阅(升级)"
+                display_c = "block"
+            } else {
+                product_type = "超级订阅"
+                display_a = "block"
+            }
+            mail_title = "电子发票申请-[剑鱼标讯]VIP订阅(" + order_code + ")"
+            mailcontent = fmt.Sprintf(config.ExConf.Mail_vip_invoice_finance_content, bill_title, company_flag, bill_company, taxnum_flag, bill_taxnum, user_email, order_code, create_time, payment_number, pay_time, pay_way, product_type, pay_money, display_a, subscription_area, industry, subscription_cycle, display_b, subscription_area, industry, subscription_cycle, display_c, subscription_area, industry, subscription_cycle, effective_date)
+        } else if product_type == "企业商机管理导出" {
+            //邮箱
+            user_email := ""
+            user_id := qutil.ObjToString((*order)["user_id"])
+            res := util.Compatible.Select(user_id, `{"s_myemail":1}`)
+            if len(*res) > 0 {
+                if qutil.ObjToString((*res)["s_myemail"]) != "" {
+                    user_email = qutil.ObjToString((*res)["s_myemail"])
+                }
+            }
+            filter := qutil.ObjToString((*order)["filter"])
+            ent_filter := map[string]interface{}{}
+            err := json.Unmarshal([]byte(filter), &ent_filter)
+            entname, personnum, cycle := "", "", ""
+            if err == nil && ent_filter != nil {
+                entname = qutil.ObjToString(ent_filter["entname"])
+                personnum = strconv.Itoa(qutil.IntAll(ent_filter["personnum"])) + "人"
+                cycle = strconv.Itoa(qutil.IntAll(ent_filter["cycle"])) + "年"
+            }
+            display_a, display_b := "", ""
+            vip_type := qutil.Int64All((*order)["vip_type"]) //判断 续费
+            if vip_type == 1 {                               //续费
+                display_a = "none"
+            } else {
+                display_b = "none"
+            }
+            product_type = "企业商机管理"
+            payment_number := getPayTransactionId(qutil.ObjToString((*order)["pay_way"]), qutil.ObjToString((*order)["out_trade_no"]))
+            mail_title = "电子发票申请-[剑鱼标讯]企业商机管理(" + order_code + ")"
+            mailcontent = fmt.Sprintf(config.ExConf.Mail_ent_invoice_finance_content, bill_title, company_flag, bill_company, taxnum_flag, bill_taxnum, user_email, order_code, create_time, payment_number, pay_time, pay_way, product_type, pay_money, entname, personnum, display_a, cycle, display_b, cycle)
+        }
+    }
+    //发送邮件
+    for _, finance_mail := range config.ExConf.Finance_emails {
+        if regexp.MustCompile("^\\d+$").MatchString(finance_mail) {
+            continue
+        }
+        if finance_mail != "" {
+            finance_remark := "剑鱼标讯历史数据订单支付邮件"
+            if mailType == 2 {
+                finance_remark = "剑鱼标讯历史数据订单发票申请邮件"
+            }
+            if util.SendRetryMail(config.ExConf.Mail_retry, finance_mail, mail_title, mailcontent, "", nil, auth) {
+                log.Println(finance_mail, "北京财务:"+finance_remark+"发送成功!")
+            } else {
+                log.Println(finance_mail, "北京财务:"+finance_remark+"发送失败!")
+            }
 
-		} else {
-			log.Println(finance_mail, "北京财务:邮件地址为空")
-		}
-	}
+        } else {
+            log.Println(finance_mail, "北京财务:邮件地址为空")
+        }
+    }
 }
 
 func GetPackDataExportMailContent(filterId, download_url string) (content string, err error) {
-	// buyer, buyerclass, winner, subtype := "", "", "", ""
-	// publishtime, region, industry, keys := "", "", "", ""
-	buyer, buyerclass, winner, subtype := "-", "全部", "-", "全部"
-	publishtime, region, industry, keys := "-", "全国", "全部", "-"
-	sc_money := ""
-	sc := dataexport.GetSqlObjFromId(util.MQFW, filterId)
-	keywordsMatchItemShow := ""
-	if sc != nil {
-		var keywordsMatchItemShowArr []string
-		for _, item := range strings.Split(sc.SelectType, ",") {
-			if item == "all" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "全部")
-			} else if item == "title" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "标题")
-			} else if item == "detail" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "正文")
-			} else if item == "mbuyer" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "采购单位")
-			} else if item == "mwinner" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "中标企业")
-			} else if item == "magency" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "招标代理机构")
-			} else if item == "filetext" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "附件")
-			} else if strings.Contains(item, "purchasing") {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "项目名称/标的物")
-			}
-		}
-		if keywordsMatchItemShowArr != nil {
-			keywordsMatchItemShow = strings.Join(keywordsMatchItemShowArr, " ")
-		} else {
-			keywordsMatchItemShow = "标题"                       //默认标题
-			if strings.Index(sc.Comeinfrom, "Portrait") > -1 { //画像导出默认为空
-				keywordsMatchItemShow = "-"
-			}
-		}
-		sc_money = GetPriceDes_SieveCondition(sc.MinPrice, sc.MaxPrice)
-		if pts := strings.Split(sc.PublishTime, "_"); len(pts) == 2 {
-			startTime, endTime := qutil.Int64All(pts[0]), qutil.Int64All(pts[1])
-			if startTime != 0 && endTime != 0 {
-				publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
-			} else if startTime == 0 && endTime != 0 {
-				publishtime = fmt.Sprintf("%s前全部", FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
-			} else if startTime != 0 && endTime == 0 {
-				publishtime = fmt.Sprintf("%s-现在", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point))
-			}
-		}
-		//超级搜索页面 筛选区域为 area           没有region    移动端数据导出改
-		if sc.Region == nil {
-			showAll := append(sc.Area, sc.City...)
-			region = strings.Join(showAll, " ")
-		} else {
-			region = strings.Join(sc.Region, " ")
-		}
-		if region == "" {
-			region = "全国"
-		}
-		var industryBuffer bytes.Buffer
-		for k, v := range sc.Industry {
-			if k > 0 {
-				industryBuffer.WriteString(" ")
-			}
-			vs := strings.Split(v, "_")
-			if len(vs) == 1 {
-				industryBuffer.WriteString(vs[0])
-			} else {
-				industryBuffer.WriteString(vs[1])
-			}
-		}
-		// industry = industryBuffer.String()
-		if len(sc.Industry) > 0 {
-			industry = industryBuffer.String()
-		}
-		var keysBuffer bytes.Buffer
-		for _, v := range sc.Keyword {
-			keysBuffer.WriteString(fmt.Sprintf(config.ExConf.Mail_attach_content_key, v.Keyword, strings.Join(v.Appended, " "), strings.Join(v.Exclude, " ")))
-		}
-		// keys = keysBuffer.String()
-		// buyer = strings.Join(sc.Buyer, " ")
-		// buyerclass = strings.Join(sc.Buyerclass, " ")
-		// winner = strings.Join(sc.Winner, " ")
-		// subtype = strings.Replace(sc.Subtype, ",", " ", -1)
-		if keysBuffer.String() != "" {
-			keys = keysBuffer.String()
-		}
-		if len(sc.Buyer) > 0 {
-			buyer = strings.Join(sc.Buyer, " ")
-		}
-		if len(sc.Buyerclass) > 0 {
-			buyerclass = strings.Join(sc.Buyerclass, " ")
-		}
-		if len(sc.Winner) > 0 {
-			winner = strings.Join(sc.Winner, " ")
-		}
-		if sc.Subtype != "" {
-			subtype = strings.Replace(sc.Subtype, ",", " ", -1)
-		}
-	} else {
-		log.Println("用户筛选条件错误", err, sc)
-	}
-	// orderCode, create_time, pay_time, product_type, data_spec, data_count, order_money, user_mail, user_phone,
-	content = fmt.Sprintf(config.ExConf.Mail_attach_pack_content, download_url, publishtime, region, industry, buyerclass, keys, keywordsMatchItemShow, sc_money, subtype, buyer, winner)
-	return content, nil
+    // buyer, buyerclass, winner, subtype := "", "", "", ""
+    // publishtime, region, industry, keys := "", "", "", ""
+    buyer, buyerclass, winner, subtype := "-", "全部", "-", "全部"
+    publishtime, region, industry, keys := "-", "全国", "全部", "-"
+    sc_money := ""
+    sc := dataexport.GetSqlObjFromId(util.MQFW, filterId)
+    keywordsMatchItemShow := ""
+    if sc != nil {
+        var keywordsMatchItemShowArr []string
+        for _, item := range strings.Split(sc.SelectType, ",") {
+            if item == "all" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "全部")
+            } else if item == "title" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "标题")
+            } else if item == "detail" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "正文")
+            } else if item == "mbuyer" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "采购单位")
+            } else if item == "mwinner" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "中标企业")
+            } else if item == "magency" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "招标代理机构")
+            } else if item == "filetext" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "附件")
+            } else if strings.Contains(item, "purchasing") {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "项目名称/标的物")
+            }
+        }
+        if keywordsMatchItemShowArr != nil {
+            keywordsMatchItemShow = strings.Join(keywordsMatchItemShowArr, " ")
+        } else {
+            keywordsMatchItemShow = "标题"                       //默认标题
+            if strings.Index(sc.Comeinfrom, "Portrait") > -1 { //画像导出默认为空
+                keywordsMatchItemShow = "-"
+            }
+        }
+        sc_money = GetPriceDes_SieveCondition(sc.MinPrice, sc.MaxPrice)
+        if pts := strings.Split(sc.PublishTime, "_"); len(pts) == 2 {
+            startTime, endTime := qutil.Int64All(pts[0]), qutil.Int64All(pts[1])
+            if startTime != 0 && endTime != 0 {
+                publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
+            } else if startTime == 0 && endTime != 0 {
+                publishtime = fmt.Sprintf("%s前全部", FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
+            } else if startTime != 0 && endTime == 0 {
+                publishtime = fmt.Sprintf("%s-现在", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point))
+            }
+        }
+        //超级搜索页面 筛选区域为 area           没有region    移动端数据导出改
+        if sc.Region == nil {
+            showAll := append(sc.Area, sc.City...)
+            region = strings.Join(showAll, " ")
+        } else {
+            region = strings.Join(sc.Region, " ")
+        }
+        if region == "" {
+            region = "全国"
+        }
+        var industryBuffer bytes.Buffer
+        for k, v := range sc.Industry {
+            if k > 0 {
+                industryBuffer.WriteString(" ")
+            }
+            vs := strings.Split(v, "_")
+            if len(vs) == 1 {
+                industryBuffer.WriteString(vs[0])
+            } else {
+                industryBuffer.WriteString(vs[1])
+            }
+        }
+        // industry = industryBuffer.String()
+        if len(sc.Industry) > 0 {
+            industry = industryBuffer.String()
+        }
+        var keysBuffer bytes.Buffer
+        for _, v := range sc.Keyword {
+            keysBuffer.WriteString(fmt.Sprintf(config.ExConf.Mail_attach_content_key, v.Keyword, strings.Join(v.Appended, " "), strings.Join(v.Exclude, " ")))
+        }
+        // keys = keysBuffer.String()
+        // buyer = strings.Join(sc.Buyer, " ")
+        // buyerclass = strings.Join(sc.Buyerclass, " ")
+        // winner = strings.Join(sc.Winner, " ")
+        // subtype = strings.Replace(sc.Subtype, ",", " ", -1)
+        if keysBuffer.String() != "" {
+            keys = keysBuffer.String()
+        }
+        if len(sc.Buyer) > 0 {
+            buyer = strings.Join(sc.Buyer, " ")
+        }
+        if len(sc.Buyerclass) > 0 {
+            buyerclass = strings.Join(sc.Buyerclass, " ")
+        }
+        if len(sc.Winner) > 0 {
+            winner = strings.Join(sc.Winner, " ")
+        }
+        if sc.Subtype != "" {
+            subtype = strings.Replace(sc.Subtype, ",", " ", -1)
+        }
+    } else {
+        log.Println("用户筛选条件错误", err, sc)
+    }
+    // orderCode, create_time, pay_time, product_type, data_spec, data_count, order_money, user_mail, user_phone,
+    content = fmt.Sprintf(config.ExConf.Mail_attach_pack_content, download_url, publishtime, region, industry, buyerclass, keys, keywordsMatchItemShow, sc_money, subtype, buyer, winner)
+    return content, nil
 }
 
 // 获取邮件内容
 func GetDataExportMailContent(orderCode string) (content string, err error) {
-	orderData := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-		"order_code": orderCode,
-	}, "", "")
-	if orderData == nil || len(*orderData) == 0 {
-		return "", fmt.Errorf("%s查询订单内容出错", orderCode)
-	}
-	user_phone := qutil.ObjToString((*orderData)["user_phone"])
-	user_mail := qutil.ObjToString((*orderData)["user_mail"])
-	data_spec := qutil.ObjToString((*orderData)["data_spec"])
-	data_count := qutil.IntAll((*orderData)["data_count"])
-	filter := qutil.ObjToString((*orderData)["filter"])
-	product_type := qutil.ObjToString((*orderData)["product_type"]) + "导出"
-	order_money := qutil.Float64All((*orderData)["order_money"]) / 100
-	pay_time := qutil.ObjToString((*orderData)["pay_time"])
-	download_url := config.Config.WebDomain + qutil.ObjToString((*orderData)["download_url"])
+    orderData := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+        "order_code": orderCode,
+    }, "", "")
+    if orderData == nil || len(*orderData) == 0 {
+        return "", fmt.Errorf("%s查询订单内容出错", orderCode)
+    }
+    user_phone := qutil.ObjToString((*orderData)["user_phone"])
+    user_mail := qutil.ObjToString((*orderData)["user_mail"])
+    data_spec := qutil.ObjToString((*orderData)["data_spec"])
+    data_count := qutil.IntAll((*orderData)["data_count"])
+    filter := qutil.ObjToString((*orderData)["filter"])
+    product_type := qutil.ObjToString((*orderData)["product_type"]) + "导出"
+    order_money := qutil.Float64All((*orderData)["order_money"]) / 100
+    pay_time := qutil.ObjToString((*orderData)["pay_time"])
+    download_url := config.Config.WebDomain + qutil.ObjToString((*orderData)["download_url"])
 
-	create_time := qutil.ObjToString((*orderData)["create_time"])
-	if create_time != "" {
-		create_time = strings.Replace(create_time, "-", ".", -1)
-		create_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(create_time, "")
-	}
-	buyer, buyerclass, winner, subtype := "-", "全部", "-", "全部"
-	publishtime, region, industry, keys := "-", "全国", "全部", "-"
-	sc_money := "-"
-	sc := new(dataexport.SieveCondition)
-	err = json.Unmarshal([]byte(filter), &sc)
-	if err != nil {
-		return "", err
-	}
-	keywordsMatchItemShow := ""
-	if sc != nil {
-		var keywordsMatchItemShowArr []string
-		for _, item := range strings.Split(sc.SelectType, ",") {
-			if item == "all" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "全部")
-			} else if item == "title" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "标题")
-			} else if item == "detail" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "正文")
-			} else if item == "mbuyer" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "采购单位")
-			} else if item == "mwinner" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "中标企业")
-			} else if item == "magency" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "招标代理机构")
-			} else if item == "filetext" {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "附件")
-			} else if strings.Contains(item, "purchasing") {
-				keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "项目名称/标的物")
-			}
-		}
-		if keywordsMatchItemShowArr != nil {
-			keywordsMatchItemShow = strings.Join(keywordsMatchItemShowArr, " ")
-		} else {
-			keywordsMatchItemShow = "标题"                       //默认标题
-			if strings.Index(sc.Comeinfrom, "Portrait") > -1 { //画像导出默认为空
-				keywordsMatchItemShow = "-"
-			}
-		}
-		//
-		if pay_time != "" {
-			pay_time = strings.Replace(pay_time, "-", ".", -1)
-			pay_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(pay_time, "")
-		}
-		sc_money = GetPriceDes_SieveCondition(sc.MinPrice, sc.MaxPrice)
-		pts := strings.Split(sc.PublishTime, "_")
-		if len(pts) == 2 {
-			startTime, endTime := qutil.Int64All(pts[0]), qutil.Int64All(pts[1])
-			if startTime != 0 && endTime != 0 {
-				publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
-			} else if startTime == 0 && endTime != 0 {
-				publishtime = fmt.Sprintf("%s前全部", FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
-			} else if startTime != 0 && endTime == 0 {
-				publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), create_time[:10])
-			}
-		}
-		//超级搜索页面 筛选区域为 area           没有region    移动端数据导出改
-		if sc.Region == nil {
-			showAll := append(sc.Area, sc.City...)
-			region = strings.Join(showAll, " ")
-		} else {
-			region = strings.Join(sc.Region, " ")
-		}
-		if region == "" {
-			region = "全国"
-		}
-		var industryBuffer bytes.Buffer
-		for k, v := range sc.Industry {
-			if k > 0 {
-				industryBuffer.WriteString(" ")
-			}
-			vs := strings.Split(v, "_")
-			if len(vs) == 1 {
-				industryBuffer.WriteString(vs[0])
-			} else {
-				industryBuffer.WriteString(vs[1])
-			}
-		}
-		if len(sc.Industry) > 0 {
-			industry = industryBuffer.String()
-		}
-		var keysBuffer bytes.Buffer
-		for _, v := range sc.Keyword {
-			keysBuffer.WriteString(fmt.Sprintf(config.ExConf.Mail_attach_content_key, v.Keyword, strings.Join(v.Appended, " "), strings.Join(v.Exclude, " ")))
-		}
-		if keysBuffer.String() != "" {
-			keys = keysBuffer.String()
-		}
-		if len(sc.Buyer) > 0 {
-			buyer = strings.Join(sc.Buyer, " ")
-		}
-		if len(sc.Buyerclass) > 0 {
-			buyerclass = strings.Join(sc.Buyerclass, " ")
-		}
-		if len(sc.Winner) > 0 {
-			winner = strings.Join(sc.Winner, " ")
-		}
-		if sc.Subtype != "" {
-			subtype = strings.Replace(sc.Subtype, ",", " ", -1)
-		}
-	} else {
-		log.Println("用户筛选条件错误", err, sc)
-	}
-	content = fmt.Sprintf(config.ExConf.Mail_attach_content, download_url, orderCode, create_time, pay_time, product_type, data_spec, data_count, order_money, user_mail, user_phone, publishtime, region, industry, buyerclass, keys, keywordsMatchItemShow, sc_money, subtype, buyer, winner)
-	return content, nil
+    create_time := qutil.ObjToString((*orderData)["create_time"])
+    if create_time != "" {
+        create_time = strings.Replace(create_time, "-", ".", -1)
+        create_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(create_time, "")
+    }
+    buyer, buyerclass, winner, subtype := "-", "全部", "-", "全部"
+    publishtime, region, industry, keys := "-", "全国", "全部", "-"
+    sc_money := "-"
+    sc := new(dataexport.SieveCondition)
+    err = json.Unmarshal([]byte(filter), &sc)
+    if err != nil {
+        return "", err
+    }
+    keywordsMatchItemShow := ""
+    if sc != nil {
+        var keywordsMatchItemShowArr []string
+        for _, item := range strings.Split(sc.SelectType, ",") {
+            if item == "all" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "全部")
+            } else if item == "title" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "标题")
+            } else if item == "detail" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "正文")
+            } else if item == "mbuyer" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "采购单位")
+            } else if item == "mwinner" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "中标企业")
+            } else if item == "magency" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "招标代理机构")
+            } else if item == "filetext" {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "附件")
+            } else if strings.Contains(item, "purchasing") {
+                keywordsMatchItemShowArr = append(keywordsMatchItemShowArr, "项目名称/标的物")
+            }
+        }
+        if keywordsMatchItemShowArr != nil {
+            keywordsMatchItemShow = strings.Join(keywordsMatchItemShowArr, " ")
+        } else {
+            keywordsMatchItemShow = "标题"                       //默认标题
+            if strings.Index(sc.Comeinfrom, "Portrait") > -1 { //画像导出默认为空
+                keywordsMatchItemShow = "-"
+            }
+        }
+        //
+        if pay_time != "" {
+            pay_time = strings.Replace(pay_time, "-", ".", -1)
+            pay_time = regexp.MustCompile(":[^:]+$").ReplaceAllString(pay_time, "")
+        }
+        sc_money = GetPriceDes_SieveCondition(sc.MinPrice, sc.MaxPrice)
+        pts := strings.Split(sc.PublishTime, "_")
+        if len(pts) == 2 {
+            startTime, endTime := qutil.Int64All(pts[0]), qutil.Int64All(pts[1])
+            if startTime != 0 && endTime != 0 {
+                publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
+            } else if startTime == 0 && endTime != 0 {
+                publishtime = fmt.Sprintf("%s前全部", FormatDateByInt64(&endTime, Date_yyyyMMdd_Point))
+            } else if startTime != 0 && endTime == 0 {
+                publishtime = fmt.Sprintf("%s-%s", FormatDateByInt64(&startTime, Date_yyyyMMdd_Point), create_time[:10])
+            }
+        }
+        //超级搜索页面 筛选区域为 area           没有region    移动端数据导出改
+        if sc.Region == nil {
+            showAll := append(sc.Area, sc.City...)
+            region = strings.Join(showAll, " ")
+        } else {
+            region = strings.Join(sc.Region, " ")
+        }
+        if region == "" {
+            region = "全国"
+        }
+        var industryBuffer bytes.Buffer
+        for k, v := range sc.Industry {
+            if k > 0 {
+                industryBuffer.WriteString(" ")
+            }
+            vs := strings.Split(v, "_")
+            if len(vs) == 1 {
+                industryBuffer.WriteString(vs[0])
+            } else {
+                industryBuffer.WriteString(vs[1])
+            }
+        }
+        if len(sc.Industry) > 0 {
+            industry = industryBuffer.String()
+        }
+        var keysBuffer bytes.Buffer
+        for _, v := range sc.Keyword {
+            keysBuffer.WriteString(fmt.Sprintf(config.ExConf.Mail_attach_content_key, v.Keyword, strings.Join(v.Appended, " "), strings.Join(v.Exclude, " ")))
+        }
+        if keysBuffer.String() != "" {
+            keys = keysBuffer.String()
+        }
+        if len(sc.Buyer) > 0 {
+            buyer = strings.Join(sc.Buyer, " ")
+        }
+        if len(sc.Buyerclass) > 0 {
+            buyerclass = strings.Join(sc.Buyerclass, " ")
+        }
+        if len(sc.Winner) > 0 {
+            winner = strings.Join(sc.Winner, " ")
+        }
+        if sc.Subtype != "" {
+            subtype = strings.Replace(sc.Subtype, ",", " ", -1)
+        }
+    } else {
+        log.Println("用户筛选条件错误", err, sc)
+    }
+    content = fmt.Sprintf(config.ExConf.Mail_attach_content, download_url, orderCode, create_time, pay_time, product_type, data_spec, data_count, order_money, user_mail, user_phone, publishtime, region, industry, buyerclass, keys, keywordsMatchItemShow, sc_money, subtype, buyer, winner)
+    return content, nil
 }
 
 /*
 获取-筛选条件-金额
 */
 func GetPriceDes_SieveCondition(minPrice, maxPrice string) string {
-	des := "全部"
-	unit := "万元"
-	if minPrice != "" && maxPrice != "" {
-		des = minPrice + unit + "—" + maxPrice + unit
-	} else if minPrice != "" {
-		des = "大于" + minPrice + unit
-	} else if maxPrice != "" {
-		des = "小于" + maxPrice + unit
-	}
-	return des
+    des := "全部"
+    unit := "万元"
+    if minPrice != "" && maxPrice != "" {
+        des = minPrice + unit + "—" + maxPrice + unit
+    } else if minPrice != "" {
+        des = "大于" + minPrice + unit
+    } else if maxPrice != "" {
+        des = "小于" + maxPrice + unit
+    }
+    return des
 }
 
 // 数据报告发送邮件
 func SendDatareportMailToPayUser(report_id int, price, out_trade_no, user_mail, order_code, phone, company, create_time, pay_time string, auth []*mail.GmailAuth) {
-	res := util.Mysql.FindOne("jy_datareport", map[string]interface{}{
-		"report_id": report_id,
-	}, "report_url", "")
-	if res == nil || (*res)["report_url"] == "" {
-		log.Printf("%d:未知数据报告\n", report_id)
-		return
-	}
-	mailcontent := fmt.Sprintf(reportEmailHtml, config.Config.WebDomain+(*res)["report_url"].(string), order_code, create_time, pay_time, price, user_mail, phone, company)
-	if util.SendRetryMail(config.ExConf.Mail_retry, user_mail, "数据报告", mailcontent, "", nil, auth) {
-		log.Printf("用户%s:数据报告附件邮件发送成功!数据报告id:%d\n", user_mail, report_id)
-		now := time.Now()
-		util.Mysql.Update("jy_datareport_order", map[string]interface{}{
-			"out_trade_no": out_trade_no,
-			"report_id":    report_id,
-		}, map[string]interface{}{
-			"service_status": 1,
-			"service_time":   FormatDate(&now, Date_Full_Layout),
-		})
-	} else {
-		log.Printf("%s数据报告发送邮件出错,数据报告id:%d\n", out_trade_no, report_id)
-	}
+    res := util.Mysql.FindOne("jy_datareport", map[string]interface{}{
+        "report_id": report_id,
+    }, "report_url", "")
+    if res == nil || (*res)["report_url"] == "" {
+        log.Printf("%d:未知数据报告\n", report_id)
+        return
+    }
+    mailcontent := fmt.Sprintf(reportEmailHtml, config.Config.WebDomain+(*res)["report_url"].(string), order_code, create_time, pay_time, price, user_mail, phone, company)
+    if util.SendRetryMail(config.ExConf.Mail_retry, user_mail, "数据报告", mailcontent, "", nil, auth) {
+        log.Printf("用户%s:数据报告附件邮件发送成功!数据报告id:%d\n", user_mail, report_id)
+        now := time.Now()
+        util.Mysql.Update("jy_datareport_order", map[string]interface{}{
+            "out_trade_no": out_trade_no,
+            "report_id":    report_id,
+        }, map[string]interface{}{
+            "service_status": 1,
+            "service_time":   FormatDate(&now, Date_Full_Layout),
+        })
+    } else {
+        log.Printf("%s数据报告发送邮件出错,数据报告id:%d\n", out_trade_no, report_id)
+    }
 }
 
 // 获取支付单号
 func getPayTransactionId(payWay, tradeNo string) (transaction_id string) {
-	if payWay == "" || tradeNo == "" {
-		return
-	}
-	table := ""
-	if strings.HasPrefix(payWay, "wx") {
-		table = "weixin_pay"
-	} else if strings.HasPrefix(payWay, "ali") {
-		table = "ali_pay"
-	} else {
-		return
-	}
-	query := map[string]interface{}{
-		"out_trade_no": tradeNo,
-	}
-	r := util.Mysql.FindOne(table, query, "transaction_id", "")
-	if r != nil {
-		transaction_id = qutil.ObjToString((*r)["transaction_id"])
-	}
-	return
+    if payWay == "" || tradeNo == "" {
+        return
+    }
+    table := ""
+    if strings.HasPrefix(payWay, "wx") {
+        table = "weixin_pay"
+    } else if strings.HasPrefix(payWay, "ali") {
+        table = "ali_pay"
+    } else {
+        return
+    }
+    query := map[string]interface{}{
+        "out_trade_no": tradeNo,
+    }
+    r := util.Mysql.FindOne(table, query, "transaction_id", "")
+    if r != nil {
+        transaction_id = qutil.ObjToString((*r)["transaction_id"])
+    }
+    return
 }
 
 // 升级续费逻辑升级后的 转换
 func newbuysetConversion(newbuyset map[string]interface{}) (subscription_area, industry string) {
-	areacount := qutil.Int64All(newbuyset["areacount"])
-	newcityscount := len(newbuyset["newcitys"].([]interface{})) //分布
-	if areacount == -1 {
-		subscription_area = "全国"
-	} else {
-		if newcityscount > 0 {
-			cityCount := 0
-			for _, v := range newbuyset["newcitys"].([]interface{}) {
-				cityCount += int(v.(float64))
-			}
-			if newcityscount > 1 { //显示(分布在x个省内)
-				if areacount != 0 {
-					subscription_area = fmt.Sprintf("%d个省、%d个地市(分布在%d个省内)", areacount, cityCount, newcityscount)
-				} else {
-					subscription_area = fmt.Sprintf("%d个地市(分布在%d个省内)", cityCount, newcityscount)
-				}
-			} else {
-				if areacount != 0 {
-					subscription_area = fmt.Sprintf("%d个省、%d个地市", areacount, cityCount)
-				} else {
-					subscription_area = fmt.Sprintf("%d个地市", cityCount)
-				}
-			}
-		} else {
-			subscription_area = fmt.Sprintf("%d个省", areacount)
-		}
-	}
-	//行业
-	buyerclasscount := qutil.Int64All(newbuyset["buyerclasscount"])
-	if buyerclasscount == -1 {
-		industry = "全行业"
-	} else {
-		industry = fmt.Sprintf("%d个行业", int(newbuyset["buyerclasscount"].(float64)))
-	}
-	return subscription_area, industry
+    areacount := qutil.Int64All(newbuyset["areacount"])
+    newcityscount := len(newbuyset["newcitys"].([]interface{})) //分布
+    if areacount == -1 {
+        subscription_area = "全国"
+    } else {
+        if newcityscount > 0 {
+            cityCount := 0
+            for _, v := range newbuyset["newcitys"].([]interface{}) {
+                cityCount += int(v.(float64))
+            }
+            if newcityscount > 1 { //显示(分布在x个省内)
+                if areacount != 0 {
+                    subscription_area = fmt.Sprintf("%d个省、%d个地市(分布在%d个省内)", areacount, cityCount, newcityscount)
+                } else {
+                    subscription_area = fmt.Sprintf("%d个地市(分布在%d个省内)", cityCount, newcityscount)
+                }
+            } else {
+                if areacount != 0 {
+                    subscription_area = fmt.Sprintf("%d个省、%d个地市", areacount, cityCount)
+                } else {
+                    subscription_area = fmt.Sprintf("%d个地市", cityCount)
+                }
+            }
+        } else {
+            subscription_area = fmt.Sprintf("%d个省", areacount)
+        }
+    }
+    //行业
+    buyerclasscount := qutil.Int64All(newbuyset["buyerclasscount"])
+    if buyerclasscount == -1 {
+        industry = "全行业"
+    } else {
+        industry = fmt.Sprintf("%d个行业", int(newbuyset["buyerclasscount"].(float64)))
+    }
+    return subscription_area, industry
 }

+ 65 - 65
src/jfw/modules/subscribepay/src/entity/distribution.go

@@ -2,74 +2,74 @@
 package entity
 
 import (
-	"database/sql"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"strings"
-	"time"
+    "database/sql"
+    "jy/src/jfw/modules/subscribepay/src/pay"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "strings"
+    "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/redis"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/redis"
 )
 
 func DisWordRecode(order_id, sale_money int, product_name, disWord, userId string) {
-	//redis 获取分销者信息
-	redisDis := redis.GetStr("other", "DIS_"+disWord[1:])
-	if redisDis != "" {
-		//分销者id
-		shareUId := strings.Split(redisDis, "##")[1]
-		//查询产品信息   获取  rate 佣金比例
-		var c_rate float64 = 0
-		if p_data, ok := util.MQFW.Find("dis_product", nil, `{"l_createdate":1}`, nil, false, -1, -1); ok && p_data != nil {
-			for _, v := range *p_data {
-				if product_name == qutil.ObjToString(v["s_name"]) {
-					c_rate = qutil.Float64All(v["f_rate"])
-				}
-			}
-		}
-		if product_name == "超级订阅企业版" {
-			product_name = "超级订阅"
-		}
-		//四舍五入 取整
-		c_money_f := float64(sale_money) * c_rate
-		c_money_i := int(qutil.RetainDecimal(c_money_f, 0))
-		now := time.Now()
-		code := pay.GetOrderCode(shareUId)
-		// 	"uid":             shareUId,                                       //分销者用户id int
-		// 	"order_id":        order_id,                                       //订单id int
-		// 	"product_name":    product_name,                                   //产品名称 str
-		// 	"sale_money":      sale_money,                                     //销售金额 int
-		// 	"commission_rate": c_rate,                                         //佣金比例 double
-		// 	"commission":      c_money_i,                                      //佣金 int
-		// 	"code":            code,                                           //佣金单号
-		// 	"sale_status":     0,                                              //状态;0:未结算,1:已结算
-		// 	"createtime":      FormatDate(&now, Date_Full_Layout), //保存时间
-		// 	"timestamp":       FormatDate(&now, Date_Full_Layout), //修改时间
-		shareType := ""
-		if userId == shareUId {
-			return
-		}
-		phone := ""
-		userMsg, _ := util.MQFW.FindById("user", userId, ``)
-		if userMsg == nil || len(*userMsg) == 0 {
+    //redis 获取分销者信息
+    redisDis := redis.GetStr("other", "DIS_"+disWord[1:])
+    if redisDis != "" {
+        //分销者id
+        shareUId := strings.Split(redisDis, "##")[1]
+        //查询产品信息   获取  rate 佣金比例
+        var c_rate float64 = 0
+        if p_data, ok := util.MQFW.Find("dis_product", nil, `{"l_createdate":1}`, nil, false, -1, -1); ok && p_data != nil {
+            for _, v := range *p_data {
+                if product_name == qutil.ObjToString(v["s_name"]) {
+                    c_rate = qutil.Float64All(v["f_rate"])
+                }
+            }
+        }
+        if product_name == "超级订阅企业版" {
+            product_name = "超级订阅"
+        }
+        //四舍五入 取整
+        c_money_f := float64(sale_money) * c_rate
+        c_money_i := int(qutil.RetainDecimal(c_money_f, 0))
+        now := time.Now()
+        code := pay.GetOrderCode(shareUId)
+        // 	"uid":             shareUId,                                       //分销者用户id int
+        // 	"order_id":        order_id,                                       //订单id int
+        // 	"product_name":    product_name,                                   //产品名称 str
+        // 	"sale_money":      sale_money,                                     //销售金额 int
+        // 	"commission_rate": c_rate,                                         //佣金比例 double
+        // 	"commission":      c_money_i,                                      //佣金 int
+        // 	"code":            code,                                           //佣金单号
+        // 	"sale_status":     0,                                              //状态;0:未结算,1:已结算
+        // 	"createtime":      FormatDate(&now, Date_Full_Layout), //保存时间
+        // 	"timestamp":       FormatDate(&now, Date_Full_Layout), //修改时间
+        shareType := ""
+        if userId == shareUId {
+            return
+        }
+        phone := ""
+        userMsg := util.Compatible.Select(userId, `{"s_phone":1,"s_m_phone":1,"shareType":1}`)
+        if userMsg == nil || len(*userMsg) == 0 {
 
-		} else {
-			phone = qutil.ObjToString(qutil.If((*userMsg)["s_phone"] != nil, (*userMsg)["s_phone"], (*userMsg)["s_m_phone"]))
-			shareType = qutil.ObjToString((*userMsg)["shareType"])
-		}
-		if !util.Mysql.ExecTx("分销记录和个人账户统计", func(tx *sql.Tx) bool {
-			//新增分销记录
-			s_count := util.Mysql.InsertBySqlByTx(tx, "INSERT INTO dis_sale (uid,order_id,product_name,sale_money,commission_rate,commission,code,sale_status,createtime,timestamp,phone,shareType) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", shareUId, order_id, product_name, sale_money, c_rate, c_money_i, code, 0, FormatDate(&now, Date_Full_Layout), FormatDate(&now, Date_Full_Layout), phone, shareType)
-			//个人账户更新
-			p_count := util.Mysql.UpdateOrDeleteBySql("UPDATE account a SET a.dis_sales = a.dis_sales+? , a.dis_order = a.dis_order+1 , a.dis_commission=a.dis_commission+? WHERE a.uid = ?", sale_money, c_money_i, shareUId)
-			util.MsgRemind.DistributionSuccess(order_id, shareUId, c_money_i, product_name)
-			return s_count > 0 && p_count > 0
-		}) {
-			log.Println("分销记录和个人账户统计 错误:", shareUId, "-佣金单号:", code)
-		}
-	} else {
-		log.Println("保存分销记录出错:", order_id)
-	}
+        } else {
+            phone = qutil.ObjToString(qutil.If((*userMsg)["s_phone"] != nil, (*userMsg)["s_phone"], (*userMsg)["s_m_phone"]))
+            shareType = qutil.ObjToString((*userMsg)["shareType"])
+        }
+        if !util.Mysql.ExecTx("分销记录和个人账户统计", func(tx *sql.Tx) bool {
+            //新增分销记录
+            s_count := util.Mysql.InsertBySqlByTx(tx, "INSERT INTO dis_sale (uid,order_id,product_name,sale_money,commission_rate,commission,code,sale_status,createtime,timestamp,phone,shareType) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", shareUId, order_id, product_name, sale_money, c_rate, c_money_i, code, 0, FormatDate(&now, Date_Full_Layout), FormatDate(&now, Date_Full_Layout), phone, shareType)
+            //个人账户更新
+            p_count := util.Mysql.UpdateOrDeleteBySql("UPDATE account a SET a.dis_sales = a.dis_sales+? , a.dis_order = a.dis_order+1 , a.dis_commission=a.dis_commission+? WHERE a.uid = ?", sale_money, c_money_i, shareUId)
+            util.MsgRemind.DistributionSuccess(order_id, shareUId, c_money_i, product_name)
+            return s_count > 0 && p_count > 0
+        }) {
+            log.Println("分销记录和个人账户统计 错误:", shareUId, "-佣金单号:", code)
+        }
+    } else {
+        log.Println("保存分销记录出错:", order_id)
+    }
 }

+ 0 - 2
src/jfw/modules/subscribepay/src/entity/order.go

@@ -1067,8 +1067,6 @@ func areaPackOrder(m map[string]interface{}, userId string, session *httpsession
 		OriginalPrice: original_price,
 	}
 	//校验
-	//rdata, ok := util.MQFW.FindById("user", userId, `{"o_jy":1}`)
-	//ojy := jy.GetSubScribeInfo(session, util.MQFW, "f", "10000")
 	rdata := util.Compatible.Select(userId, `{"o_jy"}`)
 	if rdata != nil && len(*rdata) > 0 {
 		ojy := qu.ObjToMap((*rdata)["o_jy"])

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 474 - 538
src/jfw/modules/subscribepay/src/entity/subscribeVip.go


+ 0 - 1
src/jfw/modules/subscribepay/src/report/report.go

@@ -128,7 +128,6 @@ func (r *Report) Index() {
 			delete(result, "month")
 		}
 	}
-	//u, ok := util.MQFW.FindById("user", userId, `{"i_vip_status":1,"i_member_status":1}`)
 	u := jy.GetBigVipUserBaseMsg(r.Session(), *config.Middleground)
 	services := []string{}
 	memberStatus := 0

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 596 - 598
src/jfw/modules/subscribepay/src/service/afterPay.go


+ 1 - 1
src/jfw/modules/subscribepay/src/service/dataexportPack.go

@@ -96,7 +96,7 @@ func (this *DataExportPack) PackGoodsList() {
 //
 // return orderCode 订单号
 func (this *DataExportPack) CreateOrder() {
-	userId, _ := this.GetSession("userId").(string)
+	userId, _ := this.GetSession("mgoUserId").(string)
 	rData, errMsg := func() (interface{}, error) {
 		packId := this.GetString("packId") //
 		// 获取用户分销口令

+ 2 - 2
src/jfw/modules/subscribepay/src/service/exceptionVerification.go

@@ -29,7 +29,7 @@ const (
 
 func (this *ExceptionVerification) PhoneVerification() {
 	defer qutil.Catch()
-	userId, _ := this.GetSession("userId").(string)
+	userId, _ := this.GetSession("mgoUserId").(string)
 	reqType := this.GetString("reqType")
 	rData, errMsg := func() (interface{}, error) {
 		if userId == "" {
@@ -39,7 +39,7 @@ func (this *ExceptionVerification) PhoneVerification() {
 		case "sendIdentCode":
 			phone, _ := this.GetSession("phone").(string)
 			if phone == "" {
-				if res, _ := util.MQFW.FindById("user", userId, `{"s_phone":1,"s_m_phone":1}`); res != nil && len(*res) > 0 {
+				if res:= util.Compatible.Select( userId, `{"s_phone":1,"s_m_phone":1}`); res != nil && len(*res) > 0 {
 					if resPhone := qutil.ObjToString((*res)["s_phone"]); resPhone != "" {
 						phone = resPhone
 					} else if resPhone := qutil.ObjToString((*res)["s_m_phone"]); resPhone != "" {

+ 0 - 1
src/jfw/modules/subscribepay/src/service/invoice.go

@@ -601,7 +601,6 @@ func (this *Invoice) Replaceinvoice() {
 		e_mail := this.GetString("email")
 		company_name := this.GetString("company")
 		id_num := strings.ToUpper(this.GetString("id_num")) //纳税人识别号
-		//user_info, _ := util.MQFW.FindOneByField("user", bson.M{"_id": bson.ObjectIdHex(qutil.ObjToString(this.GetSession("userId")))}, `{"s_nickname":1}`)
 		if invoice_type == "个人" {
 			if phone == (*res)["phone"] && e_mail == (*res)["mail"] && (*res)["invoice_type"] == "个人" {
 				emailHtml := emailHtml_gr

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 876 - 876
src/jfw/modules/subscribepay/src/service/orderListDetails.go


+ 3 - 3
src/jfw/modules/subscribepay/src/service/phoneCollent.go

@@ -26,7 +26,7 @@ func (this *PhoneCollent) CollectPhone() {
 	if !R.CheckReqParam(this.ResponseWriter, this.Request, "phone", "step") {
 		return
 	}
-	userId, _ := this.GetSession("userId").(string)
+	userId, _ := this.GetSession("mgoUserId").(string)
 	phone := this.GetString("phone")
 	step, _ := this.GetInteger("step")
 	r, msg := func() (interface{}, error) {
@@ -75,11 +75,11 @@ func (this *PhoneCollent) CollectPhone() {
 
 func (this *PhoneCollent) NeedBind() {
 	r := func() bool {
-		uid, _ := this.GetSession("userId").(string)
+		uid, _ := this.GetSession("mgoUserId").(string)
 		if uid == "" {
 			return false
 		}
-		if person, ok := util.MQFW.FindById("user", uid, `{"s_phone":1,"s_m_phone":1,"l_registedate":1}`); person != nil && len(*person) > 0 && ok {
+		if person:= util.Compatible.Select( uid, `{"s_phone":1,"s_m_phone":1,"l_registedate":1}`); person != nil && len(*person) > 0  {
 			s_phone := qutil.ObjToString((*person)["s_phone"])
 			if s_phone == "" {
 				s_phone = qutil.ObjToString((*person)["s_m_phone"])

+ 541 - 541
src/jfw/modules/subscribepay/src/service/salesCreateOrder.go

@@ -1,607 +1,607 @@
 package service
 
 import (
-	"encoding/base64"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/entity"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"net/url"
-	"strconv"
-	"time"
+    "encoding/base64"
+    "encoding/json"
+    "errors"
+    "fmt"
+    "jy/src/jfw/modules/subscribepay/src/config"
+    "jy/src/jfw/modules/subscribepay/src/entity"
+    "jy/src/jfw/modules/subscribepay/src/pay"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "net/url"
+    "strconv"
+    "time"
 
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"github.com/SKatiyar/qr"
-	"go.mongodb.org/mongo-driver/bson"
-	"go.mongodb.org/mongo-driver/bson/primitive"
+    . "app.yhyue.com/moapp/jybase/api"
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jybase/redis"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "github.com/SKatiyar/qr"
+    "go.mongodb.org/mongo-driver/bson"
+    "go.mongodb.org/mongo-driver/bson/primitive"
 )
 
 type SalesCreateOrder struct {
-	*xweb.Action
-	createBySeller    xweb.Mapper `xweb:"/free/seller/createOrder"`           //销售代用户下单-创建订单
-	wxPaymentPage     xweb.Mapper `xweb:"/free/seller/wxPaymentPage"`         //销售代用户下单-无身份微信订单页面
-	getOrderPayAllMsg xweb.Mapper `xweb:"/free/seller/getOrderPayAllMsg"`     //销售代用户下单-获取订单详情
-	getCommonPayParam xweb.Mapper `xweb:"/free/seller/getCommonPayParam"`     //销售代用户下单-获取支付参数
-	isPaySuccess      xweb.Mapper `xweb:"/free/seller/isPaySuccess"`          //销售代用户下单-是否支付成功
-	getSubBuyMsg      xweb.Mapper `xweb:"/free/seller/svip/getSubBuyMsg"`     //超级订阅-获取已购买信息
-	getPrice          xweb.Mapper `xweb:"/free/seller/svip/getPrice"`         //超级订阅-获取超级订阅价格
-	getSelectPrice    xweb.Mapper `xweb:"/free/seller/svip/getSelectPrice"`   //超级订阅-获取选择价格
-	getValuationList  xweb.Mapper `xweb:"/free/seller/svip/getValuationList"` //超级订阅-计价清单
+    *xweb.Action
+    createBySeller    xweb.Mapper `xweb:"/free/seller/createOrder"`           //销售代用户下单-创建订单
+    wxPaymentPage     xweb.Mapper `xweb:"/free/seller/wxPaymentPage"`         //销售代用户下单-无身份微信订单页面
+    getOrderPayAllMsg xweb.Mapper `xweb:"/free/seller/getOrderPayAllMsg"`     //销售代用户下单-获取订单详情
+    getCommonPayParam xweb.Mapper `xweb:"/free/seller/getCommonPayParam"`     //销售代用户下单-获取支付参数
+    isPaySuccess      xweb.Mapper `xweb:"/free/seller/isPaySuccess"`          //销售代用户下单-是否支付成功
+    getSubBuyMsg      xweb.Mapper `xweb:"/free/seller/svip/getSubBuyMsg"`     //超级订阅-获取已购买信息
+    getPrice          xweb.Mapper `xweb:"/free/seller/svip/getPrice"`         //超级订阅-获取超级订阅价格
+    getSelectPrice    xweb.Mapper `xweb:"/free/seller/svip/getSelectPrice"`   //超级订阅-获取选择价格
+    getValuationList  xweb.Mapper `xweb:"/free/seller/svip/getValuationList"` //超级订阅-计价清单
 
-	//tokenShow xweb.Mapper `xweb:"/free/seller/tokenShow"` //超级订阅-获取选择价格
+    //tokenShow xweb.Mapper `xweb:"/free/seller/tokenShow"` //超级订阅-获取选择价格
 }
 
 func (this *SalesCreateOrder) TokenShow() {
-	vmap := map[string]interface{}{}
-	for key := range this.Request.Form {
-		value := this.Request.Form.Get(key)
-		if key != "token" {
-			vmap[key] = value
-		} else {
-			userid, sellPName, sellPid, sellData, err := util.SellerTokenDecrypt(value)
-			if err != nil {
-				vmap[key] = err.Error()
-				continue
-			}
-			vmap[key] = map[string]interface{}{
-				"userid":    userid,
-				"sellPName": sellPName,
-				"sellPid":   sellPid,
-				"sellData":  sellData,
-			}
-		}
-	}
-	this.ServeJson(vmap)
+    vmap := map[string]interface{}{}
+    for key := range this.Request.Form {
+        value := this.Request.Form.Get(key)
+        if key != "token" {
+            vmap[key] = value
+        } else {
+            userid, sellPName, sellPid, sellData, err := util.SellerTokenDecrypt(value)
+            if err != nil {
+                vmap[key] = err.Error()
+                continue
+            }
+            vmap[key] = map[string]interface{}{
+                "userid":    userid,
+                "sellPName": sellPName,
+                "sellPid":   sellPid,
+                "sellData":  sellData,
+            }
+        }
+    }
+    this.ServeJson(vmap)
 }
 
 // CreateBySeller 销售为用户创建订单
 // 逻辑和Createorder 一致
 // 无用户身份,额外赠送
 func (this *SalesCreateOrder) CreateBySeller() {
-	var userid string
-	rData, errMsg := func() (interface{}, error) {
-		//参数接收
-		infoMap := map[string]interface{}{}
-		body := xweb.FilterXSS(string(this.Body()))
-		//接收参数
-		_ = json.Unmarshal([]byte(body), &infoMap)
-		if len(infoMap) == 0 {
-			return nil, fmt.Errorf("无效参数")
-		}
-		//解密请求参数
-		userid, sellPName, sellPid, sellData, err := util.SellerTokenDecrypt(qutil.ObjToString(infoMap["token"]))
-		if err != nil {
-			return nil, err
-		}
-		//产品类型
-		product, _ := infoMap["product"].(string)
-		if product != "VIP订阅" { //目前仅超级订阅
-			return nil, fmt.Errorf("请求产品类型有误")
-		}
-		productId := strconv.Itoa(qutil.IntAll(infoMap["productId"]))
+    var userid string
+    rData, errMsg := func() (interface{}, error) {
+        //参数接收
+        infoMap := map[string]interface{}{}
+        body := xweb.FilterXSS(string(this.Body()))
+        //接收参数
+        _ = json.Unmarshal([]byte(body), &infoMap)
+        if len(infoMap) == 0 {
+            return nil, fmt.Errorf("无效参数")
+        }
+        //解密请求参数
+        userid, sellPName, sellPid, sellData, err := util.SellerTokenDecrypt(qutil.ObjToString(infoMap["token"]))
+        if err != nil {
+            return nil, err
+        }
+        //产品类型
+        product, _ := infoMap["product"].(string)
+        if product != "VIP订阅" { //目前仅超级订阅
+            return nil, fmt.Errorf("请求产品类型有误")
+        }
+        productId := strconv.Itoa(qutil.IntAll(infoMap["productId"]))
 
-		//
-		data, _ := infoMap["data"].(map[string]interface{})
-		if len(data) <= 0 {
-			return nil, fmt.Errorf("无效参数")
-		}
+        //
+        data, _ := infoMap["data"].(map[string]interface{})
+        if len(data) <= 0 {
+            return nil, fmt.Errorf("无效参数")
+        }
 
-		//获取卡券相关
-		lotteryId := qutil.ObjToString(data["lotteryId"]) //卡卷信息的id
-		i_discountId := qutil.IntAll(data["discountId"])  //赠品相关
-		discountId := strconv.Itoa(i_discountId)
-		inserMap, msg := entity.JyCommonOrderStruct.InserMap(product, productId, userid, lotteryId, discountId, data, this.Session())
-		//错误信息
-		if msg != "" {
-			return nil, fmt.Errorf(msg)
-		}
-		//销售额外赠送
-		if product == "VIP订阅" && len(sellData) > 0 {
-			tt := qutil.IntAll(sellData["tt"])
-			tn := qutil.IntAll(sellData["tn"])
-			if inserMap.VipEndTime != "" {
-				endTime, _ := time.ParseInLocation(Date_Full_Layout, inserMap.VipEndTime, time.Local)
-				if tt == 1 {
-					endTime = endTime.AddDate(0, 0, tn)
-				} else if tt == 2 {
-					endTime = endTime.AddDate(0, tn, 0)
-				}
-				inserMap.VipEndTime = endTime.Format(Date_Full_Layout)
-			}
+        //获取卡券相关
+        lotteryId := qutil.ObjToString(data["lotteryId"]) //卡卷信息的id
+        i_discountId := qutil.IntAll(data["discountId"])  //赠品相关
+        discountId := strconv.Itoa(i_discountId)
+        inserMap, msg := entity.JyCommonOrderStruct.InserMap(product, productId, userid, lotteryId, discountId, data, this.Session())
+        //错误信息
+        if msg != "" {
+            return nil, fmt.Errorf(msg)
+        }
+        //销售额外赠送
+        if product == "VIP订阅" && len(sellData) > 0 {
+            tt := qutil.IntAll(sellData["tt"])
+            tn := qutil.IntAll(sellData["tn"])
+            if inserMap.VipEndTime != "" {
+                endTime, _ := time.ParseInLocation(Date_Full_Layout, inserMap.VipEndTime, time.Local)
+                if tt == 1 {
+                    endTime = endTime.AddDate(0, 0, tn)
+                } else if tt == 2 {
+                    endTime = endTime.AddDate(0, tn, 0)
+                }
+                inserMap.VipEndTime = endTime.Format(Date_Full_Layout)
+            }
 
-			filterMap := map[string]interface{}{}
-			if err := json.Unmarshal([]byte(inserMap.Filter), &filterMap); err != nil {
-				return nil, fmt.Errorf("创建订单异常Unmarshal")
-			}
+            filterMap := map[string]interface{}{}
+            if err := json.Unmarshal([]byte(inserMap.Filter), &filterMap); err != nil {
+                return nil, fmt.Errorf("创建订单异常Unmarshal")
+            }
 
-			if inserMap.VipType != 2 {
-				filterMap["seller_give_type"] = tt
-				filterMap["seller_give_cycle"] = tn
-			}
+            if inserMap.VipType != 2 {
+                filterMap["seller_give_type"] = tt
+                filterMap["seller_give_cycle"] = tn
+            }
 
-			bb, err := json.Marshal(filterMap)
-			if err != nil {
-				return nil, fmt.Errorf("创建订单异常-Marshal")
-			}
-			inserMap.Filter = string(bb)
-		}
-		now := time.Now()
-		_, userErr := primitive.ObjectIDFromHex(userid)
-		buy_subject := 1
-		entId := 0
-		if userErr != nil {
-			//雇员标识
-			positionData := util.InfoMysql.FindOne("base_position", map[string]interface{}{"id": userid}, "ent_id", "")
-			if positionData != nil {
-				entId = qutil.IntAll((*positionData)["ent_id"])
-			}
-		}
-		insertM := map[string]interface{}{
-			"order_money":          inserMap.OrderMoney,
-			"order_status":         inserMap.OrderStatus,
-			"service_status":       inserMap.ServiceStatus,
-			"user_phone":           inserMap.UserPhone,
-			"order_code":           inserMap.OrderCode,
-			"product_type":         product,
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       inserMap.OriginalPrice,
-			"user_id":              userid,
-			"filter":               inserMap.Filter,
-			"discount_price":       inserMap.DiscountPrice,
-			"d_relation_id":        inserMap.DrelationId,
-			"data_spec":            inserMap.DataSpec,
-			"user_mail":            inserMap.UserMail,
-			"data_count":           inserMap.DataCount,
-			"filter_publishtime":   inserMap.FilterPublishtime,
-			"is_backstage_order":   0,
-			"filter_keys":          inserMap.FilterKeys,
-			"download_url":         inserMap.DownloadUrl,
-			"dis_word":             inserMap.DisWord,
-			"distribution_channel": "x020",
-			"order_channel":        "xdqd04",  //下单渠道-启明星后台销售创建
-			"salesperson":          sellPName, //销售人员
-			"salesperson_id":       sellPid,   //销售人员id
-			"audit_status":         3,         //默认审核通过
-			"buy_subject":          buy_subject,
-			"ent_id":               entId,
-		}
+            bb, err := json.Marshal(filterMap)
+            if err != nil {
+                return nil, fmt.Errorf("创建订单异常-Marshal")
+            }
+            inserMap.Filter = string(bb)
+        }
+        now := time.Now()
+        _, userErr := primitive.ObjectIDFromHex(userid)
+        buy_subject := 1
+        entId := 0
+        if userErr != nil {
+            //雇员标识
+            positionData := util.InfoMysql.FindOne("base_position", map[string]interface{}{"id": userid}, "ent_id", "")
+            if positionData != nil {
+                entId = qutil.IntAll((*positionData)["ent_id"])
+            }
+        }
+        insertM := map[string]interface{}{
+            "order_money":          inserMap.OrderMoney,
+            "order_status":         inserMap.OrderStatus,
+            "service_status":       inserMap.ServiceStatus,
+            "user_phone":           inserMap.UserPhone,
+            "order_code":           inserMap.OrderCode,
+            "product_type":         product,
+            "create_time":          FormatDate(&now, Date_Full_Layout),
+            "original_price":       inserMap.OriginalPrice,
+            "user_id":              userid,
+            "filter":               inserMap.Filter,
+            "discount_price":       inserMap.DiscountPrice,
+            "d_relation_id":        inserMap.DrelationId,
+            "data_spec":            inserMap.DataSpec,
+            "user_mail":            inserMap.UserMail,
+            "data_count":           inserMap.DataCount,
+            "filter_publishtime":   inserMap.FilterPublishtime,
+            "is_backstage_order":   0,
+            "filter_keys":          inserMap.FilterKeys,
+            "download_url":         inserMap.DownloadUrl,
+            "dis_word":             inserMap.DisWord,
+            "distribution_channel": "x020",
+            "order_channel":        "xdqd04",  //下单渠道-启明星后台销售创建
+            "salesperson":          sellPName, //销售人员
+            "salesperson_id":       sellPid,   //销售人员id
+            "audit_status":         3,         //默认审核通过
+            "buy_subject":          buy_subject,
+            "ent_id":               entId,
+        }
 
-		if inserMap.VipStartTime != "" && inserMap.VipEndTime != "" {
-			insertM["vip_starttime"] = inserMap.VipStartTime
-			insertM["vip_endtime"] = inserMap.VipEndTime
-		}
-		if inserMap.PrepayTime != "" {
-			insertM["prepay_time"] = inserMap.PrepayTime
-		}
-		if inserMap.PayWay != "" {
-			insertM["pay_way"] = inserMap.PayWay
-		}
-		if inserMap.PrepayId != "" {
-			insertM["prepay_id"] = inserMap.PrepayId
-		}
-		if inserMap.FilterId != "" {
-			insertM["filter_id"] = inserMap.FilterId
-		}
-		if inserMap.VipType != 0 {
-			insertM["vip_type"] = inserMap.VipType
-		}
+        if inserMap.VipStartTime != "" && inserMap.VipEndTime != "" {
+            insertM["vip_starttime"] = inserMap.VipStartTime
+            insertM["vip_endtime"] = inserMap.VipEndTime
+        }
+        if inserMap.PrepayTime != "" {
+            insertM["prepay_time"] = inserMap.PrepayTime
+        }
+        if inserMap.PayWay != "" {
+            insertM["pay_way"] = inserMap.PayWay
+        }
+        if inserMap.PrepayId != "" {
+            insertM["prepay_id"] = inserMap.PrepayId
+        }
+        if inserMap.FilterId != "" {
+            insertM["filter_id"] = inserMap.FilterId
+        }
+        if inserMap.VipType != 0 {
+            insertM["vip_type"] = inserMap.VipType
+        }
 
-		orderid := util.Mysql.Insert("dataexport_order", insertM)
-		if orderid <= 0 {
-			return nil, fmt.Errorf("创建订单异常")
-		}
-		//发送站内信
-		pcUrl := fmt.Sprintf(config.Config.WebSiteParameter.Link, inserMap.OrderCode)
-		appUrl := fmt.Sprintf(config.Config.WebSiteParameter.AndroidUrl, inserMap.OrderCode)
-		wxUrl := fmt.Sprintf(config.Config.WebSiteParameter.WeChatUrl, inserMap.OrderCode)
-		go util.SendStationMessages(config.Config.WebSiteParameter.Addr, userid, config.Config.WebSiteParameter.Action,
-			"1", config.Config.WebSiteParameter.Title, config.Config.WebSiteParameter.Content,
-			pcUrl, appUrl, appUrl, wxUrl, qutil.InterfaceToStr(orderid))
+        orderid := util.Mysql.Insert("dataexport_order", insertM)
+        if orderid <= 0 {
+            return nil, fmt.Errorf("创建订单异常")
+        }
+        //发送站内信
+        pcUrl := fmt.Sprintf(config.Config.WebSiteParameter.Link, inserMap.OrderCode)
+        appUrl := fmt.Sprintf(config.Config.WebSiteParameter.AndroidUrl, inserMap.OrderCode)
+        wxUrl := fmt.Sprintf(config.Config.WebSiteParameter.WeChatUrl, inserMap.OrderCode)
+        go util.SendStationMessages(config.Config.WebSiteParameter.Addr, userid, config.Config.WebSiteParameter.Action,
+            "1", config.Config.WebSiteParameter.Title, config.Config.WebSiteParameter.Content,
+            pcUrl, appUrl, appUrl, wxUrl, qutil.InterfaceToStr(orderid))
 
-		if i_discountId > 0 {
-			go util.FindUserLotteryId(userid, orderid, i_discountId)
-		}
-		rdata := map[string]interface{}{"order_code": inserMap.OrderCode, "needPay": !inserMap.UnNeedPay}
-		return rdata, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s CreateBySeller 异常:%s\n", userid, errMsg.Error())
-	}
-	//创建完订单后更新卡券信息
-	this.ServeJson(NewResult(rData, errMsg))
+        if i_discountId > 0 {
+            go util.FindUserLotteryId(userid, orderid, i_discountId)
+        }
+        rdata := map[string]interface{}{"order_code": inserMap.OrderCode, "needPay": !inserMap.UnNeedPay}
+        return rdata, nil
+    }()
+    if errMsg != nil {
+        log.Printf("%s CreateBySeller 异常:%s\n", userid, errMsg.Error())
+    }
+    //创建完订单后更新卡券信息
+    this.ServeJson(NewResult(rData, errMsg))
 }
 
 // WxPaymentPage
 // 微信支付将openid添加至token
 // 并重定向至指定url
 func (this *SalesCreateOrder) WxPaymentPage() error {
-	stateKey := this.GetString("state")
-	if (this.GetString("href") == "" || this.GetString("token") == "") &&
-		stateKey == "" {
-		return this.WriteBytes([]byte("请求异常"))
-	}
-	param := this.Request.Form
-	if stateKey == "" { //公众号回调
-		stateKey = func() string {
-			return fmt.Sprintf("%s_%s", time.Now().Format("20060102150405"), qutil.GetLetterRandom(5))
-		}()
-		redis.Put("other", stateKey, param, 60*5) //存储信息
-		return this.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(this.Site()+this.Url()), stateKey), 302)
-	}
-	//获取wx跳转前参数
-	if redisValue := redis.Get("other", stateKey); redisValue != nil {
-		if t, ok := redisValue.(url.Values); ok {
-			param = t
-		}
-	}
-	//获取用户openid
-	openid := util.Getopenid(this.GetString("code"))
-	if openid == "" {
-		return this.WriteBytes([]byte("获取用户身份异常"))
-	}
-	userid, sellPName, sellPid, sellData, err := util.SellerTokenDecrypt(param.Get("token"))
-	if err != nil {
-		return this.WriteBytes([]byte(err.Error()))
-	}
-	sellData["openid"] = openid
-	toHref := param.Get("href")
-	param.Set("token", util.GetSellerToken(userid, sellPName, sellPid, sellData)) //更新token
-	for _, key := range []string{"state", "code", "href"} {
-		param.Del(key)
-	}
-	return this.Redirect(toHref+"?"+param.Encode(), 302)
+    stateKey := this.GetString("state")
+    if (this.GetString("href") == "" || this.GetString("token") == "") &&
+        stateKey == "" {
+        return this.WriteBytes([]byte("请求异常"))
+    }
+    param := this.Request.Form
+    if stateKey == "" { //公众号回调
+        stateKey = func() string {
+            return fmt.Sprintf("%s_%s", time.Now().Format("20060102150405"), qutil.GetLetterRandom(5))
+        }()
+        redis.Put("other", stateKey, param, 60*5) //存储信息
+        return this.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(this.Site()+this.Url()), stateKey), 302)
+    }
+    //获取wx跳转前参数
+    if redisValue := redis.Get("other", stateKey); redisValue != nil {
+        if t, ok := redisValue.(url.Values); ok {
+            param = t
+        }
+    }
+    //获取用户openid
+    openid := util.Getopenid(this.GetString("code"))
+    if openid == "" {
+        return this.WriteBytes([]byte("获取用户身份异常"))
+    }
+    userid, sellPName, sellPid, sellData, err := util.SellerTokenDecrypt(param.Get("token"))
+    if err != nil {
+        return this.WriteBytes([]byte(err.Error()))
+    }
+    sellData["openid"] = openid
+    toHref := param.Get("href")
+    param.Set("token", util.GetSellerToken(userid, sellPName, sellPid, sellData)) //更新token
+    for _, key := range []string{"state", "code", "href"} {
+        param.Del(key)
+    }
+    return this.Redirect(toHref+"?"+param.Encode(), 302)
 }
 
 // GetCommonPayParam 销售为用户创建订单
 // 逻辑和commonAction.go GetCommonPayParam 一致
 func (this *SalesCreateOrder) GetCommonPayParam() {
-	orderCode := this.GetString("orderCode")
-	//userId := qutil.ObjToString(this.GetSession("userId"))
-	payway_req := this.GetString("payway")
-	var userId string
-	r := func() *entity.FuncResult {
-		//解密请求参数
-		userId, _, _, desc, err := util.SellerTokenDecrypt(this.GetString("token"))
-		if err != nil {
-			return &entity.FuncResult{false, err, nil}
-		}
-		query := map[string]interface{}{
-			"user_id":       userId,
-			"order_code":    orderCode,
-			"order_channel": "xdqd04", //仅查询销售创建订单
-			"order_status":  0,
-		}
-		oData := util.Mysql.FindOne("dataexport_order", query, "id,code_url,prepay_time,pay_way,order_money,product_type,out_trade_no,course_status", "")
-		if oData == nil || len(*oData) == 0 {
-			return &entity.FuncResult{false, errors.New("未知订单"), nil}
-		}
-		//对公转账审核中
-		if qutil.IntAll((*oData)["course_status"]) == 2 || qutil.IntAll((*oData)["course_status"]) == 4 {
-			return &entity.FuncResult{false, errors.New("转账审核中,请勿重复支付"), nil}
-		}
-		payParam := qutil.ObjToString((*oData)["code_url"])
-		payway := qutil.ObjToString((*oData)["pay_way"])
-		totalfee := qutil.IntAll((*oData)["order_money"])
-		//上次订单支付串是否可用
-		if prepayTime, err := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*oData)["prepay_time"]), time.Local); err == nil && payParam != "" && payway != "wx_js" { //微信公众号支付需要openid,不通账户支付不能通用
-			if time.Now().Before(prepayTime.Add(time.Hour * 2)) { //支付串未过期
-				if payway == payway_req {
-					if payParam != "" {
-						return &entity.FuncResult{true, nil, map[string]interface{}{
-							"orderCode": orderCode,
-							"res":       payParam,
-							"price":     totalfee,
-							"timeout":   prepayTime.Unix() + 2*60*60 - time.Now().Unix(),
-							"payWay":    payway}}
-					}
-				} else {
-					//关闭之前支付串(防止重复支付)
-					if !pay.CloseOrder(qutil.ObjToString((*oData)["out_trade_no"]), payway) {
-						log.Printf("SalesCreateOrder GetCommonPayParam 关闭订单%s出错\n", orderCode)
-						return &entity.FuncResult{false, errors.New("支付方式切换异常"), nil}
-					}
-				}
-			}
-		}
-		openid := ""
-		if payway_req == "wx_js" {
-			if openid, _ = desc["openid"].(string); openid == "" {
-				return &entity.FuncResult{false, fmt.Errorf("微信支付缺少参数"), nil}
-			}
-		} //重新生成支付串
-		productFlag, ok := pay.PayWayAndSign[qutil.ObjToString((*oData)["product_type"])][payway_req]
-		if !ok {
-			return &entity.FuncResult{false, errors.New("未知支付类型:" + payway_req), nil}
-		}
-		tradeno, prepayid, payParam, err := pay.CreateOrderPay(totalfee, productFlag, this.IP(), openid, payway_req, orderCode)
-		if err != nil {
-			return &entity.FuncResult{false, errors.New(fmt.Sprintf("创建支付失败[%v]", err)), nil}
-		}
-		//更新订单表
-		now := time.Now()
-		ok = util.Mysql.Update("dataexport_order", query, map[string]interface{}{
-			"code_url":     payParam,
-			"prepay_time":  FormatDate(&now, Date_Full_Layout),
-			"out_trade_no": tradeno,
-			"prepay_id":    prepayid,
-			"pay_way":      payway_req,
-		})
-		if !ok {
-			return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"orderCode": orderCode,
-			"res":       payParam,
-			"price":     totalfee,
-			"timeout":   2 * 60 * 60,
-			"payWay":    payway_req}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s SalesCreateOrder GetCommonPayParam err:%v\n", userId, r.Err.Error())
-	}
-	if payway_req == "wx_pc" && r.Data["res"] != nil {
-		rEncode, _ := qr.Encode(qutil.ObjToString(r.Data["res"]), qr.M)
-		pngdat := rEncode.PNG()
-		r.Data["res"] = base64.StdEncoding.EncodeToString(pngdat)
-	}
-	this.ServeJson(r.Format())
+    orderCode := this.GetString("orderCode")
+    //userId := qutil.ObjToString(this.GetSession("userId"))
+    payway_req := this.GetString("payway")
+    var userId string
+    r := func() *entity.FuncResult {
+        //解密请求参数
+        userId, _, _, desc, err := util.SellerTokenDecrypt(this.GetString("token"))
+        if err != nil {
+            return &entity.FuncResult{false, err, nil}
+        }
+        query := map[string]interface{}{
+            "user_id":       userId,
+            "order_code":    orderCode,
+            "order_channel": "xdqd04", //仅查询销售创建订单
+            "order_status":  0,
+        }
+        oData := util.Mysql.FindOne("dataexport_order", query, "id,code_url,prepay_time,pay_way,order_money,product_type,out_trade_no,course_status", "")
+        if oData == nil || len(*oData) == 0 {
+            return &entity.FuncResult{false, errors.New("未知订单"), nil}
+        }
+        //对公转账审核中
+        if qutil.IntAll((*oData)["course_status"]) == 2 || qutil.IntAll((*oData)["course_status"]) == 4 {
+            return &entity.FuncResult{false, errors.New("转账审核中,请勿重复支付"), nil}
+        }
+        payParam := qutil.ObjToString((*oData)["code_url"])
+        payway := qutil.ObjToString((*oData)["pay_way"])
+        totalfee := qutil.IntAll((*oData)["order_money"])
+        //上次订单支付串是否可用
+        if prepayTime, err := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*oData)["prepay_time"]), time.Local); err == nil && payParam != "" && payway != "wx_js" { //微信公众号支付需要openid,不通账户支付不能通用
+            if time.Now().Before(prepayTime.Add(time.Hour * 2)) { //支付串未过期
+                if payway == payway_req {
+                    if payParam != "" {
+                        return &entity.FuncResult{true, nil, map[string]interface{}{
+                            "orderCode": orderCode,
+                            "res":       payParam,
+                            "price":     totalfee,
+                            "timeout":   prepayTime.Unix() + 2*60*60 - time.Now().Unix(),
+                            "payWay":    payway}}
+                    }
+                } else {
+                    //关闭之前支付串(防止重复支付)
+                    if !pay.CloseOrder(qutil.ObjToString((*oData)["out_trade_no"]), payway) {
+                        log.Printf("SalesCreateOrder GetCommonPayParam 关闭订单%s出错\n", orderCode)
+                        return &entity.FuncResult{false, errors.New("支付方式切换异常"), nil}
+                    }
+                }
+            }
+        }
+        openid := ""
+        if payway_req == "wx_js" {
+            if openid, _ = desc["openid"].(string); openid == "" {
+                return &entity.FuncResult{false, fmt.Errorf("微信支付缺少参数"), nil}
+            }
+        } //重新生成支付串
+        productFlag, ok := pay.PayWayAndSign[qutil.ObjToString((*oData)["product_type"])][payway_req]
+        if !ok {
+            return &entity.FuncResult{false, errors.New("未知支付类型:" + payway_req), nil}
+        }
+        tradeno, prepayid, payParam, err := pay.CreateOrderPay(totalfee, productFlag, this.IP(), openid, payway_req, orderCode)
+        if err != nil {
+            return &entity.FuncResult{false, errors.New(fmt.Sprintf("创建支付失败[%v]", err)), nil}
+        }
+        //更新订单表
+        now := time.Now()
+        ok = util.Mysql.Update("dataexport_order", query, map[string]interface{}{
+            "code_url":     payParam,
+            "prepay_time":  FormatDate(&now, Date_Full_Layout),
+            "out_trade_no": tradeno,
+            "prepay_id":    prepayid,
+            "pay_way":      payway_req,
+        })
+        if !ok {
+            return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
+        }
+        return &entity.FuncResult{true, nil, map[string]interface{}{
+            "orderCode": orderCode,
+            "res":       payParam,
+            "price":     totalfee,
+            "timeout":   2 * 60 * 60,
+            "payWay":    payway_req}}
+    }()
+    if r.Err != nil {
+        log.Printf("%s SalesCreateOrder GetCommonPayParam err:%v\n", userId, r.Err.Error())
+    }
+    if payway_req == "wx_pc" && r.Data["res"] != nil {
+        rEncode, _ := qr.Encode(qutil.ObjToString(r.Data["res"]), qr.M)
+        pngdat := rEncode.PNG()
+        r.Data["res"] = base64.StdEncoding.EncodeToString(pngdat)
+    }
+    this.ServeJson(r.Format())
 }
 
 func (this *SalesCreateOrder) IsPaySuccess() {
-	defer qutil.Catch()
-	var userId string
-	rMap, err := func() (rData map[string]interface{}, err error) {
-		code := this.GetString("code")
-		userId, _, _, _, err = util.SellerTokenDecrypt(this.GetString("token"))
-		if err != nil {
-			return nil, err
-		}
-		if code != "" && userId != "" {
-			data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-				"order_code":    code,
-				"user_id":       userId,
-				"order_channel": "xdqd04",
-			}, "order_status,pay_time,user_mail,pay_way,pay_money,filter", "")
-			if data != nil && qutil.IntAll((*data)["order_status"]) == 1 {
-				t, _ := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*data)["pay_time"]), time.Local)
-				return map[string]interface{}{
-					"success":   true,
-					"email":     qutil.ObjToString((*data)["user_mail"]),
-					"payTime":   t.Unix(),
-					"pay_way":   (*data)["pay_way"],
-					"price":     (*data)["pay_money"],
-					"filter":    (*data)["filter"],
-					"orderCode": code,
-				}, nil
-			}
-		}
-		rData["success"] = false
-		return
-	}()
-	if err != nil {
-		log.Printf("%s SalesCreateOrder IsPaySuccess err:%v\n", userId, err.Error())
-	}
-	this.ServeJson(rMap)
+    defer qutil.Catch()
+    var userId string
+    rMap, err := func() (rData map[string]interface{}, err error) {
+        code := this.GetString("code")
+        userId, _, _, _, err = util.SellerTokenDecrypt(this.GetString("token"))
+        if err != nil {
+            return nil, err
+        }
+        if code != "" && userId != "" {
+            data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                "order_code":    code,
+                "user_id":       userId,
+                "order_channel": "xdqd04",
+            }, "order_status,pay_time,user_mail,pay_way,pay_money,filter", "")
+            if data != nil && qutil.IntAll((*data)["order_status"]) == 1 {
+                t, _ := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*data)["pay_time"]), time.Local)
+                return map[string]interface{}{
+                    "success":   true,
+                    "email":     qutil.ObjToString((*data)["user_mail"]),
+                    "payTime":   t.Unix(),
+                    "pay_way":   (*data)["pay_way"],
+                    "price":     (*data)["pay_money"],
+                    "filter":    (*data)["filter"],
+                    "orderCode": code,
+                }, nil
+            }
+        }
+        rData["success"] = false
+        return
+    }()
+    if err != nil {
+        log.Printf("%s SalesCreateOrder IsPaySuccess err:%v\n", userId, err.Error())
+    }
+    this.ServeJson(rMap)
 }
 
 // GetSubBuyMsg 获取购买订阅相关信息
 // 逻辑和vipSubscribeChange.go getSubBuyMsg 一致
 func (this *SalesCreateOrder) GetSubBuyMsg() {
-	var userId string
-	r := func() *entity.FuncResult {
-		userId, _, _, _, err := util.SellerTokenDecrypt(this.GetString("token"))
-		ent_id := qutil.IntAll(this.GetSession("entId"))
-		entUserId := qutil.IntAll(this.GetSession("entUserId"))
-		if err != nil {
-			return &entity.FuncResult{false, err, nil}
-		}
-		rData, buyset, vip := entity.JyVipSubStruct.GetVipDetail(userId)
-		if rData == nil || len(*rData) == 0 {
-			return &entity.FuncResult{false, errors.New("获取信息失败"), nil}
-		}
-		var isread = false
-		if (*rData)["isread"] != nil {
-			isread = (*rData)["isread"].(bool)
-		}
-		o_vipjy := &map[string]interface{}{}
-		//判断版本是企业的还是个人的
-		infoCount := util.Mysql.CountBySql("select  count(id) from  entniche_wait_empower where  ent_id=? and  end_time>NOW() and  product_type like '%VIP订阅%' ", ent_id)
-		if infoCount > 0 {
-			query := map[string]interface{}{
-				"i_userid": entUserId,
-				"i_entid":  ent_id,
-				"i_type":   1,
-			}
-			res, _ := util.MQFW.FindOne("entniche_rule", query)
-			if res != nil && len(*res) > 0 {
-				o_vipjy = qutil.ObjToMap((*res)["o_entniche"])
-			}
-		} else {
-			o_vipjy = qutil.ObjToMap((*rData)["o_vipjy"])
-		}
-		vipStatus := qutil.IntAll((*rData)["i_vip_status"])
-		var renewList *[]map[string]interface{}
-		if vipStatus == 2 { //查询是否有未执行的续费订单
-			renewList, _ = util.MQFW.Find("vip_upgrade", &bson.M{"s_userid": userId, "i_isvalid": 0}, `{"l_validtime":1}`, `{"o_buyset":1,"l_validtime":1}`, false, -1, -1)
-			for i := 0; i < len(*renewList); i++ {
-				delete((*renewList)[i], "_id")
-			}
-		}
-		bigPower := jy.GetBigVipUserBaseMsg(this.Session(), *config.Middleground)
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"isTrial":         vipStatus == 1,
-			"area":            (*o_vipjy)["o_area"],
-			"industry":        (*o_vipjy)["a_buyerclass"],
-			"buyset":          buyset,
-			"renewList":       renewList,
-			"infotype":        (*o_vipjy)["a_infotype"],
-			"items":           (*o_vipjy)["a_items"],
-			"projectmatch":    (*o_vipjy)["i_projectmatch"],
-			"ratemode":        (*o_vipjy)["i_ratemode"],
-			"matchway":        (*o_vipjy)["i_matchway"],
-			"startTime":       (*rData)["l_vip_starttime"],
-			"endTime":         (*rData)["l_vip_endtime"],
-			"otherbuyerclass": (*o_vipjy)["i_matchbuyerclass_other"],
-			"isread":          isread,
-			"isvip":           vip,
-			"isnew":           NewUserByVIP(userId, this.Session()), //免费订阅区分新老用户
-			"isUpgrade":       bigPower.IsUpgrade,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s SalesCreateOrder  GetSubBuyMsg err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+    var userId string
+    r := func() *entity.FuncResult {
+        userId, _, _, _, err := util.SellerTokenDecrypt(this.GetString("token"))
+        ent_id := qutil.IntAll(this.GetSession("entId"))
+        entUserId := qutil.IntAll(this.GetSession("entUserId"))
+        if err != nil {
+            return &entity.FuncResult{false, err, nil}
+        }
+        rData, buyset, vip := entity.JyVipSubStruct.GetVipDetail(userId)
+        if rData == nil || len(*rData) == 0 {
+            return &entity.FuncResult{false, errors.New("获取信息失败"), nil}
+        }
+        var isread = false
+        if (*rData)["isread"] != nil {
+            isread = (*rData)["isread"].(bool)
+        }
+        o_vipjy := &map[string]interface{}{}
+        //判断版本是企业的还是个人的
+        infoCount := util.Mysql.CountBySql("select  count(id) from  entniche_wait_empower where  ent_id=? and  end_time>NOW() and  product_type like '%VIP订阅%' ", ent_id)
+        if infoCount > 0 {
+            query := map[string]interface{}{
+                "i_userid": entUserId,
+                "i_entid":  ent_id,
+                "i_type":   1,
+            }
+            res, _ := util.MQFW.FindOne("entniche_rule", query)
+            if res != nil && len(*res) > 0 {
+                o_vipjy = qutil.ObjToMap((*res)["o_entniche"])
+            }
+        } else {
+            o_vipjy = qutil.ObjToMap((*rData)["o_vipjy"])
+        }
+        vipStatus := qutil.IntAll((*rData)["i_vip_status"])
+        var renewList *[]map[string]interface{}
+        if vipStatus == 2 { //查询是否有未执行的续费订单
+            renewList, _ = util.MQFW.Find("vip_upgrade", &bson.M{"s_userid": userId, "i_isvalid": 0}, `{"l_validtime":1}`, `{"o_buyset":1,"l_validtime":1}`, false, -1, -1)
+            for i := 0; i < len(*renewList); i++ {
+                delete((*renewList)[i], "_id")
+            }
+        }
+        bigPower := jy.GetBigVipUserBaseMsg(this.Session(), *config.Middleground)
+        return &entity.FuncResult{true, nil, map[string]interface{}{
+            "isTrial":         vipStatus == 1,
+            "area":            (*o_vipjy)["o_area"],
+            "industry":        (*o_vipjy)["a_buyerclass"],
+            "buyset":          buyset,
+            "renewList":       renewList,
+            "infotype":        (*o_vipjy)["a_infotype"],
+            "items":           (*o_vipjy)["a_items"],
+            "projectmatch":    (*o_vipjy)["i_projectmatch"],
+            "ratemode":        (*o_vipjy)["i_ratemode"],
+            "matchway":        (*o_vipjy)["i_matchway"],
+            "startTime":       (*rData)["l_vip_starttime"],
+            "endTime":         (*rData)["l_vip_endtime"],
+            "otherbuyerclass": (*o_vipjy)["i_matchbuyerclass_other"],
+            "isread":          isread,
+            "isvip":           vip,
+            "isnew":           NewUserByVIP(userId, this.Session()), //免费订阅区分新老用户
+            "isUpgrade":       bigPower.IsUpgrade,
+        }}
+    }()
+    if r.Err != nil {
+        log.Printf("%s SalesCreateOrder  GetSubBuyMsg err:%v\n", userId, r.Err.Error())
+    }
+    this.ServeJson(r.Format())
 }
 
 // GetSelectPrice 计算价格
 // 复制 vipSubscribePay.go getSelectPrice
 func (this *SalesCreateOrder) GetSelectPrice() {
-	var userId string
-	r := func() *entity.FuncResult {
-		userId, _, _, _, err := util.SellerTokenDecrypt(this.GetString("token"))
-		if err != nil {
-			return &entity.FuncResult{false, err, nil}
-		}
-		area := qutil.ObjToMap(this.GetString("area")) //地区
-		timeRenew := this.GetString("time")            //周期
-		orderType, _ := this.GetInteger("orderType")   //1 购买;2 续费;3 升级
-		//卡卷信息的id
-		lotteryId := this.GetString("lotteryId")
-		useProduct, _ := this.GetInteger("useProduct")
-		return CommonBilling(area, timeRenew, userId, lotteryId, orderType, useProduct, this.Session())
-	}()
-	if r.Err != nil {
-		log.Printf("%s 价格计算 err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+    var userId string
+    r := func() *entity.FuncResult {
+        userId, _, _, _, err := util.SellerTokenDecrypt(this.GetString("token"))
+        if err != nil {
+            return &entity.FuncResult{false, err, nil}
+        }
+        area := qutil.ObjToMap(this.GetString("area")) //地区
+        timeRenew := this.GetString("time")            //周期
+        orderType, _ := this.GetInteger("orderType")   //1 购买;2 续费;3 升级
+        //卡卷信息的id
+        lotteryId := this.GetString("lotteryId")
+        useProduct, _ := this.GetInteger("useProduct")
+        return CommonBilling(area, timeRenew, userId, lotteryId, orderType, useProduct, this.Session())
+    }()
+    if r.Err != nil {
+        log.Printf("%s 价格计算 err:%v\n", userId, r.Err.Error())
+    }
+    this.ServeJson(r.Format())
 }
 
 // GetValuationList 订单详情-计价清单
 // 逻辑与 orderListDetails.go GetValuationList保持一致
 func (this *SalesCreateOrder) GetValuationList() {
-	var userId string
-	r, err := func() (map[string]interface{}, error) {
-		userId, _, _, _, err := util.SellerTokenDecrypt(this.GetString("token"))
-		if err != nil {
-			return nil, err
-		}
-		order_code := this.GetString("order_code")
-		upgradeSubtotail := []map[string]interface{}{}
-		queryMap := map[string]interface{}{
-			"order_code": order_code,
-			"user_Id":    userId,
-		}
-		filter := util.Mysql.FindOne(tableName_order, queryMap, "filter,order_money", "")
-		if filter == nil {
-			return nil, fmt.Errorf("未知订单")
-		}
-		res := qutil.ObjToMap((*filter)["filter"])
-		upgradeSubtotail = qutil.ObjArrToMapArr((*res)["upgradeSubtotail"].([]interface{}))
-		if len(upgradeSubtotail) > 0 {
-			for _, v := range upgradeSubtotail {
-				//续费 没有oldBuyset
-				if v["oldBuyset"] == nil {
-					v["oldBuyset"] = (*res)["newBuyset"]
-				}
-			}
-		}
-		return map[string]interface{}{
-			"list":        upgradeSubtotail,
-			"order_money": (*filter)["order_money"],
-		}, nil
-	}()
-	if err != nil {
-		log.Printf("%s 价格计算 err:%v\n", userId, r)
-	}
-	this.ServeJson(r)
+    var userId string
+    r, err := func() (map[string]interface{}, error) {
+        userId, _, _, _, err := util.SellerTokenDecrypt(this.GetString("token"))
+        if err != nil {
+            return nil, err
+        }
+        order_code := this.GetString("order_code")
+        upgradeSubtotail := []map[string]interface{}{}
+        queryMap := map[string]interface{}{
+            "order_code": order_code,
+            "user_Id":    userId,
+        }
+        filter := util.Mysql.FindOne(tableName_order, queryMap, "filter,order_money", "")
+        if filter == nil {
+            return nil, fmt.Errorf("未知订单")
+        }
+        res := qutil.ObjToMap((*filter)["filter"])
+        upgradeSubtotail = qutil.ObjArrToMapArr((*res)["upgradeSubtotail"].([]interface{}))
+        if len(upgradeSubtotail) > 0 {
+            for _, v := range upgradeSubtotail {
+                //续费 没有oldBuyset
+                if v["oldBuyset"] == nil {
+                    v["oldBuyset"] = (*res)["newBuyset"]
+                }
+            }
+        }
+        return map[string]interface{}{
+            "list":        upgradeSubtotail,
+            "order_money": (*filter)["order_money"],
+        }, nil
+    }()
+    if err != nil {
+        log.Printf("%s 价格计算 err:%v\n", userId, r)
+    }
+    this.ServeJson(r)
 }
 
 // GetPrice 销售代下单 支付价格
 // 逻辑和vipSubscribeChange.go GetPrice 一致
 func (this *SalesCreateOrder) GetPrice() {
-	res := map[string]interface{}{
-		"isActiving": true,
-		"isWritten":  0,
-	}
-	j, _ := json.Marshal(&entity.SubVipPrice)
-	_ = json.Unmarshal(j, &res)
-	userId, _, _, _, _ := util.SellerTokenDecrypt(this.GetString("token"))
-	if userId != "" {
-		data := util.Compatible.Select(userId, `{"i_member_give":1}`)
-		if data != nil && *data != nil {
-			//已录入信息 已激活大会员赠送
-			if (*data)["i_member_give"] != nil {
-				res["isWritten"] = qutil.IntAll((*data)["i_member_give"])
-			}
-		}
-	}
-	this.ServeJson(res)
+    res := map[string]interface{}{
+        "isActiving": true,
+        "isWritten":  0,
+    }
+    j, _ := json.Marshal(&entity.SubVipPrice)
+    _ = json.Unmarshal(j, &res)
+    userId, _, _, _, _ := util.SellerTokenDecrypt(this.GetString("token"))
+    if userId != "" {
+        data := util.Compatible.Select(userId, `{"i_member_give":1}`)
+        if data != nil && *data != nil {
+            //已录入信息 已激活大会员赠送
+            if (*data)["i_member_give"] != nil {
+                res["isWritten"] = qutil.IntAll((*data)["i_member_give"])
+            }
+        }
+    }
+    this.ServeJson(res)
 }
 
 // GetOrderPayAllMsg 代付订单详情页
 func (o *SalesCreateOrder) GetOrderPayAllMsg() {
-	order_code := o.GetString("orderCode")
-	token := o.GetString("token")
+    order_code := o.GetString("orderCode")
+    token := o.GetString("token")
 
-	data := map[string]interface{}{}
-	var (
-		r             entity.FuncResult
-		transactionId string
-	)
-	t := make(map[string]interface{})
-	if order_code != "" && token != "" {
-		fields := "order_code,user_id"
-		info := map[string]interface{}{}
-		userId, _, _, _, err := util.SellerTokenDecrypt(token)
-		if err != nil {
-			r.Err = errors.New("获取订单信息失败")
-			goto env
-		}
-		info["order_code"] = order_code
-		info["user_id"] = userId
-		info["order_channel"] = "xdqd04"
-		dataMap := util.Mysql.FindOne(tableName_order, info, fields, "")
-		if dataMap != nil && len(*dataMap) > 0 {
-			data = *dataMap
-			//查询userid
-			//userId := qutil.InterfaceToStr(data["user_id"])
-			//if userId == "" {
-			//	r.Err = errors.New("获取订单信息失败")
-			//	goto env
-			//}
-			field := "id,order_code,del_status,prepay_time,create_time,pay_time,pay_way,user_phone,original_price,order_money,pay_money,applybill_status,out_trade_no,filter,product_type,order_status,applybill_type,applybill_taxnum,applybill_company,vip_starttime,vip_endtime,vip_type,discount_price,d_relation_id,billingMode,return_status,is_backstage_order,vip_starttime,vip_endtime"
-			data, t, transactionId = CommonDetail(4, field, userId, order_code, o.Session())
-			//如果手机号号为空查找通过userid查找手机号
-			//if qutil.InterfaceToStr(data["user_phone"]) == "" {
-			dataPhone, _ := util.MQFW.FindById("user", userId, "s_phone,s_m_phone")
-			sPhone := qutil.InterfaceToStr((*dataPhone)["s_phone"])
-			data["user_phone"] = qutil.If(sPhone == "", qutil.InterfaceToStr((*dataPhone)["s_m_phone"]), sPhone)
-			dataMapSta := make(map[string]interface{})
-			if qutil.IntAll(data["del_status"]) == 1 || qutil.IntAll(data["order_status"]) == -1 {
-				dataMapSta["del_status"] = qutil.IntAll(data["del_status"])
-				dataMapSta["order_status"] = qutil.IntAll(data["order_status"])
-			} else {
-				dataMapSta = data
-			}
-			//}
-			r.Success = true
-			r.Data = map[string]interface{}{
-				"order":          dataMapSta,
-				"time":           t,
-				"transaction_id": transactionId,
-			}
-		}
-	}
+    data := map[string]interface{}{}
+    var (
+        r             entity.FuncResult
+        transactionId string
+    )
+    t := make(map[string]interface{})
+    if order_code != "" && token != "" {
+        fields := "order_code,user_id"
+        info := map[string]interface{}{}
+        userId, _, _, _, err := util.SellerTokenDecrypt(token)
+        if err != nil {
+            r.Err = errors.New("获取订单信息失败")
+            goto env
+        }
+        info["order_code"] = order_code
+        info["user_id"] = userId
+        info["order_channel"] = "xdqd04"
+        dataMap := util.Mysql.FindOne(tableName_order, info, fields, "")
+        if dataMap != nil && len(*dataMap) > 0 {
+            data = *dataMap
+            //查询userid
+            //userId := qutil.InterfaceToStr(data["user_id"])
+            //if userId == "" {
+            //	r.Err = errors.New("获取订单信息失败")
+            //	goto env
+            //}
+            field := "id,order_code,del_status,prepay_time,create_time,pay_time,pay_way,user_phone,original_price,order_money,pay_money,applybill_status,out_trade_no,filter,product_type,order_status,applybill_type,applybill_taxnum,applybill_company,vip_starttime,vip_endtime,vip_type,discount_price,d_relation_id,billingMode,return_status,is_backstage_order,vip_starttime,vip_endtime"
+            data, t, transactionId = CommonDetail(4, field, userId, order_code, o.Session())
+            //如果手机号号为空查找通过userid查找手机号
+            //if qutil.InterfaceToStr(data["user_phone"]) == "" {
+            dataPhone := util.Compatible.Select(userId, "s_phone,s_m_phone")
+            sPhone := qutil.InterfaceToStr((*dataPhone)["s_phone"])
+            data["user_phone"] = qutil.If(sPhone == "", qutil.InterfaceToStr((*dataPhone)["s_m_phone"]), sPhone)
+            dataMapSta := make(map[string]interface{})
+            if qutil.IntAll(data["del_status"]) == 1 || qutil.IntAll(data["order_status"]) == -1 {
+                dataMapSta["del_status"] = qutil.IntAll(data["del_status"])
+                dataMapSta["order_status"] = qutil.IntAll(data["order_status"])
+            } else {
+                dataMapSta = data
+            }
+            //}
+            r.Success = true
+            r.Data = map[string]interface{}{
+                "order":          dataMapSta,
+                "time":           t,
+                "transaction_id": transactionId,
+            }
+        }
+    }
 env:
-	o.ServeJson(r.Format())
+    o.ServeJson(r.Format())
 }

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 574 - 574
src/jfw/modules/subscribepay/src/service/userAccountInfo.go


+ 610 - 642
src/jfw/modules/subscribepay/src/service/vipSubscribeChange.go

@@ -1,684 +1,652 @@
 package service
 
 import (
-	"encoding/json"
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/entity"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"math"
-	"strings"
-	"time"
-
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"go.mongodb.org/mongo-driver/bson"
+    "encoding/json"
+    "errors"
+    "fmt"
+    "jy/src/jfw/modules/subscribepay/src/config"
+    "jy/src/jfw/modules/subscribepay/src/entity"
+    "jy/src/jfw/modules/subscribepay/src/pay"
+    "jy/src/jfw/modules/subscribepay/src/util"
+    "log"
+    "math"
+    "strings"
+    "time"
+
+    qutil "app.yhyue.com/moapp/jybase/common"
+    . "app.yhyue.com/moapp/jybase/date"
+    "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+    "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+    "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+    "go.mongodb.org/mongo-driver/bson"
 )
 
 //订阅修改 or 升级
 type SubscribeChange struct {
-	*xweb.Action
-	getSubBuyMsg   xweb.Mapper `xweb:"/vipsubscribe/getSubBuyMsg"`   //获取vip订阅详情
-	saveChange     xweb.Mapper `xweb:"/vipsubscribe/saveChange"`     //订阅修改
-	mergeIndustry  xweb.Mapper `xweb:"/vipsubscribe/mergeIndustry"`  //行业合并
-	upgrade        xweb.Mapper `xweb:"/vipsubscribe/upgrade"`        //升级超级订阅
-	freeSaveChange xweb.Mapper `xweb:"/vipsubscribe/freeSaveChange"` //免费用户试用超级订阅
+    *xweb.Action
+    getSubBuyMsg   xweb.Mapper `xweb:"/vipsubscribe/getSubBuyMsg"`   //获取vip订阅详情
+    saveChange     xweb.Mapper `xweb:"/vipsubscribe/saveChange"`     //订阅修改
+    mergeIndustry  xweb.Mapper `xweb:"/vipsubscribe/mergeIndustry"`  //行业合并
+    upgrade        xweb.Mapper `xweb:"/vipsubscribe/upgrade"`        //升级超级订阅
+    freeSaveChange xweb.Mapper `xweb:"/vipsubscribe/freeSaveChange"` //免费用户试用超级订阅
 }
 
 func init() {
-	xweb.AddAction(&SubscribeChange{})
+    xweb.AddAction(&SubscribeChange{})
 }
 
 //获取购买订阅相关信息
 func (this *SubscribeChange) GetSubBuyMsg() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		ent_id := qutil.IntAll(this.GetSession("entId"))
-		entUserId := qutil.IntAll(this.GetSession("entUserId"))
-		rData, buyset, vip := entity.JyVipSubStruct.GetVipDetail(userId)
-		if rData == nil || len(*rData) == 0 {
-			return &entity.FuncResult{false, errors.New("获取信息失败"), nil}
-		}
-		var isread = false
-		if (*rData)["isread"] != nil {
-			isread = (*rData)["isread"].(bool)
-		}
-		o_vipjy := &map[string]interface{}{}
-		//判断版本是企业的还是个人的
-		infoCount := util.Mysql.CountBySql("select  count(id) from  entniche_wait_empower where  ent_id=? and  end_time>NOW() and  product_type like '%VIP订阅%' ", ent_id)
-		if infoCount > 0 {
-			query := map[string]interface{}{
-				"i_userid": entUserId,
-				"i_entid":  ent_id,
-				"i_type":   1,
-			}
-			res, _ := util.MQFW.FindOne("entniche_rule", query)
-			if res != nil && len(*res) > 0 {
-				o_vipjy = qutil.ObjToMap((*res)["o_entniche"])
-			}
-		} else {
-			o_vipjy = qutil.ObjToMap((*rData)["o_vipjy"])
-		}
-
-		vipStatus := qutil.IntAll((*rData)["i_vip_status"])
-		var renewList *[]map[string]interface{}
-		if vipStatus == 2 { //查询是否有未执行的续费订单
-			renewList, _ = util.MQFW.Find("vip_upgrade", &bson.M{"s_userid": userId, "i_isvalid": 0}, `{"l_validtime":1}`, `{"o_buyset":1,"l_validtime":1}`, false, -1, -1)
-			for i := 0; i < len(*renewList); i++ {
-				delete((*renewList)[i], "_id")
-			}
-		}
-		bigPower := jy.GetBigVipUserBaseMsg(this.Session(), *config.Middleground)
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"isTrial":         vipStatus == 1,
-			"area":            (*o_vipjy)["o_area"],
-			"industry":        (*o_vipjy)["a_buyerclass"],
-			"buyset":          buyset,
-			"renewList":       renewList,
-			"infotype":        (*o_vipjy)["a_infotype"],
-			"items":           (*o_vipjy)["a_items"],
-			"projectmatch":    (*o_vipjy)["i_projectmatch"],
-			"ratemode":        (*o_vipjy)["i_ratemode"],
-			"matchway":        (*o_vipjy)["i_matchway"],
-			"startTime":       (*rData)["l_vip_starttime"],
-			"endTime":         (*rData)["l_vip_endtime"],
-			"otherbuyerclass": (*o_vipjy)["i_matchbuyerclass_other"],
-			"isread":          isread,
-			"isvip":           vip,
-			"isnew":           NewUserByVIP(userId, this.Session()), //免费订阅区分新老用户
-			"key_max_length":  qutil.If(vip, config.Config.VipKeyMaxLength, 10),
-			"isUpgrade":       bigPower.IsUpgrade,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s GetSubBuyMsg err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    r := func() *entity.FuncResult {
+        ent_id := qutil.IntAll(this.GetSession("entId"))
+        entUserId := qutil.IntAll(this.GetSession("entUserId"))
+        rData, buyset, vip := entity.JyVipSubStruct.GetVipDetail(userId)
+        if rData == nil || len(*rData) == 0 {
+            return &entity.FuncResult{false, errors.New("获取信息失败"), nil}
+        }
+        var isread = false
+        if (*rData)["isread"] != nil {
+            isread = (*rData)["isread"].(bool)
+        }
+        o_vipjy := &map[string]interface{}{}
+        //判断版本是企业的还是个人的
+        infoCount := util.Mysql.CountBySql("select  count(id) from  entniche_wait_empower where  ent_id=? and  end_time>NOW() and  product_type like '%VIP订阅%' ", ent_id)
+        if infoCount > 0 {
+            query := map[string]interface{}{
+                "i_userid": entUserId,
+                "i_entid":  ent_id,
+                "i_type":   1,
+            }
+            res, _ := util.MQFW.FindOne("entniche_rule", query)
+            if res != nil && len(*res) > 0 {
+                o_vipjy = qutil.ObjToMap((*res)["o_entniche"])
+            }
+        } else {
+            o_vipjy = qutil.ObjToMap((*rData)["o_vipjy"])
+        }
+
+        vipStatus := qutil.IntAll((*rData)["i_vip_status"])
+        var renewList *[]map[string]interface{}
+        if vipStatus == 2 { //查询是否有未执行的续费订单
+            renewList, _ = util.MQFW.Find("vip_upgrade", &bson.M{"s_userid": userId, "i_isvalid": 0}, `{"l_validtime":1}`, `{"o_buyset":1,"l_validtime":1}`, false, -1, -1)
+            for i := 0; i < len(*renewList); i++ {
+                delete((*renewList)[i], "_id")
+            }
+        }
+        bigPower := jy.GetBigVipUserBaseMsg(this.Session(), *config.Middleground)
+        return &entity.FuncResult{true, nil, map[string]interface{}{
+            "isTrial":         vipStatus == 1,
+            "area":            (*o_vipjy)["o_area"],
+            "industry":        (*o_vipjy)["a_buyerclass"],
+            "buyset":          buyset,
+            "renewList":       renewList,
+            "infotype":        (*o_vipjy)["a_infotype"],
+            "items":           (*o_vipjy)["a_items"],
+            "projectmatch":    (*o_vipjy)["i_projectmatch"],
+            "ratemode":        (*o_vipjy)["i_ratemode"],
+            "matchway":        (*o_vipjy)["i_matchway"],
+            "startTime":       (*rData)["l_vip_starttime"],
+            "endTime":         (*rData)["l_vip_endtime"],
+            "otherbuyerclass": (*o_vipjy)["i_matchbuyerclass_other"],
+            "isread":          isread,
+            "isvip":           vip,
+            "isnew":           NewUserByVIP(userId, this.Session()), //免费订阅区分新老用户
+            "key_max_length":  qutil.If(vip, config.Config.VipKeyMaxLength, 10),
+            "isUpgrade":       bigPower.IsUpgrade,
+        }}
+    }()
+    if r.Err != nil {
+        log.Printf("%s GetSubBuyMsg err:%v\n", userId, r.Err.Error())
+    }
+    this.ServeJson(r.Format())
 }
 
 //订阅修改
 func (this *SubscribeChange) SaveChange() {
-	area := qutil.ObjToMap(this.GetString("area"))
-	industry := strings.Split(this.GetString("industry"), ",")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		if len(industry) == 1 && industry[0] == "" {
-			industry = []string{}
-		}
-		rData, oldBuyset, isVip := entity.JyVipSubStruct.GetVipDetail(userId)
-		if !isVip {
-			return &entity.FuncResult{false, errors.New("请求异常,非vip状态"), nil}
-		}
-		if rData == nil || len(*rData) == 0 {
-			return &entity.FuncResult{false, errors.New("获取信息失败"), nil}
-		}
-		newBuyset := entity.JyVipSubStruct.NewBuySet(area, industry, oldBuyset.Upgrade == 1)
-		if needUpgrade := needUpgrade(newBuyset, oldBuyset); needUpgrade {
-			log.Printf("%s 订阅内容超出套餐 %+v area:%s industry:%s", userId, oldBuyset, this.GetString("area"), this.GetString("industry"))
-			return &entity.FuncResult{false, errors.New("订阅内容超出套餐"), nil}
-		}
-		if !entity.JyVipSubStruct.SubChange(userId, qutil.ObjToMap((*rData)["o_vipjy"]), area, industry, this.Session()) {
-			return &entity.FuncResult{false, errors.New("保存修改出错"), nil}
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"doSuccess": true,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s SaveChange err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+    area := qutil.ObjToMap(this.GetString("area"))
+    industry := strings.Split(this.GetString("industry"), ",")
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    r := func() *entity.FuncResult {
+        if len(industry) == 1 && industry[0] == "" {
+            industry = []string{}
+        }
+        rData, oldBuyset, isVip := entity.JyVipSubStruct.GetVipDetail(userId)
+        if !isVip {
+            return &entity.FuncResult{false, errors.New("请求异常,非vip状态"), nil}
+        }
+        if rData == nil || len(*rData) == 0 {
+            return &entity.FuncResult{false, errors.New("获取信息失败"), nil}
+        }
+        newBuyset := entity.JyVipSubStruct.NewBuySet(area, industry, oldBuyset.Upgrade == 1)
+        if needUpgrade := needUpgrade(newBuyset, oldBuyset); needUpgrade {
+            log.Printf("%s 订阅内容超出套餐 %+v area:%s industry:%s", userId, oldBuyset, this.GetString("area"), this.GetString("industry"))
+            return &entity.FuncResult{false, errors.New("订阅内容超出套餐"), nil}
+        }
+        if !entity.JyVipSubStruct.SubChange(userId, qutil.ObjToMap((*rData)["o_vipjy"]), area, industry, this.Session()) {
+            return &entity.FuncResult{false, errors.New("保存修改出错"), nil}
+        }
+        return &entity.FuncResult{true, nil, map[string]interface{}{
+            "doSuccess": true,
+        }}
+    }()
+    if r.Err != nil {
+        log.Printf("%s SaveChange err:%v\n", userId, r.Err.Error())
+    }
+    this.ServeJson(r.Format())
 }
 
 //免费用户设置超级订阅(体验)
 func (this *SubscribeChange) FreeSaveChange() {
-	area := qutil.ObjToMap(this.GetString("area"))
-	industry := strings.Split(this.GetString("industry"), ",")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		if len(industry) == 1 && industry[0] == "" {
-			industry = []string{}
-		}
-		positionType := qutil.Int64All(this.GetSession("positionType"))
-		vipType := "o_vipjy"
-		if positionType == 1 {
-			vipType = "o_entniche"
-		}
-		saveData := bson.M{"$set": bson.M{
-			vipType + ".o_area":       area,     //设置地区
-			vipType + ".a_buyerclass": industry, //设置行业
-		}}
-		updateOk := false
-		if positionType == 0 {
-			updateOk = util.MQFW.UpdateById("user", userId,
-				bson.M{"$set": saveData})
-		} else {
-			query := map[string]interface{}{
-				"i_userid": qutil.Int64All(this.GetSession("entUserId")),
-				"i_entid":  qutil.Int64All(this.GetSession("entId")),
-				"i_type":   1,
-			}
-			updateOk = util.MQFW.Update("entniche_rule", query,
-				bson.M{"$set": saveData}, true, false)
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"doSuccess": updateOk,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s SaveChange err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+    area := qutil.ObjToMap(this.GetString("area"))
+    industry := strings.Split(this.GetString("industry"), ",")
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    r := func() *entity.FuncResult {
+        if len(industry) == 1 && industry[0] == "" {
+            industry = []string{}
+        }
+        vipType := "o_vipjy"
+        saveData := bson.M{"$set": bson.M{
+            vipType + ".o_area":       area,     //设置地区
+            vipType + ".a_buyerclass": industry, //设置行业
+        }}
+        updateOk := util.Compatible.Update(userId,
+            bson.M{"$set": saveData})
+        return &entity.FuncResult{true, nil, map[string]interface{}{
+            "doSuccess": updateOk,
+        }}
+    }()
+    if r.Err != nil {
+        log.Printf("%s SaveChange err:%v\n", userId, r.Err.Error())
+    }
+    this.ServeJson(r.Format())
 }
 
 //升级订阅
 func (this *SubscribeChange) Upgrade() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		area_count, _ := this.GetInteger("area_count") //地区
-		area := qutil.ObjToMap(this.GetString("area")) //地区
-
-		timeRenew := this.GetString("time")      //周期
-		req_price, _ := this.GetInteger("price") //前端展示金额
-		openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-		order_phone := this.GetString("order_phone") //p19.3用户信息采集 手机号
-
-		rData, oldBuyset, isVip := entity.JyVipSubStruct.GetVipDetail(userId)
-		if !isVip {
-			return &entity.FuncResult{false, errors.New("请求异常,非vip状态"), nil}
-		}
-
-		now := time.Now()
-		date_count, date_unit, needRenew := 0, 0, false
-		endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
-		startUnix := qutil.Int64All((*rData)["l_vip_starttime"])
-		if timeRenew != "" {
-			var err error
-			date_count, date_unit, err = entity.JyVipSubStruct.CheckReqDate(timeRenew)
-			if err != nil {
-				return &entity.FuncResult{false, errors.New("格式化日期出错"), nil}
-			}
-			isTrail := qutil.IntAll((*rData)["i_vip_status"]) == 1
-			//校验是否超过三年
-			if time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).
-				AddDate(3, 0, 0).Before(util.GetDATE(date_unit, date_count, endUnix)) && !isTrail {
-				return &entity.FuncResult{false, errors.New("订阅周期超过三年"), nil}
-			}
-			needRenew = true
-		}
-		area_select := true                     //是否回显城市选择
-		if len(*area) == 0 && area_count != 0 { //升级时为传入选择省份
-			(*area)["areacount"] = area_count
-			area_select = false
-		}
-		newBuyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
-
-		//升级校验
-		totalPrice, subtotail := getNewUpgradeDetail(userId, newBuyset, oldBuyset, endUnix, date_count, date_unit)
-		if totalPrice < 0 {
-			if totalPrice == -1 {
-				return &entity.FuncResult{false, errors.New("不能升级此状态"), nil}
-			} else {
-				return &entity.FuncResult{false, errors.New("查询续费订单出错"), nil}
-			}
-		}
-
-		filter := entity.VipSimpleMsg{
-			Industry:         []string{}, //行业保存默认选择
-			Cyclecount:       date_count,
-			Cycleunit:        date_unit,
-			OldBuyset:        oldBuyset,
-			NewBuyset:        newBuyset,
-			UpgradeSubtotail: subtotail,
-			OrderType:        3,
-			DisWord:          "",
-		}
-		if area_select {
-			filter.Area = area
-		}
-
-		var startTime, endTime time.Time = time.Unix(startUnix, 0), time.Unix(endUnix, 0)
-		if needRenew {
-			startTime = now
-			if needRenew {
-				endTime = util.GetDATE(filter.Cycleunit, filter.Cyclecount, endUnix)
-			} else {
-				endTime = time.Unix(endUnix, 0)
-			}
-		}
-
-		final_price, discount_price := totalPrice, 0
-		if req_price != final_price {
-			return &entity.FuncResult{false, errors.New(fmt.Sprintf("金额校验异常[%d,%d]", final_price, req_price)), nil}
-		}
-		order_status := 0
-		//老用户 0元升级
-		if req_price == 0 && 0 == final_price {
-			if oldBuyset.Upgrade == 0 {
-				order_status = 1
-			} else {
-				return &entity.FuncResult{false, errors.New("超级订阅升级异常"), nil}
-			}
-		}
-		//卡卷使用
-		userLotteryId, lotteryId := "", this.GetString("lotteryId")
-		full_price, reduce_price := 0, 0
-		var discount float64
-		if lotteryId != "" {
-			full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, config.CouponConfig.Products["超级订阅"])
-			if reduce_price > 0 && full_price <= final_price {
-				if discount == 100 {
-					final_price = final_price - reduce_price
-					discount_price = reduce_price
-				} else {
-					//折扣
-					disCount_int := int(math.Ceil(discount * 100))
-					discount_price = final_price - final_price*disCount_int/1000
-					final_price = final_price * disCount_int / 1000
-				}
-			} else {
-				userLotteryId = ""
-			}
-		}
-		//测试打折
-		if entity.SubVipPrice.Discount < 1 {
-			tmp := float64(final_price) * entity.SubVipPrice.Discount
-			if tmp < 1 {
-				if tmp != 0 {
-					final_price = 1
-				}
-			} else {
-				final_price = int(tmp)
-			}
-		}
-
-		//创建订单
-		filterStr, err := json.Marshal(filter)
-		if err != nil {
-			return &entity.FuncResult{false, errors.New("订单数据生成异常"), nil}
-		}
-		disWord := ""
-		//查询用户是否有分销链接
-		disWordStr := ""
-		userfilter, ok := util.MQFW.FindById("user", userId, "")
-		if ok && userfilter != nil {
-			startTime := qutil.Int64All((*userfilter)["startTime"])
-			endTime := qutil.Int64All((*userfilter)["endTime"])
-			if startTime != 0 {
-				if startTime <= time.Now().Unix() && endTime >= time.Now().Unix() {
-					disWordStr = qutil.ObjToString((*userfilter)["disWords"])
-				}
-			}
-		}
-		if disWordStr != "" {
-			disWord = disWordStr
-		}
-		ordercode := pay.GetOrderCode(userId)
-		/*if disWord == "" {
-			start_time := TimeProcessing(time.Now().Format(DateFullLayout), -config.Config.TermValidity).Format(DateFullLayout)
-			stop_time := TimeProcessing(time.Now().Format(DateFullLayout), config.Config.TermValidity).Format(DateFullLayout)
-			infoList := util.Mysql.SelectBySql("select  * from  dis_word where userId=?  and  ?<=start_time  and stop_time<? ORDER BY id ", userId, start_time, stop_time)
-			if len(*infoList) != 0 {
-				disWord = fmt.Sprint((*infoList)[0]["password"])
-			}
-		}*/
-		distributionChannel, orderChannel := util.GetJyOrderChannel(disWord, this.Header("User-Agent"))
-		entId := qutil.Int64All(this.GetSession("entId"))
-		buy_subject := 1
-		if entId > 0 {
-			buy_subject = 2
-		}
-		insertMap := map[string]interface{}{
-			"order_money":          final_price,
-			"order_status":         order_status,
-			"user_openid":          openId,
-			"order_code":           ordercode,
-			"product_type":         "VIP订阅",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       final_price + discount_price, //原价
-			"filter_id":            "",
-			"user_id":              userId,
-			"filter":               string(filterStr), //筛选
-			"vip_endtime":          FormatDate(&endTime, Date_Full_Layout),
-			"vip_starttime":        FormatDate(&startTime, Date_Full_Layout),
-			"discount_price":       discount_price,
-			"d_relation_id":        userLotteryId,
-			"vip_type":             2, //立即升级
-			"user_phone":           order_phone,
-			"dis_word":             disWord,
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-			"buy_subject":          buy_subject,
-			"ent_id":               entId,
-		}
-		if order_phone != "" {
-			if !jy.PhoneReg.MatchString(order_phone) {
-				return &entity.FuncResult{false, errors.New("手机号格式异常"), nil}
-			}
-		} else if userfilter == nil || len(*userfilter) > 0 {
-			order_phone, _ = qutil.If((*userfilter)["s_phone"] != nil, (*userfilter)["s_phone"], (*userfilter)["s_m_phone"]).(string)
-
-		}
-		insertMap["user_phone"] = order_phone
-		orderid := util.Mysql.Insert("dataexport_order", insertMap)
-		if orderid == -1 {
-			return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
-		}
-		//老用户升级 一个省 全行业 时间不变 会出现零元升级得情况 0元升级直接到支付成功页面 开通超级订阅
-		if req_price == 0 && 0 == final_price && oldBuyset.Upgrade == 0 {
-			//后期
-			if !entity.JyVipSubStruct.StartSubVip(userId, filter, time.Unix(startUnix, 0), time.Unix(endUnix, 0), false, 0, 0, 0) {
-				return &entity.FuncResult{false, errors.New("老用户升级超级订阅高版本异常"), nil}
-			}
-			return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode, "needPay": false}}
-		}
-		//绑定卡卷
-		if userLotteryId != "" && lotteryId != "" {
-			go func(userId, userLotteryId, order_code string) {
-				nickname, _ := this.Session().Get("s_nickname").(string)
-				if !util.UpdateCouponState(userId, userLotteryId, nickname, order_phone, order_code, "VIP订阅", "", 3, 0) {
-					log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-				}
-			}(userId, userLotteryId, ordercode)
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode, "needPay": true}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s Upgrade err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    r := func() *entity.FuncResult {
+        area_count, _ := this.GetInteger("area_count") //地区
+        area := qutil.ObjToMap(this.GetString("area")) //地区
+
+        timeRenew := this.GetString("time")      //周期
+        req_price, _ := this.GetInteger("price") //前端展示金额
+        openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+        order_phone := this.GetString("order_phone") //p19.3用户信息采集 手机号
+
+        rData, oldBuyset, isVip := entity.JyVipSubStruct.GetVipDetail(userId)
+        if !isVip {
+            return &entity.FuncResult{false, errors.New("请求异常,非vip状态"), nil}
+        }
+
+        now := time.Now()
+        date_count, date_unit, needRenew := 0, 0, false
+        endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
+        startUnix := qutil.Int64All((*rData)["l_vip_starttime"])
+        if timeRenew != "" {
+            var err error
+            date_count, date_unit, err = entity.JyVipSubStruct.CheckReqDate(timeRenew)
+            if err != nil {
+                return &entity.FuncResult{false, errors.New("格式化日期出错"), nil}
+            }
+            isTrail := qutil.IntAll((*rData)["i_vip_status"]) == 1
+            //校验是否超过三年
+            if time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).
+                AddDate(3, 0, 0).Before(util.GetDATE(date_unit, date_count, endUnix)) && !isTrail {
+                return &entity.FuncResult{false, errors.New("订阅周期超过三年"), nil}
+            }
+            needRenew = true
+        }
+        area_select := true                     //是否回显城市选择
+        if len(*area) == 0 && area_count != 0 { //升级时为传入选择省份
+            (*area)["areacount"] = area_count
+            area_select = false
+        }
+        newBuyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
+
+        //升级校验
+        totalPrice, subtotail := getNewUpgradeDetail(userId, newBuyset, oldBuyset, endUnix, date_count, date_unit)
+        if totalPrice < 0 {
+            if totalPrice == -1 {
+                return &entity.FuncResult{false, errors.New("不能升级此状态"), nil}
+            } else {
+                return &entity.FuncResult{false, errors.New("查询续费订单出错"), nil}
+            }
+        }
+
+        filter := entity.VipSimpleMsg{
+            Industry:         []string{}, //行业保存默认选择
+            Cyclecount:       date_count,
+            Cycleunit:        date_unit,
+            OldBuyset:        oldBuyset,
+            NewBuyset:        newBuyset,
+            UpgradeSubtotail: subtotail,
+            OrderType:        3,
+            DisWord:          "",
+        }
+        if area_select {
+            filter.Area = area
+        }
+
+        var startTime, endTime time.Time = time.Unix(startUnix, 0), time.Unix(endUnix, 0)
+        if needRenew {
+            startTime = now
+            if needRenew {
+                endTime = util.GetDATE(filter.Cycleunit, filter.Cyclecount, endUnix)
+            } else {
+                endTime = time.Unix(endUnix, 0)
+            }
+        }
+
+        final_price, discount_price := totalPrice, 0
+        if req_price != final_price {
+            return &entity.FuncResult{false, errors.New(fmt.Sprintf("金额校验异常[%d,%d]", final_price, req_price)), nil}
+        }
+        order_status := 0
+        //老用户 0元升级
+        if req_price == 0 && 0 == final_price {
+            if oldBuyset.Upgrade == 0 {
+                order_status = 1
+            } else {
+                return &entity.FuncResult{false, errors.New("超级订阅升级异常"), nil}
+            }
+        }
+        //卡卷使用
+        userLotteryId, lotteryId := "", this.GetString("lotteryId")
+        full_price, reduce_price := 0, 0
+        var discount float64
+        if lotteryId != "" {
+            full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, config.CouponConfig.Products["超级订阅"])
+            if reduce_price > 0 && full_price <= final_price {
+                if discount == 100 {
+                    final_price = final_price - reduce_price
+                    discount_price = reduce_price
+                } else {
+                    //折扣
+                    disCount_int := int(math.Ceil(discount * 100))
+                    discount_price = final_price - final_price*disCount_int/1000
+                    final_price = final_price * disCount_int / 1000
+                }
+            } else {
+                userLotteryId = ""
+            }
+        }
+        //测试打折
+        if entity.SubVipPrice.Discount < 1 {
+            tmp := float64(final_price) * entity.SubVipPrice.Discount
+            if tmp < 1 {
+                if tmp != 0 {
+                    final_price = 1
+                }
+            } else {
+                final_price = int(tmp)
+            }
+        }
+
+        //创建订单
+        filterStr, err := json.Marshal(filter)
+        if err != nil {
+            return &entity.FuncResult{false, errors.New("订单数据生成异常"), nil}
+        }
+        disWord := ""
+        //查询用户是否有分销链接
+        disWordStr := ""
+        userfilter, ok := util.MQFW.FindById("user", userId, "")
+        if ok && userfilter != nil {
+            startTime := qutil.Int64All((*userfilter)["startTime"])
+            endTime := qutil.Int64All((*userfilter)["endTime"])
+            if startTime != 0 {
+                if startTime <= time.Now().Unix() && endTime >= time.Now().Unix() {
+                    disWordStr = qutil.ObjToString((*userfilter)["disWords"])
+                }
+            }
+        }
+        if disWordStr != "" {
+            disWord = disWordStr
+        }
+        ordercode := pay.GetOrderCode(userId)
+        /*if disWord == "" {
+        	start_time := TimeProcessing(time.Now().Format(DateFullLayout), -config.Config.TermValidity).Format(DateFullLayout)
+        	stop_time := TimeProcessing(time.Now().Format(DateFullLayout), config.Config.TermValidity).Format(DateFullLayout)
+        	infoList := util.Mysql.SelectBySql("select  * from  dis_word where userId=?  and  ?<=start_time  and stop_time<? ORDER BY id ", userId, start_time, stop_time)
+        	if len(*infoList) != 0 {
+        		disWord = fmt.Sprint((*infoList)[0]["password"])
+        	}
+        }*/
+        distributionChannel, orderChannel := util.GetJyOrderChannel(disWord, this.Header("User-Agent"))
+        entId := qutil.Int64All(this.GetSession("entId"))
+        buy_subject := 1
+        if entId > 0 {
+            buy_subject = 2
+        }
+        insertMap := map[string]interface{}{
+            "order_money":          final_price,
+            "order_status":         order_status,
+            "user_openid":          openId,
+            "order_code":           ordercode,
+            "product_type":         "VIP订阅",
+            "create_time":          FormatDate(&now, Date_Full_Layout),
+            "original_price":       final_price + discount_price, //原价
+            "filter_id":            "",
+            "user_id":              userId,
+            "filter":               string(filterStr), //筛选
+            "vip_endtime":          FormatDate(&endTime, Date_Full_Layout),
+            "vip_starttime":        FormatDate(&startTime, Date_Full_Layout),
+            "discount_price":       discount_price,
+            "d_relation_id":        userLotteryId,
+            "vip_type":             2, //立即升级
+            "user_phone":           order_phone,
+            "dis_word":             disWord,
+            "distribution_channel": distributionChannel, //销售渠道
+            "order_channel":        orderChannel,        //下单渠道
+            "audit_status":         3,                   //默认审核通过
+            "buy_subject":          buy_subject,
+            "ent_id":               entId,
+        }
+        if order_phone != "" {
+            if !jy.PhoneReg.MatchString(order_phone) {
+                return &entity.FuncResult{false, errors.New("手机号格式异常"), nil}
+            }
+        } else if userfilter == nil || len(*userfilter) > 0 {
+            order_phone, _ = qutil.If((*userfilter)["s_phone"] != nil, (*userfilter)["s_phone"], (*userfilter)["s_m_phone"]).(string)
+
+        }
+        insertMap["user_phone"] = order_phone
+        orderid := util.Mysql.Insert("dataexport_order", insertMap)
+        if orderid == -1 {
+            return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
+        }
+        //老用户升级 一个省 全行业 时间不变 会出现零元升级得情况 0元升级直接到支付成功页面 开通超级订阅
+        if req_price == 0 && 0 == final_price && oldBuyset.Upgrade == 0 {
+            //后期
+            if !entity.JyVipSubStruct.StartSubVip(userId, filter, time.Unix(startUnix, 0), time.Unix(endUnix, 0), false, 0, 0, 0) {
+                return &entity.FuncResult{false, errors.New("老用户升级超级订阅高版本异常"), nil}
+            }
+            return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode, "needPay": false}}
+        }
+        //绑定卡卷
+        if userLotteryId != "" && lotteryId != "" {
+            go func(userId, userLotteryId, order_code string) {
+                nickname, _ := this.Session().Get("s_nickname").(string)
+                if !util.UpdateCouponState(userId, userLotteryId, nickname, order_phone, order_code, "VIP订阅", "", 3, 0) {
+                    log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                }
+            }(userId, userLotteryId, ordercode)
+        }
+        return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode, "needPay": true}}
+    }()
+    if r.Err != nil {
+        log.Printf("%s Upgrade err:%v\n", userId, r.Err.Error())
+    }
+    this.ServeJson(r.Format())
 }
 
 //获取新版超级订阅升级价格、清单
 func getNewUpgradeDetail(userId string, newBuySet, oldBuySet *entity.SubvipBuySet, oldEndtime int64, count, unit int) (totalPrice int, subtotals []map[string]interface{}) {
-	rResult, ok := util.MQFW.Find("vip_upgrade", &bson.M{"s_userid": userId, "i_isvalid": 0}, `{"l_validtime":1}`, `{"o_buyset":1,"l_validtime":1}`, false, -1, -1)
-	if !ok {
-		return -2, nil
-	}
-	nowEndTime := oldEndtime
-	if len(*rResult) != 0 {
-		for i := len(*rResult) - 1; i >= 0; i-- {
-			thisObj := qutil.ObjToMap((*rResult)[i])
-			thisStartTime := qutil.Int64All((*thisObj)["l_validtime"])
-			buySetMap := qutil.ObjToMap((*thisObj)["o_buyset"])
-			thisBuyset := entity.JyVipSubStruct.GetMergeNewBuyset(*buySetMap)
-
-			this_price := entity.JyVipSubStruct.GetSubtotalPrice(thisBuyset, newBuySet, qutil.Int64All((*thisObj)["l_validtime"]), nowEndTime)
-			if this_price < 0 {
-				return -1, nil
-			}
-			totalPrice += this_price
-			subtotals = append(subtotals, map[string]interface{}{
-				"type":      1,
-				"startTime": thisStartTime,
-				"endTime":   nowEndTime,
-				"price":     this_price,
-				"oldBuyset": thisBuyset,
-			})
-			nowEndTime = thisStartTime
-		}
-	}
-	//当前升级
-	now := time.Now()
-	price_now := entity.JyVipSubStruct.GetSubtotalPrice(oldBuySet, newBuySet, now.Unix(), nowEndTime)
-	if price_now < 0 {
-		return -1, nil
-	}
-	totalPrice += price_now
-	subtotals = append(subtotals, map[string]interface{}{
-		"type":      0,
-		"startTime": now.Unix(),
-		"endTime":   nowEndTime,
-		"price":     price_now,
-		"oldBuyset": oldBuySet,
-	})
-	//此次新增续费价格计算
-	if count > 0 {
-		renew_price := entity.JyVipSubStruct.GetSubVipPriceByBuySet(newBuySet, count, unit, false)
-		if renew_price < 0 {
-			return -1, nil
-		}
-		totalPrice += renew_price
-		subtotals = append(subtotals, map[string]interface{}{
-			"type":      2,
-			"startTime": oldEndtime,
-			"endTime":   util.GetDATE(unit, count, oldEndtime).Unix(),
-			"price":     renew_price,
-		})
-	}
-	log.Printf("%s升级所需费用%d 计价清单%v\n", userId, totalPrice, subtotals)
-	return totalPrice, subtotals
+    rResult, ok := util.MQFW.Find("vip_upgrade", &bson.M{"s_userid": userId, "i_isvalid": 0}, `{"l_validtime":1}`, `{"o_buyset":1,"l_validtime":1}`, false, -1, -1)
+    if !ok {
+        return -2, nil
+    }
+    nowEndTime := oldEndtime
+    if len(*rResult) != 0 {
+        for i := len(*rResult) - 1; i >= 0; i-- {
+            thisObj := qutil.ObjToMap((*rResult)[i])
+            thisStartTime := qutil.Int64All((*thisObj)["l_validtime"])
+            buySetMap := qutil.ObjToMap((*thisObj)["o_buyset"])
+            thisBuyset := entity.JyVipSubStruct.GetMergeNewBuyset(*buySetMap)
+
+            this_price := entity.JyVipSubStruct.GetSubtotalPrice(thisBuyset, newBuySet, qutil.Int64All((*thisObj)["l_validtime"]), nowEndTime)
+            if this_price < 0 {
+                return -1, nil
+            }
+            totalPrice += this_price
+            subtotals = append(subtotals, map[string]interface{}{
+                "type":      1,
+                "startTime": thisStartTime,
+                "endTime":   nowEndTime,
+                "price":     this_price,
+                "oldBuyset": thisBuyset,
+            })
+            nowEndTime = thisStartTime
+        }
+    }
+    //当前升级
+    now := time.Now()
+    price_now := entity.JyVipSubStruct.GetSubtotalPrice(oldBuySet, newBuySet, now.Unix(), nowEndTime)
+    if price_now < 0 {
+        return -1, nil
+    }
+    totalPrice += price_now
+    subtotals = append(subtotals, map[string]interface{}{
+        "type":      0,
+        "startTime": now.Unix(),
+        "endTime":   nowEndTime,
+        "price":     price_now,
+        "oldBuyset": oldBuySet,
+    })
+    //此次新增续费价格计算
+    if count > 0 {
+        renew_price := entity.JyVipSubStruct.GetSubVipPriceByBuySet(newBuySet, count, unit, false)
+        if renew_price < 0 {
+            return -1, nil
+        }
+        totalPrice += renew_price
+        subtotals = append(subtotals, map[string]interface{}{
+            "type":      2,
+            "startTime": oldEndtime,
+            "endTime":   util.GetDATE(unit, count, oldEndtime).Unix(),
+            "price":     renew_price,
+        })
+    }
+    log.Printf("%s升级所需费用%d 计价清单%v\n", userId, totalPrice, subtotals)
+    return totalPrice, subtotals
 }
 
 //是否需要升级
 func needUpgrade(newBuySet, oldBuySet *entity.SubvipBuySet) bool {
-	if newBuySet.Upgrade != 1 { //旧版本订阅是否需要升级校验
-		BuyerclassUpgrade, AreaNeedUpgrade := false, false
-		UpgradeBuyset := &entity.SubvipBuySet{
-			oldBuySet.Upgrade,
-			oldBuySet.AreaCount,
-			oldBuySet.NewCitys,
-			oldBuySet.BuyerclassCount,
-		}
-		//比较行业
-		if oldBuySet.BuyerclassCount != -1 {
-			//若当前买的不是全行业,并且当前行业数量小于新行业数量时
-			if oldBuySet.BuyerclassCount < newBuySet.BuyerclassCount || newBuySet.BuyerclassCount == -1 {
-				BuyerclassUpgrade = true
-				//计算升级后的buySet
-				UpgradeBuyset.BuyerclassCount = newBuySet.BuyerclassCount
-			}
-		}
-		//比较地区
-		if oldBuySet.AreaCount != -1 {
-			if newBuySet.AreaCount == -1 { //升级为全国
-				UpgradeBuyset.AreaCount = newBuySet.AreaCount
-				UpgradeBuyset.NewCitys = newBuySet.NewCitys
-				AreaNeedUpgrade = true
-			} else {
-				oldCitysBuyOne, oldCitysBuyTwo := 0, 0
-				newCitysBuyOne, newCitysBuyTwo := 0, 0
-				oldCopy := []int{} //复制(防止影响原数组)
-				for _, v := range oldBuySet.NewCitys {
-					if v == 1 {
-						oldCitysBuyOne++
-					} else {
-						oldCitysBuyTwo++
-					}
-					oldCopy = append(oldCopy, v)
-				}
-				UpgradeBuyset.NewCitys = oldCopy
-				for _, v := range newBuySet.NewCitys {
-					if v == 1 {
-						newCitysBuyOne++
-					} else {
-						newCitysBuyTwo++
-					}
-				}
-
-				p_Diff := newBuySet.AreaCount - oldBuySet.AreaCount
-				c_1_diff := newCitysBuyOne - oldCitysBuyOne
-				c_2_diff := newCitysBuyTwo - oldCitysBuyTwo
-
-				if p_Diff > 0 {
-					UpgradeBuyset.AreaCount = newBuySet.AreaCount
-				}
-
-				if p_Diff > 0 || p_Diff+c_2_diff > 0 || p_Diff+c_2_diff+c_1_diff > 0 {
-					//有多余未使用名额保留
-					if p_Diff+c_2_diff+c_1_diff < 0 {
-						if c_1_diff < 0 && p_Diff+c_2_diff >= 0 {
-							c_1_diff = -(p_Diff + c_2_diff)
-						}
-						if c_2_diff < 0 && p_Diff+c_1_diff >= 0 {
-							c_2_diff = -(p_Diff + c_1_diff)
-						}
-					}
-
-					//需要升级
-					AreaNeedUpgrade = true
-					//计算升级后的buySet
-					if p_Diff < 0 { //有剩余省份未使用
-						if c_2_diff > 0 {
-							c_2_diff += p_Diff //转移给两个市使用
-						} else {
-							c_1_diff += p_Diff //转移给一个市使用
-						}
-					} else { //省份数量增加
-						UpgradeBuyset.AreaCount = newBuySet.AreaCount
-					}
-					del_2_flag, del_1_flag := 0, 0 //被占用
-					if c_2_diff < 0 {              //有两个城市的名额未使用完
-						if p_Diff > 0 {
-							//转移给一个省使用
-							if c_2_diff+p_Diff > 0 {
-								del_2_flag += -c_2_diff
-								c_2_diff = 0
-								//p_Diff -= -c_2_diff;
-							} else {
-								c_2_diff += p_Diff
-								del_2_flag += p_Diff
-								//p_Diff = 0
-							}
-						}
-						if c_1_diff > 0 && c_2_diff < 0 { //转移给一个市使用
-							c_1_diff += c_2_diff
-						}
-					}
-					if c_1_diff < 0 { //有一个城市的名额未使用完
-						if p_Diff > 0 {
-							if c_1_diff+p_Diff > 0 {
-								del_1_flag += -c_1_diff
-								c_1_diff = 0
-								//p_Diff -= -c_1_diff
-							} else {
-								c_1_diff += p_Diff
-								del_1_flag += p_Diff
-								//p_Diff = 0
-							}
-						}
-						if c_2_diff > 0 && c_1_diff < 0 {
-							if c_1_diff+c_2_diff > 0 {
-								del_1_flag += -c_1_diff
-								c_1_diff = 0
-								//c_2_diff -= -c_1_diff;
-							} else {
-								c_1_diff += c_2_diff
-								del_1_flag += c_2_diff
-								//c_2_diff = 0
-							}
-						}
-					}
-					//删除顶替
-					index_flag := 0
-					for del_2_flag > 0 || del_1_flag > 0 {
-						valueFlag := UpgradeBuyset.NewCitys[index_flag]
-						if del_2_flag > 0 && valueFlag == 2 {
-							UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
-							del_2_flag--
-							continue
-						} else if del_1_flag > 0 && valueFlag == 1 {
-							UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
-							del_1_flag--
-							continue
-						}
-						index_flag++
-					}
-					//增加新增
-					for i := c_2_diff; i > 0; i-- { //添加购买两个市数量
-						UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 2)
-					}
-
-					for i := c_1_diff; i > 0; i-- { //添加购买一个市数量
-						UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 1)
-					}
-				} else {
-					//不需要升级
-					AreaNeedUpgrade = false
-				}
-			}
-		}
-		if BuyerclassUpgrade || AreaNeedUpgrade {
-			return true
-		} else {
-			return false
-		}
-	} else {
-		//return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
-		if oldBuySet.AreaCount != -1 {
-			return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
-		} else {
-			return false
-		}
-	}
+    if newBuySet.Upgrade != 1 { //旧版本订阅是否需要升级校验
+        BuyerclassUpgrade, AreaNeedUpgrade := false, false
+        UpgradeBuyset := &entity.SubvipBuySet{
+            oldBuySet.Upgrade,
+            oldBuySet.AreaCount,
+            oldBuySet.NewCitys,
+            oldBuySet.BuyerclassCount,
+        }
+        //比较行业
+        if oldBuySet.BuyerclassCount != -1 {
+            //若当前买的不是全行业,并且当前行业数量小于新行业数量时
+            if oldBuySet.BuyerclassCount < newBuySet.BuyerclassCount || newBuySet.BuyerclassCount == -1 {
+                BuyerclassUpgrade = true
+                //计算升级后的buySet
+                UpgradeBuyset.BuyerclassCount = newBuySet.BuyerclassCount
+            }
+        }
+        //比较地区
+        if oldBuySet.AreaCount != -1 {
+            if newBuySet.AreaCount == -1 { //升级为全国
+                UpgradeBuyset.AreaCount = newBuySet.AreaCount
+                UpgradeBuyset.NewCitys = newBuySet.NewCitys
+                AreaNeedUpgrade = true
+            } else {
+                oldCitysBuyOne, oldCitysBuyTwo := 0, 0
+                newCitysBuyOne, newCitysBuyTwo := 0, 0
+                oldCopy := []int{} //复制(防止影响原数组)
+                for _, v := range oldBuySet.NewCitys {
+                    if v == 1 {
+                        oldCitysBuyOne++
+                    } else {
+                        oldCitysBuyTwo++
+                    }
+                    oldCopy = append(oldCopy, v)
+                }
+                UpgradeBuyset.NewCitys = oldCopy
+                for _, v := range newBuySet.NewCitys {
+                    if v == 1 {
+                        newCitysBuyOne++
+                    } else {
+                        newCitysBuyTwo++
+                    }
+                }
+
+                p_Diff := newBuySet.AreaCount - oldBuySet.AreaCount
+                c_1_diff := newCitysBuyOne - oldCitysBuyOne
+                c_2_diff := newCitysBuyTwo - oldCitysBuyTwo
+
+                if p_Diff > 0 {
+                    UpgradeBuyset.AreaCount = newBuySet.AreaCount
+                }
+
+                if p_Diff > 0 || p_Diff+c_2_diff > 0 || p_Diff+c_2_diff+c_1_diff > 0 {
+                    //有多余未使用名额保留
+                    if p_Diff+c_2_diff+c_1_diff < 0 {
+                        if c_1_diff < 0 && p_Diff+c_2_diff >= 0 {
+                            c_1_diff = -(p_Diff + c_2_diff)
+                        }
+                        if c_2_diff < 0 && p_Diff+c_1_diff >= 0 {
+                            c_2_diff = -(p_Diff + c_1_diff)
+                        }
+                    }
+
+                    //需要升级
+                    AreaNeedUpgrade = true
+                    //计算升级后的buySet
+                    if p_Diff < 0 { //有剩余省份未使用
+                        if c_2_diff > 0 {
+                            c_2_diff += p_Diff //转移给两个市使用
+                        } else {
+                            c_1_diff += p_Diff //转移给一个市使用
+                        }
+                    } else { //省份数量增加
+                        UpgradeBuyset.AreaCount = newBuySet.AreaCount
+                    }
+                    del_2_flag, del_1_flag := 0, 0 //被占用
+                    if c_2_diff < 0 {              //有两个城市的名额未使用完
+                        if p_Diff > 0 {
+                            //转移给一个省使用
+                            if c_2_diff+p_Diff > 0 {
+                                del_2_flag += -c_2_diff
+                                c_2_diff = 0
+                                //p_Diff -= -c_2_diff;
+                            } else {
+                                c_2_diff += p_Diff
+                                del_2_flag += p_Diff
+                                //p_Diff = 0
+                            }
+                        }
+                        if c_1_diff > 0 && c_2_diff < 0 { //转移给一个市使用
+                            c_1_diff += c_2_diff
+                        }
+                    }
+                    if c_1_diff < 0 { //有一个城市的名额未使用完
+                        if p_Diff > 0 {
+                            if c_1_diff+p_Diff > 0 {
+                                del_1_flag += -c_1_diff
+                                c_1_diff = 0
+                                //p_Diff -= -c_1_diff
+                            } else {
+                                c_1_diff += p_Diff
+                                del_1_flag += p_Diff
+                                //p_Diff = 0
+                            }
+                        }
+                        if c_2_diff > 0 && c_1_diff < 0 {
+                            if c_1_diff+c_2_diff > 0 {
+                                del_1_flag += -c_1_diff
+                                c_1_diff = 0
+                                //c_2_diff -= -c_1_diff;
+                            } else {
+                                c_1_diff += c_2_diff
+                                del_1_flag += c_2_diff
+                                //c_2_diff = 0
+                            }
+                        }
+                    }
+                    //删除顶替
+                    index_flag := 0
+                    for del_2_flag > 0 || del_1_flag > 0 {
+                        valueFlag := UpgradeBuyset.NewCitys[index_flag]
+                        if del_2_flag > 0 && valueFlag == 2 {
+                            UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
+                            del_2_flag--
+                            continue
+                        } else if del_1_flag > 0 && valueFlag == 1 {
+                            UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys[:index_flag], UpgradeBuyset.NewCitys[index_flag+1:]...)
+                            del_1_flag--
+                            continue
+                        }
+                        index_flag++
+                    }
+                    //增加新增
+                    for i := c_2_diff; i > 0; i-- { //添加购买两个市数量
+                        UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 2)
+                    }
+
+                    for i := c_1_diff; i > 0; i-- { //添加购买一个市数量
+                        UpgradeBuyset.NewCitys = append(UpgradeBuyset.NewCitys, 1)
+                    }
+                } else {
+                    //不需要升级
+                    AreaNeedUpgrade = false
+                }
+            }
+        }
+        if BuyerclassUpgrade || AreaNeedUpgrade {
+            return true
+        } else {
+            return false
+        }
+    } else {
+        //return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
+        if oldBuySet.AreaCount != -1 {
+            return newBuySet.AreaCount == -1 || newBuySet.AreaCount > oldBuySet.AreaCount
+        } else {
+            return false
+        }
+    }
 }
 
 func (this *SubscribeChange) MergeIndustry() {
-	industry := strings.Split(this.GetString("industry"), ",")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	isread, _ := this.GetBool("isread")
-	r := func() *entity.FuncResult {
-		if userId != "" {
-			positionType := qutil.Int64All(this.GetSession("positionType"))
-			updateOk := false
-			if positionType == 0 {
-				updateOk = util.MQFW.UpdateById("user", userId,
-					bson.M{"$set": bson.M{
-						"o_vipjy.a_buyerclass": industry, //设置行业
-						"isread":               isread,
-					}})
-			} else {
-				query := map[string]interface{}{
-					"i_userid": qutil.Int64All(this.GetSession("entUserId")),
-					"i_entid":  qutil.Int64All(this.GetSession("entId")),
-					"i_type":   1,
-				}
-				util.MQFW.UpdateById("user", userId,
-					bson.M{"$set": bson.M{
-						"isread": isread,
-					}})
-				updateOk = util.MQFW.Update("entniche_rule", query,
-					bson.M{"$set": bson.M{
-						"o_entniche.a_buyerclass": industry, //设置行业
-					}}, true, false)
-			}
-
-			if updateOk {
-				return &entity.FuncResult{true, nil, nil}
-			} else {
-
-				return &entity.FuncResult{false, nil, nil}
-			}
-		} else {
-			return &entity.FuncResult{false, nil, nil}
-		}
-
-	}()
-
-	this.ServeJson(r.Format())
+    industry := strings.Split(this.GetString("industry"), ",")
+    userId := qutil.ObjToString(this.GetSession("userId"))
+    isread, _ := this.GetBool("isread")
+    r := func() *entity.FuncResult {
+        if userId != "" {
+            updateOk := false
+            updateOk = util.Compatible.Update(userId,
+                bson.M{"$set": bson.M{
+                    "o_vipjy.a_buyerclass": industry, //设置行业
+                    "isread":               isread,
+                }})
+
+            if updateOk {
+                return &entity.FuncResult{true, nil, nil}
+            } else {
+
+                return &entity.FuncResult{false, nil, nil}
+            }
+        } else {
+            return &entity.FuncResult{false, nil, nil}
+        }
+
+    }()
+
+    this.ServeJson(r.Format())
 }
 
 //超级订阅优化,免费订阅判断新老用户  1:新用户 0:老用户
 func NewUserByVIP(userId string, session *httpsession.Session) int {
-	mData := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
-	ojy := jy.GetSubScribeInfo(session, util.MQFW, "f", "10000")
-	if len(*ojy) > 0 {
-		if (*ojy)["i_new"] != nil {
-			return qutil.IntAllDef((*ojy)["i_new"], 1)
-		}
-		optime, _ := time.ParseInLocation(Date_Full_Layout, config.Config.OptimalTime, time.Local)
-		regtime := mData.Data.Free.Registedate
-		//如果a_key 存在 即为老用户
-		if ((*ojy)["a_key"] == nil && time.Unix(regtime, 0).Before(optime)) || (time.Unix(regtime, 0).After(optime)) {
-			return 1
-		}
-	}
-	return 0
+    mData := jy.GetBigVipUserBaseMsg(session, *config.Middleground)
+    ojy := jy.GetSubScribeInfo(session, util.MQFW, "f", "10000")
+    if len(*ojy) > 0 {
+        if (*ojy)["i_new"] != nil {
+            return qutil.IntAllDef((*ojy)["i_new"], 1)
+        }
+        optime, _ := time.ParseInLocation(Date_Full_Layout, config.Config.OptimalTime, time.Local)
+        regtime := mData.Data.Free.Registedate
+        //如果a_key 存在 即为老用户
+        if ((*ojy)["a_key"] == nil && time.Unix(regtime, 0).Before(optime)) || (time.Unix(regtime, 0).After(optime)) {
+            return 1
+        }
+    }
+    return 0
 }

Nem az összes módosított fájl került megjelenítésre, mert túl sok fájl változott