Bladeren bron

fix:切库

Roc 1 jaar geleden
bovenliggende
commit
fd34614e0e

+ 1 - 1
.gitignore

@@ -15,4 +15,4 @@
 *DS_Store
 /static/images/*.svg
 hz_crm_api.exe
-hz_crm_api.exe~
+hz_crm_api.exe~

+ 186 - 9
controllers/company_user.go

@@ -12,6 +12,7 @@ import (
 	"hongze/hz_crm_api/models/company_user"
 	"hongze/hz_crm_api/models/company_user/request"
 	"hongze/hz_crm_api/models/company_user/response"
+	"hongze/hz_crm_api/models/cygx"
 	"hongze/hz_crm_api/models/system"
 	"hongze/hz_crm_api/models/yb"
 	"hongze/hz_crm_api/services"
@@ -2910,10 +2911,14 @@ Loop:
 	br.Data = resp
 }
 
+// ViewReportList
 // @Title 联系人阅读报告记录
 // @Description 联系人阅读报告记录
 // @Param   UserId   query   int  true       "用户id"
 // @Param   TxtType   query   int  true       "类型0全部,1权益,2ficc"
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   LastViewTime   query   string  true       "最近一次的阅读时间,没有的话,那就是获取最新数据"
 // @Success 200 {object} company.ViewReportListResp
 // @router /view/report/list [get]
 func (this *CompanyUserController) ViewReportList() {
@@ -2931,11 +2936,23 @@ func (this *CompanyUserController) ViewReportList() {
 	}
 	userId, _ := this.GetInt("UserId")
 	txtType, _ := this.GetInt("TxtType")
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+	lastViewTime := this.GetString("LastViewTime")
 	if userId <= 0 {
 		br.Msg = "参数错误"
 		return
 	}
 
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = paging.StartIndex(currentIndex, pageSize)
+
 	item, err := models.GetWxUserByUserId(userId)
 	if err != nil {
 		br.Msg = "获取失败"
@@ -2943,28 +2960,188 @@ func (this *CompanyUserController) ViewReportList() {
 		return
 	}
 
-	list := make([]*company.ViewReportList, 0)
-
-	if item.Mobile != "" {
-		items, err := company.GetViewReportListByMobile(item.Mobile, txtType)
+	var lastViewTimeT time.Time
+	if lastViewTime == `` {
+		lastViewTimeT = time.Now()
+		lastViewTime = lastViewTimeT.Format(utils.FormatDateTime)
+	} else {
+		lastViewTimeT, err = time.ParseInLocation(utils.FormatDateTime, lastViewTime, time.Local)
 		if err != nil {
 			br.Msg = "获取失败"
-			br.Msg = "获取失败,Err:" + err.Error()
+			br.Msg = "最近一次阅读时间转换异常,Err:" + err.Error()
 			return
 		}
-		list = append(list, items...)
 	}
 
-	if item.Email != "" && item.Mobile == "" {
-		items, err := company.GetViewReportListByEmail2(item.Email, txtType)
+	list := make([]*company.ViewReportList, 0)
+	recordList := make([]*models.UserReportViewRecord, 0)
+
+	obj := models.UserReportViewRecord{}
+
+	var baseCondition string // 基础条件
+	var basePars []interface{}
+	if item.Mobile != "" {
+		baseCondition = ` AND mobile = ? `
+		basePars = append(basePars, item.Mobile)
+	} else if item.Email == "" {
+		baseCondition = ` AND email = ? `
+		basePars = append(basePars, item.Email)
+	}
+
+	switch txtType {
+	case 1:
+		baseCondition = ` AND source = ? `
+		basePars = append(basePars, 4)
+	// 权益
+	case 2: // ficc
+		baseCondition = ` AND source in (?,?,?) `
+		basePars = append(basePars, 1, 2, 3)
+	}
+
+	// 开始实际的查询
+	{
+		condition := baseCondition
+		pars := basePars
+
+		condition += `AND create_time <  ?`
+		pars = append(pars, lastViewTime)
+
+		total, items, err := obj.GetViewReportList(lastViewTimeT.Year(), condition, pars, startSize, pageSize)
 		if err != nil {
 			br.Msg = "获取失败"
 			br.Msg = "获取失败,Err:" + err.Error()
 			return
 		}
-		list = append(list, items...)
+
+		recordList = append(recordList, items...)
+
+		// 查询去年的表
+		if total < int64(pageSize) {
+			secondCondition := baseCondition
+			secondPars := basePars
+
+			secondCondition += `AND create_time <  ?`
+			secondPars = append(secondPars, lastViewTime)
+
+			_, items, err := obj.GetViewReportList(lastViewTimeT.Year(), secondCondition, secondPars, 0, int(total)-pageSize)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.Msg = "获取失败,Err:" + err.Error()
+				return
+			}
+
+			recordList = append(recordList, items...)
+		}
+	}
+
+	viewReportMap := make(map[string]company.ViewReportList) // 阅读记录map
+	sourceReportIdListMap := make(map[int8][]int)
+
+	for _, v := range recordList {
+		tmpList, ok := sourceReportIdListMap[v.Source]
+		if !ok {
+			tmpList = make([]int, 0)
+		}
+		tmpList = append(tmpList, v.ReportId)
+		sourceReportIdListMap[v.Source] = tmpList
+
+		tmpTxtType := `ficc`
+		if v.Source == 4 {
+			tmpTxtType = `rights`
+		}
+		stopTime := `--`
+		if v.StopTime > 0 {
+			stopTime = fmt.Sprint(stopTime)
+		}
+		viewReportMap[fmt.Sprint(v.Source, "_", v.ReportId)] = company.ViewReportList{
+			ResearchReportName: "",
+			ReportType:         "",
+			CreatedTime:        v.CreateTime,
+			TxtType:            tmpTxtType,
+			MatchTypeName:      "--",
+			StopTime:           stopTime,
+		}
+	}
+
+	// 获取报告详情
+	for source, reportIdList := range sourceReportIdListMap {
+		switch source {
+		case 1: // rddp报告
+			tmpReportList, err := models.GetReportByIdList(reportIdList)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
+				return
+			}
+			for _, v := range tmpReportList {
+				tmpKey := fmt.Sprint(source, "_", v.Id)
+				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
+					tmpInfo.ResearchReportName = v.Title
+					tmpInfo.ReportType = `rddp`
+					tmpInfo.MatchTypeName = v.ClassifyNameFirst
+					viewReportMap[tmpKey] = tmpInfo
+				}
+			}
+		case 2: // weekly报告
+			tmpReportList, err := models.GetResearchReportListByIdList(reportIdList)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
+				return
+			}
+			for _, v := range tmpReportList {
+				tmpKey := fmt.Sprint(source, "_", v.ResearchReportId)
+				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
+					tmpInfo.ResearchReportName = v.ResearchReportName
+					tmpInfo.ReportType = v.Type
+					viewReportMap[tmpKey] = tmpInfo
+				}
+			}
+		case 3: // weekly_report商品的报告(应该是作废了);
+			tmpReportList, err := models.GetChartPermissionByIdList(reportIdList)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
+				return
+			}
+			for _, v := range tmpReportList {
+				tmpKey := fmt.Sprint(source, "_", v.ChartPermissionId)
+				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
+					tmpInfo.ResearchReportName = v.ChartPermissionName
+					tmpInfo.ReportType = `advisory`
+					tmpInfo.MatchTypeName = v.ClassifyName
+					viewReportMap[tmpKey] = tmpInfo
+				}
+			}
+		case 4: // 察研观向的报告
+			tmpReportList, err := cygx.GetArticleListByIdList(reportIdList)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.Msg = "获取weekly报告详情失败,Err:" + err.Error()
+				return
+			}
+			for _, v := range tmpReportList {
+				tmpKey := fmt.Sprint(source, "_", v.ArticleId)
+				if tmpInfo, ok := viewReportMap[tmpKey]; ok {
+					tmpInfo.ResearchReportName = v.Title
+					tmpInfo.ReportType = `cygx`
+					tmpInfo.MatchTypeName = v.MatchTypeName
+					viewReportMap[tmpKey] = tmpInfo
+				}
+			}
+
+		}
+	}
+
+	// 报告标题处理
+	for _, v := range recordList {
+		tmpKey := fmt.Sprint(v.Source, "_", v.ReportId)
+		if tmpInfo, ok := viewReportMap[tmpKey]; ok {
+			list = append(list, &tmpInfo)
+		}
 	}
 
+	// 类型处理
 	for k, v := range list {
 		if v.ReportType == "day" {
 			list[k].MatchTypeName = "晨报"

+ 1 - 13
controllers/roadshow/company.go

@@ -4,9 +4,7 @@ import (
 	"hongze/hz_crm_api/models"
 	"hongze/hz_crm_api/models/company"
 	"hongze/hz_crm_api/models/roadshow"
-	"hongze/hz_crm_api/services"
 	"hongze/hz_crm_api/utils"
-	"strconv"
 	"strings"
 )
 
@@ -101,23 +99,13 @@ func (this *CalendarController) CompanyDetail() {
 		for _, v := range permissionList {
 			permissionArr = append(permissionArr, v.PermissionName)
 		}
-		readMap, err := services.GetFiccCountUserViewHistoryByCompanyIds(strconv.Itoa(companyId))
-		if err != nil {
-			br.Msg = "获取阅读次数失败!"
-			br.ErrMsg = "获取阅读次数失败!Err:" + err.Error()
-			return
-		}
-		readNum, ok := readMap[companyId]
-		if !ok {
-			readNum = 0
-		}
 		detailView.CompanyId = companyProductItem.CompanyId
 		detailView.CompanyName = companyProductItem.CompanyName
 		detailView.Status = companyProductItem.Status
 		detailView.IndustryId = companyProductItem.IndustryId
 		detailView.IndustryName = companyProductItem.IndustryName
 		detailView.PermissionName = strings.Join(permissionArr, "/")
-		detailView.ReportReadTotal = readNum //ficc报告-累计阅读次数
+		detailView.ReportReadTotal = companyProductItem.ViewTotal //ficc报告-累计阅读次数
 		br.Ret = 200
 		br.Success = true
 		br.Msg = "获取成功"

+ 16 - 1
models/chart_permission.go

@@ -2,6 +2,7 @@ package models
 
 import (
 	"github.com/beego/beego/v2/client/orm"
+	"hongze/hz_crm_api/utils"
 	"time"
 )
 
@@ -108,7 +109,21 @@ func GetChartPermissionByIds(permissionIds []string) (list []*ChartPermission, e
 	return
 }
 
-// GetChartPermissionByIds 主键获取权限
+// GetChartPermissionByIdList 主键获取权限
+func GetChartPermissionByIdList(chartPermissionIdList []int) (list []*ChartPermission, err error) {
+	num := len(chartPermissionIdList)
+	if num <= 0 {
+		return
+	}
+
+	o := orm.NewOrm()
+	sql := `select * from chart_permission where chart_permission_id in (` + utils.GetOrmInReplace(num) + `)`
+	_, err = o.Raw(sql, chartPermissionIdList).QueryRows(&list)
+
+	return
+}
+
+// GetChartPermissionByNames 主键获取权限
 func GetChartPermissionByNames(permissionNames []string) (list []*ChartPermission, err error) {
 	qb, _ := orm.NewQueryBuilder("mysql")
 	// 构建查询对象

+ 100 - 309
models/company/company_user.go

@@ -283,315 +283,6 @@ type ViewReportListResp struct {
 	List  []*ViewReportList
 }
 
-func GetViewReportListByMobile(mobile string, txtType int) (items []*ViewReportList, err error) {
-	dataName := ""
-	sql := ``
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-
-	ficcSql := `SELECT
-	rr.research_report_name,
-		rr.type AS report_type,
-		'ficc' AS txt_type,
-		'--' AS match_type_name,
-		'--' AS stop_time,
-	uvh.created_time AS created_time
-	FROM
-	user_view_history uvh
-	LEFT JOIN research_report rr ON rr.research_report_id = uvh.research_report_id
-	WHERE
-	uvh.mobile = ?
-	UNION ALL
-	SELECT
-	r.title AS research_report_name,
-		'rddp' AS report_type,
-		'ficc' AS txt_type,
-		r.classify_name_first AS match_type_name,
-		'--' AS stop_time,
-		rvr.create_time AS created_time
-	FROM %s.report_view_record rvr
-	LEFT JOIN %s.report r ON r.id = rvr.report_id
-	WHERE
-	rvr.mobile=?
-	UNION ALL
-	SELECT
-	cha.permission_name AS research_report_name,
-		'advisory' AS report_type,
-		'ficc' AS txt_type,
-		cha.classify_name AS match_type_name,
-		'--' AS stop_time,
-		auc.create_time AS created_time
-	FROM
-	advisory_user_chart_article_record auc
-	LEFT JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id
-	WHERE
-	auc.mobile = ?`
-
-	rightsSql := `SELECT
-		art.title AS research_report_name,
-		'cygx' AS report_type,
-		'rights' AS txt_type,
-		art.match_type_name,
-		h.stop_time,
-		h.create_time AS created_time 
-	FROM
-		cygx_article_history_record_all h
-		INNER JOIN cygx_article art ON art.article_id = h.article_id
-	WHERE
-		h.mobile = ? AND h.company_id != 16  AND h.is_del = 0 `
-
-	if txtType == 1 {
-		sql = ` SELECT * FROM ( ` + rightsSql + `
-	      )AS t ORDER BY t.created_time DESC`
-	} else if txtType == 2 {
-		sql = ` SELECT * FROM ( ` + ficcSql + `
-	      )AS t ORDER BY t.created_time DESC`
-	} else {
-		sql = ` SELECT * FROM ( ` + ficcSql + " UNION ALL " + rightsSql + `
-	      )AS t ORDER BY t.created_time DESC`
-	}
-
-	//报告统计删除晨报部分统计加入每日资讯 2021-4-9
-	//sql := ` SELECT * FROM (
-	//					SELECT
-	//							r.title AS research_report_name,
-	//							'rddp' AS report_type,
-	//							rvr.create_time AS created_time
-	//						FROM %s.report_view_record rvr
-	//						INNER JOIN %s.report r ON r.id = rvr.report_id
-	//						WHERE
-	//							rvr.mobile=?
-	//					UNION ALL
-	//					SELECT
-	//					cha.permission_name AS research_report_name,
-	//					'advisory' AS report_type,
-	//					auc.create_time AS created_time
-	//				FROM
-	//					advisory_user_chart_article_record auc
-	//					INNER JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id
-	//				WHERE
-	//					auc.mobile = ?
-	//       )AS t ORDER BY t.created_time DESC
-	//    `
-
-	o := orm.NewOrm()
-
-	if txtType == 1 {
-		_, err = o.Raw(sql, mobile).QueryRows(&items)
-	} else if txtType == 2 {
-		sql = fmt.Sprintf(sql, dataName, dataName)
-		_, err = o.Raw(sql, mobile, mobile, mobile).QueryRows(&items)
-	} else {
-		sql = fmt.Sprintf(sql, dataName, dataName)
-		_, err = o.Raw(sql, mobile, mobile, mobile, mobile).QueryRows(&items)
-	}
-
-	return
-}
-
-func GetViewReportListByEmail2(email string, txtType int) (items []*ViewReportList, err error) {
-	dataName := ""
-	sql := ``
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-
-	ficcSql := `SELECT
-	rr.research_report_name,
-		rr.type AS report_type,
-		'ficc' AS txt_type,
-		'--' AS match_type_name,
-		'--' AS stop_time,
-	uvh.created_time AS created_time
-	FROM
-	user_view_history uvh
-	INNER JOIN research_report rr ON rr.research_report_id = uvh.research_report_id
-	WHERE
-	uvh.email = ?
-	UNION ALL
-	SELECT
-	r.title AS research_report_name,
-		'rddp' AS report_type,
-		'ficc' AS txt_type,
-		r.classify_name_first AS match_type_name,
-		'--' AS stop_time,
-		rvr.create_time AS created_time
-	FROM %s.report_view_record rvr
-	INNER JOIN %s.report r ON r.id = rvr.report_id
-	WHERE
-	rvr.email=?
-	UNION ALL
-	SELECT
-	cha.permission_name AS research_report_name,
-		'advisory' AS report_type,
-		'ficc' AS txt_type,
-		cha.classify_name AS match_type_name,
-		'--' AS stop_time,
-		auc.create_time AS created_time
-	FROM
-	advisory_user_chart_article_record auc
-	INNER JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id
-	WHERE
-	auc.email = ?`
-
-	rightsSql := `SELECT
-		art.title AS research_report_name,
-		'cygx' AS report_type,
-		'rights' AS txt_type,
-		art.match_type_name,
-		h.stop_time,
-		h.create_time AS created_time 
-	FROM
-		cygx_article_history_record_all h
-		INNER JOIN cygx_article art ON art.article_id = h.article_id
-	WHERE
-		h.email = ? AND h.company_id != 16 AND h.is_del = 0 `
-
-	if txtType == 1 {
-		sql = ` SELECT * FROM ( ` + rightsSql + `
-	      )AS t ORDER BY t.created_time DESC`
-	} else if txtType == 2 {
-		sql = ` SELECT * FROM ( ` + ficcSql + `
-	      )AS t ORDER BY t.created_time DESC`
-	} else {
-		sql = ` SELECT * FROM ( ` + ficcSql + " UNION ALL " + rightsSql + `
-	      )AS t ORDER BY t.created_time DESC`
-	}
-
-	//报告统计删除晨报部分统计加入每日资讯 2021-4-9
-	//sql := ` SELECT * FROM (
-	//					SELECT
-	//							r.title AS research_report_name,
-	//							'rddp' AS report_type,
-	//							rvr.create_time AS created_time
-	//						FROM %s.report_view_record rvr
-	//						INNER JOIN %s.report r ON r.id = rvr.report_id
-	//						WHERE
-	//							rvr.mobile=?
-	//					UNION ALL
-	//					SELECT
-	//					cha.permission_name AS research_report_name,
-	//					'advisory' AS report_type,
-	//					auc.create_time AS created_time
-	//				FROM
-	//					advisory_user_chart_article_record auc
-	//					INNER JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id
-	//				WHERE
-	//					auc.mobile = ?
-	//       )AS t ORDER BY t.created_time DESC
-	//    `
-
-	o := orm.NewOrm()
-	if txtType == 1 {
-		_, err = o.Raw(sql, email).QueryRows(&items)
-	} else if txtType == 2 {
-		sql = fmt.Sprintf(sql, dataName, dataName)
-		_, err = o.Raw(sql, email, email, email).QueryRows(&items)
-	} else {
-		sql = fmt.Sprintf(sql, dataName, dataName)
-		_, err = o.Raw(sql, email, email, email, email).QueryRows(&items)
-	}
-
-	return
-}
-
-func GetViewReportListByEmail(email string) (items []*ViewReportList, err error) {
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
-	}
-	sql := ` SELECT * FROM (
-				SELECT
-							rr.research_report_name,
-							rr.type AS report_type,
-							uvh.created_time AS created_time
-						FROM
-							user_view_history uvh
-							INNER JOIN research_report rr ON rr.research_report_id = uvh.research_report_id
-						WHERE
-							uvh.email = ?
-						UNION ALL
-						SELECT
-								r.title AS research_report_name,
-								'rddp' AS report_type,
-								rvr.create_time AS created_time
-							FROM %s.report_view_record rvr
-							INNER JOIN %s.report r ON r.id = rvr.report_id
-							WHERE
-								rvr.email=?
-						UNION ALL
-						SELECT
-						cha.permission_name AS research_report_name,
-						'advisory' AS report_type,
-						auc.create_time AS created_time 
-					FROM
-						advisory_user_chart_article_record auc
-						INNER JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id 
-					WHERE
-						auc.email = ?
-	      )AS t ORDER BY t.created_time DESC
-       `
-	//报告统计删除晨报部分统计加入每日资讯 2021-4-9
-	//sql := ` SELECT * FROM (
-	//					SELECT
-	//							r.title AS research_report_name,
-	//							'rddp' AS report_type,
-	//							rvr.create_time AS created_time
-	//						FROM %s.report_view_record rvr
-	//						INNER JOIN %s.report r ON r.id = rvr.report_id
-	//						WHERE
-	//							rvr.email=?
-	//					UNION ALL
-	//					SELECT
-	//					cha.permission_name AS research_report_name,
-	//					'advisory' AS report_type,
-	//					auc.create_time AS created_time
-	//				FROM
-	//					advisory_user_chart_article_record auc
-	//					INNER JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id
-	//				WHERE
-	//					auc.email = ?
-	//       )AS t ORDER BY t.created_time DESC
-	//    `
-	sql = fmt.Sprintf(sql, dataName, dataName)
-	o := orm.NewOrm()
-	_, err = o.Raw(sql, email, email, email).QueryRows(&items)
-	return
-}
-
-func GetCompanyUserByCompanyId(companyId int) (items []*CompanyUser, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT a.*,b.company_name,
-             (SELECT count(1) FROM user_view_history AS uvh WHERE uvh.user_id=a.user_id GROUP BY a.user_id) AS view_total,
-             (SELECT max(uvh.created_time) FROM user_view_history AS uvh WHERE uvh.user_id=a.user_id GROUP BY a.user_id) AS last_view_time
-              FROM wx_user AS a 
-			 INNER JOIN company AS b ON a.company_id=b.company_id
-			 WHERE a.company_id=? `
-	sql += `ORDER BY  a.last_updated_time DESC `
-	_, err = o.Raw(sql, companyId).QueryRows(&items)
-	return
-}
-
-func GetCompanyUserExportByCompanyId(companyId int) (items []*CompanyUser, err error) {
-	o := orm.NewOrm()
-	sql := ` SELECT a.*,b.company_name,
-             (SELECT count(1) FROM user_view_history AS uvh WHERE uvh.user_id=a.user_id GROUP BY a.user_id) AS view_total,
-             (SELECT max(uvh.created_time) FROM user_view_history AS uvh WHERE uvh.user_id=a.user_id GROUP BY a.user_id) AS last_view_time
-              FROM wx_user AS a 
-			 INNER JOIN company AS b ON a.company_id=b.company_id
-			 WHERE a.company_id=? AND a.company_id<>1 `
-	sql += `ORDER BY  a.last_updated_time DESC `
-	_, err = o.Raw(sql, companyId).QueryRows(&items)
-	return
-}
-
 func ModifyCompanyUserCompanyId(userId, companyId int) (err error) {
 	o := orm.NewOrm()
 	sql := ` UPDATE wx_user SET company_id=?  WHERE user_id=? `
@@ -676,3 +367,103 @@ func GetCompanyUsersByCondition(condition string, pars []interface{}) (list []*C
 	_, err = orm.NewOrm().Raw(sql, pars).QueryRows(&list)
 	return
 }
+
+type ViewReportListV2 struct {
+	Id                 int    `description:"阅读记录id"`
+	UserId             int    `description:"用户id"`
+	Mobile             string `description:"手机号"`
+	Email              string `description:"邮箱"`
+	RealName           string `description:"真实姓名"`
+	CompanyName        string `description:"客户名称"`
+	ResearchReportName string `description:"报告标题"`
+	ReportType         int8   `description:"来源:1:rddp的报告;2:weekly_report的PHP报告;3:weekly_report商品的报告(应该是作废了);4:察研观向的报告""`
+	CreatedTime        string `description:"创建时间"`
+	TxtType            string `description:"类型 ficc:ficc  、 rights:权益"`
+	MatchTypeName      string `description:"匹配类型"`
+	StopTime           int    `description:"停留时间"`
+	ReportId           int    `description:"报告id"`
+	ReportChapterId    int    `description:"报告章节id"`
+}
+
+func GetViewReportListByDate(startDate, endDate string) (items []*ViewReportListV2, err error) {
+	dataName := ""
+	sql := ``
+	if utils.RunMode == "debug" {
+		dataName = "test_v2_hongze_rddp"
+	} else {
+		dataName = "hongze_rddp"
+	}
+
+	ficcSql := `SELECT
+    uvh.user_id,uvh.mobile,uvh.email,uvh.view_history_id AS id,uvh.real_name,uvh.company_name,
+    uvh.research_report_id as report_id,
+    uvh.research_report_type_id as report_chapter_id,
+	rr.research_report_name,
+		"2" AS report_type,
+		'ficc' AS txt_type,
+		'--' AS match_type_name,
+		'0' AS stop_time,
+	uvh.created_time AS created_time
+	FROM
+	user_view_history uvh
+	LEFT JOIN research_report rr ON rr.research_report_id = uvh.research_report_id
+	WHERE
+	uvh.created_time >= ? AND uvh.created_time< ?
+	UNION ALL
+	SELECT
+    rvr.user_id,rvr.mobile,rvr.email,rvr.id,rvr.real_name,rvr.company_name,
+    rvr.report_id,
+    rvr.report_chapter_id,
+	r.title AS research_report_name,
+		'1' AS report_type,
+		'ficc' AS txt_type,
+		r.classify_name_first AS match_type_name,
+		'0' AS stop_time,
+		rvr.create_time AS created_time
+	FROM %s.report_view_record rvr
+	LEFT JOIN %s.report r ON r.id = rvr.report_id
+	WHERE
+	rvr.create_time >= ? AND rvr.create_time< ?
+	UNION ALL
+	SELECT
+    auc.user_id,auc.mobile,auc.email,auc.id,auc.real_name,auc.company_name,
+    auc.chart_permission_id as report_id,
+    '0' AS report_chapter_id,
+	cha.permission_name AS research_report_name,
+		'3' AS report_type,
+		'ficc' AS txt_type,
+		cha.classify_name AS match_type_name,
+		'0' AS stop_time,
+		auc.create_time AS created_time
+	FROM
+	advisory_user_chart_article_record auc
+	LEFT JOIN chart_permission cha ON cha.chart_permission_id = auc.chart_permission_id
+	WHERE
+	auc.create_time >= ? AND auc.create_time< ?`
+
+	rightsSql := `SELECT
+    h.user_id,h.mobile,h.email,h.id,h.company_name,'' AS real_name,
+    h.article_id AS  report_id,
+    '0' AS report_chapter_id,
+		art.title AS research_report_name,
+		'4' AS report_type,
+		'rights' AS txt_type,
+		art.match_type_name,
+		h.stop_time,
+		h.create_time AS created_time 
+	FROM
+		cygx_article_history_record_newpv h
+		INNER JOIN cygx_article art ON art.article_id = h.article_id
+	WHERE
+	h.create_time >= ? AND h.create_time< ? `
+
+	sql = ` SELECT * FROM ( ` + ficcSql + " UNION ALL " + rightsSql + `
+	      )AS t ORDER BY t.created_time asc`
+
+	o := orm.NewOrm()
+
+	sql = fmt.Sprintf(sql, dataName, dataName)
+	_, err = o.Raw(sql, startDate, endDate, startDate, endDate, startDate, endDate, startDate, endDate).QueryRows(&items)
+
+	return
+}

+ 14 - 1
models/cygx/report_article.go

@@ -1054,7 +1054,20 @@ func GetArticlList(condition string, pars []interface{}, startSize, pageSize int
 	return
 }
 
-// 修改发布状态
+// GetArticleListByIdList 根据报告id列表获取报告列表
+func GetArticleListByIdList(articleLIdList []int) (items []*CygxArticle, err error) {
+	num := len(articleLIdList)
+	if num <= 0 {
+		return
+	}
+
+	o := orm.NewOrm()
+	sql := `SELECT * FROM cygx_article as art WHERE 1= 1 AND article_id in (` + utils.GetOrmInReplace(num) + `)`
+	_, err = o.Raw(sql, articleLIdList).QueryRows(&items)
+	return
+}
+
+// RoadshowEssencePublishAndCancel 修改发布状态
 func RoadshowEssencePublishAndCancel(item *CygxResearchSummaryRep) (err error) {
 	o := orm.NewOrm()
 	sql := `UPDATE cygx_article SET  publish_status=? , last_updated_time= ?, periods= ?,admin_id =? ,admin_name =? ,have_publish = 1 WHERE article_id=? `

+ 1 - 0
models/cygx/summary_manage.go

@@ -68,6 +68,7 @@ type CygxArticle struct {
 	IsReport           int       `description:"是否属于报告 1是、0否"`
 	ReportType         int       `description:"'报告类型,1行业报告,2产业报告'"`
 	Source             int       `description:"来源 0策略平台同步,1小程序后台添加"`
+	MatchTypeName      string    `description:"匹配类型名称"`
 	ArticleIdMd5       string    `description:"ID,md5值"`
 	UpdateFrequency    string    `description:"更新周期"`
 	SellerAndMobile    string    `description:"销售和手机号"`

+ 2 - 1
models/db.go

@@ -276,7 +276,8 @@ func initReport() {
 		new(ClassifyMenuRelation), // 报告分类-子目录关联表
 		new(ReportSendThsConfig),  //产品推送给同花顺的配置表
 		//new(ChartPermissionChapterMapping), // 权限mapping表
-		new(ReportChapterType), // 报告章节类型表
+		new(ReportChapterType),    // 报告章节类型表
+		new(UserReportViewRecord), // 用户报告阅读记录表(汇总表)
 	)
 }
 

+ 15 - 0
models/report.go

@@ -3,6 +3,7 @@ package models
 import (
 	"github.com/beego/beego/v2/client/orm"
 	"github.com/rdlucklib/rdluck_tools/paging"
+	"hongze/hz_crm_api/utils"
 	"strings"
 	"time"
 )
@@ -126,6 +127,20 @@ func GetReportByIds(reportIds string) (list []*ReportDetail, err error) {
 	return
 }
 
+// GetReportByIdList 根据报告id列表获取报告列表
+func GetReportByIdList(reportIdList []int) (list []*ReportDetail, err error) {
+	num := len(reportIdList)
+	if num <= 0 {
+		return
+	}
+
+	o := orm.NewOrmUsingDB("rddp")
+	sql := `SELECT * FROM report WHERE id in  (` + utils.GetOrmInReplace(num) + `)`
+	_, err = o.Raw(sql, reportIdList).QueryRows(&list)
+
+	return
+}
+
 // GetSimpleReportByIds 根据报告ID查询报告基本信息
 func GetSimpleReportByIds(reportIds string) (list []*ReportDetail, err error) {
 	o := orm.NewOrmUsingDB("rddp")

+ 56 - 1
models/research_report.go

@@ -1,6 +1,61 @@
 package models
 
-import "time"
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"hongze/hz_crm_api/utils"
+	"time"
+)
+
+// ResearchReport 研究报告表(晨报、周报等)结构体
+type ResearchReport struct {
+	ResearchReportId    int       `orm:"column(research_report_id);pk" description:"研究报告id"`
+	ResearchReportName  string    `description:"研究报告名称"`
+	ResearchReportTitle string    `description:"研究报告标题"`
+	ResearchReportImg   string    `description:"报告缩略图URL"`
+	ResearchReportDate  time.Time `description:"报告日期"`
+	Type                string    `description:"报告类型,枚举值:day 晨报  week 周报 twoweek双周报 month 月报;默认:day"`
+	Author              string    `description:"作者"`
+	ReportVariety       string    `description:"研究报告的品种,双周报和月报有标识"`
+	IsHasMenu           int8      `description:"报告是否含有目录"`
+	IsSendedMsg         int8      `description:"是否发送过模板消息"`
+	Periods             int       `description:"期数"`
+	Status              string    `description:"状态,draft:草稿,"`
+	Enabled             int8      `description:"报告状态"`
+	CreatedTime         string    `description:"创建时间"`
+	LastUpdatedTime     time.Time `description:"最近一次更新时间"`
+	Viewers             int       `description:"H5观看用户数"`
+}
+
+// GetResearchReportListByIds 根据报告id集合获取报告数据列表
+func GetResearchReportListByIds(researchReportIds string) (list []*ResearchReport, err error) {
+	if researchReportIds == "" {
+		return
+	}
+	o := orm.NewOrm()
+	sql := `select * from research_report where research_report_id in (` + researchReportIds + `)`
+	_, err = o.Raw(sql).QueryRows(&list)
+	return
+}
+
+// GetResearchReportListByIdList 根据报告id集合获取报告数据列表
+func GetResearchReportListByIdList(researchReportIdList []int) (list []*ResearchReport, err error) {
+	num := len(researchReportIdList)
+	if num <= 0 {
+		return
+	}
+
+	o := orm.NewOrm()
+	sql := `select * from research_report where research_report_id in (` + utils.GetOrmInReplace(num) + `)`
+	_, err = o.Raw(sql, researchReportIdList).QueryRows(&list)
+	return
+}
+
+// Update 更新数据
+func (researchReport *ResearchReport) Update(updateCols []string) (err error) {
+	o := orm.NewOrm()
+	_, err = o.Update(researchReport, updateCols...)
+	return
+}
 
 type ResearchReportList struct {
 	ResearchReportId    int       `orm:"column(research_report_id);pk" description:"研究报告id"`

+ 148 - 0
models/user_report_view_record.go

@@ -0,0 +1,148 @@
+package models
+
+import (
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"strings"
+	"sync"
+)
+
+// UserReportViewRecord 用户报告阅读记录表(汇总表)
+type UserReportViewRecord struct {
+	Id              int    `orm:"column(id);pk"`
+	Source          int8   `description:"来源,1:rddp的报告;2:weekly_report的PHP报告;3:weekly_report商品的报告(应该是作废了);4:察研观向的报告"`
+	UserId          int    `description:"用户id"`
+	ReportId        int    `description:"报告id"`
+	ReportChapterId int    `description:"报告章节id"`
+	Mobile          string `description:"手机号"`
+	Email           string `description:"邮箱"`
+	RealName        string `description:"用户实际姓名"`
+	CompanyName     string `description:"公司名称"`
+	StopTime        int    `description:"停留时间"`
+	OutId           string `description:"外部关联id"`
+	CreateTime      string `description:"创建时间"`
+}
+
+// TableName 表名
+func (obj UserReportViewRecord) TableName() string {
+	return `user_report_view_record`
+}
+
+// GetViewReportList 单条记录插入
+func (obj UserReportViewRecord) GetViewReportList(year int, condition string, pars []interface{}, startSize, pageSize int) (total int64, items []*UserReportViewRecord, err error) {
+	tableName := obj.GetTableName(year)
+
+	o := orm.NewOrm()
+	sql := fmt.Sprintf(`SELECT *  FROM %s WHERE 1 = 1 `, tableName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` ORDER BY create_time DESC,id DESC LIMIT ?,? `
+	total, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+
+	return
+
+}
+
+// Insert 单条记录插入
+func (obj UserReportViewRecord) Insert(year int, item *UserReportViewRecord) (err error) {
+	tableName := obj.GetTableName(year)
+
+	sql := "INSERT INTO " + tableName + " (`source`, `user_id`, `report_id`, `report_chapter_id`, `mobile`, `email`, `real_name`, `company_name`, `stop_time`, `out_id`, `create_time`) VALUES "
+
+	valStr := fmt.Sprintf(`( %d, %d, %d, %d, "%s", "%s","%s", "%s", %d, "%s", "%s")`, item.Source, item.UserId, item.ReportId, item.ReportChapterId, item.Mobile, item.Email, item.RealName, item.CompanyName, item.StopTime, item.OutId, item.CreateTime)
+
+	sql = sql + valStr + ";"
+
+	o := orm.NewOrm()
+
+	// 先校验表是否存在,不存在的话,需要创建表
+	err = obj.CheckAndCreateTable(o, tableName)
+	if err != nil {
+		return
+	}
+
+	// 插入数据
+	_, err = o.Raw(sql).Exec()
+
+	return
+
+}
+
+// InsertMul 单条记录插入
+func (obj UserReportViewRecord) InsertMul(year int, items []*UserReportViewRecord) (err error) {
+	tableName := obj.GetTableName(year)
+
+	sql := "INSERT INTO " + tableName + " (`source`, `user_id`, `report_id`, `report_chapter_id`, `mobile`, `email`, `real_name`, `company_name`, `stop_time`, `out_id`, `create_time`) VALUES "
+
+	valStrList := make([]string, 0)
+	for _, item := range items {
+		valStrList = append(valStrList, fmt.Sprintf(`( %d, %d, %d, %d, "%s", "%s","%s", "%s", %d, "%s", "%s")`, item.Source, item.UserId, item.ReportId, item.ReportChapterId, item.Mobile, item.Email, item.RealName, item.CompanyName, item.StopTime, item.OutId, item.CreateTime))
+	}
+
+	if len(valStrList) <= 0 {
+		return
+	}
+
+	valStr := strings.Join(valStrList, ",")
+	sql = sql + valStr + ";"
+
+	o := orm.NewOrm()
+
+	// 先校验表是否存在,不存在的话,需要创建表
+	err = obj.CheckAndCreateTable(o, tableName)
+	if err != nil {
+		return
+	}
+
+	// 插入数据
+	_, err = o.Raw(sql).Exec()
+
+	return
+
+}
+
+// GetTableName 获取表名
+func (obj UserReportViewRecord) GetTableName(year int) string {
+	return fmt.Sprintf(`user_report_view_record_%d`, year)
+}
+
+// tableNameMap 已创建表的map
+var tableNameMap = map[string]string{}
+
+// createTableMutex 创建表的时候的锁
+var createTableMutex = &sync.Mutex{}
+
+// CheckAndCreateTable 通过表名校验表是否存在,不存在的话,需要创建表
+func (obj UserReportViewRecord) CheckAndCreateTable(o orm.Ormer, tableName string) (err error) {
+	if _, ok := tableNameMap[tableName]; ok {
+		return
+	}
+
+	// 表判断的时候需要加锁,避免多个协程调用时,表还没有创建成功,又被另一个协程发现表不存在,然后再次创建表
+	createTableMutex.Lock()
+	defer func() {
+		createTableMutex.Unlock()
+	}()
+
+	db := o.Raw(fmt.Sprintf(`SHOW TABLES LIKE "%s"`, tableName))
+	var result []orm.Params
+	_, err = db.Values(&result)
+	if err != nil {
+		fmt.Println("查询表失败:", err)
+		return
+	}
+
+	// 不存在该表,那么就去创建表
+	if len(result) <= 0 {
+		baseSql := fmt.Sprintf("CREATE TABLE `%s` (\n  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',\n  `source` tinyint(20) NOT NULL DEFAULT '0' COMMENT '来源,1:rddp的报告;2:weekly_report的PHP报告;3:weekly_report商品的报告(应该是作废了);4:察研观向的报告',\n  `user_id` int(11) DEFAULT '0' COMMENT '用户id',\n  `report_id` int(11) DEFAULT '0' COMMENT '报告id',\n  `report_chapter_id` int(10) DEFAULT NULL COMMENT '报告章节id',\n  `mobile` varchar(20) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '手机号',\n  `email` varchar(100) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '邮箱',\n  `real_name` varchar(30) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '用户时间名称',\n  `company_name` varchar(100) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '公司名称',\n  `stop_time` int(5) NOT NULL DEFAULT '0' COMMENT '停留时间',\n  `out_id` varchar(20) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '外部关联id',\n  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '阅读时间',\n  PRIMARY KEY (`id`),\n  KEY `idx_user_id` (`user_id`),\n  KEY `idx_report_id` (`report_id`),\n  KEY `idx_mobile` (`mobile`),\n  KEY `idx_email` (`email`),\n  KEY `idx_ctime` (`create_time`)\n) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;", tableName)
+		_, err = o.Raw(baseSql).Exec()
+		if err != nil {
+			return
+		}
+	}
+
+	tableNameMap[tableName] = tableName
+
+	return
+}

+ 60 - 60
models/user_view_history.go

@@ -183,41 +183,39 @@ WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""
 	return
 }
 
-// GetLastReportViewRecordByCompanyIdsMobile 根据手机号获取客户的最新浏览时间
-func GetLastReportViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
+// MobileOrEmailLastViewSlice 根据手机号/邮箱获取客户的最新浏览时间
+type MobileOrEmailLastViewSlice struct {
+	Mobile   string    `description:"手机号/邮箱"`
+	ViewTime time.Time `description:"用户浏览时间"`
+}
+
+// GetLastReportViewRecordByMobileList 根据手机号获取客户的最新浏览时间
+func GetLastReportViewRecordByMobileList(mobileList []string) (items []*MobileOrEmailLastViewSlice, err error) {
+	num := len(mobileList)
+	if num <= 0 {
+		return
 	}
-	sql := `SELECT
-	a.company_id ,max(b.create_time) view_time
-FROM
-	wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and b.create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
+	today := time.Now().Format(utils.FormatDate)
+	o := orm.NewOrmUsingDB("rddp")
+
+	sql := `SELECT mobile ,max(create_time) view_time FROM report_view_record 
+WHERE mobile IN ( ` + utils.GetOrmInReplace(num) + ` )  and mobile !="" and create_time>=? GROUP BY mobile`
+	_, err = o.Raw(sql, mobileList, today).QueryRows(&items)
 	return
 }
 
-// GetLastReportViewRecordByCompanyIdsEmail 根据邮箱获取客户的最新浏览时间
-func GetLastReportViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyLastViewSlice, err error) {
-	today := time.Now().Format(utils.FormatDate)
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
+// GetLastReportViewRecordByEmailList 根据邮箱获取客户的最新浏览时间
+func GetLastReportViewRecordByEmailList(emailList []string) (items []*MobileOrEmailLastViewSlice, err error) {
+	num := len(emailList)
+	if num <= 0 {
+		return
 	}
-	sql := `SELECT	a.company_id ,max(b.create_time) view_time FROM wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile=""   and b.create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
+	today := time.Now().Format(utils.FormatDate)
+	o := orm.NewOrmUsingDB("rddp")
+
+	sql := `SELECT email AS mobile ,max(create_time) view_time FROM report_view_record 
+WHERE email IN ( ` + utils.GetOrmInReplace(num) + ` )  and email !="" and create_time>=? GROUP BY email`
+	_, err = o.Raw(sql, emailList, today).QueryRows(&items)
 	return
 }
 
@@ -348,41 +346,43 @@ WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile="" GR
 	return
 }
 
-// GetCountReportViewRecordByCompanyIdsMobile 根据手机号获取客户的浏览次数
-func GetCountReportViewRecordByCompanyIdsMobile(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
+// MobileOrEmailViewTotalSlice 获取客户的浏览次数
+type MobileOrEmailViewTotalSlice struct {
+	Mobile    string `description:"客户手机号/邮箱"`
+	ViewTotal int    `description:"用户浏览次数"`
+}
+
+// GetCountReportViewRecordByMobileList 根据手机号获取客户的浏览次数
+func GetCountReportViewRecordByMobileList(mobileList []string) (items []*MobileOrEmailViewTotalSlice, err error) {
+	num := len(mobileList)
+	if num <= 0 {
+		return
 	}
-	sql := `SELECT
-	a.company_id ,count(1) view_total
-FROM
-	wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.mobile = b.mobile 
-WHERE
-	a.company_id IN ( ` + companyIds + ` )  and b.mobile !="" and create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
+
+	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
+	o := orm.NewOrmUsingDB("rddp")
+
+	sql := `SELECT mobile ,count(1) AS view_total FROM report_view_record
+WHERE mobile IN ( ` + utils.GetOrmInReplace(num) + ` )  and mobile !="" and create_time>=? GROUP BY mobile`
+	_, err = o.Raw(sql, mobileList, today).QueryRows(&items)
+
 	return
 }
 
-// GetCountReportViewRecordByCompanyIdsEmail 根据邮箱获取客户的浏览次数
-func GetCountReportViewRecordByCompanyIdsEmail(companyIds string) (items []*CompanyViewTotalSlice, err error) {
-	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
-	o := orm.NewOrm()
-	dataName := ""
-	if utils.RunMode == "debug" {
-		dataName = "test_v2_hongze_rddp"
-	} else {
-		dataName = "hongze_rddp"
+// GetCountReportViewRecordByEmailList 根据邮箱获取客户的浏览次数
+func GetCountReportViewRecordByEmailList(emailList []string) (items []*MobileOrEmailViewTotalSlice, err error) {
+	num := len(emailList)
+	if num <= 0 {
+		return
 	}
-	sql := `SELECT	a.company_id ,count(1) view_total FROM wx_user a
-	JOIN ` + dataName + `.report_view_record b ON a.email = b.email 
-WHERE a.company_id IN ( ` + companyIds + ` ) and b.email !="" and b.mobile="" and create_time>=? GROUP BY company_id`
-	_, err = o.Raw(sql, today).QueryRows(&items)
+
+	today := time.Now().Format(utils.FormatDate) + " 00:00:00"
+	o := orm.NewOrmUsingDB("rddp")
+
+	sql := `SELECT email AS mobile ,count(1) AS view_total FROM report_view_record
+WHERE email IN ( ` + utils.GetOrmInReplace(num) + ` )  and email !="" and create_time>=? GROUP BY email`
+	_, err = o.Raw(sql, emailList, today).QueryRows(&items)
+
 	return
 }
 

+ 13 - 1
models/wx_user.go

@@ -521,4 +521,16 @@ func GetWxUserListCompanyId(companyId int) (list []*WxUserItem, err error) {
 	sql := ` SELECT* FROM wx_user  WHERE company_id = ?   `
 	_, err = o.Raw(sql, companyId).QueryRows(&list)
 	return
-}
+}
+
+// GetWxUserByCompanyIds 根据客户ID集合获取用户列表
+func GetWxUserByCompanyIds(companyIds []int) (items []*WxUser, err error) {
+	num := len(companyIds)
+	if num == 0 {
+		return
+	}
+	sql := `SELECT * FROM wx_user  WHERE company_id in (` + utils.GetOrmInReplace(num) + `)  `
+	o := orm.NewOrm()
+	_, err = o.Raw(sql, companyIds).QueryRows(&items)
+	return
+}

+ 102 - 40
services/company.go

@@ -1807,7 +1807,7 @@ func GetLastContractPermissionList(companyId, productId int) (permissionMap map[
 }
 
 // GetFiccLastUserViewHistoryByCompanyIds 根据客户id集合map获取ficc最后一次阅读时间
-func GetFiccLastUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTime map[int]time.Time, err error) {
+func GetFiccLastUserViewHistoryByCompanyIds(companyIdStr string, mobileList, emailList []string, mobileCompanyIdMap, emailCompanyIdMap map[string]int) (companyViewTime map[int]time.Time, err error) {
 	//user_view_record mobile
 	companyViewTime = make(map[int]time.Time)
 	userViewList, err := models.GetLastUserViewHistoryByCompanyIdsMobile(companyIdStr)
@@ -1840,18 +1840,18 @@ func GetFiccLastUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTim
 	checkLastTime(companyViewTime, userViewList)
 
 	//ReportViewRecord mobile
-	userViewList, err = models.GetLastReportViewRecordByCompanyIdsMobile(companyIdStr)
+	mobileOrEmailViewList, err := models.GetLastReportViewRecordByMobileList(mobileList)
 	if err != nil {
 		return
 	}
-	checkLastTime(companyViewTime, userViewList)
+	checkMobileOrEmailLastTime(companyViewTime, mobileOrEmailViewList, mobileCompanyIdMap)
 
 	//ReportViewRecord email
-	userViewList, err = models.GetLastReportViewRecordByCompanyIdsEmail(companyIdStr)
+	mobileOrEmailViewList, err = models.GetLastReportViewRecordByEmailList(emailList)
 	if err != nil {
 		return
 	}
-	checkLastTime(companyViewTime, userViewList)
+	checkMobileOrEmailLastTime(companyViewTime, mobileOrEmailViewList, emailCompanyIdMap)
 
 	//UserViewStatistics mobile
 	userViewList, err = models.GetLastUserViewStatisticsByCompanyIdsMobile(companyIdStr)
@@ -1905,8 +1905,30 @@ func checkLastTime(companyViewTime map[int]time.Time, userViewList []*models.Com
 	return
 }
 
+// checkMobileOrEmailLastTime 根据用户信息检测最后的时间并重新赋值
+func checkMobileOrEmailLastTime(companyViewTime map[int]time.Time, userViewList []*models.MobileOrEmailLastViewSlice, companyMap map[string]int) {
+	for _, userView := range userViewList {
+		// 先找到客户id
+		companyId, ok := companyMap[userView.Mobile]
+		if !ok {
+			continue
+		}
+
+		// 相同客户id的数据进行比较
+
+		if viewTime, ok := companyViewTime[companyId]; ok {
+			if userView.ViewTime.After(viewTime) { //如果当前时间晚于 map中的时间,那么重新赋值
+				companyViewTime[companyId] = userView.ViewTime
+			}
+		} else { //如果没有数据,那么直接赋值
+			companyViewTime[companyId] = userView.ViewTime
+		}
+	}
+	return
+}
+
 // GetFiccCountUserViewHistoryByCompanyIds 根据客户id集合map获取ficc的阅读次数
-func GetFiccCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTotal map[int]int, err error) {
+func GetFiccCountUserViewHistoryByCompanyIds(companyIdStr string, mobileList, emailList []string, mobileCompanyIdMap, emailCompanyIdMap map[string]int) (companyViewTotal map[int]int, err error) {
 	//user_view_record mobile
 	companyViewTotal = make(map[int]int)
 	userViewList, err := models.GetCountUserViewHistoryByCompanyIdsMobile(companyIdStr)
@@ -1937,18 +1959,18 @@ func GetFiccCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTo
 	checkCount(companyViewTotal, userViewList)
 
 	//ReportViewRecord mobile
-	userViewList, err = models.GetCountReportViewRecordByCompanyIdsMobile(companyIdStr)
+	mobileOrEmailViewList, err := models.GetCountReportViewRecordByMobileList(mobileList)
 	if err != nil {
 		return
 	}
-	checkCount(companyViewTotal, userViewList)
+	checkMobileOrEmailCount(companyViewTotal, mobileOrEmailViewList, mobileCompanyIdMap)
 
 	//ReportViewRecord email
-	userViewList, err = models.GetCountReportViewRecordByCompanyIdsEmail(companyIdStr)
+	mobileOrEmailViewList, err = models.GetCountReportViewRecordByEmailList(emailList)
 	if err != nil {
 		return
 	}
-	checkCount(companyViewTotal, userViewList)
+	checkMobileOrEmailCount(companyViewTotal, mobileOrEmailViewList, emailCompanyIdMap)
 
 	//UserViewStatistics mobile
 	userViewList, err = models.GetUserViewStatisticsByCompanyIdsMobile(companyIdStr)
@@ -1988,34 +2010,34 @@ func GetRaiCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTot
 }
 
 // GetAllCountUserViewHistoryByCompanyIds 根据客户id集合map获取所有的阅读次数
-func GetAllCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTotal map[int]int, err error) {
-	companyViewTotal = make(map[int]int)
-	companyFiccViewTotal, err := GetFiccCountUserViewHistoryByCompanyIds(companyIdStr)
-	if err != nil {
-		return
-	}
-
-	companyRaiViewTotal, err := GetRaiCountUserViewHistoryByCompanyIds(companyIdStr)
-	if err != nil {
-		return
-	}
-
-	companyIdList := strings.Split(companyIdStr, ",")
-
-	for _, companyIdStr := range companyIdList {
-		companyId, _ := strconv.Atoi(companyIdStr)
-		ficcTotal, ok := companyFiccViewTotal[companyId]
-		if !ok {
-			ficcTotal = 0
-		}
-		raiTotal, ok := companyRaiViewTotal[companyId]
-		if !ok {
-			raiTotal = 0
-		}
-		companyViewTotal[companyId] = ficcTotal + raiTotal
-	}
-	return
-}
+//func GetAllCountUserViewHistoryByCompanyIds(companyIdStr string) (companyViewTotal map[int]int, err error) {
+//	companyViewTotal = make(map[int]int)
+//	companyFiccViewTotal, err := GetFiccCountUserViewHistoryByCompanyIds(companyIdStr)
+//	if err != nil {
+//		return
+//	}
+//
+//	companyRaiViewTotal, err := GetRaiCountUserViewHistoryByCompanyIds(companyIdStr)
+//	if err != nil {
+//		return
+//	}
+//
+//	companyIdList := strings.Split(companyIdStr, ",")
+//
+//	for _, companyIdStr := range companyIdList {
+//		companyId, _ := strconv.Atoi(companyIdStr)
+//		ficcTotal, ok := companyFiccViewTotal[companyId]
+//		if !ok {
+//			ficcTotal = 0
+//		}
+//		raiTotal, ok := companyRaiViewTotal[companyId]
+//		if !ok {
+//			raiTotal = 0
+//		}
+//		companyViewTotal[companyId] = ficcTotal + raiTotal
+//	}
+//	return
+//}
 
 func checkCount(companyViewTotal map[int]int, userViewList []*models.CompanyViewTotalSlice) {
 	for _, userView := range userViewList {
@@ -2028,6 +2050,25 @@ func checkCount(companyViewTotal map[int]int, userViewList []*models.CompanyView
 	return
 }
 
+// checkMobileOrEmailCount 根据手机号或者邮箱进行数据比较
+func checkMobileOrEmailCount(companyViewTotal map[int]int, mobileOrEmailViewList []*models.MobileOrEmailViewTotalSlice, companyMap map[string]int) {
+	for _, userView := range mobileOrEmailViewList {
+		// 先找到客户id
+		companyId, ok := companyMap[userView.Mobile]
+		if !ok {
+			continue
+		}
+
+		// 相同客户id的数据进行比较
+		if viewTotal, ok := companyViewTotal[companyId]; ok {
+			companyViewTotal[companyId] = viewTotal + userView.ViewTotal
+		} else { //如果没有数据,那么直接赋值
+			companyViewTotal[companyId] = userView.ViewTotal
+		}
+	}
+	return
+}
+
 // ModifyCompanyProductLastViewData 修改客户产品的总共阅读次数以及最近阅读时间
 func ModifyCompanyProductLastViewData(companyIdList []int) (err error) {
 	defer func() {
@@ -2036,18 +2077,39 @@ func ModifyCompanyProductLastViewData(companyIdList []int) (err error) {
 			//go utils.SendEmail("修改客户产品的总共阅读次数以及最近阅读时间失败", fmt.Sprint("companyIdList:", companyIdList, ";err:", err), utils.EmailSendToUsers)
 		}
 	}()
+
+	wxUserList, err := models.GetWxUserByCompanyIds(companyIdList)
+	if err != nil {
+		return
+	}
+	mobileList := make([]string, 0)
+	mobileCompanyIdMap := make(map[string]int, 0)
+	emailList := make([]string, 0)
+	emailCompanyIdMap := make(map[string]int, 0)
+
+	for _, v := range wxUserList {
+		if v.Mobile != `` {
+			mobileList = append(mobileList, v.Mobile)
+			mobileCompanyIdMap[v.Mobile] = v.CompanyId
+		}
+		if v.Email != `` {
+			emailList = append(emailList, v.Email)
+			emailCompanyIdMap[v.Email] = v.CompanyId
+		}
+	}
+
 	companyIdStr := ``
 	for _, companyId := range companyIdList {
 		companyIdStr += fmt.Sprint(companyId, ",")
 	}
 	companyIdStr = companyIdStr[:len(companyIdStr)-1]
 
-	companyFiccViewTotalMap, err := GetFiccCountUserViewHistoryByCompanyIds(companyIdStr)
+	companyFiccViewTotalMap, err := GetFiccCountUserViewHistoryByCompanyIds(companyIdStr, mobileList, emailList, mobileCompanyIdMap, emailCompanyIdMap)
 	if err != nil {
 		return
 	}
 
-	companyFiccLastViewMap, err := GetFiccLastUserViewHistoryByCompanyIds(companyIdStr)
+	companyFiccLastViewMap, err := GetFiccLastUserViewHistoryByCompanyIds(companyIdStr, mobileList, emailList, mobileCompanyIdMap, emailCompanyIdMap)
 	if err != nil {
 		return
 	}