Browse Source

Merge branch 'feature/eta_1.1.9'

hsun 1 year ago
parent
commit
79033e31f4

+ 1216 - 0
controllers/smart_report/smart_report.go

@@ -0,0 +1,1216 @@
+package smart_report
+
+import (
+	"encoding/json"
+	"eta/eta_api/controllers"
+	"eta/eta_api/models"
+	"eta/eta_api/models/smart_report"
+	"eta/eta_api/models/system"
+	"eta/eta_api/services"
+	smartReportService "eta/eta_api/services/smart_report"
+	"eta/eta_api/utils"
+	"fmt"
+	"github.com/kgiannakakis/mp3duration/src/mp3duration"
+	"github.com/rdlucklib/rdluck_tools/paging"
+	"html"
+	"io/ioutil"
+	"os"
+	"path"
+	"strings"
+	"time"
+)
+
+// SmartReportController 智能研报
+type SmartReportController struct {
+	controllers.BaseAuthController
+}
+
+// Add
+// @Title 新增
+// @Description 新增
+// @Param	request	body smart_report.SmartReportAddReq true "type json string"
+// @Success 200 {object} smart_report.SmartReportItem
+// @router /add [post]
+func (this *SmartReportController) Add() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportAddReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.AddType != 1 && req.AddType != 2 {
+		br.Msg = "请选择新增方式"
+		return
+	}
+	if req.ClassifyIdFirst <= 0 || req.ClassifyIdSecond <= 0 {
+		br.Msg = "请选择分类"
+		return
+	}
+	req.Title = strings.TrimSpace(req.Title)
+	if req.Title == "" {
+		br.Msg = "请输入标题"
+		return
+	}
+
+	reportOB := new(smart_report.SmartReport)
+	stageMax, e := reportOB.GetMaxStageByClassifyId(req.ClassifyIdSecond)
+	if e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取期数失败, Err: " + e.Error()
+		return
+	}
+	stageMax += 1
+
+	item := new(smart_report.SmartReport)
+	item.AddType = req.AddType
+	item.ClassifyIdFirst = req.ClassifyIdFirst
+	item.ClassifyNameFirst = req.ClassifyNameFirst
+	item.ClassifyIdSecond = req.ClassifyIdSecond
+	item.ClassifyNameSecond = req.ClassifyNameSecond
+	item.Title = req.Title
+	item.Abstract = req.Abstract
+	item.Author = req.Author
+	item.Frequency = req.Frequency
+	item.Stage = stageMax
+	item.AdminId = sysUser.AdminId
+	item.AdminRealName = sysUser.RealName
+	item.LastModifyAdminId = sysUser.AdminId
+	item.LastModifyAdminName = sysUser.RealName
+	item.State = smart_report.SmartReportStateWaitPublish
+	item.CreateTime = time.Now().Local()
+	item.ModifyTime = time.Now().Local()
+	// 继承报告
+	if req.AddType == 2 {
+		ob := new(smart_report.SmartReport)
+		cond := ` AND classify_id_first = ? AND classify_id_second = ?`
+		pars := make([]interface{}, 0)
+		pars = append(pars, req.ClassifyIdFirst, req.ClassifyIdSecond)
+		lastReport, e := ob.GetItemByCondition(cond, pars, "stage DESC")
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取往期研报失败, Err: " + e.Error()
+			return
+		}
+		if lastReport != nil {
+			item.Content = lastReport.Content
+			item.ContentSub = lastReport.ContentSub
+			item.ContentStruct = lastReport.ContentStruct
+		}
+	}
+	if e = item.Create(); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "新增研报失败, Err: " + e.Error()
+		return
+	}
+	uniqueCode := utils.MD5(fmt.Sprint("smart_", item.SmartReportId))
+	item.ReportCode = uniqueCode
+	if e = item.Update([]string{"ReportCode"}); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "更新研报编码失败, Err: " + e.Error()
+		return
+	}
+	resp := smart_report.FormatSmartReport2Item(item)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+	br.Data = resp
+}
+
+// Edit
+// @Title 编辑
+// @Description 编辑
+// @Param	request	body smart_report.SmartReportEditReq true "type json string"
+// @Success 200 {object} smart_report.SmartReportItem
+// @router /edit [post]
+func (this *SmartReportController) Edit() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportEditReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.SmartReportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = "报告ID为空"
+		return
+	}
+	if req.ClassifyIdFirst <= 0 || req.ClassifyIdSecond <= 0 {
+		br.Msg = "请选择分类"
+		return
+	}
+	req.Title = strings.TrimSpace(req.Title)
+	if req.Title == "" {
+		br.Msg = "请输入标题"
+		return
+	}
+	var subContent string
+	if req.Content != "" {
+		req.Content = html.EscapeString(req.Content)
+		// 前两个章节
+		sub, e := services.GetReportContentSub(req.Content)
+		if e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = "读取报告前两个章节内容失败, Err: " + e.Error()
+			return
+		}
+		subContent = html.EscapeString(sub)
+	}
+	req.ContentStruct = html.EscapeString(req.ContentStruct)
+
+	ob := new(smart_report.SmartReport)
+	item, e := ob.GetItemById(req.SmartReportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取研报失败, Err: " + e.Error()
+		return
+	}
+	if item.State == 2 {
+		br.Msg = "报告已发布, 请取消发布后编辑"
+		return
+	}
+
+	// 内容是否变更, 只有内容产生变更时, 才更新最后更新人和内容更新时间字段
+	contentModify := false
+	if item.ClassifyIdFirst != req.ClassifyIdFirst ||
+		item.ClassifyIdSecond != req.ClassifyIdSecond ||
+		item.Title != req.Title ||
+		item.Abstract != req.Abstract ||
+		item.Frequency != req.Frequency ||
+		utils.MD5(item.Content) != utils.MD5(req.Content) {
+		contentModify = true
+	}
+	cols := []string{"ClassifyIdFirst", "ClassifyNameFirst", "ClassifyIdSecond", "ClassifyNameSecond", "Title", "Abstract", "Author",
+		"Frequency", "Content", "ContentSub", "ContentStruct", "ModifyTime"}
+	item.ClassifyIdFirst = req.ClassifyIdFirst
+	item.ClassifyNameFirst = req.ClassifyNameFirst
+	item.ClassifyIdSecond = req.ClassifyIdSecond
+	item.ClassifyNameSecond = req.ClassifyNameSecond
+	item.Title = req.Title
+	item.Abstract = req.Abstract
+	item.Author = req.Author
+	item.Frequency = req.Frequency
+	item.Content = req.Content
+	item.ContentSub = subContent
+	item.ContentStruct = req.ContentStruct
+	item.ModifyTime = time.Now().Local()
+	if contentModify {
+		//fmt.Println(contentModify)
+		item.LastModifyAdminId = sysUser.AdminId
+		item.LastModifyAdminName = sysUser.RealName
+		item.ContentModifyTime = time.Now().Local()
+		cols = append(cols, "LastModifyAdminId", "LastModifyAdminName", "ContentModifyTime")
+	}
+	if e := item.Update(cols); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "更新报告失败, Err: " + e.Error()
+		return
+	}
+	resp := smart_report.FormatSmartReport2Item(item)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+	br.Data = resp
+}
+
+// Remove
+// @Title 删除
+// @Description 删除
+// @Param	request	body smart_report.SmartReportRemoveReq true "type json string"
+// @Success 200 string "操作成功"
+// @router /remove [post]
+func (this *SmartReportController) Remove() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportRemoveReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.SmartReportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = "报告ID为空"
+		return
+	}
+
+	ob := new(smart_report.SmartReport)
+	item, e := ob.GetItemById(req.SmartReportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Ret = 200
+			br.Success = true
+			br.Msg = "操作成功"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取研报失败, Err: " + e.Error()
+		return
+	}
+	if e = item.Del(); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "删除报告失败, Err: " + e.Error()
+		return
+	}
+
+	// ES更新报告为未发布
+	go func() {
+		_ = smartReportService.SmartReportElasticUpsert(item.SmartReportId, 1)
+	}()
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+}
+
+// Detail
+// @Title 详情
+// @Description 详情
+// @Param   SmartReportId	query	int	true	"智能研报ID"
+// @Success 200 {object} smart_report.SmartReportItem
+// @router /detail [get]
+func (this *SmartReportController) Detail() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	reportId, _ := this.GetInt("SmartReportId")
+	if reportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = "报告ID有误"
+		return
+	}
+
+	ob := new(smart_report.SmartReport)
+	item, e := ob.GetItemById(reportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取研报失败, Err: " + e.Error()
+		return
+	}
+	resp := smart_report.FormatSmartReport2Item(item)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// Publish
+// @Title 发布/取消发布
+// @Description 发布/取消发布
+// @Param	request	body smart_report.SmartReportPublishReq true "type json string"
+// @Success 200 string "操作成功"
+// @router /publish [post]
+func (this *SmartReportController) Publish() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportPublishReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.SmartReportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = "报告ID为空"
+		return
+	}
+	if req.PublishState != smart_report.SmartReportStateWaitPublish && req.PublishState != smart_report.SmartReportStatePublished {
+		br.Msg = "参数有误"
+		return
+	}
+
+	ob := new(smart_report.SmartReport)
+	item, e := ob.GetItemById(req.SmartReportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取研报失败, Err: " + e.Error()
+		return
+	}
+
+	cols := []string{"State", "ModifyTime"}
+	item.State = req.PublishState
+	item.ModifyTime = time.Now().Local()
+	if req.PublishState == smart_report.SmartReportStatePublished {
+		cols = append(cols, "PublishTime")
+		item.PublishTime = time.Now().Local()
+
+		// 写入队列
+		var queue smart_report.Report2ImgQueueReq
+		queue.ReportType = 2
+		queue.ReportCode = item.ReportCode
+		_ = utils.Rc.LPush(utils.CACHE_CREATE_REPORT_IMGPDF_QUEUE, queue)
+	}
+	// 取消发布时同时清除掉Img和PDF的文件地址
+	if req.PublishState == smart_report.SmartReportStateWaitPublish {
+		cols = append(cols, "DetailImgUrl", "DetailPdfUrl")
+		item.DetailImgUrl = ""
+		item.DetailPdfUrl = ""
+	}
+	if e = item.Update(cols); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "更新研报失败, Err: " + e.Error()
+		return
+	}
+
+	// 生成音频
+	if req.PublishState == smart_report.SmartReportStatePublished && item.VideoUrl == "" {
+		go smartReportService.SmartReportBuildVideoAndUpdate(item)
+	}
+
+	// ES更新报告
+	go func() {
+		_ = smartReportService.SmartReportElasticUpsert(item.SmartReportId, req.PublishState)
+	}()
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+}
+
+// PrePublish
+// @Title 设置定时发布
+// @Description 设置定时发布
+// @Param	request	body smart_report.SmartReportPrePublishReq true "type json string"
+// @Success 200 string "操作成功"
+// @router /pre_publish [post]
+func (this *SmartReportController) PrePublish() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportPrePublishReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	reportId := req.SmartReportId
+	if reportId == 0 {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,报告id不可为空"
+		return
+	}
+	if req.PrePublishTime == "" {
+		br.Msg = "发布时间不能为空"
+		return
+	}
+	if req.PreMsgSend != 0 && req.PreMsgSend != 1 {
+		br.Msg = "参数错误"
+		br.ErrMsg = "是否发送模版消息标识错误"
+		return
+	}
+	preTime, e := time.ParseInLocation(utils.FormatDateTime, req.PrePublishTime, time.Local)
+	if e != nil {
+		br.Msg = "发布时间格式错误"
+		br.ErrMsg = "发布时间格式错误,Err:" + e.Error()
+		return
+	}
+	if preTime.Before(time.Now()) {
+		br.Msg = "发布时间不允许选择过去时间"
+		return
+	}
+	if preTime.Before(time.Now().Add(2 * time.Minute)) {
+		br.Msg = "发布时间距离当前时间太近了"
+		return
+	}
+
+	reportOB := new(smart_report.SmartReport)
+	item, e := reportOB.GetItemById(reportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "获取报告失败"
+		br.ErrMsg = "获取报告失败, Err:" + e.Error()
+		return
+	}
+	if item.Content == "" {
+		br.Msg = "报告内容为空, 不可发布"
+		return
+	}
+	if item.State == 2 {
+		br.Msg = "报告已发布, 不可设置定时发布"
+		return
+	}
+
+	item.PrePublishTime = preTime
+	item.PreMsgSend = req.PreMsgSend
+	cols := []string{"PrePublishTime", "PreMsgSend"}
+	if e = item.Update(cols); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "更新报告预发布失败, Err: " + e.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+}
+
+// SendMsg
+// @Title 消息推送
+// @Description 消息推送
+// @Param	request	body models.SendTemplateMsgReq true "type json string"
+// @Success 200 Ret=200 推送成功
+// @router /send_msg [post]
+func (this *SmartReportController) SendMsg() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportSendMsgReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.SmartReportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = fmt.Sprintf("参数有误, SmartReportId: %d", req.SmartReportId)
+		return
+	}
+
+	// 避免重复推送
+	{
+		redisKey := fmt.Sprint(utils.CACHE_SMART_REPORT_SEND_MSG, req.SmartReportId)
+		ok := utils.Rc.SetNX(redisKey, 1, time.Second*300)
+		if !ok {
+			br.Msg = "报告已推送, 请勿重复推送"
+			return
+		}
+		defer func() {
+			_ = utils.Rc.Delete(redisKey)
+		}()
+	}
+
+	reportOB := new(smart_report.SmartReport)
+	item, e := reportOB.GetItemById(req.SmartReportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取报告失败, Err: " + e.Error()
+		return
+	}
+	if item.MsgIsSend == 1 {
+		br.Msg = "消息已推送,请勿重复操作"
+		return
+	}
+	if item.State != 2 {
+		br.Msg = "报告未发布, 不可推送"
+		return
+	}
+
+	item.MsgIsSend = 1
+	item.MsgSendTime = time.Now().Local()
+	item.ModifyTime = time.Now().Local()
+	if e = item.Update([]string{"MsgIsSend", "MsgSendTime", "ModifyTime"}); e != nil {
+		br.Msg = "操作失败"
+		br.ErrMsg = "更新报告推送状态失败, Err: " + e.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+	br.IsAddLog = true
+}
+
+// SaveContent
+// @Title 保存草稿
+// @Description 保存草稿
+// @Param	request	body smart_report.SmartReportSaveContentReq true "type json string"
+// @Success 200 {object} smart_report.SmartReportSaveContentResp
+// @router /save_content [post]
+func (this *SmartReportController) SaveContent() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportSaveContentReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	resp := new(smart_report.SmartReportSaveContentResp)
+	if req.SmartReportId <= 0 {
+		br.Ret = 200
+		br.Success = true
+		br.Msg = "操作成功"
+		br.Data = resp
+		return
+	}
+
+	reportOB := new(smart_report.SmartReport)
+	item, _ := reportOB.GetItemById(req.SmartReportId)
+	if item == nil {
+		br.Ret = 200
+		br.Success = true
+		br.Msg = "操作成功"
+		br.Data = resp
+		return
+	}
+	if item.State == smart_report.SmartReportStatePublished {
+		br.Msg = "报告已发布, 不允许编辑"
+		return
+	}
+
+	// 更新编辑状态
+	adminIdName := make(map[int]string)
+	admins, e := system.GetSysAdminList(``, make([]interface{}, 0), []string{}, "")
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取系统用户列表失败, Err: " + e.Error()
+		return
+	}
+	for _, ad := range admins {
+		adminIdName[ad.AdminId] = ad.RealName
+	}
+	editing, e := smartReportService.UpdateSmartReportEditing(req.SmartReportId, 1, sysUser.AdminId, sysUser.RealName, adminIdName)
+	if e != nil {
+		br.Msg = e.Error()
+		return
+	}
+	if editing.Status == 1 {
+		br.Msg = editing.Msg
+		return
+	}
+
+	// 内容有改动
+	if req.NoChange != 1 && req.Content != "" && req.ContentStruct != "" {
+		req.Content = html.EscapeString(req.Content)
+		req.ContentStruct = html.EscapeString(req.ContentStruct)
+		sub, e := services.GetReportContentSub(req.Content)
+		if e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = "读取报告前两个章节内容失败, Err: " + e.Error()
+			return
+		}
+		subContent := html.EscapeString(sub)
+
+		item.Content = req.Content
+		item.ContentSub = subContent
+		item.ContentStruct = req.ContentStruct
+		item.ContentModifyTime = time.Now().Local()
+		item.LastModifyAdminId = sysUser.AdminId
+		item.LastModifyAdminName = sysUser.RealName
+		item.ModifyTime = time.Now().Local()
+		cols := []string{"Content", "ContentSub", "ContentStruct", "ContentModifyTime", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime"}
+		if e = item.Update(cols); e != nil {
+			br.Msg = "操作失败"
+			br.ErrMsg = "更新报告内容失败"
+			return
+		}
+
+		go func() {
+			saveLog := new(smart_report.SmartReportSaveLog)
+			saveLog.SmartReportId = item.SmartReportId
+			saveLog.Content = item.Content
+			saveLog.ContentSub = item.ContentSub
+			saveLog.ContentStruct = item.ContentStruct
+			saveLog.AdminId = sysUser.AdminId
+			saveLog.AdminName = sysUser.RealName
+			saveLog.CreateTime = time.Now().Local()
+			_ = saveLog.Create()
+		}()
+	}
+
+	resp.SmartReportId = item.SmartReportId
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "保存成功"
+	br.Data = resp
+}
+
+// MarkEditStatus
+// @Title 标记报告编辑状态
+// @Description 标记报告编辑状态接口
+// @Param	request	body request.MarkEditEnReport true "type json string"
+// @Success 200 标记成功 ;202 标记成功
+// @router /mark_edit [post]
+func (this *SmartReportController) MarkEditStatus() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	var req smart_report.SmartReportMarkEditReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.SmartReportId <= 0 {
+		br.Msg = "缺少报告Id"
+		return
+	}
+	if req.Status <= 0 {
+		br.Msg = "标记状态异常"
+		return
+	}
+
+	// 获取系统用户列表-用于匹配编辑中的用户
+	adminIdName := make(map[int]string)
+	admins, e := system.GetSysAdminList(``, make([]interface{}, 0), []string{}, "")
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取系统用户列表失败, Err: " + e.Error()
+		return
+	}
+	for _, ad := range admins {
+		adminIdName[ad.AdminId] = ad.RealName
+	}
+
+	data, e := smartReportService.UpdateSmartReportEditing(req.SmartReportId, req.Status, sysUser.AdminId, sysUser.RealName, adminIdName)
+	if e != nil {
+		br.Msg = e.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "标记成功"
+	br.Data = data
+}
+
+// List
+// @Title 报告列表
+// @Description 报告列表
+// @Param   PageSize			query	int		true	"每页数据条数"
+// @Param   CurrentIndex		query	int		true	"当前页页码"
+// @Param   TimeType			query	string	false	"筛选的时间类别: publish_time-发布时间, modify_time-更新时间"
+// @Param   StartDate			query   string  false	"开始时间"
+// @Param   EndDate				query   string  false	"结束时间"
+// @Param   Frequency			query   string  false	"频度"
+// @Param   ClassifyIdFirst		query	int		false	"一级分类ID"
+// @Param   ClassifyIdSecond	query	int		false	"二级分类ID"
+// @Param   State				query	int		false	"发布状态: 1-待发布; 2-已发布"
+// @Param   Keyword				query	string	false	"搜索关键词"
+// @Success 200 {object} smart_report.SmartReportListResp
+// @router /list [get]
+func (this *SmartReportController) List() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	type SmartReportListReq struct {
+		PageSize         int    `form:"PageSize"`
+		CurrentIndex     int    `form:"CurrentIndex"`
+		TimeType         string `form:"TimeType"`
+		StartDate        string `form:"StartDate"`
+		EndDate          string `form:"EndDate"`
+		Frequency        string `form:"Frequency"`
+		ClassifyIdFirst  int    `form:"ClassifyIdFirst"`
+		ClassifyIdSecond int    `form:"ClassifyIdSecond"`
+		State            int    `form:"State"`
+		Keyword          string `form:"Keyword"`
+	}
+	params := new(SmartReportListReq)
+	if e := this.ParseForm(params); e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "入参解析失败, Err: " + e.Error()
+		return
+	}
+	if params.TimeType == "" {
+		params.TimeType = "publish_time"
+	}
+	if params.TimeType != "publish_time" && params.TimeType != "modify_time" {
+		br.Msg = "请选择正确的时间类型"
+		return
+	}
+	// 更新时间指的是内容更新时间
+	if params.TimeType == "modify_time" {
+		params.TimeType = "content_modify_time"
+	}
+
+	var condition string
+	var pars []interface{}
+	// 筛选项
+	{
+		keyword := strings.TrimSpace(params.Keyword)
+		if keyword != "" {
+			kw := fmt.Sprint("%", keyword, "%")
+			condition += fmt.Sprintf(` AND (title LIKE ? OR admin_real_name LIKE ? OR last_modify_admin_name LIKE ?)`)
+			pars = append(pars, kw, kw, kw)
+		}
+		if params.StartDate != "" && params.EndDate != "" {
+			st := fmt.Sprintf("%s 00:00:00", params.StartDate)
+			ed := fmt.Sprintf("%s 23:59:59", params.EndDate)
+			condition += fmt.Sprintf(` AND %s >= ? AND %s <= ?`, params.TimeType, params.TimeType)
+			pars = append(pars, st, ed)
+		}
+		if params.Frequency != "" {
+			condition += ` AND frequency = ?`
+			pars = append(pars, params.Frequency)
+		}
+		if params.ClassifyIdFirst > 0 {
+			condition += ` AND classify_id_first = ?`
+			pars = append(pars, params.ClassifyIdFirst)
+		}
+		if params.ClassifyIdSecond > 0 {
+			condition += ` AND classify_id_second = ?`
+			pars = append(pars, params.ClassifyIdSecond)
+		}
+		if params.State > 0 {
+			condition += ` AND state = ?`
+			pars = append(pars, params.State)
+		}
+	}
+
+	resp := new(smart_report.SmartReportListResp)
+	reportOB := new(smart_report.SmartReport)
+	total, e := reportOB.GetCountByCondition(condition, pars)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取报告总数失败, Err:" + e.Error()
+		return
+	}
+	if total <= 0 {
+		page := paging.GetPaging(params.CurrentIndex, params.PageSize, total)
+		resp.Paging = page
+		br.Ret = 200
+		br.Success = true
+		br.Msg = "获取成功"
+		br.Data = resp
+		return
+	}
+
+	// 分页列表
+	var startSize int
+	if params.PageSize <= 0 {
+		params.PageSize = utils.PageSize20
+	}
+	if params.CurrentIndex <= 0 {
+		params.CurrentIndex = 1
+	}
+	startSize = utils.StartIndex(params.CurrentIndex, params.PageSize)
+
+	// 列表查询过滤掉富文本内容
+	fields := []string{
+		"smart_report_id", "report_code", "classify_id_first", "classify_name_first", "classify_id_second", "classify_name_second", "add_type",
+		"title", "abstract", "author", "frequency", "stage", "video_url", "video_name", "video_play_seconds", "video_size", "detail_img_url", "detail_pdf_url",
+		"admin_id", "admin_real_name", "state", "publish_time", "pre_publish_time", "pre_msg_send", "msg_is_send", "msg_send_time", "create_time", "modify_time",
+		"last_modify_admin_id", "last_modify_admin_name", "content_modify_time", "pv", "uv",
+	}
+	list, e := reportOB.GetPageItemsByCondition(condition, pars, fields, "", startSize, params.PageSize)
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取报告分页列表失败, Err:" + e.Error()
+		return
+	}
+
+	// 获取系统用户列表-用于匹配编辑中的用户
+	adminIdName := make(map[int]string)
+	admins, e := system.GetSysAdminList(``, make([]interface{}, 0), []string{}, "")
+	if e != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取系统用户列表失败, Err: " + e.Error()
+		return
+	}
+	for _, ad := range admins {
+		adminIdName[ad.AdminId] = ad.RealName
+	}
+
+	for _, v := range list {
+		item := smart_report.FormatSmartReport2Item(v)
+		mark, e := smartReportService.UpdateSmartReportEditing(v.SmartReportId, 2, sysUser.AdminId, sysUser.RealName, adminIdName)
+		if e != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "查询编辑中标记失败, Err:" + e.Error()
+			return
+		}
+		if mark.Status == 0 {
+			item.CanEdit = true
+		} else {
+			item.Editor = mark.Editor
+		}
+		resp.List = append(resp.List, item)
+	}
+
+	page := paging.GetPaging(params.CurrentIndex, params.PageSize, total)
+	resp.Paging = page
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// DetailImg
+// @Title 生成长图
+// @Description 生成长图
+// @Param   SmartReportId	query	int	true	"智能研报ID"
+// @Success 200 {object} smart_report.SmartReportSaveContentResp
+// @router /detail_img [get]
+func (this *SmartReportController) DetailImg() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	reportId, _ := this.GetInt("SmartReportId", 0)
+	if reportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = fmt.Sprintf("参数有误, SmartReportId: %d", reportId)
+		return
+	}
+
+	reportOB := new(smart_report.SmartReport)
+	item, e := reportOB.GetItemById(reportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取报告失败, Err: " + e.Error()
+		return
+	}
+	if item.DetailImgUrl != "" {
+		br.Data = item.DetailImgUrl
+		br.Ret = 200
+		br.Success = true
+		br.Msg = "获取成功"
+		return
+	}
+
+	// 写入队列
+	var queue smart_report.Report2ImgQueueReq
+	queue.ReportType = 2
+	queue.ReportCode = item.ReportCode
+	_ = utils.Rc.LPush(utils.CACHE_CREATE_REPORT_IMGPDF_QUEUE, queue)
+
+	br.Msg = "图片正在生成中, 请稍后下载"
+	return
+}
+
+// LastPublishedReport
+// @Title 上期已发布的报告
+// @Description 上期已发布的报告
+// @Param   ClassifyIdFirst		query	int	false	"一级分类ID"
+// @Param   ClassifyIdSecond	query	int	false	"二级分类ID"
+// @Success 200 {object} smart_report.SmartReportItem
+// @router /last_published_report [get]
+func (this *SmartReportController) LastPublishedReport() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	firstId, _ := this.GetInt("ClassifyIdFirst")
+	secondId, _ := this.GetInt("ClassifyIdSecond")
+
+	ob := new(smart_report.SmartReport)
+	cond := ` AND classify_id_first = ? AND classify_id_second = ?`
+	pars := make([]interface{}, 0)
+	pars = append(pars, firstId, secondId)
+	item, e := ob.GetItemByCondition(cond, pars, "stage DESC")
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取研报失败, Err: " + e.Error()
+		return
+	}
+	resp := smart_report.FormatSmartReport2Item(item)
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// VoiceUpload
+// @Title 音频上传
+// @Description 音频上传接口
+// @Param   file   query   file  true       "文件"
+// @Param   SmartReportId	query   int  true       "报告ID"
+// @Success Ret=200 上传成功
+// @router /voice_upload [post]
+func (this *SmartReportController) VoiceUpload() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		if br.ErrMsg == "" {
+			br.IsSendEmail = false
+		}
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	reportId, _ := this.GetInt("SmartReportId")
+	if reportId <= 0 {
+		br.Msg = "参数有误"
+		br.ErrMsg = fmt.Sprintf("参数有误, SmartReportId: %d", reportId)
+		return
+	}
+	f, h, err := this.GetFile("file")
+	if err != nil {
+		br.Msg = "获取资源信息失败"
+		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
+		return
+	}
+	defer func() {
+		_ = f.Close()
+	}()
+
+	reportOb := new(smart_report.SmartReport)
+	item, e := reportOb.GetItemById(reportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			br.Msg = "报告不存在, 请刷新页面"
+			return
+		}
+		br.Msg = "操作失败"
+		br.ErrMsg = "获取报告信息失败, Err:" + err.Error()
+		return
+	}
+
+	ext := path.Ext(h.Filename)
+	uploadDir := utils.STATIC_DIR + "hongze/" + time.Now().Format("20060102")
+	if e = os.MkdirAll(uploadDir, 0766); e != nil {
+		br.Msg = "存储目录创建失败"
+		br.ErrMsg = "存储目录创建失败, Err:" + e.Error()
+		return
+	}
+	ossFileName := utils.GetRandStringNoSpecialChar(28) + ext
+	filePath := uploadDir + "/" + ossFileName
+	if e = this.SaveToFile("file", filePath); e != nil {
+		br.Msg = "文件保存失败"
+		br.ErrMsg = "文件保存失败, Err:" + e.Error()
+		return
+	}
+	defer func() {
+		_ = os.Remove(filePath)
+	}()
+	ossDir := "static/audio/"
+
+	resourceUrl := ``
+	//上传到阿里云 和 minio
+	if utils.ObjectStorageClient == "minio" {
+		resourceUrl, e = services.UploadMinIoToDir(ossFileName, filePath, ossDir, "")
+		if e != nil {
+			br.Msg = "文件上传失败"
+			br.ErrMsg = "文件上传失败, Err:" + e.Error()
+			return
+		}
+	} else {
+		resourceUrl, e = services.UploadAliyunToDir(ossFileName, filePath, ossDir, "")
+		if e != nil {
+			br.Msg = "文件上传失败"
+			br.ErrMsg = "文件上传失败, Err:" + e.Error()
+			return
+		}
+	}
+
+	resource := new(models.Resource)
+	resource.ResourceUrl = resourceUrl
+	resource.ResourceType = 2
+	resource.CreateTime = time.Now()
+	newId, err := models.AddResource(resource)
+	if err != nil {
+		br.Msg = "资源上传失败"
+		br.ErrMsg = "资源上传失败,Err:" + err.Error()
+		return
+	}
+	//fmt.Println(filePath)
+	playSeconds, err := mp3duration.Calculate(filePath)
+	if playSeconds <= 0 {
+		playSeconds, err = utils.GetVideoPlaySeconds(filePath)
+		if err != nil {
+			br.Msg = "获取音频时间失败"
+			br.ErrMsg = "获取音频时间失败,Err:" + err.Error()
+			return
+		}
+	}
+	createTime := item.CreateTime.Format("0102")
+	videoName := item.Title + "(" + createTime + ")"
+	fileBody, err := ioutil.ReadFile(filePath)
+	videoSize := len(fileBody)
+	sizeFloat := (float64(videoSize) / float64(1024)) / float64(1024)
+	sizeStr := utils.SubFloatToFloatStr(sizeFloat, 2)
+
+	item.VideoUrl = resourceUrl
+	item.VideoName = videoName
+	item.VideoPlaySeconds = playSeconds
+	item.VideoSize = sizeStr
+	item.ModifyTime = time.Now().Local()
+	updateCols := []string{"VideoUrl", "VideoName", "VideoPlaySeconds", "VideoSize", "ModifyTime"}
+	if e = item.Update(updateCols); e != nil {
+		br.Msg = "上传失败"
+		br.ErrMsg = "上传失败,Err:" + e.Error()
+		return
+	}
+
+	resp := new(models.ResourceResp)
+	resp.Id = newId
+	resp.ResourceUrl = resourceUrl
+	br.Msg = "上传成功"
+	br.Ret = 200
+	br.Success = true
+	br.Data = resp
+	return
+}

