WH01243 2 år sedan
förälder
incheckning
a057628ab6
85 ändrade filer med 24325 tillägg och 22822 borttagningar
  1. 7 5
      src/go.mod
  2. 15 10
      src/go.sum
  3. 1330 1297
      src/jfw/front/front.go
  4. 992 972
      src/jfw/front/swordfish.go
  5. 420 410
      src/jfw/front/vipsubscribe.go
  6. 264 261
      src/jfw/front/wxMyOrder.go
  7. 372 341
      src/jfw/front/wxkeyset.go
  8. 616 607
      src/jfw/modules/app/src/app/front/front.go
  9. 402 397
      src/jfw/modules/app/src/app/front/me.go
  10. 509 479
      src/jfw/modules/app/src/app/front/swordfish.go
  11. 4 6
      src/jfw/modules/app/src/app/front/wxkeyset.go
  12. 25 14
      src/jfw/modules/app/src/go.mod
  13. 33 22
      src/jfw/modules/app/src/go.sum
  14. 12 11
      src/jfw/modules/bigmember/src/entity/analysisEntName.go
  15. 146 142
      src/jfw/modules/bigmember/src/entity/portrailUtil.go
  16. 15 14
      src/jfw/modules/bigmember/src/entity/portrait.go
  17. 4 3
      src/jfw/modules/bigmember/src/entity/portraitBuyerSearch.go
  18. 15 14
      src/jfw/modules/bigmember/src/go.mod
  19. 33 22
      src/jfw/modules/bigmember/src/go.sum
  20. 272 256
      src/jfw/modules/bigmember/src/service/analysis/analysis.go
  21. 4 7
      src/jfw/modules/bigmember/src/service/analysis/decision.go
  22. 543 542
      src/jfw/modules/bigmember/src/service/analysis/forecastproject.go
  23. 3 3
      src/jfw/modules/bigmember/src/service/analysis/forecastwinner.go
  24. 805 805
      src/jfw/modules/bigmember/src/service/analysis/potential.go
  25. 171 171
      src/jfw/modules/bigmember/src/service/analysis/util.go
  26. 75 81
      src/jfw/modules/bigmember/src/service/bidfile/bidfile.go
  27. 5 5
      src/jfw/modules/bigmember/src/service/follow/projectPdf.go
  28. 459 458
      src/jfw/modules/bigmember/src/service/portrait/memberPortraitAction.go
  29. 455 454
      src/jfw/modules/bigmember/src/service/portrait/subvipPortraitAction.go
  30. 436 413
      src/jfw/modules/bigmember/src/service/push/push.go
  31. 201 177
      src/jfw/modules/bigmember/src/service/report/marketAnalysis.go
  32. 535 511
      src/jfw/modules/bigmember/src/service/report/report.go
  33. 372 314
      src/jfw/modules/bigmember/src/service/subscribe/subscribe.go
  34. 863 811
      src/jfw/modules/bigmember/src/service/use/use.go
  35. 53 48
      src/jfw/modules/bigmember/src/util/power.go
  36. 249 248
      src/jfw/modules/bigmember/src/util/view.go
  37. 5 3
      src/jfw/modules/distribution/src/service/action/share.go
  38. 36 32
      src/jfw/modules/publicapply/src/dataexport/entity/collection.go
  39. 1 1
      src/jfw/modules/publicapply/src/dataexport/service/action.go
  40. 6 5
      src/jfw/modules/publicapply/src/go.mod
  41. 15 10
      src/jfw/modules/publicapply/src/go.sum
  42. 28 28
      src/jfw/modules/publicapply/src/grpc/usercenter.go
  43. 205 259
      src/jfw/modules/publicapply/src/me/me.go
  44. 245 206
      src/jfw/modules/publicapply/src/subscribe/entity/entity.go
  45. 3 3
      src/jfw/modules/publicapply/src/subscribe/service/service.go
  46. 301 279
      src/jfw/modules/publicapply/src/subscribePush/entity/historyPush.go
  47. 1029 947
      src/jfw/modules/publicapply/src/subscribePush/entity/keyWords.go
  48. 524 539
      src/jfw/modules/publicapply/src/subscribePush/entity/setting.go
  49. 345 349
      src/jfw/modules/publicapply/src/subscribePush/entity/vrew.go
  50. 306 306
      src/jfw/modules/publicapply/src/subscribePush/service/pushList.go
  51. 0 1
      src/jfw/modules/publicapply/src/subscribePush/service/subscribe.go
  52. 54 51
      src/jfw/modules/subscribepay/src/active/active.go
  53. 254 207
      src/jfw/modules/subscribepay/src/entity/areaPack.go
  54. 179 165
      src/jfw/modules/subscribepay/src/entity/dataReportStruct.go
  55. 235 220
      src/jfw/modules/subscribepay/src/entity/jyCourseOnlineStruct.go
  56. 205 175
      src/jfw/modules/subscribepay/src/entity/member.go
  57. 1042 1040
      src/jfw/modules/subscribepay/src/entity/order.go
  58. 144 129
      src/jfw/modules/subscribepay/src/entity/shareFission.go
  59. 561 483
      src/jfw/modules/subscribepay/src/entity/subscribeVip.go
  60. 16 19
      src/jfw/modules/subscribepay/src/go.mod
  61. 33 33
      src/jfw/modules/subscribepay/src/go.sum
  62. 115 110
      src/jfw/modules/subscribepay/src/rpcfollow/share.go
  63. 598 587
      src/jfw/modules/subscribepay/src/service/afterPay.go
  64. 87 80
      src/jfw/modules/subscribepay/src/service/aiForecastPack.go
  65. 193 183
      src/jfw/modules/subscribepay/src/service/areaPack.go
  66. 75 68
      src/jfw/modules/subscribepay/src/service/bidfile.go
  67. 120 113
      src/jfw/modules/subscribepay/src/service/bigmember.go
  68. 550 543
      src/jfw/modules/subscribepay/src/service/commonAction.go
  69. 750 743
      src/jfw/modules/subscribepay/src/service/courseAction.go
  70. 237 230
      src/jfw/modules/subscribepay/src/service/dataExportPay.go
  71. 423 416
      src/jfw/modules/subscribepay/src/service/dataexportPack.go
  72. 251 236
      src/jfw/modules/subscribepay/src/service/entniche.go
  73. 206 206
      src/jfw/modules/subscribepay/src/service/index_p1.go
  74. 156 149
      src/jfw/modules/subscribepay/src/service/integral.go
  75. 8 3
      src/jfw/modules/subscribepay/src/service/orderDetails.go
  76. 883 878
      src/jfw/modules/subscribepay/src/service/orderListDetails.go
  77. 160 153
      src/jfw/modules/subscribepay/src/service/resourcePack.go
  78. 541 529
      src/jfw/modules/subscribepay/src/service/salesCreateOrder.go
  79. 649 602
      src/jfw/modules/subscribepay/src/service/vipSubscribeChange.go
  80. 533 519
      src/jfw/modules/subscribepay/src/service/vipSubscribePay.go
  81. 302 294
      src/jfw/modules/subscribepay/src/service/vipSubscribeTrial.go
  82. 383 339
      src/jfw/modules/subscribepay/src/util/vrew.go
  83. 79 8
      src/jfw/modules/weixin/src/go.mod
  84. 538 11
      src/jfw/modules/weixin/src/go.sum
  85. 1 1
      src/jfw/modules/weixin/src/wx/wx.go

+ 7 - 5
src/go.mod

@@ -3,23 +3,24 @@ module jy/src
 go 1.18
 
 require (
-	app.yhyue.com/moapp/jybase v0.0.0-20230110071808-0c8ff7f798c6
-	app.yhyue.com/moapp/jypkg v0.0.0-20230110072459-b8e28d30c98d
-	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230109023014-2cd2a0b9b979
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab
+	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/dchest/captcha v1.0.0
 	github.com/fsnotify/fsnotify v1.6.0
 	github.com/gogf/gf/v2 v2.2.6
 	github.com/robfig/cron v1.2.0
-	github.com/zeromicro/go-zero v1.4.3
+	github.com/zeromicro/go-zero v1.4.4
 	go.mongodb.org/mongo-driver v1.11.1
 )
 
 
+
 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/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c // 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
@@ -89,6 +90,7 @@ require (
 	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

+ 15 - 10
src/go.sum

@@ -11,17 +11,17 @@ app.yhyue.com/moapp/jybase v0.0.0-20220427020729-974c1a148186/go.mod h1:qNRA0sHu
 app.yhyue.com/moapp/jybase v0.0.0-20220719064915-2fef79005dfa/go.mod h1:FjBF25AYoBrPhVKTXGXWcmEAbBT0ATTK6KJMOA+I80Q=
 app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tcD9TcKb/HOP2BLbzppyDz2kpQSFhPMQTUgbQ=
 app.yhyue.com/moapp/jybase v0.0.0-20230109015757-aa3d5e19b196/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jybase v0.0.0-20230110071808-0c8ff7f798c6 h1:Szt9G37MxAN5xJXGGS87EtMdIKoucilK5inP3zRLUIE=
-app.yhyue.com/moapp/jybase v0.0.0-20230110071808-0c8ff7f798c6/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110072459-b8e28d30c98d h1:N/71mg7rkJnKNtxVGji0xID2PdRt4BnAj7uKpjA3ZO0=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110072459-b8e28d30c98d/go.mod h1:Arq5I8RsXJvV6i8K7f0ZG6MBt26MLhzuQswoU3SSqjc=
+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-20230128092104-d8ae3867d2ab h1:a9XvegdF3aM0y9v5SHtX03LIGMS3+8J1ofoNeyw5J0Y=
+app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab/go.mod h1:MqJfBFTSfZhrNDEnE4e19BmaLkaMr+lYActLXm6lrpw=
 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/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-20230106052936-bd3ab7edf7a4 h1:Xv1D9avDKeaM5kQTisF/pIt8y7B7yQ/hAxuWEg75LMs=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c h1:g49jOlhZlBCJ3IgJA0rotfNf2Gh22pISffUtqxB8XtY=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
 bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.0-20220418005748-8ba5d936dd53/go.mod h1:E5lcDI3k4FESLxiAetCfWQTq8qfpy9cv0yN1oKoEO34=
 bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.0-20220419023723-0b32d4a41751/go.mod h1:6KL5LMEku83uRbre0W/bj5kXG2I6pJGBFtktmtp51yM=
 bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.0-20220419063004-233fc7ce006c/go.mod h1:6KL5LMEku83uRbre0W/bj5kXG2I6pJGBFtktmtp51yM=
@@ -31,8 +31,8 @@ bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4/go.mod h1:rRiGzKG4F/fmkN
 bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20220418072311-2062bed1e700/go.mod h1:KjcrxTzM96tBc6G4B8tlLBn1lrVy5UJYF8+eTdP4xAE=
 bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20220421015128-4a36f3eac5c5/go.mod h1:GT0QC4aaKDuXxAvaU4G02XjCc31TU1ctqBGqxQYOfC4=
 bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20220905055615-8540037e1b06/go.mod h1:LS21iwbgP8i3ZHJ1n4yNpLXQ/nzEudUOk0klC6VM2dQ=
-bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230109023014-2cd2a0b9b979 h1:hC97JNmBonTAsnDH4XMWLXVqWdo85tCo0ge04cy0e4E=
-bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230109023014-2cd2a0b9b979/go.mod h1:m7/aZ1r1FapNT2h3gqmCFVb0EV+CaJaNKNPHMzLHx8Y=
+bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1 h1:LH/gm2iRShZ64FEuF7LTzF62iJhOVVD9AxGVHFd0ORI=
+bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1/go.mod h1:m7/aZ1r1FapNT2h3gqmCFVb0EV+CaJaNKNPHMzLHx8Y=
 cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw=
@@ -442,8 +442,9 @@ github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGn
 github.com/alicebob/miniredis/v2 v2.14.1/go.mod h1:uS970Sw5Gs9/iK3yBg0l9Uj9s25wXxSpQUE9EaJ/Blg=
 github.com/alicebob/miniredis/v2 v2.17.0/go.mod h1:gquAfGbzn92jvtrSC69+6zZnwSODVXVpYDRaGhWaL6I=
 github.com/alicebob/miniredis/v2 v2.22.0/go.mod h1:XNqvJdQJv5mSuVMc0ynneafpnL/zv52acZ6kqeS0t88=
-github.com/alicebob/miniredis/v2 v2.23.1 h1:jR6wZggBxwWygeXcdNyguCOCIjPsZyNUNlAkTx2fu0U=
 github.com/alicebob/miniredis/v2 v2.23.1/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
+github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
+github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
 github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
 github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=
@@ -811,6 +812,7 @@ github.com/jhump/protoreflect v1.10.3/go.mod h1:7GcYQDdMU/O/BBrl/cX6PNHpXh6cenjd
 github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E=
 github.com/jhump/protoreflect v1.12.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jhump/protoreflect v1.14.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
+github.com/jhump/protoreflect v1.14.1/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs=
 github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
 github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
@@ -1115,8 +1117,9 @@ github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQ
 github.com/zeromicro/go-zero v1.3.2/go.mod h1:DEj3Fwj1Ui1ltsgf6YqwTL9nD4+tYzIRX0c1pWtQo1E=
 github.com/zeromicro/go-zero v1.3.5/go.mod h1:wh4o794b7Ul3W0k35Pw9nc3iB4O0OpaQTMQz/PJc1bc=
 github.com/zeromicro/go-zero v1.4.0/go.mod h1:1amLn98K7c6FLntb9f8hdmq26ajtolOg4DTFWnRt54o=
-github.com/zeromicro/go-zero v1.4.3 h1:sTQ++6fxQHJnpGCN7h2CUrhWmbvhBqEgE75cJl635SM=
 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=
@@ -1170,6 +1173,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0/go.mod h1:FnDp7XemjN3o
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0/go.mod h1:OfUCyyIiDvNXHWpcWgbF+MWvqPZiNa3YDEnivcnYsV0=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0 h1:j2RFV0Qdt38XQ2Jvi4WIsQ56w8T7eSirYbMw19VXRDg=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0/go.mod h1:pILgiTEtrqvZpoiuGdblDgS5dbIaTgDrkIuKfEFkt+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 h1:S8DedULB3gp93Rh+9Z+7NTEv+6Id/KYS7LDyipZ9iCE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0/go.mod h1:5WV40MLWwvWlGP7Xm8g3pMcg0pKOUY609qxJn8y7LmM=
 go.opentelemetry.io/otel/exporters/zipkin v1.3.0/go.mod h1:LxGGfHIYbvsFnrJtBcazb0yG24xHdDGrT/H6RB9r3+8=
 go.opentelemetry.io/otel/exporters/zipkin v1.8.0/go.mod h1:0uYAyCuGT67MFV9Z/Mmx93wGuugHw0FbxMc74fs3LNo=
 go.opentelemetry.io/otel/exporters/zipkin v1.9.0/go.mod h1:HyIvYIu37wV4Wx5azd7e05x9k/dOz9KB4x0plw2QNvs=

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 1330 - 1297
src/jfw/front/front.go


Filskillnaden har hållts tillbaka eftersom den är för stor
+ 992 - 972
src/jfw/front/swordfish.go


+ 420 - 410
src/jfw/front/vipsubscribe.go

@@ -1,546 +1,556 @@
 package front
 
 import (
-	"encoding/hex"
-	"fmt"
-	"jy/src/jfw/config"
-	"jy/src/jfw/wx"
-	"net/url"
-	"strings"
-	"time"
+        "encoding/hex"
+        "fmt"
+        "jy/src/jfw/config"
+        "jy/src/jfw/wx"
+        "net/url"
+        "strings"
+        "time"
 
-	"jy/src/jfw/jyutil"
+        "jy/src/jfw/jyutil"
 
-	"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"
 
-	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"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Subscribepay struct {
-	*xweb.Action
-	introduce         xweb.Mapper `xweb:"/front/vipsubscribe/introducePage"`     //订阅收费介绍页
-	trialInfo         xweb.Mapper `xweb:"/front/vipsubscribe/trialInfo"`         //vip订阅服务-用户信息录入页面
-	toPurchasePage    xweb.Mapper `xweb:"/front/vipsubscribe/vipsubscribe_(.*)"` //订阅收费购买页面(试用用户)
-	toChooseArea      xweb.Mapper `xweb:"/front/vipsubscribe/toChooseArea"`      //订阅收费地区筛选
-	toChooseIndustry  xweb.Mapper `xweb:"/front/vipsubscribe/toChooseIndustry"`  //订阅收费行业筛选
-	toPaySuccessPage  xweb.Mapper `xweb:"/front/vipsubscribe/toPaySuccessPage"`  //订阅支付完成页面
-	toOrderDetailPage xweb.Mapper `xweb:"/front/vipsubscribe/toOrderDetailPage"` //订阅收费支付订单详情页面
-	toSetKeyWordPage  xweb.Mapper `xweb:"/front/vipsubscribe/toSetKeyWordPage"`  //订阅收费设置关键词
-
-	//toSetPageOld      xweb.Mapper `xweb:"/front/vipsubscribe/toSetPageOld"`      //订阅收费设置
-	toSetInfoTypePage xweb.Mapper `xweb:"/front/vipsubscribe/toSetInfoTypePage"` //订阅收费设置信息类型
-	toSetOtherKwsPage xweb.Mapper `xweb:"/front/vipsubscribe/toSet(.*)Page"`     //订阅收费附加词和排除词设置
-	toVIPViewPage     xweb.Mapper `xweb:"/front/vipsubscribe/toVIPViewPage"`     //订阅收费预览
-
-	//修改升级
-	toSetPage        xweb.Mapper `xweb:"/front/vipsubscribe/toSubVipSetPage"`  //订阅收费设置
-	toChangeArea     xweb.Mapper `xweb:"/front/vipsubscribe/toChangeArea"`     //修改区域
-	toChangeIndustry xweb.Mapper `xweb:"/front/vipsubscribe/toChangeIndustry"` //修改行业
-	toChangeTime     xweb.Mapper `xweb:"/front/vipsubscribe/toChangeTime"`     //修改时间
-	toSetPushSetPage xweb.Mapper `xweb:"/front/vipsubscribe/toSetPushSetPage"` //订阅收费推送设置
-
-	//续费
-	renewPage xweb.Mapper `xweb:"/front/vipsubscribe/renewPage/(.*)"` //订阅到期(will:即将到期,exprie:已到期)
-
-	//发票
-	openInvoice xweb.Mapper `xweb:"/front/vipsubscribe/openInvoice/(\\w+)"` //开发票
-
-	//预热活动链接跳转
-	preheatPoster xweb.Mapper `xweb:"/front/preheat/poster"` //预热活动链接跳转
-
-	upgradeDetail xweb.Mapper `xweb:"/front/vipsubscribe/upgradeDetail"` //新超级订阅介绍页
-	upgradePage   xweb.Mapper `xweb:"/front/vipsubscribe/upgradePage"`   //升级页面
-	//超级订阅企业搜索
-	entSearch xweb.Mapper `xweb:"/front/vipsubscribe/entSearch"` //企业搜索
-
-	//超级订阅改版公共url
-	pcViewPage xweb.Mapper `xweb:"/vipsubscribe/pc/page/(.*)"` //超级订阅pc
-	wxViewPage xweb.Mapper `xweb:"/vipsubscribe/wx/page/(.*)"` //超级订阅wx
-	//订阅付费消息提醒中转
-	msgremind xweb.Mapper `xweb:"/front/vipsubscribe/msgremind"`
+        *xweb.Action
+        introduce         xweb.Mapper `xweb:"/front/vipsubscribe/introducePage"`     //订阅收费介绍页
+        trialInfo         xweb.Mapper `xweb:"/front/vipsubscribe/trialInfo"`         //vip订阅服务-用户信息录入页面
+        toPurchasePage    xweb.Mapper `xweb:"/front/vipsubscribe/vipsubscribe_(.*)"` //订阅收费购买页面(试用用户)
+        toChooseArea      xweb.Mapper `xweb:"/front/vipsubscribe/toChooseArea"`      //订阅收费地区筛选
+        toChooseIndustry  xweb.Mapper `xweb:"/front/vipsubscribe/toChooseIndustry"`  //订阅收费行业筛选
+        toPaySuccessPage  xweb.Mapper `xweb:"/front/vipsubscribe/toPaySuccessPage"`  //订阅支付完成页面
+        toOrderDetailPage xweb.Mapper `xweb:"/front/vipsubscribe/toOrderDetailPage"` //订阅收费支付订单详情页面
+        toSetKeyWordPage  xweb.Mapper `xweb:"/front/vipsubscribe/toSetKeyWordPage"`  //订阅收费设置关键词
+
+        //toSetPageOld      xweb.Mapper `xweb:"/front/vipsubscribe/toSetPageOld"`      //订阅收费设置
+        toSetInfoTypePage xweb.Mapper `xweb:"/front/vipsubscribe/toSetInfoTypePage"` //订阅收费设置信息类型
+        toSetOtherKwsPage xweb.Mapper `xweb:"/front/vipsubscribe/toSet(.*)Page"`     //订阅收费附加词和排除词设置
+        toVIPViewPage     xweb.Mapper `xweb:"/front/vipsubscribe/toVIPViewPage"`     //订阅收费预览
+
+        //修改升级
+        toSetPage        xweb.Mapper `xweb:"/front/vipsubscribe/toSubVipSetPage"`  //订阅收费设置
+        toChangeArea     xweb.Mapper `xweb:"/front/vipsubscribe/toChangeArea"`     //修改区域
+        toChangeIndustry xweb.Mapper `xweb:"/front/vipsubscribe/toChangeIndustry"` //修改行业
+        toChangeTime     xweb.Mapper `xweb:"/front/vipsubscribe/toChangeTime"`     //修改时间
+        toSetPushSetPage xweb.Mapper `xweb:"/front/vipsubscribe/toSetPushSetPage"` //订阅收费推送设置
+
+        //续费
+        renewPage xweb.Mapper `xweb:"/front/vipsubscribe/renewPage/(.*)"` //订阅到期(will:即将到期,exprie:已到期)
+
+        //发票
+        openInvoice xweb.Mapper `xweb:"/front/vipsubscribe/openInvoice/(\\w+)"` //开发票
+
+        //预热活动链接跳转
+        preheatPoster xweb.Mapper `xweb:"/front/preheat/poster"` //预热活动链接跳转
+
+        upgradeDetail xweb.Mapper `xweb:"/front/vipsubscribe/upgradeDetail"` //新超级订阅介绍页
+        upgradePage   xweb.Mapper `xweb:"/front/vipsubscribe/upgradePage"`   //升级页面
+        //超级订阅企业搜索
+        entSearch xweb.Mapper `xweb:"/front/vipsubscribe/entSearch"` //企业搜索
+
+        //超级订阅改版公共url
+        pcViewPage xweb.Mapper `xweb:"/vipsubscribe/pc/page/(.*)"` //超级订阅pc
+        wxViewPage xweb.Mapper `xweb:"/vipsubscribe/wx/page/(.*)"` //超级订阅wx
+        //订阅付费消息提醒中转
+        msgremind xweb.Mapper `xweb:"/front/vipsubscribe/msgremind"`
 }
 
 func init() {
-	xweb.AddAction(&Subscribepay{})
+        xweb.AddAction(&Subscribepay{})
 }
 
 func (s *Subscribepay) EntSearch() {
-	s.Render("/weixin/vipsubscribe/vip_entSearch.html")
+        s.Render("/weixin/vipsubscribe/vip_entSearch.html")
 }
 
 func (s *Subscribepay) UpgradeDetail() {
-	s.Render("/weixin/vipsubscribe/vip_UpgradeDetail.html")
+        s.Render("/weixin/vipsubscribe/vip_UpgradeDetail.html")
 }
 
 func (s *Subscribepay) UpgradePage() {
-	s.Render("/weixin/vipsubscribe/vip_UpgradePage.html")
+        s.Render("/weixin/vipsubscribe/vip_UpgradePage.html")
 }
 
 var (
-	liveActiveStartTime = config.ActiveConfig.Live_Active_Start
-	liveActiveEndTime   = config.ActiveConfig.Live_Active_End
-	activeDiscount      = config.ActiveConfig.ActiveDiscount
+        liveActiveStartTime = config.ActiveConfig.Live_Active_Start
+        liveActiveEndTime   = config.ActiveConfig.Live_Active_End
+        activeDiscount      = config.ActiveConfig.ActiveDiscount
 )
 
 //推送设置
 func (s *Subscribepay) ToVIPViewPage() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/vip_viewPage.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/vip_viewPage.html")
 }
 
 //附加词|排除词
 func (s *Subscribepay) ToSetOtherKwsPage(page string) {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/" + page + "Word.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/" + page + "Word.html")
 }
 
 //推送设置
 func (s *Subscribepay) ToSetPushSetPage() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/vip_seniorset.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/vip_seniorset.html")
 }
 
 //信息类型
 func (s *Subscribepay) ToSetInfoTypePage() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/messageType.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/messageType.html")
 }
 
 //订阅设置
 func (s *Subscribepay) ToSetPage() error {
-	userid := util.ObjToString(s.GetSession("userId"))
-	vSwitch := s.GetString("vSwitch")
-	if vSwitch != "" {
-		if vSwitch == jy.SwitchService.Vip {
-			s.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Vip)
-		} else if vSwitch == jy.SwitchService.Member {
-			s.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Member)
-		}
-	}
-	etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
-	vipMsg := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
-	if vipMsg.VipStatus <= 0 && vipMsg.Status <= 0 && isInTSguide(userid) { //仅免费用户跳转向导页面
-		return s.Redirect("/front/tenderSubscribe/guide?url=" + url.QueryEscape(s.Request.RequestURI))
-	} else if (vSwitch == "" || vSwitch == "v") && vipMsg.VipStatus <= 0 && !vipMsg.IsUpgrade {
-		if s.GetString("advertcode") != "" {
-			return s.Redirect("/wxkeyset/keyset/index?advertcode=" + s.GetString("advertcode"))
-		}
-		return s.Redirect("/wxkeyset/keyset/index")
-	}
-	nowTime := time.Now().Unix()
-	if nowTime >= liveActiveStartTime && nowTime < liveActiveEndTime {
-		s.T["isLiveActive"] = true
-	}
-	s.T["liveActiveStartTime"] = liveActiveStartTime
-	s.T["liveActiveEndTime"] = liveActiveEndTime
-	s.T["activeDiscount"] = activeDiscount
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	return s.Render("/weixin/vipsubscribe/vip_index_new.html")
+        userid := util.ObjToString(s.GetSession("userId"))
+        vSwitch := s.GetString("vSwitch")
+        if vSwitch != "" {
+                if vSwitch == jy.SwitchService.Vip {
+                        s.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Vip)
+                } else if vSwitch == jy.SwitchService.Member {
+                        s.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Member)
+                }
+        }
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        vipMsg := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+        if vipMsg.VipStatus <= 0 && vipMsg.Status <= 0 && isInTSguide(userid) { //仅免费用户跳转向导页面
+                return s.Redirect("/front/tenderSubscribe/guide?url=" + url.QueryEscape(s.Request.RequestURI))
+        } else if (vSwitch == "" || vSwitch == "v") && vipMsg.VipStatus <= 0 && !vipMsg.IsUpgrade {
+                if s.GetString("advertcode") != "" {
+                        return s.Redirect("/wxkeyset/keyset/index?advertcode=" + s.GetString("advertcode"))
+                }
+                return s.Redirect("/wxkeyset/keyset/index")
+        }
+        nowTime := time.Now().Unix()
+        if nowTime >= liveActiveStartTime && nowTime < liveActiveEndTime {
+                s.T["isLiveActive"] = true
+        }
+        s.T["liveActiveStartTime"] = liveActiveStartTime
+        s.T["liveActiveEndTime"] = liveActiveEndTime
+        s.T["activeDiscount"] = activeDiscount
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        return s.Render("/weixin/vipsubscribe/vip_index_new.html")
 }
 
 func (s *Subscribepay) ToSetPageOld() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/vip_index.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/vip_index.html")
 }
 
 //修改升级 选择地区
 func (s *Subscribepay) ToChangeArea() {
-	s.Render("/weixin/vipsubscribe/change_area.html")
+        s.Render("/weixin/vipsubscribe/change_area.html")
 }
 
 //修改升级 选择行业
 func (s *Subscribepay) ToChangeIndustry() {
-	s.Render("/weixin/vipsubscribe/change_industry.html")
+        s.Render("/weixin/vipsubscribe/change_industry.html")
 }
 
 //修改升级 选择时间
 func (s *Subscribepay) ToChangeTime() {
-	s.Render("/weixin/vipsubscribe/change_time.html")
+        s.Render("/weixin/vipsubscribe/change_time.html")
 }
 
 //vip订阅介绍页
 func (s *Subscribepay) Introduce() error {
-	userId := util.ObjToString(s.GetSession("userId"))
-	if userId == "" {
-		if s.GetString("state") == "wx" {
-			//微信跳回来的
-			code := s.GetString("code")
-			if code != "" {
-				openid := jyutil.Getopenid(code)
-				if openid != "" {
-					isSubscribe := CheckUserIsSubscribe(openid)
-					if isSubscribe {
-						FindUserAndCreateSess(openid, s.Session(), "wx", false)
-						userId = util.ObjToString(s.GetSession("userId"))
-					}
-				}
-			}
-		} else {
-			if public.CheckWxBrowser(s.Request) {
-				//所有参数都不再使用,跳到微信验证用户
-				return s.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(s.Site()+s.Url()), "wx"), 302)
-			}
-			return s.Redirect("/swordfish/about?v=0")
-		}
-	}
-	if userId == "" {
-		return s.Redirect("/swordfish/about?v=1")
-	}
-	m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1}`)
-	if !ok {
-		return s.Redirect("/swordfish/about?v=2")
-	}
-	nowTime := time.Now().Unix()
-	if nowTime >= liveActiveStartTime && nowTime < liveActiveEndTime {
-		s.T["isLiveActive"] = true
-	}
-	obj := util.ObjToMap((*m)["o_vipjy"])
-	from := s.GetString("type") //双十一活动 接受参数renew 跳转到介绍页(续费)
-	if util.IntAll((*m)["i_vip_status"]) > 0 && from != "renew" {
-		if s.GetString("disWord") != "" {
-			//分销识别 直接VIP续费
-			if util.IntAll((*m)["i_vip_status"]) == 1 { //试用用户
-				return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&vSwitch=v&disWord=" + s.GetString("disWord") + "&advertcode=" + s.GetString("advertcode"))
-			} else {
-				return s.Redirect("/jy_mobile/common/order/create/svip?type=renew&vSwitch=v&disWord=" + s.GetString("disWord") + "&advertcode=" + s.GetString("advertcode"))
-			}
-		}
-		return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + s.GetString("advertcode") + "&vSwitch=v")
-	}
-	s.T["notShowTrial"] = util.IntAll((*obj)["i_trial"]) == -1 || (*m)["i_vip_status"] != nil
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	//直播活动和预热活动期间
-	if config.ActiveConfig.Live_Active_End > time.Now().Unix() && time.Now().Unix() > config.ActiveConfig.Live_Preheat_Start {
-		s.T["LiveState"] = true
-	}
-	s.T["disWord"] = s.GetString("disWord")
-	return s.Render("/weixin/vipsubscribe/vip_introduce.html")
+        userId := util.ObjToString(s.GetSession("userId"))
+        if userId == "" {
+                if s.GetString("state") == "wx" {
+                        //微信跳回来的
+                        code := s.GetString("code")
+                        if code != "" {
+                                openid := jyutil.Getopenid(code)
+                                if openid != "" {
+                                        isSubscribe := CheckUserIsSubscribe(openid)
+                                        if isSubscribe {
+                                                FindUserAndCreateSess(openid, s.Session(), "wx", false)
+                                                userId = util.ObjToString(s.GetSession("userId"))
+                                        }
+                                }
+                        }
+                } else {
+                        if public.CheckWxBrowser(s.Request) {
+                                //所有参数都不再使用,跳到微信验证用户
+                                return s.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(s.Site()+s.Url()), "wx"), 302)
+                        }
+                        return s.Redirect("/swordfish/about?v=0")
+                }
+        }
+        if userId == "" {
+                return s.Redirect("/swordfish/about?v=1")
+        }
+        // m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1}`)
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        m := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+        if m == nil {
+                return s.Redirect("/swordfish/about?v=2")
+        }
+        nowTime := time.Now().Unix()
+        if nowTime >= liveActiveStartTime && nowTime < liveActiveEndTime {
+                s.T["isLiveActive"] = true
+        }
+        //obj := util.ObjToMap((*m)["o_vipjy"])
+        from := s.GetString("type") //双十一活动 接受参数renew 跳转到介绍页(续费)
+        if m.VipStatus > 0 && from != "renew" {
+                if s.GetString("disWord") != "" {
+                        //分销识别 直接VIP续费
+                        if m.VipStatus == 1 { //试用用户
+                                return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&vSwitch=v&disWord=" + s.GetString("disWord") + "&advertcode=" + s.GetString("advertcode"))
+                        } else {
+                                return s.Redirect("/jy_mobile/common/order/create/svip?type=renew&vSwitch=v&disWord=" + s.GetString("disWord") + "&advertcode=" + s.GetString("advertcode"))
+                        }
+                }
+                return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + s.GetString("advertcode") + "&vSwitch=v")
+        }
+        // s.T["notShowTrial"] = util.IntAll((*obj)["i_trial"]) == -1 || (*m)["i_vip_status"] != nil
+        s.T["notShowTrial"] = m.VipStatus != 0
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        //直播活动和预热活动期间
+        if config.ActiveConfig.Live_Active_End > time.Now().Unix() && time.Now().Unix() > config.ActiveConfig.Live_Preheat_Start {
+                s.T["LiveState"] = true
+        }
+        s.T["disWord"] = s.GetString("disWord")
+        return s.Render("/weixin/vipsubscribe/vip_introduce.html")
 }
 
 //试用完善信息
 func (s *Subscribepay) TrialInfo() error {
-	userId := util.ObjToString(s.GetSession("userId"))
-	if userId == "" {
-		return s.Redirect("/swordfish/about")
-	}
-	m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1}`)
-	if !ok || len(*m) == 0 {
-		return s.Redirect("/swordfish/about")
-	}
-	obj := util.ObjToMap((*m)["o_vipjy"])
-	s.T["trialSign"] = util.IntAll((*obj)["i_trial"]) == 1
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	return s.Render("/weixin/vipsubscribe/trial_info.html", &s.T)
+        userId := util.ObjToString(s.GetSession("userId"))
+        if userId == "" {
+                return s.Redirect("/swordfish/about")
+        }
+        //m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1}`)
+        if !ok || len(*m) == 0 {
+                return s.Redirect("/swordfish/about")
+        }
+        //obj := util.ObjToMap((*m)["o_vipjy"])
+        //  s.T["trialSign"] = util.IntAll((*obj)["i_trial"]) == 1
+        s.T["trialSign"] = true
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        return s.Render("/weixin/vipsubscribe/trial_info.html", &s.T)
 }
 
 //订阅收费购买页面
 func (s *Subscribepay) ToPurchasePage(flag string) {
-	userId := util.ObjToString(s.GetSession("userId"))
-	if userId == "" {
-		return
-	}
-	m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1}`)
-	if !ok {
-		s.Redirect("/swordfish/about?v=2")
-		return
-	}
-	if util.IntAll((*m)["i_vip_status"]) > 0 && flag == "new" {
-		s.Redirect("/front/vipsubscribe/introducePage")
-		return
-	}
-	//直播活动
-	nowTime := time.Now().Unix()
-	if nowTime >= liveActiveStartTime && nowTime < liveActiveEndTime {
-		s.T["isLiveActive"] = true
-		//虚拟人数
-		buyCount := redis.Get("other", "liveactiveRTB")
-		s.T["buyCount"] = buyCount
-	}
-	s.T["liveActiveStartTime"] = liveActiveStartTime
-	s.T["liveActiveEndTime"] = liveActiveEndTime
-	s.T["activeDiscount"] = activeDiscount
-	if flag == "trial" { //试用
-		s.T["isTrial"] = true
-		s.T["orderType"] = -1
-	} else { //付费
-		s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url()) //微信支付准备参数
-		if flag == "renew" {
-			s.Render("/weixin/vipsubscribe/vip_renew.html")
-			return
-		}
-		if flag == "renewOld" {
-			s.T["orderType"] = 5
-		} else {
-			s.T["orderType"] = 1
-		}
-		if s.GetString("orderCode") != "" && s.GetString("orderCode") != "undefined" {
-			s.T["again"] = 1 //再次购买
-		}
-	}
-	s.Render("/weixin/vipsubscribe/vip_purchase.html")
+        userId := util.ObjToString(s.GetSession("userId"))
+        if userId == "" {
+                return
+        }
+        //m, ok := public.MQFW.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1}`)
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        m := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+        if m == nil {
+                s.Redirect("/swordfish/about?v=2")
+                return
+        }
+        if m.VipStatus > 0 && flag == "new" {
+                s.Redirect("/front/vipsubscribe/introducePage")
+                return
+        }
+        //直播活动
+        nowTime := time.Now().Unix()
+        if nowTime >= liveActiveStartTime && nowTime < liveActiveEndTime {
+                s.T["isLiveActive"] = true
+                //虚拟人数
+                buyCount := redis.Get("other", "liveactiveRTB")
+                s.T["buyCount"] = buyCount
+        }
+        s.T["liveActiveStartTime"] = liveActiveStartTime
+        s.T["liveActiveEndTime"] = liveActiveEndTime
+        s.T["activeDiscount"] = activeDiscount
+        if flag == "trial" { //试用
+                s.T["isTrial"] = true
+                s.T["orderType"] = -1
+        } else { //付费
+                s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url()) //微信支付准备参数
+                if flag == "renew" {
+                        s.Render("/weixin/vipsubscribe/vip_renew.html")
+                        return
+                }
+                if flag == "renewOld" {
+                        s.T["orderType"] = 5
+                } else {
+                        s.T["orderType"] = 1
+                }
+                if s.GetString("orderCode") != "" && s.GetString("orderCode") != "undefined" {
+                        s.T["again"] = 1 //再次购买
+                }
+        }
+        s.Render("/weixin/vipsubscribe/vip_purchase.html")
 }
 
 //订阅收费地区筛选
 func (s *Subscribepay) ToChooseArea() {
-	s.Render("/weixin/vipsubscribe/choose_area.html", &s.T)
+        s.Render("/weixin/vipsubscribe/choose_area.html", &s.T)
 }
 
 //订阅收费地区筛选
 func (s *Subscribepay) ToChooseIndustry() {
-	s.Render("/weixin/vipsubscribe/choose_industry.html", &s.T)
+        s.Render("/weixin/vipsubscribe/choose_industry.html", &s.T)
 }
 
 //订阅收费支付订单详情页面
 func (s *Subscribepay) ToOrderDetailPage() {
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url()) //微信支付准备参数
-	s.T["liveActiveStartTime"] = liveActiveStartTime
-	s.T["liveActiveEndTime"] = liveActiveEndTime
-	s.T["activeDiscount"] = activeDiscount
-	s.Render("/weixin/vipsubscribe/vip_order_detail.html")
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url()) //微信支付准备参数
+        s.T["liveActiveStartTime"] = liveActiveStartTime
+        s.T["liveActiveEndTime"] = liveActiveEndTime
+        s.T["activeDiscount"] = activeDiscount
+        s.Render("/weixin/vipsubscribe/vip_order_detail.html")
 }
 
 //订阅收费设置关键词
 func (s *Subscribepay) ToSetKeyWordPage() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/keyWord.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/keyWord.html")
 }
 
 //修改订阅页面
 func (s *Subscribepay) ToEditSubPage() {
-	s.Render("/weixin/vipsubscribe/edit_subscribe.html")
+        s.Render("/weixin/vipsubscribe/edit_subscribe.html")
 }
 
 //合并后修改地区
 func (s *Subscribepay) ToEditSubAreaPage() {
-	s.Render("/weixin/vipsubscribe/edit_city_new.html")
+        s.Render("/weixin/vipsubscribe/edit_city_new.html")
 }
 
 //修改订阅行业
 func (s *Subscribepay) ToEditSubInduPage() {
-	s.Render("/weixin/vipsubscribe/edit_subscribe_industry.html")
+        s.Render("/weixin/vipsubscribe/edit_subscribe_industry.html")
 }
 
 //提交订阅修改
 func (s *Subscribepay) SubmitEditSubFinish() {
-	s.Render("/weixin/vipsubscribe/edit_subscribe_success.html")
+        s.Render("/weixin/vipsubscribe/edit_subscribe_success.html")
 }
 
 //升级订阅新增区域
 func (s *Subscribepay) AddArea() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/choose_area_upgrade.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/choose_area_upgrade.html")
 }
 
 //升级订阅新增行业
 func (s *Subscribepay) AddIndustry() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.Render("/weixin/vipsubscribe/choose_industry_upgrade.html")
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.Render("/weixin/vipsubscribe/choose_industry_upgrade.html")
 }
 
 //服务续费(will:即将到期,exprie:已到期)
 func (s *Subscribepay) RenewPage(sign string) {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	mynickname, _ := s.Session().Get("s_nickname").(string)
-	myavatar, _ := s.Session().Get("s_avatar").(string)
-	startTime := util.Int64All(s.GetString("startTime"))
-	endTime := util.Int64All(s.GetString("endTime"))
-	orderId := s.GetString("orderId")
-	startTimes := time.Unix(startTime, 0).Format("2006-01-02")
-	endTimes := time.Unix(endTime, 0).Format("2006-01-02")
-	s.T["orderId"] = orderId
-	s.T["startTime"] = startTimes
-	s.T["endTime"] = endTimes
-	s.T["nickname"] = mynickname
-	s.T["avatar"] = myavatar
-	s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
-	s.T["openid"] = se.EncodeString(myopenid)
-	s.T["exprie"] = sign //是否已到期
-	s.Render("/weixin/vipsubscribe/renew_notice.html", &s.T)
+        myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        mynickname, _ := s.Session().Get("s_nickname").(string)
+        myavatar, _ := s.Session().Get("s_avatar").(string)
+        startTime := util.Int64All(s.GetString("startTime"))
+        endTime := util.Int64All(s.GetString("endTime"))
+        orderId := s.GetString("orderId")
+        startTimes := time.Unix(startTime, 0).Format("2006-01-02")
+        endTimes := time.Unix(endTime, 0).Format("2006-01-02")
+        s.T["orderId"] = orderId
+        s.T["startTime"] = startTimes
+        s.T["endTime"] = endTimes
+        s.T["nickname"] = mynickname
+        s.T["avatar"] = myavatar
+        s.T["signature"] = wx.SignJSSDK(s.Site() + s.Url())
+        s.T["openid"] = se.EncodeString(myopenid)
+        s.T["exprie"] = sign //是否已到期
+        s.Render("/weixin/vipsubscribe/renew_notice.html", &s.T)
 }
 
 //开发票
 func (s *Subscribepay) OpenInvoice(order_code string) {
-	s.T["order_code"] = order_code
-	s.Render("/weixin/dataExport/dataExport_applyInvoice.html", &s.T)
+        s.T["order_code"] = order_code
+        s.Render("/weixin/dataExport/dataExport_applyInvoice.html", &s.T)
 }
 
 //预热活动链接跳转
 func (s *Subscribepay) PreheatPoster() {
-	myopenid := util.ObjToString(s.GetSession("s_m_openid"))
-	u, ok := public.MQFW.FindOne("user", `{"s_m_openid":"`+myopenid+`","s_unionid":{"$ne":"`+myopenid+`"}}`)
-	if len(*u) > 0 && ok {
-		if util.Int64All((*u)["i_vip_status"]) == 1 || util.Int64All((*u)["i_vip_status"]) == 2 {
-			s.Redirect("/front/vipsubscribe/toSubVipSetPage")
-		} else {
-			s.Redirect("/front/vipsubscribe/introducePage")
-		}
-	}
+        //myopenid := util.ObjToString(s.GetSession("s_m_openid"))
+        // u, ok := public.MQFW.FindOne("user", `{"s_m_openid":"`+myopenid+`","s_unionid":{"$ne":"`+myopenid+`"}}`)
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        u := jy.GetBigVipUserBaseMsg("10000", s.Session(), qutil.InterfaceToStr(etcdMap["hosts"]), qutil.InterfaceToStr(etcdMap["key"]))
+        if u != nil {
+                if u.VipStatus == 1 || u.VipStatus == 2 {
+                        s.Redirect("/front/vipsubscribe/toSubVipSetPage")
+                } else {
+                        s.Redirect("/front/vipsubscribe/introducePage")
+                }
+        }
 }
 
 func (this *Subscribepay) PcViewPage(htmlName string) error {
-	this.T["logid"] = config.Seoconfig["bigmember"].(string)
-	return this.Render("/vipsubscribe/pc/page_"+htmlName+".html", &this.T)
+        this.T["logid"] = config.Seoconfig["bigmember"].(string)
+        return this.Render("/vipsubscribe/pc/page_"+htmlName+".html", &this.T)
 }
 
 func (this *Subscribepay) WxViewPage(htmlName string) error {
-	this.T["logid"] = config.Seoconfig["bigmember"].(string)
-	return this.Render("/vipsubscribe/wx/page_"+htmlName+".html", &this.T)
+        this.T["logid"] = config.Seoconfig["bigmember"].(string)
+        return this.Render("/vipsubscribe/wx/page_"+htmlName+".html", &this.T)
 }
 
 //
 func (s *Subscribepay) Msgremind() error {
-	param := map[string]string{}
-	if array := strings.Split(s.Url(), "?"); len(array) == 2 {
-		decode, _ := hex.DecodeString(array[1])
-		for _, v := range strings.Split(string(decode), "&") {
-			if vv := strings.Split(v, "="); len(vv) == 2 {
-				param[vv[0]] = vv[1]
-			}
-		}
-	}
-	t := param["type"]
-	advertcode := param["advertcode"]
-	if t == "unpaid" { //未支付 已支付
-		return s.Redirect("/front/vipsubscribe/toOrderDetailPage?orderCode=" + param["ordercode"] + "&advertcode=" + advertcode)
-	} else if t == "bigmember_unpaid" {
-		return s.Redirect("/front/wxMyOrder/memberDetail/" + param["ordercode"] + "?advertcode=" + advertcode)
-	} else if t == "unknow_unpaid" {
-		return s.Redirect("/weixin/pay/toMyWxOrder")
-	}
-	userId, _ := s.GetSession("userId").(string)
-	if userId == "" {
-		return s.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 {
-		return s.Render("_error.html")
-	}
-	myLastOrderCode := func(user_id string) string {
-		order := public.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"user_id":      user_id,
-			"order_status": 1,
-			"product_type": "VIP订阅",
-		}, "id,order_code", "pay_time desc")
-		if order != nil && len(*order) > 0 {
-			return util.ObjToString((*order)["order_code"])
-		} else {
-			return ""
-		}
-	}
-	i_vip_status := util.IntAll((*user)["i_vip_status"])
-	if t == "bigmember_soonexprie" || t == "bigmember_expried" { //大会员即将到期、已到期
-		now_unix := time.Now().Unix()
-		i_member_endtime := util.Int64All((*user)["i_member_endtime"])
-		if now_unix < i_member_endtime-259200 {
-			//已续费
-			return s.Redirect("/big/wx/page/landingPage?advertcode=" + advertcode)
-		} else {
-			if now_unix > i_member_endtime {
-				//未续费已到期,跳转到再次购买页面
-				return s.Redirect("/jy_mobile/common/order/create/bigmember?advertcode=" + advertcode)
-			} else {
-				//未续费未到期,跳转到续费页面
-				return s.Redirect("/big/wx/page/landingPage?advertcode=" + advertcode)
-			}
-		}
-	} else if t == "paid" {
-		if i_vip_status > 0 {
-			return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
-		} else {
-			return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&orderCode=" + myLastOrderCode(userId) + "&advertcode=" + advertcode)
-		}
-	} else if t == "bigmember_paid" {
-		if util.IntAll((*user)["i_member_status"]) > 0 {
-			return s.Redirect("/big/wx/page/open_app?type=1&advertcode=" + advertcode)
-		} else {
-			return s.Redirect("/big/wx/page/landingPage?advertcode=" + advertcode)
-		}
-	} else if t == "soonexprie" || t == "expried" { //即将到期 已到期
-		now_unix := time.Now().Unix()
-		l_vip_endtime := util.Int64All((*user)["l_vip_endtime"])
-		if now_unix < l_vip_endtime-259200 {
-			//已续费
-			return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
-		} else {
-			if now_unix > l_vip_endtime {
-				//未续费已到期,跳转到再次购买页面
-				return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&orderCode=" + myLastOrderCode(userId) + "&advertcode=" + advertcode)
-			} else {
-				//未续费未到期,跳转到续费页面
-				return s.Redirect("/jy_mobile/common/order/create/svip?type=renew&advertcode=" + advertcode)
-			}
-		}
-	} else if t == "ontrial_soonexprie" || t == "ontrial_expried" { //试用即将到期 试用已到期
-		if i_vip_status == 2 {
-			return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
-		} else {
-			return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&advertcode=" + advertcode)
-		}
-	} else if t == "buyerclass" { //公共资源交易提醒
-		if i_vip_status > 0 { //vip未到期
-			return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
-		} else if i_vip_status < 0 { //vip已到期
-			return s.Redirect("/front/vipsubscribe/introducePage?advertcode=" + advertcode)
-		}
-	}
-	return s.Render("_error.html")
+        param := map[string]string{}
+        if array := strings.Split(s.Url(), "?"); len(array) == 2 {
+                decode, _ := hex.DecodeString(array[1])
+                for _, v := range strings.Split(string(decode), "&") {
+                        if vv := strings.Split(v, "="); len(vv) == 2 {
+                                param[vv[0]] = vv[1]
+                        }
+                }
+        }
+        t := param["type"]
+        advertcode := param["advertcode"]
+        if t == "unpaid" { //未支付 已支付
+                return s.Redirect("/front/vipsubscribe/toOrderDetailPage?orderCode=" + param["ordercode"] + "&advertcode=" + advertcode)
+        } else if t == "bigmember_unpaid" {
+                return s.Redirect("/front/wxMyOrder/memberDetail/" + param["ordercode"] + "?advertcode=" + advertcode)
+        } else if t == "unknow_unpaid" {
+                return s.Redirect("/weixin/pay/toMyWxOrder")
+        }
+        userId, _ := s.GetSession("userId").(string)
+        if userId == "" {
+                return s.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}`)
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        user := jy.GetBigVipUserBaseMsg("10000", s.Session(), qutil.InterfaceToStr(etcdMap["hosts"]), qutil.InterfaceToStr(etcdMap["key"]))
+        if user == nil {
+                return s.Render("_error.html")
+        }
+        myLastOrderCode := func(user_id string) string {
+                order := public.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "user_id":      user_id,
+                        "order_status": 1,
+                        "product_type": "VIP订阅",
+                }, "id,order_code", "pay_time desc")
+                if order != nil && len(*order) > 0 {
+                        return util.ObjToString((*order)["order_code"])
+                } else {
+                        return ""
+                }
+        }
+        i_vip_status := user.VipStatus
+        if t == "bigmember_soonexprie" || t == "bigmember_expried" { //大会员即将到期、已到期
+                now_unix := time.Now().Unix()
+                i_member_endtime := user.EndTime
+                if now_unix < i_member_endtime-259200 {
+                        //已续费
+                        return s.Redirect("/big/wx/page/landingPage?advertcode=" + advertcode)
+                } else {
+                        if now_unix > i_member_endtime {
+                                //未续费已到期,跳转到再次购买页面
+                                return s.Redirect("/jy_mobile/common/order/create/bigmember?advertcode=" + advertcode)
+                        } else {
+                                //未续费未到期,跳转到续费页面
+                                return s.Redirect("/big/wx/page/landingPage?advertcode=" + advertcode)
+                        }
+                }
+        } else if t == "paid" {
+                if i_vip_status > 0 {
+                        return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
+                } else {
+                        return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&orderCode=" + myLastOrderCode(userId) + "&advertcode=" + advertcode)
+                }
+        } else if t == "bigmember_paid" {
+                if user.Status > 0 {
+                        return s.Redirect("/big/wx/page/open_app?type=1&advertcode=" + advertcode)
+                } else {
+                        return s.Redirect("/big/wx/page/landingPage?advertcode=" + advertcode)
+                }
+        } else if t == "soonexprie" || t == "expried" { //即将到期 已到期
+                now_unix := time.Now().Unix()
+                l_vip_endtime := user.Data.Vip.EndTime
+                if now_unix < l_vip_endtime-259200 {
+                        //已续费
+                        return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
+                } else {
+                        if now_unix > l_vip_endtime {
+                                //未续费已到期,跳转到再次购买页面
+                                return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&orderCode=" + myLastOrderCode(userId) + "&advertcode=" + advertcode)
+                        } else {
+                                //未续费未到期,跳转到续费页面
+                                return s.Redirect("/jy_mobile/common/order/create/svip?type=renew&advertcode=" + advertcode)
+                        }
+                }
+        } else if t == "ontrial_soonexprie" || t == "ontrial_expried" { //试用即将到期 试用已到期
+                if i_vip_status == 2 {
+                        return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
+                } else {
+                        return s.Redirect("/jy_mobile/common/order/create/svip?type=buy&advertcode=" + advertcode)
+                }
+        } else if t == "buyerclass" { //公共资源交易提醒
+                if i_vip_status > 0 { //vip未到期
+                        return s.Redirect("/front/vipsubscribe/toSubVipSetPage?advertcode=" + advertcode)
+                } else if i_vip_status < 0 { //vip已到期
+                        return s.Redirect("/front/vipsubscribe/introducePage?advertcode=" + advertcode)
+                }
+        }
+        return s.Render("_error.html")
 }

+ 264 - 261
src/jfw/front/wxMyOrder.go

@@ -1,342 +1,345 @@
 package front
 
 import (
-	"errors"
-	"fmt"
-	"jy/src/jfw/config"
-	"jy/src/jfw/wx"
-	"net/url"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "errors"
+        "fmt"
+        "jy/src/jfw/config"
+        "jy/src/jfw/wx"
+        "net/url"
 
-	"jy/src/jfw/jyutil"
+        "jy/src/jfw/jyutil"
 
-	"app.yhyue.com/moapp/jypkg/public"
+        "app.yhyue.com/moapp/jypkg/public"
 
-	util "app.yhyue.com/moapp/jybase/common"
+        util "app.yhyue.com/moapp/jybase/common"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type WxMyOrder struct {
-	*xweb.Action
-	myMenu         xweb.Mapper `xweb:"/front/wxMyOrder/myMenu"`                //微信我的目录
-	myEmail        xweb.Mapper `xweb:"/front/wxMyOrder/myEmail"`               //微信我的邮箱
-	myPhone        xweb.Mapper `xweb:"/front/wxMyOrder/myPhone"`               //微信我的手机
-	setSuccess     xweb.Mapper `xweb:"/front/wxMyOrder/setSuccess"`            //查询订单
-	wxGetOrderCode xweb.Mapper `xweb:"/front/wxMyOrder/wxGetOrderCode/(\\w+)"` //申请发票获取订单编号
-	wxPaySuccess   xweb.Mapper `xweb:"/front/wxMyorder/wxPaySuccess/(\\w+)"`
-
-	getValuationList xweb.Mapper `xweb:"/front/wxMyOrder/getValuationList/(\\w+)"` //计价清单
-	myset            xweb.Mapper `xweb:"/front/wxMyOrder/myset"`                   //设置页面
-
-	getpage              xweb.Mapper `xweb:"/front/invoice/showpage"`           //开发票
-	check_invoice        xweb.Mapper `xweb:"/front/invoice/check_invoice.html"` //查看发票
-	cantInvoice          xweb.Mapper `xweb:"/front/invoice/cantInvoice"`
-	memberDetail         xweb.Mapper `xweb:"/front/wxMyOrder/memberDetail/(\\w+)"`         //大会员订单详情页面
-	aiForecastPackdetail xweb.Mapper `xweb:"/front/wxMyOrder/aiForecastPackdetail/(\\w+)"` //大会员订单详情页面
-	subAccountDetail     xweb.Mapper `xweb:"/front/wxMyOrder/subAccountDetail/(\\w+)"`     //子账号订单详情
-	bidfileDetail        xweb.Mapper `xweb:"/front/wxMyOrder/bidfileDetail/(\\w+)"`        //招标文件解读订单详情
-	integralDetail       xweb.Mapper `xweb:"/front/wxMyOrder/integralDetail/(\\w+)"`       //剑鱼币订单详情
-
-	//创建订单
-	wxFilePackCreateOrder xweb.Mapper `xweb:"/swordfish/filePack/createOrder"` //附件下载包 wx
-	pcFilePackCreateOrder xweb.Mapper `xweb:"/front/filepack/createOrder"`     //pc
-	pcfilePackDetail      xweb.Mapper `xweb:"/front/file/packDetail"`
+        *xweb.Action
+        myMenu         xweb.Mapper `xweb:"/front/wxMyOrder/myMenu"`                //微信我的目录
+        myEmail        xweb.Mapper `xweb:"/front/wxMyOrder/myEmail"`               //微信我的邮箱
+        myPhone        xweb.Mapper `xweb:"/front/wxMyOrder/myPhone"`               //微信我的手机
+        setSuccess     xweb.Mapper `xweb:"/front/wxMyOrder/setSuccess"`            //查询订单
+        wxGetOrderCode xweb.Mapper `xweb:"/front/wxMyOrder/wxGetOrderCode/(\\w+)"` //申请发票获取订单编号
+        wxPaySuccess   xweb.Mapper `xweb:"/front/wxMyorder/wxPaySuccess/(\\w+)"`
+
+        getValuationList xweb.Mapper `xweb:"/front/wxMyOrder/getValuationList/(\\w+)"` //计价清单
+        myset            xweb.Mapper `xweb:"/front/wxMyOrder/myset"`                   //设置页面
+
+        getpage              xweb.Mapper `xweb:"/front/invoice/showpage"`           //开发票
+        check_invoice        xweb.Mapper `xweb:"/front/invoice/check_invoice.html"` //查看发票
+        cantInvoice          xweb.Mapper `xweb:"/front/invoice/cantInvoice"`
+        memberDetail         xweb.Mapper `xweb:"/front/wxMyOrder/memberDetail/(\\w+)"`         //大会员订单详情页面
+        aiForecastPackdetail xweb.Mapper `xweb:"/front/wxMyOrder/aiForecastPackdetail/(\\w+)"` //大会员订单详情页面
+        subAccountDetail     xweb.Mapper `xweb:"/front/wxMyOrder/subAccountDetail/(\\w+)"`     //子账号订单详情
+        bidfileDetail        xweb.Mapper `xweb:"/front/wxMyOrder/bidfileDetail/(\\w+)"`        //招标文件解读订单详情
+        integralDetail       xweb.Mapper `xweb:"/front/wxMyOrder/integralDetail/(\\w+)"`       //剑鱼币订单详情
+
+        //创建订单
+        wxFilePackCreateOrder xweb.Mapper `xweb:"/swordfish/filePack/createOrder"` //附件下载包 wx
+        pcFilePackCreateOrder xweb.Mapper `xweb:"/front/filepack/createOrder"`     //pc
+        pcfilePackDetail      xweb.Mapper `xweb:"/front/file/packDetail"`
 }
 
 func init() {
-	xweb.AddAction(&WxMyOrder{})
+        xweb.AddAction(&WxMyOrder{})
 }
 
 var (
-	pagesize_max int = 10
+        pagesize_max int = 10
 )
 
 //
 func (w *WxMyOrder) MyMenu() error {
-	if w.Session().Get("userId") == nil {
-
-		if w.GetString("state") == "wx" {
-			//微信跳回来的
-			code := w.GetString("code")
-			if code != "" {
-				openid := jyutil.Getopenid(code)
-				if openid != "" {
-					FindUserAndCreateSess(openid, w.Session(), "wx", false)
-				}
-			}
-		} else {
-			if public.CheckWxBrowser(w.Request) {
-				//所有参数都不再使用,跳到微信验证用户
-				return w.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(w.Site()+w.Url()), "wx"), 302)
-			}
-		}
-		userid := util.ObjToString(w.GetSession("userId"))
-		if userid == "" {
-			return errors.New("未登录")
-		}
-	}
-	//分享
-	w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
-	w.T["nickname"], _ = w.Session().Get("s_nickname").(string)
-	myopenid, _ := w.Session().Get("s_m_openid").(string)
-	w.T["openid"] = se.EncodeString(myopenid)
-	w.T["avatar"], _ = w.Session().Get("s_avatar").(string)
-	return w.Render("weixin/my.html", &w.T)
+        if w.Session().Get("userId") == nil {
+
+                if w.GetString("state") == "wx" {
+                        //微信跳回来的
+                        code := w.GetString("code")
+                        if code != "" {
+                                openid := jyutil.Getopenid(code)
+                                if openid != "" {
+                                        FindUserAndCreateSess(openid, w.Session(), "wx", false)
+                                }
+                        }
+                } else {
+                        if public.CheckWxBrowser(w.Request) {
+                                //所有参数都不再使用,跳到微信验证用户
+                                return w.Redirect(fmt.Sprintf(config.Wxoauth, url.QueryEscape(w.Site()+w.Url()), "wx"), 302)
+                        }
+                }
+                userid := util.ObjToString(w.GetSession("userId"))
+                if userid == "" {
+                        return errors.New("未登录")
+                }
+        }
+        //分享
+        w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
+        w.T["nickname"], _ = w.Session().Get("s_nickname").(string)
+        myopenid, _ := w.Session().Get("s_m_openid").(string)
+        w.T["openid"] = se.EncodeString(myopenid)
+        w.T["avatar"], _ = w.Session().Get("s_avatar").(string)
+        return w.Render("weixin/my.html", &w.T)
 }
 
 func (w *WxMyOrder) MyEmail() {
-	//分享
-	w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
-	myopenid, _ := w.Session().Get("s_m_openid").(string)
-	w.T["openid"] = se.EncodeString(myopenid)
-	mynickname, _ := w.Session().Get("s_nickname").(string)
-	myavatar, _ := w.Session().Get("s_avatar").(string)
-	w.T["nickname"] = mynickname
-	w.T["avatar"] = myavatar
-	w.T["userId"] = util.ObjToString(w.GetSession("userId"))
-
-	name := w.GetString("name") //
-	//检测用户是否绑定邮箱
-	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 {
-		if util.ObjToString((*res)["s_myemail"]) == "" || name != "" {
-			//未绑定邮箱 进入绑定邮箱界面
-			if name != "" && util.ObjToString((*res)["s_myemail"]) != "" {
-				w.T["text_email"] = util.ObjToString((*res)["s_myemail"])
-				//invoice 是从开发票跳转过来的
-				if name == "invoice" {
-					orderCode := w.GetString("orderCode")
-					if orderCode != "" {
-						w.T["orderCode"] = orderCode
-					}
-				}
-			}
-			w.Render("/weixin/email/bind_email.html", &w.T)
-		} else {
-			//绑定邮箱进入 更换解绑邮箱界面
-			if util.ObjToString((*res)["s_myemail"]) != "" {
-				w.T["text_email"] = util.ObjToString((*res)["s_myemail"])
-			}
-			w.Render("/weixin/email/unbind_email.html", &w.T)
-		}
-	}
+        //分享
+        w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
+        myopenid, _ := w.Session().Get("s_m_openid").(string)
+        w.T["openid"] = se.EncodeString(myopenid)
+        mynickname, _ := w.Session().Get("s_nickname").(string)
+        myavatar, _ := w.Session().Get("s_avatar").(string)
+        w.T["nickname"] = mynickname
+        w.T["avatar"] = myavatar
+        w.T["userId"] = util.ObjToString(w.GetSession("userId"))
+
+        name := w.GetString("name") //
+        //检测用户是否绑定邮箱
+        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 {
+                if util.ObjToString((*res)["s_myemail"]) == "" || name != "" {
+                        //未绑定邮箱 进入绑定邮箱界面
+                        if name != "" && util.ObjToString((*res)["s_myemail"]) != "" {
+                                w.T["text_email"] = util.ObjToString((*res)["s_myemail"])
+                                //invoice 是从开发票跳转过来的
+                                if name == "invoice" {
+                                        orderCode := w.GetString("orderCode")
+                                        if orderCode != "" {
+                                                w.T["orderCode"] = orderCode
+                                        }
+                                }
+                        }
+                        w.Render("/weixin/email/bind_email.html", &w.T)
+                } else {
+                        //绑定邮箱进入 更换解绑邮箱界面
+                        if util.ObjToString((*res)["s_myemail"]) != "" {
+                                w.T["text_email"] = util.ObjToString((*res)["s_myemail"])
+                        }
+                        w.Render("/weixin/email/unbind_email.html", &w.T)
+                }
+        }
 }
 
 func (w *WxMyOrder) SetSuccess() {
-	//分享
-	w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
-	myopenid, _ := w.Session().Get("s_m_openid").(string)
-	w.T["openid"] = se.EncodeString(myopenid)
-	mynickname, _ := w.Session().Get("s_nickname").(string)
-	myavatar, _ := w.Session().Get("s_avatar").(string)
-	w.T["nickname"] = mynickname
-	w.T["avatar"] = myavatar
-	w.T["userId"] = util.ObjToString(w.GetSession("userId"))
-
-	w.Render("/weixin/email/bind_success.html", &w.T)
+        //分享
+        w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
+        myopenid, _ := w.Session().Get("s_m_openid").(string)
+        w.T["openid"] = se.EncodeString(myopenid)
+        mynickname, _ := w.Session().Get("s_nickname").(string)
+        myavatar, _ := w.Session().Get("s_avatar").(string)
+        w.T["nickname"] = mynickname
+        w.T["avatar"] = myavatar
+        w.T["userId"] = util.ObjToString(w.GetSession("userId"))
+
+        w.Render("/weixin/email/bind_success.html", &w.T)
 }
 
 func (w *WxMyOrder) WxGetOrderCode(order_code string) error {
-	myOpenid := ""
-	if openid := w.GetSession("s_m_openid"); openid != nil {
-		myOpenid = openid.(string)
-	} else {
-		return errors.New("未登录")
-	}
-	//分享
-	w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
-	w.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := w.Session().Get("s_nickname").(string)
-	myavatar, _ := w.Session().Get("s_avatar").(string)
-	w.T["nickname"] = mynickname
-	w.T["avatar"] = myavatar
-	//-----------------------
-	var status, order_status int64
-	queryMap := map[string]interface{}{
-		"order_code": order_code,
-	}
-	oDate := public.Mysql.FindOne(tableName_order, queryMap, "", "")
-	status = (*oDate)["applybill_status"].(int64)
-	order_status = (*oDate)["order_status"].(int64)
-	w.T["order_code"] = order_code
-	//是否申请发票 支付状态
-	if status == 1 || order_status == 0 {
-		w.Redirect("/front/wx_dataExport/wxToOrderDetail?orderCode=" + order_code)
-	} else {
-		w.Render("/weixin/dataExport/dataExport_applyInvoice.html", &w.T)
-	}
-	return nil
+        myOpenid := ""
+        if openid := w.GetSession("s_m_openid"); openid != nil {
+                myOpenid = openid.(string)
+        } else {
+                return errors.New("未登录")
+        }
+        //分享
+        w.T["signature"] = wx.SignJSSDK(w.Site() + w.Url())
+        w.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := w.Session().Get("s_nickname").(string)
+        myavatar, _ := w.Session().Get("s_avatar").(string)
+        w.T["nickname"] = mynickname
+        w.T["avatar"] = myavatar
+        //-----------------------
+        var status, order_status int64
+        queryMap := map[string]interface{}{
+                "order_code": order_code,
+        }
+        oDate := public.Mysql.FindOne(tableName_order, queryMap, "", "")
+        status = (*oDate)["applybill_status"].(int64)
+        order_status = (*oDate)["order_status"].(int64)
+        w.T["order_code"] = order_code
+        //是否申请发票 支付状态
+        if status == 1 || order_status == 0 {
+                w.Redirect("/front/wx_dataExport/wxToOrderDetail?orderCode=" + order_code)
+        } else {
+                w.Render("/weixin/dataExport/dataExport_applyInvoice.html", &w.T)
+        }
+        return nil
 }
 
 func (w *WxMyOrder) WxPaySuccess(order_code string) error {
-	userId := w.Session().Get("userId")
-	openid := w.Session().Get("s_m_openid")
-	if userId == nil || openid == nil {
-		return errors.New("未登录")
-	}
-	w.T["order_code"] = order_code
-	return w.Render("/weixin/dataExport/dataExport_invoiceSuccess.html", &w.T)
+        userId := w.Session().Get("userId")
+        openid := w.Session().Get("s_m_openid")
+        if userId == nil || openid == nil {
+                return errors.New("未登录")
+        }
+        w.T["order_code"] = order_code
+        return w.Render("/weixin/dataExport/dataExport_invoiceSuccess.html", &w.T)
 }
 
 //设置页面
 func (w *WxMyOrder) Myset() error {
-	userid := util.ObjToString(w.GetSession("userId"))
-	isVip := false
-	if userid != "" {
-		user, ok := mongodb.FindById("user", userid, `{"i_vip_status":1}`)
-		if ok && user != nil {
-			if util.Int64All((*user)["i_vip_status"]) == 1 || util.Int64All((*user)["i_vip_status"]) == 2 {
-				isVip = true
-			}
-		}
-
-	}
-	w.T["isVip"] = isVip
-	return w.Render("/weixin/setpage.html")
+        userid := util.ObjToString(w.GetSession("userId"))
+        isVip := false
+        if userid != "" {
+                //user, ok := mongodb.FindById("user", userid, `{"i_vip_status":1}`)
+                etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                user := jy.GetBigVipUserBaseMsg("10000", s.Session(), qutil.InterfaceToStr(etcdMap["hosts"]), qutil.InterfaceToStr(etcdMap["key"]))
+                if user != nil {
+                        if user.VipStatus == 1 || user.VipStatus == 2 {
+                                isVip = true
+                        }
+                }
+
+        }
+        w.T["isVip"] = isVip
+        return w.Render("/weixin/setpage.html")
 }
 
 //设置页面
 func (w *WxMyOrder) MyPhone() error {
-	return w.Render("/weixin/setphone.html")
+        return w.Render("/weixin/setphone.html")
 }
 
 func (w *WxMyOrder) GetValuationList(order_code string) error {
-	w.T["order_code"] = order_code
-	return w.Render("/weixin/vipsubscribe/valuation_list.html", &w.T)
+        w.T["order_code"] = order_code
+        return w.Render("/weixin/vipsubscribe/valuation_list.html", &w.T)
 }
 func (w *WxMyOrder) Datas(queryM map[string]interface{}, pageNum int) (haveNextPage bool, result []map[string]interface{}, err error) {
-	res := *public.Mysql.Find(tableName_order, queryM, "id,order_code,filter_publishtime,create_time,data_spec,filter_id,filter_keys,order_money,data_count,order_status,pay_way", "create_time desc", -1, 0)
-	if len(res) > 0 {
-		start := (pageNum - 1) * pagesize_max
-		end := pageNum * pagesize_max
-		if end > len(res) {
-			end = len(res)
-		}
-		if start < len(res) {
-			result = res[start:end]
-		}
-	}
-	haveNextPage = len(result) >= pagesize_max
-	return
+        res := *public.Mysql.Find(tableName_order, queryM, "id,order_code,filter_publishtime,create_time,data_spec,filter_id,filter_keys,order_money,data_count,order_status,pay_way", "create_time desc", -1, 0)
+        if len(res) > 0 {
+                start := (pageNum - 1) * pagesize_max
+                end := pageNum * pagesize_max
+                if end > len(res) {
+                        end = len(res)
+                }
+                if start < len(res) {
+                        result = res[start:end]
+                }
+        }
+        haveNextPage = len(result) >= pagesize_max
+        return
 }
 
 func (t *WxMyOrder) Getpage() {
-	order_code := t.GetString("order_code")
-	c := t.GetString("c") //重开发票
-	if order_code != "" {
-		res := public.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code}, "order_money,product_type,user_mail,user_phone,applybill_status", "")
-		if res != nil {
-			price := (*res)["order_money"]
-			product_name := (*res)["product_type"].(string)
-			if product_name == "历史数据" {
-				t.T["e_mail"] = (*res)["user_mail"]
-				t.T["phone"] = (*res)["user_phone"]
-			}
-			t.T["order_code"] = order_code
-			t.T["price"] = price
-			t.T["product_name"] = product_name
-			t.T["applybill_status"] = (*res)["applybill_status"]
-
-		}
-		t.T["c"] = c
-		_ = t.Render("/weixin/invoice/invoicing.html", &t.T)
-	}
+        order_code := t.GetString("order_code")
+        c := t.GetString("c") //重开发票
+        if order_code != "" {
+                res := public.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": order_code}, "order_money,product_type,user_mail,user_phone,applybill_status", "")
+                if res != nil {
+                        price := (*res)["order_money"]
+                        product_name := (*res)["product_type"].(string)
+                        if product_name == "历史数据" {
+                                t.T["e_mail"] = (*res)["user_mail"]
+                                t.T["phone"] = (*res)["user_phone"]
+                        }
+                        t.T["order_code"] = order_code
+                        t.T["price"] = price
+                        t.T["product_name"] = product_name
+                        t.T["applybill_status"] = (*res)["applybill_status"]
+
+                }
+                t.T["c"] = c
+                _ = t.Render("/weixin/invoice/invoicing.html", &t.T)
+        }
 }
 
 func (t *WxMyOrder) Check_invoice() {
-	order_code := t.GetString("order_code")
-	t.T["order_code"] = order_code
-	t.Render("/weixin/invoice/check_invoice.html", &t.T)
+        order_code := t.GetString("order_code")
+        t.T["order_code"] = order_code
+        t.Render("/weixin/invoice/check_invoice.html", &t.T)
 }
 
 func (t *WxMyOrder) CantInvoice() {
-	t.Render("/weixin/invoice/cantInvocie.html")
+        t.Render("/weixin/invoice/cantInvocie.html")
 }
 
 func (t *WxMyOrder) MemberDetail(order_code string) {
-	//分享
-	myOpenid, _ := t.GetSession("s_m_openid").(string)
-	t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
-	t.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := t.Session().Get("s_nickname").(string)
-	myavatar, _ := t.Session().Get("s_avatar").(string)
-	t.T["nickname"] = mynickname
-	t.T["avatar"] = myavatar
-	t.T["order_code"] = order_code
-	t.Render("/weixin/member/memberdetail.html", &t.T)
+        //分享
+        myOpenid, _ := t.GetSession("s_m_openid").(string)
+        t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
+        t.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := t.Session().Get("s_nickname").(string)
+        myavatar, _ := t.Session().Get("s_avatar").(string)
+        t.T["nickname"] = mynickname
+        t.T["avatar"] = myavatar
+        t.T["order_code"] = order_code
+        t.Render("/weixin/member/memberdetail.html", &t.T)
 }
 
 func (t *WxMyOrder) AiForecastPackdetail(order_code string) {
-	//分享
-	myOpenid, _ := t.GetSession("s_m_openid").(string)
-	t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
-	t.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := t.Session().Get("s_nickname").(string)
-	myavatar, _ := t.Session().Get("s_avatar").(string)
-	t.T["nickname"] = mynickname
-	t.T["avatar"] = myavatar
-	t.T["order_code"] = order_code
-	t.Render("/weixin/member/aiForecastPackdetail.html", &t.T)
+        //分享
+        myOpenid, _ := t.GetSession("s_m_openid").(string)
+        t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
+        t.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := t.Session().Get("s_nickname").(string)
+        myavatar, _ := t.Session().Get("s_avatar").(string)
+        t.T["nickname"] = mynickname
+        t.T["avatar"] = myavatar
+        t.T["order_code"] = order_code
+        t.Render("/weixin/member/aiForecastPackdetail.html", &t.T)
 }
 
 func (t *WxMyOrder) SubAccountDetail(order_code string) {
-	//分享
-	myOpenid, _ := t.GetSession("s_m_openid").(string)
-	t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
-	t.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := t.Session().Get("s_nickname").(string)
-	myavatar, _ := t.Session().Get("s_avatar").(string)
-	t.T["nickname"] = mynickname
-	t.T["avatar"] = myavatar
-	t.T["order_code"] = order_code
-	t.Render("/weixin/member/subAccountDetail.html", &t.T)
+        //分享
+        myOpenid, _ := t.GetSession("s_m_openid").(string)
+        t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
+        t.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := t.Session().Get("s_nickname").(string)
+        myavatar, _ := t.Session().Get("s_avatar").(string)
+        t.T["nickname"] = mynickname
+        t.T["avatar"] = myavatar
+        t.T["order_code"] = order_code
+        t.Render("/weixin/member/subAccountDetail.html", &t.T)
 }
 
 func (t *WxMyOrder) BidfileDetail(order_code string) {
-	myOpenid, _ := t.GetSession("s_m_openid").(string)
-	t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
-	t.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := t.Session().Get("s_nickname").(string)
-	myavatar, _ := t.Session().Get("s_avatar").(string)
-	t.T["nickname"] = mynickname
-	t.T["avatar"] = myavatar
-	t.T["order_code"] = order_code
-	t.Render("/weixin/commonPay/bidfile/bidfiledetail.html", &t.T)
+        myOpenid, _ := t.GetSession("s_m_openid").(string)
+        t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
+        t.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := t.Session().Get("s_nickname").(string)
+        myavatar, _ := t.Session().Get("s_avatar").(string)
+        t.T["nickname"] = mynickname
+        t.T["avatar"] = myavatar
+        t.T["order_code"] = order_code
+        t.Render("/weixin/commonPay/bidfile/bidfiledetail.html", &t.T)
 }
 
 func (t *WxMyOrder) IntegralDetail(order_code string) {
-	myOpenid, _ := t.GetSession("s_m_openid").(string)
-	t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
-	t.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := t.Session().Get("s_nickname").(string)
-	myavatar, _ := t.Session().Get("s_avatar").(string)
-	t.T["nickname"] = mynickname
-	t.T["avatar"] = myavatar
-	t.T["order_code"] = order_code
-	t.Render("/weixin/commonPay/integral/integralDetail.html", &t.T)
+        myOpenid, _ := t.GetSession("s_m_openid").(string)
+        t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
+        t.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := t.Session().Get("s_nickname").(string)
+        myavatar, _ := t.Session().Get("s_avatar").(string)
+        t.T["nickname"] = mynickname
+        t.T["avatar"] = myavatar
+        t.T["order_code"] = order_code
+        t.Render("/weixin/commonPay/integral/integralDetail.html", &t.T)
 }
 
 //
 func (t *WxMyOrder) WxFilePackCreateOrder() {
-	t.Render("/weixin/commonPay/filePack/createorder.html")
+        t.Render("/weixin/commonPay/filePack/createorder.html")
 }
 
 //
 func (t *WxMyOrder) PcFilePackCreateOrder() {
-	t.Render("/pc/filePack/createorder.html")
+        t.Render("/pc/filePack/createorder.html")
 }
 
 func (t *WxMyOrder) PcfilePackDetail() {
-	myOpenid, _ := t.GetSession("s_m_openid").(string)
-	t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
-	t.T["openid"] = se.EncodeString(myOpenid)
-	mynickname, _ := t.Session().Get("s_nickname").(string)
-	myavatar, _ := t.Session().Get("s_avatar").(string)
-	t.T["nickname"] = mynickname
-	t.T["avatar"] = myavatar
-	t.T["order_code"] = t.GetString("order_code")
-	t.Render("/order/pc/filePack/detail.html", &t.T)
+        myOpenid, _ := t.GetSession("s_m_openid").(string)
+        t.T["signature"] = wx.SignJSSDK(t.Site() + t.Url())
+        t.T["openid"] = se.EncodeString(myOpenid)
+        mynickname, _ := t.Session().Get("s_nickname").(string)
+        myavatar, _ := t.Session().Get("s_avatar").(string)
+        t.T["nickname"] = mynickname
+        t.T["avatar"] = myavatar
+        t.T["order_code"] = t.GetString("order_code")
+        t.Render("/order/pc/filePack/detail.html", &t.T)
 }

+ 372 - 341
src/jfw/front/wxkeyset.go

@@ -1,373 +1,404 @@
 package front
 
 import (
-	"fmt"
-	"jy/src/jfw/config"
-	"jy/src/jfw/wx"
-	"net/url"
-	"regexp"
-	"strconv"
-	"strings"
+        "fmt"
+        "jy/src/jfw/config"
+        "jy/src/jfw/wx"
+        "net/url"
+        "regexp"
+        "strconv"
+        "strings"
 
-	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"
 )
 
 //进入订阅词设置
 func (m *Front) WxKeyset(tpl string) error {
-	defer util.Catch()
-	userid := util.ObjToString(m.GetSession("userId"))
-	surprise := m.GetSession("surprise")
-	if userid == "" {
-		return m.Redirect("/swordfish/share/-1")
-	}
-	if tiptext := m.GetString("tiptext"); tiptext != "" {
-		go mongodb.Save("opentip_log", map[string]interface{}{
-			"tiptext":    tiptext,
-			"userid":     userid,
-			"createtime": time.Now().Unix(),
-			"type":       "keyset",
-		})
-	}
-	etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
-	vipMsg := jy.GetBigVipUserBaseMsg("10000", m.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
-	if (tpl == "index" || tpl == "filterset") && vipMsg.VipStatus <= 0 && vipMsg.Status <= 0 && isInTSguide(userid) { //仅免费用户跳转向导页面
-		return m.Redirect("/front/tenderSubscribe/guide?url=" + url.QueryEscape(m.Request.RequestURI))
-	}
-	//到新订阅设置
-	if vipMsg.VipStatus > 0 || vipMsg.IsUpgrade {
-		return m.Redirect("/front/vipsubscribe/toSubVipSetPage")
-	}
-	if tpl == "seniorset" {
-		data, ok := mongodb.FindById("user", userid, `{"o_jy":1}`)
-		if ok && 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
-			}
-		}
-	}
-	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
-	m.T["openid"] = se.EncodeString(util.ObjToString(m.GetSession("s_m_openid")))
-	m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
-	mynickname, _ := m.Session().Get("s_nickname").(string)
-	myavatar, _ := m.Session().Get("s_avatar").(string)
-	m.T["nickname"] = mynickname
-	m.T["avatar"] = myavatar
-	//直播活动和预热活动期间
-	if config.ActiveConfig.Live_Active_End > time.Now().Unix() && time.Now().Unix() > config.ActiveConfig.Live_Preheat_Start {
-		m.T["LiveState"] = true
-	}
-	return m.Render("/weixin/wxkeyset/"+tpl+".html", &m.T)
+        defer util.Catch()
+        userid := util.ObjToString(m.GetSession("userId"))
+        surprise := m.GetSession("surprise")
+        if userid == "" {
+                return m.Redirect("/swordfish/share/-1")
+        }
+        if tiptext := m.GetString("tiptext"); tiptext != "" {
+                go mongodb.Save("opentip_log", map[string]interface{}{
+                        "tiptext":    tiptext,
+                        "userid":     userid,
+                        "createtime": time.Now().Unix(),
+                        "type":       "keyset",
+                })
+        }
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        vipMsg := jy.GetBigVipUserBaseMsg("10000", m.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+        if (tpl == "index" || tpl == "filterset") && vipMsg.VipStatus <= 0 && vipMsg.Status <= 0 && isInTSguide(userid) { //仅免费用户跳转向导页面
+                return m.Redirect("/front/tenderSubscribe/guide?url=" + url.QueryEscape(m.Request.RequestURI))
+        }
+        //到新订阅设置
+        if vipMsg.VipStatus > 0 || vipMsg.IsUpgrade {
+                return m.Redirect("/front/vipsubscribe/toSubVipSetPage")
+        }
+        if tpl == "seniorset" {
+                //data, ok := mongodb.FindById("user", userid, `{"o_jy":1}`)
+                etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                data := jy.GetBigVipUserBaseMsg("10000",  m.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+
+                if data != nil {
+                        if data.Data.Free.FreeHasKey {
+                                m.T["haskeyword"] = true
+                        }
+
+                }
+        }
+        s_surprise := ""
+        if tpl == "index" || tpl == "filterset" {
+                //data, ok := mongodb.FindById("user", userid, `{"o_jy":1}`)
+                o_jy := jy.GetSubScribeInfo(m.Session(), mongodb, "f", "10000")
+                if o_jy != nil && len(*o_jy) > 0 {
+                        s_surprise = util.ObjToString((*o_jy)["s_surprise"])
+                }
+        }
+        m.T["s_surprise"] = s_surprise
+        m.T["surprise"] = surprise
+        m.T["openid"] = se.EncodeString(util.ObjToString(m.GetSession("s_m_openid")))
+        m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
+        mynickname, _ := m.Session().Get("s_nickname").(string)
+        myavatar, _ := m.Session().Get("s_avatar").(string)
+        m.T["nickname"] = mynickname
+        m.T["avatar"] = myavatar
+        //直播活动和预热活动期间
+        if config.ActiveConfig.Live_Active_End > time.Now().Unix() && time.Now().Unix() > config.ActiveConfig.Live_Preheat_Start {
+                m.T["LiveState"] = true
+        }
+        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
-		//接收方式:1微信  2邮箱 3信息+邮箱
-		wxpush, _ := m.GetInteger("wxpush")
-		mailpush, _ := m.GetInteger("mailpush")
-		if wxpush == 0 && mailpush == 0 {
-			wxpush = 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_wxpush"] = wxpush
-		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)
+        positionType := qutil.Int64All(session.Get("positionType"))
+        if userId == "" {
+                m.ServeJson(map[string]interface{}{
+                        "flag": false,
+                })
+                return
+        }
+        types := "o_jy"
+        if positionType == 1 {
+                types = "o_entniche"
+        }
+        //增加锁,防止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}`)
+                o_jy := jy.GetSubScribeInfo(m.Session(), mongodb, "f", "10000")
+                etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                m := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+                if o_jy != nil {
+                        //o_jy, _ = (*data)["o_jy"].(map[string]interface{})
+                        (*o_jy)["i_new"] = NewUserByVIP(o_jy, m.Data.Free.Registedate)
+                        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[fmt.Sprintf("%s.a_key", types)] = keyMaps
+        } else if reqType == "saveArea" { //保存信息范围
+                index = m.GetString("index")
+                saveData[types+"o.a_key."+index+".area"] = m.GetSlice("area")
+        } else if reqType == "saveInfotype" { //保存信息类型
+                index = m.GetString("index")
+                saveData[types+".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[types+".a_key."+index+".notkey"] = notkey
+        } else if reqType == "saveSeniorset" { //保存高级设置
+                //推送频率:1实时 2每日一推 3自定义时间
+                ratemode, _ := m.GetInteger("ratemode")
+                if ratemode != 2 && ratemode != 3 {
+                        ratemode = 1
+                }
+                saveData[types+".i_ratemode"] = ratemode
+                //接收方式:1微信  2邮箱 3信息+邮箱
+                wxpush, _ := m.GetInteger("wxpush")
+                mailpush, _ := m.GetInteger("mailpush")
+                if wxpush == 0 && mailpush == 0 {
+                        wxpush = 1
+                }
+                if ratemode == 3 {
+                        saveData[types+".i_rmstart"], _ = m.GetInteger("rmstart")
+                        saveData[types+".i_rmend"], _ = m.GetInteger("rmend")
+                }
+                saveData[types+".s_email"] = strings.Trim(m.GetString("email"), " ")
+                saveData[types+".i_wxpush"] = wxpush
+                saveData[types+"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[types+".a_key"] = keyMaps
+        } else if reqType == "setSurp" {
+                saveData[types+".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 o_jy := jy.GetSubScribeInfo(m.Session(), mongodb, "f", "10000"); o_jy != nil && len(*o_jy) > 0 {
+                        //if rd, ok := mongodb.FindById("user", userId, `{"o_jy":1,"l_registedate":1}`); rd != nil && ok && len(*rd) > 0 {
+                        //获取活动上线时间
+                        o_jy := jy.GetSubScribeInfo(m.Session(), mongodb, "f", "10000")
+                        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                        data := jy.GetBigVipUserBaseMsg("10000", m.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+                        optimalTime, _ := config.Sysconfig["optimalTime"].(string)
+                        optime, _ = time.ParseInLocation(Date_Full_Layout, optimalTime, time.Local)
+                        regtime = data.Data.Free.Registedate
+                        if o_jy != nil && len(*o_jy) > 0 {
+                                if (*o_jy)["i_new"] == nil {
+                                        if time.Unix(regtime, 0).After(optime) {
+                                                saveData[types+".i_new"] = 1
+                                        } else {
+                                                saveData[types+".i_new"] = 0
+                                        }
+                                }
+                                if (*o_jy)["a_key"] != nil {
+                                        ak, _ := (*o_jy)["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[types+".a_key"] = []map[string]interface{}{saveKey}
+                        if time.Unix(regtime, 0).Before(optime) {
+                                saveData[types+".i_new"] = 1
+                        }
+                } else { //修改新增
+                        if indexInt > len(a_key) {
+                                indexInt = len(a_key)
+                        }
+                        saveData[fmt.Sprintf("%s.a_key.%d", types, indexInt)] = saveKey
+                }
+        }
+        //修改操作
+        var flag bool
+        if len(saveData) > 0 {
+                saveData[types+".l_modifydate"] = time.Now().Unix()
+                query := map[string]interface{}{
+                        "i_userid": util.Int64All(a.GetSession("entUserId")),
+                        "i_entid":  util.Int64All(a.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)
+                        }
+
+                } 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)
+                                }
+
+                        }
+                }
+        }
+        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 {
-	defer util.Catch()
-	userid := util.ObjToString(m.GetSession("userId"))
-	myopenid := util.ObjToString(m.GetSession("s_m_openid"))
-	if myopenid == "" || userid == "" {
-		return m.Redirect("/swordfish/share/-1")
-	}
-	m.T["openid"] = se.EncodeString(myopenid)
-	m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
-	mynickname, _ := m.Session().Get("s_nickname").(string)
-	myavatar, _ := m.Session().Get("s_avatar").(string)
-	m.T["nickname"] = mynickname
-	m.T["avatar"] = myavatar
-	return m.Render("/weixin/wxkeyset/seniorset.html")
+        defer util.Catch()
+        userid := util.ObjToString(m.GetSession("userId"))
+        myopenid := util.ObjToString(m.GetSession("s_m_openid"))
+        if myopenid == "" || userid == "" {
+                return m.Redirect("/swordfish/share/-1")
+        }
+        m.T["openid"] = se.EncodeString(myopenid)
+        m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
+        mynickname, _ := m.Session().Get("s_nickname").(string)
+        myavatar, _ := m.Session().Get("s_avatar").(string)
+        m.T["nickname"] = mynickname
+        m.T["avatar"] = myavatar
+        return m.Render("/weixin/wxkeyset/seniorset.html")
 }
 
 //高级设置
 func (m *Front) WxKeysetFilterset() error {
-	defer util.Catch()
-	userid := util.ObjToString(m.GetSession("userId"))
-	myopenid := util.ObjToString(m.GetSession("s_m_openid"))
-	if myopenid == "" || userid == "" {
-		return m.Redirect("/swordfish/share/-1")
-	}
-	m.T["openid"] = se.EncodeString(myopenid)
-	m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
-	mynickname, _ := m.Session().Get("s_nickname").(string)
-	myavatar, _ := m.Session().Get("s_avatar").(string)
-	m.T["nickname"] = mynickname
-	m.T["avatar"] = myavatar
-	return m.Render("/weixin/wxkeyset/filterset.html")
+        defer util.Catch()
+        userid := util.ObjToString(m.GetSession("userId"))
+        myopenid := util.ObjToString(m.GetSession("s_m_openid"))
+        if myopenid == "" || userid == "" {
+                return m.Redirect("/swordfish/share/-1")
+        }
+        m.T["openid"] = se.EncodeString(myopenid)
+        m.T["signature"] = wx.SignJSSDK(m.Site() + m.Url())
+        mynickname, _ := m.Session().Get("s_nickname").(string)
+        myavatar, _ := m.Session().Get("s_avatar").(string)
+        m.T["nickname"] = mynickname
+        m.T["avatar"] = myavatar
+        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
+func NewUserByVIP(ojy *map[string]interface{}, regtime int64) int {
+        /*  if len(*mData) == 0 || mData == nil {
+                    return 1
+            }
+            ojy, _ := (*mData)["o_jy"].(map[string]interface{})*/
+        if len(*ojy) > 0 && ojy != nil {
+                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
 }

+ 616 - 607
src/jfw/modules/app/src/app/front/front.go

@@ -1,84 +1,85 @@
 package front
 
 import (
-	"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"
+
+        . "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"
 )
 
 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 //微信的加密方法
@@ -89,417 +90,427 @@ 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, 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 保存报错")
+        }
 }
 
 func (m *Front) Wxerr() error {
-	return m.Render("/_err.html")
+        return m.Render("/_err.html")
 }
-func isInTSguide(userid string) bool {
-	if userid == "" {
-		return false
-	}
-	data, ok := mongodb.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1,"s_phone":1,"s_m_phone":1}`)
-	if ok {
-		/*phone := ""
-		  if s_phone, _ := (*data)["s_phone"].(string); s_phone != "" {
-		  	phone = s_phone
-		  } else if s_m_phone, _ := (*data)["s_m_phone"].(string); s_m_phone != "" {
-		  	phone = s_m_phone
-		  }
-		  isEnt := false
-		  if phone != "" {
-		  	//已购买企业未过期
-		  	if entInfo := public.Mysql.SelectBySql(`SELECT status 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) {
-		  			if util.IntAll(v["status"]) == 1 {
-		  				isEnt = true
-		  				break
-		  			}
-		  		}
-		  	}
-		  }*/
-		//付费用户无免费订阅,不进入订阅向导页面
-		if util.IntAll((*data)["i_member_status"]) > 0 || util.IntAll((*data)["i_vip_status"]) > 0 {
-			return false
-		}
-		o_jy, _ := (*data)["o_jy"].(map[string]interface{})
-		i_ts_guide := util.IntAll((*data)["i_ts_guide"])
-		if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
-			return true
-		}
-	}
-	return false
+func isInTSguide(userid string, session *httpsession.Session) bool {
+        if userid == "" {
+                return false
+        }
+        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+        //data, ok := mongodb.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1,"s_phone":1,"s_m_phone":1}`)
+        data := jy.GetBigVipUserBaseMsg("10000", session, util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+        //付费用户无免费订阅,不进入订阅向导页面
+        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"))
-	if f.Method() == "GET" {
-		if !isInTSguide(userid) {
-			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{
-					"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 if reqType == "over" {
-			saveData := bson.M{
-				"i_ts_guide": 1,
-			}
-			result["flag"] = mongodb.UpdateById("user", 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) {
-			jy.ClearBigVipUserPower(userid)
-		}
-		f.ServeJson(result)
-	}
-	return nil
+        defer util.Catch()
+        userid := util.ObjToString(f.GetSession("userId"))
+        positionType := util.Int64All(f.GetSession("positionType"))
+        if f.Method() == "GET" {
+                if !isInTSguide(userid) {
+                        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
 }
 
 // 查看原文中转
 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,
+                })
+        }
 }
 
 /*
@@ -510,214 +521,212 @@ 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 != "" {
-		user, 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}`)
-		if ok && user != nil {
-			uid := ""
-			s_phone, _ := (*user)["s_phone"].(string)
-			if s_phone != "" {
-				s_phone = s_phone
-			} else if s_m_phone, _ := (*user)["s_m_phone"].(string); s_m_phone != "" {
-				s_phone = s_m_phone
-			}
-			isNew := false
-			res := public.Mysql.SelectBySql(`SELECT isNew,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=? `, s_phone)
-			if res != nil && len(*res) > 0 {
-				//entname := qutil.ObjToString((*res)[0]["name"])
-				/*d["entname"] = entname*/
-				//已购买企业未过期-商机管理用户
-				for _, v := range *res {
-					if util.IntAll(v["status"]) == 1 && util.IntAll(v["power"]) == 1 {
-						if util.IntAll(v["isNew"]) == 1 {
-							isNew = true
-						}
-						break
-					}
-				}
-			}
-			if jy.SwitchService.IsMember(s.Session(), mongodb, public.Mysql) {
-				subscribe = util.IntAll((*user)["i_member_apppushunread"])
-			} else if isNew {
-				subscribe = 0
-			} else {
-				subscribe = util.IntAll((*user)["i_apppushunread"])
-			}
-			memberStatus := util.IntAll((*user)["i_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
-			}
-			etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
-			powerMap := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"])).PowerMap
-			//powerMap := jy.GetBigVipUserBaseMsg(userid, public.Mysql, public.MQFW).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 != "" {
+                //user, 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}`)
+                etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                user := jy.GetBigVipUserBaseMsg("10000", s.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+                uid := ""
+
+                isNew := user.Data.Entniche.IsNew > 0
+                /* res := public.Mysql.SelectBySql(`SELECT isNew,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=? `, s_phone)
+                                   if res != nil && len(*res) > 0 {
+                                           //entname := qutil.ObjToString((*res)[0]["name"])
+                                           //已购买企业未过期-商机管理用户
+                                           for _, v := range *res {
+                                                   if util.IntAll(v["status"]) == 1 && util.IntAll(v["power"]) == 1 {
+                                                           if util.IntAll(v["isNew"]) == 1 {
+                                                                   isNew = true
+                                                           }
+                                                           break
+                                                   }
+                                           }
+                                   }*/
+                if jy.SwitchService.IsMember(s.Session(), mongodb, public.Mysql) {
+                        subscribe = util.IntAll((*user)["i_member_apppushunread"])
+                } else if isNew {
+                        subscribe = 0
+                } else {
+                        subscribe = util.IntAll((*user)["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
+                //powerMap := jy.GetBigVipUserBaseMsg(userid, public.Mysql, public.MQFW).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))
 }

+ 402 - 397
src/jfw/modules/app/src/app/front/me.go

@@ -1,282 +1,282 @@
 package front
 
 import (
-	"fmt"
-	. "jy/src/jfw/modules/app/src/app/jyutil"
-	"jy/src/jfw/modules/app/src/jfw/config"
-	"log"
-	"strings"
-	"time"
+        "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"
+        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("userId"))
-	//检测用户是否绑定邮箱
-	if userid != "" {
-		res, err := mongodb.FindById("user", userid, nil)
-		if len(*res) > 0 && err {
-			if qutil.ObjToString((*res)["s_myemail"]) == "" {
-				m.T["isNoEmail"] = true
-			}
-			if qutil.Int64All((*res)["i_vip_status"]) == 1 || qutil.Int64All((*res)["i_vip_status"]) == 2 {
-				m.T["isVip"] = true
-			}
-			m.T["member_status"] = qutil.If((*res)["i_member_status"] != nil, qutil.Int64All((*res)["i_member_status"]), 0)
-			power := []int{} //GetNewPower(userid)
-			etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
-			powerMap := jy.GetBigVipUserBaseMsg("10000", m.Session(), qutil.InterfaceToStr(etcdMap["hosts"]), qutil.InterfaceToStr(etcdMap["key"])).PowerMap
-			for k := range powerMap {
-				power = append(power, k)
-			}
-			m.T["power"] = power
-		} else {
-			return m.Redirect("/jyapp/free/login?back=index&flag=quit")
-		}
-	} 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("userId"))
+        //检测用户是否绑定邮箱
+        if userid != "" {
+                res, err := mongodb.FindById("user", userid, nil)
+                if len(*res) > 0 && err {
+                        if qutil.ObjToString((*res)["s_myemail"]) == "" {
+                                m.T["isNoEmail"] = true
+                        }
+                        if qutil.Int64All((*res)["i_vip_status"]) == 1 || qutil.Int64All((*res)["i_vip_status"]) == 2 {
+                                m.T["isVip"] = true
+                        }
+                        m.T["member_status"] = qutil.If((*res)["i_member_status"] != nil, qutil.Int64All((*res)["i_member_status"]), 0)
+                        power := []int{} //GetNewPower(userid)
+                        etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                        powerMap := jy.GetBigVipUserBaseMsg("10000", m.Session(), qutil.InterfaceToStr(etcdMap["hosts"]), qutil.InterfaceToStr(etcdMap["key"])).PowerMap
+                        for k := range powerMap {
+                                power = append(power, k)
+                        }
+                        m.T["power"] = power
+                } else {
+                        return m.Redirect("/jyapp/free/login?back=index&flag=quit")
+                }
+        } 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("userId"))
-	hasPwd := false
-	isVip := false
-	if userid != "" {
-		user, ok := mongodb.FindById("user", userid, `{"s_password":1,"i_vip_status":1}`)
-		if ok && user != nil {
-			if qutil.ObjToString((*user)["s_password"]) != "" {
-				hasPwd = true
-			}
-			if qutil.Int64All((*user)["i_vip_status"]) == 1 || qutil.Int64All((*user)["i_vip_status"]) == 2 {
-				isVip = true
-			}
-		}
+        userid := qutil.ObjToString(m.GetSession("userId"))
+        hasPwd := false
+        isVip := false
+        if userid != "" {
+                user, ok := mongodb.FindById("user", userid, `{"s_password":1,"i_vip_status":1}`)
+                if ok && user != nil {
+                        if qutil.ObjToString((*user)["s_password"]) != "" {
+                                hasPwd = true
+                        }
+                        if qutil.Int64All((*user)["i_vip_status"]) == 1 || qutil.Int64All((*user)["i_vip_status"]) == 2 {
+                                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("userId"))
-		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("userId"))
+                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
 }
 
 //
 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("userId").(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("userId").(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
 }
 
 /*
@@ -299,188 +299,193 @@ 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)
-	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}`)
-	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)
+        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 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 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
+                                        }
+
+                                }
+                        }
+                }
+                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("userId").(string)
-	info := map[string]interface{}{}
+        userid := l.GetSession("userId").(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, _ := 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
 }
 
 //
 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)
+                        }
+                }
+        }
 }

+ 509 - 479
src/jfw/modules/app/src/app/front/swordfish.go

@@ -1,351 +1,381 @@
 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"
+        . "app.yhyue.com/moapp/jybase/date"
 
-	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"
+        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, _ := (*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 {
-					if 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()},
-						}) {
-						flag = "y"
-					}
-				}
-			} else {
-				if mongodb.UpdateById("user", userid,
-					bson.M{
-						"$set": bson.M{"i_ts_guide": 1},
-					}) {
-					flag = "y"
-				}
-			}
-		}
-		break
-	}
-	m.ServeJson(map[string]interface{}{
-		"flag": flag,
-	})
-	return nil
+        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 {
+
+                                        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
 }
 
 // 获取我的反馈列表
 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)
-		if isPayedUser {
-			buyerclass = m.GetString("buyerclass")
-			hasBuyerTel, hasWinnerTel = m.GetString("buyertel"), m.GetString("winnertel")
-			notkey = m.GetString("notkey")
-			city = m.GetString("city")
-		}
-		//校验是否有大会员中标企业查询权限
-		etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
-		bigBaseMsg := jy.GetBigVipUserBaseMsg("10000", m.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
-		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)
+                if isPayedUser {
+                        buyerclass = m.GetString("buyerclass")
+                        hasBuyerTel, hasWinnerTel = m.GetString("buyertel"), m.GetString("winnertel")
+                        notkey = m.GetString("notkey")
+                        city = m.GetString("city")
+                }
+                //校验是否有大会员中标企业查询权限
+                etcdMap := config.Sysconfig["etcd"].(map[string]interface{})
+                bigBaseMsg := jy.GetBigVipUserBaseMsg("10000", m.Session(), util.InterfaceToStr(etcdMap["hosts"]), util.InterfaceToStr(etcdMap["key"]))
+                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() {
@@ -439,126 +469,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, 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)
 }
 
 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
 }
 
 /*
@@ -576,80 +606,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
 }

+ 4 - 6
src/jfw/modules/app/src/app/front/wxkeyset.go

@@ -34,13 +34,11 @@ func (m *Front) WxKeyset(tpl string) error {
 		return m.Redirect("/jyapp/vipsubscribe/toSubVipSetPage")
 	}
 	if tpl == "seniorset" {
-		data, ok := mongodb.FindById("user", userid, `{"o_jy":1}`)
-		if ok && 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 {
+		/*data, ok := mongodb.FindById("user", userid, `{"o_jy":1}`)*/
+vipMsg
+
 				m.T["haskeyword"] = true
-			}
+
 		}
 	}
 	userId, _ := m.GetSession("userId").(string)

+ 25 - 14
src/jfw/modules/app/src/go.mod

@@ -3,21 +3,25 @@ module jy/src/jfw/modules/app/src
 go 1.18
 
 require (
-	app.yhyue.com/moapp/jybase v0.0.0-20221230025810-b88f2a62c467
-	app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg d8ae3867d2abebd3d05c9e473df5372fbf4ac21c
+	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/dchest/captcha v1.0.0
+	github.com/gogf/gf/v2 v2.0.6
 	github.com/pkg/errors v0.9.1
 	go.mongodb.org/mongo-driver v1.11.1
 )
 
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
-	app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c // indirect
-	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 // indirect
+	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter a6b26e74a68ce961a9df05650224d0d8dbcb67af
+	github.com/BurntSushi/toml v0.4.1 // 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
@@ -40,19 +44,24 @@ require (
 	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/longbridgeapp/sqlparser v0.3.1 // 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/nsqio/go-nsq v1.1.0 // 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
@@ -60,6 +69,7 @@ require (
 	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/robfig/cron v1.2.0 // indirect
 	github.com/spaolacci/murmur3 v1.1.0 // indirect
 	github.com/tealeg/xlsx v1.0.5 // indirect
@@ -68,19 +78,20 @@ require (
 	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.3 // 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
-	go.opentelemetry.io/otel v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/jaeger v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/zipkin v1.10.0 // indirect
-	go.opentelemetry.io/otel/sdk v1.10.0 // indirect
-	go.opentelemetry.io/otel/trace v1.10.0 // 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
@@ -90,7 +101,7 @@ require (
 	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-20220728004956-3c1f35247d10 // 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

+ 33 - 22
src/jfw/modules/app/src/go.sum

@@ -2,14 +2,14 @@ app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d h1:WPsYuuptAd3UEgN+j
 app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d/go.mod h1:91/lSD/hS+ckMVP3WdidRzDhC60lLMdyce9QHy0cSMA=
 app.yhyue.com/moapp/jyPoints v1.1.1/go.mod h1:SvP8p5L3jGrejHiH2LXfgCg/NPlFiKBC5Yd0gsI12FU=
 app.yhyue.com/moapp/jybase v0.0.0-20220427020729-974c1a148186/go.mod h1:qNRA0sHuYqcLoYoP8irpaWnW9YsXixe6obBIkwaXpD0=
-app.yhyue.com/moapp/jybase v0.0.0-20221230025810-b88f2a62c467 h1:MTZBSIzrqrwieb1gLhls3Wjz0Q2u75n+O2jfPw40iEA=
-app.yhyue.com/moapp/jybase v0.0.0-20221230025810-b88f2a62c467/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf h1:NMVZDXa4yZtL2BTM8gJLpRU4fSN9a1cj7mTVYa1RUZY=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf/go.mod h1:7D6zNxrg+Tma3VC43TLu7XPczubl4uJavua89kaFS1Q=
-app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c h1:CrcvbsXZ4aQkNikBi7FUUQZNnY8hKsNo2LLe/SqeXs8=
-app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 h1:Xv1D9avDKeaM5kQTisF/pIt8y7B7yQ/hAxuWEg75LMs=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
+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-20230128092104-d8ae3867d2ab h1:a9XvegdF3aM0y9v5SHtX03LIGMS3+8J1ofoNeyw5J0Y=
+app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab/go.mod h1:MqJfBFTSfZhrNDEnE4e19BmaLkaMr+lYActLXm6lrpw=
+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/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c h1:g49jOlhZlBCJ3IgJA0rotfNf2Gh22pISffUtqxB8XtY=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
 cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw=
@@ -409,8 +409,8 @@ github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZp
 github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
 github.com/alicebob/miniredis/v2 v2.14.1/go.mod h1:uS970Sw5Gs9/iK3yBg0l9Uj9s25wXxSpQUE9EaJ/Blg=
 github.com/alicebob/miniredis/v2 v2.22.0/go.mod h1:XNqvJdQJv5mSuVMc0ynneafpnL/zv52acZ6kqeS0t88=
-github.com/alicebob/miniredis/v2 v2.23.1 h1:jR6wZggBxwWygeXcdNyguCOCIjPsZyNUNlAkTx2fu0U=
-github.com/alicebob/miniredis/v2 v2.23.1/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
+github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
+github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
 github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=
 github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
 github.com/antlr/antlr4 v0.0.0-20210105212045-464bcbc32de2/go.mod h1:T7PbCXFs94rrTttyxjbyT5+/1V8T2TYDejxUfHJjw1Y=
@@ -750,7 +750,7 @@ github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+
 github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ=
 github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E=
 github.com/jhump/protoreflect v1.12.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
-github.com/jhump/protoreflect v1.14.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
+github.com/jhump/protoreflect v1.14.1/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
 github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
 github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
@@ -1033,8 +1033,8 @@ github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64 h1:5mLPGnFdSsevFRF
 github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
 github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
 github.com/zeromicro/go-zero v1.3.5/go.mod h1:wh4o794b7Ul3W0k35Pw9nc3iB4O0OpaQTMQz/PJc1bc=
-github.com/zeromicro/go-zero v1.4.3 h1:sTQ++6fxQHJnpGCN7h2CUrhWmbvhBqEgE75cJl635SM=
-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=
@@ -1065,31 +1065,41 @@ go.opentelemetry.io/otel v1.0.0/go.mod h1:AjRVh9A5/5DE7S+mZtTR6t8vpKKryam+0lREnf
 go.opentelemetry.io/otel v1.3.0/go.mod h1:PWIKzi6JCp7sM0k9yZ43VX+T345uNbAkDKwHVjb2PTs=
 go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk=
 go.opentelemetry.io/otel v1.8.0/go.mod h1:2pkj+iMj0o03Y+cW6/m8Y4WkRdYN3AvCXCnzRMp9yvM=
-go.opentelemetry.io/otel v1.10.0 h1:Y7DTJMR6zs1xkS/upamJYk0SxxN4C9AqRd77jmZnyY4=
 go.opentelemetry.io/otel v1.10.0/go.mod h1:NbvWjCthWHKBEUMpf0/v8ZRZlni86PpGFEMA9pnQSnQ=
+go.opentelemetry.io/otel v1.11.0 h1:kfToEGMDq6TrVrJ9Vht84Y8y9enykSZzDDZglV0kIEk=
+go.opentelemetry.io/otel v1.11.0/go.mod h1:H2KtuEphyMvlhZ+F7tg9GRhAOe60moNx61Ex+WmiKkk=
 go.opentelemetry.io/otel/exporters/jaeger v1.8.0/go.mod h1:GbWg+ng88rDtx+id26C34QLqw2erqJeAjsCx9AFeHfE=
-go.opentelemetry.io/otel/exporters/jaeger v1.10.0 h1:7W3aVVjEYayu/GOqOVF4mbTvnCuxF1wWu3eRxFGQXvw=
 go.opentelemetry.io/otel/exporters/jaeger v1.10.0/go.mod h1:n9IGyx0fgyXXZ/i0foLHNxtET9CzXHzZeKCucvRBFgA=
-go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0 h1:TaB+1rQhddO1sF71MpZOZAuSPW1klK2M8XxfrBMfK7Y=
+go.opentelemetry.io/otel/exporters/jaeger v1.11.0 h1:Sv2valcFfMlfu6g8USSS+ZUN5vwbuGj1aY/CFtMG33w=
+go.opentelemetry.io/otel/exporters/jaeger v1.11.0/go.mod h1:nRgyJbgJ0hmaUdHwyDpTTfBYz61cTTeeGhVzfQc+FsI=
 go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0/go.mod h1:78XhIg8Ht9vR4tbLNUhXsiOnE2HOuSeKAiAcoVQEpOY=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0 h1:pDDYmo0QadUPal5fwXoY1pmMpFcdyhXOmL5drCrI3vU=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0 h1:0dly5et1i/6Th3WHn0M6kYiJfFNzhhxanrJ0bOfnjEo=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0/go.mod h1:+Lq4/WkdCkjbGcBMVHHg2apTbv8oMBf29QCnyCCJjNQ=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0/go.mod h1:Krqnjl22jUJ0HgMzw5eveuCvFDXY4nSYb4F8t5gdrag=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0 h1:KtiUEhQmj/Pa874bVYKGNVdq8NPKiacPbaRRtgXi+t4=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0 h1:eyJ6njZmH16h9dOKCi7lMswAnGsSOwgTqWzfxqcuNr8=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0/go.mod h1:FnDp7XemjN3oZ3xGunnfOUTVwd2XcvLbtRAuOSU3oc8=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0/go.mod h1:OfUCyyIiDvNXHWpcWgbF+MWvqPZiNa3YDEnivcnYsV0=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0 h1:j2RFV0Qdt38XQ2Jvi4WIsQ56w8T7eSirYbMw19VXRDg=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0/go.mod h1:pILgiTEtrqvZpoiuGdblDgS5dbIaTgDrkIuKfEFkt+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 h1:S8DedULB3gp93Rh+9Z+7NTEv+6Id/KYS7LDyipZ9iCE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0/go.mod h1:5WV40MLWwvWlGP7Xm8g3pMcg0pKOUY609qxJn8y7LmM=
 go.opentelemetry.io/otel/exporters/zipkin v1.8.0/go.mod h1:0uYAyCuGT67MFV9Z/Mmx93wGuugHw0FbxMc74fs3LNo=
-go.opentelemetry.io/otel/exporters/zipkin v1.10.0 h1:HcPAFsFpEBKF+G5NIOA+gBsxifd3Ej+wb+KsdBLa15E=
 go.opentelemetry.io/otel/exporters/zipkin v1.10.0/go.mod h1:HdfvgwcOoCB0+zzrTHycW6btjK0zNpkz2oTGO815SCI=
+go.opentelemetry.io/otel/exporters/zipkin v1.11.0 h1:v/Abo5REOWrCj4zcEIUHFZtXpsCVjrwZj28iyX2rHXE=
+go.opentelemetry.io/otel/exporters/zipkin v1.11.0/go.mod h1:unWnsLCMYfINP8ue0aXVrB/GYHoXNn/lbTnupvLekGQ=
 go.opentelemetry.io/otel/sdk v1.0.0/go.mod h1:PCrDHlSy5x1kjezSdL37PhbFUMjrsLRshJ2zCzeXwbM=
 go.opentelemetry.io/otel/sdk v1.3.0/go.mod h1:rIo4suHNhQwBIPg9axF8V9CA72Wz2mKF1teNrup8yzs=
 go.opentelemetry.io/otel/sdk v1.8.0/go.mod h1:uPSfc+yfDH2StDM/Rm35WE8gXSNdvCg023J6HeGNO0c=
-go.opentelemetry.io/otel/sdk v1.10.0 h1:jZ6K7sVn04kk/3DNUdJ4mqRlGDiXAVuIG+MMENpTNdY=
 go.opentelemetry.io/otel/sdk v1.10.0/go.mod h1:vO06iKzD5baltJz1zarxMCNHFpUlUiOy4s65ECtn6kE=
+go.opentelemetry.io/otel/sdk v1.11.0 h1:ZnKIL9V9Ztaq+ME43IUi/eo22mNsb6a7tGfzaOWB5fo=
+go.opentelemetry.io/otel/sdk v1.11.0/go.mod h1:REusa8RsyKaq0OlyangWXaw97t2VogoO4SSEeKkSTAk=
 go.opentelemetry.io/otel/trace v1.0.0/go.mod h1:PXTWqayeFUlJV1YDNhsJYB184+IvAH814St6o6ajzIs=
 go.opentelemetry.io/otel/trace v1.3.0/go.mod h1:c/VDhno8888bvQYmbYLqe41/Ldmr/KKunbvWM4/fEjk=
 go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU=
 go.opentelemetry.io/otel/trace v1.8.0/go.mod h1:0Bt3PXY8w+3pheS3hQUt+wow8b1ojPaTBoTCh2zIFI4=
-go.opentelemetry.io/otel/trace v1.10.0 h1:npQMbR8o7mum8uF95yFbOEJffhs1sbCOfDh8zAJiH5E=
 go.opentelemetry.io/otel/trace v1.10.0/go.mod h1:Sij3YYczqAdz+EhmGhE6TpTxUO5/F/AzrK+kxfGqySM=
+go.opentelemetry.io/otel/trace v1.11.0 h1:20U/Vj42SX+mASlXLmSGBg6jpI1jQtv682lZtTAOVFI=
+go.opentelemetry.io/otel/trace v1.11.0/go.mod h1:nyYjis9jy0gytE9LXGU+/m1sHTKbRY0fX0hulNNDP1U=
 go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
 go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw=
 go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U=
@@ -1368,8 +1378,9 @@ golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 h1:WIoqL4EROvwiPdUtaip4VcDdpZ4kha7wBWZrbVKCIZg=
 golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 h1:h+EGohizhe9XlX18rfpa8k8RAc5XyaeamM+0VHRd4lc=
+golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=

+ 12 - 11
src/jfw/modules/bigmember/src/entity/analysisEntName.go

@@ -2,15 +2,16 @@
 package entity
 
 import (
-	"jy/src/jfw/modules/bigmember/src/db"
-	"encoding/json"
-	"fmt"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"regexp"
-	"strings"
-	"sync"
-	"jy/src/jfw/modules/bigmember/src/util"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        elastic "app.yhyue.com/moapp/jybase/esv1"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "jy/src/jfw/modules/bigmember/src/util"
+        "regexp"
+        "strings"
+        "sync"
 )
 
 /**即时获取项目名称列表
@@ -224,8 +225,8 @@ type ViewKeyWord struct {
 	MatchWay int      `json:"matchway"`  //匹配模式
 }
 
-func CheckPower(userId string) (string, bool) {
-	main_userId, _, member_status := util.MainUserId(userId, "", 0)
+func CheckPower(session *httpsession.Session) (string, bool) {
+	main_userId, _, member_status := util.MainUserId(session)
 	return main_userId, member_status > 0
 }
 

+ 146 - 142
src/jfw/modules/bigmember/src/entity/portrailUtil.go

@@ -1,216 +1,220 @@
 package entity
 
 import (
-	"jy/src/jfw/modules/bigmember/src/db"
-	"encoding/json"
-	"fmt"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"regexp"
-	"time"
+        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"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "regexp"
+        "time"
 )
 
 var (
-	//画像金额展示分段
-	moneyRange   = []int{0, 1e4, 1e5, 5e5, 1e6, 5e6, 1e7, 5e7, 1e8, 1e9, 1e10}
-	capitalRange = []int{0, 1e4, 5e5, 1e6, 2e6, 5e6, 1e7, 5e7, 1e8, 1e9, 1e10}
-	//画像年份展示分段
-	yearsRange        = []int{0, 1, 2, 5, 10, 15, 20, 30, 40}
-	excludeAddressReg = regexp.MustCompile("[省|市]")
+        //画像金额展示分段
+        moneyRange   = []int{0, 1e4, 1e5, 5e5, 1e6, 5e6, 1e7, 5e7, 1e8, 1e9, 1e10}
+        capitalRange = []int{0, 1e4, 5e5, 1e6, 2e6, 5e6, 1e7, 5e7, 1e8, 1e9, 1e10}
+        //画像年份展示分段
+        yearsRange        = []int{0, 1, 2, 5, 10, 15, 20, 30, 40}
+        excludeAddressReg = regexp.MustCompile("[省|市]")
 )
 
 const (
-	//折扣率查询语句
-	YearRate = `{"filter":{"bool":{"must":{"range":{"project_rate":{"gte":0,"lte":0.6}}}}},"aggs":{"yearRate":{"range":{"field":"firsttime","ranges":[%s]},"aggs":{"bidamount_count":{"sum":{"field":"bidamount"}},"budget_count":{"sum":{"field":"budget"}}}}}}`
-	BaseRate = `{"filter":{"bool":{"must":{"range":{"project_rate":{"gte":0,"lte":0.6}}}}},"aggs":{"bidamount_count":{"sum":{"field":"bidamount"}},"budget_count":{"sum":{"field":"budget"}}}}`
+        //折扣率查询语句
+        YearRate = `{"filter":{"bool":{"must":{"range":{"project_rate":{"gte":0,"lte":0.6}}}}},"aggs":{"yearRate":{"range":{"field":"firsttime","ranges":[%s]},"aggs":{"bidamount_count":{"sum":{"field":"bidamount"}},"budget_count":{"sum":{"field":"budget"}}}}}}`
+        BaseRate = `{"filter":{"bool":{"must":{"range":{"project_rate":{"gte":0,"lte":0.6}}}}},"aggs":{"bidamount_count":{"sum":{"field":"bidamount"}},"budget_count":{"sum":{"field":"budget"}}}}`
 )
 
 //redis存储月份键值
 func getPortraitRedisCatchKey(sType, name string) string {
-	timeFlag := time.Now()
-	timeStr := timeFlag.Format("20060102")
-	return fmt.Sprintf("portrait_%s_%s_%s", timeStr, name, sType)
+        timeFlag := time.Now()
+        timeStr := timeFlag.Format("20060102")
+        return fmt.Sprintf("portrait_%s_%s_%s", timeStr, name, sType)
 }
 
 type AggsValue struct {
-	Value float64 `json:"value"`
+        Value float64 `json:"value"`
 }
 
 //topShow
 type TopShowItem struct {
-	EntId        string  `json:"entId"`
-	WinnerName   string  `json:"winnerName"`
-	LastTime     int64   `json:"lastTime"`
-	CountProject int     `json:"countProject"`
-	CountMoney   float64 `json:"countMoney"` //用于展示中标总金额
+        EntId        string  `json:"entId"`
+        WinnerName   string  `json:"winnerName"`
+        LastTime     int64   `json:"lastTime"`
+        CountProject int     `json:"countProject"`
+        CountMoney   float64 `json:"countMoney"` //用于展示中标总金额
 }
 type TopShow struct {
-	ClassName string        `json:"class"`
-	TopData   []TopShowItem `json:"topData"`
+        ClassName string        `json:"class"`
+        TopData   []TopShowItem `json:"topData"`
 }
 
 //中标金额聚合结果
 type YearBidamount struct {
-	Buckets []struct {
-		DateStr string    `json:"key"`
-		AllNum  int       `json:"doc_count"`
-		Count   AggsValue `json:"count"`
-	} `json:"buckets"`
+        Buckets []struct {
+                DateStr string    `json:"key"`
+                AllNum  int       `json:"doc_count"`
+                Count   AggsValue `json:"count"`
+        } `json:"buckets"`
 }
 
 //折扣率
 type PortraitRate struct {
-	DocCount       int       `json:"doc_count"`
-	BudgetCount    AggsValue `json:"budget_count"`
-	BidamountCount AggsValue `json:"bidamount_count"`
+        DocCount       int       `json:"doc_count"`
+        BudgetCount    AggsValue `json:"budget_count"`
+        BidamountCount AggsValue `json:"bidamount_count"`
 }
 
 //分段折扣率
 type RangePortraitRate struct {
-	*PortraitRate
-	Key string `json:"key"`
+        *PortraitRate
+        Key string `json:"key"`
 }
 
 //计算折扣率
 func CalculationRate(buyget, bidamount float64) interface{} {
-	if buyget > 0 {
-		return (buyget - bidamount) / buyget
-	}
-	return nil
+        if buyget > 0 {
+                return (buyget - bidamount) / buyget
+        }
+        return nil
 }
 
 //计算占比
 func CalculationShare(one, all float64) float64 {
-	if all > 0 {
-		return one / all
-	}
-	return 0.0
+        if all > 0 {
+                return one / all
+        }
+        return 0.0
 }
 
 type SimpleStringKeyValue struct {
-	Key string `json:"key"`
+        Key string `json:"key"`
 }
 
 //获取中标金额聚合查询语句(近三年统计月份,5-3年统计年份)
 func getBidamountStatistics(sTime, eTime time.Time) string {
-	timeRange := ``
-	tmpTime, rTime, tEndTime := sTime, sTime, getMonthRange(eTime, false)
-	for rTime.Before(tEndTime) {
-		ts, te := getMonthRange(tmpTime, true), getMonthRange(tmpTime, false)
-		if sTime == tmpTime {
-			ts = sTime
-		}
-		if te == tEndTime {
-			te = eTime
-		}
-		if ts.Before(te) {
-			timeRange += fmt.Sprintf(`{"key":"%s","from":%d,"to":%d},`, fmt.Sprintf("%d-%d", ts.Year(), ts.Month()), ts.Unix(), te.Unix())
-		}
-		rTime = rTime.AddDate(0, 1, 0)
-		if int(rTime.Month())-int(tmpTime.Month()) > 1 { //防止01-30 加一月 返回 03-01
-			rTime = rTime.AddDate(0, -1, 0)
-		}
-		tmpTime = rTime
-	}
-	if timeRange == `` {
-		return ""
-	}
-	return timeRange[:len(timeRange)-1]
+        timeRange := ``
+        tmpTime, rTime, tEndTime := sTime, sTime, getMonthRange(eTime, false)
+        for rTime.Before(tEndTime) {
+                ts, te := getMonthRange(tmpTime, true), getMonthRange(tmpTime, false)
+                if sTime == tmpTime {
+                        ts = sTime
+                }
+                if te == tEndTime {
+                        te = eTime
+                }
+                if ts.Before(te) {
+                        timeRange += fmt.Sprintf(`{"key":"%s","from":%d,"to":%d},`, fmt.Sprintf("%d-%d", ts.Year(), ts.Month()), ts.Unix(), te.Unix())
+                }
+                rTime = rTime.AddDate(0, 1, 0)
+                if int(rTime.Month())-int(tmpTime.Month()) > 1 { //防止01-30 加一月 返回 03-01
+                        rTime = rTime.AddDate(0, -1, 0)
+                }
+                tmpTime = rTime
+        }
+        if timeRange == `` {
+                return ""
+        }
+        return timeRange[:len(timeRange)-1]
 }
 
 //getMonthRange获取月份范围
 //isStart true本月月初  false 本月月末(下月月初)
 func getMonthRange(t time.Time, isStart bool) time.Time {
-	if isStart {
-		return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
-	}
-	return time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, t.Location())
+        if isStart {
+                return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
+        }
+        return time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, t.Location())
 }
 
 //getYearRange获取月份范围
 //isStart true本月月初  false 本月月末(下月月初)
 func getYearRange(t time.Time, isStart bool) time.Time {
-	if isStart {
-		return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
-	}
-	return time.Date(t.Year()+1, 1, 1, 0, 0, 0, 0, t.Location())
+        if isStart {
+                return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
+        }
+        return time.Date(t.Year()+1, 1, 1, 0, 0, 0, 0, t.Location())
 }
 
 //年份统计
 func getCommonYearStatistics(sTime, eTime time.Time) string {
-	timeRange := ``
-	tmpTime, rTime, tEndTime := sTime, sTime, getYearRange(eTime, false)
-	for rTime.Before(tEndTime) {
-		ts, te := getYearRange(tmpTime, true), getYearRange(tmpTime, false)
-		if sTime == tmpTime {
-			ts = sTime
-		}
-		if te == tEndTime {
-			te = eTime
-		}
-		if ts.Before(te) {
-			timeRange += fmt.Sprintf(`{"key":"%d","from":%d,"to":%d},`, ts.Year(), ts.Unix(), te.Unix())
-		}
-		rTime = rTime.AddDate(1, 0, 0)
-		tmpTime = rTime
-	}
-	if timeRange == `` {
-		return ""
-	}
-	return timeRange[:len(timeRange)-1]
+        timeRange := ``
+        tmpTime, rTime, tEndTime := sTime, sTime, getYearRange(eTime, false)
+        for rTime.Before(tEndTime) {
+                ts, te := getYearRange(tmpTime, true), getYearRange(tmpTime, false)
+                if sTime == tmpTime {
+                        ts = sTime
+                }
+                if te == tEndTime {
+                        te = eTime
+                }
+                if ts.Before(te) {
+                        timeRange += fmt.Sprintf(`{"key":"%d","from":%d,"to":%d},`, ts.Year(), ts.Unix(), te.Unix())
+                }
+                rTime = rTime.AddDate(1, 0, 0)
+                tmpTime = rTime
+        }
+        if timeRange == `` {
+                return ""
+        }
+        return timeRange[:len(timeRange)-1]
 }
 
 //采购规模分布
 func getMoneyRange() string {
-	moneyRangeSql := ``
-	tmpValue, maxRange := 0, moneyRange[len(moneyRange)-1]
-	for _, thisMax := range moneyRange {
-		if thisMax == 0 {
-			continue
-		}
-		sLen := (thisMax - tmpValue) / 10
-		if thisMax == maxRange {
-			sLen = (thisMax - tmpValue) / 9
-		}
-		for thisMin := tmpValue; thisMin < thisMax; {
-			tmpValue = thisMin + sLen
-			moneyRangeSql += fmt.Sprintf(`{"key":"%d-%d","from":%d,"to":%d},`, thisMin, tmpValue, thisMin, tmpValue)
-			thisMin = tmpValue
-		}
-	}
-	//大于100亿
-	moneyRangeSql += fmt.Sprintf(`{"key":"%d","from":%d}`, maxRange, maxRange)
-	return moneyRangeSql
+        moneyRangeSql := ``
+        tmpValue, maxRange := 0, moneyRange[len(moneyRange)-1]
+        for _, thisMax := range moneyRange {
+                if thisMax == 0 {
+                        continue
+                }
+                sLen := (thisMax - tmpValue) / 10
+                if thisMax == maxRange {
+                        sLen = (thisMax - tmpValue) / 9
+                }
+                for thisMin := tmpValue; thisMin < thisMax; {
+                        tmpValue = thisMin + sLen
+                        moneyRangeSql += fmt.Sprintf(`{"key":"%d-%d","from":%d,"to":%d},`, thisMin, tmpValue, thisMin, tmpValue)
+                        thisMin = tmpValue
+                }
+        }
+        //大于100亿
+        moneyRangeSql += fmt.Sprintf(`{"key":"%d","from":%d}`, maxRange, maxRange)
+        return moneyRangeSql
 }
 
 func InterfaceToStruct(src, to interface{}) error {
-	bytes, err := json.Marshal(src)
-	if err != nil {
-		return err
-	}
-	err = json.Unmarshal(bytes, to)
-	if err != nil {
-		return err
-	}
-	return nil
+        bytes, err := json.Marshal(src)
+        if err != nil {
+                return err
+        }
+        err = json.Unmarshal(bytes, to)
+        if err != nil {
+                return err
+        }
+        return nil
 }
 
 //获取用户行业
-func getUserSetIndustry(userId string) []string {
-	uData, _ := db.Mgo.FindById("user", userId, `{"o_member_jy":1}`)
-	if uData == nil || len(*uData) == 0 {
-		return nil
-	}
-	memberSet := qutil.ObjToMap((*uData)["o_member_jy"])
-	if len(*memberSet) == 0 {
-		return nil
-	}
-	industrySet := qutil.ObjToMap((*memberSet)["o_industry"])
-	if len(*industrySet) == 0 {
-		return nil
-	}
-	returnIndustryArr := []string{}
-	for k, _ := range *industrySet {
-		returnIndustryArr = append(returnIndustryArr, k)
-	}
-	return returnIndustryArr
+func getUserSetIndustry(session *httpsession.Session) []string {
+        /*uData, _ := db.Mgo.FindById(C_User, userId, `{"o_member_jy":1}`)
+        if uData == nil || len(*uData) == 0 {
+        	return nil
+        }
+        memberSet := qutil.ObjToMap((*uData)["o_member_jy"])
+        */
+        memberSet := jy.GetSubScribeInfo(session, db.Mgo, "m", "10000")
+        if len(*memberSet) == 0 {
+                return nil
+        }
+        industrySet := qutil.ObjToMap((*memberSet)["o_industry"])
+        if len(*industrySet) == 0 {
+                return nil
+        }
+        returnIndustryArr := []string{}
+        for k, _ := range *industrySet {
+                returnIndustryArr = append(returnIndustryArr, k)
+        }
+        return returnIndustryArr
 }

+ 15 - 14
src/jfw/modules/bigmember/src/entity/portrait.go

@@ -18,6 +18,7 @@ import (
 
 type Portrait struct {
 	UserId string //用户id
+	Session *httpsession.Session
 }
 
 const (
@@ -40,11 +41,11 @@ func CreatePortraitManager(session *httpsession.Session, pageFlag string) (*Port
 			free = true
 		}
 		if bigMsg.Status <= 0 || !bigMsg.CheckBigVipBackPower(pageFlag) {
-			return &Portrait{userid}, false, nil, free
+			return &Portrait{userid,session}, false, nil, free
 		}
 	}
 	uid := qutil.If(bigMsg.Pid == "", userid, bigMsg.Pid).(string) //若为子账号则显示主账号行业信息
-	return &Portrait{uid}, true, nil, false
+	return &Portrait{uid,session}, true, nil, false
 }
 
 /*
@@ -76,13 +77,13 @@ func CreatePortraitManagerForContacts(session *httpsession.Session, entType int6
 	case 0:
 		//大会员用户
 		if bigMsg.Status > 0 {
-			return &Portrait{userid}, nil
+			return &Portrait{userid,session}, nil
 		}
 		//新版超级订阅
 		if bigMsg.VipStatus > 0 && bigMsg.Vip_BuySet.Upgrade > 0 {
 			err := bigMsg.NewSubVipPortrait(db.Mysql, entName, false).SubVipPortraitTimesCheck()
 			if err == nil {
-				return &Portrait{userid}, nil
+				return &Portrait{userid,session}, nil
 			}
 			log.Printf("用户%s 超级订阅使用画像%s次数异常 %v\n", userid, entName, err)
 		}
@@ -91,7 +92,7 @@ func CreatePortraitManagerForContacts(session *httpsession.Session, entType int6
 			//次数判断
 			err := EntnichePortraitTimesCheck(db.Mysql, entName, userid)
 			if err == nil {
-				return &Portrait{userid}, nil
+				return &Portrait{userid,session}, nil
 			}
 			log.Printf("用户%s 新版商机管理使用画像%s次数异常 %v\n", userid, entName, err)
 		}
@@ -99,17 +100,17 @@ func CreatePortraitManagerForContacts(session *httpsession.Session, entType int6
 		if bigMsg.VipStatus <= 0 {
 			//其他(免费、老版商机管理)(老版超级订阅 --> 提示用户升级到新版超级订阅)
 			if jy.Portraitexperience(userid, entName, false) {
-				return &Portrait{userid}, nil
+				return &Portrait{userid,session}, nil
 			}
 		}
-		return &Portrait{userid}, errors.New("暂无权限")
+		return &Portrait{userid,session}, errors.New("暂无权限")
 	case 1:
 		if bigMsg.Status <= 0 {
-			return &Portrait{userid}, errors.New("暂无权限")
+			return &Portrait{userid,session}, errors.New("暂无权限")
 		}
 	}
 	uid := qutil.If(bigMsg.Pid == "", userid, bigMsg.Pid).(string) //若为子账号则显示主账号行业信息
-	return &Portrait{uid}, nil
+	return &Portrait{uid,session}, nil
 }
 
 //CreateSubVipPortraitManager 超级订阅权限校验
@@ -126,9 +127,9 @@ func CreateSubVipPortraitManager(userid string, pageFlag, searchValue string, is
 
 		if bigMsg.VipStatus <= 0 || bigMsg.Vip_BuySet.Upgrade != 1 { //免费用户留资体验
 			if searchValue != "" && jy.Portraitexperience(userid, searchValue, isWinner) {
-				return &Portrait{userid}, 3, nil, true
+				return &Portrait{userid,session}, 3, nil, true
 			}
-			return &Portrait{userid}, -1, nil, true
+			return &Portrait{userid,session}, -1, nil, true
 		} else { //超级订阅升级版-校验超级订阅画像浏览次数
 			//免费用户判断
 			free := false
@@ -137,7 +138,7 @@ func CreateSubVipPortraitManager(userid string, pageFlag, searchValue string, is
 			}
 			err := bigMsg.NewSubVipPortrait(db.Mysql, searchValue, isWinner).SubVipPortraitTimesCheck()
 			if err == nil {
-				return &Portrait{userid}, 2, nil, free
+				return &Portrait{userid,session}, 2, nil, free
 			} else {
 				log.Printf("用户%s 超级订阅使用画像%s次数异常 %v\n", userid, searchValue, err)
 			}
@@ -145,7 +146,7 @@ func CreateSubVipPortraitManager(userid string, pageFlag, searchValue string, is
 
 	}
 
-	return &Portrait{userid}, 1, nil, true
+	return &Portrait{userid,session}, 1, nil, true
 }
 
 // GetEntInfo 获取企业基本信息
@@ -395,7 +396,7 @@ func (this *Portrait) BuyerPortraitData(screen *PortraitScreen, flag string) (ma
 	if buyerPortraitData != nil { //只有查询全部或者查询b分布画像时,返回内容有重点合作企业
 		//重点合作企业 展示读者行业
 		if topShow, ok := buyerPortraitData["topShow"]; ok {
-			buyerPortraitData["topShow"] = formatUserTopShowList(this.UserId, topShow)
+			buyerPortraitData["topShow"] = formatUserTopShowList(this.Session, topShow)
 		}
 		//删除多余数据
 		delete(buyerPortraitData, "allWinnerList")

+ 4 - 3
src/jfw/modules/bigmember/src/entity/portraitBuyerSearch.go

@@ -1,7 +1,8 @@
 package entity
 
 import (
-	"encoding/json"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "encoding/json"
 	"errors"
 	"fmt"
 	"log"
@@ -786,7 +787,7 @@ func mAggsSum(winnerName []string, AllData map[string]AllWinner) (mCount float64
 //若读者(投标企业)所在的行业排名在前 5,则取前 5 行业+其他(没被列出的所有行业)
 //若读者(投标企业)所在的行业排名不在前 5,则取前 4 行业+读者所在行业+其他
 //识别不到读者(投标企业)所在的行业,则用第一种方案
-func formatUserTopShowList(userId string, allTopShow interface{}) []TopShow {
+func formatUserTopShowList(session  *httpsession.Session, allTopShow interface{}) []TopShow {
 	alltopShowStruct := &[]TopShow{}
 	if err := InterfaceToStruct(allTopShow, alltopShowStruct); err != nil {
 		return nil
@@ -794,7 +795,7 @@ func formatUserTopShowList(userId string, allTopShow interface{}) []TopShow {
 	if len(*alltopShowStruct) <= 5 {
 		return *alltopShowStruct
 	}
-	userIndustry := getUserSetIndustry(userId)
+	userIndustry := getUserSetIndustry(session)
 	userSetIndustry := ""
 	if len(userIndustry) > 0 {
 		for _, oneShow := range *alltopShowStruct {

+ 15 - 14
src/jfw/modules/bigmember/src/go.mod

@@ -4,15 +4,15 @@ go 1.18
 
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d
-	app.yhyue.com/moapp/jybase v0.0.0-20221229074840-790b25997170
-	app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab
 	github.com/donnie4w/go-logger v0.0.0-20170827050443-4740c51383f4
 	go.mongodb.org/mongo-driver v1.11.1
 )
 
 require (
-	app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c // indirect
-	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 // indirect
+	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c // 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
@@ -65,18 +65,19 @@ require (
 	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.3 // 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.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/jaeger v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/zipkin v1.10.0 // indirect
-	go.opentelemetry.io/otel/sdk v1.10.0 // indirect
-	go.opentelemetry.io/otel/trace v1.10.0 // 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
@@ -86,7 +87,7 @@ require (
 	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-20220728004956-3c1f35247d10 // 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

+ 33 - 22
src/jfw/modules/bigmember/src/go.sum

@@ -2,14 +2,14 @@ app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d h1:WPsYuuptAd3UEgN+j
 app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d/go.mod h1:91/lSD/hS+ckMVP3WdidRzDhC60lLMdyce9QHy0cSMA=
 app.yhyue.com/moapp/jyPoints v1.1.1/go.mod h1:SvP8p5L3jGrejHiH2LXfgCg/NPlFiKBC5Yd0gsI12FU=
 app.yhyue.com/moapp/jybase v0.0.0-20220427020729-974c1a148186/go.mod h1:qNRA0sHuYqcLoYoP8irpaWnW9YsXixe6obBIkwaXpD0=
-app.yhyue.com/moapp/jybase v0.0.0-20221229074840-790b25997170 h1:gjx6+x7P1Vp/++OyfuEdR3Bcjj4/HrgIaRnE1cMTP3k=
-app.yhyue.com/moapp/jybase v0.0.0-20221229074840-790b25997170/go.mod h1:efAeRPDpJ13JuNODuqtfLlKQSQgCbnUcwGPzhFU5krY=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf h1:NMVZDXa4yZtL2BTM8gJLpRU4fSN9a1cj7mTVYa1RUZY=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf/go.mod h1:7D6zNxrg+Tma3VC43TLu7XPczubl4uJavua89kaFS1Q=
-app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c h1:CrcvbsXZ4aQkNikBi7FUUQZNnY8hKsNo2LLe/SqeXs8=
-app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 h1:Xv1D9avDKeaM5kQTisF/pIt8y7B7yQ/hAxuWEg75LMs=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
+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-20230128092104-d8ae3867d2ab h1:a9XvegdF3aM0y9v5SHtX03LIGMS3+8J1ofoNeyw5J0Y=
+app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab/go.mod h1:MqJfBFTSfZhrNDEnE4e19BmaLkaMr+lYActLXm6lrpw=
+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/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c h1:g49jOlhZlBCJ3IgJA0rotfNf2Gh22pISffUtqxB8XtY=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
 cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw=
@@ -407,8 +407,8 @@ github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZp
 github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
 github.com/alicebob/miniredis/v2 v2.14.1/go.mod h1:uS970Sw5Gs9/iK3yBg0l9Uj9s25wXxSpQUE9EaJ/Blg=
 github.com/alicebob/miniredis/v2 v2.22.0/go.mod h1:XNqvJdQJv5mSuVMc0ynneafpnL/zv52acZ6kqeS0t88=
-github.com/alicebob/miniredis/v2 v2.23.1 h1:jR6wZggBxwWygeXcdNyguCOCIjPsZyNUNlAkTx2fu0U=
-github.com/alicebob/miniredis/v2 v2.23.1/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
+github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
+github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
 github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=
 github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
 github.com/antlr/antlr4 v0.0.0-20210105212045-464bcbc32de2/go.mod h1:T7PbCXFs94rrTttyxjbyT5+/1V8T2TYDejxUfHJjw1Y=
@@ -748,7 +748,7 @@ github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+
 github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ=
 github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E=
 github.com/jhump/protoreflect v1.12.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
-github.com/jhump/protoreflect v1.14.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
+github.com/jhump/protoreflect v1.14.1/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
 github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
 github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
@@ -1027,8 +1027,8 @@ github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64 h1:5mLPGnFdSsevFRF
 github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
 github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
 github.com/zeromicro/go-zero v1.3.5/go.mod h1:wh4o794b7Ul3W0k35Pw9nc3iB4O0OpaQTMQz/PJc1bc=
-github.com/zeromicro/go-zero v1.4.3 h1:sTQ++6fxQHJnpGCN7h2CUrhWmbvhBqEgE75cJl635SM=
-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/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=
@@ -1057,31 +1057,41 @@ go.opentelemetry.io/otel v1.0.0/go.mod h1:AjRVh9A5/5DE7S+mZtTR6t8vpKKryam+0lREnf
 go.opentelemetry.io/otel v1.3.0/go.mod h1:PWIKzi6JCp7sM0k9yZ43VX+T345uNbAkDKwHVjb2PTs=
 go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk=
 go.opentelemetry.io/otel v1.8.0/go.mod h1:2pkj+iMj0o03Y+cW6/m8Y4WkRdYN3AvCXCnzRMp9yvM=
-go.opentelemetry.io/otel v1.10.0 h1:Y7DTJMR6zs1xkS/upamJYk0SxxN4C9AqRd77jmZnyY4=
 go.opentelemetry.io/otel v1.10.0/go.mod h1:NbvWjCthWHKBEUMpf0/v8ZRZlni86PpGFEMA9pnQSnQ=
+go.opentelemetry.io/otel v1.11.0 h1:kfToEGMDq6TrVrJ9Vht84Y8y9enykSZzDDZglV0kIEk=
+go.opentelemetry.io/otel v1.11.0/go.mod h1:H2KtuEphyMvlhZ+F7tg9GRhAOe60moNx61Ex+WmiKkk=
 go.opentelemetry.io/otel/exporters/jaeger v1.8.0/go.mod h1:GbWg+ng88rDtx+id26C34QLqw2erqJeAjsCx9AFeHfE=
-go.opentelemetry.io/otel/exporters/jaeger v1.10.0 h1:7W3aVVjEYayu/GOqOVF4mbTvnCuxF1wWu3eRxFGQXvw=
 go.opentelemetry.io/otel/exporters/jaeger v1.10.0/go.mod h1:n9IGyx0fgyXXZ/i0foLHNxtET9CzXHzZeKCucvRBFgA=
-go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0 h1:TaB+1rQhddO1sF71MpZOZAuSPW1klK2M8XxfrBMfK7Y=
+go.opentelemetry.io/otel/exporters/jaeger v1.11.0 h1:Sv2valcFfMlfu6g8USSS+ZUN5vwbuGj1aY/CFtMG33w=
+go.opentelemetry.io/otel/exporters/jaeger v1.11.0/go.mod h1:nRgyJbgJ0hmaUdHwyDpTTfBYz61cTTeeGhVzfQc+FsI=
 go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0/go.mod h1:78XhIg8Ht9vR4tbLNUhXsiOnE2HOuSeKAiAcoVQEpOY=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0 h1:pDDYmo0QadUPal5fwXoY1pmMpFcdyhXOmL5drCrI3vU=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0 h1:0dly5et1i/6Th3WHn0M6kYiJfFNzhhxanrJ0bOfnjEo=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0/go.mod h1:+Lq4/WkdCkjbGcBMVHHg2apTbv8oMBf29QCnyCCJjNQ=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0/go.mod h1:Krqnjl22jUJ0HgMzw5eveuCvFDXY4nSYb4F8t5gdrag=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0 h1:KtiUEhQmj/Pa874bVYKGNVdq8NPKiacPbaRRtgXi+t4=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0 h1:eyJ6njZmH16h9dOKCi7lMswAnGsSOwgTqWzfxqcuNr8=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0/go.mod h1:FnDp7XemjN3oZ3xGunnfOUTVwd2XcvLbtRAuOSU3oc8=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0/go.mod h1:OfUCyyIiDvNXHWpcWgbF+MWvqPZiNa3YDEnivcnYsV0=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0 h1:j2RFV0Qdt38XQ2Jvi4WIsQ56w8T7eSirYbMw19VXRDg=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0/go.mod h1:pILgiTEtrqvZpoiuGdblDgS5dbIaTgDrkIuKfEFkt+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 h1:S8DedULB3gp93Rh+9Z+7NTEv+6Id/KYS7LDyipZ9iCE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0/go.mod h1:5WV40MLWwvWlGP7Xm8g3pMcg0pKOUY609qxJn8y7LmM=
 go.opentelemetry.io/otel/exporters/zipkin v1.8.0/go.mod h1:0uYAyCuGT67MFV9Z/Mmx93wGuugHw0FbxMc74fs3LNo=
-go.opentelemetry.io/otel/exporters/zipkin v1.10.0 h1:HcPAFsFpEBKF+G5NIOA+gBsxifd3Ej+wb+KsdBLa15E=
 go.opentelemetry.io/otel/exporters/zipkin v1.10.0/go.mod h1:HdfvgwcOoCB0+zzrTHycW6btjK0zNpkz2oTGO815SCI=
+go.opentelemetry.io/otel/exporters/zipkin v1.11.0 h1:v/Abo5REOWrCj4zcEIUHFZtXpsCVjrwZj28iyX2rHXE=
+go.opentelemetry.io/otel/exporters/zipkin v1.11.0/go.mod h1:unWnsLCMYfINP8ue0aXVrB/GYHoXNn/lbTnupvLekGQ=
 go.opentelemetry.io/otel/sdk v1.0.0/go.mod h1:PCrDHlSy5x1kjezSdL37PhbFUMjrsLRshJ2zCzeXwbM=
 go.opentelemetry.io/otel/sdk v1.3.0/go.mod h1:rIo4suHNhQwBIPg9axF8V9CA72Wz2mKF1teNrup8yzs=
 go.opentelemetry.io/otel/sdk v1.8.0/go.mod h1:uPSfc+yfDH2StDM/Rm35WE8gXSNdvCg023J6HeGNO0c=
-go.opentelemetry.io/otel/sdk v1.10.0 h1:jZ6K7sVn04kk/3DNUdJ4mqRlGDiXAVuIG+MMENpTNdY=
 go.opentelemetry.io/otel/sdk v1.10.0/go.mod h1:vO06iKzD5baltJz1zarxMCNHFpUlUiOy4s65ECtn6kE=
+go.opentelemetry.io/otel/sdk v1.11.0 h1:ZnKIL9V9Ztaq+ME43IUi/eo22mNsb6a7tGfzaOWB5fo=
+go.opentelemetry.io/otel/sdk v1.11.0/go.mod h1:REusa8RsyKaq0OlyangWXaw97t2VogoO4SSEeKkSTAk=
 go.opentelemetry.io/otel/trace v1.0.0/go.mod h1:PXTWqayeFUlJV1YDNhsJYB184+IvAH814St6o6ajzIs=
 go.opentelemetry.io/otel/trace v1.3.0/go.mod h1:c/VDhno8888bvQYmbYLqe41/Ldmr/KKunbvWM4/fEjk=
 go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU=
 go.opentelemetry.io/otel/trace v1.8.0/go.mod h1:0Bt3PXY8w+3pheS3hQUt+wow8b1ojPaTBoTCh2zIFI4=
-go.opentelemetry.io/otel/trace v1.10.0 h1:npQMbR8o7mum8uF95yFbOEJffhs1sbCOfDh8zAJiH5E=
 go.opentelemetry.io/otel/trace v1.10.0/go.mod h1:Sij3YYczqAdz+EhmGhE6TpTxUO5/F/AzrK+kxfGqySM=
+go.opentelemetry.io/otel/trace v1.11.0 h1:20U/Vj42SX+mASlXLmSGBg6jpI1jQtv682lZtTAOVFI=
+go.opentelemetry.io/otel/trace v1.11.0/go.mod h1:nyYjis9jy0gytE9LXGU+/m1sHTKbRY0fX0hulNNDP1U=
 go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
 go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw=
 go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U=
@@ -1360,8 +1370,9 @@ golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 h1:WIoqL4EROvwiPdUtaip4VcDdpZ4kha7wBWZrbVKCIZg=
 golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 h1:h+EGohizhe9XlX18rfpa8k8RAc5XyaeamM+0VHRd4lc=
+golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=

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

@@ -2,279 +2,295 @@
 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/db"
+        "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"
-	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{}{}
-					//查库获得大会员用户的信息
-					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}`)
-					}
-					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{}{}
+                                        //查库获得大会员用户的信息
+                                        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)
 }
 
 // 根据项目名称获取项目名称
 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)
 }

+ 4 - 7
src/jfw/modules/bigmember/src/service/analysis/decision.go

@@ -49,7 +49,6 @@ var ServiceId = 6
 //采购单位和中标企业 其他项目明细/类似项目明细
 func (this *Analysis) ProjectInfoByBW() {
 	defer qutil.Catch()
-	userId, _ := this.GetSession("userId").(string)
 	r := func() Result {
 		if this.Method() != "POST" {
 			return Result{Data: nil, Error_msg: Error_msg_1005}
@@ -64,7 +63,7 @@ func (this *Analysis) ProjectInfoByBW() {
 			return Result{Data: nil, Error_msg: Error_msg_1003}
 		}
 		//是否是大会员用户
-		if EAD.UserId, EAD.IsPower = entity.CheckPower(userId); !EAD.IsPower {
+		if EAD.UserId, EAD.IsPower = entity.CheckPower(this.Session()); !EAD.IsPower {
 			return Result{Data: nil, Error_msg: Error_msg_1004}
 		}
 		EAD.ServiceId = ServiceId
@@ -79,7 +78,7 @@ func (this *Analysis) TrialInfo() {
 	defer qutil.Catch()
 	userId, _ := this.GetSession("userId").(string)
 	rData, errMsg := func() (interface{}, error) {
-		//userInfo, ok := db.Mgo.FindById("user", userId, nil)
+		//userInfo, ok := db.Mgo.FindById(C_User, userId, nil)
 		baseMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
 
 		if baseMsg == nil {
@@ -136,8 +135,7 @@ func (this *Analysis) FreeDecInfo() {
 		}
 		if getRes.Sid != "" && getRes.Pname != "" && len(getRes.BuyerContent) > 0 {
 			userId, _ := this.GetSession("userId").(string)
-			var s_phone, _ = this.GetSession("s_phone").(string)
-			main_userId, phone, _ := util.MainUserId(userId, s_phone, 0)
+			main_userId, phone, _ := util.MainUserId(this.Session())
 			entity.UIL.Lock()
 			if entity.UIL.DecLock[main_userId] == nil {
 				entity.UIL.DecLock[main_userId] = &sync.Mutex{}
@@ -195,8 +193,7 @@ func (this *Analysis) DecInfo() {
 			var base64Key = "" //加密串
 			userId, _ := this.GetSession("userId").(string)
 			//是否是子账号
-			var s_phone, _ = this.GetSession("s_phone").(string)
-			main_userId, phone, member_status := util.MainUserId(userId, s_phone, 0)
+			main_userId, phone, member_status := util.MainUserId(this.Session())
 			if member_status == 0 {
 				regMap.Error_code = Error_code_1004
 				regMap.Error_msg = Error_msg_1004

+ 543 - 542
src/jfw/modules/bigmember/src/service/analysis/forecastproject.go

@@ -2,40 +2,40 @@
 package analysis
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/bigmember/src/config"
-	"jy/src/jfw/modules/bigmember/src/db"
-	"jy/src/jfw/modules/bigmember/src/util"
-
-	. "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"
-
-	"sort"
-	"strconv"
-	"strings"
-	"time"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/config"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "jy/src/jfw/modules/bigmember/src/util"
+
+        . "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"
+
+        "sort"
+        "strconv"
+        "strings"
+        "time"
 )
 
 const (
-	INDEX           = "forecast"
-	TYPE            = "forecast"
-	bidSearch_sort  = `{"yucetime":-1}`
-	findfields      = `"title"`
-	bidSearch_field = ``
-
-	forecastQuery            = `{"query":{"filtered":{"filter":{"bool":{"must":[%s]}},"query":{"bool":{"should":[%s],"minimum_should_match":1}}}}}`
-	filter_must_time         = `{"bool":{"should":[{"bool":{"must":[{"missing":{"field":"yuceendtime"}},{"range":{"yucetime":{"gte":%d}}}]}},{"bool":{"must":[{"exists":{"field":"yuceendtime"}},{"range":{"yuceendtime":{"gte":%d}}}]}}]}}`
-	filter_must_area_city    = `{"bool":{"should":[%s]}}`
-	query_should_keys        = `{"bool":{"must":[%s],"must_not":[%s]}}`
-	query_should_multi_match = `{"multi_match":{"query":"%s","type":"phrase","fields":["results.purchasing.mypurchasing"]}}`
+        INDEX           = "forecast"
+        TYPE            = "forecast"
+        bidSearch_sort  = `{"yucetime":-1}`
+        findfields      = `"title"`
+        bidSearch_field = ``
+
+        forecastQuery            = `{"query":{"filtered":{"filter":{"bool":{"must":[%s]}},"query":{"bool":{"should":[%s],"minimum_should_match":1}}}}}`
+        filter_must_time         = `{"bool":{"should":[{"bool":{"must":[{"missing":{"field":"yuceendtime"}},{"range":{"yucetime":{"gte":%d}}}]}},{"bool":{"must":[{"exists":{"field":"yuceendtime"}},{"range":{"yuceendtime":{"gte":%d}}}]}}]}}`
+        filter_must_area_city    = `{"bool":{"should":[%s]}}`
+        query_should_keys        = `{"bool":{"must":[%s],"must_not":[%s]}}`
+        query_should_multi_match = `{"multi_match":{"query":"%s","type":"phrase","fields":["results.purchasing.mypurchasing"]}}`
 )
 
 /**
@@ -47,551 +47,552 @@ const (
 	另有省份、城市、采购单位类型等;from 赵龙玥
 **/
 func getForecastProjectSql(scd *util.ViewCondition) string {
-	musts := []string{}
-	bools := []string{}
-	musts = append(musts, fmt.Sprintf(filter_must_time, time.Now().AddDate(0, -3, 0).Unix(), time.Now().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(filter_must_area_city, strings.Join(areaCity, ",")))
-	}
-
-	//采购单位类型
-	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)
-	}
-
-	//should
-	if len(scd.Keyword) > 0 {
-		multi_match := query_should_multi_match
-		for _, v := range scd.Keyword {
-			bool_must := []string{}
-			bool_must_not := []string{}
-			//附加词
-			for _, vv := range v.Keyword {
-				bool_must = append(bool_must, fmt.Sprintf(multi_match, vv))
-			}
-
-			for _, vv := range v.Appended {
-				bool_must = append(bool_must, fmt.Sprintf(multi_match, vv))
-			}
-
-			//排除词
-			for _, vv := range v.Exclude {
-				bool_must_not = append(bool_must_not, fmt.Sprintf(multi_match, vv))
-			}
-
-			//添加
-			if len(bool_must) > 0 {
-				bools = append(bools, fmt.Sprintf(query_should_keys, strings.Join(bool_must, ","), strings.Join(bool_must_not, ",")))
-			}
-		}
-	}
-
-	qstr := fmt.Sprintf(forecastQuery, strings.Join(musts, ","), strings.Join(bools, ","))
-	log.Println("qstr:", qstr)
-	return qstr
+        musts := []string{}
+        bools := []string{}
+        musts = append(musts, fmt.Sprintf(filter_must_time, time.Now().AddDate(0, -3, 0).Unix(), time.Now().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(filter_must_area_city, strings.Join(areaCity, ",")))
+        }
+
+        //采购单位类型
+        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)
+        }
+
+        //should
+        if len(scd.Keyword) > 0 {
+                multi_match := query_should_multi_match
+                for _, v := range scd.Keyword {
+                        bool_must := []string{}
+                        bool_must_not := []string{}
+                        //附加词
+                        for _, vv := range v.Keyword {
+                                bool_must = append(bool_must, fmt.Sprintf(multi_match, vv))
+                        }
+
+                        for _, vv := range v.Appended {
+                                bool_must = append(bool_must, fmt.Sprintf(multi_match, vv))
+                        }
+
+                        //排除词
+                        for _, vv := range v.Exclude {
+                                bool_must_not = append(bool_must_not, fmt.Sprintf(multi_match, vv))
+                        }
+
+                        //添加
+                        if len(bool_must) > 0 {
+                                bools = append(bools, fmt.Sprintf(query_should_keys, strings.Join(bool_must, ","), strings.Join(bool_must_not, ",")))
+                        }
+                }
+        }
+
+        qstr := fmt.Sprintf(forecastQuery, strings.Join(musts, ","), strings.Join(bools, ","))
+        log.Println("qstr:", qstr)
+        return qstr
 }
 
 // ForPContent 预测详情页
 func (this *Analysis) ForPContent() {
-	defer qutil.Catch()
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		id := this.GetString("id")     //项目预测id
-		keys := this.GetString("keys") //关键词
-		if id == "" || keys == "" {
-			return -1, nil
-		}
-		id = util.DecodeId(id)
-		data, ok := db.Mgo_Ent.FindById(C_FPContent, id, nil)
-		if ok && data != nil && (*data)["results"] != nil {
-			yucetime := (*data)["yucetime"]
-			(*data)["yucetime"] = FormatDateWithObj(&yucetime, "2006/01/02")
-			results := qutil.ObjArrToMapArr((*data)["results"].([]interface{}))
-			resultsArr := []map[string]interface{}{}
-			resultsMap := map[string]interface{}{}
-			if len(results) > 0 {
-				for _, rv := range results {
-					if rv["p_projects"] == nil {
-						continue
-					}
-					p_projects := qutil.ObjArrToMapArr(rv["p_projects"].([]interface{}))
-					for _, pv := range p_projects {
-						if pv["p_id"] == nil || pv["p_purchasing"] == nil {
-							continue
-						}
-						pv_key := qutil.ObjToString(pv["p_purchasing"])
-						for _, kv := range strings.Split(keys, "、") {
-							if strings.Contains(pv_key, kv) {
-								if resultsMap[pv["p_id"].(string)] != nil {
-									rmp := qutil.ObjToMap(resultsMap[pv["p_id"].(string)])
-									if qutil.ObjToString((*rmp)["p_purchasing"]) == pv_key {
-										continue
-									}
-									pv_key = qutil.ObjToString((*rmp)["p_purchasing"]) + "、" + pv["p_purchasing"].(string)
-									if pv["p_person"] == nil && (*rmp)["p_purchasing"] != nil {
-										pv["p_person"] = (*rmp)["p_person"]
-									}
-									if pv["p_phone"] == nil && (*rmp)["p_phone"] != nil {
-										pv["p_phone"] = (*rmp)["p_phone"]
-									}
-								}
-								resultsMap[pv["p_id"].(string)] = map[string]interface{}{
-									"p_purchasing": pv_key,
-									"p_phone":      pv["p_phone"],
-									"p_person":     pv["p_person"],
-									"p_id":         util.EncodeId(pv["p_id"].(string)),
-									"p_orther":     pv["p_orther"],
-								}
-							}
-						}
-					}
-				}
-				if resultsMap != nil {
-					for _, rmv := range resultsMap {
-						resultsArr = append(resultsArr, *qutil.ObjToMap(rmv))
-					}
-				}
-			}
-			power := []int{}
-			powerMap := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key).PowerMap
-			for k, _ := range powerMap {
-				power = append(power, k)
-			}
-			(*data)["power"] = power
-			(*data)["results"] = []map[string]interface{}{}
-			if len(resultsArr) > 0 {
-				(*data)["results"] = resultsArr
-			}
-			delete(*data, "_id")
-			delete(*data, "infoid")
-			return *data, nil
-		}
-		return 0, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s   获取此预测项目信息出错-%s", userId, errMsg)
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        defer qutil.Catch()
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                id := this.GetString("id")     //项目预测id
+                keys := this.GetString("keys") //关键词
+                if id == "" || keys == "" {
+                        return -1, nil
+                }
+                id = util.DecodeId(id)
+                data, ok := db.Mgo_Ent.FindById(C_FPContent, id, nil)
+                if ok && data != nil && (*data)["results"] != nil {
+                        yucetime := (*data)["yucetime"]
+                        (*data)["yucetime"] = FormatDateWithObj(&yucetime, "2006/01/02")
+                        results := qutil.ObjArrToMapArr((*data)["results"].([]interface{}))
+                        resultsArr := []map[string]interface{}{}
+                        resultsMap := map[string]interface{}{}
+                        if len(results) > 0 {
+                                for _, rv := range results {
+                                        if rv["p_projects"] == nil {
+                                                continue
+                                        }
+                                        p_projects := qutil.ObjArrToMapArr(rv["p_projects"].([]interface{}))
+                                        for _, pv := range p_projects {
+                                                if pv["p_id"] == nil || pv["p_purchasing"] == nil {
+                                                        continue
+                                                }
+                                                pv_key := qutil.ObjToString(pv["p_purchasing"])
+                                                for _, kv := range strings.Split(keys, "、") {
+                                                        if strings.Contains(pv_key, kv) {
+                                                                if resultsMap[pv["p_id"].(string)] != nil {
+                                                                        rmp := qutil.ObjToMap(resultsMap[pv["p_id"].(string)])
+                                                                        if qutil.ObjToString((*rmp)["p_purchasing"]) == pv_key {
+                                                                                continue
+                                                                        }
+                                                                        pv_key = qutil.ObjToString((*rmp)["p_purchasing"]) + "、" + pv["p_purchasing"].(string)
+                                                                        if pv["p_person"] == nil && (*rmp)["p_purchasing"] != nil {
+                                                                                pv["p_person"] = (*rmp)["p_person"]
+                                                                        }
+                                                                        if pv["p_phone"] == nil && (*rmp)["p_phone"] != nil {
+                                                                                pv["p_phone"] = (*rmp)["p_phone"]
+                                                                        }
+                                                                }
+                                                                resultsMap[pv["p_id"].(string)] = map[string]interface{}{
+                                                                        "p_purchasing": pv_key,
+                                                                        "p_phone":      pv["p_phone"],
+                                                                        "p_person":     pv["p_person"],
+                                                                        "p_id":         util.EncodeId(pv["p_id"].(string)),
+                                                                        "p_orther":     pv["p_orther"],
+                                                                }
+                                                        }
+                                                }
+                                        }
+                                }
+                                if resultsMap != nil {
+                                        for _, rmv := range resultsMap {
+                                                resultsArr = append(resultsArr, *qutil.ObjToMap(rmv))
+                                        }
+                                }
+                        }
+                        power := []int{}
+                        powerMap := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key).PowerMap
+                        for k, _ := range powerMap {
+                                power = append(power, k)
+                        }
+                        (*data)["power"] = power
+                        (*data)["results"] = []map[string]interface{}{}
+                        if len(resultsArr) > 0 {
+                                (*data)["results"] = resultsArr
+                        }
+                        delete(*data, "_id")
+                        delete(*data, "infoid")
+                        return *data, nil
+                }
+                return 0, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s   获取此预测项目信息出错-%s", userId, errMsg)
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 func (this *Analysis) ForPList() {
-	defer qutil.Catch()
-	var regMap = Result{
-		Data:       []map[string]interface{}{},
-		Error_code: Error_code,
-		Error_msg:  "",
-	}
-	if this.Method() == METHOD {
-		msg := ""
-		code := 0
-		list := []map[string]interface{}{}
-		flist := []map[string]interface{}{}
-		count := 0
-		var fcount int64 = 0
-		userId, _ := this.GetSession("userId").(string)
-		main_userId, _, _ := util.MainUserId(userId, "", 0)
-		isSubCount := false
-		//子账号
-		if userId != main_userId {
-			isSubCount = true
-		}
-		pageNum, _ := this.GetInteger("pageNum")
-		pageSize, _ := this.GetInteger("pageSize")
-		if pageSize == 0 {
-			pageSize = 10
-		}
-		o_member_jy := &map[string]interface{}{}
-		//查库获得大会员用户的信息
-		o_mb, ok := db.Mgo.FindById(C_User, main_userId, `{"o_member_jy":1}`)
-		if ok && o_mb != nil && (*o_mb) != nil {
-			if (*o_mb)["o_member_jy"] != nil {
-				// list, count = getNewProjects(main_userId, pageNum)
-				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 {
-				//PC端大会员 没有进行初始化
-				msg = "暂无设置订阅关键词,无法进行预测"
-				code = 1
-			}
-		}
-		regMap.Data = map[string]interface{}{
-			"msg":        msg,
-			"code":       code,
-			"list":       forecastMerge(list, flist),
-			"count":      int64(count) + fcount,
-			"isSubCount": isSubCount,
-		}
-	} 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 {
+                msg := ""
+                code := 0
+                list := []map[string]interface{}{}
+                flist := []map[string]interface{}{}
+                count := 0
+                var fcount int64 = 0
+                userId, _ := this.GetSession("userId").(string)
+                main_userId, _, _ := util.MainUserId(this.Session())
+                isSubCount := false
+                //子账号
+                if userId != main_userId {
+                        isSubCount = true
+                }
+                pageNum, _ := this.GetInteger("pageNum")
+                pageSize, _ := this.GetInteger("pageSize")
+                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_mb := jy.GetSubScribeInfo(this.Session(), db.Mgo, "m", "10000")
+                if o_mb != nil && (*o_mb) != nil {
+                        if (*o_mb)["o_member_jy"] != nil {
+                                // list, count = getNewProjects(main_userId, pageNum)
+                                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 {
+                                //PC端大会员 没有进行初始化
+                                msg = "暂无设置订阅关键词,无法进行预测"
+                                code = 1
+                        }
+                }
+                regMap.Data = map[string]interface{}{
+                        "msg":        msg,
+                        "code":       code,
+                        "list":       forecastMerge(list, flist),
+                        "count":      int64(count) + fcount,
+                        "isSubCount": isSubCount,
+                }
+        } else {
+                regMap.Error_code = Error_code_1005
+                regMap.Error_msg = Error_msg_1005
+        }
+        this.ServeJson(regMap)
 }
 
 type ForecastInfo struct {
-	Buyer      string   `json:"buyer"`
-	Id         string   `json:"id"`
-	Purchasing []string `json:"purchasing"`
-	Title      string   `json:"title"`
-	Createtime int64    `json:"createtime"`
-	Keys       string   `json:"keys"`
-	Jyhref     string   `json:"jyhref"`
+        Buyer      string   `json:"buyer"`
+        Id         string   `json:"id"`
+        Purchasing []string `json:"purchasing"`
+        Title      string   `json:"title"`
+        Createtime int64    `json:"createtime"`
+        Keys       string   `json:"keys"`
+        Jyhref     string   `json:"jyhref"`
 }
 
 //合并去重
 func forecastMerge(r, f []map[string]interface{}) []*ForecastInfo {
-	var idMap = map[string]bool{}
-	var res = []*ForecastInfo{}
-	var isSort = 0
-	if len(r) > 0 {
-		isSort = isSort + 1
-		for _, rv := range r {
-			idMap[qutil.ObjToString(rv["id"])] = true
-			res = append(res, &ForecastInfo{
-				Buyer:      qutil.ObjToString(rv["buyer"]),
-				Id:         util.EncodeId(qutil.ObjToString(rv["id"])),
-				Purchasing: rv["results"].([]string),
-				Title:      qutil.ObjToString(rv["title"]),
-				Createtime: qutil.Int64All(rv["createtime"]),
-				Keys:       "",
-			})
-		}
-	}
-	if len(f) > 0 {
-		isSort = isSort + 1
-		for _, fv := range f {
-			if idMap[qutil.ObjToString(fv["id"])] {
-				continue
-			}
-			res = append(res, &ForecastInfo{
-				Buyer:      qutil.ObjToString(fv["buyer"]),
-				Id:         util.EncodeId(qutil.ObjToString(fv["id"])),
-				Purchasing: fv["results"].([]string),
-				Title:      qutil.ObjToString(fv["title"]),
-				Createtime: qutil.Int64All(fv["yucetime"]),
-				Jyhref:     qutil.ObjToString(fv["jyhref"]),
-				Keys:       "",
-			})
-		}
-	}
-	//
-	if isSort > 1 {
-		sort.Slice(res, func(i, j int) bool {
-			return res[i].Createtime > res[j].Createtime
-		})
-	}
-	return res
+        var idMap = map[string]bool{}
+        var res = []*ForecastInfo{}
+        var isSort = 0
+        if len(r) > 0 {
+                isSort = isSort + 1
+                for _, rv := range r {
+                        idMap[qutil.ObjToString(rv["id"])] = true
+                        res = append(res, &ForecastInfo{
+                                Buyer:      qutil.ObjToString(rv["buyer"]),
+                                Id:         util.EncodeId(qutil.ObjToString(rv["id"])),
+                                Purchasing: rv["results"].([]string),
+                                Title:      qutil.ObjToString(rv["title"]),
+                                Createtime: qutil.Int64All(rv["createtime"]),
+                                Keys:       "",
+                        })
+                }
+        }
+        if len(f) > 0 {
+                isSort = isSort + 1
+                for _, fv := range f {
+                        if idMap[qutil.ObjToString(fv["id"])] {
+                                continue
+                        }
+                        res = append(res, &ForecastInfo{
+                                Buyer:      qutil.ObjToString(fv["buyer"]),
+                                Id:         util.EncodeId(qutil.ObjToString(fv["id"])),
+                                Purchasing: fv["results"].([]string),
+                                Title:      qutil.ObjToString(fv["title"]),
+                                Createtime: qutil.Int64All(fv["yucetime"]),
+                                Jyhref:     qutil.ObjToString(fv["jyhref"]),
+                                Keys:       "",
+                        })
+                }
+        }
+        //
+        if isSort > 1 {
+                sort.Slice(res, func(i, j int) bool {
+                        return res[i].Createtime > res[j].Createtime
+                })
+        }
+        return res
 }
 
 var d = &dfa.DFA{}
 
 //
 func getNewForecast(userId string, pageNum int, o_member_jy map[string]interface{}, pageSize int) (list []map[string]interface{}, count int64) {
-	if userId == "" {
-		return
-	}
-	sql := getSqlObjFromId(o_member_jy)
-	if sql == nil {
-		return
-	}
-	keys := []string{}
-	keyIsexists := map[string]bool{}
-	for _, v := range sql.Keyword {
-		var keys_one []string
-		for _, k := range v.Keyword {
-			keys_one = append(keys_one, k)
-		}
-		for _, k := range v.Appended {
-			keys_one = append(keys_one, k)
-		}
-		if keyIsexists[strings.Join(keys_one, "+")] {
-			continue
-		}
-		keyIsexists[strings.Join(keys_one, "+")] = true
-		keys = append(keys, strings.Join(keys_one, "+"))
-	}
-	if len(keys) == 0 {
-		return
-	}
-	// qstr := GetMemberForecastSql(sql)
-	qstr := getForecastProjectSql(sql)
-	count = elastic.Count(INDEX, TYPE, qstr)
-	list = *elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSearch_sort, bidSearch_field, (pageNum-1)*pageSize, pageSize, 0, false)
-	if list != nil {
-		d.AddWord(keys...)
-		for _, v := range list {
-			var rsArr = []string{}
-			var rsArrRes = []string{}
-			if v["results"] != nil {
-				results := qutil.ObjArrToMapArr(v["results"].([]interface{}))
-				rsvMap := map[string]bool{}
-				for _, rsv := range results {
-					rsArr = append(rsArr, d.Analy(rsv["purchasing"].(string))...)
-				}
-				for _, rv := range rsArr {
-					if rsvMap[strings.Join(rsArr, "+")] {
-						continue
-					}
-					rsArrRes = append(rsArrRes, rv)
-					rsvMap[strings.Join(rsArr, "+")] = true
-				}
-			}
-			v["results"] = rsArrRes
-			v["id"] = qutil.ObjToString(v["_id"])
-			v["yucetime"] = qutil.Int64All(v["yucetime"].(float64))
-		}
-		d.Clear()
-	}
-	return
+        if userId == "" {
+                return
+        }
+        sql := getSqlObjFromId(o_member_jy)
+        if sql == nil {
+                return
+        }
+        keys := []string{}
+        keyIsexists := map[string]bool{}
+        for _, v := range sql.Keyword {
+                var keys_one []string
+                for _, k := range v.Keyword {
+                        keys_one = append(keys_one, k)
+                }
+                for _, k := range v.Appended {
+                        keys_one = append(keys_one, k)
+                }
+                if keyIsexists[strings.Join(keys_one, "+")] {
+                        continue
+                }
+                keyIsexists[strings.Join(keys_one, "+")] = true
+                keys = append(keys, strings.Join(keys_one, "+"))
+        }
+        if len(keys) == 0 {
+                return
+        }
+        // qstr := GetMemberForecastSql(sql)
+        qstr := getForecastProjectSql(sql)
+        count = elastic.Count(INDEX, TYPE, qstr)
+        list = *elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSearch_sort, bidSearch_field, (pageNum-1)*pageSize, pageSize, 0, false)
+        if list != nil {
+                d.AddWord(keys...)
+                for _, v := range list {
+                        var rsArr = []string{}
+                        var rsArrRes = []string{}
+                        if v["results"] != nil {
+                                results := qutil.ObjArrToMapArr(v["results"].([]interface{}))
+                                rsvMap := map[string]bool{}
+                                for _, rsv := range results {
+                                        rsArr = append(rsArr, d.Analy(rsv["purchasing"].(string))...)
+                                }
+                                for _, rv := range rsArr {
+                                        if rsvMap[strings.Join(rsArr, "+")] {
+                                                continue
+                                        }
+                                        rsArrRes = append(rsArrRes, rv)
+                                        rsvMap[strings.Join(rsArr, "+")] = true
+                                }
+                        }
+                        v["results"] = rsArrRes
+                        v["id"] = qutil.ObjToString(v["_id"])
+                        v["yucetime"] = qutil.Int64All(v["yucetime"].(float64))
+                }
+                d.Clear()
+        }
+        return
 }
 
 //获取大会员forecast 检索库查询语句 - 查询逻辑有调整 dev4.6.8 -ws 新方法:getForecastProjectSql()
 func GetMemberForecastSql(scd *util.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_must_exists := `{"bool":{"should":{"filtered":{"filter":{"bool":{"must":[{"exists":{"field":"yuceendtime"}},{"range":{"yuceendtime":{"lte":%d}}}]}}}}}}`
-
-	bools := []string{}
-	musts := []string{}
-	//预测时间最新三个月
-	musts = append(musts, fmt.Sprintf(`{"range":{"yucetime":{"gte":%d}}}`, time.Now().AddDate(-2, 0, 0).Unix()), fmt.Sprintf(query_must_exists, time.Now().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
-		multi_match = fmt.Sprintf(multi_match, "%s", `"results.purchasing.mypurchasing"`)
-
-		for _, v := range scd.Keyword {
-			shoulds := []string{}
-			must_not := []string{}
-			//附加词
-			for _, vv := range v.Keyword {
-				shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
-
-			for _, vv := range v.Appended {
-				shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
-
-			//排除词
-			for _, vv := range v.Exclude {
-				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))
-			}
-		}
-	}
-
-	qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
-	return qstr
+        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_must_exists := `{"bool":{"should":{"filtered":{"filter":{"bool":{"must":[{"exists":{"field":"yuceendtime"}},{"range":{"yuceendtime":{"lte":%d}}}]}}}}}}`
+
+        bools := []string{}
+        musts := []string{}
+        //预测时间最新三个月
+        musts = append(musts, fmt.Sprintf(`{"range":{"yucetime":{"gte":%d}}}`, time.Now().AddDate(-2, 0, 0).Unix()), fmt.Sprintf(query_must_exists, time.Now().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
+                multi_match = fmt.Sprintf(multi_match, "%s", `"results.purchasing.mypurchasing"`)
+
+                for _, v := range scd.Keyword {
+                        shoulds := []string{}
+                        must_not := []string{}
+                        //附加词
+                        for _, vv := range v.Keyword {
+                                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+                        }
+
+                        for _, vv := range v.Appended {
+                                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+                        }
+
+                        //排除词
+                        for _, vv := range v.Exclude {
+                                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))
+                        }
+                }
+        }
+
+        qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
+        return qstr
 }
 
 //member_jy
 func getSqlObjFromId(o_member_jy map[string]interface{}) *util.ViewCondition {
-	if o_member_jy["a_items"] == nil {
-		return nil
-	}
-	a_items := []interface{}{}
-	if o_member_jy["a_items"] != nil {
-		a_items = o_member_jy["a_items"].([]interface{})
-	}
-	a_buyerclass := []interface{}{}
-	if o_member_jy["a_buyerclass"] != nil {
-		a_buyerclass = o_member_jy["a_buyerclass"].([]interface{})
-	}
-	if len(a_buyerclass) > 0 && qutil.IntAllDef(o_member_jy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
-		a_buyerclass = append(a_buyerclass, "其它")
-	}
-	a_infotype := []interface{}{}
-	if o_member_jy["a_infotype"] != nil {
-		a_infotype = o_member_jy["a_infotype"].([]interface{})
-	}
-	o_area := map[string]interface{}{}
-	if o_member_jy["o_area"] != nil {
-		o_area = o_member_jy["o_area"].(map[string]interface{})
-	}
-	return &util.ViewCondition{
-		Keyword:    getKeyWordArr(a_items, "", -1),
-		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_member_jy["i_matchway"])),
-	}
+        if o_member_jy["a_items"] == nil {
+                return nil
+        }
+        a_items := []interface{}{}
+        if o_member_jy["a_items"] != nil {
+                a_items = o_member_jy["a_items"].([]interface{})
+        }
+        a_buyerclass := []interface{}{}
+        if o_member_jy["a_buyerclass"] != nil {
+                a_buyerclass = o_member_jy["a_buyerclass"].([]interface{})
+        }
+        if len(a_buyerclass) > 0 && qutil.IntAllDef(o_member_jy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
+                a_buyerclass = append(a_buyerclass, "其它")
+        }
+        a_infotype := []interface{}{}
+        if o_member_jy["a_infotype"] != nil {
+                a_infotype = o_member_jy["a_infotype"].([]interface{})
+        }
+        o_area := map[string]interface{}{}
+        if o_member_jy["o_area"] != nil {
+                o_area = o_member_jy["o_area"].(map[string]interface{})
+        }
+        return &util.ViewCondition{
+                Keyword:    getKeyWordArr(a_items, "", -1),
+                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_member_jy["i_matchway"])),
+        }
 }
 
 //关键词 附加词 排除词
 func getKeyWordArr(a_items []interface{}, item string, index int) (arr []util.ViewKeyWord) {
-	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
-		}
-		if vm["a_key"] == nil {
-			continue
-		}
-		kwsArr := vm["a_key"]
-		for i, k := range kwsArr.([]interface{}) {
-			if item != "" && index >= 0 && i != index {
-				continue
-			}
-			kw := util.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, util.ViewKeyWord{
-						Keyword: []string{kk},
-						Exclude: kw.Exclude,
-					})
-				}
-				for _, kk := range kw.Appended {
-					arr = append(arr, util.ViewKeyWord{
-						Keyword: []string{kk},
-						Exclude: kw.Exclude,
-					})
-				}
-			} else {
-				arr = append(arr, kw)
-			}
-		}
-	}
-	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
+                }
+                if vm["a_key"] == nil {
+                        continue
+                }
+                kwsArr := vm["a_key"]
+                for i, k := range kwsArr.([]interface{}) {
+                        if item != "" && index >= 0 && i != index {
+                                continue
+                        }
+                        kw := util.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, util.ViewKeyWord{
+                                                Keyword: []string{kk},
+                                                Exclude: kw.Exclude,
+                                        })
+                                }
+                                for _, kk := range kw.Appended {
+                                        arr = append(arr, util.ViewKeyWord{
+                                                Keyword: []string{kk},
+                                                Exclude: kw.Exclude,
+                                        })
+                                }
+                        } else {
+                                arr = append(arr, kw)
+                        }
+                }
+        }
+        return
 }
 
 //
 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
-	} else {
-		arr = cityArr
-	}
-	return
+        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
+        } else {
+                arr = cityArr
+        }
+        return
 }

+ 3 - 3
src/jfw/modules/bigmember/src/service/analysis/forecastwinner.go

@@ -122,7 +122,7 @@ func (this *Analysis) FWData() {
 					if s_phone == "" {
 						s_phone, _ = this.GetSession("s_m_phone").(string)
 					}
-					main_userId, phone, member_status := util.MainUserId(userId, s_phone, 0)
+					main_userId, phone, member_status := util.MainUserId(this.Session())
 					entity.UIL.Lock()
 					if entity.UIL.ForWLock[main_userId] == nil {
 						entity.UIL.ForWLock[main_userId] = &sync.Mutex{}
@@ -282,7 +282,7 @@ func (this *Analysis) FWStatus() {
 		if userId != "" {
 			//父级userid
 			// userid := util.MainUserId(userId)
-			main_userId, _, _ := util.MainUserId(userId, "", 0)
+			main_userId, _, _ := util.MainUserId(this.Session())
 			rfrExist, _ := redis.Exists("other", redis_forecast_res+userId)
 			f_id := redis.GetStr("other", redis_forecast_date+userId)
 			var isFFalse = 0  //是否预测失败
@@ -311,7 +311,7 @@ func (this *Analysis) FWStatus() {
 							}
 							// 订阅及搜索优化版本dev4.3.4调整为预测成功后才扣次数
 							go func(userId, f_id string) {
-								main_userId, _, _ := util.MainUserId(userId, "", 0)
+								main_userId, _, _ := util.MainUserId(this.Session())
 								if ok, _ := redis.Exists("newother", "jyPredictedDeduction_"+main_userId); ok {
 									//扣除次数
 									UpdatePower(main_userId, 15)

+ 805 - 805
src/jfw/modules/bigmember/src/service/analysis/potential.go

@@ -2,886 +2,886 @@
 package analysis
 
 import (
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/bigmember/src/config"
-	"jy/src/jfw/modules/bigmember/src/db"
-	"jy/src/jfw/modules/bigmember/src/entity"
-	"log"
-	"sort"
-	"strings"
-	"sync"
-	"time"
+        . "app.yhyue.com/moapp/jybase/api"
+        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"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/config"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "jy/src/jfw/modules/bigmember/src/entity"
+        "log"
+        "sort"
+        "strings"
+        "sync"
+        "time"
 
-	"jy/src/jfw/modules/bigmember/src/util"
+        "jy/src/jfw/modules/bigmember/src/util"
 
-	"go.mongodb.org/mongo-driver/bson"
+        "go.mongodb.org/mongo-driver/bson"
 )
 
 // 大会员首页
 func (this *Analysis) PotIndex() {
-	userId, _ := this.GetSession("userId").(string)
-	defer qutil.Catch()
-	r := func() Result {
-		if this.Method() != "POST" {
-			return Result{Data: nil, Error_msg: Error_msg_1005}
-		}
-		//接受前端参数
-		ptst := new(SelectC)
-		if string(this.Body()) != "" {
-			//接收参数
-			json.Unmarshal(this.Body(), &ptst)
-		}
-		ptst.UserId = userId
-		ptst.Session = this.Session()
-		if !ptst.UserStatusChecked() {
-			return Result{Data: nil, Error_msg: Error_msg_1004}
-		}
-		if ptst.PCOR != "" && ptst.IsIndex {
-			list := []*PTComs{}
-			ok, _ := redis.Exists("other", "CRIndex_"+ptst.PCOR+"_"+ptst.UserId)
-			redis_baseKeys := "CRIndex_new_" + ptst.UserId + "_" + ptst.Base64Keys()
-			_res := redis.Get("other", redis_baseKeys)
-			if ok && _res != nil {
-				b, e := json.Marshal(_res)
-				if e != nil {
-					log.Println(e.Error())
-				}
-				json.Unmarshal(b, &list)
-			} else {
-				//客户
-				if ptst.PCOR == "C" {
-					potComQ := PCQuery(ptst.Area, ptst.Industry, ptst.BuyerClass, ptst.Business_scope, ptst.Sort_no, ptst.PCOR)
-					list = getPCostomers(ptst.UserId, ptst.EntName, potComQ, ptst.PCOR)
+        userId, _ := this.GetSession("userId").(string)
+        defer qutil.Catch()
+        r := func() Result {
+                if this.Method() != "POST" {
+                        return Result{Data: nil, Error_msg: Error_msg_1005}
+                }
+                //接受前端参数
+                ptst := new(SelectC)
+                if string(this.Body()) != "" {
+                        //接收参数
+                        json.Unmarshal(this.Body(), &ptst)
+                }
+                ptst.UserId = userId
+                ptst.Session = this.Session()
+                if !ptst.UserStatusChecked() {
+                        return Result{Data: nil, Error_msg: Error_msg_1004}
+                }
+                if ptst.PCOR != "" && ptst.IsIndex {
+                        list := []*PTComs{}
+                        ok, _ := redis.Exists("other", "CRIndex_"+ptst.PCOR+"_"+ptst.UserId)
+                        redis_baseKeys := "CRIndex_new_" + ptst.UserId + "_" + ptst.Base64Keys()
+                        _res := redis.Get("other", redis_baseKeys)
+                        if ok && _res != nil {
+                                b, e := json.Marshal(_res)
+                                if e != nil {
+                                        log.Println(e.Error())
+                                }
+                                json.Unmarshal(b, &list)
+                        } else {
+                                //客户
+                                if ptst.PCOR == "C" {
+                                        potComQ := PCQuery(ptst.Area, ptst.Industry, ptst.BuyerClass, ptst.Business_scope, ptst.Sort_no, ptst.PCOR)
+                                        list = getPCostomers(ptst.UserId, ptst.EntName, potComQ, ptst.PCOR)
 
-				} else if ptst.PCOR == "R" {
-					potRivQ := PCQuery(ptst.Area, ptst.Industry, ptst.BuyerClass, ptst.Business_scope, ptst.Sort_no, ptst.PCOR)
-					list = getPRivals(ptst.UserId, potRivQ, ptst.PCOR)
-				}
-			}
-			if len(list) > 20 {
-				list = list[:20]
-			}
-			if len(list) > 0 {
-				redis.Put("other", redis_baseKeys, list, 8*60*60)
-				redis.Put("other", "CRIndex_"+ptst.PCOR+"_"+ptst.UserId, "CR", 8*60*60)
-			}
-			return Result{Data: map[string]interface{}{
-				"list": list,
-			}}
-		}
-		return Result{Data: nil}
-	}()
-	this.ServeJson(r)
+                                } else if ptst.PCOR == "R" {
+                                        potRivQ := PCQuery(ptst.Area, ptst.Industry, ptst.BuyerClass, ptst.Business_scope, ptst.Sort_no, ptst.PCOR)
+                                        list = getPRivals(ptst.UserId, potRivQ, ptst.PCOR)
+                                }
+                        }
+                        if len(list) > 20 {
+                                list = list[:20]
+                        }
+                        if len(list) > 0 {
+                                redis.Put("other", redis_baseKeys, list, 8*60*60)
+                                redis.Put("other", "CRIndex_"+ptst.PCOR+"_"+ptst.UserId, "CR", 8*60*60)
+                        }
+                        return Result{Data: map[string]interface{}{
+                                "list": list,
+                        }}
+                }
+                return Result{Data: nil}
+        }()
+        this.ServeJson(r)
 }
 
 // 移除我的潜在对手
 func (this *Analysis) RMyRivals() {
-	defer qutil.Catch()
-	var regMap = Result{
-		Data:       []map[string]interface{}{},
-		Error_code: Error_code,
-		Error_msg:  "",
-	}
-	if this.Method() == METHOD {
-		entId := util.DecodeId(this.GetString("entId"))
-		userId, _ := this.GetSession("userId").(string)
-		if userId != "" {
-			main_userId, _, _ := util.MainUserId(userId, "", 0)
-			if entId != "" && main_userId != "" {
-				ok := db.Mgo.Update(C_Member, `{"userid":"`+main_userId+`"}`, bson.M{
-					"$addToSet": bson.M{
-						"outMyRivalIds": entId,
-					},
-				}, true, false)
-				regMap.Data = map[string]interface{}{
-					"success": ok,
-				}
-				go func(userId string) {
-					//首页潜在竞争对手缓存
-					redis.Del("other", fmt.Sprintf("CRIndex_R_%s", userId))
-				}(main_userId)
-			}
-		} 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 {
+                entId := util.DecodeId(this.GetString("entId"))
+                userId, _ := this.GetSession("userId").(string)
+                if userId != "" {
+                        main_userId, _, _ := util.MainUserId(this.Session())
+                        if entId != "" && main_userId != "" {
+                                ok := db.Mgo.Update(C_Member, `{"userid":"`+main_userId+`"}`, bson.M{
+                                        "$addToSet": bson.M{
+                                                "outMyRivalIds": entId,
+                                        },
+                                }, true, false)
+                                regMap.Data = map[string]interface{}{
+                                        "success": ok,
+                                }
+                                go func(userId string) {
+                                        //首页潜在竞争对手缓存
+                                        redis.Del("other", fmt.Sprintf("CRIndex_R_%s", userId))
+                                }(main_userId)
+                        }
+                } 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) CsORRsList() {
-	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 entName = "" //企业名称
-		//接受前端参数
-		getRes := new(SelectC)
-		if string(this.Body()) != "" {
-			//接收参数
-			json.Unmarshal(this.Body(), &getRes)
-		}
-		if getRes.PCOR != "" {
-			main_userId, _, _ := util.MainUserId(userId, "", 0)
-			// getRes.Searchbool -- 0:默认查询 1:条件查询
-			// log.Println(len(getRes.Area), "----", getRes.BuyerClass, "----", getRes.Business_scope, "--", getRes.Searchbool)
-			if getRes.Searchbool == 0 && (len(getRes.Area) == 0 || len(getRes.BuyerClass) == 0 || len(getRes.Business_scope) == 0) {
-				//查库获得大会员用户的信息
-				getRes.Area, getRes.BuyerClass, getRes.Business_scope = GetUserInfo(main_userId)
-			} else {
-				getRes.Business_scope = BuyerContentStruct(getRes.Business_scope)
-			}
-			//查库获得大会员用户的行业信息
-			entInfo, ok := db.Mgo.FindOneByField(C_Member, `{"userid":"`+main_userId+`"}`, `{"entname":1,"industry":1}`)
-			if ok && entInfo != nil {
-				if (*entInfo)["entname"] != nil {
-					entName = (*entInfo)["entname"].(string)
-				}
-				if len(getRes.Industry) == 0 && (*entInfo)["industry"] != nil {
-					industryMap := *qutil.ObjToMap((*entInfo)["industry"].(map[string]interface{})) //行业
-					for k, v := range industryMap {
-						idst := qutil.ObjArrToStringArr(v.([]interface{}))
-						if len(idst) > 0 {
-							for _, vv := range idst {
-								getRes.Industry = append(getRes.Industry, k+"_"+vv)
-							}
-						}
-					}
-				}
-			}
-			//
-			if entName == "" {
-				log.Println("大会员初始化 企业名称有误-", userId, main_userId)
-			}
-			//userInfo, ok := db.Mgo.FindById("user", main_userId, nil)
-			userInfo := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
+        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 entName = "" //企业名称
+                //接受前端参数
+                getRes := new(SelectC)
+                if string(this.Body()) != "" {
+                        //接收参数
+                        json.Unmarshal(this.Body(), &getRes)
+                }
+                if getRes.PCOR != "" {
+                        main_userId, _, _ := util.MainUserId(this.Session())
+                        // getRes.Searchbool -- 0:默认查询 1:条件查询
+                        // log.Println(len(getRes.Area), "----", getRes.BuyerClass, "----", getRes.Business_scope, "--", getRes.Searchbool)
+                        if getRes.Searchbool == 0 && (len(getRes.Area) == 0 || len(getRes.BuyerClass) == 0 || len(getRes.Business_scope) == 0) {
+                                //查库获得大会员用户的信息
+                                getRes.Area, getRes.BuyerClass, getRes.Business_scope = GetUserInfo(this.Session())
+                        } else {
+                                getRes.Business_scope = BuyerContentStruct(getRes.Business_scope)
+                        }
+                        //查库获得大会员用户的行业信息
+                        entInfo, ok := db.Mgo.FindOneByField(C_Member, `{"userid":"`+main_userId+`"}`, `{"entname":1,"industry":1}`)
+                        if ok && entInfo != nil {
+                                if (*entInfo)["entname"] != nil {
+                                        entName = (*entInfo)["entname"].(string)
+                                }
+                                if len(getRes.Industry) == 0 && (*entInfo)["industry"] != nil {
+                                        industryMap := *qutil.ObjToMap((*entInfo)["industry"].(map[string]interface{})) //行业
+                                        for k, v := range industryMap {
+                                                idst := qutil.ObjArrToStringArr(v.([]interface{}))
+                                                if len(idst) > 0 {
+                                                        for _, vv := range idst {
+                                                                getRes.Industry = append(getRes.Industry, k+"_"+vv)
+                                                        }
+                                                }
+                                        }
+                                }
+                        }
+                        //
+                        if entName == "" {
+                                log.Println("大会员初始化 企业名称有误-", userId, main_userId)
+                        }
+                        //userInfo, ok := db.Mgo.FindById(C_User, main_userId, nil)
+                        userInfo := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
 
-			if userInfo != nil {
-				var isTrial = userInfo.Status == 4
-				var c_limitcount = 5
-				var r_limitcount = 5
-				if getRes.ServiceId == 0 {
-					getRes.ServiceId = 7 //潜在客户-潜在伙伴/竞争对手
-				}
-				//客户
-				if getRes.PCOR == "C" {
-					potComQ := PCQuery(getRes.Area, getRes.Industry, getRes.BuyerClass, getRes.Business_scope, getRes.Sort_no, getRes.PCOR)
-					var list []*PTComs
-					if config.Config.PotentialSwitch {
-						list = CustomersInfo(main_userId, entName, potComQ, getRes.PCOR)
-					} else {
-						list = getPCostomers(main_userId, entName, potComQ, getRes.PCOR)
-					}
-					surpluscount := -1
-					//排序
-					if len(list) > 0 && config.Config.PotentialSwitch {
-						if getRes.Sort_no == 0 {
-							sort.Slice(list, func(i, j int) bool {
-								return list[i].PNCount > list[j].PNCount
-							})
-						} else {
-							sort.Slice(list, func(i, j int) bool {
-								return list[i].Budget > list[j].Budget
-							})
-						}
-					} //剩余数量
-					if isTrial {
-						c_limitcount = getBAmountInfo(main_userId, getRes.ServiceId)
-						if len(list) > c_limitcount {
-							surpluscount = len(list) - c_limitcount
-							list = list[:c_limitcount]
-						}
-					}
-					if len(list) > 100 {
-						list = list[:100]
-					}
-					regMap.Data = map[string]interface{}{
-						"list":         list,
-						"surpluscount": surpluscount,
-						"param": map[string]interface{}{
-							"area":           getRes.Area,
-							"industry":       getRes.Industry,
-							"buyerClass":     getRes.BuyerClass,
-							"business_scope": getRes.Business_scope,
-						},
-					}
-				} else if getRes.PCOR == "R" {
-					potRivQ := PCQuery(getRes.Area, getRes.Industry, getRes.BuyerClass, getRes.Business_scope, getRes.Sort_no, getRes.PCOR)
-					var list []*PTComs
-					if config.Config.PotentialSwitch {
-						list = PRivals(main_userId, potRivQ, getRes.PCOR)
-					} else {
-						list = getPRivals(main_userId, potRivQ, getRes.PCOR)
-					}
-					//排序
-					if len(list) > 0 && config.Config.PotentialSwitch {
-						if getRes.Sort_no == 0 {
-							sort.Slice(list, func(i, j int) bool {
-								return list[i].PNCount > list[j].PNCount
-							})
-						} else {
-							sort.Slice(list, func(i, j int) bool {
-								return list[i].Budget > list[j].Budget
-							})
-						}
-					}
-					surpluscount := -1 //剩余数量
-					if isTrial {
-						r_limitcount = getBAmountInfo(main_userId, getRes.ServiceId)
-						if len(list) > r_limitcount {
-							surpluscount = len(list) - r_limitcount
-							list = list[:r_limitcount]
-						}
-					}
+                        if userInfo != nil {
+                                var isTrial = userInfo.Status == 4
+                                var c_limitcount = 5
+                                var r_limitcount = 5
+                                if getRes.ServiceId == 0 {
+                                        getRes.ServiceId = 7 //潜在客户-潜在伙伴/竞争对手
+                                }
+                                //客户
+                                if getRes.PCOR == "C" {
+                                        potComQ := PCQuery(getRes.Area, getRes.Industry, getRes.BuyerClass, getRes.Business_scope, getRes.Sort_no, getRes.PCOR)
+                                        var list []*PTComs
+                                        if config.Config.PotentialSwitch {
+                                                list = CustomersInfo(main_userId, entName, potComQ, getRes.PCOR)
+                                        } else {
+                                                list = getPCostomers(main_userId, entName, potComQ, getRes.PCOR)
+                                        }
+                                        surpluscount := -1
+                                        //排序
+                                        if len(list) > 0 && config.Config.PotentialSwitch {
+                                                if getRes.Sort_no == 0 {
+                                                        sort.Slice(list, func(i, j int) bool {
+                                                                return list[i].PNCount > list[j].PNCount
+                                                        })
+                                                } else {
+                                                        sort.Slice(list, func(i, j int) bool {
+                                                                return list[i].Budget > list[j].Budget
+                                                        })
+                                                }
+                                        } //剩余数量
+                                        if isTrial {
+                                                c_limitcount = getBAmountInfo(main_userId, getRes.ServiceId)
+                                                if len(list) > c_limitcount {
+                                                        surpluscount = len(list) - c_limitcount
+                                                        list = list[:c_limitcount]
+                                                }
+                                        }
+                                        if len(list) > 100 {
+                                                list = list[:100]
+                                        }
+                                        regMap.Data = map[string]interface{}{
+                                                "list":         list,
+                                                "surpluscount": surpluscount,
+                                                "param": map[string]interface{}{
+                                                        "area":           getRes.Area,
+                                                        "industry":       getRes.Industry,
+                                                        "buyerClass":     getRes.BuyerClass,
+                                                        "business_scope": getRes.Business_scope,
+                                                },
+                                        }
+                                } else if getRes.PCOR == "R" {
+                                        potRivQ := PCQuery(getRes.Area, getRes.Industry, getRes.BuyerClass, getRes.Business_scope, getRes.Sort_no, getRes.PCOR)
+                                        var list []*PTComs
+                                        if config.Config.PotentialSwitch {
+                                                list = PRivals(main_userId, potRivQ, getRes.PCOR)
+                                        } else {
+                                                list = getPRivals(main_userId, potRivQ, getRes.PCOR)
+                                        }
+                                        //排序
+                                        if len(list) > 0 && config.Config.PotentialSwitch {
+                                                if getRes.Sort_no == 0 {
+                                                        sort.Slice(list, func(i, j int) bool {
+                                                                return list[i].PNCount > list[j].PNCount
+                                                        })
+                                                } else {
+                                                        sort.Slice(list, func(i, j int) bool {
+                                                                return list[i].Budget > list[j].Budget
+                                                        })
+                                                }
+                                        }
+                                        surpluscount := -1 //剩余数量
+                                        if isTrial {
+                                                r_limitcount = getBAmountInfo(main_userId, getRes.ServiceId)
+                                                if len(list) > r_limitcount {
+                                                        surpluscount = len(list) - r_limitcount
+                                                        list = list[:r_limitcount]
+                                                }
+                                        }
 
-					if len(list) > 100 {
-						list = list[:100]
-					}
-					regMap.Data = map[string]interface{}{
-						"list":         list,
-						"surpluscount": surpluscount,
-						"param": map[string]interface{}{
-							"area":           getRes.Area,
-							"industry":       getRes.Industry,
-							"buyerClass":     getRes.BuyerClass,
-							"business_scope": getRes.Business_scope,
-						},
-					}
-				}
-			} else {
-				regMap.Error_code = Error_code_1003
-				regMap.Error_msg = Error_msg_1003
-			}
-			//记录查询日志
-			go savePOTLogs(userId, main_userId, entName, getRes.Area, getRes.BuyerClass, getRes.Industry, getRes.Business_scope, getRes.Sort_no, getRes.PCOR, regMap)
+                                        if len(list) > 100 {
+                                                list = list[:100]
+                                        }
+                                        regMap.Data = map[string]interface{}{
+                                                "list":         list,
+                                                "surpluscount": surpluscount,
+                                                "param": map[string]interface{}{
+                                                        "area":           getRes.Area,
+                                                        "industry":       getRes.Industry,
+                                                        "buyerClass":     getRes.BuyerClass,
+                                                        "business_scope": getRes.Business_scope,
+                                                },
+                                        }
+                                }
+                        } else {
+                                regMap.Error_code = Error_code_1003
+                                regMap.Error_msg = Error_msg_1003
+                        }
+                        //记录查询日志
+                        go savePOTLogs(userId, main_userId, entName, getRes.Area, getRes.BuyerClass, getRes.Industry, getRes.Business_scope, getRes.Sort_no, getRes.PCOR, regMap)
 
-		} 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)
+                } 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 GetUserInfo(main_userId string) (map[string]interface{}, []string, []ViewKeyWord) {
-	var (
-		query *map[string]interface{}
-		ok    bool
-	)
-	if query, ok = db.Mgo.FindById("user", main_userId, `{"o_member_jy":1}`); !ok && (*query)["o_member_jy"] == nil {
-		return nil, []string{}, nil
-	}
-	o_member_jy, _ := (*query)["o_member_jy"].(map[string]interface{})
-	if o_member_jy["a_items"] == nil && o_member_jy["a_buyerclass"] == nil && o_member_jy["a_infotype"] == nil && o_member_jy["o_area"] == nil {
-		return nil, []string{}, nil
-	}
-	a_items := []interface{}{}
-	if o_member_jy["a_items"] != nil {
-		a_items = o_member_jy["a_items"].([]interface{})
-	}
-	a_buyerclass := []interface{}{}
-	if o_member_jy["a_buyerclass"] != nil {
-		a_buyerclass = o_member_jy["a_buyerclass"].([]interface{})
-	}
-	if len(a_buyerclass) > 0 && qutil.IntAllDef(o_member_jy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
-		a_buyerclass = append(a_buyerclass, "其它")
-	}
-	o_area := map[string]interface{}{}
-	if o_member_jy["o_area"] != nil {
-		o_area = o_member_jy["o_area"].(map[string]interface{})
-	}
-	return o_area, qutil.ObjArrToStringArr(a_buyerclass), getKeyWordArrFromDbResult(a_items, "", -1)
+func GetUserInfo(session *httpsession.Session) (map[string]interface{}, []string, []ViewKeyWord) {
+        var (
+                query *map[string]interface{}
+        )
+        if query := jy.GetSubScribeInfo(session, db.Mgo, "m", "10000"); query == nil {
+                return nil, []string{}, nil
+        }
+        o_member_jy, _ := (*query)["o_member_jy"].(map[string]interface{})
+        if o_member_jy["a_items"] == nil && o_member_jy["a_buyerclass"] == nil && o_member_jy["a_infotype"] == nil && o_member_jy["o_area"] == nil {
+                return nil, []string{}, nil
+        }
+        a_items := []interface{}{}
+        if o_member_jy["a_items"] != nil {
+                a_items = o_member_jy["a_items"].([]interface{})
+        }
+        a_buyerclass := []interface{}{}
+        if o_member_jy["a_buyerclass"] != nil {
+                a_buyerclass = o_member_jy["a_buyerclass"].([]interface{})
+        }
+        if len(a_buyerclass) > 0 && qutil.IntAllDef(o_member_jy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
+                a_buyerclass = append(a_buyerclass, "其它")
+        }
+        o_area := map[string]interface{}{}
+        if o_member_jy["o_area"] != nil {
+                o_area = o_member_jy["o_area"].(map[string]interface{})
+        }
+        return o_area, qutil.ObjArrToStringArr(a_buyerclass), getKeyWordArrFromDbResult(a_items, "", -1)
 }
 
 // 关键词 附加词 排除词
 func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
-	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
-		}
-		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)
-			}
-		}
-	}
-	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
+                }
+                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)
+                        }
+                }
+        }
+        return
 }
 
 // 记录查询日志
 func savePOTLogs(userId, main_userId, entName string, area map[string]interface{}, buyerClass, industry []string, business_scope []ViewKeyWord, sort_no int, pcor string, regMap Result) {
-	var saveData = map[string]interface{}{
-		"userId":         userId,
-		"main_userId":    main_userId,
-		"entName":        entName,
-		"area":           area,
-		"buyerclass":     buyerClass,
-		"industry":       industry,
-		"business_scope": business_scope,
-		"sort_no":        sort_no,
-		"pcor":           pcor,
-		"regMap":         regMap,
-		"createdate":     time.Now().Unix(),
-	}
-	db.Mgo_Log.Save(C_PTLog, saveData)
+        var saveData = map[string]interface{}{
+                "userId":         userId,
+                "main_userId":    main_userId,
+                "entName":        entName,
+                "area":           area,
+                "buyerclass":     buyerClass,
+                "industry":       industry,
+                "business_scope": business_scope,
+                "sort_no":        sort_no,
+                "pcor":           pcor,
+                "regMap":         regMap,
+                "createdate":     time.Now().Unix(),
+        }
+        db.Mgo_Log.Save(C_PTLog, saveData)
 }
 
 // 潜在竞争对手
 func getPRivals(userId string, potRivQ, pcor string) []*PTComs {
-	var regMap = []*PTComs{}
-	//我关注的企业
-	MyFollowEnts := getMyFollowEnts(userId)
-	//非我的潜在竞争对手
-	OutLMyRivals := gerOutLMyRivals(userId)
-	aggs, _ := GetAggs(P_INDEX, P_TYPE, potRivQ)
-	if aggs != nil {
-		if aggsMap_g, ok := aggs.Children("group_field"); ok {
-			var aggsMap []map[string]interface{}
-			bs, _ := aggsMap_g.Aggregations["buckets"].MarshalJSON()
-			if len(bs) > 0 {
-				json.Unmarshal(bs, &aggsMap)
-				if len(aggsMap) > 0 {
-					regMap = analysisDataByWinner(aggsMap, MyFollowEnts, OutLMyRivals, pcor)
-				}
-			}
-		}
-	}
-	return regMap
+        var regMap = []*PTComs{}
+        //我关注的企业
+        MyFollowEnts := getMyFollowEnts(userId)
+        //非我的潜在竞争对手
+        OutLMyRivals := gerOutLMyRivals(userId)
+        aggs, _ := GetAggs(P_INDEX, P_TYPE, potRivQ)
+        if aggs != nil {
+                if aggsMap_g, ok := aggs.Children("group_field"); ok {
+                        var aggsMap []map[string]interface{}
+                        bs, _ := aggsMap_g.Aggregations["buckets"].MarshalJSON()
+                        if len(bs) > 0 {
+                                json.Unmarshal(bs, &aggsMap)
+                                if len(aggsMap) > 0 {
+                                        regMap = analysisDataByWinner(aggsMap, MyFollowEnts, OutLMyRivals, pcor)
+                                }
+                        }
+                }
+        }
+        return regMap
 }
 
 // 非我的潜在竞争对手
 func gerOutLMyRivals(userId string) map[string]interface{} {
-	var OutLMyRivals = map[string]interface{}{}
-	entData, ok := db.Mgo.FindOne(C_Member, `{"userid":"`+userId+`"}`)
-	if ok && entData != nil && (*entData)["outMyRivalIds"] != nil {
-		for _, v := range qutil.ObjArrToStringArr((*entData)["outMyRivalIds"].([]interface{})) {
-			if v != "" {
-				if v != "" {
-					OutLMyRivals[v] = true
-				}
-			}
-		}
-	}
-	return OutLMyRivals
+        var OutLMyRivals = map[string]interface{}{}
+        entData, ok := db.Mgo.FindOne(C_Member, `{"userid":"`+userId+`"}`)
+        if ok && entData != nil && (*entData)["outMyRivalIds"] != nil {
+                for _, v := range qutil.ObjArrToStringArr((*entData)["outMyRivalIds"].([]interface{})) {
+                        if v != "" {
+                                if v != "" {
+                                        OutLMyRivals[v] = true
+                                }
+                        }
+                }
+        }
+        return OutLMyRivals
 }
 
 // 获取我关注的企业
 func getMyFollowEnts(userId string) map[string]interface{} {
-	var MyEntInfo = map[string]interface{}{}
-	entData := db.Base.Find(C_FEnt, map[string]interface{}{
-		"s_userid": userId,
-	}, "s_entId", "", 0, 500)
-	if entData != nil && len(*entData) > 0 {
-		for _, v := range *entData {
-			s_entId := qutil.ObjToString(v["s_entId"])
-			if s_entId != "" {
-				MyEntInfo[s_entId] = true
-			}
-		}
-	}
-	return MyEntInfo
+        var MyEntInfo = map[string]interface{}{}
+        entData := db.Base.Find(C_FEnt, map[string]interface{}{
+                "s_userid": userId,
+        }, "s_entId", "", 0, 500)
+        if entData != nil && len(*entData) > 0 {
+                for _, v := range *entData {
+                        s_entId := qutil.ObjToString(v["s_entId"])
+                        if s_entId != "" {
+                                MyEntInfo[s_entId] = true
+                        }
+                }
+        }
+        return MyEntInfo
 }
 
 type AggregationsBucket struct {
-	Key       string `json:"key"`
-	Doc_count int    `json:"doc_count"`
-	Count     struct {
-		Value float64 `json:value`
-	} `json:"count"`
+        Key       string `json:"key"`
+        Doc_count int    `json:"doc_count"`
+        Count     struct {
+                Value float64 `json:value`
+        } `json:"count"`
 }
 
 // 潜在竞争对手--new
 func PRivals(userId string, potRivQ, pcor string) []*PTComs {
-	var regMap = []*PTComs{}
-	//我关注的企业
-	MyFollowEnts := getMyFollowEnts(userId)
-	//非我的潜在竞争对手
-	OutLMyRivals := gerOutLMyRivals(userId)
-	aggs, _ := GetAggs(P_INDEX, P_TYPE, potRivQ)
-	if aggs != nil {
-		if aggsMap_g, ok := aggs.Children("group_field"); ok {
-			var aggsMap []*AggregationsBucket
-			bs, _ := aggsMap_g.Aggregations["buckets"].MarshalJSON()
-			if len(bs) > 0 {
-				json.Unmarshal(bs, &aggsMap)
-				if len(aggsMap) > 0 {
-					regMap = analysisData(aggsMap, MyFollowEnts, OutLMyRivals, pcor)
-					//regMap = analysisDataByWinner(aggsMap, MyFollowEnts, OutLMyRivals, pcor)
-				}
-			}
-		}
-	}
-	return regMap
+        var regMap = []*PTComs{}
+        //我关注的企业
+        MyFollowEnts := getMyFollowEnts(userId)
+        //非我的潜在竞争对手
+        OutLMyRivals := gerOutLMyRivals(userId)
+        aggs, _ := GetAggs(P_INDEX, P_TYPE, potRivQ)
+        if aggs != nil {
+                if aggsMap_g, ok := aggs.Children("group_field"); ok {
+                        var aggsMap []*AggregationsBucket
+                        bs, _ := aggsMap_g.Aggregations["buckets"].MarshalJSON()
+                        if len(bs) > 0 {
+                                json.Unmarshal(bs, &aggsMap)
+                                if len(aggsMap) > 0 {
+                                        regMap = analysisData(aggsMap, MyFollowEnts, OutLMyRivals, pcor)
+                                        //regMap = analysisDataByWinner(aggsMap, MyFollowEnts, OutLMyRivals, pcor)
+                                }
+                        }
+                }
+        }
+        return regMap
 }
 
 // 潜在客户--new
 func CustomersInfo(userId, entName string, potComQ, pcor string) []*PTComs {
-	var regMap = []*PTComs{}
-	//获取用户默认企业的客户信息+手动关注的企业信息+不是我的客户信息 此三项都不展示在我的客户列表
-	MyCustomers := getMyCostomers(userId, entName)
-	// log.Println("MyCustomers:", MyCustomers)
-	aggs, _ := GetAggs(P_INDEX, P_TYPE, potComQ)
-	if aggs != nil {
-		if aggs_g, ok := aggs.Children("group_field"); ok {
-			var aggsMap = []*AggregationsBucket{}
-			bs, _ := aggs_g.Aggregations["buckets"].MarshalJSON()
-			if len(bs) > 0 {
-				json.Unmarshal(bs, &aggsMap)
-				if len(aggsMap) > 0 {
-					regMap = analysisData(aggsMap, MyCustomers, nil, pcor)
-				}
-			}
-		}
-	}
-	return regMap
+        var regMap = []*PTComs{}
+        //获取用户默认企业的客户信息+手动关注的企业信息+不是我的客户信息 此三项都不展示在我的客户列表
+        MyCustomers := getMyCostomers(userId, entName)
+        // log.Println("MyCustomers:", MyCustomers)
+        aggs, _ := GetAggs(P_INDEX, P_TYPE, potComQ)
+        if aggs != nil {
+                if aggs_g, ok := aggs.Children("group_field"); ok {
+                        var aggsMap = []*AggregationsBucket{}
+                        bs, _ := aggs_g.Aggregations["buckets"].MarshalJSON()
+                        if len(bs) > 0 {
+                                json.Unmarshal(bs, &aggsMap)
+                                if len(aggsMap) > 0 {
+                                        regMap = analysisData(aggsMap, MyCustomers, nil, pcor)
+                                }
+                        }
+                }
+        }
+        return regMap
 }
 
 // 潜在客户
 func getPCostomers(userId, entName string, potComQ, pcor string) []*PTComs {
-	var regMap = []*PTComs{}
-	//获取用户默认企业的客户信息+手动关注的企业信息+不是我的客户信息 此三项都不展示在我的客户列表
-	MyCustomers := getMyCostomers(userId, entName)
-	// log.Println("MyCustomers:", MyCustomers)
-	aggs, _ := GetAggs(P_INDEX, P_TYPE, potComQ)
-	if aggs != nil {
-		if aggs_g, ok := aggs.Children("group_field"); ok {
-			var aggsMap []map[string]interface{}
-			bs, _ := aggs_g.Aggregations["buckets"].MarshalJSON()
-			if len(bs) > 0 {
-				json.Unmarshal(bs, &aggsMap)
-				if len(aggsMap) > 0 {
-					regMap = analysisDataByBuyer(aggsMap, MyCustomers)
-				}
-			}
-		}
-	}
-	return regMap
+        var regMap = []*PTComs{}
+        //获取用户默认企业的客户信息+手动关注的企业信息+不是我的客户信息 此三项都不展示在我的客户列表
+        MyCustomers := getMyCostomers(userId, entName)
+        // log.Println("MyCustomers:", MyCustomers)
+        aggs, _ := GetAggs(P_INDEX, P_TYPE, potComQ)
+        if aggs != nil {
+                if aggs_g, ok := aggs.Children("group_field"); ok {
+                        var aggsMap []map[string]interface{}
+                        bs, _ := aggs_g.Aggregations["buckets"].MarshalJSON()
+                        if len(bs) > 0 {
+                                json.Unmarshal(bs, &aggsMap)
+                                if len(aggsMap) > 0 {
+                                        regMap = analysisDataByBuyer(aggsMap, MyCustomers)
+                                }
+                        }
+                }
+        }
+        return regMap
 }
 
 // 获取当前我的客户信息(大会员初始化的企业名称+关注的客户名称)
 func getMyCostomers(userId, entName string) map[string]interface{} {
-	MyCS := map[string]interface{}{}
-	r_MyCS := redis.Get("other", "mycostomer_"+userId)
-	if r_MyCS == nil {
-		query_str := getQueryByEntName(entName)
-		aggs, _ := GetAggs(P_INDEX, P_TYPE, query_str)
-		if aggs != nil {
-			if aggs_g, ok := aggs.Children("group_buyer"); ok {
-				var aggsMap []map[string]interface{}
-				bs, _ := aggs_g.Aggregations["buckets"].MarshalJSON()
-				if len(bs) > 0 {
-					json.Unmarshal(bs, &aggsMap)
-					if len(aggsMap) > 0 {
-						for _, v := range aggsMap {
-							if v["key"] != nil {
-								key, _ := v["key"].(string)
-								if key != "" {
-									MyCS[key] = true
-								}
-							}
-						}
-					}
-				}
-			}
-		}
-		if MyCS != nil {
-			redis.Put("other", "mycostomer_"+userId, MyCS, P_redis_time)
-		}
-	} else {
-		MyCS = r_MyCS.(map[string]interface{})
-	}
-	//我关注的客户
-	r_ATTCS := redis.GetStr("other", "customer_list_"+userId)
-	if r_ATTCS == "" {
-		clist, ok := db.Mgo.Find("follow_customer", map[string]interface{}{
-			"userId": userId,
-		}, nil, `{"name":1}`, false, -1, -1)
-		if ok && clist != nil && len(*clist) > 0 {
-			names := []string{}
-			for _, v := range *clist {
-				names = append(names, v["name"].(string))
-			}
-			r_ATTCS = strings.Join(names, ",")
-			redis.Put("other", "customer_list_"+userId, r_ATTCS, 2*60*60)
-		}
-	}
-	for _, v := range strings.Split(r_ATTCS, ",") {
-		if v != "" {
-			MyCS[v] = true
-		}
-	}
-	//不是我的客户
-	r_EXCCS := redis.GetStr("other", "customer_exclude_"+userId)
-	if r_EXCCS == "" {
-		clist, ok := db.Mgo.Find("exclude_customer", map[string]interface{}{
-			"userId": userId,
-		}, nil, `{"name":1}`, false, -1, -1)
-		if ok && clist != nil && len(*clist) > 0 {
-			names := []string{}
-			for _, v := range *clist {
-				names = append(names, v["name"].(string))
-			}
-			r_EXCCS = strings.Join(names, ",")
-			redis.Put("other", "customer_exclude_"+userId, r_EXCCS, 2*60*60)
-		}
-	}
-	for _, v := range strings.Split(r_EXCCS, ",") {
-		if v != "" {
-			MyCS[v] = true
-		}
-	}
-	// log.Println(userId, "---", MyCS)
-	return MyCS
+        MyCS := map[string]interface{}{}
+        r_MyCS := redis.Get("other", "mycostomer_"+userId)
+        if r_MyCS == nil {
+                query_str := getQueryByEntName(entName)
+                aggs, _ := GetAggs(P_INDEX, P_TYPE, query_str)
+                if aggs != nil {
+                        if aggs_g, ok := aggs.Children("group_buyer"); ok {
+                                var aggsMap []map[string]interface{}
+                                bs, _ := aggs_g.Aggregations["buckets"].MarshalJSON()
+                                if len(bs) > 0 {
+                                        json.Unmarshal(bs, &aggsMap)
+                                        if len(aggsMap) > 0 {
+                                                for _, v := range aggsMap {
+                                                        if v["key"] != nil {
+                                                                key, _ := v["key"].(string)
+                                                                if key != "" {
+                                                                        MyCS[key] = true
+                                                                }
+                                                        }
+                                                }
+                                        }
+                                }
+                        }
+                }
+                if MyCS != nil {
+                        redis.Put("other", "mycostomer_"+userId, MyCS, P_redis_time)
+                }
+        } else {
+                MyCS = r_MyCS.(map[string]interface{})
+        }
+        //我关注的客户
+        r_ATTCS := redis.GetStr("other", "customer_list_"+userId)
+        if r_ATTCS == "" {
+                clist, ok := db.Mgo.Find("follow_customer", map[string]interface{}{
+                        "userId": userId,
+                }, nil, `{"name":1}`, false, -1, -1)
+                if ok && clist != nil && len(*clist) > 0 {
+                        names := []string{}
+                        for _, v := range *clist {
+                                names = append(names, v["name"].(string))
+                        }
+                        r_ATTCS = strings.Join(names, ",")
+                        redis.Put("other", "customer_list_"+userId, r_ATTCS, 2*60*60)
+                }
+        }
+        for _, v := range strings.Split(r_ATTCS, ",") {
+                if v != "" {
+                        MyCS[v] = true
+                }
+        }
+        //不是我的客户
+        r_EXCCS := redis.GetStr("other", "customer_exclude_"+userId)
+        if r_EXCCS == "" {
+                clist, ok := db.Mgo.Find("exclude_customer", map[string]interface{}{
+                        "userId": userId,
+                }, nil, `{"name":1}`, false, -1, -1)
+                if ok && clist != nil && len(*clist) > 0 {
+                        names := []string{}
+                        for _, v := range *clist {
+                                names = append(names, v["name"].(string))
+                        }
+                        r_EXCCS = strings.Join(names, ",")
+                        redis.Put("other", "customer_exclude_"+userId, r_EXCCS, 2*60*60)
+                }
+        }
+        for _, v := range strings.Split(r_EXCCS, ",") {
+                if v != "" {
+                        MyCS[v] = true
+                }
+        }
+        // log.Println(userId, "---", MyCS)
+        return MyCS
 }
 
 type PTComs struct {
-	Buyer     string
-	Budget    float64
-	PNCount   int
-	WCity     string
-	WProvince string
-	EntId     string `json:"entId"`
+        Buyer     string
+        Budget    float64
+        PNCount   int
+        WCity     string
+        WProvince string
+        EntId     string `json:"entId"`
 }
 
 type PCInfo struct {
-	Province string //省份
-	City     string //城市
+        Province string //省份
+        City     string //城市
 }
 
 // 采购单位||中标单位
 func analysisData(res []*AggregationsBucket, mycs map[string]interface{}, omyr map[string]interface{}, pcor string) []*PTComs {
-	defer qutil.Catch()
-	var (
-		ADRes_r     []*PTComs
-		entersFifty []string
-		entInfos    []*entity.EnterQYXYInfo
-		wg          = sync.WaitGroup{}
-		wc          = make(chan bool, 10)
-		entMap      = map[string]*AggregationsBucket{}
-		lock        = &sync.Mutex{}
-	)
-	for ak, av := range res {
-		var isContinue = false
-		//清洗无效数据
-		if av.Key == "" || av.Key == "null" {
-			isContinue = true
-		}
-		//清洗无效客户
-		if mycs != nil && mycs[av.Key] != nil {
-			isContinue = true
-		}
-		//排除移除的我的潜在竞争对手
-		if omyr != nil && omyr[av.Key] != nil {
-			isContinue = true
-		}
-		if isContinue {
-			//防止最后一个企业不匹配  直接跳出
-			if len(res) != ak+1 {
-				continue
-			}
-		} else {
-			entMap[av.Key] = av
-			//并发查询企业库是否包含此企业信息
-			entersFifty = append(entersFifty, av.Key)
-		}
-		if len(entersFifty)%50 == 0 || (len(res) == ak+1 && len(entersFifty) > 0) {
-			wg.Add(1)
-			wc <- true
-			go func(entersFifty []string) {
-				defer qutil.Catch()
-				defer func() {
-					wg.Done()
-					<-wc
-				}()
-				entInfo := entity.GetEntInfo(entersFifty, pcor)
-				lock.Lock()
-				defer lock.Unlock()
-				entInfos = append(entInfos, entInfo...)
-			}(entersFifty)
-			entersFifty = []string{}
-		}
-		wg.Wait()
-	}
-	if len(entInfos) > 0 {
-		for _, ev := range entInfos {
-			if (ev.Name != "" && entMap[ev.Name] != nil) || (len([]rune(ev.Id)) > 12 && entMap[ev.Id] != nil) {
-				var budget float64 = 0
-				pnCount := 0
-				if entMap[ev.Name] != nil {
-					budget = entMap[ev.Name].Count.Value
-					pnCount = entMap[ev.Name].Doc_count
-				}
-				if entMap[ev.Id] != nil {
-					budget = entMap[ev.Id].Count.Value
-					pnCount = entMap[ev.Id].Doc_count
-				}
-				ADRes_r = append(ADRes_r, &PTComs{
-					Budget:    budget,
-					PNCount:   pnCount,
-					Buyer:     ev.Name,
-					WCity:     ev.City,
-					WProvince: ev.Area,
-					EntId:     util.EncodeId(ev.Id),
-				})
-			}
-		}
-	}
-	return ADRes_r
+        defer qutil.Catch()
+        var (
+                ADRes_r     []*PTComs
+                entersFifty []string
+                entInfos    []*entity.EnterQYXYInfo
+                wg          = sync.WaitGroup{}
+                wc          = make(chan bool, 10)
+                entMap      = map[string]*AggregationsBucket{}
+                lock        = &sync.Mutex{}
+        )
+        for ak, av := range res {
+                var isContinue = false
+                //清洗无效数据
+                if av.Key == "" || av.Key == "null" {
+                        isContinue = true
+                }
+                //清洗无效客户
+                if mycs != nil && mycs[av.Key] != nil {
+                        isContinue = true
+                }
+                //排除移除的我的潜在竞争对手
+                if omyr != nil && omyr[av.Key] != nil {
+                        isContinue = true
+                }
+                if isContinue {
+                        //防止最后一个企业不匹配  直接跳出
+                        if len(res) != ak+1 {
+                                continue
+                        }
+                } else {
+                        entMap[av.Key] = av
+                        //并发查询企业库是否包含此企业信息
+                        entersFifty = append(entersFifty, av.Key)
+                }
+                if len(entersFifty)%50 == 0 || (len(res) == ak+1 && len(entersFifty) > 0) {
+                        wg.Add(1)
+                        wc <- true
+                        go func(entersFifty []string) {
+                                defer qutil.Catch()
+                                defer func() {
+                                        wg.Done()
+                                        <-wc
+                                }()
+                                entInfo := entity.GetEntInfo(entersFifty, pcor)
+                                lock.Lock()
+                                defer lock.Unlock()
+                                entInfos = append(entInfos, entInfo...)
+                        }(entersFifty)
+                        entersFifty = []string{}
+                }
+                wg.Wait()
+        }
+        if len(entInfos) > 0 {
+                for _, ev := range entInfos {
+                        if (ev.Name != "" && entMap[ev.Name] != nil) || (len([]rune(ev.Id)) > 12 && entMap[ev.Id] != nil) {
+                                var budget float64 = 0
+                                pnCount := 0
+                                if entMap[ev.Name] != nil {
+                                        budget = entMap[ev.Name].Count.Value
+                                        pnCount = entMap[ev.Name].Doc_count
+                                }
+                                if entMap[ev.Id] != nil {
+                                        budget = entMap[ev.Id].Count.Value
+                                        pnCount = entMap[ev.Id].Doc_count
+                                }
+                                ADRes_r = append(ADRes_r, &PTComs{
+                                        Budget:    budget,
+                                        PNCount:   pnCount,
+                                        Buyer:     ev.Name,
+                                        WCity:     ev.City,
+                                        WProvince: ev.Area,
+                                        EntId:     util.EncodeId(ev.Id),
+                                })
+                        }
+                }
+        }
+        return ADRes_r
 }
 
 // 采购单位
 func analysisDataByBuyer(res []map[string]interface{}, mycs map[string]interface{}) []*PTComs {
-	defer qutil.Catch()
-	var ADRes = []*PTComs{}
-	var ADRes_r = []*PTComs{}
-	var enters = []string{}
-	var EnterPOC = map[string]PCInfo{}
-	var EnterQYXY = []*entity.EnterQYXYInfo{} //企业信用是否有此企业数据
-	var EnterQYXY_map = map[string]string{}   //企业信用是否有此企业数据
-	var wg sync.WaitGroup
-	var wc = make(chan bool, 10)
-	var wl = &sync.Mutex{}
-	var entersFifty = []string{}
-	for k, v := range res {
-		var isContinue = false
-		var key_val = qutil.ObjToString(v["key"]) //采购单位
-		if key_val == "" || key_val == "null" {
-			isContinue = true
-		}
-		//排除我的客户 和 我的企业情报数据
-		if !isContinue && mycs != nil && mycs[key_val] != nil {
-			isContinue = true
-		}
-		if isContinue {
-			//防止最后一个企业不匹配  直接跳出
-			if len(res) == k+1 && len(entersFifty) > 0 {
-				wg.Add(1)
-				wc <- true
-				go func(entersFifty []string) {
-					defer qutil.Catch()
-					defer func() {
-						wg.Done()
-						<-wc
-					}()
-					entInfo := entity.GetEntInfoByQYXY(entersFifty, "C")
-					wl.Lock()
-					defer wl.Unlock()
-					EnterQYXY = append(EnterQYXY, entInfo...)
-				}(entersFifty)
-				entersFifty = []string{}
-			}
-			continue
-		}
-		var budget_val = qutil.ObjToMap(v["count"])  //预算总金额
-		var pname_val = qutil.IntAll(v["doc_count"]) //项目总数
-		var ptcs = &PTComs{}
-		ptcs.Buyer = key_val
-		ptcs.PNCount = pname_val
-		ptcs.Budget = qutil.Float64All((*budget_val)["value"])
-		ADRes = append(ADRes, ptcs)
-		enters = append(enters, key_val)
-		if (k+1)%20 == 0 || len(res) == k+1 {
-			//获取企业或者采购单位的省份和城市
-			var pcData = entity.GetEntPC(enters) //采购单位
-			if pcData != nil && len(pcData) > 0 {
-				for _, v := range pcData {
-					province := ""
-					city := ""
-					if v["province"] != nil {
-						province = qutil.ObjToString(v["province"])
-					}
-					//排除全国
-					if strings.Contains(province, "全国") {
-						continue
-					}
-					if v["city"] != nil {
-						city = qutil.ObjToString(v["city"])
-					}
-					EnterPOC[v["name"].(string)] = PCInfo{
-						Province: province,
-						City:     city,
-					}
-				}
-			}
-			enters = []string{}
-		}
-		//并发查询企业库是否包含此企业信息
-		entersFifty = append(entersFifty, key_val)
-		if (k+1)%50 == 0 || len(res) == k+1 {
-			wg.Add(1)
-			wc <- true
-			go func(entersFifty []string) {
-				defer func() {
-					wg.Done()
-					<-wc
-					qutil.Catch()
-				}()
-				entInfo := entity.GetEntInfoByQYXY(entersFifty, "C")
-				wl.Lock()
-				defer wl.Unlock()
-				EnterQYXY = append(EnterQYXY, entInfo...)
-			}(entersFifty)
-			entersFifty = []string{}
-		}
-	}
-	wg.Wait()
-	for _, ev := range EnterQYXY {
-		if (*ev).Name != "" {
-			EnterQYXY_map[(*ev).Name] = (*ev).Id
-		}
-	}
-	for _, vv := range ADRes {
-		if EnterQYXY_map[vv.Buyer] != "" {
-			ADRes_r = append(ADRes_r, &PTComs{
-				Budget:    vv.Budget,
-				Buyer:     vv.Buyer,
-				PNCount:   vv.PNCount,
-				WCity:     EnterPOC[vv.Buyer].City,
-				WProvince: EnterPOC[vv.Buyer].Province,
-			})
-		}
-	}
-	return ADRes_r
+        defer qutil.Catch()
+        var ADRes = []*PTComs{}
+        var ADRes_r = []*PTComs{}
+        var enters = []string{}
+        var EnterPOC = map[string]PCInfo{}
+        var EnterQYXY = []*entity.EnterQYXYInfo{} //企业信用是否有此企业数据
+        var EnterQYXY_map = map[string]string{}   //企业信用是否有此企业数据
+        var wg sync.WaitGroup
+        var wc = make(chan bool, 10)
+        var wl = &sync.Mutex{}
+        var entersFifty = []string{}
+        for k, v := range res {
+                var isContinue = false
+                var key_val = qutil.ObjToString(v["key"]) //采购单位
+                if key_val == "" || key_val == "null" {
+                        isContinue = true
+                }
+                //排除我的客户 和 我的企业情报数据
+                if !isContinue && mycs != nil && mycs[key_val] != nil {
+                        isContinue = true
+                }
+                if isContinue {
+                        //防止最后一个企业不匹配  直接跳出
+                        if len(res) == k+1 && len(entersFifty) > 0 {
+                                wg.Add(1)
+                                wc <- true
+                                go func(entersFifty []string) {
+                                        defer qutil.Catch()
+                                        defer func() {
+                                                wg.Done()
+                                                <-wc
+                                        }()
+                                        entInfo := entity.GetEntInfoByQYXY(entersFifty, "C")
+                                        wl.Lock()
+                                        defer wl.Unlock()
+                                        EnterQYXY = append(EnterQYXY, entInfo...)
+                                }(entersFifty)
+                                entersFifty = []string{}
+                        }
+                        continue
+                }
+                var budget_val = qutil.ObjToMap(v["count"])  //预算总金额
+                var pname_val = qutil.IntAll(v["doc_count"]) //项目总数
+                var ptcs = &PTComs{}
+                ptcs.Buyer = key_val
+                ptcs.PNCount = pname_val
+                ptcs.Budget = qutil.Float64All((*budget_val)["value"])
+                ADRes = append(ADRes, ptcs)
+                enters = append(enters, key_val)
+                if (k+1)%20 == 0 || len(res) == k+1 {
+                        //获取企业或者采购单位的省份和城市
+                        var pcData = entity.GetEntPC(enters) //采购单位
+                        if pcData != nil && len(pcData) > 0 {
+                                for _, v := range pcData {
+                                        province := ""
+                                        city := ""
+                                        if v["province"] != nil {
+                                                province = qutil.ObjToString(v["province"])
+                                        }
+                                        //排除全国
+                                        if strings.Contains(province, "全国") {
+                                                continue
+                                        }
+                                        if v["city"] != nil {
+                                                city = qutil.ObjToString(v["city"])
+                                        }
+                                        EnterPOC[v["name"].(string)] = PCInfo{
+                                                Province: province,
+                                                City:     city,
+                                        }
+                                }
+                        }
+                        enters = []string{}
+                }
+                //并发查询企业库是否包含此企业信息
+                entersFifty = append(entersFifty, key_val)
+                if (k+1)%50 == 0 || len(res) == k+1 {
+                        wg.Add(1)
+                        wc <- true
+                        go func(entersFifty []string) {
+                                defer func() {
+                                        wg.Done()
+                                        <-wc
+                                        qutil.Catch()
+                                }()
+                                entInfo := entity.GetEntInfoByQYXY(entersFifty, "C")
+                                wl.Lock()
+                                defer wl.Unlock()
+                                EnterQYXY = append(EnterQYXY, entInfo...)
+                        }(entersFifty)
+                        entersFifty = []string{}
+                }
+        }
+        wg.Wait()
+        for _, ev := range EnterQYXY {
+                if (*ev).Name != "" {
+                        EnterQYXY_map[(*ev).Name] = (*ev).Id
+                }
+        }
+        for _, vv := range ADRes {
+                if EnterQYXY_map[vv.Buyer] != "" {
+                        ADRes_r = append(ADRes_r, &PTComs{
+                                Budget:    vv.Budget,
+                                Buyer:     vv.Buyer,
+                                PNCount:   vv.PNCount,
+                                WCity:     EnterPOC[vv.Buyer].City,
+                                WProvince: EnterPOC[vv.Buyer].Province,
+                        })
+                }
+        }
+        return ADRes_r
 }
 
 // 中标单位
 func analysisDataByWinner(res []map[string]interface{}, mycs map[string]interface{}, omyr map[string]interface{}, pcor string) []*PTComs {
-	defer qutil.Catch()
-	var ADRes = []*PTComs{}
-	var ADRes_r = []*PTComs{}
-	var enters = []string{}
-	var EnterQYXY = []*entity.EnterQYXYInfo{}             //企业信用是否有此企业数据
-	var EnterQYXY_map = map[string]entity.EnterQYXYInfo{} //企业信用是否有此企业数据
-	var wg sync.WaitGroup
-	var wc = make(chan bool, 10)
-	var wl = &sync.Mutex{}
-	var entersFifty = []string{}
-	for k, v := range res {
-		var isContinue = false
-		var key_val = qutil.ObjToString(v["key"]) //中标单位
-		if key_val == "" || key_val == "null" {
-			isContinue = true
-		}
-		//排除我的客户 和 我的企业情报数据
-		if !isContinue && mycs != nil && mycs[key_val] != nil {
-			isContinue = true
-		}
-		//排除移除的我的潜在竞争对手
-		if !isContinue && omyr != nil && omyr[key_val] != nil {
-			isContinue = true
-		}
-		if isContinue {
-			//防止最后一个企业不匹配  直接跳出
-			if len(res) == k+1 && len(entersFifty) > 0 {
-				wg.Add(1)
-				wc <- true
-				go func(entersFifty []string, pcor string) {
-					defer qutil.Catch()
-					defer func() {
-						wg.Done()
-						<-wc
-					}()
-					entInfo := entity.GetEntInfoByQYXY(entersFifty, pcor)
-					wl.Lock()
-					defer wl.Unlock()
-					EnterQYXY = append(EnterQYXY, entInfo...)
-				}(entersFifty, pcor)
-				entersFifty = []string{}
-			}
-			continue
-		}
-		var budget_val = qutil.ObjToMap(v["count"])  //预算总金额
-		var pname_val = qutil.IntAll(v["doc_count"]) //项目总数
-		var ptcs = &PTComs{}
-		ptcs.EntId = key_val
-		ptcs.PNCount = pname_val
-		ptcs.Budget = qutil.Float64All((*budget_val)["value"])
-		ADRes = append(ADRes, ptcs)
-		enters = append(enters, key_val)
-		//并发查询企业库是否包含此企业信息
-		entersFifty = append(entersFifty, key_val)
-		if (k+1)%50 == 0 || len(res) == k+1 {
-			wg.Add(1)
-			wc <- true
-			go func(entersFifty []string, pcor string) {
-				defer qutil.Catch()
-				defer func() {
-					wg.Done()
-					<-wc
-				}()
-				entInfo := entity.GetEntInfoByQYXY(entersFifty, pcor)
-				wl.Lock()
-				defer wl.Unlock()
-				EnterQYXY = append(EnterQYXY, entInfo...)
-			}(entersFifty, pcor)
-			entersFifty = []string{}
-		}
-	}
-	wg.Wait()
-	for _, ev := range EnterQYXY {
-		if (*ev).Name != "" {
-			EnterQYXY_map[ev.Id] = entity.EnterQYXYInfo{
-				Id:   (*ev).Id,
-				Name: (*ev).Name,
-				Area: (*ev).Area,
-				City: (*ev).City,
-			}
-		}
-	}
-	for _, vv := range ADRes {
-		if EnterQYXY_map[vv.EntId].Name != "" {
-			ADRes_r = append(ADRes_r, &PTComs{
-				Budget:    vv.Budget,
-				Buyer:     EnterQYXY_map[vv.EntId].Name,
-				PNCount:   vv.PNCount,
-				WCity:     EnterQYXY_map[vv.EntId].City,
-				WProvince: EnterQYXY_map[vv.EntId].Area,
-				EntId:     util.EncodeId(vv.EntId),
-			})
-		}
-	}
-	return ADRes_r
+        defer qutil.Catch()
+        var ADRes = []*PTComs{}
+        var ADRes_r = []*PTComs{}
+        var enters = []string{}
+        var EnterQYXY = []*entity.EnterQYXYInfo{}             //企业信用是否有此企业数据
+        var EnterQYXY_map = map[string]entity.EnterQYXYInfo{} //企业信用是否有此企业数据
+        var wg sync.WaitGroup
+        var wc = make(chan bool, 10)
+        var wl = &sync.Mutex{}
+        var entersFifty = []string{}
+        for k, v := range res {
+                var isContinue = false
+                var key_val = qutil.ObjToString(v["key"]) //中标单位
+                if key_val == "" || key_val == "null" {
+                        isContinue = true
+                }
+                //排除我的客户 和 我的企业情报数据
+                if !isContinue && mycs != nil && mycs[key_val] != nil {
+                        isContinue = true
+                }
+                //排除移除的我的潜在竞争对手
+                if !isContinue && omyr != nil && omyr[key_val] != nil {
+                        isContinue = true
+                }
+                if isContinue {
+                        //防止最后一个企业不匹配  直接跳出
+                        if len(res) == k+1 && len(entersFifty) > 0 {
+                                wg.Add(1)
+                                wc <- true
+                                go func(entersFifty []string, pcor string) {
+                                        defer qutil.Catch()
+                                        defer func() {
+                                                wg.Done()
+                                                <-wc
+                                        }()
+                                        entInfo := entity.GetEntInfoByQYXY(entersFifty, pcor)
+                                        wl.Lock()
+                                        defer wl.Unlock()
+                                        EnterQYXY = append(EnterQYXY, entInfo...)
+                                }(entersFifty, pcor)
+                                entersFifty = []string{}
+                        }
+                        continue
+                }
+                var budget_val = qutil.ObjToMap(v["count"])  //预算总金额
+                var pname_val = qutil.IntAll(v["doc_count"]) //项目总数
+                var ptcs = &PTComs{}
+                ptcs.EntId = key_val
+                ptcs.PNCount = pname_val
+                ptcs.Budget = qutil.Float64All((*budget_val)["value"])
+                ADRes = append(ADRes, ptcs)
+                enters = append(enters, key_val)
+                //并发查询企业库是否包含此企业信息
+                entersFifty = append(entersFifty, key_val)
+                if (k+1)%50 == 0 || len(res) == k+1 {
+                        wg.Add(1)
+                        wc <- true
+                        go func(entersFifty []string, pcor string) {
+                                defer qutil.Catch()
+                                defer func() {
+                                        wg.Done()
+                                        <-wc
+                                }()
+                                entInfo := entity.GetEntInfoByQYXY(entersFifty, pcor)
+                                wl.Lock()
+                                defer wl.Unlock()
+                                EnterQYXY = append(EnterQYXY, entInfo...)
+                        }(entersFifty, pcor)
+                        entersFifty = []string{}
+                }
+        }
+        wg.Wait()
+        for _, ev := range EnterQYXY {
+                if (*ev).Name != "" {
+                        EnterQYXY_map[ev.Id] = entity.EnterQYXYInfo{
+                                Id:   (*ev).Id,
+                                Name: (*ev).Name,
+                                Area: (*ev).Area,
+                                City: (*ev).City,
+                        }
+                }
+        }
+        for _, vv := range ADRes {
+                if EnterQYXY_map[vv.EntId].Name != "" {
+                        ADRes_r = append(ADRes_r, &PTComs{
+                                Budget:    vv.Budget,
+                                Buyer:     EnterQYXY_map[vv.EntId].Name,
+                                PNCount:   vv.PNCount,
+                                WCity:     EnterQYXY_map[vv.EntId].City,
+                                WProvince: EnterQYXY_map[vv.EntId].Area,
+                                EntId:     util.EncodeId(vv.EntId),
+                        })
+                }
+        }
+        return ADRes_r
 }

+ 171 - 171
src/jfw/modules/bigmember/src/service/analysis/util.go

@@ -1,241 +1,241 @@
 package analysis
 
 import (
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"bytes"
-	"crypto/hmac"
-	"crypto/sha1"
-	"encoding/base64"
-	"encoding/json"
-	"hash"
-	"io"
-	"jy/src/jfw/modules/bigmember/src/config"
-	"jy/src/jfw/modules/bigmember/src/db"
-	"jy/src/jfw/modules/bigmember/src/util"
-	"net/url"
-	"sort"
-	"strings"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "bytes"
+        "crypto/hmac"
+        "crypto/sha1"
+        "encoding/base64"
+        "encoding/json"
+        "hash"
+        "io"
+        "jy/src/jfw/modules/bigmember/src/config"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "jy/src/jfw/modules/bigmember/src/util"
+        "net/url"
+        "sort"
+        "strings"
 )
 
 type SignStr struct {
-	Key []string
-	Val []string
+        Key []string
+        Val []string
 }
 
 var secret = "20202020"
 
 type SelectC struct {
-	Area           map[string]interface{} //区域
-	BuyerClass     []string               //客户类型(采购单位行业)
-	Industry       []string               //行业分类(信息行业)
-	Business_scope []ViewKeyWord          //业务范围(关键词 附加词 排除词)
-	Sort_no        int                    //排序规则
-	PCOR           string                 //客户还是竞争对手 C:客户;R:对手
-	ServiceId      int                    //大会员服务id
-	Searchbool     int                    //是否是查询
-	IsIndex        bool                   //是否首页查询
-	EntName        string                 //我的企业
-	UserId         string
-	Session        *httpsession.Session
+        Area           map[string]interface{} //区域
+        BuyerClass     []string               //客户类型(采购单位行业)
+        Industry       []string               //行业分类(信息行业)
+        Business_scope []ViewKeyWord          //业务范围(关键词 附加词 排除词)
+        Sort_no        int                    //排序规则
+        PCOR           string                 //客户还是竞争对手 C:客户;R:对手
+        ServiceId      int                    //大会员服务id
+        Searchbool     int                    //是否是查询
+        IsIndex        bool                   //是否首页查询
+        EntName        string                 //我的企业
+        UserId         string
+        Session        *httpsession.Session
 }
 
 // UserStatusChecked 查看权限
 func (this *SelectC) UserStatusChecked() bool {
-	serviceId := 7
-	if this.PCOR == "R" {
-		serviceId = 8
-	}
-	userPower := jy.GetBigVipUserBaseMsg("10000", this.Session, config.Config.Etcd.Key, config.Config.Etcd.Key)
+        serviceId := 7
+        if this.PCOR == "R" {
+                serviceId = 8
+        }
+        userPower := jy.GetBigVipUserBaseMsg("10000", this.Session, config.Config.Etcd.Key, config.Config.Etcd.Key)
 
-	return userPower.Status > 0 && userPower.PowerMap[serviceId]
+        return userPower.Status > 0 && userPower.PowerMap[serviceId]
 }
 
 // Base64Keys 查看数据
 func (this *SelectC) Base64Keys() (baseKey string) {
-	this.UserId, _, _ = util.MainUserId(this.UserId, "", 0)
-	this.Area, this.BuyerClass, this.Business_scope = GetUserInfo(this.UserId)
-	area, _ := json.Marshal(this.Area)
-	//查库获得大会员用户的行业信息
-	industry := []byte{}
-	entInfo, ok := db.Mgo.FindOneByField("member", `{"userid":"`+this.UserId+`"}`, `{"entname":1,"industry":1}`)
-	if ok && entInfo != nil {
-		if (*entInfo)["entname"] != nil {
-			this.EntName = (*entInfo)["entname"].(string)
-		}
-		if (*entInfo)["industry"] != nil {
-			industry, _ = json.Marshal((*entInfo)["industry"])
-		}
-	}
-	var keywordsaggregate = ""
-	for _, v := range this.Business_scope {
-		keywordsaggregate = keywordsaggregate + strings.Join(v.Keyword, "") + strings.Join(v.Appended, "") + strings.Join(v.Exclude, "")
-	}
-	baseKey = GetBase64KeyForPotential(this.UserId, string(area), strings.Join(this.BuyerClass, ""), keywordsaggregate, this.EntName, string(industry)) + "_" + this.PCOR
-	return
+        this.UserId, _, _ = util.MainUserId(this.Session)
+        this.Area, this.BuyerClass, this.Business_scope = GetUserInfo(this.Session)
+        area, _ := json.Marshal(this.Area)
+        //查库获得大会员用户的行业信息
+        industry := []byte{}
+        entInfo, ok := db.Mgo.FindOneByField("member", `{"userid":"`+this.UserId+`"}`, `{"entname":1,"industry":1}`)
+        if ok && entInfo != nil {
+                if (*entInfo)["entname"] != nil {
+                        this.EntName = (*entInfo)["entname"].(string)
+                }
+                if (*entInfo)["industry"] != nil {
+                        industry, _ = json.Marshal((*entInfo)["industry"])
+                }
+        }
+        var keywordsaggregate = ""
+        for _, v := range this.Business_scope {
+                keywordsaggregate = keywordsaggregate + strings.Join(v.Keyword, "") + strings.Join(v.Appended, "") + strings.Join(v.Exclude, "")
+        }
+        baseKey = GetBase64KeyForPotential(this.UserId, string(area), strings.Join(this.BuyerClass, ""), keywordsaggregate, this.EntName, string(industry)) + "_" + this.PCOR
+        return
 }
 
 //
 func GetBase64KeyForPotential(userId, area, buyerClass, business_scope, entName, industry string) (signedStr string) {
-	var param = [][]string{
-		[]string{"userId", userId},
-		[]string{"area", area},
-		[]string{"buyerClass", buyerClass},
-		[]string{"business_scope", business_scope},
-		[]string{"entName", entName},
-		[]string{"industry", industry},
-	}
-	sgt := &SignStr{[]string{}, []string{}}
-	for _, v := range param {
-		sgt.Key = append(sgt.Key, v[0])
-		sgt.Val = append(sgt.Val, v[1])
-	}
-	sgt.Sort()
-	reqStr := sgt.ToString()
-	str := percentEncode(reqStr)
-	h := hmac.New(func() hash.Hash {
-		return sha1.New()
-	}, []byte(secret))
-	io.WriteString(h, str)
-	signedStr = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
-	return
+        var param = [][]string{
+                []string{"userId", userId},
+                []string{"area", area},
+                []string{"buyerClass", buyerClass},
+                []string{"business_scope", business_scope},
+                []string{"entName", entName},
+                []string{"industry", industry},
+        }
+        sgt := &SignStr{[]string{}, []string{}}
+        for _, v := range param {
+                sgt.Key = append(sgt.Key, v[0])
+                sgt.Val = append(sgt.Val, v[1])
+        }
+        sgt.Sort()
+        reqStr := sgt.ToString()
+        str := percentEncode(reqStr)
+        h := hmac.New(func() hash.Hash {
+                return sha1.New()
+        }, []byte(secret))
+        io.WriteString(h, str)
+        signedStr = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
+        return
 }
 
 //
 func GetBase64Key(userId, pname, sid string) (signedStr string) {
-	var param = [][]string{
-		[]string{"userId", userId},
-		[]string{"pname", pname},
-		[]string{"sid", sid},
-	}
-	sgt := &SignStr{[]string{}, []string{}}
-	for _, v := range param {
-		sgt.Key = append(sgt.Key, v[0])
-		sgt.Val = append(sgt.Val, v[1])
-	}
-	sgt.Sort()
-	reqStr := sgt.ToString()
-	str := percentEncode(reqStr)
-	h := hmac.New(func() hash.Hash {
-		return sha1.New()
-	}, []byte(secret))
-	io.WriteString(h, str)
-	signedStr = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
-	return
+        var param = [][]string{
+                []string{"userId", userId},
+                []string{"pname", pname},
+                []string{"sid", sid},
+        }
+        sgt := &SignStr{[]string{}, []string{}}
+        for _, v := range param {
+                sgt.Key = append(sgt.Key, v[0])
+                sgt.Val = append(sgt.Val, v[1])
+        }
+        sgt.Sort()
+        reqStr := sgt.ToString()
+        str := percentEncode(reqStr)
+        h := hmac.New(func() hash.Hash {
+                return sha1.New()
+        }, []byte(secret))
+        io.WriteString(h, str)
+        signedStr = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
+        return
 }
 
 //
 func GetRedisBase64Key(pname, area, city, buyer string, buyerContent []string) (signedStr string) {
-	if len(buyerContent) > 0 {
-		sort.Slice(buyerContent, func(i, j int) bool {
-			return buyerContent[i] < buyerContent[j]
-		})
-	}
-	var param = [][]string{
-		[]string{"pname", pname},
-		[]string{"area", area},
-		[]string{"city", city},
-		[]string{"buyer", buyer},
-		[]string{"buyerContent", strings.Join(buyerContent, ",")},
-	}
-	sgt := &SignStr{[]string{}, []string{}}
-	for _, v := range param {
-		sgt.Key = append(sgt.Key, v[0])
-		sgt.Val = append(sgt.Val, v[1])
-	}
-	sgt.Sort()
-	reqStr := sgt.ToString()
-	str := percentEncode(reqStr)
-	h := hmac.New(func() hash.Hash {
-		return sha1.New()
-	}, []byte(secret))
-	io.WriteString(h, str)
-	signedStr = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
-	return
+        if len(buyerContent) > 0 {
+                sort.Slice(buyerContent, func(i, j int) bool {
+                        return buyerContent[i] < buyerContent[j]
+                })
+        }
+        var param = [][]string{
+                []string{"pname", pname},
+                []string{"area", area},
+                []string{"city", city},
+                []string{"buyer", buyer},
+                []string{"buyerContent", strings.Join(buyerContent, ",")},
+        }
+        sgt := &SignStr{[]string{}, []string{}}
+        for _, v := range param {
+                sgt.Key = append(sgt.Key, v[0])
+                sgt.Val = append(sgt.Val, v[1])
+        }
+        sgt.Sort()
+        reqStr := sgt.ToString()
+        str := percentEncode(reqStr)
+        h := hmac.New(func() hash.Hash {
+                return sha1.New()
+        }, []byte(secret))
+        io.WriteString(h, str)
+        signedStr = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
+        return
 }
 
 var Sp = strings.Replace
 
 func percentEncode(str string) string {
-	str = url.QueryEscape(str)
-	str = Sp(Sp(Sp(str, "+", "%20", -1), "*", "%2A", -1), "&7E", "~", -1)
-	return str
+        str = url.QueryEscape(str)
+        str = Sp(Sp(Sp(str, "+", "%20", -1), "*", "%2A", -1), "&7E", "~", -1)
+        return str
 }
 
 func (this *SignStr) ToString() string {
-	str := ""
-	for k, v := range this.Key {
-		if k > 0 {
-			str += "&"
-		}
-		str += v + "=" + this.Val[k]
-	}
-	return str
+        str := ""
+        for k, v := range this.Key {
+                if k > 0 {
+                        str += "&"
+                }
+                str += v + "=" + this.Val[k]
+        }
+        return str
 }
 
 func (this *SignStr) Sort() {
-	sort.Sort(this)
+        sort.Sort(this)
 }
 
 func (this *SignStr) Len() int {
-	return len(this.Val)
+        return len(this.Val)
 }
 
 func (this *SignStr) Less(i, j int) bool {
-	return bytes.Compare([]byte(this.Key[i]), []byte(this.Key[j])) < 1
+        return bytes.Compare([]byte(this.Key[i]), []byte(this.Key[j])) < 1
 }
 
 func (this *SignStr) Swap(i, j int) {
-	this.Key[i], this.Key[j] = this.Key[j], this.Key[i]
-	this.Val[i], this.Val[j] = this.Val[j], this.Val[i]
+        this.Key[i], this.Key[j] = this.Key[j], this.Key[i]
+        this.Val[i], this.Val[j] = this.Val[j], this.Val[i]
 }
 
 //投标决策分析-类似项目热点中标企业排序
 
 type DecWinnerInfo struct {
-	Key                string    `json:"key"`                //中标企业名称
-	Doc_count          float64   `json:"doc_count"`          //项目数量
-	Total_project      int       `json:"total_project"`      //项目金额
-	Buyer_similar_list BuyerSOOL `json:"buyer_similar_list"` //与采购单位类似项目合作历史
-	Buyer_other_list   BuyerSOOL `json:"buyer_other_list"`   //与采购单位其他项目合作历史
-	Capital            int64     `json:"capital"`            //中标企业注册资本
-	EntId              string    `json:"entId"`              //中标企业加密id
-	Max_jytime         int64     `json:"max_jytime"`         //类似项目中标时间
+        Key                string    `json:"key"`                //中标企业名称
+        Doc_count          float64   `json:"doc_count"`          //项目数量
+        Total_project      int       `json:"total_project"`      //项目金额
+        Buyer_similar_list BuyerSOOL `json:"buyer_similar_list"` //与采购单位类似项目合作历史
+        Buyer_other_list   BuyerSOOL `json:"buyer_other_list"`   //与采购单位其他项目合作历史
+        Capital            int64     `json:"capital"`            //中标企业注册资本
+        EntId              string    `json:"entId"`              //中标企业加密id
+        Max_jytime         int64     `json:"max_jytime"`         //类似项目中标时间
 }
 
 type BuyerSOOL struct {
-	Buyer           string  `json:"buyer"`
-	Doc_count       int     `json:"doc_count"`
-	Total_project   float64 `json:"total_project"`
-	Bid_winner_time string  `json:"bid_winner_time"`
+        Buyer           string  `json:"buyer"`
+        Doc_count       int     `json:"doc_count"`
+        Total_project   float64 `json:"total_project"`
+        Bid_winner_time string  `json:"bid_winner_time"`
 }
 type DWIArray []*DecWinnerInfo
 
 func (this DWIArray) Len() int {
-	return len(this)
+        return len(this)
 }
 
 func (this DWIArray) Swap(i, j int) {
-	this[i], this[j] = this[j], this[i]
+        this[i], this[j] = this[j], this[i]
 }
 func (this DWIArray) Less(i, j int) bool {
-	//类似项目优先
-	if this[i].Buyer_similar_list.Doc_count != this[j].Buyer_similar_list.Doc_count {
-		if this[i].Buyer_similar_list.Doc_count > this[j].Buyer_similar_list.Doc_count {
-			return true
-		}
-		return false
-	}
-	//其它项目次之
-	if this[i].Buyer_other_list.Doc_count != this[j].Buyer_other_list.Doc_count {
-		if this[i].Buyer_other_list.Doc_count > this[j].Buyer_other_list.Doc_count {
-			return true
-		}
-		return false
-	}
-	//项目金额最后
-	if this[i].Doc_count == this[j].Doc_count {
-		return this[i].Total_project > this[j].Total_project
-	}
-	return false
+        //类似项目优先
+        if this[i].Buyer_similar_list.Doc_count != this[j].Buyer_similar_list.Doc_count {
+                if this[i].Buyer_similar_list.Doc_count > this[j].Buyer_similar_list.Doc_count {
+                        return true
+                }
+                return false
+        }
+        //其它项目次之
+        if this[i].Buyer_other_list.Doc_count != this[j].Buyer_other_list.Doc_count {
+                if this[i].Buyer_other_list.Doc_count > this[j].Buyer_other_list.Doc_count {
+                        return true
+                }
+                return false
+        }
+        //项目金额最后
+        if this[i].Doc_count == this[j].Doc_count {
+                return this[i].Total_project > this[j].Total_project
+        }
+        return false
 }

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

@@ -1,103 +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/jybase/mongodb"
-	"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(userid, "", 0)
-		if mainid == userid {
-			isSub = false
-		}
-		//获取用户权限详情
-		power := []int{}
-		bigPower := jy.GetBigVipUserBaseMsg("10000", b.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
-		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("10000", b.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
+                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(mainid)
-		person, ok := db.Mgo.FindOneByField("user", map[string]interface{}{
-			"_id": mongodb.StringTOBsonId(userid),
-		}, `{"i_bidfileCount":1}`)
-		if ok && person != nil && len(*person) > 0 {
-			bidfileCount += qu.IntAll((*person)["i_bidfileCount"])
-		}
-		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, 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 ""
 }
 
 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
 }

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

@@ -124,13 +124,13 @@ func (this *FollowProject) GetPdfDetail() {
 //校验是否是付费用户
 func checkPay(session *httpsession.Session) bool {
 	bigPower := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key)
-	userId := qutil.InterfaceToStr(session.Get("userId"))
+	//userId := qutil.InterfaceToStr(session.Get("userId"))
 	if bigPower.Status > 0 || bigPower.VipStatus > 0 {
 		return true
 	}
 	//校验是否为商机管理用户
-	phone := ""
-	u, ok := db.Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1}`)
+	/*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
@@ -151,8 +151,8 @@ func checkPay(session *httpsession.Session) bool {
 				return true
 			}
 		}
-	}
-	return false
+	}*/
+	return bigPower.IsEntService
 }
 
 func getProjectSimpleData(sid string) (pid string, lasttime int64, err error) {

+ 459 - 458
src/jfw/modules/bigmember/src/service/portrait/memberPortraitAction.go

@@ -1,463 +1,464 @@
 package portrait
 
 import (
-	"fmt"
-	"jy/src/jfw/modules/bigmember/src/entity"
-	"jy/src/jfw/modules/bigmember/src/util"
-	"log"
-	"strings"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/entity"
+        "jy/src/jfw/modules/bigmember/src/util"
+        "log"
+        "strings"
 
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/encrypt"
+        . "app.yhyue.com/moapp/jybase/api"
+        qutil "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/go-xweb/xweb"
 )
 
 //EntPortrait 大会员画像接口
 type EntPortrait struct {
-	*xweb.Action
-	//中标企业画像
-	entDetail          xweb.Mapper `xweb:"/portrait/ent/detail"`                //企业基本信息
-	winnerContacts     xweb.Mapper `xweb:"/portrait/winner/contacts"`           //历史项目联系方式
-	winnerSelects      xweb.Mapper `xweb:"/portrait/winner/selects"`            //企业画像可筛选项
-	winnerNewMsg       xweb.Mapper `xweb:"/portrait/winner/getNewMsg"`          //最新项目动态(需购买项目进度监控)[筛选]
-	winnerNewMsgExport xweb.Mapper `xweb:"/portrait/winner/winnerNewMsgExport"` //最新项目动态数据导出
-	winnerPortrait     xweb.Mapper `xweb:"/portrait/winner/getData"`            //中标企业画像数据[筛选]
-	winnerMiniPortrait xweb.Mapper `xweb:"/portrait/winner/miniData"`           //三级页展示中标企业基础画像信息
-	//采购单位画像
-	buyerContacts     xweb.Mapper `xweb:"/portrait/buyer/contacts"`        //采购项目联系方式
-	buyerSelects      xweb.Mapper `xweb:"/portrait/buyer/selects"`         //采购单位画像可筛选项
-	buyerNewMsg       xweb.Mapper `xweb:"/portrait/buyer/getNewMsg"`       //最新项目动态[筛选]
-	buyerNewMsgExport xweb.Mapper `xweb:"/portrait/buyer/getNewMsgExport"` //最新项目动态数据导出[筛选]
-	buyerPortrait     xweb.Mapper `xweb:"/portrait/buyer/getData"`         //采购单位画像数据[筛选]
-	buyerMiniPortrait xweb.Mapper `xweb:"/portrait/buyer/miniData"`        //三级页展示采购单位基础画像信息
-	portraitContacts  xweb.Mapper `xweb:"/portrait/contacts"`              // 画像通讯录接口
+        *xweb.Action
+        //中标企业画像
+        entDetail          xweb.Mapper `xweb:"/portrait/ent/detail"`                //企业基本信息
+        winnerContacts     xweb.Mapper `xweb:"/portrait/winner/contacts"`           //历史项目联系方式
+        winnerSelects      xweb.Mapper `xweb:"/portrait/winner/selects"`            //企业画像可筛选项
+        winnerNewMsg       xweb.Mapper `xweb:"/portrait/winner/getNewMsg"`          //最新项目动态(需购买项目进度监控)[筛选]
+        winnerNewMsgExport xweb.Mapper `xweb:"/portrait/winner/winnerNewMsgExport"` //最新项目动态数据导出
+        winnerPortrait     xweb.Mapper `xweb:"/portrait/winner/getData"`            //中标企业画像数据[筛选]
+        winnerMiniPortrait xweb.Mapper `xweb:"/portrait/winner/miniData"`           //三级页展示中标企业基础画像信息
+        //采购单位画像
+        buyerContacts     xweb.Mapper `xweb:"/portrait/buyer/contacts"`        //采购项目联系方式
+        buyerSelects      xweb.Mapper `xweb:"/portrait/buyer/selects"`         //采购单位画像可筛选项
+        buyerNewMsg       xweb.Mapper `xweb:"/portrait/buyer/getNewMsg"`       //最新项目动态[筛选]
+        buyerNewMsgExport xweb.Mapper `xweb:"/portrait/buyer/getNewMsgExport"` //最新项目动态数据导出[筛选]
+        buyerPortrait     xweb.Mapper `xweb:"/portrait/buyer/getData"`         //采购单位画像数据[筛选]
+        buyerMiniPortrait xweb.Mapper `xweb:"/portrait/buyer/miniData"`        //三级页展示采购单位基础画像信息
+        portraitContacts  xweb.Mapper `xweb:"/portrait/contacts"`              // 画像通讯录接口
 
 }
 
 //EntDetail 企业基本信息
 func (this *EntPortrait) EntDetail() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, _, err, _ := entity.CreatePortraitManager(this.Session(), "entDetail")
-		if err != nil {
-			return nil, err
-		}
-		entId := this.GetString("entId")
-		entInfo, err := cepm.GetEntInfo(util.DecodeId(entId))
-		if err != nil {
-			return nil, err
-		}
-		return entInfo, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s 企业画像-查询企业基本信息:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, _, err, _ := entity.CreatePortraitManager(this.Session(), "entDetail")
+                if err != nil {
+                        return nil, err
+                }
+                entId := this.GetString("entId")
+                entInfo, err := cepm.GetEntInfo(util.DecodeId(entId))
+                if err != nil {
+                        return nil, err
+                }
+                return entInfo, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s 企业画像-查询企业基本信息:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //WinnerContacts 中标企业历史联系人
 func (this *EntPortrait) WinnerContacts() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "entPortrait")
-		if err != nil {
-			return nil, err
-		}
-		if !hasPower {
-			return nil, fmt.Errorf("非法请求")
-		}
-		entId := util.DecodeId(this.GetString("entId"))
-		rData, err := cepm.GetWinnerContactsMsg(entId)
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list": rData,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s WinnerContacts获取历史项目联系方式出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "entPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                if !hasPower {
+                        return nil, fmt.Errorf("非法请求")
+                }
+                entId := util.DecodeId(this.GetString("entId"))
+                rData, err := cepm.GetWinnerContactsMsg(entId)
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list": rData,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s WinnerContacts获取历史项目联系方式出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // WinnerSelects 企业画像可供筛选的条件
 func (this *EntPortrait) WinnerSelects() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("企业参数异常")
-		}
-		_, _, err, _ := entity.CreatePortraitManager(this.Session(), "entNewMsg")
-		if err != nil {
-			return nil, err
-		}
-		//if !hasPower {
-		//	return nil, fmt.Errorf("非法请求")
-		//}
-		pwp := &entity.PortraitScreen{Ent: qutil.InterfaceToStr(entId)}
-		return pwp.GetProjectSelectItems(true)
-	}()
-	if errMsg != nil {
-		log.Printf("%s WinnerSelects 获取企业画像可筛选条件出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("企业参数异常")
+                }
+                _, _, err, _ := entity.CreatePortraitManager(this.Session(), "entNewMsg")
+                if err != nil {
+                        return nil, err
+                }
+                //if !hasPower {
+                //	return nil, fmt.Errorf("非法请求")
+                //}
+                pwp := &entity.PortraitScreen{Ent: qutil.InterfaceToStr(entId)}
+                return pwp.GetProjectSelectItems(true)
+        }()
+        if errMsg != nil {
+                log.Printf("%s WinnerSelects 获取企业画像可筛选条件出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //WinnerNewMsg 企业画像-最新项目动态
 func (this *EntPortrait) WinnerNewMsg() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("企业参数异常")
-		}
-		cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "entNewMsg")
-		if err != nil {
-			return nil, err
-		}
-		if !hasPower {
-			return nil, fmt.Errorf("非法请求")
-		}
-		pageNum, _ := this.GetInteger("pageNum")
-		pageSize, _ := this.GetInteger("pageSize")
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("企业参数异常")
+                }
+                cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "entNewMsg")
+                if err != nil {
+                        return nil, err
+                }
+                if !hasPower {
+                        return nil, fmt.Errorf("非法请求")
+                }
+                pageNum, _ := this.GetInteger("pageNum")
+                pageSize, _ := this.GetInteger("pageSize")
 
-		rData, total, err := cepm.GetWinnerNewMsg(&entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        entId,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   hasPower,
-			},
-			PageNum:  pageNum,
-			PageSize: pageSize,
-		})
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list":  rData,
-			"count": total,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s WinnerNewMsg获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                rData, total, err := cepm.GetWinnerNewMsg(&entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        entId,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   hasPower,
+                        },
+                        PageNum:  pageNum,
+                        PageSize: pageSize,
+                })
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list":  rData,
+                        "count": total,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s WinnerNewMsg获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //WinnerNewMsgExport 企业画像-最新项目动态
 func (this *EntPortrait) WinnerNewMsgExport() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("企业参数异常")
-		}
-		cepm, hasPower, err, free := entity.CreatePortraitManager(this.Session(), "entNewMsg")
-		if err != nil {
-			return nil, err
-		}
-		if !hasPower {
-			return nil, fmt.Errorf("非法请求")
-		}
-		//查询数据导出数据id列
-		pps := &entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        entId,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   hasPower,
-			},
-			IsExport: true,
-			Free:     free,
-		}
-		ids := getSelectIds(this.GetString("selectIds"))
-		if ids == nil || len(ids) == 0 {
-			ids, err = cepm.GetWinnerNewExport(pps)
-			if err != nil {
-				return nil, err
-			}
-		} else {
-			pps.CommonPare(true)
-		}
-		_id, err := cepm.SaveExportRecord(pps, ids, entId, "winnerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		return _id, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s WinnerNewMsgExport获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("企业参数异常")
+                }
+                cepm, hasPower, err, free := entity.CreatePortraitManager(this.Session(), "entNewMsg")
+                if err != nil {
+                        return nil, err
+                }
+                if !hasPower {
+                        return nil, fmt.Errorf("非法请求")
+                }
+                //查询数据导出数据id列
+                pps := &entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        entId,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   hasPower,
+                        },
+                        IsExport: true,
+                        Free:     free,
+                }
+                ids := getSelectIds(this.GetString("selectIds"))
+                if ids == nil || len(ids) == 0 {
+                        ids, err = cepm.GetWinnerNewExport(pps)
+                        if err != nil {
+                                return nil, err
+                        }
+                } else {
+                        pps.CommonPare(true)
+                }
+                _id, err := cepm.SaveExportRecord(pps, ids, entId, "winnerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                return _id, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s WinnerNewMsgExport获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //WinnerPortrait 企业画像-画像数据查询
 func (this *EntPortrait) WinnerPortrait() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "entPortrait")
-		if err != nil {
-			return nil, err
-		}
-		entId := this.GetString("entId")
-		rData, err := cepm.WinnerPortraitData(&entity.PortraitScreen{
-			Ent:        util.DecodeId(entId),
-			Match:      this.GetString("match"),
-			ExactMatch: this.GetString("exactMatch") == "1",
-			MatchRange: this.GetString("matchRange"),
-			Area:       this.GetString("area"),
-			ScopeClass: this.GetString("scopeClass"),
-			TimeRange:  this.GetString("timeRange"),
-			HasPower:   hasPower,
-		})
-		if err != nil {
-			return nil, err
-		}
-		return rData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s WinnerPortrait获取企业画像标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "entPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                entId := this.GetString("entId")
+                rData, err := cepm.WinnerPortraitData(&entity.PortraitScreen{
+                        Ent:        util.DecodeId(entId),
+                        Match:      this.GetString("match"),
+                        ExactMatch: this.GetString("exactMatch") == "1",
+                        MatchRange: this.GetString("matchRange"),
+                        Area:       this.GetString("area"),
+                        ScopeClass: this.GetString("scopeClass"),
+                        TimeRange:  this.GetString("timeRange"),
+                        HasPower:   hasPower,
+                })
+                if err != nil {
+                        return nil, err
+                }
+                return rData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s WinnerPortrait获取企业画像标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //WinnerMiniPortrait 三级页中标单位引流数据展示(免费)
 func (this *EntPortrait) WinnerMiniPortrait() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, _, err, _ := entity.CreatePortraitManager(this.Session(), "entPortrait")
-		if err != nil {
-			return nil, err
-		}
-		entId := util.DecodeId(this.GetString("entId"))
-		rData, err := cepm.WinnerMiniPortraitData(entId) //项目个数,项目金额
-		if err != nil {
-			return nil, err
-		}
-		//公司状态
-		if entInfo, err := cepm.GetEntInfo(entId); err == nil {
-			rData["status"] = entInfo["status"]
-			rData["type"] = entInfo["type"]
-			rData["company_name"] = entInfo["entName"]
-		}
-		//项目动态数量
-		rData["biddingCount"] = cepm.GetWinnerNewCount(entId)
-		//历史联系人
-		if contactList, err := cepm.GetWinnerContactsMsg(entId); err == nil {
-			rData["contactList"], rData["contactCount"] = formatContact(contactList)
-		}
-		return rData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s WinnerPortrait获取企业画像标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, _, err, _ := entity.CreatePortraitManager(this.Session(), "entPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                entId := util.DecodeId(this.GetString("entId"))
+                rData, err := cepm.WinnerMiniPortraitData(entId) //项目个数,项目金额
+                if err != nil {
+                        return nil, err
+                }
+                //公司状态
+                if entInfo, err := cepm.GetEntInfo(entId); err == nil {
+                        rData["status"] = entInfo["status"]
+                        rData["type"] = entInfo["type"]
+                        rData["company_name"] = entInfo["entName"]
+                }
+                //项目动态数量
+                rData["biddingCount"] = cepm.GetWinnerNewCount(entId)
+                //历史联系人
+                if contactList, err := cepm.GetWinnerContactsMsg(entId); err == nil {
+                        rData["contactList"], rData["contactCount"] = formatContact(contactList)
+                }
+                return rData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s WinnerPortrait获取企业画像标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerSelects 采购单位画像可供筛选的条件
 //dev.6.2.1免费用户可筛选画像
 func (this *EntPortrait) BuyerSelects() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		buyer := this.GetString("buyer")
-		if buyer == "" {
-			return nil, fmt.Errorf("企业参数异常")
-		}
-		_, _, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		pwp := &entity.PortraitScreen{Ent: buyer}
-		return pwp.GetProjectSelectItems(false)
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerSelects 获取采购的单位画像可筛选条件出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                buyer := this.GetString("buyer")
+                if buyer == "" {
+                        return nil, fmt.Errorf("企业参数异常")
+                }
+                _, _, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                pwp := &entity.PortraitScreen{Ent: buyer}
+                return pwp.GetProjectSelectItems(false)
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerSelects 获取采购的单位画像可筛选条件出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerNewMsg 采购单位画像-最新招标动态(免费用户仅可查看3条记录,付费50条)
 func (this *EntPortrait) BuyerNewMsg() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
 
-		buyer := this.GetString("buyer")
-		pageNum, _ := this.GetInteger("pageNum")
-		pageSize, _ := this.GetInteger("pageSize")
+                buyer := this.GetString("buyer")
+                pageNum, _ := this.GetInteger("pageNum")
+                pageSize, _ := this.GetInteger("pageSize")
 
-		//免费用户仅可查看三条记录
-		rData, total, err := cepm.GetBuyerNewMsg(&entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        buyer,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   hasPower,
-			},
-			PageNum:  pageNum,
-			PageSize: pageSize,
-		})
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list":  rData,
-			"count": total,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerNewMsg获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                //免费用户仅可查看三条记录
+                rData, total, err := cepm.GetBuyerNewMsg(&entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        buyer,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   hasPower,
+                        },
+                        PageNum:  pageNum,
+                        PageSize: pageSize,
+                })
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list":  rData,
+                        "count": total,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerNewMsg获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 func (this *EntPortrait) BuyerNewMsgExport() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, hasPower, err, free := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		buyer := this.GetString("buyer")
-		//免费用户仅可查看三条记录
-		pps := &entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        buyer,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   hasPower,
-			},
-			IsExport: true,
-			Free:     free,
-		}
-		ids := getSelectIds(this.GetString("selectIds"))
-		if ids == nil || len(ids) == 0 {
-			ids, err = cepm.GetBuyerNewMsgExport(pps)
-			if err != nil {
-				return nil, err
-			}
-		} else {
-			pps.CommonPare(false)
-		}
-		_id, err := cepm.SaveExportRecord(pps, ids, buyer, "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		return _id, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerNewMsgExport获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, hasPower, err, free := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                buyer := this.GetString("buyer")
+                //免费用户仅可查看三条记录
+                pps := &entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        buyer,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   hasPower,
+                        },
+                        IsExport: true,
+                        Free:     free,
+                }
+                ids := getSelectIds(this.GetString("selectIds"))
+                if ids == nil || len(ids) == 0 {
+                        ids, err = cepm.GetBuyerNewMsgExport(pps)
+                        if err != nil {
+                                return nil, err
+                        }
+                } else {
+                        pps.CommonPare(false)
+                }
+                _id, err := cepm.SaveExportRecord(pps, ids, buyer, "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                return _id, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerNewMsgExport获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerContacts 采购单位联系人(必须开通会员)
 func (this *EntPortrait) BuyerContacts() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		if !hasPower {
-			return nil, fmt.Errorf("非法请求")
-		}
-		buyerName := this.GetString("buyer")
-		rData, err := cepm.GetBuyerContactsMsg(buyerName)
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list": rData,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerContacts获取历史项目联系方式出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                if !hasPower {
+                        return nil, fmt.Errorf("非法请求")
+                }
+                buyerName := this.GetString("buyer")
+                rData, err := cepm.GetBuyerContactsMsg(buyerName)
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list": rData,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerContacts获取历史项目联系方式出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerPortrait 采购单位画像-数据(免费用户可查看基本信息、项目统计、合作企业资本、年龄及地区分布)
 func (this *EntPortrait) BuyerPortrait() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		entName := this.GetString("buyer")
-		flag := this.GetString("flag") //分段请求标识
-		rData, err := cepm.BuyerPortraitData(&entity.PortraitScreen{
-			Ent:        entName,
-			Match:      this.GetString("match"),
-			ExactMatch: this.GetString("exactMatch") == "1",
-			MatchRange: this.GetString("matchRange"),
-			Area:       this.GetString("area"),
-			ScopeClass: this.GetString("scopeClass"),
-			TimeRange:  this.GetString("timeRange"),
-			HasPower:   hasPower,
-		}, flag)
-		if err != nil {
-			return nil, err
-		}
-		return rData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerPortrait获取采购单位画像标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, hasPower, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
+                cepm.Session = this.Session()
+                if err != nil {
+                        return nil, err
+                }
+                entName := this.GetString("buyer")
+                flag := this.GetString("flag") //分段请求标识
+                rData, err := cepm.BuyerPortraitData(&entity.PortraitScreen{
+                        Ent:        entName,
+                        Match:      this.GetString("match"),
+                        ExactMatch: this.GetString("exactMatch") == "1",
+                        MatchRange: this.GetString("matchRange"),
+                        Area:       this.GetString("area"),
+                        ScopeClass: this.GetString("scopeClass"),
+                        TimeRange:  this.GetString("timeRange"),
+                        HasPower:   hasPower,
+                }, flag)
+                if err != nil {
+                        return nil, err
+                }
+                return rData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerPortrait获取采购单位画像标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerMiniPortrait 三级页采购单位引流数据展示(免费)
 func (this *EntPortrait) BuyerMiniPortrait() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		cepm, _, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		entName := this.GetString("buyer")
-		//所在地(省、市)、采购单位类型、采购项目数量、采购规模
-		rData, err := cepm.BuyerMiniPortraitData(entName)
-		if err != nil {
-			return nil, err
-		}
-		//招标动态数量
-		rData["biddingCount"] = cepm.GetBuyerNewCount(entName)
-		//采购联系人数量及历史联系人方式,成交时间(加密展示2条)
-		if contactList, err := cepm.GetBuyerContactsMsg(entName); err == nil {
-			rData["contactList"], rData["contactCount"] = formatContact(contactList)
-		}
-		return rData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerMiniPortrait获取采购单位画像标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                cepm, _, err, _ := entity.CreatePortraitManager(this.Session(), "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                entName := this.GetString("buyer")
+                //所在地(省、市)、采购单位类型、采购项目数量、采购规模
+                rData, err := cepm.BuyerMiniPortraitData(entName)
+                if err != nil {
+                        return nil, err
+                }
+                //招标动态数量
+                rData["biddingCount"] = cepm.GetBuyerNewCount(entName)
+                //采购联系人数量及历史联系人方式,成交时间(加密展示2条)
+                if contactList, err := cepm.GetBuyerContactsMsg(entName); err == nil {
+                        rData["contactList"], rData["contactCount"] = formatContact(contactList)
+                }
+                return rData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerMiniPortrait获取采购单位画像标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 /*
@@ -475,77 +476,77 @@ func (this *EntPortrait) BuyerMiniPortrait() {
  */
 // PortraitContacts 画像通讯录
 func (this *EntPortrait) PortraitContacts() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entType, _ := this.GetInt("entType")
-		entName := this.GetString("entName")
-		// 画像通讯里访问权限
-		cepm, err := entity.CreatePortraitManagerForContacts(this.Session(), entType, entName)
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entType, _ := this.GetInt("entType")
+                entName := this.GetString("entName")
+                // 画像通讯里访问权限
+                cepm, err := entity.CreatePortraitManagerForContacts(this.Session(), entType, entName)
 
-		if err != nil {
-			return nil, err
-		}
-		rData, err := cepm.GetContacts(entName, int(entType))
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list": rData,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s PortraitContacts获取通讯录出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                if err != nil {
+                        return nil, err
+                }
+                rData, err := cepm.GetContacts(entName, int(entType))
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list": rData,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s PortraitContacts获取通讯录出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //formatContact 格式化混淆联系人电话
 func formatContact(contactList []map[string]interface{}) (confusing []map[string]interface{}, total int) {
-	total = len(contactList)
-	deConfusingMap := make(map[string]bool) //去重
-	for _, contactMap := range contactList {
-		var thePhone string
-		rowData, _ := contactMap["contacts"].(map[string]string)
-		for phone := range rowData {
-			if !deConfusingMap[phone] && phone != "" {
-				thePhone = phone
-			}
-		}
-		if len(thePhone) < 7 {
-			continue
-		}
+        total = len(contactList)
+        deConfusingMap := make(map[string]bool) //去重
+        for _, contactMap := range contactList {
+                var thePhone string
+                rowData, _ := contactMap["contacts"].(map[string]string)
+                for phone := range rowData {
+                        if !deConfusingMap[phone] && phone != "" {
+                                thePhone = phone
+                        }
+                }
+                if len(thePhone) < 7 {
+                        continue
+                }
 
-		var confusingPhone string
-		if len([]rune(thePhone)) == 11 {
-			confusingPhone = thePhone[:3] + "****" + thePhone[8:]
-		} else if len([]rune(thePhone)) == 7 {
-			confusingPhone = thePhone[:2] + "***" + thePhone[5:]
-		} else {
-			confusingPhone = thePhone[:5] + "***" + thePhone[8:]
-		}
-		deConfusingMap[confusingPhone] = true
+                var confusingPhone string
+                if len([]rune(thePhone)) == 11 {
+                        confusingPhone = thePhone[:3] + "****" + thePhone[8:]
+                } else if len([]rune(thePhone)) == 7 {
+                        confusingPhone = thePhone[:2] + "***" + thePhone[5:]
+                } else {
+                        confusingPhone = thePhone[:5] + "***" + thePhone[8:]
+                }
+                deConfusingMap[confusingPhone] = true
 
-		confusing = append(confusing, map[string]interface{}{
-			"contact": confusingPhone,
-			"date":    contactMap["date"],
-		})
-		//仅返回两条
-		if len(confusing) == 2 {
-			break
-		}
-	}
-	return
+                confusing = append(confusing, map[string]interface{}{
+                        "contact": confusingPhone,
+                        "date":    contactMap["date"],
+                })
+                //仅返回两条
+                if len(confusing) == 2 {
+                        break
+                }
+        }
+        return
 }
 
 func getSelectIds(selectIds string) (ids []string) {
-	if selectIds != "" { //选中导出
-		for _, encodeId := range strings.Split(selectIds, ",") {
-			if tmp := encrypt.CommonDecodeArticle("content", encodeId); len(tmp) > 0 {
-				if id := tmp[0]; id != "" {
-					ids = append(ids, id)
-				}
-			}
-		}
-	}
-	return
+        if selectIds != "" { //选中导出
+                for _, encodeId := range strings.Split(selectIds, ",") {
+                        if tmp := encrypt.CommonDecodeArticle("content", encodeId); len(tmp) > 0 {
+                                if id := tmp[0]; id != "" {
+                                        ids = append(ids, id)
+                                }
+                        }
+                }
+        }
+        return
 }

+ 455 - 454
src/jfw/modules/bigmember/src/service/portrait/subvipPortraitAction.go

@@ -1,526 +1,527 @@
 package portrait
 
 import (
-	"errors"
-	"fmt"
-	"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"
-	"log"
-	"strings"
-	"time"
+        "errors"
+        "fmt"
+        "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"
+        "log"
+        "strings"
+        "time"
 
-	. "app.yhyue.com/moapp/jybase/api"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"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/date"
+        elastic "app.yhyue.com/moapp/jybase/esv1"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 // SubVipPortrait 超级订阅升级版画像接口
 type SubVipPortrait struct {
-	*xweb.Action
-	portraitUsage  xweb.Mapper `xweb:"/portrait/subVipPortrait/usage"`  //超级订阅升级版画像浏览详情
-	portraitRecord xweb.Mapper `xweb:"/portrait/subVipPortrait/record"` //超级订阅升级版画像浏览记录
+        *xweb.Action
+        portraitUsage  xweb.Mapper `xweb:"/portrait/subVipPortrait/usage"`  //超级订阅升级版画像浏览详情
+        portraitRecord xweb.Mapper `xweb:"/portrait/subVipPortrait/record"` //超级订阅升级版画像浏览记录
 
-	subVipEntDetail     xweb.Mapper `xweb:"/portrait/subVipPortrait/entDetail"`          //企业基本信息
-	subVipPortrait      xweb.Mapper `xweb:"/portrait/subVipPortrait/winner"`             //超级订阅升级版查看画像
-	subVipWinnerNewMsg  xweb.Mapper `xweb:"/portrait/subVipPortrait/winnerNewMsg"`       //超级订阅升级版查看最新项目动态
-	winnerNewMsgExport  xweb.Mapper `xweb:"/portrait/subVipPortrait/winnerNewMsgExport"` //最新项目动态数据导出
-	subVipNewMsgSelects xweb.Mapper `xweb:"/portrait/subVipPortrait/selects"`            //最新招标信息可筛选项
+        subVipEntDetail     xweb.Mapper `xweb:"/portrait/subVipPortrait/entDetail"`          //企业基本信息
+        subVipPortrait      xweb.Mapper `xweb:"/portrait/subVipPortrait/winner"`             //超级订阅升级版查看画像
+        subVipWinnerNewMsg  xweb.Mapper `xweb:"/portrait/subVipPortrait/winnerNewMsg"`       //超级订阅升级版查看最新项目动态
+        winnerNewMsgExport  xweb.Mapper `xweb:"/portrait/subVipPortrait/winnerNewMsgExport"` //最新项目动态数据导出
+        subVipNewMsgSelects xweb.Mapper `xweb:"/portrait/subVipPortrait/selects"`            //最新招标信息可筛选项
 
-	buyerContacts     xweb.Mapper `xweb:"/subVipPortrait/buyer/contacts"`        //采购项目联系方式
-	buyerSelects      xweb.Mapper `xweb:"/subVipPortrait/buyer/selects"`         //采购单位画像可筛选项
-	buyerNewMsg       xweb.Mapper `xweb:"/subVipPortrait/buyer/getNewMsg"`       //最新项目动态[筛选]
-	buyerNewMsgExport xweb.Mapper `xweb:"/subVipPortrait/buyer/getNewMsgExport"` //最新项目动态数据导出[筛选]
-	buyerPortrait     xweb.Mapper `xweb:"/subVipPortrait/buyer/getData"`         //采购单位画像数据[筛选]
+        buyerContacts     xweb.Mapper `xweb:"/subVipPortrait/buyer/contacts"`        //采购项目联系方式
+        buyerSelects      xweb.Mapper `xweb:"/subVipPortrait/buyer/selects"`         //采购单位画像可筛选项
+        buyerNewMsg       xweb.Mapper `xweb:"/subVipPortrait/buyer/getNewMsg"`       //最新项目动态[筛选]
+        buyerNewMsgExport xweb.Mapper `xweb:"/subVipPortrait/buyer/getNewMsgExport"` //最新项目动态数据导出[筛选]
+        buyerPortrait     xweb.Mapper `xweb:"/subVipPortrait/buyer/getData"`         //采购单位画像数据[筛选]
 }
 
 //SubVipEntDetail 超级订阅升级版查询基本信息
 func (this *SubVipPortrait) SubVipEntDetail() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		cepm, _, err, _ := entity.CreateSubVipPortraitManager(userId, "entDetail", entId, true, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		entInfo, err := cepm.GetEntInfo(entId)
-		if err != nil {
-			return nil, err
-		}
-		return entInfo, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s 企业画像-查询企业基本信息:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                cepm, _, err, _ := entity.CreateSubVipPortraitManager(userId, "entDetail", entId, true, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                entInfo, err := cepm.GetEntInfo(entId)
+                if err != nil {
+                        return nil, err
+                }
+                return entInfo, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s 企业画像-查询企业基本信息:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //SubVipWinnerNewMsg 超级订阅升级版查看最新中标动态
 func (this *SubVipPortrait) SubVipWinnerNewMsg() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "entNewMsg", entId, true, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		if power <= 1 {
-			return nil, errors.New("非法请求")
-		}
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "entNewMsg", entId, true, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                if power <= 1 {
+                        return nil, errors.New("非法请求")
+                }
 
-		pageNum, _ := this.GetInteger("pageNum")
-		pageSize, _ := this.GetInteger("pageSize")
+                pageNum, _ := this.GetInteger("pageNum")
+                pageSize, _ := this.GetInteger("pageSize")
 
-		rData, total, err := cepm.GetWinnerNewMsg(&entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        entId,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("matchType") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   true,
-			},
-			PageNum:  pageNum,
-			PageSize: pageSize,
-		})
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list":  rData,
-			"count": total,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubVipPortrait-SubVipWinnerNewMsg 获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                rData, total, err := cepm.GetWinnerNewMsg(&entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        entId,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("matchType") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   true,
+                        },
+                        PageNum:  pageNum,
+                        PageSize: pageSize,
+                })
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list":  rData,
+                        "count": total,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubVipPortrait-SubVipWinnerNewMsg 获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //WinnerNewMsgExport 超级订阅升级版查看最新中标动态数据导出
 func (this *SubVipPortrait) WinnerNewMsgExport() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		cepm, power, err, free := entity.CreateSubVipPortraitManager(userId, "entNewMsg", entId, true, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		if power <= 1 {
-			return nil, errors.New("非法请求")
-		}
-		//查询数据导出数据id列
-		pps := &entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        entId,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   true,
-			},
-			IsExport: true,
-			Free:     free,
-		}
-		ids := getSelectIds(this.GetString("selectIds"))
-		if ids == nil || len(ids) == 0 {
-			ids, err = cepm.GetWinnerNewExport(pps)
-			if err != nil {
-				return nil, err
-			}
-		} else {
-			pps.CommonPare(true)
-		}
-		_id, err := cepm.SaveExportRecord(pps, ids, entId, "winnerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		return _id, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubVipPortrait-WinnerNewMsgExport 获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                cepm, power, err, free := entity.CreateSubVipPortraitManager(userId, "entNewMsg", entId, true, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                if power <= 1 {
+                        return nil, errors.New("非法请求")
+                }
+                //查询数据导出数据id列
+                pps := &entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        entId,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   true,
+                        },
+                        IsExport: true,
+                        Free:     free,
+                }
+                ids := getSelectIds(this.GetString("selectIds"))
+                if ids == nil || len(ids) == 0 {
+                        ids, err = cepm.GetWinnerNewExport(pps)
+                        if err != nil {
+                                return nil, err
+                        }
+                } else {
+                        pps.CommonPare(true)
+                }
+                _id, err := cepm.SaveExportRecord(pps, ids, entId, "winnerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                return _id, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubVipPortrait-WinnerNewMsgExport 获取企业最新中标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //SubVipNewMsgSelects 获取画像可筛选项
 func (this *SubVipPortrait) SubVipNewMsgSelects() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		_, _, err, _ := entity.CreateSubVipPortraitManager(userId, "entNewMsg", entId, true, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		pwp := &entity.PortraitScreen{Ent: entId}
-		return pwp.GetProjectSelectItems(true)
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubVipNewMsgSelects 获取企业最新中标信息筛选条件出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                _, _, err, _ := entity.CreateSubVipPortraitManager(userId, "entNewMsg", entId, true, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                pwp := &entity.PortraitScreen{Ent: entId}
+                return pwp.GetProjectSelectItems(true)
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubVipNewMsgSelects 获取企业最新中标信息筛选条件出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //SubVipPortrait 超级订阅升级版查看企业画像
 func (this *SubVipPortrait) SubVipPortrait() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		entId := util.DecodeId(this.GetString("entId"))
-		if entId == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "entPortrait", entId, true, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		rData, err := cepm.WinnerPortraitData(&entity.PortraitScreen{
-			Ent:        entId,
-			Match:      this.GetString("match"),
-			ExactMatch: this.GetString("exactMatch") == "1",
-			MatchRange: this.GetString("matchRange"),
-			Area:       this.GetString("area"),
-			ScopeClass: this.GetString("scopeClass"),
-			TimeRange:  this.GetString("timeRange"),
-			HasPower:   power > 1,
-		})
-		if power == 3 {
-			rData["onTrial"] = true
-		}
-		return rData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubVipPortrait 获取企业画像标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                entId := util.DecodeId(this.GetString("entId"))
+                if entId == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "entPortrait", entId, true, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                rData, err := cepm.WinnerPortraitData(&entity.PortraitScreen{
+                        Ent:        entId,
+                        Match:      this.GetString("match"),
+                        ExactMatch: this.GetString("exactMatch") == "1",
+                        MatchRange: this.GetString("matchRange"),
+                        Area:       this.GetString("area"),
+                        ScopeClass: this.GetString("scopeClass"),
+                        TimeRange:  this.GetString("timeRange"),
+                        HasPower:   power > 1,
+                })
+                if power == 3 {
+                        rData["onTrial"] = true
+                }
+                return rData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubVipPortrait 获取企业画像标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //PortraitUsage 超级订阅升级版画像浏览量查询
 func (this *SubVipPortrait) PortraitUsage() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		bigMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                bigMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
 
-		if bigMsg.VipStatus <= 0 && bigMsg.Vip_BuySet.Upgrade != 1 {
-			return nil, fmt.Errorf("非法请求")
-		}
-		isWinner, queryEnt := this.GetString("p_type") != "1", ""
-		if isWinner {
-			queryEnt = util.DecodeId(this.GetString("entId"))
-		} else {
-			queryEnt = this.GetString("buyer")
-		}
+                if bigMsg.VipStatus <= 0 && bigMsg.Vip_BuySet.Upgrade != 1 {
+                        return nil, fmt.Errorf("非法请求")
+                }
+                isWinner, queryEnt := this.GetString("p_type") != "1", ""
+                if isWinner {
+                        queryEnt = util.DecodeId(this.GetString("entId"))
+                } else {
+                        queryEnt = this.GetString("buyer")
+                }
 
-		vipTotal, vipSurplus, packSurplus, isUsed := bigMsg.NewSubVipPortrait(db.Mysql, queryEnt, isWinner).AccountStatus()
-		returnMap := map[string]interface{}{
-			"total":   vipTotal, //超级订阅数量+流量包数量
-			"balance": vipSurplus + packSurplus,
-			"usage":   vipTotal - (vipSurplus + packSurplus),
-			"provin":  bigMsg.Vip_BuySet.AreaCount,
-		}
-		if queryEnt != "" {
-			returnMap["visited"] = isUsed
-		}
-		return returnMap, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubVipPortrait-portraitUsage 企业画像浏览量查询出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                vipTotal, vipSurplus, packSurplus, isUsed := bigMsg.NewSubVipPortrait(db.Mysql, queryEnt, isWinner).AccountStatus()
+                returnMap := map[string]interface{}{
+                        "total":   vipTotal, //超级订阅数量+流量包数量
+                        "balance": vipSurplus + packSurplus,
+                        "usage":   vipTotal - (vipSurplus + packSurplus),
+                        "provin":  bigMsg.Vip_BuySet.AreaCount,
+                }
+                if queryEnt != "" {
+                        returnMap["visited"] = isUsed
+                }
+                return returnMap, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubVipPortrait-portraitUsage 企业画像浏览量查询出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //PortraitRecord 超级订阅升级版画像查看记录
 func (this *SubVipPortrait) PortraitRecord() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		year, _ := this.GetInteger("year")
-		month, _ := this.GetInteger("month")
-		pageNum, _ := this.GetInteger("pageNum")
-		pageSize, _ := this.GetInteger("pageSize")
-		if year == 0 || month == 0 {
-			return nil, fmt.Errorf("请求参数异常")
-		}
-		queryDate := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
-		if pageSize < 1 || pageSize > 50 {
-			pageSize = 50
-		}
-		bigMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
-		if bigMsg.VipStatus <= 0 && bigMsg.Vip_BuySet.Upgrade != 1 {
-			return nil, fmt.Errorf("非法请求")
-		}
-		isWinner := this.GetString("p_type") != "1"
-		//获取画像企业id
-		recordList, total := bigMsg.NewSubVipPortrait(db.Mysql, "", isWinner).GetPortraitRecord(queryDate, pageNum, pageSize, pageNum == 0)
-		var infoList []map[string]interface{}
-		if isWinner { //企业画像
-			entDetailMap := getEntListMsg(recordList)
-			for _, eid := range recordList {
-				if entDetail, ok := entDetailMap[eid]; ok && entDetail != nil {
-					entDetail["id"] = util.EncodeId(eid)
-					infoList = append(infoList, entDetail)
-				}
-			}
-		} else { //采购单位画像
-			buyerDetailMap := getBuyerListMsg(recordList)
-			for _, buyerName := range recordList {
-				if buyerDetail, ok := buyerDetailMap[buyerName]; ok && buyerDetail != nil {
-					infoList = append(infoList, buyerDetail)
-				} else {
-					infoList = append(infoList, map[string]interface{}{"name": buyerName})
-				}
-			}
-		}
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                year, _ := this.GetInteger("year")
+                month, _ := this.GetInteger("month")
+                pageNum, _ := this.GetInteger("pageNum")
+                pageSize, _ := this.GetInteger("pageSize")
+                if year == 0 || month == 0 {
+                        return nil, fmt.Errorf("请求参数异常")
+                }
+                queryDate := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
+                if pageSize < 1 || pageSize > 50 {
+                        pageSize = 50
+                }
+                bigMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
+                if bigMsg.VipStatus <= 0 && bigMsg.Vip_BuySet.Upgrade != 1 {
+                        return nil, fmt.Errorf("非法请求")
+                }
+                isWinner := this.GetString("p_type") != "1"
+                //获取画像企业id
+                recordList, total := bigMsg.NewSubVipPortrait(db.Mysql, "", isWinner).GetPortraitRecord(queryDate, pageNum, pageSize, pageNum == 0)
+                var infoList []map[string]interface{}
+                if isWinner { //企业画像
+                        entDetailMap := getEntListMsg(recordList)
+                        for _, eid := range recordList {
+                                if entDetail, ok := entDetailMap[eid]; ok && entDetail != nil {
+                                        entDetail["id"] = util.EncodeId(eid)
+                                        infoList = append(infoList, entDetail)
+                                }
+                        }
+                } else { //采购单位画像
+                        buyerDetailMap := getBuyerListMsg(recordList)
+                        for _, buyerName := range recordList {
+                                if buyerDetail, ok := buyerDetailMap[buyerName]; ok && buyerDetail != nil {
+                                        infoList = append(infoList, buyerDetail)
+                                } else {
+                                        infoList = append(infoList, map[string]interface{}{"name": buyerName})
+                                }
+                        }
+                }
 
-		returnMap := map[string]interface{}{
-			"list": infoList,
-		}
-		if total != -1 {
-			returnMap["total"] = total
-		}
-		return returnMap, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubVipPortrait-PortraitRecord 企业画像浏览记录查询出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                returnMap := map[string]interface{}{
+                        "list": infoList,
+                }
+                if total != -1 {
+                        returnMap["total"] = total
+                }
+                return returnMap, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubVipPortrait-PortraitRecord 企业画像浏览记录查询出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerSelects 超级订阅筛选画像
 func (this *SubVipPortrait) BuyerSelects() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		buyer := this.GetString("buyer")
-		if buyer == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		_, _, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyer, false, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		pwp := &entity.PortraitScreen{Ent: buyer}
-		return pwp.GetProjectSelectItems(false)
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerSelects 获取采购的单位画像可筛选条件出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                buyer := this.GetString("buyer")
+                if buyer == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                _, _, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyer, false, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                pwp := &entity.PortraitScreen{Ent: buyer}
+                return pwp.GetProjectSelectItems(false)
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerSelects 获取采购的单位画像可筛选条件出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerNewMsg 超级订阅采购单位画像动态
 func (this *SubVipPortrait) BuyerNewMsg() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		buyer := this.GetString("buyer")
-		if buyer == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		pageNum, _ := this.GetInteger("pageNum")
-		pageSize, _ := this.GetInteger("pageSize")
-		cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyer, false, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		//免费用户仅可查看三条记录
-		rData, total, err := cepm.GetBuyerNewMsg(&entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        buyer,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   power > 1,
-			},
-			PageNum:  pageNum,
-			PageSize: pageSize,
-		})
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list":  rData,
-			"count": total,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerNewMsg获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                buyer := this.GetString("buyer")
+                if buyer == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                pageNum, _ := this.GetInteger("pageNum")
+                pageSize, _ := this.GetInteger("pageSize")
+                cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyer, false, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                //免费用户仅可查看三条记录
+                rData, total, err := cepm.GetBuyerNewMsg(&entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        buyer,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   power > 1,
+                        },
+                        PageNum:  pageNum,
+                        PageSize: pageSize,
+                })
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list":  rData,
+                        "count": total,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerNewMsg获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerNewMsgExport 超级订阅采购单位画像动态数据导出
 func (this *SubVipPortrait) BuyerNewMsgExport() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		buyer := this.GetString("buyer")
-		if buyer == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		cepm, power, err, free := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyer, false, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		pps := &entity.PortraitProjectScreen{
-			Screen: &entity.PortraitScreen{
-				Ent:        buyer,
-				Match:      this.GetString("match"),
-				ExactMatch: this.GetString("exactMatch") == "1",
-				MatchRange: this.GetString("matchRange"),
-				Area:       this.GetString("area"),
-				ScopeClass: this.GetString("scopeClass"),
-				TimeRange:  this.GetString("timeRange"),
-				HasPower:   power > 1,
-			},
-			IsExport: true,
-			Free:     free,
-		}
-		ids := getSelectIds(this.GetString("selectIds"))
-		if ids == nil || len(ids) == 0 {
-			ids, err = cepm.GetBuyerNewMsgExport(pps)
-			if err != nil {
-				return nil, err
-			}
-		} else {
-			pps.CommonPare(false)
-		}
-		_id, err := cepm.SaveExportRecord(pps, ids, buyer, "buyerPortrait")
-		if err != nil {
-			return nil, err
-		}
-		return _id, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerNewMsgExport获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                buyer := this.GetString("buyer")
+                if buyer == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                cepm, power, err, free := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyer, false, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                pps := &entity.PortraitProjectScreen{
+                        Screen: &entity.PortraitScreen{
+                                Ent:        buyer,
+                                Match:      this.GetString("match"),
+                                ExactMatch: this.GetString("exactMatch") == "1",
+                                MatchRange: this.GetString("matchRange"),
+                                Area:       this.GetString("area"),
+                                ScopeClass: this.GetString("scopeClass"),
+                                TimeRange:  this.GetString("timeRange"),
+                                HasPower:   power > 1,
+                        },
+                        IsExport: true,
+                        Free:     free,
+                }
+                ids := getSelectIds(this.GetString("selectIds"))
+                if ids == nil || len(ids) == 0 {
+                        ids, err = cepm.GetBuyerNewMsgExport(pps)
+                        if err != nil {
+                                return nil, err
+                        }
+                } else {
+                        pps.CommonPare(false)
+                }
+                _id, err := cepm.SaveExportRecord(pps, ids, buyer, "buyerPortrait")
+                if err != nil {
+                        return nil, err
+                }
+                return _id, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerNewMsgExport获取采购单位最新招标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerContacts 超级订阅采购单位联系人
 func (this *SubVipPortrait) BuyerContacts() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		buyerName := this.GetString("buyer")
-		if buyerName == "" {
-			return nil, fmt.Errorf("企业参数异常")
-		}
-		cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyerName, false, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		if power <= 1 {
-			return nil, errors.New("非法请求")
-		}
-		rData, err := cepm.GetBuyerContactsMsg(buyerName)
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"list": rData,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerContacts获取历史项目联系方式出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                buyerName := this.GetString("buyer")
+                if buyerName == "" {
+                        return nil, fmt.Errorf("企业参数异常")
+                }
+                cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyerName, false, this.Session())
+                if err != nil {
+                        return nil, err
+                }
+                if power <= 1 {
+                        return nil, errors.New("非法请求")
+                }
+                rData, err := cepm.GetBuyerContactsMsg(buyerName)
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "list": rData,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerContacts获取历史项目联系方式出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //BuyerPortrait 超级订阅采购单位画像-数据
 func (this *SubVipPortrait) BuyerPortrait() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	rData, errMsg := func() (interface{}, error) {
-		buyerName := this.GetString("buyer")
-		if buyerName == "" {
-			return nil, fmt.Errorf("参数异常")
-		}
-		cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyerName, false, this.Session())
-		if err != nil {
-			return nil, err
-		}
-		flag := this.GetString("flag") //分段请求标识
-		rData, err := cepm.BuyerPortraitData(&entity.PortraitScreen{
-			Ent:        buyerName,
-			Match:      this.GetString("match"),
-			ExactMatch: this.GetString("exactMatch") == "1",
-			MatchRange: this.GetString("matchRange"),
-			Area:       this.GetString("area"),
-			ScopeClass: this.GetString("scopeClass"),
-			TimeRange:  this.GetString("timeRange"),
-			HasPower:   power > 1,
-		}, flag)
-		if err != nil {
-			return nil, err
-		}
-		if power == 3 {
-			rData["onTrial"] = true
-		}
-		return rData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s BuyerPortrait获取采购单位画像标信息出错:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        rData, errMsg := func() (interface{}, error) {
+                buyerName := this.GetString("buyer")
+                if buyerName == "" {
+                        return nil, fmt.Errorf("参数异常")
+                }
+                cepm, power, err, _ := entity.CreateSubVipPortraitManager(userId, "buyerPortrait", buyerName, false, this.Session())
+                cepm.Session = this.Session()
+                if err != nil {
+                        return nil, err
+                }
+                flag := this.GetString("flag") //分段请求标识
+                rData, err := cepm.BuyerPortraitData(&entity.PortraitScreen{
+                        Ent:        buyerName,
+                        Match:      this.GetString("match"),
+                        ExactMatch: this.GetString("exactMatch") == "1",
+                        MatchRange: this.GetString("matchRange"),
+                        Area:       this.GetString("area"),
+                        ScopeClass: this.GetString("scopeClass"),
+                        TimeRange:  this.GetString("timeRange"),
+                        HasPower:   power > 1,
+                }, flag)
+                if err != nil {
+                        return nil, err
+                }
+                if power == 3 {
+                        rData["onTrial"] = true
+                }
+                return rData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s BuyerPortrait获取采购单位画像标信息出错:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //getEntListMsg 获取企业基本信息
 func getEntListMsg(ids []string) (dMap map[string]map[string]interface{}) {
-	dMap = make(map[string]map[string]interface{})
-	rData := elastic.Get("qyxy", "qyxy", fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"id":["%s"]}}]}},"_source":["_id","company_name","company_status","legal_person","capital","company_address","company_shortname","company_phone","establish_date"],"size":%d}`, strings.Join(ids, `","`), len(ids)))
-	if rData == nil || len(*rData) == 0 {
-		return
-	}
-	for _, data := range *rData {
-		if id, ok := data["_id"].(string); ok && id != "" {
-			if dateTimestamp := qutil.Int64All(data["establish_date"]); dateTimestamp > 0 {
-				data["establish_date"] = time.Unix(dateTimestamp, 0).Format(Date_Short_Layout)
-			}
-			dMap[id] = data
-		}
-	}
-	return
+        dMap = make(map[string]map[string]interface{})
+        rData := elastic.Get("qyxy", "qyxy", fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"id":["%s"]}}]}},"_source":["_id","company_name","company_status","legal_person","capital","company_address","company_shortname","company_phone","establish_date"],"size":%d}`, strings.Join(ids, `","`), len(ids)))
+        if rData == nil || len(*rData) == 0 {
+                return
+        }
+        for _, data := range *rData {
+                if id, ok := data["_id"].(string); ok && id != "" {
+                        if dateTimestamp := qutil.Int64All(data["establish_date"]); dateTimestamp > 0 {
+                                data["establish_date"] = time.Unix(dateTimestamp, 0).Format(Date_Short_Layout)
+                        }
+                        dMap[id] = data
+                }
+        }
+        return
 }
 
 //getBuyerListMsg 获取采购单位基本信息
 func getBuyerListMsg(buyerNames []string) (dMap map[string]map[string]interface{}) {
-	dMap = make(map[string]map[string]interface{})
-	rData := elastic.Get("buyer", "buyer", fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"buyer_name":["%s"]}}]}},"size":%d,"_source":["buyer_name","city","province","buyerclass"]}`, strings.Join(buyerNames, `","`), len(buyerNames)))
-	if rData == nil || len(*rData) == 0 {
-		return
-	}
-	for _, data := range *rData {
-		if id, ok := data["_id"].(string); ok && id != "" {
-			if dateTimestamp := qutil.Int64All(data["establish_date"]); dateTimestamp > 0 {
-				data["establish_date"] = time.Unix(dateTimestamp, 0).Format(Date_Short_Layout)
-			}
-			dMap[id] = data
-		}
-		if buyerName, _ := data["buyer_name"].(string); buyerName != "" {
-			dMap[buyerName] = map[string]interface{}{
-				"name":       buyerName,
-				"city":       data["city"],
-				"province":   data["province"],
-				"buyerclass": data["buyerclass"],
-			}
-		}
-	}
-	return
+        dMap = make(map[string]map[string]interface{})
+        rData := elastic.Get("buyer", "buyer", fmt.Sprintf(`{"query":{"bool":{"must":[{"terms":{"buyer_name":["%s"]}}]}},"size":%d,"_source":["buyer_name","city","province","buyerclass"]}`, strings.Join(buyerNames, `","`), len(buyerNames)))
+        if rData == nil || len(*rData) == 0 {
+                return
+        }
+        for _, data := range *rData {
+                if id, ok := data["_id"].(string); ok && id != "" {
+                        if dateTimestamp := qutil.Int64All(data["establish_date"]); dateTimestamp > 0 {
+                                data["establish_date"] = time.Unix(dateTimestamp, 0).Format(Date_Short_Layout)
+                        }
+                        dMap[id] = data
+                }
+                if buyerName, _ := data["buyer_name"].(string); buyerName != "" {
+                        dMap[buyerName] = map[string]interface{}{
+                                "name":       buyerName,
+                                "city":       data["city"],
+                                "province":   data["province"],
+                                "buyerclass": data["buyerclass"],
+                        }
+                }
+        }
+        return
 }

+ 436 - 413
src/jfw/modules/bigmember/src/service/push/push.go

@@ -1,438 +1,461 @@
 package push
 
 import (
-	. "app.yhyue.com/moapp/jybase/api"
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"encoding/json"
-	"jy/src/jfw/modules/bigmember/src/config"
-	. "jy/src/jfw/modules/bigmember/src/db"
-	"log"
-	"time"
-
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        . "app.yhyue.com/moapp/jybase/api"
+        util "app.yhyue.com/moapp/jybase/common"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/config"
+        . "jy/src/jfw/modules/bigmember/src/db"
+        "log"
+        "time"
 )
 
 type Action struct {
-	*xweb.Action
-	items  xweb.Mapper `xweb:"/pushset/items"`  //推送项
-	detail xweb.Mapper `xweb:"/pushset/detail"` //推送设置详情
-	update xweb.Mapper `xweb:"/pushset/update"` //推送设置修改
+        *xweb.Action
+        items  xweb.Mapper `xweb:"/pushset/items"`  //推送项
+        detail xweb.Mapper `xweb:"/pushset/detail"` //推送设置详情
+        update xweb.Mapper `xweb:"/pushset/update"` //推送设置修改
 }
 
 type pushSet struct {
-	Item                string //推送设置项 member_subscribe super_subscribe free_subscribe follow_ent follow_project entniche
-	Ratemode            int    //推送时间 1:6-20点实时推送,2:每天9点推送,3:每周推送,4:每月推送
-	Apppush             int    //app推送
-	Mailpush            int    //邮箱推送
-	Mail                string //邮箱
-	Subscribe           int    //订阅
-	Follow_project      int    //项目关注
-	Follow_ent          int    //企业关注
-	Newproject_forecast int    //新项目预测
-	Analy_report        int    //分析报告
-	Entinfo             int    //企业情报
-	WXPush              int    // wx推送
+        Item                string //推送设置项 member_subscribe super_subscribe free_subscribe follow_ent follow_project entniche
+        Ratemode            int    //推送时间 1:6-20点实时推送,2:每天9点推送,3:每周推送,4:每月推送
+        Apppush             int    //app推送
+        Mailpush            int    //邮箱推送
+        Mail                string //邮箱
+        Subscribe           int    //订阅
+        Follow_project      int    //项目关注
+        Follow_ent          int    //企业关注
+        Newproject_forecast int    //新项目预测
+        Analy_report        int    //分析报告
+        Entinfo             int    //企业情报
+        WXPush              int    // wx推送
 }
 
+//后期
 //4.6.0修改 只把有权益的存入map返给前端, k:权益 v:是否开启
 func (a *Action) Items() {
-	userId, _ := a.GetSession("userId").(string)
-	user, _ := Mgo.FindById("user", userId, `{"i_member_status":1,"i_vip_status":1,"s_phone":1,"s_m_phone":1,"o_member_jy":1}`)
-	s_phone, _ := (*user)["s_phone"].(string)
-	if s_phone == "" {
-		s_phone, _ = (*user)["s_m_phone"].(string)
-	}
-	data := M{}
-	member_status := util.IntAll((*user)["i_member_status"])
-	vip_status := util.IntAll((*user)["i_vip_status"])
-	if vip_status > 0 {
-		data["super_subscribe"] = true //超级订阅
-	} else {
-		data["free_subscribe"] = true //免费订阅
-	}
-	if member_status > 0 {
-		o_member_jy, _ := (*user)["o_member_jy"].(map[string]interface{})
-		data["member_subscribe"] = OpenStatus(o_member_jy, "member_subscribe", a.Session()) //大会员订阅
-		delete(data, "free_subscribe")                                                      //有大会员订阅没有免费订阅
-	}
-	if member_status <= 0 && vip_status <= 0 {
-		data["follow_ent"] = true     //企业关注
-		data["follow_project"] = true //项目关注
-	}
-	//商机管理
-	if Mysql.Count("entniche_info", map[string]interface{}{
-		"phone":  s_phone,
-		"status": 1,
-	}) > 0 {
-		data["entniche"] = true
-	}
-	a.ServeJson(Result{
-		Data: data,
-	})
+        //userId, _ := a.GetSession("userId").(string)
+        bigMsg := jy.GetBigVipUserBaseMsg("10000", a.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        subScribeInfo := jy.GetSubScribeInfo(a.Session(), Mgo, "m", "10000")
+        /*user, _ := Mgo.FindById(C_User, userId, `{"i_member_status":1,"i_vip_status":1,"s_phone":1,"s_m_phone":1,"o_member_jy":1}`)
+          s_phone, _ := (*user)["s_phone"].(string)
+          if s_phone == "" {
+          	s_phone, _ = (*user)["s_m_phone"].(string)
+          }
+          data := M{}
+          member_status := util.IntAll((*user)["i_member_status"])
+          vip_status := util.IntAll((*user)["i_vip_status"])
+          if vip_status > 0 {
+          	data["super_subscribe"] = true //超级订阅
+          } else {
+          	data["super_subscribe"] = true //超级订阅
+          }
+          if member_status > 0 {
+          	o_member_jy, _ := (*user)["o_member_jy"].(map[string]interface{})
+          	data["member_subscribe"] = OpenStatus(o_member_jy, "member_subscribe", a.Session()) //大会员订阅
+          	delete(data, "free_subscribe")                                                      //有大会员订阅没有免费订阅
+          }
+          if member_status <= 0 && vip_status <= 0 {
+          	data["follow_ent"] = true     //企业关注
+          	data["follow_project"] = true //项目关注
+          }
+          //商机管理
+          if Mysql.Count("entniche_info", map[string]interface{}{
+          	"phone":  s_phone,
+          	"status": 1,
+          }) > 0 {
+          	data["entniche"] = true
+          }*/
+        data := M{}
+        data["super_subscribe"] = true //超级订阅
+        if bigMsg.Status > 0 {
+                data["member_subscribe"] = OpenStatus(*subScribeInfo, "member_subscribe", bigMsg) //大会员订阅
+                delete(data, "free_subscribe")
+        }
+        if bigMsg.Status <= 0 && bigMsg.VipStatus <= 0 {
+                data["follow_ent"] = true     //企业关注
+                data["follow_project"] = true //项目关注
+        }
+
+        data["entniche"] = bigMsg.IsEntService
+        a.ServeJson(Result{
+                Data: data,
+        })
 }
 func (a *Action) Detail() {
-	userId, _ := a.GetSession("userId").(string)
-	if !R.CheckReqParam(a.ResponseWriter, a.Request, "item") {
-		return
-	}
-	var data M
-	switch a.GetString("item") {
-	case "member_subscribe":
-		user, _ := Mgo.FindById("user", userId, `{"i_member_status":1,"s_myemail":1,"o_member_jy":1}`)
-		o_member_jy, _ := (*user)["o_member_jy"].(map[string]interface{})
-		mail, _ := o_member_jy["s_email"].(string)
-		if mail == "" {
-			mail, _ = (*user)["s_myemail"].(string)
-		}
-		data = M{
-			"ratemode":       util.IntAllDef(o_member_jy["i_ratemode"], 1),
-			"apppush":        util.IntAllDef(o_member_jy["i_apppush"], 1),
-			"mailpush":       util.IntAll(o_member_jy["i_mailpush"]),
-			"mail":           mail,
-			"subscribe":      util.IntAllDef(o_member_jy["i_subscribe"], 1),
-			"follow_project": util.IntAllDef(o_member_jy["i_follow_project"], 1),
-			"follow_ent":     util.IntAllDef(o_member_jy["i_follow_ent"], 1),
-			"wxpush":         util.IntAll(o_member_jy["i_wxpush"]),
-		}
-		power := []int{}
-		BigMsg := jy.GetBigVipUserBaseMsg("10000", a.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
-		for k, _ := range BigMsg.PowerMap {
-			power = append(power, k)
-		}
-		data["power"] = power
-		//潜在项目预测
-		if BigMsg.CheckBigVipBackPower("forecast") {
-			data["newproject_forecast"] = util.IntAllDef(o_member_jy["i_newproject_forecast"], 1)
-		}
-		//企业情报
-		if BigMsg.CheckBigVipBackPower("entChange") {
-			data["jy/src/jfw/modules/bigmember/src/entinfo"] = util.IntAllDef(o_member_jy["i_entinfo"], 1)
-		}
-		//分析报告
-		if BigMsg.CheckBigVipBackPower("report") {
-			data["analy_report"] = util.IntAllDef(o_member_jy["i_analy_report"], 1)
-		}
-	case "super_subscribe":
-		user, _ := Mgo.FindById("user", userId, `{"s_myemail":1,"o_vipjy":1}`)
-		o_vipjy, _ := (*user)["o_vipjy"].(map[string]interface{})
-		apppush := util.IntAll(o_vipjy["i_apppush"])
-		mailpush := util.IntAll(o_vipjy["i_mailpush"])
-		if apppush == 0 && mailpush == 0 {
-			apppush = 1
-		}
-		mail, _ := o_vipjy["s_email"].(string)
-		if mail == "" {
-			mail, _ = (*user)["s_myemail"].(string)
-		}
-		data = M{
-			"subscribe":      util.IntAllDef(o_vipjy["i_subscribe"], 1),      //订阅开关
-			"follow_ent":     util.IntAllDef(o_vipjy["i_follow_ent"], 1),     //关注企业推送开关
-			"follow_project": util.IntAllDef(o_vipjy["i_follow_project"], 1), //关注项目推送开关
-			"ratemode":       util.IntAllDef(o_vipjy["i_ratemode"], 2),
-			"apppush":        apppush,
-			"mailpush":       mailpush,
-			"mail":           mail,
-			"analy_report":   util.IntAllDef(o_vipjy["i_analy_report"], 1),
-			"wxpush":         util.IntAll(o_vipjy["i_wxpush"]),
-		}
-	case "free_subscribe":
-		user, _ := Mgo.FindById("user", userId, `{"s_myemail":1,"o_jy":1}`)
-		o_jy, _ := (*user)["o_jy"].(map[string]interface{})
-		apppush := util.IntAll(o_jy["i_apppush"])
-		mailpush := util.IntAll(o_jy["i_mailpush"])
-		if apppush == 0 && mailpush == 0 {
-			apppush = 1
-		}
-		mail, _ := o_jy["s_email"].(string)
-		if mail == "" {
-			mail, _ = (*user)["s_myemail"].(string)
-		}
-		data = M{
-			"apppush":  apppush,
-			"mailpush": mailpush,
-			"mail":     mail,
-		}
-	case "follow_ent":
-		user, _ := Mgo.FindById("user", 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"])
-		if apppush == 0 && mailpush == 0 {
-			apppush = 1
-		}
-		mail, _ := o_follow_ent["s_email"].(string)
-		if mail == "" {
-			mail, _ = (*user)["s_myemail"].(string)
-		}
-		data = M{
-			"apppush":  apppush,
-			"mailpush": mailpush,
-			"mail":     mail,
-		}
-	case "follow_project":
-		user, _ := Mgo.FindById("user", 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"])
-		if apppush == 0 && mailpush == 0 {
-			apppush = 1
-		}
-		mail, _ := o_follow_project["s_email"].(string)
-		if mail == "" {
-			mail, _ = (*user)["s_myemail"].(string)
-		}
-		data = M{
-			"apppush":  apppush,
-			"mailpush": mailpush,
-			"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{})
-		ratemode, apppush, mailpush := 0, 0, 0
-		mail := ""
-		flag := true
-		if len(o_entniche) == 0 {
-			phone, _ := (*user)["s_phone"]
-			if phone == "" {
-				phone, _ = (*user)["s_m_phone"]
-			}
-			entniche_user := Mysql.SelectBySql(`select a.id,a.ent_id,a.mail,b.model,c.dept_id from entniche_user a
+        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("10000", a.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        switch a.GetString("item") {
+        case "member_subscribe":
+                o_member_jy := jy.GetSubScribeInfo(a.Session(), Mgo, "m", "10000")
+                mail, _ := (*o_member_jy)["s_email"].(string)
+                if mail == "" {
+                        mail = bigMsg.Data.Free.Mail
+                }
+                data = M{
+                        "ratemode":       util.IntAllDef((*o_member_jy)["i_ratemode"], 1),
+                        "apppush":        util.IntAllDef((*o_member_jy)["i_apppush"], 1),
+                        "mailpush":       util.IntAll((*o_member_jy)["i_mailpush"]),
+                        "mail":           mail,
+                        "subscribe":      util.IntAllDef((*o_member_jy)["i_subscribe"], 1),
+                        "follow_project": util.IntAllDef((*o_member_jy)["i_follow_project"], 1),
+                        "follow_ent":     util.IntAllDef((*o_member_jy)["i_follow_ent"], 1),
+                        "wxpush":         util.IntAll((*o_member_jy)["i_wxpush"]),
+                }
+                power := []int{}
+                BigMsg := jy.GetBigVipUserBaseMsg("10000", a.Session(), config.Config.Etcd.Key, config.Config.Etcd.Key)
+                for k, _ := range BigMsg.PowerMap {
+                        power = append(power, k)
+                }
+                data["power"] = power
+                //潜在项目预测
+                if BigMsg.CheckBigVipBackPower("forecast") {
+                        data["newproject_forecast"] = util.IntAllDef((*o_member_jy)["i_newproject_forecast"], 1)
+                }
+                //企业情报
+                if BigMsg.CheckBigVipBackPower("entChange") {
+                        data["jy/src/jfw/modules/bigmember/src/entinfo"] = util.IntAllDef((*o_member_jy)["i_entinfo"], 1)
+                }
+                //分析报告
+                if BigMsg.CheckBigVipBackPower("report") {
+                        data["analy_report"] = util.IntAllDef((*o_member_jy)["i_analy_report"], 1)
+                }
+        case "super_subscribe":
+                o_vipjy := jy.GetSubScribeInfo(a.Session(), Mgo, "v", "10000")
+                apppush := util.IntAll((*o_vipjy)["i_apppush"])
+                mailpush := util.IntAll((*o_vipjy)["i_mailpush"])
+                if apppush == 0 && mailpush == 0 {
+                        apppush = 1
+                }
+                mail, _ := (*o_vipjy)["s_email"].(string)
+                if mail == "" {
+                        mail = bigMsg.Data.Free.Mail
+                }
+                data = M{
+                        "subscribe":      util.IntAllDef((*o_vipjy)["i_subscribe"], 1),      //订阅开关
+                        "follow_ent":     util.IntAllDef((*o_vipjy)["i_follow_ent"], 1),     //关注企业推送开关
+                        "follow_project": util.IntAllDef((*o_vipjy)["i_follow_project"], 1), //关注项目推送开关
+                        "ratemode":       util.IntAllDef((*o_vipjy)["i_ratemode"], 2),
+                        "apppush":        apppush,
+                        "mailpush":       mailpush,
+                        "mail":           mail,
+                        "analy_report":   util.IntAllDef((*o_vipjy)["i_analy_report"], 1),
+                        "wxpush":         util.IntAll((*o_vipjy)["i_wxpush"]),
+                }
+        case "free_subscribe":
+                //user, _ := Mgo.FindById(C_User, userId, `{"s_myemail":1,"o_jy":1}`)
+                o_jy := jy.GetSubScribeInfo(a.Session(), Mgo, "f", "10000")
+                //o_jy, _ := (*user)["o_jy"].(map[string]interface{})
+                apppush := util.IntAll((*o_jy)["i_apppush"])
+                mailpush := util.IntAll((*o_jy)["i_mailpush"])
+                if apppush == 0 && mailpush == 0 {
+                        apppush = 1
+                }
+                mail, _ := (*o_jy)["s_email"].(string)
+                if mail == "" {
+                        mail = bigMsg.Data.Free.Mail
+                }
+                data = M{
+                        "apppush":  apppush,
+                        "mailpush": mailpush,
+                        "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}`)
+                }
+                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"])
+                if apppush == 0 && mailpush == 0 {
+                        apppush = 1
+                }
+                mail, _ := o_follow_ent["s_email"].(string)
+                if mail == "" {
+                        mail = bigMsg.Data.Free.Mail
+                }
+                data = M{
+                        "apppush":  apppush,
+                        "mailpush": mailpush,
+                        "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}`)
+                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"])
+                if apppush == 0 && mailpush == 0 {
+                        apppush = 1
+                }
+                mail, _ := o_follow_project["s_email"].(string)
+                if mail == "" {
+                        mail = bigMsg.Data.Free.Mail
+                }
+                data = M{
+                        "apppush":  apppush,
+                        "mailpush": mailpush,
+                        "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)
-					user_id := util.IntAll((*entniche_user)[0]["id"])
-					ent_id := util.IntAll((*entniche_user)[0]["ent_id"])
-					var query map[string]interface{}
-					if model == 1 {
-						dept_id := util.IntAll((*entniche_user)[0]["dept_id"])
-						user_rule := map[int]bool{}
-						for _, v := range *Mysql.SelectBySql(`select dept_id from entniche_user_rule where user_id=?`, user_id) {
-							user_rule[util.IntAll(v["dept_id"])] = true
-						}
-						did := dept_id
-						for {
-							department := Mysql.SelectBySql(`select pid,nodiff,subdis from entniche_department where id=?`, did)
-							if len(*department) != 1 {
-								break
-							} else {
-								if util.IntAll((*department)[0]["subdis"]) == 1 && (util.IntAll((*department)[0]["nodiff"]) == 1 || user_rule[did]) {
-									dept_id = did
-								}
-								pid := util.IntAll((*department)[0]["pid"])
-								if pid == 0 {
-									break
-								}
-								did = pid
-							}
-						}
-						query = map[string]interface{}{
-							"i_entid":  ent_id,
-							"i_deptid": dept_id,
-						}
-					} else if model == 2 {
-						query = map[string]interface{}{
-							"i_entid":  ent_id,
-							"i_userid": user_id,
-						}
-					}
-					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, _ = (*user)["s_myemail"].(string)
-		}
-		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
-	}
-	a.ServeJson(Result{Data: data})
+                        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
+        }
+        a.ServeJson(Result{Data: data})
 }
 
 func (a *Action) Update() {
-	userId, _ := a.GetSession("userId").(string)
-	ps := pushSet{
-		Subscribe:           -1,
-		Follow_project:      -1,
-		Follow_ent:          -1,
-		Newproject_forecast: -1,
-		Analy_report:        -1,
-		Entinfo:             -1,
-	}
-	err := json.Unmarshal(a.Body(), &ps)
-	status := 0
-	if err == nil {
-		if ps.Mailpush == 1 && ps.Mail == "" {
-			R.InvalidReqParam(a.ResponseWriter, a.Request, "mail")
-			return
-		} else if ps.Item != "member_subscribe" && ps.Apppush == 0 && ps.Mailpush == 0 {
-			R.InvalidReqParam(a.ResponseWriter, a.Request, "apppush mailpush 至少打开一个")
-			return
-		}
-		var set map[string]interface{}
-		switch ps.Item {
-		case "member_subscribe":
-			set = map[string]interface{}{
-				"o_member_jy.i_ratemode":   ps.Ratemode,
-				"o_member_jy.i_apppush":    ps.Apppush,
-				"o_member_jy.i_mailpush":   ps.Mailpush,
-				"o_member_jy.s_email":      ps.Mail,
-				"o_member_jy.l_modifydate": time.Now().Unix(),
-				"o_member_jy.i_wxpush":     ps.WXPush,
-			}
-			if ps.Subscribe >= 0 {
-				set["o_member_jy.i_subscribe"] = ps.Subscribe
-			}
-			if ps.Follow_project >= 0 {
-				set["o_member_jy.i_follow_project"] = ps.Follow_project
-			}
-			if ps.Follow_ent >= 0 {
-				set["o_member_jy.i_follow_ent"] = ps.Follow_ent
-			}
-			if ps.Newproject_forecast >= 0 {
-				set["o_member_jy.i_newproject_forecast"] = ps.Newproject_forecast
-			}
-			if ps.Analy_report >= 0 {
-				set["o_member_jy.i_analy_report"] = ps.Analy_report
-			}
-			if ps.Entinfo >= 0 {
-				set["o_member_jy.i_entinfo"] = ps.Entinfo
-			}
-		case "super_subscribe":
-			set = map[string]interface{}{
-				"o_vipjy.i_subscribe":      ps.Subscribe,      //订阅开关
-				"o_vipjy.i_follow_ent":     ps.Follow_ent,     //关注企业推送开关
-				"o_vipjy.i_follow_project": ps.Follow_project, //关注项目推送开关
-				"o_vipjy.i_ratemode":       ps.Ratemode,
-				"o_vipjy.i_apppush":        ps.Apppush,
-				"o_vipjy.i_mailpush":       ps.Mailpush,
-				"o_vipjy.s_email":          ps.Mail,
-				"o_vipjy.l_modifydate":     time.Now().Unix(),
-				"o_vipjy.i_analy_report":   ps.Analy_report,
-			}
-		case "free_subscribe":
-			set = map[string]interface{}{
-				"o_jy.i_apppush":    ps.Apppush,
-				"o_jy.i_mailpush":   ps.Mailpush,
-				"o_jy.s_email":      ps.Mail,
-				"o_jy.l_modifydate": time.Now().Unix(),
-			}
-		case "follow_ent":
-			set = map[string]interface{}{
-				"o_follow_ent.i_apppush":    ps.Apppush,
-				"o_follow_ent.i_mailpush":   ps.Mailpush,
-				"o_follow_ent.s_email":      ps.Mail,
-				"o_follow_ent.l_modifydate": time.Now().Unix(),
-			}
-		case "follow_project":
-			set = map[string]interface{}{
-				"o_follow_project.i_apppush":    ps.Apppush,
-				"o_follow_project.i_mailpush":   ps.Mailpush,
-				"o_follow_project.s_email":      ps.Mail,
-				"o_follow_project.l_modifydate": time.Now().Unix(),
-			}
-		case "entniche":
-			set = map[string]interface{}{
-				"o_entniche.i_ratemode":   ps.Ratemode,
-				"o_entniche.i_apppush":    ps.Apppush,
-				"o_entniche.i_mailpush":   ps.Mailpush,
-				"o_entniche.s_email":      ps.Mail,
-				"o_entniche.l_modifydate": time.Now().Unix(),
-			}
-		default:
-			R.InvalidReqParam(a.ResponseWriter, a.Request, "item")
-			return
-		}
-		if set != nil && Mgo.UpdateById("user", userId, map[string]interface{}{"$set": set}) {
-			status = 1
-		}
-	} else {
-		log.Println("修改推送设置 json.Unmarshal 出错:", err)
-		R.InvalidReqParam(a.ResponseWriter, a.Request, "json格式错误")
-		return
-	}
-	a.ServeJson(Result{Data: M{"status": status}})
+        userId, _ := a.GetSession("userId").(string)
+        positionType := util.Int64All(a.GetSession("positionType"))
+        ps := pushSet{
+                Subscribe:           -1,
+                Follow_project:      -1,
+                Follow_ent:          -1,
+                Newproject_forecast: -1,
+                Analy_report:        -1,
+                Entinfo:             -1,
+        }
+        err := json.Unmarshal(a.Body(), &ps)
+        status := 0
+        if err == nil {
+                if ps.Mailpush == 1 && ps.Mail == "" {
+                        R.InvalidReqParam(a.ResponseWriter, a.Request, "mail")
+                        return
+                } else if ps.Item != "member_subscribe" && ps.Apppush == 0 && ps.Mailpush == 0 {
+                        R.InvalidReqParam(a.ResponseWriter, a.Request, "apppush mailpush 至少打开一个")
+                        return
+                }
+                var set map[string]interface{}
+                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,
+                                fmt.Sprintf("%s.i_mailpush", mType):   ps.Mailpush,
+                                fmt.Sprintf("%s.s_email", mType):      ps.Mail,
+                                fmt.Sprintf("%s.l_modifydate", mType): time.Now().Unix(),
+                                fmt.Sprintf("%s.i_wxpush", mType):     ps.WXPush,
+                        }
+                        if ps.Subscribe >= 0 {
+                                set[fmt.Sprintf("%s.i_subscribe", mType)] = ps.Subscribe
+                        }
+                        if ps.Follow_project >= 0 {
+                                set[fmt.Sprintf("%s.i_ratemode", mType)] = ps.Follow_project
+                        }
+                        if ps.Follow_ent >= 0 {
+                                set[fmt.Sprintf("%s.i_ratemode", mType)] = ps.Follow_ent
+                        }
+                        if ps.Newproject_forecast >= 0 {
+                                set[fmt.Sprintf("%s.i_ratemode", mType)] = ps.Newproject_forecast
+                        }
+                        if ps.Analy_report >= 0 {
+                                set[fmt.Sprintf("%s.i_ratemode", mType)] = ps.Analy_report
+                        }
+                        if ps.Entinfo >= 0 {
+                                set[fmt.Sprintf("%s.i_ratemode", mType)] = ps.Entinfo
+                        }
+                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,     //关注企业推送开关
+                                fmt.Sprintf("%s.i_follow_project", vType): ps.Follow_project, //关注项目推送开关
+                                fmt.Sprintf("%s.i_ratemode", vType):       ps.Ratemode,
+                                fmt.Sprintf("%s.i_apppush", vType):        ps.Apppush,
+                                fmt.Sprintf("%s.i_mailpush", vType):       ps.Mailpush,
+                                fmt.Sprintf("%s.s_email", vType):          ps.Mail,
+                                fmt.Sprintf("%s.l_modifydate", vType):     time.Now().Unix(),
+                                fmt.Sprintf("%s.i_analy_report", vType):   ps.Analy_report,
+                        }
+                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,
+                                fmt.Sprintf("%s.s_email", ftype):      ps.Mail,
+                                fmt.Sprintf("%s.l_modifydate", ftype): time.Now().Unix(),
+                        }
+                case "follow_ent":
+                        set = map[string]interface{}{
+                                "o_follow_ent.i_apppush":    ps.Apppush,
+                                "o_follow_ent.i_mailpush":   ps.Mailpush,
+                                "o_follow_ent.s_email":      ps.Mail,
+                                "o_follow_ent.l_modifydate": time.Now().Unix(),
+                        }
+                case "follow_project":
+                        set = map[string]interface{}{
+                                "o_follow_project.i_apppush":    ps.Apppush,
+                                "o_follow_project.i_mailpush":   ps.Mailpush,
+                                "o_follow_project.s_email":      ps.Mail,
+                                "o_follow_project.l_modifydate": time.Now().Unix(),
+                        }
+                default:
+                        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
+                        }
+                }
+        } else {
+                log.Println("修改推送设置 json.Unmarshal 出错:", err)
+                R.InvalidReqParam(a.ResponseWriter, a.Request, "json格式错误")
+                return
+        }
+        a.ServeJson(Result{Data: M{"status": status}})
 }
 
 //判断按钮是否全部开启
-func OpenStatus(ojy map[string]interface{}, types string, session *httpsession.Session) bool {
-	push, data := M{}, M{}
-	pushStatus, subscribe := false, false
-	switch types {
-	case "member_subscribe":
-		push = M{
-			"apppush":  util.IntAllDef(ojy["i_apppush"], 1),
-			"mailpush": util.IntAll(ojy["i_mailpush"]),
-		}
-		data = M{
-			"subscribe":      util.IntAllDef(ojy["i_subscribe"], 1),
-			"follow_project": util.IntAllDef(ojy["i_follow_project"], 1),
-			"follow_ent":     util.IntAllDef(ojy["i_follow_ent"], 1),
-		}
-		power := []int{}
-		BigMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key)
-		for k, _ := range BigMsg.PowerMap {
-			power = append(power, k)
-		}
-		//潜在项目预测
-		if BigMsg.CheckBigVipBackPower("forecast") {
-			data["newproject_forecast"] = util.IntAllDef(ojy["i_newproject_forecast"], 1)
-		}
-		//企业情报
-		if BigMsg.CheckBigVipBackPower("entChange") {
-			data["jy/src/jfw/modules/bigmember/src/entinfo"] = util.IntAllDef(ojy["i_entinfo"], 1)
-		}
-		//分析报告
-		if BigMsg.CheckBigVipBackPower("report") {
-			data["analy_report"] = util.IntAllDef(ojy["i_analy_report"], 1)
-		}
-	}
+func OpenStatus(ojy map[string]interface{}, types string, BigMsg *jy.BigVipBaseMsg) bool {
+        push, data := M{}, M{}
+        pushStatus, subscribe := false, false
+        switch types {
+        case "member_subscribe":
+                push = M{
+                        "apppush":  util.IntAllDef(ojy["i_apppush"], 1),
+                        "mailpush": util.IntAll(ojy["i_mailpush"]),
+                }
+                data = M{
+                        "subscribe":      util.IntAllDef(ojy["i_subscribe"], 1),
+                        "follow_project": util.IntAllDef(ojy["i_follow_project"], 1),
+                        "follow_ent":     util.IntAllDef(ojy["i_follow_ent"], 1),
+                }
+                power := []int{}
+                //BigMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key)
+                for k, _ := range BigMsg.PowerMap {
+                        power = append(power, k)
+                }
+                //潜在项目预测
+                if BigMsg.CheckBigVipBackPower("forecast") {
+                        data["newproject_forecast"] = util.IntAllDef(ojy["i_newproject_forecast"], 1)
+                }
+                //企业情报
+                if BigMsg.CheckBigVipBackPower("entChange") {
+                        data["jy/src/jfw/modules/bigmember/src/entinfo"] = util.IntAllDef(ojy["i_entinfo"], 1)
+                }
+                //分析报告
+                if BigMsg.CheckBigVipBackPower("report") {
+                        data["analy_report"] = util.IntAllDef(ojy["i_analy_report"], 1)
+                }
+        }
 
-	for _, v := range data {
-		if util.IntAll(v) > 0 {
-			subscribe = true
-			break
-		}
-	}
-	for _, v := range push {
-		if util.Int64All(v) > 0 {
-			pushStatus = true
-			break
-		}
-	}
-	return subscribe && pushStatus
+        for _, v := range data {
+                if util.IntAll(v) > 0 {
+                        subscribe = true
+                        break
+                }
+        }
+        for _, v := range push {
+                if util.Int64All(v) > 0 {
+                        pushStatus = true
+                        break
+                }
+        }
+        return subscribe && pushStatus
 }

+ 201 - 177
src/jfw/modules/bigmember/src/service/report/marketAnalysis.go

@@ -1,208 +1,232 @@
 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/db"
+        "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("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key)
-	return bigMeg.Pid, nil
+        userId := qutil.InterfaceToStr(session.Get("base_user_id"))
+        if userId == "" {
+                return "", fmt.Errorf("未登录")
+        }
+        //仅购买《周报/月报/定制化市场分析报告》的大会员有权限
+        bigMeg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key)
+        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(userid, "", 0)
-		d := map[string]interface{}{
-			"member_status": 0,
-		}
-		data, _ := db.Mgo.FindById("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.IntAll((*data)["i_member_status"])
-		i_vip_status := qutil.IntAll((*data)["i_vip_status"])
-
-		o_member_jy := qutil.ObjToMap((*data)["o_member_jy"])
-		oJy, _ := (*data)["o_jy"].(map[string]interface{})      //免费用户关键词
-		vipJy, _ := (*data)["o_vipjy"].(map[string]interface{}) //超级订阅关键词
-		if i_member_status > 0 {
-			btip, _ := (*o_member_jy)["b_keytip"].(bool)
-			KeyWord(btip, i_member_status, qutil.IntAll((*data)["i_member_starttime"]), qutil.IntAll((*data)["i_member_starttime"]), *o_member_jy, *data, d)
-		} else if i_vip_status > 0 {
-			btip, _ := vipJy["b_keytip"].(bool)
-			KeyWord(btip, i_vip_status, qutil.IntAll((*data)["l_vip_endtime"]), qutil.IntAll((*data)["l_vip_starttime"]), vipJy, *data, 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)
+                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("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                        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)
 }
 
-func KeyWord(btip bool, status, i_member_starttime, i_member_endtime int, o_member_jy, data, 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
-						}
-					}
-				}
-			}
-		}
+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
+                                                }
+                                        }
+                                }
+                        }
+                }
 
-		//订阅设置优化版本上线之前的用户弹窗提醒
-		optime := time.Unix(config.Config.OldSubscribeMoveTip, 0)
-		regtime, _ := data["l_registedate"].(int64)
-		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
 }

+ 535 - 511
src/jfw/modules/bigmember/src/service/report/report.go

@@ -1,592 +1,616 @@
 package report
 
 import (
-	"fmt"
-	. "jy/src/jfw/modules/bigmember/src/db"
-	"sort"
-	"strings"
-	"time"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/config"
+        . "jy/src/jfw/modules/bigmember/src/db"
+        "sort"
+        "strings"
+        "time"
 
-	. "app.yhyue.com/moapp/jybase/api"
-	util "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/jybase/api"
+        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"
 )
 
 // Report vip订阅报告
 type Report struct {
-	*xweb.Action
-	index       xweb.Mapper `xweb:"/report/index"`
-	detail      xweb.Mapper `xweb:"/report/detail"`
-	tip         xweb.Mapper `xweb:"/report/tip"`
-	tipover     xweb.Mapper `xweb:"/report/tipover"`
-	openpushmsg xweb.Mapper `xweb:"/report/openpushmsg"`
-	starttime   xweb.Mapper `xweb:"/report/starttime"`
+        *xweb.Action
+        index       xweb.Mapper `xweb:"/report/index"`
+        detail      xweb.Mapper `xweb:"/report/detail"`
+        tip         xweb.Mapper `xweb:"/report/tip"`
+        tipover     xweb.Mapper `xweb:"/report/tipover"`
+        openpushmsg xweb.Mapper `xweb:"/report/openpushmsg"`
+        starttime   xweb.Mapper `xweb:"/report/starttime"`
 }
 
 type BarChart struct {
-	Key        int64       `json:"key"`
-	Value      interface{} `json:"value"`
-	GrowthRate float64     `json:"growthrate"`
+        Key        int64       `json:"key"`
+        Value      interface{} `json:"value"`
+        GrowthRate float64     `json:"growthrate"`
 }
 
 type BarCharts struct {
-	Keys map[int64]bool
-	List []*BarChart
+        Keys map[int64]bool
+        List []*BarChart
 }
 
 func (s BarCharts) Len() int {
-	return len(s.List)
+        return len(s.List)
 }
 
 func (s BarCharts) Less(i, j int) bool {
-	return s.List[i].Key < s.List[j].Key
+        return s.List[i].Key < s.List[j].Key
 }
 
 func (s BarCharts) Swap(i, j int) {
-	s.List[i], s.List[j] = s.List[j], s.List[i]
+        s.List[i], s.List[j] = s.List[j], s.List[i]
 }
 
 const (
-	oneday                                       = 86400
-	pushspace_experience_member_statistic        = "pushspace_experience_member_statistic"
-	pushspace_experience_member_statistic_winner = "pushspace_experience_member_statistic_winner"
-	pushspace_member_statistic                   = "pushspace_member_statistic"
-	pushspace_member_statistic_winner            = "pushspace_member_statistic_winner"
+        oneday                                       = 86400
+        pushspace_experience_member_statistic        = "pushspace_experience_member_statistic"
+        pushspace_experience_member_statistic_winner = "pushspace_experience_member_statistic_winner"
+        pushspace_member_statistic                   = "pushspace_member_statistic"
+        pushspace_member_statistic_winner            = "pushspace_member_statistic_winner"
+        C_User                                       = "user"
+        C_Entniche_Rule                              = "entniche_rule"
 )
 
 func (r *Report) Index() {
-	if !R.CheckReqParam(r.ResponseWriter, r.Request, "ym") {
-		return
-	}
-	ym := r.GetString("ym")
-	result := M{}
-	userId, qk, qv := getQuery(r.Session())
-	if qk == "" || qv == nil {
-		return
-	}
-	// userId, _, _ = MainUserId(userId, "", 0)
-	var query map[string]interface{}
-	if len(ym) == 4 {
-		query = map[string]interface{}{
-			qk: qv,
-			"dateym": map[string]interface{}{
-				"$gte": util.IntAll(ym + "00"),
-				"$lt":  util.IntAll(ym+"00") + 100,
-			},
-			"type": 3,
-		}
-	} else if len(ym) == 6 {
-		query = map[string]interface{}{
-			qk:       qv,
-			"dateym": util.IntAll(ym),
-			"type":   2,
-		}
-	} else {
-		R.InvalidReqParam(r.ResponseWriter, r.Request, "ym")
-		return
-	}
-	list, ok := Mgo.Find(pushspace_member_statistic, query, `{"startdate":-1}`, `{"startdate":1,"enddate":1,"pushcount":1,"pushtime":1,"unread":1}`, false, -1, -1)
-	array := []map[string]interface{}{}
-	if ok && list != nil {
-		for _, v := range *list {
-			array = append(array, map[string]interface{}{
-				"pushtime":  v["pushtime"],
-				"pushcount": v["pushcount"],
-				"unread":    util.IntAll(v["unread"]),
-				"startdate": v["startdate"],
-				"enddate":   v["enddate"],
-			})
-		}
-	}
-	result["list"] = array
-	result["subscribe"] = false
-	user, ok := Mgo.FindById("user", userId, `{"o_member_jy":1,"i_member_status":1,"s_member_mainid":1,"i_member_sub_status":1}`)
-	if ok && user != nil {
-		if s_member_mainid := util.ObjToString((*user)["s_member_mainid"]); s_member_mainid != "" && util.IntAll((*user)["i_member_sub_status"]) == 1 && util.IntAll((*user)["i_member_status"]) > 0 {
-			user, ok = Mgo.FindById("user", s_member_mainid, `{"o_member_jy":1}`)
-		}
-	}
-	if ok && user != nil {
-		o_member_jy, _ := (*user)["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 {
-			result["subscribe"] = true
-		} else {
-			a_items, _ := o_member_jy["a_items"].([]interface{})
-		L:
-			for _, a_item := range a_items {
-				itemMap, _ := a_item.(map[string]interface{})
-				a_keys, _ := itemMap["a_key"].([]interface{})
-				for _, a_key := range a_keys {
-					keyMap, _ := a_key.(map[string]interface{})
-					keys, _ := keyMap["key"].([]interface{})
-					for _, key := range keys {
-						if strings.TrimSpace(util.ObjToString(key)) != "" {
-							result["subscribe"] = true
-							break L
-						}
-					}
-				}
-			}
-		}
-	}
-	r.ServeJson(Result{
-		Data: result,
-	})
+        if !R.CheckReqParam(r.ResponseWriter, r.Request, "ym") {
+                return
+        }
+        ym := r.GetString("ym")
+        result := M{}
+        userId, qk, qv := getQuery(r.Session())
+        if qk == "" || qv == nil {
+                return
+        }
+        // userId, _, _ = MainUserId(userId, "", 0)
+        var query map[string]interface{}
+        if len(ym) == 4 {
+                query = map[string]interface{}{
+                        qk: qv,
+                        "dateym": map[string]interface{}{
+                                "$gte": qutil.IntAll(ym + "00"),
+                                "$lt":  qutil.IntAll(ym+"00") + 100,
+                        },
+                        "type": 3,
+                }
+        } else if len(ym) == 6 {
+                query = map[string]interface{}{
+                        qk:       qv,
+                        "dateym": qutil.IntAll(ym),
+                        "type":   2,
+                }
+        } else {
+                R.InvalidReqParam(r.ResponseWriter, r.Request, "ym")
+                return
+        }
+        list, ok := Mgo.Find(pushspace_member_statistic, query, `{"startdate":-1}`, `{"startdate":1,"enddate":1,"pushcount":1,"pushtime":1,"unread":1}`, false, -1, -1)
+        array := []map[string]interface{}{}
+        if ok && list != nil {
+                for _, v := range *list {
+                        array = append(array, map[string]interface{}{
+                                "pushtime":  v["pushtime"],
+                                "pushcount": v["pushcount"],
+                                "unread":    qutil.IntAll(v["unread"]),
+                                "startdate": v["startdate"],
+                                "enddate":   v["enddate"],
+                        })
+                }
+        }
+        result["list"] = array
+        result["subscribe"] = false
+        positionType := qutil.Int64All(r.GetSession("positionType"))
+        o_mb := &map[string]interface{}{}
+        if positionType == 0 {
+                data:=jy.GetBigVipUserBaseMsg("10000",r.Session(),config.Config.Etcd.Hosts,config.Config.Etcd.Key)
+                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)["o_entniche"]
+                        }
+                }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"]
+                }
+        }
+
+        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 {
+                        result["subscribe"] = true
+                } else {
+                        a_items, _ := o_member_jy["a_items"].([]interface{})
+                L:
+                        for _, a_item := range a_items {
+                                itemMap, _ := a_item.(map[string]interface{})
+                                a_keys, _ := itemMap["a_key"].([]interface{})
+                                for _, a_key := range a_keys {
+                                        keyMap, _ := a_key.(map[string]interface{})
+                                        keys, _ := keyMap["key"].([]interface{})
+                                        for _, key := range keys {
+                                                if strings.TrimSpace(qutil.ObjToString(key)) != "" {
+                                                        result["subscribe"] = true
+                                                        break L
+                                                }
+                                        }
+                                }
+                        }
+                }
+        }
+        r.ServeJson(Result{
+                Data: result,
+        })
 }
 func (r *Report) Detail() {
-	if !R.CheckReqParam(r.ResponseWriter, r.Request, "start", "end") {
-		return
-	}
-	start, _ := r.GetInt("start")
-	end, _ := r.GetInt("end")
-	var m M
-	userId, qk, qv := getQuery(r.Session())
-	if qk == "" || qv == nil {
-		return
-	}
-	coll, coll_winner := getColl(r.Header("referer"), r.GetString("type"))
-	// userId, _, _ = MainUserId(userId, "", 0)
-	if end-start == 518400 { //周
-		m = weekResult(qk, qv, start, end, coll, coll_winner)
-	} else if 518400 < end-start && end-start <= 2592000 { //月
-		m = monthResult(userId, qk, qv, start, end, coll, coll_winner)
-	} else {
-		R.InvalidReqParam(r.ResponseWriter, r.Request, "start", "end")
-		return
-	}
-	go Mgo.Update(coll, map[string]interface{}{
-		qk:          qv,
-		"startdate": start,
-		"enddate":   end,
-	}, map[string]interface{}{
-		"$set": map[string]interface{}{
-			"unread": 0,
-		},
-	}, false, true)
-	r.ServeJson(Result{
-		Data: m,
-	})
+        if !R.CheckReqParam(r.ResponseWriter, r.Request, "start", "end") {
+                return
+        }
+        start, _ := r.GetInt("start")
+        end, _ := r.GetInt("end")
+        var m M
+        userId, qk, qv := getQuery(r.Session())
+        if qk == "" || qv == nil {
+                return
+        }
+        coll, coll_winner := getColl(r.Header("referer"), r.GetString("type"))
+        // userId, _, _ = MainUserId(userId, "", 0)
+        if end-start == 518400 { //周
+                m = weekResult(qk, qv, start, end, coll, coll_winner)
+        } else if 518400 < end-start && end-start <= 2592000 { //月
+                m = monthResult(userId, qk, qv, start, end, coll, coll_winner)
+        } else {
+                R.InvalidReqParam(r.ResponseWriter, r.Request, "start", "end")
+                return
+        }
+        go Mgo.Update(coll, map[string]interface{}{
+                qk:          qv,
+                "startdate": start,
+                "enddate":   end,
+        }, map[string]interface{}{
+                "$set": map[string]interface{}{
+                        "unread": 0,
+                },
+        }, false, true)
+        r.ServeJson(Result{
+                Data: m,
+        })
 }
 
 //周报
 func weekResult(qk string, qv interface{}, start, end int64, coll, coll_winner string) M {
-	prevWeekStartDate := start - 7*oneday
-	list, ok := Mgo.Find(coll, map[string]interface{}{
-		qk: qv,
-		"startdate": map[string]interface{}{
-			"$gte": prevWeekStartDate,
-		},
-		"enddate": map[string]interface{}{
-			"$lte": end,
-		},
-		"type": 2,
-	}, `{"startdate":1}`, `{"startdate":1,"type":1,"item":1,"bidamount":1,"budget":1,"zhao_matchitem":1,"zhong_matchitem":1,"follow_project":1,"follow_ent":1,"nextweek_bidopen":1,"project_amount":1}`, false, 0, 2)
-	result := M{}
-	prevWeek := map[string]interface{}{}
-	if ok && list != nil {
-		for _, v := range *list {
-			if util.Int64All(v["startdate"]) == prevWeekStartDate {
-				prevWeek = v
-				continue
-			}
-			//订阅关键词组
-			result["item"] = v["item"]
-			//本周新增招标项目数量
-			result["zhao_matchitem"] = v["zhao_matchitem"]
-			//本周新增开标项目数量
-			result["zhong_matchitem"] = v["zhong_matchitem"]
-			//重点关注项目
-			result["follow_project"] = v["follow_project"]
-			//重点关注企业
-			result["follow_ent"] = v["follow_ent"]
-			//下周开标提醒
-			result["nextweek_bidopen"] = v["nextweek_bidopen"]
-			//项目金额排行榜
-			result["project_amount"] = v["project_amount"]
-			//本周新增招标项目预算
-			result["budget"] = matchitemGrowthRateHandle(prevWeek, v, "budget", "budget")
-			//本周新增招标项目规模
-			result["bidamount"] = matchitemGrowthRateHandle(prevWeek, v, "bidamount", "bidamount")
-		}
-	}
-	return result
+        prevWeekStartDate := start - 7*oneday
+        list, ok := Mgo.Find(coll, map[string]interface{}{
+                qk: qv,
+                "startdate": map[string]interface{}{
+                        "$gte": prevWeekStartDate,
+                },
+                "enddate": map[string]interface{}{
+                        "$lte": end,
+                },
+                "type": 2,
+        }, `{"startdate":1}`, `{"startdate":1,"type":1,"item":1,"bidamount":1,"budget":1,"zhao_matchitem":1,"zhong_matchitem":1,"follow_project":1,"follow_ent":1,"nextweek_bidopen":1,"project_amount":1}`, false, 0, 2)
+        result := M{}
+        prevWeek := map[string]interface{}{}
+        if ok && list != nil {
+                for _, v := range *list {
+                        if qutil.Int64All(v["startdate"]) == prevWeekStartDate {
+                                prevWeek = v
+                                continue
+                        }
+                        //订阅关键词组
+                        result["item"] = v["item"]
+                        //本周新增招标项目数量
+                        result["zhao_matchitem"] = v["zhao_matchitem"]
+                        //本周新增开标项目数量
+                        result["zhong_matchitem"] = v["zhong_matchitem"]
+                        //重点关注项目
+                        result["follow_project"] = v["follow_project"]
+                        //重点关注企业
+                        result["follow_ent"] = v["follow_ent"]
+                        //下周开标提醒
+                        result["nextweek_bidopen"] = v["nextweek_bidopen"]
+                        //项目金额排行榜
+                        result["project_amount"] = v["project_amount"]
+                        //本周新增招标项目预算
+                        result["budget"] = matchitemGrowthRateHandle(prevWeek, v, "budget", "budget")
+                        //本周新增招标项目规模
+                        result["bidamount"] = matchitemGrowthRateHandle(prevWeek, v, "bidamount", "bidamount")
+                }
+        }
+        return result
 }
 
 //月报
 func monthResult(userId, qk string, qv interface{}, start, end int64, coll, coll_winner string) M {
-	result := M{}
-	//最近6个月
-	fiveMonthStart := time.Unix(start, 0).AddDate(0, -5, 0).Unix()
-	sixDatas, ok := Mgo.Find(coll, map[string]interface{}{
-		qk:     qv,
-		"type": 3,
-		"startdate": map[string]interface{}{
-			"$gte": fiveMonthStart,
-		},
-		"enddate": map[string]interface{}{
-			"$lte": end,
-		},
-	}, `{"startdate":1}`, `{"startdate":1,"item":1,"project_matchitem_count":1,"project_matchitem_bidamount":1,"project_count":1,"project_bidamount_count":1,"project_area_count":1,"project_area_bidamount":1,"project_buyerclass_count":1,"project_buyerclass_bidamount":1,"project_buyerclass_average_bidamount":1,"winner_area":1,"buyer":1,"winner":1,"project_bidamount":1}`, false, -1, -1)
-	if ok && sixDatas != nil {
-		project_count := &BarCharts{
-			Keys: map[int64]bool{},
-		}
-		project_bidamount_count := &BarCharts{
-			Keys: map[int64]bool{},
-		}
-		earliest := map[string]interface{}{}
-		for _, v := range *sixDatas {
-			startdate := util.Int64All(v["startdate"])
-			if startdate == fiveMonthStart { //上个月
-				earliest = v
-				continue
-			} else if startdate == start { //本月
-				//订阅关键词组
-				result["item"] = v["item"]
-				//本月项目规模
-				result["project_matchitem_count"] = v["project_matchitem_count"]
-				//本月项目规模
-				result["project_matchitem_bidamount"] = matchitemGrowthRateHandle(earliest, v, "project_matchitem_bidamount", "bidamount")
-				//本月项目数量分布
-				result["project_area_count"] = v["project_area_count"]
-				//本月项目规模分布
-				result["project_area_bidamount"] = v["project_area_bidamount"]
-				//本月项目数量TOP10采购行业
-				result["project_buyerclass_count"] = v["project_buyerclass_count"]
-				//本月项目规模TOP10采购行业
-				result["project_buyerclass_bidamount"] = v["project_buyerclass_bidamount"]
-				//本月项目平均规模TOP10采购行业
-				result["project_buyerclass_average_bidamount"] = v["project_buyerclass_average_bidamount"]
-				//本月中标企业注册地分布
-				result["winner_area"] = v["winner_area"]
-				//本月采购单位排行榜
-				result["buyer"] = v["buyer"]
-				//本月中标企业排行榜
-				result["winner"] = v["winner"]
-				//本月项目规模排行榜
-				result["project_bidamount"] = v["project_bidamount"]
-				//
-				result["winner_capital"] = v["winner_capital"]
-				//本月中标企业中标项目数量分布
-				result["winner_project"] = v["winner_project"]
-			}
-			project_count.Keys[startdate] = true
-			project_count.List = append(project_count.List, &BarChart{
-				Key:   startdate,
-				Value: util.IntAll(v["project_count"]),
-			})
-			project_bidamount_count.Keys[startdate] = true
-			project_bidamount_count.List = append(project_bidamount_count.List, &BarChart{
-				Key:   startdate,
-				Value: util.IntAll(v["project_bidamount_count"]),
-			})
-		}
-		//项目数量
-		result["project_count"] = formatMonths(fiveMonthStart, start, project_count, earliest["project_count"]).List
-		//项目规模
-		result["project_bidamount_count"] = formatMonths(fiveMonthStart, start, project_bidamount_count, earliest["project_bidamount_count"]).List
-	}
-	if result["winner_capital"] == nil || result["winner_project"] == nil {
-		sess := Mgo_Log.GetMgoConn()
-		defer Mgo_Log.DestoryMongoConn(sess)
-		it := sess.DB("push").C(coll_winner).Find(map[string]interface{}{
-			"userid": userId,
-			"type":   3,
-			"startdate": map[string]interface{}{
-				"$gte": start,
-			},
-			"enddate": map[string]interface{}{
-				"$lte": end,
-			},
-		}).Select(map[string]interface{}{
-			"capital":       1,
-			"project_count": 1,
-		}).Iter()
-		winner_capital_map := map[string]int{}
-		winner_project_length := 5
-		winner_project := make([]map[string]interface{}, winner_project_length)
-		for i := 0; i < winner_project_length; i++ {
-			projectcount := fmt.Sprint(i + 1)
-			if i == winner_project_length-1 {
-				projectcount = fmt.Sprintf("%d-%d", winner_project_length, winner_project_length+1)
-			}
-			winner_project[i] = map[string]interface{}{
-				"projectcount": projectcount,
-				"entcount":     0,
-				"proportion":   float64(0),
-			}
-		}
-		var count float64
-		for m := make(map[string]interface{}); it.Next(&m); {
-			if scope := getEntCapitalScopt(util.Float64All(m["capital"])); scope != "" {
-				winner_capital_map[scope] = winner_capital_map[scope] + 1
-			}
-			project_count := util.IntAll(m["project_count"])
-			if project_count > 0 && project_count <= winner_project_length+1 {
-				count++
-				if project_count >= winner_project_length {
-					winner_project[winner_project_length-1]["entcount"] = winner_project[winner_project_length-1]["entcount"].(int) + 1
-				} else {
-					winner_project[project_count-1]["entcount"] = winner_project[project_count-1]["entcount"].(int) + 1
-				}
-			}
-			m = make(map[string]interface{})
-		}
-		if count > 0 {
-			for k, v := range winner_project {
-				v["proportion"] = util.RetainDecimal(float64(v["entcount"].(int))/count*100, 2)
-				for i := 0; i < k; i++ {
-					v["proportion"] = util.RetainDecimal(v["proportion"].(float64)+(float64(winner_project[i]["entcount"].(int))/count)*100, 2)
-				}
-				if v["proportion"].(float64) > 100 {
-					v["proportion"] = float64(100)
-				}
-				if k == len(winner_project)-1 && v["proportion"].(float64) != 100 {
-					v["proportion"] = float64(100)
-				}
-			}
-		}
-		//本月中标企业注册资本分布
-		winner_capital_array := []map[string]interface{}{}
-		for _, v := range []string{"0-100万", "100-200万", "200-500万", "500-1000万", "1000-5000万", "5000-10000万", "1-10亿", "10-100亿", "大于100亿"} {
-			if winner_capital_map[v] == 0 {
-				continue
-			}
-			winner_capital_array = append(winner_capital_array, map[string]interface{}{
-				"range": v,
-				"count": winner_capital_map[v],
-			})
-		}
-		result["winner_capital"] = winner_capital_array
-		//本月中标企业中标项目数量分布
-		result["winner_project"] = winner_project
-	}
-	return result
+        result := M{}
+        //最近6个月
+        fiveMonthStart := time.Unix(start, 0).AddDate(0, -5, 0).Unix()
+        sixDatas, ok := Mgo.Find(coll, map[string]interface{}{
+                qk:     qv,
+                "type": 3,
+                "startdate": map[string]interface{}{
+                        "$gte": fiveMonthStart,
+                },
+                "enddate": map[string]interface{}{
+                        "$lte": end,
+                },
+        }, `{"startdate":1}`, `{"startdate":1,"item":1,"project_matchitem_count":1,"project_matchitem_bidamount":1,"project_count":1,"project_bidamount_count":1,"project_area_count":1,"project_area_bidamount":1,"project_buyerclass_count":1,"project_buyerclass_bidamount":1,"project_buyerclass_average_bidamount":1,"winner_area":1,"buyer":1,"winner":1,"project_bidamount":1}`, false, -1, -1)
+        if ok && sixDatas != nil {
+                project_count := &BarCharts{
+                        Keys: map[int64]bool{},
+                }
+                project_bidamount_count := &BarCharts{
+                        Keys: map[int64]bool{},
+                }
+                earliest := map[string]interface{}{}
+                for _, v := range *sixDatas {
+                        startdate := qutil.Int64All(v["startdate"])
+                        if startdate == fiveMonthStart { //上个月
+                                earliest = v
+                                continue
+                        } else if startdate == start { //本月
+                                //订阅关键词组
+                                result["item"] = v["item"]
+                                //本月项目规模
+                                result["project_matchitem_count"] = v["project_matchitem_count"]
+                                //本月项目规模
+                                result["project_matchitem_bidamount"] = matchitemGrowthRateHandle(earliest, v, "project_matchitem_bidamount", "bidamount")
+                                //本月项目数量分布
+                                result["project_area_count"] = v["project_area_count"]
+                                //本月项目规模分布
+                                result["project_area_bidamount"] = v["project_area_bidamount"]
+                                //本月项目数量TOP10采购行业
+                                result["project_buyerclass_count"] = v["project_buyerclass_count"]
+                                //本月项目规模TOP10采购行业
+                                result["project_buyerclass_bidamount"] = v["project_buyerclass_bidamount"]
+                                //本月项目平均规模TOP10采购行业
+                                result["project_buyerclass_average_bidamount"] = v["project_buyerclass_average_bidamount"]
+                                //本月中标企业注册地分布
+                                result["winner_area"] = v["winner_area"]
+                                //本月采购单位排行榜
+                                result["buyer"] = v["buyer"]
+                                //本月中标企业排行榜
+                                result["winner"] = v["winner"]
+                                //本月项目规模排行榜
+                                result["project_bidamount"] = v["project_bidamount"]
+                                //
+                                result["winner_capital"] = v["winner_capital"]
+                                //本月中标企业中标项目数量分布
+                                result["winner_project"] = v["winner_project"]
+                        }
+                        project_count.Keys[startdate] = true
+                        project_count.List = append(project_count.List, &BarChart{
+                                Key:   startdate,
+                                Value: qutil.IntAll(v["project_count"]),
+                        })
+                        project_bidamount_count.Keys[startdate] = true
+                        project_bidamount_count.List = append(project_bidamount_count.List, &BarChart{
+                                Key:   startdate,
+                                Value: qutil.IntAll(v["project_bidamount_count"]),
+                        })
+                }
+                //项目数量
+                result["project_count"] = formatMonths(fiveMonthStart, start, project_count, earliest["project_count"]).List
+                //项目规模
+                result["project_bidamount_count"] = formatMonths(fiveMonthStart, start, project_bidamount_count, earliest["project_bidamount_count"]).List
+        }
+        if result["winner_capital"] == nil || result["winner_project"] == nil {
+                sess := Mgo_Log.GetMgoConn()
+                defer Mgo_Log.DestoryMongoConn(sess)
+                it := sess.DB("push").C(coll_winner).Find(map[string]interface{}{
+                        "userid": userId,
+                        "type":   3,
+                        "startdate": map[string]interface{}{
+                                "$gte": start,
+                        },
+                        "enddate": map[string]interface{}{
+                                "$lte": end,
+                        },
+                }).Select(map[string]interface{}{
+                        "capital":       1,
+                        "project_count": 1,
+                }).Iter()
+                winner_capital_map := map[string]int{}
+                winner_project_length := 5
+                winner_project := make([]map[string]interface{}, winner_project_length)
+                for i := 0; i < winner_project_length; i++ {
+                        projectcount := fmt.Sprint(i + 1)
+                        if i == winner_project_length-1 {
+                                projectcount = fmt.Sprintf("%d-%d", winner_project_length, winner_project_length+1)
+                        }
+                        winner_project[i] = map[string]interface{}{
+                                "projectcount": projectcount,
+                                "entcount":     0,
+                                "proportion":   float64(0),
+                        }
+                }
+                var count float64
+                for m := make(map[string]interface{}); it.Next(&m); {
+                        if scope := getEntCapitalScopt(qutil.Float64All(m["capital"])); scope != "" {
+                                winner_capital_map[scope] = winner_capital_map[scope] + 1
+                        }
+                        project_count := qutil.IntAll(m["project_count"])
+                        if project_count > 0 && project_count <= winner_project_length+1 {
+                                count++
+                                if project_count >= winner_project_length {
+                                        winner_project[winner_project_length-1]["entcount"] = winner_project[winner_project_length-1]["entcount"].(int) + 1
+                                } else {
+                                        winner_project[project_count-1]["entcount"] = winner_project[project_count-1]["entcount"].(int) + 1
+                                }
+                        }
+                        m = make(map[string]interface{})
+                }
+                if count > 0 {
+                        for k, v := range winner_project {
+                                v["proportion"] = qutil.RetainDecimal(float64(v["entcount"].(int))/count*100, 2)
+                                for i := 0; i < k; i++ {
+                                        v["proportion"] = qutil.RetainDecimal(v["proportion"].(float64)+(float64(winner_project[i]["entcount"].(int))/count)*100, 2)
+                                }
+                                if v["proportion"].(float64) > 100 {
+                                        v["proportion"] = float64(100)
+                                }
+                                if k == len(winner_project)-1 && v["proportion"].(float64) != 100 {
+                                        v["proportion"] = float64(100)
+                                }
+                        }
+                }
+                //本月中标企业注册资本分布
+                winner_capital_array := []map[string]interface{}{}
+                for _, v := range []string{"0-100万", "100-200万", "200-500万", "500-1000万", "1000-5000万", "5000-10000万", "1-10亿", "10-100亿", "大于100亿"} {
+                        if winner_capital_map[v] == 0 {
+                                continue
+                        }
+                        winner_capital_array = append(winner_capital_array, map[string]interface{}{
+                                "range": v,
+                                "count": winner_capital_map[v],
+                        })
+                }
+                result["winner_capital"] = winner_capital_array
+                //本月中标企业中标项目数量分布
+                result["winner_project"] = winner_project
+        }
+        return result
 }
 
 //处理关键词分组环比增长率
 func matchitemGrowthRateHandle(earliest, curr map[string]interface{}, key1, key2 string) []interface{} {
-	e, _ := earliest[key1].([]interface{})
-	c, _ := curr[key1].([]interface{})
-	m := map[string]float64{}
-	for _, v := range e {
-		vm, _ := v.(map[string]interface{})
-		m[util.ObjToString(vm["item"])] = util.Float64All(vm[key2])
-	}
-	for _, v := range c {
-		vm, _ := v.(map[string]interface{})
-		vm["growthrate"] = getGrowthRate(util.Float64All(vm[key2]), m[util.ObjToString(vm["item"])])
-	}
-	return c
+        e, _ := earliest[key1].([]interface{})
+        c, _ := curr[key1].([]interface{})
+        m := map[string]float64{}
+        for _, v := range e {
+                vm, _ := v.(map[string]interface{})
+                m[qutil.ObjToString(vm["item"])] = qutil.Float64All(vm[key2])
+        }
+        for _, v := range c {
+                vm, _ := v.(map[string]interface{})
+                vm["growthrate"] = getGrowthRate(qutil.Float64All(vm[key2]), m[qutil.ObjToString(vm["item"])])
+        }
+        return c
 }
 
 //获取企业注册资本范围
 func getEntCapitalScopt(capital float64) string {
-	if 0 <= capital && capital < 100 {
-		return "0-100万"
-	} else if 100 <= capital && capital < 200 {
-		return "100-200万"
-	} else if 200 <= capital && capital < 500 {
-		return "200-500万"
-	} else if 500 <= capital && capital < 1000 {
-		return "500-1000万"
-	} else if 1000 <= capital && capital < 5000 {
-		return "1000-5000万"
-	} else if 5000 <= capital && capital < 10000 {
-		return "5000-10000万"
-	} else if 10000 <= capital && capital < 100000 {
-		return "1-10亿"
-	} else if 100000 <= capital && capital < 1000000 {
-		return "10-100亿"
-	} else if 1000000 <= capital {
-		return "大于100亿"
-	} else {
-		return ""
-	}
+        if 0 <= capital && capital < 100 {
+                return "0-100万"
+        } else if 100 <= capital && capital < 200 {
+                return "100-200万"
+        } else if 200 <= capital && capital < 500 {
+                return "200-500万"
+        } else if 500 <= capital && capital < 1000 {
+                return "500-1000万"
+        } else if 1000 <= capital && capital < 5000 {
+                return "1000-5000万"
+        } else if 5000 <= capital && capital < 10000 {
+                return "5000-10000万"
+        } else if 10000 <= capital && capital < 100000 {
+                return "1-10亿"
+        } else if 100000 <= capital && capital < 1000000 {
+                return "10-100亿"
+        } else if 1000000 <= capital {
+                return "大于100亿"
+        } else {
+                return ""
+        }
 }
 
 //
 func formatMonths(start, end int64, bcs *BarCharts, pv interface{}) *BarCharts {
-	if len(bcs.List) == 0 {
-		return bcs
-	}
-	date := time.Unix(end, 0)
-	for i := 0; i < 6; i++ {
-		date = date.AddDate(0, -1, 0)
-		if date.Unix() < start {
-			break
-		} else if bcs.Keys[date.Unix()] {
-			continue
-		}
-		bcs.List = append(bcs.List, &BarChart{
-			Value: 0,
-			Key:   date.Unix(),
-		})
-	}
-	sort.Sort(bcs)
-	for k, v := range bcs.List {
-		if k == 0 {
-			v.GrowthRate = getGrowthRate(util.Float64All(v.Value), util.Float64All(pv))
-		} else {
-			v.GrowthRate = getGrowthRate(util.Float64All(v.Value), util.Float64All(bcs.List[k-1].Value))
-		}
-	}
-	return bcs
+        if len(bcs.List) == 0 {
+                return bcs
+        }
+        date := time.Unix(end, 0)
+        for i := 0; i < 6; i++ {
+                date = date.AddDate(0, -1, 0)
+                if date.Unix() < start {
+                        break
+                } else if bcs.Keys[date.Unix()] {
+                        continue
+                }
+                bcs.List = append(bcs.List, &BarChart{
+                        Value: 0,
+                        Key:   date.Unix(),
+                })
+        }
+        sort.Sort(bcs)
+        for k, v := range bcs.List {
+                if k == 0 {
+                        v.GrowthRate = getGrowthRate(qutil.Float64All(v.Value), qutil.Float64All(pv))
+                } else {
+                        v.GrowthRate = getGrowthRate(qutil.Float64All(v.Value), qutil.Float64All(bcs.List[k-1].Value))
+                }
+        }
+        return bcs
 }
 
 //环比增长率
 func getGrowthRate(v1, v2 float64) float64 {
-	if v2 == 0 {
-		return 0
-	}
-	return util.RetainDecimal((v1-v2)/v2*100, 2)
+        if v2 == 0 {
+                return 0
+        }
+        return qutil.RetainDecimal((v1-v2)/v2*100, 2)
 }
 
 //
 func (r *Report) Tip() {
-	_, qk, qv := getQuery(r.Session())
-	if qk == "" || qv == nil {
-		return
-	}
-	unread := Mgo.Count(pushspace_member_statistic, map[string]interface{}{
-		qk:       qv,
-		"unread": 1,
-	})
-	list, ok := Mgo.Find(pushspace_member_statistic, map[string]interface{}{
-		qk:    qv,
-		"tip": 1,
-	}, `{"enddate":-1}`, `{"_id":0,"type":1,"startdate":1,"enddate":1,"pushcount":1}`, false, 0, 1)
-	result := map[string]interface{}{
-		"unread": unread,
-	}
-	if ok && list != nil && len(*list) == 1 {
-		result["tip"] = (*list)[0]
-	}
-	r.ServeJson(result)
+        _, qk, qv := getQuery(r.Session())
+        if qk == "" || qv == nil {
+                return
+        }
+        unread := Mgo.Count(pushspace_member_statistic, map[string]interface{}{
+                qk:       qv,
+                "unread": 1,
+        })
+        list, ok := Mgo.Find(pushspace_member_statistic, map[string]interface{}{
+                qk:    qv,
+                "tip": 1,
+        }, `{"enddate":-1}`, `{"_id":0,"type":1,"startdate":1,"enddate":1,"pushcount":1}`, false, 0, 1)
+        result := map[string]interface{}{
+                "unread": unread,
+        }
+        if ok && list != nil && len(*list) == 1 {
+                result["tip"] = (*list)[0]
+        }
+        r.ServeJson(result)
 }
 func (r *Report) Tipover() {
-	_, qk, qv := getQuery(r.Session())
-	if qk == "" || qv == nil {
-		return
-	}
-	r.ServeJson(map[string]interface{}{"flag": tipover(qk, qv, pushspace_member_statistic)})
+        _, qk, qv := getQuery(r.Session())
+        if qk == "" || qv == nil {
+                return
+        }
+        r.ServeJson(map[string]interface{}{"flag": tipover(qk, qv, pushspace_member_statistic)})
 }
 
 func tipover(qk string, qv interface{}, coll string) bool {
-	return Mgo.Update(coll, map[string]interface{}{
-		qk:    qv,
-		"tip": 1,
-	}, map[string]interface{}{
-		"$set": map[string]interface{}{
-			"tip": 0,
-		},
-	}, false, true)
+        return Mgo.Update(coll, map[string]interface{}{
+                qk:    qv,
+                "tip": 1,
+        }, map[string]interface{}{
+                "$set": map[string]interface{}{
+                        "tip": 0,
+                },
+        }, false, true)
 }
 func (r *Report) Openpushmsg() error {
-	userId, qk, qv := getQuery(r.Session())
-	if qk == "" || qv == nil {
-		return nil
-	}
-	// userId, _, _ = MainUserId(userId, "", 0)
-	pushcount, _ := r.GetInteger("pushcount")
-	start, _ := r.GetInt("start")
-	end, _ := r.GetInt("end")
-	tp := "month"
-	if end-start == 518400 {
-		tp = "week"
-	}
-	if r.GetString("t") == "wx_experience" {
-		if !isFree(userId) {
-			return r.Redirect("/swordfish/about?advertcode=" + r.GetString("advertcode"))
-		}
-		go tipover(qk, qv, pushspace_experience_member_statistic)
-		return r.Redirect(fmt.Sprintf("/big/wx/page/report_detail_%s?t=wx_experience&f=push&type=free&start=%d&end=%d&pushcount=%d&advertcode=%s", tp, start, end, pushcount, r.GetString("advertcode")))
-	} else if r.GetString("t") == "app_experience" {
-		if !isFree(userId) {
-			return r.Redirect("/jyapp/free/swordfish/about")
-		}
-		go tipover(qk, qv, pushspace_experience_member_statistic)
-		return r.Redirect(fmt.Sprintf("/jyapp/big/page/report_detail_%s?t=app_experience&f=push&type=free&start=%d&end=%d&pushcount=%d", tp, start, end, pushcount))
-	} else {
-		go tipover(qk, qv, pushspace_member_statistic)
-		//return r.Redirect(fmt.Sprintf("/jyapp/big/page/bigvip_subreport_%s?f=push&start=%d&end=%d&pushcount=%d", tp, start, end, pushcount))
-		return r.Redirect(fmt.Sprintf("/vipreport/page/subreport.html?f=push&type=member&start=%d&end=%d&advertcode=%s", start, end, r.GetString("advertcode")))
-	}
+        userId, qk, qv := getQuery(r.Session())
+        pushcount, _ := r.GetInteger("pushcount")
+        positionType := qutil.Int64All(r.GetSession("positionType "))
+        start, _ := r.GetInt("start")
+        end, _ := r.GetInt("end")
+        tp := "month"
+        if end-start == 518400 {
+                tp = "week"
+        }
+        if r.GetString("t") == "wx_experience" {
+                if !isFree(userId, positionType, r.Session()) {
+                        return r.Redirect("/swordfish/about?advertcode=" + r.GetString("advertcode"))
+                }
+                go tipover(qk, qv, pushspace_experience_member_statistic)
+                return r.Redirect(fmt.Sprintf("/big/wx/page/report_detail_%s?t=wx_experience&f=push&type=free&start=%d&end=%d&pushcount=%d&advertcode=%s", tp, start, end, pushcount, r.GetString("advertcode")))
+        } else if r.GetString("t") == "app_experience" {
+                if !isFree(userId, positionType, r.Session()) {
+                        return r.Redirect("/jyapp/free/swordfish/about")
+                }
+                go tipover(qk, qv, pushspace_experience_member_statistic)
+                return r.Redirect(fmt.Sprintf("/jyapp/big/page/report_detail_%s?t=app_experience&f=push&type=free&start=%d&end=%d&pushcount=%d", tp, start, end, pushcount))
+        } else {
+                go tipover(qk, qv, pushspace_member_statistic)
+                //return r.Redirect(fmt.Sprintf("/jyapp/big/page/bigvip_subreport_%s?f=push&start=%d&end=%d&pushcount=%d", tp, start, end, pushcount))
+                return r.Redirect(fmt.Sprintf("/vipreport/page/subreport.html?f=push&type=member&start=%d&end=%d&advertcode=%s", start, end, r.GetString("advertcode")))
+        }
 }
 
 func (r *Report) Starttime() {
-	_, qk, qv := getQuery(r.Session())
-	if qk == "" || qv == nil {
-		return
-	}
-	week_start, month_start := 0, 0
-	week_list, _ := Mgo.Find(pushspace_member_statistic, map[string]interface{}{
-		qk:     qv,
-		"type": 2,
-	}, `{"enddate":1}`, `{"enddate":1,"dateym":1}`, false, 0, 1)
-	if week_list != nil && len(*week_list) == 1 {
-		enddate := util.Int64All((*week_list)[0]["enddate"])
-		if time.Now().After(time.Unix(enddate, 0).AddDate(0, 0, 1)) {
-			week_start = util.IntAll((*week_list)[0]["dateym"])
-		}
-	}
-	//
-	month_list, _ := Mgo.Find(pushspace_member_statistic, map[string]interface{}{
-		qk:     qv,
-		"type": 3,
-	}, `{"enddate":1}`, `{"enddate":1,"dateym":1}`, false, 0, 1)
-	if month_list != nil && len(*month_list) == 1 {
-		enddate := util.Int64All((*month_list)[0]["enddate"])
-		if time.Now().After(time.Unix(enddate, 0).AddDate(0, 0, 1)) {
-			month_start = util.IntAll((*month_list)[0]["dateym"])
-		}
-	}
-	r.ServeJson(Result{
-		Data: M{
-			"week_firsttime":  week_start,
-			"month_firsttime": month_start,
-		},
-	})
+        _, qk, qv := getQuery(r.Session())
+        if qk == "" || qv == nil {
+                return
+        }
+        week_start, month_start := 0, 0
+        week_list, _ := Mgo.Find(pushspace_member_statistic, map[string]interface{}{
+                qk:     qv,
+                "type": 2,
+        }, `{"enddate":1}`, `{"enddate":1,"dateym":1}`, false, 0, 1)
+        if week_list != nil && len(*week_list) == 1 {
+                enddate := qutil.Int64All((*week_list)[0]["enddate"])
+                if time.Now().After(time.Unix(enddate, 0).AddDate(0, 0, 1)) {
+                        week_start = qutil.IntAll((*week_list)[0]["dateym"])
+                }
+        }
+        //
+        month_list, _ := Mgo.Find(pushspace_member_statistic, map[string]interface{}{
+                qk:     qv,
+                "type": 3,
+        }, `{"enddate":1}`, `{"enddate":1,"dateym":1}`, false, 0, 1)
+        if month_list != nil && len(*month_list) == 1 {
+                enddate := qutil.Int64All((*month_list)[0]["enddate"])
+                if time.Now().After(time.Unix(enddate, 0).AddDate(0, 0, 1)) {
+                        month_start = qutil.IntAll((*month_list)[0]["dateym"])
+                }
+        }
+        r.ServeJson(Result{
+                Data: M{
+                        "week_firsttime":  week_start,
+                        "month_firsttime": month_start,
+                },
+        })
 }
 
 //
 func getColl(referer, t string) (string, string) {
-	if t == "free" || strings.Contains(referer, "t=wx_experience") || strings.Contains(referer, "t=app_experience") {
-		return pushspace_experience_member_statistic, pushspace_experience_member_statistic_winner
-	} else {
-		return pushspace_member_statistic, pushspace_member_statistic_winner
-	}
+        if t == "free" || strings.Contains(referer, "t=wx_experience") || strings.Contains(referer, "t=app_experience") {
+                return pushspace_experience_member_statistic, pushspace_experience_member_statistic_winner
+        } else {
+                return pushspace_member_statistic, pushspace_member_statistic_winner
+        }
 }
-func isFree(userId string) bool {
-	user, ok := Mgo.FindById("user", userId, `{"i_vip_status":1,"i_member_status":1}`)
-	if !ok || user == nil {
-		return true
-	} else if util.IntAll((*user)["i_vip_status"]) <= 0 && util.IntAll((*user)["i_member_status"]) <= 0 {
-		return true
-	}
-	return false
+func isFree(userId string, positionType int64, session *httpsession.Session) bool {
+        bigVipBaseMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        if bigVipBaseMsg == nil {
+                return true
+        } else if bigVipBaseMsg.Data.Vip.Status <= 0 && bigVipBaseMsg.Data.Member.Status <= 0 {
+                return true
+        }
+        return false
 }
 
 //
 func getQuery(sess *httpsession.Session) (string, string, interface{}) {
-	sessMap := sess.GetMultiple()
-	userId := util.ObjToString(sessMap["userId"])
-	user, ok := Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1}`)
-	if !ok || user == nil {
-		return "", "", nil
-	}
-	phone := util.ObjToString((*user)["s_phone"])
-	if phone == "" {
-		phone = util.ObjToString((*user)["s_m_phone"])
-	}
-	if Mysql.CountBySql(`SELECT count(1) as count from entniche_user a
+        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 {
+                return "", "", nil
+        }
+        phone := qutil.ObjToString((*user)["s_phone"])
+        if phone == "" {
+                phone = qutil.ObjToString((*user)["s_m_phone"])
+        }
+        if Mysql.CountBySql(`SELECT count(1) as count from entniche_user a
 		inner join entniche_power b on (a.phone=? and b.status=1 and a.id=b.ent_user_id)
 		inner join entniche_wait_empower c on (c.end_time>? and (c.product_type like '%VIP订阅%' or c.product_type like '%大会员%') and b.wait_empower_id=c.id)`, phone, NowFormat(Date_Full_Layout)) > 0 {
-		return userId, "ent_userid", util.IntAll(sessMap["entUserId"])
-	} else {
-		return userId, "userid", userId
-	}
+                return userId, "ent_userid", qutil.IntAll(sessMap["entUserId"])
+        } else {
+                return userId, "userid", userId
+        }
 }

+ 372 - 314
src/jfw/modules/bigmember/src/service/subscribe/subscribe.go

@@ -1,344 +1,384 @@
 package subscribe
 
 import (
-	. "app.yhyue.com/moapp/jybase/api"
-	"jy/src/jfw/modules/bigmember/src/config"
-	"jy/src/jfw/modules/bigmember/src/db"
-	"encoding/json"
-	"fmt"
-	"log"
-	"app.yhyue.com/moapp/jybase/mongodb"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/redis"
-	"sort"
-	"strings"
-	"time"
-	"jy/src/jfw/modules/bigmember/src/util"
+        . "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"
+        "fmt"
+        "jy/src/jfw/modules/bigmember/src/config"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "jy/src/jfw/modules/bigmember/src/util"
+        "log"
+        "sort"
+        "strings"
+        "time"
 
-	"go.mongodb.org/mongo-driver/bson"
+        "go.mongodb.org/mongo-driver/bson"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Subscribe struct {
-	*xweb.Action
-	key_update           xweb.Mapper `xweb:"/subscribe/key/update"`           //修改关键词
-	area_update          xweb.Mapper `xweb:"/subscribe/area/update"`          //修改地区
-	infotype_update      xweb.Mapper `xweb:"/subscribe/infotype/update"`      //修改信息类型
-	buyerclass_update    xweb.Mapper `xweb:"/subscribe/buyerclass/update"`    //修改采购单位行业
-	projectmatch_update  xweb.Mapper `xweb:"/subscribe/projectmatch/update"`  //修改项目匹配
-	otherbuyclass_update xweb.Mapper `xweb:"/subscribe/otherbuyclass/update"` //修改"其他"采购单位按钮
-	matchtype_update     xweb.Mapper `xweb:"/subscribe/matchtype/update"`     //修改"其他"采购单位按钮
-	getPushView          xweb.Mapper `xweb:"/subscribe/getPushView"`          //推送预览
-	list                 xweb.Mapper `xweb:"/subscribe/push/list"`            //推送列表
-	visit                xweb.Mapper `xweb:"/subscribe/push/visit"`           //推送记录访问接口
+        *xweb.Action
+        key_update           xweb.Mapper `xweb:"/subscribe/key/update"`           //修改关键词
+        area_update          xweb.Mapper `xweb:"/subscribe/area/update"`          //修改地区
+        infotype_update      xweb.Mapper `xweb:"/subscribe/infotype/update"`      //修改信息类型
+        buyerclass_update    xweb.Mapper `xweb:"/subscribe/buyerclass/update"`    //修改采购单位行业
+        projectmatch_update  xweb.Mapper `xweb:"/subscribe/projectmatch/update"`  //修改项目匹配
+        otherbuyclass_update xweb.Mapper `xweb:"/subscribe/otherbuyclass/update"` //修改"其他"采购单位按钮
+        matchtype_update     xweb.Mapper `xweb:"/subscribe/matchtype/update"`     //修改"其他"采购单位按钮
+        getPushView          xweb.Mapper `xweb:"/subscribe/getPushView"`          //推送预览
+        list                 xweb.Mapper `xweb:"/subscribe/push/list"`            //推送列表
+        visit                xweb.Mapper `xweb:"/subscribe/push/visit"`           //推送记录访问接口
 
-	freeUserSubscribe xweb.Mapper `xweb:"/subscribe/freeUser/searchSubscribe"` //免费用户搜索订阅
-	subscribeSearch   xweb.Mapper `xweb:"/subscribe/freeUser/subscribeSearch"` //免费用户订阅搜索词设置
+        freeUserSubscribe xweb.Mapper `xweb:"/subscribe/freeUser/searchSubscribe"` //免费用户搜索订阅
+        subscribeSearch   xweb.Mapper `xweb:"/subscribe/freeUser/subscribeSearch"` //免费用户订阅搜索词设置
 }
 
 func (s *Subscribe) FreeUserSubscribe() {
-	//isVip, isMember 付费用户 isEntNiche, isEntNicheNew 商机管理用户 iPpStatus 非省份订阅包 promptBool 是否今日已提醒 areaConfig 区域配置
-	var isVip, isMember, isEntNiche, isEntNicheNew, iPpStatus, searchPrompt, promptBool, isAreaConfig bool
-	userId := s.GetSession("userId").(string)
-	if userId == "" {
-		fmt.Println("用户未登录,搜索词不进行校验")
-		s.ServeJson(Result{Data: M{"prompt": false, "areaSet": false, "freeArea": false}})
-		return
-	}
-	t := time.Now()
-	redisKey := fmt.Sprintf("%d_%s_%d_freeSubscription_%s", t.Year(), t.Month(), t.Day(), userId)
+        //isVip, isMember 付费用户 isEntNiche, isEntNicheNew 商机管理用户 iPpStatus 非省份订阅包 promptBool 是否今日已提醒 areaConfig 区域配置
+        var isVip, isMember, isEntNiche, isEntNicheNew, iPpStatus, searchPrompt, promptBool, isAreaConfig bool
+        userId := s.GetSession("userId").(string)
+        if userId == "" {
+                fmt.Println("用户未登录,搜索词不进行校验")
+                s.ServeJson(Result{Data: M{"prompt": false, "areaSet": false, "freeArea": false}})
+                return
+        }
+        t := time.Now()
+        redisKey := fmt.Sprintf("%d_%s_%d_freeSubscription_%s", t.Year(), t.Month(), t.Day(), userId)
+        bigMsg := jy.GetBigVipUserBaseMsg("10000", s.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        /*res, _ := db.Mgo.FindById(C_User, userId, `{"i_vip_status":1,"i_member_status":1,"s_m_phone":1,"s_phone":1,"o_jy":1,""l_search_prompt":1}`)
+          isVip = qutil.IntAll((*res)["i_vip_status"]) > 0*/
 
-	res, _ := db.Mgo.FindById("user", userId, `{"i_vip_status":1,"i_member_status":1,"s_m_phone":1,"s_phone":1,"o_jy":1,""l_search_prompt":1}`)
-	isVip = qutil.IntAll((*res)["i_vip_status"]) > 0
-	oJy, _ := (*res)["o_jy"].(map[string]interface{})
-	freeArea := true
-	//校验区域设置
-	if v, ok := oJy["o_area"]; ok && v != nil && len(v.(map[string]interface{})) > 0 {
-		isAreaConfig = true
-	}
-	if !isVip && !isAreaConfig {
-		freeArea = false
-	}
-	isMember = qutil.IntAll((*res)["i_member_status"]) > 0
-	//是否免费用户(免费用户:非省份订阅包、超级订阅、大会员、商机管理用户)
-	if phone, _ := qutil.If(qutil.ObjToString((*res)["s_phone"]) != "", qutil.ObjToString((*res)["s_phone"]), qutil.ObjToString((*res)["s_m_phone"])).(string); phone != "" {
-		isEntNiche = db.Mysql.CountBySql(`SELECT count(1) from entniche_user a INNER JOIN entniche_info b on (a.phone=? and a.power=1 and a.ent_id=b.id and b.status>0)`, phone) > 0
-		isEntNicheNew = db.Mysql.CountBySql(`SELECT count(1) from entniche_user a INNER JOIN entniche_info b on (a.phone=? and a.power=1 and a.ent_id=b.id and b.status>0 and b.isNew > 0)`, phone) > 0
-	}
-	//非省份订阅包
-	if oJy["i_ppstatus"] != nil && qutil.IntAll(oJy["i_ppstatus"]) > 0 {
-		iPpStatus = true
-	}
-	if isVip || isMember || isEntNiche || isEntNicheNew || iPpStatus {
-		goto env
-	}
-	//校验新老用户
-	//if o_jy["i_newfree"] != nil && qutil.IntAll(o_jy["i_newfree"]) > 0 {
-	//	nweOldUser = true
-	//}
+        oJy := jy.GetSubScribeInfo(s.Session(), db.Mgo, "f", "10000")
+        //oJy, _ := (*res)["o_jy"].(map[string]interface{})
+        freeArea := true
+        //校验区域设置
+        if v, ok := (*oJy)["o_area"]; ok && v != nil && len(v.(map[string]interface{})) > 0 {
+                isAreaConfig = true
+        }
+        if !isVip && !isAreaConfig {
+                freeArea = false
+        }
+        isMember = bigMsg.Data.Member.Status > 0
+        //后期处理
+        //是否免费用户(免费用户:非省份订阅包、超级订阅、大会员、商机管理用户)
+        /*if phone, _ := qutil.If(qutil.ObjToString((*res)["s_phone"]) != "", qutil.ObjToString((*res)["s_phone"]), qutil.ObjToString((*res)["s_m_phone"])).(string); phone != "" {
+                isEntNiche = db.Mysql.CountBySql(`SELECT count(1) from entniche_user a INNER JOIN entniche_info b on (a.phone=? and a.power=1 and a.ent_id=b.id and b.status>0)`, phone) > 0
+                isEntNicheNew = db.Mysql.CountBySql(`SELECT count(1) from entniche_user a INNER JOIN entniche_info b on (a.phone=? and a.power=1 and a.ent_id=b.id and b.status>0 and b.isNew > 0)`, phone) > 0
+        }*/
+        isEntNiche = bigMsg.EntnicheStatus > 0
+        isEntNicheNew = bigMsg.EntIsNew
+        //非省份订阅包
+        if (*oJy)["i_ppstatus"] != nil && qutil.IntAll((*oJy)["i_ppstatus"]) > 0 {
+                iPpStatus = true
+        }
+        if isVip || isMember || isEntNiche || isEntNicheNew || iPpStatus {
+                goto env
+        }
+        //校验新老用户
+        //if o_jy["i_newfree"] != nil && qutil.IntAll(o_jy["i_newfree"]) > 0 {
+        //	nweOldUser = true
+        //}
 
-	//是否有关键词
-	if oJy["a_key"] != nil && len(oJy["a_key"].([]interface{})) > 0 {
-		goto env
-	}
-	//是否勾选不在提示
-	if v, ok := oJy["l_search_prompt"]; ok && v != nil && v.(bool) {
-		goto env
-	}
-	//今天是否提示过
-	if searchPrompt, _ = redis.Exists("other", redisKey); !searchPrompt {
-		promptBool = true
-		redis.Put("other", redisKey, 1, 24*60*60)
-	}
+        //是否有关键词
+        if (*oJy)["a_key"] != nil && len((*oJy)["a_key"].([]interface{})) > 0 {
+                goto env
+        }
+        //是否勾选不在提示
+        if v, ok := (*oJy)["l_search_prompt"]; ok && v != nil && v.(bool) {
+                goto env
+        }
+        //今天是否提示过
+        if searchPrompt, _ = redis.Exists("other", redisKey); !searchPrompt {
+                promptBool = true
+                redis.Put("other", redisKey, 1, 24*60*60)
+        }
 env:
-	s.ServeJson(Result{Data: M{"prompt": promptBool, "areaSet": !isAreaConfig, "freeArea": freeArea}})
+        s.ServeJson(Result{Data: M{"prompt": promptBool, "areaSet": !isAreaConfig, "freeArea": freeArea}})
 
 }
 
 func (s *Subscribe) SubscribeSearch() {
-	isNoSubscribe := s.GetString("isNoSubscribe")
-	area := s.GetString("area")
-	subsequentPrompt := s.GetString("subsequentPrompt")
-	key := s.GetString("key")
-	userId := s.GetSession("userId").(string)
+        isNoSubscribe := s.GetString("isNoSubscribe")
+        area := s.GetString("area")
+        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
+        }
+        var search_prompt bool
+        if subsequentPrompt == "Y" {
+                search_prompt = true
+        } else if subsequentPrompt == "N" {
+                search_prompt = false
+        }
 
-	if userId == "" {
-		s.ServeJson(Result{Data: nil, Error_msg: "未登录"})
-		return
-	}
-	var search_prompt bool
-	if subsequentPrompt == "Y" {
-		search_prompt = true
-	} else if subsequentPrompt == "N" {
-		search_prompt = false
-	}
+        //暂不订阅修改
+        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)
+                }
+                s.ServeJson(Result{Data: M{"status": aa}})
+                return
+        }
 
-	//暂不订阅修改
-	if isNoSubscribe == "N" {
-		aa := db.Mgo.UpdateById("user", userId, bson.M{"$set": bson.M{"o_jy.l_search_prompt": search_prompt}})
-		s.ServeJson(Result{Data: M{"status": aa}})
-		return
-	}
-
-	//一键订阅修改
-	res, _ := db.Mgo.FindById("user", userId, `{"o_jy":1,"i_ts_guide":1}`)
-	//获取原有订阅词
-	oJy, _ := (*res)["o_jy"].(map[string]interface{})
-	aKey, _ := oJy["a_key"].([]interface{})
-	if key != "" {
-		keyData := []string{strings.Replace(key, " ", "", -1)}
-		var aKeys = map[string]interface{}{"key": keyData}
-		aKey = append(aKey, aKeys)
-	}
-	var newFree int
-	if v, ok := oJy["i_newfree"]; ok && v != nil {
-		newFree = qutil.IntAll(v)
-	}
-	//更新新订阅词并升级
-	data := make(map[string]interface{})
-	data["o_jy.l_search_prompt"] = search_prompt
-	data["o_jy.i_newfree"] = 1
-	data["o_jy.a_key"] = aKey
-	if area != "" {
-		data["o_jy.o_area"] = map[string]interface{}{
-			area: []string{},
-		}
-		if v, ok := (*res)["i_ts_guide"]; !ok || qutil.IntAll(v) != 1 {
-			data["i_ts_guide"] = 1
-		}
-	}
-	UpData := map[string]interface{}{
-		"$set": data,
-	}
-	status := db.Mgo.UpdateById("user", userId, UpData)
-	if status && newFree == 0 {
-		if !redis.Del("other", "bigmember_power_3_"+userId) {
-			log.Println("redis delete bigmember_power ", userId)
-		}
-	}
-	s.ServeJson(Result{Data: M{"status": status}})
+        //一键订阅修改
+        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"
+        }
+        //获取原有订阅词
+        aKey, _ := oJy["a_key"].([]interface{})
+        if key != "" {
+                keyData := []string{strings.Replace(key, " ", "", -1)}
+                var aKeys = map[string]interface{}{"key": keyData}
+                aKey = append(aKey, aKeys)
+        }
+        var newFree int
+        if v, ok := oJy["i_newfree"]; ok && v != nil {
+                newFree = qutil.IntAll(v)
+        }
+        //更新新订阅词并升级
+        data := make(map[string]interface{})
+        data[fmt.Sprintf("%s.l_search_prompt", fType)] = search_prompt
+        data[fmt.Sprintf("%s.i_newfree", fType)] = 1
+        data[fmt.Sprintf("%s.a_key", fType)] = aKey
+        if area != "" {
+                data[fmt.Sprintf("%s.o_area", fType)] = map[string]interface{}{
+                        area: []string{},
+                }
+                if v, ok := (*res)["i_ts_guide"]; !ok || qutil.IntAll(v) != 1 {
+                        data["i_ts_guide"] = 1
+                }
+        }
+        UpData := map[string]interface{}{
+                "$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)
+        }
+        if status && newFree == 0 {
+                if !redis.Del("other", "bigmember_power_3_"+userId) {
+                        log.Println("redis delete bigmember_power ", userId)
+                }
+        }
+        s.ServeJson(Result{Data: M{"status": status}})
 }
 
 func (s *Subscribe) Key_update() {
-	r := func() Result {
-		keywords := map[string]interface{}{}
-		getkeywords := s.Body()
-		if len(getkeywords) > 0 {
-			err := json.Unmarshal(getkeywords, &keywords)
-			if err != nil {
-				log.Println("Umarshal failed:", err)
-				return Result{Data: M{"status": -1}, Error_msg: "格式解析失败"}
-			}
-			a_items, _ := keywords["a_items"].([]interface{})
-			real_aitems := []map[string]interface{}{}
-			if a_items == nil {
-				return Result{Data: M{"status": -1}, Error_msg: "格式错误"}
-			}
-			new_item := []string{} //分类名
-			new_key := []string{}  //关键词
-			count := 0             //关键词数量
-			for _, v := range qutil.ObjArrToMapArr(a_items) {
-				if v["a_key"] != nil {
-					a_key, _ := v["a_key"].([]interface{})
-					if len(a_key) == 0 {
-						continue //过滤掉错误数据
-					}
-					for _, vv := range qutil.ObjArrToMapArr(a_key) {
-						count++
-						key, _ := vv["key"].([]interface{})
-						appendArr := qutil.ObjArrToStringArr(key)
-						sort.Strings(appendArr)
-						new_key = append(new_key, strings.Join(appendArr, "&&"))
-					}
-				} else {
-					continue //过滤掉错误数据
-				}
-				if v["s_item"] != nil {
-					new_item = append(new_item, qutil.ObjToString(v["s_item"]))
-				}
-				real_aitems = append(real_aitems, v)
-			}
-			if isRepeat(new_item) {
-				return Result{Data: M{"status": -1}, Error_msg: "分类名重复"}
-			}
-			if isRepeat(new_key) {
-				return Result{Data: M{"status": -1}, Error_msg: "关键词重复"}
-			}
-			if count > config.Config.KeyMaxLength {
-				return Result{Data: M{"status": -1}, Error_msg: "关键词数量超过上限"}
-			}
-			if s.UpdateSub("a_items", real_aitems) {
-				return Result{Data: M{"status": 1}}
-			}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "修改失败"}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                keywords := map[string]interface{}{}
+                getkeywords := s.Body()
+                if len(getkeywords) > 0 {
+                        err := json.Unmarshal(getkeywords, &keywords)
+                        if err != nil {
+                                log.Println("Umarshal failed:", err)
+                                return Result{Data: M{"status": -1}, Error_msg: "格式解析失败"}
+                        }
+                        a_items, _ := keywords["a_items"].([]interface{})
+                        real_aitems := []map[string]interface{}{}
+                        if a_items == nil {
+                                return Result{Data: M{"status": -1}, Error_msg: "格式错误"}
+                        }
+                        new_item := []string{} //分类名
+                        new_key := []string{}  //关键词
+                        count := 0             //关键词数量
+                        for _, v := range qutil.ObjArrToMapArr(a_items) {
+                                if v["a_key"] != nil {
+                                        a_key, _ := v["a_key"].([]interface{})
+                                        if len(a_key) == 0 {
+                                                continue //过滤掉错误数据
+                                        }
+                                        for _, vv := range qutil.ObjArrToMapArr(a_key) {
+                                                count++
+                                                key, _ := vv["key"].([]interface{})
+                                                appendArr := qutil.ObjArrToStringArr(key)
+                                                sort.Strings(appendArr)
+                                                new_key = append(new_key, strings.Join(appendArr, "&&"))
+                                        }
+                                } else {
+                                        continue //过滤掉错误数据
+                                }
+                                if v["s_item"] != nil {
+                                        new_item = append(new_item, qutil.ObjToString(v["s_item"]))
+                                }
+                                real_aitems = append(real_aitems, v)
+                        }
+                        if isRepeat(new_item) {
+                                return Result{Data: M{"status": -1}, Error_msg: "分类名重复"}
+                        }
+                        if isRepeat(new_key) {
+                                return Result{Data: M{"status": -1}, Error_msg: "关键词重复"}
+                        }
+                        if count > config.Config.KeyMaxLength {
+                                return Result{Data: M{"status": -1}, Error_msg: "关键词数量超过上限"}
+                        }
+                        if s.UpdateSub("a_items", real_aitems) {
+                                return Result{Data: M{"status": 1}}
+                        }
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "修改失败"}
+        }()
+        s.ServeJson(r)
 }
 
 //修改地区
 func (s *Subscribe) Area_update() {
-	r := func() Result {
-		area := map[string]interface{}{}
-		getarea := s.Body()
-		if len(getarea) > 0 {
-			err := json.Unmarshal(getarea, &area)
-			if err != nil {
-				log.Println("Umarshal failed:", err)
-				return Result{Data: M{"status": -1}, Error_msg: "格式解析失败"}
-			}
-			if s.UpdateSub("o_area", area) {
-				return Result{Data: M{"status": 1}}
-			}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                area := map[string]interface{}{}
+                getarea := s.Body()
+                if len(getarea) > 0 {
+                        err := json.Unmarshal(getarea, &area)
+                        if err != nil {
+                                log.Println("Umarshal failed:", err)
+                                return Result{Data: M{"status": -1}, Error_msg: "格式解析失败"}
+                        }
+                        if s.UpdateSub("o_area", area) {
+                                return Result{Data: M{"status": 1}}
+                        }
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
+        }()
+        s.ServeJson(r)
 }
 
 //修改信息类型设置
 func (s *Subscribe) Infotype_update() {
-	r := func() Result {
-		infotype_map := map[string]interface{}{}
-		infotype := []string{}
-		getinfotype := s.Body()
-		if len(getinfotype) != 0 {
-			err := json.Unmarshal(getinfotype, &infotype_map)
-			if err != nil {
-				log.Println("Umarshal failed:", err)
-				return Result{Data: M{"status": -1}, Error_msg: "格式解析错误"}
-			}
-			for _, v := range infotype_map {
-				infotype = qutil.ObjArrToStringArr(v.([]interface{}))
-			}
-			if s.UpdateSub("a_infotype", infotype) {
-				return Result{Data: M{"status": 1}}
-			}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                infotype_map := map[string]interface{}{}
+                infotype := []string{}
+                getinfotype := s.Body()
+                if len(getinfotype) != 0 {
+                        err := json.Unmarshal(getinfotype, &infotype_map)
+                        if err != nil {
+                                log.Println("Umarshal failed:", err)
+                                return Result{Data: M{"status": -1}, Error_msg: "格式解析错误"}
+                        }
+                        for _, v := range infotype_map {
+                                infotype = qutil.ObjArrToStringArr(v.([]interface{}))
+                        }
+                        if s.UpdateSub("a_infotype", infotype) {
+                                return Result{Data: M{"status": 1}}
+                        }
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
+        }()
+        s.ServeJson(r)
 }
 
 //修改采购单位行业设置
 func (s *Subscribe) Buyerclass_update() {
-	r := func() Result {
-		buyerclass_map := map[string]interface{}{}
-		buyerclass := []string{}
-		getbuyerclass := s.Body()
-		if len(getbuyerclass) != 0 {
-			err := json.Unmarshal(getbuyerclass, &buyerclass_map)
-			if err != nil {
-				log.Println("Umarshal failed:", err)
-				return Result{Data: M{"status": -1}, Error_msg: "格式解析错误"}
-			}
-			for _, v := range buyerclass_map {
-				buyerclass = qutil.ObjArrToStringArr(v.([]interface{}))
-			}
-			if s.UpdateSub("a_buyerclass", buyerclass) {
-				return Result{Data: M{"status": 1}}
-			}
-		}
-		return Result{Data: M{"status": -1}}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                buyerclass_map := map[string]interface{}{}
+                buyerclass := []string{}
+                getbuyerclass := s.Body()
+                if len(getbuyerclass) != 0 {
+                        err := json.Unmarshal(getbuyerclass, &buyerclass_map)
+                        if err != nil {
+                                log.Println("Umarshal failed:", err)
+                                return Result{Data: M{"status": -1}, Error_msg: "格式解析错误"}
+                        }
+                        for _, v := range buyerclass_map {
+                                buyerclass = qutil.ObjArrToStringArr(v.([]interface{}))
+                        }
+                        if s.UpdateSub("a_buyerclass", buyerclass) {
+                                return Result{Data: M{"status": 1}}
+                        }
+                }
+                return Result{Data: M{"status": -1}}
+        }()
+        s.ServeJson(r)
 }
 
 //修改项目匹配
 func (s *Subscribe) Projectmatch_update() {
-	r := func() Result {
-		projectmatch, _ := s.GetInteger("projectmatch")
-		if s.UpdateSub("i_projectmatch", projectmatch) {
-			return Result{Data: M{"status": 1}}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                projectmatch, _ := s.GetInteger("projectmatch")
+                if s.UpdateSub("i_projectmatch", projectmatch) {
+                        return Result{Data: M{"status": 1}}
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
+        }()
+        s.ServeJson(r)
 }
 
 //修改“其他”采购单位行业
 func (s *Subscribe) Otherbuyclass_update() {
-	r := func() Result {
-		otherbuyclass, _ := s.GetInteger("otherbuyclass")
-		if s.UpdateSub("i_matchbuyerclass_other", otherbuyclass) {
-			return Result{Data: M{"status": 1}}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                otherbuyclass, _ := s.GetInteger("otherbuyclass")
+                if s.UpdateSub("i_matchbuyerclass_other", otherbuyclass) {
+                        return Result{Data: M{"status": 1}}
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
+        }()
+        s.ServeJson(r)
 }
 
 //匹配方式
 func (s *Subscribe) Matchtype_update() {
-	r := func() Result {
-		matchtype, _ := s.GetInteger("matchtype")
-		if s.UpdateSub("i_matchway", matchtype) {
-			return Result{Data: M{"status": 1}}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                matchtype, _ := s.GetInteger("matchtype")
+                if s.UpdateSub("i_matchway", matchtype) {
+                        return Result{Data: M{"status": 1}}
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "保存失败"}
+        }()
+        s.ServeJson(r)
 }
 
 //推送预览
 func (s *Subscribe) GetPushView() {
-	r := func() Result {
-		userId, _ := s.GetSession("userId").(string)
-		if userId == "" {
-			return Result{Data: nil, Error_msg: "未登录"}
-		}
-		pageNum, _ := s.GetInteger("pageNum")
-		pageSize, _ := s.GetInteger("pageSize")
-		keys, list, hasNextPage, count := util.SubViewDatas(userId, "", pageNum, pageSize)
-		return Result{Data: M{
-			"total":       count,
-			"keys":        strings.Replace(strings.Trim(fmt.Sprint(keys), "[]"), " ", ",", -1),
-			"list":        list,
-			"hasNextPage": hasNextPage,
-		}}
-	}()
-	s.ServeJson(r)
+        r := func() Result {
+                userId, _ := s.GetSession("userId").(string)
+                if userId == "" {
+                        return Result{Data: nil, Error_msg: "未登录"}
+                }
+                pageNum, _ := s.GetInteger("pageNum")
+                pageSize, _ := s.GetInteger("pageSize")
+                keys, list, hasNextPage, count := util.SubViewDatas(userId, "", pageNum, pageSize, s.Session())
+                return Result{Data: M{
+                        "total":       count,
+                        "keys":        strings.Replace(strings.Trim(fmt.Sprint(keys), "[]"), " ", ",", -1),
+                        "list":        list,
+                        "hasNextPage": hasNextPage,
+                }}
+        }()
+        s.ServeJson(r)
 }
 
 //推送列表
@@ -392,33 +432,51 @@ func (s *Subscribe) GetPushView() {
 
 //判断同一个数组是否重复
 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
 }
 
 //修改订阅信息  parameter_name参数名  parameter参数
 func (s *Subscribe) UpdateSub(parameter_name string, parameter interface{}) bool {
-	userid := mongodb.StringTOBsonId(qutil.ObjToString(s.GetSession("userId")))
-	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)
-	if ok {
-		go func() {
-			db.Mgo_Log.Save("bigmember_sub_logs", map[string]interface{}{
-				"userid":       s.GetSession("userId"),
-				parameter_name: parameter,
-				"createtime":   time.Now().Unix(),
-			})
-		}()
-	}
-	return ok
+        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)
+        }
+        if ok {
+                go func() {
+                        db.Mgo_Log.Save("bigmember_sub_logs", map[string]interface{}{
+                                "userid":       s.GetSession("userId"),
+                                parameter_name: parameter,
+                                "createtime":   time.Now().Unix(),
+                        })
+                }()
+        }
+        return ok
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 863 - 811
src/jfw/modules/bigmember/src/service/use/use.go


+ 53 - 48
src/jfw/modules/bigmember/src/util/power.go

@@ -1,65 +1,70 @@
 package util
 
 import (
-	"jy/src/jfw/modules/bigmember/src/db"
-	"app.yhyue.com/moapp/jybase/mongodb"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"time"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "app.yhyue.com/moapp/jybase/mongodb"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "jy/src/jfw/modules/bigmember/src/config"
+        "jy/src/jfw/modules/bigmember/src/db"
+        "time"
 )
 
+//后期
 //获取用户主账号userid
-func MainUserId(userid, phone string, i_member_status int) (string, string, int) {
-	data, ok := db.Mgo.FindById("user", userid, `{"s_member_mainid":1,"s_phone":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"])
-		}
-		if (*data)["s_phone"] != nil {
-			phone = qutil.ObjToString((*data)["s_phone"])
-		} else if (*data)["s_m_phone"] != nil {
-			phone = qutil.ObjToString((*data)["s_m_phone"])
-		}
-		if (*data)["i_member_status"] != nil {
-			i_member_status = qutil.IntAll((*data)["i_member_status"])
-		}
-	}
-	return userid, phone, i_member_status
+func MainUserId(session *httpsession.Session) (string, string, int) {
+        /*data, ok := db.Mgo.FindById("user", userid, `{"s_member_mainid":1,"s_phone":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"])
+          	}
+          	if (*data)["s_phone"] != nil {
+          		phone = qutil.ObjToString((*data)["s_phone"])
+          	} else if (*data)["s_m_phone"] != nil {
+          		phone = qutil.ObjToString((*data)["s_m_phone"])
+          	}
+          	if (*data)["i_member_status"] != nil {
+          		i_member_status = qutil.IntAll((*data)["i_member_status"])
+          	}
+          }*/
+        bigMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        return bigMsg.Data.Member.Pid, "phone", bigMsg.Status
 }
 
 //获取该用户所有主账号+子账号
-func AllAccount(userid string) []string {
-	mainId, _, _ := MainUserId(userid, "", 0)
-	account := []string{mainId}
-	data, ok := db.Mgo.Find("user", map[string]interface{}{"s_member_mainid": mainId, "i_member_sub_status": 1}, nil, `{"_id":1}`, false, -1, -1)
-	if ok && data != nil && len(*data) > 0 {
-		for _, v := range *data {
-			account = append(account, mongodb.BsonIdToSId(v["_id"]))
-		}
-	}
-	return account
+func AllAccount(session *httpsession.Session) []string {
+        mainId, _, _ := MainUserId(session)
+        account := []string{mainId}
+        data, ok := db.Mgo.Find("user", map[string]interface{}{"s_member_mainid": mainId, "i_member_sub_status": 1}, nil, `{"_id":1}`, false, -1, -1)
+        if ok && data != nil && len(*data) > 0 {
+                for _, v := range *data {
+                        account = append(account, mongodb.BsonIdToSId(v["_id"]))
+                }
+        }
+        return account
 }
 
 //招标文件解读次数
-func IsBidfilePower(userid string) (int, bool) {
-	overdue := false
-	count := 0
-	mainid, _, _ := MainUserId(userid, "", 0)
-	res := db.Mysql.SelectBySql(`select i_frequency from bigmember_service_user 
+func IsBidfilePower(session *httpsession.Session) (int, bool) {
+        overdue := false
+        count := 0
+        mainid, _, _ := MainUserId(session)
+        res := db.Mysql.SelectBySql(`select i_frequency from bigmember_service_user
 			where s_userid =? and s_serviceid=?  and i_status=0`, mainid, 11)
-	if res != nil && len(*res) > 0 {
-		count = qutil.IntAll((*res)[0]["i_frequency"])
-		bidfile_endtime := "2021年11月15日" //目前招标文件解读到11/15到期
-		bed := GetTime("2006年01月02日", bidfile_endtime)
-		overdue = true
-		n := time.Now()
-		if bed.Before(n) {
-			overdue = false
-		}
-	}
-	return count, overdue
+        if res != nil && len(*res) > 0 {
+                count = qutil.IntAll((*res)[0]["i_frequency"])
+                bidfile_endtime := "2021年11月15日" //目前招标文件解读到11/15到期
+                bed := GetTime("2006年01月02日", bidfile_endtime)
+                overdue = true
+                n := time.Now()
+                if bed.Before(n) {
+                        overdue = false
+                }
+        }
+        return count, overdue
 }
 
 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
 }

+ 249 - 248
src/jfw/modules/bigmember/src/util/view.go

@@ -1,288 +1,289 @@
 package util
 
 import (
-	"jy/src/jfw/modules/bigmember/src/db"
-	"encoding/json"
-	"fmt"
-	"log"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"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/bigmember/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"
-	bidSearch_sort = `{"publishtime":-1}`
-	findfields     = `"title"`
+        INDEX          = "bidding"
+        TYPE           = "bidding"
+        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"`
 )
 
-func SubViewDatas(userId, allquery string, pageNum, pageSize int) (keys []interface{}, list *[]map[string]interface{}, hasNextPage bool, count int64) {
-	if userId == "" {
-		return
-	}
-	sql := GetSqlObjFromId(userId, "", -1)
-	if sql == nil {
-		return
-	}
-	//PC端
-	if pageSize == 0 || pageSize > 100 {
-		pageSize = view_pageSize
-	}
-	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, "++"))
-	}
-	qstr := GetMemberViewSql(sql)
-	count = elastic.Count(INDEX, TYPE, qstr)
-	list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSearch_sort, bidSearch_field, (pageNum-1)*pageSize, pageSize, 0, false)
-	if list != nil {
-		for _, v := range *list {
-			v["_id"] = EncodeId(qutil.ObjToString(v["_id"]))
-		}
-	}
-	hasNextPage = list != nil && len(*list) == pageSize && pageNum < view_maxPageNum
-	return
+func SubViewDatas(userId, allquery string, pageNum, pageSize int,session *httpsession.Session) (keys []interface{}, list *[]map[string]interface{}, hasNextPage bool, count int64) {
+        if userId == "" {
+                return
+        }
+        sql := GetSqlObjFromId(session, "", -1)
+        if sql == nil {
+                return
+        }
+        //PC端
+        if pageSize == 0 || pageSize > 100 {
+                pageSize = view_pageSize
+        }
+        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, "++"))
+        }
+        qstr := GetMemberViewSql(sql)
+        count = elastic.Count(INDEX, TYPE, qstr)
+        list = elastic.GetAllByNgram(INDEX, TYPE, qstr, findfields, bidSearch_sort, bidSearch_field, (pageNum-1)*pageSize, pageSize, 0, false)
+        if list != nil {
+                for _, v := range *list {
+                        v["_id"] = EncodeId(qutil.ObjToString(v["_id"]))
+                }
+        }
+        hasNextPage = list != nil && len(*list) == pageSize && pageNum < view_maxPageNum
+        return
 }
 
 //member_jy
-func GetSqlObjFromId(_id, item string, index int) *ViewCondition {
-	var (
-		query *map[string]interface{}
-		ok    bool
-	)
-	if query, ok = db.Mgo.FindById("user", _id, `{"o_member_jy":1}`); !ok && (*query)["o_member_jy"] == nil {
-		return nil
-	}
-	o_member_jy, _ := (*query)["o_member_jy"].(map[string]interface{})
-	if o_member_jy["a_items"] == nil && o_member_jy["a_buyerclass"] == nil && o_member_jy["a_infotype"] == nil && o_member_jy["o_area"] == nil {
-		return nil
-	}
-	a_items := []interface{}{}
-	if o_member_jy["a_items"] != nil {
-		a_items = o_member_jy["a_items"].([]interface{})
-	}
-	a_buyerclass := []interface{}{}
-	if o_member_jy["a_buyerclass"] != nil {
-		a_buyerclass = o_member_jy["a_buyerclass"].([]interface{})
-	}
-	if len(a_buyerclass) > 0 && qutil.IntAllDef(o_member_jy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
-		a_buyerclass = append(a_buyerclass, "其它")
-	}
-	a_infotype := []interface{}{}
-	if o_member_jy["a_infotype"] != nil {
-		a_infotype = o_member_jy["a_infotype"].([]interface{})
-	}
-	o_area := map[string]interface{}{}
-	if o_member_jy["o_area"] != nil {
-		o_area = o_member_jy["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_member_jy["i_matchway"])),
-	}
+func GetSqlObjFromId(session *httpsession.Session, item string, index int) *ViewCondition {
+        var (
+                query *map[string]interface{}
+        )
+        if query := jy.GetSubScribeInfo(session, db.Mgo, "m", "10000"); query == nil {
+                return nil
+        }
+        o_member_jy, _ := (*query)["o_member_jy"].(map[string]interface{})
+        if o_member_jy["a_items"] == nil && o_member_jy["a_buyerclass"] == nil && o_member_jy["a_infotype"] == nil && o_member_jy["o_area"] == nil {
+                return nil
+        }
+        a_items := []interface{}{}
+        if o_member_jy["a_items"] != nil {
+                a_items = o_member_jy["a_items"].([]interface{})
+        }
+        a_buyerclass := []interface{}{}
+        if o_member_jy["a_buyerclass"] != nil {
+                a_buyerclass = o_member_jy["a_buyerclass"].([]interface{})
+        }
+        if len(a_buyerclass) > 0 && qutil.IntAllDef(o_member_jy["i_matchbuyerclass_other"], 1) == 1 && len(a_items) > 0 {
+                a_buyerclass = append(a_buyerclass, "其它")
+        }
+        a_infotype := []interface{}{}
+        if o_member_jy["a_infotype"] != nil {
+                a_infotype = o_member_jy["a_infotype"].([]interface{})
+        }
+        o_area := map[string]interface{}{}
+        if o_member_jy["o_area"] != nil {
+                o_area = o_member_jy["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_member_jy["i_matchway"])),
+        }
 }
 
 //获取大会员预览的查询语句
 func GetMemberViewSql(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(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 {
-				shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
+                for _, v := range scd.Keyword {
+                        shoulds := []string{}
+                        must_not := []string{}
+                        //附加词
+                        for _, vv := range v.Keyword {
+                                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+                        }
 
-			for _, vv := range v.Appended {
-				shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
+                        for _, vv := range v.Appended {
+                                shoulds = append(shoulds, fmt.Sprintf(multi_match, "\""+vv+"\""))
+                        }
 
-			//排除词
-			for _, vv := range v.Exclude {
-				must_not = append(must_not, fmt.Sprintf(multi_match, "\""+vv+"\""))
-			}
+                        //排除词
+                        for _, vv := range v.Exclude {
+                                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", qstr)
-	return qstr
+        qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
+        // log.Println("------qstr", qstr)
+        return qstr
 }
 
 //关键词 附加词 排除词
 func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
-	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
-		}
-		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)
-			}
-		}
-	}
-	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
+                }
+                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)
+                        }
+                }
+        }
+        return
 }
 
 //
 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
-	} else {
-		arr = cityArr
-	}
-	return
+        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
+        } else {
+                arr = cityArr
+        }
+        return
 }

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

@@ -1,7 +1,8 @@
 package action
 
 import (
-	"database/sql"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "database/sql"
 	"encoding/base64"
 	"fmt"
 	. "jy/src/jfw/modules/distribution/src/service/config"
@@ -121,10 +122,11 @@ func (this *Share) LinkShare(discored string) error {
 	fmt.Println(userId, openid, "user", `{"s_m_openid":"`+openid+`}`, `{"o_jy":1:"o_vipjy":1,"i_vip_status":1}`)
 	if discored[len(discored)-4:len(discored)-2] == "GX" {
 		if disType == "A" {
-			user, ok := MQFW.FindOneByField("user", `{"s_m_openid":"`+openid+`"}`, `{"o_jy":1:"o_vipjy":1,"i_vip_status":1}`)
+			//user, ok := MQFW.FindOneByField("user", `{"s_m_openid":"`+openid+`"}`, `{"o_jy":1:"o_vipjy":1,"i_vip_status":1}`)
+                            user := jy.GetSubScribeInfo(this.Session(),MQFW,"f", "10000")
 			log.Println(user)
 			if ok && user != nil {
-				i_vip_status := qu.IntAll((*user)["i_vip_status"])
+				i_vip_status := user.VipStatus
 				if i_vip_status > 0 {
 					modular := util.ObjToMap(Sysconfig.Modular[discored[:1]])
 					url = (*modular)["upgradeUrl"].(string)

+ 36 - 32
src/jfw/modules/publicapply/src/dataexport/entity/collection.go

@@ -1,38 +1,42 @@
 package entity
 
 import (
-	"jy/src/jfw/modules/publicapply/src/db"
-	util "app.yhyue.com/moapp/jybase/common"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "jy/src/jfw/modules/publicapply/src/config"
 )
 
-func IsPay(userid string) bool {
-	isVip, isMember, isEnt := false, false, false
-	phone := ""
-	data, ok := db.Mgo.FindById("user", userid, `"i_member_status":1,"i_vip_status":1,"s_m_phone":1,"s_phone":1,"o_vipjy":1`)
-	if data != nil && len(*data) > 0 && ok {
-		i_vip_status := util.IntAll((*data)["i_vip_status"])
-		if i_vip_status > 1 {
-			isVip = true
-		}
-		if i_member_status := util.IntAllDef((*data)["i_member_status"], 0); i_member_status > 0 {
-			isMember = true
-		}
-		if s_phone, _ := (*data)["s_phone"].(string); s_phone != "" {
-			phone = s_phone
-		} else if s_m_phone, _ := (*data)["s_m_phone"].(string); s_m_phone != "" {
-			phone = s_m_phone
-		}
-		if phone != "" {
-			//已购买企业未过期
-			if entInfo := *db.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 {
-					if util.IntAll(v["status"]) == 1 && util.IntAll(v["isNew"]) == 1 {
-						isEnt = true
-						break
-					}
-				}
-			}
-		}
-	}
-	return isVip || isEnt || isMember
+func IsPay(session *httpsession.Session) bool {
+        isVip, isMember, isEnt := false, false, false
+        /*data, ok := db.Mgo.FindById("user", userid, `"i_member_status":1,"i_vip_status":1,"s_m_phone":1,"s_phone":1,"o_vipjy":1`)
+        if data != nil && len(*data) > 0 && ok {
+        	i_vip_status := util.IntAll((*data)["i_vip_status"])
+        	if i_vip_status > 1 {
+        		isVip = true
+        	}
+        	if i_member_status := util.IntAllDef((*data)["i_member_status"], 0); i_member_status > 0 {
+        		isMember = true
+        	}
+        	if s_phone, _ := (*data)["s_phone"].(string); s_phone != "" {
+        		phone = s_phone
+        	} else if s_m_phone, _ := (*data)["s_m_phone"].(string); s_m_phone != "" {
+        		phone = s_m_phone
+        	}
+        	if phone != "" {
+        		//已购买企业未过期
+        		if entInfo := *db.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 {
+        				if util.IntAll(v["status"]) == 1 && util.IntAll(v["isNew"]) == 1 {
+        					isEnt = true
+        					break
+        				}
+        			}
+        		}
+        	}
+        }*/
+        data := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        isVip = data.Data.Vip.Status > 0
+        isEnt = data.Data.Entniche.Status > 0
+        isMember = data.Data.Member.Status > 0
+        return isVip || isEnt || isMember
 }

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

@@ -155,7 +155,7 @@ func (des *DataExportStruct) ByCollection() {
 				Buyerclass:  des.GetString("buyerclass"),
 				BuyerPhone:  buyerPhone,
 				WinnerPhone: winnerPhone,
-			}, entity.IsPay(userId), userId)
+			}, entity.IsPay(des.Session()), userId)
 			data := db.Mysql.SelectBySql(sql)
 			if data != nil && len(*data) > 0 {
 				for _, v := range *data {

+ 6 - 5
src/jfw/modules/publicapply/src/go.mod

@@ -3,19 +3,19 @@ module jy/src/jfw/modules/publicapply/src
 go 1.18
 
 require (
-	app.yhyue.com/moapp/jybase v0.0.0-20230109053435-fe962d69e751
-	app.yhyue.com/moapp/jypkg v0.0.0-20230110033557-004ea51c1d18
-	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230109023014-2cd2a0b9b979
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab
+	bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/gogf/gf/v2 v2.0.6
-	github.com/zeromicro/go-zero v1.4.3
+	github.com/zeromicro/go-zero v1.4.4
 	go.mongodb.org/mongo-driver v1.11.1
 )
 
 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/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c // indirect
 	github.com/BurntSushi/toml v0.4.1 // indirect
 	github.com/beorn7/perks v1.0.1 // indirect
 	github.com/cenkalti/backoff/v4 v4.1.3 // indirect
@@ -86,6 +86,7 @@ require (
 	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

+ 15 - 10
src/jfw/modules/publicapply/src/go.sum

@@ -11,17 +11,17 @@ app.yhyue.com/moapp/jybase v0.0.0-20220427020729-974c1a148186/go.mod h1:qNRA0sHu
 app.yhyue.com/moapp/jybase v0.0.0-20220719064915-2fef79005dfa/go.mod h1:FjBF25AYoBrPhVKTXGXWcmEAbBT0ATTK6KJMOA+I80Q=
 app.yhyue.com/moapp/jybase v0.0.0-20220802080941-07f401baab8b/go.mod h1:HelrO6tcD9TcKb/HOP2BLbzppyDz2kpQSFhPMQTUgbQ=
 app.yhyue.com/moapp/jybase v0.0.0-20230109015757-aa3d5e19b196/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jybase v0.0.0-20230109053435-fe962d69e751 h1:Z3Ye/xauzer3FymqIElv9/iEIfDOUkQBfnQPcKthoSc=
-app.yhyue.com/moapp/jybase v0.0.0-20230109053435-fe962d69e751/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033557-004ea51c1d18 h1:VEImnN1BTIOgjEwUUvqatGqz9/CUoLPumMfRvrbgAEY=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033557-004ea51c1d18/go.mod h1:n2XBXZGvxUuc4AZMeMYUZuK7ayrwDQ7UdrZd6AJkUVM=
+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-20230128092104-d8ae3867d2ab h1:a9XvegdF3aM0y9v5SHtX03LIGMS3+8J1ofoNeyw5J0Y=
+app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab/go.mod h1:MqJfBFTSfZhrNDEnE4e19BmaLkaMr+lYActLXm6lrpw=
 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/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-20230106052936-bd3ab7edf7a4 h1:Xv1D9avDKeaM5kQTisF/pIt8y7B7yQ/hAxuWEg75LMs=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c h1:g49jOlhZlBCJ3IgJA0rotfNf2Gh22pISffUtqxB8XtY=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
 bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.0-20220418005748-8ba5d936dd53/go.mod h1:E5lcDI3k4FESLxiAetCfWQTq8qfpy9cv0yN1oKoEO34=
 bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.0-20220419023723-0b32d4a41751/go.mod h1:6KL5LMEku83uRbre0W/bj5kXG2I6pJGBFtktmtp51yM=
 bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.0-20220419063004-233fc7ce006c/go.mod h1:6KL5LMEku83uRbre0W/bj5kXG2I6pJGBFtktmtp51yM=
@@ -31,8 +31,8 @@ bp.jydev.jianyu360.cn/BaseService/resourceCenter v0.0.4/go.mod h1:rRiGzKG4F/fmkN
 bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20220418072311-2062bed1e700/go.mod h1:KjcrxTzM96tBc6G4B8tlLBn1lrVy5UJYF8+eTdP4xAE=
 bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20220421015128-4a36f3eac5c5/go.mod h1:GT0QC4aaKDuXxAvaU4G02XjCc31TU1ctqBGqxQYOfC4=
 bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20220905055615-8540037e1b06/go.mod h1:LS21iwbgP8i3ZHJ1n4yNpLXQ/nzEudUOk0klC6VM2dQ=
-bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230109023014-2cd2a0b9b979 h1:hC97JNmBonTAsnDH4XMWLXVqWdo85tCo0ge04cy0e4E=
-bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230109023014-2cd2a0b9b979/go.mod h1:m7/aZ1r1FapNT2h3gqmCFVb0EV+CaJaNKNPHMzLHx8Y=
+bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1 h1:LH/gm2iRShZ64FEuF7LTzF62iJhOVVD9AxGVHFd0ORI=
+bp.jydev.jianyu360.cn/BaseService/userCenter v0.0.0-20230128064517-23fe8581b7f1/go.mod h1:m7/aZ1r1FapNT2h3gqmCFVb0EV+CaJaNKNPHMzLHx8Y=
 cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
 cloud.google.com/go v0.37.4/go.mod h1:NHPJ89PdicEuT9hdPXMROBD91xc5uRDxsMtSB16k7hw=
@@ -441,8 +441,9 @@ github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGn
 github.com/alicebob/miniredis/v2 v2.14.1/go.mod h1:uS970Sw5Gs9/iK3yBg0l9Uj9s25wXxSpQUE9EaJ/Blg=
 github.com/alicebob/miniredis/v2 v2.17.0/go.mod h1:gquAfGbzn92jvtrSC69+6zZnwSODVXVpYDRaGhWaL6I=
 github.com/alicebob/miniredis/v2 v2.22.0/go.mod h1:XNqvJdQJv5mSuVMc0ynneafpnL/zv52acZ6kqeS0t88=
-github.com/alicebob/miniredis/v2 v2.23.1 h1:jR6wZggBxwWygeXcdNyguCOCIjPsZyNUNlAkTx2fu0U=
 github.com/alicebob/miniredis/v2 v2.23.1/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
+github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
+github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
 github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
 github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=
@@ -807,6 +808,7 @@ github.com/jhump/protoreflect v1.10.3/go.mod h1:7GcYQDdMU/O/BBrl/cX6PNHpXh6cenjd
 github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E=
 github.com/jhump/protoreflect v1.12.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jhump/protoreflect v1.14.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
+github.com/jhump/protoreflect v1.14.1/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs=
 github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
 github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
@@ -1108,8 +1110,9 @@ github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQ
 github.com/zeromicro/go-zero v1.3.2/go.mod h1:DEj3Fwj1Ui1ltsgf6YqwTL9nD4+tYzIRX0c1pWtQo1E=
 github.com/zeromicro/go-zero v1.3.5/go.mod h1:wh4o794b7Ul3W0k35Pw9nc3iB4O0OpaQTMQz/PJc1bc=
 github.com/zeromicro/go-zero v1.4.0/go.mod h1:1amLn98K7c6FLntb9f8hdmq26ajtolOg4DTFWnRt54o=
-github.com/zeromicro/go-zero v1.4.3 h1:sTQ++6fxQHJnpGCN7h2CUrhWmbvhBqEgE75cJl635SM=
 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/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=
@@ -1161,6 +1164,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0/go.mod h1:FnDp7XemjN3o
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0/go.mod h1:OfUCyyIiDvNXHWpcWgbF+MWvqPZiNa3YDEnivcnYsV0=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0 h1:j2RFV0Qdt38XQ2Jvi4WIsQ56w8T7eSirYbMw19VXRDg=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0/go.mod h1:pILgiTEtrqvZpoiuGdblDgS5dbIaTgDrkIuKfEFkt+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 h1:S8DedULB3gp93Rh+9Z+7NTEv+6Id/KYS7LDyipZ9iCE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0/go.mod h1:5WV40MLWwvWlGP7Xm8g3pMcg0pKOUY609qxJn8y7LmM=
 go.opentelemetry.io/otel/exporters/zipkin v1.3.0/go.mod h1:LxGGfHIYbvsFnrJtBcazb0yG24xHdDGrT/H6RB9r3+8=
 go.opentelemetry.io/otel/exporters/zipkin v1.8.0/go.mod h1:0uYAyCuGT67MFV9Z/Mmx93wGuugHw0FbxMc74fs3LNo=
 go.opentelemetry.io/otel/exporters/zipkin v1.9.0/go.mod h1:HyIvYIu37wV4Wx5azd7e05x9k/dOz9KB4x0plw2QNvs=

+ 28 - 28
src/jfw/modules/publicapply/src/grpc/usercenter.go

@@ -1,15 +1,15 @@
 package grpc
 
 import (
-	"context"
-	"log"
+        "context"
+        "log"
 
-	"bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/pb"
-	"bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/usercenter"
-	"github.com/gogf/gf/v2/frame/g"
-	"github.com/gogf/gf/v2/os/gctx"
-	"github.com/zeromicro/go-zero/core/discov"
-	"github.com/zeromicro/go-zero/zrpc"
+        "bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/pb"
+        "bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/usercenter"
+        "github.com/gogf/gf/v2/frame/g"
+        "github.com/gogf/gf/v2/os/gctx"
+        "github.com/zeromicro/go-zero/core/discov"
+        "github.com/zeromicro/go-zero/zrpc"
 )
 
 var UserCenter = &userCenter{}
@@ -17,24 +17,24 @@ var UserCenter = &userCenter{}
 type userCenter struct{}
 
 func (u *userCenter) IdentityList(userId int64) []*pb.Identity {
-	var ctx = gctx.New()
-	client, err := zrpc.NewClient(zrpc.RpcClientConf{
-		Etcd: discov.EtcdConf{
-			Hosts: g.Cfg().MustGet(ctx, "etcd.hosts").Strings(),
-			Key:   g.Cfg().MustGet(ctx, "userCenterKey").String(),
-		},
-	})
-	if err != nil {
-		log.Println(err)
-		return nil
-	}
-	defer client.Conn().Close()
-	resp, err := usercenter.NewUserCenter(client).IdentityList(context.Background(), &pb.IdentityReq{
-		UserId: userId,
-	})
-	if err != nil {
-		log.Println(err)
-		return nil
-	}
-	return resp.Identitys
+        var ctx = gctx.New()
+        client, err := zrpc.NewClient(zrpc.RpcClientConf{
+                Etcd: discov.EtcdConf{
+                        Hosts: g.Cfg().MustGet(ctx, "etcd.hosts").Strings(),
+                        Key:   g.Cfg().MustGet(ctx, "userCenterKey").String(),
+                },
+        })
+        if err != nil {
+                log.Println(err)
+                return nil
+        }
+        defer client.Conn().Close()
+        resp, err := usercenter.NewUserCenter(client).IdentityList(context.Background(), &pb.IdentityReq{
+                Id: userId,
+        })
+        if err != nil {
+                log.Println(err)
+                return nil
+        }
+        return resp.Identitys
 }

+ 205 - 259
src/jfw/modules/publicapply/src/me/me.go

@@ -1,294 +1,240 @@
 package me
 
 import (
-	"jy/src/jfw/modules/publicapply/src/db"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"app.yhyue.com/moapp/jybase/redis"
-	"time"
-	"jy/src/jfw/modules/publicapply/src/util"
+        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"
+        "jy/src/jfw/modules/publicapply/src/config"
+        "jy/src/jfw/modules/publicapply/src/db"
+        "jy/src/jfw/modules/publicapply/src/util"
+        "time"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Me struct {
-	*xweb.Action
+        *xweb.Action
 
-	myInfo xweb.Mapper `xweb:"/myinfo"`
+        myInfo xweb.Mapper `xweb:"/myinfo"`
 }
 
 func init() {
-	xweb.AddAction(&Me{})
+        xweb.AddAction(&Me{})
 }
 
 const (
-	Role_admin_system     = 1 //系统管理员
-	Role_admin_department = 2 //部门管理员
+        Role_admin_system     = 1 //系统管理员
+        Role_admin_department = 2 //部门管理员
 )
 
 //
 func (m *Me) MyInfo() {
-	r := map[string]interface{}{
-		"userType": "free",
-	}
-	userId, _ := m.GetSession("userId").(string)
-	entId := qutil.IntAll(m.GetSession("entId"))
-	user, ok := db.Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,"o_jy":1,"i_vip_status":1,"l_vip_endtime":1,"o_vipjy":1,"o_member_jy":1}`)
-	if ok && user != nil {
-		isExpire := -1
-		isPassCount := 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
-		} else {
-			isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+tedayNum+"_"+userId) >= 150
-		}
-		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 != "" {
-			//已购买企业未过期
-			if entInfo := db.Mysql.SelectBySql(`SELECT status,isNew,id,power_source 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 {
-					if entId > 0 {
-						if entId == qutil.IntAll(v["id"]) {
-							if qutil.IntAll(v["power_source"]) == 1 {
-								break
-							} else if qutil.IntAll(v["status"]) == 1 && qutil.IntAll(v["isNew"]) == 1 {
-								isEnt = true
-								break
-							}
-						}
-					} else {
-						if qutil.IntAll(v["status"]) == 1 && qutil.IntAll(v["isNew"]) == 1 && qutil.IntAll(v["power_source"]) != 1 {
-							isEnt = true
-							break
-						}
-					}
-				}
-			}
-		}
-		o_entniche := &map[string]interface{}{}
-		data := []string{}
-		if isEnt {
-			r["userType"] = "entniche"
-			entId := qutil.IntAll(m.GetSession("entId"))
-			entUserId := qutil.IntAll(m.GetSession("entUserId"))
-			entInfo := GetEntInfo(entId, entUserId)
-			if entId != 0 && entUserId != 0 {
-				model := entInfo.Ent.Model //1-统一订阅 2-个人订阅
-				var res_ *map[string]interface{}
-				switch model {
-				case 1:
-					res_, _ = db.Mgo.FindOne("entniche_rule", map[string]interface{}{
-						"i_deptid": entInfo.Dept.Id,
-						"i_entid":  entId,
-					})
-				case 2:
-					res_, _ = db.Mgo.FindOne("entniche_rule", map[string]interface{}{
-						"i_userid": entUserId,
-						"i_entid":  entId,
-					})
-				}
-				if res_ != nil {
-					o_entniche = qutil.ObjToMap((*res_)["o_entniche"])
-				}
-				if (*o_entniche)["a_items"] != nil {
-					a_items := qutil.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
-					for _, v := range a_items {
-						if v["a_key"] != nil {
-							a_key_arr := qutil.ObjArrToMapArr(v["a_key"].([]interface{}))
-							for kk, vv := range a_key_arr {
-								if vv["notkey"] == nil {
-									a_key_arr[kk]["notkey"] = []string{}
-								}
-								if vv["appendkey"] == nil {
-									a_key_arr[kk]["appendkey"] = []string{}
-								}
-								for kkk, vvv := range vv {
-									if vvv == nil && kkk == "notkey" {
-										a_key_arr[kk][kkk] = []string{}
-									}
-									if vvv == nil && kkk == "appendkey" {
-										a_key_arr[kk][kkk] = []string{}
-									}
-								}
-							}
-							v["a_key"] = a_key_arr
-						}
-					}
-					data = qutil.ObjArrToStringArr(qutil.MapArrToObjArr(a_items))
-				}
-
-			}
-
-		}
-		r["isExpire"] = isExpire
-		r["vipStatus"] = qutil.IntAll((*user)["i_vip_status"])
-		r["isPassCount"] = isPassCount
-		r["haskey"], _ = GetKeySet(jy.SwitchService.GetEntniche(m.Session(), db.Mgo, db.Mysql), user, data)
-	}
-	m.ServeJson(r)
+        r := map[string]interface{}{
+                "userType": "free",
+        }
+        userId, _ := m.GetSession("userId").(string)
+        //user, ok := db.Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,"o_jy":1,"i_vip_status":1,"l_vip_endtime":1,"o_vipjy":1,"o_member_jy":1}`)
+        user := jy.GetBigVipUserBaseMsg("10000", m.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        if user != nil {
+                isExpire := -1
+                isPassCount := false
+                tedayNum := time.Unix(time.Now().Unix(), 1).Format("20060102")
+                if user.Data.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 := user.Data.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
+                } else {
+                        isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+tedayNum+"_"+userId) >= 150
+                }
+                isEnt := user.Data.Entniche.Status > 0
+                if isEnt {
+                        r["userType"] = "entniche"
+                       /* o_entniche := jy.GetSubScribeInfo(m.Session(), db.Mgo, "s", "10000")
+                        if (*o_entniche)["a_items"] != nil {
+                                a_items := qutil.ObjArrToMapArr((*o_entniche)["a_items"].([]interface{}))
+                                for _, v := range a_items {
+                                        if v["a_key"] != nil {
+                                                a_key_arr := qutil.ObjArrToMapArr(v["a_key"].([]interface{}))
+                                                for kk, vv := range a_key_arr {
+                                                        if vv["notkey"] == nil {
+                                                                a_key_arr[kk]["notkey"] = []string{}
+                                                        }
+                                                        if vv["appendkey"] == nil {
+                                                                a_key_arr[kk]["appendkey"] = []string{}
+                                                        }
+                                                        for kkk, vvv := range vv {
+                                                                if vvv == nil && kkk == "notkey" {
+                                                                        a_key_arr[kk][kkk] = []string{}
+                                                                }
+                                                                if vvv == nil && kkk == "appendkey" {
+                                                                        a_key_arr[kk][kkk] = []string{}
+                                                                }
+                                                        }
+                                                }
+                                                v["a_key"] = a_key_arr
+                                        }
+                                }
+                                data = qutil.ObjArrToStringArr(qutil.MapArrToObjArr(a_items))
+                        }*/
+                }
+                r["isExpire"] = isExpire
+                r["vipStatus"] = user.Data.Vip.Status
+                r["isPassCount"] = isPassCount
+                r["haskey"], _ = GetKeySet(jy.SwitchService.GetEntniche(m.Session(), db.Mgo, db.Mysql),m.Session())
+        }
+        m.ServeJson(r)
 }
 
 //是否有订阅词
-func GetKeySet(t string, u *map[string]interface{}, data []string) (bool, []string) {
-	var industry_ = []string{}
-	if u != nil {
-		if t == jy.SwitchService.Free {
-			o_jy, _ := (*u)["o_jy"].(map[string]interface{})
-			a_key, _ := o_jy["a_key"].([]interface{})
-			return len(a_key) > 0, industry_
-		} else {
-			var obj map[string]interface{}
-			if t == jy.SwitchService.Vip {
-				obj, _ = (*u)["o_vipjy"].(map[string]interface{})
-			} else if t == jy.SwitchService.Member {
-				obj, _ = (*u)["o_member_jy"].(map[string]interface{})
-			} else if t == jy.SwitchService.Entniche {
-				if len(data) > 0 {
-					return true, data
-				} else {
-					return false, data
-				}
+func GetKeySet(t string, session  *httpsession.Session) (bool, []string) {
+        var industry_ = []string{}
+
+                if t == jy.SwitchService.Free{
+                        o_jy:= jy.GetSubScribeInfo(session,db.Mgo,"f","10000")
+                        a_key, _ := (*o_jy)["a_key"].([]interface{})
+                        return len(a_key) > 0, industry_
+                } else {
+                        obj:= &map[string]interface{}{}
+                        if t == jy.SwitchService.Vip {
+                                obj= jy.GetSubScribeInfo(session,db.Mgo,"v","10000")
+                                //obj, _ = (*u)["o_vipjy"].(map[string]interface{})
+                        } else if t == jy.SwitchService.Member {
+                                obj= jy.GetSubScribeInfo(session,db.Mgo,"m","10000")
+
+                        } else if t == jy.SwitchService.Entniche {
+                                obj= jy.GetSubScribeInfo(session,db.Mgo,"m","10000")
 
-			}
-			if obj != nil {
-				if buyerclassObj, ok := obj["a_buyerclass"].([]interface{}); ok {
-					industry_ = qutil.ObjArrToStringArr(buyerclassObj)
-				}
-				itmes, _ := obj["a_items"].([]interface{})
-				for _, v := range itmes {
-					item, _ := v.(map[string]interface{})
-					keys, _ := item["a_key"].([]interface{})
-					if len(keys) > 0 {
-						return true, industry_
-					}
-				}
-			}
-		}
-	}
-	return false, industry_
+                        }
+                        if obj != nil {
+                                if buyerclassObj, ok := (*obj)["a_buyerclass"].([]interface{}); ok {
+                                        industry_ = qutil.ObjArrToStringArr(buyerclassObj)
+                                }
+                                itmes, _ := (*obj)["a_items"].([]interface{})
+                                for _, v := range itmes {
+                                        item, _ := v.(map[string]interface{})
+                                        keys, _ := item["a_key"].([]interface{})
+                                        if len(keys) > 0 {
+                                                return true, industry_
+                                        }
+                                }
+                        }
+                }
+        return false, industry_
 }
 
 type CurrentUser struct {
-	Role_admin_department bool        //是否是部门管理员
-	Role_admin_system     bool        //是否是系统管理员
-	Ent                   *EntInfo    //企业信息
-	Dept                  *Department //部门信息
-	BondPhone             string      //手机号
-	NickName              string      //昵称
-	HeadImageUrl          string      //头像
-	PersonalAuth          int         //个人认证
-	PersonalAuthReason    string      //个人认证不通过原因
-	User_power            int         //是否分配权限
-	User_name             string      //用户姓名
+        Role_admin_department bool        //是否是部门管理员
+        Role_admin_system     bool        //是否是系统管理员
+        Ent                   *EntInfo    //企业信息
+        Dept                  *Department //部门信息
+        BondPhone             string      //手机号
+        NickName              string      //昵称
+        HeadImageUrl          string      //头像
+        PersonalAuth          int         //个人认证
+        PersonalAuthReason    string      //个人认证不通过原因
+        User_power            int         //是否分配权限
+        User_name             string      //用户姓名
 }
 type EntInfo struct {
-	Id                    int    //企业id
-	Name                  string //企业名
-	Phone                 string //手机号
-	Model                 int    //1-统一订阅,2-个人订阅
-	Status                int    //0:未生效,1:已生效,-1:已到期
-	Quota                 int    //限额人数
-	Startdate             int    //开始时间
-	Enddate               int    //结束时间
-	Createtime            string //创建时间
-	Mail                  string //邮箱
-	Marketarea            string
-	Industryclass         string //行业分类
-	Admin                 string //管理员姓名-只有商机洞察中有,可能没什么用
-	Code                  string //统一社会信用代码
-	License               string //营业执照
-	Legal_name            string //法人姓名
-	Legal_idcard          string //身份证号
-	Legal_idcard_front    string //身份证前面
-	Legal_idcard_after    string //身份证后面
-	Auth_status           int    //-1-未通过 0-未认证 1-已认证
-	Auth_reason           string //审核不通过的原因说明
-	Auth_time             string //提交时间
-	Audit_time            string //审核时间
-	User_id               int
-	Auth_type             int    //认证类型 1-事业单位  其他:企业
-	Legal_mancard         string //法人证
-	IsNew                 int    //1新商机管理0老商机管理
-	Power_virtual_account int    //是否有添加虚拟账号权限
-	Virtual_account_rule  string //虚拟账号的手机号规则
+        Id                    int    //企业id
+        Name                  string //企业名
+        Phone                 string //手机号
+        Model                 int    //1-统一订阅,2-个人订阅
+        Status                int    //0:未生效,1:已生效,-1:已到期
+        Quota                 int    //限额人数
+        Startdate             int    //开始时间
+        Enddate               int    //结束时间
+        Createtime            string //创建时间
+        Mail                  string //邮箱
+        Marketarea            string
+        Industryclass         string //行业分类
+        Admin                 string //管理员姓名-只有商机洞察中有,可能没什么用
+        Code                  string //统一社会信用代码
+        License               string //营业执照
+        Legal_name            string //法人姓名
+        Legal_idcard          string //身份证号
+        Legal_idcard_front    string //身份证前面
+        Legal_idcard_after    string //身份证后面
+        Auth_status           int    //-1-未通过 0-未认证 1-已认证
+        Auth_reason           string //审核不通过的原因说明
+        Auth_time             string //提交时间
+        Audit_time            string //审核时间
+        User_id               int
+        Auth_type             int    //认证类型 1-事业单位  其他:企业
+        Legal_mancard         string //法人证
+        IsNew                 int    //1新商机管理0老商机管理
+        Power_virtual_account int    //是否有添加虚拟账号权限
+        Virtual_account_rule  string //虚拟账号的手机号规则
 }
 type Department struct {
-	Id         int
-	Name       string //部门名
-	Pid        int    //上级部门id
-	Pname      string //上级部门名称
-	Nodiff     int    //全员无差别接收 0:关闭 1:打开
-	Subdis     int    //订阅分发 0:关闭 1:打开
-	Aid        int    //管理员id
-	Aname      string //管理员姓名
-	Rname      string //角色名
-	User_count int    //该部门下员工的总数
-	Dept_count int    //该部门下子部门总数
-	Ent_id     int    //公司id
+        Id         int
+        Name       string //部门名
+        Pid        int    //上级部门id
+        Pname      string //上级部门名称
+        Nodiff     int    //全员无差别接收 0:关闭 1:打开
+        Subdis     int    //订阅分发 0:关闭 1:打开
+        Aid        int    //管理员id
+        Aname      string //管理员姓名
+        Rname      string //角色名
+        User_count int    //该部门下员工的总数
+        Dept_count int    //该部门下子部门总数
+        Ent_id     int    //公司id
 }
 
 //当前登录用户的信息
 func GetEntInfo(entId, entUserId int) *CurrentUser {
-	currentUser := &CurrentUser{
-		Ent:  &EntInfo{},
-		Dept: &Department{},
-	}
-	currentUser.Ent = &EntInfo{Id: entId}
-	user := db.Mysql.SelectBySql(`SELECT a.name as user_name from entniche_user a INNER JOIN entniche_user_role b on (a.id=b.user_id) where a.id=? and b.role_id=? limit 1`, entUserId, Role_admin_system)
-	if user != nil && len(*user) > 0 {
-		currentUser.Role_admin_system = true
-		currentUser.User_name, _ = (*user)[0]["user_name"].(string)
-		currentUser.User_power = 1
-		r := db.Mysql.SelectBySql(`SELECT id,name,subdis,nodiff from entniche_department where ent_id=? and pid=0 limit 1`, entId)
-		if r != nil && len(*r) == 1 {
-			department := util.JsonUnmarshal((*r)[0], &Department{}).(*Department)
-			if department != nil {
-				department.Pid = department.Id
-				currentUser.Dept = department
-			}
-		}
-	} else {
-		//角色、权限
-		r := db.Mysql.SelectBySql(`SELECT a.name as user_name,a.power as user_power,b.role_id,d.id as dept_id,d.name as dept_name,d.subdis as dept_subdis,d.nodiff as dept_nodiff,e.id as dept_pid from entniche_user a 
-			LEFT JOIN entniche_user_role b on (b.user_id=?) 
-			INNER JOIN entniche_department_user c on (a.id=? and a.id=c.user_id) 
-			INNER JOIN entniche_department d on (c.dept_id=d.id) 
-			INNER JOIN entniche_department e on (e.ent_id=? and e.pid=0) 
+        currentUser := &CurrentUser{
+                Ent:  &EntInfo{},
+                Dept: &Department{},
+        }
+        currentUser.Ent = &EntInfo{Id: entId}
+        user := db.Mysql.SelectBySql(`SELECT a.name as user_name from entniche_user a INNER JOIN entniche_user_role b on (a.id=b.user_id) where a.id=? and b.role_id=? limit 1`, entUserId, Role_admin_system)
+        if user != nil && len(*user) > 0 {
+                currentUser.Role_admin_system = true
+                currentUser.User_name, _ = (*user)[0]["user_name"].(string)
+                currentUser.User_power = 1
+                r := db.Mysql.SelectBySql(`SELECT id,name,subdis,nodiff from entniche_department where ent_id=? and pid=0 limit 1`, entId)
+                if r != nil && len(*r) == 1 {
+                        department := util.JsonUnmarshal((*r)[0], &Department{}).(*Department)
+                        if department != nil {
+                                department.Pid = department.Id
+                                currentUser.Dept = department
+                        }
+                }
+        } else {
+                //角色、权限
+                r := db.Mysql.SelectBySql(`SELECT a.name as user_name,a.power as user_power,b.role_id,d.id as dept_id,d.name as dept_name,d.subdis as dept_subdis,d.nodiff as dept_nodiff,e.id as dept_pid from entniche_user a
+			LEFT JOIN entniche_user_role b on (b.user_id=?)
+			INNER JOIN entniche_department_user c on (a.id=? and a.id=c.user_id)
+			INNER JOIN entniche_department d on (c.dept_id=d.id)
+			INNER JOIN entniche_department e on (e.ent_id=? and e.pid=0)
 			order by a.id desc limit 1`, entUserId, entUserId, entId)
-		if r != nil && len(*r) == 1 {
-			currentUser.User_name, _ = (*r)[0]["user_name"].(string)
-			currentUser.User_power = qutil.IntAll((*r)[0]["user_power"])
-			if qutil.IntAll((*r)[0]["role_id"]) == Role_admin_department {
-				currentUser.Role_admin_department = true
-			}
-			currentUser.Dept.Id = qutil.IntAll((*r)[0]["dept_id"])
-			currentUser.Dept.Pid = qutil.IntAll((*r)[0]["dept_pid"])
-			currentUser.Dept.Name = qutil.ObjToString((*r)[0]["dept_name"])
-			currentUser.Dept.Subdis = qutil.IntAll((*r)[0]["dept_subdis"])
-			currentUser.Dept.Nodiff = qutil.IntAll((*r)[0]["dept_nodiff"])
-		}
-	}
-	return currentUser
+                if r != nil && len(*r) == 1 {
+                        currentUser.User_name, _ = (*r)[0]["user_name"].(string)
+                        currentUser.User_power = qutil.IntAll((*r)[0]["user_power"])
+                        if qutil.IntAll((*r)[0]["role_id"]) == Role_admin_department {
+                                currentUser.Role_admin_department = true
+                        }
+                        currentUser.Dept.Id = qutil.IntAll((*r)[0]["dept_id"])
+                        currentUser.Dept.Pid = qutil.IntAll((*r)[0]["dept_pid"])
+                        currentUser.Dept.Name = qutil.ObjToString((*r)[0]["dept_name"])
+                        currentUser.Dept.Subdis = qutil.IntAll((*r)[0]["dept_subdis"])
+                        currentUser.Dept.Nodiff = qutil.IntAll((*r)[0]["dept_nodiff"])
+                }
+        }
+        return currentUser
 }

+ 245 - 206
src/jfw/modules/publicapply/src/subscribe/entity/entity.go

@@ -1,212 +1,234 @@
 package entity
 
 import (
-	"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/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
+        UserId  string
+        Session *httpsession.Session
 }
 
 //
-func NewParamInfo(userId string) *ParamInfo {
-	return &ParamInfo{userId}
+func NewParamInfo(userId string, session *httpsession.Session) *ParamInfo {
+        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}`)
-	if ok && mData != nil && len(*mData) != 0 {
-		o_jy, _ := (*mData)["o_jy"].(map[string]interface{})
-		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{},
-			}
-		}
-		if db.Mgo.UpdateById("user", this.UserId, map[string]interface{}{"$set": setMap}) {
-			jy.ClearBigVipUserPower(this.UserId)
-		}
-	}
-	return b
+        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)
+                }
+        }
+        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
-	}
-	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, "++"))
-	}
-	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
+        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)
+                }
+                //dev3.5 附加词也要高亮
+                for _, k := range v.Appended {
+                        keys_one = append(keys_one, k)
+                }
+                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
 }
 
 //
 func (pi *ParamInfo) GetSubMsg() UserSubMsg {
-	mData, ok := db.Mgo.FindById("user", pi.UserId, `{"o_jy":1}`)
-	var res = UserSubMsg{
-		Basenum: jy.BaseAreaNum,
-	}
-	if ok && mData != nil && len(*mData) != 0 {
-		o_jy, _ := (*mData)["o_jy"].(map[string]interface{})
-		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{})
+        // mData, ok := db.Mgo.FindById("user", pi.UserId, `{"o_jy":1}`)
+        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{})
+                }
+                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
-		}
-		//关键词
-		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,
-				})
-			}
-		}
-		res.Matchway = 1 //匹配方式 1:标题 2:正文  免费默认1
-	}
-	return res
+                //免费用户未购买省份订阅包 按年算
+                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{}))
+                                }
+                                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,
+                                })
+                        }
+                }
+                res.Matchway = 1 //匹配方式 1:标题 2:正文  免费默认1
+        }
+        return res
 }
 
 /*是否需要到期弹窗提醒
@@ -214,51 +236,68 @@ tip : true需要 false不需要
 area : 免费订阅的地区
 */
 func (pi *ParamInfo) AreaPackTip() map[string]interface{} {
-	m := map[string]interface{}{
-		"tip":  false,
-		"area": "",
-	}
-	mData, ok := db.Mgo.FindById("user", pi.UserId, `{"o_jy":1}`)
-	if ok && mData != nil && len(*mData) != 0 {
-		o_jy, _ := (*mData)["o_jy"].(map[string]interface{})
-		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
-				}
-			}
-		}
-	}
-	return m
+        m := map[string]interface{}{
+                "tip":  false,
+                "area": "",
+        }
+        /*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
+                                }
+                        }
+                }
+        }
+        return m
 }
 
 //修改到期提醒状态
 func (pi *ParamInfo) UpdateAreaPackTip() bool {
-	return db.Mgo.UpdateById("user", pi.UserId, map[string]interface{}{
-		"$set": map[string]interface{}{
-			"o_jy.i_areapackTip": 0,
-		},
-	})
+        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
 }
 
 //
 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
 }

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

@@ -17,7 +17,7 @@ func (this *ServiceStruct) OneProvinceSet() {
 		if this.Method() != "POST" {
 			return Result{Data: nil, Error_msg: Error_msg_1005}
 		}
-		newFN := entity.NewParamInfo(userId)
+		newFN := entity.NewParamInfo(userId,this.Session())
 		return Result{Data: newFN.SetAreaByOneProvince()}
 	}()
 	this.ServeJson(r)
@@ -31,7 +31,7 @@ func (this *ServiceStruct) SubscribeMsg() {
 		if this.Method() != "POST" {
 			return Result{Data: nil, Error_msg: Error_msg_1005}
 		}
-		newFN := entity.NewParamInfo(userId)
+		newFN := entity.NewParamInfo(userId,this.Session())
 		return Result{Data: newFN.GetSubMsg()}
 	}()
 	this.ServeJson(r)
@@ -80,7 +80,7 @@ func (this *ServiceStruct) AreaPackEndTip(types string) {
 	userId, _ := this.GetSession("userId").(string)
 	defer qu.Catch()
 	r := func() Result {
-		newFN := entity.NewParamInfo(userId)
+		newFN := entity.NewParamInfo(userId,this.Session())
 		switch types {
 		case "tip":
 			return Result{Data: newFN.AreaPackTip()}

+ 301 - 279
src/jfw/modules/publicapply/src/subscribePush/entity/historyPush.go

@@ -1,18 +1,18 @@
 package entity
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/publicapply/src/db"
-	es "jy/src/jfw/modules/publicapply/src/subscribePush/entity/service"
-	"log"
-	"strconv"
-	"strings"
-	"time"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/publicapply/src/config"
+        "jy/src/jfw/modules/publicapply/src/db"
+        "log"
+        "strings"
+        "time"
 
-	util "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        util "app.yhyue.com/moapp/jybase/common"
+        elastic "app.yhyue.com/moapp/jybase/esv1"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 type historyPush struct {
@@ -22,302 +22,324 @@ 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 {
+                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}})
 
-	}
+        }
 }
 
 //IsInTsGuide 是否进入向导
-func (hp *historyPush) IsInTsGuide(userid string) bool {
-	if userid == "" {
-		return false
-	}
-	data, ok := db.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
-	if ok {
-		//付费用户无免费订阅,不进入订阅向导页面
-		if util.IntAll((*data)["i_member_status"]) > 0 || util.IntAll((*data)["i_vip_status"]) > 0 {
-			return false
-		}
-		o_jy, _ := (*data)["o_jy"].(map[string]interface{})
-		i_ts_guide := util.IntAll((*data)["i_ts_guide"])
-		if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
-			return true
-		}
-	}
-	return false
+func (hp *historyPush) IsInTsGuide(session *httpsession.Session) bool {
+        //后期
+        /*data, ok := db.Mgo.FindById("user", userid, `{"o_jy":1,"i_ts_guide":1,"":1,"i_member_status":1,"i_vip_status":1}`)
+          if ok {
+          	//付费用户无免费订阅,不进入订阅向导页面
+          	if util.IntAll((*data)["i_member_status"]) > 0 || util.IntAll((*data)["i_vip_status"]) > 0 {
+          		return false
+          	}
+          	o_jy, _ := (*data)["o_jy"].(map[string]interface{})
+          	i_ts_guide := util.IntAll((*data)["i_ts_guide"])
+          	if i_ts_guide == 2 || (i_ts_guide == 0 && len(o_jy) == 0) {
+          		return true
+          	}
+          }*/
+        data := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        if data.Data.Member.Status > 0 || data.Data.Vip.Status > 0 {
+                return false
+        }
+        return false
 }
 
-func PushView(userid, allquery, field string, pageNum, pageSize int) (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
-	}
-	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
+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
 }
 
 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
+        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
-	}{}
-	switch d.ModuleFlag {
-	case "m":
-		//大会员
-		userMap, ok := db.Mgo.FindById("user", d.UserId, `{"o_member_jy":1,"i_member_status":1}`)
-		if !ok || userMap == nil || len(*userMap) == 0 {
-			return &ViewCondition{}, 0
-		}
-		if util.IntAll((*userMap)["i_member_status"]) > 0 {
-			isPayBool = true
-			o_member_jy, _ := (*userMap)["o_member_jy"].(map[string]interface{})
-			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":
-		//超级订阅
-		userMap, ok := db.Mgo.FindById("user", d.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
-		if !ok || userMap == nil || len(*userMap) == 0 {
-			return &ViewCondition{}, 0
-		}
-		if util.IntAll((*userMap)["i_vip_status"]) > 0 {
-			isPayBool = true
-			o_vipjy, _ := (*userMap)["o_vipjy"].(map[string]interface{})
-			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:
-		//免费用户
-		userMap, ok := db.Mgo.FindById("user", d.UserId, `{"o_jy":1}`)
-		if !ok || userMap == nil || len(*userMap) == 0 {
-			return &ViewCondition{}, 0
-		}
-		o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})
-		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("10000", d.Session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        switch d.ModuleFlag {
+        case "m":
+                //大会员
+                /* userMap, ok := db.Mgo.FindById("user", d.UserId, `{"o_member_jy":1,"i_member_status":1}`)
+                   if !ok || userMap == nil || len(*userMap) == 0 {
+                           return &ViewCondition{}, 0
+                   }*/
+                //if util.IntAll((*userMap)["i_member_status"]) > 0 {
+                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":
+                //超级订阅
+                /*  userMap, ok := db.Mgo.FindById("user", d.UserId, `{"o_vipjy":1,"i_vip_status":1}`)
+                    if !ok || userMap == nil || len(*userMap) == 0 {
+                            return &ViewCondition{}, 0
+                    }
+                    if util.IntAll((*userMap)["i_vip_status"]) > 0 {*/
+                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 {
+                if data.Data.Entniche.Status > 0 {
+                        //订阅词获取
+                        entInfo := jy.GetSubScribeInfo(d.Session, db.Mgo, "s", "10000")
+                        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:
+                //免费用户
+                /*userMap, ok := db.Mgo.FindById("user", d.UserId, `{"o_jy":1}`)
+                if !ok || userMap == nil || len(*userMap) == 0 {
+                        return &ViewCondition{}, 0
+                }
+                o_jy, _ := (*userMap)["o_jy"].(map[string]interface{})*/
+
+                        //订阅词获取
+                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}}`
+        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)
-	}
+        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
 }

+ 1029 - 947
src/jfw/modules/publicapply/src/subscribePush/entity/keyWords.go

@@ -1,1016 +1,1098 @@
 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("10000", this.Session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-	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.Power, this.Session)
-		case "DK": //删除关键词
-			return DeleteKeyWords(types, this.DeleteKey, this.UserId, this.Power, this.Session)
-		case "SC": //保存/修改分类
-			return AddClass(types, this.ClassifyIndex, this.ClassifyName, this.UserId, this.Power, this.Session)
-		case "DC": //删除分类
-			return DeleteClass(types, this.ClassifyIndex, this.UserId, this.Power, this.Session)
-		case "directSubKWS": //搜索列表直接订阅关键词
-			return directSubKWS(types, this.KeyWordName, this.UserId, this.Power, 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("10000", this.Session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        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(updateItems string, keys string, session *httpsession.Session) map[string]interface{} {
-	userId := qutil.ObjToString(session.Get("userId"))
-	data, ok := db.Mgo.FindById("user", userId, fmt.Sprintf(`{"%s":1}`, updateItems))
-	var repleat = false
-	var kwsCount = 0
-	if len([]rune(keys)) > 20 {
-		keys = qutil.SubString(keys, 0, 20)
-	}
-	flag := "n"
-	if ok && data != nil && len(*data) > 0 && keys != "" {
-		updateObj, _ := (*data)[updateItems].(map[string]interface{})
-		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 := db.Mgo.UpdateById("user", userId, bson.M{"$set": bson.M{
-				fmt.Sprintf("%s.a_key", updateItems): bson.A{
-					bson.M{
-						"key":        bson.A{keys},
-						"appendkey":  bson.A{},
-						"notkey":     bson.A{},
-						"updatetime": time.Now().Unix(),
-					},
-				},
-				updateItems + ".l_modifydate": time.Now().Unix(),
-				// updateItems + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
-			},
-			}); 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 := db.Mgo.UpdateById("user", userId, bson.M{
-					"$push": bson.M{
-						updateItems + ".a_key": bson.M{
-							"$each": a_key,
-						},
-					},
-					"$set": bson.M{
-						updateItems + ".l_modifydate": time.Now().Unix(),
-						updateItems + ".s_item":       classify_name,
-						// updateItems + ".i_newfree":    1, //老免费用户=>新订阅设置页面 20211122
-					},
-				})
-				if ok {
-					flag = "y"
-				}
-			}
-		}
-	}
-	if flag == "y" {
-		//清楚缓存
-		jy.ClearBigVipUserPower(userId)
-	}
-	return map[string]interface{}{"flag": flag}
+func directSubKWSFree(types string, keys string, session *httpsession.Session) map[string]interface{} {
+        userId := qutil.ObjToString(session.Get("userId"))
+        //data, ok := db.Mgo.FindById("user", userId, fmt.Sprintf(`{"%s":1}`, types))
+        data := jy.GetSubScribeInfo(session, db.Mgo, "f", "10000")
+        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"
+        if data != nil && len(*data) > 0 && keys != "" {
+                updateObj, _ := (*data)[types].(map[string]interface{})
+                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}
 }
 
 //免费用户删除关键词
 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, ok := db.Mgo.FindById("user", userId, `{"`+types+`":1}`)
-		if data != nil && ok && 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 = db.Mgo.UpdateById("user", userId, map[string]interface{}{
-			"$set": saveData,
-		})
-		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 {
+                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": ""}
 }
 
 //免费用户修改 保存关键词
 func AddKeyWordsFree(types, userId, classIndex, className, keywordsIndex, keywordName, keywordCount string, notKeyword, appendKeyword []string, matchWay int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	data, ok := db.Mgo.FindById("user", userId, `{"`+types+`":1}`)
-	saveData := map[string]interface{}{}
-	if ok && data != nil && len(*data) > 0 {
-		a_items := make([]interface{}, 0)
-		ojy, _ := (*data)[types].(map[string]interface{})
-		a_key, errs := ojy["a_key"].([]interface{})
-		if !errs {
-			db.Mgo.UpdateById("user", 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 {
-		if db.Mgo.UpdateById("user", userId, map[string]interface{}{
-			"$set": saveData,
-		}) {
-			flag = true
-			//清楚缓存
-			jy.ClearBigVipUserPower(userId)
-		}
-		SetLog(userId, types, 0, session)
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+        flag := true
+        //data, ok := db.Mgo.FindById("user", userId, `{"`+types+`":1}`)
+        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": ""}
 }
 
 //保存/修改关键词
-func AddKeyWords(types, userId, classIndex, className, keywordsIndex, keywordName, keywordCount string, notKeyword, appendKeyword []string, matchWay int, power int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	if power != 1 {
-		//个人版
-		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, power, 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, power, 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": ""}
 }
 
 //删除关键词可以批量
-func DeleteKeyWords(types, deletekey, userId string, power int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	if power != 1 {
-		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, power, 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": ""}
 }
 
 //删除分类【可以批量删除】
-func DeleteClass(types, classIndex, userId string, power int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	if power != 1 {
-		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, power, 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 != 1 {
+                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": ""}
 }
 
 //创建分类名
-func AddClass(types, classIndex, className, userId string, power int, session *httpsession.Session) map[string]interface{} {
-	flag := true
-	if power != 1 {
-		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, power, 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": ""}
 
 }
 
 //关键词判重
 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 //其它采购单位
-	Power           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("10000", this.Session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-	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.Power == 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 this.Power == 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, this.Power, 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, this.Power, this.Session)
-
-		}
-
-	}
-	return map[string]interface{}{"flag": flag, "msg": ""}
+        power := jy.GetBigVipUserBaseMsg("10000", this.Session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        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": ""}
 }
 
 //
 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, power int, session *httpsession.Session) map[string]interface{} {
-	flag := "n"
-	if power != 1 {
-		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}
+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}
 }
 
 //订阅设置记录
-func SetLog(userid, types string, power int, 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)
-		}
-	}
+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)
+                }
+        }
 }

+ 524 - 539
src/jfw/modules/publicapply/src/subscribePush/entity/setting.go

@@ -1,611 +1,596 @@
 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
-	power := 0
-	if typ == "m" {
-		infoCount := db.Mysql.CountBySql("select  count(id) from  entniche_wait_empower where  ent_id=? and  end_time>NOW() and  product_type like '%大会员%' ", this.EntId)
-		if infoCount > 0 {
-			power = 1
-		}
-		return memberSet(area, industry, userId, power, this.Session)
-	} else if typ == "v" {
-		infoCount := db.Mysql.CountBySql("select  count(id) from  entniche_wait_empower where  ent_id=? and  end_time>NOW() and  product_type like '%VIP订阅%' ", this.EntId)
-		if infoCount > 0 {
-			power = 1
-		}
-		return vipSet(area, industry, userId, power, 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)
-	//购买省份订阅包 已调整地区次数
-	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}
+                }
+        }
+        //清楚缓存
+        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,
+        }}
 }
 
 //免费用户地区调整
 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 := db.Mgo.UpdateById("user", userId, setMap)
+        if !updateOk {
+                return false
+        }
+        return true
 }
 
 //是否可进行地区调整
-func IsCanSet(userId string, areamap map[string]interface{}) (bool, bool, int) {
-	areacount := 0
-	myarea := []string{}
-	setarea := []string{}
-	myareamap := map[string]interface{}{}
-	mData, ok := db.Mgo.FindById("user", userId, `{"o_jy":1}`)
-	if !ok || len(*mData) == 0 || mData == nil {
-		return false, false, areacount
-	}
-	o_jy, _ := (*mData)["o_jy"].(map[string]interface{})
-	//地区是否完全一致
-	if o_jy["o_area"] != nil {
-		myareamap = *qutil.ObjToMap(o_jy["o_area"])
+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")
+        //mData, ok := db.Mgo.FindById("user", userId, `{"o_jy":1}`)
+        /*if !ok || len(*mData) == 0 || mData == nil {
+                return false, false, areacount
+        }*/
+        //o_jy, _ := (*mData)["o_jy"].(map[string]interface{})
+        //地区是否完全一致
+        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, power int, session *httpsession.Session) *FuncResult {
-	if len(industry) == 1 && industry[0] == "" {
-		industry = []string{}
-	}
-	rData, oldBuyset, isVip := GetVipDetail(userId)
-	if !isVip {
-		return &FuncResult{false, errors.New("请求异常,非vip状态"), nil}
-	}
-	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 {
-			rData = qutil.ObjToMap((*res))
-		}
-	}
-	if rData == nil || len(*rData) == 0 {
-		return &FuncResult{false, errors.New("获取信息失败"), nil}
-	}
-	newBuyset := NewBuySet(&area, industry, oldBuyset.Upgrade == 1)
+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 needUpgrade := needUpgrade(newBuyset, oldBuyset); needUpgrade {
-		log.Printf("%s 订阅内容超出套餐 %+v area:%v industry:%v", userId, oldBuyset, area, industry)
-		return &FuncResult{false, errors.New("订阅内容超出套餐"), nil}
-	}
-	if power == 1 {
-		if !VipSubChange(userId, qutil.ObjToMap((*rData)["o_entniche"]), &area, industry, power, session) {
-			return &FuncResult{false, errors.New("保存修改出错"), nil}
-		}
-	} else {
-		if !VipSubChange(userId, qutil.ObjToMap((*rData)["o_vipjy"]), &area, industry, power, 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 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}
+                }
+        }
 
-	SetLog(userId, "o_vipjy", power, 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, power int, session *httpsession.Session) *FuncResult {
-	if data := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key); data.Status <= 0 {
-		return &FuncResult{false, errors.New("请求异常,非大会员状态"), nil}
-	}
-	if len(industry) == 1 && industry[0] == "" {
-		industry = []string{}
-	}
-	if !MemberSubChange(userId, &area, industry, power, session) {
-		return &FuncResult{false, errors.New("保存修改出错"), nil}
-	}
-	SetLog(userId, "o_member_jy", power, 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("10000", session, config.Config.Etcd.Key, config.Config.Etcd.Key); 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(userId string) (*map[string]interface{}, *SubvipBuySet, bool) {
-	mData, ok := db.Mgo.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1,"l_vip_endtime":1,"l_vip_starttime":1,"isread":1}`)
-	if !ok || len(*mData) == 0 || mData == nil {
-		return nil, nil, false
-	}
-	//是否处于vip状态
-	vipStatus := qutil.IntAll((*mData)["i_vip_status"])
-	tmp := qutil.ObjToMap((*qutil.ObjToMap((*mData)["o_vipjy"]))["o_buyset"])
-
-	newCity, ok := (*tmp)["newcitys"].([]interface{})
-
-	return mData, &SubvipBuySet{
-		qutil.IntAll((*tmp)["upgrade"]),
-		qutil.IntAll((*tmp)["areacount"]),
-		util.ConfirmIntArr(newCity),
-		qutil.IntAll((*tmp)["buyerclasscount"]),
-	}, vipStatus > 0
+func GetVipDetail(session *httpsession.Session) (*map[string]interface{}, *SubvipBuySet, bool) {
+        /* mData, ok := db.Mgo.FindById("user", userId, `{"o_vipjy":1,"i_vip_status":1,"l_vip_endtime":1,"l_vip_starttime":1,"isread":1}`)
+           if !ok || len(*mData) == 0 || mData == nil {
+                   return nil, nil, false
+           }*/
+        data := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        //是否处于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, power int, session *httpsession.Session) bool {
-	updateOk := false
-	if power == 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
+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
 }
 
 //超级订阅 订阅修改
-func MemberSubChange(userId string, areaNew *map[string]interface{}, industryNew []string, power int, session *httpsession.Session) bool {
-	if power == 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
-		}
-	}
+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
+                }
+        }
 
-	return true
+        return true
 }

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

@@ -1,39 +1,40 @@
 package entity
 
 import (
-	"jy/src/jfw/modules/publicapply/src/db"
-	"encoding/json"
-	"fmt"
-	"log"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
-	"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/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"
 )
 
 /*某组关键词-推送结果预览总数
@@ -42,38 +43,38 @@ const (
  *@param notkey 排除词
  *@param matchway 0:精准 1:模糊
  */
-func KeysetViewDatasCount(userId, vType, key, notkey string, matchway int) 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)
-	}
+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,
-			})
-		}
-	}
-	sql.Keyword = viewKeyWords
-	qstr := GetVIPViewSql(userId, sql)
-	return elastic.Count(INDEX, TYPE, qstr)
+        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)
 }
 
 /*推送结果预览总数
@@ -81,335 +82,330 @@ func KeysetViewDatasCount(userId, vType, key, notkey string, matchway int) int64
  *@param item 分类名称
  *@param index 关键词在分类下的索引位置
  */
-func SubViewDatasCount(userId, vType, item string, index int) int64 {
-	sql := GetSqlObjFromId(userId, vType, item, index)
-	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(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(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) *ViewCondition {
-	var (
-		query *map[string]interface{}
-		ok    bool
-	)
-	if query, ok = db.Mgo.FindById("user", _id, `{"o_vipjy":1,"o_member_jy":1}`); !ok {
-		return nil
-	}
-	o_vipjy := map[string]interface{}{}
-	if vType == jy.MemberFlag {
-		o_vipjy, _ = (*query)["o_member_jy"].(map[string]interface{})
-	} else {
-		o_vipjy, _ = (*query)["o_vipjy"].(map[string]interface{})
-	}
-	a_items, _ := o_vipjy["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 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"])),
+        }
 }
 
 //
 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
-	} else {
-		arr = cityArr
-	}
-	return
+        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
+        } else {
+                arr = cityArr
+        }
+        return
 }
 
 //关键词 附加词 排除词
 func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
-	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
-		}
-		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)
-			}
-		}
-	}
-	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
+                }
+                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)
+                        }
+                }
+        }
+        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{}
+                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{})
 
-	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
-	}
-	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
-		}
-		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)
-			}
-		}
-	}
-	return
+        if a_items == nil || len(a_items) == 0 {
+                return
+        }
+        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
+                }
+                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)
+                        }
+                }
+        }
+        return
 }

+ 306 - 306
src/jfw/modules/publicapply/src/subscribePush/service/pushList.go

@@ -1,307 +1,307 @@
 package service
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/publicapply/src/config"
-	"jy/src/jfw/modules/publicapply/src/db"
-	"jy/src/jfw/modules/publicapply/src/me"
-	"jy/src/jfw/modules/publicapply/src/subscribePush/entity"
-	"log"
-	"time"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/publicapply/src/config"
+        "jy/src/jfw/modules/publicapply/src/db"
+        "jy/src/jfw/modules/publicapply/src/me"
+        "jy/src/jfw/modules/publicapply/src/subscribePush/entity"
+        "log"
+        "time"
 
-	. "app.yhyue.com/moapp/jybase/api"
-	util "app.yhyue.com/moapp/jybase/common"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        . "app.yhyue.com/moapp/jybase/api"
+        util "app.yhyue.com/moapp/jybase/common"
+        "app.yhyue.com/moapp/jybase/encrypt"
+        "app.yhyue.com/moapp/jybase/redis"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type SubscribePush struct {
-	*xweb.Action
-	hasPushHistory  xweb.Mapper `xweb:"/subscribe/historyPush"`         //推送历史查询
-	historyPaging   xweb.Mapper `xweb:"/subscribe/historyPaging"`       //推送历史翻页
-	setRead         xweb.Mapper `xweb:"/subscribe/setRead"`             //推送记录已读
-	keywordUpdate   xweb.Mapper `xweb:"/subscribe/keywordUpdate"`       //订阅词修改
-	pushSetting     xweb.Mapper `xweb:"/subscribe/pushSetting"`         //推送设置
-	vipSwitch       xweb.Mapper `xweb:"/subscribe/vipSwitch"`           //大会员、超级订阅切换
-	getPushCount    xweb.Mapper `xweb:"/subscribe/keyset/getPushCount"` //近3个月匹配数量【某组关键词】
-	getPushAllCount xweb.Mapper `xweb:"/subscribe/getPushAllCount"`     //全部关键词-推送结果预览总数
+        *xweb.Action
+        hasPushHistory  xweb.Mapper `xweb:"/subscribe/historyPush"`         //推送历史查询
+        historyPaging   xweb.Mapper `xweb:"/subscribe/historyPaging"`       //推送历史翻页
+        setRead         xweb.Mapper `xweb:"/subscribe/setRead"`             //推送记录已读
+        keywordUpdate   xweb.Mapper `xweb:"/subscribe/keywordUpdate"`       //订阅词修改
+        pushSetting     xweb.Mapper `xweb:"/subscribe/pushSetting"`         //推送设置
+        vipSwitch       xweb.Mapper `xweb:"/subscribe/vipSwitch"`           //大会员、超级订阅切换
+        getPushCount    xweb.Mapper `xweb:"/subscribe/keyset/getPushCount"` //近3个月匹配数量【某组关键词】
+        getPushAllCount xweb.Mapper `xweb:"/subscribe/getPushAllCount"`     //全部关键词-推送结果预览总数
 }
 
 // VipSwitch 大会员、超级订阅、商机管理切换
 func (sp *SubscribePush) VipSwitch() {
-	userId, _ := sp.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		if userId == "" {
-			return nil, fmt.Errorf("未登录")
-		}
-		switchOk := false
-		vt := sp.GetString("vt")
-		if vt == "" {
-			vt = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
-		} else if vt == jy.SubVipFlag {
-			vipMsg := jy.GetBigVipUserBaseMsg("10000", sp.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-			if vipMsg.VipStatus <= 0 {
-				return nil, fmt.Errorf("未购买超级订阅")
-			}
-			sp.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Vip)
-			switchOk = true
-		} else if vt == jy.MemberFlag {
-			vipMsg := jy.GetBigVipUserBaseMsg("10000", sp.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-			if vipMsg.Status <= 0 {
-				return nil, fmt.Errorf("未购买大会员")
-			}
-			sp.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Member)
-			switchOk = true
-		} else if vt == jy.EntnicheFlag {
-			vipMsg := jy.GetEntnicheState(userId, db.Mysql, db.Mgo)
-			if vipMsg.EntnicheStatus <= 0 {
-				return nil, fmt.Errorf("未购买商机管理")
-			}
-			sp.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Entniche)
-			switchOk = true
-		} else {
-			return nil, fmt.Errorf("未知请求")
-		}
-		return map[string]interface{}{
-			"vt":   util.ObjToString(sp.GetSession(jy.SwitchService.SessionKey)),
-			"flag": switchOk,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s SubscribePush VipSwitch异常:%s\n", userId, errMsg.Error())
-	}
-	sp.ServeJson(NewResult(rData, errMsg))
+        userId, _ := sp.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                if userId == "" {
+                        return nil, fmt.Errorf("未登录")
+                }
+                switchOk := false
+                vt := sp.GetString("vt")
+                if vt == "" {
+                        vt = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
+                } else if vt == jy.SubVipFlag {
+                        vipMsg := jy.GetBigVipUserBaseMsg("10000", sp.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                        if vipMsg.VipStatus <= 0 {
+                                return nil, fmt.Errorf("未购买超级订阅")
+                        }
+                        sp.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Vip)
+                        switchOk = true
+                } else if vt == jy.MemberFlag {
+                        vipMsg := jy.GetBigVipUserBaseMsg("10000", sp.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                        if vipMsg.Status <= 0 {
+                                return nil, fmt.Errorf("未购买大会员")
+                        }
+                        sp.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Member)
+                        switchOk = true
+                } else if vt == jy.EntnicheFlag {
+                        vipMsg := jy.GetEntnicheState(userId, db.Mysql, db.Mgo)
+                        if vipMsg.EntnicheStatus <= 0 {
+                                return nil, fmt.Errorf("未购买商机管理")
+                        }
+                        sp.SetSession(jy.SwitchService.SessionKey, jy.SwitchService.Entniche)
+                        switchOk = true
+                } else {
+                        return nil, fmt.Errorf("未知请求")
+                }
+                return map[string]interface{}{
+                        "vt":   util.ObjToString(sp.GetSession(jy.SwitchService.SessionKey)),
+                        "flag": switchOk,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s SubscribePush VipSwitch异常:%s\n", userId, errMsg.Error())
+        }
+        sp.ServeJson(NewResult(rData, errMsg))
 }
 
 // HasPushHistory 大会员、超级订阅,商机管理推送历史 (原wx推送更改)
 func (sp *SubscribePush) HasPushHistory() {
-	userId := util.ObjToString(sp.GetSession("userId"))
-	if userId == "" {
-		return
-	}
-	_userId := userId
-	vipType := sp.GetString("vt")
-	if vipType == "" { //默认取已切换的企业
-		vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
-	}
-	if vipType == jy.SwitchService.Entniche {
-		userId = fmt.Sprint(util.IntAll(sp.GetSession("entUserId")))
-	}
-	//entId := util.IntAll(sp.GetSession("entId"))
-	go entity.HistoryPush.UpdateUserPushUnread(userId, vipType)
-	user, _ := jy.NewSubscribePush().UserInfo(db.Mgo, userId)
-	hasKeyFlag, industry_ := me.GetKeySet(vipType, user, []string{})
-	var isVipFlag, isPassCount, isread, otherFlag bool = false, false, false, false
-	isExpire, isOnTail := -1, 0
-	todayNum := time.Unix(time.Now().Unix(), 1).Format("20060102")
-	if user != nil {
-		//超级订阅
-		if util.IntAll((*user)["i_vip_status"]) == 1 || util.IntAll((*user)["i_vip_status"]) == 2 {
-			var threeRemind = int64(3 * 24 * 60 * 60)
-			var twoRemind = int64(2 * 24 * 60 * 60)
-			var oneRemind = int64(1 * 24 * 60 * 60)
-			if (*user)["isread"] != nil {
-				isread = (*user)["isread"].(bool)
-			}
-			isVipFlag = true
-			isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+todayNum+"_"+userId) >= 2000
-			isOnTail = util.IntAll((*user)["i_vip_status"])
-			_endtime := (*user)["l_vip_endtime"]
-			//是否到期
-			if util.Int64All(_endtime)-time.Now().Unix() < threeRemind && util.Int64All(_endtime)-time.Now().Unix() >= twoRemind {
-				isExpire = 3 //即将到期
-			} else if util.Int64All(_endtime)-time.Now().Unix() < twoRemind && util.Int64All(_endtime)-time.Now().Unix() >= oneRemind {
-				isExpire = 2 //即将到期
-			} else if util.Int64All(_endtime)-time.Now().Unix() < oneRemind && util.Int64All(_endtime)-time.Now().Unix() >= 0 {
-				isExpire = 1 //即将到期
-			}
-			//判断首次用户是否推送的带有”其他“
-			t, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local)
-			today_1 := t.Unix()
-			today_2 := t.AddDate(0, 0, 1).Unix()
-			if db.MysqlPush.CountBySql("select count(1) as count from pushsubscribe where isvip =1 and userid =? and buyerclass=?  and (date between ? and ? )", userId, 93, today_1, today_2) > 0 {
-				otherFlag = true
-			}
-		} else {
-			if (*user)["i_vip_status"] == nil {
-				isExpire = 0
-			} else {
-				isOnTail = util.IntAll((*user)["i_vip_status"])
-			}
-			isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+todayNum+"_"+userId) >= 150
-		}
-	}
-	//推送记录查询
-	/*pageNum, _ := sp.GetInteger("pageNum")
-	  spqp := &jy.SubPushQueryParam{
-	  	Mgo_bidding:   db.Mgo_Bidding,
-	  	Bidding:       db.DbConf.Mongodb.Bidding.Collection,
-	  	Bidding_back:  db.DbConf.Mongodb.Bidding.Collection_change,
-	  	UserId:        userId,
-	  	EntId:         entId,
-	  	PageNum:       pageNum,
-	  	SelectTime:    sp.GetString("selectTime"),
-	  	Area:          sp.GetString("area"),
-	  	City:          sp.GetString("city"),
-	  	Buyerclass:    sp.GetString("buyerclass"),
-	  	Subtype:       sp.GetString("subtype"),
-	  	Subscopeclass: sp.GetString("subscopeclass"),
-	  	Key:           sp.GetString("key"),
-	  	Price:         sp.GetString("price"),      //价格
-	  	FileExists:    sp.GetString("fileExists"), //附件
-	  }
-	  if vipType == jy.SwitchService.Member {
-	  	spqp.PushMysql = db.MysqlMemberPush
-	  } else if vipType == jy.SwitchService.Entniche {
-	  	spqp.PushMysql = db.MysqlEntnichePush
-	  } else {
-	  	spqp.PushMysql = db.MysqlPush
-	  }
-	  hasNextPage, _, list := jy.NewSubscribePush(vipType).Datas(spqp)
-	  //免费用户无推送记录生成推送记录=>默认推送调整-付费用户默认1000条 免费不变
-	  if spqp.PageNum <= 1 && len(list) == 0 && spqp.IsEmpty() {
-	  	//flag, data := jy.NewSubscribePush().MakeHistoryDatas(db.Mgo, db.MysqlPush, userId, entity.PushView)
-	  	flag, data, _ := jy.NewSubscribePush(vipType).MakeHistoryDatasNew(spqp.PushMysql, userId, entId, entity.DefaultPushList)
-	  	if data != nil {
-	  		hasNextPage = flag
-	  		jsonBytes, err := json.Marshal(data)
-	  		err = json.Unmarshal(jsonBytes, &list)
-	  		if err != nil {
-	  			log.Println("err:", err)
-	  		}
-	  	}
-	  }
-	  //查询是否收藏
-	  jy.NewSubscribePush().MakeCollection(_userId, db.Mysql, list, config.Config.FileSignBool)
-	  //仅表格第一页展示全部字段
-	  if !(sp.GetString("format") == "table" && pageNum == 1) && len(list) > 0 {
-	  	for i := 0; i < len(list); i++ {
-	  		list[i].S_winner = ""
-	  		list[i].ProjectName = ""
-	  		list[i].Buyer = ""
-	  		list[i].Bidopentime = -1
-	  	}
-	  }*/
-	sp.ServeJson(map[string]interface{}{
-		"userId":      encrypt.EncodeArticleId(_userId),        //用户id
-		"haskey":      hasKeyFlag,                              //免费用户和超级订阅是否有订阅词
-		"isInTSguide": entity.HistoryPush.IsInTsGuide(_userId), //是否进入向导
-		"isVipSub":    isVipFlag,                               //是否是超级订阅
-		"isExpire":    isExpire,                                //超级订阅到期提醒
-		"isOnTail":    isOnTail,                                //超级订阅状态
-		"isPassCount": isPassCount,                             //推送数量校验
-		"otherFlag":   otherFlag,                               //首次用户推送查询“其他”
-		"isread":      isread,                                  //某个通知??是否已读
-		//"data":        list,                                    //推送记录字段 *适配大会员
-		//"hasNextPage": hasNextPage,                             //是否有下一页 *适配大会员
-		"industry": industry_, //会员订阅的行业
-	})
+        userId := util.ObjToString(sp.GetSession("userId"))
+        if userId == "" {
+                return
+        }
+        _userId := userId
+        vipType := sp.GetString("vt")
+        if vipType == "" { //默认取已切换的企业
+                vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
+        }
+        if vipType == jy.SwitchService.Entniche {
+                userId = fmt.Sprint(util.IntAll(sp.GetSession("entUserId")))
+        }
+        //entId := util.IntAll(sp.GetSession("entId"))
+        go entity.HistoryPush.UpdateUserPushUnread(userId, vipType)
+        user, _ := jy.NewSubscribePush().UserInfo(db.Mgo, userId)
+        hasKeyFlag, industry_ := me.GetKeySet(vipType, sp.Session())
+        var isVipFlag, isPassCount, isread, otherFlag bool = false, false, false, false
+        isExpire, isOnTail := -1, 0
+        todayNum := time.Unix(time.Now().Unix(), 1).Format("20060102")
+        if user != nil {
+                //超级订阅
+                if util.IntAll((*user)["i_vip_status"]) == 1 || util.IntAll((*user)["i_vip_status"]) == 2 {
+                        var threeRemind = int64(3 * 24 * 60 * 60)
+                        var twoRemind = int64(2 * 24 * 60 * 60)
+                        var oneRemind = int64(1 * 24 * 60 * 60)
+                        if (*user)["isread"] != nil {
+                                isread = (*user)["isread"].(bool)
+                        }
+                        isVipFlag = true
+                        isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+todayNum+"_"+userId) >= 2000
+                        isOnTail = util.IntAll((*user)["i_vip_status"])
+                        _endtime := (*user)["l_vip_endtime"]
+                        //是否到期
+                        if util.Int64All(_endtime)-time.Now().Unix() < threeRemind && util.Int64All(_endtime)-time.Now().Unix() >= twoRemind {
+                                isExpire = 3 //即将到期
+                        } else if util.Int64All(_endtime)-time.Now().Unix() < twoRemind && util.Int64All(_endtime)-time.Now().Unix() >= oneRemind {
+                                isExpire = 2 //即将到期
+                        } else if util.Int64All(_endtime)-time.Now().Unix() < oneRemind && util.Int64All(_endtime)-time.Now().Unix() >= 0 {
+                                isExpire = 1 //即将到期
+                        }
+                        //判断首次用户是否推送的带有”其他“
+                        t, _ := time.ParseInLocation("2006-01-02", time.Now().Format("2006-01-02"), time.Local)
+                        today_1 := t.Unix()
+                        today_2 := t.AddDate(0, 0, 1).Unix()
+                        if db.MysqlPush.CountBySql("select count(1) as count from pushsubscribe where isvip =1 and userid =? and buyerclass=?  and (date between ? and ? )", userId, 93, today_1, today_2) > 0 {
+                                otherFlag = true
+                        }
+                } else {
+                        if (*user)["i_vip_status"] == nil {
+                                isExpire = 0
+                        } else {
+                                isOnTail = util.IntAll((*user)["i_vip_status"])
+                        }
+                        isPassCount = redis.GetInt("pushcache_2_a", "oncecount_"+todayNum+"_"+userId) >= 150
+                }
+        }
+        //推送记录查询
+        /*pageNum, _ := sp.GetInteger("pageNum")
+          spqp := &jy.SubPushQueryParam{
+          	Mgo_bidding:   db.Mgo_Bidding,
+          	Bidding:       db.DbConf.Mongodb.Bidding.Collection,
+          	Bidding_back:  db.DbConf.Mongodb.Bidding.Collection_change,
+          	UserId:        userId,
+          	EntId:         entId,
+          	PageNum:       pageNum,
+          	SelectTime:    sp.GetString("selectTime"),
+          	Area:          sp.GetString("area"),
+          	City:          sp.GetString("city"),
+          	Buyerclass:    sp.GetString("buyerclass"),
+          	Subtype:       sp.GetString("subtype"),
+          	Subscopeclass: sp.GetString("subscopeclass"),
+          	Key:           sp.GetString("key"),
+          	Price:         sp.GetString("price"),      //价格
+          	FileExists:    sp.GetString("fileExists"), //附件
+          }
+          if vipType == jy.SwitchService.Member {
+          	spqp.PushMysql = db.MysqlMemberPush
+          } else if vipType == jy.SwitchService.Entniche {
+          	spqp.PushMysql = db.MysqlEntnichePush
+          } else {
+          	spqp.PushMysql = db.MysqlPush
+          }
+          hasNextPage, _, list := jy.NewSubscribePush(vipType).Datas(spqp)
+          //免费用户无推送记录生成推送记录=>默认推送调整-付费用户默认1000条 免费不变
+          if spqp.PageNum <= 1 && len(list) == 0 && spqp.IsEmpty() {
+          	//flag, data := jy.NewSubscribePush().MakeHistoryDatas(db.Mgo, db.MysqlPush, userId, entity.PushView)
+          	flag, data, _ := jy.NewSubscribePush(vipType).MakeHistoryDatasNew(spqp.PushMysql, userId, entId, entity.DefaultPushList)
+          	if data != nil {
+          		hasNextPage = flag
+          		jsonBytes, err := json.Marshal(data)
+          		err = json.Unmarshal(jsonBytes, &list)
+          		if err != nil {
+          			log.Println("err:", err)
+          		}
+          	}
+          }
+          //查询是否收藏
+          jy.NewSubscribePush().MakeCollection(_userId, db.Mysql, list, config.Config.FileSignBool)
+          //仅表格第一页展示全部字段
+          if !(sp.GetString("format") == "table" && pageNum == 1) && len(list) > 0 {
+          	for i := 0; i < len(list); i++ {
+          		list[i].S_winner = ""
+          		list[i].ProjectName = ""
+          		list[i].Buyer = ""
+          		list[i].Bidopentime = -1
+          	}
+          }*/
+        sp.ServeJson(map[string]interface{}{
+                "userId":      encrypt.EncodeArticleId(_userId),             //用户id
+                "haskey":      hasKeyFlag,                                   //免费用户和超级订阅是否有订阅词
+                "isInTSguide": entity.HistoryPush.IsInTsGuide(sp.Session()), //是否进入向导
+                "isVipSub":    isVipFlag,                                    //是否是超级订阅
+                "isExpire":    isExpire,                                     //超级订阅到期提醒
+                "isOnTail":    isOnTail,                                     //超级订阅状态
+                "isPassCount": isPassCount,                                  //推送数量校验
+                "otherFlag":   otherFlag,                                    //首次用户推送查询“其他”
+                "isread":      isread,                                       //某个通知??是否已读
+                //"data":        list,                                    //推送记录字段 *适配大会员
+                //"hasNextPage": hasNextPage,                             //是否有下一页 *适配大会员
+                "industry": industry_, //会员订阅的行业
+        })
 }
 
 // HistoryPaging 推送历史翻页
 func (sp *SubscribePush) HistoryPaging() {
-	userId, _ := sp.GetSession("userId").(string)
-	if userId == "" {
-		return
-	}
-	vipType := sp.GetString("vt")
-	if vipType == "" { //默认取已切换的企业
-		vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
-	}
-	if vipType == jy.SwitchService.Entniche {
-		userId = fmt.Sprint(util.IntAll(sp.GetSession("entUserId")))
-	}
-	entId := util.IntAll(sp.GetSession("entId"))
-	pageNum, _ := sp.GetInteger("pageNum")
-	PageSize, _ := sp.GetInteger("pageSize")
-	if pageNum == 1 {
-		go entity.HistoryPush.UpdateUserPushUnread(userId, vipType)
-	}
-	spqp := &jy.SubPushQueryParam{
-		Mgo_bidding:   db.Mgo_Bidding,
-		Bidding:       db.DbConf.Mongodb.Bidding.Collection,
-		Bidding_back:  db.DbConf.Mongodb.Bidding.Collection_change,
-		UserId:        userId,
-		PageNum:       pageNum,
-		PageSize:      PageSize,
-		SelectTime:    sp.GetString("selectTime"),
-		Area:          sp.GetString("area"),
-		City:          sp.GetString("city"),
-		Buyerclass:    sp.GetString("buyerclass"),
-		Subtype:       sp.GetString("subtype"),
-		Subscopeclass: sp.GetString("subscopeclass"),
-		Key:           sp.GetString("key"),
-		Price:         sp.GetString("price"),
-		FileExists:    sp.GetString("fileExists"),
-	}
-	if vipType == jy.SwitchService.Member {
-		spqp.PushMysql = db.MysqlMemberPush
-	} else if vipType == jy.SwitchService.Entniche {
-		spqp.PushMysql = db.MysqlEntnichePush
-	} else {
-		spqp.PushMysql = db.MysqlPush
-	}
-	hasNextPage, total, list := jy.NewSubscribePush(vipType).Datas(spqp)
-	//免费用户无推送记录生成推送记录=>默认推送调整-付费用户默认1000条 免费不变
-	if spqp.PageNum <= 1 && len(list) == 0 && spqp.IsEmpty() {
-		flag, data, count := jy.NewSubscribePush(vipType).MakeHistoryDatasNew(spqp.PushMysql, userId, entId, entity.DefaultPushList)
-		if data != nil {
-			hasNextPage = flag
-			total = int64(count)
-			jsonBytes, err := json.Marshal(data)
-			err = json.Unmarshal(jsonBytes, &list)
-			if err != nil {
-				log.Println("err:", err)
-			}
-		}
-	}
-	//查询是否收藏
-	jy.NewSubscribePush().MakeCollection(userId, db.Mysql, list, config.Config.FileSignBool)
-	//是否有关键词
-	user, _ := jy.NewSubscribePush(vipType).UserInfo(db.Mgo, userId)
-	hasKeyFlag, _ := me.GetKeySet(vipType, user, []string{})
-	//仅表格第一页展示全部字段
-	if !(sp.GetString("format") == "table" && pageNum == 1 && PageSize <= 20) && len(list) > 0 {
-		for i := 0; i < len(list); i++ {
-			list[i].Winner = ""
-			list[i].ProjectName = ""
-			list[i].Buyer = ""
-			list[i].BidOpenTime = -1
-		}
-	}
-	sp.ServeJson(map[string]interface{}{
-		"hasNextPage": hasNextPage,
-		"total":       total,
-		"data":        list,
-		"haskey":      hasKeyFlag,
-	})
+        userId, _ := sp.GetSession("userId").(string)
+        if userId == "" {
+                return
+        }
+        vipType := sp.GetString("vt")
+        if vipType == "" { //默认取已切换的企业
+                vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
+        }
+        if vipType == jy.SwitchService.Entniche {
+                userId = fmt.Sprint(util.IntAll(sp.GetSession("entUserId")))
+        }
+        entId := util.IntAll(sp.GetSession("entId"))
+        pageNum, _ := sp.GetInteger("pageNum")
+        PageSize, _ := sp.GetInteger("pageSize")
+        if pageNum == 1 {
+                go entity.HistoryPush.UpdateUserPushUnread(userId, vipType)
+        }
+        spqp := &jy.SubPushQueryParam{
+                Mgo_bidding:   db.Mgo_Bidding,
+                Bidding:       db.DbConf.Mongodb.Bidding.Collection,
+                Bidding_back:  db.DbConf.Mongodb.Bidding.Collection_change,
+                UserId:        userId,
+                PageNum:       pageNum,
+                PageSize:      PageSize,
+                SelectTime:    sp.GetString("selectTime"),
+                Area:          sp.GetString("area"),
+                City:          sp.GetString("city"),
+                Buyerclass:    sp.GetString("buyerclass"),
+                Subtype:       sp.GetString("subtype"),
+                Subscopeclass: sp.GetString("subscopeclass"),
+                Key:           sp.GetString("key"),
+                Price:         sp.GetString("price"),
+                FileExists:    sp.GetString("fileExists"),
+        }
+        if vipType == jy.SwitchService.Member {
+                spqp.PushMysql = db.MysqlMemberPush
+        } else if vipType == jy.SwitchService.Entniche {
+                spqp.PushMysql = db.MysqlEntnichePush
+        } else {
+                spqp.PushMysql = db.MysqlPush
+        }
+        hasNextPage, total, list := jy.NewSubscribePush(vipType).Datas(spqp)
+        //免费用户无推送记录生成推送记录=>默认推送调整-付费用户默认1000条 免费不变
+        if spqp.PageNum <= 1 && len(list) == 0 && spqp.IsEmpty() {
+                flag, data, count := jy.NewSubscribePush(vipType).MakeHistoryDatasNew(spqp.PushMysql, userId, entId, entity.DefaultPushList)
+                if data != nil {
+                        hasNextPage = flag
+                        total = int64(count)
+                        jsonBytes, err := json.Marshal(data)
+                        err = json.Unmarshal(jsonBytes, &list)
+                        if err != nil {
+                                log.Println("err:", err)
+                        }
+                }
+        }
+        //查询是否收藏
+        jy.NewSubscribePush().MakeCollection(userId, db.Mysql, list, config.Config.FileSignBool)
+        //是否有关键词
+        //user, _ := jy.NewSubscribePush(vipType).UserInfo(db.Mgo, userId)
+        hasKeyFlag, _ := me.GetKeySet(vipType, sp.Session())
+        //仅表格第一页展示全部字段
+        if !(sp.GetString("format") == "table" && pageNum == 1 && PageSize <= 20) && len(list) > 0 {
+                for i := 0; i < len(list); i++ {
+                        list[i].Winner = ""
+                        list[i].ProjectName = ""
+                        list[i].Buyer = ""
+                        list[i].BidOpenTime = -1
+                }
+        }
+        sp.ServeJson(map[string]interface{}{
+                "hasNextPage": hasNextPage,
+                "total":       total,
+                "data":        list,
+                "haskey":      hasKeyFlag,
+        })
 }
 
 // SetRead 推送记录设置已读
 func (sp *SubscribePush) SetRead() error {
-	defer util.Catch()
-	vsid, _ := sp.GetInteger("vsid")
-	if vsid <= 0 {
-		return nil
-	}
-	vipType := sp.GetString("vt")
-	if vipType == "" { //默认取已切换的企业
-		vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
-	}
-	if userId := util.ObjToString(sp.GetSession("userId")); userId != "" {
-		if vipType == jy.SwitchService.Member {
-			jy.NewSubscribePush(vipType).Visit(db.MysqlMemberPush, userId, vsid)
-		} else if vipType == jy.SwitchService.Entniche {
-			jy.NewSubscribePush(vipType).Visit(db.MysqlEntnichePush, userId, vsid)
-		} else {
-			jy.NewSubscribePush(vipType).Visit(db.MysqlPush, userId, vsid)
-		}
-	}
-	return nil
+        defer util.Catch()
+        vsid, _ := sp.GetInteger("vsid")
+        if vsid <= 0 {
+                return nil
+        }
+        vipType := sp.GetString("vt")
+        if vipType == "" { //默认取已切换的企业
+                vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
+        }
+        if userId := util.ObjToString(sp.GetSession("userId")); userId != "" {
+                if vipType == jy.SwitchService.Member {
+                        jy.NewSubscribePush(vipType).Visit(db.MysqlMemberPush, userId, vsid)
+                } else if vipType == jy.SwitchService.Entniche {
+                        jy.NewSubscribePush(vipType).Visit(db.MysqlEntnichePush, userId, vsid)
+                } else {
+                        jy.NewSubscribePush(vipType).Visit(db.MysqlPush, userId, vsid)
+                }
+        }
+        return nil
 }
 
 // KeywordUpdate 大会员、超级订阅订阅词修改
@@ -316,35 +316,35 @@ func (sp *SubscribePush) PushSetting() {
 
 // GetPushCount 订阅设置订阅词近三个月推送数量
 func (sp *SubscribePush) GetPushCount() error {
-	defer util.Catch()
-	userId, _ := sp.GetSession("userId").(string)
-	if userId != "" {
-		vipType := sp.GetString("vt")
-		if vipType == "" { //默认取已切换的企业
-			vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
+        defer util.Catch()
+        userId, _ := sp.GetSession("userId").(string)
+        if userId != "" {
+                vipType := sp.GetString("vt")
+                if vipType == "" { //默认取已切换的企业
+                        vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
 
-		}
-		matchway, _ := sp.GetInteger("matchway")
-		sp.ServeJson(map[string]interface{}{
-			"count": entity.KeysetViewDatasCount(userId, vipType, sp.GetString("key"), sp.GetString("notkey"), matchway),
-		})
-	}
-	return nil
+                }
+                matchway, _ := sp.GetInteger("matchway")
+                sp.ServeJson(map[string]interface{}{
+                        "count": entity.KeysetViewDatasCount(userId, vipType, sp.GetString("key"), sp.GetString("notkey"), matchway,sp.Session()),
+                })
+        }
+        return nil
 }
 
 // getPushAllCount 全部关键词-最近三个月推送结果预览总数
 func (sp *SubscribePush) GetPushAllCount() error {
-	defer util.Catch()
-	userId, _ := sp.GetSession("userId").(string)
-	if userId != "" {
-		index, _ := sp.GetInteger("index")
-		vipType := sp.GetString("vt")
-		if vipType == "" { //默认取已切换的企业
-			vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
-		}
-		sp.ServeJson(map[string]interface{}{
-			"count": entity.SubViewDatasCount(userId, vipType, sp.GetString("item"), index),
-		})
-	}
-	return nil
+        defer util.Catch()
+        userId, _ := sp.GetSession("userId").(string)
+        if userId != "" {
+                index, _ := sp.GetInteger("index")
+                vipType := sp.GetString("vt")
+                if vipType == "" { //默认取已切换的企业
+                        vipType = jy.SwitchService.GetEntniche(sp.Session(), db.Mgo, db.Mysql)
+                }
+                sp.ServeJson(map[string]interface{}{
+                        "count": entity.SubViewDatasCount(userId, vipType, sp.GetString("item"), index, sp.Session()),
+                })
+        }
+        return nil
 }

+ 0 - 1
src/jfw/modules/publicapply/src/subscribePush/service/subscribe.go

@@ -102,7 +102,6 @@ func (s *Subscribe) SetUserInfo() {
 			UserId:          userId,
 			Type:            vSwitch,
 			OtherBuyerclass: other,
-			Power:           power,
 			EntUserId:       entUserId,
 			EntId:           entId,
 			Session:         s.session,

+ 54 - 51
src/jfw/modules/subscribepay/src/active/active.go

@@ -1,71 +1,74 @@
 package active
 
 import (
-	. "app.yhyue.com/moapp/jybase/api"
-	"errors"
-	"log"
-	qutil "app.yhyue.com/moapp/jybase/common"
-	"time"
-	"jy/src/jfw/modules/subscribepay/src/util"
+        . "app.yhyue.com/moapp/jybase/api"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "errors"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "time"
 
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Active struct {
-	*xweb.Action
-	isActiving xweb.Mapper `xweb:"/(.*)/isActiving"` //活动时间
+        *xweb.Action
+        isActiving xweb.Mapper `xweb:"/(.*)/isActiving"` //活动时间
 }
 
 type activeConfig struct {
-	DoubleEleven struct {
-		Active_Start int64 `json:"active_Start"` //活动开始时间
-		Active_End   int64 `json:"active_End"`   //活动开始时间
-	}
+        DoubleEleven struct {
+                Active_Start int64 `json:"active_Start"` //活动开始时间
+                Active_End   int64 `json:"active_End"`   //活动开始时间
+        }
 }
 
 var ActiveConfig activeConfig
 
 func init() {
-	qutil.ReadConfig("./active.json", &ActiveConfig)
+        qutil.ReadConfig("./active.json", &ActiveConfig)
 }
 
 //
 func (this *Active) IsActiving(activeName string) {
-	defer qutil.Catch()
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		now := time.Now()
-		res := map[string]interface{}{}
-		if activeName == "doubleEleven" {
-			res = map[string]interface{}{
-				"isActiving": false,
-				"isWritten":  0,
-			}
-			if ActiveConfig.DoubleEleven.Active_Start < now.Unix() && ActiveConfig.DoubleEleven.Active_End > now.Unix() {
-				res["isActiving"] = true
-				if userId != "" {
-					data, ok := util.MQFW.FindById("user", userId, nil)
-					if ok && data != nil && *data != nil {
-						//已录入信息 已激活大会员赠送
-						if (*data)["i_member_give"] != nil {
-							res["isWritten"] = qutil.IntAll((*data)["i_member_give"])
-						}
-						//是否是大会员用户
-						if (*data)["i_member_status"] != nil && qutil.IntAll((*data)["i_member_status"]) > 0 {
-							res["isWritten"] = 2
-						}
-					}
-				}
-			}
-			return res, nil
-		}
-		if res == nil || len(res) == 0 {
-			return nil, errors.New("暂无活动")
-		}
-		return "", nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s   获取活动信息出错-%s", userId, errMsg)
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        defer qutil.Catch()
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                now := time.Now()
+                res := map[string]interface{}{}
+                if activeName == "doubleEleven" {
+                        res = map[string]interface{}{
+                                "isActiving": false,
+                                "isWritten":  0,
+                        }
+                        if ActiveConfig.DoubleEleven.Active_Start < now.Unix() && ActiveConfig.DoubleEleven.Active_End > now.Unix() {
+                                res["isActiving"] = true
+                                if userId != "" {
+                                        data, ok := util.MQFW.FindById("user", userId, nil)
+                                        if ok && data != nil && *data != nil {
+                                                //已录入信息 已激活大会员赠送
+                                                if (*data)["i_member_give"] != nil {
+                                                        res["isWritten"] = qutil.IntAll((*data)["i_member_give"])
+                                                }
+                                                //是否是大会员用户
+                                                vipUser := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                                                if vipUser.Status > 0 {
+                                                        res["isWritten"] = 2
+                                                }
+                                        }
+                                }
+                        }
+                        return res, nil
+                }
+                if res == nil || len(res) == 0 {
+                        return nil, errors.New("暂无活动")
+                }
+                return "", nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s   获取活动信息出错-%s", userId, errMsg)
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }

+ 254 - 207
src/jfw/modules/subscribepay/src/entity/areaPack.go

@@ -1,240 +1,287 @@
 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) int {
-	beforePrice, newPrice := 0, 0
-	data, ok := util.MQFW.FindById("user", userid, `{"o_jy":1}`)
-	if ok && 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
+func (this *AreaPackFilter) UpgradePrice(userId string, positionType, entId, entUserId int64) int {
+        beforePrice, newPrice := 0, 0
+        data, ok := &map[string]interface{}{}, false
+        if positionType == 0 {
+                data, ok = util.MQFW.FindById("user", userId, `{"o_jy":1}`)
+        } else {
+                query := map[string]interface{}{
+                        "i_userid": entUserId,
+                        "i_entid":  entId,
+                        "i_type":   1,
+                }
+                data, ok = util.MQFW.FindOne("entniche_rule", query)
+        }
+        if ok && data != nil && len(*data) > 0 {
+                ojy := &map[string]interface{}{}
+                if positionType == 0 {
+                        ojy = qutil.ObjToMap((*data)["o_jy"])
+                } else {
+                        ojy = qutil.ObjToMap((*data)["entniche_rule"])
+                }
+                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": "省份订阅包"}),
-		"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)
-			if !areaPack.Power(userId, start, end) {
-				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) bool {
-	setMap := map[string]interface{}{
-		"o_jy.o_buyset_p":  map[string]interface{}{"areacount": this.Num},
-		"o_jy.l_areaEnd_p": endtime.Unix(),
-		"o_jy.i_ppstatus":  1,
-		"o_jy.i_newfree":   1, //新免费用户=>新订阅设置页面 20211122
-	}
-	if this.OrderType == 1 || this.OrderType == 2 {
-		setMap["o_jy.l_areaStart_p"] = startime.Unix()
-		setMap["o_jy.o_area_p"] = this.Area
-	}
-	if util.MQFW.UpdateById("user", userid, map[string]interface{}{
-		"$set": setMap,
-	}) {
-		//清除 用户权限缓存
-		jy.ClearBigVipUserPower(userid)
-		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
 }
 
 // 获取产品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
 }
 
 /*
@@ -243,13 +290,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
 }

+ 179 - 165
src/jfw/modules/subscribepay/src/entity/dataReportStruct.go

@@ -1,20 +1,21 @@
 package entity
 
 import (
-	"encoding/json"
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"strconv"
-	"time"
+        "encoding/json"
+        "errors"
+        "fmt"
+        "go.mongodb.org/mongo-driver/bson/primitive"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/pay"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "strconv"
+        "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	frpc "app.yhyue.com/moapp/jybase/rpc"
-	. "bp.jydev.jianyu360.cn/BaseService/pushpkg/p"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        frpc "app.yhyue.com/moapp/jybase/rpc"
+        . "bp.jydev.jianyu360.cn/BaseService/pushpkg/p"
 )
 
 // 数据报告
@@ -23,171 +24,184 @@ type dataReportStruct struct{}
 var JyDataReportStruct dataReportStruct
 
 func (this *dataReportStruct) PayCallBack(param *CallBackParam) (update bool) {
-	orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,order_money,order_status,create_time,user_mail,user_openid,product_type,order_code,filter,dis_word,user_id", "")
-	if orderdata != nil {
-		now := time.Now()
-		order_status := qutil.IntAll((*orderdata)["order_status"])
-		if 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 {
-				//发送数据
-				str := map[string]interface{}{}
-				filterStr := qutil.ObjToString((*orderdata)["filter"])
-				if err := json.Unmarshal([]byte(filterStr), &str); err != nil {
-					log.Printf("Unmarshal 出错 [%s]\n", filterStr)
-					return false
-				}
-				orderCode := qutil.ObjToString((*orderdata)["order_code"])
-				createTime := qutil.ObjToString((*orderdata)["create_time"])
-				price := param.CashFee
-				prices := strconv.FormatFloat(float64(price)/100, 'f', -1, 64)
-				email := qutil.ObjToString(str["email"])
-				phone := qutil.ObjToString(str["phone"])
-				company := qutil.ObjToString(str["company"])
-				report_id := qutil.IntAll(str["report_id"])
-				openid := qutil.ObjToString((*orderdata)["user_openid"])
-				product_type := qutil.ObjToString((*orderdata)["product_type"])
-				report_name := qutil.ObjToString(str["report_name"])
-				go sendtemp(openid, orderCode, report_name+" "+product_type, payTime)
-				go SendDatareportMailToPayUser(report_id, prices, param.OutTradeno, email, orderCode, phone, company, createTime, payTime, config.GmailAuth)
-				/*if qutil.ObjToString((*orderdata)["dis_word"]) != "" {
-					suffix := qutil.ObjToString((*orderdata)["dis_word"])[len(qutil.ObjToString((*orderdata)["dis_word"]))-3 : len(qutil.ObjToString((*orderdata)["dis_word"]))]
-					if suffix == suffix_msgt {
-						go OtherDisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据报告", qutil.ObjToString((*orderdata)["dis_word"]), qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["create_time"]))
-					} else {
-						go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据报告", qutil.ObjToString((*orderdata)["dis_word"]))
-					}
-				}*/
-			}
-		}
-	}
-	return
+        orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,order_money,order_status,create_time,user_mail,user_openid,product_type,order_code,filter,dis_word,user_id", "")
+        if orderdata != nil {
+                now := time.Now()
+                order_status := qutil.IntAll((*orderdata)["order_status"])
+                if 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 {
+                                //发送数据
+                                str := map[string]interface{}{}
+                                filterStr := qutil.ObjToString((*orderdata)["filter"])
+                                if err := json.Unmarshal([]byte(filterStr), &str); err != nil {
+                                        log.Printf("Unmarshal 出错 [%s]\n", filterStr)
+                                        return false
+                                }
+                                orderCode := qutil.ObjToString((*orderdata)["order_code"])
+                                createTime := qutil.ObjToString((*orderdata)["create_time"])
+                                price := param.CashFee
+                                prices := strconv.FormatFloat(float64(price)/100, 'f', -1, 64)
+                                email := qutil.ObjToString(str["email"])
+                                phone := qutil.ObjToString(str["phone"])
+                                company := qutil.ObjToString(str["company"])
+                                report_id := qutil.IntAll(str["report_id"])
+                                openid := qutil.ObjToString((*orderdata)["user_openid"])
+                                product_type := qutil.ObjToString((*orderdata)["product_type"])
+                                report_name := qutil.ObjToString(str["report_name"])
+                                go sendtemp(openid, orderCode, report_name+" "+product_type, payTime)
+                                go SendDatareportMailToPayUser(report_id, prices, param.OutTradeno, email, orderCode, phone, company, createTime, payTime, config.GmailAuth)
+                                /*if qutil.ObjToString((*orderdata)["dis_word"]) != "" {
+                                	suffix := qutil.ObjToString((*orderdata)["dis_word"])[len(qutil.ObjToString((*orderdata)["dis_word"]))-3 : len(qutil.ObjToString((*orderdata)["dis_word"]))]
+                                	if suffix == suffix_msgt {
+                                		go OtherDisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据报告", qutil.ObjToString((*orderdata)["dis_word"]), qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["create_time"]))
+                                	} else {
+                                		go DisWordRecode(qutil.IntAll((*orderdata)["id"]), qutil.IntAll((*orderdata)["order_money"]), "数据报告", qutil.ObjToString((*orderdata)["dis_word"]))
+                                	}
+                                }*/
+                        }
+                }
+        }
+        return
 }
 
 // 创建订单
 func (this *dataReportStruct) NewOrder(param frpc.JyPayOrderParam) (ordercode string, err error) {
-	//插入数据库
-	now := time.Now()
-	ordercode = pay.GetOrderCode(param.Userid)
-	detailByte, marshalErr := json.Marshal(param.Detail)
-	if marshalErr != nil {
-		err = marshalErr
-		return
-	}
-	distributionChannel, _ := util.GetJyOrderChannel(qutil.ObjToString(param.Detail["disWord"]), "")
-	orderId := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-		"order_money":          param.Price,
-		"order_status":         0,
-		"user_openid":          param.Openid,
-		"order_code":           ordercode,
-		"product_type":         "数据报告",
-		"create_time":          FormatDate(&now, Date_Full_Layout),
-		"prepay_time":          FormatDate(&now, Date_Full_Layout),
-		"original_price":       param.Price,
-		"filter_id":            qutil.If(param.Detail != nil && param.Detail["report_id"] != nil, param.Detail["report_id"], ""), //课程id
-		"pay_way":              param.PayWay,
-		"user_id":              param.Userid,
-		"user_phone":           param.Detail["phone"],
-		"user_mail":            param.Detail["email"],
-		"filter":               string(detailByte),                    //订单详情
-		"dis_word":             param.Detail["disWord"],               //分销口令
-		"distribution_channel": distributionChannel,                   //销售渠道
-		"order_channel":        util.GetRpcOrderChannel(param.PayWay), //下单渠道
-		"audit_status":         3,                                     //默认审核通过
-	})
-	if orderId <= 0 {
-		err = errors.New("订单插入失败")
-		return
-	}
-	return
+        //插入数据库
+        now := time.Now()
+        ordercode = pay.GetOrderCode(param.Userid)
+        detailByte, marshalErr := json.Marshal(param.Detail)
+        if marshalErr != nil {
+                err = marshalErr
+                return
+        }
+        _, userErr := primitive.ObjectIDFromHex(param.Userid)
+        buy_subject := 1
+        entId := 0
+        if userErr != nil {
+                //雇员标识
+                positionData := util.InfoMysql.FindOne("base_position", map[string]interface{}{"id": param.Userid}, "ent_id", "")
+                if positionData != nil {
+                        entId = qutil.IntAll((*positionData)["ent_id"])
+                }
+                buy_subject = 2
+        }
+        distributionChannel, _ := util.GetJyOrderChannel(qutil.ObjToString(param.Detail["disWord"]), "")
+        orderId := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                "order_money":          param.Price,
+                "order_status":         0,
+                "user_openid":          param.Openid,
+                "order_code":           ordercode,
+                "product_type":         "数据报告",
+                "create_time":          FormatDate(&now, Date_Full_Layout),
+                "prepay_time":          FormatDate(&now, Date_Full_Layout),
+                "original_price":       param.Price,
+                "filter_id":            qutil.If(param.Detail != nil && param.Detail["report_id"] != nil, param.Detail["report_id"], ""), //课程id
+                "pay_way":              param.PayWay,
+                "user_id":              param.Userid,
+                "user_phone":           param.Detail["phone"],
+                "user_mail":            param.Detail["email"],
+                "filter":               string(detailByte),                    //订单详情
+                "dis_word":             param.Detail["disWord"],               //分销口令
+                "distribution_channel": distributionChannel,                   //销售渠道
+                "order_channel":        util.GetRpcOrderChannel(param.PayWay), //下单渠道
+                "audit_status":         3,
+                "buy_subject":          buy_subject,
+                "ent_id":               entId, //默认审核通过
+        })
+        if orderId <= 0 {
+                err = errors.New("订单插入失败")
+                return
+        }
+        return
 }
 
 // 更新订单
 func (this *dataReportStruct) FlushOrder(param frpc.JyPayOrderChangeParam) (string, error) {
-	productSign, ok := pay.PayWayAndSign["datareport"][param.PayWay]
-	if !ok || productSign == "" {
-		return "", errors.New("未知支付类型")
-	}
-	//查询订单
-	res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-		"order_code":   param.OrderCode,
-		"order_status": 0,
-	}, "order_money,out_trade_no,pay_way", "")
-	if res == nil || len(*res) == 0 {
-		return "", errors.New("未找到订单" + param.OrderCode)
-	}
-	price := qutil.IntAll((*res)["order_money"])
-	if price == 0 {
-		return "", errors.New("查询金额异常" + param.OrderCode)
-	}
-	//关闭之前交易
-	pay.CloseOrder(qutil.ObjToString((*res)["pay_way"]), qutil.ObjToString((*res)["out_trade_no"]))
+        productSign, ok := pay.PayWayAndSign["datareport"][param.PayWay]
+        if !ok || productSign == "" {
+                return "", errors.New("未知支付类型")
+        }
+        //查询订单
+        res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                "order_code":   param.OrderCode,
+                "order_status": 0,
+        }, "order_money,out_trade_no,pay_way", "")
+        if res == nil || len(*res) == 0 {
+                return "", errors.New("未找到订单" + param.OrderCode)
+        }
+        price := qutil.IntAll((*res)["order_money"])
+        if price == 0 {
+                return "", errors.New("查询金额异常" + param.OrderCode)
+        }
+        //关闭之前交易
+        pay.CloseOrder(qutil.ObjToString((*res)["pay_way"]), qutil.ObjToString((*res)["out_trade_no"]))
 
-	//创建支付串
-	tradeno, prepayid, payParam, payErr := pay.CreateOrderPay(price, productSign, param.Ip, param.Openid, param.PayWay, param.OrderCode)
-	if payErr != nil {
-		return "", payErr
-	}
-	now := time.Now()
-	if !util.Mysql.Update("dataexport_order", map[string]interface{}{
-		"order_status": 0,
-		"order_code":   param.OrderCode,
-	}, map[string]interface{}{
-		"prepay_time":  FormatDate(&now, Date_Full_Layout),
-		"prepay_id":    prepayid,
-		"code_url":     payParam,
-		"out_trade_no": tradeno,
-		"pay_way":      param.PayWay,
-	}) {
-		return "", errors.New(fmt.Sprintf("%s,%s更新数据库出错", param.OrderCode, param.PayWay))
-	}
-	return payParam, nil
+        //创建支付串
+        tradeno, prepayid, payParam, payErr := pay.CreateOrderPay(price, productSign, param.Ip, param.Openid, param.PayWay, param.OrderCode)
+        if payErr != nil {
+                return "", payErr
+        }
+        now := time.Now()
+        if !util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "order_status": 0,
+                "order_code":   param.OrderCode,
+        }, map[string]interface{}{
+                "prepay_time":  FormatDate(&now, Date_Full_Layout),
+                "prepay_id":    prepayid,
+                "code_url":     payParam,
+                "out_trade_no": tradeno,
+                "pay_way":      param.PayWay,
+        }) {
+                return "", errors.New(fmt.Sprintf("%s,%s更新数据库出错", param.OrderCode, param.PayWay))
+        }
+        return payParam, nil
 }
 
 func (this *dataReportStruct) CloseOrder(ordercode string) error {
-	err := pay.CloseOrderByOrderCode(ordercode)
-	if err != nil {
-		return err
-	}
-	if !util.Mysql.Update("dataexport_order", map[string]interface{}{
-		"order_status": 0,
-		"order_code":   ordercode,
-	}, map[string]interface{}{
-		"order_status": -2,
-	}) {
-		return errors.New(fmt.Sprintf("%s关闭订单更新数据库出错", ordercode))
-	}
-	return nil
+        err := pay.CloseOrderByOrderCode(ordercode)
+        if err != nil {
+                return err
+        }
+        if !util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "order_status": 0,
+                "order_code":   ordercode,
+        }, map[string]interface{}{
+                "order_status": -2,
+        }) {
+                return errors.New(fmt.Sprintf("%s关闭订单更新数据库出错", ordercode))
+        }
+        return nil
 }
 
 func sendtemp(openid, order_coded, product_type, pay_time string) {
-	if openid == "" || order_coded == "" || product_type == "" || pay_time == "" {
-		fmt.Println("数据报告模板参数异常")
-	} else {
-		util.DataReport_WTMCS.Reload()
-		wtmc := util.DataReport_WTMCS.Get(config.MessageConfig.WxTpl_DataReport.First.Value)
-		if wtmc == nil {
-			fmt.Println("数据报告模板参数异常")
-			return
-		}
-		ok, status := frpc.WxPush(config.Config.Weixinrpc, "WeiXinRpc.SendDataReportMsg", &frpc.NotifyMsg{
-			Openid:  openid,
-			Title:   wtmc.FirstData,
-			Detail:  product_type, //产品类型
-			Service: order_coded,  //订单编号
-			Date:    pay_time,     //支付时间
-			Remark:  "数据报告将以电子版形式发送至您的邮箱,请注意垃圾邮件过滤,感谢您的光临",
-			Url:     config.Config.WebDomain + "/front/sess/" + Se.EncodeString(openid+",uid,"+strconv.Itoa(int(time.Now().Unix()))+",datareport") + "__" + order_coded + "__" + wtmc.AdvertCode,
-		})
-		log.Println("数据报告", order_coded, ok, status, wtmc.AdvertCode, wtmc.FirstData)
-	}
+        if openid == "" || order_coded == "" || product_type == "" || pay_time == "" {
+                fmt.Println("数据报告模板参数异常")
+        } else {
+                util.DataReport_WTMCS.Reload()
+                wtmc := util.DataReport_WTMCS.Get(config.MessageConfig.WxTpl_DataReport.First.Value)
+                if wtmc == nil {
+                        fmt.Println("数据报告模板参数异常")
+                        return
+                }
+                ok, status := frpc.WxPush(config.Config.Weixinrpc, "WeiXinRpc.SendDataReportMsg", &frpc.NotifyMsg{
+                        Openid:  openid,
+                        Title:   wtmc.FirstData,
+                        Detail:  product_type, //产品类型
+                        Service: order_coded,  //订单编号
+                        Date:    pay_time,     //支付时间
+                        Remark:  "数据报告将以电子版形式发送至您的邮箱,请注意垃圾邮件过滤,感谢您的光临",
+                        Url:     config.Config.WebDomain + "/front/sess/" + Se.EncodeString(openid+",uid,"+strconv.Itoa(int(time.Now().Unix()))+",datareport") + "__" + order_coded + "__" + wtmc.AdvertCode,
+                })
+                log.Println("数据报告", order_coded, ok, status, wtmc.AdvertCode, wtmc.FirstData)
+        }
 }

+ 235 - 220
src/jfw/modules/subscribepay/src/entity/jyCourseOnlineStruct.go

@@ -1,21 +1,22 @@
 package entity
 
 import (
-	"encoding/json"
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"math"
-	"time"
+        "encoding/json"
+        "errors"
+        "fmt"
+        "go.mongodb.org/mongo-driver/bson/primitive"
+        "jy/src/jfw/modules/subscribepay/src/pay"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "math"
+        "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	. "app.yhyue.com/moapp/jybase/mongodb"
-	frpc "app.yhyue.com/moapp/jybase/rpc"
-	"go.mongodb.org/mongo-driver/bson"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/encrypt"
+        . "app.yhyue.com/moapp/jybase/mongodb"
+        frpc "app.yhyue.com/moapp/jybase/rpc"
+        "go.mongodb.org/mongo-driver/bson"
 )
 
 //剑鱼线上课程
@@ -26,224 +27,238 @@ var JyCourseOnline jyCourseOnline
 
 // 支付完成回调
 func (this *jyCourseOnline) PayCallBack(param *CallBackParam) bool {
-	now := time.Now()
-	update := false
-	orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,order_status,order_money,order_code,filter_id,user_id,dis_word", "")
-	pay_time := FormatDate(&now, Date_Full_Layout)
-	if orderdata != nil {
-		order_status := qutil.IntAll((*orderdata)["order_status"])
-		if order_status == 0 {
-			update = util.Mysql.Update("dataexport_order", map[string]interface{}{
-				"id": (*orderdata)["id"],
-			}, map[string]interface{}{
-				"pay_money":    param.CashFee,
-				"pay_time":     pay_time,
-				"order_status": 1,
-				//支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
-				"out_trade_no": param.OutTradeno,
-			})
-			courseId := qutil.ObjToString((*orderdata)["filter_id"])
-			if update && courseId != "" {
-				//更新课程销量
-				util.MQFW.Update("jy_course", &map[string]interface{}{
-					"_id": StringTOBsonId(courseId),
-				}, &map[string]interface{}{
-					"$inc": bson.M{"i_tradeRate": 1},
-				}, false, false)
-				//取消此用户其他此课程订单
-				util.Mysql.Update("dataexport_order", map[string]interface{}{
-					"user_id":      (*orderdata)["user_id"],
-					"filter_id":    courseId,
-					"order_status": 0,
-				}, map[string]interface{}{
-					"order_status": -2,
-				})
-			}
-		} else {
-			update = true
-		}
-	}
+        now := time.Now()
+        update := false
+        orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,order_status,order_money,order_code,filter_id,user_id,dis_word", "")
+        pay_time := FormatDate(&now, Date_Full_Layout)
+        if orderdata != nil {
+                order_status := qutil.IntAll((*orderdata)["order_status"])
+                if order_status == 0 {
+                        update = util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                "id": (*orderdata)["id"],
+                        }, map[string]interface{}{
+                                "pay_money":    param.CashFee,
+                                "pay_time":     pay_time,
+                                "order_status": 1,
+                                //支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
+                                "out_trade_no": param.OutTradeno,
+                        })
+                        courseId := qutil.ObjToString((*orderdata)["filter_id"])
+                        if update && courseId != "" {
+                                //更新课程销量
+                                util.MQFW.Update("jy_course", &map[string]interface{}{
+                                        "_id": StringTOBsonId(courseId),
+                                }, &map[string]interface{}{
+                                        "$inc": bson.M{"i_tradeRate": 1},
+                                }, false, false)
+                                //取消此用户其他此课程订单
+                                util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                        "user_id":      (*orderdata)["user_id"],
+                                        "filter_id":    courseId,
+                                        "order_status": 0,
+                                }, map[string]interface{}{
+                                        "order_status": -2,
+                                })
+                        }
+                } else {
+                        update = true
+                }
+        }
 
-	//  调用分销记录
-	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 update
+        //  调用分销记录
+        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 update
 }
 
 // 生成订单
 func (this *jyCourseOnline) NewOrder(param frpc.JyPayOrderParam) (ordercode string, err error) {
-	productSign, ok := pay.PayWayAndSign["onlineCourse"][param.PayWay]
-	// 获取分销口令
-	disWordStr := ""
-	userid := param.Userid
-	// 查询用户携带的分销口令
-	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 !ok || productSign == "" {
-		err = errors.New("未知支付类型")
-		return
-	}
+        productSign, ok := pay.PayWayAndSign["onlineCourse"][param.PayWay]
+        // 获取分销口令
+        disWordStr := ""
+        userid := param.Userid
+        // 查询用户携带的分销口令
+        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 !ok || productSign == "" {
+                err = errors.New("未知支付类型")
+                return
+        }
 
-	//插入数据库
-	now := time.Now()
-	ordercode = pay.GetOrderCode(userid)
-	detailByte, marshalErr := json.Marshal(param.Detail)
-	if marshalErr != nil {
-		err = marshalErr
-		return
-	}
-	original_price, discount_price := param.Price, 0 //原价,优惠价格
-	totalfee := param.Price
-	lotteryId := param.LotteryId
-	userLotteryId := "" //使用的卡券
-	if lotteryId != "" {
-		lotteryId = encrypt.SE.Encode2Hex(lotteryId)
-		products := param.UseProduct
-		full_price, reduce_price, discount, userLotteryId_ := util.GetCouponInfo(userid, lotteryId, products)
-		userLotteryId = userLotteryId_
-		if full_price <= totalfee {
-			if discount == 100 { //满减
-				totalfee = totalfee - reduce_price
-				discount_price = reduce_price
-			} else { //满折
-				disCount_int := int(math.Ceil(discount * 100))
-				discount_price = totalfee - totalfee*disCount_int/1000
-				totalfee = totalfee * disCount_int / 1000
-			}
-		} else {
-			userLotteryId = ""
-		}
-	}
-	//创建支付串
-	tradeno, prepayid, payParam, payErr := pay.CreateOrderPay(totalfee, productSign, param.Ip, param.Openid, param.PayWay, ordercode)
-	if payErr != nil {
-		err = payErr
-		return
-	}
-	distributionChannel, _ := util.GetJyOrderChannel(disWordStr, "")
-	insertMap := map[string]interface{}{
-		"order_money":          totalfee,
-		"order_status":         0,
-		"user_openid":          param.Openid,
-		"prepay_id":            prepayid,
-		"code_url":             payParam,
-		"out_trade_no":         tradeno,
-		"order_code":           ordercode,
-		"product_type":         "中标必听课",
-		"create_time":          FormatDate(&now, Date_Full_Layout),
-		"prepay_time":          FormatDate(&now, Date_Full_Layout),
-		"original_price":       original_price,
-		"filter_id":            qutil.If(param.Detail != nil && param.Detail["_id"] != nil, param.Detail["_id"], ""), //课程id
-		"pay_way":              param.PayWay,
-		"user_id":              userid,
-		"filter":               string(detailByte),                    //订单详情
-		"dis_word":             disWordStr,                            //分销口令
-		"distribution_channel": distributionChannel,                   //销售渠道
-		"order_channel":        util.GetRpcOrderChannel(param.PayWay), //下单渠道
-		"discount_price":       discount_price,
-		"d_relation_id":        userLotteryId,
-		"audit_status":         3, //默认审核通过
-	}
-	if param.Phone != "" {
-		insertMap["user_phone"] = param.Phone
-	}
-	orderId := util.Mysql.Insert("dataexport_order", insertMap)
+        //插入数据库
+        now := time.Now()
+        ordercode = pay.GetOrderCode(userid)
+        detailByte, marshalErr := json.Marshal(param.Detail)
+        if marshalErr != nil {
+                err = marshalErr
+                return
+        }
+        original_price, discount_price := param.Price, 0 //原价,优惠价格
+        totalfee := param.Price
+        lotteryId := param.LotteryId
+        userLotteryId := "" //使用的卡券
+        if lotteryId != "" {
+                lotteryId = encrypt.SE.Encode2Hex(lotteryId)
+                products := param.UseProduct
+                full_price, reduce_price, discount, userLotteryId_ := util.GetCouponInfo(userid, lotteryId, products)
+                userLotteryId = userLotteryId_
+                if full_price <= totalfee {
+                        if discount == 100 { //满减
+                                totalfee = totalfee - reduce_price
+                                discount_price = reduce_price
+                        } else { //满折
+                                disCount_int := int(math.Ceil(discount * 100))
+                                discount_price = totalfee - totalfee*disCount_int/1000
+                                totalfee = totalfee * disCount_int / 1000
+                        }
+                } else {
+                        userLotteryId = ""
+                }
+        }
+        //创建支付串
+        tradeno, prepayid, payParam, payErr := pay.CreateOrderPay(totalfee, productSign, param.Ip, param.Openid, param.PayWay, ordercode)
+        if payErr != nil {
+                err = payErr
+                return
+        }
+        distributionChannel, _ := util.GetJyOrderChannel(disWordStr, "")
+        //企业id查找
+        _, 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"])
+                }
+                buy_subject = 2
+        }
+        insertMap := map[string]interface{}{
+                "order_money":          totalfee,
+                "order_status":         0,
+                "user_openid":          param.Openid,
+                "prepay_id":            prepayid,
+                "code_url":             payParam,
+                "out_trade_no":         tradeno,
+                "order_code":           ordercode,
+                "product_type":         "中标必听课",
+                "create_time":          FormatDate(&now, Date_Full_Layout),
+                "prepay_time":          FormatDate(&now, Date_Full_Layout),
+                "original_price":       original_price,
+                "filter_id":            qutil.If(param.Detail != nil && param.Detail["_id"] != nil, param.Detail["_id"], ""), //课程id
+                "pay_way":              param.PayWay,
+                "user_id":              userid,
+                "filter":               string(detailByte),                    //订单详情
+                "dis_word":             disWordStr,                            //分销口令
+                "distribution_channel": distributionChannel,                   //销售渠道
+                "order_channel":        util.GetRpcOrderChannel(param.PayWay), //下单渠道
+                "discount_price":       discount_price,
+                "d_relation_id":        userLotteryId,
+                "audit_status":         3, //默认审核通过
+                "buy_subject":          buy_subject,
+                "ent_id":               entId,
+        }
+        if param.Phone != "" {
+                insertMap["user_phone"] = param.Phone
+        }
+        orderId := util.Mysql.Insert("dataexport_order", insertMap)
 
-	if orderId <= 0 {
-		err = errors.New("订单插入失败")
-		return
-	}
-	//绑定卡卷
-	if userLotteryId != "" && lotteryId != "" {
-		go func(userId, userLotteryId, order_code string) {
-			phone, nickname := util.GetMyPhoneAndName(userId)
-			if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "中标必听课", "", 3, 0) {
-				log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-			}
-		}(userid, userLotteryId, ordercode)
-	}
-	return
+        if orderId <= 0 {
+                err = errors.New("订单插入失败")
+                return
+        }
+        //绑定卡卷
+        if userLotteryId != "" && lotteryId != "" {
+                go func(userId, userLotteryId, order_code string) {
+                        phone, nickname := util.GetMyPhoneAndName(userId)
+                        if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "中标必听课", "", 3, 0) {
+                                log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                        }
+                }(userid, userLotteryId, ordercode)
+        }
+        return
 }
 
 // 更新订单
 func (this *jyCourseOnline) FlushOrder(param frpc.JyPayOrderChangeParam) (string, error) {
-	productSign, ok := pay.PayWayAndSign["onlineCourse"][param.PayWay]
-	if !ok || productSign == "" {
-		return "", errors.New("未知支付类型")
-	}
-	//查询订单
-	res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": param.OrderCode}, "order_money", "")
-	if res == nil || len(*res) == 0 {
-		return "", errors.New("未找到订单" + param.OrderCode)
-	}
-	price := qutil.IntAll((*res)["order_money"])
-	if price == 0 {
-		return "", errors.New("查询金额异常" + param.OrderCode)
-	}
-	//创建支付串
-	tradeno, prepayid, payParam, payErr := pay.CreateOrderPay(price, productSign, param.Ip, param.Openid, param.PayWay, param.OrderCode)
-	if payErr != nil {
-		return "", payErr
-	}
-	now := time.Now()
-	if !util.Mysql.Update("dataexport_order", map[string]interface{}{
-		"order_status": 0,
-		"order_code":   param.OrderCode,
-	}, map[string]interface{}{
-		"prepay_time":  FormatDate(&now, Date_Full_Layout),
-		"prepay_id":    prepayid,
-		"code_url":     payParam,
-		"out_trade_no": tradeno,
-		"pay_way":      param.PayWay,
-	}) {
-		return "", errors.New(fmt.Sprintf("%s,%s更新数据库出错", param.OrderCode, param.PayWay))
-	}
-	return payParam, nil
+        productSign, ok := pay.PayWayAndSign["onlineCourse"][param.PayWay]
+        if !ok || productSign == "" {
+                return "", errors.New("未知支付类型")
+        }
+        //查询订单
+        res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{"order_code": param.OrderCode}, "order_money", "")
+        if res == nil || len(*res) == 0 {
+                return "", errors.New("未找到订单" + param.OrderCode)
+        }
+        price := qutil.IntAll((*res)["order_money"])
+        if price == 0 {
+                return "", errors.New("查询金额异常" + param.OrderCode)
+        }
+        //创建支付串
+        tradeno, prepayid, payParam, payErr := pay.CreateOrderPay(price, productSign, param.Ip, param.Openid, param.PayWay, param.OrderCode)
+        if payErr != nil {
+                return "", payErr
+        }
+        now := time.Now()
+        if !util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "order_status": 0,
+                "order_code":   param.OrderCode,
+        }, map[string]interface{}{
+                "prepay_time":  FormatDate(&now, Date_Full_Layout),
+                "prepay_id":    prepayid,
+                "code_url":     payParam,
+                "out_trade_no": tradeno,
+                "pay_way":      param.PayWay,
+        }) {
+                return "", errors.New(fmt.Sprintf("%s,%s更新数据库出错", param.OrderCode, param.PayWay))
+        }
+        return payParam, nil
 }
 
 func (this *jyCourseOnline) CloseOrder(ordercode string) error {
-	err := pay.CloseOrderByOrderCode(ordercode)
-	if err != nil {
-		return err
-	}
-	if !util.Mysql.Update("dataexport_order", map[string]interface{}{
-		"order_status": 0,
-		"order_code":   ordercode,
-	}, map[string]interface{}{
-		"order_status": -2,
-	}) {
-		res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_status": ordercode,
-		}, "id,order_code,create_time,pay_way,out_trade_no,prepay_time,order_status,discount_price,d_relation_id,user_id,filter,product_type", "")
-		user_id := qutil.ObjToString((*res)["user_id"])
-		userLotteryId := qutil.ObjToString((*res)["d_relation_id"])
-		go func(userId, userLotteryId, order_code string) {
-			if !util.UpdateCouponState(userId, userLotteryId, "", "", order_code, qutil.ObjToString((*res)["product_type"]), "0", 0, 1) {
-				log.Println(fmt.Sprintf("单号%s-解绑失败-卡卷%s", order_code, userLotteryId))
-			}
-		}(user_id, userLotteryId, ordercode)
-		return errors.New(fmt.Sprintf("%s关闭订单更新数据库出错", ordercode))
-	}
-	return nil
+        err := pay.CloseOrderByOrderCode(ordercode)
+        if err != nil {
+                return err
+        }
+        if !util.Mysql.Update("dataexport_order", map[string]interface{}{
+                "order_status": 0,
+                "order_code":   ordercode,
+        }, map[string]interface{}{
+                "order_status": -2,
+        }) {
+                res := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_status": ordercode,
+                }, "id,order_code,create_time,pay_way,out_trade_no,prepay_time,order_status,discount_price,d_relation_id,user_id,filter,product_type", "")
+                user_id := qutil.ObjToString((*res)["user_id"])
+                userLotteryId := qutil.ObjToString((*res)["d_relation_id"])
+                go func(userId, userLotteryId, order_code string) {
+                        if !util.UpdateCouponState(userId, userLotteryId, "", "", order_code, qutil.ObjToString((*res)["product_type"]), "0", 0, 1) {
+                                log.Println(fmt.Sprintf("单号%s-解绑失败-卡卷%s", order_code, userLotteryId))
+                        }
+                }(user_id, userLotteryId, ordercode)
+                return errors.New(fmt.Sprintf("%s关闭订单更新数据库出错", ordercode))
+        }
+        return nil
 }

+ 205 - 175
src/jfw/modules/subscribepay/src/entity/member.go

@@ -1,18 +1,18 @@
 package entity
 
 import (
-	"encoding/json"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"strconv"
-	"strings"
-	"time"
+        "encoding/json"
+        "fmt"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "strconv"
+        "strings"
+        "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 memberStruct struct{}
@@ -21,177 +21,207 @@ var MemberStruct memberStruct
 var Bigmember_serice map[int]map[int]int //权益 k:子id ; v:map[int]int{父id:年数量}
 
 func init() {
-	log.Println("初始化大会员权益")
-	//初始化用户权益
-	member_serice := map[int]map[int]int{}
-	if rdata := util.Mysql.SelectBySql(`SELECT id,s_name,i_pid,s_count_year FROM bigmember_service`); rdata != nil && len(*rdata) > 0 {
-		for _, v := range *rdata {
-			sid := qutil.IntAll(v["id"])
-			pid := qutil.IntAll(v["i_pid"])
-			count_year := qutil.IntAll(v["s_count_year"])
-			// log.Println(pid, sid, count_year)
-			if pid != 0 {
-				member_serice[sid] = map[int]int{
-					pid: count_year,
-				}
-			} else {
-				member_serice[sid] = map[int]int{
-					sid: count_year,
-				}
-			}
-		}
-	}
-	Bigmember_serice = member_serice
-	log.Println("初始化大会员权益已结束")
+        log.Println("初始化大会员权益")
+        //初始化用户权益
+        member_serice := map[int]map[int]int{}
+        if rdata := util.Mysql.SelectBySql(`SELECT id,s_name,i_pid,s_count_year FROM bigmember_service`); rdata != nil && len(*rdata) > 0 {
+                for _, v := range *rdata {
+                        sid := qutil.IntAll(v["id"])
+                        pid := qutil.IntAll(v["i_pid"])
+                        count_year := qutil.IntAll(v["s_count_year"])
+                        // log.Println(pid, sid, count_year)
+                        if pid != 0 {
+                                member_serice[sid] = map[int]int{
+                                        pid: count_year,
+                                }
+                        } else {
+                                member_serice[sid] = map[int]int{
+                                        sid: count_year,
+                                }
+                        }
+                }
+        }
+        Bigmember_serice = member_serice
+        log.Println("初始化大会员权益已结束")
 }
 
 // 大会员支付完成回调方法
 func (m *memberStruct) PayCallBack(param *CallBackParam) bool {
-	orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,filter,order_code,order_status,user_id,vip_type,prepay_time", "")
-	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)
-		var filter map[string]interface{}
-		if err := json.Unmarshal([]byte(qutil.ObjToString((*orderdata)["filter"])), &filter); err != nil {
-			log.Println("大会员支付成功json.Unmarshal出错", err)
-		} else {
-			cycle := qutil.IntAll(filter["cycle"])
-			level := qutil.IntAll(filter["level"])
-			var enddate = time.Now()
-			if level == 4 { //试用用户 试用七天
-				enddate = time.Date(now.Year(), now.Month(), now.Day()+cycle, 23, 59, 59, 0, time.Local)
-			} else {
-				enddate = time.Date(now.Year()+cycle, now.Month(), now.Day(), 23, 59, 59, 0, time.Local)
-			}
-			normal_member(level, enddate, userId)
-			//
-			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,
-				"vip_starttime": nowFormat,
-				"vip_endtime":   FormatDate(&enddate, Date_Full_Layout),
-				//支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
-				"out_trade_no": param.OutTradeno,
-			})
-			if update {
-				util.MsgRemind.BigMemberPaySuccess(qutil.IntAll((*orderdata)["id"]), qutil.ObjToString((*orderdata)["order_code"]), qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["prepay_time"]), qutil.IntAllDef((*orderdata)["vip_type"], -1))
-				//取消其他订单
-				go PayCancel(userId, "大会员", "")
-			}
-		}
-	}
-	return true
+        orderdata := util.Mysql.FindOne("dataexport_order", param.GetPaySuccessOrderQuery(), "id,filter,order_code,order_status,user_id,vip_type,prepay_time", "")
+        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)
+                var filter map[string]interface{}
+                if err := json.Unmarshal([]byte(qutil.ObjToString((*orderdata)["filter"])), &filter); err != nil {
+                        log.Println("大会员支付成功json.Unmarshal出错", err)
+                } else {
+                        cycle := qutil.IntAll(filter["cycle"])
+                        level := qutil.IntAll(filter["level"])
+                        var enddate = time.Now()
+                        if level == 4 { //试用用户 试用七天
+                                enddate = time.Date(now.Year(), now.Month(), now.Day()+cycle, 23, 59, 59, 0, time.Local)
+                        } else {
+                                enddate = time.Date(now.Year()+cycle, now.Month(), now.Day(), 23, 59, 59, 0, time.Local)
+                        }
+                        normal_member(level, enddate, userId,0,0,0)
+                        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,
+                                "vip_starttime": nowFormat,
+                                "vip_endtime":   FormatDate(&enddate, Date_Full_Layout),
+                                //支付成功后更新成支付成功的out_trade_no 避免多人支付重复刷新字段
+                                "out_trade_no": param.OutTradeno,
+                        })
+                        if update {
+                                util.MsgRemind.BigMemberPaySuccess(qutil.IntAll((*orderdata)["id"]), qutil.ObjToString((*orderdata)["order_code"]), qutil.ObjToString((*orderdata)["user_id"]), qutil.ObjToString((*orderdata)["prepay_time"]), qutil.IntAllDef((*orderdata)["vip_type"], -1))
+                                //取消其他订单
+                                go PayCancel(userId, "大会员", "")
+                        }
+                }
+        }
+        return true
 }
 
-func normal_member(level int, enddate time.Time, userId string) {
-	//修改用户表权限
-	set := map[string]interface{}{
-		"i_member_status":      level,
-		"i_member_starttime":   time.Now().Unix(),
-		"i_member_endtime":     enddate.Unix(),
-		"o_member_jy.i_wxpush": 1,
-	}
-	if level == 4 { //试用用户
-		set["i_member_trial"] = 1 //试用标识
-	} else {
-		//查看当前用户是否是试用用户 正在试用中(大会员状态ing)
-		userInfo, ok := util.MQFW.FindById("user", userId, nil)
-		if ok && userInfo != nil && *userInfo != nil {
-			if (*userInfo)["i_member_status"] != nil && qutil.IntAll((*userInfo)["i_member_status"]) > 0 {
-				//禁用当前大会员服务
-				util.Mysql.UpdateOrDeleteBySql(`UPDATE `+jy.BigmemberUserPowerTable+` a SET a.i_frequency = 0 , a.i_status = -1, a.l_updatetime=? WHERE a.s_userid = ?`, NowFormat(Date_Full_Layout), userId)
-			}
-		}
-	}
-	util.MQFW.UpdateById("user", userId, map[string]interface{}{
-		"$set": set,
-	})
-	//更新大会员用户服务表
-	bigmember_combo_list := util.Mysql.SelectBySql(`SELECT * FROM bigmember_combo a WHERE a.id = ?`, level)
-	serviceCode := "" //大会员服务id集合
-	if len(*bigmember_combo_list) > 0 {
-		list := (*bigmember_combo_list)[0]
-		serviceCode = list["s_servers"].(string)
-	}
-	if serviceCode != "" {
-		for _, v := range strings.Split(serviceCode, ",") {
-			var s_serviceid = v
-			var frequency = 0
-			sid, _ := strconv.Atoi(v)
-			if Bigmember_serice[sid] != nil {
-				for k, v := range Bigmember_serice[sid] {
-					s_serviceid = strconv.Itoa(k)
-					frequency = v
-				}
-			}
-			if util.Mysql.CountBySql(`select count(*) from `+jy.BigmemberUserPowerTable+` where s_userid=? and s_serviceid=?`, userId, v) == 0 {
-				insert := map[string]interface{}{
-					"s_userid":     userId,
-					"s_serviceid":  s_serviceid,
-					"i_frequency":  frequency,
-					"l_starttime":  NowFormat(Date_Full_Layout),
-					"l_endtime":    FormatDate(&enddate, Date_Full_Layout),
-					"i_status":     0,
-					"l_createtime": NowFormat(Date_Full_Layout),
-					"l_updatetime": NowFormat(Date_Full_Layout),
-					"s_smainid":    v,
-				}
-				order_id := util.Mysql.Insert(jy.BigmemberUserPowerTable, insert)
-				if order_id == 0 {
-					log.Println("保存出错:", userId, "---", v)
-				}
-			} else {
-				query := map[string]interface{}{
-					"s_userid":    userId,
-					"s_serviceid": s_serviceid,
-				}
-				update := map[string]interface{}{
-					"i_status":     0,
-					"i_frequency":  frequency,
-					"l_updatetime": NowFormat(Date_Full_Layout),
-					"l_endtime":    FormatDate(&enddate, Date_Full_Layout),
-					"s_smainid":    v,
-				}
-				if !util.Mysql.Update(jy.BigmemberUserPowerTable, query, update) {
-					log.Println("更新大会员用户服务表出错:", userId, v)
-				}
-			}
-		}
-		//redis 存储缓存
-		go func() {
-			if !jy.ClearBigVipUserPower(userId) {
-				log.Println("userid:", userId, "清除redis缓存失败-")
-			}
-		}()
-	} else {
-		log.Println("查询 大会员套餐 信息出错:", userId, ";大会员等级:", level)
-	}
+func normal_member(level int, enddate time.Time, userId string, positionType, entId, entUserId int64) {
+        //修改用户表权限
+        set := map[string]interface{}{}
+        if positionType == 0 {
+                set = map[string]interface{}{
+                        "i_member_status":      level,
+                        "i_member_starttime":   time.Now().Unix(),
+                        "i_member_endtime":     enddate.Unix(),
+                        "o_member_jy.i_wxpush": 1,
+                }
+        } else {
+                set = map[string]interface{}{
+                        "i_status":            level,
+                        "i_starttime":         time.Now().Unix(),
+                        "i_endtime":           enddate.Unix(),
+                        "o_entniche.i_wxpush": 1,
+                }
+        }
+        if level == 4 { //试用用户
+                set["i_member_trial"] = 1 //试用标识
+        } else {
+                //查看当前用户是否是试用用户 正在试用中(大会员状态ing)
+                userInfo, ok:=&map[string]interface{}{},false
+                if  positionType==0{
+                        userInfo, ok = util.MQFW.FindById("user", userId, nil)
+                }else{
+                        query := map[string]interface{}{
+                                "i_userid": entUserId,
+                                "i_entid":  entId,
+                                "i_type":   1,
+                        }
+                        userInfo, ok = util.MQFW.FindOne("entniche_rule", query)
+                }
+                if ok && userInfo != nil && *userInfo != nil {
+                        if (*userInfo)["i_member_status"] != nil && qutil.IntAll((*userInfo)["i_member_status"]) > 0 {
+                                //禁用当前大会员服务
+                                util.Mysql.UpdateOrDeleteBySql(`UPDATE `+jy.BigmemberUserPowerTable+` a SET a.i_frequency = 0 , a.i_status = -1, a.l_updatetime=? WHERE a.s_userid = ?`, NowFormat(Date_Full_Layout), userId)
+                        }
+                }
+        }
+        if positionType == 0 {
+                util.MQFW.UpdateById("user", userId, map[string]interface{}{
+                        "$set": set,
+                })
+        } else {
+                query := map[string]interface{}{
+                        "i_userid": entUserId,
+                        "i_entid":  entId,
+                        "i_type":   1,
+                }
+                util.MQFW.Update("entniche_rule", query, map[string]interface{}{
+                        "$set": set,
+                }, true, false)
+        }
+        //更新大会员用户服务表
+        bigmember_combo_list := util.Mysql.SelectBySql(`SELECT * FROM bigmember_combo a WHERE a.id = ?`, level)
+        serviceCode := "" //大会员服务id集合
+        if len(*bigmember_combo_list) > 0 {
+                list := (*bigmember_combo_list)[0]
+                serviceCode = list["s_servers"].(string)
+        }
+        if serviceCode != "" {
+                for _, v := range strings.Split(serviceCode, ",") {
+                        var s_serviceid = v
+                        var frequency = 0
+                        sid, _ := strconv.Atoi(v)
+                        if Bigmember_serice[sid] != nil {
+                                for k, v := range Bigmember_serice[sid] {
+                                        s_serviceid = strconv.Itoa(k)
+                                        frequency = v
+                                }
+                        }
+                        if util.Mysql.CountBySql(`select count(*) from `+jy.BigmemberUserPowerTable+` where s_userid=? and s_serviceid=?`, userId, v) == 0 {
+                                insert := map[string]interface{}{
+                                        "s_userid":     userId,
+                                        "s_serviceid":  s_serviceid,
+                                        "i_frequency":  frequency,
+                                        "l_starttime":  NowFormat(Date_Full_Layout),
+                                        "l_endtime":    FormatDate(&enddate, Date_Full_Layout),
+                                        "i_status":     0,
+                                        "l_createtime": NowFormat(Date_Full_Layout),
+                                        "l_updatetime": NowFormat(Date_Full_Layout),
+                                        "s_smainid":    v,
+                                }
+                                order_id := util.Mysql.Insert(jy.BigmemberUserPowerTable, insert)
+                                if order_id == 0 {
+                                        log.Println("保存出错:", userId, "---", v)
+                                }
+                        } else {
+                                query := map[string]interface{}{
+                                        "s_userid":    userId,
+                                        "s_serviceid": s_serviceid,
+                                }
+                                update := map[string]interface{}{
+                                        "i_status":     0,
+                                        "i_frequency":  frequency,
+                                        "l_updatetime": NowFormat(Date_Full_Layout),
+                                        "l_endtime":    FormatDate(&enddate, Date_Full_Layout),
+                                        "s_smainid":    v,
+                                }
+                                if !util.Mysql.Update(jy.BigmemberUserPowerTable, query, update) {
+                                        log.Println("更新大会员用户服务表出错:", userId, v)
+                                }
+                        }
+                }
+                //redis 存储缓存
+                go func() {
+                        if !jy.ClearBigVipUserPower(userId) {
+                                log.Println("userid:", userId, "清除redis缓存失败-")
+                        }
+                }()
+        } else {
+                log.Println("查询 大会员套餐 信息出错:", userId, ";大会员等级:", level)
+        }
 }
 
 func (m *memberStruct) GetMoney(userId string, level, cycle int) int {
-	if level > 7 || cycle < 1 {
-		log.Println(userId, "大会员订单level、cycle参数不合法", level, cycle)
-		return -1
-	}
-	var price float64
-	price = config.MemberConfig.Price[fmt.Sprintf("%v", level)] * float64(cycle)
-	if level == 4 {
-		price = config.MemberConfig.Price[fmt.Sprintf("%v", level)]
-	}
-	log.Println(level, " : ", price)
-	if price == 0 {
-		log.Println(userId, "大会员订单获取price错误")
-		return -1
-	}
-	if price < 1 {
-		price = 1
-	}
-	return int(price)
+        if level > 7 || cycle < 1 {
+                log.Println(userId, "大会员订单level、cycle参数不合法", level, cycle)
+                return -1
+        }
+        var price float64
+        price = config.MemberConfig.Price[fmt.Sprintf("%v", level)] * float64(cycle)
+        if level == 4 {
+                price = config.MemberConfig.Price[fmt.Sprintf("%v", level)]
+        }
+        log.Println(level, " : ", price)
+        if price == 0 {
+                log.Println(userId, "大会员订单获取price错误")
+                return -1
+        }
+        if price < 1 {
+                price = 1
+        }
+        return int(price)
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 1042 - 1040
src/jfw/modules/subscribepay/src/entity/order.go


+ 144 - 129
src/jfw/modules/subscribepay/src/entity/shareFission.go

@@ -1,97 +1,98 @@
 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"
-	"net/http"
-	"regexp"
-	"time"
+        "encoding/json"
+        "fmt"
+        "go.mongodb.org/mongo-driver/bson/primitive"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/pay"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "net/http"
+        "regexp"
+        "time"
 
-	qu "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/redis"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        qu "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/redis"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 type ShareFission struct {
-	UserId    string //被分享者
-	ShareUid  string //分享者
-	NewSource string // 来源
+        UserId    string //被分享者
+        ShareUid  string //分享者
+        NewSource string // 来源
 }
 
 func NewShareFission(userId, shareUid, newSource string) *ShareFission {
-	return &ShareFission{
-		UserId:    userId,
-		ShareUid:  shareUid,
-		NewSource: newSource,
-	}
+        return &ShareFission{
+                UserId:    userId,
+                ShareUid:  shareUid,
+                NewSource: newSource,
+        }
 }
 
 // 活动赠送
 const (
-	SaleChannel051    = "x051"          // 销售渠道活动赠送
-	OrderPassed       = 3               // 订单审核状态-审核通过
-	TableAuditRecords = "audit_records" // 审核记录表
-	OperateCreate     = 1               // 审核轨迹操作类型-新增
-	AuditCreate       = 2               // 审核类型-创建订单
+        SaleChannel051    = "x051"          // 销售渠道活动赠送
+        OrderPassed       = 3               // 订单审核状态-审核通过
+        TableAuditRecords = "audit_records" // 审核记录表
+        OperateCreate     = 1               // 审核轨迹操作类型-新增
+        AuditCreate       = 2               // 审核类型-创建订单
 )
 
 var jianyubiReg = regexp.MustCompile(`达到(\d+)剑鱼币`)
 
 //增加权益
 func (this *ShareFission) AddPower(r *http.Request) {
-	if this.ShareUid != "" { //有分享人
-		err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invited, this.UserId, jy.Jywx_node1)
-		if err != nil {
-			log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invited, this.UserId)
-		}
-		err = jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invite, this.ShareUid, jy.Jywx_node1)
-		if err != nil {
-			log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invite, this.ShareUid)
-		}
-		//记录分享记录
-		this.Record()
-	} else { //无分享人-新用户
-		// 年终报告分享过来的
-		if this.NewSource == "reportShare" {
-			err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_report_invited, this.UserId, jy.Jywx_node1)
-			if err != nil {
-				log.Println("nsq队列写入失败-->", err, jy.Jywx_report_invited, this.UserId)
-			}
-			return
-		}
-		e_code := jy.Jyapp_phone_register
-		if !mobileReg.MatchString(r.UserAgent()) { //PC端绑定手机号
-			e_code = jy.Jypc_phone_register
-		} else if qu.IsWxBrowser(r) { //微信端绑定手机号
-			e_code = jy.Jywx_subscribe_new
-		}
-		err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, e_code, this.UserId, jy.Jywx_node1)
-		if err != nil {
-			log.Println("nsq队列写入失败-->", err, e_code, this.UserId)
-		}
-	}
+        if this.ShareUid != "" { //有分享人
+                err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invited, this.UserId, jy.Jywx_node1)
+                if err != nil {
+                        log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invited, this.UserId)
+                }
+                err = jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invite, this.ShareUid, jy.Jywx_node1)
+                if err != nil {
+                        log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invite, this.ShareUid)
+                }
+                //记录分享记录
+                this.Record()
+        } else { //无分享人-新用户
+                // 年终报告分享过来的
+                if this.NewSource == "reportShare" {
+                        err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_report_invited, this.UserId, jy.Jywx_node1)
+                        if err != nil {
+                                log.Println("nsq队列写入失败-->", err, jy.Jywx_report_invited, this.UserId)
+                        }
+                        return
+                }
+                e_code := jy.Jyapp_phone_register
+                if !mobileReg.MatchString(r.UserAgent()) { //PC端绑定手机号
+                        e_code = jy.Jypc_phone_register
+                } else if qu.IsWxBrowser(r) { //微信端绑定手机号
+                        e_code = jy.Jywx_subscribe_new
+                }
+                err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, e_code, this.UserId, jy.Jywx_node1)
+                if err != nil {
+                        log.Println("nsq队列写入失败-->", err, e_code, this.UserId)
+                }
+        }
 }
 
 var mobileReg = regexp.MustCompile("(?i)(Android|Mobile|Phone)")
 
 func AddPower(s_m_openid, userId string, r *http.Request) {
-	if shareUid := redis.GetStr(config.Config.ShareRedisName, fmt.Sprintf("rec_%s", s_m_openid)); shareUid != "" {
-		err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invited, userId, jy.Jywx_node1)
-		if err != nil {
-			log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invited, userId)
-		}
-		err = jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invite, shareUid, jy.Jywx_node1)
-		if err != nil {
-			log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invite, shareUid)
-		}
-	} else {
+        if shareUid := redis.GetStr(config.Config.ShareRedisName, fmt.Sprintf("rec_%s", s_m_openid)); shareUid != "" {
+                err := jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invited, userId, jy.Jywx_node1)
+                if err != nil {
+                        log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invited, userId)
+                }
+                err = jy.Publish(util.Mgo_log, config.Config.Nsq, config.Config.Nsq_Topic, jy.Jywx_subscribe_invite, shareUid, jy.Jywx_node1)
+                if err != nil {
+                        log.Println("nsq队列写入失败-->", err, jy.Jywx_subscribe_invite, shareUid)
+                }
+        } else {
 
-	}
+        }
 }
 
 /*
@@ -99,73 +100,87 @@ func AddPower(s_m_openid, userId string, r *http.Request) {
 	types:订单类型  1: 仅延长周期  2: 开通权益
 */
 func Order(userid, starttime, endtime string, types, dayNum int, remark string) bool {
-	_, buyset, isvip := JyVipSubStruct.GetVipDetail(userid)
-	filter := VipSimpleMsg{
-		Area:       nil,
-		Industry:   nil,
-		NewBuyset:  buyset,
-		OrderType:  qu.IntAll(qu.If(isvip, 1, 5)),
-		Cycleunit:  3,
-		Cyclecount: dayNum,
-		Badge:      "give",
-		Remark:     remark,
-	}
-	if types == 2 {
-		filter.Area = &map[string]interface{}{"北京": []string{}}
-		filter.Industry = []string{}
-		util.MergeKws(userid)
-	}
-	filterStr, _ := json.Marshal(filter)
-	ordercode := pay.GetOrderCode(userid)
-	now := time.Now()
-	insertMap := map[string]interface{}{
-		"order_money":    0,
-		"order_status":   1,
-		"order_code":     ordercode,
-		"product_type":   "VIP订阅",
-		"create_time":    FormatDate(&now, Date_Full_Layout),
-		"original_price": 0,
-		"user_id":        userid,
-		"filter":         string(filterStr), //筛选
-		"vip_starttime":  starttime,
-		"vip_endtime":    endtime,
-		"billingMode":    0, //计费模式 0免费 1付费
-	}
-	// 如果备注为剑鱼币兑换
-	if jianyubiReg.MatchString(remark) {
-		insertMap["distribution_channel"] = SaleChannel051 // 销售渠道
-	}
-	insertMap["audit_status"] = OrderPassed // 订单审核状态
-	if util.Mysql.Insert("dataexport_order", insertMap) != 0 {
-		// 新增一条审核记录
-		CreateOrderAuditRecord(ordercode, FormatDate(&now, Date_Full_Layout))
-		return true
-	} else {
-		return false
-	}
+        _, buyset, isvip := JyVipSubStruct.GetVipDetail(userid)
+        filter := VipSimpleMsg{
+                Area:       nil,
+                Industry:   nil,
+                NewBuyset:  buyset,
+                OrderType:  qu.IntAll(qu.If(isvip, 1, 5)),
+                Cycleunit:  3,
+                Cyclecount: dayNum,
+                Badge:      "give",
+                Remark:     remark,
+        }
+        if types == 2 {
+                filter.Area = &map[string]interface{}{"北京": []string{}}
+                filter.Industry = []string{}
+                util.MergeKws(userid, 0, 0, 0)
+        }
+        filterStr, _ := json.Marshal(filter)
+        ordercode := pay.GetOrderCode(userid)
+        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 = qu.IntAll((*positionData)["ent_id"])
+                }
+                buy_subject = 2
+        }
+        insertMap := map[string]interface{}{
+                "order_money":    0,
+                "order_status":   1,
+                "order_code":     ordercode,
+                "product_type":   "VIP订阅",
+                "create_time":    FormatDate(&now, Date_Full_Layout),
+                "original_price": 0,
+                "user_id":        userid,
+                "filter":         string(filterStr), //筛选
+                "vip_starttime":  starttime,
+                "vip_endtime":    endtime,
+                "billingMode":    0, //计费模式 0免费 1付费
+                "buy_subject":    buy_subject,
+                "ent_id":         entId,
+        }
+        // 如果备注为剑鱼币兑换
+        if jianyubiReg.MatchString(remark) {
+                insertMap["distribution_channel"] = SaleChannel051 // 销售渠道
+        }
+        insertMap["audit_status"] = OrderPassed // 订单审核状态
+
+        if util.Mysql.Insert("dataexport_order", insertMap) != 0 {
+                // 新增一条审核记录
+                CreateOrderAuditRecord(ordercode, FormatDate(&now, Date_Full_Layout))
+                return true
+        } else {
+                return false
+        }
 }
 
 func (this *ShareFission) Record() {
-	util.MQFW.Save("user_share", map[string]interface{}{
-		"share_uid":  this.ShareUid,
-		"shared_uid": this.UserId,
-		"createtime": time.Now().Unix(),
-	})
+        util.MQFW.Save("user_share", map[string]interface{}{
+                "share_uid":  this.ShareUid,
+                "shared_uid": this.UserId,
+                "createtime": time.Now().Unix(),
+        })
 }
 
 func CreateOrderAuditRecord(orderCode string, createTime string) {
-	saveData := map[string]interface{}{
-		"operator":      "-",
-		"create_time":   createTime,
-		"operator_type": OperateCreate,
-		"audit_status":  OrderPassed,
-		"order_code":    orderCode,
-		"audit_type":    AuditCreate,
-	}
-	if !InsertAudit(saveData) {
-		log.Println("新增审核轨迹保存失败", saveData)
-	}
+        saveData := map[string]interface{}{
+                "operator":      "-",
+                "create_time":   createTime,
+                "operator_type": OperateCreate,
+                "audit_status":  OrderPassed,
+                "order_code":    orderCode,
+                "audit_type":    AuditCreate,
+        }
+        if !InsertAudit(saveData) {
+                log.Println("新增审核轨迹保存失败", saveData)
+        }
 }
 func InsertAudit(data map[string]interface{}) bool {
-	return util.Mysql.Insert(TableAuditRecords, data) > 0
+        return util.Mysql.Insert(TableAuditRecords, data) > 0
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 561 - 483
src/jfw/modules/subscribepay/src/entity/subscribeVip.go


+ 16 - 19
src/jfw/modules/subscribepay/src/go.mod

@@ -3,22 +3,23 @@ module jy/src/jfw/modules/subscribepay/src
 go 1.18
 
 require (
-	app.yhyue.com/moapp/jybase v0.0.0-20221230025810-b88f2a62c467
-	app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab
 	bp.jydev.jianyu360.cn/BaseService/pushpkg v0.0.0-20221230024250-38ee6578aff5
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	github.com/dchest/captcha v1.0.0
-	github.com/go-xweb/xweb v0.2.1
 	github.com/shopspring/decimal v1.3.1
 	github.com/tealeg/xlsx v1.0.5
 	go.mongodb.org/mongo-driver v1.11.1
 	gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
 )
 
+require go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 // indirect
+
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
-	app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c // indirect
-	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 // indirect
+	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c // 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
@@ -34,9 +35,6 @@ require (
 	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/go-xweb/httpsession v0.0.0-20141220075701-356d3b4d38d6 // indirect
-	github.com/go-xweb/log v0.0.0-20140701090824-270d183ad77e // indirect
-	github.com/go-xweb/uuid v0.0.0-20140604020037-d7dce341f851 // indirect
 	github.com/gogo/protobuf v1.3.2 // indirect
 	github.com/golang-jwt/jwt/v4 v4.4.3 // indirect
 	github.com/golang/mock v1.6.0 // indirect
@@ -53,7 +51,6 @@ require (
 	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/lunny/csession v0.0.0-20130910075847-fe53c5de3dfd // indirect
 	github.com/mattn/go-colorable v0.1.9 // indirect
 	github.com/mattn/go-isatty v0.0.14 // indirect
 	github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
@@ -75,18 +72,18 @@ require (
 	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.3 // 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.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/jaeger v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0 // indirect
-	go.opentelemetry.io/otel/exporters/zipkin v1.10.0 // indirect
-	go.opentelemetry.io/otel/sdk v1.10.0 // indirect
-	go.opentelemetry.io/otel/trace v1.10.0 // 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/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
@@ -96,7 +93,7 @@ require (
 	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-20220728004956-3c1f35247d10 // 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

+ 33 - 33
src/jfw/modules/subscribepay/src/go.sum

@@ -2,14 +2,14 @@ app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d h1:WPsYuuptAd3UEgN+j
 app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d/go.mod h1:91/lSD/hS+ckMVP3WdidRzDhC60lLMdyce9QHy0cSMA=
 app.yhyue.com/moapp/jyPoints v1.1.1/go.mod h1:SvP8p5L3jGrejHiH2LXfgCg/NPlFiKBC5Yd0gsI12FU=
 app.yhyue.com/moapp/jybase v0.0.0-20220427020729-974c1a148186/go.mod h1:qNRA0sHuYqcLoYoP8irpaWnW9YsXixe6obBIkwaXpD0=
-app.yhyue.com/moapp/jybase v0.0.0-20221230025810-b88f2a62c467 h1:MTZBSIzrqrwieb1gLhls3Wjz0Q2u75n+O2jfPw40iEA=
-app.yhyue.com/moapp/jybase v0.0.0-20221230025810-b88f2a62c467/go.mod h1:zB47XTeJvpcbtBRYgkQuxOICWNexiZfbUO+7aUf6mNs=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf h1:NMVZDXa4yZtL2BTM8gJLpRU4fSN9a1cj7mTVYa1RUZY=
-app.yhyue.com/moapp/jypkg v0.0.0-20230110033535-d6c3e4b755cf/go.mod h1:7D6zNxrg+Tma3VC43TLu7XPczubl4uJavua89kaFS1Q=
-app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c h1:CrcvbsXZ4aQkNikBi7FUUQZNnY8hKsNo2LLe/SqeXs8=
-app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c/go.mod h1:b0zZHev3gmJao1Fo+2Z2KPVjsuLOJVvVxf+kCnu9WkA=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4 h1:Xv1D9avDKeaM5kQTisF/pIt8y7B7yQ/hAxuWEg75LMs=
-bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230106052936-bd3ab7edf7a4/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
+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-20230128092104-d8ae3867d2ab h1:a9XvegdF3aM0y9v5SHtX03LIGMS3+8J1ofoNeyw5J0Y=
+app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab/go.mod h1:MqJfBFTSfZhrNDEnE4e19BmaLkaMr+lYActLXm6lrpw=
+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/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c h1:g49jOlhZlBCJ3IgJA0rotfNf2Gh22pISffUtqxB8XtY=
+bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c/go.mod h1:5nimT8GJh46AyfeeDeyRlDQygMlO7TRM8Pwm41Gxemc=
 bp.jydev.jianyu360.cn/BaseService/pushpkg v0.0.0-20221230024250-38ee6578aff5 h1:XIx7gUaO2Wl7iPMHMrZj5QVqv1fpk5CR/Y9y+d3vNNI=
 bp.jydev.jianyu360.cn/BaseService/pushpkg v0.0.0-20221230024250-38ee6578aff5/go.mod h1:UKLwPLx9be595yaiIwqqdKSloKK/Kdf/wTLr4XUClV0=
 cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
@@ -411,8 +411,8 @@ github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZp
 github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc=
 github.com/alicebob/miniredis/v2 v2.14.1/go.mod h1:uS970Sw5Gs9/iK3yBg0l9Uj9s25wXxSpQUE9EaJ/Blg=
 github.com/alicebob/miniredis/v2 v2.22.0/go.mod h1:XNqvJdQJv5mSuVMc0ynneafpnL/zv52acZ6kqeS0t88=
-github.com/alicebob/miniredis/v2 v2.23.1 h1:jR6wZggBxwWygeXcdNyguCOCIjPsZyNUNlAkTx2fu0U=
-github.com/alicebob/miniredis/v2 v2.23.1/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
+github.com/alicebob/miniredis/v2 v2.30.0 h1:uA3uhDbCxfO9+DI/DuGeAMr9qI+noVWwGPNTFuKID5M=
+github.com/alicebob/miniredis/v2 v2.30.0/go.mod h1:84TWKZlxYkfgMucPBf5SOQBYJceZeQRFIaQgNMiCX6Q=
 github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q=
 github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
 github.com/antlr/antlr4 v0.0.0-20210105212045-464bcbc32de2/go.mod h1:T7PbCXFs94rrTttyxjbyT5+/1V8T2TYDejxUfHJjw1Y=
@@ -560,14 +560,6 @@ github.com/go-test/deep v1.0.7/go.mod h1:QV8Hv/iy04NyLBxAdO9njL0iVPN1S4d/A3NVv1V
 github.com/go-xorm/builder v0.3.4/go.mod h1:KxkQkNN1DpPKTedxXyTQcmH+rXfvk4LZ9SOOBoZBAxw=
 github.com/go-xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:56xuuqnHyryaerycW3BfssRdxQstACi0Epw/yC5E2xM=
 github.com/go-xorm/xorm v0.7.9/go.mod h1:XiVxrMMIhFkwSkh96BW7PACl7UhLtx2iJIHMdmjh5sQ=
-github.com/go-xweb/httpsession v0.0.0-20141220075701-356d3b4d38d6 h1:DUiWdm3rS8cC96Y0XeVkDeizzEK6X+qiNgXytLVtbkM=
-github.com/go-xweb/httpsession v0.0.0-20141220075701-356d3b4d38d6/go.mod h1:lwPk13GS+i/NK4FkMm68IcJrAwiu+HtjYa1Y4kW59aY=
-github.com/go-xweb/log v0.0.0-20140701090824-270d183ad77e h1:xmffs7hgrWpAOcquZrdlWpAEaAdlI9myaYcUUmhIP7k=
-github.com/go-xweb/log v0.0.0-20140701090824-270d183ad77e/go.mod h1:ASmYUSBf32lWkkNVX/pnOU4MLuUQpFH4qYHvWHt/l0w=
-github.com/go-xweb/uuid v0.0.0-20140604020037-d7dce341f851 h1:D46USD6oGNWzoJ/h5CWaFq3ELLoLoJzllJ03Xh78VYg=
-github.com/go-xweb/uuid v0.0.0-20140604020037-d7dce341f851/go.mod h1:OmDEC58ZYO1Esk+Uy32SB6LWof9lyROl7q76dBFOCWw=
-github.com/go-xweb/xweb v0.2.1 h1:u5t/ttuSfxiIMDTXj/Pouw9C2ASNABWT16JWHyrtdvY=
-github.com/go-xweb/xweb v0.2.1/go.mod h1:vPjYJgfidYAgBKIwiAyKFC1hfczlqsw9rRT8LtwrGew=
 github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
 github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
 github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg=
@@ -761,7 +753,7 @@ github.com/jhump/gopoet v0.1.0/go.mod h1:me9yfT6IJSlOL3FCfrg+L6yzUEZ+5jW6WHt4Sk+
 github.com/jhump/goprotoc v0.5.0/go.mod h1:VrbvcYrQOrTi3i0Vf+m+oqQWk9l72mjkJCYo7UvLHRQ=
 github.com/jhump/protoreflect v1.11.0/go.mod h1:U7aMIjN0NWq9swDP7xDdoMfRHb35uiuTd3Z9nFXJf5E=
 github.com/jhump/protoreflect v1.12.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
-github.com/jhump/protoreflect v1.14.0/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
+github.com/jhump/protoreflect v1.14.1/go.mod h1:JytZfP5d0r8pVNLZvai7U/MCuTWITgrI4tTg7puQFKI=
 github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
 github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
 github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
@@ -813,8 +805,6 @@ github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
 github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
 github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4=
 github.com/longbridgeapp/sqlparser v0.3.1/go.mod h1:GIHaUq8zvYyHLCLMJJykx1CdM6LHtkUih/QaJXySSx4=
-github.com/lunny/csession v0.0.0-20130910075847-fe53c5de3dfd h1:DXxmBCahjva4Ox4AWOv6pR1Csv33zSj97SaLOElfIsw=
-github.com/lunny/csession v0.0.0-20130910075847-fe53c5de3dfd/go.mod h1:3w9PScemEkJoLw3OYvLWMoD8XRCmXgGwsSpT6pFpJ0g=
 github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
 github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
 github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
@@ -838,7 +828,6 @@ github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m
 github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
 github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
 github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
-github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o=
 github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
 github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
 github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI=
@@ -1046,8 +1035,8 @@ github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64 h1:5mLPGnFdSsevFRF
 github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
 github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
 github.com/zeromicro/go-zero v1.3.5/go.mod h1:wh4o794b7Ul3W0k35Pw9nc3iB4O0OpaQTMQz/PJc1bc=
-github.com/zeromicro/go-zero v1.4.3 h1:sTQ++6fxQHJnpGCN7h2CUrhWmbvhBqEgE75cJl635SM=
-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/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=
@@ -1076,31 +1065,41 @@ go.opentelemetry.io/otel v1.0.0/go.mod h1:AjRVh9A5/5DE7S+mZtTR6t8vpKKryam+0lREnf
 go.opentelemetry.io/otel v1.3.0/go.mod h1:PWIKzi6JCp7sM0k9yZ43VX+T345uNbAkDKwHVjb2PTs=
 go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk=
 go.opentelemetry.io/otel v1.8.0/go.mod h1:2pkj+iMj0o03Y+cW6/m8Y4WkRdYN3AvCXCnzRMp9yvM=
-go.opentelemetry.io/otel v1.10.0 h1:Y7DTJMR6zs1xkS/upamJYk0SxxN4C9AqRd77jmZnyY4=
 go.opentelemetry.io/otel v1.10.0/go.mod h1:NbvWjCthWHKBEUMpf0/v8ZRZlni86PpGFEMA9pnQSnQ=
+go.opentelemetry.io/otel v1.11.0 h1:kfToEGMDq6TrVrJ9Vht84Y8y9enykSZzDDZglV0kIEk=
+go.opentelemetry.io/otel v1.11.0/go.mod h1:H2KtuEphyMvlhZ+F7tg9GRhAOe60moNx61Ex+WmiKkk=
 go.opentelemetry.io/otel/exporters/jaeger v1.8.0/go.mod h1:GbWg+ng88rDtx+id26C34QLqw2erqJeAjsCx9AFeHfE=
-go.opentelemetry.io/otel/exporters/jaeger v1.10.0 h1:7W3aVVjEYayu/GOqOVF4mbTvnCuxF1wWu3eRxFGQXvw=
 go.opentelemetry.io/otel/exporters/jaeger v1.10.0/go.mod h1:n9IGyx0fgyXXZ/i0foLHNxtET9CzXHzZeKCucvRBFgA=
-go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0 h1:TaB+1rQhddO1sF71MpZOZAuSPW1klK2M8XxfrBMfK7Y=
+go.opentelemetry.io/otel/exporters/jaeger v1.11.0 h1:Sv2valcFfMlfu6g8USSS+ZUN5vwbuGj1aY/CFtMG33w=
+go.opentelemetry.io/otel/exporters/jaeger v1.11.0/go.mod h1:nRgyJbgJ0hmaUdHwyDpTTfBYz61cTTeeGhVzfQc+FsI=
 go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.10.0/go.mod h1:78XhIg8Ht9vR4tbLNUhXsiOnE2HOuSeKAiAcoVQEpOY=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0 h1:pDDYmo0QadUPal5fwXoY1pmMpFcdyhXOmL5drCrI3vU=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0 h1:0dly5et1i/6Th3WHn0M6kYiJfFNzhhxanrJ0bOfnjEo=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.11.0/go.mod h1:+Lq4/WkdCkjbGcBMVHHg2apTbv8oMBf29QCnyCCJjNQ=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0/go.mod h1:Krqnjl22jUJ0HgMzw5eveuCvFDXY4nSYb4F8t5gdrag=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0 h1:KtiUEhQmj/Pa874bVYKGNVdq8NPKiacPbaRRtgXi+t4=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0 h1:eyJ6njZmH16h9dOKCi7lMswAnGsSOwgTqWzfxqcuNr8=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.11.0/go.mod h1:FnDp7XemjN3oZ3xGunnfOUTVwd2XcvLbtRAuOSU3oc8=
 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0/go.mod h1:OfUCyyIiDvNXHWpcWgbF+MWvqPZiNa3YDEnivcnYsV0=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0 h1:j2RFV0Qdt38XQ2Jvi4WIsQ56w8T7eSirYbMw19VXRDg=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.11.0/go.mod h1:pILgiTEtrqvZpoiuGdblDgS5dbIaTgDrkIuKfEFkt+A=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 h1:S8DedULB3gp93Rh+9Z+7NTEv+6Id/KYS7LDyipZ9iCE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0/go.mod h1:5WV40MLWwvWlGP7Xm8g3pMcg0pKOUY609qxJn8y7LmM=
 go.opentelemetry.io/otel/exporters/zipkin v1.8.0/go.mod h1:0uYAyCuGT67MFV9Z/Mmx93wGuugHw0FbxMc74fs3LNo=
-go.opentelemetry.io/otel/exporters/zipkin v1.10.0 h1:HcPAFsFpEBKF+G5NIOA+gBsxifd3Ej+wb+KsdBLa15E=
 go.opentelemetry.io/otel/exporters/zipkin v1.10.0/go.mod h1:HdfvgwcOoCB0+zzrTHycW6btjK0zNpkz2oTGO815SCI=
+go.opentelemetry.io/otel/exporters/zipkin v1.11.0 h1:v/Abo5REOWrCj4zcEIUHFZtXpsCVjrwZj28iyX2rHXE=
+go.opentelemetry.io/otel/exporters/zipkin v1.11.0/go.mod h1:unWnsLCMYfINP8ue0aXVrB/GYHoXNn/lbTnupvLekGQ=
 go.opentelemetry.io/otel/sdk v1.0.0/go.mod h1:PCrDHlSy5x1kjezSdL37PhbFUMjrsLRshJ2zCzeXwbM=
 go.opentelemetry.io/otel/sdk v1.3.0/go.mod h1:rIo4suHNhQwBIPg9axF8V9CA72Wz2mKF1teNrup8yzs=
 go.opentelemetry.io/otel/sdk v1.8.0/go.mod h1:uPSfc+yfDH2StDM/Rm35WE8gXSNdvCg023J6HeGNO0c=
-go.opentelemetry.io/otel/sdk v1.10.0 h1:jZ6K7sVn04kk/3DNUdJ4mqRlGDiXAVuIG+MMENpTNdY=
 go.opentelemetry.io/otel/sdk v1.10.0/go.mod h1:vO06iKzD5baltJz1zarxMCNHFpUlUiOy4s65ECtn6kE=
+go.opentelemetry.io/otel/sdk v1.11.0 h1:ZnKIL9V9Ztaq+ME43IUi/eo22mNsb6a7tGfzaOWB5fo=
+go.opentelemetry.io/otel/sdk v1.11.0/go.mod h1:REusa8RsyKaq0OlyangWXaw97t2VogoO4SSEeKkSTAk=
 go.opentelemetry.io/otel/trace v1.0.0/go.mod h1:PXTWqayeFUlJV1YDNhsJYB184+IvAH814St6o6ajzIs=
 go.opentelemetry.io/otel/trace v1.3.0/go.mod h1:c/VDhno8888bvQYmbYLqe41/Ldmr/KKunbvWM4/fEjk=
 go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU=
 go.opentelemetry.io/otel/trace v1.8.0/go.mod h1:0Bt3PXY8w+3pheS3hQUt+wow8b1ojPaTBoTCh2zIFI4=
-go.opentelemetry.io/otel/trace v1.10.0 h1:npQMbR8o7mum8uF95yFbOEJffhs1sbCOfDh8zAJiH5E=
 go.opentelemetry.io/otel/trace v1.10.0/go.mod h1:Sij3YYczqAdz+EhmGhE6TpTxUO5/F/AzrK+kxfGqySM=
+go.opentelemetry.io/otel/trace v1.11.0 h1:20U/Vj42SX+mASlXLmSGBg6jpI1jQtv682lZtTAOVFI=
+go.opentelemetry.io/otel/trace v1.11.0/go.mod h1:nyYjis9jy0gytE9LXGU+/m1sHTKbRY0fX0hulNNDP1U=
 go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
 go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw=
 go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U=
@@ -1379,8 +1378,9 @@ golang.org/x/sys v0.0.0-20220610221304-9f5ed59c137d/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 h1:WIoqL4EROvwiPdUtaip4VcDdpZ4kha7wBWZrbVKCIZg=
 golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 h1:h+EGohizhe9XlX18rfpa8k8RAc5XyaeamM+0VHRd4lc=
+golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=

+ 115 - 110
src/jfw/modules/subscribepay/src/rpcfollow/share.go

@@ -1,123 +1,128 @@
 package rpcfollow
 
 import (
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"encoding/json"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/entity"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"time"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "encoding/json"
+        "go.mongodb.org/mongo-driver/bson/primitive"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/entity"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "time"
 
-	qu "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	frpc "app.yhyue.com/moapp/jybase/rpc"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        qu "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        frpc "app.yhyue.com/moapp/jybase/rpc"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 //用户分享完成后,分享者和被分享者订单处理
 func (s *JyPayRpc) ShareFissionNew(p *frpc.JYShareUserIdsRes, r *frpc.JYShareResp) error {
-	if len(p.ShareUserInfo) > 0 {
-		errArr := []interface{}{}
-		for _, ps := range p.ShareUserInfo {
-			userId := ps.UserId
-			data, ok := util.MQFW.FindById("user", userId, `{"i_vip_status":1,"l_vip_starttime":1,"l_vip_endtime":1,"o_vipjy":1,"i_shareCount":1,"s_m_openid":1}`)
-			if ok && data != nil && len(*data) > 0 {
-				now := time.Now()
-				vip_status := qu.IntAll((*data)["i_vip_status"])
-				nowDay := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).Unix() //当前晚上23:59:59
-				endtime := qu.Int64All(qu.If(qu.Int64All((*data)["l_vip_endtime"]) < nowDay, nowDay, qu.Int64All((*data)["l_vip_endtime"])))
-				//更新user表
-				setMap := map[string]interface{}{}
-				var updateMap = map[string]interface{}{}
-				endT := time.Unix(endtime, 0).AddDate(0, 0, ps.TimeExpand)
-				types := 2 //默认开通权益
-				if vip_status == 2 {
-					types = 1 //仅延长周期
-					//超级订阅用户
-					updateMap = map[string]interface{}{
-						"l_vip_endtime": endT.Unix(),
-					}
-				} else if vip_status <= 0 {
-					var (
-						area      = map[string]interface{}{"北京": []string{}}
-						areaCount = 1
-					)
-					//22年双十一预热福利---2021年至今的免费用户
-					if ps.Remark == "22年双十一预热福利" {
-						//活动赠送7天  全国  超级订阅
-						area = map[string]interface{}{}
-						areaCount = -1
-					}
-					//非超级订阅用户
-					updateMap = map[string]interface{}{
-						"i_vip_status":                     2,
-						"l_vip_starttime":                  now.Unix(),
-						"l_vip_endtime":                    endT.Unix(),
-						"o_vipjy.o_area":                   area,
-						"o_vipjy.o_buyset.areacount":       areaCount,
-						"o_vipjy.o_buyset.buyerclasscount": -1,
-						"o_vipjy.o_buyset.upgrade":         1,
-						"o_vipjy.o_buyset.newcitys":        []string{},
-					}
-					if vip_status == 0 {
-						updateMap["o_vipjy.i_trial"] = -1
-						updateMap["o_vipjy.a_buyerclass"] = []string{}
-					}
-				}
-				setMap["$set"] = updateMap
-				if !util.MQFW.UpdateById("user", userId, setMap) {
-					errArr = append(errArr, map[string]interface{}{
-						"code":   -3,
-						"msg":    "更新用户超级订阅状态失败",
-						"userId": userId,
-					})
-				}
-				jy.ClearBigVipUserPower(userId)
-				st, et := "", ""
-				st = time.Unix(endtime, 0).Format(Date_Full_Layout)
-				et = endT.Format(Date_Full_Layout)
-				if !entity.Order(userId, st, et, types, ps.TimeExpand, ps.Remark) {
-					r.Error_code = -2
-					errArr = append(errArr, map[string]interface{}{
-						"code":   -2,
-						"msg":    "保存记录失败",
-						"userId": userId,
-					})
-				}
-			} else {
-				r.Error_code = -1
-				errArr = append(errArr, map[string]interface{}{
-					"code":   -1,
-					"msg":    "mgo获取用户信息失败",
-					"userId": userId,
-				})
-			}
-		}
-		if len(errArr) > 0 {
-			b, _ := json.Marshal(errArr)
-			r.Data = b
-		}
-	}
-	return nil
+        if len(p.ShareUserInfo) > 0 {
+                errArr := []interface{}{}
+                for _, ps := range p.ShareUserInfo {
+                        userId := ps.UserId
+                        _, err := primitive.ObjectIDFromHex(userId)
+                        if err!=nil{
+                                continue
+                        }
+                        data, ok := util.MQFW.FindById("user", userId, `{"i_vip_status":1,"l_vip_starttime":1,"l_vip_endtime":1,"o_vipjy":1,"i_shareCount":1,"s_m_openid":1}`)
+                        if ok && data != nil && len(*data) > 0 {
+                                now := time.Now()
+                                vip_status := qu.IntAll((*data)["i_vip_status"])
+                                nowDay := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).Unix() //当前晚上23:59:59
+                                endtime := qu.Int64All(qu.If(qu.Int64All((*data)["l_vip_endtime"]) < nowDay, nowDay, qu.Int64All((*data)["l_vip_endtime"])))
+                                //更新user表
+                                setMap := map[string]interface{}{}
+                                var updateMap = map[string]interface{}{}
+                                endT := time.Unix(endtime, 0).AddDate(0, 0, ps.TimeExpand)
+                                types := 2 //默认开通权益
+                                if vip_status == 2 {
+                                        types = 1 //仅延长周期
+                                        //超级订阅用户
+                                        updateMap = map[string]interface{}{
+                                                "l_vip_endtime": endT.Unix(),
+                                        }
+                                } else if vip_status <= 0 {
+                                        var (
+                                                area      = map[string]interface{}{"北京": []string{}}
+                                                areaCount = 1
+                                        )
+                                        //22年双十一预热福利---2021年至今的免费用户
+                                        if ps.Remark == "22年双十一预热福利" {
+                                                //活动赠送7天  全国  超级订阅
+                                                area = map[string]interface{}{}
+                                                areaCount = -1
+                                        }
+                                        //非超级订阅用户
+                                        updateMap = map[string]interface{}{
+                                                "i_vip_status":                     2,
+                                                "l_vip_starttime":                  now.Unix(),
+                                                "l_vip_endtime":                    endT.Unix(),
+                                                "o_vipjy.o_area":                   area,
+                                                "o_vipjy.o_buyset.areacount":       areaCount,
+                                                "o_vipjy.o_buyset.buyerclasscount": -1,
+                                                "o_vipjy.o_buyset.upgrade":         1,
+                                                "o_vipjy.o_buyset.newcitys":        []string{},
+                                        }
+                                        if vip_status == 0 {
+                                                updateMap["o_vipjy.i_trial"] = -1
+                                                updateMap["o_vipjy.a_buyerclass"] = []string{}
+                                        }
+                                }
+                                setMap["$set"] = updateMap
+                                if !util.MQFW.UpdateById("user", userId, setMap) {
+                                        errArr = append(errArr, map[string]interface{}{
+                                                "code":   -3,
+                                                "msg":    "更新用户超级订阅状态失败",
+                                                "userId": userId,
+                                        })
+                                }
+                                jy.ClearBigVipUserPower(userId)
+                                st, et := "", ""
+                                st = time.Unix(endtime, 0).Format(Date_Full_Layout)
+                                et = endT.Format(Date_Full_Layout)
+                                if !entity.Order(userId, st, et, types, ps.TimeExpand, ps.Remark) {
+                                        r.Error_code = -2
+                                        errArr = append(errArr, map[string]interface{}{
+                                                "code":   -2,
+                                                "msg":    "保存记录失败",
+                                                "userId": userId,
+                                        })
+                                }
+                        } else {
+                                r.Error_code = -1
+                                errArr = append(errArr, map[string]interface{}{
+                                        "code":   -1,
+                                        "msg":    "mgo获取用户信息失败",
+                                        "userId": userId,
+                                })
+                        }
+                }
+                if len(errArr) > 0 {
+                        b, _ := json.Marshal(errArr)
+                        r.Data = b
+                }
+        }
+        return nil
 }
 
 //获取用户权益信息
 func (s *JyPayRpc) GetUserPowerInfo(p *frpc.JYShareUserIdsRes, r *frpc.JYShareResp, session *httpsession.Session) error {
-	if len(p.ShareUserInfo) > 0 {
-		ps := p.ShareUserInfo[0]
-		bigBaseMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-		if bigBaseMsg == nil {
-			r.Error_code = -1
-			r.Error_msg = ps.UserId
-			r.Data = map[string]interface{}{
-				"code":   -1,
-				"msg":    "获取用户权益详情失败",
-				"userId": ps.UserId,
-			}
-		} else {
-			data, _ := json.Marshal(*bigBaseMsg)
-			r.Data = data
-		}
-	}
-	return nil
+        if len(p.ShareUserInfo) > 0 {
+                ps := p.ShareUserInfo[0]
+                bigBaseMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                if bigBaseMsg == nil {
+                        r.Error_code = -1
+                        r.Error_msg = ps.UserId
+                        r.Data = map[string]interface{}{
+                                "code":   -1,
+                                "msg":    "获取用户权益详情失败",
+                                "userId": ps.UserId,
+                        }
+                } else {
+                        data, _ := json.Marshal(*bigBaseMsg)
+                        r.Data = data
+                }
+        }
+        return nil
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 598 - 587
src/jfw/modules/subscribepay/src/service/afterPay.go


+ 87 - 80
src/jfw/modules/subscribepay/src/service/aiForecastPack.go

@@ -1,95 +1,102 @@
 package service
 
 import (
-	"encoding/json"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"time"
+        "encoding/json"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/pay"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "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/api"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type AiForecastPack struct {
-	*xweb.Action
-	createOrder xweb.Mapper `xweb:"/aiForecastPack/createOrder"` //创建订单
+        *xweb.Action
+        createOrder xweb.Mapper `xweb:"/aiForecastPack/createOrder"` //创建订单
 }
 
 // CreateOrder 创建订单
 func (a *AiForecastPack) CreateOrder() {
-	if !R.CheckReqParam(a.ResponseWriter, a.Request, "count") {
-		return
-	}
-	r := func() Result {
-		defer qutil.Catch()
-		userId := qutil.ObjToString(a.GetSession("userId"))
-		log.Println(userId)
-		if userId == "" {
-			return Result{Data: M{"status": -1}, Error_msg: "未登录"}
-		}
-		count, _ := a.GetInteger("count")
-		member_status, endtime := 0, ""
-		data, ok := util.MQFW.FindById("user", userId, `{"i_member_status":1,"s_member_mainId":1,"i_member_endtime":1}`)
-		if *data != nil && ok && len(*data) > 0 {
-			member_status = qutil.IntAll((*data)["i_member_status"])
-			mainId := qutil.ObjToString((*data)["s_member_mainId"])
-			tm := time.Unix(qutil.Int64All((*data)["i_member_endtime"]), 0)
-			endtime = tm.Format("2006/01/02")
-			if member_status < 0 || mainId != "" {
-				return Result{Data: M{"status": -1}, Error_msg: "该账号没有购买权益"}
-			}
-		}
-		order_money := getAiMoney(userId, count)
-		if order_money == -1 {
-			return Result{Data: M{"status": -1}, Error_msg: "AI预测包生成订单价格计算错误"}
-		}
-		code := pay.GetOrderCode(userId)
-		filter_map := map[string]interface{}{
-			"count":          count,
-			"level":          member_status,
-			"effective_date": endtime,
-		}
-		log.Println(filter_map)
-		filter, _ := json.Marshal(filter_map)
-		order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":    order_money,
-			"order_status":   0,
-			"filter":         string(filter),
-			"order_code":     code,
-			"product_type":   "大会员-AI中标预测包",
-			"create_time":    NowFormat(Date_Full_Layout),
-			"prepay_time":    NowFormat(Date_Full_Layout),
-			"user_id":        userId,
-			"pay_way":        "",
-			"original_price": order_money,
-			"audit_status":   3, //默认审核通过
-		})
-		log.Println("AI预测包购买订单", userId, order_id, code)
-		if order_id > 0 {
-			return Result{Data: M{"status": 1, "order_code": code}}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "AI预测包生成订单失败"}
-	}()
-	a.ServeJson(r)
+        if !R.CheckReqParam(a.ResponseWriter, a.Request, "count") {
+                return
+        }
+        r := func() Result {
+                defer qutil.Catch()
+                userId := qutil.ObjToString(a.GetSession("userId"))
+                log.Println(userId)
+                if userId == "" {
+                        return Result{Data: M{"status": -1}, Error_msg: "未登录"}
+                }
+                count, _ := a.GetInteger("count")
+                member_status, endtime := 0, ""
+                data, ok := util.MQFW.FindById("user", userId, `{"i_member_status":1,"s_member_mainId":1,"i_member_endtime":1}`)
+                if *data != nil && ok && len(*data) > 0 {
+                        member_status = qutil.IntAll((*data)["i_member_status"])
+                        mainId := qutil.ObjToString((*data)["s_member_mainId"])
+                        tm := time.Unix(qutil.Int64All((*data)["i_member_endtime"]), 0)
+                        endtime = tm.Format("2006/01/02")
+                        if member_status < 0 || mainId != "" {
+                                return Result{Data: M{"status": -1}, Error_msg: "该账号没有购买权益"}
+                        }
+                }
+                order_money := getAiMoney(userId, count)
+                if order_money == -1 {
+                        return Result{Data: M{"status": -1}, Error_msg: "AI预测包生成订单价格计算错误"}
+                }
+                code := pay.GetOrderCode(userId)
+                filter_map := map[string]interface{}{
+                        "count":          count,
+                        "level":          member_status,
+                        "effective_date": endtime,
+                }
+                log.Println(filter_map)
+                filter, _ := json.Marshal(filter_map)
+                entId := qutil.Int64All(a.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":    order_money,
+                        "order_status":   0,
+                        "filter":         string(filter),
+                        "order_code":     code,
+                        "product_type":   "大会员-AI中标预测包",
+                        "create_time":    NowFormat(Date_Full_Layout),
+                        "prepay_time":    NowFormat(Date_Full_Layout),
+                        "user_id":        userId,
+                        "pay_way":        "",
+                        "original_price": order_money,
+                        "audit_status":   3, //默认审核通过
+                        "buy_subject":    buy_subject,
+                        "ent_id":         entId,
+                })
+                log.Println("AI预测包购买订单", userId, order_id, code)
+                if order_id > 0 {
+                        return Result{Data: M{"status": 1, "order_code": code}}
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "AI预测包生成订单失败"}
+        }()
+        a.ServeJson(r)
 }
 
 func getAiMoney(userId string, count int) int {
-	if count < 1 {
-		log.Println(userId, "AI预测包count参数不合法", count)
-		return -1
-	}
-	var price float64
-	price = config.MemberConfig.AiForecastPack * float64(count)
-	if price == 0 {
-		log.Println(userId, "AI中标预测包订单获取price错误")
-		return -1
-	}
-	if price < 1 {
-		price = 1
-	}
-	return int(price)
+        if count < 1 {
+                log.Println(userId, "AI预测包count参数不合法", count)
+                return -1
+        }
+        var price float64
+        price = config.MemberConfig.AiForecastPack * float64(count)
+        if price == 0 {
+                log.Println(userId, "AI中标预测包订单获取price错误")
+                return -1
+        }
+        if price < 1 {
+                price = 1
+        }
+        return int(price)
 }

+ 193 - 183
src/jfw/modules/subscribepay/src/service/areaPack.go

@@ -1,28 +1,29 @@
 package service
 
 import (
-	"encoding/json"
-	"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"
-	"strconv"
-	"time"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "encoding/json"
+        "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"
+        "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/api"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 //省份订阅包
 type AreaPack struct {
-	*xweb.Action
-	createOrder xweb.Mapper `xweb:"/areaPack/createOrder"`
-	price       xweb.Mapper `xweb:"/areaPack/price"`
+        *xweb.Action
+        createOrder xweb.Mapper `xweb:"/areaPack/createOrder"`
+        price       xweb.Mapper `xweb:"/areaPack/price"`
 }
 
 /*
@@ -31,174 +32,183 @@ type AreaPack struct {
 */
 
 func (this *AreaPack) CreateOrder() {
-	userId, _ := this.GetSession("userId").(string)
-	if !R.CheckReqParam(this.ResponseWriter, this.Request, "orderType", "area", "unit", "num") {
-		return
-	}
-	rData, errMsg := func() (interface{}, error) {
-		orderType, _ := this.GetInteger("orderType")
-		area := qutil.ObjToMap(this.GetString("area"))
-		unit, _ := this.GetInteger("unit") //1月 2季 3年
-		num, _ := this.GetInteger("num")   //购买的数量
-		isgive := false
-		if num > entity.AreaPackPrice.ProvinceMaxCount {
-			num = -1
-		}
-		orderCode := pay.GetOrderCode()
-		now := time.Now()
-		filter := entity.AreaPackFilter{
-			Area:      area,
-			Cycleunit: unit,
-			OrderType: orderType,
-			Num:       num,
-		}
-		totalfee := 0
-		if filter.OrderType == 2 {
-			totalfee = filter.UpgradePrice(userId)
-		} else {
-			totalfee = filter.Price()
-		}
-		original_price := totalfee //原价
-		//活动相关
-		//卡卷信息的id
-		lotteryId := this.GetString("lotteryId")
-		discount_price, userLotteryId := 0, ""
-		useProduct, _ := this.GetInteger("useProduct")
-		//赠品相关
-		discountId, _ := this.GetInteger("discountId")
-		if discountId > 0 {
-			isgive = true
-			_, timeNum, timeType, _, _, _, _, _ := util.GiveInfo(userId, useProduct, 0, discountId) //获取满赠时长
-			filter.GiveCycle = timeNum
-			filter.GiveType = timeType
-			filter.DisCountId = discountId
-		} else {
-			if lotteryId != "" {
-				products := config.CouponConfig.Products[filter.ProductId()]
-				if useProduct > 0 {
-					products = strconv.Itoa(useProduct)
-				}
-				full_price, reduce_price := 0, 0
-				var discount float64
-				full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
-				if full_price <= totalfee {
-					if discount == 100 { //满减
-						totalfee = totalfee - reduce_price
-						discount_price = reduce_price
-					} else { //满折
-						disCount_int := int(math.Ceil(discount * 100))
-						discount_price = totalfee - totalfee*disCount_int/1000
-						totalfee = totalfee * disCount_int / 1000
-					}
-				} else {
-					userLotteryId = ""
-				}
-			}
-		}
-		//
-		if totalfee <= 0 {
-			return nil, fmt.Errorf("订单金额异常")
-		}
-		nickname := qutil.ObjToString(this.GetSession("s_nickname"))
-		openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
-		insertM := map[string]interface{}{
-			"order_money":          totalfee,
-			"order_status":         0,
-			"service_status":       0,
-			"user_nickname":        nickname,
-			"user_openid":          openId,
-			"user_phone":           this.GetString("order_phone"),
-			"order_code":           orderCode,
-			"product_type":         "省份订阅包",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       original_price,
-			"user_id":              userId,
-			"discount_price":       discount_price,
-			"d_relation_id":        userLotteryId,
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		}
-		//校验
-		rdata, ok := util.MQFW.FindById("user", userId, `{"o_jy":1}`)
-		if ok && rdata != nil && len(*rdata) > 0 {
-			ojy := qutil.ObjToMap((*rdata)["o_jy"])
-			area_status := qutil.IntAllDef((*ojy)["i_ppstatus"], -1)
-			if area_status == 1 && filter.OrderType == 1 { //1为非省份订阅用户可购买
-				return nil, fmt.Errorf("非法请求")
-			}
-			if area_status < 0 && filter.OrderType > 1 { //非省份订阅用户不可升级续费
-				return nil, fmt.Errorf("非法请求")
-			}
-			o_buyset_p := qutil.ObjToMap((*ojy)["o_buyset_p"])
-			count := qutil.IntAllDef((*o_buyset_p)["areacount"], 0)
-			if area_status == 1 && count == -1 && filter.OrderType == 2 {
-				return nil, fmt.Errorf("非法请求")
-			}
-			start := qutil.Int64All((*ojy)["l_areaStart_p"])
-			end := qutil.Int64All((*ojy)["l_areaEnd_p"])
-			//续费
-			if filter.OrderType == 3 {
-				startTime := time.Unix(end, 0)
-				endTime := util.GetDATE(filter.ForGetDATE(), 1, end)
-				if isgive { //满赠
-					if filter.GiveType == 1 {
-						endTime = endTime.AddDate(0, 0, filter.GiveCycle)
-					} else if filter.GiveType == 2 {
-						endTime = endTime.AddDate(0, filter.GiveCycle, 0)
-					}
-				}
-				now := time.Now()
-				if time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).
-					AddDate(3, 0, 0).Before(endTime) && !isgive {
-					return nil, fmt.Errorf("订阅周期超过三年")
-				}
-				insertM["vip_type"] = 1
-				insertM["vip_starttime"] = FormatDate(&startTime, Date_Full_Layout)
-				insertM["vip_endtime"] = FormatDate(&endTime, Date_Full_Layout)
-				//升级
-			} else if filter.OrderType == 2 {
-				s := time.Unix(start, 0)
-				e := time.Unix(end, 0)
-				insertM["vip_starttime"] = FormatDate(&s, Date_Full_Layout)
-				insertM["vip_endtime"] = FormatDate(&e, Date_Full_Layout)
-				insertM["vip_type"] = 2
-				o_buyset_p := qutil.ObjToMap((*ojy)["o_buyset_p"])
-				filter.OldNum = qutil.IntAllDef((*o_buyset_p)["areacount"], 0)
-			}
-		}
-		filterStr, _ := json.Marshal(filter)
+        userId, _ := this.GetSession("userId").(string)
+        entId := qutil.Int64All(this.GetSession("ent_id"))
+        entUserId := qutil.Int64All(this.GetSession("id"))
+        positionType := qutil.Int64All(this.GetSession("positionType"))
+        if !R.CheckReqParam(this.ResponseWriter, this.Request, "orderType", "area", "unit", "num") {
+                return
+        }
+        rData, errMsg := func() (interface{}, error) {
+                orderType, _ := this.GetInteger("orderType")
+                area := qutil.ObjToMap(this.GetString("area"))
+                unit, _ := this.GetInteger("unit") //1月 2季 3年
+                num, _ := this.GetInteger("num")   //购买的数量
+                isgive := false
+                if num > entity.AreaPackPrice.ProvinceMaxCount {
+                        num = -1
+                }
+                orderCode := pay.GetOrderCode()
+                now := time.Now()
+                filter := entity.AreaPackFilter{
+                        Area:      area,
+                        Cycleunit: unit,
+                        OrderType: orderType,
+                        Num:       num,
+                }
+                totalfee := 0
+                if filter.OrderType == 2 {
+                        totalfee = filter.UpgradePrice(userId, positionType, entId, entUserId)
+                } else {
+                        totalfee = filter.Price()
+                }
+                original_price := totalfee //原价
+                //活动相关
+                //卡卷信息的id
+                lotteryId := this.GetString("lotteryId")
+                discount_price, userLotteryId := 0, ""
+                useProduct, _ := this.GetInteger("useProduct")
+                //赠品相关
+                discountId, _ := this.GetInteger("discountId")
+                if discountId > 0 {
+                        isgive = true
+                        _, timeNum, timeType, _, _, _, _, _ := util.GiveInfo(userId, useProduct, 0, discountId) //获取满赠时长
+                        filter.GiveCycle = timeNum
+                        filter.GiveType = timeType
+                        filter.DisCountId = discountId
+                } else {
+                        if lotteryId != "" {
+                                products := config.CouponConfig.Products[filter.ProductId()]
+                                if useProduct > 0 {
+                                        products = strconv.Itoa(useProduct)
+                                }
+                                full_price, reduce_price := 0, 0
+                                var discount float64
+                                full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
+                                if full_price <= totalfee {
+                                        if discount == 100 { //满减
+                                                totalfee = totalfee - reduce_price
+                                                discount_price = reduce_price
+                                        } else { //满折
+                                                disCount_int := int(math.Ceil(discount * 100))
+                                                discount_price = totalfee - totalfee*disCount_int/1000
+                                                totalfee = totalfee * disCount_int / 1000
+                                        }
+                                } else {
+                                        userLotteryId = ""
+                                }
+                        }
+                }
+                //
+                if totalfee <= 0 {
+                        return nil, fmt.Errorf("订单金额异常")
+                }
+                nickname := qutil.ObjToString(this.GetSession("s_nickname"))
+                openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                insertM := map[string]interface{}{
+                        "order_money":          totalfee,
+                        "order_status":         0,
+                        "service_status":       0,
+                        "user_nickname":        nickname,
+                        "user_openid":          openId,
+                        "user_phone":           this.GetString("order_phone"),
+                        "order_code":           orderCode,
+                        "product_type":         "省份订阅包",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       original_price,
+                        "user_id":              userId,
+                        "discount_price":       discount_price,
+                        "d_relation_id":        userLotteryId,
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                }
+                //校验
+                //rdata, ok := util.MQFW.FindById("user", userId, `{"o_jy":1}`)
+                ojy := jy.GetSubScribeInfo(this.Session(), util.MQFW, "f", "10000")
+                if ojy != nil && len(*ojy) > 0 {
+                        area_status := qutil.IntAllDef((*ojy)["i_ppstatus"], -1)
+                        if area_status == 1 && filter.OrderType == 1 { //1为非省份订阅用户可购买
+                                return nil, fmt.Errorf("非法请求")
+                        }
+                        if area_status < 0 && filter.OrderType > 1 { //非省份订阅用户不可升级续费
+                                return nil, fmt.Errorf("非法请求")
+                        }
+                        o_buyset_p := qutil.ObjToMap((*ojy)["o_buyset_p"])
+                        count := qutil.IntAllDef((*o_buyset_p)["areacount"], 0)
+                        if area_status == 1 && count == -1 && filter.OrderType == 2 {
+                                return nil, fmt.Errorf("非法请求")
+                        }
+                        start := qutil.Int64All((*ojy)["l_areaStart_p"])
+                        end := qutil.Int64All((*ojy)["l_areaEnd_p"])
+                        //续费
+                        if filter.OrderType == 3 {
+                                startTime := time.Unix(end, 0)
+                                endTime := util.GetDATE(filter.ForGetDATE(), 1, end)
+                                if isgive { //满赠
+                                        if filter.GiveType == 1 {
+                                                endTime = endTime.AddDate(0, 0, filter.GiveCycle)
+                                        } else if filter.GiveType == 2 {
+                                                endTime = endTime.AddDate(0, filter.GiveCycle, 0)
+                                        }
+                                }
+                                now := time.Now()
+                                if time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).
+                                        AddDate(3, 0, 0).Before(endTime) && !isgive {
+                                        return nil, fmt.Errorf("订阅周期超过三年")
+                                }
+                                insertM["vip_type"] = 1
+                                insertM["vip_starttime"] = FormatDate(&startTime, Date_Full_Layout)
+                                insertM["vip_endtime"] = FormatDate(&endTime, Date_Full_Layout)
+                                //升级
+                        } else if filter.OrderType == 2 {
+                                s := time.Unix(start, 0)
+                                e := time.Unix(end, 0)
+                                insertM["vip_starttime"] = FormatDate(&s, Date_Full_Layout)
+                                insertM["vip_endtime"] = FormatDate(&e, Date_Full_Layout)
+                                insertM["vip_type"] = 2
+                                o_buyset_p := qutil.ObjToMap((*ojy)["o_buyset_p"])
+                                filter.OldNum = qutil.IntAllDef((*o_buyset_p)["areacount"], 0)
+                        }
+                }
+                filterStr, _ := json.Marshal(filter)
 
-		insertM["filter"] = string(filterStr)
-		orderid := util.Mysql.Insert("dataexport_order", insertM)
-		if orderid <= 0 {
-			return nil, fmt.Errorf("创建订单异常")
-		}
-		//绑定卡卷
-		if (userLotteryId != "" && lotteryId != "") || (discountId > 0) {
-			go func(userId, userLotteryId, order_code string) {
-				phone, nickname := util.GetMyPhoneAndName(userId)
-				if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "省份订阅包", strconv.Itoa(discountId), 3, 0) {
-					log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-				}
-				if discountId > 0 {
-					if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
-						userLotteryId = strconv.Itoa(ulid)
-					}
-				}
-			}(userId, userLotteryId, orderCode)
-		}
-		return map[string]interface{}{
-			"orderCode": orderCode,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s AreaPack CreateOrder 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                insertM["filter"] = string(filterStr)
+                orderid := util.Mysql.Insert("dataexport_order", insertM)
+                if orderid <= 0 {
+                        return nil, fmt.Errorf("创建订单异常")
+                }
+                //绑定卡卷
+                if (userLotteryId != "" && lotteryId != "") || (discountId > 0) {
+                        go func(userId, userLotteryId, order_code string) {
+                                phone, nickname := util.GetMyPhoneAndName(userId)
+                                if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "省份订阅包", strconv.Itoa(discountId), 3, 0) {
+                                        log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                                }
+                                if discountId > 0 {
+                                        if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
+                                                userLotteryId = strconv.Itoa(ulid)
+                                        }
+                                }
+                        }(userId, userLotteryId, orderCode)
+                }
+                return map[string]interface{}{
+                        "orderCode": orderCode,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s AreaPack CreateOrder 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 func (this *AreaPack) Price() {
-	this.ServeJson(entity.AreaPackPrice)
+        this.ServeJson(entity.AreaPackPrice)
 }

+ 75 - 68
src/jfw/modules/subscribepay/src/service/bidfile.go

@@ -1,87 +1,94 @@
 package service
 
 import (
-	"encoding/json"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"time"
+        "encoding/json"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/pay"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "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/api"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
 )
 
 type Bidfile struct {
-	*xweb.Action
-	createOrder xweb.Mapper `xweb:"/bidfile/createOrder"` //创建订单
+        *xweb.Action
+        createOrder xweb.Mapper `xweb:"/bidfile/createOrder"` //创建订单
 }
 
 //创建订单 from -bigmember 大会员补充包产生的订单  -pc PC端购买
 func (b *Bidfile) CreateOrder() {
-	if !R.CheckReqParam(b.ResponseWriter, b.Request, "count", "from") {
-		return
-	}
-	r := func() Result {
-		defer qutil.Catch()
-		userId := qutil.ObjToString(b.GetSession("userId"))
-		if userId == "" {
-			return Result{Data: M{"status": -1}, Error_msg: "未登录"}
-		}
-		Product_type := "招标文件解读"
-		count, _ := b.GetInteger("count")
-		order_money := float64(count) * config.BidfileConfig.Price
-		if order_money == -1 {
-			return Result{Data: M{"status": -1}, Error_msg: "招标文件解读生成订单价格计算错误"}
-		}
-		code := pay.GetOrderCode(userId)
-		from := b.GetString("from")
-		filter_map := map[string]interface{}{
-			"count": count,
-		}
-		if from == "bigmember" { //大会员购买的订单
-			Product_type = "大会员-招标文件解读"
-			effective_date := EndMember(userId)
-			filter_map["effective_date"] = effective_date
-		}
-		filter, _ := json.Marshal(filter_map)
-		order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":    order_money,
-			"order_status":   0,
-			"filter":         string(filter),
-			"order_code":     code,
-			"product_type":   Product_type,
-			"create_time":    NowFormat(Date_Full_Layout),
-			"prepay_time":    NowFormat(Date_Full_Layout),
-			"user_id":        userId,
-			"pay_way":        "",
-			"original_price": order_money,
-		})
-		if order_id > 0 {
-			return Result{Data: M{"status": 1, "order_code": code}}
-		}
-		return Result{Data: M{"status": -1}, Error_msg: "招标文件解读生成订单失败"}
-	}()
-	b.ServeJson(r)
+        if !R.CheckReqParam(b.ResponseWriter, b.Request, "count", "from") {
+                return
+        }
+        r := func() Result {
+                defer qutil.Catch()
+                userId := qutil.ObjToString(b.GetSession("userId"))
+                if userId == "" {
+                        return Result{Data: M{"status": -1}, Error_msg: "未登录"}
+                }
+                Product_type := "招标文件解读"
+                count, _ := b.GetInteger("count")
+                order_money := float64(count) * config.BidfileConfig.Price
+                if order_money == -1 {
+                        return Result{Data: M{"status": -1}, Error_msg: "招标文件解读生成订单价格计算错误"}
+                }
+                code := pay.GetOrderCode(userId)
+                from := b.GetString("from")
+                filter_map := map[string]interface{}{
+                        "count": count,
+                }
+                if from == "bigmember" { //大会员购买的订单
+                        Product_type = "大会员-招标文件解读"
+                        effective_date := EndMember(userId)
+                        filter_map["effective_date"] = effective_date
+                }
+                filter, _ := json.Marshal(filter_map)
+                entId := qutil.Int64All(b.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":    order_money,
+                        "order_status":   0,
+                        "filter":         string(filter),
+                        "order_code":     code,
+                        "product_type":   Product_type,
+                        "create_time":    NowFormat(Date_Full_Layout),
+                        "prepay_time":    NowFormat(Date_Full_Layout),
+                        "user_id":        userId,
+                        "pay_way":        "",
+                        "original_price": order_money,
+                        "buy_subject":    buy_subject,
+                        "ent_id":         entId,
+                })
+                if order_id > 0 {
+                        return Result{Data: M{"status": 1, "order_code": code}}
+                }
+                return Result{Data: M{"status": -1}, Error_msg: "招标文件解读生成订单失败"}
+        }()
+        b.ServeJson(r)
 }
 
 //
 func EndMember(userid string) (bidfile_endtime string) {
-	bidfile_endtime = "2021年11月15日" //目前招标文件解读到11/15到期
-	bed := GetTime("2006年01月02日", bidfile_endtime)
-	data, ok := util.MQFW.FindById("user", userid, `{"i_member_endtime":1}`)
-	if data != nil && ok && len(*data) > 0 {
-		endtime := qutil.Int64All((*data)["i_member_endtime"])
-		et := time.Unix(endtime, 0)
-		if bed.After(et) {
-			bidfile_endtime = et.Format("2006年01月02日")
-		}
-	}
-	return
+        bidfile_endtime = "2021年11月15日" //目前招标文件解读到11/15到期
+        bed := GetTime("2006年01月02日", bidfile_endtime)
+        data, ok := util.MQFW.FindById("user", userid, `{"i_member_endtime":1}`)
+        if data != nil && ok && len(*data) > 0 {
+                endtime := qutil.Int64All((*data)["i_member_endtime"])
+                et := time.Unix(endtime, 0)
+                if bed.After(et) {
+                        bidfile_endtime = et.Format("2006年01月02日")
+                }
+        }
+        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
 }

+ 120 - 113
src/jfw/modules/subscribepay/src/service/bigmember.go

@@ -1,133 +1,140 @@
 package service
 
 import (
-	"encoding/json"
-	"errors"
-	"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"
+        "encoding/json"
+        "errors"
+        "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"
 
-	. "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/jypkg/common/src/qfw/util/jy"
+        . "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/jypkg/common/src/qfw/util/jy"
 )
 
 type Bigmember struct {
-	*xweb.Action
-	createOrderCheck xweb.Mapper `xweb:"/bigmember/createOrderCheck"` //是否可以支付
-	createOrder      xweb.Mapper `xweb:"/bigmember/createOrder"`      //创建订单
-	price            xweb.Mapper `xweb:"/bigmember/price"`            //价格计算
+        *xweb.Action
+        createOrderCheck xweb.Mapper `xweb:"/bigmember/createOrderCheck"` //是否可以支付
+        createOrder      xweb.Mapper `xweb:"/bigmember/createOrder"`      //创建订单
+        price            xweb.Mapper `xweb:"/bigmember/price"`            //价格计算
 }
 
 func (this *Bigmember) CreateOrderCheck() {
-	rData, errMsg := func() (interface{}, error) {
-		userId := qutil.ObjToString(this.GetSession("userId"))
-		if userId == "" {
-			return nil, errors.New("未登录")
-		}
-		//校验是否有转账待审核订单
-		num := util.Mysql.Count("dataexport_order", map[string]interface{}{
-			"user_id":       userId,
-			"product_type":  "大会员",
-			"order_status":  0,
-			"course_status": 2,
-		})
-		//校验是否是大会员
-		vipStatus := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-		return map[string]interface{}{
-			"vipStatus":        vipStatus.Status,
-			"hasPid":           vipStatus.Pid != "",
-			"hasAccountsOrder": num > 0,
-		}, nil
-	}()
-	this.ServeJson(NewResult(rData, errMsg))
+        rData, errMsg := func() (interface{}, error) {
+                userId := qutil.ObjToString(this.GetSession("userId"))
+                if userId == "" {
+                        return nil, errors.New("未登录")
+                }
+                //校验是否有转账待审核订单
+                num := util.Mysql.Count("dataexport_order", map[string]interface{}{
+                        "user_id":       userId,
+                        "product_type":  "大会员",
+                        "order_status":  0,
+                        "course_status": 2,
+                })
+                //校验是否是大会员
+                vipStatus := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                return map[string]interface{}{
+                        "vipStatus":        vipStatus.Status,
+                        "hasPid":           vipStatus.Pid != "",
+                        "hasAccountsOrder": num > 0,
+                }, nil
+        }()
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //创建订单
 func (b *Bigmember) CreateOrder() {
-	if !R.CheckReqParam(b.ResponseWriter, b.Request, "level", "cycle") {
-		return
-	}
-	r := func() Result {
-		defer qutil.Catch()
-		userId := qutil.ObjToString(b.GetSession("userId"))
-		if userId == "" {
-			return Result{-1, "未登录", nil}
-		}
-		//校验是否有转账待审核订单
-		num := util.Mysql.Count("dataexport_order", map[string]interface{}{
-			"user_id":       userId,
-			"product_type":  "大会员",
-			"order_status":  0,
-			"course_status": 2,
-		})
-		if num > 0 {
-			return Result{-1, "有待审核订单", nil}
-		}
+        if !R.CheckReqParam(b.ResponseWriter, b.Request, "level", "cycle") {
+                return
+        }
+        r := func() Result {
+                defer qutil.Catch()
+                userId := qutil.ObjToString(b.GetSession("userId"))
+                if userId == "" {
+                        return Result{-1, "未登录", nil}
+                }
+                //校验是否有转账待审核订单
+                num := util.Mysql.Count("dataexport_order", map[string]interface{}{
+                        "user_id":       userId,
+                        "product_type":  "大会员",
+                        "order_status":  0,
+                        "course_status": 2,
+                })
+                if num > 0 {
+                        return Result{-1, "有待审核订单", nil}
+                }
 
-		level, _ := b.GetInteger("level") //1:专业版;2:智慧版;3:商机版;4:试用版 5:试用版 6:商机版2.0 7:专家版2.0
-		cycle, _ := b.GetInteger("cycle")
-		//校验是否是大会员
-		vipStatus := jy.GetBigVipUserBaseMsg("10000", b.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-		if vipStatus.Status > 0 && vipStatus.Status != 4 { //已经是大会员
-			return Result{-1, "您已经是大会员用户", nil}
-		}
-		if vipStatus.Status > 0 && vipStatus.Status == 4 && level == 4 {
-			return Result{-1, "您已经是大会员用户-试用版", nil}
-		}
-		order_money := entity.MemberStruct.GetMoney(userId, level, cycle)
-		if order_money == -1 {
-			return Result{-1, "大会员生成订单价格计算错误", nil}
-		}
-		code := pay.GetOrderCode(userId)
-		filter_map := map[string]interface{}{
-			"cycle": cycle,
-			"level": level,
-		}
-		filter, _ := json.Marshal(filter_map)
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", b.Header("User-Agent"))
-		insertObj := map[string]interface{}{
-			"order_money":          order_money,
-			"order_status":         0,
-			"filter":               string(filter),
-			"order_code":           code,
-			"product_type":         "大会员",
-			"create_time":          NowFormat(Date_Full_Layout),
-			"prepay_time":          NowFormat(Date_Full_Layout),
-			"user_id":              userId,
-			"pay_way":              "",
-			"original_price":       order_money,
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		}
-		order_phone := b.GetString("order_phone") //p19.3用户信息采集 手机号
-		if order_phone != "" {
-			if !jy.PhoneReg.MatchString(order_phone) {
-				return Result{-1, "手机号格式异常", nil}
-			}
-			insertObj["user_phone"] = order_phone
-		}
-		order_id := util.Mysql.Insert("dataexport_order", insertObj)
-		if order_id > 0 {
-			return Result{0, "", M{"order_code": code}}
-		}
-		return Result{-1, "大会员生成订单失败", nil}
-	}()
-	b.ServeJson(r)
+                level, _ := b.GetInteger("level") //1:专业版;2:智慧版;3:商机版;4:试用版 5:试用版 6:商机版2.0 7:专家版2.0
+                cycle, _ := b.GetInteger("cycle")
+                //校验是否是大会员
+                vipStatus := jy.GetBigVipUserBaseMsg("10000", b.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                if vipStatus.Status > 0 && vipStatus.Status != 4 { //已经是大会员
+                        return Result{-1, "您已经是大会员用户", nil}
+                }
+                if vipStatus.Status > 0 && vipStatus.Status == 4 && level == 4 {
+                        return Result{-1, "您已经是大会员用户-试用版", nil}
+                }
+                order_money := entity.MemberStruct.GetMoney(userId, level, cycle)
+                if order_money == -1 {
+                        return Result{-1, "大会员生成订单价格计算错误", nil}
+                }
+                code := pay.GetOrderCode(userId)
+                filter_map := map[string]interface{}{
+                        "cycle": cycle,
+                        "level": level,
+                }
+                filter, _ := json.Marshal(filter_map)
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", b.Header("User-Agent"))
+                entId := qutil.Int64All(b.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                insertObj := map[string]interface{}{
+                        "order_money":          order_money,
+                        "order_status":         0,
+                        "filter":               string(filter),
+                        "order_code":           code,
+                        "product_type":         "大会员",
+                        "create_time":          NowFormat(Date_Full_Layout),
+                        "prepay_time":          NowFormat(Date_Full_Layout),
+                        "user_id":              userId,
+                        "pay_way":              "",
+                        "original_price":       order_money,
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                }
+                order_phone := b.GetString("order_phone") //p19.3用户信息采集 手机号
+                if order_phone != "" {
+                        if !jy.PhoneReg.MatchString(order_phone) {
+                                return Result{-1, "手机号格式异常", nil}
+                        }
+                        insertObj["user_phone"] = order_phone
+                }
+                order_id := util.Mysql.Insert("dataexport_order", insertObj)
+                if order_id > 0 {
+                        return Result{0, "", M{"order_code": code}}
+                }
+                return Result{-1, "大会员生成订单失败", nil}
+        }()
+        b.ServeJson(r)
 }
 
 //价格计算
 func (this *Bigmember) Price() {
-	level, _ := this.GetInteger("level") //1:专业版;2:智慧版;3:商机版;4:试用版
-	cycle, _ := this.GetInteger("cycle")
-	price := entity.MemberStruct.GetMoney("", level, cycle)
-	this.ServeJson(Result{0, "", M{
-		"money":         config.MemberConfig.Price,
-		"price":         price,
-		"originalPrice": config.MemberConfig.OriginalPrice,
-	}})
+        level, _ := this.GetInteger("level") //1:专业版;2:智慧版;3:商机版;4:试用版
+        cycle, _ := this.GetInteger("cycle")
+        price := entity.MemberStruct.GetMoney("", level, cycle)
+        this.ServeJson(Result{0, "", M{
+                "money":         config.MemberConfig.Price,
+                "price":         price,
+                "originalPrice": config.MemberConfig.OriginalPrice,
+        }})
 }

+ 550 - 543
src/jfw/modules/subscribepay/src/service/commonAction.go

@@ -1,178 +1,178 @@
 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/rpc"
-	"regexp"
-	"strconv"
-	"strings"
-	"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/rpc"
+        "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"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
-	"app.yhyue.com/moapp/jybase/go-xweb/xweb"
-	. "app.yhyue.com/moapp/jybase/mongodb"
-	"app.yhyue.com/moapp/jybase/redis"
-	"github.com/SKatiyar/qr"
-	"go.mongodb.org/mongo-driver/bson"
+        . "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"
+        elastic "app.yhyue.com/moapp/jybase/esv1"
+        "app.yhyue.com/moapp/jybase/go-xweb/xweb"
+        . "app.yhyue.com/moapp/jybase/mongodb"
+        "app.yhyue.com/moapp/jybase/redis"
+        "github.com/SKatiyar/qr"
+        "go.mongodb.org/mongo-driver/bson"
 )
 
 //付费公用方法
 type CommonAction struct {
-	*xweb.Action
-	getwxSdkSign         xweb.Mapper `xweb:"/wx/getwxSdkSign"`             //微信js参数
-	getDomain            xweb.Mapper `xweb:"/getDomain"`                   //微信js参数
-	getCommonOrderPrice  xweb.Mapper `xweb:"/common/getOrderPrice"`        //获取订单价格
-	getCommonPayParam    xweb.Mapper `xweb:"/common/getPayParam"`          //公共获取支付方法
-	saveTransferAccounts xweb.Mapper `xweb:"/common/saveTransferAccounts"` //公共对公转账接口
-	isPaySuccess         xweb.Mapper `xweb:"/isPaySuccess"`                //是否支付成功
-	deleteOrder          xweb.Mapper `xweb:"/deleteOrder"`                 //删除订单
-	applyInvoice         xweb.Mapper `xweb:"/applyInvoice"`                //申请发票
-	sendMailNote         xweb.Mapper `xweb:"/sendMailNote/(.*)"`           //发送附件邮件通知
-	createorder          xweb.Mapper `xweb:"/common/createorder"`          //创建订单公共方法
+        *xweb.Action
+        getwxSdkSign         xweb.Mapper `xweb:"/wx/getwxSdkSign"`             //微信js参数
+        getDomain            xweb.Mapper `xweb:"/getDomain"`                   //微信js参数
+        getCommonOrderPrice  xweb.Mapper `xweb:"/common/getOrderPrice"`        //获取订单价格
+        getCommonPayParam    xweb.Mapper `xweb:"/common/getPayParam"`          //公共获取支付方法
+        saveTransferAccounts xweb.Mapper `xweb:"/common/saveTransferAccounts"` //公共对公转账接口
+        isPaySuccess         xweb.Mapper `xweb:"/isPaySuccess"`                //是否支付成功
+        deleteOrder          xweb.Mapper `xweb:"/deleteOrder"`                 //删除订单
+        applyInvoice         xweb.Mapper `xweb:"/applyInvoice"`                //申请发票
+        sendMailNote         xweb.Mapper `xweb:"/sendMailNote/(.*)"`           //发送附件邮件通知
+        createorder          xweb.Mapper `xweb:"/common/createorder"`          //创建订单公共方法
 }
 
 var pdfNameReg = regexp.MustCompilePOSIX(`[^//]*\.pdf`)
 
 func (this *CommonAction) GetDomain() {
-	this.ServeJson(NewResult(map[string]interface{}{
-		"web": config.Config.WebDomain,
-		"app": config.Config.AppDomain,
-		"wx":  config.Config.WxDomain,
-	}, nil))
+        this.ServeJson(NewResult(map[string]interface{}{
+                "web": config.Config.WebDomain,
+                "app": config.Config.AppDomain,
+                "wx":  config.Config.WxDomain,
+        }, nil))
 }
 
 func (this *CommonAction) SendMailNote(mailType string) {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		downurl := this.GetString("downurl")
-		userMail := this.GetString("email")
-		if downurl == "" || userMail == "" {
-			return nil, fmt.Errorf("缺少字段")
-		}
-		//mailShowName := "附件"
-		detail := "您好,您的附件已发送到您的邮箱,请查收!"
-		mail_title := "剑鱼标讯"
-		switch mailType {
-		case "projectPdfFile":
-			mail_title = "项目报告"
-			detail = "您好,您的“%s”项目报告已发送到您的邮箱,请查收!"
-			projectName, pid := "", ""
-			strArr := pdfNameReg.FindStringSubmatch(downurl)
-			if len(strArr) != 1 {
-				return nil, fmt.Errorf("发送异常")
-			}
-			if arr := strings.Split(strings.ReplaceAll(strArr[0], ".pdf", ""), "_"); len(arr) != 0 {
-				pid = arr[0]
-			}
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                downurl := this.GetString("downurl")
+                userMail := this.GetString("email")
+                if downurl == "" || userMail == "" {
+                        return nil, fmt.Errorf("缺少字段")
+                }
+                //mailShowName := "附件"
+                detail := "您好,您的附件已发送到您的邮箱,请查收!"
+                mail_title := "剑鱼标讯"
+                switch mailType {
+                case "projectPdfFile":
+                        mail_title = "项目报告"
+                        detail = "您好,您的“%s”项目报告已发送到您的邮箱,请查收!"
+                        projectName, pid := "", ""
+                        strArr := pdfNameReg.FindStringSubmatch(downurl)
+                        if len(strArr) != 1 {
+                                return nil, fmt.Errorf("发送异常")
+                        }
+                        if arr := strings.Split(strings.ReplaceAll(strArr[0], ".pdf", ""), "_"); len(arr) != 0 {
+                                pid = arr[0]
+                        }
 
-			if pid != "" {
-				res := elastic.Get("projectset", "projectset", fmt.Sprintf(`{"query": {"bool": {"must": [{"term": {"_id": "%s"}}]}},"_source":["projectname"],"from": 0,"size": 1}`, pid))
-				if res != nil && len(*res) == 1 {
-					projectName, _ = (*res)[0]["projectname"].(string)
-				}
-			}
-			detail = fmt.Sprintf("您好,您的“%s”项目报告已发送到您的邮箱,请查收!", projectName)
-		}
-		if !(strings.HasPrefix(downurl, "https://") || strings.HasPrefix(downurl, "http://")) {
-			downurl = config.Config.WebDomain + downurl
-		}
-		mailContent := fmt.Sprintf(config.ExConf.Mail_attach_common_attachment, detail, downurl)
-		//用户发送邮件
-		sendOk := false
-		if userMail != "" {
-			if sendOk = util.SendRetryMail(config.ExConf.Mail_retry, userMail, mail_title, mailContent, "", nil, config.GmailAuth); sendOk {
-				log.Printf("DataExportPack SendMailNote 地址%s:邮箱%s邮件发送成功!", downurl, userMail)
-			} else {
-				sendErr := fmt.Sprintf("DataExportPack SendMailNote%s:邮箱%s邮件发送失败", downurl, userMail)
-				log.Printf("%s DataExportPack SendMailNote 发送邮件失败 %v\n", userId, sendErr)
-			}
-		}
-		return sendOk, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack SendExportMail 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                        if pid != "" {
+                                res := elastic.Get("projectset", "projectset", fmt.Sprintf(`{"query": {"bool": {"must": [{"term": {"_id": "%s"}}]}},"_source":["projectname"],"from": 0,"size": 1}`, pid))
+                                if res != nil && len(*res) == 1 {
+                                        projectName, _ = (*res)[0]["projectname"].(string)
+                                }
+                        }
+                        detail = fmt.Sprintf("您好,您的“%s”项目报告已发送到您的邮箱,请查收!", projectName)
+                }
+                if !(strings.HasPrefix(downurl, "https://") || strings.HasPrefix(downurl, "http://")) {
+                        downurl = config.Config.WebDomain + downurl
+                }
+                mailContent := fmt.Sprintf(config.ExConf.Mail_attach_common_attachment, detail, downurl)
+                //用户发送邮件
+                sendOk := false
+                if userMail != "" {
+                        if sendOk = util.SendRetryMail(config.ExConf.Mail_retry, userMail, mail_title, mailContent, "", nil, config.GmailAuth); sendOk {
+                                log.Printf("DataExportPack SendMailNote 地址%s:邮箱%s邮件发送成功!", downurl, userMail)
+                        } else {
+                                sendErr := fmt.Sprintf("DataExportPack SendMailNote%s:邮箱%s邮件发送失败", downurl, userMail)
+                                log.Printf("%s DataExportPack SendMailNote 发送邮件失败 %v\n", userId, sendErr)
+                        }
+                }
+                return sendOk, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack SendExportMail 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 //----------------------------申请发票------------------------------------
 func (d *CommonAction) ApplyInvoice() error {
-	var applyBill_status int
-	var order_code, applyBill_company, applyBill_taxnum, applyBill_type string
-	var updateBl bool = false
-	order_code = d.GetString("order_code")
-	//获取数据
-	applyBill_type = d.GetString("demo-radio") //个人 单位
-	queryMap := map[string]interface{}{
-		"order_code": order_code,
-	}
-	my_email, product := "", ""
-	product_type := util.Mysql.FindOne("dataexport_order", queryMap, "product_type", "")
-	if product_type != nil {
-		product = qutil.ObjToString((*product_type)["product_type"])
-	}
-	if product == "VIP订阅" {
-		//获取开发票时 用户所绑定的邮箱 user--s_myemail
-		email, _ := util.MQFW.FindOneByField("user", bson.M{"_id": StringTOBsonId(qutil.ObjToString(d.GetSession("userId")))}, `{"s_myemail":1}`)
-		if len(*email) > 0 {
-			my_email = qutil.ObjToString((*email)["s_myemail"])
-		}
-	}
-	if applyBill_type == "个人" {
-		applyBill_status = 1
-		if product == "VIP订阅" && my_email != "" {
-			updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{"applyBill_status": applyBill_status, "user_mail": my_email})
-		} else {
-			updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{"applyBill_status": applyBill_status})
-		}
-	} else if applyBill_type == "单位" {
-		applyBill_status = 1                                 //状态
-		applyBill_company = d.GetString("applyBill_company") //公司名
-		applyBill_taxnum = d.GetString("applyBill_taxnum")   //纳税人识别号
-		if product == "VIP订阅" && my_email != "" {
-			updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{
-				"applyBill_company": applyBill_company,
-				"applyBill_taxnum":  applyBill_taxnum,
-				"applyBill_status":  applyBill_status,
-				"applyBill_type":    1,
-				"user_mail":         my_email,
-			}) //修改操作
-		} else {
-			updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{
-				"applyBill_company": applyBill_company,
-				"applyBill_taxnum":  applyBill_taxnum,
-				"applyBill_status":  applyBill_status,
-				"applyBill_type":    1,
-			}) //修改操作
-		}
-	}
-	//判断条件
-	if updateBl {
-		go func() {
-			orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-				"order_code": order_code,
-			}, "id,filter,user_mail,user_phone,product_type,data_spec,filter_id,order_code,data_count,order_status,order_money,out_trade_no,applybill_type,applybill_company,applybill_taxnum,user_openid,create_time,pay_time,pay_way,pay_money,vip_starttime,vip_endtime,user_id,vip_type", "")
-			tt := time.Now()
-			pay_time := FormatDate(&tt, Date_Full_Layout)
-			entity.SendMailToBJFinance(orderdata, pay_time, "", 2, config.GmailAuth)
-		}()
-	}
-	d.ServeJson(map[string]interface{}{
-		"flag": updateBl,
-	})
-	return nil
+        var applyBill_status int
+        var order_code, applyBill_company, applyBill_taxnum, applyBill_type string
+        var updateBl bool = false
+        order_code = d.GetString("order_code")
+        //获取数据
+        applyBill_type = d.GetString("demo-radio") //个人 单位
+        queryMap := map[string]interface{}{
+                "order_code": order_code,
+        }
+        my_email, product := "", ""
+        product_type := util.Mysql.FindOne("dataexport_order", queryMap, "product_type", "")
+        if product_type != nil {
+                product = qutil.ObjToString((*product_type)["product_type"])
+        }
+        if product == "VIP订阅" {
+                //获取开发票时 用户所绑定的邮箱 user--s_myemail
+                email, _ := util.MQFW.FindOneByField("user", bson.M{"_id": StringTOBsonId(qutil.ObjToString(d.GetSession("userId")))}, `{"s_myemail":1}`)
+                if len(*email) > 0 {
+                        my_email = qutil.ObjToString((*email)["s_myemail"])
+                }
+        }
+        if applyBill_type == "个人" {
+                applyBill_status = 1
+                if product == "VIP订阅" && my_email != "" {
+                        updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{"applyBill_status": applyBill_status, "user_mail": my_email})
+                } else {
+                        updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{"applyBill_status": applyBill_status})
+                }
+        } else if applyBill_type == "单位" {
+                applyBill_status = 1                                 //状态
+                applyBill_company = d.GetString("applyBill_company") //公司名
+                applyBill_taxnum = d.GetString("applyBill_taxnum")   //纳税人识别号
+                if product == "VIP订阅" && my_email != "" {
+                        updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{
+                                "applyBill_company": applyBill_company,
+                                "applyBill_taxnum":  applyBill_taxnum,
+                                "applyBill_status":  applyBill_status,
+                                "applyBill_type":    1,
+                                "user_mail":         my_email,
+                        }) //修改操作
+                } else {
+                        updateBl = util.Mysql.Update("dataexport_order", queryMap, map[string]interface{}{
+                                "applyBill_company": applyBill_company,
+                                "applyBill_taxnum":  applyBill_taxnum,
+                                "applyBill_status":  applyBill_status,
+                                "applyBill_type":    1,
+                        }) //修改操作
+                }
+        }
+        //判断条件
+        if updateBl {
+                go func() {
+                        orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                                "order_code": order_code,
+                        }, "id,filter,user_mail,user_phone,product_type,data_spec,filter_id,order_code,data_count,order_status,order_money,out_trade_no,applybill_type,applybill_company,applybill_taxnum,user_openid,create_time,pay_time,pay_way,pay_money,vip_starttime,vip_endtime,user_id,vip_type", "")
+                        tt := time.Now()
+                        pay_time := FormatDate(&tt, Date_Full_Layout)
+                        entity.SendMailToBJFinance(orderdata, pay_time, "", 2, config.GmailAuth)
+                }()
+        }
+        d.ServeJson(map[string]interface{}{
+                "flag": updateBl,
+        })
+        return nil
 }
 
 /**
@@ -180,129 +180,129 @@ func (d *CommonAction) ApplyInvoice() error {
 根据 id+openid 删除
 */
 func (d *CommonAction) DeleteOrder() error {
-	if userId := d.GetSession("userId"); userId != nil {
-		queryMap := map[string]interface{}{
-			"id":      d.GetString("id"),
-			"user_id": userId.(string),
-		}
-		flag := false
-		order := util.Mysql.FindOne(tableName_order, queryMap, "filter,product_type,pay_way,out_trade_no,prepay_time,order_status,order_code,discount_price,d_relation_id,user_id", "")
-		if order != nil {
-			if qutil.IntAll((*order)["order_status"]) == 0 && qutil.ObjToString((*order)["pay_way"]) != "transferAccounts" { //未支付状态下 删除订单需要先关闭订单
-				flag = pay.CloseDataExportOrder(qutil.ObjToString((*order)["pay_way"]), qutil.ObjToString((*order)["out_trade_no"]), qutil.ObjToString((*order)["prepay_time"]))
-				//未支付 非对公转账
-				//卡卷取消绑定
-				userLotteryId := qutil.ObjToString((*order)["d_relation_id"])
-				if userLotteryId != "" {
-					productType := 0 //商品类型0普通的1线上课程
-					if product_type := qutil.ObjToString((*order)["product_type"]); product_type == "中标必听课" {
-						productType = 1
-					}
-					discountId := ""
-					var filter map[string]interface{}
-					//关闭未支付订单
-					if err := json.Unmarshal([]byte(qutil.ObjToString((*order)["filter"])), &filter); err != nil {
-						log.Println("filter.json.Unmarshal出错", err)
-					} else {
-						if filter["discountId"] != nil {
-							discountId = strconv.Itoa(qutil.IntAll(filter["discountId"]))
-						}
-					}
-					order_code := qutil.ObjToString((*order)["order_code"])
-					user_id := qutil.ObjToString((*order)["user_id"])
-					go func(userId, userLotteryId, order_code string) {
-						if !util.UpdateCouponState(userId, userLotteryId, qutil.ObjToString(d.GetSession("s_nickname")), qutil.ObjToString(d.GetSession("phone")), order_code, qutil.ObjToString((*order)["product_type"]), discountId, 0, productType) {
-							log.Println(fmt.Sprintf("单号%s-解绑失败-卡卷%s", order_code, userLotteryId))
-						}
-					}(user_id, userLotteryId, order_code)
-				}
-			} else {
-				flag = true
-			}
-		}
-		if flag {
-			now := time.Now()
-			flag = util.Mysql.Update(tableName_order, queryMap, map[string]interface{}{"del_status": 1, "del_time": FormatDate(&now, Date_Full_Layout)})
-		}
-		d.ServeJson(map[string]interface{}{"success": flag})
-	}
-	return nil
+        if userId := d.GetSession("userId"); userId != nil {
+                queryMap := map[string]interface{}{
+                        "id":      d.GetString("id"),
+                        "user_id": userId.(string),
+                }
+                flag := false
+                order := util.Mysql.FindOne(tableName_order, queryMap, "filter,product_type,pay_way,out_trade_no,prepay_time,order_status,order_code,discount_price,d_relation_id,user_id", "")
+                if order != nil {
+                        if qutil.IntAll((*order)["order_status"]) == 0 && qutil.ObjToString((*order)["pay_way"]) != "transferAccounts" { //未支付状态下 删除订单需要先关闭订单
+                                flag = pay.CloseDataExportOrder(qutil.ObjToString((*order)["pay_way"]), qutil.ObjToString((*order)["out_trade_no"]), qutil.ObjToString((*order)["prepay_time"]))
+                                //未支付 非对公转账
+                                //卡卷取消绑定
+                                userLotteryId := qutil.ObjToString((*order)["d_relation_id"])
+                                if userLotteryId != "" {
+                                        productType := 0 //商品类型0普通的1线上课程
+                                        if product_type := qutil.ObjToString((*order)["product_type"]); product_type == "中标必听课" {
+                                                productType = 1
+                                        }
+                                        discountId := ""
+                                        var filter map[string]interface{}
+                                        //关闭未支付订单
+                                        if err := json.Unmarshal([]byte(qutil.ObjToString((*order)["filter"])), &filter); err != nil {
+                                                log.Println("filter.json.Unmarshal出错", err)
+                                        } else {
+                                                if filter["discountId"] != nil {
+                                                        discountId = strconv.Itoa(qutil.IntAll(filter["discountId"]))
+                                                }
+                                        }
+                                        order_code := qutil.ObjToString((*order)["order_code"])
+                                        user_id := qutil.ObjToString((*order)["user_id"])
+                                        go func(userId, userLotteryId, order_code string) {
+                                                if !util.UpdateCouponState(userId, userLotteryId, qutil.ObjToString(d.GetSession("s_nickname")), qutil.ObjToString(d.GetSession("phone")), order_code, qutil.ObjToString((*order)["product_type"]), discountId, 0, productType) {
+                                                        log.Println(fmt.Sprintf("单号%s-解绑失败-卡卷%s", order_code, userLotteryId))
+                                                }
+                                        }(user_id, userLotteryId, order_code)
+                                }
+                        } else {
+                                flag = true
+                        }
+                }
+                if flag {
+                        now := time.Now()
+                        flag = util.Mysql.Update(tableName_order, queryMap, map[string]interface{}{"del_status": 1, "del_time": FormatDate(&now, Date_Full_Layout)})
+                }
+                d.ServeJson(map[string]interface{}{"success": flag})
+        }
+        return nil
 }
 
 func (p *CommonAction) IsPaySuccess() {
-	defer qutil.Catch()
-	code := p.GetString("code")
-	userId, _ := p.GetSession("userId").(string)
-	if code != "" || userId != "" {
-		data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": code,
-			"user_id":    userId,
-		}, "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)
-			p.ServeJson(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,
-			})
-		}
-	}
-	p.ServeJson(map[string]interface{}{
-		"success": false,
-	})
+        defer qutil.Catch()
+        code := p.GetString("code")
+        userId, _ := p.GetSession("userId").(string)
+        if code != "" || userId != "" {
+                data := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": code,
+                        "user_id":    userId,
+                }, "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)
+                        p.ServeJson(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,
+                        })
+                }
+        }
+        p.ServeJson(map[string]interface{}{
+                "success": false,
+        })
 }
 
 func (d *CommonAction) GetwxSdkSign() {
-	var sign []string
-	url := d.GetString("url")
-	if url != "" {
-		sign = SignJSSDK(url)
-	}
-	nickname, _ := d.Session().Get("s_nickname").(string)
-	avatar, _ := d.Session().Get("s_avatar").(string)
-	openid := encrypt.SE.EncodeString(qutil.ObjToString(d.GetSession("s_m_openid")))
-	d.ServeJson(map[string]interface{}{
-		"wxsdk":    sign,
-		"wxDomain": config.Config.WxDomain,
-		"nickname": nickname,
-		"avatar":   avatar,
-		"openid":   openid,
-	})
+        var sign []string
+        url := d.GetString("url")
+        if url != "" {
+                sign = SignJSSDK(url)
+        }
+        nickname, _ := d.Session().Get("s_nickname").(string)
+        avatar, _ := d.Session().Get("s_avatar").(string)
+        openid := encrypt.SE.EncodeString(qutil.ObjToString(d.GetSession("s_m_openid")))
+        d.ServeJson(map[string]interface{}{
+                "wxsdk":    sign,
+                "wxDomain": config.Config.WxDomain,
+                "nickname": nickname,
+                "avatar":   avatar,
+                "openid":   openid,
+        })
 }
 
 func SignJSSDK(url string) []string {
-	qutil.Catch()
-	var signature []string
-	var key = "wxsignature_" + url
-	if ret := redis.Get("other", key); ret != nil {
-		if d, err := json.Marshal(ret); err == nil {
-			json.Unmarshal(d, &signature)
-		}
-	}
-	if signature == nil || len(signature) == 0 {
-		qutil.Try(func() {
-			client, err := rpc.DialHTTP("tcp", config.Config.Weixinrpc)
-			defer client.Close()
-			if err != nil {
-				log.Println(err.Error())
-				return
-			}
-			err = client.Call("WeiXinRpc.GetJSInterfaceParam", url, &signature)
-			if err != nil {
-				log.Println(err.Error())
-			}
-		}, func(e interface{}) {})
-		if signature == nil || len(signature) != 4 || signature[3] == "" {
-			signature = []string{"", "", "", ""}
-		} else {
-			redis.Put("other", key, signature, 90*60)
-		}
-	}
-	return signature
+        qutil.Catch()
+        var signature []string
+        var key = "wxsignature_" + url
+        if ret := redis.Get("other", key); ret != nil {
+                if d, err := json.Marshal(ret); err == nil {
+                        json.Unmarshal(d, &signature)
+                }
+        }
+        if signature == nil || len(signature) == 0 {
+                qutil.Try(func() {
+                        client, err := rpc.DialHTTP("tcp", config.Config.Weixinrpc)
+                        defer client.Close()
+                        if err != nil {
+                                log.Println(err.Error())
+                                return
+                        }
+                        err = client.Call("WeiXinRpc.GetJSInterfaceParam", url, &signature)
+                        if err != nil {
+                                log.Println(err.Error())
+                        }
+                }, func(e interface{}) {})
+                if signature == nil || len(signature) != 4 || signature[3] == "" {
+                        signature = []string{"", "", "", ""}
+                } else {
+                        redis.Put("other", key, signature, 90*60)
+                }
+        }
+        return signature
 }
 
 /*
@@ -311,25 +311,25 @@ param
 orderCode 订单号
 */
 func (this *CommonAction) GetCommonOrderPrice() {
-	orderCode := this.GetString("orderCode")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		query := map[string]interface{}{
-			"user_id":    userId,
-			"order_code": orderCode,
-		}
-		oData := util.Mysql.FindOne("dataexport_order", query, "order_money", "")
-		if oData == nil || len(*oData) == 0 {
-			return &entity.FuncResult{false, errors.New("未知订单"), nil}
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"price": (*oData)["order_money"],
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s GetCommonOrderPrice err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        orderCode := this.GetString("orderCode")
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                query := map[string]interface{}{
+                        "user_id":    userId,
+                        "order_code": orderCode,
+                }
+                oData := util.Mysql.FindOne("dataexport_order", query, "order_money", "")
+                if oData == nil || len(*oData) == 0 {
+                        return &entity.FuncResult{false, errors.New("未知订单"), nil}
+                }
+                return &entity.FuncResult{true, nil, map[string]interface{}{
+                        "price": (*oData)["order_money"],
+                }}
+        }()
+        if r.Err != nil {
+                log.Printf("%s GetCommonOrderPrice err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 /*
@@ -340,84 +340,84 @@ payway 支付方式
 dotype 产品类型
 */
 func (this *CommonAction) GetCommonPayParam() {
-	orderCode := this.GetString("orderCode")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	payway_req := this.GetString("payway")
-	r := func() *entity.FuncResult {
-		query := map[string]interface{}{
-			"user_id":      userId,
-			"order_code":   orderCode,
-			"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 != "" {
-			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("GetCommonPayParam 关闭订单%s出错\n", orderCode)
-						return &entity.FuncResult{false, errors.New("支付方式切换异常"), 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(), qutil.ObjToString(this.GetSession("s_m_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 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")
+        r := func() *entity.FuncResult {
+                query := map[string]interface{}{
+                        "user_id":      userId,
+                        "order_code":   orderCode,
+                        "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 != "" {
+                        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("GetCommonPayParam 关闭订单%s出错\n", orderCode)
+                                                return &entity.FuncResult{false, errors.New("支付方式切换异常"), 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(), qutil.ObjToString(this.GetSession("s_m_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 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())
 }
 
 /*
@@ -430,195 +430,202 @@ dotype 产品类型
 var imgReg = regexp.MustCompile(".*.(gif|jpeg|png|jpg)$")
 
 func (this *CommonAction) SaveTransferAccounts() {
-	orderCode := this.GetString("orderCode")
-	transferV := this.GetString("transferV")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	productType := ""
-	r := func() *entity.FuncResult {
-		if !imgReg.MatchString(transferV) {
-			return &entity.FuncResult{false, errors.New("上传图片异常"), nil}
-		}
-		query := map[string]interface{}{"order_code": orderCode, "user_id": userId}
-		rSearch := util.Mysql.FindOne("dataexport_order", query, "order_status,product_type,filter,course_status,out_trade_no,pay_way", "")
-		if rSearch == nil || len(*rSearch) == 0 {
-			return &entity.FuncResult{false, errors.New("未查到订单数据"), nil}
-		}
-		if !(qutil.IntAll((*rSearch)["order_status"]) == 0 && (qutil.IntAll((*rSearch)["course_status"]) == 0 || qutil.IntAll((*rSearch)["course_status"]) == 1 || qutil.IntAll((*rSearch)["course_status"]) == 3)) {
-			return &entity.FuncResult{false, errors.New("操作异常"), nil}
-		}
-		productType = qutil.ObjToString((*rSearch)["product_type"])
-		if !(productType == "招投标课程" || productType == "大会员") {
-			return &entity.FuncResult{false, errors.New("非法请求"), nil}
-		}
-		//保存更新filter
-		filterStr := qutil.ObjToString((*rSearch)["filter"])
-		mapTmp := map[string]interface{}{}
-		if json.Unmarshal([]byte(filterStr), &mapTmp) != nil || len(mapTmp) == 0 {
-			return &entity.FuncResult{false, errors.New("存储失败"), nil}
-		}
-		mapTmp["transferV"] = transferV
-		mapTmp["transferVTime"] = time.Now().Format(Date_Full_Layout)
+        orderCode := this.GetString("orderCode")
+        transferV := this.GetString("transferV")
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        productType := ""
+        r := func() *entity.FuncResult {
+                if !imgReg.MatchString(transferV) {
+                        return &entity.FuncResult{false, errors.New("上传图片异常"), nil}
+                }
+                query := map[string]interface{}{"order_code": orderCode, "user_id": userId}
+                rSearch := util.Mysql.FindOne("dataexport_order", query, "order_status,product_type,filter,course_status,out_trade_no,pay_way", "")
+                if rSearch == nil || len(*rSearch) == 0 {
+                        return &entity.FuncResult{false, errors.New("未查到订单数据"), nil}
+                }
+                if !(qutil.IntAll((*rSearch)["order_status"]) == 0 && (qutil.IntAll((*rSearch)["course_status"]) == 0 || qutil.IntAll((*rSearch)["course_status"]) == 1 || qutil.IntAll((*rSearch)["course_status"]) == 3)) {
+                        return &entity.FuncResult{false, errors.New("操作异常"), nil}
+                }
+                productType = qutil.ObjToString((*rSearch)["product_type"])
+                if !(productType == "招投标课程" || productType == "大会员") {
+                        return &entity.FuncResult{false, errors.New("非法请求"), nil}
+                }
+                //保存更新filter
+                filterStr := qutil.ObjToString((*rSearch)["filter"])
+                mapTmp := map[string]interface{}{}
+                if json.Unmarshal([]byte(filterStr), &mapTmp) != nil || len(mapTmp) == 0 {
+                        return &entity.FuncResult{false, errors.New("存储失败"), nil}
+                }
+                mapTmp["transferV"] = transferV
+                mapTmp["transferVTime"] = time.Now().Format(Date_Full_Layout)
 
-		finalStr, err := json.Marshal(mapTmp)
-		if err != nil || string(filterStr) == "" {
-			return &entity.FuncResult{false, errors.New("存储失败"), nil}
-		}
-		//保存更新filter--end
+                finalStr, err := json.Marshal(mapTmp)
+                if err != nil || string(filterStr) == "" {
+                        return &entity.FuncResult{false, errors.New("存储失败"), nil}
+                }
+                //保存更新filter--end
 
-		saveFlag := util.Mysql.Update("dataexport_order", query, map[string]interface{}{
-			"course_status": 2, //公对公转账审核中----
-			"pay_way":       "transferAccounts",
-			"filter":        string(finalStr),
-		})
+                saveFlag := util.Mysql.Update("dataexport_order", query, map[string]interface{}{
+                        "course_status": 2, //公对公转账审核中----
+                        "pay_way":       "transferAccounts",
+                        "filter":        string(finalStr),
+                })
 
-		if !saveFlag {
-			return &entity.FuncResult{false, errors.New("保存失败"), nil}
-		}
-		go func() {
-			entity.SendMailToOperation(1, orderCode, productType, config.GmailAuth)
-			//关闭之前支付串(防止重复支付)
-			if qutil.ObjToString((*rSearch)["pay_way"]) != "" {
-				if !pay.CloseOrder(qutil.ObjToString((*rSearch)["out_trade_no"]), qutil.ObjToString((*rSearch)["pay_way"])) {
-					log.Printf("SaveTransferAccounts 关闭订单%s出错\n", orderCode)
-				}
-			}
-		}()
-		return &entity.FuncResult{true, nil, nil}
-	}()
-	if r.Err != nil {
-		log.Printf("%s SaveTransferAccounts [%s ,%s] err:%v\n", userId, orderCode, transferV, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+                if !saveFlag {
+                        return &entity.FuncResult{false, errors.New("保存失败"), nil}
+                }
+                go func() {
+                        entity.SendMailToOperation(1, orderCode, productType, config.GmailAuth)
+                        //关闭之前支付串(防止重复支付)
+                        if qutil.ObjToString((*rSearch)["pay_way"]) != "" {
+                                if !pay.CloseOrder(qutil.ObjToString((*rSearch)["out_trade_no"]), qutil.ObjToString((*rSearch)["pay_way"])) {
+                                        log.Printf("SaveTransferAccounts 关闭订单%s出错\n", orderCode)
+                                }
+                        }
+                }()
+                return &entity.FuncResult{true, nil, nil}
+        }()
+        if r.Err != nil {
+                log.Printf("%s SaveTransferAccounts [%s ,%s] err:%v\n", userId, orderCode, transferV, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 func (this *CommonAction) Createorder() {
-	userid, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		//参数接收
-		infoMap := map[string]interface{}{}
-		if string(this.Body()) == "" {
-			return nil, fmt.Errorf("无效参数")
-		}
-		body := xweb.FilterXSS(string(this.Body()))
-		//接收参数
-		_ = json.Unmarshal([]byte(body), &infoMap)
-		if len(infoMap) == 0 {
-			return nil, fmt.Errorf("无效参数")
-		}
-		//产品类型
-		product, _ := infoMap["product"].(string)
-		if !config.Config.Product[product] {
-			return nil, fmt.Errorf("请求产品类型有误")
-		}
-		productId := strconv.Itoa(qutil.IntAll(infoMap["productId"]))
+        userid, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                //参数接收
+                infoMap := map[string]interface{}{}
+                if string(this.Body()) == "" {
+                        return nil, fmt.Errorf("无效参数")
+                }
+                body := xweb.FilterXSS(string(this.Body()))
+                //接收参数
+                _ = json.Unmarshal([]byte(body), &infoMap)
+                if len(infoMap) == 0 {
+                        return nil, fmt.Errorf("无效参数")
+                }
+                //产品类型
+                product, _ := infoMap["product"].(string)
+                if !config.Config.Product[product] {
+                        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("无效参数")
-		}
-		log.Println(infoMap)
+                //
+                data, _ := infoMap["data"].(map[string]interface{})
+                if len(data) <= 0 {
+                        return nil, fmt.Errorf("无效参数")
+                }
+                log.Println(infoMap)
 
-		//校验
-		if err := entity.JyCommonOrderStruct.RequestCheck(product, data, this.Session()); err != "" {
-			return nil, fmt.Errorf(err)
-		}
+                //校验
+                if err := entity.JyCommonOrderStruct.RequestCheck(product, data, this.Session()); err != "" {
+                        return nil, fmt.Errorf(err)
+                }
 
-		//获取卡券相关
-		lotteryId := qutil.ObjToString(data["lotteryId"]) //卡卷信息的id
-		i_discountId := qutil.IntAll(data["discountId"])  //赠品相关
-		discountId := strconv.Itoa(i_discountId)
+                //获取卡券相关
+                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)
-		}
-		now := time.Now()
-		distributionChannel, orderChannel := util.GetJyOrderChannel(inserMap.DisWord, this.Header("User-Agent"))
-		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,
-			"filter_keys":          inserMap.FilterKeys,
-			"download_url":         inserMap.DownloadUrl,
-			"dis_word":             inserMap.DisWord,
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		}
+                inserMap, msg := entity.JyCommonOrderStruct.InserMap(product, productId, userid, lotteryId, discountId, data, this.Session())
+                //错误信息
+                if msg != "" {
+                        return nil, fmt.Errorf(msg)
+                }
+                now := time.Now()
+                distributionChannel, orderChannel := util.GetJyOrderChannel(inserMap.DisWord, this.Header("User-Agent"))
+                entId := qutil.Int64All(this.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                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,
+                        "filter_keys":          inserMap.FilterKeys,
+                        "download_url":         inserMap.DownloadUrl,
+                        "dis_word":             inserMap.DisWord,
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                }
 
-		if openId := qutil.ObjToString(this.GetSession("s_m_openid")); openId != "" {
-			insertM["user_openid"] = openId
-		}
+                if openId := qutil.ObjToString(this.GetSession("s_m_openid")); openId != "" {
+                        insertM["user_openid"] = openId
+                }
 
-		if nickname := qutil.ObjToString(this.GetSession("s_nickname")); nickname != "" {
-			insertM["user_nickname"] = nickname
-		}
+                if nickname := qutil.ObjToString(this.GetSession("s_nickname")); nickname != "" {
+                        insertM["user_nickname"] = nickname
+                }
 
-		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.OutTradeNo != "" {
-			insertM["out_trade_no"] = inserMap.OutTradeNo
-		}
-		if inserMap.PayWay != "" {
-			insertM["pay_way"] = inserMap.PayWay
-		}
-		if inserMap.PrepayId != "" {
-			insertM["prepay_id"] = inserMap.PrepayId
-		}
-		if inserMap.CodeUrl != "" {
-			insertM["code_url"] = inserMap.CodeUrl
-		}
-		if inserMap.FilterId != "" {
-			insertM["filter_id"] = inserMap.FilterId
-		}
-		if inserMap.VipType != 0 {
-			insertM["vip_type"] = inserMap.VipType
-		}
-		if inserMap.ExpirationTime != "" {
-			insertM["expiration_time"] = inserMap.ExpirationTime
-		}
-		orderid := util.Mysql.Insert("dataexport_order", insertM)
-		//审核轨迹
-		util.Mysql.Insert("audit_records", map[string]interface{}{
-			"operator":      "-",
-			"create_time":   NowFormat(Date_Full_Layout),
-			"operator_type": 1,
-			"audit_status":  3,
-			"order_code":    inserMap.OrderCode,
-			"audit_type":    2,
-		})
-		if orderid <= 0 {
-			return nil, fmt.Errorf("创建订单异常")
-		}
-		if i_discountId > 0 {
-			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 CreateOrder 异常:%s\n", userid, errMsg.Error())
-	}
-	//创建完订单后更新卡券信息
-	this.ServeJson(NewResult(rData, errMsg))
+                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.OutTradeNo != "" {
+                        insertM["out_trade_no"] = inserMap.OutTradeNo
+                }
+                if inserMap.PayWay != "" {
+                        insertM["pay_way"] = inserMap.PayWay
+                }
+                if inserMap.PrepayId != "" {
+                        insertM["prepay_id"] = inserMap.PrepayId
+                }
+                if inserMap.CodeUrl != "" {
+                        insertM["code_url"] = inserMap.CodeUrl
+                }
+                if inserMap.FilterId != "" {
+                        insertM["filter_id"] = inserMap.FilterId
+                }
+                if inserMap.VipType != 0 {
+                        insertM["vip_type"] = inserMap.VipType
+                }
+                if inserMap.ExpirationTime != "" {
+                        insertM["expiration_time"] = inserMap.ExpirationTime
+                }
+                orderid := util.Mysql.Insert("dataexport_order", insertM)
+                //审核轨迹
+                util.Mysql.Insert("audit_records", map[string]interface{}{
+                        "operator":      "-",
+                        "create_time":   NowFormat(Date_Full_Layout),
+                        "operator_type": 1,
+                        "audit_status":  3,
+                        "order_code":    inserMap.OrderCode,
+                        "audit_type":    2,
+                })
+                if orderid <= 0 {
+                        return nil, fmt.Errorf("创建订单异常")
+                }
+                if i_discountId > 0 {
+                        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 CreateOrder 异常:%s\n", userid, errMsg.Error())
+        }
+        //创建完订单后更新卡券信息
+        this.ServeJson(NewResult(rData, errMsg))
 }

+ 750 - 743
src/jfw/modules/subscribepay/src/service/courseAction.go

@@ -1,795 +1,802 @@
 package service
 
 import (
-	"encoding/base64"
-	"encoding/json"
-	"errors"
-	"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"
-	"regexp"
-	"strconv"
-	"time"
-
-	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/mongodb"
-	"github.com/SKatiyar/qr"
-	"go.mongodb.org/mongo-driver/bson"
+        "encoding/base64"
+        "encoding/json"
+        "errors"
+        "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"
+        "regexp"
+        "strconv"
+        "time"
+
+        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/mongodb"
+        "github.com/SKatiyar/qr"
+        "go.mongodb.org/mongo-driver/bson"
 )
 
 //剑鱼招标课程公共接口
 
 type CourseAction struct {
-	*xweb.Action
-	courseList    xweb.Mapper `xweb:"/course/free/list"`    //获取招标课程列表
-	courseContent xweb.Mapper `xweb:"/course/free/content"` //获取招标课程三级页信息
-	reserve       xweb.Mapper `xweb:"/course/reserve/add"`  //课程预定
-	//xzh
-	codePay     xweb.Mapper `xweb:"/course/reserve/codePay"`     //扫码支付调用
-	orderPay    xweb.Mapper `xweb:"/course/reserve/orderPay"`    //支付已创建订单(移动端)
-	orderInfo   xweb.Mapper `xweb:"/course/reserve/orderInfo"`   //查询订单详情
-	refund      xweb.Mapper `xweb:"/course/reserve/refund"`      //提交退款申请
-	saveInvoice xweb.Mapper `xweb:"/course/reserve/saveInvoice"` //保存发票信息
-
-	saveVoucher xweb.Mapper `xweb:"/course/reserve/saveVoucher"` //保存转账凭证
+        *xweb.Action
+        courseList    xweb.Mapper `xweb:"/course/free/list"`    //获取招标课程列表
+        courseContent xweb.Mapper `xweb:"/course/free/content"` //获取招标课程三级页信息
+        reserve       xweb.Mapper `xweb:"/course/reserve/add"`  //课程预定
+        //xzh
+        codePay     xweb.Mapper `xweb:"/course/reserve/codePay"`     //扫码支付调用
+        orderPay    xweb.Mapper `xweb:"/course/reserve/orderPay"`    //支付已创建订单(移动端)
+        orderInfo   xweb.Mapper `xweb:"/course/reserve/orderInfo"`   //查询订单详情
+        refund      xweb.Mapper `xweb:"/course/reserve/refund"`      //提交退款申请
+        saveInvoice xweb.Mapper `xweb:"/course/reserve/saveInvoice"` //保存发票信息
+
+        saveVoucher xweb.Mapper `xweb:"/course/reserve/saveVoucher"` //保存转账凭证
 }
 
 var (
-	emailReg = regexp.MustCompile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")
+        emailReg = regexp.MustCompile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")
 )
 
 //课程上传公对公转账凭证
 func (this *CourseAction) SaveVoucher() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		if userId == "" {
-			return &entity.FuncResult{false, errors.New("未登录"), nil}
-		}
-		orderCode := this.GetString("orderCode")
-		transferV := this.GetString("transferV") //凭证地址
-		orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": orderCode,
-			"user_id":    userId,
-		}, "id,course_status,filter,order_status", "")
-		if orderdata == nil {
-			return &entity.FuncResult{false, errors.New("未找到订单"), nil}
-		}
-		orderStatus := qutil.IntAll((*orderdata)["order_status"])
-		if orderStatus != 0 {
-			return &entity.FuncResult{false, errors.New("订单暂不能支付或者已支付"), nil}
-		}
-		courseStatus := qutil.IntAll((*orderdata)["course_status"])
-		if courseStatus == 2 || courseStatus > 3 {
-			return &entity.FuncResult{false, errors.New("已提交过对公转账凭证"), nil}
-		}
-		vmsg := entity.JyCourseDetailMsg{}
-		filterStr := qutil.ObjToString((*orderdata)["filter"])
-		if err := json.Unmarshal([]byte(filterStr), &vmsg); err != nil {
-			log.Printf("%s course PayCallBack Unmarshal 出错 [%s]\n", userId, filterStr)
-			return &entity.FuncResult{false, errors.New("序列化出错"), nil}
-		}
-		vmsg.TransferV = transferV
-		now := time.Now()
-		transferVTime := FormatDate(&now, Date_Full_Layout) //转账时间
-		vmsg.TransferVTime = transferVTime
-		datailMsg, errs := json.Marshal(vmsg)
-		if errs != nil {
-			return &entity.FuncResult{false, errors.New("数据格式转换异常"), nil}
-		}
-		update := util.Mysql.Update("dataexport_order", map[string]interface{}{
-			//			"order_status": 0,
-			"order_code": orderCode,
-			"user_id":    userId,
-		}, map[string]interface{}{
-			"course_status": 2, //公对公转账审核中----
-			"filter":        string(datailMsg),
-			"pay_way":       "transferAccounts",
-		})
-		return &entity.FuncResult{update, nil, nil}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	} else {
-		//0:支付成功 1:对公转账凭证提交  2:申请退款
-		go entity.SendMailToOperation(1, this.GetString("orderCode"), "招投标课程", config.GmailAuth)
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                if userId == "" {
+                        return &entity.FuncResult{false, errors.New("未登录"), nil}
+                }
+                orderCode := this.GetString("orderCode")
+                transferV := this.GetString("transferV") //凭证地址
+                orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": orderCode,
+                        "user_id":    userId,
+                }, "id,course_status,filter,order_status", "")
+                if orderdata == nil {
+                        return &entity.FuncResult{false, errors.New("未找到订单"), nil}
+                }
+                orderStatus := qutil.IntAll((*orderdata)["order_status"])
+                if orderStatus != 0 {
+                        return &entity.FuncResult{false, errors.New("订单暂不能支付或者已支付"), nil}
+                }
+                courseStatus := qutil.IntAll((*orderdata)["course_status"])
+                if courseStatus == 2 || courseStatus > 3 {
+                        return &entity.FuncResult{false, errors.New("已提交过对公转账凭证"), nil}
+                }
+                vmsg := entity.JyCourseDetailMsg{}
+                filterStr := qutil.ObjToString((*orderdata)["filter"])
+                if err := json.Unmarshal([]byte(filterStr), &vmsg); err != nil {
+                        log.Printf("%s course PayCallBack Unmarshal 出错 [%s]\n", userId, filterStr)
+                        return &entity.FuncResult{false, errors.New("序列化出错"), nil}
+                }
+                vmsg.TransferV = transferV
+                now := time.Now()
+                transferVTime := FormatDate(&now, Date_Full_Layout) //转账时间
+                vmsg.TransferVTime = transferVTime
+                datailMsg, errs := json.Marshal(vmsg)
+                if errs != nil {
+                        return &entity.FuncResult{false, errors.New("数据格式转换异常"), nil}
+                }
+                update := util.Mysql.Update("dataexport_order", map[string]interface{}{
+                        //			"order_status": 0,
+                        "order_code": orderCode,
+                        "user_id":    userId,
+                }, map[string]interface{}{
+                        "course_status": 2, //公对公转账审核中----
+                        "filter":        string(datailMsg),
+                        "pay_way":       "transferAccounts",
+                })
+                return &entity.FuncResult{update, nil, nil}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        } else {
+                //0:支付成功 1:对公转账凭证提交  2:申请退款
+                go entity.SendMailToOperation(1, this.GetString("orderCode"), "招投标课程", config.GmailAuth)
+        }
+        this.ServeJson(r.Format())
 }
 
 //获取招标课程列表
 func (this *CourseAction) CourseList() {
-	flagStr := this.GetString("flag")            // 1:招标管理课程 or 2:投标实务课程
-	pageSize, _ := this.GetInteger("pageSize")   //每页数据量
-	pageIndex, _ := this.GetInteger("pageIndex") //当前页码数
-	r := func() *entity.FuncResult {
-		flag := qutil.If(flagStr == "2", 2, 1).(int)
-		pageIndex = qutil.If(pageIndex < 1, 1, pageIndex).(int)
-		pageSize = qutil.If(pageSize < 20 && pageSize > 0, pageSize, 20).(int)
-		rData := &[]map[string]interface{}{}
-		query := bson.M{"i_type": flag, "i_status": bson.M{"$in": []int{1, -1}}} //查询已发布or已结束的课程
-		count := util.MQFW.Count("jy_course", query)
-		if count != 0 {
-			rData, _ = util.MQFW.Find("jy_course", query, `{"l_publishtime":-1}`,
-				`{"_id":1,"i_type":1,"s_address":1,"i_status":1,"s_name":1,"i_price":1,"l_starttime":1,"l_endtime":1,"l_publishtime":1}`, false, (pageIndex-1)*pageSize, pageSize)
-		}
-		for _, v := range *rData {
-			//			v["l_starttime"] = time.Unix(qutil.Int64All(v["l_starttime"]), 0).Format(Date_Short_Layout)
-			v["l_starttime"] = time.Unix(qutil.Int64All(v["l_starttime"]), 0).Format("2006-01-02 15:04")
-			v["l_endtime"] = time.Unix(qutil.Int64All(v["l_endtime"]), 0).Format(Date_Short_Layout)
-			v["l_publishtime"] = time.Unix(qutil.Int64All(v["l_publishtime"]), 0).Format(Date_Short_Layout)
-			v["_id"] = encrypt.EncodeArticleId2ByCheck(BsonIdToSId(v["_id"]))
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"list":      rData, //数据
-			"totalRows": count, //总数
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf(" CourseList err:%v\n", r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        flagStr := this.GetString("flag")            // 1:招标管理课程 or 2:投标实务课程
+        pageSize, _ := this.GetInteger("pageSize")   //每页数据量
+        pageIndex, _ := this.GetInteger("pageIndex") //当前页码数
+        r := func() *entity.FuncResult {
+                flag := qutil.If(flagStr == "2", 2, 1).(int)
+                pageIndex = qutil.If(pageIndex < 1, 1, pageIndex).(int)
+                pageSize = qutil.If(pageSize < 20 && pageSize > 0, pageSize, 20).(int)
+                rData := &[]map[string]interface{}{}
+                query := bson.M{"i_type": flag, "i_status": bson.M{"$in": []int{1, -1}}} //查询已发布or已结束的课程
+                count := util.MQFW.Count("jy_course", query)
+                if count != 0 {
+                        rData, _ = util.MQFW.Find("jy_course", query, `{"l_publishtime":-1}`,
+                                `{"_id":1,"i_type":1,"s_address":1,"i_status":1,"s_name":1,"i_price":1,"l_starttime":1,"l_endtime":1,"l_publishtime":1}`, false, (pageIndex-1)*pageSize, pageSize)
+                }
+                for _, v := range *rData {
+                        //			v["l_starttime"] = time.Unix(qutil.Int64All(v["l_starttime"]), 0).Format(Date_Short_Layout)
+                        v["l_starttime"] = time.Unix(qutil.Int64All(v["l_starttime"]), 0).Format("2006-01-02 15:04")
+                        v["l_endtime"] = time.Unix(qutil.Int64All(v["l_endtime"]), 0).Format(Date_Short_Layout)
+                        v["l_publishtime"] = time.Unix(qutil.Int64All(v["l_publishtime"]), 0).Format(Date_Short_Layout)
+                        v["_id"] = encrypt.EncodeArticleId2ByCheck(BsonIdToSId(v["_id"]))
+                }
+                return &entity.FuncResult{true, nil, map[string]interface{}{
+                        "list":      rData, //数据
+                        "totalRows": count, //总数
+                }}
+        }()
+        if r.Err != nil {
+                log.Printf(" CourseList err:%v\n", r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //获取招标课程三级页信息
 func (this *CourseAction) CourseContent() {
-	_id := this.GetString("_id")             //课程id
-	showAbout := this.GetString("aboutFlag") //是否需要相关课程
-	r := func() *entity.FuncResult {
-		if _id == "" {
-			return &entity.FuncResult{false, errors.New("信息id为空"), nil}
-		}
-		_id = encrypt.DecodeArticleId2ByCheck(_id)[0]
-		//课程基本信息
-		rData, _ := util.MQFW.FindById("jy_course", _id, `{"i_type":1,"s_address":1,"i_status":1,"s_name":1,"i_price":1,"l_starttime":1,"l_endtime":1,"s_content":1,"s_discountPlan":1,"_id":1}`)
-		if rData == nil || len(*rData) == 0 {
-			return &entity.FuncResult{false, errors.New("未找到此课程的信息"), nil}
-		}
-		if !(qutil.IntAll((*rData)["i_status"]) == 1 || qutil.IntAll((*rData)["i_status"]) == -1) {
-			return &entity.FuncResult{false, errors.New("未找到此课程信息"), nil}
-		}
-		resultMap := map[string]interface{}{}
-		//		(*rData)["l_starttime"] = time.Unix(qutil.Int64All((*rData)["l_starttime"]), 0).Format(Date_Short_Layout)
-		(*rData)["l_starttime"] = time.Unix(qutil.Int64All((*rData)["l_starttime"]), 0).Format("2006-01-02 15:04")
-		(*rData)["l_endtime"] = time.Unix(qutil.Int64All((*rData)["l_endtime"]), 0).Format(Date_Short_Layout)
-		resultMap["detail"] = rData
-		i_type := qutil.IntAll((*rData)["i_type"])
-
-		if showAbout != "" {
-			//相关课程信息
-			s_name := (*rData)["s_name"]
-			queryAbout := bson.M{"i_type": i_type, "s_name": s_name, "i_status": bson.M{"$in": []int{1, -1}}, "_id": bson.M{"$ne": StringTOBsonId(_id)}} //查询已发布or已结束的课程
-			aboutList, _ := util.MQFW.Find("jy_course", queryAbout, `{"l_publishtime":-1}`,
-				`{"_id":1,"i_type":1,"s_address":1,"i_status":1,"s_name":1,"i_price":1,"l_starttime":1}`, false, 0, 3)
-			for _, v := range *aboutList {
-				v["l_starttime"] = time.Unix(qutil.Int64All(v["l_starttime"]), 0).Format(Date_Short_Layout)
-				v["l_endtime"] = time.Unix(qutil.Int64All(v["l_endtime"]), 0).Format(Date_Short_Layout)
-				v["l_publishtime"] = time.Unix(qutil.Int64All(v["l_publishtime"]), 0).Format(Date_Short_Layout)
-				v["_id"] = encrypt.EncodeArticleId2ByCheck(BsonIdToSId(v["_id"]))
-			}
-			resultMap["aboutList"] = aboutList
-		}
-
-		//优惠
-		discount := map[string]interface{}{}
-		if i_type == 1 { //招标管理课程 优惠
-			//满减是否到期
-			if time.Now().Before(entity.JyCourseDiscount.TenderingDiscount.Reduce.EndTime) {
-				discount["reduceAmount"] = entity.JyCourseDiscount.TenderingDiscount.Reduce.Amount
-				discount["endTime"] = entity.JyCourseDiscount.TenderingDiscount.Reduce.EndTime.Unix()
-			}
-		} else { //投标务实课程 优惠
-			if time.Now().Before(entity.JyCourseDiscount.BiddingDiscount.Reduce.EndTime) {
-				discount["reduceAmount"] = entity.JyCourseDiscount.BiddingDiscount.Reduce.Amount
-			}
-			//多人折扣
-			discount["discountMap"] = entity.JyCourseDiscount.BiddingDiscount.Discount
-			discount["endTime"] = entity.JyCourseDiscount.BiddingDiscount.Reduce.EndTime.Unix()
-		}
-		resultMap["discount"] = discount
-		return &entity.FuncResult{true, nil, resultMap}
-	}()
-	if r.Err != nil {
-		log.Printf(" CourseContent err:%v\n", r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        _id := this.GetString("_id")             //课程id
+        showAbout := this.GetString("aboutFlag") //是否需要相关课程
+        r := func() *entity.FuncResult {
+                if _id == "" {
+                        return &entity.FuncResult{false, errors.New("信息id为空"), nil}
+                }
+                _id = encrypt.DecodeArticleId2ByCheck(_id)[0]
+                //课程基本信息
+                rData, _ := util.MQFW.FindById("jy_course", _id, `{"i_type":1,"s_address":1,"i_status":1,"s_name":1,"i_price":1,"l_starttime":1,"l_endtime":1,"s_content":1,"s_discountPlan":1,"_id":1}`)
+                if rData == nil || len(*rData) == 0 {
+                        return &entity.FuncResult{false, errors.New("未找到此课程的信息"), nil}
+                }
+                if !(qutil.IntAll((*rData)["i_status"]) == 1 || qutil.IntAll((*rData)["i_status"]) == -1) {
+                        return &entity.FuncResult{false, errors.New("未找到此课程信息"), nil}
+                }
+                resultMap := map[string]interface{}{}
+                //		(*rData)["l_starttime"] = time.Unix(qutil.Int64All((*rData)["l_starttime"]), 0).Format(Date_Short_Layout)
+                (*rData)["l_starttime"] = time.Unix(qutil.Int64All((*rData)["l_starttime"]), 0).Format("2006-01-02 15:04")
+                (*rData)["l_endtime"] = time.Unix(qutil.Int64All((*rData)["l_endtime"]), 0).Format(Date_Short_Layout)
+                resultMap["detail"] = rData
+                i_type := qutil.IntAll((*rData)["i_type"])
+
+                if showAbout != "" {
+                        //相关课程信息
+                        s_name := (*rData)["s_name"]
+                        queryAbout := bson.M{"i_type": i_type, "s_name": s_name, "i_status": bson.M{"$in": []int{1, -1}}, "_id": bson.M{"$ne": StringTOBsonId(_id)}} //查询已发布or已结束的课程
+                        aboutList, _ := util.MQFW.Find("jy_course", queryAbout, `{"l_publishtime":-1}`,
+                                `{"_id":1,"i_type":1,"s_address":1,"i_status":1,"s_name":1,"i_price":1,"l_starttime":1}`, false, 0, 3)
+                        for _, v := range *aboutList {
+                                v["l_starttime"] = time.Unix(qutil.Int64All(v["l_starttime"]), 0).Format(Date_Short_Layout)
+                                v["l_endtime"] = time.Unix(qutil.Int64All(v["l_endtime"]), 0).Format(Date_Short_Layout)
+                                v["l_publishtime"] = time.Unix(qutil.Int64All(v["l_publishtime"]), 0).Format(Date_Short_Layout)
+                                v["_id"] = encrypt.EncodeArticleId2ByCheck(BsonIdToSId(v["_id"]))
+                        }
+                        resultMap["aboutList"] = aboutList
+                }
+
+                //优惠
+                discount := map[string]interface{}{}
+                if i_type == 1 { //招标管理课程 优惠
+                        //满减是否到期
+                        if time.Now().Before(entity.JyCourseDiscount.TenderingDiscount.Reduce.EndTime) {
+                                discount["reduceAmount"] = entity.JyCourseDiscount.TenderingDiscount.Reduce.Amount
+                                discount["endTime"] = entity.JyCourseDiscount.TenderingDiscount.Reduce.EndTime.Unix()
+                        }
+                } else { //投标务实课程 优惠
+                        if time.Now().Before(entity.JyCourseDiscount.BiddingDiscount.Reduce.EndTime) {
+                                discount["reduceAmount"] = entity.JyCourseDiscount.BiddingDiscount.Reduce.Amount
+                        }
+                        //多人折扣
+                        discount["discountMap"] = entity.JyCourseDiscount.BiddingDiscount.Discount
+                        discount["endTime"] = entity.JyCourseDiscount.BiddingDiscount.Reduce.EndTime.Unix()
+                }
+                resultMap["discount"] = discount
+                return &entity.FuncResult{true, nil, resultMap}
+        }()
+        if r.Err != nil {
+                log.Printf(" CourseContent err:%v\n", r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //查看课程是否已经结束
 func courseStatus(id string) bool {
-	if id != "" {
-		courseData, _ := util.MQFW.FindById("jy_course", id, `{"i_status":1}`)
-		if qutil.IntAll((*courseData)["i_status"]) == 1 { //正在进行中
-			return true
-		}
-	}
-	return false
+        if id != "" {
+                courseData, _ := util.MQFW.FindById("jy_course", id, `{"i_status":1}`)
+                if qutil.IntAll((*courseData)["i_status"]) == 1 { //正在进行中
+                        return true
+                }
+        }
+        return false
 }
 
 //课程预定
 func (this *CourseAction) Reserve() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		company := this.GetString("company")
-		name := this.GetString("name")
-		phone := this.GetString("phone")
-		email := this.GetString("email")
-		courseId := this.GetString("courseId")
-		peoleNum, _ := this.GetInteger("peopleNum")
-		payWay := this.GetString("pay_way")
-		prices := this.GetString("price")
-		courseName := this.GetString("courseName")
-		courseType := this.GetString("courseType")
-		courseAddress := this.GetString("courseAddress")
-		coursePrice := this.GetString("coursePrice")
-		price, _ := strconv.Atoi(prices)
-
-		//数据校验
-		if !nameReg.MatchString(name) || !phoneReg.MatchString(phone) || !emailReg.MatchString(email) ||
-			company == "" || price == 0 || courseId == "" || peoleNum < 1 || peoleNum > 50 {
-			return &entity.FuncResult{false, errors.New("数据校验不通过"), nil}
-		}
-		//课程校验
-		_id := encrypt.DecodeArticleId2ByCheck(courseId)[0]
-		courseMsg, final_price := entity.JyCourse.GetCourseMsgAndPrice(_id, peoleNum)
-		if courseMsg == nil {
-			return &entity.FuncResult{false, errors.New("未找到相关课程"), nil}
-		}
-		if qutil.IntAll((*courseMsg)["i_status"]) != 1 {
-			return &entity.FuncResult{false, errors.New("此课程不能支付"), nil}
-		}
-		startTime := qutil.Int64All((*courseMsg)["l_starttime"])
-		endTime := qutil.Int64All((*courseMsg)["l_endtime"])
-		//金额校验
-		if price != final_price {
-			return &entity.FuncResult{false, errors.New("支付金额校验异常"), nil}
-		}
-
-		discount := entity.JyCourseDiscount
-		//存入预定表&生成订单
-		datailMsg, err := json.Marshal(entity.JyCourseDetailMsg{
-			company, name, phone, email, _id, peoleNum, courseName, courseType, courseAddress, startTime, endTime, coursePrice, "", "", discount, "", "", "", ""})
-		if err != nil {
-			return &entity.FuncResult{false, errors.New("数据格式转换异常"), nil}
-		}
-
-		openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-		tradeno, prepayid, payStr := "", "", ""
-		order_status := 0
-		course_status := 0      //课程状态-默认:0;选择对公转账则是1;1:对公转账未上传凭证;2:对公转账审核中;3:对公转账审核未通过;4:对公转账审核通过(同时修改订单状态为已完成);5:退款审核中;6:已退款;(1,2,3为订单未支付状态;4,5,6为订单完成状态)
-		if payWay == "wx_app" { //"wx_app" app微信支付
-			var ret *map[string]string
-			tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_APP, this.IP(), "", "", final_price)
-			if ret == nil || (*ret)["status"] != "1" {
-				return &entity.FuncResult{false, errors.New("APP微信支付生成订单出错"), nil}
-			}
-			prepayid = qutil.ObjToString((*ret)["prepayid"])
-			payStr = pay.WxStruct.GetAppWxPayStr(prepayid)
-		} else if payWay == "wx_js" { //微信端js支付
-			var ret *map[string]string
-			tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_JSAPI, this.IP(), openId, "", final_price)
-			if ret == nil || (*ret)["status"] != "1" {
-				return &entity.FuncResult{false, errors.New("微信JS支付生成订单出错"), nil}
-			}
-			prepayid = qutil.ObjToString((*ret)["prepayid"])
-			payStr = pay.WxStruct.GetWxjsPaySign(prepayid)
-		} else if payWay == "wx_pc" { //pc端微信扫码支付
-			var ret *map[string]string
-			tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_NATIVE, this.IP(), openId, "", final_price)
-			if ret == nil || (*ret)["status"] != "1" {
-				return &entity.FuncResult{false, errors.New("pc微信扫码支付生成订单出错"), nil}
-			}
-			prepayid = (*ret)["prepayid"]
-			payStr = (*ret)["codeurl"]
-		} else if payWay == "ali_app" { //"ali_app" APP支付宝支付
-			var err error
-			payStr, tradeno, err = pay.Alipay.GetOrderPayParam((qutil.Float64All(final_price)), pay.ALI_COURSE_APP)
-			if err != nil {
-				return &entity.FuncResult{false, errors.New("支付宝APP订单生成出错"), nil}
-			}
-		} else if payWay == "ali_pc" { //pc端支付宝扫码支付
-			var err error
-			payStr, tradeno, err = pay.Alipay.GetOrderPayParam(qutil.Float64All(final_price), pay.ALI_COURSE_NATIVE)
-			if err != nil {
-				return &entity.FuncResult{false, errors.New("pc支付宝扫码生成出错"), nil}
-			}
-		} else if payWay == "transferAccounts" { //对公转账
-			course_status = 1 //1:对公转账代上传凭证
-		} else {
-			return &entity.FuncResult{false, errors.New("未知支付方式"), nil}
-		}
-		now := time.Now()
-		ordercode := pay.GetOrderCode(userId)
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
-		orderId := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":          final_price,
-			"user_nickname":        name,
-			"order_status":         order_status,
-			"course_status":        course_status,
-			"user_openid":          openId,
-			"prepay_id":            prepayid,
-			"code_url":             payStr,
-			"out_trade_no":         tradeno,
-			"order_code":           ordercode,
-			"product_type":         "招投标课程",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"prepay_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       final_price,
-			"filter_id":            _id, //课程id
-			"pay_way":              payWay,
-			"user_id":              userId,
-			"user_mail":            email,
-			"user_phone":           phone,
-			"filter":               string(datailMsg),   //订单详情
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		})
-		if orderId == 0 {
-			return &entity.FuncResult{false, errors.New("数据库操作异常,请稍后重试"), nil}
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"code": ordercode,
-			"res":  payStr,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                company := this.GetString("company")
+                name := this.GetString("name")
+                phone := this.GetString("phone")
+                email := this.GetString("email")
+                courseId := this.GetString("courseId")
+                peoleNum, _ := this.GetInteger("peopleNum")
+                payWay := this.GetString("pay_way")
+                prices := this.GetString("price")
+                courseName := this.GetString("courseName")
+                courseType := this.GetString("courseType")
+                courseAddress := this.GetString("courseAddress")
+                coursePrice := this.GetString("coursePrice")
+                price, _ := strconv.Atoi(prices)
+
+                //数据校验
+                if !nameReg.MatchString(name) || !phoneReg.MatchString(phone) || !emailReg.MatchString(email) ||
+                        company == "" || price == 0 || courseId == "" || peoleNum < 1 || peoleNum > 50 {
+                        return &entity.FuncResult{false, errors.New("数据校验不通过"), nil}
+                }
+                //课程校验
+                _id := encrypt.DecodeArticleId2ByCheck(courseId)[0]
+                courseMsg, final_price := entity.JyCourse.GetCourseMsgAndPrice(_id, peoleNum)
+                if courseMsg == nil {
+                        return &entity.FuncResult{false, errors.New("未找到相关课程"), nil}
+                }
+                if qutil.IntAll((*courseMsg)["i_status"]) != 1 {
+                        return &entity.FuncResult{false, errors.New("此课程不能支付"), nil}
+                }
+                startTime := qutil.Int64All((*courseMsg)["l_starttime"])
+                endTime := qutil.Int64All((*courseMsg)["l_endtime"])
+                //金额校验
+                if price != final_price {
+                        return &entity.FuncResult{false, errors.New("支付金额校验异常"), nil}
+                }
+
+                discount := entity.JyCourseDiscount
+                //存入预定表&生成订单
+                datailMsg, err := json.Marshal(entity.JyCourseDetailMsg{
+                        company, name, phone, email, _id, peoleNum, courseName, courseType, courseAddress, startTime, endTime, coursePrice, "", "", discount, "", "", "", ""})
+                if err != nil {
+                        return &entity.FuncResult{false, errors.New("数据格式转换异常"), nil}
+                }
+
+                openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+                tradeno, prepayid, payStr := "", "", ""
+                order_status := 0
+                course_status := 0      //课程状态-默认:0;选择对公转账则是1;1:对公转账未上传凭证;2:对公转账审核中;3:对公转账审核未通过;4:对公转账审核通过(同时修改订单状态为已完成);5:退款审核中;6:已退款;(1,2,3为订单未支付状态;4,5,6为订单完成状态)
+                if payWay == "wx_app" { //"wx_app" app微信支付
+                        var ret *map[string]string
+                        tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_APP, this.IP(), "", "", final_price)
+                        if ret == nil || (*ret)["status"] != "1" {
+                                return &entity.FuncResult{false, errors.New("APP微信支付生成订单出错"), nil}
+                        }
+                        prepayid = qutil.ObjToString((*ret)["prepayid"])
+                        payStr = pay.WxStruct.GetAppWxPayStr(prepayid)
+                } else if payWay == "wx_js" { //微信端js支付
+                        var ret *map[string]string
+                        tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_JSAPI, this.IP(), openId, "", final_price)
+                        if ret == nil || (*ret)["status"] != "1" {
+                                return &entity.FuncResult{false, errors.New("微信JS支付生成订单出错"), nil}
+                        }
+                        prepayid = qutil.ObjToString((*ret)["prepayid"])
+                        payStr = pay.WxStruct.GetWxjsPaySign(prepayid)
+                } else if payWay == "wx_pc" { //pc端微信扫码支付
+                        var ret *map[string]string
+                        tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_NATIVE, this.IP(), openId, "", final_price)
+                        if ret == nil || (*ret)["status"] != "1" {
+                                return &entity.FuncResult{false, errors.New("pc微信扫码支付生成订单出错"), nil}
+                        }
+                        prepayid = (*ret)["prepayid"]
+                        payStr = (*ret)["codeurl"]
+                } else if payWay == "ali_app" { //"ali_app" APP支付宝支付
+                        var err error
+                        payStr, tradeno, err = pay.Alipay.GetOrderPayParam((qutil.Float64All(final_price)), pay.ALI_COURSE_APP)
+                        if err != nil {
+                                return &entity.FuncResult{false, errors.New("支付宝APP订单生成出错"), nil}
+                        }
+                } else if payWay == "ali_pc" { //pc端支付宝扫码支付
+                        var err error
+                        payStr, tradeno, err = pay.Alipay.GetOrderPayParam(qutil.Float64All(final_price), pay.ALI_COURSE_NATIVE)
+                        if err != nil {
+                                return &entity.FuncResult{false, errors.New("pc支付宝扫码生成出错"), nil}
+                        }
+                } else if payWay == "transferAccounts" { //对公转账
+                        course_status = 1 //1:对公转账代上传凭证
+                } else {
+                        return &entity.FuncResult{false, errors.New("未知支付方式"), nil}
+                }
+                now := time.Now()
+                ordercode := pay.GetOrderCode(userId)
+                entId := qutil.Int64All(this.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
+                orderId := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":          final_price,
+                        "user_nickname":        name,
+                        "order_status":         order_status,
+                        "course_status":        course_status,
+                        "user_openid":          openId,
+                        "prepay_id":            prepayid,
+                        "code_url":             payStr,
+                        "out_trade_no":         tradeno,
+                        "order_code":           ordercode,
+                        "product_type":         "招投标课程",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "prepay_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       final_price,
+                        "filter_id":            _id, //课程id
+                        "pay_way":              payWay,
+                        "user_id":              userId,
+                        "user_mail":            email,
+                        "user_phone":           phone,
+                        "filter":               string(datailMsg),   //订单详情
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                })
+                if orderId == 0 {
+                        return &entity.FuncResult{false, errors.New("数据库操作异常,请稍后重试"), nil}
+                }
+                return &entity.FuncResult{true, nil, map[string]interface{}{
+                        "code": ordercode,
+                        "res":  payStr,
+                }}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //扫码支付
 func (this *CourseAction) CodePay() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-	r := func() *entity.FuncResult {
-		if userId == "" {
-			return &entity.FuncResult{false, errors.New("用户异常"), nil}
-		}
-		orderCode := this.GetString("orderCode")
-		pay_way := this.GetString("payway")
-		if orderCode == "" {
-			return &entity.FuncResult{false, errors.New("参数异常"), nil}
-		}
-		orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": orderCode,
-			"user_id":    userId,
-		}, "id,code_url,prepay_time,pay_way,order_code,out_trade_no,order_status,order_money,filter_id", "")
-		if orderdata == nil {
-			return &entity.FuncResult{false, errors.New("未找到订单"), nil}
-		}
-		orderStatus := qutil.IntAll((*orderdata)["order_status"])
-		if orderStatus == 1 {
-			return &entity.FuncResult{false, errors.New("已支付过订单"), nil}
-		}
-		if orderStatus != 0 {
-			return &entity.FuncResult{false, errors.New("订单状态异常"), nil}
-		}
-		filter_id := qutil.ObjToString((*orderdata)["filter_id"])
-		if !courseStatus(filter_id) {
-			return &entity.FuncResult{false, errors.New("此课程已结束"), nil}
-		}
-		orderId := qutil.Int64All((*orderdata)["id"])
-		payWay := qutil.ObjToString((*orderdata)["pay_way"]) //订单原支付方式
-		orderMoney := qutil.IntAll((*orderdata)["order_money"])
-		order_code := qutil.ObjToString((*orderdata)["order_code"])
-
-		codeUrl := ""
-		var surplus_second int64
-		//在此关闭没有超时之前的订单 在pc端支付微信端订单,pay_way是wx_js 先进行关闭,再重新创建订单的时候,pay_way需要修改成wx_pc。
-		//对公转账的订单不用关闭
-		if pay_way != "" {
-			if payWay != "transferAccounts" && !pay.CloseDataExportOrder(payWay, qutil.ObjToString((*orderdata)["out_trade_no"]), qutil.ObjToString((*orderdata)["prepay_time"])) {
-				return &entity.FuncResult{false, errors.New("订单关闭异常"), nil}
-			}
-		} else {
-			pay_way = payWay
-			prepayTime, err := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*orderdata)["prepay_time"]), time.Local)
-			surplus_second = prepayTime.Unix() + 7200 - time.Now().Unix()
-			if err == nil && surplus_second <= 0 { //重新生成预订单
-				if payWay != "transferAccounts" && !pay.CloseDataExportOrder(payWay, qutil.ObjToString((*orderdata)["out_trade_no"]), qutil.ObjToString((*orderdata)["prepay_time"])) {
-					return &entity.FuncResult{false, errors.New("订单关闭异常"), nil}
-				}
-			}
-		}
-		now := time.Now()
-		prepay_time := FormatDate(&now, Date_Full_Layout)
-		if pay_way == "wx_pc" { //pc端重生支付码 更新数据库
-			tradeno, ret := pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_NATIVE, this.IP(), openId, "", orderMoney)
-			if ret != nil && (*ret)["status"] == "1" {
-				if util.Mysql.Update("dataexport_order", map[string]interface{}{
-					"id": orderId,
-				}, map[string]interface{}{
-					"prepay_time":  prepay_time,
-					"prepay_id":    (*ret)["prepayid"],
-					"code_url":     (*ret)["codeurl"],
-					"out_trade_no": tradeno,
-					"pay_way":      pay_way,
-				}) {
-					r, _ := qr.Encode(qutil.ObjToString((*ret)["codeurl"]), qr.M)
-					pngdat := r.PNG()
-					codeUrl = base64.StdEncoding.EncodeToString(pngdat)
-					surplus_second = 7200
-				} else {
-					return &entity.FuncResult{false, errors.New(pay_way + "更新数据库出错"), nil}
-				}
-			} else {
-				return &entity.FuncResult{false, errors.New(pay_way + "创建微信订单出错"), nil}
-			}
-		} else if pay_way == "ali_pc" {
-			if qr_url, tradeno, err := pay.Alipay.GetOrderPayParam(qutil.Float64All(orderMoney), pay.ALI_COURSE_NATIVE); err == nil {
-				if util.Mysql.Update("dataexport_order", map[string]interface{}{
-					"id": orderId,
-				}, map[string]interface{}{
-					"prepay_time":  prepay_time,
-					"prepay_id":    "",
-					"code_url":     qr_url,
-					"out_trade_no": tradeno,
-					"pay_way":      pay_way,
-				}) {
-					codeUrl = qr_url
-					surplus_second = 7200
-				} else {
-					return &entity.FuncResult{false, errors.New(pay_way + "更新数据库出错"), nil}
-				}
-			} else {
-				return &entity.FuncResult{false, errors.New(pay_way + "创建支付宝订单出错"), nil}
-			}
-		} else if pay_way == "transferAccounts" {
-			var sql = `update dataexport_order set prepay_time='` + prepay_time + `',pay_way='` + pay_way + `' where order_code='` + orderCode + `'`
-			i := util.Mysql.UpdateOrDeleteBySql(sql)
-			if i > -1 {
-				codeUrl = ""
-			} else {
-				return &entity.FuncResult{false, errors.New(pay_way + "更新数据库出错"), nil}
-			}
-		}
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"payWay":         payWay,
-			"rCode":          codeUrl,
-			"orderMoney":     orderMoney,
-			"surplus_second": surplus_second,
-			"orderCode":      order_code,
-			"prepay_time":    prepay_time,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+        r := func() *entity.FuncResult {
+                if userId == "" {
+                        return &entity.FuncResult{false, errors.New("用户异常"), nil}
+                }
+                orderCode := this.GetString("orderCode")
+                pay_way := this.GetString("payway")
+                if orderCode == "" {
+                        return &entity.FuncResult{false, errors.New("参数异常"), nil}
+                }
+                orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": orderCode,
+                        "user_id":    userId,
+                }, "id,code_url,prepay_time,pay_way,order_code,out_trade_no,order_status,order_money,filter_id", "")
+                if orderdata == nil {
+                        return &entity.FuncResult{false, errors.New("未找到订单"), nil}
+                }
+                orderStatus := qutil.IntAll((*orderdata)["order_status"])
+                if orderStatus == 1 {
+                        return &entity.FuncResult{false, errors.New("已支付过订单"), nil}
+                }
+                if orderStatus != 0 {
+                        return &entity.FuncResult{false, errors.New("订单状态异常"), nil}
+                }
+                filter_id := qutil.ObjToString((*orderdata)["filter_id"])
+                if !courseStatus(filter_id) {
+                        return &entity.FuncResult{false, errors.New("此课程已结束"), nil}
+                }
+                orderId := qutil.Int64All((*orderdata)["id"])
+                payWay := qutil.ObjToString((*orderdata)["pay_way"]) //订单原支付方式
+                orderMoney := qutil.IntAll((*orderdata)["order_money"])
+                order_code := qutil.ObjToString((*orderdata)["order_code"])
+
+                codeUrl := ""
+                var surplus_second int64
+                //在此关闭没有超时之前的订单 在pc端支付微信端订单,pay_way是wx_js 先进行关闭,再重新创建订单的时候,pay_way需要修改成wx_pc。
+                //对公转账的订单不用关闭
+                if pay_way != "" {
+                        if payWay != "transferAccounts" && !pay.CloseDataExportOrder(payWay, qutil.ObjToString((*orderdata)["out_trade_no"]), qutil.ObjToString((*orderdata)["prepay_time"])) {
+                                return &entity.FuncResult{false, errors.New("订单关闭异常"), nil}
+                        }
+                } else {
+                        pay_way = payWay
+                        prepayTime, err := time.ParseInLocation(Date_Full_Layout, qutil.ObjToString((*orderdata)["prepay_time"]), time.Local)
+                        surplus_second = prepayTime.Unix() + 7200 - time.Now().Unix()
+                        if err == nil && surplus_second <= 0 { //重新生成预订单
+                                if payWay != "transferAccounts" && !pay.CloseDataExportOrder(payWay, qutil.ObjToString((*orderdata)["out_trade_no"]), qutil.ObjToString((*orderdata)["prepay_time"])) {
+                                        return &entity.FuncResult{false, errors.New("订单关闭异常"), nil}
+                                }
+                        }
+                }
+                now := time.Now()
+                prepay_time := FormatDate(&now, Date_Full_Layout)
+                if pay_way == "wx_pc" { //pc端重生支付码 更新数据库
+                        tradeno, ret := pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_NATIVE, this.IP(), openId, "", orderMoney)
+                        if ret != nil && (*ret)["status"] == "1" {
+                                if util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                        "id": orderId,
+                                }, map[string]interface{}{
+                                        "prepay_time":  prepay_time,
+                                        "prepay_id":    (*ret)["prepayid"],
+                                        "code_url":     (*ret)["codeurl"],
+                                        "out_trade_no": tradeno,
+                                        "pay_way":      pay_way,
+                                }) {
+                                        r, _ := qr.Encode(qutil.ObjToString((*ret)["codeurl"]), qr.M)
+                                        pngdat := r.PNG()
+                                        codeUrl = base64.StdEncoding.EncodeToString(pngdat)
+                                        surplus_second = 7200
+                                } else {
+                                        return &entity.FuncResult{false, errors.New(pay_way + "更新数据库出错"), nil}
+                                }
+                        } else {
+                                return &entity.FuncResult{false, errors.New(pay_way + "创建微信订单出错"), nil}
+                        }
+                } else if pay_way == "ali_pc" {
+                        if qr_url, tradeno, err := pay.Alipay.GetOrderPayParam(qutil.Float64All(orderMoney), pay.ALI_COURSE_NATIVE); err == nil {
+                                if util.Mysql.Update("dataexport_order", map[string]interface{}{
+                                        "id": orderId,
+                                }, map[string]interface{}{
+                                        "prepay_time":  prepay_time,
+                                        "prepay_id":    "",
+                                        "code_url":     qr_url,
+                                        "out_trade_no": tradeno,
+                                        "pay_way":      pay_way,
+                                }) {
+                                        codeUrl = qr_url
+                                        surplus_second = 7200
+                                } else {
+                                        return &entity.FuncResult{false, errors.New(pay_way + "更新数据库出错"), nil}
+                                }
+                        } else {
+                                return &entity.FuncResult{false, errors.New(pay_way + "创建支付宝订单出错"), nil}
+                        }
+                } else if pay_way == "transferAccounts" {
+                        var sql = `update dataexport_order set prepay_time='` + prepay_time + `',pay_way='` + pay_way + `' where order_code='` + orderCode + `'`
+                        i := util.Mysql.UpdateOrDeleteBySql(sql)
+                        if i > -1 {
+                                codeUrl = ""
+                        } else {
+                                return &entity.FuncResult{false, errors.New(pay_way + "更新数据库出错"), nil}
+                        }
+                }
+                return &entity.FuncResult{true, nil, map[string]interface{}{
+                        "payWay":         payWay,
+                        "rCode":          codeUrl,
+                        "orderMoney":     orderMoney,
+                        "surplus_second": surplus_second,
+                        "orderCode":      order_code,
+                        "prepay_time":    prepay_time,
+                }}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //支付已创建订单(移动端)
 func (this *CourseAction) OrderPay() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	orderCode := qutil.ObjToString(this.GetString("orderCode"))
-	payway := qutil.ObjToString(this.GetString("payWay"))
-	r := func() *entity.FuncResult {
-		if payway == "" { //默认微信js支付
-			payway = "wx_js"
-		}
-		if !(payway == "wx_js" || payway == "wx_app" || payway == "ali_app" || payway == "transferAccounts") { //
-			return &entity.FuncResult{false, errors.New("未知支付方式"), nil}
-		}
-		//根据订单号获取订单数据
-		query := map[string]interface{}{
-			"user_id":      userId,
-			"order_code":   orderCode,
-			"order_status": 0,
-		}
-		oData := util.Mysql.FindOne("dataexport_order", query, "id,code_url,prepay_time,pay_way,order_money,filter_id", "")
-		if oData == nil || len(*oData) == 0 {
-			return &entity.FuncResult{false, errors.New("未知订单"), nil}
-		}
-
-		filter_id := qutil.ObjToString((*oData)["filter_id"])
-		if !courseStatus(filter_id) {
-			return &entity.FuncResult{false, errors.New("此课程已结束"), nil}
-		}
-		jsPayParam := qutil.ObjToString((*oData)["code_url"])
-		course_status := 0
-		//重新生成订单
-		totalfee := qutil.IntAll((*oData)["order_money"])
-		tradeno, prepayid := "", ""
-		if payway == "wx_js" { //微信js支付
-			var ret *map[string]string
-			tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_JSAPI, this.IP(), qutil.ObjToString(this.GetSession("s_m_openid")), "", totalfee)
-			if ret == nil || (*ret)["status"] != "1" {
-				errMsg := "创建微信订单出错"
-				if (*ret)["errcodedes"] != "" {
-					errMsg = (*ret)["errcodedes"]
-				} else if (*ret)["errcode"] != "" {
-					errMsg = (*ret)["errcode"]
-				}
-				return &entity.FuncResult{false, errors.New(errMsg), nil}
-			}
-			prepayid = qutil.ObjToString((*ret)["prepayid"])
-			jsPayParam = pay.GetWxJsPayStr(prepayid)
-		} else if payway == "wx_app" { //微信app支付
-			var ret *map[string]string
-			tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_APP, this.IP(), qutil.ObjToString(this.GetSession("s_m_openid")), "", totalfee)
-			if ret == nil || (*ret)["status"] != "1" {
-				errMsg := "创建微信订单出错"
-				if (*ret)["errcodedes"] != "" {
-					errMsg = (*ret)["errcodedes"]
-				} else if (*ret)["errcode"] != "" {
-					errMsg = (*ret)["errcode"]
-				}
-				return &entity.FuncResult{false, errors.New(errMsg), nil}
-			}
-			prepayid = qutil.ObjToString((*ret)["prepayid"])
-			jsPayParam = pay.WxStruct.GetAppWxPayStr(prepayid)
-		} else if payway == "ali_app" { //支付宝app支付
-			var err error
-			jsPayParam, tradeno, err = pay.Alipay.GetOrderPayParam((qutil.Float64All(totalfee)), pay.ALI_COURSE_APP)
-			if err != nil {
-				return &entity.FuncResult{false, errors.New("创建支付宝订单出错"), nil}
-			}
-		} else if payway == "transferAccounts" {
-			course_status = 2
-		}
-		//更新订单表
-		now := time.Now()
-		ok := util.Mysql.Update("dataexport_order", query, map[string]interface{}{
-			"code_url":      jsPayParam,
-			"prepay_time":   FormatDate(&now, Date_Full_Layout),
-			"out_trade_no":  tradeno,
-			"prepay_id":     prepayid,
-			"course_status": course_status,
-			"pay_way":       payway,
-		})
-		if !ok {
-			return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
-		}
-		if payway != "transferAccounts" {
-			return &entity.FuncResult{true, nil, map[string]interface{}{"res": jsPayParam}}
-		} else {
-			return &entity.FuncResult{true, nil, nil}
-		}
-
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        orderCode := qutil.ObjToString(this.GetString("orderCode"))
+        payway := qutil.ObjToString(this.GetString("payWay"))
+        r := func() *entity.FuncResult {
+                if payway == "" { //默认微信js支付
+                        payway = "wx_js"
+                }
+                if !(payway == "wx_js" || payway == "wx_app" || payway == "ali_app" || payway == "transferAccounts") { //
+                        return &entity.FuncResult{false, errors.New("未知支付方式"), nil}
+                }
+                //根据订单号获取订单数据
+                query := map[string]interface{}{
+                        "user_id":      userId,
+                        "order_code":   orderCode,
+                        "order_status": 0,
+                }
+                oData := util.Mysql.FindOne("dataexport_order", query, "id,code_url,prepay_time,pay_way,order_money,filter_id", "")
+                if oData == nil || len(*oData) == 0 {
+                        return &entity.FuncResult{false, errors.New("未知订单"), nil}
+                }
+
+                filter_id := qutil.ObjToString((*oData)["filter_id"])
+                if !courseStatus(filter_id) {
+                        return &entity.FuncResult{false, errors.New("此课程已结束"), nil}
+                }
+                jsPayParam := qutil.ObjToString((*oData)["code_url"])
+                course_status := 0
+                //重新生成订单
+                totalfee := qutil.IntAll((*oData)["order_money"])
+                tradeno, prepayid := "", ""
+                if payway == "wx_js" { //微信js支付
+                        var ret *map[string]string
+                        tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_JSAPI, this.IP(), qutil.ObjToString(this.GetSession("s_m_openid")), "", totalfee)
+                        if ret == nil || (*ret)["status"] != "1" {
+                                errMsg := "创建微信订单出错"
+                                if (*ret)["errcodedes"] != "" {
+                                        errMsg = (*ret)["errcodedes"]
+                                } else if (*ret)["errcode"] != "" {
+                                        errMsg = (*ret)["errcode"]
+                                }
+                                return &entity.FuncResult{false, errors.New(errMsg), nil}
+                        }
+                        prepayid = qutil.ObjToString((*ret)["prepayid"])
+                        jsPayParam = pay.GetWxJsPayStr(prepayid)
+                } else if payway == "wx_app" { //微信app支付
+                        var ret *map[string]string
+                        tradeno, ret = pay.WxStruct.CreatePrepayOrder(pay.WX_COURSE_APP, this.IP(), qutil.ObjToString(this.GetSession("s_m_openid")), "", totalfee)
+                        if ret == nil || (*ret)["status"] != "1" {
+                                errMsg := "创建微信订单出错"
+                                if (*ret)["errcodedes"] != "" {
+                                        errMsg = (*ret)["errcodedes"]
+                                } else if (*ret)["errcode"] != "" {
+                                        errMsg = (*ret)["errcode"]
+                                }
+                                return &entity.FuncResult{false, errors.New(errMsg), nil}
+                        }
+                        prepayid = qutil.ObjToString((*ret)["prepayid"])
+                        jsPayParam = pay.WxStruct.GetAppWxPayStr(prepayid)
+                } else if payway == "ali_app" { //支付宝app支付
+                        var err error
+                        jsPayParam, tradeno, err = pay.Alipay.GetOrderPayParam((qutil.Float64All(totalfee)), pay.ALI_COURSE_APP)
+                        if err != nil {
+                                return &entity.FuncResult{false, errors.New("创建支付宝订单出错"), nil}
+                        }
+                } else if payway == "transferAccounts" {
+                        course_status = 2
+                }
+                //更新订单表
+                now := time.Now()
+                ok := util.Mysql.Update("dataexport_order", query, map[string]interface{}{
+                        "code_url":      jsPayParam,
+                        "prepay_time":   FormatDate(&now, Date_Full_Layout),
+                        "out_trade_no":  tradeno,
+                        "prepay_id":     prepayid,
+                        "course_status": course_status,
+                        "pay_way":       payway,
+                })
+                if !ok {
+                        return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
+                }
+                if payway != "transferAccounts" {
+                        return &entity.FuncResult{true, nil, map[string]interface{}{"res": jsPayParam}}
+                } else {
+                        return &entity.FuncResult{true, nil, nil}
+                }
+
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //订单详情
 func (this *CourseAction) OrderInfo() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		orderCode := this.GetString("orderCode")
-		orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": orderCode,
-			"user_id":    userId,
-		}, "id,prepay_time,pay_way,order_code,order_money,out_trade_no,product_type,pay_time,order_status,course_status,applybill_status,filter,filter_id", "")
-		if orderdata == nil {
-			return &entity.FuncResult{false, errors.New("未找到订单"), nil}
-		}
-
-		filter_id := qutil.ObjToString((*orderdata)["filter_id"])
-		courseFlag := courseStatus(filter_id) //课程状态 已结束:false   正在进行中:true
-		orderId := qutil.Int64All((*orderdata)["id"])
-		payWay := qutil.ObjToString((*orderdata)["pay_way"])
-		orderMoney := qutil.IntAll((*orderdata)["order_money"])
-		order_code := qutil.ObjToString((*orderdata)["order_code"])
-		payTime := (*orderdata)["prepay_time"] //下单时间
-		out_trade_no := qutil.ObjToString((*orderdata)["out_trade_no"])
-		payTimes := (*orderdata)["pay_time"] //支付时间
-		orderStatus := qutil.IntAll((*orderdata)["order_status"])
-		courseStatus := qutil.IntAll((*orderdata)["course_status"])
-		applybill_status := qutil.IntAll((*orderdata)["applybill_status"]) //发票申请状态
-		vmsg := entity.JyCourseDetailMsg{}
-		filterStr := qutil.ObjToString((*orderdata)["filter"])
-		openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-		canpaywx := false
-		if openId != "" {
-			canpaywx = true
-		}
-		if err := json.Unmarshal([]byte(filterStr), &vmsg); err != nil {
-			log.Printf("%s course PayCallBack Unmarshal 出错 [%s]\n", userId, filterStr)
-			return &entity.FuncResult{false, errors.New("序列化出错"), nil}
-		}
-		if orderStatus == 1 {
-			out_trade_no = func() string {
-				table := ""
-				// 0微信支付 1支付宝支付
-				if payWay == "wx_pc" || payWay == "wx_js" || payWay == "wx_app" {
-					table = "weixin_pay"
-				} else if payWay == "ali_pc" || payWay == "ali_app" {
-					table = "ali_pay"
-				} else {
-					return ""
-				}
-				wxPayMap := map[string]interface{}{}
-				wxPayMap["out_trade_no"] = out_trade_no
-				wxpay := util.Mysql.FindOne(table, wxPayMap, "", "")
-				return qutil.ObjToString((*wxpay)["transaction_id"])
-			}()
-		}
-
-		invoiceInfo := map[string]interface{}{}
-
-		//申请发票状态为1时返回发票信息
-		if applybill_status == 1 {
-			rdata := util.Mysql.FindOne("apply_invoice", map[string]interface{}{
-				"order_id": orderId,
-			}, "invoice_type,invoice_content,invoice_rise,apply_company,apply_tinumber,apply_regaddress,apply_regphone,apply_accountbank,apply_banknumber,apply_rcway,apply_realyname,apply_addressee,apply_phone,apply_address,apply_addressmore", "")
-			if rdata == nil {
-				return &entity.FuncResult{false, errors.New("未找到此订单发票信息"), nil}
-			}
-			invoiceInfo = map[string]interface{}{
-				"invoice_type":      (*rdata)["invoice_type"],
-				"invoice_content":   (*rdata)["invoice_content"],
-				"invoice_rise":      (*rdata)["invoice_rise"],
-				"apply_company":     (*rdata)["apply_company"],
-				"apply_tinumber":    (*rdata)["apply_tinumber"],
-				"apply_regaddress":  (*rdata)["apply_regaddress"],
-				"apply_regphone":    (*rdata)["apply_regphone"],
-				"apply_accountbank": (*rdata)["apply_accountbank"],
-				"apply_banknumber":  (*rdata)["apply_banknumber"],
-				"apply_rcway":       (*rdata)["apply_rcway"],
-				"apply_realyname":   (*rdata)["apply_realyname"],
-				"apply_addressee":   (*rdata)["apply_addressee"],
-				"apply_phone":       (*rdata)["apply_phone"],
-				"apply_address":     (*rdata)["apply_address"],
-				"apply_addressmore": (*rdata)["apply_addressmore"],
-			}
-		}
-
-		return &entity.FuncResult{true, nil, map[string]interface{}{
-			"payWay":           payWay,
-			"orderMoney":       orderMoney,
-			"orderCode":        order_code,
-			"orderId":          orderId,
-			"orderStatus":      orderStatus,
-			"payTime":          payTime,
-			"payTimes":         payTimes,
-			"out_trade_no":     out_trade_no,
-			"courseStatus":     courseStatus,
-			"applybill_status": applybill_status,
-			"invoiceInfo":      invoiceInfo,
-			"filter":           vmsg,
-			"canpaywx":         canpaywx,
-			"courseFlag":       courseFlag,
-		}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                orderCode := this.GetString("orderCode")
+                orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": orderCode,
+                        "user_id":    userId,
+                }, "id,prepay_time,pay_way,order_code,order_money,out_trade_no,product_type,pay_time,order_status,course_status,applybill_status,filter,filter_id", "")
+                if orderdata == nil {
+                        return &entity.FuncResult{false, errors.New("未找到订单"), nil}
+                }
+
+                filter_id := qutil.ObjToString((*orderdata)["filter_id"])
+                courseFlag := courseStatus(filter_id) //课程状态 已结束:false   正在进行中:true
+                orderId := qutil.Int64All((*orderdata)["id"])
+                payWay := qutil.ObjToString((*orderdata)["pay_way"])
+                orderMoney := qutil.IntAll((*orderdata)["order_money"])
+                order_code := qutil.ObjToString((*orderdata)["order_code"])
+                payTime := (*orderdata)["prepay_time"] //下单时间
+                out_trade_no := qutil.ObjToString((*orderdata)["out_trade_no"])
+                payTimes := (*orderdata)["pay_time"] //支付时间
+                orderStatus := qutil.IntAll((*orderdata)["order_status"])
+                courseStatus := qutil.IntAll((*orderdata)["course_status"])
+                applybill_status := qutil.IntAll((*orderdata)["applybill_status"]) //发票申请状态
+                vmsg := entity.JyCourseDetailMsg{}
+                filterStr := qutil.ObjToString((*orderdata)["filter"])
+                openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+                canpaywx := false
+                if openId != "" {
+                        canpaywx = true
+                }
+                if err := json.Unmarshal([]byte(filterStr), &vmsg); err != nil {
+                        log.Printf("%s course PayCallBack Unmarshal 出错 [%s]\n", userId, filterStr)
+                        return &entity.FuncResult{false, errors.New("序列化出错"), nil}
+                }
+                if orderStatus == 1 {
+                        out_trade_no = func() string {
+                                table := ""
+                                // 0微信支付 1支付宝支付
+                                if payWay == "wx_pc" || payWay == "wx_js" || payWay == "wx_app" {
+                                        table = "weixin_pay"
+                                } else if payWay == "ali_pc" || payWay == "ali_app" {
+                                        table = "ali_pay"
+                                } else {
+                                        return ""
+                                }
+                                wxPayMap := map[string]interface{}{}
+                                wxPayMap["out_trade_no"] = out_trade_no
+                                wxpay := util.Mysql.FindOne(table, wxPayMap, "", "")
+                                return qutil.ObjToString((*wxpay)["transaction_id"])
+                        }()
+                }
+
+                invoiceInfo := map[string]interface{}{}
+
+                //申请发票状态为1时返回发票信息
+                if applybill_status == 1 {
+                        rdata := util.Mysql.FindOne("apply_invoice", map[string]interface{}{
+                                "order_id": orderId,
+                        }, "invoice_type,invoice_content,invoice_rise,apply_company,apply_tinumber,apply_regaddress,apply_regphone,apply_accountbank,apply_banknumber,apply_rcway,apply_realyname,apply_addressee,apply_phone,apply_address,apply_addressmore", "")
+                        if rdata == nil {
+                                return &entity.FuncResult{false, errors.New("未找到此订单发票信息"), nil}
+                        }
+                        invoiceInfo = map[string]interface{}{
+                                "invoice_type":      (*rdata)["invoice_type"],
+                                "invoice_content":   (*rdata)["invoice_content"],
+                                "invoice_rise":      (*rdata)["invoice_rise"],
+                                "apply_company":     (*rdata)["apply_company"],
+                                "apply_tinumber":    (*rdata)["apply_tinumber"],
+                                "apply_regaddress":  (*rdata)["apply_regaddress"],
+                                "apply_regphone":    (*rdata)["apply_regphone"],
+                                "apply_accountbank": (*rdata)["apply_accountbank"],
+                                "apply_banknumber":  (*rdata)["apply_banknumber"],
+                                "apply_rcway":       (*rdata)["apply_rcway"],
+                                "apply_realyname":   (*rdata)["apply_realyname"],
+                                "apply_addressee":   (*rdata)["apply_addressee"],
+                                "apply_phone":       (*rdata)["apply_phone"],
+                                "apply_address":     (*rdata)["apply_address"],
+                                "apply_addressmore": (*rdata)["apply_addressmore"],
+                        }
+                }
+
+                return &entity.FuncResult{true, nil, map[string]interface{}{
+                        "payWay":           payWay,
+                        "orderMoney":       orderMoney,
+                        "orderCode":        order_code,
+                        "orderId":          orderId,
+                        "orderStatus":      orderStatus,
+                        "payTime":          payTime,
+                        "payTimes":         payTimes,
+                        "out_trade_no":     out_trade_no,
+                        "courseStatus":     courseStatus,
+                        "applybill_status": applybill_status,
+                        "invoiceInfo":      invoiceInfo,
+                        "filter":           vmsg,
+                        "canpaywx":         canpaywx,
+                        "courseFlag":       courseFlag,
+                }}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //退款
 func (this *CourseAction) Refund() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	productType := ""
-	r := func() *entity.FuncResult {
-		orderCode := this.GetString("orderCode")
-		refundReason := this.GetString("refundReason") //退款原因
-		orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": orderCode,
-			"user_id":    userId,
-		}, "id,course_status,filter,product_type", "")
-		if orderdata == nil {
-			return &entity.FuncResult{false, errors.New("未找到订单"), nil}
-		}
-
-		courseStatus := qutil.IntAll((*orderdata)["course_status"])
-		if courseStatus >= 5 {
-			return &entity.FuncResult{false, errors.New("已提交过退款申请"), nil}
-		}
-		vmsg := entity.JyCourseDetailMsg{}
-		filterStr := qutil.ObjToString((*orderdata)["filter"])
-		productType = qutil.ObjToString((*orderdata)["product_type"])
-		if err := json.Unmarshal([]byte(filterStr), &vmsg); err != nil {
-			log.Printf("%s course PayCallBack Unmarshal 出错 [%s]\n", userId, filterStr)
-			return &entity.FuncResult{false, errors.New("序列化出错"), nil}
-		}
-		vmsg.RefundReason = refundReason
-		now := time.Now()
-		refundTime := FormatDate(&now, Date_Full_Layout) //退款时间
-		vmsg.RefundTime = refundTime
-		datailMsg, errs := json.Marshal(vmsg)
-		if errs != nil {
-			return &entity.FuncResult{false, errors.New("数据格式转换异常"), nil}
-		}
-
-		update := util.Mysql.Update("dataexport_order", map[string]interface{}{
-			"order_status": 1,
-			"order_code":   orderCode,
-			"user_id":      userId,
-		}, map[string]interface{}{
-			"course_status": 5,
-			"filter":        string(datailMsg),
-		})
-		return &entity.FuncResult{update, nil, nil}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	} else {
-		//0:支付成功 1:对公转账凭证提交  2:申请退款
-		go entity.SendMailToOperation(2, this.GetString("orderCode"), productType, config.GmailAuth)
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        productType := ""
+        r := func() *entity.FuncResult {
+                orderCode := this.GetString("orderCode")
+                refundReason := this.GetString("refundReason") //退款原因
+                orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": orderCode,
+                        "user_id":    userId,
+                }, "id,course_status,filter,product_type", "")
+                if orderdata == nil {
+                        return &entity.FuncResult{false, errors.New("未找到订单"), nil}
+                }
+
+                courseStatus := qutil.IntAll((*orderdata)["course_status"])
+                if courseStatus >= 5 {
+                        return &entity.FuncResult{false, errors.New("已提交过退款申请"), nil}
+                }
+                vmsg := entity.JyCourseDetailMsg{}
+                filterStr := qutil.ObjToString((*orderdata)["filter"])
+                productType = qutil.ObjToString((*orderdata)["product_type"])
+                if err := json.Unmarshal([]byte(filterStr), &vmsg); err != nil {
+                        log.Printf("%s course PayCallBack Unmarshal 出错 [%s]\n", userId, filterStr)
+                        return &entity.FuncResult{false, errors.New("序列化出错"), nil}
+                }
+                vmsg.RefundReason = refundReason
+                now := time.Now()
+                refundTime := FormatDate(&now, Date_Full_Layout) //退款时间
+                vmsg.RefundTime = refundTime
+                datailMsg, errs := json.Marshal(vmsg)
+                if errs != nil {
+                        return &entity.FuncResult{false, errors.New("数据格式转换异常"), nil}
+                }
+
+                update := util.Mysql.Update("dataexport_order", map[string]interface{}{
+                        "order_status": 1,
+                        "order_code":   orderCode,
+                        "user_id":      userId,
+                }, map[string]interface{}{
+                        "course_status": 5,
+                        "filter":        string(datailMsg),
+                })
+                return &entity.FuncResult{update, nil, nil}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        } else {
+                //0:支付成功 1:对公转账凭证提交  2:申请退款
+                go entity.SendMailToOperation(2, this.GetString("orderCode"), productType, config.GmailAuth)
+        }
+        this.ServeJson(r.Format())
 }
 
 //保存发票信息
 func (this *CourseAction) SaveInvoice() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		orderCode := this.GetString("orderCode")
-		invoiceType := this.GetString("invoiceType")             //发票类型
-		regAddress := this.GetString("regAddress")               //注册地址
-		regPhone := this.GetString("regPhone")                   //注册电话
-		accountBank := this.GetString("accountBank")             //开户银行
-		bankNum := this.GetString("bankNum")                     //银行账号
-		invoiceRise := this.GetString("invoiceRise")             //发票抬头
-		invoiceCompany := this.GetString("invoiceCompany")       //开票单位
-		identificationNum := this.GetString("identificationNum") //纳税人识别号
-		name := this.GetString("name")                           //发票类型
-		rcWay := this.GetString("rcWay")                         //领取方式
-		addressee := this.GetString("addressee")                 //收件人
-		phone := this.GetString("phone")                         //手机号
-		address := this.GetString("address")                     //所在地区
-		addressMore := this.GetString("addressMore")             //详细地址
-		log.Println("orderCode", orderCode)
-		orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": orderCode,
-			"user_id":    userId,
-		}, "id,applybill_status", "")
-		if orderdata == nil {
-			return &entity.FuncResult{false, errors.New("未找到订单"), nil}
-		}
-		orderId := qutil.Int64All((*orderdata)["id"])
-
-		applybill_status := qutil.IntAll((*orderdata)["applybill_status"]) //发票申请状态
-		if applybill_status == 1 {
-			log.Println("发票已申请过")
-			return &entity.FuncResult{true, nil, nil}
-		}
-
-		//判断sql库是否  已经有此订单的发票申请。。。。
-		invoiceId := util.Mysql.Insert("apply_invoice", map[string]interface{}{
-			"invoice_type":      invoiceType,
-			"invoice_content":   "明细",
-			"invoice_rise":      invoiceRise,
-			"apply_company":     invoiceCompany,
-			"apply_tinumber":    identificationNum,
-			"apply_regaddress":  regAddress,
-			"apply_regphone":    regPhone,
-			"apply_accountbank": accountBank,
-			"apply_banknumber":  bankNum,
-			"apply_rcway":       rcWay,
-			"apply_realyname":   name,
-			"apply_addressee":   addressee,
-			"apply_phone":       phone,
-			"apply_address":     address,
-			"apply_addressmore": addressMore,
-			"order_id":          orderId,
-			"apply_date":        time.Now().Unix(),
-		})
-		if invoiceId == 0 {
-			return &entity.FuncResult{false, errors.New("数据库操作异常,请稍后重试"), nil}
-		}
-
-		//发票信息保存成功后修改订单发票申请状态
-		update := util.Mysql.Update("dataexport_order", map[string]interface{}{
-			"order_status": 1,
-			"user_id":      userId,
-			"id":           orderId,
-		}, map[string]interface{}{
-			"applybill_status": 1,
-		})
-		return &entity.FuncResult{update, nil, nil}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                orderCode := this.GetString("orderCode")
+                invoiceType := this.GetString("invoiceType")             //发票类型
+                regAddress := this.GetString("regAddress")               //注册地址
+                regPhone := this.GetString("regPhone")                   //注册电话
+                accountBank := this.GetString("accountBank")             //开户银行
+                bankNum := this.GetString("bankNum")                     //银行账号
+                invoiceRise := this.GetString("invoiceRise")             //发票抬头
+                invoiceCompany := this.GetString("invoiceCompany")       //开票单位
+                identificationNum := this.GetString("identificationNum") //纳税人识别号
+                name := this.GetString("name")                           //发票类型
+                rcWay := this.GetString("rcWay")                         //领取方式
+                addressee := this.GetString("addressee")                 //收件人
+                phone := this.GetString("phone")                         //手机号
+                address := this.GetString("address")                     //所在地区
+                addressMore := this.GetString("addressMore")             //详细地址
+                log.Println("orderCode", orderCode)
+                orderdata := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": orderCode,
+                        "user_id":    userId,
+                }, "id,applybill_status", "")
+                if orderdata == nil {
+                        return &entity.FuncResult{false, errors.New("未找到订单"), nil}
+                }
+                orderId := qutil.Int64All((*orderdata)["id"])
+
+                applybill_status := qutil.IntAll((*orderdata)["applybill_status"]) //发票申请状态
+                if applybill_status == 1 {
+                        log.Println("发票已申请过")
+                        return &entity.FuncResult{true, nil, nil}
+                }
+
+                //判断sql库是否  已经有此订单的发票申请。。。。
+                invoiceId := util.Mysql.Insert("apply_invoice", map[string]interface{}{
+                        "invoice_type":      invoiceType,
+                        "invoice_content":   "明细",
+                        "invoice_rise":      invoiceRise,
+                        "apply_company":     invoiceCompany,
+                        "apply_tinumber":    identificationNum,
+                        "apply_regaddress":  regAddress,
+                        "apply_regphone":    regPhone,
+                        "apply_accountbank": accountBank,
+                        "apply_banknumber":  bankNum,
+                        "apply_rcway":       rcWay,
+                        "apply_realyname":   name,
+                        "apply_addressee":   addressee,
+                        "apply_phone":       phone,
+                        "apply_address":     address,
+                        "apply_addressmore": addressMore,
+                        "order_id":          orderId,
+                        "apply_date":        time.Now().Unix(),
+                })
+                if invoiceId == 0 {
+                        return &entity.FuncResult{false, errors.New("数据库操作异常,请稍后重试"), nil}
+                }
+
+                //发票信息保存成功后修改订单发票申请状态
+                update := util.Mysql.Update("dataexport_order", map[string]interface{}{
+                        "order_status": 1,
+                        "user_id":      userId,
+                        "id":           orderId,
+                }, map[string]interface{}{
+                        "applybill_status": 1,
+                })
+                return &entity.FuncResult{update, nil, nil}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }

+ 237 - 230
src/jfw/modules/subscribepay/src/service/dataExportPay.go

@@ -1,34 +1,34 @@
 package service
 
 import (
-	"bytes"
-	"encoding/json"
-	"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"
-	"regexp"
-	"time"
+        "bytes"
+        "encoding/json"
+        "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"
+        "regexp"
+        "time"
 
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	"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/dataexport"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/encrypt"
+        "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/dataexport"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
+        qutil "app.yhyue.com/moapp/jybase/common"
 )
 
 type DataExportPay struct {
-	*xweb.Action
-	getPrice    xweb.Mapper `xweb:"/dataexport/getPrice"`    //获取数据导出价格
-	createOrder xweb.Mapper `xweb:"/dataExport/createOrder"` //移动端创建订单
-	//vipDailyDataExport        xweb.Mapper `xweb:"/dataExport/vipDaily"`        //大会员数据包数据导出
-	//vipDailyDataExportSuccess xweb.Mapper `xweb:"/dataExport/vipDailySuccess"` //大会员数据包导出生成是否成功
-	historyById xweb.Mapper `xweb:"/dataExport/historyById"` //历史条件
+        *xweb.Action
+        getPrice    xweb.Mapper `xweb:"/dataexport/getPrice"`    //获取数据导出价格
+        createOrder xweb.Mapper `xweb:"/dataExport/createOrder"` //移动端创建订单
+        //vipDailyDataExport        xweb.Mapper `xweb:"/dataExport/vipDaily"`        //大会员数据包数据导出
+        //vipDailyDataExportSuccess xweb.Mapper `xweb:"/dataExport/vipDailySuccess"` //大会员数据包导出生成是否成功
+        historyById xweb.Mapper `xweb:"/dataExport/historyById"` //历史条件
 }
 
 var reg *regexp.Regexp //匹配特殊字符
@@ -36,234 +36,241 @@ var reg *regexp.Regexp //匹配特殊字符
 var DateFullLayout = "2006-01-02 15:04:05"
 
 func init() {
-	reg, _ = regexp.Compile("[^A-Za-z0-9\u4e00-\u9fa5]")
+        reg, _ = regexp.Compile("[^A-Za-z0-9\u4e00-\u9fa5]")
 }
 
 // dataExportPhoneAndMailCheck 数据导出获取邮箱和手机号
 func dataExportPhoneAndMailCheck(sess *httpsession.Session) (phone, mail string, mailCheck bool) {
-	mail, _ = sess.Get("DataExportVerifyEmail_val").(string)
-	phone, _ = sess.Get("DataExportVerifyPhone").(string)
-	if phone != "" {
-		sess.Set("DataExportVerifyPhone_val", phone) //提交后下次默认带出手机号
-	} else {
-		phone, _ = sess.Get("DataExportVerifyPhone_val").(string)
-	}
-	mailCheck = qutil.ObjToString(sess.Get("DataExportVerifyEmail_val")) != ""
-	return
+        mail, _ = sess.Get("DataExportVerifyEmail_val").(string)
+        phone, _ = sess.Get("DataExportVerifyPhone").(string)
+        if phone != "" {
+                sess.Set("DataExportVerifyPhone_val", phone) //提交后下次默认带出手机号
+        } else {
+                phone, _ = sess.Get("DataExportVerifyPhone_val").(string)
+        }
+        mailCheck = qutil.ObjToString(sess.Get("DataExportVerifyEmail_val")) != ""
+        return
 }
 
 //移动端创建订单
 func (p *DataExportPay) CreateOrder() {
-	defer qutil.Catch()
-	openId, _ := p.GetSession("s_m_openid").(string)
-	userId, _ := p.GetSession("userId").(string)
-	id := encrypt.SE.Decode4Hex(p.GetString("id"))
-	if userId == "" || id == "" {
-		p.ServeJson(map[string]interface{}{
-			"status": "n",
-		})
-		return
-	}
-	//
-	data_spec := p.GetString("data_spec")
-	if data_spec == "standard" {
-		data_spec = "标准字段包"
-	} else if data_spec == "senior" {
-		data_spec = "高级字段包"
-	}
+        defer qutil.Catch()
+        openId, _ := p.GetSession("s_m_openid").(string)
+        userId, _ := p.GetSession("userId").(string)
+        id := encrypt.SE.Decode4Hex(p.GetString("id"))
+        if userId == "" || id == "" {
+                p.ServeJson(map[string]interface{}{
+                        "status": "n",
+                })
+                return
+        }
+        //
+        data_spec := p.GetString("data_spec")
+        if data_spec == "standard" {
+                data_spec = "标准字段包"
+        } else if data_spec == "senior" {
+                data_spec = "高级字段包"
+        }
 
-	data_count := dataexport.GetDataExportSearchCountByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, id)
-	if data_count > config.ExConf.MsgMaxCount || data_count == -1 {
-		data_count = config.ExConf.MsgMaxCount
-	}
+        data_count := dataexport.GetDataExportSearchCountByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, id)
+        if data_count > config.ExConf.MsgMaxCount || data_count == -1 {
+                data_count = config.ExConf.MsgMaxCount
+        }
 
-	if data_count <= 0 {
-		p.ServeJson(map[string]interface{}{
-			"status": "n",
-		})
-		return
-	}
+        if data_count <= 0 {
+                p.ServeJson(map[string]interface{}{
+                        "status": "n",
+                })
+                return
+        }
 
-	user_phone, user_mail, user_mail_status := entity.JyCommonOrderStruct.DataExportPhoneAndMailCheck(p.Session())
+        user_phone, user_mail, user_mail_status := entity.JyCommonOrderStruct.DataExportPhoneAndMailCheck(p.Session())
 
-	order_money_, original_price_ := float64(0), float64(0)
-	if data_spec == "标准字段包" {
-		original_price_ = float64(data_count) * config.ExConf.UnitPrice_normal
-	} else if data_spec == "高级字段包" {
-		original_price_ = float64(data_count) * config.ExConf.UnitPrice_senior
-	}
-	order_money_ = float64(original_price_) * config.ExConf.Discount
-	if order_money_ < config.ExConf.OrderMinPrice {
-		order_money_ = config.ExConf.OrderMinPrice
-	}
-	if original_price_ < config.ExConf.OrderMinPrice {
-		original_price_ = config.ExConf.OrderMinPrice
-	}
-	order_money := int(order_money_ * 100)
-	original_price := int(original_price_ * 100)
+        order_money_, original_price_ := float64(0), float64(0)
+        if data_spec == "标准字段包" {
+                original_price_ = float64(data_count) * config.ExConf.UnitPrice_normal
+        } else if data_spec == "高级字段包" {
+                original_price_ = float64(data_count) * config.ExConf.UnitPrice_senior
+        }
+        order_money_ = float64(original_price_) * config.ExConf.Discount
+        if order_money_ < config.ExConf.OrderMinPrice {
+                order_money_ = config.ExConf.OrderMinPrice
+        }
+        if original_price_ < config.ExConf.OrderMinPrice {
+                original_price_ = config.ExConf.OrderMinPrice
+        }
+        order_money := int(order_money_ * 100)
+        original_price := int(original_price_ * 100)
 
-	filter_keys, filter_publishtime, filter, disWord := "", "", "", ""
+        filter_keys, filter_publishtime, filter, disWord := "", "", "", ""
 
-	isPass := func() bool {
-		if user_mail == "" || user_phone == "" || !user_mail_status || data_spec == "" || order_money <= 0 || data_count <= 0 || original_price <= 0 {
-			log.Println("参数不合法! user_mail,user_phone, user_mail_status, data_spec, order_money, data_count, original_price", user_mail, user_phone, user_mail_status, data_spec, order_money, data_count, original_price)
-			return false
-		}
-		userfilter, ok := util.MQFW.FindById("export_search", id, nil)
-		if ok && userfilter != nil {
-			keywords, _ := (*userfilter)["keywords"].([]interface{})
-			var buffer bytes.Buffer
-			for _, v := range keywords {
-				vm, _ := v.(map[string]interface{})
-				if buffer.Len() > 0 {
-					buffer.WriteString(",")
-				}
-				buffer.WriteString(qutil.ObjToString(vm["keyword"]))
-			}
-			filter_keys = buffer.String()
-			filter_publishtime = qutil.ObjToString((*userfilter)["publishtime"])
-			disWord = qutil.ObjToString((*userfilter)["disWord"])
-			log.Println("口令:", disWord, config.Config.TermValidity)
-			delete(*userfilter, "selectIds")
-			filterByte, _ := json.Marshal(userfilter)
-			filter = string(filterByte)
+        isPass := func() bool {
+                if user_mail == "" || user_phone == "" || !user_mail_status || data_spec == "" || order_money <= 0 || data_count <= 0 || original_price <= 0 {
+                        log.Println("参数不合法! user_mail,user_phone, user_mail_status, data_spec, order_money, data_count, original_price", user_mail, user_phone, user_mail_status, data_spec, order_money, data_count, original_price)
+                        return false
+                }
+                userfilter, ok := util.MQFW.FindById("export_search", id, nil)
+                if ok && userfilter != nil {
+                        keywords, _ := (*userfilter)["keywords"].([]interface{})
+                        var buffer bytes.Buffer
+                        for _, v := range keywords {
+                                vm, _ := v.(map[string]interface{})
+                                if buffer.Len() > 0 {
+                                        buffer.WriteString(",")
+                                }
+                                buffer.WriteString(qutil.ObjToString(vm["keyword"]))
+                        }
+                        filter_keys = buffer.String()
+                        filter_publishtime = qutil.ObjToString((*userfilter)["publishtime"])
+                        disWord = qutil.ObjToString((*userfilter)["disWord"])
+                        log.Println("口令:", disWord, config.Config.TermValidity)
+                        delete(*userfilter, "selectIds")
+                        filterByte, _ := json.Marshal(userfilter)
+                        filter = string(filterByte)
 
-		} else {
-			return false
-		}
-		return true
-	}()
-	nickname, _ := p.GetSession("s_nickname").(string)
-	result := map[string]interface{}{
-		"status": "n",
-	}
-	if isPass {
-		//用户当前使用卡卷
-		userLotteryId := ""
-		var discount float64
-		full_price, reduce_price := 0, 0
-		//卡卷信息的id
-		lotteryId := p.GetString("lotteryId")
-		discount_price := 0
-		if lotteryId != "" {
-			full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, config.CouponConfig.Products["数据导出"])
-			if full_price <= order_money {
-				if discount == 100 {
-					order_money = order_money - reduce_price
-					discount_price = reduce_price
-				} else {
-					//折扣
-					disCount_int := int(math.Ceil(discount * 100))
-					discount_price = order_money - order_money*disCount_int/1000
-					order_money = order_money * disCount_int / 1000
-				}
-			} else {
-				userLotteryId = ""
-			}
-		}
-		ordercode := pay.GetOrderCode(openId)
-		download_url := util.GetExcelFilePath(ordercode)
-		go func() {
-			list, err := dataexport.GetDataExportSearchResultByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, id, qutil.If(data_spec == "高级字段包", "2", "1").(string), data_count)
-			if err == nil && list != nil && len(*list) > 0 {
-				list = dataexport.FormatExportData(util.MQFWENT, list, config.Config.WebDomain, qutil.If(data_spec == "高级字段包", "2", "1").(string))
-				err = util.CreateDataExportExcelFile(list, data_spec == "高级字段包", config.ExConf.ExcelReadyPath+download_url)
-			}
-			if err != nil {
-				errMeg := fmt.Sprintf("数据导出生成订单异常\n用户id:%s\n订单号:%s\n异常信息:%v:", userId, ordercode, err)
-				util.SendErrNoteToMail(errMeg)
-			}
-		}()
-		now := time.Now()
-		distributionChannel, orderChannel := util.GetJyOrderChannel(disWord, p.Header("User-Agent"))
-		orderid := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":          order_money,
-			"order_status":         0,
-			"service_status":       0,
-			"user_nickname":        nickname,
-			"user_openid":          openId,
-			"filter":               filter,
-			"order_code":           ordercode,
-			"product_type":         "历史数据",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       original_price,
-			"data_spec":            data_spec,
-			"user_mail":            user_mail,
-			"user_phone":           user_phone,
-			"data_count":           data_count,
-			"filter_publishtime":   filter_publishtime,
-			"filter_keys":          filter_keys,
-			"filter_id":            id,
-			"user_id":              userId, //20190719 移动端数据导出 生订单添加用户id
-			"download_url":         download_url,
-			"discount_price":       discount_price,
-			"d_relation_id":        userLotteryId,
-			"dis_word":             disWord,             //202020817分销口令
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		})
-		if orderid > 0 {
-			p.SetSession("DataExportVerifyPhone_val", user_phone)
-			result["status"] = "y"
-			result["code"] = ordercode
-			//保存结构化数据信息 记录
-			go func() {
-				if p.GetSession("Structed") != nil && p.GetSession("Structed").(bool) {
-					//姓名  手机号  邮箱
-					nickname, _ := p.GetSession("s_nickname").(string)
-					user_mail, _ := p.GetSession("DataExportVerifyEmail_val").(string)
-					user_phone, _ := p.GetSession("DataExportVerifyPhone").(string)
-					if user_phone == "" {
-						user_phone, _ = p.GetSession("DataExportVerifyPhone_val").(string)
-					}
-					util.StructedDataByExportData(nickname, user_mail, user_phone)
-					//清除存储标识
-					p.DelSession("Structed")
-				}
-			}()
-			//绑定卡卷
-			if userLotteryId != "" && lotteryId != "" {
-				go func(userId, userLotteryId, order_code string) {
-					nickname, _ := p.Session().Get("s_nickname").(string)
-					phone, _ := p.Session().Get("phone").(string)
-					if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "数据导出", "", 3, 0) {
-						log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-					}
-				}(userId, userLotteryId, ordercode)
-			}
-		}
-	}
-	p.ServeJson(result)
+                } else {
+                        return false
+                }
+                return true
+        }()
+        nickname, _ := p.GetSession("s_nickname").(string)
+        result := map[string]interface{}{
+                "status": "n",
+        }
+        if isPass {
+                //用户当前使用卡卷
+                userLotteryId := ""
+                var discount float64
+                full_price, reduce_price := 0, 0
+                //卡卷信息的id
+                lotteryId := p.GetString("lotteryId")
+                discount_price := 0
+                if lotteryId != "" {
+                        full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, config.CouponConfig.Products["数据导出"])
+                        if full_price <= order_money {
+                                if discount == 100 {
+                                        order_money = order_money - reduce_price
+                                        discount_price = reduce_price
+                                } else {
+                                        //折扣
+                                        disCount_int := int(math.Ceil(discount * 100))
+                                        discount_price = order_money - order_money*disCount_int/1000
+                                        order_money = order_money * disCount_int / 1000
+                                }
+                        } else {
+                                userLotteryId = ""
+                        }
+                }
+                ordercode := pay.GetOrderCode(openId)
+                download_url := util.GetExcelFilePath(ordercode)
+                go func() {
+                        list, err := dataexport.GetDataExportSearchResultByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, id, qutil.If(data_spec == "高级字段包", "2", "1").(string), data_count)
+                        if err == nil && list != nil && len(*list) > 0 {
+                                list = dataexport.FormatExportData(util.MQFWENT, list, config.Config.WebDomain, qutil.If(data_spec == "高级字段包", "2", "1").(string))
+                                err = util.CreateDataExportExcelFile(list, data_spec == "高级字段包", config.ExConf.ExcelReadyPath+download_url)
+                        }
+                        if err != nil {
+                                errMeg := fmt.Sprintf("数据导出生成订单异常\n用户id:%s\n订单号:%s\n异常信息:%v:", userId, ordercode, err)
+                                util.SendErrNoteToMail(errMeg)
+                        }
+                }()
+                now := time.Now()
+                distributionChannel, orderChannel := util.GetJyOrderChannel(disWord, p.Header("User-Agent"))
+                entId := qutil.Int64All(p.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                orderid := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":          order_money,
+                        "order_status":         0,
+                        "service_status":       0,
+                        "user_nickname":        nickname,
+                        "user_openid":          openId,
+                        "filter":               filter,
+                        "order_code":           ordercode,
+                        "product_type":         "历史数据",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       original_price,
+                        "data_spec":            data_spec,
+                        "user_mail":            user_mail,
+                        "user_phone":           user_phone,
+                        "data_count":           data_count,
+                        "filter_publishtime":   filter_publishtime,
+                        "filter_keys":          filter_keys,
+                        "filter_id":            id,
+                        "user_id":              userId, //20190719 移动端数据导出 生订单添加用户id
+                        "download_url":         download_url,
+                        "discount_price":       discount_price,
+                        "d_relation_id":        userLotteryId,
+                        "dis_word":             disWord,             //202020817分销口令
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                })
+                if orderid > 0 {
+                        p.SetSession("DataExportVerifyPhone_val", user_phone)
+                        result["status"] = "y"
+                        result["code"] = ordercode
+                        //保存结构化数据信息 记录
+                        go func() {
+                                if p.GetSession("Structed") != nil && p.GetSession("Structed").(bool) {
+                                        //姓名  手机号  邮箱
+                                        nickname, _ := p.GetSession("s_nickname").(string)
+                                        user_mail, _ := p.GetSession("DataExportVerifyEmail_val").(string)
+                                        user_phone, _ := p.GetSession("DataExportVerifyPhone").(string)
+                                        if user_phone == "" {
+                                                user_phone, _ = p.GetSession("DataExportVerifyPhone_val").(string)
+                                        }
+                                        util.StructedDataByExportData(nickname, user_mail, user_phone)
+                                        //清除存储标识
+                                        p.DelSession("Structed")
+                                }
+                        }()
+                        //绑定卡卷
+                        if userLotteryId != "" && lotteryId != "" {
+                                go func(userId, userLotteryId, order_code string) {
+                                        nickname, _ := p.Session().Get("s_nickname").(string)
+                                        phone, _ := p.Session().Get("phone").(string)
+                                        if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "数据导出", "", 3, 0) {
+                                                log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                                        }
+                                }(userId, userLotteryId, ordercode)
+                        }
+                }
+        }
+        p.ServeJson(result)
 }
 
 //获取价格
 func (p *DataExportPay) GetPrice() {
-	//获取数量
-	p.ServeJson(map[string]interface{}{
-		"unitPrice_normal": config.ExConf.UnitPrice_normal,
-		"unitPrice_senior": config.ExConf.UnitPrice_senior,
-		"discount":         config.ExConf.Discount,
-		"orderMinPrice":    config.ExConf.OrderMinPrice,
-		"msgMaxCount":      config.ExConf.MsgMaxCount,
-	})
+        //获取数量
+        p.ServeJson(map[string]interface{}{
+                "unitPrice_normal": config.ExConf.UnitPrice_normal,
+                "unitPrice_senior": config.ExConf.UnitPrice_senior,
+                "discount":         config.ExConf.Discount,
+                "orderMinPrice":    config.ExConf.OrderMinPrice,
+                "msgMaxCount":      config.ExConf.MsgMaxCount,
+        })
 }
 
 //根据id获取导出条件
 func (p *DataExportPay) HistoryById() {
-	id := p.GetString("id")
-	id = encrypt.SE.Decode4Hex(id)
-	if id != "" {
-		data, _ := util.MQFW.FindById("export_search", id, nil)
-		if data != nil {
-			delete(*data, "_id")
-			delete(*data, "comeintime")
-			delete(*data, "comeinfrom")
-			delete(*data, "s_openid")
-			delete(*data, "s_userid")
-		}
-		p.ServeJson(data)
-		return
-	}
-	p.ServeJson(map[string]interface{}{})
+        id := p.GetString("id")
+        id = encrypt.SE.Decode4Hex(id)
+        if id != "" {
+                data, _ := util.MQFW.FindById("export_search", id, nil)
+                if data != nil {
+                        delete(*data, "_id")
+                        delete(*data, "comeintime")
+                        delete(*data, "comeinfrom")
+                        delete(*data, "s_openid")
+                        delete(*data, "s_userid")
+                }
+                p.ServeJson(data)
+                return
+        }
+        p.ServeJson(map[string]interface{}{})
 }

+ 423 - 416
src/jfw/modules/subscribepay/src/service/dataexportPack.go

@@ -1,92 +1,92 @@
 package service
 
 import (
-	"encoding/json"
-	"fmt"
-	"io/ioutil"
-	"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"
-	"net/http"
-	"strconv"
-	"strings"
-	"time"
+        "encoding/json"
+        "fmt"
+        "io/ioutil"
+        "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"
+        "net/http"
+        "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/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/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/redis"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/dataexport"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 // 数据导出-数据包
 type DataExportPack struct {
-	*xweb.Action
-	packGoodsList  xweb.Mapper `xweb:"/dataExportPack/goodsList"`    //线上自助数据包充值-数据包列表
-	createOrder    xweb.Mapper `xweb:"/dataExportPack/createOrder"`  //线上自助数据包充值-创建订单
-	account        xweb.Mapper `xweb:"/dataExportPack/account"`      //数据导出-账户信息
-	statistics     xweb.Mapper `xweb:"/dataExportPack/statistics"`   //数据导出-选择导出去重统计
-	packPay        xweb.Mapper `xweb:"/dataExportPack/packPay"`      //数据导出-使用流量包扣除
-	fileCheck      xweb.Mapper `xweb:"/dataExportPack/fileCheck"`    //数据导出-使用流量包文件生成完成查询
-	rechargeList   xweb.Mapper `xweb:"/dataExportPack/rechargeList"` //数据导出-流量包充值记录
-	recordList     xweb.Mapper `xweb:"/dataExportPack/recordList"`   //数据导出记录
-	sendExportMail xweb.Mapper `xweb:"/dataExportPack/sendMail"`     //移动端导出记录发送附件邮件
+        *xweb.Action
+        packGoodsList  xweb.Mapper `xweb:"/dataExportPack/goodsList"`    //线上自助数据包充值-数据包列表
+        createOrder    xweb.Mapper `xweb:"/dataExportPack/createOrder"`  //线上自助数据包充值-创建订单
+        account        xweb.Mapper `xweb:"/dataExportPack/account"`      //数据导出-账户信息
+        statistics     xweb.Mapper `xweb:"/dataExportPack/statistics"`   //数据导出-选择导出去重统计
+        packPay        xweb.Mapper `xweb:"/dataExportPack/packPay"`      //数据导出-使用流量包扣除
+        fileCheck      xweb.Mapper `xweb:"/dataExportPack/fileCheck"`    //数据导出-使用流量包文件生成完成查询
+        rechargeList   xweb.Mapper `xweb:"/dataExportPack/rechargeList"` //数据导出-流量包充值记录
+        recordList     xweb.Mapper `xweb:"/dataExportPack/recordList"`   //数据导出记录
+        sendExportMail xweb.Mapper `xweb:"/dataExportPack/sendMail"`     //移动端导出记录发送附件邮件
 }
 
 // PackGoodsList 数据包规格及价格列表
 func (this *DataExportPack) PackGoodsList() {
-	packList, _ := entity.JyDataExportPack.GetPackPriceList()
-	userId, _ := this.GetSession("userId").(string)
-	if userId != "" {
-		getUrl := fmt.Sprintf("%s?useProduct=%s&appId=%s&useProductType=%v&userId=%s", config.CouponConfig.Giveinfo, config.CouponConfig.Products["数据流量包"], config.CouponConfig.AppId, 0, userId)
-		res, err := http.Get(getUrl)
-		if err != nil {
-			log.Println(err.Error())
-			this.ServeJson(packList)
-			return
-		}
-		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)
-		} else {
-			proDuctM := map[string]string{} //产品码对应关系
-			for k, v := range config.CouponConfig.Products {
-				proDuctM[v] = k
-			}
-			pl, _ := packList.(map[string]interface{})
-			marr := []map[string]interface{}{}
-			if qutil.IntAll(resMap["Code"]) == 1 {
-				for _, vv := range config.ExConf.Packs_showList {
-					m := map[string]interface{}{
-						"packNum":         vv.PackNum,
-						"normal_discount": vv.Normal_discount,
-						"senior_discount": vv.Senior_discount,
-					}
-					if resMap["Data"] != nil {
-						for _, v := range qutil.ObjArrToMapArr(resMap["Data"].([]interface{})) {
-							product := strconv.Itoa(qutil.IntAll(v["ProductCode"]))
-							if strings.Contains(proDuctM[product], strconv.Itoa(vv.PackNum)) {
-								m[fmt.Sprintf("%v_num", strings.Split(proDuctM[product], "_")[0])] = v["Time"]
-							}
-						}
-					}
-					marr = append(marr, m)
-				}
-				pl["packs_showList"] = marr
-				packList = pl
-			}
-		}
-	}
-	this.ServeJson(packList)
+        packList, _ := entity.JyDataExportPack.GetPackPriceList()
+        userId, _ := this.GetSession("userId").(string)
+        if userId != "" {
+                getUrl := fmt.Sprintf("%s?useProduct=%s&appId=%s&useProductType=%v&userId=%s", config.CouponConfig.Giveinfo, config.CouponConfig.Products["数据流量包"], config.CouponConfig.AppId, 0, userId)
+                res, err := http.Get(getUrl)
+                if err != nil {
+                        log.Println(err.Error())
+                        this.ServeJson(packList)
+                        return
+                }
+                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)
+                } else {
+                        proDuctM := map[string]string{} //产品码对应关系
+                        for k, v := range config.CouponConfig.Products {
+                                proDuctM[v] = k
+                        }
+                        pl, _ := packList.(map[string]interface{})
+                        marr := []map[string]interface{}{}
+                        if qutil.IntAll(resMap["Code"]) == 1 {
+                                for _, vv := range config.ExConf.Packs_showList {
+                                        m := map[string]interface{}{
+                                                "packNum":         vv.PackNum,
+                                                "normal_discount": vv.Normal_discount,
+                                                "senior_discount": vv.Senior_discount,
+                                        }
+                                        if resMap["Data"] != nil {
+                                                for _, v := range qutil.ObjArrToMapArr(resMap["Data"].([]interface{})) {
+                                                        product := strconv.Itoa(qutil.IntAll(v["ProductCode"]))
+                                                        if strings.Contains(proDuctM[product], strconv.Itoa(vv.PackNum)) {
+                                                                m[fmt.Sprintf("%v_num", strings.Split(proDuctM[product], "_")[0])] = v["Time"]
+                                                        }
+                                                }
+                                        }
+                                        marr = append(marr, m)
+                                }
+                                pl["packs_showList"] = marr
+                                packList = pl
+                        }
+                }
+        }
+        this.ServeJson(packList)
 }
 
 // CreateOrder 购买数据流量包公共方法
@@ -96,141 +96,148 @@ func (this *DataExportPack) PackGoodsList() {
 //
 // return orderCode 订单号
 func (this *DataExportPack) CreateOrder() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		packId := this.GetString("packId") //
-		// 获取用户分销口令
-		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() {
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                packId := this.GetString("packId") //
+                // 获取用户分销口令
+                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"])
-				}
-			}
-		}
+                                        disWordStr = qutil.ObjToString((*userfilter)["disWords"])
+                                }
+                        }
+                }
 
-		//根据id查询流量包价格
-		packDetail, err := entity.JyDataExportPack.GetPackDetailById(packId)
-		packDetail.GiveCycle = 0
-		packDetail.DisCountId = 0
-		if err != nil {
-			return nil, err
-		}
-		//卡券折扣
-		orderMoney, discountPrice := packDetail.Price, 0 //订单金额,卡券折扣金额
-		var userLotteryId string                         //用户卡券id
-		var discount float64
-		useProduct, _ := this.GetInteger("useProduct")
-		discountId, _ := this.GetInteger("discountId") //赠品相关
-		if lotteryId := this.GetString("lotteryId"); lotteryId != "" {
-			products := config.CouponConfig.Products["数据流量包"]
-			if useProduct > 0 {
-				products = strconv.Itoa(useProduct)
-			}
-			var fullPrice, reducePrice int
-			fullPrice, reducePrice, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
-			if fullPrice <= orderMoney {
-				if discount == 100 {
-					orderMoney = orderMoney - reducePrice
-					discountPrice = reducePrice
-				} else {
-					//折扣
-					disCount_int := int(math.Ceil(discount * 100))
-					discountPrice = orderMoney - orderMoney*disCount_int/1000
-					orderMoney = orderMoney * disCount_int / 1000
-				}
-				log.Printf("用户%s 购买数据流量包 使用卡券:%s 折扣金额:%d", userId, userLotteryId, discountPrice)
-			} else {
-				userLotteryId = ""
-			}
-		}
-		//赠品相关
-		useProduct, _ = strconv.Atoi(config.CouponConfig.Products[packId])
-		giveArr := entity.GiveInfo(userId, useProduct, 0, 0) //获取满赠时长
-		if giveArr != nil && len(giveArr) > 0 {
-			packDetail.GiveCycle = qutil.IntAll(giveArr[0]["Time"])
-			packDetail.DisCountId = qutil.IntAll(giveArr[0]["DiscountId"])
-			discountId = qutil.IntAll(giveArr[0]["DiscountId"])
-			if strings.Contains(qutil.ObjToString(giveArr[0]["ActivityName"]), config.Config.ActivityName) {
-				packDetail.Badge = "202111" //双十一角标展示
-			}
-		}
-		//
-		orderCode := pay.GetOrderCode()
-		nickname, _ := this.GetSession("s_nickname").(string)
-		openId, _ := this.GetSession("s_m_openid").(string)
-		now := time.Now()
-		filter, err := json.Marshal(packDetail)
-		if err != nil {
-			return nil, fmt.Errorf("数据异常")
-		}
-		distributionChannel, orderChannel := util.GetJyOrderChannel(disWordStr, this.Header("User-Agent"))
-		orderid := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":          orderMoney,
-			"order_status":         0,
-			"service_status":       0,
-			"user_nickname":        nickname,
-			"user_openid":          openId,
-			"user_phone":           this.GetString("order_phone"),
-			"order_code":           orderCode,
-			"product_type":         "数据流量包",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       packDetail.Price,
-			"filter":               string(filter),
-			"user_id":              userId, //20190719 移动端数据导出 生订单添加用户id
-			"discount_price":       discountPrice,
-			"d_relation_id":        userLotteryId,
-			"dis_word":             disWordStr,
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		})
-		if orderid <= 0 {
-			return nil, fmt.Errorf("创建订单异常")
-		}
-		//绑定核销卡券
-		if (userLotteryId != "" && this.GetString("lotteryId") != "") || (discountId > 0) {
-			go func(userId, userLotteryId, orderCode, discountIdStr string) {
-				phone, nickname := util.GetMyPhoneAndName(userId)
-				if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, orderCode, "数据流量包", discountIdStr, 3, 0) {
-					log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", orderCode, userLotteryId))
-				}
-				if discountId > 0 {
-					if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
-						userLotteryId = strconv.Itoa(ulid)
-					}
-				}
-			}(userId, userLotteryId, orderCode, strconv.Itoa(discountId))
-		}
-		return map[string]interface{}{
-			"orderCode": orderCode,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack CreateOrder 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                //根据id查询流量包价格
+                packDetail, err := entity.JyDataExportPack.GetPackDetailById(packId)
+                packDetail.GiveCycle = 0
+                packDetail.DisCountId = 0
+                if err != nil {
+                        return nil, err
+                }
+                //卡券折扣
+                orderMoney, discountPrice := packDetail.Price, 0 //订单金额,卡券折扣金额
+                var userLotteryId string                         //用户卡券id
+                var discount float64
+                useProduct, _ := this.GetInteger("useProduct")
+                discountId, _ := this.GetInteger("discountId") //赠品相关
+                if lotteryId := this.GetString("lotteryId"); lotteryId != "" {
+                        products := config.CouponConfig.Products["数据流量包"]
+                        if useProduct > 0 {
+                                products = strconv.Itoa(useProduct)
+                        }
+                        var fullPrice, reducePrice int
+                        fullPrice, reducePrice, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
+                        if fullPrice <= orderMoney {
+                                if discount == 100 {
+                                        orderMoney = orderMoney - reducePrice
+                                        discountPrice = reducePrice
+                                } else {
+                                        //折扣
+                                        disCount_int := int(math.Ceil(discount * 100))
+                                        discountPrice = orderMoney - orderMoney*disCount_int/1000
+                                        orderMoney = orderMoney * disCount_int / 1000
+                                }
+                                log.Printf("用户%s 购买数据流量包 使用卡券:%s 折扣金额:%d", userId, userLotteryId, discountPrice)
+                        } else {
+                                userLotteryId = ""
+                        }
+                }
+                //赠品相关
+                useProduct, _ = strconv.Atoi(config.CouponConfig.Products[packId])
+                giveArr := entity.GiveInfo(userId, useProduct, 0, 0) //获取满赠时长
+                if giveArr != nil && len(giveArr) > 0 {
+                        packDetail.GiveCycle = qutil.IntAll(giveArr[0]["Time"])
+                        packDetail.DisCountId = qutil.IntAll(giveArr[0]["DiscountId"])
+                        discountId = qutil.IntAll(giveArr[0]["DiscountId"])
+                        if strings.Contains(qutil.ObjToString(giveArr[0]["ActivityName"]), config.Config.ActivityName) {
+                                packDetail.Badge = "202111" //双十一角标展示
+                        }
+                }
+                //
+                orderCode := pay.GetOrderCode()
+                nickname, _ := this.GetSession("s_nickname").(string)
+                openId, _ := this.GetSession("s_m_openid").(string)
+                now := time.Now()
+                filter, err := json.Marshal(packDetail)
+                if err != nil {
+                        return nil, fmt.Errorf("数据异常")
+                }
+                distributionChannel, orderChannel := util.GetJyOrderChannel(disWordStr, this.Header("User-Agent"))
+                entId := qutil.Int64All(this.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                orderid := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":          orderMoney,
+                        "order_status":         0,
+                        "service_status":       0,
+                        "user_nickname":        nickname,
+                        "user_openid":          openId,
+                        "user_phone":           this.GetString("order_phone"),
+                        "order_code":           orderCode,
+                        "product_type":         "数据流量包",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       packDetail.Price,
+                        "filter":               string(filter),
+                        "user_id":              userId, //20190719 移动端数据导出 生订单添加用户id
+                        "discount_price":       discountPrice,
+                        "d_relation_id":        userLotteryId,
+                        "dis_word":             disWordStr,
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                })
+                if orderid <= 0 {
+                        return nil, fmt.Errorf("创建订单异常")
+                }
+                //绑定核销卡券
+                if (userLotteryId != "" && this.GetString("lotteryId") != "") || (discountId > 0) {
+                        go func(userId, userLotteryId, orderCode, discountIdStr string) {
+                                phone, nickname := util.GetMyPhoneAndName(userId)
+                                if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, orderCode, "数据流量包", discountIdStr, 3, 0) {
+                                        log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", orderCode, userLotteryId))
+                                }
+                                if discountId > 0 {
+                                        if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
+                                                userLotteryId = strconv.Itoa(ulid)
+                                        }
+                                }
+                        }(userId, userLotteryId, orderCode, strconv.Itoa(discountId))
+                }
+                return map[string]interface{}{
+                        "orderCode": orderCode,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack CreateOrder 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // Account 数据导出数据包账户详情
 func (this *DataExportPack) Account() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		accountMap, err := entity.JyDataExportPack.GetAccountMsg(this.Session(), userId)
-		if err != nil {
-			return nil, err
-		}
-		return accountMap, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack Account 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                accountMap, err := entity.JyDataExportPack.GetAccountMsg(this.Session(), userId)
+                if err != nil {
+                        return nil, err
+                }
+                return accountMap, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack Account 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // Statistics 数据导出筛选结果使用流量包扣除,去重
@@ -239,53 +246,53 @@ func (this *DataExportPack) Account() {
 //
 //	repeat 去重数量
 func (this *DataExportPack) Statistics() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		//企业数据包、个人数据包去重数量查询
-		filterId := encrypt.SE.Decode4Hex(this.GetString("filterId"))
-		if filterId == "" {
-			return nil, fmt.Errorf("请求参数异常")
-		}
-		selectCount := dataexport.GetDataExportSearchCountByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, filterId)
-		if selectCount > config.ExConf.MsgMaxCount || selectCount == -1 {
-			selectCount = config.ExConf.MsgMaxCount
-		}
-		if selectCount <= 0 {
-			return nil, fmt.Errorf("导出数据异常")
-		}
-		if entId := this.GetString("entId"); entId != "" {
-			deduct, err := entity.JyDataExportPack.DoEntPackRepeatCheck(this.Session(), userId, entId, filterId, selectCount)
-			if err != nil {
-				log.Printf("%s Statistics-DoEntPackRepeatCheck 查询导出id失败 %v\n", userId, err)
-				return nil, fmt.Errorf("去重查询失败")
-			}
-			return map[string]interface{}{
-				"repeat": selectCount - deduct,
-				"deduct": deduct,
-			}, nil
-		} else if packType := this.GetString("packType"); packType != "" {
-			ids, err := dataexport.GetDataExportIdArrByScdId(util.MQFW, config.Config.Elasticsearch, filterId, selectCount)
-			if err != nil {
-				log.Printf("%s Statistics 查询导出id失败 %v\n", userId, err)
-				return nil, fmt.Errorf("查询去重异常")
-			}
-			repeat, deduct, err := entity.JyDataExportPack.DoPerPackRepeatCheck(userId, packType == "senior", ids)
-			if err != nil {
-				log.Printf("%s Statistics-DoPerPackRepeatCheck 查询导出id失败 %v\n", userId, err)
-				return nil, fmt.Errorf("去重查询失败")
-			}
-			return map[string]interface{}{
-				"repeat": repeat,
-				"deduct": deduct,
-			}, nil
-		} else {
-			return nil, fmt.Errorf("未知请求")
-		}
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack Statistics 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                //企业数据包、个人数据包去重数量查询
+                filterId := encrypt.SE.Decode4Hex(this.GetString("filterId"))
+                if filterId == "" {
+                        return nil, fmt.Errorf("请求参数异常")
+                }
+                selectCount := dataexport.GetDataExportSearchCountByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, filterId)
+                if selectCount > config.ExConf.MsgMaxCount || selectCount == -1 {
+                        selectCount = config.ExConf.MsgMaxCount
+                }
+                if selectCount <= 0 {
+                        return nil, fmt.Errorf("导出数据异常")
+                }
+                if entId := this.GetString("entId"); entId != "" {
+                        deduct, err := entity.JyDataExportPack.DoEntPackRepeatCheck(this.Session(), userId, entId, filterId, selectCount)
+                        if err != nil {
+                                log.Printf("%s Statistics-DoEntPackRepeatCheck 查询导出id失败 %v\n", userId, err)
+                                return nil, fmt.Errorf("去重查询失败")
+                        }
+                        return map[string]interface{}{
+                                "repeat": selectCount - deduct,
+                                "deduct": deduct,
+                        }, nil
+                } else if packType := this.GetString("packType"); packType != "" {
+                        ids, err := dataexport.GetDataExportIdArrByScdId(util.MQFW, config.Config.Elasticsearch, filterId, selectCount)
+                        if err != nil {
+                                log.Printf("%s Statistics 查询导出id失败 %v\n", userId, err)
+                                return nil, fmt.Errorf("查询去重异常")
+                        }
+                        repeat, deduct, err := entity.JyDataExportPack.DoPerPackRepeatCheck(userId, packType == "senior", ids)
+                        if err != nil {
+                                log.Printf("%s Statistics-DoPerPackRepeatCheck 查询导出id失败 %v\n", userId, err)
+                                return nil, fmt.Errorf("去重查询失败")
+                        }
+                        return map[string]interface{}{
+                                "repeat": repeat,
+                                "deduct": deduct,
+                        }, nil
+                } else {
+                        return nil, fmt.Errorf("未知请求")
+                }
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack Statistics 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // PackPay 数据流量包扣除
@@ -295,189 +302,189 @@ func (this *DataExportPack) Statistics() {
 //
 // return	serialNumber 流水号(暂定为记录id)
 func (this *DataExportPack) PackPay() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		//企业数据包、个人数据包流量包支付
-		//数据总量,扣除量
-		total_req, _ := this.GetInteger("total") //导出总量
-		filterId := encrypt.SE.Decode4Hex(this.GetString("filterId"))
-		if filterId == "" {
-			return nil, fmt.Errorf("请求参数异常")
-		}
-		selectCount := dataexport.GetDataExportSearchCountByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, filterId)
-		if selectCount > config.ExConf.MsgMaxCount || selectCount == -1 {
-			selectCount = config.ExConf.MsgMaxCount
-		}
-		if total_req != selectCount {
-			return nil, fmt.Errorf("数据总量发生变化请重新导出")
-		}
-		switch this.GetString("doType") {
-		case "entPack": //企业数据包支付
-			entId := this.GetString("entId")
-			var userPhone, userMail string
-			if reqPhone, reqMail := this.GetString("order_phone"), this.GetString("order_email"); reqPhone != "" && reqMail != "" {
-				user_phone, user_mail, user_mail_status := dataExportPhoneAndMailCheck(this.Session())
-				if user_phone == "" || user_mail == "" || !user_mail_status || reqMail != user_mail {
-					log.Printf("%s 验证手机号邮箱异常 session[phone:%s,mail:%s,mailCheck:%v] request[phone:%s,mail:%s]\n", userId, user_phone, user_mail, user_mail_status, reqPhone, reqMail)
-					return nil, fmt.Errorf("验证手机号邮箱异常")
-				}
-				userPhone = reqPhone
-				userMail = reqMail
-			}
-			//扣除数量查询
-			err := entity.JyDataExportPack.UseEntPack(this.Session(), userId, entId, filterId, userPhone, userMail)
-			if err != nil {
-				return nil, err
-			}
-			return "success", nil
-		case "personalPack": //个人数据包支付
-			var userPhone, userMail string
-			if reqPhone, reqMail := this.GetString("order_phone"), this.GetString("order_email"); reqPhone != "" && reqMail != "" {
-				user_phone, user_mail, user_mail_status := dataExportPhoneAndMailCheck(this.Session())
-				if user_phone == "" || user_mail == "" || !user_mail_status || reqMail != user_mail {
-					log.Printf("%s 验证手机号邮箱异常 session[phone:%s,mail:%s,mailCheck:%v] request[phone:%s,mail:%s]\n", userId, user_phone, user_mail, user_mail_status, reqPhone, reqMail)
-					return nil, fmt.Errorf("验证手机号邮箱异常")
-				}
-				userPhone = reqPhone
-				userMail = reqMail
-			} else {
-				return nil, fmt.Errorf("验证手机号邮箱不能为空")
-			}
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                //企业数据包、个人数据包流量包支付
+                //数据总量,扣除量
+                total_req, _ := this.GetInteger("total") //导出总量
+                filterId := encrypt.SE.Decode4Hex(this.GetString("filterId"))
+                if filterId == "" {
+                        return nil, fmt.Errorf("请求参数异常")
+                }
+                selectCount := dataexport.GetDataExportSearchCountByScdId(util.MQFW, util.Mgo_bidding, config.Config.Mongobidding.DbName, config.Config.Elasticsearch, filterId)
+                if selectCount > config.ExConf.MsgMaxCount || selectCount == -1 {
+                        selectCount = config.ExConf.MsgMaxCount
+                }
+                if total_req != selectCount {
+                        return nil, fmt.Errorf("数据总量发生变化请重新导出")
+                }
+                switch this.GetString("doType") {
+                case "entPack": //企业数据包支付
+                        entId := this.GetString("entId")
+                        var userPhone, userMail string
+                        if reqPhone, reqMail := this.GetString("order_phone"), this.GetString("order_email"); reqPhone != "" && reqMail != "" {
+                                user_phone, user_mail, user_mail_status := dataExportPhoneAndMailCheck(this.Session())
+                                if user_phone == "" || user_mail == "" || !user_mail_status || reqMail != user_mail {
+                                        log.Printf("%s 验证手机号邮箱异常 session[phone:%s,mail:%s,mailCheck:%v] request[phone:%s,mail:%s]\n", userId, user_phone, user_mail, user_mail_status, reqPhone, reqMail)
+                                        return nil, fmt.Errorf("验证手机号邮箱异常")
+                                }
+                                userPhone = reqPhone
+                                userMail = reqMail
+                        }
+                        //扣除数量查询
+                        err := entity.JyDataExportPack.UseEntPack(this.Session(), userId, entId, filterId, userPhone, userMail)
+                        if err != nil {
+                                return nil, err
+                        }
+                        return "success", nil
+                case "personalPack": //个人数据包支付
+                        var userPhone, userMail string
+                        if reqPhone, reqMail := this.GetString("order_phone"), this.GetString("order_email"); reqPhone != "" && reqMail != "" {
+                                user_phone, user_mail, user_mail_status := dataExportPhoneAndMailCheck(this.Session())
+                                if user_phone == "" || user_mail == "" || !user_mail_status || reqMail != user_mail {
+                                        log.Printf("%s 验证手机号邮箱异常 session[phone:%s,mail:%s,mailCheck:%v] request[phone:%s,mail:%s]\n", userId, user_phone, user_mail, user_mail_status, reqPhone, reqMail)
+                                        return nil, fmt.Errorf("验证手机号邮箱异常")
+                                }
+                                userPhone = reqPhone
+                                userMail = reqMail
+                        } else {
+                                return nil, fmt.Errorf("验证手机号邮箱不能为空")
+                        }
 
-			packType := this.GetString("packType") //senior 高级字段;normal 普通字段包
-			//生成excel扣除,
-			_ = entity.JyDataExportPack.UsePersonalPack(userId, filterId, userPhone, userMail, packType == "senior", selectCount)
-			return "success", nil
-		case "dailyPack": //每日限量包扣除
-			var userPhone, userMail string
-			if reqPhone, reqMail := this.GetString("order_phone"), this.GetString("order_email"); reqPhone != "" && reqMail != "" {
-				user_phone, user_mail, user_mail_status := dataExportPhoneAndMailCheck(this.Session())
-				if user_phone == "" || user_mail == "" || !user_mail_status || reqMail != user_mail {
-					log.Printf("%s 验证手机号邮箱异常 session[phone:%s,mail:%s,mailCheck:%v] request[phone:%s,mail:%s]\n", userId, user_phone, user_mail, user_mail_status, reqPhone, reqMail)
-					return nil, fmt.Errorf("验证手机号邮箱异常")
-				}
-				userPhone = reqPhone
-				userMail = reqMail
-			}
-			err := entity.JyDataExportPack.UseDailyPack(userId, filterId, userPhone, userMail, selectCount, this.Session())
-			if err != nil {
-				return nil, err
-			}
-			return "success", nil
-		}
-		return nil, fmt.Errorf("未知请求")
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack PackPay 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                        packType := this.GetString("packType") //senior 高级字段;normal 普通字段包
+                        //生成excel扣除,
+                        _ = entity.JyDataExportPack.UsePersonalPack(userId, filterId, userPhone, userMail, packType == "senior", selectCount)
+                        return "success", nil
+                case "dailyPack": //每日限量包扣除
+                        var userPhone, userMail string
+                        if reqPhone, reqMail := this.GetString("order_phone"), this.GetString("order_email"); reqPhone != "" && reqMail != "" {
+                                user_phone, user_mail, user_mail_status := dataExportPhoneAndMailCheck(this.Session())
+                                if user_phone == "" || user_mail == "" || !user_mail_status || reqMail != user_mail {
+                                        log.Printf("%s 验证手机号邮箱异常 session[phone:%s,mail:%s,mailCheck:%v] request[phone:%s,mail:%s]\n", userId, user_phone, user_mail, user_mail_status, reqPhone, reqMail)
+                                        return nil, fmt.Errorf("验证手机号邮箱异常")
+                                }
+                                userPhone = reqPhone
+                                userMail = reqMail
+                        }
+                        err := entity.JyDataExportPack.UseDailyPack(userId, filterId, userPhone, userMail, selectCount, this.Session())
+                        if err != nil {
+                                return nil, err
+                        }
+                        return "success", nil
+                }
+                return nil, fmt.Errorf("未知请求")
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack PackPay 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // FileCheck 流量包导出,文件是否创建完成
 // param	serialNumber 流水号
 // return	filePath 下载文件地址
 func (this *DataExportPack) FileCheck() {
-	userId, _ := this.GetSession("userId").(string)
-	//查询是否完成
-	filterId := encrypt.SE.Decode4Hex(this.GetString("filterId"))
-	doType := this.GetString("doType")
-	var redisKey string
-	if doType == "personalPack" {
-		packType := this.GetString("packType") //senior 高级字段;normal 普通字段包
-		redisKey = fmt.Sprintf("%sResult_%s_%s_%v", doType, userId, filterId, qutil.If(packType == "senior", true, false))
-	} else {
-		redisKey = fmt.Sprintf("%sResult_%s_%s", doType, userId, filterId)
-	}
+        userId, _ := this.GetSession("userId").(string)
+        //查询是否完成
+        filterId := encrypt.SE.Decode4Hex(this.GetString("filterId"))
+        doType := this.GetString("doType")
+        var redisKey string
+        if doType == "personalPack" {
+                packType := this.GetString("packType") //senior 高级字段;normal 普通字段包
+                redisKey = fmt.Sprintf("%sResult_%s_%s_%v", doType, userId, filterId, qutil.If(packType == "senior", true, false))
+        } else {
+                redisKey = fmt.Sprintf("%sResult_%s_%s", doType, userId, filterId)
+        }
 
-	if data := redis.Get("other", redisKey); data != nil {
-		var returnData Result
-		apiStr, _ := data.(string)
-		err := json.Unmarshal([]byte(apiStr), &returnData)
-		if err != nil {
-			log.Printf("%s FileCheck %v apistr:%s\n", userId, err, apiStr)
-		}
-		this.ServeJson(returnData)
-	} else {
-		this.ServeJson(Result{
-			Error_code: 1,
-		})
-	}
+        if data := redis.Get("other", redisKey); data != nil {
+                var returnData Result
+                apiStr, _ := data.(string)
+                err := json.Unmarshal([]byte(apiStr), &returnData)
+                if err != nil {
+                        log.Printf("%s FileCheck %v apistr:%s\n", userId, err, apiStr)
+                }
+                this.ServeJson(returnData)
+        } else {
+                this.ServeJson(Result{
+                        Error_code: 1,
+                })
+        }
 }
 
 // RechargeList 数据流量包充值记录
 func (this *DataExportPack) RechargeList() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		pageSize, _ := this.GetInteger("pageSize")
-		pageNum, _ := this.GetInteger("pageNum")
-		total, list, err := entity.JyDataExportPack.PerRechargeList(userId, pageNum, pageSize)
-		if err != nil {
-			return nil, err
-		}
-		return map[string]interface{}{
-			"total": total,
-			"list":  list,
-		}, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack RechargeList 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                pageSize, _ := this.GetInteger("pageSize")
+                pageNum, _ := this.GetInteger("pageNum")
+                total, list, err := entity.JyDataExportPack.PerRechargeList(userId, pageNum, pageSize)
+                if err != nil {
+                        return nil, err
+                }
+                return map[string]interface{}{
+                        "total": total,
+                        "list":  list,
+                }, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack RechargeList 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // RecordList 数据导出记录
 func (this *DataExportPack) RecordList() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		pageSize, _ := this.GetInteger("pageSize")
-		pageNum, _ := this.GetInteger("pageNum")
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                pageSize, _ := this.GetInteger("pageSize")
+                pageNum, _ := this.GetInteger("pageNum")
 
-		vipMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-		entId := qutil.IntAll(this.GetSession("entId"))
-		entUserId := qutil.IntAll(this.GetSession("entUserId"))
+                vipMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                entId := qutil.IntAll(this.GetSession("entId"))
+                entUserId := qutil.IntAll(this.GetSession("entUserId"))
 
-		returnList, total, err := entity.JyDataExportPack.GetDataExportRecordList(userId, vipMsg.Pid, entId, entUserId, pageNum, pageSize)
-		if err != nil {
-			return nil, err
-		}
-		returnData := map[string]interface{}{
-			"list": returnList,
-		}
-		if total != -1 {
-			returnData["total"] = total
-		}
-		return returnData, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack RecordList 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+                returnList, total, err := entity.JyDataExportPack.GetDataExportRecordList(userId, vipMsg.Pid, entId, entUserId, pageNum, pageSize)
+                if err != nil {
+                        return nil, err
+                }
+                returnData := map[string]interface{}{
+                        "list": returnList,
+                }
+                if total != -1 {
+                        returnData["total"] = total
+                }
+                return returnData, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack RecordList 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }
 
 // sendExportMail 发送邮件
 func (this *DataExportPack) SendExportMail() {
-	userId, _ := this.GetSession("userId").(string)
-	rData, errMsg := func() (interface{}, error) {
-		downurl := this.GetString("downurl")
-		userMail := this.GetString("email")
-		if downurl == "" || userMail == "" {
-			return nil, fmt.Errorf("缺少字段")
-		}
-		mailContent := fmt.Sprintf(config.ExConf.Mail_attach_pack_attachment, downurl)
-		//用户发送邮件
-		sendOk := false
-		if userMail != "" {
-			if sendOk = util.SendRetryMail(config.ExConf.Mail_retry, userMail, "历史数据", mailContent, "", nil, config.GmailAuth); sendOk {
-				log.Printf("DataExportPack SendExportMail 地址%s:邮箱%s数据导出邮件发送成功!", downurl, userMail)
-			} else {
-				sendErr := fmt.Sprintf("DataExportPack SendExportMail地址%s:邮箱%s数据导出邮件发送失败", downurl, userMail)
-				log.Printf("%s DataExportPack SendExportMail 发送邮件失败 %v\n", userId, sendErr)
-			}
-		}
-		return sendOk, nil
-	}()
-	if errMsg != nil {
-		log.Printf("%s DataExportPack SendExportMail 异常:%s\n", userId, errMsg.Error())
-	}
-	this.ServeJson(NewResult(rData, errMsg))
+        userId, _ := this.GetSession("userId").(string)
+        rData, errMsg := func() (interface{}, error) {
+                downurl := this.GetString("downurl")
+                userMail := this.GetString("email")
+                if downurl == "" || userMail == "" {
+                        return nil, fmt.Errorf("缺少字段")
+                }
+                mailContent := fmt.Sprintf(config.ExConf.Mail_attach_pack_attachment, downurl)
+                //用户发送邮件
+                sendOk := false
+                if userMail != "" {
+                        if sendOk = util.SendRetryMail(config.ExConf.Mail_retry, userMail, "历史数据", mailContent, "", nil, config.GmailAuth); sendOk {
+                                log.Printf("DataExportPack SendExportMail 地址%s:邮箱%s数据导出邮件发送成功!", downurl, userMail)
+                        } else {
+                                sendErr := fmt.Sprintf("DataExportPack SendExportMail地址%s:邮箱%s数据导出邮件发送失败", downurl, userMail)
+                                log.Printf("%s DataExportPack SendExportMail 发送邮件失败 %v\n", userId, sendErr)
+                        }
+                }
+                return sendOk, nil
+        }()
+        if errMsg != nil {
+                log.Printf("%s DataExportPack SendExportMail 异常:%s\n", userId, errMsg.Error())
+        }
+        this.ServeJson(NewResult(rData, errMsg))
 }

+ 251 - 236
src/jfw/modules/subscribepay/src/service/entniche.go

@@ -1,254 +1,269 @@
 package service
 
 import (
-	"encoding/json"
-	"jy/src/jfw/modules/subscribepay/src/entity"
-	"jy/src/jfw/modules/subscribepay/src/pay"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"strings"
-	"time"
+        "encoding/json"
+        "jy/src/jfw/modules/subscribepay/src/entity"
+        "jy/src/jfw/modules/subscribepay/src/pay"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "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/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/go-xweb/xweb"
 )
 
 type Entniche struct {
-	*xweb.Action
-	buy      xweb.Mapper `xweb:"/entniche/buy"`
-	pay      xweb.Mapper `xweb:"/entniche/pay"`
-	buyAgain xweb.Mapper `xweb:"/entniche/buyAgain"`
+        *xweb.Action
+        buy      xweb.Mapper `xweb:"/entniche/buy"`
+        pay      xweb.Mapper `xweb:"/entniche/pay"`
+        buyAgain xweb.Mapper `xweb:"/entniche/buyAgain"`
 }
 
 func (e *Entniche) Buy() {
-	defer qutil.Catch()
-	if !R.CheckReqParam(e.ResponseWriter, e.Request, "entname", "industry", "personnum", "cycle") {
-		return
-	}
-	userId, _ := e.GetSession("userId").(string)
-	if phone, _ := util.GetMyPhoneAndName(userId); phone == "" {
-		R.NoPermissionReq(e.ResponseWriter, e.Request, "没有绑定手机号")
-		return
-	}
-	entname := strings.TrimSpace(e.GetString("entname"))
-	industry := strings.TrimSpace(e.GetString("industry"))
-	personnum, _ := e.GetInteger("personnum")
-	cycle, _ := e.GetInteger("cycle")
-	status, ordercode := func() (int, string) {
-		order_money := entity.EntnichePirce.GetOrderMoney(userId, personnum, cycle)
-		if order_money == -1 {
-			return 0, ""
-		}
-		code := pay.GetOrderCode(userId)
-		filter_map := map[string]interface{}{
-			"cycle":     cycle,
-			"personnum": personnum,
-			"industry":  industry,
-			"entname":   entname,
-		}
-		entId := entity.DecodeEntId(e.GetString("entid"))
-		if entId > 0 {
-			filter_map["entid"] = entId
-		}
-		filter, _ := json.Marshal(filter_map)
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", e.Header("User-Agent"))
-		order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":          order_money,
-			"order_status":         0,
-			"filter":               string(filter),
-			"order_code":           code,
-			"product_type":         "企业商机管理",
-			"create_time":          NowFormat(Date_Full_Layout),
-			"prepay_time":          NowFormat(Date_Full_Layout),
-			"user_id":              userId,
-			"pay_way":              "",
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		})
-		if order_id > 0 {
-			return 1, code
-		}
-		return 0, ""
-	}()
-	e.ServeJson(map[string]interface{}{
-		"error_code": 0,
-		"data": map[string]interface{}{
-			"status":    status,
-			"ordercode": ordercode,
-		},
-	})
+        defer qutil.Catch()
+        if !R.CheckReqParam(e.ResponseWriter, e.Request, "entname", "industry", "personnum", "cycle") {
+                return
+        }
+        userId, _ := e.GetSession("userId").(string)
+        if phone, _ := util.GetMyPhoneAndName(userId); phone == "" {
+                R.NoPermissionReq(e.ResponseWriter, e.Request, "没有绑定手机号")
+                return
+        }
+        entname := strings.TrimSpace(e.GetString("entname"))
+        industry := strings.TrimSpace(e.GetString("industry"))
+        personnum, _ := e.GetInteger("personnum")
+        cycle, _ := e.GetInteger("cycle")
+        status, ordercode := func() (int, string) {
+                order_money := entity.EntnichePirce.GetOrderMoney(userId, personnum, cycle)
+                if order_money == -1 {
+                        return 0, ""
+                }
+                code := pay.GetOrderCode(userId)
+                filter_map := map[string]interface{}{
+                        "cycle":     cycle,
+                        "personnum": personnum,
+                        "industry":  industry,
+                        "entname":   entname,
+                }
+                entId := entity.DecodeEntId(e.GetString("entid"))
+                if entId > 0 {
+                        filter_map["entid"] = entId
+                }
+
+                filter, _ := json.Marshal(filter_map)
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", e.Header("User-Agent"))
+                entid := qutil.Int64All(e.GetSession("entId"))
+                buy_subject := 1
+                if entid > 0 {
+                        buy_subject = 2
+                }
+                order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":          order_money,
+                        "order_status":         0,
+                        "filter":               string(filter),
+                        "order_code":           code,
+                        "product_type":         "企业商机管理",
+                        "create_time":          NowFormat(Date_Full_Layout),
+                        "prepay_time":          NowFormat(Date_Full_Layout),
+                        "user_id":              userId,
+                        "pay_way":              "",
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                })
+                if order_id > 0 {
+                        return 1, code
+                }
+                return 0, ""
+        }()
+        e.ServeJson(map[string]interface{}{
+                "error_code": 0,
+                "data": map[string]interface{}{
+                        "status":    status,
+                        "ordercode": ordercode,
+                },
+        })
 }
 func (e *Entniche) Pay() {
-	defer qutil.Catch()
-	if !R.CheckReqParam(e.ResponseWriter, e.Request, "ordercode", "payway") {
-		return
-	}
-	userId, _ := e.GetSession("userId").(string)
-	payway := e.GetString("payway")
-	status, payStr := func() (int, string) {
-		if payway != "wx_app" && payway != "ali_app" {
-			return 0, ""
-		}
-		order := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-			"order_code": e.GetString("ordercode"),
-		}, "id,order_money,filter,user_id", "")
-		user_id := qutil.ObjToString((*order)["user_id"])
-		if user_id != userId {
-			return 0, ""
-		}
-		var filter map[string]interface{}
-		err := json.Unmarshal([]byte(qutil.ObjToString((*order)["filter"])), &filter)
-		if err != nil {
-			log.Println("企业商机管理支付成功json.Unmarshal出错", err)
-			return 0, ""
-		}
-		order_money := qutil.IntAll((*order)["order_money"])
-		prepayid, payStr, tradeno := "", "", ""
-		if payway == "wx_app" {
-			var ret *map[string]string
-			tradeno, ret = pay.WxStruct.CreatePrepayOrder("H", e.IP(), "", "", order_money)
-			if ret == nil || (*ret)["status"] != "1" {
-				return 0, ""
-			}
-			prepayid = qutil.ObjToString((*ret)["prepayid"])
-			payStr = pay.WxStruct.GetAppWxPayStr(qutil.ObjToString((*ret)["prepayid"]))
-			if payStr == "" {
-				return 0, ""
-			}
-		} else if payway == "ali_app" {
-			var err error
-			payStr, tradeno, err = pay.Alipay.GetOrderPayParam((qutil.Float64All(order_money)), pay.ALI_ENTNICHE_APP)
-			if err != nil {
-				return 0, ""
-			}
-		}
-		now := time.Now()
-		if util.Mysql.Update("dataexport_order", map[string]interface{}{
-			"id": (*order)["id"],
-		}, map[string]interface{}{
-			"prepay_id":    prepayid,
-			"code_url":     payStr,
-			"out_trade_no": tradeno,
-			"prepay_time":  FormatDate(&now, Date_Full_Layout),
-			"pay_way":      payway,
-		}) {
-			return 1, payStr
-		} else {
-			return 0, ""
-		}
-	}()
-	e.ServeJson(map[string]interface{}{
-		"error_code": 0,
-		"data": map[string]interface{}{
-			"status": status,
-			"paystr": payStr,
-		},
-	})
+        defer qutil.Catch()
+        if !R.CheckReqParam(e.ResponseWriter, e.Request, "ordercode", "payway") {
+                return
+        }
+        userId, _ := e.GetSession("userId").(string)
+        payway := e.GetString("payway")
+        status, payStr := func() (int, string) {
+                if payway != "wx_app" && payway != "ali_app" {
+                        return 0, ""
+                }
+                order := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                        "order_code": e.GetString("ordercode"),
+                }, "id,order_money,filter,user_id", "")
+                user_id := qutil.ObjToString((*order)["user_id"])
+                if user_id != userId {
+                        return 0, ""
+                }
+                var filter map[string]interface{}
+                err := json.Unmarshal([]byte(qutil.ObjToString((*order)["filter"])), &filter)
+                if err != nil {
+                        log.Println("企业商机管理支付成功json.Unmarshal出错", err)
+                        return 0, ""
+                }
+                order_money := qutil.IntAll((*order)["order_money"])
+                prepayid, payStr, tradeno := "", "", ""
+                if payway == "wx_app" {
+                        var ret *map[string]string
+                        tradeno, ret = pay.WxStruct.CreatePrepayOrder("H", e.IP(), "", "", order_money)
+                        if ret == nil || (*ret)["status"] != "1" {
+                                return 0, ""
+                        }
+                        prepayid = qutil.ObjToString((*ret)["prepayid"])
+                        payStr = pay.WxStruct.GetAppWxPayStr(qutil.ObjToString((*ret)["prepayid"]))
+                        if payStr == "" {
+                                return 0, ""
+                        }
+                } else if payway == "ali_app" {
+                        var err error
+                        payStr, tradeno, err = pay.Alipay.GetOrderPayParam((qutil.Float64All(order_money)), pay.ALI_ENTNICHE_APP)
+                        if err != nil {
+                                return 0, ""
+                        }
+                }
+                now := time.Now()
+                if util.Mysql.Update("dataexport_order", map[string]interface{}{
+                        "id": (*order)["id"],
+                }, map[string]interface{}{
+                        "prepay_id":    prepayid,
+                        "code_url":     payStr,
+                        "out_trade_no": tradeno,
+                        "prepay_time":  FormatDate(&now, Date_Full_Layout),
+                        "pay_way":      payway,
+                }) {
+                        return 1, payStr
+                } else {
+                        return 0, ""
+                }
+        }()
+        e.ServeJson(map[string]interface{}{
+                "error_code": 0,
+                "data": map[string]interface{}{
+                        "status": status,
+                        "paystr": payStr,
+                },
+        })
 }
 
 //再次购买或续费 -- 参数 renew 1是续费 0再次购买
 func (e *Entniche) BuyAgain() {
-	defer qutil.Catch()
-	if !R.CheckReqParam(e.ResponseWriter, e.Request, "entname", "industry", "personnum", "cycle", "renew") {
-		return
-	}
-	entname := strings.TrimSpace(e.GetString("entname"))
-	industry := strings.TrimSpace(e.GetString("industry"))
-	personnum, _ := e.GetInteger("personnum")
-	cycle, _ := e.GetInteger("cycle")
-	userId, _ := e.GetSession("userId").(string)
-	renew, _ := e.GetInteger("renew") //1是续费 0再次购买
-	effective_cycle := 0
-	entid := 0
-	status, newOrderCode := func() (int, string) {
-		if renew == 1 {
-			var ent *map[string]interface{}
-			if encodeEntId := e.GetString("entid"); encodeEntId != "" {
-				entid = entity.DecodeEntId(encodeEntId)
-			} else if ordercode := e.GetString("ordercode"); ordercode != "" {
-				order := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
-					"order_code": ordercode,
-				}, "filter_id", "")
-				if order != nil {
-					entid = qutil.IntAll((*order)["filter_id"])
-				}
-			}
-			if entid > 0 {
-				ent = util.Mysql.FindOne("entniche_info", map[string]interface{}{
-					"id": entid,
-				}, "startdate,enddate", "")
-			}
-			if ent != nil {
-				//计算周期
-				year := time.Now().Year()
-				month := time.Now().Format("01")
-				end_year := time.Unix(qutil.Int64All((*ent)["enddate"]), 0).Format("2006")
-				end_month := time.Unix(qutil.Int64All((*ent)["enddate"]), 0).Format("01")
-				have_year := qutil.IntAll(end_year) - year
-				expect_cycle := 0
-				if have_year == 0 {
-					//生效日期
-					expect_cycle = qutil.IntAll(end_month) - qutil.IntAll(month) + cycle*12
-				} else if have_year > 0 {
-					if end_month > month {
-						expect_cycle = (qutil.IntAll(end_month) - qutil.IntAll(month)) + have_year*12 - +cycle*12
-					} else if end_month < month {
-						expect_cycle = (qutil.IntAll(end_month) + 12 - qutil.IntAll(month)) + (have_year-1)*12 + cycle*12
-					} else {
-						expect_cycle = have_year*12 + cycle*12
-					}
-				}
-				effective_cycle = expect_cycle - cycle*12
-				if expect_cycle > 36 {
-					return -1, ""
-				}
-			}
-		}
-		order_money := entity.EntnichePirce.GetOrderMoney(userId, personnum, cycle)
-		if order_money == -1 {
-			return 0, ""
-		}
-		code := pay.GetOrderCode(userId)
-		filter_map := map[string]interface{}{
-			"cycle":     cycle,
-			"personnum": personnum,
-			"industry":  industry,
-			"entname":   entname,
-		}
-		if entid > 0 {
-			filter_map["entid"] = entid
-		}
-		filter, _ := json.Marshal(filter_map)
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", e.Header("User-Agent"))
-		order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-			"order_money":          order_money,
-			"order_status":         0,
-			"filter":               string(filter),
-			"order_code":           code,
-			"product_type":         "企业商机管理",
-			"create_time":          NowFormat(Date_Full_Layout),
-			"prepay_time":          NowFormat(Date_Full_Layout),
-			"user_id":              userId,
-			"vip_type":             renew,
-			"pay_way":              "",
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-		})
-		if order_id > 0 {
-			return 1, code
-		}
-		return 0, ""
-	}()
+        defer qutil.Catch()
+        if !R.CheckReqParam(e.ResponseWriter, e.Request, "entname", "industry", "personnum", "cycle", "renew") {
+                return
+        }
+        entname := strings.TrimSpace(e.GetString("entname"))
+        industry := strings.TrimSpace(e.GetString("industry"))
+        personnum, _ := e.GetInteger("personnum")
+        cycle, _ := e.GetInteger("cycle")
+        userId, _ := e.GetSession("userId").(string)
+        entId := qutil.Int64All(e.GetSession("entId"))
+        renew, _ := e.GetInteger("renew") //1是续费 0再次购买
+        effective_cycle := 0
+        entid := 0
+        status, newOrderCode := func() (int, string) {
+                if renew == 1 {
+                        var ent *map[string]interface{}
+                        if encodeEntId := e.GetString("entid"); encodeEntId != "" {
+                                entid = entity.DecodeEntId(encodeEntId)
+                        } else if ordercode := e.GetString("ordercode"); ordercode != "" {
+                                order := util.Mysql.FindOne("dataexport_order", map[string]interface{}{
+                                        "order_code": ordercode,
+                                }, "filter_id", "")
+                                if order != nil {
+                                        entid = qutil.IntAll((*order)["filter_id"])
+                                }
+                        }
+                        if entid > 0 {
+                                ent = util.Mysql.FindOne("entniche_info", map[string]interface{}{
+                                        "id": entid,
+                                }, "startdate,enddate", "")
+                        }
+                        if ent != nil {
+                                //计算周期
+                                year := time.Now().Year()
+                                month := time.Now().Format("01")
+                                end_year := time.Unix(qutil.Int64All((*ent)["enddate"]), 0).Format("2006")
+                                end_month := time.Unix(qutil.Int64All((*ent)["enddate"]), 0).Format("01")
+                                have_year := qutil.IntAll(end_year) - year
+                                expect_cycle := 0
+                                if have_year == 0 {
+                                        //生效日期
+                                        expect_cycle = qutil.IntAll(end_month) - qutil.IntAll(month) + cycle*12
+                                } else if have_year > 0 {
+                                        if end_month > month {
+                                                expect_cycle = (qutil.IntAll(end_month) - qutil.IntAll(month)) + have_year*12 - +cycle*12
+                                        } else if end_month < month {
+                                                expect_cycle = (qutil.IntAll(end_month) + 12 - qutil.IntAll(month)) + (have_year-1)*12 + cycle*12
+                                        } else {
+                                                expect_cycle = have_year*12 + cycle*12
+                                        }
+                                }
+                                effective_cycle = expect_cycle - cycle*12
+                                if expect_cycle > 36 {
+                                        return -1, ""
+                                }
+                        }
+                }
+                order_money := entity.EntnichePirce.GetOrderMoney(userId, personnum, cycle)
+                if order_money == -1 {
+                        return 0, ""
+                }
+                code := pay.GetOrderCode(userId)
+                filter_map := map[string]interface{}{
+                        "cycle":     cycle,
+                        "personnum": personnum,
+                        "industry":  industry,
+                        "entname":   entname,
+                }
+                if entid > 0 {
+                        filter_map["entid"] = entid
+                }
+                filter, _ := json.Marshal(filter_map)
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", e.Header("User-Agent"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                order_id := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                        "order_money":          order_money,
+                        "order_status":         0,
+                        "filter":               string(filter),
+                        "order_code":           code,
+                        "product_type":         "企业商机管理",
+                        "create_time":          NowFormat(Date_Full_Layout),
+                        "prepay_time":          NowFormat(Date_Full_Layout),
+                        "user_id":              userId,
+                        "vip_type":             renew,
+                        "pay_way":              "",
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                })
+                if order_id > 0 {
+                        return 1, code
+                }
+                return 0, ""
+        }()
 
-	e.ServeJson(map[string]interface{}{
-		"error_code": 0,
-		"data": map[string]interface{}{
-			"status":          status,
-			"ordercode":       newOrderCode,
-			"effective_cycle": effective_cycle,
-		},
-	})
+        e.ServeJson(map[string]interface{}{
+                "error_code": 0,
+                "data": map[string]interface{}{
+                        "status":          status,
+                        "ordercode":       newOrderCode,
+                        "effective_cycle": effective_cycle,
+                },
+        })
 }

+ 206 - 206
src/jfw/modules/subscribepay/src/service/index_p1.go

@@ -1,230 +1,230 @@
 package service
 
 import (
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/config"
-	"jy/src/jfw/modules/subscribepay/src/entity"
-	"jy/src/jfw/modules/subscribepay/src/util"
-	"log"
-	"strings"
-	"time"
+        "fmt"
+        "jy/src/jfw/modules/subscribepay/src/config"
+        "jy/src/jfw/modules/subscribepay/src/entity"
+        "jy/src/jfw/modules/subscribepay/src/util"
+        "log"
+        "strings"
+        "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/go-xweb/xweb"
-	"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/go-xweb/xweb"
+        "app.yhyue.com/moapp/jybase/redis"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 )
 
 type IndexSearch struct {
-	*xweb.Action
-	getIndexMessage xweb.Mapper `xweb:"/index/getIndexMessage"` //首页p1数据
+        *xweb.Action
+        getIndexMessage xweb.Mapper `xweb:"/index/getIndexMessage"` //首页p1数据
 }
 
 const (
-	search_index = "bidding"
-	search_type  = "bidding"
-	search_field = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","budget","spidercode","site"`
+        search_index = "bidding"
+        search_type  = "bidding"
+        search_field = `"_id","title","publishtime","toptype","subtype","type","area","city","s_subscopeclass","budget","spidercode","site"`
 
-	query               = `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": 1}},"highlight": {"pre_tags": ["<a>"],"post_tags": ["</a>"],"fields": {"title": {"fragment_size": 0,"number_of_fragments": 1}}},"_source":[` + search_field + `],"sort":[{"publishtime":"desc"},{"budget":"desc"}],"from":0,"size":20}`
-	multi_match         = `{"multi_match": {"query": %s,"type": "phrase", "fields": ["title"]}}`
-	query_bool_must     = `{"terms":{"%s":[%s]}}`
-	query_bool_must_and = `{"bool":{"must":[%s],"must_not":[%s]}}`
+        query               = `{"query":{"bool":{"must":[%s],"should":[%s],"minimum_should_match": 1}},"highlight": {"pre_tags": ["<a>"],"post_tags": ["</a>"],"fields": {"title": {"fragment_size": 0,"number_of_fragments": 1}}},"_source":[` + search_field + `],"sort":[{"publishtime":"desc"},{"budget":"desc"}],"from":0,"size":20}`
+        multi_match         = `{"multi_match": {"query": %s,"type": "phrase", "fields": ["title"]}}`
+        query_bool_must     = `{"terms":{"%s":[%s]}}`
+        query_bool_must_and = `{"bool":{"must":[%s],"must_not":[%s]}}`
 )
 
 func (this *IndexSearch) GetIndexMessage() {
-	areaCity := this.GetString("city")
-	nReq, _ := this.GetInteger("nReq")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	if userId != "" {
-		redisData := redis.Get("other", "p1_indexMessage_"+userId)
-		if redisData != nil {
-			result_, ok := redisData.(map[string]interface{})
-			if ok {
-				this.ServeJson(map[string]interface{}{
-					"success": true,
-					"errMsg":  "",
-					"data":    result_,
-				})
-				return
-			}
-		}
-		r := func() *entity.FuncResult {
-			//获取订阅信息
-			userMap, ok := util.MQFW.FindById("user", userId, `{"o_jy":1,"o_vipjy":1,"i_vip_status":1}`)
-			if !ok || userMap == nil || len(*userMap) == 0 {
-				//查询出错
-				return &entity.FuncResult{false, errors.New("未查询到用户信息"), nil}
-			}
-			//根据订阅词获取查询语句
-			vipStatus := qutil.IntAll((*userMap)["i_vip_status"])
-			//vip用户
-			if vipStatus > 0 {
-				o_msgset := qutil.ObjToMap((*userMap)["o_vipjy"])
-				vip_items, ok := (*o_msgset)["a_items"].([]interface{})
-				//vip查询推送历史
-				result := getPushHistory(userId)
-				return &entity.FuncResult{true, nil, map[string]interface{}{
-					"isVip":        true,                     //是否是vip用户
-					"hasSubscribe": ok && len(vip_items) > 0, //是否有订阅词
-					"listLength":   len(result),              //数据长度
-					"list":         result,                   //数据
-				}}
-			}
-			//普通用户用户
-			o_msgset := qutil.ObjToMap((*userMap)["o_jy"])
-			items, ok := (*o_msgset)["a_key"].([]interface{})
-			if ok && len(items) > 0 {
-				//普通用户查询推送历史
-				result := getPushHistory(userId)
-				return &entity.FuncResult{true, nil, map[string]interface{}{
-					"isVip":        false,                //是否是vip用户
-					"hasSubscribe": ok && len(items) > 0, //是否有订阅词
-					"listLength":   len(result),          //数据长度
-					"list":         result,               //数据
-				}}
-			}
-			//普通用户无订阅词
-			var history []string
-			var _history []string
-			h := redis.GetStr("other", "s_"+userId) //用户所有的搜索历史
-			if h != "" {
-				history = strings.Split(h, ",")
-				_history = strings.Split(h, ",")
-				for k, v := range _history {
-					//默认关键词不超过35个字符
-					b_word, _, _ := jy.InterceptSearchKW(v, qutil.IntAllDef(config.Config.KeywordsLimit, 35), true)
-					if b_word == "" {
-						_history = append(_history[:k], _history[k+1:]...)
-					}
-				}
-			}
-			var list *[]map[string]interface{}
-			if nReq == 2 || len(_history) > 0 { //根据定位请求数据
-				doSearchStr := getSimpleSql(areaCity, _history)
-				list = elastic.Get(search_index, search_type, doSearchStr)
-				util.BidListConvert("", list)
-			}
-			listLength := 0
-			if list != nil {
-				for _, v := range *list {
-					v["_id"] = encrypt.EncodeArticleId2ByCheck(v["_id"].(string))
-					delete(v, "s_subscopeclass")
-				}
-				listLength = len(*list)
-			}
-			return &entity.FuncResult{true, nil, map[string]interface{}{
-				"isVip":        false,            //是否是vip用户
-				"hasSubscribe": false,            //是否有订阅词
-				"hasHistory":   len(history) > 0, //是否有搜索历史
-				"listLength":   listLength,       //数据长度
-				"list":         list,             //数据
-				"history":      history,          //历史数据
-			}}
-		}()
-		result := r.Format()
-		if r.Err != nil {
-			log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-		}
-		//如果有数据,则缓存redis
-		if r.Success && qutil.IntAll(r.Data["listLength"]) > 0 {
-			redis.Put("other", "p1_indexMessage_"+userId, r.Data, 24*60*60)
-		}
-		this.ServeJson(result)
-		return
-	} else {
-		redisData := redis.Get("other", "p1_indexMessage_"+areaCity)
-		if redisData != nil {
-			result_, ok := redisData.(map[string]interface{})
-			if ok {
-				this.ServeJson(map[string]interface{}{
-					"success": true,
-					"errMsg":  "",
-					"data":    result_,
-				})
-				return
-			}
-		}
-		r := func() *entity.FuncResult {
-			var list *[]map[string]interface{}
-			if nReq == 2 { //根据定位请求数据
-				doSearchStr := getSimpleSql(areaCity, nil)
-				list = elastic.Get(search_index, search_type, doSearchStr)
-				util.BidListConvert("", list)
-			}
-			listLength := 0
-			if list != nil {
-				for _, v := range *list {
-					v["_id"] = encrypt.EncodeArticleId2ByCheck(v["_id"].(string))
-					delete(v, "s_subscopeclass")
-				}
-				listLength = len(*list)
-			}
-			return &entity.FuncResult{true, nil, map[string]interface{}{
-				"isVip":        false,      //是否是vip用户
-				"hasSubscribe": false,      //是否有订阅词
-				"hasHistory":   false,      //是否有搜索历史
-				"listLength":   listLength, //数据长度
-				"list":         list,       //数据
-				"history":      nil,        //历史数据
-			}}
-		}()
-		if r.Err != nil {
-			log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-		}
-		//如果有数据,则缓存redis
-		if r.Success && qutil.IntAll(r.Data["listLength"]) > 0 {
-			redis.Put("other", "p1_indexMessage_"+areaCity, r.Data, 24*60*60)
-		}
-		result := r.Format()
-		this.ServeJson(result)
-		return
-	}
+        areaCity := this.GetString("city")
+        nReq, _ := this.GetInteger("nReq")
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        if userId != "" {
+                redisData := redis.Get("other", "p1_indexMessage_"+userId)
+                if redisData != nil {
+                        result_, ok := redisData.(map[string]interface{})
+                        if ok {
+                                this.ServeJson(map[string]interface{}{
+                                        "success": true,
+                                        "errMsg":  "",
+                                        "data":    result_,
+                                })
+                                return
+                        }
+                }
+                r := func() *entity.FuncResult {
+                        //获取订阅信息
+                        /*userMap, ok := util.MQFW.FindById("user", userId, `{"o_jy":1,"o_vipjy":1,"i_vip_status":1}`)
+                          if !ok || userMap == nil || len(*userMap) == 0 {
+                          	//查询出错
+                          	return &entity.FuncResult{false, errors.New("未查询到用户信息"), nil}
+                          }*/
+                        //根据订阅词获取查询语句
+                        userMap := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                        vipStatus := userMap.Data.Vip.Status
+                        //vip用户
+                        if vipStatus > 0 {
+                                o_msgset := jy.GetSubScribeInfo(this.Session(), util.MQFW, "v", "10000")
+                                vip_items, ok := (*o_msgset)["a_items"].([]interface{})
+                                //vip查询推送历史
+                                result := getPushHistory(userId)
+                                return &entity.FuncResult{true, nil, map[string]interface{}{
+                                        "isVip":        true,                     //是否是vip用户
+                                        "hasSubscribe": ok && len(vip_items) > 0, //是否有订阅词
+                                        "listLength":   len(result),              //数据长度
+                                        "list":         result,                   //数据
+                                }}
+                        }
+                        //普通用户用户
+                        o_msgset := jy.GetSubScribeInfo(this.Session(), util.MQFW, "f", "10000")
+                        items, ok := (*o_msgset)["a_key"].([]interface{})
+                        if ok && len(items) > 0 {
+                                //普通用户查询推送历史
+                                result := getPushHistory(userId)
+                                return &entity.FuncResult{true, nil, map[string]interface{}{
+                                        "isVip":        false,                //是否是vip用户
+                                        "hasSubscribe": ok && len(items) > 0, //是否有订阅词
+                                        "listLength":   len(result),          //数据长度
+                                        "list":         result,               //数据
+                                }}
+                        }
+                        //普通用户无订阅词
+                        var history []string
+                        var _history []string
+                        h := redis.GetStr("other", "s_"+userId) //用户所有的搜索历史
+                        if h != "" {
+                                history = strings.Split(h, ",")
+                                _history = strings.Split(h, ",")
+                                for k, v := range _history {
+                                        //默认关键词不超过35个字符
+                                        b_word, _, _ := jy.InterceptSearchKW(v, qutil.IntAllDef(config.Config.KeywordsLimit, 35), true)
+                                        if b_word == "" {
+                                                _history = append(_history[:k], _history[k+1:]...)
+                                        }
+                                }
+                        }
+                        var list *[]map[string]interface{}
+                        if nReq == 2 || len(_history) > 0 { //根据定位请求数据
+                                doSearchStr := getSimpleSql(areaCity, _history)
+                                list = elastic.Get(search_index, search_type, doSearchStr)
+                                util.BidListConvert("", list)
+                        }
+                        listLength := 0
+                        if list != nil {
+                                for _, v := range *list {
+                                        v["_id"] = encrypt.EncodeArticleId2ByCheck(v["_id"].(string))
+                                        delete(v, "s_subscopeclass")
+                                }
+                                listLength = len(*list)
+                        }
+                        return &entity.FuncResult{true, nil, map[string]interface{}{
+                                "isVip":        false,            //是否是vip用户
+                                "hasSubscribe": false,            //是否有订阅词
+                                "hasHistory":   len(history) > 0, //是否有搜索历史
+                                "listLength":   listLength,       //数据长度
+                                "list":         list,             //数据
+                                "history":      history,          //历史数据
+                        }}
+                }()
+                result := r.Format()
+                if r.Err != nil {
+                        log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+                }
+                //如果有数据,则缓存redis
+                if r.Success && qutil.IntAll(r.Data["listLength"]) > 0 {
+                        redis.Put("other", "p1_indexMessage_"+userId, r.Data, 24*60*60)
+                }
+                this.ServeJson(result)
+                return
+        } else {
+                redisData := redis.Get("other", "p1_indexMessage_"+areaCity)
+                if redisData != nil {
+                        result_, ok := redisData.(map[string]interface{})
+                        if ok {
+                                this.ServeJson(map[string]interface{}{
+                                        "success": true,
+                                        "errMsg":  "",
+                                        "data":    result_,
+                                })
+                                return
+                        }
+                }
+                r := func() *entity.FuncResult {
+                        var list *[]map[string]interface{}
+                        if nReq == 2 { //根据定位请求数据
+                                doSearchStr := getSimpleSql(areaCity, nil)
+                                list = elastic.Get(search_index, search_type, doSearchStr)
+                                util.BidListConvert("", list)
+                        }
+                        listLength := 0
+                        if list != nil {
+                                for _, v := range *list {
+                                        v["_id"] = encrypt.EncodeArticleId2ByCheck(v["_id"].(string))
+                                        delete(v, "s_subscopeclass")
+                                }
+                                listLength = len(*list)
+                        }
+                        return &entity.FuncResult{true, nil, map[string]interface{}{
+                                "isVip":        false,      //是否是vip用户
+                                "hasSubscribe": false,      //是否有订阅词
+                                "hasHistory":   false,      //是否有搜索历史
+                                "listLength":   listLength, //数据长度
+                                "list":         list,       //数据
+                                "history":      nil,        //历史数据
+                        }}
+                }()
+                if r.Err != nil {
+                        log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+                }
+                //如果有数据,则缓存redis
+                if r.Success && qutil.IntAll(r.Data["listLength"]) > 0 {
+                        redis.Put("other", "p1_indexMessage_"+areaCity, r.Data, 24*60*60)
+                }
+                result := r.Format()
+                this.ServeJson(result)
+                return
+        }
 }
 
 //根据历史记录获取查询语句
 func getSimpleSql(city string, history []string) string {
-	var musts, bools []string
-	if len(history) > 0 {
-		for _, v := range history {
-			keys := strings.Split(v, " ") //历史搜索 空格划分
-			must_tmp := []string{}
-			for _, key := range keys {
-				must_tmp = append(must_tmp, fmt.Sprintf(multi_match, "\""+key+"\""))
-			}
-			bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(must_tmp, ","), ""))
-		}
+        var musts, bools []string
+        if len(history) > 0 {
+                for _, v := range history {
+                        keys := strings.Split(v, " ") //历史搜索 空格划分
+                        must_tmp := []string{}
+                        for _, key := range keys {
+                                must_tmp = append(must_tmp, fmt.Sprintf(multi_match, "\""+key+"\""))
+                        }
+                        bools = append(bools, fmt.Sprintf(query_bool_must_and, strings.Join(must_tmp, ","), ""))
+                }
 
-	}
-	if city != "" {
-		musts = append(musts, fmt.Sprintf(query_bool_must, "city", `"`+city+`"`))
-	}
-	return fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","))
+        }
+        if city != "" {
+                musts = append(musts, fmt.Sprintf(query_bool_must, "city", `"`+city+`"`))
+        }
+        return fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","))
 }
 
 //查询查询推送记录
 func getPushHistory(userId string) (result []*jy.SubPushList) {
-	if userId == "" {
-		return
-	}
-	subPush, err := jy.NewSubscribePush().GetSevenDayCache(userId)
-	if err != nil {
-		log.Println(userId, "GetSevenDayCache Error", err)
-	}
-	if err == nil && subPush != nil && len(subPush) > 0 {
-		result = subPush
-	} else {
-		findSQL := "select * from pushsubscribe where userid = '" + userId + "'  and date >= %d order by id desc limit 50"
-		list := util.PushMysql.SelectBySql(fmt.Sprintf(findSQL, time.Now().AddDate(0, 0, -7).Unix()))
-		if len(*list) > 0 {
-			pushCas := jy.NewSubscribePush().GetJyPushs(*list)
-			result = jy.NewSubscribePush().GetInfoByIds(util.Mgo_bidding, config.Config.Mongobidding.Collection, config.Config.Mongobidding.Collection_change, pushCas)
-		} else {
-			result = []*jy.SubPushList{}
-		}
-		jy.NewSubscribePush().PutSevenDayCache(userId, result)
-	}
-	return
+        if userId == "" {
+                return
+        }
+        subPush, err := jy.NewSubscribePush().GetSevenDayCache(userId)
+        if err != nil {
+                log.Println(userId, "GetSevenDayCache Error", err)
+        }
+        if err == nil && subPush != nil && len(subPush) > 0 {
+                result = subPush
+        } else {
+                findSQL := "select * from pushsubscribe where userid = '" + userId + "'  and date >= %d order by id desc limit 50"
+                list := util.PushMysql.SelectBySql(fmt.Sprintf(findSQL, time.Now().AddDate(0, 0, -7).Unix()))
+                if len(*list) > 0 {
+                        pushCas := jy.NewSubscribePush().GetJyPushs(*list)
+                        result = jy.NewSubscribePush().GetInfoByIds(util.Mgo_bidding, config.Config.Mongobidding.Collection, config.Config.Mongobidding.Collection_change, pushCas)
+                } else {
+                        result = []*jy.SubPushList{}
+                }
+                jy.NewSubscribePush().PutSevenDayCache(userId, result)
+        }
+        return
 }

+ 156 - 149
src/jfw/modules/subscribepay/src/service/integral.go

@@ -1,166 +1,173 @@
 package service
 
 import (
-	"encoding/json"
-	"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"
+        "encoding/json"
+        "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"
 
-	. "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/jypkg/common/src/qfw/util/jy"
+        . "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/jypkg/common/src/qfw/util/jy"
 )
 
 //剑鱼积分
 type Integral struct {
-	*xweb.Action
-	createOrder xweb.Mapper `xweb:"/Integral/createOrder"` //创建订单
-	getPrice    xweb.Mapper `xweb:"/Integral/getPrice"`    //获取剑鱼币价格
+        *xweb.Action
+        createOrder xweb.Mapper `xweb:"/Integral/createOrder"` //创建订单
+        getPrice    xweb.Mapper `xweb:"/Integral/getPrice"`    //获取剑鱼币价格
 }
 
 //
 func (b *Integral) GetPrice() {
-	//参数验证 price:价格(已折扣);score:购买积分
-	if !R.CheckReqParam(b.ResponseWriter, b.Request, "score") {
-		return
-	}
-	if b.Method() != "POST" {
-		b.ServeJson(Result{
-			Error_msg: "请求方式有误",
-		})
-		return
-	}
-	r := func() Result {
-		defer qutil.Catch()
-		userId := qutil.ObjToString(b.GetSession("userId"))
-		if userId == "" {
-			return Result{-1, "未登录", nil}
-		}
-		score, _ := b.GetInteger("score")
-		order_money, order_score := entity.Integral.GetIntegralMoney(userId, -1, score)
-		if order_money == -1 {
-			return Result{-1, "-剑鱼币生成订单价格计算错误-", nil}
-		}
-		return Result{Data: map[string]interface{}{
-			"price": order_money,
-			"score": order_score,
-		},
-		}
-	}()
-	b.ServeJson(r)
+        //参数验证 price:价格(已折扣);score:购买积分
+        if !R.CheckReqParam(b.ResponseWriter, b.Request, "score") {
+                return
+        }
+        if b.Method() != "POST" {
+                b.ServeJson(Result{
+                        Error_msg: "请求方式有误",
+                })
+                return
+        }
+        r := func() Result {
+                defer qutil.Catch()
+                userId := qutil.ObjToString(b.GetSession("userId"))
+                if userId == "" {
+                        return Result{-1, "未登录", nil}
+                }
+                score, _ := b.GetInteger("score")
+                order_money, order_score := entity.Integral.GetIntegralMoney(userId, -1, score)
+                if order_money == -1 {
+                        return Result{-1, "-剑鱼币生成订单价格计算错误-", nil}
+                }
+                return Result{Data: map[string]interface{}{
+                        "price": order_money,
+                        "score": order_score,
+                },
+                }
+        }()
+        b.ServeJson(r)
 }
 
 //创建订单
 func (b *Integral) CreateOrder() {
-	//参数验证 price:价格(已折扣);score:购买积分
-	if !R.CheckReqParam(b.ResponseWriter, b.Request, "price", "score") {
-		return
-	}
-	if b.Method() != "POST" {
-		b.ServeJson(Result{
-			Error_msg: "请求方式有误",
-		})
-		return
-	}
-	r := func() Result {
-		defer qutil.Catch()
-		userId := qutil.ObjToString(b.GetSession("userId"))
-		price, _ := b.GetInteger("price")
-		score, _ := b.GetInteger("score")
-		phone := b.GetString("phone")
-		order_money, order_score := entity.Integral.GetIntegralMoney(userId, price, score)
-		original_price := order_money
-		//用户当前使用卡卷
-		userLotteryId := ""
-		full_price := 0
-		reduce_price := 0
-		//卡卷信息的id
-		lotteryId := b.GetString("lotteryId")
-		discount_price := 0
-		if lotteryId != "" {
-			var discount float64
-			full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, config.CouponConfig.Products["剑鱼币"])
-			if full_price <= order_money {
-				if discount == 100 {
-					order_money = order_money - reduce_price
-					discount_price = reduce_price
-				} else {
-					//折扣
-					disCount_int := int(math.Ceil(discount * 100))
-					discount_price = order_money - order_money*disCount_int/1000
-					order_money = order_money * disCount_int / 1000
-				}
-			} else {
-				userLotteryId = ""
-			}
-		}
-		if order_money == -1 {
-			return Result{-1, "剑鱼币生成订单价格计算错误", nil}
-		}
-		code := pay.GetOrderCode(userId)
-		filter_map := map[string]interface{}{
-			"price":       price,
-			"score":       score,
-			"order_score": order_score,
-			"isPermanent": true,
-			"phone":       phone,
-		}
-		filter, _ := json.Marshal(filter_map)
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", b.Header("User-Agent"))
-		insertObj := map[string]interface{}{
-			"order_money":          order_money,
-			"order_status":         0,
-			"filter":               string(filter),
-			"order_code":           code,
-			"product_type":         "剑鱼币",
-			"create_time":          NowFormat(Date_Full_Layout),
-			"prepay_time":          NowFormat(Date_Full_Layout),
-			"user_id":              userId,
-			"pay_way":              "",
-			"original_price":       original_price,
-			"user_phone":           phone,
-			"discount_price":       discount_price,
-			"d_relation_id":        userLotteryId,
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		}
-		order_phone := b.GetString("order_phone") //p19.3用户信息采集 手机号
-		if order_phone != "" {
-			if !jy.PhoneReg.MatchString(order_phone) {
-				return Result{-1, "手机号格式异常", nil}
-			}
-			insertObj["user_phone"] = order_phone
-		}
-		order_id := util.Mysql.Insert("dataexport_order", insertObj)
-		//审核轨迹
-		util.Mysql.Insert("audit_records", map[string]interface{}{
-			"operator":      "-",
-			"create_time":   NowFormat(Date_Full_Layout),
-			"operator_type": 1,
-			"audit_status":  3,
-			"order_code":    code,
-			"audit_type":    2,
-		})
-		if order_id > 0 {
-			//绑定卡卷
-			if userLotteryId != "" && lotteryId != "" {
-				go func(userId, userLotteryId, order_code string) {
-					nickname, _ := b.Session().Get("s_nickname").(string)
-					if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "剑鱼币", "", 3, 0) {
-						log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-					}
-				}(userId, userLotteryId, code)
-			}
-			return Result{0, "", M{"order_code": code}}
-		}
-		return Result{-1, "剑鱼币生成订单失败", nil}
-	}()
-	b.ServeJson(r)
+        //参数验证 price:价格(已折扣);score:购买积分
+        if !R.CheckReqParam(b.ResponseWriter, b.Request, "price", "score") {
+                return
+        }
+        if b.Method() != "POST" {
+                b.ServeJson(Result{
+                        Error_msg: "请求方式有误",
+                })
+                return
+        }
+        r := func() Result {
+                defer qutil.Catch()
+                userId := qutil.ObjToString(b.GetSession("userId"))
+                price, _ := b.GetInteger("price")
+                score, _ := b.GetInteger("score")
+                phone := b.GetString("phone")
+                order_money, order_score := entity.Integral.GetIntegralMoney(userId, price, score)
+                original_price := order_money
+                //用户当前使用卡卷
+                userLotteryId := ""
+                full_price := 0
+                reduce_price := 0
+                //卡卷信息的id
+                lotteryId := b.GetString("lotteryId")
+                discount_price := 0
+                if lotteryId != "" {
+                        var discount float64
+                        full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, config.CouponConfig.Products["剑鱼币"])
+                        if full_price <= order_money {
+                                if discount == 100 {
+                                        order_money = order_money - reduce_price
+                                        discount_price = reduce_price
+                                } else {
+                                        //折扣
+                                        disCount_int := int(math.Ceil(discount * 100))
+                                        discount_price = order_money - order_money*disCount_int/1000
+                                        order_money = order_money * disCount_int / 1000
+                                }
+                        } else {
+                                userLotteryId = ""
+                        }
+                }
+                if order_money == -1 {
+                        return Result{-1, "剑鱼币生成订单价格计算错误", nil}
+                }
+                code := pay.GetOrderCode(userId)
+                filter_map := map[string]interface{}{
+                        "price":       price,
+                        "score":       score,
+                        "order_score": order_score,
+                        "isPermanent": true,
+                        "phone":       phone,
+                }
+                filter, _ := json.Marshal(filter_map)
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", b.Header("User-Agent"))
+                entId := qutil.Int64All(b.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                insertObj := map[string]interface{}{
+                        "order_money":          order_money,
+                        "order_status":         0,
+                        "filter":               string(filter),
+                        "order_code":           code,
+                        "product_type":         "剑鱼币",
+                        "create_time":          NowFormat(Date_Full_Layout),
+                        "prepay_time":          NowFormat(Date_Full_Layout),
+                        "user_id":              userId,
+                        "pay_way":              "",
+                        "original_price":       original_price,
+                        "user_phone":           phone,
+                        "discount_price":       discount_price,
+                        "d_relation_id":        userLotteryId,
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                }
+                order_phone := b.GetString("order_phone") //p19.3用户信息采集 手机号
+                if order_phone != "" {
+                        if !jy.PhoneReg.MatchString(order_phone) {
+                                return Result{-1, "手机号格式异常", nil}
+                        }
+                        insertObj["user_phone"] = order_phone
+                }
+                order_id := util.Mysql.Insert("dataexport_order", insertObj)
+                //审核轨迹
+                util.Mysql.Insert("audit_records", map[string]interface{}{
+                        "operator":      "-",
+                        "create_time":   NowFormat(Date_Full_Layout),
+                        "operator_type": 1,
+                        "audit_status":  3,
+                        "order_code":    code,
+                        "audit_type":    2,
+                })
+                if order_id > 0 {
+                        //绑定卡卷
+                        if userLotteryId != "" && lotteryId != "" {
+                                go func(userId, userLotteryId, order_code string) {
+                                        nickname, _ := b.Session().Get("s_nickname").(string)
+                                        if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "剑鱼币", "", 3, 0) {
+                                                log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                                        }
+                                }(userId, userLotteryId, code)
+                        }
+                        return Result{0, "", M{"order_code": code}}
+                }
+                return Result{-1, "剑鱼币生成订单失败", nil}
+        }()
+        b.ServeJson(r)
 }

+ 8 - 3
src/jfw/modules/subscribepay/src/service/orderDetails.go

@@ -1,7 +1,8 @@
 package service
 
 import (
-	"encoding/json"
+        "app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
+        "encoding/json"
 	"jy/src/jfw/modules/subscribepay/src/config"
 	"jy/src/jfw/modules/subscribepay/src/util"
 	"log"
@@ -119,11 +120,15 @@ func (o *OrderDetail) CommonDetail(bigm int, fields string) (data map[string]int
 				for _, n := range lastOrderMap {
 					if n == order_code {
 						data["lastbuy_code"] = n
-						if datas, ok := util.MQFW.FindById("user", userId, `{"i_vip_status":1,"o_jy":1}`); data != nil && ok && len(*datas) > 0 {
+						/*if datas, ok := util.MQFW.FindById("user", userId, `{"i_vip_status":1,"o_jy":1}`); data != nil && ok && len(*datas) > 0 {
 							data["i_vip_status"] = qutil.Int64All((*datas)["i_vip_status"])
 							ojy := qutil.ObjToMap((*datas)["o_jy"])
 							data["i_pp_status"] = qutil.IntAllDef((*ojy)["i_ppstatus"], 0) //i_pp_status : -1 到期  0未购买 1已购买
-						}
+						}*/
+                                                          datas:=jy.GetBigVipUserBaseMsg("10000",o.Session(),config.Config.Etcd.Hosts,config.Config.Etcd.Key)
+                                                          data["i_vip_status"] =datas.Data.Vip.Status
+                                                          ojy := jy.GetSubScribeInfo(o.Session(),util.MQFW,"f","10000")
+                                                          data["i_pp_status"] = qutil.IntAllDef((*ojy)["i_ppstatus"], 0) //i_pp_status : -1 到期  0未购买 1已购买
 					}
 				}
 				delete(data, "_id")

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 883 - 878
src/jfw/modules/subscribepay/src/service/orderListDetails.go


+ 160 - 153
src/jfw/modules/subscribepay/src/service/resourcePack.go

@@ -1,42 +1,42 @@
 package service
 
 import (
-	"encoding/json"
-	"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"
-	"strconv"
-	"time"
+        "encoding/json"
+        "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"
+        "strconv"
+        "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 ResourcePack struct {
-	*xweb.Action
-	price       xweb.Mapper `xweb:"/resourcePack/price"`       //价格
-	createOrder xweb.Mapper `xweb:"/resourcePack/createOrder"` //线上自助数据包充值-创建订单
-	account     xweb.Mapper `xweb:"/resourcePack/account"`     //个人账户
-	recordList  xweb.Mapper `xweb:"/resourcePack/recordList"`  //“资源包”使用记录
-	consumePack xweb.Mapper `xweb:"/resourcePack/consumePack"` //“资源包”消费
+        *xweb.Action
+        price       xweb.Mapper `xweb:"/resourcePack/price"`       //价格
+        createOrder xweb.Mapper `xweb:"/resourcePack/createOrder"` //线上自助数据包充值-创建订单
+        account     xweb.Mapper `xweb:"/resourcePack/account"`     //个人账户
+        recordList  xweb.Mapper `xweb:"/resourcePack/recordList"`  //“资源包”使用记录
+        consumePack xweb.Mapper `xweb:"/resourcePack/consumePack"` //“资源包”消费
 }
 
 const (
-	METHOD = "POST"
+        METHOD = "POST"
 )
 
 type OrderResult struct {
-	Status    int    `json:"status"`     //返回状态 0失败 1成功
-	OrderCode string `json:"order_code"` //订单编号
-	Msg       string `json:"msg"`        //消息
+        Status    int    `json:"status"`     //返回状态 0失败 1成功
+        OrderCode string `json:"order_code"` //订单编号
+        Msg       string `json:"msg"`        //消息
 }
 
 // CreateOrder 资源中心流量包创建订单接口
@@ -45,96 +45,103 @@ type OrderResult struct {
 // @Success"{"status":1,"order_code":123456789,"msg":"创建成功"}"
 // @Router /jypay/ResourcePack/createOrder [post]
 func (this *ResourcePack) CreateOrder() {
-	defer qu.Catch()
-	if this.Method() != METHOD {
-		this.ServeJson(OrderResult{Msg: "请求方式有误"})
-		return
-	}
-	openId, _ := this.GetSession("s_m_openid").(string)
-	nickname, _ := this.GetSession("s_nickname").(string)
-	userId, _ := this.GetSession("userId").(string)
-	if userId == "" {
-		this.ServeJson(OrderResult{Msg: "未登录"})
-		return
-	}
-	infoMap := map[string]interface{}{}
-	if string(this.Body()) == "" {
-		this.ServeJson(OrderResult{Msg: "参数错误"})
-		return
-	}
-	body := xweb.FilterXSS(string(this.Body()))
-	//接收参数
-	json.Unmarshal([]byte(body), &infoMap)
-	if len(infoMap) == 0 {
-		this.ServeJson(OrderResult{Msg: "参数错误"})
-		return
-	}
-	//产品类型
-	product, _ := infoMap["product"].(string)
-	if config.ResConf.Product[product] == "" {
-		this.ServeJson(OrderResult{Msg: "请求产品类型有误"})
-		return
-	}
-	//
-	data, _ := infoMap["data"].(map[string]interface{})
-	if len(data) <= 0 {
-		this.ServeJson(OrderResult{Msg: "参数错误"})
-		return
-	}
-	lotteryId := qu.ObjToString(infoMap["lotteryId"])
-	discountId := qu.ObjToString(infoMap["discountId"])
-	i_discountId, _ := strconv.Atoi(discountId)
-	filter, msg := entity.JyresoucePack.Filter(product, userId, lotteryId, discountId, data, this.Session())
-	//错误信息
-	if msg != "" {
-		this.ServeJson(OrderResult{Msg: msg})
-		return
-	}
-	//生成订单号
-	orderCode := pay.GetOrderCode(userId)
-	order_phone := qu.ObjToString(infoMap["order_phone"])
-	now := time.Now()
-	filterStr, _ := json.Marshal(filter.Filter)
-	distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
-	orderid := util.Mysql.Insert("dataexport_order", map[string]interface{}{
-		"order_money":          filter.OrderMoney,
-		"order_status":         0,
-		"service_status":       0,
-		"user_nickname":        nickname,
-		"user_openid":          openId,
-		"user_phone":           order_phone,
-		"order_code":           orderCode,
-		"product_type":         config.ResConf.Product[product],
-		"create_time":          FormatDate(&now, Date_Full_Layout),
-		"original_price":       filter.Price,
-		"filter":               string(filterStr),
-		"user_id":              userId, //20190719 移动端数据导出 生订单添加用户id
-		"discount_price":       filter.DiscountPrice,
-		"d_relation_id":        filter.UserLotteryId,
-		"distribution_channel": distributionChannel, //销售渠道
-		"order_channel":        orderChannel,        //下单渠道
-		"audit_status":         3,                   //默认审核通过
-	})
-	if orderid <= 0 {
-		this.ServeJson(OrderResult{Msg: "创建订单异常"})
-		return
-	}
-	//绑定核销卡券
-	if filter.UserLotteryId != "" && lotteryId != "" {
-		go func(userId, userLotteryId, orderCode string, i_discountId int) {
-			phone, nickname := util.GetMyPhoneAndName(userId)
-			if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, orderCode, config.ResConf.Product[product], strconv.Itoa(i_discountId), 3, 0) {
-				log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", orderCode, userLotteryId))
-			}
-			if i_discountId > 0 {
-				if ulid := util.FindUserLotteryId(userId, orderid, i_discountId); ulid != 0 {
-					userLotteryId = strconv.Itoa(ulid)
-				}
-			}
-		}(userId, filter.UserLotteryId, orderCode, i_discountId)
-	}
-	this.ServeJson(OrderResult{OrderCode: orderCode, Status: 1})
-	return
+        defer qu.Catch()
+        if this.Method() != METHOD {
+                this.ServeJson(OrderResult{Msg: "请求方式有误"})
+                return
+        }
+        openId, _ := this.GetSession("s_m_openid").(string)
+        nickname, _ := this.GetSession("s_nickname").(string)
+        userId, _ := this.GetSession("userId").(string)
+        if userId == "" {
+                this.ServeJson(OrderResult{Msg: "未登录"})
+                return
+        }
+        infoMap := map[string]interface{}{}
+        if string(this.Body()) == "" {
+                this.ServeJson(OrderResult{Msg: "参数错误"})
+                return
+        }
+        body := xweb.FilterXSS(string(this.Body()))
+        //接收参数
+        json.Unmarshal([]byte(body), &infoMap)
+        if len(infoMap) == 0 {
+                this.ServeJson(OrderResult{Msg: "参数错误"})
+                return
+        }
+        //产品类型
+        product, _ := infoMap["product"].(string)
+        if config.ResConf.Product[product] == "" {
+                this.ServeJson(OrderResult{Msg: "请求产品类型有误"})
+                return
+        }
+        //
+        data, _ := infoMap["data"].(map[string]interface{})
+        if len(data) <= 0 {
+                this.ServeJson(OrderResult{Msg: "参数错误"})
+                return
+        }
+        lotteryId := qu.ObjToString(infoMap["lotteryId"])
+        discountId := qu.ObjToString(infoMap["discountId"])
+        i_discountId, _ := strconv.Atoi(discountId)
+        filter, msg := entity.JyresoucePack.Filter(product, userId, lotteryId, discountId, data, this.Session())
+        //错误信息
+        if msg != "" {
+                this.ServeJson(OrderResult{Msg: msg})
+                return
+        }
+        //生成订单号
+        orderCode := pay.GetOrderCode(userId)
+        order_phone := qu.ObjToString(infoMap["order_phone"])
+        now := time.Now()
+        filterStr, _ := json.Marshal(filter.Filter)
+        distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
+        entId := qu.Int64All(this.GetSession("entId"))
+        buy_subject := 1
+        if entId > 0 {
+                buy_subject = 2
+        }
+        orderid := util.Mysql.Insert("dataexport_order", map[string]interface{}{
+                "order_money":          filter.OrderMoney,
+                "order_status":         0,
+                "service_status":       0,
+                "user_nickname":        nickname,
+                "user_openid":          openId,
+                "user_phone":           order_phone,
+                "order_code":           orderCode,
+                "product_type":         config.ResConf.Product[product],
+                "create_time":          FormatDate(&now, Date_Full_Layout),
+                "original_price":       filter.Price,
+                "filter":               string(filterStr),
+                "user_id":              userId, //20190719 移动端数据导出 生订单添加用户id
+                "discount_price":       filter.DiscountPrice,
+                "d_relation_id":        filter.UserLotteryId,
+                "distribution_channel": distributionChannel, //销售渠道
+                "order_channel":        orderChannel,        //下单渠道
+                "audit_status":         3,                   //默认审核通过
+                "buy_subject":          buy_subject,
+                "ent_id":               entId,
+        })
+        if orderid <= 0 {
+                this.ServeJson(OrderResult{Msg: "创建订单异常"})
+                return
+        }
+        //绑定核销卡券
+        if filter.UserLotteryId != "" && lotteryId != "" {
+                go func(userId, userLotteryId, orderCode string, i_discountId int) {
+                        phone, nickname := util.GetMyPhoneAndName(userId)
+                        if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, orderCode, config.ResConf.Product[product], strconv.Itoa(i_discountId), 3, 0) {
+                                log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", orderCode, userLotteryId))
+                        }
+                        if i_discountId > 0 {
+                                if ulid := util.FindUserLotteryId(userId, orderid, i_discountId); ulid != 0 {
+                                        userLotteryId = strconv.Itoa(ulid)
+                                }
+                        }
+                }(userId, filter.UserLotteryId, orderCode, i_discountId)
+        }
+        this.ServeJson(OrderResult{OrderCode: orderCode, Status: 1})
+        return
 
 }
 
@@ -144,46 +151,46 @@ func (this *ResourcePack) CreateOrder() {
 // @Success"{"status":1,"order_code":123456789,"msg":"创建成功"}"
 // @Router /jypay/resourcePack/account [post]
 func (this *ResourcePack) Account() {
-	defer qu.Catch()
-	if this.Method() != METHOD {
-		this.ServeJson(Result{Error_msg: "请求方式有误"})
-		return
-	}
-	userId, _ := this.GetSession("userId").(string)
-	if userId == "" {
-		this.ServeJson(Result{Error_msg: "未登录"})
-		return
-	}
-	product := this.GetString("product")
-	if config.ResConf.Product[product] == "" {
-		this.ServeJson(Result{Error_msg: "参数错误"})
-		return
-	}
-	vipMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-	if vipMsg.VipStatus <= 0 {
-		this.ServeJson(Result{Error_msg: "无权限,请联系管理员"})
-		return
-	}
-	dbs := &entity.FindBalanceStruct{
-		AccountId:    userId,
-		ResourceType: config.ResConf.Product[product],
-	}
-	data, err := dbs.FindBalance()
-	if err != nil {
-		this.ServeJson(Result{Error_msg: "获取失败"})
-		return
-	}
-	this.ServeJson(Result{Data: data})
+        defer qu.Catch()
+        if this.Method() != METHOD {
+                this.ServeJson(Result{Error_msg: "请求方式有误"})
+                return
+        }
+        userId, _ := this.GetSession("userId").(string)
+        if userId == "" {
+                this.ServeJson(Result{Error_msg: "未登录"})
+                return
+        }
+        product := this.GetString("product")
+        if config.ResConf.Product[product] == "" {
+                this.ServeJson(Result{Error_msg: "参数错误"})
+                return
+        }
+        vipMsg := jy.GetBigVipUserBaseMsg("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        if vipMsg.VipStatus <= 0 {
+                this.ServeJson(Result{Error_msg: "无权限,请联系管理员"})
+                return
+        }
+        dbs := &entity.FindBalanceStruct{
+                AccountId:    userId,
+                ResourceType: config.ResConf.Product[product],
+        }
+        data, err := dbs.FindBalance()
+        if err != nil {
+                this.ServeJson(Result{Error_msg: "获取失败"})
+                return
+        }
+        this.ServeJson(Result{Data: data})
 }
 
 func (this *ResourcePack) Price() {
-	product := this.GetString("product")
-	switch product {
-	case "attachmentDownPack":
-		this.ServeJson(Result{Data: config.ResConf.AttachmentDownPackPrice})
-	case "buyerPortraitPack":
-		this.ServeJson(Result{Data: config.ResConf.BuyerPortraitPackPrice})
-		return
-	}
-	this.ServeJson(Result{Error_msg: "参数错误"})
+        product := this.GetString("product")
+        switch product {
+        case "attachmentDownPack":
+                this.ServeJson(Result{Data: config.ResConf.AttachmentDownPackPrice})
+        case "buyerPortraitPack":
+                this.ServeJson(Result{Data: config.ResConf.BuyerPortraitPackPrice})
+                return
+        }
+        this.ServeJson(Result{Error_msg: "参数错误"})
 }

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

@@ -1,594 +1,606 @@
 package service
 
 import (
-	. "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"
-	"encoding/base64"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"github.com/SKatiyar/qr"
-	"go.mongodb.org/mongo-driver/bson"
-	"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"
+        "encoding/base64"
+        "encoding/json"
+        "errors"
+        "fmt"
+        "github.com/SKatiyar/qr"
+        "go.mongodb.org/mongo-driver/bson"
+        "go.mongodb.org/mongo-driver/bson/primitive"
+        "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"
 )
 
 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)
-		}
+                        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,
+                }
 
-		now := time.Now()
-		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,         //默认审核通过
-		}
+                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("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-		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), //免费订阅区分新老用户
-			"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("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                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, ok := util.MQFW.FindById("user", userId, nil)
-		if ok && 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, ok := util.MQFW.FindById("user", userId, nil)
+                if ok && 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)
-			//如果手机号号为空查找通过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.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,
+                        }
+                }
+        }
 env:
-	o.ServeJson(r.Format())
+        o.ServeJson(r.Format())
 }

+ 649 - 602
src/jfw/modules/subscribepay/src/service/vipSubscribeChange.go

@@ -1,643 +1,690 @@
 package service
 
 import (
-	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/jypkg/common/src/qfw/util/jy"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"go.mongodb.org/mongo-driver/bson"
-	"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"
+        "encoding/json"
+        "errors"
+        "fmt"
+        "go.mongodb.org/mongo-driver/bson"
+        "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"
 )
 
 //订阅修改 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("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-		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), //免费订阅区分新老用户
-			"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("10000", this.Session(), config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+                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) {
-			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) {
+                        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{}
-		}
-		updateOk := util.MQFW.UpdateById("user", userId,
-			bson.M{"$set": bson.M{
-				"o_vipjy.o_area":       area,     //设置地区
-				"o_vipjy.a_buyerclass": industry, //设置行业
-			}})
-		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{}
+                }
+                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())
 }
 
 //升级订阅
 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"))
-		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,                   //默认审核通过
-		}
-		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) {
-				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 != "" {
-			updateOk := util.MQFW.UpdateById("user", 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())
+        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())
 }
 
 //超级订阅优化,免费订阅判断新老用户  1:新用户 0:老用户
-func NewUserByVIP(userId string) int {
-	mData, ok := util.MQFW.FindById("user", userId, `{"o_jy":1,"l_registedate":1}`)
-	if !ok || len(*mData) == 0 || mData == nil {
-		return 1
-	}
-	ojy, _ := (*mData)["o_jy"].(map[string]interface{})
-	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)["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
+func NewUserByVIP(userId string, session *httpsession.Session) int {
+        /*mData, ok := util.MQFW.FindById("user", userId, `{"o_jy":1,"l_registedate":1}`)
+          if !ok || len(*mData) == 0 || mData == nil {
+          	return 1
+          }
+          ojy, _ := (*mData)["o_jy"].(map[string]interface{})*/
+        mData := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        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
 }

+ 533 - 519
src/jfw/modules/subscribepay/src/service/vipSubscribePay.go

@@ -1,563 +1,577 @@
 package service
 
 import (
-	"app.yhyue.com/moapp/jybase/go-xweb/httpsession"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"jy/src/jfw/modules/subscribepay/src/active"
-	"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"
-	"strconv"
-	"strings"
-	"time"
+        "app.yhyue.com/moapp/jybase/go-xweb/httpsession"
+        "encoding/json"
+        "errors"
+        "fmt"
+        "jy/src/jfw/modules/subscribepay/src/active"
+        "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"
+        "strconv"
+        "strings"
+        "time"
 
-	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/jypkg/common/src/qfw/util/jy"
+        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/jypkg/common/src/qfw/util/jy"
 )
 
 //vip订阅付费
 type SubVipPayOrder struct {
-	*xweb.Action
-	getPrice       xweb.Mapper `xweb:"/vipsubscribe/getPrice"`       //获取价格
-	createOrder    xweb.Mapper `xweb:"/vipsubscribe/createOrder"`    //创建订单并支付
-	renew          xweb.Mapper `xweb:"/vipsubscribe/renew"`          //续费超级订阅
-	getSelectPrice xweb.Mapper `xweb:"/vipsubscribe/getSelectPrice"` //获取当前选择内容的价格
+        *xweb.Action
+        getPrice       xweb.Mapper `xweb:"/vipsubscribe/getPrice"`       //获取价格
+        createOrder    xweb.Mapper `xweb:"/vipsubscribe/createOrder"`    //创建订单并支付
+        renew          xweb.Mapper `xweb:"/vipsubscribe/renew"`          //续费超级订阅
+        getSelectPrice xweb.Mapper `xweb:"/vipsubscribe/getSelectPrice"` //获取当前选择内容的价格
 }
 
 func init() {
-	xweb.AddAction(&SubVipPayOrder{})
+        xweb.AddAction(&SubVipPayOrder{})
 }
 
 // 获取当前选择内容的价格
 func (this *SubVipPayOrder) GetSelectPrice() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		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())
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                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())
 }
 func CommonBilling(area *map[string]interface{}, timeRenew, userId, lotteryId string, orderType, useProduct int, session *httpsession.Session) *entity.FuncResult {
-	//area := qutil.ObjToMap(this.GetString("area")) //地区
-	//timeRenew := this.GetString("time")            //周期
-	//orderType, _ := this.GetInteger("orderType")   //1 购买;2 续费;3 升级
-	// 原价;订单价
-	original_price, order_price := 0, 0
-	userMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
-	if (userMsg.VipStatus > 0 && orderType == 1) || (userMsg.VipStatus <= 0 && (orderType == 3 || orderType == 2)) {
-		return &entity.FuncResult{false, errors.New("参数异常"), nil}
-	} else if userMsg.VipStatus <= 0 && orderType == 1 { //购买价格
-		date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(timeRenew)
-		if err != nil {
-			return &entity.FuncResult{false, err, nil}
-		}
-		buyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
-		//计算价格
-		original_price = entity.JyVipSubStruct.GetSubVipPrice(buyset, date_count, date_unit)
-	} else if userMsg.VipStatus > 0 { //2:续费价格(只延长时间);3:升级价格(升级只升级地区)
-		rData, oldBuyset, _ := entity.JyVipSubStruct.GetVipDetail(userId)
-		switch orderType {
-		case 2:
-			now := time.Now()
-			date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(timeRenew)
-			if err != nil {
-				return &entity.FuncResult{false, err, nil}
-			}
-			endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
-			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}
-			}
-			original_price = entity.JyVipSubStruct.GetSubVipPriceByBuySet(oldBuyset, date_count, date_unit, false)
-		case 3:
-			endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
-			newBuyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
-			//升级校验
-			original_price, _ = getNewUpgradeDetail(userId, newBuyset, oldBuyset, endUnix, 0, 0)
-			if original_price < 0 {
-				if original_price == -1 {
-					return &entity.FuncResult{false, errors.New("不能升级此状态"), nil}
-				} else {
-					return &entity.FuncResult{false, errors.New("查询续费订单出错"), nil}
-				}
-			}
-		}
-	}
-	order_price = original_price
-	//卡卷信息的id
-	if lotteryId != "" {
-		products := config.CouponConfig.Products["超级订阅"]
-		if useProduct > 0 {
-			products = strconv.Itoa(useProduct)
-		}
-		full_price, reduce_price := 0, 0
-		var discount float64
-		full_price, reduce_price, discount, _ = util.GetCouponInfo(userId, lotteryId, products)
-		if full_price <= original_price {
-			if discount == 100 { //满减
-				order_price = original_price - reduce_price
-			} else { //满折
-				disCount_int := int(math.Ceil(discount * 100))
-				order_price = original_price * disCount_int / 1000
-			}
-		}
-	}
-	return &entity.FuncResult{true, nil, map[string]interface{}{
-		"original_price": original_price,
-		"order_price":    order_price,
-	},
-	}
+        //area := qutil.ObjToMap(this.GetString("area")) //地区
+        //timeRenew := this.GetString("time")            //周期
+        //orderType, _ := this.GetInteger("orderType")   //1 购买;2 续费;3 升级
+        // 原价;订单价
+        original_price, order_price := 0, 0
+        userMsg := jy.GetBigVipUserBaseMsg("10000", session, config.Config.Etcd.Hosts, config.Config.Etcd.Key)
+        if (userMsg.VipStatus > 0 && orderType == 1) || (userMsg.VipStatus <= 0 && (orderType == 3 || orderType == 2)) {
+                return &entity.FuncResult{false, errors.New("参数异常"), nil}
+        } else if userMsg.VipStatus <= 0 && orderType == 1 { //购买价格
+                date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(timeRenew)
+                if err != nil {
+                        return &entity.FuncResult{false, err, nil}
+                }
+                buyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
+                //计算价格
+                original_price = entity.JyVipSubStruct.GetSubVipPrice(buyset, date_count, date_unit)
+        } else if userMsg.VipStatus > 0 { //2:续费价格(只延长时间);3:升级价格(升级只升级地区)
+                rData, oldBuyset, _ := entity.JyVipSubStruct.GetVipDetail(userId)
+                switch orderType {
+                case 2:
+                        now := time.Now()
+                        date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(timeRenew)
+                        if err != nil {
+                                return &entity.FuncResult{false, err, nil}
+                        }
+                        endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
+                        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}
+                        }
+                        original_price = entity.JyVipSubStruct.GetSubVipPriceByBuySet(oldBuyset, date_count, date_unit, false)
+                case 3:
+                        endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
+                        newBuyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
+                        //升级校验
+                        original_price, _ = getNewUpgradeDetail(userId, newBuyset, oldBuyset, endUnix, 0, 0)
+                        if original_price < 0 {
+                                if original_price == -1 {
+                                        return &entity.FuncResult{false, errors.New("不能升级此状态"), nil}
+                                } else {
+                                        return &entity.FuncResult{false, errors.New("查询续费订单出错"), nil}
+                                }
+                        }
+                }
+        }
+        order_price = original_price
+        //卡卷信息的id
+        if lotteryId != "" {
+                products := config.CouponConfig.Products["超级订阅"]
+                if useProduct > 0 {
+                        products = strconv.Itoa(useProduct)
+                }
+                full_price, reduce_price := 0, 0
+                var discount float64
+                full_price, reduce_price, discount, _ = util.GetCouponInfo(userId, lotteryId, products)
+                if full_price <= original_price {
+                        if discount == 100 { //满减
+                                order_price = original_price - reduce_price
+                        } else { //满折
+                                disCount_int := int(math.Ceil(discount * 100))
+                                order_price = original_price * disCount_int / 1000
+                        }
+                }
+        }
+        return &entity.FuncResult{true, nil, map[string]interface{}{
+                "original_price": original_price,
+                "order_price":    order_price,
+        },
+        }
 
 }
 
 //支付价格
 func (this *SubVipPayOrder) GetPrice() {
-	if active.ActiveConfig.DoubleEleven.Active_Start < time.Now().Unix() && active.ActiveConfig.DoubleEleven.Active_End > time.Now().Unix() {
-		res := map[string]interface{}{
-			"isActiving": true,
-			"isWritten":  0,
-		}
-		j, _ := json.Marshal(&entity.SubVipPrice)
-		json.Unmarshal(j, &res)
-		userId, _ := this.GetSession("userId").(string)
-		if userId != "" {
-			data, ok := util.MQFW.FindById("user", userId, nil)
-			if ok && data != nil && *data != nil {
-				//已录入信息 已激活大会员赠送
-				if (*data)["i_member_give"] != nil {
-					res["isWritten"] = qutil.IntAll((*data)["i_member_give"])
-				}
-			}
-		}
-		this.ServeJson(res)
-	} else {
-		this.ServeJson(entity.SubVipPrice)
-	}
+        if active.ActiveConfig.DoubleEleven.Active_Start < time.Now().Unix() && active.ActiveConfig.DoubleEleven.Active_End > time.Now().Unix() {
+                res := map[string]interface{}{
+                        "isActiving": true,
+                        "isWritten":  0,
+                }
+                j, _ := json.Marshal(&entity.SubVipPrice)
+                json.Unmarshal(j, &res)
+                userId, _ := this.GetSession("userId").(string)
+                if userId != "" {
+                        data, ok := util.MQFW.FindById("user", userId, nil)
+                        if ok && data != nil && *data != nil {
+                                //已录入信息 已激活大会员赠送
+                                if (*data)["i_member_give"] != nil {
+                                        res["isWritten"] = qutil.IntAll((*data)["i_member_give"])
+                                }
+                        }
+                }
+                this.ServeJson(res)
+        } else {
+                this.ServeJson(entity.SubVipPrice)
+        }
 }
 
 //新订单 或 即将到期续费
 //4.4 超级订阅升级 只能选择购买省份和全行业
 func (this *SubVipPayOrder) CreateOrder() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		area := qutil.ObjToMap(this.GetString("area"))
-		date := this.GetString("time")
-		orderType, _ := this.GetInteger("orderType") //1 简单付费,5 升降级续费
-		openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-		disWord := this.GetString("disWord")
-		if disWord != "" {
-			if len(strings.Split(disWord, "_")) > 1 {
-				if fmt.Sprint(strings.Split(disWord, "_")[1]) == "GX" {
-					userfilter, ok := util.MQFW.FindById("user", userId, "")
-					if ok && userfilter != nil {
-						dis := qutil.ObjToString((*userfilter)["disWords"])
-						if dis != disWord {
-							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
-		}
-		req_price, _ := this.GetInteger("price")     //前端展示金额
-		order_phone := this.GetString("order_phone") //p19.3用户信息采集 手机号
-		/*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"])
-			}
-		}*/
-		now := time.Now()
-		userData, oldBuyset, _ := entity.JyVipSubStruct.GetVipDetail(userId)
-		isgive := false
-		pass := func() bool { //校验订单是否合法
-			if orderType == 1 {
-				vipStatus := qutil.IntAll((*userData)["i_vip_status"])
-				if vipStatus > 1 { //仅非VIP用户购买
-					return false
-				}
-			} else if orderType == 5 { //仅即将到期用户购买
-				endTime := qutil.Int64All((*userData)["l_vip_endtime"])
-				if endTime > now.Unix()+60*60*24*7 {
-					return false
-				}
-			} else {
-				return false
-			}
-			return true
-		}()
-		if !pass {
-			return &entity.FuncResult{false, fmt.Errorf("非法请求"), nil}
-		}
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                area := qutil.ObjToMap(this.GetString("area"))
+                date := this.GetString("time")
+                orderType, _ := this.GetInteger("orderType") //1 简单付费,5 升降级续费
+                openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+                disWord := this.GetString("disWord")
+                if disWord != "" {
+                        if len(strings.Split(disWord, "_")) > 1 {
+                                if fmt.Sprint(strings.Split(disWord, "_")[1]) == "GX" {
+                                        userfilter, ok := util.MQFW.FindById("user", userId, "")
+                                        if ok && userfilter != nil {
+                                                dis := qutil.ObjToString((*userfilter)["disWords"])
+                                                if dis != disWord {
+                                                        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
+                }
+                req_price, _ := this.GetInteger("price")     //前端展示金额
+                order_phone := this.GetString("order_phone") //p19.3用户信息采集 手机号
+                /*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"])
+                	}
+                }*/
+                now := time.Now()
+                userData, oldBuyset, _ := entity.JyVipSubStruct.GetVipDetail(userId)
+                isgive := false
+                pass := func() bool { //校验订单是否合法
+                        if orderType == 1 {
+                                vipStatus := qutil.IntAll((*userData)["i_vip_status"])
+                                if vipStatus > 1 { //仅非VIP用户购买
+                                        return false
+                                }
+                        } else if orderType == 5 { //仅即将到期用户购买
+                                endTime := qutil.Int64All((*userData)["l_vip_endtime"])
+                                if endTime > now.Unix()+60*60*24*7 {
+                                        return false
+                                }
+                        } else {
+                                return false
+                        }
+                        return true
+                }()
+                if !pass {
+                        return &entity.FuncResult{false, fmt.Errorf("非法请求"), nil}
+                }
 
-		date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(date)
-		if err != nil {
-			return &entity.FuncResult{false, err, nil}
-		}
-		buyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
-		filter := entity.VipSimpleMsg{
-			Area:       area,
-			Industry:   []string{},
-			Cyclecount: date_count,
-			Cycleunit:  date_unit,
-			NewBuyset:  buyset,
-			OrderType:  orderType,
-			DisWord:    disWord,
-		}
-		//即将到期
-		if orderType == 5 {
-			o_vipjy := qutil.ObjToMap((*userData)["o_vipjy"])
-			thisBuySet := qutil.ObjToMap((*o_vipjy)["o_buyset"])
-			if len(*thisBuySet) == 0 {
-				return &entity.FuncResult{false, errors.New("创建续费订单出错"), nil}
-			}
-			filter.OldBuyset = oldBuyset
-		}
-		//插入订单表
-		mog_id := entity.JyVipSubStruct.SaveSelectLog(userId, openId, &filter)
-		if mog_id == "" {
-			return &entity.FuncResult{false, errors.New("创建订单出错"), nil}
-		}
-		//计算价格
-		totalfee := entity.JyVipSubStruct.GetSubVipPrice(buyset, date_count, date_unit)
-		if req_price != totalfee {
-			return &entity.FuncResult{false, errors.New(fmt.Sprintf("金额校验异常[%d,%d]", totalfee, req_price)), nil}
-		}
-		//原价
-		original_price := totalfee
-		ordercode := pay.GetOrderCode(userId)
-		//卡卷信息的id
-		lotteryId := this.GetString("lotteryId")
-		discount_price, userLotteryId := 0, ""
-		useProduct, _ := this.GetInteger("useProduct")
-		if lotteryId != "" {
-			products := config.CouponConfig.Products["超级订阅"]
-			if useProduct > 0 {
-				products = strconv.Itoa(useProduct)
-			}
-			full_price, reduce_price := 0, 0
-			var discount float64
-			full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
-			if full_price <= totalfee {
-				if discount == 100 { //满减
-					totalfee = totalfee - reduce_price
-					discount_price = reduce_price
+                date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(date)
+                if err != nil {
+                        return &entity.FuncResult{false, err, nil}
+                }
+                buyset := entity.JyVipSubStruct.NewBuySet(area, nil, true) //改版后只能购买升级版超级订阅
+                filter := entity.VipSimpleMsg{
+                        Area:       area,
+                        Industry:   []string{},
+                        Cyclecount: date_count,
+                        Cycleunit:  date_unit,
+                        NewBuyset:  buyset,
+                        OrderType:  orderType,
+                        DisWord:    disWord,
+                }
+                //即将到期
+                if orderType == 5 {
+                        o_vipjy := qutil.ObjToMap((*userData)["o_vipjy"])
+                        thisBuySet := qutil.ObjToMap((*o_vipjy)["o_buyset"])
+                        if len(*thisBuySet) == 0 {
+                                return &entity.FuncResult{false, errors.New("创建续费订单出错"), nil}
+                        }
+                        filter.OldBuyset = oldBuyset
+                }
+                //插入订单表
+                mog_id := entity.JyVipSubStruct.SaveSelectLog(userId, openId, &filter)
+                if mog_id == "" {
+                        return &entity.FuncResult{false, errors.New("创建订单出错"), nil}
+                }
+                //计算价格
+                totalfee := entity.JyVipSubStruct.GetSubVipPrice(buyset, date_count, date_unit)
+                if req_price != totalfee {
+                        return &entity.FuncResult{false, errors.New(fmt.Sprintf("金额校验异常[%d,%d]", totalfee, req_price)), nil}
+                }
+                //原价
+                original_price := totalfee
+                ordercode := pay.GetOrderCode(userId)
+                //卡卷信息的id
+                lotteryId := this.GetString("lotteryId")
+                discount_price, userLotteryId := 0, ""
+                useProduct, _ := this.GetInteger("useProduct")
+                if lotteryId != "" {
+                        products := config.CouponConfig.Products["超级订阅"]
+                        if useProduct > 0 {
+                                products = strconv.Itoa(useProduct)
+                        }
+                        full_price, reduce_price := 0, 0
+                        var discount float64
+                        full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
+                        if full_price <= totalfee {
+                                if discount == 100 { //满减
+                                        totalfee = totalfee - reduce_price
+                                        discount_price = reduce_price
 
-				} else { //满折
-					disCount_int := int(math.Ceil(discount * 100))
-					discount_price = totalfee - totalfee*disCount_int/1000
-					totalfee = totalfee * disCount_int / 1000
-				}
-			} else {
-				userLotteryId = ""
-			}
-		}
-		//赠品相关
-		discountId, _ := this.GetInteger("discountId")
-		if discountId > 0 {
-			isgive = true
-			_, timeNum, timeType, _, _, _, activityName, _ := util.GiveInfo(userId, useProduct, 0, discountId) //获取满赠时长
-			filter.GiveCycle = timeNum
-			filter.GiveType = timeType
-			filter.DisCountId = discountId
-			if strings.Contains(activityName, config.Config.ActivityName) {
-				filter.Badge = "202111" //双十一角标展示
-			}
-		}
-		filterStr, _ := json.Marshal(filter)
-		distributionChannel, orderChannel := util.GetJyOrderChannel(disWord, this.Header("User-Agent"))
-		insertMap := map[string]interface{}{
-			"order_money":          totalfee,
-			"order_status":         0,
-			"user_nickname":        qutil.ObjToString(this.GetSession("s_nickname")),
-			"user_openid":          openId,
-			"order_code":           ordercode,
-			"product_type":         "VIP订阅",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       original_price,
-			"filter_id":            mog_id,
-			"user_id":              userId,
-			"filter":               string(filterStr), //筛选
-			"discount_price":       discount_price,
-			"d_relation_id":        userLotteryId,
-			"dis_word":             disWord,             //分销口令
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		}
-		if orderType != 5 && order_phone != "" { //p19.3用户信息采集(仅付费可填写手机号)
-			if !jy.PhoneReg.MatchString(order_phone) {
-				return &entity.FuncResult{false, errors.New("手机号格式异常"), nil}
-			}
+                                } else { //满折
+                                        disCount_int := int(math.Ceil(discount * 100))
+                                        discount_price = totalfee - totalfee*disCount_int/1000
+                                        totalfee = totalfee * disCount_int / 1000
+                                }
+                        } else {
+                                userLotteryId = ""
+                        }
+                }
+                //赠品相关
+                discountId, _ := this.GetInteger("discountId")
+                if discountId > 0 {
+                        isgive = true
+                        _, timeNum, timeType, _, _, _, activityName, _ := util.GiveInfo(userId, useProduct, 0, discountId) //获取满赠时长
+                        filter.GiveCycle = timeNum
+                        filter.GiveType = timeType
+                        filter.DisCountId = discountId
+                        if strings.Contains(activityName, config.Config.ActivityName) {
+                                filter.Badge = "202111" //双十一角标展示
+                        }
+                }
+                filterStr, _ := json.Marshal(filter)
+                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":          totalfee,
+                        "order_status":         0,
+                        "user_nickname":        qutil.ObjToString(this.GetSession("s_nickname")),
+                        "user_openid":          openId,
+                        "order_code":           ordercode,
+                        "product_type":         "VIP订阅",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       original_price,
+                        "filter_id":            mog_id,
+                        "user_id":              userId,
+                        "filter":               string(filterStr), //筛选
+                        "discount_price":       discount_price,
+                        "d_relation_id":        userLotteryId,
+                        "dis_word":             disWord,             //分销口令
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "audit_status":         3,                   //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                }
+                if orderType != 5 && order_phone != "" { //p19.3用户信息采集(仅付费可填写手机号)
+                        if !jy.PhoneReg.MatchString(order_phone) {
+                                return &entity.FuncResult{false, errors.New("手机号格式异常"), nil}
+                        }
 
-		}
-		if order_phone == "" && userfilter != nil && len(*userfilter) > 0 {
-			order_phone, _ = qutil.If((*userfilter)["s_phone"] != nil, (*userfilter)["s_phone"], (*userfilter)["s_m_phone"]).(string)
-		}
-		if orderType == 5 { //插入生效时间和结束时间
-			timeStamp := qutil.Int64All((*userData)["l_vip_endtime"])
-			startTime := time.Unix(timeStamp, 0)
-			endTime := util.GetDATE(filter.Cycleunit, filter.Cyclecount, timeStamp)
-			if isgive { //满赠
-				if filter.GiveType == 1 {
-					endTime = endTime.AddDate(0, 0, filter.GiveCycle)
-				} else if filter.GiveType == 2 {
-					endTime = endTime.AddDate(0, filter.GiveCycle, 0)
-				}
-			}
-			//校验是否超过三年
-			if time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).
-				AddDate(3, 0, 0).Before(endTime) && !entity.JyVipSubStruct.IsActiving() && !isgive {
-				return &entity.FuncResult{false, errors.New("订阅周期超过三年"), nil}
-			}
-			insertMap["vip_type"] = 1
-			insertMap["vip_starttime"] = FormatDate(&startTime, Date_Full_Layout)
-			insertMap["vip_endtime"] = FormatDate(&endTime, Date_Full_Layout)
-		}
-		insertMap["user_phone"] = order_phone
-		orderid := util.Mysql.Insert("dataexport_order", insertMap)
-		if orderid == -1 {
-			return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
-		} else {
-			//绑定卡卷
-			if (userLotteryId != "" && lotteryId != "") || (discountId > 0) {
-				go func(userId, userLotteryId, order_code string) {
-					phone, nickname := util.GetMyPhoneAndName(userId)
-					if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "超级订阅", strconv.Itoa(discountId), 3, 0) {
-						log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-					}
-					if discountId > 0 {
-						if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
-							userLotteryId = strconv.Itoa(ulid)
-						}
-					}
-				}(userId, userLotteryId, ordercode)
-			}
-		}
-		//支付提醒
-		//util.MsgRemind.Add(qutil.IntAll(orderid), totalfee, qutil.If(orderType == 5, 1, -1).(int), 0, ordercode, userId, now.Unix())
-		return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+                }
+                if order_phone == "" && userfilter != nil && len(*userfilter) > 0 {
+                        order_phone, _ = qutil.If((*userfilter)["s_phone"] != nil, (*userfilter)["s_phone"], (*userfilter)["s_m_phone"]).(string)
+                }
+                if orderType == 5 { //插入生效时间和结束时间
+                        timeStamp := qutil.Int64All((*userData)["l_vip_endtime"])
+                        startTime := time.Unix(timeStamp, 0)
+                        endTime := util.GetDATE(filter.Cycleunit, filter.Cyclecount, timeStamp)
+                        if isgive { //满赠
+                                if filter.GiveType == 1 {
+                                        endTime = endTime.AddDate(0, 0, filter.GiveCycle)
+                                } else if filter.GiveType == 2 {
+                                        endTime = endTime.AddDate(0, filter.GiveCycle, 0)
+                                }
+                        }
+                        //校验是否超过三年
+                        if time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 59, now.Location()).
+                                AddDate(3, 0, 0).Before(endTime) && !entity.JyVipSubStruct.IsActiving() && !isgive {
+                                return &entity.FuncResult{false, errors.New("订阅周期超过三年"), nil}
+                        }
+                        insertMap["vip_type"] = 1
+                        insertMap["vip_starttime"] = FormatDate(&startTime, Date_Full_Layout)
+                        insertMap["vip_endtime"] = FormatDate(&endTime, Date_Full_Layout)
+                }
+                insertMap["user_phone"] = order_phone
+                orderid := util.Mysql.Insert("dataexport_order", insertMap)
+                if orderid == -1 {
+                        return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
+                } else {
+                        //绑定卡卷
+                        if (userLotteryId != "" && lotteryId != "") || (discountId > 0) {
+                                go func(userId, userLotteryId, order_code string) {
+                                        phone, nickname := util.GetMyPhoneAndName(userId)
+                                        if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "超级订阅", strconv.Itoa(discountId), 3, 0) {
+                                                log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                                        }
+                                        if discountId > 0 {
+                                                if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
+                                                        userLotteryId = strconv.Itoa(ulid)
+                                                }
+                                        }
+                                }(userId, userLotteryId, ordercode)
+                        }
+                }
+                //支付提醒
+                //util.MsgRemind.Add(qutil.IntAll(orderid), totalfee, qutil.If(orderType == 5, 1, -1).(int), 0, ordercode, userId, now.Unix())
+                return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode}}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 //续费
 func (this *SubVipPayOrder) Renew() {
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	r := func() *entity.FuncResult {
-		disWord := this.GetString("disWord")
-		openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-		req_price, _ := this.GetInteger("price") //前端展示金额
-		if disWord != "" {
-			if len(strings.Split(disWord, "_")) > 1 {
-				if fmt.Sprint(strings.Split(disWord, "_")[1]) == "GX" {
-					userfilter, ok := util.MQFW.FindById("user", userId, "")
-					if ok && userfilter != nil {
-						dis := qutil.ObjToString((*userfilter)["disWords"])
-						if dis != disWord {
-							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
-		}
-		now := time.Now()
-		date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(this.GetString("time"))
-		if err != nil {
-			return &entity.FuncResult{false, err, nil}
-		}
+        userId := qutil.ObjToString(this.GetSession("userId"))
+        r := func() *entity.FuncResult {
+                disWord := this.GetString("disWord")
+                openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+                req_price, _ := this.GetInteger("price") //前端展示金额
+                if disWord != "" {
+                        if len(strings.Split(disWord, "_")) > 1 {
+                                if fmt.Sprint(strings.Split(disWord, "_")[1]) == "GX" {
+                                        userfilter, ok := util.MQFW.FindById("user", userId, "")
+                                        if ok && userfilter != nil {
+                                                dis := qutil.ObjToString((*userfilter)["disWords"])
+                                                if dis != disWord {
+                                                        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
+                }
+                now := time.Now()
+                date_count, date_unit, err := entity.JyVipSubStruct.CheckReqDate(this.GetString("time"))
+                if err != nil {
+                        return &entity.FuncResult{false, err, nil}
+                }
 
-		rData, buyset, isVip := entity.JyVipSubStruct.GetVipDetail(userId)
-		if !isVip {
-			return &entity.FuncResult{false, errors.New("请求异常,非vip状态"), nil}
-		}
-		endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
-		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}
-		}
+                rData, buyset, isVip := entity.JyVipSubStruct.GetVipDetail(userId)
+                if !isVip {
+                        return &entity.FuncResult{false, errors.New("请求异常,非vip状态"), nil}
+                }
+                endUnix := qutil.Int64All((*rData)["l_vip_endtime"])
+                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}
+                }
 
-		totalfee := entity.JyVipSubStruct.GetSubVipPriceByBuySet(buyset, date_count, date_unit, false)
-		if req_price != totalfee {
-			return &entity.FuncResult{false, errors.New(fmt.Sprintf("金额校验异常[%d,%d]", totalfee, req_price)), nil}
-		}
-		filter := entity.VipSimpleMsg{
-			Area:       nil,
-			Industry:   nil,
-			Cyclecount: date_count,
-			Cycleunit:  date_unit,
-			NewBuyset:  buyset,
-			OrderType:  2,
-			DisWord:    disWord,
-		}
-		//满赠的id
-		discountId, _ := this.GetInteger("discountId")
-		useProduct, _ := this.GetInteger("useProduct")
-		if discountId > 0 && useProduct > 0 {
-			_, timeNum, timeType, _, _, _, activityName, _ := util.GiveInfo(userId, useProduct, 0, discountId) //获取满赠时长
-			filter.GiveCycle = timeNum
-			filter.GiveType = timeType
-			filter.DisCountId = discountId
-			if strings.Contains(activityName, config.Config.ActivityName) {
-				filter.Badge = "202111" //双十一角标展示
-			}
-		}
-		mog_id := entity.JyVipSubStruct.SaveSelectLog(userId, openId, &filter)
-		if mog_id == "" {
-			return &entity.FuncResult{false, errors.New("创建订单出错"), nil}
-		}
+                totalfee := entity.JyVipSubStruct.GetSubVipPriceByBuySet(buyset, date_count, date_unit, false)
+                if req_price != totalfee {
+                        return &entity.FuncResult{false, errors.New(fmt.Sprintf("金额校验异常[%d,%d]", totalfee, req_price)), nil}
+                }
+                filter := entity.VipSimpleMsg{
+                        Area:       nil,
+                        Industry:   nil,
+                        Cyclecount: date_count,
+                        Cycleunit:  date_unit,
+                        NewBuyset:  buyset,
+                        OrderType:  2,
+                        DisWord:    disWord,
+                }
+                //满赠的id
+                discountId, _ := this.GetInteger("discountId")
+                useProduct, _ := this.GetInteger("useProduct")
+                if discountId > 0 && useProduct > 0 {
+                        _, timeNum, timeType, _, _, _, activityName, _ := util.GiveInfo(userId, useProduct, 0, discountId) //获取满赠时长
+                        filter.GiveCycle = timeNum
+                        filter.GiveType = timeType
+                        filter.DisCountId = discountId
+                        if strings.Contains(activityName, config.Config.ActivityName) {
+                                filter.Badge = "202111" //双十一角标展示
+                        }
+                }
+                mog_id := entity.JyVipSubStruct.SaveSelectLog(userId, openId, &filter)
+                if mog_id == "" {
+                        return &entity.FuncResult{false, errors.New("创建订单出错"), nil}
+                }
 
-		//计算开始价格和结束价格
-		startTime := time.Unix(endUnix, 0)
-		endTime := util.GetDATE(filter.Cycleunit, filter.Cyclecount, endUnix)
-		if filter.GiveCycle > 0 && filter.GiveType > 0 {
-			if filter.GiveType == 1 {
-				endTime = endTime.AddDate(0, 0, filter.GiveCycle)
-			} else if filter.GiveType == 2 {
-				endTime = endTime.AddDate(0, filter.GiveCycle, 0)
-			}
-		}
-		//原价
-		original_price := totalfee
+                //计算开始价格和结束价格
+                startTime := time.Unix(endUnix, 0)
+                endTime := util.GetDATE(filter.Cycleunit, filter.Cyclecount, endUnix)
+                if filter.GiveCycle > 0 && filter.GiveType > 0 {
+                        if filter.GiveType == 1 {
+                                endTime = endTime.AddDate(0, 0, filter.GiveCycle)
+                        } else if filter.GiveType == 2 {
+                                endTime = endTime.AddDate(0, filter.GiveCycle, 0)
+                        }
+                }
+                //原价
+                original_price := totalfee
 
-		//卡卷信息的id
-		lotteryId := this.GetString("lotteryId")
-		userLotteryId, discount_price := "", 0
-		if lotteryId != "" {
-			//用户当前使用卡卷
-			full_price, reduce_price := 0, 0
-			var discount float64
-			products := config.CouponConfig.Products["超级订阅"]
-			if useProduct > 0 {
-				products = strconv.Itoa(useProduct)
-			}
-			full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
-			if full_price <= totalfee {
-				if discount == 100 { //满减
-					totalfee = totalfee - reduce_price
-					discount_price = reduce_price
-				} else { //满折
-					disCount_int := int(math.Ceil(discount * 100))
-					discount_price = totalfee - totalfee*disCount_int/1000
-					totalfee = totalfee * disCount_int / 1000
-				}
-			} else {
-				userLotteryId = ""
-			}
-		}
-		filterStr, _ := json.Marshal(filter)
-		ordercode := pay.GetOrderCode(userId)
-		distributionChannel, orderChannel := util.GetJyOrderChannel(disWord, this.Header("User-Agent"))
-		insertMap := map[string]interface{}{
-			"order_money":          totalfee,
-			"order_status":         0,
-			"user_nickname":        qutil.ObjToString(this.GetSession("s_nickname")),
-			"user_openid":          openId,
-			"order_code":           ordercode,
-			"product_type":         "VIP订阅",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       original_price,
-			"filter_id":            mog_id,
-			"user_id":              userId,
-			"filter":               string(filterStr),   //筛选
-			"dis_word":             disWord,             //分销口令
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"discount_price":       discount_price,
-			"d_relation_id":        userLotteryId,
-			"vip_starttime":        FormatDate(&startTime, Date_Full_Layout),
-			"vip_endtime":          FormatDate(&endTime, Date_Full_Layout),
-			"vip_type":             1,
-			"audit_status":         3, //默认审核通过
-		}
+                //卡卷信息的id
+                lotteryId := this.GetString("lotteryId")
+                userLotteryId, discount_price := "", 0
+                if lotteryId != "" {
+                        //用户当前使用卡卷
+                        full_price, reduce_price := 0, 0
+                        var discount float64
+                        products := config.CouponConfig.Products["超级订阅"]
+                        if useProduct > 0 {
+                                products = strconv.Itoa(useProduct)
+                        }
+                        full_price, reduce_price, discount, userLotteryId = util.GetCouponInfo(userId, lotteryId, products)
+                        if full_price <= totalfee {
+                                if discount == 100 { //满减
+                                        totalfee = totalfee - reduce_price
+                                        discount_price = reduce_price
+                                } else { //满折
+                                        disCount_int := int(math.Ceil(discount * 100))
+                                        discount_price = totalfee - totalfee*disCount_int/1000
+                                        totalfee = totalfee * disCount_int / 1000
+                                }
+                        } else {
+                                userLotteryId = ""
+                        }
+                }
+                filterStr, _ := json.Marshal(filter)
+                ordercode := pay.GetOrderCode(userId)
+                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":          totalfee,
+                        "order_status":         0,
+                        "user_nickname":        qutil.ObjToString(this.GetSession("s_nickname")),
+                        "user_openid":          openId,
+                        "order_code":           ordercode,
+                        "product_type":         "VIP订阅",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       original_price,
+                        "filter_id":            mog_id,
+                        "user_id":              userId,
+                        "filter":               string(filterStr),   //筛选
+                        "dis_word":             disWord,             //分销口令
+                        "distribution_channel": distributionChannel, //销售渠道
+                        "order_channel":        orderChannel,        //下单渠道
+                        "discount_price":       discount_price,
+                        "d_relation_id":        userLotteryId,
+                        "vip_starttime":        FormatDate(&startTime, Date_Full_Layout),
+                        "vip_endtime":          FormatDate(&endTime, Date_Full_Layout),
+                        "vip_type":             1,
+                        "audit_status":         3, //默认审核通过
+                        "buy_subject":          buy_subject,
+                        "ent_id":               entId,
+                }
 
-		if userfilter != nil && len(*userfilter) > 0 {
-			insertMap["user_phone"], _ = qutil.If((*userfilter)["s_phone"] != nil, (*userfilter)["s_phone"], (*userfilter)["s_m_phone"]).(string)
-		}
+                if userfilter != nil && len(*userfilter) > 0 {
+                        insertMap["user_phone"], _ = qutil.If((*userfilter)["s_phone"] != nil, (*userfilter)["s_phone"], (*userfilter)["s_m_phone"]).(string)
+                }
 
-		orderid := util.Mysql.Insert("dataexport_order", insertMap)
-		if orderid == -1 {
-			return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
-		} else {
-			//绑定卡卷
-			if (userLotteryId != "" && lotteryId != "") || discountId > 0 {
-				go func(userId, userLotteryId, order_code string) {
-					phone, nickname := util.GetMyPhoneAndName(userId)
-					if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "超级订阅", strconv.Itoa(discountId), 3, 0) {
-						log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
-					}
-					if discountId > 0 {
-						if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
-							userLotteryId = strconv.Itoa(ulid)
-						}
-					}
-				}(userId, userLotteryId, ordercode)
-			}
-		}
-		//支付提醒
-		//util.MsgRemind.Add(qutil.IntAll(orderid), totalfee, -1, 0, ordercode, userId, now.Unix())
-		return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
-	}
-	this.ServeJson(r.Format())
+                orderid := util.Mysql.Insert("dataexport_order", insertMap)
+                if orderid == -1 {
+                        return &entity.FuncResult{false, errors.New("数据库操作异常"), nil}
+                } else {
+                        //绑定卡卷
+                        if (userLotteryId != "" && lotteryId != "") || discountId > 0 {
+                                go func(userId, userLotteryId, order_code string) {
+                                        phone, nickname := util.GetMyPhoneAndName(userId)
+                                        if !util.UpdateCouponState(userId, userLotteryId, nickname, phone, order_code, "超级订阅", strconv.Itoa(discountId), 3, 0) {
+                                                log.Println(fmt.Sprintf("单号%s-绑定失败-卡卷%s", order_code, userLotteryId))
+                                        }
+                                        if discountId > 0 {
+                                                if ulid := util.FindUserLotteryId(userId, orderid, discountId); ulid != 0 {
+                                                        userLotteryId = strconv.Itoa(ulid)
+                                                }
+                                        }
+                                }(userId, userLotteryId, ordercode)
+                        }
+                }
+                //支付提醒
+                //util.MsgRemind.Add(qutil.IntAll(orderid), totalfee, -1, 0, ordercode, userId, now.Unix())
+                return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode}}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }
 
 func TimeProcessing(hour interface{}, duration int) time.Time {
-	todayZero, _ := time.ParseInLocation(DateFullLayout, fmt.Sprint(hour), time.Local)
-	mm, _ := time.ParseDuration(fmt.Sprint(duration) + "m")
-	t := todayZero.Add(mm)
-	return t
+        todayZero, _ := time.ParseInLocation(DateFullLayout, fmt.Sprint(hour), time.Local)
+        mm, _ := time.ParseDuration(fmt.Sprint(duration) + "m")
+        t := todayZero.Add(mm)
+        return t
 }

+ 302 - 294
src/jfw/modules/subscribepay/src/service/vipSubscribeTrial.go

@@ -1,347 +1,355 @@
 package service
 
 import (
-	"encoding/json"
-	"errors"
-	"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"
-	"regexp"
-	"strings"
-	"time"
+        "encoding/json"
+        "errors"
+        "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"
+        "regexp"
+        "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"
-	"github.com/dchest/captcha"
-	"go.mongodb.org/mongo-driver/bson"
+        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"
+        "github.com/dchest/captcha"
+        "go.mongodb.org/mongo-driver/bson"
 )
 
 //试用用户
 type TrialOrder struct {
-	*xweb.Action
-	showTrailTip        xweb.Mapper `xweb:"/trial/showTrailTip"`        //首页试用弹框是否展示
-	closeTrailTip       xweb.Mapper `xweb:"/trial/closeTrailTip"`       //关闭首页试用弹框
-	getUserPhone        xweb.Mapper `xweb:"/trial/GetUserPhone"`        //获取用户手机号码
-	captcha             xweb.Mapper `xweb:"/trial/captcha"`             //图形验证码
-	sendPhoneCaptcha    xweb.Mapper `xweb:"/trial/sendPhoneCaptcha"`    //发送手机验证码
-	submitApply         xweb.Mapper `xweb:"/trial/submitApply"`         //提交申请信息
-	trialPay            xweb.Mapper `xweb:"/order/trialPay"`            //试用用户创建订单
-	getTrialOrderPayMsg xweb.Mapper `xweb:"/order/getTrialOrderPayMsg"` //订单数据展示(支付成功页面)
+        *xweb.Action
+        showTrailTip        xweb.Mapper `xweb:"/trial/showTrailTip"`        //首页试用弹框是否展示
+        closeTrailTip       xweb.Mapper `xweb:"/trial/closeTrailTip"`       //关闭首页试用弹框
+        getUserPhone        xweb.Mapper `xweb:"/trial/GetUserPhone"`        //获取用户手机号码
+        captcha             xweb.Mapper `xweb:"/trial/captcha"`             //图形验证码
+        sendPhoneCaptcha    xweb.Mapper `xweb:"/trial/sendPhoneCaptcha"`    //发送手机验证码
+        submitApply         xweb.Mapper `xweb:"/trial/submitApply"`         //提交申请信息
+        trialPay            xweb.Mapper `xweb:"/order/trialPay"`            //试用用户创建订单
+        getTrialOrderPayMsg xweb.Mapper `xweb:"/order/getTrialOrderPayMsg"` //订单数据展示(支付成功页面)
 }
 
 var (
-	phoneReg = regexp.MustCompile("^[1][3-9][0-9]{9}$")
-	nameReg  = regexp.MustCompile("^[\u4E00-\u9FA5A-Za-z\\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$")
+        phoneReg = regexp.MustCompile("^[1][3-9][0-9]{9}$")
+        nameReg  = regexp.MustCompile("^[\u4E00-\u9FA5A-Za-z\\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$")
 )
 
 //首页试用弹框是否展示
 func (t *TrialOrder) ShowTrailTip() {
-	userId := qutil.ObjToString(t.GetSession("userId"))
-	showTrailTip := true
-	m, _ := util.MQFW.FindById("user", userId, `{"o_vipjy":1}`)
-	if m != nil && len(*m) > 0 {
-		if (*qutil.ObjToMap((*m)["o_vipjy"]))["i_trial"] != nil {
-			showTrailTip = false
-		}
-	}
-	t.ServeJson(map[string]interface{}{
-		"showTrailTip": showTrailTip,
-	})
+        userId := qutil.ObjToString(t.GetSession("userId"))
+        showTrailTip := true
+        m, _ := util.MQFW.FindById("user", userId, `{"o_vipjy":1}`)
+        if m != nil && len(*m) > 0 {
+                if (*qutil.ObjToMap((*m)["o_vipjy"]))["i_trial"] != nil {
+                        showTrailTip = false
+                }
+        }
+        t.ServeJson(map[string]interface{}{
+                "showTrailTip": showTrailTip,
+        })
 }
 
 //关闭首页试用弹框
 func (t *TrialOrder) CloseTrailTip() {
-	userId := qutil.ObjToString(t.GetSession("userId"))
-	ok := false
-	if util.MQFW.UpdateById("user", userId,
-		bson.M{"$set": bson.M{
-			"o_vipjy.i_trial": 2}}) {
-		ok = true
-	} //已激活试用
-	t.ServeJson(map[string]interface{}{
-		"success": ok,
-	})
+        userId := qutil.ObjToString(t.GetSession("userId"))
+        ok := false
+        if util.MQFW.UpdateById("user", userId,
+                bson.M{"$set": bson.M{
+                        "o_vipjy.i_trial": 2}}) {
+                ok = true
+        } //已激活试用
+        t.ServeJson(map[string]interface{}{
+                "success": ok,
+        })
 }
 
 //获取之前用户信息
 func (t *TrialOrder) GetUserPhone() {
-	var phoneNum string
-	userId := qutil.ObjToString(t.GetSession("userId"))
-	if userId != "" {
-		m, ok := util.MQFW.FindById("user", userId, `{"s_phone":1}`)
-		if ok && len(*m) > 0 {
-			phoneNum = qutil.ObjToString((*m)["s_phone"])
-		}
-	}
-	if phoneNum == "" {
-		openid := qutil.ObjToString(t.GetSession("s_m_openid"))
-		if openid != "" {
-			m, ok := util.MQFW.FindOneByField("applysub_user", bson.M{"s_openid": openid}, `{"s_phone":1}`)
-			if ok && len(*m) > 0 {
-				phoneNum = qutil.ObjToString((*m)["s_phone"])
-			}
-		}
-	}
-	t.ServeJson(map[string]interface{}{
-		"success":  qutil.If(phoneNum == "", false, true).(bool),
-		"phoneNum": phoneNum,
-	})
+        var phoneNum string
+        userId := qutil.ObjToString(t.GetSession("userId"))
+        if userId != "" {
+                m, ok := util.MQFW.FindById("user", userId, `{"s_phone":1}`)
+                if ok && len(*m) > 0 {
+                        phoneNum = qutil.ObjToString((*m)["s_phone"])
+                }
+        }
+        if phoneNum == "" {
+                openid := qutil.ObjToString(t.GetSession("s_m_openid"))
+                if openid != "" {
+                        m, ok := util.MQFW.FindOneByField("applysub_user", bson.M{"s_openid": openid}, `{"s_phone":1}`)
+                        if ok && len(*m) > 0 {
+                                phoneNum = qutil.ObjToString((*m)["s_phone"])
+                        }
+                }
+        }
+        t.ServeJson(map[string]interface{}{
+                "success":  qutil.If(phoneNum == "", false, true).(bool),
+                "phoneNum": phoneNum,
+        })
 }
 
 //试用用户图片验证码
 func (t *TrialOrder) Captcha() error {
-	id := captcha.NewLen(4)
-	t.SetSession("subvip_trial_imgCode", id)
-	w := t.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)
+        t.SetSession("subvip_trial_imgCode", id)
+        w := t.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 (t *TrialOrder) SendPhoneCaptcha() {
-	phoneNum := t.GetString("phoneNum")
-	imgcode_req := t.GetString("imgCancode")
-	ok, errMsg := func() (bool, string) {
-		if !phoneReg.MatchString(phoneNum) {
-			return false, "手机格式不正确"
-		}
-		imgcode_sess := qutil.ObjToString(t.GetSession("subvip_trial_imgCode"))
-		if !captcha.VerifyString(imgcode_sess, imgcode_req) || imgcode_req == "" {
-			return false, "图形验证码错误"
-		}
-		//获取上次发送验证码时间
-		lastSend := qutil.Int64All(t.GetSession("subvip_trial_lastSend"))
-		if time.Now().Unix()-lastSend < 60 {
-			return false, "信息已发送"
-		}
-		//判断手机号是否存在
-		if isExist(phoneNum) {
-			return false, "手机号已使用"
-		}
-		MsgCode := qutil.GetRandom(6)
-		t.SetSession("subvip_trial_MsgCode", MsgCode)
-		t.SetSession("subvip_trial_phoneNum", phoneNum)
-		t.SetSession("subvip_trial_lastSend", time.Now().Unix())
-		log.Printf("%s 发送短信验证码 %s\n", t.GetSession("userId"), MsgCode)
-		go func() {
-			jy.SendSMS(config.Config.SmsServiceRpc, phoneNum, MsgCode)
-		}()
-		return true, ""
-	}()
-	t.ServeJson(map[string]interface{}{
-		"success": ok,
-		"errMsg":  errMsg,
-	})
+        phoneNum := t.GetString("phoneNum")
+        imgcode_req := t.GetString("imgCancode")
+        ok, errMsg := func() (bool, string) {
+                if !phoneReg.MatchString(phoneNum) {
+                        return false, "手机格式不正确"
+                }
+                imgcode_sess := qutil.ObjToString(t.GetSession("subvip_trial_imgCode"))
+                if !captcha.VerifyString(imgcode_sess, imgcode_req) || imgcode_req == "" {
+                        return false, "图形验证码错误"
+                }
+                //获取上次发送验证码时间
+                lastSend := qutil.Int64All(t.GetSession("subvip_trial_lastSend"))
+                if time.Now().Unix()-lastSend < 60 {
+                        return false, "信息已发送"
+                }
+                //判断手机号是否存在
+                if isExist(phoneNum) {
+                        return false, "手机号已使用"
+                }
+                MsgCode := qutil.GetRandom(6)
+                t.SetSession("subvip_trial_MsgCode", MsgCode)
+                t.SetSession("subvip_trial_phoneNum", phoneNum)
+                t.SetSession("subvip_trial_lastSend", time.Now().Unix())
+                log.Printf("%s 发送短信验证码 %s\n", t.GetSession("userId"), MsgCode)
+                go func() {
+                        jy.SendSMS(config.Config.SmsServiceRpc, phoneNum, MsgCode)
+                }()
+                return true, ""
+        }()
+        t.ServeJson(map[string]interface{}{
+                "success": ok,
+                "errMsg":  errMsg,
+        })
 }
 
 //提交申请信息
 func (t *TrialOrder) SubmitApply() {
-	name := t.GetString("name")
-	tel := t.GetString("tel")
-	code := t.GetString("code")
-	company := t.GetString("company")
-	job := t.GetString("job")
-	ok, errMsg := func() (bool, string) {
-		//校验数据
-		if !nameReg.MatchString(name) || code == "" || company == "" {
-			return false, "输入校验不通过"
-		}
-		//校验验证码
-		lastSend := qutil.Int64All(t.GetSession("subvip_trial_lastSend"))
-		if time.Now().Unix()-lastSend > 60*5 {
-			return false, "短信验证码已过期"
-		}
-		code_sess := qutil.ObjToString(t.GetSession("subvip_trial_MsgCode"))
-		tel_sess := qutil.ObjToString(t.GetSession("subvip_trial_phoneNum"))
-		if code != code_sess || tel != tel_sess {
-			return false, "短信验证码错误"
-		}
-		if isExist(tel_sess) {
-			return false, "手机号已使用"
-		}
-		//储存数据
-		userId := qutil.ObjToString(t.GetSession("userId"))
-		flag := util.MQFW.Save("user_msg", map[string]interface{}{
-			"s_userId":  userId,
-			"s_name":    name,
-			"s_phone":   tel,
-			"s_openid":  t.GetSession("s_m_openid"),
-			"s_company": company,
-			"s_job":     job,
-			"i_time":    time.Now().Unix(),
-			"s_source":  "vipsub_trial",
-		})
-		util.CollectPhone(userId, tel) //收集手机号
-		if flag == "" {
-			return false, "稍后重试"
-		}
-		go func() {
-			//更新user表可试用(未试用状态)
-			res, ok := util.MQFW.FindById("user", userId, `{"o_vipjy.i_trial":1}`)
-			if res != nil && len(*res) > 0 && ok {
-				o_vipjy := qutil.ObjToMap((*res)["o_vipjy"])
-				i_trial, ok := (*o_vipjy)["i_trial"]
-				if !ok || qutil.IntAll(i_trial) == 2 { //2为不提示状态
-					if !util.MQFW.UpdateById("user", userId, bson.M{"$set": bson.M{"o_vipjy.i_trial": 1}}) {
-						log.Println("更新使用状态出错", userId)
-					}
-				} else {
-					log.Printf("%s: 状态%d不能修改为试用状态\n", userId, i_trial)
-				}
-			}
-		}()
-		clearTrialSession(t.Session())
-		return true, ""
-	}()
-	t.ServeJson(map[string]interface{}{
-		"success": ok,
-		"errMsg":  errMsg,
-	})
+        name := t.GetString("name")
+        tel := t.GetString("tel")
+        code := t.GetString("code")
+        company := t.GetString("company")
+        job := t.GetString("job")
+        ok, errMsg := func() (bool, string) {
+                //校验数据
+                if !nameReg.MatchString(name) || code == "" || company == "" {
+                        return false, "输入校验不通过"
+                }
+                //校验验证码
+                lastSend := qutil.Int64All(t.GetSession("subvip_trial_lastSend"))
+                if time.Now().Unix()-lastSend > 60*5 {
+                        return false, "短信验证码已过期"
+                }
+                code_sess := qutil.ObjToString(t.GetSession("subvip_trial_MsgCode"))
+                tel_sess := qutil.ObjToString(t.GetSession("subvip_trial_phoneNum"))
+                if code != code_sess || tel != tel_sess {
+                        return false, "短信验证码错误"
+                }
+                if isExist(tel_sess) {
+                        return false, "手机号已使用"
+                }
+                //储存数据
+                userId := qutil.ObjToString(t.GetSession("userId"))
+                flag := util.MQFW.Save("user_msg", map[string]interface{}{
+                        "s_userId":  userId,
+                        "s_name":    name,
+                        "s_phone":   tel,
+                        "s_openid":  t.GetSession("s_m_openid"),
+                        "s_company": company,
+                        "s_job":     job,
+                        "i_time":    time.Now().Unix(),
+                        "s_source":  "vipsub_trial",
+                })
+                util.CollectPhone(userId, tel) //收集手机号
+                if flag == "" {
+                        return false, "稍后重试"
+                }
+                go func() {
+                        //更新user表可试用(未试用状态)
+                        res, ok := util.MQFW.FindById("user", userId, `{"o_vipjy.i_trial":1}`)
+                        if res != nil && len(*res) > 0 && ok {
+                                o_vipjy := qutil.ObjToMap((*res)["o_vipjy"])
+                                i_trial, ok := (*o_vipjy)["i_trial"]
+                                if !ok || qutil.IntAll(i_trial) == 2 { //2为不提示状态
+                                        if !util.MQFW.UpdateById("user", userId, bson.M{"$set": bson.M{"o_vipjy.i_trial": 1}}) {
+                                                log.Println("更新使用状态出错", userId)
+                                        }
+                                } else {
+                                        log.Printf("%s: 状态%d不能修改为试用状态\n", userId, i_trial)
+                                }
+                        }
+                }()
+                clearTrialSession(t.Session())
+                return true, ""
+        }()
+        t.ServeJson(map[string]interface{}{
+                "success": ok,
+                "errMsg":  errMsg,
+        })
 }
 
 //查询手机号是否存在
 func isExist(phone string) bool {
-	res, ok := util.MQFW.FindOne("user_msg", bson.M{"s_phone": phone, "s_source": "vipsub_trial"})
-	if ok && len(*res) > 0 {
-		return true
-	}
-	return false
+        res, ok := util.MQFW.FindOne("user_msg", bson.M{"s_phone": phone, "s_source": "vipsub_trial"})
+        if ok && len(*res) > 0 {
+                return true
+        }
+        return false
 }
 
 //清除session
 func clearTrialSession(session *httpsession.Session) {
-	session.Del("subvip_trial_MsgCode")
-	session.Del("subvip_trial_phoneNum")
-	session.Del("subvip_trial_lastSend")
-	session.Del("subvip_trial_imgCode")
+        session.Del("subvip_trial_MsgCode")
+        session.Del("subvip_trial_phoneNum")
+        session.Del("subvip_trial_lastSend")
+        session.Del("subvip_trial_imgCode")
 }
 
 //订单数据展示(支付成功页面)
 func (this *TrialOrder) GetTrialOrderPayMsg() {
-	orderCode := this.GetString("orderCode")
-	userId := this.GetSession("userId")
-	query := map[string]interface{}{
-		"user_id":      userId,
-		"order_code":   orderCode,
-		"order_status": 1,
-	}
-	m := util.Mysql.FindOne("dataexport_order", query, "pay_time,pay_way", "")
-	result := map[string]interface{}{}
-	if m == nil || len(*m) == 0 {
-		result["success"] = false
-		result["errMsg"] = "未找到订单"
-	} else {
-		result["success"] = true
-		result["pay_time"] = (*m)["pay_time"]
-		result["pay_way"] = (*m)["pay_way"]
-	}
-	this.ServeJson(result)
+        orderCode := this.GetString("orderCode")
+        userId := this.GetSession("userId")
+        query := map[string]interface{}{
+                "user_id":      userId,
+                "order_code":   orderCode,
+                "order_status": 1,
+        }
+        m := util.Mysql.FindOne("dataexport_order", query, "pay_time,pay_way", "")
+        result := map[string]interface{}{}
+        if m == nil || len(*m) == 0 {
+                result["success"] = false
+                result["errMsg"] = "未找到订单"
+        } else {
+                result["success"] = true
+                result["pay_time"] = (*m)["pay_time"]
+                result["pay_way"] = (*m)["pay_way"]
+        }
+        this.ServeJson(result)
 
 }
 
 //试用用户 创建订单
 func (this *TrialOrder) TrialPay() {
-	area := qutil.ObjToMap(this.GetString("area"))
-	industry := strings.Split(this.GetString("industry"), ",")
-	userId := qutil.ObjToString(this.GetSession("userId"))
-	openId := qutil.ObjToString(this.GetSession("s_m_openid"))
-	r := func() *entity.FuncResult {
-		date_count, date_unit := 7, 3
-		now := time.Now()
-		//数据校验
-		if len(industry) == 1 && industry[0] == "" { //去掉[""]
-			industry = []string{}
-		}
-		order_phone := this.GetString("order_phone") //p19.3用户信息采集 手机号
-		//插入订单表
-		mog_id := util.MQFW.Save("subvip_select", map[string]interface{}{
-			"o_area":       area,     //地区(对象)
-			"a_industry":   industry, //行业(数组)
-			"s_userid":     userId,
-			"s_openid":     openId,
-			"i_cyclecount": date_count, //时长
-			"i_cycleunit":  date_unit,  //单位
-			"i_comeintime": now.Unix(),
-		})
-		if mog_id == "" {
-			return &entity.FuncResult{false, errors.New("创建订单出错"), nil}
-		}
-		if !entity.JyVipSubStruct.CanTrial(userId) {
-			return &entity.FuncResult{false, errors.New("无试用权限"), nil}
-		}
-		//计算价格
-		totalfee := 0
-		ordercode := pay.GetOrderCode(userId)
-		//存入订单表
-		buyset := entity.JyVipSubStruct.NewBuySet(area, industry, true) //试用用户
-		filter := entity.VipSimpleMsg{
-			Area:       area,
-			Industry:   industry,
-			Cyclecount: date_count,
-			Cycleunit:  date_unit,
-			NewBuyset:  buyset,
-			OrderType:  0,
-			DisWord:    "",
-		}
-		filterStr, _ := json.Marshal(filter)
-		//结束日期 按照 自然周 算 (例:11.11开通 11.17 23.59.59结束)
-		//endTime := now.AddDate(0, 0, 7)
-		endTime_format := now.AddDate(0, 0, 7).Format(Date_Short_Layout)
-		stamp, _ := time.ParseInLocation(Date_Short_Layout, endTime_format, time.Local)
-		stamp_time := stamp.Unix() - 1 //23.59.59
-		endt := time.Unix(stamp_time, 0).Format(Date_Full_Layout)
-		endTime, _ := time.ParseInLocation(Date_Full_Layout, endt, time.Local)
-		distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
-		insertObj := map[string]interface{}{
-			"order_money":          totalfee,
-			"order_status":         1,
-			"user_nickname":        qutil.ObjToString(this.GetSession("s_nickname")),
-			"user_openid":          openId,
-			"out_trade_no":         "tradeno",
-			"order_code":           ordercode,
-			"product_type":         "VIP订阅",
-			"create_time":          FormatDate(&now, Date_Full_Layout),
-			"prepay_time":          FormatDate(&now, Date_Full_Layout),
-			"original_price":       totalfee,
-			"filter_id":            mog_id,
-			"pay_way":              "trial", //试用
-			"user_id":              userId,
-			"vip_type":             0,                 //试用用户订单
-			"filter":               string(filterStr), //筛选
-			"pay_time":             FormatDate(&now, Date_Full_Layout),
-			"vip_starttime":        FormatDate(&now, Date_Full_Layout),
-			"vip_endtime":          FormatDate(&endTime, Date_Full_Layout),
-			"distribution_channel": distributionChannel, //销售渠道
-			"order_channel":        orderChannel,        //下单渠道
-			"audit_status":         3,                   //默认审核通过
-		}
-		if order_phone != "" {
-			if !jy.PhoneReg.MatchString(order_phone) {
-				return &entity.FuncResult{false, errors.New("手机号格式异常"), nil}
-			}
-			insertObj["user_phone"] = order_phone
-		}
-		orderid := util.Mysql.Insert("dataexport_order", insertObj)
-		if orderid == -1 {
-			return &entity.FuncResult{false, errors.New("数据保存异常"), nil}
-		}
-		if !entity.JyVipSubStruct.StartSubVip(userId, filter, now, endTime, true) { //设置开始试用
-			return &entity.FuncResult{false, errors.New("开通试用异常"), nil}
-		}
-		//支付提醒
-		util.MsgRemind.PaySuccess(qutil.IntAll(orderid), ordercode, userId, FormatDate(&now, Date_Full_Layout), 0)
-		return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode}}
-	}()
-	if r.Err != nil {
-		log.Printf("%s CreateTrialOrder 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"))
+        openId := qutil.ObjToString(this.GetSession("s_m_openid"))
+        r := func() *entity.FuncResult {
+                date_count, date_unit := 7, 3
+                now := time.Now()
+                //数据校验
+                if len(industry) == 1 && industry[0] == "" { //去掉[""]
+                        industry = []string{}
+                }
+                order_phone := this.GetString("order_phone") //p19.3用户信息采集 手机号
+                //插入订单表
+                mog_id := util.MQFW.Save("subvip_select", map[string]interface{}{
+                        "o_area":       area,     //地区(对象)
+                        "a_industry":   industry, //行业(数组)
+                        "s_userid":     userId,
+                        "s_openid":     openId,
+                        "i_cyclecount": date_count, //时长
+                        "i_cycleunit":  date_unit,  //单位
+                        "i_comeintime": now.Unix(),
+                })
+                if mog_id == "" {
+                        return &entity.FuncResult{false, errors.New("创建订单出错"), nil}
+                }
+                if !entity.JyVipSubStruct.CanTrial(userId) {
+                        return &entity.FuncResult{false, errors.New("无试用权限"), nil}
+                }
+                //计算价格
+                totalfee := 0
+                ordercode := pay.GetOrderCode(userId)
+                //存入订单表
+                buyset := entity.JyVipSubStruct.NewBuySet(area, industry, true) //试用用户
+                filter := entity.VipSimpleMsg{
+                        Area:       area,
+                        Industry:   industry,
+                        Cyclecount: date_count,
+                        Cycleunit:  date_unit,
+                        NewBuyset:  buyset,
+                        OrderType:  0,
+                        DisWord:    "",
+                }
+                filterStr, _ := json.Marshal(filter)
+                //结束日期 按照 自然周 算 (例:11.11开通 11.17 23.59.59结束)
+                //endTime := now.AddDate(0, 0, 7)
+                endTime_format := now.AddDate(0, 0, 7).Format(Date_Short_Layout)
+                stamp, _ := time.ParseInLocation(Date_Short_Layout, endTime_format, time.Local)
+                stamp_time := stamp.Unix() - 1 //23.59.59
+                endt := time.Unix(stamp_time, 0).Format(Date_Full_Layout)
+                endTime, _ := time.ParseInLocation(Date_Full_Layout, endt, time.Local)
+                distributionChannel, orderChannel := util.GetJyOrderChannel("", this.Header("User-Agent"))
+                entId := qutil.Int64All(this.GetSession("entId"))
+                buy_subject := 1
+                if entId > 0 {
+                        buy_subject = 2
+                }
+                insertObj := map[string]interface{}{
+                        "order_money":          totalfee,
+                        "order_status":         1,
+                        "user_nickname":        qutil.ObjToString(this.GetSession("s_nickname")),
+                        "user_openid":          openId,
+                        "out_trade_no":         "tradeno",
+                        "order_code":           ordercode,
+                        "product_type":         "VIP订阅",
+                        "create_time":          FormatDate(&now, Date_Full_Layout),
+                        "prepay_time":          FormatDate(&now, Date_Full_Layout),
+                        "original_price":       totalfee,
+                        "filter_id":            mog_id,
+                        "pay_way":              "trial", //试用
+                        "user_id":              userId,
+                        "vip_type":             0,                 //试用用户订单
+                        "filter":               string(filterStr), //筛选
+                        "pay_time":             FormatDate(&now, Date_Full_Layout),
+                        "vip_starttime":        FormatDate(&now, Date_Full_Layout),
+                        "vip_endtime":          FormatDate(&endTime, Date_Full_Layout),
+                        "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}
+                        }
+                        insertObj["user_phone"] = order_phone
+                }
+                orderid := util.Mysql.Insert("dataexport_order", insertObj)
+                if orderid == -1 {
+                        return &entity.FuncResult{false, errors.New("数据保存异常"), nil}
+                }
+                //后期
+                if !entity.JyVipSubStruct.StartSubVip(userId, filter, now, endTime, true, 0, 0, 0) { //设置开始试用
+                        return &entity.FuncResult{false, errors.New("开通试用异常"), nil}
+                }
+                //支付提醒
+                util.MsgRemind.PaySuccess(qutil.IntAll(orderid), ordercode, userId, FormatDate(&now, Date_Full_Layout), 0)
+                return &entity.FuncResult{true, nil, map[string]interface{}{"code": ordercode}}
+        }()
+        if r.Err != nil {
+                log.Printf("%s CreateTrialOrder err:%v\n", userId, r.Err.Error())
+        }
+        this.ServeJson(r.Format())
 }

+ 383 - 339
src/jfw/modules/subscribepay/src/util/vrew.go

@@ -1,75 +1,75 @@
 package util
 
 import (
-	"encoding/json"
-	"fmt"
-	"log"
-	"strconv"
-	"strings"
-	"time"
+        "encoding/json"
+        "fmt"
+        "log"
+        "strconv"
+        "strings"
+        "time"
 
-	qutil "app.yhyue.com/moapp/jybase/common"
-	. "app.yhyue.com/moapp/jybase/date"
-	"app.yhyue.com/moapp/jybase/encrypt"
-	elastic "app.yhyue.com/moapp/jybase/esv1"
+        qutil "app.yhyue.com/moapp/jybase/common"
+        . "app.yhyue.com/moapp/jybase/date"
+        "app.yhyue.com/moapp/jybase/encrypt"
+        elastic "app.yhyue.com/moapp/jybase/esv1"
 
-	"go.mongodb.org/mongo-driver/bson"
+        "go.mongodb.org/mongo-driver/bson"
 )
 
 /*已选条件--关键词*/
 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"
-	bidSearch_sort = `{"publishtime":-1}`
-	findfields     = `"title"`
+        INDEX          = "bidding"
+        TYPE           = "bidding"
+        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"`
 )
 
-func SubViewDatas(userId, allquery string, pageNum int) (keys []interface{}, list *[]map[string]interface{}, hasNextPage bool) {
-	if userId == "" {
-		return
-	}
-	sql := GetSqlObjFromId(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, "++"))
-	}
-	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
+func SubViewDatas(userId, allquery string, pageNum int, positionType, entId, entUserId int64) (keys []interface{}, list *[]map[string]interface{}, hasNextPage bool) {
+        if userId == "" {
+                return
+        }
+        sql := GetSqlObjFromId(userId, "", -1, positionType, entId, entUserId)
+        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, "++"))
+        }
+        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
 }
 
 /*推送结果预览总数
@@ -77,14 +77,14 @@ func SubViewDatas(userId, allquery string, pageNum int) (keys []interface{}, lis
  *@param item 分类名称
  *@param index 关键词在分类下的索引位置
  */
-func SubViewDatasCount(userId, item string, index int) int64 {
-	sql := GetSqlObjFromId(userId, item, index)
-	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, item string, index int, positionType, entId, entUserId int64) int64 {
+        sql := GetSqlObjFromId(userId, item, index, positionType, entId, entUserId)
+        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)
 }
 
 /*某组关键词-推送结果预览总数
@@ -93,311 +93,355 @@ func SubViewDatasCount(userId, item string, index int) int64 {
  *@param notkey 排除词
  *@param matchway 0:精准 1:模糊
  */
-func KeysetViewDatasCount(userId, key, notkey string, matchway int) int64 {
-	key = strings.TrimSpace(key)
-	notkey = strings.TrimSpace(notkey)
-	if key == "" {
-		return 0
-	}
-	sql := GetSqlObjFromId(userId, "", -1)
-	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)
+func KeysetViewDatasCount(userId, key, notkey string, matchway int, positionType, entId, entUserId int64) int64 {
+        key = strings.TrimSpace(key)
+        notkey = strings.TrimSpace(notkey)
+        if key == "" {
+                return 0
+        }
+        sql := GetSqlObjFromId(userId, "", -1, positionType, entId, entUserId)
+        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)
 }
 
 //获取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(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(userId, "推送结果预览", qstr)
-	return qstr
+        qstr := fmt.Sprintf(query, strings.Join(musts, ","), strings.Join(bools, ","), boolsNum)
+        log.Println(userId, "推送结果预览", qstr)
+        return qstr
 }
 
 //
-func GetSqlObjFromId(_id, item string, index int) *ViewCondition {
-	var (
-		query *map[string]interface{}
-		ok    bool
-	)
-	if query, ok = MQFW.FindById("user", _id, `{"o_vipjy":1}`); !ok {
-		return nil
-	}
-	o_vipjy, _ := (*query)["o_vipjy"].(map[string]interface{})
-	a_items, _ := o_vipjy["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 GetSqlObjFromId(_id, item string, index int, positionType, entId, entUserId int64) *ViewCondition {
+        var (
+                query *map[string]interface{}
+                ok    bool
+        )
+        o_vipjy := map[string]interface{}{}
+        if positionType == 0 {
+                query, ok = MQFW.FindById("user", _id, `{"o_vipjy":1}`)
+                if !ok {
+                        return nil
+                }
+                o_vipjy, _ = (*query)["o_vipjy"].(map[string]interface{})
+        } else {
+                query, ok = MQFW.FindOne("entniche_rule", map[string]interface{}{
+                        "i_userid": entUserId,
+                        "i_entid":  entId,
+                        "i_type":   1,
+                })
+                if !ok {
+                        return nil
+                }
+                o_vipjy, _ = (*query)["o_entniche"].(map[string]interface{})
+        }
+        a_items, _ := o_vipjy["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
-	} else {
-		arr = cityArr
-	}
-	return
+        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
+        } else {
+                arr = cityArr
+        }
+        return
 }
 
 //关键词 附加词 排除词
 func getKeyWordArrFromDbResult(a_items []interface{}, item string, index int) (arr []ViewKeyWord) {
-	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
-		}
-		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)
-			}
-		}
-	}
-	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
+                }
+                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)
+                        }
+                }
+        }
+        return
 }
 
 //初始化vip订阅关键词
-func MergeKws(userId string) {
-	defer qutil.Catch()
-	if userId == "" { //11-11 取消此操作
-		return
-	}
-	data, ok := MQFW.FindById("user", userId, `{"o_jy":1,"o_vipjy":1}`)
-	var o_vipjy map[string]interface{}
-	if ok && data != nil && len(*data) > 0 {
-		o_vipjy, _ = (*data)["o_vipjy"].(map[string]interface{})
-		a_items, _ := o_vipjy["a_items"].([]interface{})
-		m := bson.M{}
-		if a_items == nil { //首次
-			m = bson.M{"o_vipjy.i_matchway": 1, "o_vipjy.i_ratemode": 1, "o_vipjy.i_wxpush": 1, "o_vipjy.i_apppush": 1, "o_vipjy.a_infotype": []string{}, "o_vipjy.a_items": []string{}, "o_vipjy.l_modifydate": time.Now().Unix()}
-		} else {
-			//免费用户试用超级订阅
-			wxpush := o_vipjy["i_wxpush"]
-			apppush := o_vipjy["i_apppush"]
-			if wxpush == nil && apppush == nil {
-				m = bson.M{"o_vipjy.i_ratemode": 1, "o_vipjy.i_wxpush": 1, "o_vipjy.i_apppush": 1, "o_vipjy.l_modifydate": time.Now().Unix()}
-			}
-		}
-		MQFW.UpdateById("user", userId, bson.M{
-			"$set": m,
-		})
-	}
+func MergeKws(userId string, positionType, entId, entUserId int64) {
+        defer qutil.Catch()
+        if userId == "" { //11-11 取消此操作
+                return
+        }
+        data := &map[string]interface{}{}
+        ok := false
+        var o_vipjy map[string]interface{}
+        if positionType == 0 {
+                data, ok = MQFW.FindById("user", userId, `{"o_jy":1,"o_vipjy":1}`)
+        } else {
+                query := map[string]interface{}{
+                        "i_userid": entUserId,
+                        "i_entid":  entId,
+                        "i_type":   1,
+                }
+                data, ok = MQFW.FindOne("entniche_rule", query)
+        }
+        if ok && data != nil && len(*data) > 0 {
+                if positionType == 0 {
+                        o_vipjy, _ = (*data)["o_vipjy"].(map[string]interface{})
+                } else {
+                        o_vipjy, _ = (*data)["o_entniche"].(map[string]interface{})
+                }
+                a_items, _ := o_vipjy["a_items"].([]interface{})
+                m := bson.M{}
+                vipjy := "o_vipjy"
+                if positionType == 1 {
+                        vipjy = "o_entniche"
+                }
+                if a_items == nil { //首次
+                        m = bson.M{fmt.Sprintf("%s.i_matchway", vipjy): 1, fmt.Sprintf("%s.i_ratemode", vipjy): 1, fmt.Sprintf("%s.i_wxpush", vipjy): 1, fmt.Sprintf("%s.i_apppush", vipjy): 1, fmt.Sprintf("%s.a_infotype", vipjy): []string{}, fmt.Sprintf("%s.a_items", vipjy): []string{}, fmt.Sprintf("%s.l_modifydate", vipjy): time.Now().Unix()}
+                } else {
+                        //免费用户试用超级订阅
+                        wxpush := o_vipjy["i_wxpush"]
+                        apppush := o_vipjy["i_apppush"]
+                        if wxpush == nil && apppush == nil {
+                                m = bson.M{fmt.Sprintf("%s.i_ratemode"): 1, fmt.Sprintf("%s.i_wxpush"): 1, fmt.Sprintf("%s.i_apppush"): 1, fmt.Sprintf("%s.l_modifydate"): time.Now().Unix()}
+                        }
+                }
+                if positionType == 0 {
+                        MQFW.UpdateById("user", userId, bson.M{
+                                "$set": m,
+                        })
+                } else {
+                        query := map[string]interface{}{
+                                "i_userid": entUserId,
+                                "i_entid":  entId,
+                                "i_type":   1,
+                        }
+                        MQFW.Update("entniche_rule", query, map[string]interface{}{
+                                "$set": m,
+                        }, true, false)
+                }
+        }
 }
 
 //m 月 超过一年传12+n月 如14; endtime 当前周期结束时间戳 int64 ;val -   1:年 2:月 4:季度
 func GetDATE(val int, m int, endtime int64) (_endtime time.Time) {
-	//一年12个月
-	if val == 1 {
-		m = m * 12
-	}
-	//一个季度3个月
-	if val == 4 {
-		m = m * 3
-	}
-	endFormat := FormatDateByInt64(&endtime, Date_Short_Layout)
-	date_y, _ := strconv.Atoi(strings.Split(endFormat, "-")[0])
-	date_m, _ := strconv.Atoi(strings.Split(endFormat, "-")[1])
-	date_d, _ := strconv.Atoi(strings.Split(endFormat, "-")[2])
-	if date_m+m > 12 {
-		date_y = date_y + (date_m+m-1)/12
-		date_m = date_m + m - 12*((date_m+m-1)/12)
-	} else {
-		date_m = date_m + m
-	}
-	mstr := strconv.Itoa(date_m)
-	if date_m < 10 {
-		mstr = "0" + mstr
-	}
-	_date := strconv.Itoa(date_y) + "-" + mstr + "-01"
-	p, _ := time.ParseInLocation(Date_Short_Layout, _date, time.Local)
-	date := time.Unix(p.Unix(), 0).AddDate(0, 1, -1)
-	thisD, _ := strconv.Atoi(strings.Split(FormatDate(&date, Date_Short_Layout), "-")[2])
-	dstr := "01"
-	if thisD < date_d {
-		dstr = strconv.Itoa(thisD)
-		if thisD < 10 {
-			dstr = "0" + strconv.Itoa(thisD)
-		}
-	} else {
-		dstr = strconv.Itoa(date_d)
-		if date_d < 10 {
-			dstr = "0" + strconv.Itoa(date_d)
-		}
-	}
-	_date = strconv.Itoa(date_y) + "-" + mstr + "-" + dstr + " 23:59:59"
-	lastDate, _ := time.ParseInLocation(Date_Full_Layout, _date, time.Local)
-	return lastDate
+        //一年12个月
+        if val == 1 {
+                m = m * 12
+        }
+        //一个季度3个月
+        if val == 4 {
+                m = m * 3
+        }
+        endFormat := FormatDateByInt64(&endtime, Date_Short_Layout)
+        date_y, _ := strconv.Atoi(strings.Split(endFormat, "-")[0])
+        date_m, _ := strconv.Atoi(strings.Split(endFormat, "-")[1])
+        date_d, _ := strconv.Atoi(strings.Split(endFormat, "-")[2])
+        if date_m+m > 12 {
+                date_y = date_y + (date_m+m-1)/12
+                date_m = date_m + m - 12*((date_m+m-1)/12)
+        } else {
+                date_m = date_m + m
+        }
+        mstr := strconv.Itoa(date_m)
+        if date_m < 10 {
+                mstr = "0" + mstr
+        }
+        _date := strconv.Itoa(date_y) + "-" + mstr + "-01"
+        p, _ := time.ParseInLocation(Date_Short_Layout, _date, time.Local)
+        date := time.Unix(p.Unix(), 0).AddDate(0, 1, -1)
+        thisD, _ := strconv.Atoi(strings.Split(FormatDate(&date, Date_Short_Layout), "-")[2])
+        dstr := "01"
+        if thisD < date_d {
+                dstr = strconv.Itoa(thisD)
+                if thisD < 10 {
+                        dstr = "0" + strconv.Itoa(thisD)
+                }
+        } else {
+                dstr = strconv.Itoa(date_d)
+                if date_d < 10 {
+                        dstr = "0" + strconv.Itoa(date_d)
+                }
+        }
+        _date = strconv.Itoa(date_y) + "-" + mstr + "-" + dstr + " 23:59:59"
+        lastDate, _ := time.ParseInLocation(Date_Full_Layout, _date, time.Local)
+        return lastDate
 }

+ 79 - 8
src/jfw/modules/weixin/src/go.mod

@@ -3,40 +3,111 @@ module jy/src/jfw/modules/weixin/src
 go 1.18
 
 require (
-	app.yhyue.com/moapp/jybase v0.0.0-20230110071808-0c8ff7f798c6
-	app.yhyue.com/moapp/jypkg v0.0.0-20221230014931-c9afd45ba90b
+	app.yhyue.com/moapp/jybase v0.0.0-20230117032034-ad7c00ffe11a
+	app.yhyue.com/moapp/jypkg v0.0.0-20230128092104-d8ae3867d2ab
 	github.com/SKatiyar/qr v0.0.0-20151201054752-25b6bdf44e67
 	go.mongodb.org/mongo-driver v1.11.1
 )
 
+require go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.10.0 // indirect
+
 require (
 	app.yhyue.com/moapp/esv1 v0.0.0-20220414031211-3da4123e648d // indirect
-	app.yhyue.com/moapp/message v0.0.0-20221202072401-d825fc65512c // indirect
+	app.yhyue.com/moapp/message v0.0.0-20221223100203-6402e389d9ae // indirect
+	bp.jydev.jianyu360.cn/BaseService/powerCheckCenter v0.0.0-20230128033309-a6b26e74a68c // 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/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.1 // indirect
 	github.com/garyburd/redigo v1.6.2 // indirect
-	github.com/go-sql-driver/mysql v1.6.0 // indirect
-	github.com/golang-jwt/jwt/v4 v4.4.2 // 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-jwt/jwt/v4 v4.4.3 // 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/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/mattn/go-colorable v0.1.9 // indirect
+	github.com/mattn/go-isatty v0.0.14 // 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/nsqio/go-nsq v1.1.0 // 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/robfig/cron v1.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/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/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
-	golang.org/x/text v0.3.8-0.20211105212822-18b340fc7af2 // 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
 )

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 538 - 11
src/jfw/modules/weixin/src/go.sum


+ 1 - 1
src/jfw/modules/weixin/src/wx/wx.go

@@ -1,6 +1,7 @@
 package wx
 
 import (
+	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 	"encoding/json"
 	"fmt"
 	"jy/src/jfw/modules/weixin/src/config"
@@ -20,7 +21,6 @@ import (
 	"app.yhyue.com/moapp/jybase/redis"
 
 	"app.yhyue.com/moapp/jybase/usercenter"
-	"app.yhyue.com/moapp/jypkg/common/src/qfw/util/jy"
 
 	. "jy/src/jfw/modules/weixin/src/github.com/wizjin/weixin"
 

Vissa filer visades inte eftersom för många filer har ändrats