Browse Source

金瑞小程序接口

hsun 1 month ago
parent
commit
aaf88e8710
63 changed files with 2067 additions and 5922 deletions
  1. 2 1
      .gitignore
  2. 65 68
      controllers/banner.go
  3. 20 19
      controllers/base_auth.go
  4. 1 2
      controllers/base_common.go
  5. 0 116
      controllers/chart.go
  6. 0 205
      controllers/chart_permission.go
  7. 74 0
      controllers/classify.go
  8. 2 23
      controllers/mini_config.go
  9. 0 335
      controllers/my_chart.go
  10. 0 445
      controllers/my_report.go
  11. 344 840
      controllers/report.go
  12. 136 988
      controllers/user.go
  13. 1 321
      controllers/wechat.go
  14. 23 29
      models/banner.go
  15. 0 14
      models/business_conf.go
  16. 0 42
      models/chart_permission.go
  17. 0 12
      models/chart_permission_search_key_word_mapping.go
  18. 121 37
      models/classify.go
  19. 21 0
      models/constants.go
  20. 3 14
      models/db.go
  21. 3 27
      models/mini_config.go
  22. 8 7
      models/msg_code.go
  23. 0 60
      models/my_chart.go
  24. 0 54
      models/my_report.go
  25. 280 70
      models/report.go
  26. 0 147
      models/report_pdf.go
  27. 0 84
      models/report_push_status.go
  28. 8 0
      models/request/classify.go
  29. 0 15
      models/request/my_chart.go
  30. 0 9
      models/request/my_report.go
  31. 14 0
      models/request/report.go
  32. 5 36
      models/request/user.go
  33. 0 104
      models/response/chart.go
  34. 0 1
      models/response/chart_permission.go
  35. 0 26
      models/response/my_chart.go
  36. 0 16
      models/response/my_report.go
  37. 5 75
      models/response/report.go
  38. 7 10
      models/response/user.go
  39. 0 32
      models/sys_department.go
  40. 0 17
      models/sys_user.go
  41. 0 123
      models/user.go
  42. 0 16
      models/user_chart_permission_mapping.go
  43. 0 26
      models/user_read_permission.go
  44. 60 59
      models/user_read_record.go
  45. 143 30
      models/user_record.go
  46. 218 0
      models/users.go
  47. 2 2
      models/wx_token.go
  48. 11 335
      routers/commentsRouter.go
  49. 12 32
      routers/router.go
  50. 0 69
      services/base_lib.go
  51. 0 40
      services/chart.go
  52. 0 140
      services/chart_permission.go
  53. 12 45
      services/classify.go
  54. 0 165
      services/report.go
  55. 69 18
      services/sms.go
  56. 106 192
      services/user.go
  57. 0 10
      services/verify.go
  58. 1 0
      services/wechat.go
  59. 145 158
      services/wechat/template_msg.go
  60. 92 106
      services/wechat/wechat.go
  61. 25 0
      utils/common.go
  62. 23 36
      utils/config.go
  63. 5 19
      utils/constants.go

+ 2 - 1
.gitignore

@@ -1,8 +1,9 @@
 /conf/
 /.vscode/
-/etalogs/
+/logs/
 *.exe
 *.exe~
 go.sum
 /rdlucklog/
 *_test.go
+/.idea

+ 65 - 68
controllers/banner.go

@@ -1,70 +1,67 @@
 package controllers
 
-import (
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/utils"
-)
-
-type BannerController struct {
-	BaseAuthController
-}
-
-// @Title List
-// @Description create users
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.BaseResponse
-// @router /list [get]
-func (this *BannerController) List() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	if pageSize <= 0 {
-		pageSize = utils.PageSize20
-	}
-	startSize := utils.StartIndex(currentIndex, pageSize)
-	banners, err := models.GetBannerList(startSize, pageSize)
-	if err != nil {
-		br.Msg = "获取banner列表失败"
-		br.ErrMsg = "获取banner列表失败,系统异常,Err:" + err.Error()
-		return
-	}
-	br.Data = banners
-	br.Msg = "获取banner列表成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title Detail
-// @Description banner详情
-// @Param   BannerId   query   int  true       "bannerId"
-// @Success 200 {object} models.BaseResponse
-// @router /detail [get]
-func (this *BannerController) Detail() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	bannerId, _ := this.GetInt("BannerId")
-
-	banners, err := models.GetBannerById(bannerId)
-	if err != nil {
-		br.Msg = "获取banner详情失败"
-		br.ErrMsg = "获取banner详情失败,系统异常,Err:" + err.Error()
-		return
-	}
-	br.Data = banners
-	br.Msg = "获取banner列表成功"
-	br.Success = true
-	br.Ret = 200
-}
+//type BannerController struct {
+//	BaseAuthController
+//}
+//
+//// List
+//// @Title List
+//// @Description create users
+//// @Param   PageSize   query   int  true       "每页数据条数"
+//// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+//// @Success 200 {object} models.BaseResponse
+//// @router /list [get]
+//func (this *BannerController) List() {
+//	br := new(models.BaseResponse).Init()
+//	defer func() {
+//		this.Data["json"] = br
+//		this.ServeJSON()
+//	}()
+//
+//	pageSize, _ := this.GetInt("PageSize")
+//	currentIndex, _ := this.GetInt("CurrentIndex")
+//
+//	if currentIndex <= 0 {
+//		currentIndex = 1
+//	}
+//	if pageSize <= 0 {
+//		pageSize = utils.PageSize20
+//	}
+//	startSize := utils.StartIndex(currentIndex, pageSize)
+//	banners, err := models.GetBannerList(startSize, pageSize)
+//	if err != nil {
+//		br.Msg = "获取banner列表失败"
+//		br.ErrMsg = "获取banner列表失败,系统异常,Err:" + err.Error()
+//		return
+//	}
+//	br.Data = banners
+//	br.Msg = "获取banner列表成功"
+//	br.Success = true
+//	br.Ret = 200
+//}
+//
+//// Detail
+//// @Title Detail
+//// @Description banner详情
+//// @Param   BannerId   query   int  true       "bannerId"
+//// @Success 200 {object} models.BaseResponse
+//// @router /detail [get]
+//func (this *BannerController) Detail() {
+//	br := new(models.BaseResponse).Init()
+//	defer func() {
+//		this.Data["json"] = br
+//		this.ServeJSON()
+//	}()
+//	bannerId, _ := this.GetInt("BannerId")
+//
+//	banners, err := models.GetBannerById(bannerId)
+//	if err != nil {
+//		br.Msg = "获取banner详情失败"
+//		br.ErrMsg = "获取banner详情失败,系统异常,Err:" + err.Error()
+//		return
+//	}
+//	br.Data = banners
+//	br.Msg = "获取banner列表成功"
+//	br.Success = true
+//	br.Ret = 200
+//}

+ 20 - 19
controllers/base_auth.go

@@ -5,17 +5,15 @@ import (
 	"eta/eta_mini_api/models"
 	"eta/eta_mini_api/utils"
 	"fmt"
+	"github.com/beego/beego/v2/server/web"
 	"net/http"
 	"net/url"
 	"strings"
-	"time"
-
-	"github.com/beego/beego/v2/server/web"
 )
 
 type BaseAuthController struct {
 	web.Controller
-	User    *models.User
+	User    *models.UsersItem
 	Session *models.WxSession
 }
 
@@ -25,6 +23,9 @@ func (c *BaseAuthController) Prepare() {
 	if method != "HEAD" {
 		if method == "POST" || method == "GET" {
 			authorization := c.Ctx.Input.Header("authorization")
+			if authorization == "" {
+				authorization = c.Ctx.Input.Header("Authorization")
+			}
 			if authorization == "" {
 				c.JSON(models.BaseResponse{Ret: 408, Msg: "请重新授权!", ErrMsg: "请重新授权:Token is empty or account is empty"}, false, false)
 				c.StopRun()
@@ -47,23 +48,23 @@ func (c *BaseAuthController) Prepare() {
 				c.StopRun()
 				return
 			}
-			user, err := models.GetUserByOpenId(session.OpenId)
-			if err != nil && err.Error() != utils.ErrNoRow() {
-				c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Err:" + err.Error()}, false, false)
-				c.StopRun()
-				return
-			}
-			c.User = user
-			c.Session = session
-			// 判断正式用户,是否在有效期内
-			if c.User != nil && c.User.Status == utils.UserStatusFormal {
-				if c.User.ValidStartTime.Before(time.Now()) && c.User.ValidEndTime.After(time.Now()) {
-					c.User.Status = utils.UserStatusFormal
-				} else {
-					c.User.Status = utils.UserStatusNo
-				}
 
+			usersOb := new(models.Users)
+			{
+				cond := fmt.Sprintf(` AND %s = ?`, usersOb.Cols().OpenId)
+				pars := make([]interface{}, 0)
+				pars = append(pars, session.OpenId)
+				users, e := usersOb.GetItemByCondition(cond, pars, "")
+				if e != nil && e.Error() != utils.ErrNoRow() {
+					c.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: fmt.Sprintf("获取用户信息异常,Err:%v", e)}, false, false)
+					c.StopRun()
+					return
+				}
+				if users != nil {
+					c.User = users.Format2Item()
+				}
 			}
+			c.Session = session
 		} else {
 			c.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
 			c.StopRun()

+ 1 - 2
controllers/base_common.go

@@ -3,7 +3,6 @@ package controllers
 import (
 	"encoding/json"
 	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/services"
 	"eta/eta_mini_api/utils"
 	"fmt"
 	"net/http"
@@ -75,7 +74,7 @@ func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding boo
 	}
 
 	// 数据加密
-	if services.CheckEncryption() {
+	if utils.RunMode == "release" {
 		content = utils.DesBase64Encrypt(content, utils.DesKey)
 		// get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
 		content = []byte(`"` + string(content) + `"`)

+ 0 - 116
controllers/chart.go

@@ -1,116 +0,0 @@
-package controllers
-
-import (
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/models/response"
-	"eta/eta_mini_api/services"
-)
-
-type ChartController struct {
-	BaseAuthController
-}
-
-// @Title List
-// @Description create users
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.BaseResponse
-// @router /list [get]
-func (this *ChartController) List() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-
-	result, err := services.GetChartList(currentIndex, pageSize)
-	if err != nil {
-		br.Msg = "查询图表失败"
-		br.ErrMsg = "查询图表失败,系统异常,Err:" + err.Error()
-		return
-	}
-	if result.Ret != 200 {
-		br.Msg = "查询图表失败"
-		br.ErrMsg = result.ErrMsg
-		return
-	}
-
-	br.Msg = "查询图表成功"
-	br.Data = result.Data
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title Locate
-// @Description create users
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.BaseResponse
-// @router /locate [get]
-func (this *ChartController) Locate() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	if pageSize <= 0 {
-		pageSize = 2
-	}
-	result, err := services.GetChartList(currentIndex, pageSize)
-	if err != nil {
-		br.Msg = "查询图表失败"
-		br.ErrMsg = "查询图表失败,系统异常,Err:" + err.Error()
-		return
-	}
-	if result.Ret != 200 {
-		br.Msg = result.Msg
-		br.ErrMsg = result.ErrMsg
-		return
-	}
-	total := len(result.Data.List)
-	charts := make([]*response.ChartLocateItem, 0)
-
-	items := result.Data.List
-	for k, v := range items {
-		var prevChartInfoId, nextChartInfoId int
-		switch k {
-		case 0:
-			prevChartInfoId = -1
-			if k < total-1 {
-				nextChartInfoId = items[k+1].ChartInfoId
-			} else {
-				nextChartInfoId = -1
-			}
-		case total - 1:
-			nextChartInfoId = -1
-			if k > 0 {
-				prevChartInfoId = items[k-1].ChartInfoId
-			}
-		default:
-			prevChartInfoId = items[k-1].ChartInfoId
-			nextChartInfoId = items[k+1].ChartInfoId
-
-		}
-		tmpLocate := &response.ChartLocateItem{
-			ChartInfoId:     v.ChartInfoId,
-			ChartName:       v.ChartName,
-			UniqueCode:      v.UniqueCode,
-			PrevChartInfoId: prevChartInfoId,
-			NextChartInfoId: nextChartInfoId,
-		}
-		charts = append(charts, tmpLocate)
-	}
-
-	br.Data = charts
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}

+ 0 - 205
controllers/chart_permission.go

@@ -1,205 +0,0 @@
-package controllers
-
-import (
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/services"
-	"eta/eta_mini_api/utils"
-)
-
-type ChartPermissionController struct {
-	BaseAuthController
-}
-
-type ChartPermissionNoAuthController struct {
-	BaseCommonController
-}
-
-// List
-// @Title 系统品种列表
-// @Description 系统品种列表
-// @Param   chartPermissonId   query   int  true       "品种权限id"
-// @Success 200 {object} models.LoginResp
-// @router /list [get]
-func (this *ChartPermissionController) List() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	id, _ := this.GetInt("chartPermissonId", 0)
-
-	var resp *models.ChartPermissionResp[[]*models.ChartPermission]
-	var err error
-	if id == 0 {
-		resp, err = services.GetChartPermissionList()
-	} else if id > 0 {
-		resp, err = services.GetChartPermissionSecondList(id)
-	}
-	if err != nil {
-		br.Msg = "权限列表获取失败"
-		br.ErrMsg = "权限列表获取失败,系统错误,Err:" + err.Error()
-		return
-	}
-	if resp.Ret != 200 {
-		br.Msg = resp.Msg
-		br.ErrMsg = resp.ErrMsg
-		return
-	}
-	chartPermissionList := make([]*models.ChartPermissionView, 0)
-	for _, item := range resp.Data {
-		chartPermissionList = append(chartPermissionList, &models.ChartPermissionView{
-			ChartPermissionId:   item.ChartPermissionId,
-			PermissionName:      item.PermissionName,
-			Remark:              item.Remark,
-			ImageUrl:            item.ImageUrl,
-			ChartPermissionType: utils.PermissionTypeEta,
-		})
-
-	}
-	// 如果id != 0, 则只返回二级品种权限,并且需要附加pdf报告品种
-	if id != 0 {
-		chartPermissionList = append(chartPermissionList, &models.ChartPermissionView{
-			ChartPermissionId:   -1,
-			PermissionName:      utils.MINI_CUSTOM_PERMISSION_NAME,
-			Remark:              "",
-			ImageUrl:            "",
-			ChartPermissionType: utils.PermissionTypeMini,
-		})
-
-	}
-
-	br.Ret = 200
-	br.Data = chartPermissionList
-	br.Msg = "列表获取成功"
-	br.Success = true
-}
-
-// ClassifyTree
-// @Title 获取品种下的分类权限列表
-// @Description 获取研报的品种权限列表
-// @Param   ChartPermissionId   query   int  true       "品种权限id"
-// @Success 200 {object} []models.ChartPermission
-// @router /classify/tree [get]
-func (this *ChartPermissionController) ClassifyTree() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	chartPermissionId, _ := this.GetInt("ChartPermissionId")
-	if chartPermissionId <= 0 {
-		br.Msg = "品种权限不能为空"
-		return
-	}
-	resp, err := services.GetClassifyTreeByChartPermission(chartPermissionId)
-	if err != nil {
-		br.Msg = "获取分类失败"
-		br.ErrMsg = "品种权限获取失败,系统错误,Err:" + err.Error()
-		return
-	}
-	if resp.Ret != 200 {
-		br.Msg = resp.Msg
-		br.ErrMsg = resp.ErrMsg
-		return
-	}
-	classifyList := resp.Data
-
-	br.Data = classifyList
-	br.Msg = "获取成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// ClassifyTree
-// @Title 获取品种下的分类权限列表
-// @Description 获取研报的品种权限列表
-// @Param   ChartPermissionId   query   int  true       "品种权限id"
-// @Success 200 {object} []models.ChartPermission
-// @router /classify/tree [get]
-func (this *ChartPermissionNoAuthController) ClassifyTree() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	chartPermissionId, _ := this.GetInt("ChartPermissionId")
-	if chartPermissionId < 0 {
-		br.Msg = "品种权限异常"
-		return
-	}
-	resp, err := services.GetClassifyTreeByChartPermission(chartPermissionId)
-	if err != nil {
-		br.Msg = "获取分类失败"
-		br.ErrMsg = "品种权限获取失败,系统错误,Err:" + err.Error()
-		return
-	}
-	if resp.Ret != 200 {
-		br.Msg = resp.Msg
-		br.ErrMsg = resp.ErrMsg
-		return
-	}
-	classifyList := resp.Data
-
-	br.Data = classifyList
-	br.Msg = "获取成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// List
-// @Title 系统品种列表
-// @Description 系统品种列表
-// @Param   chartPermissonId   query   int  true       "品种权限id"
-// @Success 200 {object} models.LoginResp
-// @router /list [get]
-func (this *ChartPermissionNoAuthController) List() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	id, _ := this.GetInt("chartPermissonId", 0)
-
-	var resp *models.ChartPermissionResp[[]*models.ChartPermission]
-	var err error
-	if id == 0 {
-		resp, err = services.GetChartPermissionList()
-	} else if id > 0 {
-		resp, err = services.GetChartPermissionSecondList(id)
-	}
-	if err != nil {
-		br.Msg = "权限列表获取失败"
-		br.ErrMsg = "权限列表获取失败,系统错误,Err:" + err.Error()
-		return
-	}
-	if resp.Ret != 200 {
-		br.Msg = resp.Msg
-		br.ErrMsg = resp.ErrMsg
-		return
-	}
-	chartPermissionList := make([]*models.ChartPermissionView, 0)
-	for _, item := range resp.Data {
-		chartPermissionList = append(chartPermissionList, &models.ChartPermissionView{
-			ChartPermissionId:   item.ChartPermissionId,
-			PermissionName:      item.PermissionName,
-			Remark:              item.Remark,
-			ImageUrl:            item.ImageUrl,
-			ChartPermissionType: utils.PermissionTypeEta,
-		})
-
-	}
-	if id > 0 {
-		chartPermissionList = append(chartPermissionList, &models.ChartPermissionView{
-			ChartPermissionId:   id,
-			PermissionName:      utils.ZC_CUSTOM_PERMISSION_NAME,
-			Remark:              "",
-			ImageUrl:            "",
-			ChartPermissionType: utils.PermissionTypeMini,
-		})
-	}
-
-	br.Ret = 200
-	br.Data = chartPermissionList
-	br.Msg = "列表获取成功"
-	br.Success = true
-}

+ 74 - 0
controllers/classify.go

@@ -0,0 +1,74 @@
+package controllers
+
+import (
+	"eta/eta_mini_api/models"
+	"eta/eta_mini_api/models/request"
+	"eta/eta_mini_api/services"
+	"eta/eta_mini_api/utils"
+	"fmt"
+)
+
+type ClassifyController struct {
+	BaseAuthController
+}
+
+// Tree
+// @Title 分类树
+// @Description 分类树
+// @Param	request	body request.ClassifyTreeForm true "type json string"
+// @Success 200 {object} models.ReportDetailResp
+// @router /tree [get]
+func (this *ClassifyController) Tree() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	params := new(request.ClassifyTreeForm)
+	if e := this.ParseForm(params); e != nil {
+		br.Msg = "参数解析异常"
+		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
+		return
+	}
+
+	classifyOb := new(models.MiniClassify)
+	cond := fmt.Sprintf(` AND %s = 1`, classifyOb.Cols().Enabled)
+	pars := make([]interface{}, 0)
+	if params.DiamondDistrict > 0 {
+		cond += fmt.Sprintf(` AND %s = ?`, classifyOb.Cols().DiamondDistrict)
+		pars = append(pars, params.DiamondDistrict)
+	}
+	if params.Frequency > 0 {
+		cond += fmt.Sprintf(` AND %s = ?`, classifyOb.Cols().Frequency)
+		pars = append(pars, params.Frequency)
+	}
+	if params.HotComment > 0 {
+		cond += fmt.Sprintf(` AND %s = ?`, classifyOb.Cols().HotComment)
+		pars = append(pars, params.HotComment)
+	}
+	if params.KeyPoint > 0 {
+		cond += fmt.Sprintf(` AND %s = ?`, classifyOb.Cols().KeyPoint)
+		pars = append(pars, params.KeyPoint)
+	}
+
+	list, e := classifyOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s ASC, %s ASC", classifyOb.Cols().Sort, classifyOb.Cols().ParentId))
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = fmt.Sprintf("获取分类失败, %v", e)
+		return
+	}
+	classifies := make([]*models.MiniClassifyItem, 0)
+	for _, v := range list {
+		classifies = append(classifies, v.Format2Item())
+	}
+	var rootId int
+	if utils.RunMode == "debug" {
+		rootId = 659
+	}
+	classifies = services.GetClassifyTreeRecursive(classifies, rootId)
+
+	br.Data = classifies
+	br.Ret = 200
+	br.Msg = "获取成功"
+	br.Success = true
+}

+ 2 - 23
controllers/mini_config.go

@@ -9,13 +9,10 @@ type MiniConfigController struct {
 	BaseCommonController
 }
 
+// MiniConfig
 // @Title 获取小程序配置项
 // @Description 获取小程序配置项
-// @Param   ReportId   query   int  true       "报告id"
-// @Param   chartPermissionId   query   int  true       "品种ID"
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.ReportDetailResp
+// @Success 200 {object} response.MiniConfigResp
 // @router /config [get]
 func (this *MiniConfigController) MiniConfig() {
 	br := new(models.BaseResponse).Init()
@@ -47,27 +44,9 @@ func (this *MiniConfigController) MiniConfig() {
 	}, response.MiniConfigResp{
 		ConfKey: "ServiceAgreement",
 		ConfVal: miniConf["ServiceAgreement"],
-	}, response.MiniConfigResp{
-		ConfKey: "MostReport",
-		ConfVal: miniConf["MostReport"],
 	}, response.MiniConfigResp{
 		ConfKey: "ServicePhone",
 		ConfVal: miniConf["ServicePhone"],
-	}, response.MiniConfigResp{
-		ConfKey: "Colors",
-		ConfVal: miniConf["Colors"],
-	}, response.MiniConfigResp{
-		ConfKey: "EmptyImg",
-		ConfVal: miniConf["EmptyImg"],
-	}, response.MiniConfigResp{
-		ConfKey: "Logo",
-		ConfVal: miniConf["Logo"],
-	}, response.MiniConfigResp{
-		ConfKey: "WxAppId",
-		ConfVal: miniConf["WxAppId"],
-	}, response.MiniConfigResp{
-		ConfKey: "BindImg",
-		ConfVal: miniConf["BindImg"],
 	})
 
 	br.Data = list

+ 0 - 335
controllers/my_chart.go

@@ -1,335 +0,0 @@
-package controllers
-
-import (
-	"encoding/json"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/models/request"
-	"eta/eta_mini_api/models/response"
-	"eta/eta_mini_api/services"
-	"eta/eta_mini_api/utils"
-	"time"
-
-	"github.com/rdlucklib/rdluck_tools/paging"
-)
-
-type MyChartController struct {
-	BaseAuthController
-}
-
-// @Title 收藏图表
-// @Description 收藏图表
-// @Success 200 {object} models.BaseResponse
-// @router /collect [post]
-func (this *MyChartController) Collect() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyChartCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	if req.ChartInfoId == 0 {
-		chartResp, err := services.GetChartDetail(req.ChartInfoId, req.UniqueCode)
-		if err != nil {
-			br.Msg = "收藏失败"
-			br.Msg = "获取图表信息失败,系统错误,Err:" + err.Error()
-			return
-		}
-		if chartResp.Ret != 200 {
-			br.Msg = chartResp.Msg
-			br.ErrMsg = chartResp.ErrMsg
-			return
-		}
-		req.ChartInfoId = chartResp.Data.ChartInfoId
-	}
-	count, err := models.GetMyChartCount(user.UserId, req.UniqueCode)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	if count > 0 {
-		br.Msg = "该图表已收藏,请重新刷新页面"
-		return
-	}
-	myChart := &models.MyChart{
-		UserId:       user.UserId,
-		UserRealName: user.RealName,
-		UniqueCode:   req.UniqueCode,
-		ChartImage:   req.ChartImage,
-		ChartName:    req.ChartName,
-		ChartInfoId:  req.ChartInfoId,
-		CreateTime:   time.Now(),
-		ModifyTime:   time.Now(),
-	}
-	err = myChart.Insert()
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "收藏失败,Err:" + err.Error()
-		return
-	}
-
-	br.Msg = "收藏成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title 取消收藏
-// @Description 取消收藏
-// @Success 200 {object} models.BaseResponse
-// @router /collectCancel [post]
-func (this *MyChartController) CollectCancel() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyChartCollectCancelReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyChartCount(user.UserId, req.UniqueCode)
-	if err != nil {
-		br.Msg = "取消收藏失败"
-		br.ErrMsg = "获取收藏信息失败,Err:" + err.Error()
-		return
-	}
-	if count == 0 {
-		br.Msg = "该图表已取消收藏,请重新刷新页面"
-		return
-	}
-	err = models.DeleteMyChart(user.UserId, req.UniqueCode)
-	if err != nil {
-		br.Msg = "取消收藏失败"
-		br.ErrMsg = "取消收藏失败,Err:" + err.Error()
-		return
-	}
-
-	br.Msg = "取消收藏成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title List
-// @Description create users
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.BaseResponse
-// @router /list [get]
-func (this *MyChartController) List() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-
-	if pageSize <= 0 {
-		pageSize = 30
-	}
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有收藏权限"
-		return
-	}
-	total, err := models.GetMyChartListCountById(user.UserId)
-	if err != nil {
-		br.Msg = "查询收藏数量失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-
-	resp := new(response.MyChartListResp)
-	startSize := utils.StartIndex(currentIndex, pageSize)
-	items, err := models.GetMyChartListById(user.UserId, startSize, pageSize)
-	if err != nil {
-		br.Msg = "查询收藏失败"
-		br.ErrMsg = "查询收藏失败,Err:" + err.Error()
-		return
-	}
-
-	page := paging.GetPaging(currentIndex, pageSize, total)
-	resp.List = items
-	resp.Paging = page
-
-	br.Data = resp
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title Locate
-// @Description create users
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.BaseResponse
-// @router /locate [get]
-func (this *MyChartController) Locate() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-	total, err := models.GetMyChartListCountById(user.UserId)
-	if err != nil {
-		br.Msg = "查询收藏数量失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	charts := make([]*response.MyChartLocateItem, 0)
-	items, err := models.GetMyChartListById(user.UserId, 0, total)
-	if err != nil {
-		br.Msg = "查询收藏失败"
-		br.ErrMsg = "查询收藏失败,Err:" + err.Error()
-		return
-	}
-	for k, v := range items {
-		var prevChartInfoId, nextChartInfoId int
-		switch k {
-		case 0:
-			prevChartInfoId = -1
-			if k < total-1 {
-				nextChartInfoId = items[k+1].ChartInfoId
-			} else {
-				nextChartInfoId = -1
-			}
-		case total - 1:
-			nextChartInfoId = -1
-			if k > 0 {
-				prevChartInfoId = items[k-1].ChartInfoId
-			}
-		default:
-			prevChartInfoId = items[k-1].ChartInfoId
-			nextChartInfoId = items[k+1].ChartInfoId
-
-		}
-		tmpChart := &response.MyChartLocateItem{
-			MyChartId:       v.MyChartId,
-			ChartInfoId:     v.ChartInfoId,
-			ChartName:       v.ChartName,
-			UniqueCode:      v.UniqueCode,
-			PrevChartInfoId: prevChartInfoId,
-			NextChartInfoId: nextChartInfoId,
-		}
-		charts = append(charts, tmpChart)
-	}
-
-	br.Data = charts
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title Detail
-// @Description 图表详情
-// @Param   ChartInfoId   query   int  true       "图表详情id"
-// @Success 200 {object} models.BaseResponse
-// @router /detail [get]
-func (this *MyChartController) Detail() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	user := this.User
-	chartInfoId, _ := this.GetInt("ChartInfoId")
-	if chartInfoId <= 0 {
-		br.Msg = "图表id错误"
-		return
-	}
-
-	result, err := services.GetChartDetail(chartInfoId, "")
-	if err != nil {
-		br.Msg = "获取图表详情失败"
-		br.ErrMsg = "获取图表详情失败,Err:" + err.Error()
-		return
-	}
-	if result.Ret != 200 {
-		br.Msg = result.Msg
-		br.ErrMsg = result.ErrMsg
-		return
-	}
-	if result.Ret == 200 && result.Data.UniqueCode == "" {
-		// 说明后台删除了这个图表,那么尝试将收藏的图表也删除
-		models.DeleteMyChartByUserIdAndChartInfoId(user.UserId, chartInfoId)
-		br.Msg = "图表已删除或不存在,请刷新页面"
-		return
-	}
-
-	count, err := models.GetMyChartCount(user.UserId, result.Data.UniqueCode)
-	if err != nil {
-		br.Msg = "图表已删除或不存在"
-		br.ErrMsg = "获取图表详情失败,Err:" + err.Error()
-	}
-	if count > 0 {
-		result.Data.IsCollect = true
-	}
-
-	br.Data = result.Data
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title IsCollect
-// @Description create users
-// @Success 200 {object} models.BaseResponse
-// @router /isCollect [post]
-func (this *MyChartController) IsCollect() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyChartIsCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-
-	user := this.User
-	count, err := models.GetMyChartCount(user.UserId, req.UniqueCode)
-	if err != nil {
-		br.Msg = "查询收藏数量失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	resp := new(response.MyChartIsCollectResp)
-	if count > 0 {
-		resp.IsCollect = true
-	} else {
-		resp.IsCollect = false
-	}
-	br.Data = resp
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}

+ 0 - 445
controllers/my_report.go

@@ -1,445 +0,0 @@
-package controllers
-
-import (
-	"encoding/json"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/models/request"
-	"eta/eta_mini_api/models/response"
-	"eta/eta_mini_api/services"
-	"eta/eta_mini_api/utils"
-	"fmt"
-	"time"
-
-	"github.com/rdlucklib/rdluck_tools/paging"
-)
-
-type MyReportController struct {
-	BaseAuthController
-}
-
-// @Title 获取我的报告列表
-// @Description 获取我的报告列表
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.MyReportResp
-// @router /list [get]
-func (this *MyReportController) List() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		if err := recover(); err != nil {
-			fmt.Println(err)
-		}
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-
-	if pageSize <= 0 {
-		pageSize = utils.PageSize30
-	}
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "该用户没有收藏权限"
-		return
-	}
-	total, err := models.GetMyReportListCountByUserId(user.UserId)
-	if err != nil {
-		br.Msg = "获取我的报告列表失败"
-		br.ErrMsg = "获取我的报告列表失败,系统异常,Err:" + err.Error()
-		return
-	}
-	resp := new(response.MyReportListResp)
-	startSize := utils.StartIndex(currentIndex, pageSize)
-	reportList, err := models.GetMyReportListByUserId(user.UserId, startSize, pageSize)
-	if err != nil {
-		br.Msg = "获取我的报告列表失败"
-		br.ErrMsg = "获取我的报告列表失败,系统异常,Err:" + err.Error()
-		return
-	}
-	page := paging.GetPaging(currentIndex, pageSize, total)
-	resp.List = reportList
-	resp.Paging = page
-
-	br.Data = resp
-	br.Success = true
-	br.Msg = "获取我的报告列表成功"
-	br.Ret = 200
-}
-
-// @Title 收藏研报
-// @Description 收藏研报
-// @Success 200 {object} models.BaseResponse
-// @Failure 403 {object} models.BaseResponse
-// @router /collect [post]
-func (this *MyReportController) Collect() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyReportCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, req.ReportId, utils.ReportTypeEta)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	if count > 0 {
-		br.Msg = "该研报已收藏,请重新刷新页面"
-		return
-	}
-	reportResp, err := services.GetReportDetail(req.ReportId, user.UserId)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "获取研报详情失败,Err:" + err.Error()
-		return
-	}
-	if reportResp.Ret != 200 {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "获取研报详情失败,Err:" + reportResp.ErrMsg
-		return
-	}
-	if reportResp.Data.Report == nil {
-		br.Msg = "该研报已删除或不存在,请刷新页面"
-		return
-	}
-	if reportResp.Data.Status != utils.ReportPermissionStatusHas {
-		br.Msg = "用户权限不足,不能收藏"
-		return
-	}
-	report := reportResp.Data.Report
-	publishTime, err := time.Parse(utils.FormatDateTime, report.PublishTime)
-	if err != nil {
-		br.Msg = "时间格式不对"
-		return
-	}
-	myChart := &models.MyReport{
-		UserId:      user.UserId,
-		ReportId:    req.ReportId,
-		Title:       report.Title,
-		Abstract:    report.Abstract,
-		Author:      report.Author,
-		PublishTime: publishTime,
-		Stage:       report.Stage,
-		CreateTime:  time.Now(),
-		ReportType:  utils.ReportTypeEta,
-	}
-	err = myChart.Insert()
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "收藏失败,Err:" + err.Error()
-		return
-	}
-
-	br.Msg = "收藏成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title 收藏pdf研报
-// @Description 收藏pdf研报
-// @Success 200 {object} models.BaseResponse
-// @Failure 403 {object} models.BaseResponse
-// @router /pdf/collect [post]
-func (this *MyReportController) PdfCollect() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyReportPdfCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, req.ReportPdfId, utils.ReportTypePdf)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	if count > 0 {
-		br.Msg = "该研报已收藏,请重新刷新页面"
-		return
-	}
-	reportPdf, err := models.GetReportPdfById(req.ReportPdfId)
-	if err != nil {
-		if err.Error() == utils.ErrNoRow() {
-			br.Msg = "研报不存在或已删除"
-			return
-		}
-		br.Msg = "收藏失败"
-		br.ErrMsg = "获取研报详情失败,Err:" + err.Error()
-		return
-	}
-	reportClassifyId := services.GetReportPdfClassify(reportPdf)
-	chartPermissionResp, err := services.GetChartPermissionListByClassifyId(reportClassifyId, 0)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "获取研报详情失败,Err:" + err.Error()
-		return
-	}
-	if chartPermissionResp.Ret != 200 {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "获取研报详情失败,Err:" + chartPermissionResp.ErrMsg
-		return
-	}
-	var IsPublic bool
-	var permissionMap = make(map[int]struct{})
-	for _, v := range chartPermissionResp.Data {
-		if v.IsPublic == 1 {
-			IsPublic = true
-		}
-		permissionMap[v.ChartPermissionId] = struct{}{}
-	}
-	// 校验是否有收藏权限
-	var IsHas bool
-	if !IsPublic {
-		chartPermissionIds, err := models.GetUserChartPermissionIdByUserId(user.UserId)
-		if err != nil {
-			br.Msg = "收藏失败"
-			br.ErrMsg = "获取用户权限失败,Err:" + err.Error()
-			return
-		}
-		if len(chartPermissionIds) == 0 {
-			br.Msg = "用户没有权限收藏"
-			return
-		}
-		for _, v := range chartPermissionIds {
-			if _, ok := permissionMap[v]; ok {
-				IsHas = true
-				break
-			}
-		}
-		if !IsHas {
-			br.Msg = "用户没有权限收藏"
-			return
-		}
-	}
-
-	publishTime, err := time.Parse(utils.FormatDateTime, reportPdf.PublishTime)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "时间格式不对, err:" + err.Error()
-		return
-	}
-	myChart := &models.MyReport{
-		UserId:      user.UserId,
-		ReportId:    req.ReportPdfId,
-		Title:       reportPdf.Title,
-		Abstract:    reportPdf.Abstract,
-		Author:      reportPdf.Author,
-		PublishTime: publishTime,
-		Stage:       reportPdf.Stage,
-		CreateTime:  time.Now(),
-		ReportType:  utils.ReportTypePdf,
-	}
-	err = myChart.Insert()
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "收藏失败,Err:" + err.Error()
-		return
-	}
-
-	br.Msg = "收藏成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title 收藏pdf研报
-// @Description 收藏pdf研报
-// @Success 200 {object} models.BaseResponse
-// @Failure 403 {object} models.BaseResponse
-// @router /pdf/collectCancel [post]
-func (this *MyReportController) PdfCollectCancel() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyReportPdfCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, req.ReportPdfId, utils.ReportTypePdf)
-	if err != nil {
-		br.Msg = "取消收藏失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	if count == 0 {
-		br.Msg = "该研报已取消收藏,请重新刷新页面"
-		return
-	}
-	err = models.DeleteMyReportByUserIdAndReportId(user.UserId, req.ReportPdfId, utils.ReportTypePdf)
-	if err != nil {
-		br.Msg = "取消收藏失败"
-		br.ErrMsg = "取消收藏失败,Err:" + err.Error()
-		return
-	}
-
-	br.Msg = "取消收藏成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title 取消收藏
-// @Description 取消收藏
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.BaseResponse
-// @Failure 403 {object} models.BaseResponse
-// @router /collectCancel [post]
-func (this *MyReportController) CollectCancel() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyReportCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, req.ReportId, utils.ReportTypeEta)
-	if err != nil {
-		br.Msg = "取消收藏失败"
-		br.ErrMsg = "获取收藏信息失败,Err:" + err.Error()
-		return
-	}
-	if count == 0 {
-		br.Msg = "该研报已取消收藏,请重新刷新页面"
-		return
-	}
-	err = models.DeleteMyReportByUserIdAndReportId(user.UserId, req.ReportId, utils.ReportTypeEta)
-	if err != nil {
-		br.Msg = "取消收藏失败"
-		br.ErrMsg = "取消收藏失败,Err:" + err.Error()
-		return
-	}
-
-	br.Msg = "取消收藏成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title 是否收藏pdf研报
-// @Description 是否收藏pdf研报
-// @Param	request	body request.MyReportCollectReq true "type json string"
-// @Success 200 {object} models.BaseResponse
-// @router /pdf/isCollect [post]
-func (this *MyReportController) IsPdfCollect() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyReportPdfCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, req.ReportPdfId, utils.ReportTypePdf)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	resp := new(response.MyReportIsCollectResp)
-	if count > 0 {
-		resp.IsCollect = true
-	} else {
-		resp.IsCollect = false
-	}
-
-	br.Data = resp
-	br.Msg = "获取成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// @Title 是否收藏研报
-// @Description 是否收藏研报
-// @Param	request	body request.MyReportCollectReq true "type json string"
-// @Success 200 {object} models.BaseResponse
-// @router /isCollect [post]
-func (this *MyReportController) IsCollect() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.MyReportCollectReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	user := this.User
-	if user.Status != utils.UserStatusFormal {
-		br.Msg = "用户没有权限收藏"
-		return
-	}
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, req.ReportId, utils.ReportTypeEta)
-	if err != nil {
-		br.Msg = "收藏失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	resp := new(response.MyReportIsCollectResp)
-	if count > 0 {
-		resp.IsCollect = true
-	} else {
-		resp.IsCollect = false
-	}
-
-	br.Data = resp
-	br.Msg = "获取成功"
-	br.Success = true
-	br.Ret = 200
-}