+ 13 - 0
models/db.go

@@ -10,6 +10,7 @@ import (
 	"eta/eta_api/models/ppt_english"
 	"eta/eta_api/models/sandbox"
 	"eta/eta_api/models/semantic_analysis"
+	"eta/eta_api/models/smart_report"
 	"eta/eta_api/models/system"
 	"eta/eta_api/models/yb"
 	"eta/eta_api/utils"
@@ -140,6 +141,10 @@ func init() {
 
 	// 外部链接
 	initOutLink()
+
+	// 智能研报
+	initSmartReport()
+
 	// ETA试用相关表
 	if utils.BusinessCode == utils.BusinessCodeSandbox {
 		initEtaTrial()
@@ -438,3 +443,11 @@ func initExcel() {
 		new(excel.ExcelEdbMapping), //ETA excel 与 指标 的关系表
 	)
 }
+
+// initSmartReport 智能研报相关表
+func initSmartReport() {
+	orm.RegisterModel(
+		new(smart_report.SmartReport),        // 智能研报主表
+		new(smart_report.SmartReportSaveLog), // 智能研报-保存记录表
+	)
+}

+ 345 - 0
models/smart_report/smart_report.go

@@ -0,0 +1,345 @@
+package smart_report
+
+import (
+	"eta/eta_api/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/rdlucklib/rdluck_tools/paging"
+	"html"
+	"strings"
+	"time"
+)
+
+const (
+	SmartReportStateWaitPublish = 1
+	SmartReportStatePublished   = 2
+)
+
+// SmartReport 智能研报
+type SmartReport struct {
+	SmartReportId       int       `orm:"column(smart_report_id);pk" description:"智能研报ID"`
+	ReportCode          string    `description:"报告唯一编码"`
+	ClassifyIdFirst     int       `description:"一级分类ID"`
+	ClassifyNameFirst   string    `description:"一级分类名称"`
+	ClassifyIdSecond    int       `description:"二级分类ID"`
+	ClassifyNameSecond  string    `description:"二级分类名称"`
+	AddType             int       `description:"新增方式:1-新增报告;2-继承报告"`
+	Title               string    `description:"标题"`
+	Abstract            string    `description:"摘要"`
+	Author              string    `description:"作者"`
+	Frequency           string    `description:"频度"`
+	Stage               int       `description:"期数"`
+	Content             string    `description:"内容"`
+	ContentSub          string    `description:"内容前两个章节"`
+	ContentStruct       string    `description:"内容组件"`
+	VideoUrl            string    `description:"音频文件URL"`
+	VideoName           string    `description:"音频文件名称"`
+	VideoPlaySeconds    float64   `description:"音频播放时长"`
+	VideoSize           string    `description:"音频文件大小,单位M"`
+	AdminId             int       `description:"创建者ID"`
+	AdminRealName       string    `description:"创建者姓名"`
+	State               int       `description:"发布状态:1-待发布;2-已发布"`
+	LastModifyAdminId   int       `description:"最后更新人ID"`
+	LastModifyAdminName string    `description:"最后更新人姓名"`
+	ContentModifyTime   time.Time `description:"内容更新时间"`
+	Pv                  int       `description:"pv"`
+	Uv                  int       `description:"uv"`
+	PublishTime         time.Time `description:"发布时间"`
+	PrePublishTime      time.Time `description:"预发布时间"`
+	PreMsgSend          int       `description:"定时发布后是否推送模版消息:0-否;1-是"`
+	MsgIsSend           int       `description:"消息是否已发送:0-否;1-是"`
+	MsgSendTime         time.Time `description:"模版消息发送时间"`
+	DetailImgUrl        string    `description:"报告详情长图地址"`
+	DetailPdfUrl        string    `description:"报告详情PDF地址"`
+	CreateTime          time.Time `description:"创建时间"`
+	ModifyTime          time.Time `description:"修改时间"`
+}
+
+func (m *SmartReport) TableName() string {
+	return "smart_report"
+}
+
+func (m *SmartReport) PrimaryId() string {
+	return "smart_report_id"
+}
+
+func (m *SmartReport) Create() (err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	id, err := o.Insert(m)
+	if err != nil {
+		return
+	}
+	m.SmartReportId = int(id)
+	return
+}
+
+func (m *SmartReport) CreateMulti(items []*SmartReport) (err error) {
+	if len(items) == 0 {
+		return
+	}
+	o := orm.NewOrmUsingDB("rddp")
+	_, err = o.InsertMulti(len(items), items)
+	return
+}
+
+func (m *SmartReport) Update(cols []string) (err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	_, err = o.Update(m, cols...)
+	return
+}
+
+func (m *SmartReport) Del() (err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
+	_, err = o.Raw(sql, m.SmartReportId).Exec()
+	return
+}
+
+func (m *SmartReport) MultiDel(menuIds []int) (err error) {
+	if len(menuIds) == 0 {
+		return
+	}
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
+	_, err = o.Raw(sql, menuIds).Exec()
+	return
+}
+
+func (m *SmartReport) GetItemById(id int) (item *SmartReport, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+func (m *SmartReport) GetItemByCondition(condition string, pars []interface{}, orderRule string) (item *SmartReport, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	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 *SmartReport) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	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 *SmartReport) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*SmartReport, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := `ORDER BY create_time DESC`
+	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 *SmartReport) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*SmartReport, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := `ORDER BY create_time DESC`
+	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
+}
+
+func (m *SmartReport) GetMaxStageByClassifyId(classifyId int) (stage int, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`SELECT MAX(stage) AS max_stage FROM %s WHERE classify_id_second = ?`, m.TableName())
+	err = o.Raw(sql, classifyId).QueryRow(&stage)
+	return
+}
+
+// SmartReportItem 智能研报信息
+type SmartReportItem struct {
+	SmartReportId       int     `description:"智能研报ID"`
+	ReportCode          string  `description:"报告唯一编码"`
+	ClassifyIdFirst     int     `description:"一级分类ID"`
+	ClassifyNameFirst   string  `description:"一级分类名称"`
+	ClassifyIdSecond    int     `description:"二级分类ID"`
+	ClassifyNameSecond  string  `description:"二级分类名称"`
+	AddType             int     `description:"新增方式:1-新增报告;2-继承报告"`
+	Title               string  `description:"标题"`
+	Abstract            string  `description:"摘要"`
+	Author              string  `description:"作者"`
+	Frequency           string  `description:"频度"`
+	Stage               int     `description:"期数"`
+	Content             string  `description:"内容"`
+	ContentSub          string  `description:"内容前两个章节"`
+	ContentStruct       string  `description:"内容组件"`
+	VideoUrl            string  `description:"音频文件URL"`
+	VideoName           string  `description:"音频文件名称"`
+	VideoPlaySeconds    float64 `description:"音频播放时长"`
+	VideoSize           string  `description:"音频文件大小,单位M"`
+	AdminId             int     `description:"创建者姓名"`
+	AdminRealName       string  `description:"创建者姓名"`
+	LastModifyAdminId   int     `description:"最后更新人ID"`
+	LastModifyAdminName string  `description:"最后更新人姓名"`
+	ContentModifyTime   string  `description:"内容更新时间"`
+	Pv                  int     `description:"pv"`
+	Uv                  int     `description:"uv"`
+	State               int     `description:"发布状态:1-待发布;2-已发布"`
+	PublishTime         string  `description:"发布时间"`
+	PrePublishTime      string  `description:"预发布时间"`
+	MsgIsSend           int     `description:"消息是否已发送:0-否;1-是"`
+	MsgSendTime         string  `description:"模版消息发送时间"`
+	DetailImgUrl        string  `description:"报告详情长图地址"`
+	DetailPdfUrl        string  `description:"报告详情PDF地址"`
+	CreateTime          string  `description:"创建时间"`
+	ModifyTime          string  `description:"修改时间"`
+	CanEdit             bool    `description:"是否可编辑"`
+	Editor              string  `description:"当前编辑人"`
+}
+
+// FormatSmartReport2Item 格式化智能研报数据格式
+func FormatSmartReport2Item(origin *SmartReport) (item *SmartReportItem) {
+	item = new(SmartReportItem)
+	if origin == nil {
+		return
+	}
+	item.SmartReportId = origin.SmartReportId
+	item.ReportCode = origin.ReportCode
+	item.ClassifyIdFirst = origin.ClassifyIdFirst
+	item.ClassifyNameFirst = origin.ClassifyNameFirst
+	item.ClassifyIdSecond = origin.ClassifyIdSecond
+	item.ClassifyNameSecond = origin.ClassifyNameSecond
+	item.AddType = origin.AddType
+	item.Title = origin.Title
+	item.Abstract = origin.Abstract
+	item.Author = origin.Author
+	item.Frequency = origin.Frequency
+	item.Stage = origin.Stage
+	item.Content = html.UnescapeString(origin.Content)
+	item.ContentSub = html.UnescapeString(origin.ContentSub)
+	item.ContentStruct = html.UnescapeString(origin.ContentStruct)
+	item.VideoUrl = origin.VideoUrl
+	item.VideoName = origin.VideoName
+	item.VideoPlaySeconds = origin.VideoPlaySeconds
+	item.VideoSize = origin.VideoSize
+	item.AdminId = origin.AdminId
+	item.AdminRealName = origin.AdminRealName
+	item.LastModifyAdminId = origin.LastModifyAdminId
+	item.LastModifyAdminName = origin.LastModifyAdminName
+	item.ContentModifyTime = utils.TimeTransferString(utils.FormatDateTime, origin.ContentModifyTime)
+	item.Pv = origin.Pv
+	item.Uv = origin.Uv
+	item.State = origin.State
+	item.PublishTime = utils.TimeTransferString(utils.FormatDateTime, origin.PublishTime)
+	item.PrePublishTime = utils.TimeTransferString(utils.FormatDateTime, origin.PrePublishTime)
+	item.MsgIsSend = origin.MsgIsSend
+	item.MsgSendTime = utils.TimeTransferString(utils.FormatDateTime, origin.MsgSendTime)
+	item.DetailImgUrl = origin.DetailImgUrl
+	item.DetailPdfUrl = origin.DetailPdfUrl
+	item.CreateTime = utils.TimeTransferString(utils.FormatDateTime, origin.CreateTime)
+	item.ModifyTime = utils.TimeTransferString(utils.FormatDateTime, origin.ModifyTime)
+	return
+}
+
+// SmartReportAddReq 新增智能研报请求体
+type SmartReportAddReq struct {
+	AddType            int    `description:"新增方式:1:新增报告,2:继承报告"`
+	ClassifyIdFirst    int    `description:"一级分类ID"`
+	ClassifyNameFirst  string `description:"一级分类名称"`
+	ClassifyIdSecond   int    `description:"二级分类ID"`
+	ClassifyNameSecond string `description:"二级分类名称"`
+	Title              string `description:"标题"`
+	Abstract           string `description:"摘要"`
+	Author             string `description:"作者"`
+	Frequency          string `description:"频度"`
+}
+
+// SmartReportEditReq 编辑智能研报请求体
+type SmartReportEditReq struct {
+	SmartReportAddReq
+	SmartReportId int    `description:"智能研报ID"`
+	Content       string `description:"内容"`
+	ContentStruct string `description:"内容结构"`
+}
+
+// SmartReportRemoveReq 删除智能研报请求体
+type SmartReportRemoveReq struct {
+	SmartReportId int `description:"智能研报ID"`
+}
+
+// SmartReportPublishReq 发布智能研报请求体
+type SmartReportPublishReq struct {
+	SmartReportId int `description:"智能研报ID"`
+	PublishState  int `description:"1-取消发布; 2-发布"`
+}
+
+// SmartReportPrePublishReq 预发布智能研报请求体
+type SmartReportPrePublishReq struct {
+	SmartReportId  int    `description:"智能研报ID"`
+	PrePublishTime string `description:"预发布时间"`
+	PreMsgSend     int    `description:"定时发布成功后是否立即推送模版消息:0否,1是"`
+}
+
+// SmartReportSaveContentReq 保存草稿请求体
+type SmartReportSaveContentReq struct {
+	SmartReportId int    `description:"智能研报ID"`
+	Content       string `description:"内容"`
+	ContentStruct string `description:"内容结构"`
+	NoChange      int    `description:"内容是否未改变:1:内容未改变"`
+}
+
+// SmartReportSaveContentResp 保存草稿响应体
+type SmartReportSaveContentResp struct {
+	SmartReportId int `description:"智能研报ID"`
+}
+
+// SmartReportSendMsgReq 消息推送请求体
+type SmartReportSendMsgReq struct {
+	SmartReportId int `description:"智能研报ID"`
+}
+
+// SmartReportMarkEditReq 标记编辑英文研报的请求数据
+type SmartReportMarkEditReq struct {
+	SmartReportId int `description:"智能研报ID"`
+	Status        int `description:"标记状态: 1-编辑中; 2-编辑完成"`
+}
+
+// SmartReportListResp 智能研报
+type SmartReportListResp struct {
+	List   []*SmartReportItem
+	Paging *paging.PagingItem `description:"分页数据"`
+}
+
+// ElasticSmartReport 智能研报es
+type ElasticSmartReport struct {
+	SmartReportId      int    `description:"智能研报ID"`
+	Title              string `description:"标题"`
+	Abstract           string `description:"摘要"`
+	BodyContent        string `description:"内容"`
+	PublishTime        string `description:"发布时间"`
+	PublishState       int    `description:"发布状态 1-未发布 2-已发布"`
+	Author             string `description:"作者"`
+	ClassifyIdFirst    int    `description:"一级分类ID"`
+	ClassifyNameFirst  string `description:"一级分类名称"`
+	ClassifyIdSecond   int    `description:"二级分类ID"`
+	ClassifyNameSecond string `description:"二级分类名称"`
+	StageStr           string `description:"报告期数"`
+	Frequency          string `description:"频度"`
+}
+
+// Report2ImgQueueReq 报告详情生成长图队列请求体
+type Report2ImgQueueReq struct {
+	ReportType int    `description:"报告类型: 1-研报; 2-智能研报"`
+	ReportCode string `description:"报告唯一编码"`
+}

