Bladeren bron

定时任务每天更新用户的标签

xingzai 2 jaren geleden
bovenliggende
commit
b2cbe9b715
5 gewijzigde bestanden met toevoegingen van 369 en 183 verwijderingen
  1. 8 0
      models/user.go
  2. 158 0
      models/wx_user.go
  3. 3 0
      services/task.go
  4. 0 183
      services/user.go
  5. 200 0
      services/wx_user.go

+ 8 - 0
models/user.go

@@ -447,3 +447,11 @@ func UpdateUserHeadimgurl(headimgurl string, userId int) (err error) {
 	_, err = o.Raw(sql, headimgurl, userId).Exec()
 	return
 }
+
+//更新用户标签
+func UpdateUserLabel(userLabel string, userId int) (err error) {
+	o := orm.NewOrm()
+	sql := `UPDATE wx_user SET user_label = ? WHERE user_id=? `
+	_, err = o.Raw(sql, userLabel, userId).Exec()
+	return
+}

+ 158 - 0
models/wx_user.go

@@ -288,3 +288,161 @@ func GetUserByThirdName(companyId int, name string) (item *WxUser, err error) {
 	err = o.Raw(sql, companyId, name).QueryRow(&item)
 	return
 }
+
+//获取所有注册的权益用户
+func GetUserRegisterList() (items []*WxUser, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+			u.user_id,
+			u.mobile,
+			u.email,
+			u.real_name,
+			u.is_register,
+			u.is_maker,
+			u.register_time 
+		FROM
+			wx_user AS u
+			INNER JOIN company AS c ON c.company_id = u.company_id
+			INNER JOIN company_product AS cp ON cp.company_id = c.company_id 
+		WHERE
+			u.company_id IN (
+			SELECT
+				a.company_id 
+			FROM
+				company AS a
+				INNER JOIN company_product AS b ON a.company_id = b.company_id 
+			WHERE
+				a.enabled = 1 
+				AND b.STATUS IN ( '正式', '试用', '冻结' ) 
+				AND cp.product_id = 2 
+			) 
+			AND u.is_register = 1 
+			AND cp.product_id = 2 
+		GROUP BY
+			u.user_id`
+	_, err = o.Raw(sql).QueryRows(&items)
+	return
+}
+
+type CygxCompanyUser struct {
+	Labels string `description:"标签,用英文,隔开"`
+}
+type UserLabel struct {
+	Label string `description:"标签 多个用  , 隔开"`
+}
+
+//对获取关注的产业
+func GetCygxCompanyUserListSplit(userIds string) (labels string, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+			(
+			SELECT
+				GROUP_CONCAT( DISTINCT man.industry_name SEPARATOR ',' ) 
+			FROM
+				cygx_industrial_management AS man 
+			WHERE
+				man.industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industry_fllow AS f WHERE f.user_id = u.user_id  AND f.type = 1 ) 
+			) AS labels
+		FROM
+			wx_user AS u WHERE  u.user_id  = ? `
+	err = o.Raw(sql, userIds).QueryRow(&labels)
+	return
+}
+
+//阅读记录
+type ArticlePvCountResp struct {
+	ArticleId int `description:"文章ID"`
+	Pv        int `description:"Pv"`
+}
+
+func GetArticlePvCount(mobile, email, dateTime string) (item []*ArticlePvCountResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+			article_id,
+			COUNT(article_id) as pv
+		FROM
+			cygx_article_history_record_newpv as h 
+		WHERE
+			mobile = ? 
+			AND email = ?  
+			AND create_time >= ?
+			GROUP BY article_id `
+	_, err = o.Raw(sql, mobile, email, dateTime).QueryRows(&item)
+	return
+}
+
+//产业名称
+
+type ArticleIndustryNameResp struct {
+	ArticleId    int    `description:"文章ID"`
+	IndustryName string `description:"产业名称"`
+	SubjectName  string `description:"标的名称"`
+}
+
+func GetArticleGroupyIndustryName(articleIds string) (item []*ArticleIndustryNameResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+			art.article_id,
+			(
+			SELECT
+				GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR '/' ) 
+			FROM
+				cygx_industrial_subject AS s 
+			WHERE
+				s.industrial_subject_id IN ( SELECT industrial_subject_id FROM cygx_industrial_article_group_subject AS sg WHERE sg.article_id = art.article_id ) 
+			) AS subject_name,
+			(
+			SELECT
+				GROUP_CONCAT( DISTINCT man.industry_name SEPARATOR '/' ) 
+			FROM
+				cygx_industrial_management AS man 
+			WHERE
+				man.industrial_management_id IN ( SELECT industrial_management_id FROM cygx_industrial_article_group_management AS man_g WHERE man_g.article_id = art.article_id ) 
+			) AS industry_name 
+		FROM
+			cygx_article_history_record_newpv AS r
+			INNER JOIN cygx_article AS art ON art.article_id = r.article_id
+			LEFT JOIN cygx_report_mapping AS re ON re.category_id = art.category_id_two
+			LEFT JOIN cygx_industrial_article_group_management AS man ON man.article_id = art.article_id 
+		WHERE
+			art.article_id IN ( ` + articleIds + `) GROUP BY art.article_id `
+	_, err = o.Raw(sql).QueryRows(&item)
+	return
+}
+
+func GetCygxArticleCollectId(uid int, dateTime string) (articleIds string, err error) {
+	sql := `SELECT
+			GROUP_CONCAT( DISTINCT article_id SEPARATOR ',' ) AS permission 
+		FROM
+			cygx_article_collect 
+		WHERE
+			user_id = ? 
+			AND create_time >= ?  `
+	o := orm.NewOrm()
+	err = o.Raw(sql, uid, dateTime).QueryRow(&articleIds)
+	return
+}
+
+//活动标签记录
+type ActivityLabelCountResp struct {
+	Label string `description:"标签"`
+	Pv    int    `description:"Pv"`
+}
+
+func GetActivitySignCount(mobile, dateTime string) (item []*ActivityLabelCountResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+			label ,
+			COUNT( label ) AS pv 
+		FROM
+			cygx_activity 
+		WHERE
+			activity_id IN ( SELECT activity_id FROM cygx_activity_signup WHERE mobile = ? )
+			AND label != ''  
+			AND activity_time >= ? 
+			AND  is_submit_meeting = 1
+		GROUP BY
+			label`
+	_, err = o.Raw(sql, mobile, dateTime).QueryRows(&item)
+	return
+}

+ 3 - 0
services/task.go

@@ -68,6 +68,9 @@ func Task() {
 
 		sendEmailFileForAskMsg := task.NewTask("sendEmailFileForAskMsg", "0 */5 8-22 * * *", SendEmailFileForAskMsg) //非研选系列专家电话会,根据主持人姓名,会前15分钟将问题列表发送给至该主持人对应邮箱
 		task.AddTask("sendEmailFileForAskMsg", sendEmailFileForAskMsg)
+
+		updateWxUserLabel := task.NewTask("updateWxUserLabel", "0 50 3 * * *", UpdateWxUserLabel) //更新用户的标签
+		task.AddTask("updateWxUserLabel", updateWxUserLabel)
 	}
 	if utils.RunMode != "release" {
 		getArticleListByApi := task.NewTask("getArticleListByApi", "0 */60 * * * *", GetArticleListByApi) //通过三方接口获取策略平台上的文章

+ 0 - 183
services/user.go

@@ -407,189 +407,6 @@ func AddUserRecord(openId, unionId, nickName, realName, province, city, country,
 	return
 }
 
-//每天新增,删除的白名单(弃用)
-func SendEmailUserWhiteList(cont context.Context) (err error) {
-	var msg string
-	var fieldStr string
-	var condition string
-	//var touser string
-	defer func() {
-		if err != nil {
-			fmt.Println("err:", err)
-			go utils.SendEmail("发送附件模版消息失败"+"【"+utils.APPNAME+"】"+time.Now().Format("2006-01-02 15:04:05"), msg+";Err:"+err.Error(), utils.EmailSendToUsers)
-			utils.FileLog.Info("发送附件模版消息失败,Err:%s", err.Error())
-		}
-		if msg != "" {
-			fmt.Println(msg)
-			utils.FileLog.Info("发送模版消息失败,msg:%s", msg)
-		}
-	}()
-	fmt.Println("发送附件")
-	fieldStr = ` u.mobile,u.country_code,u.real_name,c.company_name,u.company_id,cp.seller_name,`
-	//condition = ` AND u.mobile = u.outbound_mobile AND cp.status IN ( '正式', '试用' ) AND u.mobile != '' AND  u.created_time > '2021-08-17 00:00:01'  AND  u.created_time < '2021-08-17 23:59:59'  `
-	condition = ` AND u.mobile = u.outbound_mobile AND cp.status IN ( '冻结' ) AND u.mobile != '' AND u.company_id IN (6965,6965,5461,6167,6167,5461) `
-	list1, err := models.GetFormalUserWhiteList(fieldStr, condition)
-	if err != nil {
-		msg = "获取失败,Err:" + err.Error()
-		return
-	}
-	fieldStr = ` u.outbound_mobile as mobile,u.outbound_country_code as country_code,u.real_name,c.company_name,u.company_id,`
-	//condition = ` AND u.mobile != u.outbound_mobile AND cp.status IN ( '正式', '试用' ) AND u.outbound_mobile != ''   AND  u.created_time > '2021-08-17 00:00:01'  AND  u.created_time < '2021-08-17 23:59:59' `
-	condition = ` AND u.mobile != u.outbound_mobile AND cp.status IN ( '冻结' ) AND u.outbound_mobile != '' AND u.company_id IN (6965,6965,5461,6167,6167,5461)  `
-	list2, err := models.GetFormalUserWhiteList(fieldStr, condition)
-	if err != nil {
-		msg = "获取失败,Err:" + err.Error()
-		return
-	}
-
-	//fieldStr = `u.mobile,u.country_code,u.real_name,c.company_name,u.company_id,`
-	//condition = ` AND u.mobile = u.outbound_mobile  AND cp.status IN ( '永续' ) AND u.mobile != '' `
-	//list3, err := models.GetSustainableUserWhiteList(fieldStr, condition)
-	//if err != nil {
-	//	msg = "获取失败,Err:" + err.Error()
-	//	return
-	//}
-	//fieldStr = ` u.outbound_mobile as mobile,u.outbound_country_code as country_code,u.real_name,c.company_name,u.company_id,`
-	//condition = ` AND u.mobile != u.outbound_mobile AND cp.status IN ( '永续') AND u.outbound_mobile != ''  `
-	//list4, err := models.GetSustainableUserWhiteList(fieldStr, condition)
-	//if err != nil {
-	//	msg = "获取失败,Err:" + err.Error()
-	//	return
-	//}
-	var rep models.UserWhiteListRep
-	for _, v := range list1 {
-		rep.List = append(rep.List, v)
-	}
-	for _, v := range list2 {
-		rep.List = append(rep.List, v)
-	}
-	//for _, v := range list3 {
-	//	rep.List = append(rep.List, v)
-	//}
-	//for _, v := range list4 {
-	//	rep.List = append(rep.List, v)
-	//}
-
-	//创建excel
-	dir, errFile := os.Executable()
-	exPath := filepath.Dir(dir)
-	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
-	xlsxFile := xlsx.NewFile()
-	if errFile != nil {
-		msg = "生成文件失败Err:" + errFile.Error()
-		return
-	}
-	style := xlsx.NewStyle()
-	alignment := xlsx.Alignment{
-		Horizontal: "center",
-		Vertical:   "center",
-		WrapText:   true,
-	}
-	style.Alignment = alignment
-	style.ApplyAlignment = true
-	sheet, err := xlsxFile.AddSheet("白名单")
-	if err != nil {
-		msg = "新增Sheet失败,Err:" + err.Error()
-		return
-	}
-	//标头
-	rowTitle := sheet.AddRow()
-	cellA := rowTitle.AddCell()
-	cellA.Value = "姓名"
-	cellB := rowTitle.AddCell()
-	cellB.Value = "手机号"
-	cellC := rowTitle.AddCell()
-	cellC.Value = "国际代码"
-	cellD := rowTitle.AddCell()
-	cellD.Value = "公司"
-	cellE := rowTitle.AddCell()
-	cellE.Value = "职位"
-	cellF := rowTitle.AddCell()
-	cellF.Value = "邮箱"
-	cellG := rowTitle.AddCell()
-	cellG.Value = "客户类型"
-	cellH := rowTitle.AddCell()
-	cellH.Value = "对口销售"
-	cellI := rowTitle.AddCell()
-	cellI.Value = "有效开始时间"
-	cellJ := rowTitle.AddCell()
-	cellJ.Value = "有效结束时间"
-	cellK := rowTitle.AddCell()
-	cellK.Value = "归属部门"
-	cellL := rowTitle.AddCell()
-	cellL.Value = "备注"
-	cellM := rowTitle.AddCell()
-	cellM.Value = "权限(消费,医药,智造,科技,策略)"
-	for _, item := range rep.List {
-		row := sheet.AddRow()
-		cellA := row.AddCell()
-		cellA.Value = item.RealName
-		cellB := row.AddCell()
-		cellB.Value = item.Mobile
-		cellC := row.AddCell()
-		cellC.Value = item.CountryCode
-		if len(item.Mobile) >= 11 && item.CountryCode == "" {
-			cellC.Value = "86"
-		}
-		cellD := row.AddCell()
-		cellD.Value = item.CompanyName
-		cellE := row.AddCell()
-		cellE.Value = ""
-		cellF := row.AddCell()
-		cellF.Value = ""
-		cellG := row.AddCell()
-		cellG.Value = ""
-		cellH := row.AddCell()
-		cellH.Value = item.SellerName
-		cellI := row.AddCell()
-		cellI.Value = ""
-		cellJ := row.AddCell()
-		cellJ.Value = ""
-		cellK := row.AddCell()
-		cellK.Value = ""
-		cellL := row.AddCell()
-		cellL.Value = ""
-		cellM := row.AddCell()
-		if item.Permission == "" {
-			item.Permission = "专家/医药/智造/消费/研选/科技/策略/路演服务"
-		}
-		cellM.Value = item.Permission
-	}
-	errFile = xlsxFile.Save(downLoadnFilePath)
-	if errFile != nil {
-		msg = "保存文件失败Err:" + errFile.Error()
-		return
-	}
-	title := "用户白名单"
-	content := "用户白名单"
-	fileName := downLoadnFilePath
-	//if activityInfo.ChartPermissionName == "科技" {
-	//	touser = utils.EmailTechnology
-	//} else if activityInfo.ChartPermissionName == "医药" {
-	//	touser = utils.EmailMedicine
-	//} else if activityInfo.ChartPermissionName == "消费" {
-	//	touser = utils.EmailConsumption
-	//} else if activityInfo.ChartPermissionName == "智造" {
-	//	touser = utils.EmailZhizao
-	//} else if activityInfo.ChartPermissionName == "策略" {
-	//	touser = utils.EmailStrategy
-	//}
-	//go utils.SendEmailHaveFile(title, content, fileName, "cxzhang@hzinsights.com;tshen@hzinsights.com")
-	go utils.SendEmailHaveFile(title, content, fileName, "cxzhang@hzinsights.com")
-	//go utils.SendEmailHaveFile(title, content, fileName, "tshen@hzinsights.com")
-	time.Sleep(time.Duration(10) * time.Second) //延迟两秒,避免过多活动的时候邮件发送没有内容
-	//errFile = models.UPdateActivityIdToSendFile(v.ActivityId)
-	//if errFile != nil {
-	//	msg = "获取失败,Err:" + errFile.Error()
-	//	return
-	//}
-	defer func() {
-		os.Remove(downLoadnFilePath)
-	}()
-	fmt.Println("发送附件完成", len(rep.List))
-	return
-}
-
 //每天新增,删除的白名单
 func SendEmailUserWhiteListChange(cont context.Context) (err error) {
 	var msg string

+ 200 - 0
services/wx_user.go

@@ -0,0 +1,200 @@
+package services
+
+import (
+	"context"
+	"fmt"
+	"hongze/hongze_cygx/models"
+	"hongze/hongze_cygx/utils"
+	"sort"
+	"strconv"
+	"strings"
+	"time"
+)
+
+func UpdateWxUserLabel(cont context.Context) (err error) {
+	defer func() {
+		if err != nil {
+			go utils.SendAlarmMsg("更新用户标签失败", 2)
+			go utils.SendEmail("更新用户标签失败"+"【"+utils.APPNAME+"】"+time.Now().Format(utils.FormatDateTime), ";Err:"+err.Error(), utils.EmailSendToUsers)
+			utils.FileLog.Info("更新用户标签失败,Err:%s", err.Error())
+		}
+	}()
+	listUser, err := models.GetUserRegisterList()
+	if err != nil {
+		fmt.Println("GetUserRegisterList Err", err)
+	}
+	for _, vUser := range listUser {
+		//fmt.Println(vUser.Mobile)
+		labels, err := models.GetCygxCompanyUserListSplit(strconv.Itoa(vUser.UserId))
+		if err != nil {
+			fmt.Println("GetCygxCompanyUserListSplit Err", err)
+			return err
+		}
+		mapLabels := make(map[string]string)
+		var labelsListStr []*models.UserLabel
+
+		mapActivityLabels := make(map[string]string)
+
+		labelsList := strings.Split(labels, ",")
+		for _, vL := range labelsList {
+			if mapLabels[vL] == "" && vL != "" {
+				mapLabels[vL] = vL
+				item := new(models.UserLabel)
+				item.Label = vL
+				labelsListStr = append(labelsListStr, item)
+			}
+		}
+
+		dateTime := time.Now().AddDate(0, -3, 0).Format(utils.FormatDate)
+		listArticlePv, err := models.GetArticlePvCount(vUser.Mobile, vUser.Email, dateTime)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			fmt.Println("GetArticlePvCount Err", err)
+			return err
+		}
+		var articleIds string
+		mapArticleIdLabelTotal := make(map[string]int)
+		mapArticleIdPv := make(map[int]int)
+		if len(listArticlePv) > 0 {
+			for _, v := range listArticlePv {
+				articleIds += strconv.Itoa(v.ArticleId) + ","
+				mapArticleIdPv[v.ArticleId] = v.Pv
+			}
+			articleIds = strings.TrimRight(articleIds, ",")
+			//产业、标的标签
+			listLabelName, err := models.GetArticleGroupyIndustryName(articleIds)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				fmt.Println("GetArticleGroupyIndustryName Err", err)
+				return err
+			}
+			if len(listLabelName) > 0 {
+				for _, v := range listLabelName {
+					labelsIndustryList := strings.Split(v.IndustryName, "/")
+					labelsSubjectList := strings.Split(v.SubjectName, "/")
+					//添加产业统计
+					if len(labelsIndustryList) > 0 {
+						for _, vIn := range labelsIndustryList {
+							if mapActivityLabels[vIn] != "" {
+								mapArticleIdLabelTotal[vIn] += mapArticleIdPv[v.ArticleId]
+							} else {
+								mapArticleIdLabelTotal[vIn] = mapArticleIdPv[v.ArticleId]
+								mapActivityLabels[vIn] = vIn
+							}
+						}
+					}
+					if len(labelsSubjectList) > 0 {
+						//添加标的统计
+						for _, vIn := range labelsSubjectList {
+							if mapActivityLabels[vIn] != "" {
+								mapArticleIdLabelTotal[vIn] += mapArticleIdPv[v.ArticleId]
+							} else {
+								mapArticleIdLabelTotal[vIn] = mapArticleIdPv[v.ArticleId]
+								mapActivityLabels[vIn] = vIn
+							}
+						}
+					}
+				}
+			}
+		}
+
+		articleIds, err = models.GetCygxArticleCollectId(vUser.UserId, dateTime)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			fmt.Println("GetCygxArticleCollectId Err", err)
+			return err
+		}
+		if articleIds != "" {
+			//产业、标的标签
+			listLabelName, err := models.GetArticleGroupyIndustryName(articleIds)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				fmt.Println("GetArticleGroupyIndustryName Err", err)
+				return err
+			}
+			if len(listLabelName) > 0 {
+				for _, v := range listLabelName {
+					labelsIndustryList := strings.Split(v.IndustryName, "/")
+					labelsSubjectList := strings.Split(v.SubjectName, "/")
+					//添加产业统计
+					if len(labelsIndustryList) > 0 {
+						for _, vIn := range labelsIndustryList {
+							if mapActivityLabels[vIn] != "" {
+								mapArticleIdLabelTotal[vIn] += 1
+							} else {
+								mapArticleIdLabelTotal[vIn] = 1
+								mapActivityLabels[vIn] = vIn
+							}
+						}
+					}
+					if len(labelsSubjectList) > 0 {
+						//添加标的统计
+						for _, vIn := range labelsSubjectList {
+							if mapActivityLabels[vIn] != "" {
+								mapArticleIdLabelTotal[vIn] += 1
+							} else {
+								mapArticleIdLabelTotal[vIn] = 1
+								mapActivityLabels[vIn] = vIn
+							}
+						}
+					}
+				}
+			}
+		}
+
+		//活动标签计算
+		listActivityPv, err := models.GetActivitySignCount(vUser.Mobile, dateTime)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			fmt.Println("GetActivitySignCount Err", err)
+			return err
+		}
+		if len(listActivityPv) > 0 {
+			for _, v := range listActivityPv {
+				labelsList := strings.Split(v.Label, "-")
+				for _, v2 := range labelsList {
+					labelsListSon := strings.Split(v2, "/")
+					for _, v3 := range labelsListSon {
+						if mapActivityLabels[v3] != "" {
+							mapArticleIdLabelTotal[v3] += 1
+						} else {
+							mapArticleIdLabelTotal[v3] = 1
+							mapActivityLabels[v3] = v3
+						}
+					}
+				}
+			}
+		}
+
+		//对标签数量进行排序
+		type KvPair struct {
+			Key string
+			Val int
+		}
+		tmpList := make([]KvPair, 0)
+		for k, v := range mapArticleIdLabelTotal {
+			tmpList = append(tmpList, KvPair{Key: k, Val: v})
+		}
+		sort.Slice(tmpList, func(i, j int) bool {
+			return tmpList[i].Val > tmpList[j].Val // 降序
+		})
+		for _, v := range tmpList {
+			if v.Key != "" {
+				mapLabels[v.Key] = v.Key
+				item := new(models.UserLabel)
+				item.Label = v.Key
+				labelsListStr = append(labelsListStr, item)
+			}
+		}
+
+		var labelNew string
+		for _, v := range labelsListStr {
+			labelNew += v.Label + ","
+		}
+		labelNew = strings.TrimRight(labelNew, ",")
+		if labelNew != "" {
+			err = models.UpdateUserLabel(labelNew, vUser.UserId)
+			if err != nil {
+				fmt.Println("UpdateUserLabel Err", err)
+				return err
+			}
+		}
+		//fmt.Println(labelNew)
+	}
+	return
+}