+ 344 - 840
controllers/report.go

@@ -1,109 +1,31 @@
 package controllers
 
 import (
+	"encoding/json"
 	"eta/eta_mini_api/models"
+	"eta/eta_mini_api/models/request"
 	"eta/eta_mini_api/models/response"
-	"eta/eta_mini_api/services"
 	"eta/eta_mini_api/utils"
-	"sort"
+	"fmt"
+	"github.com/rdlucklib/rdluck_tools/paging"
+	"html"
 	"strconv"
+	"strings"
 	"time"
-
-	"github.com/rdlucklib/rdluck_tools/paging"
 )
 
 type ReportController struct {
 	BaseAuthController
 }
 
-type ReportNoAuthController struct {
+type ReportOpenController struct {
 	BaseCommonController
 }
 
-// @Title 研报详情
-// @Description 研报详情接口
-// @Param   ReportId   query   int  true       "报告id"
-// @Success 200 {object} models.ReportDetailResp
-// @router /detail [get]
-func (this *ReportController) Detail() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	reportId, _ := this.GetInt("ReportId")
-	if reportId <= 0 {
-		br.Msg = "报告不存在"
-		return
-	}
-	user := this.User
-	if user == nil {
-		// 如果没有用户没有绑定信息,单独处理
-		resp, er := services.GetReportDetailNoUser(reportId)
-		if er != nil {
-			br.Msg = "查询报告详情失败"
-			br.ErrMsg = "查询报告失败,系统异常,Err:" + er.Error()
-			return
-		}
-		if resp.Ret != 200 {
-			br.Msg = resp.Msg
-			br.ErrMsg = resp.ErrMsg
-			return
-		}
-		br.Msg = "查询成功"
-		br.Data = resp.Data
-		br.Success = true
-		br.Ret = 200
-		return
-	}
-	result, err := services.GetReportDetail(reportId, user.UserId)
-	if err != nil {
-		br.Msg = "查询报告详情失败"
-		br.ErrMsg = "查询报告失败,系统异常,Err:" + err.Error()
-		return
-	}
-
-	if result.Ret == 403 {
-		br.Msg = result.Msg
-		br.ErrMsg = result.ErrMsg
-		return
-	}
-	if result.Ret == 200 && result.Data.Report == nil {
-		// 后台没有这个报告,那么尝试删除我的收藏
-		models.DeleteMyReportByUserIdAndReportId(user.UserId, reportId, utils.ReportTypeEta)
-		br.Msg = "该报告已删除或不存在,请刷新页面"
-		return
-	}
-
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, reportId, utils.ReportTypeEta)
-	if err != nil {
-		br.Msg = "查询收藏数量失败"
-		br.ErrMsg = "查询收藏数量失败,Err:" + err.Error()
-		return
-	}
-	if count > 0 {
-		result.Data.IsCollect = true
-	} else {
-		result.Data.IsCollect = false
-	}
-	if user.UserId != 0 {
-		result.Data.IsSignIn = true
-	}
-
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-	br.Data = result.Data
-}
-
+// List
 // @Title 研报列表
 // @Description 研报列表