+ 122 - 0
models/smart_report/smart_report_save_log.go

@@ -0,0 +1,122 @@
+package smart_report
+
+import (
+	"eta/eta_api/utils"
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"strings"
+	"time"
+)
+
+// SmartReportSaveLog 智能研报保存记录
+type SmartReportSaveLog struct {
+	Id            int       `orm:"column(id);pk"`
+	SmartReportId int       `description:"智能研报ID"`
+	Content       string    `description:"内容"`
+	ContentSub    string    `description:"内容前两个章节"`
+	ContentStruct string    `description:"内容组件"`
+	AdminId       int       `description:"操作人ID"`
+	AdminName     string    `description:"操作人姓名"`
+	CreateTime    time.Time `description:"创建时间"`
+}
+
+func (m *SmartReportSaveLog) TableName() string {
+	return "smart_report_save_log"
+}
+
+func (m *SmartReportSaveLog) PrimaryId() string {
+	return "id"
+}
+
+func (m *SmartReportSaveLog) Create() (err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	id, err := o.Insert(m)
+	if err != nil {
+		return
+	}
+	m.Id = int(id)
+	return
+}
+
+func (m *SmartReportSaveLog) CreateMulti(items []*SmartReportSaveLog) (err error) {
+	if len(items) == 0 {
+		return
+	}
+	o := orm.NewOrmUsingDB("rddp")
+	_, err = o.InsertMulti(len(items), items)
+	return
+}
+
+func (m *SmartReportSaveLog) Update(cols []string) (err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	_, err = o.Update(m, cols...)
+	return
+}
+
+func (m *SmartReportSaveLog) Del() (err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
+	_, err = o.Raw(sql, m.Id).Exec()
+	return
+}
+
+func (m *SmartReportSaveLog) MultiDel(menuIds []int) (err error) {
+	if len(menuIds) == 0 {
+		return
+	}
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s IN (%s)`, m.TableName(), m.PrimaryId(), utils.GetOrmInReplace(len(menuIds)))
+	_, err = o.Raw(sql, menuIds).Exec()
+	return
+}
+
+func (m *SmartReportSaveLog) GetItemById(id int) (item *SmartReportSaveLog, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), m.PrimaryId())
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+func (m *SmartReportSaveLog) GetItemByCondition(condition string, pars []interface{}) (item *SmartReportSaveLog, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 %s LIMIT 1`, m.TableName(), condition)
+	err = o.Raw(sql, pars).QueryRow(&item)
+	return
+}
+
+func (m *SmartReportSaveLog) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	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 *SmartReportSaveLog) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*SmartReportSaveLog, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := `ORDER BY create_time DESC`
+	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 *SmartReportSaveLog) GetPageItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string, startSize, pageSize int) (items []*SmartReportSaveLog, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	fields := strings.Join(fieldArr, ",")
+	if len(fieldArr) == 0 {
+		fields = `*`
+	}
+	order := `ORDER BY create_time DESC`
+	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
+}

+ 117 - 0
routers/commentsRouter.go

@@ -4651,6 +4651,123 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "Add",
+            Router: `/add`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "Detail",
+            Router: `/detail`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "DetailImg",
+            Router: `/detail_img`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "Edit",
+            Router: `/edit`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "LastPublishedReport",
+            Router: `/last_published_report`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "List",
+            Router: `/list`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "MarkEditStatus",
+            Router: `/mark_edit`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "PrePublish",
+            Router: `/pre_publish`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "Publish",
+            Router: `/publish`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "Remove",
+            Router: `/remove`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "SaveContent",
+            Router: `/save_content`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "SendMsg",
+            Router: `/send_msg`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/smart_report:SmartReportController"],
+        beego.ControllerComments{
+            Method: "VoiceUpload",
+            Router: `/voice_upload`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_api/controllers/trade_analysis:TradeAnalysisController"] = append(beego.GlobalControllerRouter["eta/eta_api/controllers/trade_analysis:TradeAnalysisController"],
         beego.ControllerComments{
             Method: "GetClassifyName",

+ 6 - 0
routers/router.go

@@ -21,6 +21,7 @@ import (
 	"eta/eta_api/controllers/roadshow"
 	"eta/eta_api/controllers/sandbox"
 	"eta/eta_api/controllers/semantic_analysis"
+	"eta/eta_api/controllers/smart_report"
 	"eta/eta_api/controllers/trade_analysis"
 	"github.com/beego/beego/v2/server/web"
 	"github.com/beego/beego/v2/server/web/filter/cors"
@@ -298,6 +299,11 @@ func init() {
 				&data_manage.ChartFrameworkController{},
 			),
 		),
+		web.NSNamespace("/smart_report",
+			web.NSInclude(
+				&smart_report.SmartReportController{},
+			),
+		),
 	)
 	web.AddNamespace(ns)
 }