-// @Param   ChartPermissionId   query   int  true       "品种ID"
-// @Param   Level   query   int  true       "品种层级"
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Param   RangeType   query   string  true       "范围类型,1-一天内,2-一周内,3-半年内"
-// @Param   ClassifyId   query   int  true       "分类id"
+// @Param	request	body request.ReportListForm true "type json string"
 // @Success 200 {object} response.ReportList
 // @router /list [get]
 func (this *ReportController) List() {
@@ -112,851 +34,433 @@ func (this *ReportController) List() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
-
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	chartPermissionId, _ := this.GetInt("ChartPermissionId")
-	level, _ := this.GetInt("Level")
-	rangeType, _ := this.GetInt("RangeType")
-	classifyId, _ := this.GetInt("ClassifyId")
-	reports, err := services.GetReportList(chartPermissionId, level, rangeType, classifyId, currentIndex, pageSize)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-	if reports.Ret != 200 {
-		br.Msg = reports.Msg
-		br.ErrMsg = reports.ErrMsg
-		return
-	}
-
-	br.Data = reports.Data
-	br.Msg = "查询成功"
-	br.Ret = 200
-	br.Success = true
-}
-
-// @Title pdf研报列表
-// @Description pdf研报列表
-// @Param   ChartPermissionId   query   int  true       "品种ID"
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Param   RangeType   query   int  true       "范围类型,1-一天内,2-一周内,3-半年内"
-// @Param   ClassifyId   query   int  true       "二级分类id"
-// @Success 200 {object} response.ReportList
-// @router /pdf/list [get]
-func (this *ReportController) PdfList() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	chartPermissionId, _ := this.GetInt("ChartPermissionId")
-	classifyId, _ := this.GetInt("ClassifyId")
-	rangeType, _ := this.GetInt("RangeType")
-
-	if pageSize <= 0 {
-		pageSize = utils.PageSize20
-	}
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	if chartPermissionId <= 0 {
-		br.Msg = "请输入品种ID"
-		return
-	}
-	var condition string
-	switch rangeType {
-	case 1:
-		condition += ` AND DATE(publish_time)=DATE(NOW()) `
-	case 2:
-		condition += ` AND DATE(publish_time) BETWEEN DATE_SUB(NOW(),INTERVAL 1 WEEK) AND NOW() `
-	case 3:
-		condition += ` AND DATE(publish_time) BETWEEN DATE_SUB(NOW(),INTERVAL 6 MONTH) AND NOW() `
-	}
-
-	startSize := utils.StartIndex(currentIndex, pageSize)
-	var leafClassifyIds []int
-	var leafClassifyIdMap map[int]struct{}
-	var classifyMap map[int]*models.ClassifyView
-	classifyResp, err := services.GetAllClassify()
-	if err != nil {
-		br.Msg = "获取数据失败"
-		br.ErrMsg = "获取数据失败,Err:" + err.Error()
-		return
-	}
-	if classifyResp.Ret != 200 {
-		br.Msg = classifyResp.Msg
-		br.ErrMsg = classifyResp.ErrMsg
-		return
-	}
-	classifyList := classifyResp.Data
-	classifyMap = make(map[int]*models.ClassifyView)
-	isHas := false
-	for _, v := range classifyList {
-		if v.Id == classifyId && classifyId != 0 {
-			isHas = true
-		}
-		classifyMap[v.Id] = v
-	}
-	if !isHas && classifyId != 0 {
-		br.Msg = "分类不存在"
-		return
-	}
-	if classifyId != 0 {
-		leafClassifyIds = getLeafClassifyIds(classifyMap, classifyId)
-		leafClassifyIdMap = make(map[int]struct{})
-		for _, v := range leafClassifyIds {
-			leafClassifyIdMap[v] = struct{}{}
-		}
-	}
-	var permissionClassifyList []int
-	if chartPermissionId != 0 {
-		resp, err := services.GetClassifyListByChartPermission(chartPermissionId)
-		if err != nil {
-			br.Msg = "获取分类失败"
-			br.ErrMsg = "获取分类失败,系统异常,Err:" + err.Error()
-			return
-		}
-		if resp.Ret != 200 {
-			br.Msg = resp.Msg
-			br.ErrMsg = resp.ErrMsg
-			return
-		}
-		classifyList := resp.Data
-		if len(classifyList) == 0 {
-			resp := new(response.ReportPdfResp)
-			br.Msg = "查询成功"
-			br.Ret = 200
-			br.Success = true
-			br.Data = resp
+	params := new(request.ReportListForm)
+	if e := this.ParseForm(params); e != nil {
+		br.Msg = "参数解析异常"
+		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
+		return
+	}
+	var (
+		reportCond, outsideCond string
+		reportPars, outsidePars []interface{}
+	)
+	// 仅取常规和智能布局的报告
+	reportCond += ` AND r.report_layout IN (1,2)`
+
+	params.Keywords = strings.TrimSpace(params.Keywords)
+	if params.Keywords != "" {
+		kw := fmt.Sprint("%", params.Keywords, "%")
+		reportCond += ` AND r.title LIKE ?`
+		reportPars = append(reportPars, kw)
+		outsideCond += ` AND o.title LIKE ?`
+		outsidePars = append(outsidePars, kw)
+	}
+
+	// 分类名称map
+	classifyOb := new(models.MiniClassify)
+	classifies, e := classifyOb.GetItemsByCondition(``, make([]interface{}, 0), []string{}, "")
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = fmt.Sprintf("获取分类失败, %v", e)
+		return
+	}
+	classifyMapping := make(map[int]*models.MiniClassify)
+	for _, v := range classifies {
+		classifyMapping[v.Id] = v
+	}
+	if params.ClassifyId > 0 {
+		classify := classifyMapping[params.ClassifyId]
+		if classify == nil || (classify != nil && classify.Enabled != 1) {
+			br.Msg = "分类不存在,请刷新页面"
 			return
 		}
-		for _, item := range classifyList {
-			permissionClassifyList = append(permissionClassifyList, item.Id)
-		}
-	}
-	queryClassifyIds := make([]int, 0)
-	if classifyId > 0 {
-		for _, v := range permissionClassifyList {
-			if _, ok := leafClassifyIdMap[v]; ok {
-				queryClassifyIds = append(queryClassifyIds, v)
-			}
-		}
-	} else {
-		queryClassifyIds = permissionClassifyList
-	}
-	firstClassifyIds := make([]int, 0)
-	secondClassifyIds := make([]int, 0)
-	thirdClassifyIds := make([]int, 0)
-	for _, v := range queryClassifyIds {
-		classify := classifyMap[v]
-		if classify.HasChild == 1 {
-			continue
-		}
-		switch classifyMap[v].Level {
+		switch classify.Level {
 		case 1:
-			firstClassifyIds = append(firstClassifyIds, v)
+			reportCond += ` AND r.classify_id_first = ?`
 		case 2:
-			secondClassifyIds = append(secondClassifyIds, v)
+			reportCond += ` AND r.classify_id_second = ?`
 		case 3:
-			thirdClassifyIds = append(thirdClassifyIds, v)
+			reportCond += ` AND r.classify_id_third = ?`
+		default:
+			br.Msg = "分类异常"
+			return
 		}
-	}
-
-	total, err := models.GetReportPdfCountByCondition(firstClassifyIds, secondClassifyIds, thirdClassifyIds, condition)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表统计查询失败,系统异常,Err:" + err.Error()
-		return
-
-	}
-	reportPdfList, err := models.GetReportPdfListByCondition(firstClassifyIds, secondClassifyIds, thirdClassifyIds, condition, startSize, pageSize)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-	page := paging.GetPaging(currentIndex, pageSize, total)
-
-	resp := new(response.ReportPdfResp)
-	resp.List = reportPdfList
-	resp.Paging = page
+		reportPars = append(reportPars, params.ClassifyId)
 
-	br.Msg = "查询成功"
-	br.Ret = 200
-	br.Success = true
-	br.Data = resp
-}
-
-func getLeafClassifyIds(classifyMap map[int]*models.ClassifyView, keyId int) []int {
-	var leafClassifyIds []int
-	curClassify := classifyMap[keyId]
-	if curClassify.HasChild == 0 {
-		leafClassifyIds = append(leafClassifyIds, curClassify.Id)
-		return leafClassifyIds
-	}
-	for _, v := range classifyMap {
-		if v.ParentId == curClassify.Id {
-			if v.HasChild == 0 {
-				leafClassifyIds = append(leafClassifyIds, v.Id)
-			} else {
-				leafClassifyIds = append(leafClassifyIds, getLeafClassifyIds(classifyMap, v.Id)...)
-			}
+		// 获取子分类IDs
+		childIds, e := classifyOb.GetChildClassifyIdsByParentId(params.ClassifyId)
+		if e != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = fmt.Sprintf("获取子分类失败, %v", e)
+			return
 		}
-	}
-	return leafClassifyIds
-}
-
-// @Title pdf研报详情
-// @Description pdf研报详情
-// @Param   ReportPdfId   query   int  true       "品种ID"
-// @Success 200 {object} response.ReportList
-// @router /pdf/detail [get]
-func (this *ReportController) PdfDetail() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-
-	// 有效期是否到期
-	var vailStatus int
-	if user.Status == utils.UserStatusFormal {
-		if user.ValidEndTime.After(time.Now()) && user.ValidStartTime.Before(time.Now()) {
-			vailStatus = 2
+		if len(childIds) > 0 {
+			outsideCond += fmt.Sprintf(` AND o.classify_id IN (%s)`, utils.GetOrmInReplace(len(childIds)))
+			outsidePars = append(outsidePars, childIds)
 		} else {
-			// 不在有效期时间则设置为过期, 将用户状态禁用
-			vailStatus = 1
-			user.Status = utils.UserStatusNo
+			outsideCond += ` AND o.classify_id = ?`
+			outsidePars = append(outsidePars, params.ClassifyId)
 		}
 	}
-	reportPdfId, _ := this.GetInt("ReportPdfId")
+	resp := new(response.ReportList)
 
-	if reportPdfId <= 0 {
-		br.Msg = "研报不存在或已删除"
-		return
+	// 分页
+	var startSize int
+	if params.PageSize <= 0 {
+		params.PageSize = utils.PageSize20
 	}
-
-	reportPdf, err := models.GetReportPdfById(reportPdfId)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		br.Msg = "研报不存在或已删除"
-		br.ErrMsg = "研报不存在或已删除,系统异常,Err:" + err.Error()
-		return
+	if params.CurrentIndex <= 0 {
+		params.CurrentIndex = 1
 	}
-	if reportPdf == nil {
-		// 尝试删除收藏列表的记录
-		models.DeleteMyReportByUserIdAndReportId(user.UserId, reportPdfId, utils.ReportTypePdf)
-		br.Msg = "研报不存在或已删除"
-		return
-	}
-	reportClassifyId := services.GetReportPdfClassify(reportPdf)
+	startSize = utils.StartIndex(params.CurrentIndex, params.PageSize)
 
-	permissionResp, err := services.GetChartPermissionListByClassifyId(reportClassifyId, 0)
-	if err != nil {
-		br.Msg = "研报不存在或已删除"
-		br.ErrMsg = "获取权限失败,系统异常,Err:" + err.Error()
+	total, e := models.GetReportAndOutsideReportCount(reportCond, outsideCond, reportPars, outsidePars)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = fmt.Sprintf("获取报告总数失败, %v", e)
 		return
 	}
-	if permissionResp.Ret != 200 {
-		br.Msg = permissionResp.Msg
-		br.ErrMsg = permissionResp.ErrMsg
-		return
-	}
-	var IsHas bool
-	var IsPublic bool
-	permissionMap := make(map[int]struct{})
-	for _, v := range permissionResp.Data {
-		if v.IsPublic == 1 {
-			IsPublic = true
-		}
-		permissionMap[v.ChartPermissionId] = struct{}{}
-	}
-	resp := new(response.ReportPdfDetailResp)
-	if !IsPublic {
-		// 如果是私有报告,用户权限过期直接返回有效期已过
-		if vailStatus == 1 || user.Status == utils.UserStatusNo {
-			resp.Report = reportPdf
-			resp.Status = utils.ReportPermissionStatusExpired
-			br.Ret = 200
-			br.Data = resp
-			br.Msg = "用户权限不足"
-			return
-		}
-		// 如果被禁用或是潜在用户,直接返回无阅读报告权限
-		if user.Status == utils.UserStatusPotential {
-			resp.Report = reportPdf
-			resp.Status = utils.ReportPermissionStatusNo
-			br.Ret = 200
-			br.Data = resp
-			br.Msg = "用户权限不足"
-			return
-		}
-		// 正式用户,判断是否有权限查看
-		userChartPermissionIds, err := models.GetUserChartPermissionIdByUserId(user.UserId)
-		if err != nil {
-			br.Msg = "获取用户权限失败"
-			br.ErrMsg = "获取用户权限失败,Err:" + err.Error()
-			return
-		}
-		if len(userChartPermissionIds) == 0 {
-			resp.Report = reportPdf
-			resp.Status = utils.ReportPermissionStatusNoPermission
-			br.Ret = 200
-			br.Data = resp
-			br.Msg = "用户权限不足"
-			return
-		}
-		for _, v := range userChartPermissionIds {
-			if _, ok := permissionMap[v]; ok {
-				IsHas = true
-				break
+	page := paging.GetPaging(params.CurrentIndex, params.PageSize, total)
+	resp.Paging = page
+
+	list, e := models.GetReportAndOutsideReportByCondition(reportCond, outsideCond, reportPars, outsidePars, startSize, params.PageSize)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = fmt.Sprintf("获取报告列表失败, %v", e)
+		return
+	}
+	for _, v := range list {
+		t := new(models.UnionReportItem)
+		t.Id = v.Id
+		t.Title = v.Title
+		t.Abstract = v.Abstract
+		t.PublishTime = utils.TimeTransferString(utils.FormatDateTime, v.PublishTime)
+		t.ReportSource = v.ReportSource
+		t.ReportFile = v.ReportFile
+		t.Author = v.Author
+		// 报告分类名称
+		if v.ReportSource == utils.ReportSourceDefault {
+			if v.ClassifyIdThird > 0 {
+				t.ClassifyId = v.ClassifyIdThird
+			} else if v.ClassifyIdSecond > 0 {
+				t.ClassifyId = v.ClassifyIdSecond
+			} else {
+				t.ClassifyId = v.ClassifyIdFirst
 			}
 		}
-		if !IsHas {
-			resp.Report = reportPdf
-			resp.Status = utils.ReportPermissionStatusNoPermission
-			br.Ret = 200
-			br.Data = resp
-			br.Msg = "用户权限不足"
-			return
+		if v.ReportSource == utils.ReportSourceOutside {
+			t.ClassifyId = v.ClassifyIdThird
 		}
-	} else {
-		reportPdf.IsPublic = IsPublic
-	}
-
-	count, err := models.GetMyReportCountByUserIdAndReportId(user.UserId, reportPdf.ReportPdfId, utils.ReportTypePdf)
-	if err != nil {
-		br.Msg = "获取研报详情失败"
-		br.ErrMsg = "获取用户收藏记录失败,Err:" + err.Error()
-		return
-	}
-	if count > 0 {
-		reportPdf.IsCollect = true
-	} else {
-		reportPdf.IsCollect = false
+		cs := classifyMapping[t.ClassifyId]
+		if cs != nil {
+			t.ClassifyName = cs.ClassifyName
+		}
+		resp.List = append(resp.List, t)
 	}
 
-	resp.Report = reportPdf
-	resp.Status = utils.ReportPermissionStatusHas
-
-	br.Msg = "查询成功"
+	br.Data = resp
 	br.Ret = 200
+	br.Msg = "获取成功"
 	br.Success = true
-	br.Data = resp
 }
 
-// @Title 今日研报列表
-// @Description 今日研报列表
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// Detail
+// @Title 研报详情H5
+// @Description 研报详情H5
+// @Param   ReportId   query   int  true       "报告ID"
 // @Success 200 {object} models.ReportDetailResp
-// @router /daily/list [get]
-func (this *ReportController) DailyList() {
+// @router /detail [get]
+func (this *ReportOpenController) Detail() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
-	// 暂不使用分页
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	if pageSize <= 0 {
-		pageSize = utils.PageSize20
-	}
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	resp, err := services.GetReportDailyList()
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-	if resp.Ret != 200 {
-		br.Msg = resp.Msg
-		br.ErrMsg = resp.ErrMsg
+	reportId, _ := this.GetInt("ReportId")
+	if reportId <= 0 {
+		br.Msg = "参数有误"
 		return
 	}
-	reportList := resp.Data
-	for _, v := range reportList.List {
-		v.ReportType = utils.ReportTypeEta
-	}
 
-	reportPdfList, err := models.GetReportPdfDailyList()
+	report, err := models.GetReportById(reportId)
 	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
+		if err.Error() == utils.ErrNoRow() {
+			br.Ret = 200
+			br.Data = new(response.ReportDetailResp)
+			br.Success = true
+			br.Msg = "该报告已删除或不存在"
+			return
+		}
+		br.Msg = "该报告已删除"
+		br.ErrMsg = "获取报告详情失败,Err:" + err.Error()
 		return
 	}
-	var classifyIds []int
-	for _, v := range reportPdfList {
-		var reportClassifyId int
-		if v.ClassifyIdFirst != 0 {
-			reportClassifyId = v.ClassifyIdFirst
+	if report.HeadResourceId > 0 || report.EndResourceId > 0 {
+		headImg, err := models.GetSmartReportResourceById(report.HeadResourceId)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			utils.FileLog.Warn("版头数据获取失败,Err:" + err.Error())
+		}
+		endImg, err := models.GetSmartReportResourceById(report.EndResourceId)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			utils.FileLog.Warn("版尾数据获取失败,Err:" + err.Error())
 		}
-		if v.ClassifyIdSecond != 0 {
-			reportClassifyId = v.ClassifyIdSecond
+		if headImg != nil {
+			report.HeadResource = headImg
 		}
-		if v.ClassifyIdThird != 0 {
-			reportClassifyId = v.ClassifyIdThird
+		if endImg != nil {
+			report.EndResource = endImg
 		}
-		classifyIds = append(classifyIds, reportClassifyId)
 	}
 
-	if len(classifyIds) > 0 {
-		classifyResp, err := services.GetFirstChartPermission(classifyIds)
+	if report.HasChapter == 1 {
+		chapterList, err := models.GetReportChapterList(report.Id)
 		if err != nil {
-			br.Msg = "研报列表查询失败"
-			br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
+			br.Msg = "该报告已删除"
+			br.ErrMsg = "获取章节列表失败,Err:" + err.Error()
 			return
 		}
-		if classifyResp.Ret != 200 {
-			br.Msg = classifyResp.Msg
-			br.ErrMsg = classifyResp.ErrMsg
-			return
-		}
-		classifyPermissionMap := make(map[int][]string)
-		for _, v := range classifyResp.Data {
-			classifyPermissionMap[v.ClassifyId] = v.PermissionNames
-		}
-		for _, v := range reportPdfList {
-			var reportClassifyId int
-			if v.ClassifyIdFirst != 0 {
-				reportClassifyId = v.ClassifyIdFirst
-			}
-			if v.ClassifyIdSecond != 0 {
-				reportClassifyId = v.ClassifyIdSecond
-			}
-			if v.ClassifyIdThird != 0 {
-				reportClassifyId = v.ClassifyIdThird
-			}
-			// 过滤没有绑定品种的研报
-			if classifyPermissionMap[reportClassifyId] == nil {
-				continue
-			}
-			reportList.List = append(reportList.List, &models.ReportView{
-				Id:                 v.ReportPdfId,
-				ClassifyIdFirst:    v.ClassifyIdFirst,
-				ClassifyNameFirst:  v.ClassifyNameFirst,
-				ClassifyIdSecond:   v.ClassifyIdSecond,
-				ClassifyNameSecond: v.ClassifyNameSecond,
-				ClassifyIdThird:    v.ClassifyIdThird,
-				ClassifyNameThird:  v.ClassifyNameThird,
-				PermissionNames:    classifyPermissionMap[reportClassifyId],
-				PdfUrl:             v.PdfUrl,
-				Title:              v.Title,
-				Abstract:           v.Abstract,
-				Stage:              v.Stage,
-				Author:             v.Author,
-				ReportType:         utils.ReportTypePdf,
-				PublishTime:        v.PublishTime.Format(utils.FormatDateTime),
-				ModifyTime:         v.ModifyTime,
-			})
+		for _, v := range chapterList {
+			v.Content = html.UnescapeString(v.Content)
 		}
+		report.ChapterContent = chapterList
 	}
-
-	sort.Sort(models.ByPublishTimeReportView(reportList.List))
-
-	br.Data = reportList
-	br.Msg = "查询成功"
-	br.Ret = 200
-	br.Success = true
-}
-
-// @Title 最新研报列表
-// @Description 最新研报列表
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.ReportDetailResp
-// @router /recent/list [get]
-func (this *ReportController) RecentList() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	// 暂不使用分页
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	if pageSize <= 0 {
-		pageSize = 3
-	}
-
-	resp, err := services.GetReportRecentList(currentIndex, pageSize)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-	// 查询已发布的pdf
-	reportPdfList, err := models.GetRecentReportPdfList(0, 3)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-
-	reportList := resp.Data
-	for _, v := range reportList.List {
-		v.ReportType = utils.ReportTypeEta
-	}
-	var classifyIds []int
-	for _, v := range reportPdfList {
-		var reportClassifyId int
-		if v.ClassifyIdFirst != 0 {
-			reportClassifyId = v.ClassifyIdFirst
-		}
-		if v.ClassifyIdSecond != 0 {
-			reportClassifyId = v.ClassifyIdSecond
-		}
-		if v.ClassifyIdThird != 0 {
-			reportClassifyId = v.ClassifyIdThird
-		}
-		classifyIds = append(classifyIds, reportClassifyId)
-	}
-
-	classifyResp, err := services.GetFirstChartPermission(classifyIds)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
+	report.ContentSub = html.UnescapeString(report.ContentSub)
+	report.Content = html.UnescapeString(report.Content)
+	if report == nil {
+		br.Msg = "报告不存在"
 		return
 	}
-	if classifyResp.Ret != 200 {
-		br.Msg = classifyResp.Msg
-		br.ErrMsg = classifyResp.ErrMsg
-	}
-	classifyPermissionMap := make(map[int][]string)
-	for _, v := range classifyResp.Data {
-		classifyPermissionMap[v.ClassifyId] = v.PermissionNames
-	}
-	for _, v := range reportPdfList {
-		var reportClassifyId int
-		if v.ClassifyIdFirst != 0 {
-			reportClassifyId = v.ClassifyIdFirst
-		}
-		if v.ClassifyIdSecond != 0 {
-			reportClassifyId = v.ClassifyIdSecond
-		}
-		if v.ClassifyIdThird != 0 {
-			reportClassifyId = v.ClassifyIdThird
-		}
-		// 过滤没有绑定品种的研报
-		if classifyPermissionMap[reportClassifyId] == nil {
-			continue
-		}
-		reportList.List = append(reportList.List, &models.ReportView{
-			Id:                 v.ReportPdfId,
-			ClassifyIdFirst:    v.ClassifyIdFirst,
-			ClassifyNameFirst:  v.ClassifyNameFirst,
-			ClassifyIdSecond:   v.ClassifyIdSecond,
-			ClassifyNameSecond: v.ClassifyNameSecond,
-			ClassifyIdThird:    v.ClassifyIdThird,
-			ClassifyNameThird:  v.ClassifyNameThird,
-			PermissionNames:    classifyPermissionMap[reportClassifyId],
-			PdfUrl:             v.PdfUrl,
-			Title:              v.Title,
-			Abstract:           v.Abstract,
-			Stage:              v.Stage,
-			Author:             v.Author,
-			ReportType:         utils.ReportTypePdf,
-			PublishTime:        v.PublishTime.Format(utils.FormatDateTime),
-			ModifyTime:         v.ModifyTime,
-		})
-	}
-	sort.Sort(models.ByPublishTimeReportView(reportList.List))
-	endIdx := len(reportList.List)
-	if endIdx > 3 {
-		endIdx = 3
-	}
-	reportList.List = reportList.List[:endIdx]
-
-	br.Data = reportList
-	br.Msg = "查询成功"
-	br.Ret = 200
-	br.Success = true
-}
-
-// @Title 研报列表
-// @Description 研报列表
-// @Param   ReportId   query   int  true       "报告id"
-// @Param   chartPermissionId   query   int  true       "品种ID"
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.ReportDetailResp
-// @router /search [get]
-func (this *ReportController) Search() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	keyWord := this.GetString("KeyWord")
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	if pageSize <= 0 {
-		pageSize = utils.PageSize30
-	}
 
-	if keyWord == "" {
-		br.Msg = "请输入关键字"
-		return
-	}
+	resp := new(response.ReportDetailResp)
+	resp.Report = report
 
-	reports, err := services.SearchReport(keyWord, currentIndex, pageSize)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-	if reports.Ret != 200 {
-		br.Msg = reports.Msg
-		br.ErrMsg = reports.ErrMsg
-		return
-	}
-	resp := new(response.ReportSearchViewResp)
-	list := make([]*response.ReportSearchListView, 0)
-	for _, v := range reports.Data.List {
-		tmpReport := &response.ReportSearchListView{
-			ReportId:            v.ReportId,
-			ReportChapterId:     v.ReportChapterId,
-			ClassifyIdFirst:     v.ClassifyIdFirst,
-			ClassifyNameFirst:   v.ClassifyNameFirst,
-			ClassifyIdSecond:    v.ClassifyIdSecond,
-			ClassifyNameSecond:  v.ClassifyNameSecond,
-			ClassifyIdThird:     v.ClassifyIdThird,
-			ClassifyNameThird:   v.ClassifyNameThird,
-			ReportChapterTypeId: v.ReportChapterTypeId,
-			PublishTime:         v.PublishTime.Format(utils.FormatDate),
-			Title:               v.Title,
-			ContentSub:          v.ContentSub,
-			Abstract:            v.Abstract,
-			Stage:               v.Stage,
-			Author:              v.Author,
-			PdfUrl:              v.PdfUrl,
-			ReportType:          v.ReportType,
-		}
-		if v.PublishTime.IsZero() {
-			tmpReport.PublishTime = ""
-		}
-		list = append(list, tmpReport)
-	}
-	resp.List = list
-	resp.Paging = reports.Data.Paging
 	br.Data = resp
-	br.Msg = "查询成功"
 	br.Ret = 200
+	br.Msg = "获取成功"
 	br.Success = true
 }
 
-// @Title 研报列表
-// @Description 研报列表
-// @Param   ChartPermissionId   query   int  true       "品种ID"
-// @Param   Level   query   int  true       "品种层级"
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Param   RangeType   query   string  true       "范围类型,1-一天内,2-一周内,3-半年内"
-// @Param   ReportType   query   string  true       "报告类型,1-eta报告,2-pdf报告"
-// @Param   ClassifyId   query   int  true       "分类id"
-// @Success 200 {object} response.ReportList
-// @router /list [get]
-func (this *ReportNoAuthController) List() {
+// OutsideDetail
+// @Title 研报详情H5-文档管理库
+// @Description 研报详情H5-文档管理库
+// @Param   ReportId   query   int  true       "报告ID"
+// @Success 200 {object} models.OutsideReportItem
+// @router /outside_detail [get]
+func (this *ReportOpenController) OutsideDetail() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
-
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	chartPermissionId, _ := this.GetInt("ChartPermissionId")
-	level, _ := this.GetInt("Level")
-	rangeType, _ := this.GetInt("RangeType")
-	reportType, _ := this.GetInt("ReportType")
-	classifyId, _ := this.GetInt("ClassifyId")
-	switch rangeType {
-	case 1, 2, 3:
-	default:
-		br.Msg = "查询失败"
-		return
-	}
-	switch reportType {
-	case utils.ReportTypeEta, utils.ReportTypePdf:
-	default:
-		br.Msg = "报告不存在"
-		return
-	}
-	reports, err := services.GetNoAuthReportList(reportType, chartPermissionId, level, rangeType, classifyId, currentIndex, pageSize)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
+	reportId, _ := this.GetInt("ReportId")
+	if reportId <= 0 {
+		br.Msg = "参数有误"
 		return
 	}
-	if reports.Ret != 200 {
-		br.Msg = reports.Msg
-		br.ErrMsg = reports.ErrMsg
+	outsideReport, e := models.GetOutsideReportById(reportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在,请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = fmt.Sprintf("获取外部报告失败, %v", e)
 		return
 	}
 
-	br.Data = reports.Data
-	br.Msg = "查询成功"
+	br.Data = outsideReport.Format2Item()
 	br.Ret = 200
+	br.Msg = "获取成功"
 	br.Success = true
 }
 
-// @Title 研报详情
-// @Description 研报详情接口
-// @Param   ReportId   query   int  true       "报告id"
-// @Param   ReportType   query   int  true       "报告类型:1-eta,2-pdf"
-// @Success 200 {object} models.ReportDetailResp
-// @router /detail [get]
-func (this *ReportNoAuthController) Detail() {
+// ReadRecord
+// @Title 新增报告阅读记录
+// @Description 新增报告阅读记录
+// @Param	request	body request.ReportReadRecordReq true "type json string"
+// @Success 200 操作成功
+// @router /read_record [post]
+func (this *ReportController) ReadRecord() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
-	reportId, _ := this.GetInt("ReportId")
-	reportType, _ := this.GetInt("ReportType")
-	if reportId <= 0 {
-		br.Msg = "报告不存在"
-		return
-	}
-	switch reportType {
-	case utils.ReportTypeEta, utils.ReportTypePdf:
-	default:
-		br.Msg = "报告不存在"
-		return
-	}
-
-	reportPush, err := models.GetReportPushStatusByReportId(reportId, reportType)
-	if err != nil {
-		br.Msg = "查询报告失败"
-		br.ErrMsg = "查询报告推送状态失败,系统异常,Err:" + err.Error()
-		return
-	}
-	if reportPush.State != utils.ReportStatePush {
-		br.Msg = "报告未推送或已删除,请刷新重试"
-		return
-	}
-	switch reportType {
-	case utils.ReportTypeEta:
-		result, err := services.GetNoAuthReportDetail(reportId)
-		if err != nil {
-			br.Msg = "查询报告详情失败"
-			br.ErrMsg = "查询报告失败,系统异常,Err:" + err.Error()
+	users := this.User
+	if users == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,用户信息为空"
+		br.Ret = 403
+		return
+	}
+	var req request.ReportReadRecordReq
+	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
+		br.Msg = "参数解析异常"
+		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
+		return
+	}
+	if req.ReportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = fmt.Sprintf("参数有误, ReportId: %d", req.ReportId)
+		return
+	}
+	if req.ReportSource != utils.ReportSourceDefault && req.ReportSource != utils.ReportSourceOutside {
+		br.Msg = "参数有误"
+		br.ErrMsg = fmt.Sprintf("参数有误, ReportSource: %d", req.ReportSource)
+		return
+	}
+
+	// 获取报告分类信息
+	var (
+		title              string
+		classifyIdFirst    int
+		classifyIdSecond   int
+		classifyIdThird    int
+		classifyNameFirst  string
+		classifyNameSecond string
+		classifyNameThird  string
+	)
+	if req.ReportSource == utils.ReportSourceDefault {
+		reportOb := new(models.Report)
+		report, e := reportOb.GetItemById(req.ReportId)
+		if e != nil {
+			if e.Error() == utils.ErrNoRow() {
+				br.Msg = "报告不存在,请刷新页面"
+				return
+			}
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("获取报告失败, %v", e)
 			return
 		}
-		if result.Ret != 200 {
-			br.Msg = result.Msg
-			br.ErrMsg = result.ErrMsg
+		title = report.Title
+		classifyIdFirst = report.ClassifyIdFirst
+		classifyIdSecond = report.ClassifyIdSecond
+		classifyIdThird = report.ClassifyIdThird
+		classifyNameFirst = report.ClassifyNameFirst
+		classifyNameSecond = report.ClassifyNameSecond
+		classifyNameThird = report.ClassifyNameThird
+	}
+	if req.ReportSource == utils.ReportSourceOutside {
+		outsideReport, e := models.GetOutsideReportById(req.ReportId)
+		if e != nil {
+			if e.Error() == utils.ErrNoRow() {
+				br.Msg = "报告不存在,请刷新页面"
+				return
+			}
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("获取外部报告失败, %v", e)
 			return
 		}
+		title = outsideReport.Title
 
-		if result.Ret == 200 && result.Data.Report == nil {
-			// 报告不存在, 就尝试删除推送的记录
-			models.DeleteReportPushStatusByReportId(reportId, utils.ReportTypeEta)
-			br.Msg = "报告已删除或未发布,请刷新重试"
+		// 根据分类层级取出所有分类ID和名称
+		classifyOb := new(models.MiniClassify)
+		classifies, e := classifyOb.GetItemsByCondition(``, make([]interface{}, 0), []string{}, "")
+		if e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("获取报告分类失败, %v", e)
 			return
 		}
-
-		br.Msg = "查询成功"
-		br.Success = true
-		br.Ret = 200
-		br.Data = result.Data
-		return
-	case utils.ReportTypePdf:
-		reportPdf, err := models.GetReportPdfById(reportId)
-		if err != nil {
-			br.Msg = "查询报告详情失败"
-			br.ErrMsg = "查询报告失败,系统异常,Err:" + err.Error()
+		classifyMapping := make(map[int]*models.MiniClassify)
+		for _, v := range classifies {
+			classifyMapping[v.Id] = v
+		}
+		thisClassify := classifyMapping[outsideReport.ClassifyId]
+		if thisClassify == nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("报告分类不存在, ClassifyId: %d", outsideReport.ClassifyId)
 			return
 		}
-
-		br.Msg = "查询成功"
-		br.Success = true
-		br.Ret = 200
-		br.Data = reportPdf
-		return
-	default:
-		br.Msg = "报告不存在"
-		return
-	}
-
-}
-
-// @Title 研报搜索
-// @Description 研报搜索
-// @Param   KeyWord   query   string  true       "每页数据条数"
-// @Param   PageSize   query   int  true       "每页数据条数"
-// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
-// @Success 200 {object} models.ReportDetailResp
-// @router /search [get]
-func (this *ReportNoAuthController) Search() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	keyWord := this.GetString("KeyWord")
-	pageSize, _ := this.GetInt("PageSize")
-	currentIndex, _ := this.GetInt("CurrentIndex")
-	if pageSize <= 0 {
-		pageSize = utils.PageSize30
-	}
-	if currentIndex <= 0 {
-		currentIndex = 1
-	}
-	startSize := utils.StartIndex(currentIndex, pageSize)
-
-	if keyWord == "" {
-		br.Msg = "请输入关键字"
-		return
+		levelArr := strings.Split(thisClassify.LevelPath, ",")
+		if len(levelArr) <= 0 {
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("报告分类层级异常, ClassifyId: %d, LevelPath: %s", thisClassify.Id, thisClassify.LevelPath)
+			return
+		}
+		if len(levelArr) > 0 {
+			classifyIdFirst, _ = strconv.Atoi(levelArr[0])
+			firstClassify := classifyMapping[classifyIdFirst]
+			if firstClassify != nil {
+				classifyNameFirst = firstClassify.ClassifyName
+			}
+			// 测试环境统一放在了一个一级分类下
+			if classifyNameFirst == "" && utils.RunMode == "debug" {
+				classifyNameFirst = "金瑞小程序分类(勿删)"
+			}
+		}
+		if len(levelArr) > 1 {
+			classifyIdSecond, _ = strconv.Atoi(levelArr[1])
+			secondClassify := classifyMapping[classifyIdSecond]
+			if secondClassify != nil {
+				classifyNameSecond = secondClassify.ClassifyName
+			}
+		}
+		if len(levelArr) > 2 {
+			classifyIdThird, _ = strconv.Atoi(levelArr[2])
+			thirdClassify := classifyMapping[classifyIdThird]
+			if thirdClassify != nil {
+				classifyNameThird = thirdClassify.ClassifyName
+			}
+		}
 	}
 
-	reports, total, err := services.SearchReportPush(keyWord, startSize, pageSize)
-	if err != nil {
-		br.Msg = "研报列表查询失败"
-		br.ErrMsg = "研报列表查询失败,系统异常,Err:" + err.Error()
-		return
-	}
-	resp := new(response.ReportSearchViewResp)
-	list := make([]*response.ReportSearchListView, 0)
-	for _, v := range reports {
-		tmpReport := &response.ReportSearchListView{
-			ReportId:           v.ReportId,
-			ClassifyIdFirst:    v.ClassifyIdFirst,
-			ClassifyNameFirst:  v.ClassifyNameFirst,
-			ClassifyIdSecond:   v.ClassifyIdSecond,
-			ClassifyNameSecond: v.ClassifyNameSecond,
-			ClassifyIdThird:    v.ClassifyIdThird,
-			ClassifyNameThird:  v.ClassifyNameThird,
-			PublishTime:        v.PublishTime.Format(utils.FormatDate),
-			Title:              v.Title,
-			Abstract:           v.Abstract,
-			Stage:              strconv.Itoa(v.Stage),
-			Author:             v.Author,
-			ReportType:         v.ReportType,
+	// 记录不存在则新增,存在则更新结束阅读时间
+	var recordId int
+	nowTime := time.Now().Local()
+	if req.RecordId <= 0 {
+		newRecord := &models.UserReadRecord{
+			UserId:             users.UserId,
+			ReportId:           req.ReportId,
+			ReportTitle:        title,
+			ClassifyIdFirst:    classifyIdFirst,
+			ClassifyNameFirst:  classifyNameFirst,
+			ClassifyIdSecond:   classifyIdSecond,
+			ClassifyNameSecond: classifyNameSecond,
+			ClassifyIdThird:    classifyIdThird,
+			ClassifyNameThird:  classifyNameThird,
+			StartTimestamp:     int(nowTime.Unix()),
+			CreateTime:         nowTime,
+			ReportSource:       req.ReportSource,
+		}
+		if e := newRecord.Create(); e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("新增阅读记录失败, %v", e)
+			return
 		}
-		if v.PublishTime.IsZero() {
-			tmpReport.PublishTime = ""
+		recordId = newRecord.Id
+	} else {
+		recordOb := new(models.UserReadRecord)
+		readRecord, e := recordOb.GetItemById(req.RecordId)
+		if e != nil {
+			if e.Error() == utils.ErrNoRow() {
+				br.Msg = "阅读记录不存在"
+				return
+			}
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("获取阅读记录失败, %v", e)
+			return
 		}
-		list = append(list, tmpReport)
-	}
+		readRecord.EndTimestamp = int(nowTime.Unix())
+		if e = readRecord.Update([]string{recordOb.Cols().EndTimestamp}); e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("更新阅读记录失败, %v", e)
+			return
+		}
+		recordId = readRecord.Id
 
-	page := paging.GetPaging(currentIndex, pageSize, total)
-	resp.List = list
-	resp.Paging = page
+		// 更新用户阅读次数
+		usersOb := new(models.Users)
+		if e = usersOb.UpdateUserReadTimes(users.UserId); e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = fmt.Sprintf("更新用户阅读次数失败, %v", e)
+			return
+		}
+	}
 
+	resp := new(response.UserReadRecordResp)
+	resp.RecordId = recordId
 	br.Data = resp
-	br.Msg = "查询成功"
 	br.Ret = 200
+	br.Msg = "操作成功"
 	br.Success = true
 }

+ 136 - 988
controllers/user.go

@@ -9,12 +9,8 @@ import (
 	"eta/eta_mini_api/services/go_redis"
 	"eta/eta_mini_api/utils"
 	"fmt"
-	"image/color"
 	"strconv"
-	"strings"
 	"time"
-
-	"github.com/mojocn/base64Captcha"
 )
 
 type UserController struct {
@@ -25,670 +21,6 @@ type UserAuthController struct {
 	BaseAuthController
 }
 
-// @Title 用户登录接口
-// @Description 用户登录
-// @Param	request	body models.LoginReq true "type json string"
-// @Success 200 {object} models.LoginResp
-// @router /login [post]
-func (this *UserAuthController) Login() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	session := this.Session
-
-	var req request.LoginReq
-	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
-	if err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	if req.RealName == "" {
-		br.Msg = "请输入姓名"
-		return
-	}
-	if req.SysDepartmentId <= 0 {
-		br.Msg = "请选择营业部门"
-		return
-	}
-
-	switch req.LoginType {
-	case 1:
-		if req.Phone == "" {
-			br.Msg = "请输入手机号"
-			br.ErrMsg = "请输入手机号"
-			return
-		}
-		if req.SmsCode == "" {
-			br.Msg = "请输入验证码"
-			br.ErrMsg = "请输入验证码"
-			return
-		}
-		req.Email = ""
-		phone := req.AreaCode + req.Phone
-		item, err := models.GetMsgCode(phone, req.SmsCode)
-		if err != nil {
-			if err.Error() == utils.ErrNoRow() {
-				br.Msg = "验证码错误,请重新输入"
-				br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-				return
-			} else {
-				br.Msg = "验证码错误,请重新输入"
-				br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-				return
-			}
-		}
-		if item == nil {
-			br.Msg = "验证码错误,请重新输入"
-			return
-		}
-	case 2:
-		if req.Email == "" {
-			br.Msg = "请输入邮箱"
-			br.ErrMsg = "请输入邮箱"
-			return
-		}
-		if req.SmsCode == "" {
-			br.Msg = "请输入验证码"
-			br.ErrMsg = "请输入验证码"
-			return
-		}
-		req.Phone = ""
-		item, err := models.GetMsgCode(req.Email, req.SmsCode)
-		if err != nil {
-			if err.Error() == utils.ErrNoRow() {
-				br.Msg = "验证码错误,请重新输入"
-				br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-				return
-			} else {
-				br.Msg = "验证码错误,请重新输入"
-				br.ErrMsg = "校验验证码失败,Err:" + err.Error()
-				return
-			}
-		}
-		if item == nil {
-			br.Msg = "验证码错误,请重新输入"
-			return
-		}
-	}
-	_, errMsg, err := services.BindUser(session.UnionId, session.OpenId, req.Phone, req.Email, req.AreaCode, req.SysDepartmentId, req.RealName)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		br.Msg = "登录失败,系统处理中,请稍后重试"
-		if errMsg != "" {
-			br.Msg = errMsg
-		}
-		br.ErrMsg = "登录失败:" + err.Error()
-		return
-	}
-
-	br.Msg = "登录成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// GenerateCaptcha
-// @Title 生成图形验证码
-// @Description 生成图形验证码
-// @Success 200 Ret=200 获取成功
-// @router /getCaptcha [get]
-func (this *UserController) GenerateCaptcha() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		if br.ErrMsg == "" {
-			br.IsSendEmail = false
-		}
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	// 自定义验证码样式
-	var driver base64Captcha.Driver
-	driverString := base64Captcha.DriverString{
-		Height:          60,    //高度
-		Width:           120,   //宽度
-		NoiseCount:      0,     //干扰数
-		ShowLineOptions: 2 | 4, //展示个数
-		Length:          4,     //长度
-		//Source:          "1234567890qwertyuioplkjhgfdsazxcvbnm", //验证码随机字符串来源
-		Source: "1234567890", //验证码随机字符串来源
-		BgColor: &color.RGBA{ // 背景颜色
-			R: 0,
-			G: 0,
-			B: 0,
-			A: 0,
-		},
-		Fonts: []string{"wqy-microhei.ttc"}, // 字体
-	}
-	driver = driverString.ConvertFonts()
-
-	// 生成验证码
-	store := services.CaptchaRedis{}
-	captcha := base64Captcha.NewCaptcha(driver, store)
-	id, b64s, _, err := captcha.Generate()
-	if err != nil {
-		br.Msg = "生成失败"
-		br.ErrMsg = "生成验证码失败, Err: " + err.Error()
-		return
-	}
-
-	type CaptchaResult struct {
-		Id         string
-		Base64Blob string
-	}
-	res := new(CaptchaResult)
-	res.Id = id
-	res.Base64Blob = b64s
-
-	br.Ret = 200
-	br.Success = true
-	br.Msg = "获取成功"
-	br.Data = res
-}
-
-// @Title 获取短信/邮箱验证码
-// @Description 用户登录
-// @Param	request	body models.LoginReq true "type json string"
-// @Success 200 {object} models.LoginResp
-// @router /getVerifyCode [post]
-func (this *UserController) GetVerifyCode() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.VerifyCodeReq
-	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
-	if err != nil {
-		br.Msg = "参数解析异常!"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	if req.VerifyType != 1 && req.VerifyType != 2 {
-		br.Msg = "验证方式有误"
-		br.ErrMsg = fmt.Sprintf("验证方式异常<%d>", req.VerifyType)
-	}
-	if req.CaptchaId == "" || req.CaptchaCode == "" {
-		br.Msg = "请输入图形验证码"
-		return
-	}
-
-	code := utils.GetRandDigit(6)
-	fmt.Println(code)
-	switch req.VerifyType {
-	case 1:
-		if req.AreaCode == "" {
-			br.Msg = "请选择区号"
-			return
-		}
-		if req.Phone == "" {
-			br.Msg = "请输入手机号"
-			return
-		}
-		if req.AreaCode == utils.TelAreaCodeHome && !utils.ValidateMobileFormatat(req.Phone) {
-			br.Msg = "您的手机号输入有误, 请检查"
-			return
-		}
-		phoneKey := utils.CACHE_ACCESS_PHONE_LOGIN_CODE + req.AreaCode + req.Phone
-		res, _ := go_redis.RedisInt(phoneKey)
-		if res >= 5 {
-			br.Msg = "验证码发送太频繁,请稍后重试"
-			return
-		}
-
-		phoneCountKey := utils.CACHE_ACCESS_PHONE_COUNT_LOGIN_CODE + req.AreaCode + req.Phone
-		resCount, _ := go_redis.RedisInt(phoneCountKey)
-		if resCount >= utils.VerifyCodeSendLimit {
-			br.Msg = fmt.Sprintf("一天最多获取%s次,已超限", strconv.Itoa(utils.VerifyCodeSendLimit))
-			return
-		}
-		store := services.CaptchaRedis{}
-		var ok bool
-		ok = store.Verify(req.CaptchaId, req.CaptchaCode, true)
-		if !ok {
-			br.Msg = "图形验证码错误"
-			return
-		}
-		if req.AreaCode == "86" {
-			ok = services.SendSmsCode(req.Phone, code)
-		}
-		if !ok {
-			br.Msg = "请检查手机号和区号"
-			br.ErrMsg = "短信验证码发送失败"
-			return
-		} else {
-			item := new(models.MsgCode)
-			item.OpenId = ""
-			item.Code = code
-			item.Mobile = req.AreaCode + req.Phone
-			item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
-			item.CreateTime = time.Now()
-			err = item.Insert()
-			if err != nil {
-				br.Msg = "发送失败"
-				br.ErrMsg = "发送失败,Err:" + err.Error()
-				return
-			}
-			br.Msg = "发送成功"
-			phoneVerifyCahcheSvc := &services.VerifyCacheIncrService{}
-			err = phoneVerifyCahcheSvc.VerifyCacheIncr(phoneKey, 15*int(time.Minute.Seconds()))
-			if err != nil {
-				utils.FileLog.Info("验证码手机号临时缓存失败", err.Error())
-			}
-			err = phoneVerifyCahcheSvc.VerifyCacheIncr(phoneCountKey, int(utils.SetKeyExpireToday().Seconds()))
-			if err != nil {
-				utils.FileLog.Info("验证码手机号当日缓存失败", err.Error())
-			}
-		}
-	case 2:
-		if req.Email == "" {
-			br.Msg = "请输入邮箱"
-		}
-		if !utils.ValidateEmailFormatat(req.Email) {
-			br.Msg = "您的邮箱格式输入有误, 请检查"
-			return
-		}
-
-		emailKey := utils.CACHE_ACCESS_EMAIL_LOGIN_CODE + req.Email
-		res, _ := go_redis.RedisInt(emailKey)
-		if res >= 5 {
-			br.Msg = "验证码发送太频繁,请稍后重试"
-			return
-		}
-		emailCountKey := utils.CACHE_ACCESS_EMAIL_COUNT_LOGIN_CODE + req.Email
-		resCount, _ := go_redis.RedisInt(emailCountKey)
-		if resCount >= utils.VerifyCodeSendLimit {
-			br.Msg = fmt.Sprintf("一天最多获取%s次,已超限", strconv.Itoa(utils.VerifyCodeSendLimit))
-			return
-		}
-
-		store := services.CaptchaRedis{}
-		var ok bool
-		ok = store.Verify(req.CaptchaId, req.CaptchaCode, true)
-		if !ok {
-			br.Msg = "图形验证码错误"
-			return
-		}
-		date := time.Now()
-		content := "尊敬的用户:</br>本次请求的验证码为:" + code + "(为了保障您账号的安全性,请在15分钟内完成验证。)</br>东吴期货研究团队 </br>" + fmt.Sprintf("%d年%02d月%02d日", date.Year(), date.Month(), date.Day())
-		title := "东吴期货登录验证"
-		result, err := utils.SendEmailByDw(title, content, req.Email)
-		if err != nil {
-			br.Msg = "发送失败"
-			br.ErrMsg = "发送失败,Err:" + err.Error()
-			return
-		}
-		if result {
-			item := new(models.MsgCode)
-			item.OpenId = ""
-			item.Code = code
-			item.Mobile = req.Email
-			item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
-			item.CreateTime = time.Now()
-			err = item.Insert()
-			if err != nil {
-				br.Msg = "发送失败"
-				br.ErrMsg = "发送失败,Err:" + err.Error()
-				return
-			}
-			br.Msg = "发送成功"
-			emailVerifyCahcheSvc := &services.VerifyCacheIncrService{}
-			err = emailVerifyCahcheSvc.VerifyCacheIncr(emailKey, 15*int(time.Minute.Seconds()))
-			if err != nil {
-				utils.FileLog.Info("验证码邮箱临时缓存失败, err:", err.Error())
-			}
-			err = emailVerifyCahcheSvc.VerifyCacheIncr(emailCountKey, int(utils.SetKeyExpireToday().Seconds()))
-			if err != nil {
-				utils.FileLog.Info("验证码邮箱当日缓存失败, err:", err.Error())
-			}
-		} else {
-			br.Msg = "发送失败"
-		}
-	}
-
-	br.Ret = 200
-	br.Success = true
-	br.Msg = "发送成功"
-}
-
-// @Title 新增报告浏览记录
-// @Description 新增报告浏览记录接口
-// @Param	request	body models.ReportRecordReq true "type json string"
-// @Success 200 新增成功
-// @router /addReportRecord [post]
-func (this *UserAuthController) AddReportRecord() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-	if user == nil {
-		br.Msg = "请登录"
-		br.ErrMsg = "请登录,用户信息为空"
-		br.Ret = 403
-		return
-	}
-	var req request.ReportRecordReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析异常!"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	if req.ReportId <= 0 {
-		br.Msg = "参数错误"
-		br.ErrMsg = "参数错误,报告id小于等于0"
-		return
-	}
-	reportResp, err := services.GetReportDetail(req.ReportId, user.UserId)
-	if err != nil {
-		br.Msg = "添加阅读记录失败"
-		br.ErrMsg = "获取研报错误,Err:" + err.Error()
-		return
-	}
-	if reportResp.Ret != 200 {
-		br.Msg = reportResp.Msg
-		br.ErrMsg = reportResp.ErrMsg
-		return
-	}
-	reportDetail := reportResp.Data.Report
-	reportPermissionResp, err := services.GetReportChartPermissionList(req.ReportId)
-	if err != nil {
-		br.Msg = "添加阅读记录失败"
-		br.ErrMsg = "获取研报品种错误,Err:" + err.Error()
-		return
-	}
-	if reportPermissionResp.Ret != 200 {
-		br.Msg = reportPermissionResp.Msg
-		br.ErrMsg = reportPermissionResp.ErrMsg
-		return
-	}
-	reportPermissionList := reportPermissionResp.Data
-	chartPermissionList, err := services.GetChartPermissionAllList()
-	if err != nil {
-		br.Msg = "添加阅读记录失败"
-		br.ErrMsg = "获取研报品种列表失败,Err:" + err.Error()
-		return
-	}
-	chartMap := make(map[int]*models.ChartPermission)
-	for _, permission := range chartPermissionList.Data {
-		chartMap[permission.ChartPermissionId] = permission
-	}
-	curTime := time.Now()
-	var insertId int64
-	if req.RecordId == 0 {
-		// 如果不存在就新增一条记录
-		permission1Ids := make([]int, 0)
-		permission2Ids := make([]int, 0)
-		permissionNames := make([]string, 0)
-		for _, item := range reportPermissionList {
-			curPermission := chartMap[item.ChartPermissionId]
-			permission1Ids = append(permission1Ids, curPermission.ParentId)
-			permission2Ids = append(permission2Ids, curPermission.ChartPermissionId)
-			permissionNames = append(permissionNames, curPermission.PermissionName)
-		}
-		permission1Ids = utils.Unique(permission1Ids)
-		permission2Ids = utils.Unique(permission2Ids)
-		permissionNames = utils.Unique(permissionNames)
-		userReadRecord := &models.UserReadRecord{
-			UserId:              user.UserId,
-			ReportId:            req.ReportId,
-			ReportTitle:         reportDetail.Title,
-			ChartPermissionName: strings.Join(permissionNames, ","),
-			ClassifyId1:         reportDetail.ClassifyIdFirst,
-			ClassifyName1:       reportDetail.ClassifyNameFirst,
-			ClassifyId2:         reportDetail.ClassifyIdSecond,
-			ClassifyName2:       reportDetail.ClassifyNameSecond,
-			ClassifyId3:         reportDetail.ClassifyIdThird,
-			ClassifyName3:       reportDetail.ClassifyNameThird,
-			Timestamp:           int(curTime.Unix()),
-			CreateTime:          curTime,
-			CreateDate:          curTime.Format(utils.FormatDate),
-			ReportType:          utils.ReportTypeEta,
-		}
-		insertId, err = userReadRecord.Insert()
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "添加阅读记录失败,Err:" + err.Error()
-			return
-		}
-
-		userReadPermission1 := make([]*models.UserReadPermission1, 0)
-		for _, id := range permission1Ids {
-			userReadPermission1 = append(userReadPermission1, &models.UserReadPermission1{
-				UserReadRecordId:  int(insertId),
-				ChartPermissionId: id,
-				PermissionName:    chartMap[id].PermissionName,
-			})
-		}
-		err = models.UserReadPermission1MultiInsert(userReadPermission1)
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "添加阅读记录失败,Err:" + err.Error()
-			return
-		}
-		userReadPermission2 := make([]*models.UserReadPermission2, 0)
-		for _, id := range permission2Ids {
-			userReadPermission2 = append(userReadPermission2, &models.UserReadPermission2{
-				UserReadRecordId:  int(insertId),
-				ChartPermissionId: id,
-			})
-		}
-		err = models.UserReadPermission2MultiInsert(userReadPermission2)
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "添加阅读记录失败,Err:" + err.Error()
-			return
-		}
-	} else {
-		// 如果存在就计算停留时间
-		userRecord, err := models.GetUserReadRecordListById(req.RecordId)
-		if err != nil {
-			if err.Error() == utils.ErrNoRow() {
-				br.Msg = "更新阅读记录不存在"
-				return
-			}
-			br.Msg = "更新阅读记录失败"
-			br.ErrMsg = "更新阅读记录失败,Err:" + err.Error()
-			return
-		}
-		stayTime := curTime.Unix() - int64(userRecord.Timestamp)
-		stayTimeStr := utils.SecondsToHMS(stayTime)
-		err = models.UpdateUserReadRecordById(req.RecordId, int(curTime.Unix()), int(stayTime), stayTimeStr)
-		if err != nil {
-			br.Msg = "更新阅读记录失败"
-			br.ErrMsg = "更新阅读记录失败,Err:" + err.Error()
-			return
-		}
-	}
-	resp := new(response.UserReadRecordResp)
-	resp.RecordId = insertId
-
-	br.Msg = "添加阅读记录成功"
-	br.Ret = 200
-	br.Success = true
-	br.Data = resp
-}
-
-// @Title 新增pdf报告浏览记录
-// @Description 新增pdf报告浏览记录接口
-// @Param	request	body models.ReportPdfRecordReq true "type json string"
-// @Success 200 新增成功
-// @router /pdf/addReportRecord [post]
-func (this *UserAuthController) AddReportPdfRecord() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-	if user == nil {
-		br.Msg = "请登录"
-		br.ErrMsg = "请登录,用户信息为空"
-		br.Ret = 403
-		return
-	}
-	var req request.ReportPdfRecordReq
-	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
-		br.Msg = "参数解析异常!"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	if req.ReportPdfId <= 0 {
-		br.Msg = "参数错误"
-		br.ErrMsg = "参数错误,报告id小于等于0"
-		return
-	}
-	reportPdf, err := models.GetReportPdfById(req.ReportPdfId)
-	if err != nil {
-		if err.Error() == utils.ErrNoRow() {
-			br.Msg = "报告不存在或已删除"
-			return
-		}
-		br.Msg = "添加阅读记录失败"
-		br.ErrMsg = "获取研报错误,Err:" + err.Error()
-		return
-	}
-	reportClassifyId := services.GetReportPdfClassify(reportPdf)
-	reportPermissionResp, err := services.GetChartPermissionListByClassifyId(reportClassifyId, 0)
-	if err != nil {
-		br.Msg = "添加阅读记录失败"
-		br.ErrMsg = "获取研报品种错误,Err:" + err.Error()
-		return
-	}
-	if reportPermissionResp.Ret != 200 {
-		br.Msg = reportPermissionResp.Msg
-		br.ErrMsg = reportPermissionResp.ErrMsg
-		return
-	}
-	reportPermissionList := reportPermissionResp.Data
-	chartPermissionList, err := services.GetChartPermissionAllList()
-	if err != nil {
-		br.Msg = "添加阅读记录失败"
-		br.ErrMsg = "获取研报品种列表失败,Err:" + err.Error()
-		return
-	}
-	chartMap := make(map[int]*models.ChartPermission)
-	for _, permission := range chartPermissionList.Data {
-		chartMap[permission.ChartPermissionId] = permission
-	}
-	curTime := time.Now()
-	var insertId int64
-	if req.RecordId == 0 {
-		// 如果不存在就新增一条记录
-		permission1Ids := make([]int, 0)
-		permission2Ids := make([]int, 0)
-		permissionNames := make([]string, 0)
-		for _, item := range reportPermissionList {
-			curPermission := chartMap[item.ChartPermissionId]
-			permission1Ids = append(permission1Ids, curPermission.ParentId)
-			permission2Ids = append(permission2Ids, curPermission.ChartPermissionId)
-			permissionNames = append(permissionNames, curPermission.PermissionName)
-		}
-		permission1Ids = utils.Unique(permission1Ids)
-		permission2Ids = utils.Unique(permission2Ids)
-		permissionNames = utils.Unique(permissionNames)
-		userReadRecord := &models.UserReadRecord{
-			UserId:              user.UserId,
-			ReportId:            reportPdf.ReportPdfId,
-			ReportTitle:         reportPdf.Title,
-			ChartPermissionName: strings.Join(permissionNames, ","),
-			ClassifyId1:         reportPdf.ClassifyIdFirst,
-			ClassifyName1:       reportPdf.ClassifyNameFirst,
-			ClassifyId2:         reportPdf.ClassifyIdSecond,
-			ClassifyName2:       reportPdf.ClassifyNameSecond,
-			Timestamp:           int(curTime.Unix()),
-			CreateTime:          curTime,
-			CreateDate:          curTime.Format(utils.FormatDate),
-			ReportType:          utils.ReportTypePdf,
-		}
-		insertId, err = userReadRecord.Insert()
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "添加阅读记录失败,Err:" + err.Error()
-			return
-		}
-
-		userReadPermission1 := make([]*models.UserReadPermission1, 0)
-		for _, id := range permission1Ids {
-			userReadPermission1 = append(userReadPermission1, &models.UserReadPermission1{
-				UserReadRecordId:  int(insertId),
-				ChartPermissionId: id,
-				PermissionName:    chartMap[id].PermissionName,
-			})
-		}
-		err = models.UserReadPermission1MultiInsert(userReadPermission1)
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "添加阅读记录失败,Err:" + err.Error()
-			return
-		}
-		userReadPermission2 := make([]*models.UserReadPermission2, 0)
-		for _, id := range permission2Ids {
-			userReadPermission2 = append(userReadPermission2, &models.UserReadPermission2{
-				UserReadRecordId:  int(insertId),
-				ChartPermissionId: id,
-			})
-		}
-		err = models.UserReadPermission2MultiInsert(userReadPermission2)
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "添加阅读记录失败,Err:" + err.Error()
-			return
-		}
-		count, err := models.GetUserReadRecordCountByReportPdfIdAndUserId(req.ReportPdfId, user.UserId)
-		if err != nil {
-			br.Msg = "添加阅读记录失败"
-			br.ErrMsg = "获取阅读记录失败,Err:" + err.Error()
-			return
-		}
-		if count > 1 {
-			err = models.UpdateReportPdfPv(req.ReportPdfId)
-			if err != nil {
-				br.Msg = "添加研报阅读记录失败"
-				br.ErrMsg = "更新阅读记录失败,Err:" + err.Error()
-				return
-			}
-		} else {
-			err = models.UpdateReportPdfUvAndPv(req.ReportPdfId)
-			if err != nil {
-				br.Msg = "添加研报阅读记录失败"
-				br.ErrMsg = "更新阅读记录失败,Err:" + err.Error()
-				return
-			}
-		}
-	} else {
-		// 如果存在就计算停留时间
-		userRecord, err := models.GetUserReadRecordListById(req.RecordId)
-		if err != nil {
-			if err.Error() == utils.ErrNoRow() {
-				br.Msg = "更新阅读记录不存在"
-				return
-			}
-			br.Msg = "更新阅读记录失败"
-			br.ErrMsg = "更新阅读记录失败,Err:" + err.Error()
-			return
-		}
-		stayTime := curTime.Unix() - int64(userRecord.Timestamp)
-		stayTimeStr := utils.SecondsToHMS(stayTime)
-		err = models.UpdateUserReadRecordById(req.RecordId, int(curTime.Unix()), int(stayTime), stayTimeStr)
-		if err != nil {
-			br.Msg = "更新阅读记录失败"
-			br.ErrMsg = "更新阅读记录失败,Err:" + err.Error()
-			return
-		}
-	}
-	resp := new(response.UserReadRecordResp)
-	resp.RecordId = insertId
-
-	br.Msg = "添加阅读记录成功"
-	br.Ret = 200
-	br.Success = true
-	br.Data = resp
-}
-
 // AreaCodeList
 // @Title 手机号区号列表
 // @Description 手机号区号列表
@@ -728,390 +60,206 @@ func (this *UserController) AreaCodeList() {
 	br.Msg = "获取成功"
 }
 