+ 62 - 2
services/elastic.go

@@ -2,12 +2,13 @@ package services
 
 import (
 	"context"
-	"fmt"
-	"github.com/olivere/elastic/v7"
 	"eta/eta_api/models"
 	saModel "eta/eta_api/models/semantic_analysis"
+	"eta/eta_api/models/smart_report"
 	"eta/eta_api/services/alarm_msg"
 	"eta/eta_api/utils"
+	"fmt"
+	"github.com/olivere/elastic/v7"
 	"strings"
 )
 
@@ -267,3 +268,62 @@ func EsAddOrEditSaDoc(indexName, docId string, item *saModel.ElasticSaDoc) (err
 	fmt.Println("AddData", resp.Status, resp.Result)
 	return
 }
+
+// EsAddOrEditSmartReport 新增编辑es智能研报
+func EsAddOrEditSmartReport(indexName, docId string, item *smart_report.ElasticSmartReport) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println("EsAddOrEditSmartReport Err:", err.Error())
+		}
+	}()
+	client, err := NewClient()
+	if err != nil {
+		return
+	}
+	// docId为报告ID
+	searchById, err := client.Get().Index(indexName).Id(docId).Do(context.Background())
+	if err != nil && !strings.Contains(err.Error(), "404") {
+		fmt.Println("Get Err" + err.Error())
+		return
+	}
+	if searchById != nil && searchById.Found {
+		resp, err := client.Update().Index(indexName).Id(docId).Doc(map[string]interface{}{
+			"SmartReportId":      item.SmartReportId,
+			"Title":              item.Title,
+			"Abstract":           item.Abstract,
+			"BodyContent":        item.BodyContent,
+			"PublishTime":        item.PublishTime,
+			"PublishState":       item.PublishState,
+			"Author":             item.Author,
+			"ClassifyIdFirst":    item.ClassifyIdFirst,
+			"ClassifyNameFirst":  item.ClassifyNameFirst,
+			"ClassifyIdSecond":   item.ClassifyIdSecond,
+			"ClassifyNameSecond": item.ClassifyNameSecond,
+			"StageStr":           item.StageStr,
+			"Frequency":          item.Frequency,
+		}).Do(context.Background())
+		if err != nil {
+			return err
+		}
+		//fmt.Println(resp.Status, resp.Result)
+		if resp.Status == 0 {
+			fmt.Println("修改成功" + docId)
+			err = nil
+		} else {
+			fmt.Println("EditData", resp.Status, resp.Result)
+		}
+	} else {
+		resp, err := client.Index().Index(indexName).Id(docId).BodyJson(item).Do(context.Background())
+		if err != nil {
+			fmt.Println("新增失败:", err.Error())
+			return err
+		}
+		if resp.Status == 0 && resp.Result == "created" {
+			fmt.Println("新增成功" + docId)
+			return nil
+		} else {
+			fmt.Println("AddData", resp.Status, resp.Result)
+		}
+	}
+	return
+}

+ 131 - 0
services/smart_report/smart_report.go

@@ -0,0 +1,131 @@
+package smart_report
+
+import (
+	"encoding/json"
+	"eta/eta_api/models"
+	"eta/eta_api/models/smart_report"
+	"eta/eta_api/services"
+	"eta/eta_api/services/alarm_msg"
+	"eta/eta_api/utils"
+	"fmt"
+	"html"
+	"strconv"
+	"time"
+)
+
+// SmartReportBuildVideoAndUpdate 生成音频
+func SmartReportBuildVideoAndUpdate(item *smart_report.SmartReport) {
+	if item == nil {
+		return
+	}
+	var err error
+	defer func() {
+		if err != nil {
+			tips := fmt.Sprintf("智能研报-音频生成, errMsg: %s", err.Error())
+			go alarm_msg.SendAlarmMsg(tips, 2)
+		}
+	}()
+
+	videoUrl, videoName, videoSize, videoPlaySeconds, e := services.CreateReportVideo(item.Title, item.Content, time.Now().Local().Format(utils.FormatDateTime))
+	if e != nil {
+		err = fmt.Errorf("create audio err: %s", e.Error())
+		return
+	}
+	item.VideoUrl = videoUrl
+	item.VideoName = videoName
+	item.VideoSize = videoSize
+	item.VideoPlaySeconds = videoPlaySeconds
+	item.ModifyTime = time.Now().Local()
+	cols := []string{"VideoUrl", "VideoName", "VideoSize", "VideoPlaySeconds", "ModifyTime"}
+	if e = item.Update(cols); e != nil {
+		err = fmt.Errorf("smart report update err: %s", e.Error())
+		return
+	}
+}
+
+// UpdateSmartReportEditing 更新研报当前更新状态
+// status 枚举值 1:编辑中,0:完成编辑, 2:只做查询
+func UpdateSmartReportEditing(reportId, status, thisUserId int, thisUserName string, adminIdName map[int]string) (ret models.MarkReportResp, err error) {
+	key := fmt.Sprint(utils.CACHE_SMART_REPORT_EDITING, reportId)
+	ret.Status = 0
+	ret.Msg = "无人编辑"
+
+	opUserId, e := utils.Rc.RedisInt(key)
+	var opUser models.MarkReportItem
+	var classifyNameFirst string
+	if e != nil {
+		opUserInfoStr, tErr := utils.Rc.RedisString(key)
+		if tErr == nil {
+			tErr = json.Unmarshal([]byte(opUserInfoStr), &opUser)
+			if tErr == nil {
+				opUserId = opUser.AdminId
+			}
+		}
+	}
+
+	if opUserId > 0 && opUserId != thisUserId {
+		editor := opUser.Editor
+		if editor == "" {
+			editor = adminIdName[opUserId]
+		}
+		ret.Status = 1
+		ret.Msg = fmt.Sprintf("当前%s正在编辑报告", editor)
+		ret.Editor = editor
+		return
+	}
+
+	if status == 1 {
+		nowUser := &models.MarkReportItem{AdminId: thisUserId, Editor: thisUserName, ReportClassifyNameFirst: classifyNameFirst}
+		bt, e := json.Marshal(nowUser)
+		if e != nil {
+			err = fmt.Errorf("格式化编辑者信息失败")
+			return
+		}
+		if opUserId > 0 {
+			utils.Rc.Do("SETEX", key, int64(180), string(bt)) //3分钟缓存
+		} else {
+			utils.Rc.SetNX(key, string(bt), time.Second*60*3) //3分钟缓存
+		}
+	} else if status == 0 {
+		//清除编辑缓存
+		_ = utils.Rc.Delete(key)
+	}
+	return
+}
+
+// SmartReportElasticUpsert 新增/编辑报告es
+func SmartReportElasticUpsert(smartReportId int, state int) (err error) {
+	if smartReportId <= 0 {
+		return
+	}
+
+	reportOB := new(smart_report.SmartReport)
+	item, e := reportOB.GetItemById(smartReportId)
+	if e != nil {
+		if e.Error() == utils.ErrNoRow() {
+			// 可能被删了就直接忽略掉
+			return
+		}
+		err = fmt.Errorf("获取报告失败, Err: %s", e.Error())
+		return
+	}
+
+	esReport := new(smart_report.ElasticSmartReport)
+	esReport.SmartReportId = item.SmartReportId
+	esReport.Title = item.Title
+	esReport.Abstract = item.Abstract
+	esReport.BodyContent = utils.TrimHtml(html.UnescapeString(item.Content))
+	esReport.PublishTime = item.PublishTime.Format(utils.FormatDateTime)
+	esReport.PublishState = state
+	esReport.Author = item.Author
+	esReport.ClassifyIdFirst = item.ClassifyIdFirst
+	esReport.ClassifyNameFirst = item.ClassifyNameFirst
+	esReport.ClassifyIdSecond = item.ClassifyIdSecond
+	esReport.ClassifyNameSecond = item.ClassifyNameSecond
+	esReport.StageStr = strconv.Itoa(item.Stage)
+	esReport.Frequency = item.Frequency
+	if err = services.EsAddOrEditSmartReport(utils.SmartReportIndexName, strconv.Itoa(item.SmartReportId), esReport); err != nil {
+		return
+	}
+	return
+}