-// 用户品种信息
-// @Title 用户信息
-// @Description 用户信息
-// @Success 200 Ret=200 获取成功
-// @router /info [get]
-func (this *UserAuthController) Info() {
+// GetVerifyCode
+// @Title 获取短信/邮箱验证码
+// @Description 用户登录
+// @Param	request	body models.LoginReq true "type json string"
+// @Success 200 {object} models.LoginResp
+// @router /get_verify_code [post]
+func (this *UserController) GetVerifyCode() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
-	user := this.User
-
-	if user == nil {
-		user = &models.User{}
-	}
-	var department *models.SysDepartment
-	var err error
-	if user.SellerDepartmentId > 0 {
-		department, err = models.GetSysDepartmentById(user.SellerDepartmentId)
-		if err != nil {
-			if err.Error() == utils.ErrNoRow() {
-				br.Msg = "查询失败"
-				br.ErrMsg = "部门不存在,系统异常,Err:" + err.Error()
-				return
-			}
-			br.Msg = "查询失败"
-			br.ErrMsg = "查询失败,系统异常,Err:" + err.Error()
-			return
-		}
-	} else {
-		department = new(models.SysDepartment)
-	}
-	private, err := services.GetPrivateChartPermissionList()
-	if err != nil {
-		br.Msg = "查询失败"
-		br.ErrMsg = "查询失败,系统异常,Err:" + err.Error()
+	var req request.VerifyCodeReq
+	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = fmt.Sprintf("参数解析失败, %v", e)
 		return
 	}
-	if private.Ret != 200 {
-		br.Msg = private.Msg
-		br.ErrMsg = private.ErrMsg
+	if req.AreaCode == "" {
+		br.Msg = "请选择区号"
 		return
 	}
-	userPermissionIds, err := models.GetUserChartPermissionIdByUserId(user.UserId)
-	if err != nil {
-		br.Msg = "查看权限失败"
-		br.ErrMsg = "查看权限失败,系统异常,Err:" + err.Error()
+	if req.Phone == "" {
+		br.Msg = "请输入手机号"
 		return
 	}
-	userPermissionMap := make(map[int]struct{})
-	for _, v := range userPermissionIds {
-		userPermissionMap[v] = struct{}{}
-	}
-	var hasPermission string
-	for _, v := range private.Data {
-		for _, vv := range v.Child {
-			if _, ok := userPermissionMap[vv.ChartPermissionId]; ok {
-				hasPermission = "私有权限"
-				break
-			}
-		}
-	}
-	if hasPermission == "" || user.Status == utils.UserStatusNo {
-		hasPermission = "公有权限"
-	}
-	miniconf, err := models.GetMiniConf()
-	if err != nil {
-		br.Msg = "获取配置失败"
-		br.ErrMsg = "获取配置失败,系统异常,Err:" + err.Error()
+	if req.AreaCode == utils.TelAreaCodeHome && !utils.ValidateMobileFormatat(req.Phone) {
+		br.Msg = "您的手机号输入有误, 请检查"
 		return
 	}
-
-	userView := &models.UserView{
-		Headimgurl:           miniconf["Logo"],
-		RealName:             user.RealName,
-		Phone:                user.Phone,
-		AreaCode:             user.AreaCode,
-		SellerDepartmentName: department.SysDepartmentName,
-		HasPermission:        hasPermission,
-		Email:                user.Email,
-		Componey:             user.Company,
-		IsRegistered:         user.IsRegistered,
-		Status:               user.Status,
-		ValidEndTime:         user.ValidEndTime.Format(utils.FormatDate),
-	}
-	// 固定电话
-	userView.SellerDepartmentPhone = append(userView.SellerDepartmentPhone,
-		[]string{"021-63123065", "021-63123067"}...)
-
-	if user.ValidEndTime.IsZero() {
-		userView.ValidEndTime = ""
-	}
-	br.Data = userView
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// PermissionList
-// @Title 用户个人权限列表
-// @Description 用户个人权限列表
-// @Param	request	body models.LoginReq true "type json string"
-// @Success 200 {object} []models.ChartPermissionTreeView
-// @router /permission/list [get]
-func (this *UserAuthController) PermissionList() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-	permissionIds, err := models.GetUserChartPermissionIdByUserId(user.UserId)
-	if err != nil {
-		br.Msg = "查询用户权限失败"
-		br.ErrMsg = "查询用户权限失败,系统异常,Err:" + err.Error()
+	phoneKey := utils.CACHE_ACCESS_PHONE_LOGIN_CODE + req.AreaCode + req.Phone
+	res, _ := go_redis.RedisInt(phoneKey)
+	if res >= 5 {
+		br.Msg = "验证码发送太频繁,请稍后重试"
 		return
 	}
-	userPermissionMap := make(map[int]struct{})
-	for _, v := range permissionIds {
-		userPermissionMap[v] = struct{}{}
-	}
-	// 查询公有权限
-	var publicView []*models.ChartPermissionTreeView
-	publicResp, err := services.GetPublicChartPermissionList()
-	if err != nil {
-		br.Msg = "查询公有权限失败"
-		br.ErrMsg = "查询私有权限失败,系统异常,Err:" + err.Error()
-	}
-	if publicResp.Ret != 200 {
-		br.Msg = publicResp.Msg
-		br.ErrMsg = publicResp.ErrMsg
+	phoneCountKey := utils.CACHE_ACCESS_PHONE_COUNT_LOGIN_CODE + req.AreaCode + req.Phone
+	resCount, _ := go_redis.RedisInt(phoneCountKey)
+	if resCount >= utils.VerifyCodeSendLimit {
+		br.Msg = fmt.Sprintf("一天最多获取%s次,已超限", strconv.Itoa(utils.VerifyCodeSendLimit))
 		return
 	}
-	publicView = publicResp.Data
-
-	// 如果是正式用户,则查询私有权限
-	var privateView []*models.ChartPermissionTreeView
-	if user.Status == utils.UserStatusFormal {
-		privateResp, err := services.GetPrivateChartPermissionList()
-		if err != nil {
-			br.Msg = "查询私有权限失败"
-			br.ErrMsg = "查询私有权限失败,系统异常,Err:" + err.Error()
-		}
-		if privateResp.Ret != 200 {
-			br.Msg = privateResp.Msg
-			br.ErrMsg = privateResp.ErrMsg
-			return
-		}
+	code := utils.GetRandDigit(6)
 
-		for _, v := range privateResp.Data {
-			IsAdd := false
-			curPermissionView := &models.ChartPermissionTreeView{
-				ChartPermissionId: v.ChartPermissionId,
-				PermissionName:    v.PermissionName,
-				IsPublic:          v.IsPublic,
-				Sort:              v.Sort,
-				Child:             make([]*models.ChartPermissionTreeView, 0),
-			}
-			for _, vv := range v.Child {
-				if _, ok := userPermissionMap[vv.ChartPermissionId]; ok {
-					curPermissionView.Child = append(curPermissionView.Child, vv)
-					IsAdd = true
-				}
-			}
-			if IsAdd {
-				privateView = append(privateView, curPermissionView)
-			}
-		}
-	}
-	privateAloneView := make([]*models.ChartPermissionTreeView, 0)
-	for _, vi := range privateView {
-		isHas := false
-		for _, vb := range publicView {
-			if vi.ChartPermissionId == vb.ChartPermissionId {
-				isHas = true
-				vb.Child = append(vb.Child, vi.Child...)
-				break
-			}
-		}
-		if !isHas {
-			privateAloneView = append(privateAloneView, vi)
-		}
-	}
-	publicView = append(publicView, privateAloneView...)
-	for _, vi := range publicView {
-		vi.ChartPermissionType = utils.PermissionTypeEta
-		for _, vi := range vi.Child {
-			vi.ChartPermissionType = utils.PermissionTypeEta
+	var (
+		sendOk     bool
+		sendResult string
+		err        error
+	)
+	if utils.RunMode == "release" {
+		var pars services.SmsApiPars
+		pars.PhoneList = append(pars.PhoneList, req.Phone)
+		pars.ServiceProvider = services.SmsApiServiceProviderDefault
+		pars.SmsContent = fmt.Sprintf("验证码短信:<br>【金瑞期货】您的短信验证码是%s,有效期15分钟", code)
+		pars.Sender = "金瑞小程序"
+		pars.Department = "信息技术部"
+		pars.Purpose = "小程序登录短信验证码"
+		result, e := services.PostSmsApi(pars)
+		sendOk = true
+		if e != nil {
+			err = fmt.Errorf("发送短信验证码失败, %v", e)
+			sendOk = false
+		}
+		sendResult = result
+	} else {
+		// 测试环境用聚合
+		ok, result, e := services.SendSmsCode(req.Phone, code)
+		if e != nil {
+			err = fmt.Errorf("发送短信验证码失败, %v", e)
 		}
+		sendOk = ok
+		sendResult = result
 	}
-
-	br.Data = publicView
-	br.Msg = "查询成功"
-	br.Success = true
-	br.Ret = 200
-}
-
-// PermissionList
-// @Title 用户已购权限列表
-// @Description 用户已购权限列表
-// @Param	request	body models.LoginReq true "type json string"
-// @Success 200 {object} []models.ChartPermissionTreeView
-// @router /purchased/list [get]
-func (this *UserAuthController) PurchasedPermission() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	user := this.User
-	permissionIds, err := models.GetUserChartPermissionIdByUserId(user.UserId)
-	if err != nil {
-		br.Msg = "查询用户权限失败"
-		br.ErrMsg = "查询用户权限失败,系统异常,Err:" + err.Error()
+	item := new(models.MsgCode)
+	item.Code = code
+	item.Mobile = req.AreaCode + req.Phone
+	item.ApiResult = sendResult
+	item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
+	item.CreateTime = time.Now()
+	if e := item.Insert(); e != nil {
+		br.Msg = "发送失败"
+		br.ErrMsg = fmt.Sprintf("新增短信发送记录失败, %v", e)
 		return
 	}
-	permissionMap := make(map[int]struct{})
-	for _, v := range permissionIds {
-		permissionMap[v] = struct{}{}
-	}
-	// 查询私有权限
-	privateResp, err := services.GetPrivateChartPermissionList()
-	if err != nil {
-		br.Msg = "查询私有权限失败"
-		br.ErrMsg = "查询私有权限失败,系统异常,Err:" + err.Error()
-	}
-	if privateResp.Ret != 200 {
-		br.Msg = privateResp.Msg
-		br.ErrMsg = privateResp.ErrMsg
+	if err != nil || !sendOk {
+		br.Msg = "发送失败"
+		br.ErrMsg = fmt.Sprintf("发送短信验证码失败, %v", err)
 		return
 	}
 
-	var privateView []*models.ChartPermissionTreeView
-	for _, v := range privateResp.Data {
-		IsAdd := false
-		curPermissionView := &models.ChartPermissionTreeView{
-			ChartPermissionId:   v.ChartPermissionId,
-			PermissionName:      v.PermissionName,
-			IsPublic:            v.IsPublic,
-			Sort:                v.Sort,
-			Child:               make([]*models.ChartPermissionTreeView, 0),
-			ChartPermissionType: utils.PermissionTypeEta,
-		}
-		for _, vv := range v.Child {
-			if _, ok := permissionMap[vv.ChartPermissionId]; ok && vv.ParentId != 0 {
-				vv.ChartPermissionType = utils.PermissionTypeEta
-				curPermissionView.Child = append(curPermissionView.Child, vv)
-				IsAdd = true
-			}
-		}
-		if IsAdd {
-			privateView = append(privateView, curPermissionView)
-		}
+	phoneVerifyCacheSvc := &services.VerifyCacheIncrService{}
+	if e := phoneVerifyCacheSvc.VerifyCacheIncr(phoneKey, 15*int(time.Minute.Seconds())); e != nil {
+		utils.FileLog.Info(fmt.Sprintf("验证码手机号临时缓存失败, %v", e))
 	}
-	for _, vi := range privateView {
-		vi.Child = append(vi.Child, &models.ChartPermissionTreeView{
-			ChartPermissionId:   -1,
-			PermissionName:      utils.MINI_CUSTOM_PERMISSION_NAME,
-			IsPublic:            0,
-			Sort:                0,
-			ChartPermissionType: utils.ReportTypePdf,
-		})
+	if e := phoneVerifyCacheSvc.VerifyCacheIncr(phoneCountKey, int(utils.SetKeyExpireToday().Seconds())); e != nil {
+		utils.FileLog.Info(fmt.Sprintf("验证码手机号当日缓存失败, %v", e))
 	}
 
-	br.Data = privateView
-	br.Msg = "查询成功"
-	br.Success = true
 	br.Ret = 200
+	br.Success = true
+	br.Msg = "发送成功"
 }
 
-// UserInfoSave
-// @Title 用户信息补充
-// @Description 用户信息补充
-// @Param   request	body request.UserEidtReq true "type json string"
-// @Success Ret=200 保存成功
-// @router /info/save [post]
-func (this *UserAuthController) UserInfoSave() {
+// Login
+// @Title 用户登录
+// @Description 用户登录接口
+// @Param	request	body models.LoginReq true "type json string"
+// @Success 200 {object} models.Users
+// @router /login [post]
+func (this *UserAuthController) Login() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
+	session := this.Session
 
-	var req request.UserInfoSaveReq
+	var req request.LoginReq
 	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
 	if err != nil {
-		br.Msg = "参数解析异常!"
-		br.ErrMsg = "参数解析失败Err:" + err.Error()
+		br.Msg = "参数解析失败"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
 		return
 	}
-	user := this.User
-	if user == nil {
-		br.Msg = "用户不存在"
+	if req.Phone == "" {
+		br.Msg = "请输入手机号"
+		br.ErrMsg = "请输入手机号"
 		return
 	}
-	if user.SellerDepartmentId > 0 {
-		req.SysDepartmentId = user.SellerDepartmentId
+	if req.SmsCode == "" {
+		br.Msg = "请输入验证码"
+		br.ErrMsg = "请输入验证码"
+		return
 	}
-	if user.RealName != "" {
-		req.RealName = user.RealName
+	if session.OpenId == "" {
+		br.Msg = "登录失败"
+		br.ErrMsg = fmt.Sprintf("用户open_id为空")
+		return
 	}
-	msg, err := services.SaveUserInfo(user.UserId, req.SysDepartmentId, req.RealName)
-	if err != nil {
-		if msg == "" {
-			br.Msg = "保存失败"
-		} else {
-			br.Msg = msg
-		}
-		br.ErrMsg = "保存失败,系统异常,Err:" + err.Error()
+	phone := req.AreaCode + req.Phone
+	_, e := models.GetMsgCode(phone, req.SmsCode)
+	if e != nil {
+		br.Msg = "验证码有误,请重新输入"
+		br.ErrMsg = fmt.Sprintf("获取验证码失败, %v", e)
 		return
 	}
-	if msg != "" {
-		br.Msg = msg
+
+	users, tips, e := services.BindUser(session.UnionId, session.OpenId, req.Phone, req.AreaCode)
+	if e != nil {
+		br.Msg = "登录失败"
+		br.ErrMsg = fmt.Sprintf("登录失败, %v", e)
+		if tips != "" {
+			br.Msg = tips
+		}
 		return
 	}
 
-	br.Msg = "用户信息保存成功"
-	br.Success = true
+	br.Data = users
 	br.Ret = 200
+	br.Msg = "登录成功"
+	br.Success = true
 }
 
-// ApplyPermission
-// @Title 用户申请认证
-// @Description 用户申请认证
-// @Success Ret=200 获取成功
-// @router /apply/permission [post]
-func (this *UserAuthController) ApplyPermission() {
+// Info
+// @Title 用户信息
+// @Description 获取用户信息
+// @Success 200 {object} response.UserInfoResp
+// @router /info [post]
+func (this *UserAuthController) Info() {
 	br := new(models.BaseResponse).Init()
 	defer func() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
-	user := this.User
-
-	if user.ApplyStatus == 1 {
-		br.Ret = 200
-		br.Msg = "您已提交过认证申请,请等待!"
-		br.Success = true
-		return
-	}
-	user.ApplyStatus = 1
-	user.ApplyTime = time.Now()
-	err := user.Update([]string{"apply_status", "apply_time"})
-	if err != nil {
-		br.Msg = "提交认证申请失败"
-		br.ErrMsg = "提交认证申请失败,系统异常,Err:" + err.Error()
+	session := this.Session
+	if session == nil || (session != nil && session.OpenId == "") {
+		br.Msg = "参数有误"
 		return
 	}
+	resp := new(response.UserInfoResp)
 
-	br.Msg = "认证申请,需要1~3个工作日"
-	br.Success = true
-	br.Ret = 200
-}
-
-// DepartmentList
-// @Title 营业部门列表
-// @Description 营业部门列表
-// @Success 200 {object} []*models.SysDepartment
-// @router /department/list [get]
-func (this *UserController) DepartmentList() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-	department, err := models.GetSysDepartmentByName("营业部")
-	if err != nil {
-		if err.Error() == utils.ErrNoRow() {
-			br.Msg = "营业部不存在"
+	usersOb := new(models.Users)
+	{
+		cond := fmt.Sprintf(` AND %s = ?`, usersOb.Cols().OpenId)
+		pars := make([]interface{}, 0)
+		pars = append(pars, session.OpenId)
+		item, e := usersOb.GetItemByCondition(cond, pars, "")
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			br.Msg = "获取失败"
+			br.ErrMsg = fmt.Sprintf("OpenId获取用户失败, %v", e)
 			return
 		}
-		br.Msg = "获取营业部失败"
-		br.ErrMsg = "获取营业部失败,系统异常,Err:" + err.Error()
-		return
-	}
-	depList, err := models.GetChildSysDepartmentByParentId(department.SysDepartmentId)
-	if err != nil {
-		br.Msg = "获取营业部门失败"
-		br.ErrMsg = "获取子部门失败,系统异常,Err:" + err.Error()
-		return
+		if item != nil {
+			resp.User = item.Format2Item()
+			resp.LoginStatus = utils.UserStatusIsLogin
+		}
 	}
+
+	br.Data = resp
+	br.Ret = 200
 	br.Msg = "获取成功"
-	br.Data = depList
 	br.Success = true
-	br.Ret = 200
 }

+ 1 - 321
controllers/wechat.go

@@ -2,12 +2,9 @@ package controllers
 
 import (
 	"encoding/json"
-	"encoding/xml"
 	"eta/eta_mini_api/models"
 	"eta/eta_mini_api/models/request"
 	"eta/eta_mini_api/models/response"
-	"eta/eta_mini_api/services/alarm_msg"
-	"eta/eta_mini_api/services/wechat"
 	"eta/eta_mini_api/services/wx_app"
 	"eta/eta_mini_api/utils"
 	"fmt"
@@ -19,228 +16,7 @@ type WechatController struct {
 	BaseCommonController
 }
 
-type Notify struct {
-	ToUserName   string `xml:"ToUserName"`
-	FromUserName string `xml:"FromUserName"`
-	CreateTime   int    `xml:"CreateTime"`
-	MsgType      string `xml:"MsgType"`
-	Event        string `xml:"Event"`
-	EventKey     string `xml:"EventKey"`
-	Content      string `xml:"Content"`
-}
-
-// @Title 微信获取签名接口
-// @Description 微信获取签名接口
-// @Param   Url   query   string  true       "url地址"
-// @Success 200 {object} models.WechatSign
-// @router /notify [get,post]
-func (this *WechatController) Notify() {
-	echostr := this.GetString("echostr")
-	method := this.Ctx.Input.Method()
-
-	if method == "POST" {
-		body := this.Ctx.Input.RequestBody
-		utils.FileLog.Info("wechat notify:" + string(body))
-		item := new(Notify)
-		err := xml.Unmarshal(body, &item)
-		if err != nil {
-			utils.FileLog.Info("xml.Unmarshal:" + err.Error())
-		}
-		contactMsg := "感谢关注东吴期货研究所\r\n公司地址:上海市黄浦区西藏南路1208号东吴证券大厦19楼\r\n\r\n业务合作:\r\n电话:021-6312 3065\r\n邮箱:lvan@dwqh88.com\r\n邮编:200001"
-
-		var openId, returnResult string
-		if item.MsgType != "" {
-			openId = item.FromUserName
-		}
-		xmlTpl := `<xml>
-		<ToUserName><![CDATA[%s]]></ToUserName>
-		<FromUserName><![CDATA[%s]]></FromUserName>
-		<CreateTime>%s</CreateTime>
-		<MsgType><![CDATA[text]]></MsgType>
-		<Content><![CDATA[%s]]></Content>
-		</xml>`
-		createTime := strconv.FormatInt(time.Now().Unix(), 10)
-		// WxId := "gh_5dc508325c6f" // 弘则投研公众号原始id
-		xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.DW_WX_Id, createTime, contactMsg)
-
-		if item.MsgType == "event" {
-			switch item.Event {
-			case "subscribe":
-				fmt.Println("关注")
-				go subscribe(openId)
-			case "unsubscribe":
-				fmt.Println("取消关注")
-				go unsubscribe(openId)
-			case "CLICK":
-				returnResult = xmlTpl
-			default:
-				utils.FileLog.Info("wechat notify event:" + item.Event)
-			}
-			this.Ctx.WriteString(xmlTpl)
-		} else {
-			returnResult = xmlTpl
-		}
-		this.Ctx.WriteString(returnResult)
-	} else {
-		this.Ctx.WriteString(echostr)
-	}
-}
-
-// subscribe 关注后的处理逻辑
-func subscribe(openId string) {
-	userRecord, err := models.GetUserRecordByOpenId(openId)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		utils.FileLog.Info("通过openid获取user_record记录失败,err:" + err.Error())
-		return
-	}
-	// openId已存在
-	if userRecord != nil {
-		if userRecord.UserId > 0 && userRecord.UnionId != "" { //已经绑定了的话,那么就去修改用户状态
-			err = models.UserSubscribe(1, openId)
-			if err != nil {
-				utils.FileLog.Info("关注后,通过openid修改user_record异常,err:" + err.Error())
-			}
-			user, err := models.GetUserByUnionId(userRecord.UnionId)
-			if err != nil {
-				utils.FileLog.Info("关注后,通过unionid获取user记录失败,err:" + err.Error())
-				return
-			}
-			if user != nil {
-				user.IsSubscribed = true
-				user.ModifyTime = time.Now()
-				err = user.Update([]string{"modify_time", "is_subscribed"})
-				if err != nil {
-					utils.FileLog.Info("关注后,修改绑定用户状态异常,err:" + err.Error())
-					return
-				}
-				userRecord.UserId = user.UserId
-				err = userRecord.Update([]string{"user_id"})
-				if err != nil {
-					utils.FileLog.Info("关注后,修改公众号绑定用户异常,err:" + err.Error())
-					return
-				}
-			}
-		} else {
-			// 没有绑定的话,那么校验下unionid,然后再去修改
-			unionId := userRecord.UnionId
-			if unionId == `` {
-				wxUserItem, err := wechat.GetUserInfo(openId)
-				if err != nil {
-					utils.FileLog.Info("获取用户信息失败,err:" + err.Error())
-					return
-				}
-				if wxUserItem.UnionID != `` {
-					unionId = wxUserItem.UnionID
-				}
-			}
-			userRecord.UnionId = unionId
-			userRecord.Subscribe = 1
-			userRecord.SubscribeTime = time.Now()
-			err = userRecord.Update([]string{"union_id", "subscribe", "subscribe_time"})
-			if err != nil {
-				utils.FileLog.Info("关注后,通过openid更新user_record异常,err:" + err.Error())
-				return
-			}
-			user, err := models.GetUserByUnionId(unionId)
-			if err != nil {
-				utils.FileLog.Info("关注后,通过unionid获取user记录失败,err:" + err.Error())
-				return
-			}
-			if user != nil {
-				user.IsSubscribed = true
-				user.ModifyTime = time.Now()
-				err = user.Update([]string{"modify_time", "is_subscribed"})
-				if err != nil {
-					utils.FileLog.Info("关注后,修改绑定用户状态异常,err:" + err.Error())
-					return
-				}
-				userRecord.UserId = user.UserId
-				err = userRecord.Update([]string{"user_id"})
-				if err != nil {
-					utils.FileLog.Info("关注后,修改公众号绑定用户异常,err:" + err.Error())
-					return
-				}
-			}
-		}
-		return
-	}
-
-	// 没有记录,那么需要获取下unionid
-	wxUserItem, err := wechat.GetUserInfo(openId)
-	if err != nil {
-		utils.FileLog.Info("获取用户信息失败,err:" + err.Error())
-		return
-	}
-	newUserRecord := &models.UserRecord{
-		OpenId:        openId,
-		UnionId:       wxUserItem.UnionID,
-		Subscribe:     1,
-		SubscribeTime: time.Now(),
-		NickName:      wxUserItem.Nickname,
-		Sex:           int(wxUserItem.Sex),
-		Province:      wxUserItem.Province,
-		City:          wxUserItem.City,
-		Country:       wxUserItem.Country,
-		Headimgurl:    wxUserItem.Headimgurl,
-		CreateTime:    time.Now(),
-	}
-	insertId, err := newUserRecord.Insert()
-	newUserRecord.UserRecordId = int(insertId)
-	if err != nil {
-		utils.FileLog.Info("关注后,添加user_record信息失败,err:" + err.Error())
-		return
-	}
-	// 检测用户是否绑定小程序,如果绑定修改用户状态
-	user, err := models.GetUserByUnionId(newUserRecord.UnionId)
-	if err != nil {
-		utils.FileLog.Info("修改绑定用户状态异常,err:" + err.Error())
-		return
-	}
-	if user != nil {
-		user.IsSubscribed = true
-		user.ModifyTime = time.Now()
-		err = user.Update([]string{"is_subscribed", "modify_time"})
-		if err != nil {
-			utils.FileLog.Info("关注后,修改绑定用户状态异常,err:" + err.Error())
-			return
-		}
-		newUserRecord.UserId = user.UserId
-		err = newUserRecord.Update([]string{"user_id"})
-		if err != nil {
-			utils.FileLog.Info("关注后,修改公众号绑定用户异常,err:" + err.Error())
-			return
-		}
-	}
-
-}
-
-// unsubscribe 取消关注后的处理逻辑
-func unsubscribe(openId string) {
-	userRecord, err := models.GetUserRecordByOpenId(openId)
-	if err != nil {
-		return
-	}
-	userRecord.Subscribe = 0
-	err = userRecord.Update([]string{"subscribe"})
-	if err != nil {
-		return
-	}
-	if userRecord.UnionId != "" {
-		user, err := models.GetUserByUnionId(userRecord.UnionId)
-		if err != nil {
-			return
-		}
-		if user != nil {
-			user.IsSubscribed = false
-			user.ModifyTime = time.Now()
-			err = user.Update([]string{"is_subscribed", "modify_time"})
-			if err != nil {
-				return
-			}
-		}
-	}
-}
-
+// Login
 // @Title 微信登录
 // @Description 微信登录
 // @Param	request	body models.LoginReq true "type json string"
@@ -315,99 +91,3 @@ func (this *WechatController) Login() {
 	br.Success = true
 	br.Ret = 200
 }
-
-// @Title 公众号绑定
-// @Description 公众号绑定
-// @Param	request	body request.WeChatLoginReq true "type json string"
-// @Success 200 {object} models.LoginResp
-// @router /subscribe [post]
-func (this *WechatController) Subscribe() {
-	br := new(models.BaseResponse).Init()
-	defer func() {
-		if br.Ret != 200 {
-			b, _ := json.Marshal(br)
-			alarm_msg.SendAlarmMsg(string(b), 1)
-		}
-		this.Data["json"] = br
-		this.ServeJSON()
-	}()
-
-	var req request.WeChatLoginReq
-	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
-	if err != nil {
-		br.Msg = "参数解析失败"
-		br.ErrMsg = "参数解析失败,Err:" + err.Error()
-		return
-	}
-	if req.Code == "" {
-		br.Msg = "授权码不存在"
-		return
-	}
-	info, err := wechat.GetWxUserInfo(req.Code)
-	if err != nil {
-		br.Msg = "获取失败"
-		br.ErrMsg = "获取失败,Err:" + err.Error()
-		return
-	}
-	if info.ErrCode != 0 {
-		br.Msg = "获取失败"
-		br.ErrMsg = "获取失败,Err:" + info.ErrMsg
-		return
-	}
-	userRecord, err := models.GetUserRecordByOpenId(info.OpenId)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		br.Msg = "获取用户关注记录失败"
-		br.ErrMsg = "获取用户关注记录失败,Err:" + err.Error()
-		return
-	}
-	// 如果不存在就新增一条记录
-	if userRecord == nil {
-		userRecord := &models.UserRecord{
-			OpenId: info.OpenId,
-		}
-		insertId, err := userRecord.Insert()
-		if err != nil {
-			br.Msg = "新增失败"
-			br.ErrMsg = "新增失败,Err:" + err.Error()
-			return
-		}
-		userRecord.UserRecordId = int(insertId)
-	}
-	if userRecord.UnionId == "" {
-		wxInfo, er := wechat.GetUserInfo(userRecord.OpenId)
-		if er != nil {
-			br.Msg = "获取失败"
-			br.ErrMsg = "获取失败,Err:" + er.Error()
-			return
-		}
-		userRecord.UnionId = wxInfo.UnionID
-		er = userRecord.Update([]string{"union_id"})
-		if er != nil {
-			br.Msg = "获取失败"
-			br.ErrMsg = "获取失败,Err:" + er.Error()
-			return
-		}
-
-	}
-	user, err := models.GetUserByUnionId(userRecord.UnionId)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		br.Msg = "获取用户信息失败"
-		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
-		return
-	}
-	if user != nil {
-		user.IsSubscribed = true
-		err := user.Update([]string{"is_subscribed"})
-		if err != nil {
-			br.Msg = "更新用户信息失败"
-			br.ErrMsg = "更新用户信息失败,Err:" + err.Error()
-			return
-		}
-		userRecord.UserId = user.UserId
-		userRecord.Update([]string{"user_id"})
-	}
-
-	br.Msg = "获取成功"
-	br.Success = true
-	br.Ret = 200
-}

+ 23 - 29
models/banner.go

@@ -1,31 +1,25 @@
 package models
 
-import (
-	"time"
-
-	"github.com/beego/beego/v2/client/orm"
-)
-
-type Banner struct {
-	BannerId   int       `orm:"pk" description:"id"`
-	ImageUrl   string    `description:"图片地址"`
-	CreateTime time.Time `description:"创建时间"`
-	ModifyTime time.Time `description:"修改时间"`
-	JumpUrl    string    `description:"跳转路径"`
-	Remake     string    `description:"备注"`
-	ImageUrlPc string    `description:"pc端图片地址"`
-}
-
-func GetBannerList(startSize, pageSize int) (items []*Banner, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM banner LIMIT ?,?`
-	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
-	return
-}
-
-func GetBannerById(bannerId int) (items *Banner, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM banner WHERE banner_id = ?`
-	err = o.Raw(sql, bannerId).QueryRow(&items)
-	return
-}
+//type Banner struct {
+//	BannerId   int       `orm:"pk" description:"id"`
+//	ImageUrl   string    `description:"图片地址"`
+//	CreateTime time.Time `description:"创建时间"`
+//	ModifyTime time.Time `description:"修改时间"`
+//	JumpUrl    string    `description:"跳转路径"`
+//	Remake     string    `description:"备注"`
+//	ImageUrlPc string    `description:"pc端图片地址"`
+//}
+//
+//func GetBannerList(startSize, pageSize int) (items []*Banner, err error) {
+//	o := orm.NewOrm()
+//	sql := `SELECT * FROM banner LIMIT ?,?`
+//	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
+//	return
+//}
+//
+//func GetBannerById(bannerId int) (items *Banner, err error) {
+//	o := orm.NewOrm()
+//	sql := `SELECT * FROM banner WHERE banner_id = ?`
+//	err = o.Raw(sql, bannerId).QueryRow(&items)
+//	return
+//}

+ 0 - 14
models/business_conf.go

@@ -1,14 +0,0 @@
-package models
-
-import "time"
-
-// BusinessConf 商户配置表
-type BusinessConf struct {
-	Id         int    `orm:"column(id);pk"`
-	ConfKey    string `description:"配置Key"`
-	ConfVal    string `description:"配置值"`
-	ValType    int    `description:"1-字符串;2-数值;3-字符串数组;4-富文本;"`
-	Necessary  int    `description:"是否必填:0-否;1-是"`
-	Remark     string `description:"备注"`
-	CreateTime time.Time
-}

+ 0 - 42
models/chart_permission.go

@@ -1,42 +0,0 @@
-package models
-
-import "time"
-
-type ChartPermissionView struct {
-	ChartPermissionId   int    `description:"权限ID"`
-	PermissionName      string `description:"权限名"`
-	Remark              string `description:"备注"`
-	ImageUrl            string `description:"图片地址"`
-	ChartPermissionType int    `description:"权限类型:1-eta权限;2-小程序权限"`
-}
-
-type ChartPermission struct {
-	ChartPermissionId   int       `description:"品种ID"`
-	ChartPermissionName string    `description:"名称"`
-	PermissionName      string    `description:"权限名"`
-	Sort                int       `description:"排序"`
-	Enabled             int       `description:"是否可用"`
-	CreatedTime         time.Time `description:"创建时间"`
-	LastUpdatedTime     time.Time `description:"更新时间"`
-	Remark              string    `description:"备注"`
-	ImageUrl            string    `description:"图片地址"`
-	ParentId            int       `description:"父级权限id"`
-	IsPublic            int       `description:"是否是公有权限1:公有权限,0私有权限"`
-}
-
-type ChartPermissionResp[T any] struct {
-	Ret    int
-	Data   T
-	Msg    string
-	ErrMsg string
-}
-
-type ChartPermissionTreeView struct {
-	ChartPermissionId   int                        `description:"权限ID"`
-	PermissionName      string                     `description:"权限名"`
-	Child               []*ChartPermissionTreeView `description:"子权限"`
-	IsPublic            int                        `description:"是否是公有权限1:公有权限,0私有权限"`
-	ParentId            int                        `description:"父级权限id"`
-	Sort                int                        `description:"排序" json:"-"`
-	ChartPermissionType int                        `description:"权限类型:1-eta权限;2-小程序权限"`
-}

+ 0 - 12
models/chart_permission_search_key_word_mapping.go

@@ -1,12 +0,0 @@
-package models
-
-import "github.com/beego/beego/v2/client/orm"
-
-func GetClassifyIdsList(chartPermissionId int) (classifyIds []int, err error) {
-	o := orm.NewOrmUsingDB("rddp")
-	sql := ` SELECT classify_id
-		FROM chart_permission_search_key_word_mapping	
-		WHERE chart_permission_id = ? `
-	_, err = o.Raw(sql, chartPermissionId).QueryRows(&classifyIds)
-	return
-}

+ 121 - 37
models/classify.go

@@ -1,44 +1,128 @@
 package models
 
 import (
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"strings"
 	"time"
 )
 
-type Classify struct {
-	Id           int       `description:"分类id"`
-	ClassifyName string    `description:"分类名称"`
-	Sort         int       `json:"-"`
-	ParentId     int       `description:"父级分类id"`
-	CreateTime   time.Time `description:"创建时间"`
-	ModifyTime   time.Time `description:"修改时间"`
-	Level        int       `description:"分类层级"`
-}
-
-type ClassifyView struct {
-	Id           int             `description:"分类id"`
-	ClassifyName string          `description:"分类名称"`
-	Sort         int             `json:"-"`
-	ParentId     int             `description:"父级分类id"`
-	Level        int             `description:"分类层级"`
-	HasChild     int             `description:"是否有子分类0:下面没有子分类,1:下面有子分类"`
-	Child        []*ClassifyView `description:"子分类"`
-}
-
-type ClassifyDetail struct {
-	ClassifyId     int       `description:"分类id"`
-	ClassifyName   string    `description:"分类名称"`
-	Sort           int       `json:"-"`
-	ParentId       int       `description:"父级分类id"`
-	CreateTime     time.Time `description:"创建时间"`
-	ModifyTime     time.Time `description:"修改时间"`
-	Abstract       string    `description:"栏目简介"`
-	Descript       string    `description:"分享描述"`
-	ReportAuthor   string    `description:"栏目作者"`
-	AuthorDescript string    `description:"作者简介"`
-	ColumnImgUrl   string    `description:"栏目配图"`
-	HeadImgUrl     string    `description:"头部banner"`
-	AvatarImgUrl   string    `description:"头像"`
-	ReportImgUrl   string    `description:"报告配图"`
-	HomeImgUrl     string    `description:"首页配图"`
-	Stage          int       `description:"最新期数"`
+// MiniClassify 小程序分类
+type MiniClassify struct {
+	Id              int       `description:"分类ID"`
+	ClassifyName    string    `description:"分类名称"`
+	ParentId        int       `description:"父级分类ID"`
+	Level           int       `description:"分类层级"`
+	LevelPath       string    `description:"层级路径"`
+	Sort            int       `description:"排序"`
+	IconUrl         string    `description:"图标地址"`
+	DiamondDistrict int       `description:"是否金刚区"`
+	Frequency       int       `description:"报告频度:1-高频;2-中频;3-低频"`
+	HotComment      int       `description:"是否热点点评"`
+	KeyPoint        int       `description:"是否重点数据更新"`
+	Enabled         int       `description:"状态:0-禁用;1-启用"`
+	CreateTime      time.Time `description:"创建时间"`
+	ModifyTime      time.Time `description:"修改时间"`
+}
+
+func (m *MiniClassify) TableName() string {
+	return "mini_classify"
+}
+
+type MultipleFactorSeriesCols struct {
+	PrimaryId       string
+	ClassifyName    string
+	ParentId        string
+	Level           string
+	LevelPath       string
+	Sort            string
+	IconUrl         string
+	DiamondDistrict string
+	Frequency       string
+	HotComment      string
+	KeyPoint        string
+	Enabled         string
+	CreateTime      string
+	ModifyTime      string
+}
+
+func (m *MiniClassify) Cols() MultipleFactorSeriesCols {
+	return MultipleFactorSeriesCols{
+		PrimaryId:       "id",
+		ClassifyName:    "classify_name",
+		ParentId:        "parent_id",
+		Level:           "level",
+		LevelPath:       "level_path",
+		Sort:            "sort",
+		IconUrl:         "icon_url",
+		DiamondDistrict: "diamond_district",
+		Frequency:       "frequency",
+		HotComment:      "hot_comment",
+		KeyPoint:        "key_point",
+		Enabled:         "enabled",
+		CreateTime:      "create_time",
+		ModifyTime:      "modify_time",
+	}
+}
+
+func (m *MiniClassify) GetItemById(id int) (item *MiniClassify, err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+func (m *MiniClassify) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*MiniClassify, err error) {
+	o := orm.NewOrm()
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}
+
+// MiniClassifyItem 小程序分类
+type MiniClassifyItem struct {
+	Id              int                 `description:"分类ID"`
+	ClassifyName    string              `description:"分类名称"`
+	ParentId        int                 `description:"父级分类ID"`
+	Level           int                 `description:"分类层级"`
+	LevelPath       string              `description:"层级路径"`
+	Sort            int                 `description:"排序"`
+	IconUrl         string              `description:"图标地址"`
+	DiamondDistrict int                 `description:"是否金刚区"`
+	Frequency       int                 `description:"报告频度:1-高频;2-中频;3-低频"`
+	HotComment      int                 `description:"是否热点点评"`
+	KeyPoint        int                 `description:"是否重点数据更新"`
+	Children        []*MiniClassifyItem `description:"子分类"`
+}
+
+func (m *MiniClassify) Format2Item() (item *MiniClassifyItem) {
+	item = new(MiniClassifyItem)
+	item.Id = m.Id
+	item.ClassifyName = m.ClassifyName
+	item.ParentId = m.ParentId
+	item.Level = m.Level
+	item.LevelPath = m.LevelPath
+	item.Sort = m.Sort
+	item.IconUrl = m.IconUrl
+	item.DiamondDistrict = m.DiamondDistrict
+	item.Frequency = m.Frequency
+	item.HotComment = m.HotComment
+	item.KeyPoint = m.KeyPoint
+	item.Children = make([]*MiniClassifyItem, 0)
+	return
+}
+
+func (m *MiniClassify) GetChildClassifyIdsByParentId(parentId int) (classifyIds []int, err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE FIND_IN_SET(?, %s)`, m.Cols().PrimaryId, m.TableName(), m.Cols().LevelPath)
+	_, err = o.Raw(sql, parentId).QueryRows(&classifyIds)
+	return
 }

+ 21 - 0
models/constants.go

@@ -0,0 +1,21 @@
+package models
+
+const (
+	RowDeletedDefault = 0 // 删除状态-正常
+	RowDeleted        = 1 // 删除状态-已删除
+)
+
+const (
+	UserTypePerson   = 1 // 用户类型-个体投资者
+	UserTypeCompany  = 2 // 用户类型-机构投资者
+	AuthStatusClose  = 0 // 权限状态-关闭
+	AuthStatusOpen   = 1 // 权限状态-开启
+	UserStatusTrial  = 1 // 用户状态-试用
+	UserStatusFormal = 2 // 用户状态-正式
+	UserNoRegistered = 0 // 用户注册状态-未注册
+	UserRegistered   = 1 // 用户注册状态-已注册
+	UserNoSubscribe  = 0 // 用户关注状态-未关注
+	UserSubscribed   = 1 // 用户关注状态-已关注
+)
+
+const ConfAreaCodeListKey = "AreaCodeList" // 配置-手机号区号列表

+ 3 - 14
models/db.go

@@ -23,29 +23,18 @@ func init() {
 	report_db, _ := orm.GetDB("rddp")
 	report_db.SetConnMaxLifetime(10 * time.Minute)
 
-	_ = orm.RegisterDataBase("eta", "mysql", utils.MYSQL_URL)
-	orm.SetMaxIdleConns("eta", 50)
-	orm.SetMaxOpenConns("eta", 100)
-
-	db, _ := orm.GetDB("eta")
-	db.SetConnMaxLifetime(10 * time.Minute)
 	orm.Debug = true
 	orm.DebugLog = orm.NewLog(utils.BinLog)
 
 	// register model
 	orm.RegisterModel(
 		new(MsgCode),
-		new(MyChart),
-		new(MyReport),
-		new(User),
+		new(Users),
 		new(WxToken),
-		new(Banner),
+		//new(Banner),
 		new(WxSession),
 		new(UserRecord),
-		new(UserTemplateRecord),
+		//new(UserTemplateRecord),
 		new(UserReadRecord),
-		new(UserReadPermission1),
-		new(UserReadPermission2),
 	)
-
 }

+ 3 - 27
models/mini_config.go

@@ -7,8 +7,6 @@ import (
 	"github.com/beego/beego/v2/client/orm"
 )
 
-const ConfAreaCodeListKey = "AreaCodeList" // 手机号区号列表
-
 type MiniConfig struct {
 	ConfigID    int       `description:"配置id"`
 	ConfigCode  string    `description:"配置编码"` // 配置编码
@@ -18,10 +16,10 @@ type MiniConfig struct {
 	CreateTime  time.Time `description:"创建时间"` // 创建时间
 }
 
-func GetConfigDetailByCode(configCode string) (config_value string, err error) {
+func GetConfigDetailByCode(configCode string) (configValue string, err error) {
 	o := orm.NewOrm()
-	sql := ` SELECT config_value FROM mini_config WHERE config_code=? `
-	err = o.Raw(sql, configCode).QueryRow(&config_value)
+	sql := ` SELECT config_value FROM mini_config WHERE config_code = ?`
+	err = o.Raw(sql, configCode).QueryRow(&configValue)
 	return
 }
 
@@ -46,25 +44,3 @@ func GetMiniConf() (list map[string]string, err error) {
 	}
 	return
 }
-
-// GetMiniConf 获取eta的服务的配置
-func GetEtaConf() (list map[string]string, err error) {
-	list = make(map[string]string)
-
-	var items []*BusinessConf
-	o := orm.NewOrmUsingDB("eta")
-	sql := `SELECT * FROM  business_conf`
-	_, err = o.Raw(sql).QueryRows(&items)
-	if err != nil {
-		return
-	}
-
-	for _, v := range items {
-		if v.ValType == 4 {
-			list[v.ConfKey] = html.UnescapeString(v.ConfVal)
-			continue
-		}
-		list[v.ConfKey] = v.ConfVal
-	}
-	return
-}

+ 8 - 7
models/msg_code.go

@@ -8,12 +8,13 @@ import (
 
 // MsgCode 验证码列表
 type MsgCode struct {
-	MsgCodeId  int64     `orm:"pk" description:"id"` // 短信验证码id
-	OpenId     string    `description:"用户openId"`    // 用户id
-	Mobile     string    `description:"手机号/邮箱"`      // 手机号/邮箱
-	Code       string    `description:"验证码"`         // 验证码
-	ExpiredIn  int64     `description:"过期时间"`        // 过期时间
-	CreateTime time.Time `description:"创建时间"`        // 创建时间
+	MsgCodeId  int64     `orm:"pk"`
+	OpenId     string    `description:"用户open_id"`
+	Mobile     string    `description:"手机号"`
+	Code       string    `description:"验证码"`
+	ApiResult  string    `description:"短信API请求结果"`
+	ExpiredIn  int64     `description:"过期时间"`
+	CreateTime time.Time `description:"创建时间"`
 }
 
 func (m *MsgCode) Insert() (err error) {
@@ -24,7 +25,7 @@ func (m *MsgCode) Insert() (err error) {
 
 func GetMsgCode(mobile, code string) (item *MsgCode, err error) {
 	o := orm.NewOrm()
-	sql := `SELECT * FROM msg_code WHERE mobile=? AND code=? AND FROM_UNIXTIME(expired_in)>=NOW() `
+	sql := `SELECT * FROM msg_code WHERE mobile = ? AND code = ? AND FROM_UNIXTIME(expired_in)>=NOW() `
 	err = o.Raw(sql, mobile, code).QueryRow(&item)
 	return
 }

+ 0 - 60
models/my_chart.go

@@ -1,60 +0,0 @@
-package models
-
-import (
-	"time"
-
-	"github.com/beego/beego/v2/client/orm"
-)
-
-type MyChart struct {
-	MyChartId    int       `orm:"pk" description:"我的图表ID"`
-	ChartName    string    `description:"图表名称"`   // 图表名称
-	UniqueCode   string    `description:"图表唯一编码"` // 图表唯一编码
-	ChartImage   string    `description:"图表图片"`   // 图表图片
-	ChartInfoId  int       `description:"图表id"`   // 图表图片
-	UserId       int       `description:"用户ID"`
-	UserRealName string    `description:"用户真实姓名"` // 真实姓名
-	CreateTime   time.Time `description:"创建时间"`
-	ModifyTime   time.Time `description:"修改时间"`
-}
-
-func (m *MyChart) Insert() (err error) {
-	o := orm.NewOrm()
-	_, err = o.Insert(m)
-	return
-}
-
-func GetMyChartCount(userId int, uniqueCode string) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM my_chart WHERE user_id=? AND unique_code=?`
-	err = o.Raw(sql, userId, uniqueCode).QueryRow(&count)
-	return
-}
-
-func GetMyChartListCountById(userId int) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM my_chart WHERE user_id=? `
-	err = o.Raw(sql, userId).QueryRow(&count)
-	return
-}
-
-func GetMyChartListById(userId int, startSize, pageSize int) (items []*MyChart, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM my_chart WHERE user_id=? ORDER BY create_time DESC LIMIT ?,?`
-	_, err = o.Raw(sql, userId, startSize, pageSize).QueryRows(&items)
-	return
-}
-
-func DeleteMyChart(userId int, uniqueCode string) (err error) {
-	o := orm.NewOrm()
-	sql := `DELETE FROM my_chart WHERE user_id=? AND unique_code=?`
-	_, err = o.Raw(sql, userId, uniqueCode).Exec()
-	return
-}
-
-func DeleteMyChartByUserIdAndChartInfoId(userId int, chartInfoId int) (err error) {
-	o := orm.NewOrm()
-	sql := `DELETE FROM my_chart WHERE user_id=? AND chart_info_id=?`
-	_, err = o.Raw(sql, userId, chartInfoId).Exec()
-	return
-}

+ 0 - 54
models/my_report.go

@@ -1,54 +0,0 @@
-package models
-
-import (
-	"time"
-
-	"github.com/beego/beego/v2/client/orm"
-)
-
-type MyReport struct {
-	MyReportId  int       `orm:"pk" description:"id"`
-	ReportId    int       `description:"报告id"`
-	UserId      int       `description:"用户id"`
-	Title       string    `description:"标题"`
-	Abstract    string    `description:"摘要"`
-	Author      string    `description:"作者"`
-	PublishTime time.Time `description:"发布时间"`
-	Stage       int       `description:"期数"`
-	CreateTime  time.Time `description:"创建时间"`
-	ReportType  int       `description:"报告类型:1-普通研报;2-pdf研报"`
-}
-
-func (m *MyReport) Insert() (err error) {
-	o := orm.NewOrm()
-	_, err = o.Insert(m)
-	return
-}
-
-func GetMyReportCountByUserIdAndReportId(userId, reportId, reportType int) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM my_report WHERE user_id = ? AND report_id = ? AND report_type = ? `
-	err = o.Raw(sql, userId, reportId, reportType).QueryRow(&count)
-	return
-}
-
-func DeleteMyReportByUserIdAndReportId(userId, reportId, reportType int) (err error) {
-	o := orm.NewOrm()
-	sql := "DELETE FROM my_report WHERE user_id = ? AND report_id = ? AND report_type = ?"
-	_, err = o.Raw(sql, userId, reportId, reportType).Exec()
-	return
-}
-
-func GetMyReportListCountByUserId(userId int) (count int, err error) {
-	o := orm.NewOrm()
-	sql := "SELECT COUNT(*) AS count FROM my_report WHERE user_id = ?"
-	err = o.Raw(sql, userId).QueryRow(&count)
-	return
-}
-
-func GetMyReportListByUserId(userId, startSize, pageSize int) (items []*MyReport, err error) {
-	o := orm.NewOrm()
-	sql := "SELECT * FROM my_report WHERE user_id = ? ORDER BY create_time DESC LIMIT ?, ?"
-	_, err = o.Raw(sql, userId, startSize, pageSize).QueryRows(&items)
-	return
-}

+ 280 - 70
models/report.go

@@ -2,10 +2,188 @@ package models
 
 import (
 	"eta/eta_mini_api/utils"
+	"github.com/beego/beego/v2/client/orm"
 	"time"
 )
 
-type ReportView struct {
+type UnionReport struct {
+	Id               int       `description:"报告ID"`
+	Title            string    `description:"报告标题"`
+	Abstract         string    `description:"摘要"`
+	PublishTime      time.Time `description:"发布时间"`
+	ReportSource     int       `description:"报告来源:1-report表;2-outside_report表"`
+	ReportFile       string    `description:"报告附件"`
+	ClassifyIdFirst  int       `description:"一级分类ID"`
+	ClassifyIdSecond int       `description:"二级分类ID"`
+	ClassifyIdThird  int       `description:"三级分类ID"`
+	Author           string    `description:"作者"`
+}
+
+type UnionReportItem struct {
+	Id           int    `description:"报告ID"`
+	Title        string `description:"报告标题"`
+	Abstract     string `description:"摘要"`
+	PublishTime  string `description:"发布时间"`
+	ReportSource int    `description:"报告来源:1-report表;2-outside_report表"`
+	ReportFile   string `description:"报告附件"`
+	ClassifyId   int    `description:"分类ID"`
+	ClassifyName string `description:"分类名称"`
+	Author       string `description:"作者"`
+}
+
+func GetReportAndOutsideReportCount(reportCond, outsideCond string, reportPars, outsidePars []interface{}) (total int, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT COUNT(*) AS total
+		FROM (
+			(
+				SELECT 
+					r.id AS id
+				FROM 
+					report r
+				WHERE 
+					r.state IN (2,6) ` + reportCond + `
+			)
+			UNION
+			(
+				SELECT 
+					o.outside_report_id AS id
+				FROM 
+					outside_report o
+				INNER JOIN 
+					outside_report_attachment oa 
+				ON 
+					o.outside_report_id = oa.outside_report_id
+				WHERE 
+					oa.title LIKE '%.pdf%' AND oa.create_time = (
+						SELECT MAX(oa2.create_time)
+						FROM outside_report_attachment oa2
+						WHERE oa2.outside_report_id = o.outside_report_id AND oa2.title LIKE '%.pdf%'
+					) ` + outsideCond + `
+			)
+		) AS t`
+	//sql = fmt.Sprintf(sql, reportCond, outsideCond)
+	err = o.Raw(sql, reportPars, outsidePars).QueryRow(&total)
+	return
+}
+
+// GetReportAndOutsideReportByCondition 查询报告及外部中PDF的报告
+func GetReportAndOutsideReportByCondition(reportCond, outsideCond string, reportPars, outsidePars []interface{}, startSize, pageSize int) (items []*UnionReport, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `(
+			SELECT 
+				r.id AS id,
+				r.title AS title,
+				r.abstract AS abstract,
+				r.publish_time AS publish_time,
+				1 AS report_source,
+				detail_pdf_url AS report_file,
+        		r.classify_id_first,
+        		r.classify_id_second,
+        		r.classify_id_third,
+				r.author
+			FROM 
+				report r
+			WHERE
+				r.state IN (2,6) ` + reportCond + `
+		)
+		UNION
+		(
+			SELECT 
+				o.outside_report_id AS id,
+				o.title AS title,
+				o.abstract AS abstract,
+				o.modify_time AS publish_time,
+				2 AS report_source,
+				oa.url AS report_file,
+				o.classify_id AS classify_name_first,
+				o.classify_id AS classify_name_second,
+				o.classify_id AS classify_name_third,
+				o.sys_user_name AS author
+			FROM 
+				outside_report o
+			INNER JOIN 
+				outside_report_attachment oa 
+			ON 
+				o.outside_report_id = oa.outside_report_id
+			WHERE 
+				oa.title LIKE '%.pdf%' AND oa.create_time = (
+					SELECT MAX(oa2.create_time)
+					FROM outside_report_attachment oa2
+					WHERE oa2.outside_report_id = o.outside_report_id AND oa2.title LIKE '%.pdf%'
+				) ` + outsideCond + `
+		)
+		ORDER BY publish_time DESC LIMIT ?,?`
+	//sql = fmt.Sprintf(sql, reportCond, outsideCond)
+	_, err = o.Raw(sql, reportPars, outsidePars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+type Report struct {
+	Id                  int       `orm:"pk" description:"报告Id"`
+	AddType             int       `description:"新增方式:1:新增报告,2:继承报告"`
+	ClassifyIdFirst     int       `description:"一级分类id"`
+	ClassifyNameFirst   string    `description:"一级分类名称"`
+	ClassifyIdSecond    int       `description:"二级分类id"`
+	ClassifyNameSecond  string    `description:"二级分类名称"`
+	ClassifyIdThird     int       `description:"三级分类id"`
+	ClassifyNameThird   string    `description:"三级分类名称"`
+	Title               string    `description:"标题"`
+	Abstract            string    `description:"摘要"`
+	Author              string    `description:"作者"`
+	Frequency           string    `description:"频度"`
+	CreateTime          string    `description:"创建时间"`
+	ModifyTime          time.Time `description:"修改时间"`
+	State               int       `description:"1:未发布;2:已发布;3-待提交;4-待审批;5-已驳回;6-已通过"`
+	PublishTime         time.Time `description:"发布时间"`
+	Stage               int       `description:"期数"`
+	MsgIsSend           int       `description:"消息是否已发送,0:否,1:是"`
+	ThsMsgIsSend        int       `description:"客户群消息是否已发送,0:否,1:是"`
+	Content             string    `description:"内容"`
+	VideoUrl            string    `description:"音频文件URL"`
+	VideoName           string    `description:"音频文件名称"`
+	VideoPlaySeconds    string    `description:"音频播放时长"`
+	VideoSize           string    `description:"音频文件大小,单位M"`
+	ContentSub          string    `description:"内容前两个章节"`
+	ReportCode          string    `description:"报告唯一编码"`
+	ReportVersion       int       `description:"1:旧版,2:新版"`
+	HasChapter          int       `description:"是否有章节 0-否 1-是"`
+	ChapterType         string    `description:"章节类型 day-晨报 week-周报"`
+	OldReportId         int       `description:"research_report表ID, 大于0则表示该报告为老后台同步过来的"`
+	MsgSendTime         time.Time `description:"模版消息发送时间"`
+	AdminId             int       `description:"创建者账号"`
+	AdminRealName       string    `description:"创建者姓名"`
+	ApproveTime         time.Time `description:"审批时间"`
+	ApproveId           int       `description:"审批ID"`
+	DetailImgUrl        string    `description:"报告详情长图地址"`
+	DetailPdfUrl        string    `description:"报告详情PDF地址"`
+	ContentStruct       string    `description:"内容组件"`
+	LastModifyAdminId   int       `description:"最后更新人ID"`
+	LastModifyAdminName string    `description:"最后更新人姓名"`
+	ContentModifyTime   time.Time `description:"内容更新时间"`
+	Pv                  int       `description:"pv"`
+	Uv                  int       `description:"uv"`
+	HeadImg             string    `description:"报告头图地址"`
+	EndImg              string    `description:"报告尾图地址"`
+	CanvasColor         string    `description:"画布颜色"`
+	NeedSplice          int       `description:"是否拼接版头版位的标记,主要是为了兼容历史报告。0-不需要 1-需要"`
+	HeadResourceId      int       `description:"版头资源ID"`
+	EndResourceId       int       `description:"版尾资源ID"`
+	CollaborateType     int8      `description:"协作方式,1:个人,2:多人协作。默认:1"`
+	ReportLayout        int8      `description:"报告布局,1:常规布局,2:智能布局。默认:1"`
+	IsPublicPublish     int8      `description:"是否公开发布,1:是,2:否"`
+	ReportCreateTime    time.Time `description:"报告时间创建时间"`
+	InheritReportId     int       `description:"待继承的报告ID"`
+	VoiceGenerateType   int       `description:"音频生成方式,0:系统生成,1:人工上传"`
+}
+
+func (m *Report) GetItemById(id int) (item *Report, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT * FROM report WHERE id = ? LIMIT 1`
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+type ReportDetail struct {
 	Id                 int                  `description:"报告Id"`
 	AddType            int                  `description:"新增方式:1:新增报告,2:继承报告"`
 	ClassifyIdFirst    int                  `description:"一级分类id"`
@@ -14,13 +192,12 @@ type ReportView struct {
 	ClassifyNameSecond string               `description:"二级分类名称"`
 	ClassifyIdThird    int                  `description:"三级分类id"`
 	ClassifyNameThird  string               `description:"三级分类名称"`
-	PermissionNames    []string             `description:"二级分类名称"`
 	Title              string               `description:"标题"`
 	Abstract           string               `description:"摘要"`
 	Author             string               `description:"作者"`
 	Frequency          string               `description:"频度"`
 	CreateTime         string               `description:"创建时间"`
-	ModifyTime         time.Time            `description:"修改时间"`
+	ModifyTime         string               `description:"修改时间"`
 	State              int                  `description:"1:未发布,2:已发布"`
 	PublishTime        string               `description:"发布时间"`
 	Stage              int                  `description:"期数"`
@@ -31,56 +208,19 @@ type ReportView struct {
 	VideoName          string               `description:"音频文件名称"`
 	VideoPlaySeconds   string               `description:"音频播放时长"`
 	VideoSize          string               `description:"音频文件大小,单位M"`
-	HasPermission      int                  `description:"是否拥有报告权限,1:拥有,0:没有"`
+	ContentSub         string               `description:"内容前两个章节"`
+	IsShowNewLabel     int                  `description:"是否显示新标签"`
+	IsCurrentDate      int                  `description:"是否当前日期"`
+	ClassifyName       string               `description:"分类名称"`
 	TitleType          string               `description:"标题类型,FICC或者权益"`
-	IsCurrentDate      int                  `description:"是否当前日期:1是,0不是"`
-	IsPublic           bool                 `description:"是否是公共报告"`
-	ReportType         int                  `description:"报告类型,1:eta报告,2:pdf报告"`
-	PdfUrl             string               `description:"pdf文件URL"`
+	IsPublic           bool                 `description:"是否是公共报告 "`
+	HeadResourceId     int                  `description:"版头资源库id"`
+	EndResourceId      int                  `description:"版尾资源库id"`
+	HeadResource       *SmartReportResource `description:"版头资源库"`
+	EndResource        *SmartReportResource `description:"版尾资源库"`
 	CollaborateType    int                  `description:"合作类型, 1:个人,2:多人协作"`
 	ReportLayout       int                  `description:"报告布局, 1:常规布局,2:智能布局"`
 	HasChapter         int                  `description:"是否有章节: 0-否 1-是"`
-	HeadResource       *SmartReportResource `description:"版头资源库"`
-	EndResource        *SmartReportResource `description:"版尾资源库"`
-	ClassifyDetail
-}
-
-type ReportDetail struct {
-	Id                 int                 `description:"报告Id"`
-	AddType            int                 `description:"新增方式:1:新增报告,2:继承报告"`
-	ClassifyIdFirst    int                 `description:"一级分类id"`
-	ClassifyNameFirst  string              `description:"一级分类名称"`
-	ClassifyIdSecond   int                 `description:"二级分类id"`
-	ClassifyNameSecond string              `description:"二级分类名称"`
-	ClassifyIdThird    int                 `description:"三级分类id"`
-	ClassifyNameThird  string              `description:"三级分类名称"`
-	Title              string              `description:"标题"`
-	Abstract           string              `description:"摘要"`
-	Author             string              `description:"作者"`
-	Frequency          string              `description:"频度"`
-	CreateTime         string              `description:"创建时间"`
-	ModifyTime         string              `description:"修改时间"`
-	State              int                 `description:"1:未发布,2:已发布"`
-	PublishTime        string              `description:"发布时间"`
-	Stage              int                 `description:"期数"`
-	MsgIsSend          int                 `description:"消息是否已发送,0:否,1:是"`
-	Content            string              `description:"内容"`
-	ChapterContent     []*ReportChapter    `description:"章节内容"`
-	VideoUrl           string              `description:"音频文件URL"`
-	VideoName          string              `description:"音频文件名称"`
-	VideoPlaySeconds   string              `description:"音频播放时长"`
-	VideoSize          string              `description:"音频文件大小,单位M"`
-	ContentSub         string              `description:"内容前两个章节"`
-	IsShowNewLabel     int                 `description:"是否显示新标签"`
-	IsCurrentDate      int                 `description:"是否当前日期"`
-	ClassifyName       string              `description:"分类名称"`
-	TitleType          string              `description:"标题类型,FICC或者权益"`
-	IsPublic           bool                `description:"是否是公共报告"`
-	CollaborateType    int                 `description:"合作类型, 1:个人,2:多人协作"`
-	ReportLayout       int                 `description:"报告布局, 1:常规布局,2:智能布局"`
-	HasChapter         int                 `description:"是否有章节: 0-否 1-是"`
-	HeadResource       SmartReportResource `description:"版头资源库"`
-	EndResource        SmartReportResource `description:"版尾资源库"`
 }
 
 type ReportChapter struct {
@@ -88,6 +228,20 @@ type ReportChapter struct {
 	Content string `description:"章节内容"`
 }
 
+func GetReportChapterList(reportId int) (items []*ReportChapter, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT * FROM report_chapter WHERE report_id=? ORDER BY sort ASC`
+	_, err = o.Raw(sql, reportId).QueryRows(&items)
+	return
+}
+
+func GetReportById(reportId int) (item *ReportDetail, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT * FROM report WHERE (state=2 OR state=6) AND id=?`
+	err = o.Raw(sql, reportId).QueryRow(&item)
+	return
+}
+
 type SmartReportResource struct {
 	ResourceId int    `description:"资源库id"`
 	ImgUrl     string `description:"图片url"`
@@ -95,24 +249,80 @@ type SmartReportResource struct {
 	Style      string `description:"版图样式"`
 }
 
-type ByPublishTimeReportView []*ReportView
-
-func (a ByPublishTimeReportView) Len() int { return len(a) }
-func (a ByPublishTimeReportView) Less(i, j int) bool {
-	if a[i].PublishTime == "" {
-		return true
-	}
-	if a[j].PublishTime == "" {
-		return false
-	}
-	aiTime, err := time.Parse(utils.FormatDateTime, a[i].PublishTime)
-	if err != nil {
-		return true
-	}
-	ajTime, err := time.Parse(utils.FormatDateTime, a[j].PublishTime)
-	if err != nil {
-		return false
-	}
-	return aiTime.After(ajTime)
-}
-func (a ByPublishTimeReportView) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func GetSmartReportResourceById(resourceId int) (item *SmartReportResource, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT * FROM smart_report_resource WHERE resource_id=?`
+	err = o.Raw(sql, resourceId).QueryRow(&item)
+	return
+}
+
+type OutsideReport struct {
+	OutsideReportId int       `description:"报告ID"`
+	Title           string    `description:"标题"`
+	Abstract        string    `description:"摘要"`
+	ClassifyId      int       `description:"分类ID"`
+	ClassifyName    string    `description:"分类名称"`
+	SysUserId       int       `description:"创建人ID"`
+	SysUserName     string    `description:"创建人姓名"`
+	ReportFile      string    `description:"报告附件"`
+	CreateTime      time.Time `description:"创建时间"`
+	ModifyTime      time.Time `description:"修改时间"`
+}
+
+func GetOutsideReportById(reportId int) (item *OutsideReport, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT 
+			o.outside_report_id,
+			o.title,
+			o.abstract,
+			o.create_time,
+			o.modify_time,
+			o.classify_id,
+			o.classify_name,
+    		o.sys_user_id,
+    		o.sys_user_name,
+			oa.url AS report_file
+		FROM 
+			outside_report o
+		INNER JOIN 
+			outside_report_attachment oa 
+		ON 
+			o.outside_report_id = oa.outside_report_id
+		WHERE 
+			o.outside_report_id = ?
+			AND oa.title LIKE '%.pdf%'
+			AND oa.create_time = (
+				SELECT MAX(oa2.create_time)
+				FROM outside_report_attachment oa2
+				WHERE oa2.outside_report_id = o.outside_report_id AND oa2.title LIKE '%.pdf%'
+			)
+		LIMIT 1`
+	err = o.Raw(sql, reportId).QueryRow(&item)
+	return
+}
+
+type OutsideReportItem struct {
+	OutsideReportId int    `description:"报告ID"`
+	Title           string `description:"标题"`
+	Abstract        string `description:"摘要"`
+	ClassifyId      int    `description:"分类ID"`
+	ClassifyName    string `description:"分类名称"`
+	Author          string `description:"作者"`
+	ReportFile      string `description:"报告附件"`
+	CreateTime      string `description:"创建时间"`
+	ModifyTime      string `description:"修改时间"`
+}
+
+func (m *OutsideReport) Format2Item() (item *OutsideReportItem) {
+	item = new(OutsideReportItem)
+	item.OutsideReportId = m.OutsideReportId
+	item.Title = m.Title
+	item.Abstract = m.Abstract
+	item.ClassifyId = m.ClassifyId
+	item.ClassifyName = m.ClassifyName
+	item.Author = m.SysUserName
+	item.ReportFile = m.ReportFile
+	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, m.CreateTime)
+	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, m.ModifyTime)
+	return
+}

+ 0 - 147
models/report_pdf.go

@@ -1,147 +0,0 @@
-package models
-
-import (
-	"eta/eta_mini_api/utils"
-	"fmt"
-	"time"
-
-	"github.com/beego/beego/v2/client/orm"
-)
-
-type ReportPdf struct {
-	ReportPdfId        int       `orm:"pk" description:"id"`
-	PdfUrl             string    `description:"pdf文件URL"`
-	Title              string    `description:"pdf文件标题"`
-	Author             string    `description:"作者"`
-	Abstract           string    `description:"摘要"`
-	ClassifyIdFirst    int       `description:"一级分类id"`
-	ClassifyNameFirst  string    `description:"一级分类名称"`
-	ClassifyIdSecond   int       `description:"二级分类id"`
-	ClassifyNameSecond string    `description:"二级分类名称"`
-	ClassifyIdThird    int       `description:"三级分类id"`
-	ClassifyNameThird  string    `description:"三级分类名称"`
-	Stage              int       `description:"期数"`
-	PublishTime        time.Time `description:"发布时间"`
-	ModifyTime         time.Time `description:"更新时间"`
-	Pv                 int       `description:"pv"`
-	Uv                 int       `description:"uv"`
-	SysUserId          int       `description:"创建人id"`
-	SysRealName        string    `description:"创建人姓名"`
-	State              int       `description:"状态:1-已发布;2-未发布"`
-}
-
-type ReportPdfView struct {
-	ReportPdfId        int    `orm:"pk" description:"id"`
-	PdfUrl             string `description:"pdf文件URL"`
-	Title              string `description:"pdf文件标题"`
-	Author             string `description:"作者"`
-	Abstract           string `description:"摘要"`
-	ClassifyIdFirst    int    `description:"一级分类id"`
-	ClassifyNameFirst  string `description:"一级分类名称"`
-	ClassifyIdSecond   int    `description:"二级分类id"`
-	ClassifyNameSecond string `description:"二级分类名称"`
-	ClassifyIdThird    int    `description:"三级分类id"`
-	ClassifyNameThird  string `description:"三级分类名称"`
-	Stage              int    `description:"期数"`
-	PublishTime        string `description:"发布时间"`
-	ModifyTime         string `description:"更新时间"`
-	Pv                 int    `description:"pv"`
-	Uv                 int    `description:"uv"`
-	SysUserId          int    `description:"创建人id"`
-	SysRealName        string `description:"创建人姓名"`
-	State              int    `description:"状态:1-已发布;2-未发布"`
-	IsPublic           bool   `description:"是否公开"`
-	IsCollect          bool   `description:"是否收藏"`
-}
-
-func GetRecentReportPdfList(startSize, pageSize int) (items []*ReportPdf, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT * FROM report_pdf WHERE state=1 ORDER BY publish_time DESC LIMIT ?,?`
-	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
-	return
-}
-
-func GetReportPdfListByCondition(firstClassifyIds, secondClassifyIds, thirdClassifyIds []int, condition string, startSize, pageSize int) (reportPdfs []*ReportPdf, err error) {
-	if len(firstClassifyIds) == 0 && len(secondClassifyIds) == 0 && len(thirdClassifyIds) == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `SELECT * FROM report_pdf WHERE 1=1 AND (1=2`
-	if len(firstClassifyIds) > 0 {
-		sql += fmt.Sprintf(" OR classify_id_first IN (%s) ", utils.GetOrmReplaceHolder(len(firstClassifyIds)))
-	}
-	if len(secondClassifyIds) > 0 {
-		sql += fmt.Sprintf(" OR classify_id_second IN (%s) ", utils.GetOrmReplaceHolder(len(secondClassifyIds)))
-	}
-	if len(thirdClassifyIds) > 0 {
-		sql += fmt.Sprintf(" OR classify_id_third IN (%s) ", utils.GetOrmReplaceHolder(len(thirdClassifyIds)))
-	}
-	sql += ")"
-	if condition != "" {
-		sql += condition
-	}
-	sql += ` ORDER BY publish_time DESC LIMIT ?,?`
-	_, err = o.Raw(sql, firstClassifyIds, secondClassifyIds, thirdClassifyIds, startSize, pageSize).QueryRows(&reportPdfs)
-	return
-}
-
-func GetReportPdfDailyList() (reportPdfs []*ReportPdf, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM report_pdf WHERE 1=1 AND state=1 AND DATE(publish_time) = DATE(NOW()) ORDER BY publish_time DESC `
-	_, err = o.Raw(sql).QueryRows(&reportPdfs)
-	return
-}
-
-func GetReportPdfCountByCondition(firstClassifyIds, secondClassifyIds, thirdClassifyIds []int, condition string) (count int, err error) {
-	if len(firstClassifyIds) == 0 && len(secondClassifyIds) == 0 && len(thirdClassifyIds) == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM report_pdf WHERE 1=1 AND (1=2 `
-
-	if len(firstClassifyIds) > 0 {
-		sql += fmt.Sprintf(" OR classify_id_first IN (%s) ", utils.GetOrmReplaceHolder(len(firstClassifyIds)))
-	}
-	if len(secondClassifyIds) > 0 {
-		sql += fmt.Sprintf(" OR classify_id_second IN (%s) ", utils.GetOrmReplaceHolder(len(secondClassifyIds)))
-	}
-	if len(thirdClassifyIds) > 0 {
-		sql += fmt.Sprintf(" OR classify_id_third IN (%s) ", utils.GetOrmReplaceHolder(len(thirdClassifyIds)))
-	}
-	sql += ` )`
-	if condition != "" {
-		sql += condition
-	}
-	err = o.Raw(sql, firstClassifyIds, secondClassifyIds, thirdClassifyIds).QueryRow(&count)
-	return
-}
-
-func GetReportPdfCountById(id int) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM report_pdf WHERE report_pdf_id = ? `
-	err = o.Raw(sql, id).QueryRow(&count)
-	return
-}
-
-func GetReportPdfById(id int) (item *ReportPdfView, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM report_pdf WHERE report_pdf_id = ? `
-	err = o.Raw(sql, id).QueryRow(&item)
-	return
-}
-
-// 更新pv
-func UpdateReportPdfPv(id int) (err error) {
-	o := orm.NewOrm()
-	sql := `UPDATE report_pdf SET pv = pv + 1 WHERE report_pdf_id = ?`
-	_, err = o.Raw(sql, id).Exec()
-	return
-}
-
-// 更新uv和pv
-func UpdateReportPdfUvAndPv(id int) (err error) {
-	o := orm.NewOrm()
-	sql := `UPDATE report_pdf SET uv = uv + 1, pv = pv + 1 WHERE report_pdf_id = ?`
-	_, err = o.Raw(sql, id).Exec()
-	return
-}

+ 0 - 84
models/report_push_status.go

@@ -1,84 +0,0 @@
-package models
-
-import (
-	"time"
-
-	"github.com/beego/beego/v2/client/orm"
-)
-
-type ReportPushStatus struct {
-	ReportPushStatusId int       `orm:"pk"`
-	ReportId           int       `description:"报告id"`
-	State              int       `description:"报告状态:0-未推送,1-已推送"`
-	Title              string    `description:"报告标题"`
-	Abstract           string    `description:"报告摘要"`
-	Stage              int       `description:"期数"`
-	ClassifyIdFirst    int       `description:"一级分类id"`
-	ClassifyNameFirst  string    `description:"一级分类名称"`
-	ClassifyIdSecond   int       `description:"二级分类id"`
-	ClassifyNameSecond string    `description:"二级分类名称"`
-	ClassifyIdThird    int       `description:"三级分类id"`
-	ClassifyNameThird  string    `description:"三级分类名称"`
-	Author             string    `description:"报告作者"`
-	ReportType         int       `description:"报告类型:1-eta报告"`
-	PublishTime        time.Time `description:"报告发布时间"`
-	CreateTime         time.Time `description:"创建时间"`
-	ModifyTime         time.Time `description:"修改时间"`
-	PushTime           time.Time `description:"推送时间"`
-}
-
-type ReportPushView struct {
-	ReportPushStatusId int    `orm:"pk"`
-	ReportId           int    `description:"报告id"`
-	Title              string `description:"报告标题"`
-	Abstract           string `description:"报告摘要"`
-	ClassifyIdFirst    int    `description:"一级分类id"`
-	ClassifyNameFirst  string `description:"一级分类名称"`
-	ClassifyIdSecond   int    `description:"二级分类id"`
-	ClassifyNameSecond string `description:"二级分类名称"`
-	ClassifyIdThird    int    `description:"二级分类id"`
-	ClassifyNameThird  string `description:"二级分类名称"`
-	Author             string `description:"报告作者"`
-	Stage              int    `description:"期数"`
-	State              int    `description:"报告状态:0-未推送,1-已推送"`
-	PushTime           string `description:"推送时间"`
-	PublishTime        string `description:"报告发布时间"`
-	ReportType         int    `description:"报告类型:1-eta报告"`
-	CreateTime         string `description:"创建时间"`
-	ModifyTime         string `description:"修改时间"`
-}
-
-func GetReportPushStatusByReportId(reportId int, reportType int) (item *ReportPushStatus, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM report_push_status WHERE report_id = ? AND report_type = ?`
-	err = o.Raw(sql, reportId, reportType).QueryRow(&item)
-	return
-}
-
-func GetReportPushStatusCountByCondition(condition string, pars []interface{}) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM report_push_status WHERE 1=1 AND state=1 `
-	if condition != "" {
-		sql += condition
-	}
-	err = o.Raw(sql, pars...).QueryRow(&count)
-	return
-}
-
-func GetReportPushStatusByCondition(condition string, pars []interface{}, startSize int, pageSize int) (items []*ReportPushStatus, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM report_push_status WHERE 1=1 AND state=1 `
-	if condition != "" {
-		sql += condition
-	}
-	sql += ` ORDER BY publish_time DESC LIMIT ?,?`
-	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
-	return
-}
-
-func DeleteReportPushStatusByReportId(reportId int, reportType int) (err error) {
-	o := orm.NewOrm()
-	sql := `DELETE FROM report_push_status WHERE report_id = ? AND report_type = ?`
-	_, err = o.Raw(sql, reportId, reportType).Exec()
-	return
-}

+ 8 - 0
models/request/classify.go

@@ -0,0 +1,8 @@
+package request
+
+type ClassifyTreeForm struct {
+	DiamondDistrict int `form:"DiamondDistrict" description:"是否为金刚区"`
+	Frequency       int `form:"Frequency" description:"报告频度:1-高频;2-中频;3-低频"`
+	HotComment      int `form:"HotComment" description:"是否热点点评"`
+	KeyPoint        int `form:"KeyPoint" description:"是否重点数据更新"`
+}

+ 0 - 15
models/request/my_chart.go

@@ -1,15 +0,0 @@
-package request
-
-type MyChartCollectReq struct {
-	ChartName   string `description:"图表名称"`   // 图表名称
-	UniqueCode  string `description:"图表唯一编码"` // 图表唯一编码
-	ChartImage  string `description:"图表图片"`   // 图表图片
-	ChartInfoId int    `description:"图表id"`   // 图表id
-}
-type MyChartCollectCancelReq struct {
-	UniqueCode string `description:"图表唯一编码"` // 图表唯一编码
-}
-
-type MyChartIsCollectReq struct {
-	UniqueCode string `description:"图表唯一编码"` // 图表唯一编码
-}

+ 0 - 9
models/request/my_report.go

@@ -1,9 +0,0 @@
-package request
-
-type MyReportCollectReq struct {
-	ReportId int `description:"报告id"`
-}
-
-type MyReportPdfCollectReq struct {
-	ReportPdfId int `description:"报告id"`
-}

+ 14 - 0
models/request/report.go

@@ -0,0 +1,14 @@
+package request
+
+type ReportListForm struct {
+	PageSize     int    `form:"PageSize" description:"每页数据量"`
+	CurrentIndex int    `form:"CurrentIndex" description:"页码"`
+	Keywords     string `form:"Keywords" description:"搜索关键词"`
+	ClassifyId   int    `form:"ClassifyId" description:"分类ID"`
+}
+
+type ReportReadRecordReq struct {
+	RecordId     int `description:"记录ID"`
+	ReportId     int `description:"报告ID"`
+	ReportSource int `description:"报告来源:1-研报中心;2-文档管理库"`
+}

+ 5 - 36
models/request/user.go

@@ -1,43 +1,12 @@
 package request
 
-// type LoginReq struct {
-// 	WxCode     string `description:"用户code"`
-// 	LoginType  int    `description:"登录方式:1:手机,2:邮箱"`
-// 	Mobile     string `description:"手机号"`
-// 	Email      string `description:"邮箱"`
-// 	AreaNum    int    `description:"国际区号"`
-// 	VerifyCode string `description:"短信/邮箱 验证码"`
-// }
 type LoginReq struct {
-	LoginType       int    `description:"登录方式:1:手机,2:邮箱"`
-	Phone           string `description:"手机号"`
-	Email           string `description:"邮箱"`
-	AreaCode        string `description:"国际区号"`
-	SmsCode         string `description:"短信/邮箱验证码"`
-	SysDepartmentId int    `description:"营业部门id"`
-	RealName        string `description:"姓名"`
+	Phone    string `description:"手机号"`
+	AreaCode string `description:"国际区号"`
+	SmsCode  string `description:"短信验证码"`
 }
 
 type VerifyCodeReq struct {
-	VerifyType  int    `description:"验证方式: 1-手机号; 2-邮箱"`
-	CaptchaId   string `description:"验证码ID"`
-	CaptchaCode string `description:"图形验证码"`
-	Phone       string `description:"手机号"`
-	AreaCode    string `description:"手机区号"`
-	Email       string `description:"邮箱"`
-}
-
-type UserInfoSaveReq struct {
-	RealName        string `description:"姓名"`
-	SysDepartmentId int    `description:"营业部门id"`
-}
-
-type ReportRecordReq struct {
-	RecordId int `description:"记录Id"`
-	ReportId int `description:"报告Id"`
-}
-
-type ReportPdfRecordReq struct {
-	RecordId    int `description:"记录Id"`
-	ReportPdfId int `description:"报告Id"`
+	Phone    string `description:"手机号"`
+	AreaCode string `description:"手机区号"`
 }

+ 0 - 104
models/response/chart.go

@@ -1,104 +0,0 @@
-package response
-
-import (
-	"time"
-
-	"github.com/rdlucklib/rdluck_tools/paging"
-)
-
-type ChartListResp struct {
-	List   []*ChartInfoView
-	Paging *paging.PagingItem
-}
-
-type ChartInfoView struct {
-	ChartInfoId       int    `orm:"column(chart_info_id);pk"`
-	ChartName         string `description:"来源名称"`
-	ChartNameEn       string `description:"英文图表名称"`
-	Unit              string `description:"中文单位名称"`
-	UnitEn            string `description:"英文单位名称"`
-	ChartClassifyId   int    `description:"图表分类id"`
-	ChartClassifyName string `description:"图表名称"`
-	SysUserId         int
-	SysUserRealName   string
-	UniqueCode        string `description:"图表唯一编码"`
-	CreateTime        time.Time
-	ModifyTime        time.Time
-	DateType          int    `description:"日期类型:1:00年至今,2:10年至今,3:15年至今,4:年初至今,5:自定义时间"`
-	StartDate         string `description:"自定义开始日期"`
-	EndDate           string `description:"自定义结束日期"`
-	IsSetName         int    `description:"设置名称"`
-	EdbInfoIds        string `description:"指标id"`
-	ChartType         int    `description:"生成样式:1:曲线图,2:季节性图"`
-	Calendar          string `description:"公历/农历"`
-	SeasonStartDate   string `description:"季节性图开始日期"`
-	SeasonEndDate     string `description:"季节性图开始日期"`
-	ChartImage        string `description:"图表图片"`
-	Sort              int    `description:"排序字段,数字越小越排前面"`
-	IsAdd             bool   `description:"true:已加入我的图库,false:未加入我的图库"`
-	MyChartId         int
-	MyChartClassifyId string `description:"我的图表分类,多个用逗号隔开"`
-	ChartClassify     []*ChartClassifyView
-	EdbEndDate        string `description:"指标最新更新日期"`
-	XMin              string `description:"图表X轴最小值"`
-	XMax              string `description:"图表X轴最大值"`
-	LeftMin           string `description:"图表左侧最小值"`
-	LeftMax           string `description:"图表左侧最大值"`
-	RightMin          string `description:"图表右侧最小值"`
-	RightMax          string `description:"图表右侧最大值"`
-	Right2Min         string `description:"图表右侧最小值"`
-	Right2Max         string `description:"图表右侧最大值"`
-	MinMaxSave        int    `description:"是否手动保存过上下限:0-否;1-是"`
-	IsEdit            bool   `description:"是否有编辑权限"`
-	IsEnChart         bool   `description:"是否展示英文标识"`
-	WarnMsg           string `description:"错误信息"`
-	Disabled          int    `description:"是否禁用,0:启用,1:禁用,默认:0"`
-	BarConfig         string `description:"柱方图的配置,json数据" json:"-"`
-	Source            int    `description:"1:ETA图库;2:商品价格曲线;3:相关性图表"`
-	//CorrelationLeadUnit string `description:"相关性图表-领先单位"`
-	ExtraConfig       string          `description:"图表额外配置,json数据"`
-	ChartSource       string          `description:"图表来源str"`
-	ChartSourceEn     string          `description:"图表来源(英文)"`
-	Button            ChartViewButton `description:"操作按钮"`
-	SeasonExtraConfig string          `description:"季节性图表中的配置,json数据"`
-	StartYear         int             `description:"当选择的日期类型为最近N年类型时,即date_type=20, 用start_year表示N"`
-	ChartThemeId      int             `description:"图表应用主题ID"`
-	ChartThemeStyle   string          `description:"图表应用主题样式"`
-	SourcesFrom       string          `description:"图表来源"`
-	Instructions      string          `description:"图表说明"`
-	MarkersLines      string          `description:"标识线"`
-	MarkersAreas      string          `description:"标识区"`
-	IsJoinPermission  int             `description:"是否加入权限管控,0:不加入;1:加入;默认:0"`
-	HaveOperaAuth     bool            `description:"是否有数据权限,默认:false"`
-	ForumChartInfoId  int             `description:"社区的图表ID"`
-	IsCollect         bool            `description:"是否收藏"`
-}
-
-type ChartClassifyView struct {
-	ChartClassifyId   int    `orm:"column(chart_classify_id);pk"`
-	ChartClassifyName string `description:"分类名称"`
-	ParentId          int    `description:"父级id"`
-}
-
-type ChartViewButton struct {
-	IsEdit    bool `description:"是否有编辑权限"`
-	IsEnChart bool `description:"是否展示英文标识"`
-	IsAdd     bool `description:"true:已加入我的图库,false:未加入我的图库"`
-	IsCopy    bool `description:"是否有另存为按钮"`
-	IsSetName int  `description:"设置名称"`
-}
-
-type ChartResp[T any] struct {
-	Ret    int
-	Data   T
-	Msg    string
-	ErrMsg string
-}
-
-type ChartLocateItem struct {
-	ChartInfoId     int
-	ChartName       string
-	UniqueCode      string
-	PrevChartInfoId int
-	NextChartInfoId int
-}

+ 0 - 1
models/response/chart_permission.go

@@ -1 +0,0 @@
-package response

+ 0 - 26
models/response/my_chart.go

@@ -1,26 +0,0 @@
-package response
-
-import (
-	"eta/eta_mini_api/models"
-
-	"github.com/rdlucklib/rdluck_tools/paging"
-)
-
-type MyChartIsCollectResp struct {
-	IsCollect bool `description:"是否收藏"`
-}
-
-type MyChartListResp struct {
-	List   []*models.MyChart  `description:"图表列表"`
-	Paging *paging.PagingItem `description:"分页信息"`
-}
-
-// MyChartLocateItem 用户图表定位
-type MyChartLocateItem struct {
-	MyChartId       int
-	ChartInfoId     int
-	ChartName       string
-	UniqueCode      string
-	PrevChartInfoId int
-	NextChartInfoId int
-}

+ 0 - 16
models/response/my_report.go

@@ -1,16 +0,0 @@
-package response
-
-import (
-	"eta/eta_mini_api/models"
-
-	"github.com/rdlucklib/rdluck_tools/paging"
-)
-
-type MyReportListResp struct {
-	List   []*models.MyReport
-	Paging *paging.PagingItem
-}
-
-type MyReportIsCollectResp struct {
-	IsCollect bool
-}

+ 5 - 75
models/response/report.go

@@ -2,89 +2,19 @@ package response
 
 import (
 	"eta/eta_mini_api/models"
-	"time"
-
 	"github.com/rdlucklib/rdluck_tools/paging"
 )
 
 type ReportList struct {
-	List   []*models.ReportView
+	List   []*models.UnionReportItem
 	Paging *paging.PagingItem
 }
 
-type ReportPushListResp struct {
-	List   []*models.ReportPushView
-	Paging *paging.PagingItem
-}
-
-type ReportResp[T any] struct {
-	Ret    int
-	Data   T
-	Msg    string
-	ErrMsg string
-}
 type ReportDetailResp struct {
-	Report    *models.ReportDetail `description:"报告"`
-	Status    int                  `description:"报告状态"`
-	IsCollect bool                 `description:"报告是否收藏"`
-	IsSignIn  bool                 `description:"是否登录"`
-}
-
-type ReportCollectListItem struct {
-	ReportId            int       `description:"报告Id"`
-	ReportChapterId     int       `description:"报告章节Id"`
-	ClassifyIdFirst     int       `description:"一级分类id"`
-	ClassifyNameFirst   string    `description:"一级分类名称"`
-	ClassifyIdSecond    int       `description:"二级分类id"`
-	ClassifyNameSecond  string    `description:"二级分类名称"`
-	ClassifyIdThird     int       `description:"三级分类id"`
-	ClassifyNameThird   string    `description:"三级分类名称"`
-	ReportChapterTypeId int       `decription:"报告章节类型id"`
-	PublishTime         time.Time `description:"发布时间"`
-	Title               string    `description:"标题"`
-	ContentSub          string    `description:"内容前两个章节"`
-	Abstract            string    `description:"摘要"`
-	Stage               string    `description:"期数"`
-	Author              string    `description:"作者"`
-	PdfUrl              string    `description:"pdf文件url"`
-	ReportType          int       `description:"报告类型:1:eta报告,2:小程序pdf报告"`
-}
-
-type ReportSearchListView struct {
-	ReportId            int    `description:"报告Id"`
-	ReportChapterId     int    `description:"报告章节Id"`
-	ClassifyIdFirst     int    `description:"一级分类id"`
-	ClassifyNameFirst   string `description:"一级分类名称"`
-	ClassifyIdSecond    int    `description:"二级分类id"`
-	ClassifyNameSecond  string `description:"二级分类名称"`
-	ClassifyIdThird     int    `description:"三级分类id"`
-	ClassifyNameThird   string `description:"三级分类名称"`
-	ReportChapterTypeId int    `decription:"报告章节类型id"`
-	PublishTime         string `description:"发布时间"`
-	Title               string `description:"标题"`
-	ContentSub          string `description:"内容前两个章节"`
-	Abstract            string `description:"摘要"`
-	Stage               string `description:"期数"`
-	Author              string `description:"作者"`
-	PdfUrl              string `description:"pdf文件url"`
-	ReportType          int    `description:"报告类型:1:eta报告,2:小程序pdf报告"`
-}
-
-type ReportSearchResp struct {
-	Paging *paging.PagingItem
-	List   []*ReportCollectListItem
-}
-type ReportSearchViewResp struct {
-	Paging *paging.PagingItem
-	List   []*ReportSearchListView
-}
-
-type ReportPdfResp struct {
-	Paging *paging.PagingItem
-	List   []*models.ReportPdf
+	Report *models.ReportDetail `description:"报告"`
+	Status int                  `description:"报告状态"`
 }
 
-type ReportPdfDetailResp struct {
-	Report *models.ReportPdfView `description:"报告"`
-	Status int                   `description:"报告状态"`
+type ReportReadRecordResp struct {
+	RecordId int64
 }

+ 7 - 10
models/response/user.go

@@ -1,24 +1,21 @@
 package response
 
-type LoginResp struct {
-	UserId        int    `description:"用户id"`
-	Authorization string `description:"Token"`
-	Headimgurl    string `description:"用户头像"`
-	Phone         string `description:"手机号"`
-	Email         string `description:"邮箱"`
-	CompanyName   string `description:"客户名称"`
-	EndDate       string `description:"到期日期"`
-}
+import "eta/eta_mini_api/models"
 
 type WeChatLoginResp struct {
 	Authorization string `description:"Token"`
 }
 
 type UserReadRecordResp struct {
-	RecordId int64
+	RecordId int
 }
 
 type AreaCodeListResp struct {
 	Name  string `description:"地区"`
 	Value string `description:"区号"`
 }
+
+type UserInfoResp struct {
+	User        *models.UsersItem `description:"用户登录信息"`
+	LoginStatus int               `description:"登录状态:0-未登录;1-已登录"`
+}

+ 0 - 32
models/sys_department.go

@@ -1,32 +0,0 @@
-package models
-
-import "github.com/beego/beego/v2/client/orm"
-
-type SysDepartment struct {
-	SysDepartmentId   int    `json:"sysDepartmentId"`
-	SysDepartmentName string `json:"sysDepartmentName"`
-	ParentId          int    `json:"sysDepartmentParentId"`
-	Sort              int    `json:"sysDepartmentSort"`
-	Level             int    `json:"level"`
-}
-
-func GetSysDepartmentByName(sysDepartmentName string) (item *SysDepartment, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM sys_department WHERE sys_department_name = ?`
-	err = o.Raw(sql, sysDepartmentName).QueryRow(&item)
-	return
-}
-
-func GetSysDepartmentById(sysDepartmentId int) (item *SysDepartment, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM sys_department WHERE sys_department_Id = ?`
-	err = o.Raw(sql, sysDepartmentId).QueryRow(&item)
-	return
-}
-
-func GetChildSysDepartmentByParentId(parentId int) (items []*SysDepartment, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM sys_department WHERE parent_id = ? ORDER BY sort ASC`
-	_, err = o.Raw(sql, parentId).QueryRows(&items)
-	return
-}

+ 0 - 17
models/sys_user.go

@@ -1,17 +0,0 @@
-package models
-
-import "github.com/beego/beego/v2/client/orm"
-
-type SysUser struct {
-	SysUserId   int    `description:"系统用户id"`
-	SysRealName string `description:"系统用户姓名"`
-	Phone       string `description:"手机号"`
-	AreaCode    string `description:"区号"`
-}
-
-func GetSellerById(sysUserId int) (items *SysUser, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM sys_user WHERE sys_user_id=?`
-	err = o.Raw(sql, sysUserId).QueryRow(&items)
-	return
-}

+ 0 - 123
models/user.go

@@ -1,123 +0,0 @@
-package models
-
-import (
-	"time"
-
-	"github.com/beego/beego/v2/client/orm"
-)
-
-type User struct {
-	UserId               int       `orm:"pk" description:"用户id"`
-	OpenId               string    `description:"openid"`
-	UnionId              string    `description:"unionid"`
-	NickName             string    `description:"用户昵称"`
-	RealName             string    `description:"姓名"`
-	Phone                string    `description:"手机号"`
-	AreaCode             string    `description:"区号"`
-	Email                string    `description:"邮箱"`
-	SellerId             int       `description:"销售id(SysUserId)"`
-	SellerDepartmentId   int       `description:"营业部门id"`
-	SellerDepartmentName string    `description:"营业部门名称"`
-	Company              string    `description:"所属公司"`
-	ValidStartTime       time.Time `description:"有效期开始时间"`
-	ValidEndTime         time.Time `description:"有效期结束时间"`
-	Status               int       `description:"用户类型: 0表示禁用,1表示潜在客户,2表示正式客户"`
-	ApplyStatus          int       `description:"申请状态: 0表示未申请,1表示已申请"`
-	CreateTime           time.Time `description:"系统中首次新增用户的时间"`
-	ModifyTime           time.Time `description:"系统中用户信息变更的时间"`
-	RegisterTime         time.Time `description:"用户首次登录小程序的时间"`
-	ApplyTime            time.Time `description:"用户提交申请的时间"`
-	IsSubscribed         bool      `description:"是否关注公众号: 0表示没有关注,1表示关注"`
-	IsRegistered         bool      `description:"是否注册: 0表示没有注册,1表示注册"`
-	AccessToken          string    `description:"用户token"`
-	Headimgurl           string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
-}
-
-func (u *User) Insert() (insertId int64, err error) {
-	o := orm.NewOrm()
-	insertId, err = o.Insert(u)
-	return
-}
-
-func (u *User) Update(cols []string) (err error) {
-	o := orm.NewOrm()
-	_, err = o.Update(u, cols...)
-	return
-}
-
-type UserView struct {
-	Headimgurl            string   `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
-	RealName              string   `description:"用户实际名称"`
-	Phone                 string   `description:"手机号码"`
-	AreaCode              string   `description:"区号"`
-	SellerDepartmentName  string   `description:"营业部名称"`
-	SellerDepartmentPhone []string `description:"营业部电话"`
-	Email                 string   `description:"邮箱"`
-	Componey              string   `description:"所属公司"`
-	HasPermission         string   `description:"拥有权限"`
-	ValidEndTime          string   `description:"服务截至时间"`
-	IsRegistered          bool     `description:"是否注册:1:已注册,0:未注册"`
-	Status                int      `description:"用户类型: 0表示禁用,1表示潜在客户,2表示正式客户"`
-	ApplyStatus           int      `description:"申请状态: 0表示未申请,1表示已申请"`
-}
-
-func GetUserByToken(token string) (item *User, err error) {
-	sql := `SELECT * FROM user WHERE access_token=? `
-	o := orm.NewOrm()
-	err = o.Raw(sql, token).QueryRow(&item)
-	return
-}
-
-// 根据openid获取用户关系
-func GetUserByOpenId(openId string) (item *User, err error) {
-	sql := `SELECT * FROM user WHERE open_id=? `
-	o := orm.NewOrm()
-	err = o.Raw(sql, openId).QueryRow(&item)
-	return
-}
-
-// 根据unionid获取用户关系
-func GetUserByUnionId(unionId string) (item *User, err error) {
-	sql := `SELECT * FROM user WHERE union_id=? `
-	o := orm.NewOrm()
-	err = o.Raw(sql, unionId).QueryRow(&item)
-	return
-}
-
-// 变更联系人是否已注册状态
-func ModifyUserRegisterStatus(userId int, status bool, registerTime, modifyTime time.Time) (err error) {
-	o := orm.NewOrm()
-	sql := `UPDATE user SET is_registered=?, register_time=?, modify_time=? WHERE user_id = ? `
-	_, err = o.Raw(sql, status, registerTime, modifyTime, userId).Exec()
-	return
-}
-
-func GetUserById(userId int) (item *User, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM user WHERE user_id=? `
-	err = o.Raw(sql, userId).QueryRow(&item)
-	return
-}
-
-func GetUserList(condition string, pars []interface{}) (items []*User, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM user WHERE 1=1 `
-	if condition != "" {
-		sql += condition
-	}
-	_, err = o.Raw(sql, pars...).QueryRows(&items)
-	return
-}
-
-func GetUserByPhone(phone string) (item *User, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM user WHERE phone=? `
-	err = o.Raw(sql, phone).QueryRow(&item)
-	return
-}
-
-func GetUserByEmail(email string) (item *User, err error) {
-	sql := `SELECT * FROM user WHERE email=? `
-	err = orm.NewOrm().Raw(sql, email).QueryRow(&item)
-	return
-}

+ 0 - 16
models/user_chart_permission_mapping.go

@@ -1,16 +0,0 @@
-package models
-
-import "github.com/beego/beego/v2/client/orm"
-
-type UserChartPermissionMapping struct {
-	UserChartPermissionMappingId int `orm:"pk" description:"id"`
-	UserId                       int `description:"用户id"`
-	ChartPermissionId            int `description:"品种id"`
-}
-
-func GetUserChartPermissionIdByUserId(UserId int) (items []int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT chart_permission_id FROM user_chart_permission_mapping WHERE user_id=?`
-	_, err = o.Raw(sql, UserId).QueryRows(&items)
-	return
-}

+ 0 - 26
models/user_read_permission.go

@@ -1,26 +0,0 @@
-package models
-
-import "github.com/beego/beego/v2/client/orm"
-
-type UserReadPermission1 struct {
-	UserReadPermissionId int    `orm:"pk" description:"用户阅读记录品种映射id"`
-	UserReadRecordId     int    `description:"用户阅读记录id"`
-	ChartPermissionId    int    `description:"品种id"`
-	PermissionName       string `description:"品种名称"`
-}
-type UserReadPermission2 struct {
-	UserReadPermissionId int `orm:"pk" description:"用户阅读记录品种映射id"`
-	UserReadRecordId     int `description:"用户阅读记录id"`
-	ChartPermissionId    int `description:"品种id"`
-}
-
-func UserReadPermission1MultiInsert(items []*UserReadPermission1) (err error) {
-	o := orm.NewOrm()
-	_, err = o.InsertMulti(len(items), items)
-	return
-}
-func UserReadPermission2MultiInsert(items []*UserReadPermission2) (err error) {
-	o := orm.NewOrm()
-	_, err = o.InsertMulti(len(items), items)
-	return
-}

+ 60 - 59
models/user_read_record.go

@@ -1,88 +1,89 @@
 package models
 
 import (
-	"strings"
+	"fmt"
 	"time"
 
 	"github.com/beego/beego/v2/client/orm"
 )
 
+// UserReadRecord 用户阅读统计表
 type UserReadRecord struct {
-	UserReadRecordId int    `orm:"pk" description:"id"`
-	UserId           int    `description:"用户id"`
-	ReportId         int    `description:"报告id"`
-	ReportTitle      string `description:"报告标题"`
-	// ChartPermissionId1  string    `description:"一级品种id"`
-	// ChartPermissionId2  string    `description:"二级品种id"`
-	ChartPermissionName string    `description:"二级品种名称"`
-	ClassifyId1         int       `description:"一级级分类id"`
-	ClassifyName1       string    `description:"一级分类名称"`
-	ClassifyId2         int       `description:"二级分类id"`
-	ClassifyName2       string    `description:"二级分类名称"`
-	ClassifyId3         int       `description:"三级分类id"`
-	ClassifyName3       string    `description:"三级分类名称"`
-	Timestamp           int       `description:"阅读开始时间戳"`
-	EndTimestamp        int       `description:"阅读结束时间戳"`
-	CreateTime          time.Time `description:"创建时间"`
-	CreateDate          string    `description:"创建日期"`
-	StayTime            string    `description:"停留时间"`
-	StayTimestamp       string    `description:"停留时间戳"`
-	ReportType          int       `description:"报告类型:1-普通研报;2-pdf研报"`
+	Id                 int       `orm:"column(id);pk"`
+	UserId             int       `description:"用户ID"`
+	ReportId           int       `description:"报告ID"`
+	ReportTitle        string    `description:"报告标题"`
+	ClassifyIdFirst    int       `description:"一级分类ID"`
+	ClassifyNameFirst  string    `description:"一级分类名称"`
+	ClassifyIdSecond   int       `description:"二级分类ID"`
+	ClassifyNameSecond string    `description:"二级分类名称"`
+	ClassifyIdThird    int       `description:"三级分类ID"`
+	ClassifyNameThird  string    `description:"三级分类名称"`
+	StartTimestamp     int       `description:"阅读开始时间戳"`
+	EndTimestamp       int       `description:"阅读结束时间戳"`
+	ReportSource       int       `description:"报告来源:1-研报中心;2-文档管理库"`
+	CreateTime         time.Time `description:"创建时间"`
 }
 
-func (u *UserReadRecord) Insert() (insertId int64, err error) {
-	o := orm.NewOrm()
-	insertId, err = o.Insert(u)
-	return
-}
-
-func (u *UserReadRecord) Update(cols []string) (err error) {
-	o := orm.NewOrm()
-	_, err = o.Update(u, cols...)
-	return
+func (m *UserReadRecord) TableName() string {
+	return "user_read_record"
 }
 
-func GetUserReadRecordListById(recordId int) (items *UserReadRecord, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT * FROM user_read_record WHERE 1=1 AND user_read_record_id = ?`
-	err = o.Raw(sql, recordId).QueryRow(&items)
-	return
+type UserReadRecordCols struct {
+	PrimaryId          string
+	UserId             string
+	ReportId           string
+	ReportTitle        string
+	ClassifyIdFirst    string
+	ClassifyNameFirst  string
+	ClassifyIdSecond   string
+	ClassifyNameSecond string
+	ClassifyIdThird    string
+	ClassifyNameThird  string
+	StartTimestamp     string
+	EndTimestamp       string
+	ReportSource       string
+	CreateTime         string
 }
 
-func GetUserReadRecordCountByReportPdfIdAndUserId(reportId, userId int) (count int, err error) {
-	o := orm.NewOrm()
-	sql := `SELECT COUNT(*) AS count FROM user_read_record WHERE 1=1 AND report_id=? AND user_id = ? AND report_type = 2`
-	err = o.Raw(sql, reportId, userId).QueryRow(&count)
-	return
+func (m *UserReadRecord) Cols() UserReadRecordCols {
+	return UserReadRecordCols{
+		PrimaryId:          "id",
+		UserId:             "user_id",
+		ReportId:           "report_id",
+		ReportTitle:        "report_title",
+		ClassifyIdFirst:    "classify_id_first",
+		ClassifyNameFirst:  "classify_name_first",
+		ClassifyIdSecond:   "classify_id_second",
+		ClassifyNameSecond: "classify_name_second",
+		ClassifyIdThird:    "classify_id_third",
+		ClassifyNameThird:  "classify_name_third",
+		StartTimestamp:     "start_timestamp",
+		EndTimestamp:       "end_timestamp",
+		ReportSource:       "report_source",
+		CreateTime:         "create_time",
+	}
 }
 
-func GetUserReadRecordListByRcordIds(recordIds []string) (items []*UserReadRecord, err error) {
+func (m *UserReadRecord) Create() (err error) {
 	o := orm.NewOrm()
-	sql := `SELECT * FROM user_read_record WHERE 1=1  `
-	var stringIds string
-	if len(recordIds) > 0 {
-		sql += ` AND user_read_record_id in (?) `
-		stringIds = strings.Join(recordIds, ",")
+	id, err := o.Insert(m)
+	if err != nil {
+		return
 	}
-	_, err = o.Raw(sql, stringIds).QueryRows(&items)
+	m.Id = int(id)
 	return
 }
 
-func UpdateUserReadRecordById(recordId, endTimeStamp, stayTime int, stayTimeStr string) (err error) {
+func (m *UserReadRecord) Update(cols []string) (err error) {
 	o := orm.NewOrm()
-	sql := `UPDATE user_read_record SET end_timestamp=?, stay_timestamp=?, stay_time=? WHERE 1=1 AND user_read_record_id = ? `
-	_, err = o.Raw(sql, endTimeStamp, stayTime, stayTimeStr, recordId).Exec()
+	_, err = o.Update(m, cols...)
 	return
 }
 
-func UpdateUserReadRecordByRecordIds(recordIds []string, endTimeStamp, stayTime int, stayTimeStr string) (err error) {
+func (m *UserReadRecord) GetItemById(id int) (item *UserReadRecord, err error) {
 	o := orm.NewOrm()
-	sql := `UPDATE user_read_record SET end_timestamp=?, stay_timestamp=?, stay_time=? WHERE 1=1 `
-	var stringIds string
-	if len(recordIds) > 0 {
-		sql += ` AND user_read_record_id in (?) `
-		stringIds = strings.Join(recordIds, ",")
-	}
-	_, err = o.Raw(sql, endTimeStamp, stayTime, stayTimeStr, stringIds).Exec()
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
+	err = o.Raw(sql, id).QueryRow(&item)
 	return
 }

+ 143 - 30
models/user_record.go

@@ -1,59 +1,172 @@
 package models
 
 import (
+	"eta/eta_mini_api/utils"
+	"fmt"
+	"strings"
 	"time"
 
 	"github.com/beego/beego/v2/client/orm"
 )
 
+// UserRecord 用户表
 type UserRecord struct {
-	UserRecordId  int       `orm:"pk"`
-	OpenId        string    `description:"用户openid,最大长度:32"`
-	UnionId       string    `description:"用户unionid,最大长度:64"`
-	Subscribe     int       `description:"是否关注"`
-	SubscribeTime time.Time `description:""`
-	NickName      string    `descritpion:"用户昵称,最大长度:32"`
-	RealName      string    `descritpion:"用户实际名称,最大长度:32"`
-	Sex           int       `descritpion:"普通用户性别,1为男性,2为女性"`
-	Province      string    `description:"普通用户个人资料填写的省份,最大长度:30"`
-	City          string    `description:"普通用户个人资料填写的城市,最大长度:30"`
-	Country       string    `description:"国家,如中国为CN,最大长度:30"`
-	Headimgurl    string    `description:"用户第三方(微信)头像,最大长度:512"`
-	CreateTime    time.Time `description:"创建时间,关系添加时间、用户授权时间"`
-	SessionKey    string    `description:"微信小程序会话密钥,最大长度:255"`
-	UserId        int       `description:"用户id"`
+	UserRecordId  int       `orm:"column(user_record_id);pk"`
+	UserId        int       `description:"用户ID"`
+	OpenId        string    `description:"open_id"`
+	UnionId       string    `description:"用户统一标识"`
+	Subscribe     int       `description:"公众号关注状态:0-未关注;1-已关注"`
+	SubscribeTime time.Time `description:"公众号关注/取消关注时间"`
+	NickName      string    `description:"用户昵称"`
+	RealName      string    `description:"用户姓名"`
+	Gender        int       `description:"性别"`
+	Avatar        string    `description:"用户头像"`
+	//SessionKey    string    `description:"微信小程序会话密钥"`
+	CreateTime time.Time `description:"创建时间"`
+	ModifyTime time.Time `description:"更新时间"`
 }
 
-func (item *UserRecord) Update(cols []string) (err error) {
+func (m *UserRecord) TableName() string {
+	return "user_record"
+}
+
+type UserRecordCols struct {
+	PrimaryId     string
+	UserId        string
+	OpenId        string
+	UnionId       string
+	Subscribe     string
+	SubscribeTime string
+	NickName      string
+	RealName      string
+	Gender        string
+	Avatar        string
+	SessionKey    string
+	CreateTime    string
+	ModifyTime    string
+}
+
+func (m *UserRecord) Cols() UserRecordCols {
+	return UserRecordCols{
+		PrimaryId:     "user_record_id",
+		UserId:        "user_id",
+		OpenId:        "open_id",
+		UnionId:       "union_id",
+		Subscribe:     "subscribe",
+		SubscribeTime: "subscribe_time",
+		NickName:      "nick_name",
+		RealName:      "real_name",
+		Gender:        "gender",
+		Avatar:        "avatar",
+		SessionKey:    "session_key",
+		CreateTime:    "create_time",
+		ModifyTime:    "modify_time",
+	}
+}
+
+func (m *UserRecord) Create() (err error) {
+	o := orm.NewOrm()
+	id, err := o.Insert(m)
+	if err != nil {
+		return
+	}
+	m.UserRecordId = int(id)
+	return
+}
+
+func (m *UserRecord) CreateMulti(items []*UserRecord) (err error) {
+	if len(items) == 0 {
+		return
+	}
+	o := orm.NewOrm()
+	_, err = o.InsertMulti(len(items), items)
+	return
+}
+
+func (m *UserRecord) Update(cols []string) (err error) {
 	o := orm.NewOrm()
-	_, err = o.Update(item, cols...)
+	_, err = o.Update(m, cols...)
 	return
 }
 
-func (item *UserRecord) Insert() (insertId int64, err error) {
+func (m *UserRecord) Remove() (err error) {
 	o := orm.NewOrm()
-	insertId, err = o.Insert(item)
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
+	_, err = o.Raw(sql, m.UserRecordId).Exec()
 	return
 }
 
-// 根据openid获取用户关系
-func GetUserRecordByOpenId(openId string) (item *UserRecord, err error) {
-	sql := `SELECT * FROM user_record WHERE open_id=? `
+func (m *UserRecord) MultiRemove(ids []int) (err error) {
+	if len(ids) == 0 {
+		return
+	}
 	o := orm.NewOrm()
-	err = o.Raw(sql, openId).QueryRow(&item)
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.Cols().PrimaryId, utils.GetOrmInReplace(len(ids)))
+	_, err = o.Raw(sql, ids).Exec()
 	return
 }
 
-func UserSubscribe(subscribeType int, openId string) (err error) {
+func (m *UserRecord) RemoveByCondition(condition string, pars []interface{}) (err error) {
+	if condition == "" {
+		return
+	}
 	o := orm.NewOrm()
-	sql := `UPDATE user_record SET subscribe=?,subscribe_time=NOW() WHERE open_id = ? `
-	_, err = o.Raw(sql, subscribeType, openId).Exec()
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s`, m.TableName(), condition)
+	_, err = o.Raw(sql, pars).Exec()
 	return
 }
 
-// GetUserRecordByUnionId 通过unionid获取已绑定用户的user_record信息
-func GetUserRecordByUnionId(unionId string) (item *UserRecord, err error) {
-	sql := `SELECT * FROM user_record WHERE union_id=? `
-	err = orm.NewOrm().Raw(sql, unionId).QueryRow(&item)
+func (m *UserRecord) GetItemById(id int) (item *UserRecord, err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().PrimaryId)
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+func (m *UserRecord) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *UserRecord, err error) {
+	o := orm.NewOrm()
+	order := ``
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s %s LIMIT 1`, m.TableName(), condition, order)
+	err = o.Raw(sql, pars).QueryRow(&item)
+	return
+}
+
+func (m *UserRecord) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
+	err = o.Raw(sql, pars).QueryRow(&count)
+	return
+}
+
+func (m *UserRecord) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*UserRecord, err error) {
+	o := orm.NewOrm()
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}
+
+func (m *UserRecord) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*UserRecord, err error) {
+	o := orm.NewOrm()
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s LIMIT ?,?`, fields, m.TableName(), condition, order)
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
 	return
 }

+ 218 - 0
models/users.go

@@ -0,0 +1,218 @@
+package models
+
+import (
+	"eta/eta_mini_api/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"strings"
+	"time"
+)
+
+// Users 用户表
+type Users struct {
+	UserId          int       `orm:"column(user_id);pk"`
+	RealName        string    `description:"用户姓名"`
+	Mobile          string    `description:"手机号"`
+	AreaCode        string    `description:"区号"`
+	SellerId        int       `description:"销售ID"`
+	SellerName      string    `description:"销售名称"`
+	SysUserId       int       `description:"操作人ID"`
+	SysUserRealName string    `description:"操作人姓名"`
+	CompanyId       int       `description:"所属机构ID"`
+	CompanyName     string    `description:"所属机构名称"`
+	Status          int       `description:"用户类型:1-试用用户;2-正式用户"`
+	AuthStatus      int       `description:"权限状态:0-关闭;1-开启"`
+	IsRegistered    int       `description:"注册状态:0-未注册;1-已注册"`
+	RegisterTime    time.Time `description:"注册时间"`
+	Subscribe       int       `description:"是否关注公众号:0-未关注;1-已关注"`
+	LastReadTime    time.Time `description:"最后一次阅读时间"`
+	ReadTimes       int       `description:"阅读次数"`
+	OpenId          string    `description:"open_id"`
+	UnionId         string    `description:"用户统一标识"`
+	IsDeleted       int       `description:"删除状态:0-正常;1-已删除"`
+	CreateTime      time.Time `description:"创建时间"`
+	ModifyTime      time.Time `description:"修改时间"`
+}
+
+func (m *Users) TableName() string {
+	return "users"
+}
+
+type UsersCols struct {
+	PrimaryId       string
+	RealName        string
+	Mobile          string
+	AreaCode        string
+	SellerId        string
+	SellerName      string
+	SysUserId       string
+	SysUserRealName string
+	CompanyId       string
+	CompanyName     string
+	Status          string
+	AuthStatus      string
+	IsRegistered    string
+	RegisterTime    string
+	Subscribe       string
+	LastReadTime    string
+	ReadTimes       string
+	OpenId          string
+	UnionId         string
+	IsDeleted       string
+	CreateTime      string
+	ModifyTime      string
+}
+
+func (m *Users) Cols() UsersCols {
+	return UsersCols{
+		PrimaryId:       "user_id",
+		RealName:        "real_name",
+		Mobile:          "mobile",
+		AreaCode:        "area_code",
+		SellerId:        "seller_id",
+		SellerName:      "seller_name",
+		SysUserId:       "sys_user_id",
+		SysUserRealName: "sys_user_real_name",
+		CompanyId:       "company_id",
+		CompanyName:     "company_name",
+		Status:          "status",
+		AuthStatus:      "auth_status",
+		IsRegistered:    "is_registered",
+		RegisterTime:    "register_time",
+		Subscribe:       "subscribe",
+		LastReadTime:    "last_read_time",
+		ReadTimes:       "read_times",
+		OpenId:          "open_id",
+		UnionId:         "union_id",
+		IsDeleted:       "is_deleted",
+		CreateTime:      "create_time",
+		ModifyTime:      "modify_time",
+	}
+}
+
+func (m *Users) Create() (err error) {
+	o := orm.NewOrm()
+	id, err := o.Insert(m)
+	if err != nil {
+		return
+	}
+	m.UserId = int(id)
+	return
+}
+
+func (m *Users) Update(cols []string) (err error) {
+	o := orm.NewOrm()
+	_, err = o.Update(m, cols...)
+	return
+}
+
+func (m *Users) GetItemById(id int) (item *Users, err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = %d AND %s = ? LIMIT 1`, m.TableName(), m.Cols().IsDeleted, RowDeletedDefault, m.Cols().PrimaryId)
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+func (m *Users) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *Users, err error) {
+	o := orm.NewOrm()
+	order := ``
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = %d %s %s LIMIT 1`, m.TableName(), m.Cols().IsDeleted, RowDeletedDefault, condition, order)
+	err = o.Raw(sql, pars).QueryRow(&item)
+	return
+}
+
+func (m *Users) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE %s = %d %s`, m.TableName(), m.Cols().IsDeleted, RowDeletedDefault, condition)
+	err = o.Raw(sql, pars).QueryRow(&count)
+	return
+}
+
+func (m *Users) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*Users, err error) {
+	o := orm.NewOrm()
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE %s = %d %s %s`, fields, m.TableName(), m.Cols().IsDeleted, RowDeletedDefault, condition, order)
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}
+
+func (m *Users) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*Users, err error) {
+	o := orm.NewOrm()
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := fmt.Sprintf(`ORDER BY %s DESC`, m.Cols().CreateTime)
+	if orderRule != "" {
+		order = ` ORDER BY ` + orderRule
+	}
+	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE %s = %d %s %s LIMIT ?,?`, fields, m.TableName(), m.Cols().IsDeleted, RowDeletedDefault, condition, order)
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// UsersItem 用户信息
+type UsersItem struct {
+	UserId       int    `description:"用户ID"`
+	RealName     string `description:"用户姓名"`
+	Mobile       string `description:"手机号"`
+	MobileHidden string `description:"手机号(隐藏中间四位)"`
+	AreaCode     string `description:"区号"`
+	SellerName   string `description:"销售名称"`
+	CompanyName  string `description:"所属机构名称"`
+	Status       int    `description:"用户类型:1-试用用户;2-正式用户"`
+	AuthStatus   int    `description:"权限状态:0-关闭;1-开启"`
+	IsRegistered int    `description:"注册状态:0-未注册;1-已注册"`
+	RegisterTime string `description:"注册时间"`
+	Subscribe    int    `description:"是否关注公众号:0-未关注;1-已关注"`
+	LastReadTime string `description:"最后一次阅读时间"`
+	ReadTimes    int    `description:"阅读次数"`
+	TrialExpired bool   `description:"试用到期:true-已到期"`
+	CreateTime   string `description:"创建时间"`
+	ModifyTime   string `description:"修改时间"`
+}
+
+func (m *Users) Format2Item() (item *UsersItem) {
+	item = new(UsersItem)
+	item.UserId = m.UserId
+	item.RealName = m.RealName
+	item.Mobile = m.Mobile
+	item.MobileHidden = utils.HideMobileMiddle(m.Mobile)
+	item.AreaCode = m.AreaCode
+	item.SellerName = m.SellerName
+	item.CompanyName = m.CompanyName
+	item.Status = m.Status
+	item.AuthStatus = m.AuthStatus
+	item.IsRegistered = m.IsRegistered
+	item.RegisterTime = utils.TimeTransferString(utils.FormatDateTime, m.RegisterTime)
+	item.Subscribe = m.Subscribe
+	item.LastReadTime = utils.TimeTransferString(utils.FormatDateTime, m.LastReadTime)
+	item.ReadTimes = m.ReadTimes
+	// 试用到期
+	if m.Status == UserStatusTrial && !m.RegisterTime.IsZero() {
+		expiredTime := m.RegisterTime.Add(3 * 24 * time.Hour)
+		if expiredTime.Before(time.Now().Local()) {
+			item.TrialExpired = true
+		}
+	}
+	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, m.CreateTime)
+	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, m.ModifyTime)
+	return
+}
+
+func (m *Users) UpdateUserReadTimes(userId int) (err error) {
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`UPDATE %s SET %s = %s + 1 WHERE %s = ? LIMIT 1`, m.TableName(), m.Cols().ReadTimes, m.Cols().ReadTimes, m.Cols().PrimaryId)
+	_, err = o.Raw(sql, userId).Exec()
+	return
+}

+ 2 - 2
models/wx_token.go

@@ -23,10 +23,10 @@ func (w *WxToken) Update(cols []string) (err error) {
 	return
 }
 
-// GetById 根据id获取accessToken信息
+// GetWxTokenById 根据id获取accessToken信息
 func GetWxTokenById() (info WxToken, err error) {
 	o := orm.NewOrm()
 	sql := `SELECT * FROM wx_token WHERE id = ?`
-	err = o.Raw(sql, 0).QueryRow(&info)
+	err = o.Raw(sql, 1).QueryRow(&info)
 	return
 }

+ 11 - 335
routers/commentsRouter.go

@@ -7,73 +7,10 @@ import (
 
 func init() {
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:BannerController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:BannerController"],
+    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ClassifyController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ClassifyController"],
         beego.ControllerComments{
-            Method: "Detail",
-            Router: `/detail`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:BannerController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:BannerController"],
-        beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartController"],
-        beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartController"],
-        beego.ControllerComments{
-            Method: "Locate",
-            Router: `/locate`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionController"],
-        beego.ControllerComments{
-            Method: "ClassifyTree",
-            Router: `/classify/tree`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionController"],
-        beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionNoAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionNoAuthController"],
-        beego.ControllerComments{
-            Method: "ClassifyTree",
-            Router: `/classify/tree`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionNoAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ChartPermissionNoAuthController"],
-        beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
+            Method: "Tree",
+            Router: `/tree`,
             AllowHTTPMethods: []string{"get"},
             MethodParams: param.Make(),
             Filters: nil,
@@ -88,141 +25,6 @@ func init() {
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"],
-        beego.ControllerComments{
-            Method: "Collect",
-            Router: `/collect`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"],
-        beego.ControllerComments{
-            Method: "CollectCancel",
-            Router: `/collectCancel`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"],
-        beego.ControllerComments{
-            Method: "Detail",
-            Router: `/detail`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"],
-        beego.ControllerComments{
-            Method: "IsCollect",
-            Router: `/isCollect`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"],
-        beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyChartController"],
-        beego.ControllerComments{
-            Method: "Locate",
-            Router: `/locate`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "Collect",
-            Router: `/collect`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "CollectCancel",
-            Router: `/collectCancel`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "IsCollect",
-            Router: `/isCollect`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "PdfCollect",
-            Router: `/pdf/collect`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "PdfCollectCancel",
-            Router: `/pdf/collectCancel`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:MyReportController"],
-        beego.ControllerComments{
-            Method: "IsPdfCollect",
-            Router: `/pdf/isCollect`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
-        beego.ControllerComments{
-            Method: "DailyList",
-            Router: `/daily/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
-        beego.ControllerComments{
-            Method: "Detail",
-            Router: `/detail`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
     beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
         beego.ControllerComments{
             Method: "List",
@@ -234,41 +36,14 @@ func init() {
 
     beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
         beego.ControllerComments{
-            Method: "PdfDetail",
-            Router: `/pdf/detail`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
-        beego.ControllerComments{
-            Method: "PdfList",
-            Router: `/pdf/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
-        beego.ControllerComments{
-            Method: "RecentList",
-            Router: `/recent/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportController"],
-        beego.ControllerComments{
-            Method: "Search",
-            Router: `/search`,
-            AllowHTTPMethods: []string{"get"},
+            Method: "ReadRecord",
+            Router: `/read_record`,
+            AllowHTTPMethods: []string{"post"},
             MethodParams: param.Make(),
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportNoAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportNoAuthController"],
+    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportOpenController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportOpenController"],
         beego.ControllerComments{
             Method: "Detail",
             Router: `/detail`,
@@ -277,55 +52,19 @@ func init() {
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportNoAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportNoAuthController"],
+    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportOpenController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportOpenController"],
         beego.ControllerComments{
-            Method: "List",
-            Router: `/list`,
+            Method: "OutsideDetail",
+            Router: `/outside_detail`,
             AllowHTTPMethods: []string{"get"},
             MethodParams: param.Make(),
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportNoAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:ReportNoAuthController"],
-        beego.ControllerComments{
-            Method: "Search",
-            Router: `/search`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
-        beego.ControllerComments{
-            Method: "AddReportRecord",
-            Router: `/addReportRecord`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
-        beego.ControllerComments{
-            Method: "ApplyPermission",
-            Router: `/apply/permission`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
     beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
         beego.ControllerComments{
             Method: "Info",
             Router: `/info`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
-        beego.ControllerComments{
-            Method: "UserInfoSave",
-            Router: `/info/save`,
             AllowHTTPMethods: []string{"post"},
             MethodParams: param.Make(),
             Filters: nil,
@@ -340,33 +79,6 @@ func init() {
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
-        beego.ControllerComments{
-            Method: "AddReportPdfRecord",
-            Router: `/pdf/addReportRecord`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
-        beego.ControllerComments{
-            Method: "PermissionList",
-            Router: `/permission/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserAuthController"],
-        beego.ControllerComments{
-            Method: "PurchasedPermission",
-            Router: `/purchased/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
     beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"],
         beego.ControllerComments{
             Method: "AreaCodeList",
@@ -376,28 +88,10 @@ func init() {
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"],
-        beego.ControllerComments{
-            Method: "DepartmentList",
-            Router: `/department/list`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"],
-        beego.ControllerComments{
-            Method: "GenerateCaptcha",
-            Router: `/getCaptcha`,
-            AllowHTTPMethods: []string{"get"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
     beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:UserController"],
         beego.ControllerComments{
             Method: "GetVerifyCode",
-            Router: `/getVerifyCode`,
+            Router: `/get_verify_code`,
             AllowHTTPMethods: []string{"post"},
             MethodParams: param.Make(),
             Filters: nil,
@@ -412,22 +106,4 @@ func init() {
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:WechatController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:WechatController"],
-        beego.ControllerComments{
-            Method: "Notify",
-            Router: `/notify`,
-            AllowHTTPMethods: []string{"get","post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
-    beego.GlobalControllerRouter["eta/eta_mini_api/controllers:WechatController"] = append(beego.GlobalControllerRouter["eta/eta_mini_api/controllers:WechatController"],
-        beego.ControllerComments{
-            Method: "Subscribe",
-            Router: `/subscribe`,
-            AllowHTTPMethods: []string{"post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
 }

+ 12 - 32
routers/router.go

@@ -28,51 +28,31 @@ func init() {
 				&controllers.WechatController{},
 			),
 		),
-		beego.NSNamespace("/report",
-			beego.NSInclude(
-				&controllers.ReportController{},
-			),
-		),
-		beego.NSNamespace("/chart",
-			beego.NSInclude(
-				&controllers.ChartController{},
-			),
-		),
-		beego.NSNamespace("/mychart",
-			beego.NSInclude(
-				&controllers.MyChartController{},
-			),
-		),
-		beego.NSNamespace("/myreport",
-			beego.NSInclude(
-				&controllers.MyReportController{},
-			),
-		),
-		beego.NSNamespace("/chart_perimission",
-			beego.NSInclude(
-				&controllers.ChartPermissionController{},
-			),
-		),
 		beego.NSNamespace("/system",
 			beego.NSInclude(
 				&controllers.MiniConfigController{},
 			),
 		),
-		beego.NSNamespace("/banner",
+		//beego.NSNamespace("/banner",
+		//	beego.NSInclude(
+		//		&controllers.BannerController{},
+		//	),
+		//),
+		beego.NSNamespace("/classify",
 			beego.NSInclude(
-				&controllers.BannerController{},
+				&controllers.ClassifyController{},
 			),
 		),
-	)
-	h5ns := beego.NewNamespace("/api/h5",
 		beego.NSNamespace("/report",
 			beego.NSInclude(
-				&controllers.ReportNoAuthController{},
+				&controllers.ReportController{},
 			),
 		),
-		beego.NSNamespace("/chart_perimission",
+	)
+	h5ns := beego.NewNamespace("/api/h5",
+		beego.NSNamespace("/report",
 			beego.NSInclude(
-				&controllers.ChartPermissionNoAuthController{},
+				&controllers.ReportOpenController{},
 			),
 		),
 	)

+ 0 - 69
services/base_lib.go

@@ -1,69 +0,0 @@
-package services
-
-import (
-	"bytes"
-	"eta/eta_mini_api/utils"
-	"io"
-	"net/http"
-	"time"
-)
-
-func HttpGet(url string) (body []byte, err error) {
-	client := &http.Client{}
-	req, err := http.NewRequest("GET", url, nil)
-	if err != nil {
-		return
-	}
-	nonce := utils.GetRandStringNoSpecialChar(16)
-	timestamp := time.Now().Format(utils.FormatDateTimeUnSpace)
-	signature := utils.GetSign(nonce, timestamp, utils.ETA_MINI_APPID, utils.ETA_MINI_APP_SECRET)
-	//增加header选项
-	req.Header.Add("Nonce", nonce)
-	req.Header.Add("Timestamp", timestamp)
-	req.Header.Add("Appid", utils.ETA_MINI_APPID)
-	req.Header.Add("Signature", signature)
-	req.Header.Set("Content-Type", "application/json")
-
-	response, err := client.Do(req)
-	if err != nil {
-		return
-	}
-	defer response.Body.Close()
-
-	body, err = io.ReadAll(response.Body)
-	if err != nil {
-		return
-	}
-	utils.FileLog.Info("result:" + string(body))
-	return
-}
-
-func HttpPost(url string, postBody []byte) (body []byte, err error) {
-	client := &http.Client{}
-	req, err := http.NewRequest("POST", url, bytes.NewReader(postBody))
-	if err != nil {
-		return
-	}
-	nonce := utils.GetRandStringNoSpecialChar(16)
-	timestamp := time.Now().Format(utils.FormatDateTimeUnSpace)
-	signature := utils.GetSign(nonce, timestamp, utils.ETA_MINI_APPID, utils.ETA_MINI_APP_SECRET)
-	//增加header选项
-	req.Header.Add("Nonce", nonce)
-	req.Header.Add("Timestamp", timestamp)
-	req.Header.Add("Appid", utils.ETA_MINI_APPID)
-	req.Header.Add("Signature", signature)
-	req.Header.Set("Content-Type", "application/json")
-
-	response, err := client.Do(req)
-	if err != nil {
-		return
-	}
-	defer response.Body.Close()
-
-	body, err = io.ReadAll(response.Body)
-	if err != nil {
-		return
-	}
-	utils.FileLog.Info("result:" + string(body))
-	return
-}

+ 0 - 40
services/chart.go

@@ -1,40 +0,0 @@
-package services
-
-import (
-	"encoding/json"
-	"eta/eta_mini_api/utils"
-	"fmt"
-
-	resp2 "eta/eta_mini_api/models/response"
-)
-
-func GetChartList(currentIndex, pageSize int) (resp *resp2.ChartResp[resp2.ChartListResp], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart/list?"
-	url += fmt.Sprintf("PageSize=%d&CurrentIndex=%d", pageSize, currentIndex)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return resp, err
-	}
-	return resp, nil
-
-}
-
-func GetChartDetail(chartInfoId int, uniqueCode string) (resp *resp2.ChartResp[resp2.ChartInfoView], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart/detail?"
-	url += fmt.Sprintf("ChartInfoId=%d&UniqueCode=%s", chartInfoId, uniqueCode)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}

+ 0 - 140
services/chart_permission.go

@@ -1,140 +0,0 @@
-package services
-
-import (
-	"encoding/json"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/utils"
-	"fmt"
-)
-
-// GetChartPermissionSecondList 获取二级品种权限
-func GetChartPermissionSecondList(chartPermissionId int) (resp *models.ChartPermissionResp[[]*models.ChartPermission], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/second/list"
-	url += fmt.Sprintf("?chartPermissonId=%d", chartPermissionId)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-
-}
-
-// GetChartPermissionList 获取一级品种权限
-func GetChartPermissionList() (resp *models.ChartPermissionResp[[]*models.ChartPermission], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/list"
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetPublicChartPermissionList 获取公共品种权限列表
-func GetPublicChartPermissionList() (resp *models.ChartPermissionResp[[]*models.ChartPermissionTreeView], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/public/list"
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetPrivateChartPermissionList 获取私有品种权限列表
-func GetPrivateChartPermissionList() (resp *models.ChartPermissionResp[[]*models.ChartPermissionTreeView], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/private/list"
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetChartPermissionAllList 获取所有品种权限列表
-func GetChartPermissionAllList() (resp *models.ChartPermissionResp[[]*models.ChartPermission], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/allList"
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetReportChartPermissionList 获取研报的权限列表
-func GetReportChartPermissionList(reportId int) (resp *models.ChartPermissionResp[[]*models.ChartPermission], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/detail"
-	url += fmt.Sprintf("?ReportId=%d", reportId)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetChartPermissionListByClassifyId 根据分类id获取权限列表 scope 0:二级品种权限,1:一级品种权限,2:所有权限
-func GetChartPermissionListByClassifyId(classifyId, scope int) (resp *models.ChartPermissionResp[[]*models.ChartPermission], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/classify/detail"
-	url += fmt.Sprintf("?ClassifyId=%d&Scope=%d", classifyId, scope)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetClassifyTreeByChartPermission 获取绑定该品种的分类树
-func GetClassifyTreeByChartPermission(chartPermissionId int) (resp *models.ChartPermissionResp[[]*models.ClassifyView], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/classify/tree"
-	url += fmt.Sprintf("?ChartPermissionId=%d", chartPermissionId)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-// GetClassifyListByChartPermission 获取绑定该品种的分类列表
-func GetClassifyListByChartPermission(chartPermissionId int) (resp *models.ChartPermissionResp[[]*models.ClassifyView], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/chart_permission/classify/list"
-	url += fmt.Sprintf("?ChartPermissionId=%d", chartPermissionId)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}

+ 12 - 45
services/classify.go

@@ -1,48 +1,15 @@
 package services
 
-import (
-	"encoding/json"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/utils"
-)
-
-type ClassifyReq struct {
-	ClassifyIds []int
-}
-
-type ClassifyPermissionItemResp struct {
-	ClassifyId      int      `description:"二级分类id"`
-	PermissionNames []string `description:"权限名称列表"`
-}
-
-func GetFirstChartPermission(classifyIds []int) (resp *models.ChartPermissionResp[[]*ClassifyPermissionItemResp], err error) {
-
-	classifyReq := ClassifyReq{classifyIds}
-	postBody, err := json.Marshal(classifyReq)
-	if err != nil {
-		return
-	}
-	url := utils.ETA_MINI_BRIDGE_URL + "/classify/chart_permission/first"
-	body, err := HttpPost(url, postBody)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetAllClassify() (resp *models.BaseResponseT[[]*models.ClassifyView], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/classify/list"
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
+import "eta/eta_mini_api/models"
+
+// GetClassifyTreeRecursive 递归获取报告分类树
+func GetClassifyTreeRecursive(list []*models.MiniClassifyItem, parentId int) []*models.MiniClassifyItem {
+	res := make([]*models.MiniClassifyItem, 0)
+	for _, v := range list {
+		if v.ParentId == parentId {
+			v.Children = GetClassifyTreeRecursive(list, v.Id)
+			res = append(res, v)
+		}
+	}
+	return res
 }

+ 0 - 165
services/report.go

@@ -1,166 +1 @@
 package services
-
-import (
-	"encoding/json"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/utils"
-	"fmt"
-
-	resp2 "eta/eta_mini_api/models/response"
-)
-
-// GetReportPdfClassify 获取pdf研报的最小分类
-func GetReportPdfClassify(report *models.ReportPdfView) int {
-	var res int
-	if report.ClassifyIdFirst != 0 {
-		res = report.ClassifyIdFirst
-	}
-	if report.ClassifyIdSecond != 0 {
-		res = report.ClassifyIdSecond
-	}
-	if report.ClassifyIdThird != 0 {
-		res = report.ClassifyIdThird
-	}
-	return res
-}
-
-func GetReportList(chartPermissionId, level, rangeType, classifyId, currentIndex, pageSize int) (resp *resp2.ReportResp[resp2.ReportList], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/report/list?"
-	url += fmt.Sprintf("RangeType=%d&ChartPermissionId=%d&Level=%d&PageSize=%d&CurrentIndex=%d&ClassifyId=%d", rangeType, chartPermissionId, level, pageSize, currentIndex, classifyId)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetNoAuthReportList(reportType, chartPermissionId, level, rangeType, classifyId, currentIndex, pageSize int) (resp *resp2.ReportResp[resp2.ReportPushListResp], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/noAuth/report/list?"
-	url += fmt.Sprintf("ReportType=%d&RangeType=%d&ChartPermissionId=%d&Level=%d&PageSize=%d&CurrentIndex=%d&ClassifyId=%d", reportType, rangeType, chartPermissionId, level, pageSize, currentIndex, classifyId)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetNoAuthReportDetail(reportId int) (resp *resp2.ReportResp[resp2.ReportDetailResp], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/noAuth/report/detail?"
-	url += fmt.Sprintf("ReportId=%d", reportId)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetReportDetail(reportId, userId int) (resp *resp2.ReportResp[resp2.ReportDetailResp], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/report/detail?"
-	url += fmt.Sprintf("ReportId=%d&UserId=%d", reportId, userId)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetReportDetailNoUser(reportId int) (resp *resp2.ReportResp[resp2.ReportDetailResp], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/report/detail/noUser?"
-	url += fmt.Sprintf("ReportId=%d", reportId)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetReportDailyList() (resp *resp2.ReportResp[resp2.ReportList], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/report/daily/list"
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-}
-
-func GetReportRecentList(currentIndex, pageSize int) (resp *resp2.ReportResp[resp2.ReportList], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/report/recent/list?"
-	url += fmt.Sprintf("PageSize=%d&CurrentIndex=%d", pageSize, currentIndex)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-
-}
-
-func SearchReport(keyWord string, currentIndex, pageSize int) (resp *resp2.ReportResp[resp2.ReportSearchResp], err error) {
-	url := utils.ETA_MINI_BRIDGE_URL + "/report/search?"
-	url += fmt.Sprintf("KeyWord=%s&PageSize=%d&CurrentIndex=%d", keyWord, pageSize, currentIndex)
-	fmt.Println(url)
-	body, err := HttpGet(url)
-	if err != nil {
-		return
-	}
-	err = json.Unmarshal(body, &resp)
-	if err != nil {
-		return
-	}
-	return
-
-}
-
-func SearchReportPush(keyWord string, startSize, pageSize int) (items []*models.ReportPushStatus, total int, err error) {
-	if keyWord == "" {
-		return
-	}
-
-	var pars []interface{}
-	condition := `AND title LIKE ?`
-	pars = append(pars, utils.GetLikeKeywordPars(pars, keyWord, 1))
-	total, err = models.GetReportPushStatusCountByCondition(condition, pars)
-	if err != nil {
-		return
-	}
-
-	items, err = models.GetReportPushStatusByCondition(condition, pars, startSize, pageSize)
-	if err != nil {
-		return
-	}
-	return
-}

+ 69 - 18
services/sms.go

@@ -1,41 +1,52 @@
 package services
 
 import (
+	"bytes"
 	"encoding/json"
 	"eta/eta_mini_api/utils"
 	"fmt"
+	"io"
 	"io/ioutil"
 	"net/http"
 	"net/url"
 )
 
-func SendSmsCode(mobile, vcode string) bool {
-	flag := false
+func SendSmsCode(mobile, verifyCode string) (sendOk bool, result string, err error) {
+	defer func() {
+		if err != nil {
+			tips := fmt.Sprintf("SendSmsCode err: %v, result: %s", err, result)
+			utils.FileLog.Info(tips)
+		}
+	}()
 	tplId := utils.SMS_TPLID
 	if tplId == "" {
 		tplId = "262642"
 	}
 	expiresTime := "15"
-	result, err := sendSms(mobile, tplId, vcode, expiresTime)
-	if err != nil {
-		fmt.Println("发送短信失败")
-		return false
+
+	postResult, e := sendSms(mobile, tplId, verifyCode, expiresTime)
+	if e != nil {
+		err = fmt.Errorf("post sms err: %v", e)
+		return
 	}
-	fmt.Println("result", string(result))
+	result = string(postResult)
+
 	var netReturn map[string]interface{}
-	err = json.Unmarshal(result, &netReturn)
-	if err != nil {
-		utils.ApiLog.Info("短信验证码发送失败", "err:"+err.Error()+" result"+string(result))
-		flag = false
+	if e = json.Unmarshal(postResult, &netReturn); e != nil {
+		err = fmt.Errorf("result unmarshal err: %v", e)
+		return
+	}
+	errCode, ok := netReturn["error_code"].(float64)
+	if !ok {
+		err = fmt.Errorf("err code err")
+		return
 	}
-	if netReturn["error_code"].(float64) == 0 {
-		fmt.Printf("接口返回result字段是:\r\n%v", netReturn["result"])
-		flag = true
-	} else {
-		utils.ApiLog.Info("短信验证码发送失败", "err:"+err.Error()+" result"+string(result))
-		flag = false
+	if errCode != 0 {
+		err = fmt.Errorf("短信验证码发送失败")
+		return
 	}
-	return flag
+	sendOk = true
+	return
 }
 
 func sendSms(mobile, tplId, code, expirdTime string) (rs []byte, err error) {
@@ -64,3 +75,43 @@ func sendSms(mobile, tplId, code, expirdTime string) (rs []byte, err error) {
 	defer resp.Body.Close()
 	return ioutil.ReadAll(resp.Body)
 }
+
+const (
+	SmsApiServiceProviderDefault = "1" // 默认短信服务商-金慧盈通
+)
+
+type SmsApiPars struct {
+	PhoneList       []string `json:"phonelist" description:"收信手机号码,最多50个一次"`
+	ServiceProvider string   `json:"serviceprovider" description:"短信服务提供商:1-金慧盈通;2-高斯通"`
+	SmsContent      string   `json:"smscontent" description:"短信内容"`
+	Sender          string   `json:"sender" description:"发送人"`
+	Department      string   `json:"department" description:"发送人部门"`
+	Purpose         string   `json:"purpose" description:"用途"`
+}
+
+func PostSmsApi(params SmsApiPars) (result string, err error) {
+	requestUrl := utils.SmsApiUrl
+	if requestUrl == "" {
+		err = fmt.Errorf("短信API地址未配置")
+		return
+	}
+
+	jsonData, e := json.Marshal(params)
+	if e != nil {
+		err = fmt.Errorf("json marshal err: %v", e)
+		return
+	}
+	resp, e := http.Post(requestUrl, "application/json", bytes.NewBuffer(jsonData))
+	if e != nil {
+		err = fmt.Errorf("http post err: %v", e)
+		return
+	}
+	defer resp.Body.Close()
+	body, e := io.ReadAll(resp.Body)
+	if e != nil {
+		err = fmt.Errorf("read body err: %v", e)
+		return
+	}
+	result = string(body)
+	return
+}

+ 106 - 192
services/user.go

@@ -5,225 +5,139 @@ import (
 	"eta/eta_mini_api/models"
 	"eta/eta_mini_api/services/go_redis"
 	"eta/eta_mini_api/utils"
+	"fmt"
 	"time"
 )
 
 // BindUser 用户绑定
-func BindUser(unionId, openId, phone, email, areaCode string, departmentId int, realName string) (userItem *models.User, errMsg string, err error) {
-	if phone == "" && email == "" {
-		err = errors.New("手机号或邮箱必填一个")
-		return
-	}
-	// 根据openid获取用户信息
-	if openId == "" {
-		err = errors.New("openid不能为空")
-		return
-	}
-	userItem, err = models.GetUserByOpenId(openId)
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		return
-	}
-	var userId int
-	curTime := time.Now()
-	if userItem != nil {
-		userId = userItem.UserId
-		if userItem.Phone != "" && userItem.Phone != phone && phone != "" {
-			errMsg = "该手机号已绑定其他微信号"
+func BindUser(unionId, openId, phone, areaCode string) (userItem *models.UsersItem, tips string, err error) {
+	users := new(models.Users)
+	{
+		cond := fmt.Sprintf(` AND %s = ?`, users.Cols().OpenId)
+		pars := make([]interface{}, 0)
+		pars = append(pars, openId)
+		item, e := users.GetItemByCondition(cond, pars, "")
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = fmt.Errorf("OpenId获取用户信息失败, %v", e)
 			return
 		}
-		if userItem.Email != "" && userItem.Email != email && email != "" {
-			errMsg = "该邮箱已绑定其他微信号"
-			return
+		if item != nil {
+			users = item
 		}
-		if userItem.Phone == "" && phone != "" {
-			user := &models.User{
-				UserId:       userItem.UserId,
-				Phone:        phone,
-				AreaCode:     areaCode,
-				RegisterTime: curTime,
-				ModifyTime:   curTime,
-			}
-			updateUserErr := user.Update([]string{"phone", "area_code", "register_time", "modify_time"})
-			if updateUserErr != nil {
-				err = updateUserErr
-				return
-			}
-		}
-		if userItem.Email == "" && email != "" {
-			user := &models.User{
-				UserId:       userItem.UserId,
-				Email:        email,
-				RegisterTime: curTime,
-				ModifyTime:   curTime,
-			}
-			updateUserErr := user.Update([]string{"email", "modify_time", "register_time"})
-			if updateUserErr != nil {
-				err = updateUserErr
-				return
-			}
+	}
+
+	// open_id用户存在
+	var updateUsers, insertUsers bool
+	var updateCols []string
+	if users.UserId > 0 {
+		if users.Mobile != "" && users.Mobile != phone {
+			tips = "该微信号已绑定其他手机号"
+			err = fmt.Errorf("该微信号已绑定其他手机号, Mobile: %s, OpenId: %s", phone, openId)
+			return
 		}
-	} else {
-		//根据手机号获取用户信息
-		var phoneUser, emailUser *models.User
-		if phone != "" {
-			tmpUser, userErr := models.GetUserByPhone(phone)
-			if userErr != nil && userErr.Error() != utils.ErrNoRow() {
-				err = userErr
-				return
-			}
-			phoneUser = tmpUser
+		if users.Mobile == "" {
+			updateUsers = true
+			updateCols = append(updateCols, users.Cols().Mobile, users.Cols().AreaCode)
+			users.Mobile = phone
+			users.AreaCode = areaCode
 		}
-		//根据邮箱获取用户信息
-		if email != "" {
-			tmpUser, userErr := models.GetUserByEmail(email)
-			if userErr != nil && userErr.Error() != utils.ErrNoRow() {
-				err = userErr
-				return
-			}
-			emailUser = tmpUser
+		if users.IsRegistered == models.UserNoRegistered {
+			updateUsers = true
+			updateCols = append(updateCols, users.Cols().IsRegistered, users.Cols().RegisterTime)
+			users.IsRegistered = models.UserRegistered
+			users.RegisterTime = time.Now().Local()
 		}
-		// 理论上来说不会同时出现手机号和邮箱同时存在的情况
-		if phoneUser != nil && emailUser != nil && phoneUser.UserId != emailUser.UserId {
-			errMsg = "该手机号和邮箱已绑定其他微信号"
-			err = errors.New("该手机号和邮箱已绑定其他微信号")
+	}
+
+	// 匹配后台添加的用户
+	if users.UserId <= 0 {
+		cond := fmt.Sprintf(` AND %s = ?`, users.Cols().Mobile)
+		pars := make([]interface{}, 0)
+		pars = append(pars, phone)
+		item, e := users.GetItemByCondition(cond, pars, "")
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = fmt.Errorf("手机号获取用户信息失败, %v", e)
 			return
 		}
-		if phoneUser != nil {
-			userItem = phoneUser
+		if item != nil {
+			users = item
 		}
-		if emailUser != nil {
-			userItem = emailUser
-		}
-		//如果查询出来的用户是nil,那么需要新增用户
-		if userItem == nil {
-			key := utils.CACHE_ACCESS_WX_BIND + phone + ":" + email
-			isHas := go_redis.IsExist(key)
-			if isHas {
-				err = errors.New("多次提交,请关闭页面重新进入")
-				return
-			}
-			go_redis.SetNX(key, "ok", time.Second*300)
-			user := &models.User{
-				Phone:    phone,
-				AreaCode: areaCode,
-				Email:    email,
-				Status:   utils.UserStatusPotential,
-				OpenId:   openId,
-				UnionId:  unionId,
-			}
-			tmpUserId, addUserErr := user.Insert()
-			//添加完成,清除缓存
-			_ = go_redis.Delete(key)
-			if addUserErr != nil {
-				err = addUserErr
-				return
-			}
-			user.UserId = int(tmpUserId)
-			userId = int(tmpUserId)
-			userItem, err = models.GetUserById(userId)
-			if err != nil {
-				errMsg = "获取用户信息失败"
-				return
-			}
-		} else {
-			userItem.OpenId = openId
-			userItem.UnionId = unionId
-			err = userItem.Update([]string{"open_id", "union_id"})
-			if err != nil {
-				errMsg = "用户绑定失败"
+		if users.UserId > 0 {
+			if users.OpenId != "" && users.OpenId != openId {
+				tips = "该手机号已绑定其他微信号"
+				err = fmt.Errorf("该手机号已绑定其他微信号, Mobile: %s, OpenId: %s", phone, openId)
 				return
 			}
-			userId = userItem.UserId
+			updateUsers = true
+			updateCols = append(updateCols, users.Cols().OpenId, users.Cols().UnionId, users.Cols().IsRegistered, users.Cols().RegisterTime)
+			users.OpenId = openId
+			users.UnionId = unionId
+			users.IsRegistered = models.UserRegistered
+			users.RegisterTime = time.Now().Local()
 		}
 	}
 
-	//如果该用户 绑定注册状态 字段处于 未注册 的情况下,那么去修改该数据
-	if !userItem.IsRegistered {
-		err = models.ModifyUserRegisterStatus(userId, true, curTime, curTime)
-		if err != nil {
-			return
-		}
-	}
-	userRecord, er := models.GetUserRecordByUnionId(userItem.UnionId)
-	if er != nil && er.Error() != utils.ErrNoRow() {
-		err = errors.New("获取用户关注记录失败")
-		return
-	}
-	if !userItem.IsSubscribed && userRecord != nil {
-		userRecord.UserId = userId
-		er = userRecord.Update([]string{"user_id"})
-		if er != nil {
-			err = errors.New("获取用户关注记录失败")
+	// 匹配不上后台添加的,那么新增试用
+	if users.UserId <= 0 {
+		key := fmt.Sprint(utils.CACHE_ACCESS_WX_BIND, phone)
+		locked := go_redis.IsExist(key)
+		if locked {
+			err = errors.New("多次提交,请关闭页面重新进入")
 			return
 		}
-		userItem.IsSubscribed = true
-		er = userItem.Update([]string{"is_subscribed"})
-		if er != nil {
-			err = errors.New("获取用户关注记录失败")
-			return
-		}
-	}
+		go_redis.SetNX(key, "ok", time.Second*300)
+		defer func() {
+			_ = go_redis.Delete(key)
+		}()
 
-	msg, err := SaveUserInfo(userId, departmentId, realName)
-	if msg != "" {
-		errMsg = msg
+		users.Mobile = phone
+		users.AreaCode = areaCode
+		users.Status = models.UserStatusTrial
+		//users.AuthStatus = models.AuthStatusOpen
+		users.IsRegistered = models.UserRegistered
+		users.RegisterTime = time.Now().Local()
+		users.OpenId = openId
+		users.UnionId = unionId
+		users.CreateTime = time.Now().Local()
+		users.ModifyTime = time.Now().Local()
+		insertUsers = true
 	}
-	return
-}
 
-// SaveUserInfo 保存用户信息
-func SaveUserInfo(userId, departmentId int, realName string) (msg string, err error) {
-	user, err := models.GetUserById(userId)
-	if err != nil {
-		return
-	}
-	if user.RealName == "" && realName == "" {
-		msg = "请输入姓名"
-		return
-	}
-	updateCols := make([]string, 0)
-	if realName != "" && user.RealName != realName {
-		user.RealName = realName
-		updateCols = append(updateCols, "real_name")
-	}
-	if departmentId > 0 && user.SellerDepartmentId != departmentId {
-		department, er := models.GetSysDepartmentById(departmentId)
-		if er != nil {
-			err = er
-			if err.Error() == utils.ErrNoRow() {
-				msg = "部门不存在,请刷新重试"
-				return
-			}
-			msg = "获取部门信息失败"
+	// 新增/更新用户
+	if insertUsers {
+		if e := users.Create(); e != nil {
+			err = fmt.Errorf("新增试用用户失败, %v", e)
 			return
 		}
-		parentDepartment, er := models.GetSysDepartmentById(department.ParentId)
-		if er != nil {
-			err = er
-			if err.Error() == utils.ErrNoRow() {
-				msg = "父级部门不存在,请刷新重试"
-				return
-			}
-			msg = "获取部门信息失败"
-			return
-		}
-		if parentDepartment.SysDepartmentName != "营业部" {
-			msg = "部门信息异常"
+	}
+	if updateUsers {
+		updateCols = append(updateCols, users.Cols().ModifyTime)
+		users.ModifyTime = time.Now().Local()
+		if e := users.Update(updateCols); e != nil {
+			err = fmt.Errorf("更新用户失败, %v", e)
 			return
 		}
-		user.SellerDepartmentId = departmentId
-		user.SellerDepartmentName = department.SysDepartmentName
-		updateCols = append(updateCols, "seller_department_id")
-		updateCols = append(updateCols, "seller_department_name")
-	}
-	if (user.SellerDepartmentName == "" || user.SellerDepartmentId == 0) && departmentId <= 0 {
-		msg = "请选择营业部门"
-		return
-	}
-	err = user.Update(updateCols)
-	if err != nil {
-		msg = "用户信息保存失败"
-		return
 	}
+	userItem = users.Format2Item()
+
+	// 绑定UserId
+	//userRecord, e := models.GetUserRecordByUnionId(unionId)
+	//if e != nil && e.Error() != utils.ErrNoRow() {
+	//	err = fmt.Errorf("获取微信用户记录失败, %v", e)
+	//	return
+	//}
+	//if users.Subscribe == models.UserNoSubscribe && userRecord != nil {
+	//	users.Subscribe = models.UserSubscribed
+	//	if e := users.Update([]string{users.Cols().Subscribe}); e != nil {
+	//		err = fmt.Errorf("更新用户关注状态失败, %v", e)
+	//		return
+	//	}
+	//
+	//	userRecord.UserId = users.UserId
+	//	if e := userRecord.Update([]string{userRecord.Cols().UserId}); e != nil {
+	//		err = fmt.Errorf("更新用户绑定状态失败, %v", e)
+	//		return
+	//	}
+	//}
 	return
 }

+ 0 - 10
services/verify.go

@@ -1,10 +0,0 @@
-package services
-
-import "eta/eta_mini_api/utils"
-
-func CheckEncryption() (ok bool) {
-	if utils.RunMode == "release" {
-		ok = true
-	}
-	return
-}

+ 1 - 0
services/wechat.go

@@ -0,0 +1 @@
+package services

+ 145 - 158
services/wechat/template_msg.go

@@ -1,172 +1,159 @@
 package wechat
 
-import (
-	"bytes"
-	"context"
-	"encoding/json"
-	"errors"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/utils"
-	"fmt"
-	"io"
-	"net/http"
-	"time"
-)
+//var (
+//	TemplateMsgSendUrl       = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s"
+//	TemplateMsgClearQuotaUrl = "https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s"
+//)
 
-var (
-	TemplateMsgSendUrl       = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s"
-	TemplateMsgClearQuotaUrl = "https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s"
-)
+//type TemplateMsgSendClient struct {
+//	AccessToken string
+//	Data        []byte
+//}
 
-type TemplateMsgSendClient struct {
-	AccessToken string
-	Data        []byte
-}
+//type SendTemplateResponse struct {
+//	Errcode int    `json:"errcode"`
+//	Errmsg  string `json:"errmsg"`
+//	MsgID   int    `json:"msgid"`
+//}
 
-type SendTemplateResponse struct {
-	Errcode int    `json:"errcode"`
-	Errmsg  string `json:"errmsg"`
-	MsgID   int    `json:"msgid"`
-}
+//type ClearQuotaResponse struct {
+//	Errcode int    `json:"errcode"`
+//	Errmsg  string `json:"errmsg"`
+//}
 
-type ClearQuotaResponse struct {
-	Errcode int    `json:"errcode"`
-	Errmsg  string `json:"errmsg"`
-}
-
-type OpenIdList struct {
-	OpenId string
-	UserId int
-}
+//type OpenIdList struct {
+//	OpenId string
+//	UserId int
+//}
 
 // TemplateMsgSendClient.ClearQuota 清除发送超过当日10万次限制
-func (c *TemplateMsgSendClient) ClearQuota() (result *ClearQuotaResponse, err error) {
-	key := "CACHE_SendTemplateMsg_ERR"
-	exists, _ := utils.Redis.Exists(context.TODO(), key).Result()
-	if exists == 1 {
-		return
-	}
-	_ = utils.Redis.SetEX(context.TODO(), key, 1, 6*time.Minute)
-
-	sendUrl := fmt.Sprintf(TemplateMsgClearQuotaUrl, c.AccessToken)
-	client := http.Client{}
-	clearData := make(map[string]interface{})
-	clearData["appid"] = WxAppId
-	clearJson, _ := json.Marshal(clearData)
-	resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(clearJson))
-	if err != nil {
-		return
-	}
-	defer func() {
-		_ = resp.Body.Close()
-	}()
-	clearBody, err := io.ReadAll(resp.Body)
-	err = json.Unmarshal(clearBody, &result)
-	return
-}
+//func (c *TemplateMsgSendClient) ClearQuota() (result *ClearQuotaResponse, err error) {
+//	key := "CACHE_SendTemplateMsg_ERR"
+//	exists, _ := utils.Redis.Exists(context.TODO(), key).Result()
+//	if exists == 1 {
+//		return
+//	}
+//	_ = utils.Redis.SetEX(context.TODO(), key, 1, 6*time.Minute)
+//
+//	sendUrl := fmt.Sprintf(TemplateMsgClearQuotaUrl, c.AccessToken)
+//	client := http.Client{}
+//	clearData := make(map[string]interface{})
+//	clearData["appid"] = WxAppId
+//	clearJson, _ := json.Marshal(clearData)
+//	resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(clearJson))
+//	if err != nil {
+//		return
+//	}
+//	defer func() {
+//		_ = resp.Body.Close()
+//	}()
+//	clearBody, err := io.ReadAll(resp.Body)
+//	err = json.Unmarshal(clearBody, &result)
+//	return
+//}
 
 // TemplateMsgSendClient.SendMsg 推送消息
-func (c *TemplateMsgSendClient) SendMsg() (sendRes *SendTemplateResponse, err error) {
-	// 请求接口
-	sendUrl := fmt.Sprintf(TemplateMsgSendUrl, c.AccessToken)
-	client := http.Client{}
-	resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(c.Data))
-	if err != nil {
-		return
-	}
-	defer func() {
-		_ = resp.Body.Close()
-	}()
-	body, _ := io.ReadAll(resp.Body)
-	if err = json.Unmarshal(body, &sendRes); err != nil {
-		return
-	}
-	// 模板消息发送超过当日10万次限制错误处理
-	if sendRes.Errcode == 45009 {
-		// 发送提示邮件
-		// 清理限制
-		clearRes, e := c.ClearQuota()
-		if e != nil {
-			err = e
-			return
-		}
-		if clearRes.Errcode != 0 {
-			clearJson, er := json.Marshal(clearRes)
-			if er != nil {
-				return nil, er
-			}
-			fmt.Println("自动清理模板消息限制接口, 调用失败, ClearQuotaResponse: " + string(clearJson))
-			return
-		}
-		// 发送成功邮件
-		// 重新推送
-		go func() {
-			_, e := c.SendMsg()
-			if e != nil {
-				return
-			}
-		}()
-	}
-	if sendRes.Errcode != 0 {
-		err = errors.New("推送模板消息失败, SendTemplateResponse: " + string(body))
-	}
-	return
-}
+//func (c *TemplateMsgSendClient) SendMsg() (sendRes *SendTemplateResponse, err error) {
+//	// 请求接口
+//	sendUrl := fmt.Sprintf(TemplateMsgSendUrl, c.AccessToken)
+//	client := http.Client{}
+//	resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(c.Data))
+//	if err != nil {
+//		return
+//	}
+//	defer func() {
+//		_ = resp.Body.Close()
+//	}()
+//	body, _ := io.ReadAll(resp.Body)
+//	if err = json.Unmarshal(body, &sendRes); err != nil {
+//		return
+//	}
+//	// 模板消息发送超过当日10万次限制错误处理
+//	if sendRes.Errcode == 45009 {
+//		// 发送提示邮件
+//		// 清理限制
+//		clearRes, e := c.ClearQuota()
+//		if e != nil {
+//			err = e
+//			return
+//		}
+//		if clearRes.Errcode != 0 {
+//			clearJson, er := json.Marshal(clearRes)
+//			if er != nil {
+//				return nil, er
+//			}
+//			fmt.Println("自动清理模板消息限制接口, 调用失败, ClearQuotaResponse: " + string(clearJson))
+//			return
+//		}
+//		// 发送成功邮件
+//		// 重新推送
+//		go func() {
+//			_, e := c.SendMsg()
+//			if e != nil {
+//				return
+//			}
+//		}()
+//	}
+//	if sendRes.Errcode != 0 {
+//		err = errors.New("推送模板消息失败, SendTemplateResponse: " + string(body))
+//	}
+//	return
+//}
 
 // AddUserTemplateRecord 新增模板消息推送记录
-func AddUserTemplateRecord(userId, sendStatus, sendType int, openid, resource, sendData, result string) (err error) {
-	item := &models.UserTemplateRecord{
-		UserID:     userId,
-		OpenID:     openid,
-		Resource:   resource,
-		SendData:   sendData,
-		Result:     result,
-		CreateDate: time.Now().Format(utils.FormatDate),
-		CreateTime: time.Now().Format(utils.FormatDateTime),
-		SendStatus: sendStatus,
-		SendType:   sendType,
-	}
-	err = item.Insert()
-	return
-}
+//func AddUserTemplateRecord(userId, sendStatus, sendType int, openid, resource, sendData, result string) (err error) {
+//	item := &models.UserTemplateRecord{
+//		UserID:     userId,
+//		OpenID:     openid,
+//		Resource:   resource,
+//		SendData:   sendData,
+//		Result:     result,
+//		CreateDate: time.Now().Format(utils.FormatDate),
+//		CreateTime: time.Now().Format(utils.FormatDateTime),
+//		SendStatus: sendStatus,
+//		SendType:   sendType,
+//	}
+//	err = item.Insert()
+//	return
+//}
 
 // SendMultiTemplateMsg 推送模板消息至多个用户
-func SendMultiTemplateMsg(sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
-	ws := GetWxChat()
-	accessToken, err := ws.GetAccessToken()
-	if err != nil {
-		return
-	}
-	for _, item := range items {
-		sendMap["touser"] = item.OpenId
-		data, e := json.Marshal(sendMap)
-		if e != nil {
-			err = e
-			return
-		}
-		ts := &TemplateMsgSendClient{
-			AccessToken: accessToken,
-			Data:        data,
-		}
-		result, e := ts.SendMsg()
-		if result == nil {
-			return
-		}
-		// 推送消息记录
-		{
-			go func(v *OpenIdList) {
-				sendStatus := 1
-				if e != nil {
-					sendStatus = 0
-				}
-				resultJson, _ := json.Marshal(result)
-				_ = AddUserTemplateRecord(v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
-			}(item)
-		}
-		if e != nil {
-			err = e
-			return
-		}
-	}
-	return
-}
+//func SendMultiTemplateMsg(sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
+//	ws := GetWxChat()
+//	accessToken, err := ws.GetAccessToken()
+//	if err != nil {
+//		return
+//	}
+//	for _, item := range items {
+//		sendMap["touser"] = item.OpenId
+//		data, e := json.Marshal(sendMap)
+//		if e != nil {
+//			err = e
+//			return
+//		}
+//		ts := &TemplateMsgSendClient{
+//			AccessToken: accessToken,
+//			Data:        data,
+//		}
+//		result, e := ts.SendMsg()
+//		if result == nil {
+//			return
+//		}
+//		// 推送消息记录
+//		{
+//			go func(v *OpenIdList) {
+//				sendStatus := 1
+//				if e != nil {
+//					sendStatus = 0
+//				}
+//				resultJson, _ := json.Marshal(result)
+//				_ = AddUserTemplateRecord(v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
+//			}(item)
+//		}
+//		if e != nil {
+//			err = e
+//			return
+//		}
+//	}
+//	return
+//}

+ 92 - 106
services/wechat/wechat.go

@@ -1,72 +1,58 @@
 package wechat
 
 import (
-	"encoding/json"
-	"eta/eta_mini_api/models"
-	"eta/eta_mini_api/services/alarm_msg"
-	"eta/eta_mini_api/utils"
 	"fmt"
-	"io"
-	"net/http"
-	"time"
-
-	"github.com/silenceper/wechat/v2"
-	"github.com/silenceper/wechat/v2/cache"
 	"github.com/silenceper/wechat/v2/credential"
-	"github.com/silenceper/wechat/v2/officialaccount"
-	"github.com/silenceper/wechat/v2/officialaccount/config"
-	"github.com/silenceper/wechat/v2/officialaccount/js"
-	"github.com/silenceper/wechat/v2/officialaccount/user"
-)
-
-var (
-	WxAppId     string
-	WxAppSecret string
 )
 
-type WechatAccessToken struct {
-}
-
-func GetWxChat() (officialAccount *officialaccount.OfficialAccount) {
-	wc := wechat.NewWechat()
-	memory := cache.NewMemory()
-	conf := &config.Config{
-		AppID:          utils.DW_WX_APPID,
-		AppSecret:      utils.DW_WX_APP_SECRET,
-		Token:          "",
-		EncodingAESKey: "",
-		Cache:          memory,
-	}
-	officialAccount = wc.GetOfficialAccount(conf)
-	wechatAccessToken := &WechatAccessToken{}
-	officialAccount.SetAccessTokenHandle(wechatAccessToken)
-	return
-}
+//var (
+//	WxAppId     string
+//	WxAppSecret string
+//)
+
+//type WechatAccessToken struct {
+//}
+
+//func GetWxChat() (officialAccount *officialaccount.OfficialAccount) {
+//	wc := wechat.NewWechat()
+//	memory := cache.NewMemory()
+//	conf := &config.Config{
+//		AppID:          utils.WX_APPID,
+//		AppSecret:      utils.WX_APP_SECRET,
+//		Token:          "",
+//		EncodingAESKey: "",
+//		Cache:          memory,
+//	}
+//	officialAccount = wc.GetOfficialAccount(conf)
+//	wechatAccessToken := &WechatAccessToken{}
+//	officialAccount.SetAccessTokenHandle(wechatAccessToken)
+//	return
+//}
 
-var DefaultKey = "zcmRedis"
+//var DefaultKey = "zcmRedis"
 
 // GetAccessToken 获取accessToken
-func (wechat WechatAccessToken) GetAccessToken() (accessToken string, err error) {
-	wxToken, err := models.GetWxTokenById()
-	if err != nil && err.Error() != utils.ErrNoRow() {
-		return
-	}
-	//如果300s就要过期了,那么就去刷新accessToken
-	if wxToken.ExpiresIn < time.Now().Unix()+300 {
-		tmpAccessToken, expires, tmpErr := getTokenFromServer(utils.DW_WX_APPID, utils.DW_WX_APP_SECRET)
-		if tmpErr != nil {
-			err = tmpErr
-			return
-		}
-
-		var updateCols = []string{"access_token", "expires_in"}
-		wxToken.AccessToken = tmpAccessToken
-		wxToken.ExpiresIn = time.Now().Unix() + expires - 600 //快过期前10分钟就刷新掉
-		wxToken.Update(updateCols)
-	}
-	accessToken = wxToken.AccessToken
-	return
-}
+//func (wechat WechatAccessToken) GetAccessToken() (accessToken string, err error) {
+//	wxToken, err := models.GetWxTokenById()
+//	if err != nil && err.Error() != utils.ErrNoRow() {
+//		return
+//	}
+//	//如果300s就要过期了,那么就去刷新accessToken
+//	if wxToken.ExpiresIn < time.Now().Unix()+300 {
+//		tmpAccessToken, expires, tmpErr := getTokenFromServer(utils.WX_APPID, utils.WX_APP_SECRET)
+//		if tmpErr != nil {
+//			err = tmpErr
+//			return
+//		}
+//
+//		var updateCols = []string{"access_token", "expires_in"}
+//		wxToken.AccessToken = tmpAccessToken
+//		wxToken.ExpiresIn = time.Now().Unix() + expires - 600 //快过期前10分钟就刷新掉
+//		wxToken.Update(updateCols)
+//	}
+//	accessToken = wxToken.AccessToken
+//	return
+//}
 
 // accessToken, err = utils.Redis.Get(context.TODO(), utils.CACHE_WX_ACCESS_TOKEN_DW).Result()
 // // wxToken, err := models.GetWxTokenById()
@@ -114,12 +100,12 @@ func getTokenFromServer(appid, wxSecret string) (accessToken string, expires int
 }
 
 // GetUserInfo 获取微信用户详情
-func GetUserInfo(openid string) (userInfo *user.Info, err error) {
-	wechatClient := GetWxChat()
-	userClient := wechatClient.GetUser()
-	userInfo, err = userClient.GetUserInfo(openid)
-	return
-}
+//func GetUserInfo(openid string) (userInfo *user.Info, err error) {
+//	wechatClient := GetWxChat()
+//	userClient := wechatClient.GetUser()
+//	userInfo, err = userClient.GetUserInfo(openid)
+//	return
+//}
 
 // GetSession 获取用户详情
 // func GetSession(code string) (userInfo auth.ResCode2Session, err error) {
@@ -130,44 +116,44 @@ func GetUserInfo(openid string) (userInfo *user.Info, err error) {
 // }
 
 // GetJsConfig 获取公众号jsConfig
-func GetJsConfig(signUrl string) (jsConf *js.Config, err error) {
-	wechatClient := GetWxChat()
-	j := wechatClient.GetJs()
-	jsConf, err = j.GetConfig(signUrl)
-	return
-}
-
-type WxUserInfo struct {
-	OpenId       string `json:"openid"`
-	AccessToken  string `json:"access_token"`
-	RefreshToken string `json:"refresh_token"`
-	Scope        string `json:"scope"`
-	ErrCode      int
-	ErrMsg       string
-}
-
-func GetWxUserInfo(code string) (info *WxUserInfo, err error) {
-	httpUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
-
-	httpUrl = fmt.Sprintf(httpUrl, utils.DW_WX_APPID, utils.DW_WX_APP_SECRET, code)
-
-	client := http.Client{}
-	wxReq, err := http.NewRequest("GET", httpUrl, nil)
-	if err != nil {
-		return
-	}
-	response, err := client.Do(wxReq)
-	if err != nil {
-		return
-	}
-	defer response.Body.Close()
-	body, err := io.ReadAll(response.Body)
-	if err != nil {
-		return
-	}
-	alarm_msg.SendAlarmMsg(string(body), 1)
-	if err = json.Unmarshal(body, &info); err != nil {
-		return
-	}
-	return
-}
+//func GetJsConfig(signUrl string) (jsConf *js.Config, err error) {
+//	wechatClient := GetWxChat()
+//	j := wechatClient.GetJs()
+//	jsConf, err = j.GetConfig(signUrl)
+//	return
+//}
+
+//type WxUserInfo struct {
+//	OpenId       string `json:"openid"`
+//	AccessToken  string `json:"access_token"`
+//	RefreshToken string `json:"refresh_token"`
+//	Scope        string `json:"scope"`
+//	ErrCode      int
+//	ErrMsg       string
+//}
+
+//func GetWxUserInfo(code string) (info *WxUserInfo, err error) {
+//	httpUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
+//
+//	httpUrl = fmt.Sprintf(httpUrl, utils.WX_APPID, utils.WX_APP_SECRET, code)
+//
+//	client := http.Client{}
+//	wxReq, err := http.NewRequest("GET", httpUrl, nil)
+//	if err != nil {
+//		return
+//	}
+//	response, err := client.Do(wxReq)
+//	if err != nil {
+//		return
+//	}
+//	defer response.Body.Close()
+//	body, err := io.ReadAll(response.Body)
+//	if err != nil {
+//		return
+//	}
+//	alarm_msg.SendAlarmMsg(string(body), 1)
+//	if err = json.Unmarshal(body, &info); err != nil {
+//		return
+//	}
+//	return
+//}

+ 25 - 0
utils/common.go

@@ -196,3 +196,28 @@ func SetKeyExpireToday() time.Duration {
 	endOfDay := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location())
 	return time.Until(endOfDay)
 }
+
+// GetOrmInReplace 获取orm的in查询替换?的方法
+func GetOrmInReplace(num int) string {
+	template := make([]string, num)
+	for i := 0; i < num; i++ {
+		template[i] = "?"
+	}
+	return strings.Join(template, ",")
+}
+
+func TimeTransferString(format string, t time.Time) string {
+	str := t.Format(format)
+	if t.IsZero() {
+		return ""
+	}
+	return str
+}
+
+// HideMobileMiddle 隐藏大陆手机号中间四位
+func HideMobileMiddle(mobile string) string {
+	if !ValidateMobileFormatat(mobile) {
+		return mobile
+	}
+	return fmt.Sprintf("%s****%s", mobile[:3], mobile[7:])
+}

+ 23 - 36
utils/config.go

@@ -16,7 +16,6 @@ var (
 	RunMode          string
 	MYSQL_URL_MASTER string
 	MYSQL_URL_RDDP   string
-	MYSQL_URL        string //数据库连接
 
 	REDIS_CACHE string        //缓存地址
 	Redis       *redis.Client //redis链接
@@ -41,27 +40,16 @@ var AlarmMsgUrl string // 报警地址
 
 // 微信相关
 var (
-	WX_MINI_APPID          string
-	WX_MINI_APP_SECRET     string
-	DW_WX_Id               string //微信原始ID
-	DW_WX_APPID            string // 东吴公众号appid
-	DW_WX_APP_SECRET       string
-	TEMPLATE_ID_BY_PRODUCT string
+	WX_MINI_APPID      string
+	WX_MINI_APP_SECRET string
+	//WX_ORIGIN_ID       string
+	//WX_APPID           string
+	//WX_APP_SECRET      string
 )
 
-// 桥接服务
-var (
-	ETA_MINI_BRIDGE_URL string
-	ETA_MINI_APPID      string
-	ETA_MINI_APP_SECRET string
-)
-var DesKey string // 接口返回加密KEY
+var SmsApiUrl string // 金瑞短信API调用地址
 
-// 自定义的品种名称
-var (
-	MINI_CUSTOM_PERMISSION_NAME string
-	ZC_CUSTOM_PERMISSION_NAME   string
-)
+var DesKey string // 接口返回加密KEY
 
 func init() {
 	tmpRunMode, err := web.AppConfig.String("run_mode")
@@ -86,7 +74,6 @@ func init() {
 		panic(any("配置文件读取错误 " + err.Error()))
 	}
 	beeLogger.Log.Info(RunMode + " 模式")
-	MYSQL_URL = config["mysql_url"]
 	MYSQL_URL_RDDP = config["mysql_url_rddp"]
 	MYSQL_URL_MASTER = config["mysql_url_master"]
 
@@ -96,23 +83,11 @@ func init() {
 	WX_MINI_APPID = config["wx_mini_appid"]
 	WX_MINI_APP_SECRET = config["wx_mini_app_secret"]
 
-	DW_WX_Id = config["dw_wx_id"]
-	DW_WX_APPID = config["dw_wx_appid"]
-	DW_WX_APP_SECRET = config["dw_wx_app_secret"]
-	TEMPLATE_ID_BY_PRODUCT = config["template_id_by_product"]
+	//WX_ORIGIN_ID = config["wx_origin_id"]
+	//WX_APPID = config["wx_appid"]
+	//WX_APP_SECRET = config["wx_app_secret"]
 
-	ETA_MINI_BRIDGE_URL = config["eta_mini_bridge_url"]
-	ETA_MINI_APPID = config["eta_mini_appid"]
-	ETA_MINI_APP_SECRET = config["eta_mini_app_secret"]
-
-	MINI_CUSTOM_PERMISSION_NAME = config["mini_custom_permission_name"]
-	if MINI_CUSTOM_PERMISSION_NAME == "" {
-		MINI_CUSTOM_PERMISSION_NAME = "PDF报告"
-	}
-	ZC_CUSTOM_PERMISSION_NAME = config["zc_custom_permission_name"]
-	if ZC_CUSTOM_PERMISSION_NAME == "" {
-		ZC_CUSTOM_PERMISSION_NAME = "PDF报告"
-	}
+	SmsApiUrl = config["sms_api_url"]
 
 	initRedis(config)
 }
@@ -148,6 +123,18 @@ func initRedis(config map[string]string) {
 		panic("redis 链接失败:" + err.Error())
 	}
 
+	// 日志配置
+	{
+		LogPath = config["log_path"]
+		LogFile = config["log_file"]
+		BinLogPath = config["binlog_path"]
+		BinLogFile = config["binlog_file"]
+		ApiLogPath = config["apilog_path"]
+		ApiLogFile = config["apilog_file"]
+		logMaxDaysStr := config["log_max_day"]
+		LogMaxDays, _ = strconv.Atoi(logMaxDaysStr)
+	}
+
 	//全局赋值redis链接
 	Redis = client
 }

+ 5 - 19
utils/constants.go

@@ -18,27 +18,14 @@ const (
 )
 
 const (
-	ReportStatePushCancel = 0 // 未推送
-	ReportStatePush       = 1 // 已推送
-)
-
-// 用户状态定义
-const (
-	UserStatusNo        = 0 //禁用
-	UserStatusPotential = 1 //潜在用户
-	UserStatusFormal    = 2 //正式用户
-)
-
-// 权限类型
-const (
-	PermissionTypeEta  = 1 // eta的品种权限
-	PermissionTypeMini = 2 // 小程序的品种权限
+	UserStatusNoLogin = 0 // 用户状态-未登录
+	UserStatusIsLogin = 1 // 用户状态-已登录
 )
 
 // 报告类型
 const (
-	ReportTypeEta = 1 // eta的研报
-	ReportTypePdf = 2 // pdf的研报
+	ReportSourceDefault = 1 // 研报中心
+	ReportSourceOutside = 2 // 文档管理库
 )
 
 // 常量定义
@@ -72,7 +59,7 @@ const (
 )
 
 const (
-	APPNAME = "东吴研报小程序"
+	APPNAME = "金瑞研报小程序"
 )
 
 const (
@@ -85,7 +72,6 @@ const (
 	CACHE_ACCESS_PHONE_COUNT_LOGIN_CODE = "eta_mini_api:login:phone_count:" //手机验证码登录次数key
 )
 
-// 缓存key
 const (
 	CACHE_WX_ACCESS_TOKEN_DW = "wx:accesstoken:dw" //东吴公众号 微信accessToken
 )