+ 10 - 1
utils/config.go

@@ -105,6 +105,7 @@ var (
 	EsEnglishReportIndexName       string //英文研报ES索引
 	MY_CHART_INDEX_NAME            string //研究图库(MY ETA)索引
 	EsSemanticAnalysisDocIndexName string //ES语义分析文档索引名
+	SmartReportIndexName           string //智能研报ES索引
 )
 
 // 科大讯飞--语音合成
@@ -124,8 +125,9 @@ var (
 
 // 对象存储客户端
 var (
-	ObjectStorageClient string       // 目前有oss minio,默认oss
+	ObjectStorageClient string // 目前有oss minio,默认oss
 )
+
 // 阿里云配置
 var (
 	Bucketname       string
@@ -205,6 +207,9 @@ var (
 	MinIoRegion           string
 )
 
+// PythonUrlReport2Img 生成长图服务地址
+var PythonUrlReport2Img string
+
 func init() {
 	tmpRunMode, err := web.AppConfig.String("run_mode")
 	if err != nil {
@@ -429,6 +434,7 @@ func init() {
 		EsReportIndexName = config["es_report_index_name"]
 		EsEnglishReportIndexName = config["es_english_report_index_name"]
 		EsSemanticAnalysisDocIndexName = config["es_semantic_analysis_doc_index_name"]
+		SmartReportIndexName = config["es_smart_report_index_name"]
 	}
 
 	CrmEtaServerUrl = config["crm_eta_server_url"]
@@ -452,6 +458,9 @@ func init() {
 		MinIoRegion = config["minio_region"]
 	}
 
+	// 生成长图服务地址
+	PythonUrlReport2Img = config["python_url_report2img"]
+
 	// 初始化ES
 	initEs()
 }

+ 5 - 0
utils/constants.go

@@ -219,6 +219,11 @@ const (
 	CACHE_SYNC_DEPARTMENT   = "hz_crm_eta:sync_department"   // 同步部门的缓存队列key
 	CACHE_SYNC_GROUP        = "hz_crm_eta:sync_group"        // 同步分组的缓存队列key
 	CACHE_SYNC_USER_EN_ROLE = "hz_crm_eta:sync_user_en_role" // 同步用户英文权限角色缓存队列key
+
+	CACHE_SMART_REPORT_EDITING  = "eta:smart_report:editing:" // 智能研报用户编辑中
+	CACHE_SMART_REPORT_SEND_MSG = "eta:smart_report:sending:" // 智能研报用户报告推送
+
+	CACHE_CREATE_REPORT_IMGPDF_QUEUE = "eta_report:report_img_pdf_queue" // 生成报告长图PDF队列
 )
 
 // 模板消息推送类型