Bladeren bron

Merge branch 'master' of http://8.136.199.33:3000/hongze/hz_crm_api into cygx/cygx_12.8.1

xingzai 1 jaar geleden
bovenliggende
commit
1b95253fdf
72 gewijzigde bestanden met toevoegingen van 5501 en 1023 verwijderingen
  1. 223 1
      controllers/company_renewal.go
  2. 50 7
      controllers/company_share.go
  3. 63 0
      controllers/company_user.go
  4. 3 4
      controllers/cygx/activity.go
  5. 4 2
      controllers/cygx/activity_signup.go
  6. 3 3
      controllers/cygx/activity_special.go
  7. 4 0
      controllers/cygx/activity_special_trip.go
  8. 19 0
      controllers/cygx/apply_record.go
  9. 1 0
      controllers/cygx/minutes_summary.go
  10. 1 0
      controllers/cygx/product_interior.go
  11. 21 2
      controllers/cygx/report_article.go
  12. 1 1
      controllers/cygx/research_summary.go
  13. 22 3
      controllers/cygx/tag_management.go
  14. 533 305
      controllers/cygx/user.go
  15. 494 29
      controllers/cygx/yanxuan_special.go
  16. 570 115
      controllers/statistic_company_merge.go
  17. 210 48
      controllers/statistic_report.go
  18. 12 9
      controllers/sys_menu.go
  19. 2 0
      models/company/company.go
  20. 43 0
      models/company/company_contract.go
  21. 17 91
      models/company/company_contract_merge.go
  22. 151 0
      models/company/company_contract_no_renewed_ascribe.go
  23. 1 1
      models/company/company_no_renewed_ascribe.go
  24. 64 0
      models/company/company_product.go
  25. 69 0
      models/company/company_renewal_record.go
  26. 4 1
      models/company/company_user.go
  27. 7 0
      models/company_user/request/follow.go
  28. 63 0
      models/contract/contract.go
  29. 1 0
      models/cygx/activity_meet.go
  30. 1 0
      models/cygx/activity_special.go
  31. 19 18
      models/cygx/activity_special_trip_bill.go
  32. 1 0
      models/cygx/apply_record.go
  33. 78 0
      models/cygx/article_and_yanxuan_record.go
  34. 46 15
      models/cygx/chart.go
  35. 7 0
      models/cygx/config.go
  36. 13 13
      models/cygx/cygx_tag.go
  37. 82 63
      models/cygx/cygx_user.go
  38. 393 37
      models/cygx/cygx_user_company.go
  39. 95 31
      models/cygx/cygx_yanxuan_special.go
  40. 86 0
      models/cygx/cygx_yanxuan_special_approval_log.go
  41. 63 0
      models/cygx/cygx_yanxuan_special_collect.go
  42. 35 0
      models/cygx/cygx_yanxuan_special_follow.go
  43. 69 21
      models/cygx/cygx_yanxuan_special_user.go
  44. 17 0
      models/cygx/industrial_article_group_management.go
  45. 22 0
      models/cygx/industrial_article_group_subject.go
  46. 3 0
      models/cygx/report_article.go
  47. 8 0
      models/cygx/report_mapping_cygx.go
  48. 7 1
      models/cygx/resource_data.go
  49. 119 20
      models/cygx/tag_history.go
  50. 4 0
      models/db.go
  51. 1 0
      models/response/statistic_report.go
  52. 130 31
      models/statistic_report.go
  53. 14 0
      models/wx_user.go
  54. 90 0
      routers/commentsRouter.go
  55. 80 3
      services/company_apply/company_approval.go
  56. 31 0
      services/company_ascribe.go
  57. 16 11
      services/cygx/acitvity.go
  58. 91 0
      services/cygx/activity_meet.go
  59. 2 0
      services/cygx/activity_ocr.go
  60. 1 1
      services/cygx/activity_permission.go
  61. 37 37
      services/cygx/activity_special.go
  62. 23 0
      services/cygx/admin_power.go
  63. 211 0
      services/cygx/article.go
  64. 184 2
      services/cygx/contract_allocation.go
  65. 86 0
      services/cygx/cygx_yanxuan_special.go
  66. 302 61
      services/cygx/resource_data.go
  67. 45 1
      services/elastic/es_comprehensive.go
  68. 91 24
      services/statistic_report/renew_company.go
  69. 46 10
      services/statistic_report/reponse.go
  70. 165 0
      services/statistic_report/unusual_renew_company.go
  71. 18 0
      utils/common.go
  72. 13 1
      utils/constants.go

+ 223 - 1
controllers/company_renewal.go

@@ -2,6 +2,7 @@ package controllers
 
 import (
 	"encoding/json"
+	"fmt"
 	"hongze/hz_crm_api/models"
 	"hongze/hz_crm_api/models/company"
 	"hongze/hz_crm_api/utils"
@@ -349,7 +350,7 @@ func (this *CompanyRenewalController) CompanyNoRenewedAscribeAddDetail() {
 		return
 	}
 	resp := new(company.CompanyNoRenewedAscribeDetailResp)
-	detail, err := company.GetCygxProductInteriorDetail(companyId, productId)
+	detail, err := company.GetCompanyNoRenewedAscribeDetail(companyId, productId)
 	if err != nil {
 		br.Msg = "获取失败"
 		br.ErrMsg = "获取失败,Err:" + err.Error()
@@ -361,3 +362,224 @@ func (this *CompanyRenewalController) CompanyNoRenewedAscribeAddDetail() {
 	br.Msg = "获取成功"
 	br.Data = resp
 }
+
+// @Title 合同通过归因添加确认不续约
+// @Description 合同通过归因添加确认不续约接口
+// @Param	request	body company.CompanyNoRenewedNoteReq true "type json string"
+// @Success 200 {object} "保存成功"
+// @router /company_contract_no_renewed_ascribe/add [post]
+func (this *CompanyRenewalController) CompanyContractNoRenewedAscribeAdd() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	//内容仅权益管理员账号可以修改
+	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_RAI_ADMIN {
+		br.Msg = "仅管理员可修改!"
+		return
+	}
+	var req company.CompanyContractNoRenewedAscribeReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常!"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	content := req.Content
+	companyAscribeId := req.CompanyAscribeId
+	companyContractId := req.CompanyContractId
+
+	if content == "" {
+		br.Msg = "内容不能为空!"
+		return
+	}
+
+	contractInfo, err := company.GetCompanyContractDetailByCompanyContractId(companyContractId)
+	if err != nil {
+		br.Msg = "获取合同失败"
+		br.ErrMsg = "获取合同失败,Err:" + err.Error()
+		return
+	}
+	companyId := contractInfo.CompanyId //公司ID
+	productId := contractInfo.ProductId //权益还是FICC
+
+	detail, err := company.GetCompanyAscribeDetail(companyAscribeId)
+	if err != nil {
+		br.Msg = "新建失败"
+		br.ErrMsg = "新建失败,GetCompanyAscribeDetail Err:" + err.Error()
+		return
+	}
+	var condition string
+	var pars []interface{}
+	condition += ` AND  company_id  = ?  AND product_id = ? AND company_contract_id = ?  `
+	pars = append(pars, companyId, productId, companyContractId)
+
+	total, err := company.GetCompanyContractNoRenewedAscribeCount(condition, pars)
+	if err != nil {
+		br.Msg = "新建失败"
+		br.ErrMsg = "新建失败,GetCompanyContractNoRenewedAscribeCount Err:" + err.Error()
+		return
+	}
+	item := new(company.CompanyContractNoRenewedAscribe)
+	item.CompanyAscribeId = companyAscribeId
+	item.AscribeContent = detail.AscribeContent
+	item.Content = content
+	item.ProductId = productId
+	item.CompanyId = companyId
+	item.CompanyContractId = companyContractId
+	item.AdminId = sysUser.AdminId
+	item.CreateTime = time.Now()
+	item.ModifyTime = time.Now()
+
+	itemLog := new(company.CompanyContractNoRenewedAscribeLog)
+	itemLog.CompanyAscribeId = companyAscribeId
+	itemLog.AscribeContent = detail.AscribeContent
+	itemLog.Content = content
+	itemLog.ProductId = productId
+	itemLog.CompanyId = companyId
+	itemLog.CompanyContractId = companyContractId
+	itemLog.AdminId = sysUser.AdminId
+	itemLog.CreateTime = time.Now()
+	itemLog.ModifyTime = time.Now()
+	if total == 0 {
+		err = company.AddCompanyContractNoRenewedAscribe(item, itemLog)
+	} else {
+		err = company.UpdateCompanyContractNoRenewedAscribe(item, itemLog)
+	}
+	if err != nil {
+		br.Msg = "新建失败"
+		br.ErrMsg = "新建失败,Err:" + err.Error()
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "新建成功"
+}
+
+// @Title 合同确认归因不续约详情接口
+// @Description 合同确认归因不续约详情接口
+// @Param   CompanyContractId   query   int  true       "合同ID"
+// @Success 200 {object} company.CompanyAscribeListResp
+// @router /company_contract_no_renewed_ascribe/detail [get]
+func (this *CompanyRenewalController) CompanyContractNoRenewedAscribeAddDetail() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		return
+	}
+	companyContractId, _ := this.GetInt("CompanyContractId")
+	if companyContractId < 1 {
+		br.Msg = "合同ID错误!"
+		return
+	}
+
+	resp := new(company.CompanyContractNoRenewedAscribeDetailResp)
+	detail, err := company.GetCompanyContractNoRenewedAscribeDetail(companyContractId)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	resp.Detail = detail
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+func init12123() {
+	var condition string
+	var pars []interface{}
+	list, e := company.GetCompanyNoRenewedAscribeList(condition, pars, 0, 0)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		fmt.Println(e)
+		return
+	}
+
+	for _, v := range list {
+		pars = make([]interface{}, 0)
+		condition = " AND  company_id = ? "
+		pars = append(pars, v.CompanyId)
+
+		companyContractList, e := company.GetCompanyContractList(condition, pars)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			fmt.Println(e)
+			return
+		}
+		for _, vC := range companyContractList {
+			item := new(company.CompanyContractNoRenewedAscribe)
+			item.CompanyAscribeId = v.CompanyAscribeId
+			item.AscribeContent = v.AscribeContent
+			item.Content = v.Content
+			item.ProductId = v.ProductId
+			item.CompanyId = v.CompanyId
+			item.CompanyContractId = vC.CompanyContractId
+			item.AdminId = v.AdminId
+			item.CreateTime = utils.StrTimeToTime(v.CreateTime)
+			item.ModifyTime = utils.StrTimeToTime(v.CreateTime)
+
+			itemLog := new(company.CompanyContractNoRenewedAscribeLog)
+			itemLog.CompanyAscribeId = v.CompanyAscribeId
+			itemLog.AscribeContent = v.AscribeContent
+			itemLog.Content = v.Content
+			itemLog.ProductId = v.ProductId
+			itemLog.CompanyId = v.CompanyId
+			itemLog.CompanyContractId = vC.CompanyContractId
+			itemLog.AdminId = v.AdminId
+			itemLog.CreateTime = utils.StrTimeToTime(v.CreateTime)
+			itemLog.ModifyTime = utils.StrTimeToTime(v.CreateTime)
+
+			err := company.AddCompanyContractNoRenewedAscribe(item, itemLog)
+			fmt.Println(err)
+		}
+	}
+	return
+}
+
+func init879() {
+
+	companyContractList, e := models.GetIncrementalCompanyListByOperationRecordMerge879()
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		fmt.Println(e)
+		return
+	}
+	fmt.Println(len(companyContractList))
+	//return
+	for _, v := range companyContractList {
+		item := new(company.CompanyContractNoRenewedAscribe)
+		item.CompanyContractId = v.CompanyContractId
+		item.ProductId = v.ProductId
+		item.CompanyId = v.CompanyId
+		item.CreateTime = time.Now()
+		item.ModifyTime = time.Now()
+
+		itemLog := new(company.CompanyContractNoRenewedAscribeLog)
+		itemLog.AscribeContent = v.AscribeContent
+		itemLog.Content = v.Content
+		itemLog.ProductId = v.ProductId
+		itemLog.CompanyId = v.CompanyId
+		itemLog.CompanyContractId = v.CompanyContractId
+		itemLog.CreateTime = time.Now()
+		itemLog.ModifyTime = time.Now()
+
+		err := company.AddCompanyContractNoRenewedAscribe(item, itemLog)
+		fmt.Println(err)
+	}
+
+	return
+}

+ 50 - 7
controllers/company_share.go

@@ -88,11 +88,13 @@ func (this *CompanyController) CompanyShare() {
 	br.Msg = "设置成功"
 }
 
+// CompanyShareList
 // @Title 共享客户列表
 // @Description 共享客户列表接口
 // @Param   SellerId   query   string  false       "选择的销售id"
+// @Param   OriginalSellerId   query   string  false       "选择的原销售id"
 // @Param   Keyword   query   string  true       "搜索关键词"
-// @Param   ListParam   query   int  false       "筛选字段参数,用来筛选的字段, 枚举值:0:全部 、 1:已分配 、 2:未分配  "
+// @Param   ListParam   query   int  false       "筛选字段参数,用来筛选的字段, 枚举值:0:全部 、 1:已分配 、 2:未分配 、 3:未共享 "
 // @Param   SortParam   query   string  false       "排序字段参数,用来排序的字段, 枚举值:'viewTotal':总阅读次数 、 'viewTime':阅读时间 、 'roadShowTotal':累计路演次数 、`expireDay:到期时间` 、 `createTime:创建时间` 、 'formalTime': 转正时间 、 'freezeTime':冻结时间 、'lossTime':流失时间  、'tryOutDay':试用天数"
 // @Param   SortType   query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
 // @Param   PageSize   query   int  true       "每页数据条数"
@@ -116,6 +118,7 @@ func (this *CompanyController) CompanyShareList() {
 	pageSize, _ := this.GetInt("PageSize")
 	currentIndex, _ := this.GetInt("CurrentIndex")
 	sellerIds := this.GetString("SellerId")
+	originalSellerIds := this.GetString("OriginalSellerId")
 	keyword := this.GetString("Keyword")
 	//排序参数
 	sortParam := this.GetString("SortParam")
@@ -150,6 +153,14 @@ func (this *CompanyController) CompanyShareList() {
 		}
 	}
 
+	// 咨询组的分组id
+	groupId := 0
+	if utils.RunMode == "release" {
+		groupId = 37
+	} else {
+		groupId = 61
+	}
+
 	roleTypeCode := sysUser.RoleTypeCode
 	productId := services.GetProductId(roleTypeCode)
 	//权限控制
@@ -165,23 +176,47 @@ func (this *CompanyController) CompanyShareList() {
 				pars = append(pars, productId)
 			}
 			if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN && sysUser.AdminId != 66 && sysUser.AdminId != 15 {
-				condition += ` AND a.share_seller_id=? `
+				if sysUser.GroupId == groupId {
+					condition += ` AND a.share_seller_id=? `
+					pars = append(pars, sysUser.AdminId)
+				} else {
+					condition += ` AND b.seller_id=? `
+					pars = append(pars, sysUser.AdminId)
+				}
+			}
+		}
+	}
+
+	if listParam == 0 {
+		if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_TEAM {
+			//非咨询组销售,那么默认查看“未共享”的客户
+			if sysUser.GroupId != groupId {
+				listParam = 3
+				condition += ` AND b.seller_id = ? `
 				pars = append(pars, sysUser.AdminId)
+			} else {
+				condition += ` AND a.is_share=1 `
 			}
+		} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
+			// 管理员,默认查看“待分配”客户
+			listParam = 2
 		}
 	}
 
 	if listParam == 1 {
-		condition += ` AND a.share_seller <> '' AND a.is_share=1 `
+		condition += ` AND a.share_seller_id > 0 AND a.is_share=1 `
 	} else if listParam == 2 {
-		condition += ` AND a.share_seller = '' AND a.is_share=1 `
-	} else {
-		condition += ` AND a.is_share=1 `
+		condition += ` AND a.share_seller_id = 0 AND a.is_share=1 `
+	} else if listParam == 3 { // 未共享
+		condition += ` AND a.is_share=0 and b.status="正式"`
 	}
 
 	if sellerIds != "" {
 		condition += ` AND a.share_seller_id IN (` + sellerIds + `) `
 	}
+	if originalSellerIds != "" {
+		condition += ` AND b.seller_id IN (` + originalSellerIds + `) `
+	}
 
 	total, err := company.GetShareCompanyListCount(condition, pars)
 	if err != nil {
@@ -561,9 +596,17 @@ func (this *CompanyController) CompanyShareList() {
 	if companyLists == nil {
 		companyLists = make([]*company.CompanyListItem, 0)
 	}
+
+	var isShareGroup bool
+	if sysUser.GroupId == groupId {
+		isShareGroup = true
+	}
+
 	page = paging.GetPaging(currentIndex, pageSize, total)
 	resp := new(company.CompanyListResp)
 	resp.List = companyLists
+	resp.IsShareGroup = isShareGroup
+	resp.Status = listParam
 	resp.Paging = page
 	br.Ret = 200
 	br.Success = true
@@ -1008,4 +1051,4 @@ func (this *CompanyController) CompanyShareListByCity() {
 	br.Msg = "获取成功"
 	br.Data = resp
 
-}
+}

+ 63 - 0
controllers/company_user.go

@@ -1210,6 +1210,10 @@ func (this *CompanyUserController) List() {
 				list[i].LastViewTimeStr = tmpLastViewTime.Format(utils.FormatDateTime)
 			}
 
+			if list[i].LastViewTime.Before(time.Now().AddDate(0,0,-7)) && list[i].IsFollow  == 1 {
+				list[i].NotRead = true
+			}
+
 			//如果有绑定数据,那么将数据返回对应的注册绑定数据
 			if _, ok := userRecordRegisterMap[int(item.UserId)]; ok {
 				list[i].IsRegister = true
@@ -5927,3 +5931,62 @@ func (this *CompanyUserController) ImportListMatchDownload() {
 	br.Ret = 200
 	br.Success = true
 }
+
+// Follow
+// @Title 关注联系人
+// @Description 关注联系人
+// @Param	request	body request.ApplyMarkReq true "type json string"
+// @Success 200 {object} 标记处理成功
+// @router /follow [post]
+func (this *CompanyUserController) Follow() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		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 request.FollowReq
+	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
+	if err != nil {
+		br.Msg = "参数解析异常"
+		br.ErrMsg = "参数解析失败,Err:" + err.Error()
+		return
+	}
+	if req.UserId <= 0  {
+		br.Msg = "用户ID异常"
+		br.ErrMsg = "用户ID异常"
+		return
+	}
+
+	// 查公司里有多少已关注,上限三个
+	count, err := models.GetCompanyFollowCount(req.CompanyId)
+	if err != nil {
+		br.Msg = "操作失败! "
+		br.ErrMsg = "操作失败,Err:" + err.Error()
+		return
+	}
+	if count == 3 && req.Type == 1 {
+		br.Msg = "关注失败,特别关注已达上限(上限三个)"
+		br.ErrMsg = "关注失败,特别关注已达上限(上限三个)"
+		return
+	}
+
+	// 关注或取关
+	err = models.SetUserFollow(req.UserId, req.Type)
+	if err != nil {
+		br.Msg = "操作失败! "
+		br.ErrMsg = "操作失败,Err:" + err.Error()
+		return
+	}
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "操作成功"
+}

+ 3 - 4
controllers/cygx/activity.go

@@ -819,10 +819,9 @@ func (this *ActivityCoAntroller) PreserveAndPublish() {
 		if req.DoType == 1 {
 			go cygxService.DoActivityOnenIdWxTemplateMsg(req.ActivityId)
 			//go cygxService.UpdateResourceData(req.ActivityId, "activity", "add", time.Now().Format(utils.FormatDateTime))
-			cygxService.UpdateActivityResourceData(req.ActivityId)                                             //写入首页最新  cygx_resource_data 表
 			go cygxService.YanXuanActivityPointsBillActivityPublishAndCancel(activityId, AdminUser.AdminId, 1) //活动发布以及取消发布处理研选扣点
 		}
-
+		cygxService.UpdateActivityResourceData(req.ActivityId) //写入首页最新  cygx_resource_data 表
 		//如果二次编辑的时候,取消了易董办会选项,那么就对易董发送取消发布到广场的通知
 		if req.IsYidongConduct == 0 {
 			go cygxService.YiDongUpdateActivityStatus(activityId)
@@ -947,8 +946,8 @@ func (this *ActivityCoAntroller) ActivityList() {
 		condition += ` AND (art.label LIKE '%` + activityLabel + `%' )  `
 	}
 
-	//C类电话会,仅本组销售、部门管理员、admin、权益研究员账号能看到。
-	if sysUser.Role != "admin" {
+	//本组可见的活动对,非产品技术部 做权限限制
+	if sysUser.DepartmentId != 3 {
 		conditionPermission, err := cygxService.GetAdminActivityPermission(sysUser, condition)
 		if err != nil {
 			br.Msg = "获取失败"

+ 4 - 2
controllers/cygx/activity_signup.go

@@ -124,8 +124,8 @@ func (this *ActivitySignupCoAntroller) SignupList() {
 	} else if publishStatus == 3 {
 		condition += ` AND art.publish_status = 0 AND  art.is_cancel = 1 `
 	}
-	//C类电话会,仅本组销售、部门管理员、admin、权益研究员账号能看到。
-	if sysUser.Role != "admin" {
+	//本组可见的活动对,非产品技术部 做权限限制
+	if sysUser.DepartmentId != 3 {
 		conditionPermission, err := cygxService.GetAdminActivityPermission(sysUser, condition)
 		if err != nil {
 			br.Msg = "获取失败"
@@ -2061,6 +2061,8 @@ func (this *ActivitySignupCoAntroller) AddSignuUser() {
 		for _, v := range items {
 			go cygxService.YanXuanActivityPointsBillSignupAdd(v.ActivityId, v.UserId, adminInfo.AdminId)
 		}
+
+		go cygxService.AddctivitySignupDetailListByAdminSignup(req.ActivityIds) //已结束的活动,管理员手动添加报名,把信息写入到联系人列表参会信息中
 	}
 	//添加操作日志记录
 	br.IsAddLog = true

+ 3 - 3
controllers/cygx/activity_special.go

@@ -276,9 +276,9 @@ func (this *ActivitySpecialCoAntroller) PreserveAndPublish() {
 	if req.DoType == 1 {
 		go services.SendWxMsgWithCygxActivitySpecial(activityId)
 		//go cygxService.UpdateResourceData(activityId, "activityspecial", "add", time.Now().Format(utils.FormatDateTime))
-		go cygxService.UpdateActivitySpecialResourceData(activityId) //写入首页最新  cygx_resource_data 表
 	}
-	go elastic.AddComprehensiveActivitySpecial(activityId) // Es添加活动
+	go cygxService.UpdateActivitySpecialResourceData(activityId) //写入首页最新  cygx_resource_data 表
+	go elastic.AddComprehensiveActivitySpecial(activityId)       // Es添加活动
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "操作成功"
@@ -523,7 +523,7 @@ func (this *ActivitySpecialCoAntroller) PublishAndCancel() {
 	} else {
 		item.PublishStatus = 0
 		// 取消专项调研返点
-		go cygxService.ActivitySpecialPublishAndCancel(activityInfo)
+		//go cygxService.ActivitySpecialPublishAndCancel(activityInfo)
 	}
 	updateParams["PublishStatus"] = item.PublishStatus
 	item.ActivityId = req.ActivityId

+ 4 - 0
controllers/cygx/activity_special_trip.go

@@ -149,6 +149,7 @@ func (this *ActivitySpecialTripCoAntroller) AddUser() {
 				itemBill.BillDetailed = -1 // 流水减一
 				itemBill.RegisterPlatform = 1
 				itemBill.ChartPermissionId = activityInfo.ChartPermissionId
+				itemBill.ChartPermissionName = activityInfo.ChartPermissionName
 				itemBill.AdminId = AdminUser.AdminId
 
 				if totalAll == 0 {
@@ -532,6 +533,7 @@ func (this *ActivitySpecialTripCoAntroller) TripCancel() {
 	itemBill.BillDetailed = 1 // 流水加一
 	itemBill.RegisterPlatform = 1
 	itemBill.ChartPermissionId = activityInfo.ChartPermissionId
+	itemBill.ChartPermissionName = activityInfo.ChartPermissionName
 	itemBill.AdminId = sysUser.AdminId
 	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
 	//48小时之内的取消也扣除一次参会记录
@@ -790,6 +792,7 @@ func (this *ActivitySpecialTripCoAntroller) MeetingDo() {
 				itemBill.BillDetailed = 1 // 流水加一
 				itemBill.RegisterPlatform = 1
 				itemBill.ChartPermissionId = activityInfo.ChartPermissionId
+				itemBill.ChartPermissionName = activityInfo.ChartPermissionName
 				itemBill.AdminId = AdminUser.AdminId
 				itemBill.Way = 2
 				userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(v.CompanyId)
@@ -847,6 +850,7 @@ func (this *ActivitySpecialTripCoAntroller) MeetingDo() {
 			itemBill.BillDetailed = -1 // 流水减一
 			itemBill.RegisterPlatform = 1
 			itemBill.ChartPermissionId = activityInfo.ChartPermissionId
+			itemBill.ChartPermissionName = activityInfo.ChartPermissionName
 			itemBill.AdminId = AdminUser.AdminId
 			itemBill.Way = 2
 			userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(v.CompanyId)

+ 19 - 0
controllers/cygx/apply_record.go

@@ -97,11 +97,13 @@ func (this *ApplyRecordController) ListSysRole() {
 	}
 	var sellerCompanyIds []int
 	var microvideoIds []int
+	var userIds []int
 	for _, v := range list {
 		if v.Source == "roadshow" {
 			microvideoIds = append(microvideoIds, v.SourceId)
 		}
 		sellerCompanyIds = append(sellerCompanyIds, v.CompanyIdPay)
+		userIds = append(userIds, v.UserId)
 	}
 	sellNameMap := services.GetSellNameMapByCompanyIds(sellerCompanyIds)
 	lenmicrovideoIds := len(microvideoIds)
@@ -124,7 +126,24 @@ func (this *ApplyRecordController) ListSysRole() {
 		}
 	}
 
+	//处理用户的邮箱
+	mapUserEmail := make(map[int]string) //用户UserId所对应的邮箱
+	lenUserId := len(userIds)
+	if lenUserId > 0 {
+		userList, err := models.GetWxUserByUserIds(userIds)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取数据失败,Err:" + err.Error()
+			return
+		}
+
+		for _, v := range userList {
+			mapUserEmail[int(v.UserId)] = v.Email
+		}
+	}
+
 	for i, v := range list {
+		v.Email = mapUserEmail[v.UserId]
 		if list[i].SellerName == "/" {
 			list[i].SellerName = ""
 		}

+ 1 - 0
controllers/cygx/minutes_summary.go

@@ -275,6 +275,7 @@ func (this *MinutesSummaryController) PreserveAndPublish() {
 		}
 	}
 	go services.CreateVideoWhithContent(articleId, req.Title, contentVideo, "cygx_minutes_summary")
+	go cygxService.UpdateMinutesSummaryResourceData(articleId) //写入首页最新  cygx_resource_data 表
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "操作成功"

+ 1 - 0
controllers/cygx/product_interior.go

@@ -133,6 +133,7 @@ func (this *ProductInteriorController) PreserveAndPublish() {
 		br.ErrMsg = "保存失败,Err:" + err.Error()
 		return
 	}
+	go cygxService.UpdateProductInteriorResourceData(productInteriorId) //写入首页最新  cygx_resource_data 表
 	br.Ret = 200
 	br.Success = true
 	br.IsAddLog = true

+ 21 - 2
controllers/cygx/report_article.go

@@ -196,8 +196,27 @@ func (this *ReportArticleController) ReportArticleList() {
 		condition += ` AND art.publish_date <= ` + "'" + endDate + " 23:59:59'"
 	}
 	//报告匹配类型
-	if matchTypeName != "" {
-		condition += ` AND re.match_type_name  =  ` + "'" + matchTypeName + "' "
+	if matchTypeName != "" && chartPermissionId > 0 {
+		//condition += ` AND re.match_type_name  =  ` + "'" + matchTypeName + "' "
+		mappingCygxDetai, err := cygx.GetCygxReportMappingCygxDetailByNameAndChartPermissionId(matchTypeName, chartPermissionId)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+		if mappingCygxDetai == nil {
+			resp := new(cygx.GetReportArticleListRep)
+			resp.List = make([]*cygx.CygxReportArticle, 0)
+			page := paging.GetPaging(currentIndex, pageSize, 0)
+			resp.Paging = page
+			br.Ret = 200
+			br.Success = true
+			br.Msg = "获取成功"
+			br.Data = resp
+			return
+		}
+		//这里量不大,走一下子查询
+		condition += ` 	AND art.category_id IN ( SELECT category_id_celue FROM cygx_report_mapping_group WHERE id_cygx = ` + strconv.Itoa(mappingCygxDetai.Id) + ` )  `
 	}
 	// 报告标签
 	if reportLabel != "" {

+ 1 - 1
controllers/cygx/research_summary.go

@@ -353,7 +353,7 @@ func (this *ResearchSummaryController) PreserveAndPublish() {
 		}
 	}
 	go services.CreateVideoWhithContent(articleId, req.Title, contentVideo, "cygx_research_summary")
-
+	go cygxService.UpdateResearchSummaryResourceData(articleId) //写入首页最新  cygx_resource_data 表
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "操作成功"

+ 22 - 3
controllers/cygx/tag_management.go

@@ -27,6 +27,8 @@ type TagManagementController struct {
 // @Param   CurrentIndex   query   int  true       "当前页码"
 // @Param   PageSize   query   int  true       "每页数据数"
 // @Param   Status   query   string  false       "发布状态,1,上线,0下线"
+// @Param   SortParam   query   string  false       "排序字段参数,用来排序的字段, 枚举值: 'pv':总Pv/Uv "
+// @Param   SortType   query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
 // @Success 200 {object} cygx.ChartPermissionResp
 // @router /tag/list [get]
 func (this *TagManagementController) TagList() {
@@ -46,6 +48,9 @@ func (this *TagManagementController) TagList() {
 	pageSize, _ := this.GetInt("PageSize")
 	currentIndex, _ := this.GetInt("CurrentIndex")
 	status, _ := this.GetInt("Status", 1)
+	//排序参数
+	sortParam := this.GetString("SortParam")
+	sortType := this.GetString("SortType")
 
 	var condition string
 	var startSize int
@@ -58,9 +63,9 @@ func (this *TagManagementController) TagList() {
 	startSize = utils.StartIndex(currentIndex, pageSize)
 
 	if status == 1 {
-		condition += ` AND status=1 ORDER BY online_time DESC  `
+		condition += ` AND status=1 `
 	} else {
-		condition += ` AND status=0 ORDER BY online_time DESC  `
+		condition += ` AND status=0  `
 	}
 
 	total, err := cygx.GetCygxTagListCount(condition)
@@ -71,6 +76,20 @@ func (this *TagManagementController) TagList() {
 	}
 	page := paging.GetPaging(currentIndex, pageSize, total)
 
+	//排序字段以及排序方式处理
+	var sortStr string
+	if sortParam != "" && sortType != "" {
+		if sortParam == "pv" {
+			if sortType == "asc" {
+				sortStr = " ORDER BY pv ASC,  online_time DESC "
+			} else {
+				sortStr = " ORDER BY pv  DESC,  online_time DESC "
+			}
+		}
+	} else {
+		sortStr = "  ORDER BY online_time DESC "
+	}
+	condition += sortStr
 	list, err := cygx.GetCygxTagListPage(condition, startSize, pageSize)
 	if err != nil {
 		br.Msg = "获取标签失败"
@@ -433,7 +452,7 @@ func (this *TagManagementController) PvExport() {
 	}
 	var condition string
 	var pars []interface{}
-	condition = ` AND tag_id = ? `
+	condition = ` AND tag_id = ? AND  company_id != 16  `
 	pars = append(pars, tagId)
 	var respList []*cygx.CygxTagHistory
 	//respList := new(cygx.CygxTacticsTimeLineHistory)

File diff suppressed because it is too large
+ 533 - 305
controllers/cygx/user.go


+ 494 - 29
controllers/cygx/yanxuan_special.go

@@ -2,13 +2,18 @@ package cygx
 
 import (
 	"encoding/json"
+	"github.com/rdlucklib/rdluck_tools/paging"
+	"github.com/tealeg/xlsx"
 	"hongze/hz_crm_api/controllers"
 	"hongze/hz_crm_api/models"
 	"hongze/hz_crm_api/models/cygx"
 	cygxService "hongze/hz_crm_api/services/cygx"
 	"hongze/hz_crm_api/services/elastic"
 	"hongze/hz_crm_api/utils"
+	"os"
+	"path/filepath"
 	"strconv"
+	"strings"
 	"time"
 )
 
@@ -145,6 +150,12 @@ func (this *YanxuanSpecialController) AuthorEnable() {
 // @Title 作者列表
 // @Description 作者列表
 // @Param	request	body help_doc.AddHelpDocReq true "type json string"
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   Status   query   string  true       "状态: 1:启用 、 2:禁用 。传其他默认所有"
+// @Param   KeyWord   query   string  false       "搜索关键词"
+// @Param   SortParam   query   string  false       "排序字段参数,用来排序的字段, 枚举值:'CreatTime':开通时间 、 'articleNum':已发布文章 、 'pv':总Pv/Uv "
+// @Param   SortType   query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
 // @Success 200 {object} models.AddEnglishReportResp
 // @router /yanxuan_special/author/list [get]
 func (this *YanxuanSpecialController) AuthorList() {
@@ -161,39 +172,116 @@ func (this *YanxuanSpecialController) AuthorList() {
 		return
 	}
 
-	list, tmpErr := cygx.GetYanxuanSpecialAuthorList()
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+	status, _ := this.GetInt("Status")
+	keyWord := this.GetString("KeyWord")
+	//排序参数
+	sortParam := this.GetString("SortParam")
+	sortType := this.GetString("SortType")
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
+	var condition string
+	var pars []interface{}
+	//作者状态处理
+	if status == 1 || status == 2 {
+		condition += ` AND art.status = ? `
+		pars = append(pars, status)
+	}
+
+	//关键词搜索
+	if keyWord != "" {
+		keyWord = "%" + keyWord + "%"
+		condition += ` AND art.special_name like  ? `
+		pars = append(pars, keyWord)
+	}
+
+	//排序字段以及排序方式处理
+	var sortStr string
+	if sortParam != "" && sortType != "" {
+		if sortParam == "CreateTime" {
+			if sortType == "asc" {
+				sortStr = " ORDER BY art.create_time ASC "
+			} else {
+				sortStr = " ORDER BY art.create_time  DESC "
+			}
+		}
+
+		if sortParam == "ArticleNum" {
+			if sortType == "asc" {
+				sortStr = " ORDER BY art.article_num ASC "
+			} else {
+				sortStr = " ORDER BY art.article_num  DESC  "
+			}
+		}
+
+		if sortParam == "pv" {
+			if sortType == "asc" {
+				sortStr = " ORDER BY art.pv ASC "
+			} else {
+				sortStr = " ORDER BY art.pv  DESC "
+			}
+		}
+		if sortStr == "" {
+			sortStr = " ORDER BY a.publish_time  DESC " // 兼容前端老六乱传字段
+		}
+	} else {
+		sortStr = " ORDER BY art.create_time  DESC "
+	}
+
+	total, err := cygx.GetYanxuanSpecialAuthorCount(condition, pars)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+
+	list, tmpErr := cygx.GetYanxuanSpecialAuthorList(condition+sortStr, pars, startSize, pageSize)
 	if tmpErr != nil {
 		br.Msg = "获取失败"
 		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
 		return
 	}
 
-	br.Data = list
+	var userIds []int
+
+	for _, v := range list {
+		userIds = append(userIds, v.UserId)
+	}
+	//获取专栏用户最新的一篇文章信息
+	mapNewTime := cygxService.GetBestNewYanxuanSpecialByUserId(userIds)
+	for _, v := range list {
+		v.SpecialAuthorId = v.Id
+		v.ArticlePublishTime = mapNewTime[v.UserId]
+	}
+	resp := new(cygx.GetCygxYanxuanSpecialAuthorItemResp)
+	page := paging.GetPaging(currentIndex, pageSize, total)
+	resp.List = list
+	resp.Paging = page
+	br.Data = resp
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "获取成功"
 }
 
-//V12.0.1 上线脚本
-//func init() {
-//	list, err := cygx.GetYanxuanSpecialAuthorList()
-//	if err != nil {
-//		fmt.Println(err)
-//	}
-//	for _, v := range list {
-//		//获取关联公司的用户信息
-//		infoUser, err := cygx.GetUserAndCompanyNameList(v.UserId)
-//		if err != nil {
-//			fmt.Println(err)
-//		}
-//		err = cygx.UpdateSpecialAuthorComapony(infoUser.UserId, infoUser.CompanyId, infoUser.CompanyName)
-//		fmt.Println(infoUser.UserId)
-//	}
-//}
-
 // @Title 审核列表
 // @Description 审核列表
-// @Param	request	body help_doc.AddHelpDocReq true "type json string"
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   Status   query   string  true       "状态: 1:待审核 、 2:已发布 。默认待审核"
+// @Param   Type   query   int  true       "文章类型,1:笔记、2:观点"
+// @Param   KeyWord   query   string  false       "搜索关键词"
+// @Param   SortParam   query   string  false       "排序字段参数,用来排序的字段, 枚举值:'CreatTime':开通时间 、 'articleNum':已发布文章 、 'pv':总Pv/Uv "
+// @Param   SortType   query   string  true       "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
+// @Param   StartDate   query   string  false       "开始时间 ,列如2021-03-06 "
+// @Param   EndDate   query   string  false       "结束时间,列如2021-03-06 "
 // @Success 200 {object} models.AddEnglishReportResp
 // @router /yanxuan_special/list [get]
 func (this *YanxuanSpecialController) List() {
@@ -211,6 +299,25 @@ func (this *YanxuanSpecialController) List() {
 	}
 
 	userId, _ := this.GetInt("UserId", 0)
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+	status, _ := this.GetInt("Status", 1)
+	specialType, _ := this.GetInt("Type")
+	keyWord := this.GetString("KeyWord")
+	//排序参数
+	sortParam := this.GetString("SortParam")
+	sortType := this.GetString("SortType")
+	startDate := this.GetString("StartDate")
+	endDate := this.GetString("EndDate")
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
 	var condition string
 	var pars []interface{}
 
@@ -218,16 +325,78 @@ func (this *YanxuanSpecialController) List() {
 		condition += ` AND a.user_id = ? `
 		pars = append(pars, userId)
 	}
+	if status == 1 {
+		condition += ` AND a.status = 2 `
+	}
+	if status == 2 {
+		condition += ` AND a.status = 3 `
+	}
+
+	if startDate != "" {
+		condition += ` AND a.publish_time >= ` + "'" + startDate + " 00:00:00'"
+	}
+	if endDate != "" {
+		condition += ` AND a.publish_time <= ` + "'" + endDate + " 23:59:59'"
+	}
+
+	//文章类型
+	if specialType == 1 || specialType == 2 {
+		condition += ` AND a.type =  ? `
+		pars = append(pars, specialType)
+	}
+
+	//关键词搜索
+	if keyWord != "" {
+		keyWord = "%" + keyWord + "%"
+		condition += ` AND a.title like  ? `
+		pars = append(pars, keyWord)
+	}
+
+	//排序字段以及排序方式处理
+	var sortStr string
+	if sortParam != "" && sortType != "" {
+		if sortParam == "pv" {
+			if sortType == "asc" {
+				sortStr = " ORDER BY a.pv ASC "
+			} else {
+				sortStr = " ORDER BY a.pv  DESC "
+			}
+		}
+		if sortStr == "" {
+			sortStr = " ORDER BY a.publish_time  DESC " // 兼容前端老六乱传字段
+		}
+	} else {
+		sortStr = " ORDER BY a.publish_time  DESC "
+	}
 
-	condition += ` AND a.status = 2 `
+	total, err := cygx.GetGetYanxuanSpecialCount(condition, pars)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
 
-	list, tmpErr := cygx.GetYanxuanSpecialList(condition, pars)
+	list, tmpErr := cygx.GetYanxuanSpecialList(condition+sortStr, pars, startSize, pageSize)
+	if tmpErr != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
+		return
+	}
+	pars = make([]interface{}, 0)
+	listAuthor, tmpErr := cygx.GetYanxuanSpecialAuthorList("", pars, 0, 999)
 	if tmpErr != nil {
 		br.Msg = "获取失败"
 		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
 		return
 	}
+
+	mapUserId := make(map[int]int)
+	for _, v := range listAuthor {
+		mapUserId[v.UserId] = v.Id
+	}
+
 	for _, v := range list {
+		v.SpecialAuthorId = mapUserId[v.UserId]
 		hasImg, err := utils.ArticleHasImgUrl(v.Content)
 		if err != nil {
 			return
@@ -245,11 +414,6 @@ func (this *YanxuanSpecialController) List() {
 			}
 			v.Docs = docs
 		}
-		if v.Type == 1 {
-			v.Title = "【笔记】" + v.Title
-		} else if v.Type == 2 {
-			v.Title = "【观点】" + v.Title
-		}
 		if v.CompanyTags != "" {
 			v.Tags += v.CompanyTags
 		}
@@ -260,8 +424,12 @@ func (this *YanxuanSpecialController) List() {
 			v.Tags += v.IndustryTags
 		}
 	}
+	resp := new(cygx.GetCygxYanxuanSpeciaResplItemResp)
+	page := paging.GetPaging(currentIndex, pageSize, total)
 
-	br.Data = list
+	resp.List = list
+	resp.Paging = page
+	br.Data = resp
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "获取成功"
@@ -307,7 +475,7 @@ func (this *YanxuanSpecialController) Enable() {
 	} else {
 		status = 4
 	}
-	if tmpErr := cygx.EnableYanxuanSpecial(req.Id, status, req.Reason); tmpErr != nil {
+	if tmpErr := cygx.EnableYanxuanSpecial(req.Id, status, req.Reason, sysUser.RealName); tmpErr != nil {
 		br.Msg = "审批失败"
 		br.ErrMsg = "审批失败, Err:" + tmpErr.Error()
 		return
@@ -322,3 +490,300 @@ func (this *YanxuanSpecialController) Enable() {
 	br.Ret = 200
 	br.Success = true
 }
+
+// @Title 收藏详情
+// @Description 收藏详情
+// @Param   SpecialId    query   int  true       "每页数据条数"
+// @Success 200 {object} models.AddEnglishReportResp
+// @router /yanxuan_special/special_collect/list [get]
+func (this *YanxuanSpecialController) SpecialCollectList() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	specialId, _ := this.GetInt("SpecialId")
+	var condition string
+	var pars []interface{}
+	condition += " AND yanxuan_special_id = ?  	ORDER BY art.create_time DESC  "
+	pars = append(pars, specialId)
+	list, err := cygx.GetCygxYanxuanSpecialCollectList(condition, pars, 0, 100000)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	resp := new(cygx.GetCygxYanxuanSpecialCollectResp)
+	resp.List = list
+	br.Data = resp
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+}
+
+// @Title  下载PV
+// @Description 下载PV接口
+// @Param   SpecialId    query   int  true       "每页数据条数"
+// @router /yanxuan_special/list_pv [get]
+func (this *YanxuanSpecialController) ListPv() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	AdminUser := this.SysUser
+	if AdminUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,用户信息为空"
+		br.Ret = 408
+		return
+	}
+	specialId, _ := this.GetInt("SpecialId")
+	if specialId < 1 {
+		br.Msg = "请输入专栏ID"
+		return
+	}
+	var condition string
+	var pars []interface{}
+	condition = ` AND yanxuan_special_id = ?   ORDER BY create_time DESC  `
+	pars = append(pars, specialId)
+
+	list, err := cygx.GetCygxYanxuanSpecialRecordList(condition, pars)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取数据失败,Err:" + err.Error()
+		return
+	}
+	//创建excel
+	dir, err := os.Executable()
+	exPath := filepath.Dir(dir)
+	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
+	xlsxFile := xlsx.NewFile()
+	if err != nil {
+		br.Msg = "生成文件失败"
+		br.ErrMsg = "生成文件失败"
+		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 {
+		br.Msg = "新增Sheet失败"
+		br.ErrMsg = "新增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 = "阅读时长"
+
+	for _, item := range list {
+		row := sheet.AddRow()
+		cellA := row.AddCell()
+		cellA.Value = item.RealName
+		cellB := row.AddCell()
+		cellB.Value = item.CompanyName
+		cellC := row.AddCell()
+		cellC.Value = item.SellerName
+		cellD := row.AddCell()
+		cellD.Value = item.CreateTime
+		cellE := row.AddCell()
+		cellE.Value = strconv.Itoa(item.StopTime)
+	}
+	err = xlsxFile.Save(downLoadnFilePath)
+	if err != nil {
+		br.Msg = "保存文件失败"
+		br.ErrMsg = "保存文件失败"
+		return
+	}
+	downloadFileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
+	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
+	defer func() {
+		os.Remove(downLoadnFilePath)
+	}()
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "导出成功"
+}
+
+// @Title 审批记录
+// @Description 审批记录接口
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Success 200 {object} models.CygxYanxuanSpecialApprovalLogListResp
+// @router /yanxuan_special/approval_log_list [get]
+func (this *YanxuanSpecialController) ApprovalLogList() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
+	var condition string
+	var pars []interface{}
+	//只是查询驳回状态的数据
+	condition += ` AND a.approval_status =  2 `
+	total, err := cygx.GetCygxYanxuanSpecialApprovalLogCount(condition, pars)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	condition += ` ORDER BY  create_time DESC `
+	list, tmpErr := cygx.GetCygxYanxuanSpecialApprovalLogList(condition, pars, startSize, pageSize)
+	if tmpErr != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
+		return
+	}
+	pars = make([]interface{}, 0)
+	listAuthor, tmpErr := cygx.GetYanxuanSpecialAuthorList("", pars, 0, 999)
+	if tmpErr != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败, Err:" + tmpErr.Error()
+		return
+	}
+	mapUserId := make(map[int]int)
+	for _, v := range listAuthor {
+		mapUserId[v.UserId] = v.Id
+	}
+
+	for _, v := range list {
+		v.SpecialAuthorId = mapUserId[v.UserId]
+	}
+
+	resp := new(cygx.CygxYanxuanSpecialApprovalLogListResp)
+	page := paging.GetPaging(currentIndex, pageSize, total)
+
+	resp.List = list
+	resp.Paging = page
+	br.Data = resp
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+}
+
+// @Title 按钮是否展示接口
+// @Description 按钮是否展示接口
+// @Success 200 {object} models.AddEnglishReportResp
+// @router /yanxuan_special/show_button [get]
+func (this *YanxuanSpecialController) ShowButton() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	resp := new(cygx.CygxYanxuanSpecialShowButton)
+	configCode := utils.TPL_MSG_NEI_RONG_ZU
+	cnfNeiRong, err := cygx.GetConfigByCode(configCode)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	//汪洋王芳手机号
+	configCode = utils.TPL_MSG_WANG_FANG_WANG_YANG
+	cnfWang, err := cygx.GetConfigByCode(configCode)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	//作者管理栏,只有内容组、汪洋、王芳、超管可见
+	if strings.Contains(cnfNeiRong.ConfigValue, sysUser.Mobile) || strings.Contains(cnfWang.ConfigValue, sysUser.Mobile) || sysUser.Role == utils.ROLE_TYPE_CODE_ADMIN {
+		resp.IsShowSpecialAuthor = true
+	}
+	br.Data = resp
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+}
+
+// @Title 作者粉丝列表
+// @Description 作者粉丝列表
+// @Param   SpecialAuthorId    query   int  true       "作者ID"
+// @Success 200 {object} models.AddEnglishReportResp
+// @router /yanxuan_special/special_author_fans_list [get]
+func (this *YanxuanSpecialController) SpecialAuthorFansList() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+	specialAuthorId, _ := this.GetInt("SpecialAuthorId")
+	detail, err := cygx.GetCygxYanxuanSpecialAuthorItemById(specialAuthorId)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	var condition string
+	var pars []interface{}
+	condition += " AND follow_user_id = ?  	ORDER BY a.create_time DESC  "
+	pars = append(pars, detail.UserId)
+	list, err := cygx.GetCygxYanxuanSpecialFollowList(condition, pars, 0, 100000)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	resp := new(cygx.GetCygxYanxuanSpecialFollowResp)
+	resp.List = list
+	br.Data = resp
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+}

+ 570 - 115
controllers/statistic_company_merge.go

@@ -11,8 +11,6 @@ import (
 	cygxService "hongze/hz_crm_api/services/cygx"
 	"os"
 	"path/filepath"
-	"strings"
-
 	//"hongze/hz_crm_api/services"
 	"hongze/hz_crm_api/utils"
 	//"strings"
@@ -79,11 +77,7 @@ func (this *StatisticCompanyMergerController) MergeCompanyList() {
 	if dataType != "续约客户" {
 		packageDifference = "" // 只有续约客户才会有值,过滤前端传过来的脏数据
 	}
-	//if startDate == "" || endDate == "" {
-	//	br.Msg = "获取失败,开始日期或结束日期未传"
-	//	br.ErrMsg = "获取失败,开始日期或结束日期未传"
-	//	return
-	//}
+
 	if startDate == "" {
 		startDate = "2015-01-01"
 	}
@@ -139,58 +133,57 @@ func (this *StatisticCompanyMergerController) MergeCompanyList() {
 	var conditionConfirm string
 	var parsConfirm []interface{}
 
-	companyConfirmList, err := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
+	companyConfirmList, err := company.GetCompanyContractNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		br.Msg = "获取失败"
 		br.ErrMsg = "获取失败,GetCompanyNoRenewedAscribeList Err:" + err.Error()
 		return
 	}
-	var noRenewedcompanyIds []int //已经确定未续约的公司ID
+	var noRenewedcompanyContractIds []int //已经确定未续约的公司ID
 	if len(companyConfirmList) == 0 {
-		noRenewedcompanyIds = append(noRenewedcompanyIds, 0) // 给一个不存在的ID
+		noRenewedcompanyContractIds = append(noRenewedcompanyContractIds, 0) // 给一个不存在的ID
 	} else {
 		for _, v := range companyConfirmList {
-			noRenewedcompanyIds = append(noRenewedcompanyIds, v.CompanyId)
+			noRenewedcompanyContractIds = append(noRenewedcompanyContractIds, v.CompanyContractId)
 		}
 	}
 	//是否确认续约 CRM 13.9
-	conditionAscribRaiTotal += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)   OR c.product_id = 1  OR  a.create_time <  '2023-01-01'  )   ` // 已确认
-	parsAscribeRaiTotal = append(parsAscribeRaiTotal, noRenewedcompanyIds)
+	conditionAscribRaiTotal += ` AND  a.company_contract_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyContractIds)) + `)  ` // 已确认
+	parsAscribeRaiTotal = append(parsAscribeRaiTotal, noRenewedcompanyContractIds)
 
-	conditionAscribRaiToBeTotal += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)  AND  c.product_id = 2  AND  a.create_time >=  '2023-01-01' )  ` // 待确认
-	parsAscribeRaiTobeTotal = append(parsAscribeRaiTobeTotal, noRenewedcompanyIds)
+	conditionAscribRaiToBeTotal += ` AND a.company_contract_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyContractIds)) + `)   ` // 待确认
+	parsAscribeRaiTobeTotal = append(parsAscribeRaiTobeTotal, noRenewedcompanyContractIds)
 
 	if isConfirm != -1 {
 		if isConfirm == 0 {
-			conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)  AND  c.product_id = 2  AND  a.create_time >=  '2023-01-01' )  ` // 待确认
+			conditionAscribRai += ` AND  a.company_contract_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyContractIds)) + `)  ` // 待确认
 		} else {
-			conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `)   OR c.product_id = 1  OR   a.create_time <  '2023-01-01' )    ` // 已确认
+			conditionAscribRai += ` AND  a.company_contract_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyContractIds)) + `)    ` // 已确认
 		}
-		parsAscribeRai = append(parsAscribeRai, noRenewedcompanyIds)
+		parsAscribeRai = append(parsAscribeRai, noRenewedcompanyContractIds)
 	}
-
 	//归因ID CRM 13.9
 	if companyAscribeId > 0 {
 		var conditionAscribe string
 		var parsAscribe []interface{}
 		conditionAscribe = "  AND  company_ascribe_id = ? "
 		parsAscribe = append(parsAscribe, companyAscribeId)
-		companyNoRenewedAscribeList, err := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
+		companyNoRenewedAscribeList, err := company.GetCompanyContractNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
 		if err != nil && err.Error() != utils.ErrNoRow() {
 			br.Msg = "获取失败"
 			br.ErrMsg = "获取失败,GetCompanyNoRenewedAscribeList Err:" + err.Error()
 			return
 		}
-		var companyIds []int
+		var noRenewedcompanyContractIds []int
 		if len(companyNoRenewedAscribeList) == 0 {
-			companyIds = append(companyIds, 0) // 给一个不存在的ID
+			noRenewedcompanyContractIds = append(noRenewedcompanyContractIds, 0) // 给一个不存在的ID
 		} else {
 			for _, v := range companyNoRenewedAscribeList {
-				companyIds = append(companyIds, v.CompanyId)
+				noRenewedcompanyContractIds = append(noRenewedcompanyContractIds, v.CompanyContractId)
 			}
 		}
-		conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
-		parsAscribeRai = append(parsAscribeRai, companyIds)
+		conditionAscribRai += ` AND a.company_contract_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyContractIds)) + `)`
+		parsAscribeRai = append(parsAscribeRai, noRenewedcompanyContractIds)
 	}
 
 	condition += ` AND c.product_id = ?   AND  a.status = 1 `
@@ -292,17 +285,8 @@ func (this *StatisticCompanyMergerController) MergeCompanyList() {
 		condition1 := condition
 		pars1 := pars
 
-		endDateTime, err := time.Parse(utils.FormatDate, endDate)
-		if err != nil {
-			br.Msg = "结束时间异常"
-			br.ErrMsg = "获取失败,Err:" + err.Error()
-			return
-		}
-		//选择的日期加一天的原因是因为:筛选条件是截止到时分秒的,如果要把选择的这一天也统计进去,那么需要在选择的结束日期基础上加上一天
-		tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)
-
-		condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
-		pars1 = append(pars1, startDate, tryOutEndDate)
+		condition1 += ` AND a.end_date >= ? AND a.end_date  <= ? `
+		pars1 = append(pars1, startDate, endDate)
 		//condition1 += ` AND a.operation = ? `
 		//pars1 = append(pars1, "try_out")
 		condition1 += ` AND c.status not in ("永续","正式","关闭")  `
@@ -370,13 +354,6 @@ func (this *StatisticCompanyMergerController) MergeCompanyList() {
 				total = notRenewalNotTryOut
 			}
 
-			//total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
-			//if err != nil && err.Error() != utils.ErrNoRow() {
-			//	br.Msg = "获取失败"
-			//	br.ErrMsg = "获取失败,Err:" + err.Error()
-			//	return
-			//}
-
 			//分页total单独计算
 			total, err = company.GetIncrementalRenewalCompanyProductMergeCount(condition1, pars1)
 			if err != nil && err.Error() != utils.ErrNoRow() {
@@ -384,7 +361,7 @@ func (this *StatisticCompanyMergerController) MergeCompanyList() {
 				br.ErrMsg = "获取失败,Err:" + err.Error()
 				return
 			}
-
+			//return
 			//列表页数据
 			tmpList, err := models.GetIncrementalCompanyListByOperationRecordMerge(condition1, pars1, startSize, pageSize)
 			if err != nil {
@@ -394,18 +371,20 @@ func (this *StatisticCompanyMergerController) MergeCompanyList() {
 			}
 
 			var ascribecompanyIds []int
+			var companyContractIds []int
 			for _, item := range tmpList {
 				//endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
 				//item.EndDate = endDateTime.Format(utils.FormatDate)
 				ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
+				companyContractIds = append(companyContractIds, item.CompanyContractId)
 			}
-			//归因标签
-			mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
+			//合同归因标签
+			mapGetCompanyAscribeContent, mapContent := services.GetCompanyContractAscribeContentMap(companyContractIds)
 			mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
 
 			for _, item := range tmpList {
-				item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
-				item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
+				item.AscribeContent = mapGetCompanyAscribeContent[item.CompanyContractId]
+				item.Content = mapContent[item.CompanyContractId]
 				item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
 			}
 
@@ -538,60 +517,9 @@ func MergeCompanyListListExport(this *StatisticCompanyMergerController, dataType
 	cellSellerName.SetStyle(style)
 	cellSellerName.SetValue("所属销售")
 
-	permissionMap := make(map[int][]string)
-	tmpPermissionMap := make(map[int]map[string][]string)
-	companyContractIdList := make([]string, 0)
-	for _, v := range resp.List {
-		companyContractIdList = append(companyContractIdList, fmt.Sprint(v.CompanyContractId))
-	}
-	if dataType == "新签客户" || dataType == "续约客户" {
-		cellMoney := titleRow.AddCell()
-		cellMoney.SetStyle(style)
-		cellMoney.SetValue("合同金额")
-		cellPermission := titleRow.AddCell()
-		cellPermission.SetStyle(style)
-		cellPermission.SetValue("合同品种")
-
-		//这么大费周章的目的是为了:权益的品种存在主观、客观的区分,如果一个品种既存在主观,又存在客观,那么就展示品种名称,否则就要列出品种名称+主、客观类型
-		if len(companyContractIdList) > 0 {
-			list, tmpErr := company.GetCompanyContractPermissionListByContractIds(strings.Join(companyContractIdList, ","))
-			if tmpErr != nil {
-				err = tmpErr
-				return
-			}
-			for _, v := range list {
-				tmpPermissionNameMap, ok := tmpPermissionMap[v.CompanyContractId]
-				if ok {
-					tmpPermissionNameList, ok2 := tmpPermissionNameMap[v.ChartPermissionName]
-					if ok2 {
-						tmpPermissionNameList = append(tmpPermissionNameList, v.PermissionRemark)
-					} else {
-						tmpPermissionNameList = []string{v.PermissionRemark}
-					}
-					tmpPermissionNameMap[v.ChartPermissionName] = tmpPermissionNameList
-				} else {
-					tmpPermissionNameMap = make(map[string][]string)
-					tmpPermissionNameMap[v.ChartPermissionName] = []string{v.PermissionRemark}
-				}
-				tmpPermissionMap[v.CompanyContractId] = tmpPermissionNameMap
-			}
-		}
-	}
-
-	for companyContractId, tmpPermissionNameMap := range tmpPermissionMap {
-		tmpPermissionName := ``
-		tmpPermissionList := []string{}
-		for tmpChartPermissionName, tmpChartPermissionNameList := range tmpPermissionNameMap {
-			if len(tmpChartPermissionNameList) > 1 {
-				tmpPermissionName = tmpChartPermissionName
-			} else {
-				tmpPermissionName = tmpChartPermissionNameList[0]
-			}
-			tmpPermissionList = append(tmpPermissionList, tmpPermissionName)
-		}
-
-		permissionMap[companyContractId] = tmpPermissionList
-	}
+	cellMoney := titleRow.AddCell()
+	cellMoney.SetStyle(style)
+	cellMoney.SetValue("合同金额")
 
 	cellTime := titleRow.AddCell()
 	cellTime.SetStyle(style)
@@ -613,7 +541,9 @@ func MergeCompanyListListExport(this *StatisticCompanyMergerController, dataType
 		cellContent.SetStyle(style)
 		cellContent.SetValue("详细原因")
 	}
-
+	cellPermissionName := titleRow.AddCell()
+	cellPermissionName.SetStyle(style)
+	cellPermissionName.SetValue("签约套餐")
 	for _, v := range resp.List {
 		dataRow := sheel.AddRow()
 		dataRow.SetHeight(20)
@@ -630,16 +560,11 @@ func MergeCompanyListListExport(this *StatisticCompanyMergerController, dataType
 		cellDataSellerName.SetStyle(style)
 		cellDataSellerName.SetValue(v.SellerName)
 
-		if dataType == "新签客户" || dataType == "续约客户" {
-			cellDataMoney := dataRow.AddCell()
-			cellDataMoney.SetStyle(style)
-			cellDataMoney.SetValue(v.Money)
-			cellDataPermission := dataRow.AddCell()
-			cellDataPermission.SetStyle(style)
-			if permissionStrList, ok := permissionMap[v.CompanyContractId]; ok {
-				cellDataPermission.SetValue(strings.Join(permissionStrList, ","))
-			}
-		}
+		//if dataType == "新签客户" || dataType == "续约客户" {
+		cellDataMoney := dataRow.AddCell()
+		cellDataMoney.SetStyle(style)
+		cellDataMoney.SetValue(v.Money)
+		//}
 
 		cellDataTime := dataRow.AddCell()
 		cellDataTime.SetStyle(style)
@@ -661,7 +586,9 @@ func MergeCompanyListListExport(this *StatisticCompanyMergerController, dataType
 			cellContent.SetStyle(style)
 			cellContent.SetValue(v.Content)
 		}
-
+		cellDataPermissionName := dataRow.AddCell()
+		cellDataPermissionName.SetStyle(style)
+		cellDataPermissionName.SetValue(v.PermissionName)
 	}
 	err = xlsxFile.Save(downLoadnFilePath)
 	if err != nil {
@@ -670,7 +597,7 @@ func MergeCompanyListListExport(this *StatisticCompanyMergerController, dataType
 		return
 	}
 	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
-	downloadFileName := "增量客户数据_" + randStr + ".xlsx"
+	downloadFileName := dataType + "数据_" + randStr + ".xlsx"
 	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
 	defer func() {
 		os.Remove(downLoadnFilePath)
@@ -740,3 +667,531 @@ func (this *StatisticCompanyMergerController) CompanyPreviousDetail() {
 	br.Msg = "获取成功"
 	br.Data = resp
 }
+
+// @Title 权益行业套餐统计
+// @Description 权益客户统计列表接口
+// @Param   PageSize   query   int  true       "每页数据条数"
+// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
+// @Param   Keyword   query   string  true       "客户名称"
+// @Param   AdminId   query   string  true       "销售id,多个用英文逗号隔开,空字符串为全部"
+// @Param   StartDate   query   string  false       "开始日期"
+// @Param   EndDate   query   string  false       "结束日期"
+// @Param   DataType   query   string  false       "报表类型,枚举值:`行业新签`,`行业续约`,`行业未续约`"
+// @Param   PermissionName   query   string  false       "行业权限名称"
+// @Param   IsExport   query   bool  false       "是否导出excel,默认是false"
+// @Success 200 {object} response.IncrementalCompanyListResp
+// @router /merge_company/company_contract_permission/list [get]
+func (this *StatisticCompanyMergerController) CompanyContractPermissionList() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+
+	adminId := this.GetString("AdminId")
+	regionType := this.GetString("RegionType")
+	//companyType := this.GetString("CompanyType")
+	dataType := this.GetString("DataType")
+	keyword := this.GetString("Keyword")
+
+	startDate := this.GetString("StartDate")
+	endDate := this.GetString("EndDate")
+	permissionName := this.GetString("PermissionName")
+	if permissionName == "" { //默认所筛选行业为医药
+		permissionName = "医药"
+	}
+
+	//if startDate == "" || endDate == "" {
+	//	br.Msg = "获取失败,开始日期或结束日期未传"
+	//	br.ErrMsg = "获取失败,开始日期或结束日期未传"
+	//	return
+	//}
+	if startDate == "" {
+		startDate = "2015-01-01"
+	}
+	if endDate == "" {
+		endDate = time.Now().Format(utils.FormatDate)
+	}
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
+
+	//是否导出报表
+	isExport, _ := this.GetBool("IsExport")
+	if isExport {
+		pageSize = 10000
+		currentIndex = 1
+		permissionName = "" //点击下载的时候不做行业筛选
+	}
+
+	var condition string
+	var pars []interface{}
+
+	//条件
+	if adminId != "" {
+		condition += ` AND c.seller_id in  (` + adminId + `) `
+		//pars = append(pars, adminId)
+	} else {
+
+		//根据当前角色来获取查询条件
+		condition, pars = getQueryParams(condition, pars, sysUser, "c.")
+
+	}
+	if regionType != "" {
+		condition += ` AND b.region_type = ? `
+		pars = append(pars, regionType)
+	}
+
+	//关键字搜索
+	if keyword != "" {
+		condition += ` and b.company_name like "%` + keyword + `%" `
+	}
+
+	var conditionAscribRai string      // 处理权益未续约客户检索列表SQL查询条件
+	var conditionAscribRaiTotal string // 处理权益未续约客户总量查询条件
+	var parsAscribeRai []interface{}
+	var parsAscribeRaiTotal []interface{} // 处理权益未续约客户总量查询条件
+
+	condition += ` AND c.product_id = ?   AND  a.status = 1 `
+	pars = append(pars, 2)
+
+	var list []*models.IncrementalList
+	var listPessionGroup []*models.CompanyContractPermissionNameGroupCountResp
+
+	var newCompanyTotal int                   //新签合同数量
+	var notRenewalCompanyTotal int            //未续约客户数已确认
+	var notRenewalCompanyToBeConfirmTotal int //未续约客户数待确认
+	var dataTotal, trialTotal, renewalCompanyTotal int
+	var notRenewalTryOut, notRenewalNotTryOut int
+
+	//if dataType == "行业未续约" {
+	//	condition += ` AND a.end_date >= ? AND a.end_date  <= ? `
+	//	pars = append(pars, startDate, endDate)
+	//} else {
+	//	condition += ` AND a.start_date >= ? AND a.start_date <= ?  `
+	//	pars = append(pars, startDate, endDate)
+	//}
+	//
+	//conditionPerssion := condition
+	//parsPerssion := pars
+	//conditionPerssion += ` AND  d.permission_name IN ('医药','消费','科技','智造','策略','买方研选')`
+	//
+	//listPessionGroup, err := models.GetCompanyContractPermissionNameGroupCount(conditionPerssion, parsPerssion)
+	//if err != nil && err.Error() != utils.ErrNoRow() {
+	//	br.Msg = "获取失败"
+	//	br.ErrMsg = "获取失败,Err:" + err.Error()
+	//	return
+	//}
+
+	//if permissionName == "" {
+	condition += ` AND  d.permission_name IN ('医药','消费','科技','智造','策略','买方研选')`
+	//}
+
+	var err error
+	//新签客户数
+	{
+		condition1 := condition
+		pars1 := pars
+		condition1 += ` AND a.start_date >= ? AND a.start_date <= ?  `
+		pars1 = append(pars1, startDate, endDate)
+		condition1 += ` AND d.contract_type = ? `
+		pars1 = append(pars1, "行业新签")
+		newCompanyTotal, err = company.GetIncrementalNewCompanyProductPermissionCount(condition1, pars1)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+
+		if dataType == "行业新签" {
+			conditionPerssion := condition1
+			parsPerssion := pars1
+			conditionPerssion += ` AND  d.permission_name IN ('医药','消费','科技','智造','策略','买方研选')`
+
+			listPessionGroup, err = models.GetCompanyContractPermissionNameGroupCount(conditionPerssion, parsPerssion)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+
+			//行业筛选查询
+			if permissionName != "" {
+				condition1 += ` AND  d.permission_name = ? `
+				pars1 = append(pars1, permissionName)
+			}
+
+			total, err := company.GetIncrementalNewCompanyProductPermissionCount(condition1, pars1)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+
+			//列表页数据
+			tmpList, err := models.GetIncrementalCompanyPermissionList(condition1, pars1, startSize, pageSize)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+			list = tmpList
+			dataTotal = total
+		}
+	}
+
+	//续约客户数
+	{
+		condition1 := condition
+		pars1 := pars
+		condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
+		pars1 = append(pars1, startDate, endDate)
+		condition1 += ` AND d.contract_type = ? `
+		pars1 = append(pars1, "行业续约")
+		////额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
+		//pars1 = append(pars1, endDate)
+
+		total, err := company.GetIncrementalNewCompanyProductPermissionCount(condition1, pars1)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+
+		renewalCompanyTotal = total
+
+		if dataType == "行业续约" {
+			conditionPerssion := condition1
+			parsPerssion := pars1
+			conditionPerssion += ` AND  d.permission_name IN ('医药','消费','科技','智造','策略','买方研选')`
+
+			listPessionGroup, err = models.GetCompanyContractPermissionNameGroupCount(conditionPerssion, parsPerssion)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+			//行业筛选查询
+			if permissionName != "" {
+				condition1 += ` AND  d.permission_name = ? `
+				pars1 = append(pars1, permissionName)
+			}
+			//列表数据数量
+			total, err := company.GetIncrementalNewCompanyProductPermissionCount(condition1, pars1)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+			//列表页数据
+			tmpList, err := models.GetIncrementalCompanyPermissionList(condition1, pars1, startSize, pageSize)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+			list = tmpList
+			dataTotal = total
+		}
+	}
+
+	//return
+
+	//行业未续约
+	{
+		condition1 := condition
+		pars1 := pars
+		condition1 += ` AND a.end_date >= ? AND a.end_date  <= ? `
+		pars1 = append(pars1, startDate, endDate)
+		condition1 += ` AND c.status not in ("永续","正式","关闭")  `
+
+		//未续约数量
+		notRenewalCondition := condition1
+		notRenewalPars := pars1
+		notRenewalCondition += conditionAscribRaiTotal
+		notRenewalPars = append(notRenewalPars, parsAscribeRaiTotal)
+		total, err := company.GetIncrementalNewCompanyProductPermissionCount(notRenewalCondition, notRenewalPars)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+		notRenewalCompanyTotal = total
+		condition1 += conditionAscribRai
+		pars1 = append(pars1, parsAscribeRai)
+		if dataType == "行业未续约" {
+			conditionPerssion := condition1
+			parsPerssion := pars1
+			conditionPerssion += ` AND  d.permission_name IN ('医药','消费','科技','智造','策略','买方研选')`
+
+			listPessionGroup, err = models.GetCompanyContractPermissionNameGroupCount(conditionPerssion, parsPerssion)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+			//行业筛选查询
+			if permissionName != "" {
+				condition1 += ` AND  d.permission_name = ? `
+				pars1 = append(pars1, permissionName)
+			}
+
+			//分页total单独计算
+			total, err = company.GetIncrementalNewCompanyProductPermissionCount(condition1, pars1)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+			//return
+			//列表页数据
+			tmpList, err := models.GetIncrementalCompanyPermissionList(condition1, pars1, startSize, pageSize)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取失败,Err:" + err.Error()
+				return
+			}
+
+			list = tmpList
+			dataTotal = total
+
+		}
+	}
+
+	listLen := len(list)
+
+	if listLen == 0 {
+		list = make([]*models.IncrementalList, 0)
+	}
+	var companyContractIds []int
+	var companyIds []int
+	for i := 0; i < listLen; i++ {
+		item := list[i]
+		companyContractIds = append(companyContractIds, item.CompanyContractId)
+		companyIds = append(companyIds, item.CompanyId)
+		//新增试用不需要计算剩余日期
+		if dataType != "新增试用" {
+			//剩余可用天数
+			endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
+			endDateTime = endDateTime.AddDate(0, 0, 1)
+			sub := endDateTime.Sub(time.Now())
+			expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
+			list[i].ExpireDay = expireDay
+		}
+	}
+
+	//行业未续约 需要处理公司对应行业权限下的权限状态
+	if dataType == "行业未续约" {
+		mappermissionNameStatus, err := cygxService.GetCompanyPermissionNameStatusMapByCompanyId(companyIds)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "获取失败,Err:" + err.Error()
+			return
+		}
+		for _, v := range list {
+			v.PermissionNameStatus = mappermissionNameStatus[fmt.Sprint(v.CompanyId, v.PermissionNameExport)]
+		}
+	}
+
+	//合并合同所对应的权限
+	mappermissionName, err := cygxService.GetCompanyContractPermissionNameMapById(companyContractIds)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	for _, v := range list {
+		v.PermissionName = mappermissionName[v.CompanyContractId]
+	}
+
+	//处理展示顺序
+	permissionNameSlice := []string{"医药", "消费", "科技", "智造", "策略", "买方研选"}
+	var itemspermissionNameSlice []*models.CompanyContractPermissionNameGroupCountResp
+	for _, vName := range permissionNameSlice {
+		item := new(models.CompanyContractPermissionNameGroupCountResp)
+		for _, v := range listPessionGroup {
+			if v.PermissionName != vName {
+				continue
+			}
+			item.Total = v.Total
+		}
+		item.PermissionName = vName
+		itemspermissionNameSlice = append(itemspermissionNameSlice, item)
+	}
+
+	page := paging.GetPaging(currentIndex, pageSize, dataTotal)
+	resp := response.IncrementalCompanyListResp{
+		Paging:                            page,
+		ListPermissionName:                itemspermissionNameSlice,
+		List:                              list,
+		TrialTotal:                        trialTotal,
+		NewCompanyTotal:                   newCompanyTotal,
+		RenewalCompanyTotal:               renewalCompanyTotal,
+		NotRenewalCompanyTotal:            notRenewalCompanyTotal,
+		NotRenewalCompanyToBeConfirmTotal: notRenewalCompanyToBeConfirmTotal,
+		NotRenewalTryOut:                  notRenewalTryOut,
+		NotRenewalNotTryOut:               notRenewalNotTryOut,
+	}
+	//fmt.Println()
+	//导出excel
+	if isExport {
+		PermissionCompanyListListExport(this, dataType, resp, br)
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}
+
+// PermissionCompanyListListExport 导出增量客户数据报表excel
+func PermissionCompanyListListExport(this *StatisticCompanyMergerController, dataType string, resp response.IncrementalCompanyListResp, br *models.BaseResponse) {
+	dir, err := os.Executable()
+	exPath := filepath.Dir(dir)
+	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
+	xlsxFile := xlsx.NewFile()
+	if err != nil {
+		br.Msg = "生成文件失败"
+		br.ErrMsg = "生成文件失败"
+		return
+	}
+	style := xlsx.NewStyle()
+	alignment := xlsx.Alignment{
+		Horizontal: "center",
+		Vertical:   "center",
+		WrapText:   true,
+	}
+	permissionNameSlice := []string{"医药", "消费", "科技", "智造", "策略", "买方研选"}
+
+	mapExport := make(map[string][]*models.IncrementalList)
+	type IncrementalCompanyListExport struct {
+		PermissionName string `description:"权限名"`
+		List           []*models.IncrementalList
+	}
+
+	for _, v := range resp.List {
+		if v.PermissionNameExport == "" {
+			continue
+		}
+		mapExport[v.PermissionNameExport] = append(mapExport[v.PermissionNameExport], v)
+	}
+
+	style.Alignment = alignment
+	style.ApplyAlignment = true
+
+	for _, vName := range permissionNameSlice {
+		sheel, err := xlsxFile.AddSheet(vName)
+		if err != nil {
+			br.Msg = "新增Sheet失败"
+			br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
+			return
+		}
+		sheel.SetColWidth(0, 0, 30)
+		sheel.SetColWidth(1, 1, 15)
+		sheel.SetColWidth(2, 2, 15)
+		sheel.SetColWidth(3, 3, 18)
+		sheel.SetColWidth(4, 4, 40)
+		sheel.SetColWidth(5, 5, 18)
+
+		//表头
+
+		titleRow := sheel.AddRow()
+
+		cellName := titleRow.AddCell()
+		cellName.SetStyle(style)
+		cellName.SetValue("客户名称")
+
+		cellSellerName := titleRow.AddCell()
+		cellSellerName.SetStyle(style)
+		cellSellerName.SetValue("所属销售")
+
+		cellMoney := titleRow.AddCell()
+		cellMoney.SetStyle(style)
+		cellMoney.SetValue("合同金额")
+
+		cellTime := titleRow.AddCell()
+		cellTime.SetStyle(style)
+		cellTime.SetValue("合同期限")
+
+		cellPermissionName := titleRow.AddCell()
+		cellPermissionName.SetStyle(style)
+		cellPermissionName.SetValue("签约套餐")
+
+		if dataType == "行业未续约" {
+			cellPermissionNameStatus := titleRow.AddCell()
+			cellPermissionNameStatus.SetStyle(style)
+			cellPermissionNameStatus.SetValue("当前行业状态")
+
+			cellCompanyProductStatus := titleRow.AddCell()
+			cellCompanyProductStatus.SetStyle(style)
+			cellCompanyProductStatus.SetValue("当前客户状态")
+		}
+		for _, v := range mapExport[vName] {
+			dataRow := sheel.AddRow()
+			dataRow.SetHeight(20)
+
+			cellDataName := dataRow.AddCell()
+			cellDataName.SetStyle(style)
+			cellDataName.SetValue(v.CompanyName)
+
+			cellDataSellerName := dataRow.AddCell()
+			cellDataSellerName.SetStyle(style)
+			cellDataSellerName.SetValue(v.SellerName)
+
+			cellDataMoney := dataRow.AddCell()
+			cellDataMoney.SetStyle(style)
+			cellDataMoney.SetValue(v.Money)
+
+			cellDataTime := dataRow.AddCell()
+			cellDataTime.SetStyle(style)
+			cellDataTime.SetValue(v.StartDate + "~" + v.EndDate)
+
+			cellDataPermissionName := dataRow.AddCell()
+			cellDataPermissionName.SetStyle(style)
+			cellDataPermissionName.SetValue(v.PermissionName)
+
+			if dataType == "行业未续约" {
+				cellDataPermissionNameStatus := dataRow.AddCell()
+				cellDataPermissionNameStatus.SetStyle(style)
+				cellDataPermissionNameStatus.SetValue(v.PermissionNameStatus)
+
+				cellDataCompanyProductStatus := dataRow.AddCell()
+				cellDataCompanyProductStatus.SetStyle(style)
+				cellDataCompanyProductStatus.SetValue(v.CompanyProductStatus)
+			}
+		}
+	}
+
+	err = xlsxFile.Save(downLoadnFilePath)
+	if err != nil {
+		br.Msg = "保存文件失败"
+		br.ErrMsg = "保存文件失败"
+		return
+	}
+	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
+	downloadFileName := dataType + "数据_" + randStr + ".xlsx"
+	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
+	defer func() {
+		os.Remove(downLoadnFilePath)
+	}()
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "导出成功"
+}

+ 210 - 48
controllers/statistic_report.go

@@ -5,6 +5,7 @@ import (
 	"errors"
 	"fmt"
 	"github.com/rdlucklib/rdluck_tools/paging"
+	"github.com/shopspring/decimal"
 	"github.com/tealeg/xlsx"
 	"hongze/hz_crm_api/models"
 	"hongze/hz_crm_api/models/company"
@@ -5394,12 +5395,15 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 	tmpAllRenewFollowNumMap := make(map[int]int)
 	tmpAllExpireNumMap := make(map[int]int)
 	tmpAllRenewNumMap := make(map[int]int)
+	tmpAllUnusualRenewNumMap := make(map[int]int)  // 续约异常客户数量汇总
+	tmpAllFormalCompanyNumMap := make(map[int]int) // 当期正式客户数量汇总
 
 	//id集合汇总
 	tmpAllNotRenewIdMap := make(map[int]string)
 	tmpAllRenewFollowIdMap := make(map[int]string)
 	tmpAllExpireIdMap := make(map[int]string)
 	tmpAllRenewIdMap := make(map[int]string)
+	tmpAllUnusualRenewIdMap := make(map[int]string) // 续约异常客户id汇总
 
 	for _, v := range group {
 		v.ResearcherList = groupMap[v.GroupId]
@@ -5411,18 +5415,21 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 		tmpGroupRenewFollowNumMap := make(map[int]int)
 		tmpGroupExpireNumMap := make(map[int]int)
 		tmpGroupRenewNumMap := make(map[int]int)
+		tmpGroupUnusualRenewNumMap := make(map[int]int) //组内续约异常客户数
 
 		//id集合
 		tmpGroupNotRenewIdSliceMap := make(map[int][]string)
 		tmpGroupRenewFollowIdSliceMap := make(map[int][]string)
 		tmpGroupExpireIdSliceMap := make(map[int][]string)
 		tmpGroupRenewIdSliceMap := make(map[int][]string)
+		tmpGroupUnusualRenewIdSliceMap := make(map[int][]string) // 组内续约异常客户id汇总
 
 		//id集合
 		tmpGroupNotRenewIdMap := make(map[int]string)
 		tmpGroupRenewFollowIdMap := make(map[int]string)
 		tmpGroupExpireIdMap := make(map[int]string)
 		tmpGroupRenewIdMap := make(map[int]string)
+		tmpGroupUnusualRenewIdMap := make(map[int]string) // 组内续约异常客户id汇总
 
 		for _, researcher := range groupMap[v.GroupId] {
 			//组内研究员数据
@@ -5433,10 +5440,10 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 				startDateIndexList[index] = adminData.StartDate
 				endDateIndexList[index] = adminData.EndDate
 
-				var tmpNotRenewNum, tmpRenewFollowNum, tmpExpireStatus, tmpRenewStatus int
+				var tmpNotRenewNum, tmpRenewFollowNum, tmpExpireStatus, tmpRenewStatus, tmpUnusualRenewStatus int
 				//var tmpNotRenewIds, tmpRenewFollowIds, tmpExpireIds string
-				var tmpNotRenewIdSlice, tmpRenewFollowIdSlice, tmpExpireIdSlice, tmpRenewIdSlice []string
-				var tmpNotRenewId, tmpRenewFollowId, tmpExpireId, tmpRenewId string
+				var tmpNotRenewIdSlice, tmpRenewFollowIdSlice, tmpExpireIdSlice, tmpRenewIdSlice, tmpUnusualRenewIdSlice []string
+				var tmpNotRenewId, tmpRenewFollowId, tmpExpireId, tmpRenewId, tmpUnusualRenewId string
 
 				if num, ok := adminData.NotRenewMap[researcher.AdminId]; ok {
 					tmpNotRenewNum = num
@@ -5458,18 +5465,26 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 					tmpRenewIdSlice = append(tmpRenewIdSlice, adminData.RenewIdMap[researcher.AdminId])
 					tmpRenewId = strings.Join(tmpRenewIdSlice, ",")
 				}
+				// 续约异常客户
+				if num, ok := adminData.UnusualRenewMap[researcher.AdminId]; ok {
+					tmpUnusualRenewStatus = num
+					tmpUnusualRenewIdSlice = append(tmpUnusualRenewIdSlice, adminData.UnusualRenewIdMap[researcher.AdminId])
+					tmpUnusualRenewId = strings.Join(tmpUnusualRenewIdSlice, ",")
+				}
 
 				tmpAdminRsRenewRecordNum := statistic_report.CompanyRenewRecordNum{
-					NotRenewNum:    tmpNotRenewNum,
-					NotRenewIds:    tmpNotRenewId,
-					RenewFollowNum: tmpRenewFollowNum,
-					RenewFollowIds: tmpRenewFollowId,
-					ExpireNum:      tmpExpireStatus,
-					ExpireIds:      tmpExpireId,
-					RenewNum:       tmpRenewStatus,
-					RenewIds:       tmpRenewId,
-					StartDate:      adminData.StartDate,
-					EndDate:        adminData.EndDate,
+					NotRenewNum:     tmpNotRenewNum,
+					NotRenewIds:     tmpNotRenewId,
+					RenewFollowNum:  tmpRenewFollowNum,
+					RenewFollowIds:  tmpRenewFollowId,
+					ExpireNum:       tmpExpireStatus,
+					ExpireIds:       tmpExpireId,
+					RenewNum:        tmpRenewStatus,
+					RenewIds:        tmpRenewId,
+					UnusualRenewNum: tmpUnusualRenewStatus,
+					UnusualRenewIds: tmpUnusualRenewId,
+					StartDate:       adminData.StartDate,
+					EndDate:         adminData.EndDate,
 				}
 				tmpCompanyRenewRecordNumList = append(tmpCompanyRenewRecordNumList, tmpAdminRsRenewRecordNum)
 
@@ -5486,11 +5501,15 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 				if _, ok := tmpGroupRenewNumMap[index]; !ok {
 					tmpGroupRenewNumMap[index] = 0
 				}
+				if _, ok := tmpGroupUnusualRenewNumMap[index]; !ok {
+					tmpGroupUnusualRenewNumMap[index] = 0
+				}
 
 				tmpGroupNotRenewNumMap[index] += tmpNotRenewNum
 				tmpGroupRenewFollowNumMap[index] += tmpRenewFollowNum
 				tmpGroupExpireNumMap[index] += tmpExpireStatus
 				tmpGroupRenewNumMap[index] += tmpRenewStatus
+				tmpGroupUnusualRenewNumMap[index] += tmpUnusualRenewStatus
 
 				//组内数据汇总
 				if _, ok := tmpGroupNotRenewIdMap[index]; !ok {
@@ -5514,6 +5533,9 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 				if tmpRenewId != "" {
 					tmpGroupRenewIdSliceMap[index] = append(tmpGroupRenewIdSliceMap[index], tmpRenewId)
 				}
+				if tmpUnusualRenewId != "" {
+					tmpGroupUnusualRenewIdSliceMap[index] = append(tmpGroupUnusualRenewIdSliceMap[index], tmpUnusualRenewId)
+				}
 
 				//总数据汇总
 				if _, ok := tmpAllNotRenewNumMap[index]; !ok {
@@ -5533,20 +5555,8 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 				tmpAllRenewFollowNumMap[index] += tmpRenewFollowNum
 				tmpAllExpireNumMap[index] += tmpExpireStatus
 				tmpAllRenewNumMap[index] += tmpRenewStatus
-
-				////总数据汇总
-				//if _, ok := tmpAllNotRenewIdMap[index]; !ok {
-				//	tmpAllNotRenewIdMap[index] = ""
-				//}
-				//if _, ok := tmpAllRenewFollowIdMap[index]; !ok {
-				//	tmpAllRenewFollowIdMap[index] = ""
-				//}
-				//if _, ok := tmpAllExpireIdMap[index]; !ok {
-				//	tmpAllExpireIdMap[index] = ""
-				//}
-				//tmpAllNotRenewIdMap[index] += tmpNotRenewId
-				//tmpAllRenewFollowIdMap[index] += tmpRenewFollowId
-				//tmpAllExpireIdMap[index] += tmpExpireId
+				tmpAllUnusualRenewNumMap[index] = adminData.UnusualRenewTotal
+				tmpAllFormalCompanyNumMap[index] = adminData.FormalCompanyTotal
 			}
 			tmpAdminRenewRecord := statistic_report.AdminRenewRecord{
 				Name:                      researcher.RealName,
@@ -5561,18 +5571,21 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 			tmpGroupRenewFollowIdMap[i] = strings.Join(tmpGroupRenewFollowIdSliceMap[i], ",")
 			tmpGroupExpireIdMap[i] = strings.Join(tmpGroupExpireIdSliceMap[i], ",")
 			tmpGroupRenewIdMap[i] = strings.Join(tmpGroupRenewIdSliceMap[i], ",")
+			tmpGroupUnusualRenewIdMap[i] = strings.Join(tmpGroupUnusualRenewIdSliceMap[i], ",")
 
 			tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
-				NotRenewNum:    tmpGroupNotRenewNumMap[i],
-				NotRenewIds:    tmpGroupNotRenewIdMap[i],
-				RenewFollowNum: tmpGroupRenewFollowNumMap[i],
-				RenewFollowIds: tmpGroupRenewFollowIdMap[i],
-				ExpireNum:      tmpGroupExpireNumMap[i],
-				ExpireIds:      tmpGroupExpireIdMap[i],
-				RenewNum:       tmpGroupRenewNumMap[i],
-				RenewIds:       tmpGroupRenewIdMap[i],
-				StartDate:      startDateIndexList[i],
-				EndDate:        endDateIndexList[i],
+				NotRenewNum:     tmpGroupNotRenewNumMap[i],
+				NotRenewIds:     tmpGroupNotRenewIdMap[i],
+				RenewFollowNum:  tmpGroupRenewFollowNumMap[i],
+				RenewFollowIds:  tmpGroupRenewFollowIdMap[i],
+				ExpireNum:       tmpGroupExpireNumMap[i],
+				ExpireIds:       tmpGroupExpireIdMap[i],
+				RenewNum:        tmpGroupRenewNumMap[i],
+				RenewIds:        tmpGroupRenewIdMap[i],
+				UnusualRenewNum: tmpGroupUnusualRenewNumMap[i],
+				UnusualRenewIds: tmpGroupUnusualRenewIdMap[i],
+				StartDate:       startDateIndexList[i],
+				EndDate:         endDateIndexList[i],
 			}
 			tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, tmpGroupCompanyRenewRecordNum)
 		}
@@ -5587,17 +5600,24 @@ func (this *StatisticReportController) RenewCompanyStatistics() {
 
 	//总体汇总数据
 	for i := 0; i < len(tmpAllRenewFollowNumMap); i++ {
+		unusualRate := ``
+		if tmpAllUnusualRenewNumMap[i] > 0 && tmpAllFormalCompanyNumMap[i] > 0 {
+			unusualRate = decimal.NewFromInt(int64(tmpAllUnusualRenewNumMap[i])*100).Div(decimal.NewFromInt(int64(tmpAllFormalCompanyNumMap[i]))).Round(2).String() + "%"
+		}
 		tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
-			NotRenewNum:    tmpAllNotRenewNumMap[i],
-			NotRenewIds:    tmpAllNotRenewIdMap[i],
-			RenewFollowNum: tmpAllRenewFollowNumMap[i],
-			RenewFollowIds: tmpAllRenewFollowIdMap[i],
-			ExpireNum:      tmpAllExpireNumMap[i],
-			ExpireIds:      tmpAllExpireIdMap[i],
-			RenewNum:       tmpAllRenewNumMap[i],
-			RenewIds:       tmpAllRenewIdMap[i],
-			StartDate:      startDateIndexList[i],
-			EndDate:        endDateIndexList[i],
+			NotRenewNum:     tmpAllNotRenewNumMap[i],
+			NotRenewIds:     tmpAllNotRenewIdMap[i],
+			RenewFollowNum:  tmpAllRenewFollowNumMap[i],
+			RenewFollowIds:  tmpAllRenewFollowIdMap[i],
+			ExpireNum:       tmpAllExpireNumMap[i],
+			ExpireIds:       tmpAllExpireIdMap[i],
+			RenewNum:        tmpAllRenewNumMap[i],
+			RenewIds:        tmpAllRenewIdMap[i],
+			UnusualRenewNum: tmpAllUnusualRenewNumMap[i],
+			UnusualRenewIds: tmpAllUnusualRenewIdMap[i],
+			UnusualRate:     unusualRate, // 异常率
+			StartDate:       startDateIndexList[i],
+			EndDate:         endDateIndexList[i],
 		}
 		allCompanyRenewRecordNum = append(allCompanyRenewRecordNum, tmpGroupCompanyRenewRecordNum)
 	}
@@ -6123,7 +6143,7 @@ func (this *StatisticReportController) InvoicePaymentList() {
 	br.Data = results
 }
 
-// ServiceList
+// SimpleList
 // @Title 合同套餐列表
 // @Description 合同套餐列表
 // @Param   ProductId  query  int  false  "套餐类型: 1-FICC(默认); 2-权益"
@@ -6195,3 +6215,145 @@ func (this *StatisticReportController) SimpleList() {
 	br.Msg = "获取成功"
 	br.Data = respList
 }
+
+// UnusualRenewCompanyStatistics
+// @Title 获取续约异常的客户统计数据
+// @Description 获取续约客户统计数据接口
+// @Param   DataType   query   string  true       "枚举值:week、month、time_interval"
+// @Param   StartDate   query   string  true       "开始日期,格式:2022-04-06"
+// @Param   EndDate   query   string  true       "结束日期,格式:2022-04-06"
+// @Success 200 {object} statistic_report.CompanyUnusualRenewRecordResp
+// @router /report/unusual_renew_company [get]
+func (this *StatisticReportController) UnusualRenewCompanyStatistics() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	sysUser := this.SysUser
+	if sysUser == nil {
+		br.Msg = "请登录"
+		br.ErrMsg = "请登录,SysUser Is Empty"
+		br.Ret = 408
+		return
+	}
+
+	dataType := this.GetString("DataType")
+	productId, _ := this.GetInt("ProductId", 1)
+	startDate := this.GetString("StartDate")
+	endDate := this.GetString("EndDate")
+
+	var companyUnusualRenewDataMapList []statistic_report.UnusualCompanyRenewDataMap
+	var err error
+	//var firstDate time.Time
+	switch dataType {
+	//获取列表
+	case "week":
+		nowWeekMonday := utils.GetNowWeekMonday() //本周周一
+		//companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
+		companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewWeekDataNum(nowWeekMonday, productId, 6)
+		if err != nil {
+			br.Msg = "数据异常"
+			br.ErrMsg = "数据异常,Err:" + err.Error()
+			return
+		}
+	case "month":
+		nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
+		companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewMonthDataNum(nowMonthFirstDay, productId, 6)
+		if err != nil {
+			br.Msg = "数据异常"
+			br.ErrMsg = "数据异常,Err:" + err.Error()
+			return
+		}
+	case "time_interval":
+		if startDate == `` || endDate == `` {
+			br.Msg = "开始日期或结束日期不能为空"
+			br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
+			return
+		}
+		companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewTimeIntervalData(productId, startDate, endDate)
+		if err != nil {
+			br.Msg = "数据异常"
+			br.ErrMsg = "数据异常,Err:" + err.Error()
+			return
+		}
+
+	}
+
+	groupId := 0
+	if utils.RunMode == "release" {
+		groupId = 37
+	} else {
+		groupId = 61
+	}
+	subAdmins, err := system.GetAdminByGroupId(groupId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "获取销售失败"
+		br.ErrMsg = "获取销售失败,Err:" + err.Error()
+		return
+	}
+
+	//数据处理
+	list := make([]statistic_report.GroupUnusualRenewRecord, 0)
+	summaryList := make([]statistic_report.SummaryUnusualRenewRecordNum, 0)
+	companyRenewRecordResp := statistic_report.CompanyUnusualRenewRecordResp{
+		List:        list,
+		SummaryList: summaryList,
+	}
+
+	// 每日期组数据的汇总客户id
+	companyIdIndexMap := make(map[int][]string)
+	for k, v := range subAdmins {
+		tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyUnusualRenewRecordNum, 0)
+
+		for index, adminData := range companyUnusualRenewDataMapList {
+			tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, statistic_report.CompanyUnusualRenewRecordNum{
+				UnusualRenewNum: adminData.UnusualRenewMap[v.AdminId],
+				UnusualRenewIds: adminData.UnusualRenewIdMap[v.AdminId],
+				StartDate:       adminData.StartDate,
+				EndDate:         adminData.EndDate,
+			})
+
+			if adminData.UnusualRenewIdMap[v.AdminId] != `` {
+				tmpCompanyIdList, ok := companyIdIndexMap[index]
+				if !ok {
+					tmpCompanyIdList = make([]string, 0)
+				}
+				companyIdIndexMap[index] = append(tmpCompanyIdList, adminData.UnusualRenewIdMap[v.AdminId])
+			}
+
+			if k == 0 {
+				unusualRate := ``
+				if adminData.UnusualRenewTotal > 0 && adminData.FormalCompanyTotal > 0 {
+					unusualRate = decimal.NewFromInt(int64(adminData.UnusualRenewTotal)*100).Div(decimal.NewFromInt(int64(adminData.FormalCompanyTotal))).Round(2).String() + `%`
+				}
+				summaryList = append(summaryList, statistic_report.SummaryUnusualRenewRecordNum{
+					UnusualRenewNum: adminData.UnusualRenewTotal,
+					UnusualRate:     unusualRate,
+				})
+			}
+		}
+		list = append(list, statistic_report.GroupUnusualRenewRecord{
+			SellerId:                  v.AdminId,
+			SellerName:                v.RealName,
+			CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
+		})
+	}
+
+	// 汇总数据
+	for index, _ := range summaryList {
+		tmpCompanyIdList, ok := companyIdIndexMap[index]
+		if ok {
+			summaryList[index].UnusualRenewIds = strings.Join(tmpCompanyIdList, ",")
+		}
+	}
+
+	companyRenewRecordResp.List = list
+	companyRenewRecordResp.SummaryList = summaryList
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = companyRenewRecordResp
+}

+ 12 - 9
controllers/sys_menu.go

@@ -90,15 +90,18 @@ func (this *SysRoleController) SysMenuList() {
 				}
 			}
 		}
-		for i, menu := range child {
-			if menu.Name == "正式客户共享" && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN &&
-				sysUser.AdminId != 66 && sysUser.AdminId != 15 {
-				//如果不是admin角色、共享客户分组下用户、楼颖丹账号、王沛账号 就不显示该页面
-				if ok, _ := shareSellerMap[sysUser.AdminId]; !ok {
-					child = append(child[:i], child[i+1:]...)
-				}
-			}
-		}
+		//for i, menu := range child {
+		//	if menu.Name == "正式客户共享" && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN &&
+		//		sysUser.AdminId != 66 && sysUser.AdminId != 15 {
+		//		//如果不是admin角色、共享客户分组下用户、楼颖丹账号、王沛账号 就不显示该页面
+		//		if ok, _ := shareSellerMap[sysUser.AdminId]; !ok {
+		//			child = append(child[:i], child[i+1:]...)
+		//		}
+		//	}
+		//	//if menu.Name == "正式客户共享" && !utils.InArrayByStr([]string{utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_FICC_SELLER, utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM}, sysUser.RoleTypeCode) {
+		//	//	child = append(child[:i], child[i+1:]...)
+		//	//}
+		//}
 
 		if strings.Contains(item.Name, "出差管理") && sysUser.AdminId == utils.ApproveUserId {
 			cm := new(system.ChildMenu)

+ 2 - 0
models/company/company.go

@@ -285,6 +285,8 @@ type CompanyListResp struct {
 	StatusCount   []*CompanyStatus
 	TryStageCount []*CompanyTryStageCount
 	AddCompanyBtn bool
+	IsShareGroup  bool `description:"是否咨询组销售"`
+	Status        int  `description:"是否咨询组销售"`
 }
 
 func GetCompanyListCount(condition string, pars []interface{}) (count int, err error) {

+ 43 - 0
models/company/company_contract.go

@@ -65,6 +65,8 @@ type CompanyContractPermission struct {
 	EndDate           string    `description:"结束日期"`
 	CreateTime        time.Time `description:"创建时间"`
 	ModifyTime        time.Time `description:"修改时间"`
+	ContractType      string    `description:"签约合同时,当前行业类型:枚举值:'行业新签','行业续约'"`
+	PermissionName    string    `description:"权限名称"`
 }
 
 // 新增客户合同
@@ -243,6 +245,38 @@ func GetCompanyContractPermissionList(condition string, pars []interface{}) (ite
 	return
 }
 
+// UpdateCompanyContractPermissionMulti 批量修改
+func UpdateCompanyContractPermissionMulti(items []*CompanyContractPermission) (err error) {
+	o, err := orm.NewOrm().Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err == nil {
+			o.Commit()
+		} else {
+			o.Rollback()
+		}
+	}()
+
+	//批量修改公司剩余点数
+	p, err := o.Raw("UPDATE company_contract_permission SET permission_name = ? ,contract_type = ? WHERE id = ?").Prepare()
+	if err != nil {
+		return
+	}
+	defer func() {
+		_ = p.Close() // 别忘记关闭 statement
+	}()
+
+	for _, v := range items {
+		_, err = p.Exec(v.PermissionName, v.ContractType, v.Id)
+		if err != nil {
+			return
+		}
+	}
+	return
+}
+
 // 通过ID获取详情
 func GetCompanyContracDetail(condition string, pars []interface{}) (item *CompanyContractResp, err error) {
 	o := orm.NewOrm()
@@ -262,3 +296,12 @@ func UpdateCompanyContractPackageDifference(packageDifference string, companyCon
 	_, err = o.Raw(sql, packageDifference, companyContractId).Exec()
 	return
 }
+
+// GetLastContractListByEndDate 通过最近一份合同的日期获取早于该合同的最晚一份合同
+func GetLastContractListByEndDate(companyId, productId int, endDate string) (item *CompanyContract, err error) {
+	o := orm.NewOrm()
+	sql := "SELECT * FROM company_contract where company_id = ? AND product_id= ? end_date < ? AND status = 1 ORDER BY end_date desc"
+	err = o.Raw(sql, companyId, productId, endDate).QueryRow(&item)
+
+	return
+}

+ 17 - 91
models/company/company_contract_merge.go

@@ -6,24 +6,6 @@ import (
 	"time"
 )
 
-type CompanyContractMerge struct {
-	CompanyContractMergeId int       `orm:"column(company_contract_merge_id);pk" description:"主键ID"`
-	ContractType           string    `description:"合同类型:枚举值:'新签合同','续约合同','补充协议'"`
-	ProductId              int       `description:"产品id"`
-	ProductName            string    `description:"产品名称"`
-	CompanyId              int       `description:"客户id"`
-	CompanyProductId       int       `description:"客户产品id"`
-	StartDate              string    `description:"合同开始时间"`
-	EndDate                string    `description:"合同结束时间"`
-	Money                  float64   `description:"合同金额"`
-	CreateTime             time.Time `description:"合同创建时间"`
-	ModifyTime             time.Time `description:"合同修改时间"`
-	CompanyContractIdGroup string    `description:"表company_contract合并的 company_contract_id"`
-	ChartPermissionName    string    `description:"权限类目名称"`
-	PackageDifference      string    `description:"和上一份合同的区别"`
-	IsBestNew              int       `description:"是否是最新的一条数据"`
-}
-
 type CompanyContractMergeResp struct {
 	CompanyContractMergeId int       `orm:"column(company_contract_merge_id);pk" description:"主键ID"`
 	ContractType           string    `description:"合同类型:枚举值:'新签合同','续约合同','补充协议'"`
@@ -59,56 +41,6 @@ type CompanyContractMergeDetailResp struct {
 	PermissionName         string    `description:"权限名"`
 }
 
-func AddCompanyContractMerge(item *CompanyContractMerge) (err error) {
-	o := orm.NewOrm()
-	_, err = o.Insert(item)
-	return
-}
-
-// MultiAddCompanyContractMerge 批量添加合同合并之后的数据
-func MultiAddCompanyContractMerge(items []*CompanyContractMerge) (err error) {
-	if len(items) == 0 {
-		return
-	}
-	o := orm.NewOrm()
-	_, err = o.InsertMulti(len(items), items)
-	return
-}
-
-// 修改
-func UpdateCompanyContractMerge(item *CompanyContractMerge) (err error) {
-	o := orm.NewOrm()
-	to, err := o.Begin()
-	if err != nil {
-		return
-	}
-	defer func() {
-		if err != nil {
-			_ = to.Rollback()
-		} else {
-			_ = to.Commit()
-		}
-	}()
-	updateParams := make(map[string]interface{})
-	updateParams["EndDate"] = item.EndDate
-	updateParams["Money"] = item.Money
-	updateParams["CompanyContractIdGroup"] = item.CompanyContractIdGroup
-	updateParams["PackageDifference"] = item.PackageDifference
-	updateParams["IsBestNew"] = item.IsBestNew
-	updateParams["ModifyTime"] = item.ModifyTime
-	ptrStructOrTableName := "company_contract_merge"
-	whereParam := map[string]interface{}{"company_contract_merge_id": item.CompanyContractMergeId}
-	qs := to.QueryTable(ptrStructOrTableName)
-	for expr, exprV := range whereParam {
-		qs = qs.Filter(expr, exprV)
-	}
-	_, err = qs.Update(updateParams)
-	if err != nil {
-		return
-	}
-	return
-}
-
 // GetIncrementalNewCompanyProductMergeCount 获取增量客户产品报表列表统计数据(根据合同来展示)
 func GetIncrementalNewCompanyProductMergeCount(condition string, pars []interface{}) (total int, err error) {
 	o := orm.NewOrm()
@@ -145,26 +77,20 @@ type GetCompanyContractMergeDetailResp struct {
 	Detail *CompanyContractMergeDetailResp
 }
 
-// 通过ID获取详情
-//func GetCompanyContractMergeDetail(condition string, pars []interface{}) (item *CompanyContractMergeDetailResp, err error) {
-//	o := orm.NewOrm()
-//	sql := `SELECT * FROM company_contract_merge  WHERE 1= 1 ` + condition
-//	err = o.Raw(sql, pars).QueryRow(&item)
-//	return
-//}
-//
-//// UpdateCompanyContractMergeIsBestNew 更改 is_best_new 状态
-//func UpdateCompanyContractMergeIsBestNew(isBestNew, companyId int) (err error) {
-//	o := orm.NewOrm()
-//	sql := `UPDATE company_contract_merge SET is_best_new = ?  WHERE company_id=? `
-//	_, err = o.Raw(sql, isBestNew, companyId).Exec()
-//	return
-//}
-//
-//// UpdateCompanyContractMergeIsBestNew 更改 is_best_new 状态
-//func UpdateCompanyContractMergeIsBestNewto1(companyContractMergeId int) (err error) {
-//	o := orm.NewOrm()
-//	sql := `UPDATE company_contract_merge SET is_best_new = 1  WHERE company_contract_merge_id=? `
-//	_, err = o.Raw(sql, companyContractMergeId).Exec()
-//	return
-//}
+// GetIncrementalNewCompanyProductMergeCount 获取增量客户产品报表列表统计数据(根据合同来展示)
+func GetIncrementalNewCompanyProductPermissionCount(condition string, pars []interface{}) (total int, err error) {
+	o := orm.NewOrm()
+
+	sql := `SELECT a.*,b.region_type,c.seller_id,c.seller_name,b.company_name FROM company_contract a
+		 JOIN company b ON a.company_id = b.company_id
+		 JOIN company_product c ON a.company_id = c.company_id and a.product_id=c.product_id
+		 JOIN company_contract_permission d ON d.company_contract_id = a.company_contract_id
+		 WHERE 1 = 1  `
+
+	if condition != "" {
+		sql += condition
+	}
+	sql = `select count(1) count from (` + sql + ` GROUP BY d.company_contract_id,d.permission_name  ) f`
+	err = o.Raw(sql, pars).QueryRow(&total)
+	return
+}

+ 151 - 0
models/company/company_contract_no_renewed_ascribe.go

@@ -0,0 +1,151 @@
+package company
+
+//合同未续约说明
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+type CompanyContractNoRenewedAscribe struct {
+	NoRenewedAscribeId int       `orm:"column(no_renewed_ascribe_id);pk" description:"主键ID"`
+	CompanyAscribeId   int       `description:"归因ID"`
+	AscribeContent     string    `description:"归因说明"`
+	Content            string    `description:"内容说明"`
+	AdminId            int       `description:"管理员ID"`
+	CompanyId          int       `description:"公司ID"`
+	CompanyContractId  int       `description:"合同id"`
+	ProductId          int       `description:"产品id"`
+	CreateTime         time.Time `description:"创建时间"`
+	ModifyTime         time.Time `description:"更新时间"`
+}
+
+type CompanyContractNoRenewedAscribeLog struct {
+	NoRenewedAscribeId int       `orm:"column(no_renewed_ascribe_id);pk" description:"主键ID"`
+	CompanyAscribeId   int       `description:"归因ID"`
+	AscribeContent     string    `description:"归因说明"`
+	Content            string    `description:"内容说明"`
+	AdminId            int       `description:"管理员ID"`
+	CompanyId          int       `description:"公司ID"`
+	CompanyContractId  int       `description:"合同id"`
+	ProductId          int       `description:"产品id"`
+	CreateTime         time.Time `description:"创建时间"`
+	ModifyTime         time.Time `description:"更新时间"`
+}
+
+type CompanyContractNoRenewedAscribeResp struct {
+	NoRenewedAscribeId int    `description:"主键ID"`
+	CompanyAscribeId   int    `description:"归因ID"`
+	AscribeContent     string `description:"归因说明"`
+	ProductId          int    `description:"产品id"`
+	Content            string `description:"内容说明"`
+	AdminId            int    `description:"管理员ID"`
+	CompanyId          int    `description:"公司ID"`
+	CompanyContractId  int    `description:"合同id"`
+	CreateTime         string `description:"创建时间"`
+	ModifyTime         string `description:"更新时间"`
+}
+type CompanyContractNoRenewedAscribeListResp struct {
+	List []*CompanyContractNoRenewedAscribeResp
+}
+
+type CompanyContractNoRenewedAscribeDetailResp struct {
+	Detail *CompanyContractNoRenewedAscribeResp
+}
+
+type CompanyContractNoRenewedAscribeReq struct {
+	CompanyAscribeId  int    `description:"归因ID"`
+	ProductId         int    `description:"产品id"`
+	Content           string `description:"内容说明"`
+	CompanyId         int    `description:"公司ID"`
+	CompanyContractId int    `description:"合同id"`
+}
+
+// 添加
+func AddCompanyContractNoRenewedAscribe(item *CompanyContractNoRenewedAscribe, itemLog *CompanyContractNoRenewedAscribeLog) (err error) {
+	o := orm.NewOrm()
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	_, err = to.Insert(item)
+	if err != nil {
+		return
+	}
+
+	_, err = to.Insert(itemLog)
+	return
+}
+
+// 修改
+func UpdateCompanyContractNoRenewedAscribe(item *CompanyContractNoRenewedAscribe, itemLog *CompanyContractNoRenewedAscribeLog) (err error) {
+	o := orm.NewOrm()
+	to, err := o.Begin()
+	if err != nil {
+		return
+	}
+	defer func() {
+		if err != nil {
+			_ = to.Rollback()
+		} else {
+			_ = to.Commit()
+		}
+	}()
+	updateParams := make(map[string]interface{})
+	updateParams["CompanyAscribeId"] = item.CompanyAscribeId
+	updateParams["ModifyTime"] = item.ModifyTime
+	updateParams["Content"] = item.Content
+	updateParams["AscribeContent"] = item.AscribeContent
+	ptrStructOrTableName := "company_contract_no_renewed_ascribe"
+	whereParam := map[string]interface{}{"company_id": item.CompanyId, "company_contract_id": item.CompanyContractId}
+	qs := to.QueryTable(ptrStructOrTableName)
+	for expr, exprV := range whereParam {
+		qs = qs.Filter(expr, exprV)
+	}
+	_, err = qs.Update(updateParams)
+	if err != nil {
+		return
+	}
+	_, err = to.Insert(itemLog)
+	return
+}
+
+// 获取数量
+func GetCompanyContractNoRenewedAscribeCount(condition string, pars []interface{}) (count int, err error) {
+	sqlCount := ` SELECT COUNT(1) AS count  FROM company_contract_no_renewed_ascribe as a WHERE 1= 1  `
+	if condition != "" {
+		sqlCount += condition
+	}
+	o := orm.NewOrm()
+	err = o.Raw(sqlCount, pars).QueryRow(&count)
+	return
+}
+
+// 通过ID获取详情
+func GetCompanyContractNoRenewedAscribeDetail(companyContractId int) (item *CompanyContractNoRenewedAscribeResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM company_contract_no_renewed_ascribe   WHERE company_contract_id=?  `
+	err = o.Raw(sql, companyContractId).QueryRow(&item)
+	return
+}
+
+// 列表
+func GetCompanyContractNoRenewedAscribeList(condition string, pars []interface{}, startSize, pageSize int) (items []*CompanyContractNoRenewedAscribeResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT * FROM company_contract_no_renewed_ascribe as a  WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	if startSize+pageSize > 0 {
+		sql += ` LIMIT ?,?  `
+		_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}

+ 1 - 1
models/company/company_no_renewed_ascribe.go

@@ -123,7 +123,7 @@ func GetCompanyNoRenewedAscribeCount(condition string, pars []interface{}) (coun
 }
 
 // 通过ID获取详情
-func GetCygxProductInteriorDetail(companyId, productId int) (item *CompanyNoRenewedAscribeResp, err error) {
+func GetCompanyNoRenewedAscribeDetail(companyId, productId int) (item *CompanyNoRenewedAscribeResp, err error) {
 	o := orm.NewOrm()
 	sql := `SELECT * FROM company_no_renewed_ascribe   WHERE company_id=?  AND product_id = ? `
 	err = o.Raw(sql, companyId, productId).QueryRow(&item)

+ 64 - 0
models/company/company_product.go

@@ -581,3 +581,67 @@ func GetCompanyProductListBycondition(condition string, pars []interface{}) (ite
 	_, err = o.Raw(sql, pars).QueryRows(&items)
 	return
 }
+
+// CompanyProductItem
+// @Description: 客户品种
+type CompanyProductItem struct {
+	CompanyProductId int       `orm:"column(company_product_id);pk" description:"客户产品id"`
+	CompanyId        int       `description:"客户id"`
+	ProductId        int       `description:"产品id"`
+	ProductName      string    `description:"产品名称"`
+	CompanyName      string    `description:"客户名称"`
+	Source           string    `description:"来源"`
+	Reasons          string    `description:"新增理由"`
+	Status           string    `description:"客户状态"`
+	IndustryId       int       `description:"行业id"`
+	IndustryName     string    `description:"行业名称"`
+	SellerId         int       `description:"销售id"`
+	SellerName       string    `description:"销售名称"`
+	GroupId          int       `description:"销售分组id"`
+	DepartmentId     int       `description:"销售部门id"`
+	IsSuspend        int       `description:"1:暂停,0:启用"`
+	SuspendTime      time.Time `description:"暂停启用时间"`
+	ApproveStatus    string    `description:"审批状态:'审批中','通过','驳回'"`
+	FreezeTime       time.Time `description:"冻结时间"`
+	Remark           string    `description:"备注信息"`
+	CreateTime       time.Time `description:"创建时间"`
+	ModifyTime       time.Time `description:"修改时间"`
+	StartDate        string    `description:"开始日期"`
+	EndDate          string    `description:"结束日期"`
+	ContractEndDate  string    `description:"合同结束日期"`
+	LoseReason       string    `description:"流失原因"`
+	LossTime         time.Time `description:"流失时间"`
+	CompanyType      string    `description:"客户类型"`
+	OpenCode         string    `description:"开放给第三方的编码,不让第三方定位我们的客户信息"`
+	Scale            string    `description:"管理规模,空不填,1::50亿以下,2:50~100亿,3:100亿以上。"`
+	ViewTotal        int       `description:"总阅读次数"`
+	RoadShowTotal    int       `description:"累计路演次数"`
+	LastViewTime     time.Time `description:"最后一次阅读时间"`
+	PackageType      int       `description:"套餐类型,0:无,1:大套餐,2:小套餐"`
+	IsFormal         int       `description:"是否已经转正式,0是没有转正式,1是已经转过正式"`
+	TodoStatus       string    `description:"任务处理状态;枚举值:'无任务','未完成','已完成'"`
+	TodoCreateTime   time.Time `description:"任务创建时间"`
+	TodoApproveTime  time.Time `description:"任务审批时间"`
+	TryStage         int       `description:"试用客户子标签:1未分类、2  推进、3 跟踪、4 预备"`
+	IsShare          int       `description:"0:非共享用户,1:共享客户"`
+	ShareSeller      string    `description:"共享销售员"`
+	ShareSellerId    int       `description:"共享销售员id"`
+}
+
+// GetCompanyProductItemByCompanyId
+// @Description: 根据客户ID获取客户产品列表
+// @author: Roc
+// @datetime 2023-12-07 11:06:58
+// @param companyIdList []int
+// @param productId int
+// @return items []*CompanyProductItem
+// @return err error
+func GetCompanyProductItemByCompanyId(companyId int, productId int) (items *CompanyProductItem, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT a.*,b.is_share,b.share_seller,b.share_seller_id FROM company_product as a 
+         JOIN company b on a.company_id=b.company_id
+         WHERE a.company_id = ? AND a.product_id = ? `
+	_, err = o.Raw(sql, companyId, productId).QueryRows(&items)
+
+	return
+}

+ 69 - 0
models/company/company_renewal_record.go

@@ -0,0 +1,69 @@
+package company
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// CompanyRenewalRecord
+// @Description: 客户续约状态记录表
+type CompanyRenewalRecord struct {
+	Id              int       `orm:"column(id);pk"`
+	CompanyId       int       `description:"客户id"`
+	ProductId       int       `description:"产品id"`
+	Source          int       `description:"类型,枚举值,1:续约异常客户;2:续约正常客户;3:超时续约客户"`
+	SellerId        int       `description:"销售id"`
+	SellerName      string    `description:"销售名称"`
+	ShareSellerId   int       `description:"共享销售id"`
+	ShareSellerName string    `description:"共享销售名称"`
+	CreateTime      time.Time `description:"创建时间"`
+	ModifyTime      time.Time `description:"修改时间"`
+}
+
+type UnusualRenewCompanyGroup struct {
+	SellerId      int `description:"所属销售id"`
+	ShareSellerId int `description:"所属共享销售id"`
+	//AdminName string `description:"所属销售名称"`
+	Num        int    `description:"汇总次数"`
+	CompanyIds string `description:"客户id字符串"`
+}
+
+// GetUnusualRenewCompanyList 获取销售未续约数据
+func GetUnusualRenewCompanyList(startDate, endDate time.Time, productId int) (list []*UnusualRenewCompanyGroup, err error) {
+	o := orm.NewOrm()
+	sql := `	SELECT
+	a.seller_id,a.share_seller_id,
+	count(
+	DISTINCT ( a.company_id )) num,
+	GROUP_CONCAT( DISTINCT a.company_id SEPARATOR ',' ) AS company_ids 
+	FROM
+	company_renewal_record as a
+WHERE
+	a.modify_time BETWEEN ? 
+	AND ? 
+    AND a.source = 1 
+	AND a.product_id = ?
+GROUP BY
+	a.seller_id;
+`
+	_, err = o.Raw(sql, startDate, endDate, productId).QueryRows(&list)
+
+	return
+}
+
+// Add
+// @Description: 添加续约用户记录
+// @author: Roc
+// @datetime 2023-12-07 14:16:37
+// @param item *CompanyRenewalRecord
+// @return err error
+func (item *CompanyRenewalRecord) Add() (err error) {
+	o := orm.NewOrm()
+	lastId, err := o.Insert(item)
+	if err != nil {
+		return
+	}
+	item.Id = int(lastId)
+
+	return
+}

+ 4 - 1
models/company/company_user.go

@@ -61,12 +61,14 @@ type CompanyUser struct {
 	IsChartPermissionSetting int       `description:"是否设置过图表权限, 0-未设置,1-已设置,2-无需设置"`
 	YbProductViewTotal       int       `description:"研报分产品阅读统计"`
 	IsSubscribe              int       `description:"是否关注了微信公众号: 0-未关注; 1-已关注"`
+	IsFollow                 int       `description:"是否特别关注: 0-未关注; 1-已关注"`
 	IsSubscribeHzyj          int       `description:"是否关注了弘则研究微信公众号: 0-未关注; 1-已关注"`
 	IsSubscribeCygx          int       `description:"是否关注了查研观向微信公众号: 0-未关注; 1-已关注"`
 	FiccViewTotal            int       `description:"ficc报告的阅读次数" json:"-"`
 	FiccLastViewTime         time.Time `description:"ficc报告最近一次阅读时间" json:"-"`
 	RaiViewTotal             int       `description:"权益报告的阅读次数" json:"-"`
 	RaiLastViewTime          time.Time `description:"权益报告的最近一次阅读时间" json:"-"`
+	NotRead                  bool      `description:"是否七天内未阅读"`
 }
 
 type CompanyUserListResp struct {
@@ -138,7 +140,8 @@ func GetCompanyUserListV2(condition string, pars []interface{}, companyId, start
 	if condition != "" {
 		sql += condition
 	}
-	sql += ` group by a.user_id ORDER BY a.is_register desc,a.report_last_view_time desc,a.last_updated_time DESC LIMIT ?,? `
+	//sql += ` group by a.user_id ORDER BY a.is_register desc,a.report_last_view_time desc,a.last_updated_time DESC LIMIT ?,? `
+	sql += ` group by a.user_id ORDER BY CASE WHEN is_follow = 1 AND (report_last_view_time < NOW()  - INTERVAL 7 DAY or report_last_view_time is NULL ) THEN 0 ELSE 1 END,a.is_register desc,a.report_last_view_time ASC,a.last_updated_time  ASC LIMIT ?,? `
 	_, err = o.Raw(sql, companyId, pars, startSize, pageSize).QueryRows(&items)
 	return
 }

+ 7 - 0
models/company_user/request/follow.go

@@ -0,0 +1,7 @@
+package request
+
+type FollowReq struct {
+	UserId    int `description:"用户ID"`
+	CompanyId int `description:"公司ID"`
+	Type      int `description:"类型 0取关 1关注"`
+}

+ 63 - 0
models/contract/contract.go

@@ -579,3 +579,66 @@ func GetContractListByCompanyName(companyName string) (item *ContractList, err e
 	err = o.Raw(sql, companyName).QueryRow(&item)
 	return
 }
+
+type RenewCompanyGroup struct {
+	SellerId int `description:"所属销售id"`
+	//AdminName string `description:"所属销售名称"`
+	Num        int    `description:"汇总次数"`
+	CompanyIds string `description:"客户id字符串"`
+}
+
+// GetExpiresCompanyGroupList 获取销售到期数据
+func GetExpiresCompanyGroupList(startDate, endDate time.Time, productId int) (list []*RenewCompanyGroup, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+	a.seller_id,
+	count(
+	DISTINCT ( a.company_id )) num,
+	GROUP_CONCAT( DISTINCT a.company_id SEPARATOR ',' ) AS company_ids 
+FROM
+	company_product as a 
+join company_contract as b on a.company_id=b.company_id and a.product_id=b.product_id
+WHERE
+	a.product_id=?
+AND	b.product_id=?
+AND
+	b.end_date >= ?
+	AND b.end_date < ? 
+AND b.status = 1
+GROUP BY
+	a.seller_id
+`
+	_, err = o.Raw(sql, productId, productId, startDate, endDate).QueryRows(&list)
+
+	return
+}
+
+// GetCountFormalCompany
+// @Description: 获取某个时间点前的合同客户数量
+// @author: Roc
+// @datetime 2023-12-05 09:36:28
+// @param endDate time.Time
+// @param productId int
+// @return total int
+// @return err error
+func GetCountFormalCompany(endDate time.Time, productId int) (total int, err error) {
+	o := orm.NewOrm()
+	sql := `select count(1) total from (
+    SELECT
+	a.seller_id
+FROM
+	company_product as a 
+join company_contract as b on a.company_id=b.company_id and a.product_id=b.product_id
+WHERE
+	a.product_id=?
+AND	b.product_id=?
+	AND b.end_date < ? 
+AND b.status = 1
+GROUP BY
+	a.company_id
+) z
+`
+	err = o.Raw(sql, productId, productId, endDate).QueryRow(&total)
+
+	return
+}

+ 1 - 0
models/cygx/activity_meet.go

@@ -466,6 +466,7 @@ func GetCygxActivityYiDongMeetNum(activityId []int) (items []*CygxAtivityIdMeetN
 
 type GetSellerUserMobileResp struct {
 	Mobile string `description:"手机号"`
+	UserId int    `description:"用户ID"`
 }
 
 // 获取销售所能查看到的手机号

+ 1 - 0
models/cygx/activity_special.go

@@ -95,6 +95,7 @@ type ActivitySpecialDetail struct {
 	DateYmdList           []*DateYmdList `description:"时间年月日"`
 	IsSubmitMeeting       int            `description:"是否提交过到会信息 ,1是,0否"`
 	LastUpdatedTime       time.Time      `description:"更新时间"`
+	PublishDate           string         `description:"发布时间"`
 }
 
 type ActivityDetailSpecialRep struct {

+ 19 - 18
models/cygx/activity_special_trip_bill.go

@@ -6,24 +6,25 @@ import (
 )
 
 type CygxActivitySpecialTripBill struct {
-	Id                int       `orm:"column(id);pk"`
-	UserId            int       `description:"用户id,多个用,隔开"`
-	ActivityId        int       `description:"活动ID"`
-	CreateTime        time.Time `description:"创建时间"`
-	Mobile            string    `description:"手机号"`
-	Email             string    `description:"邮箱号"`
-	CompanyId         int       `description:"公司ID"`
-	CompanyName       string    `description:"公司名称"`
-	RealName          string    `description:"用户实际名称"`
-	AdminId           int       `description:"销售/管理员ID"`
-	Source            int       `description:"来源,1小程序,2后台添加, 3开发人员手动添加"`
-	BillDetailed      int       `description:"流水明细,判断是进账还是出账"`
-	DoType            int       `description:"操作方式,1报名,2取消报名"`
-	RegisterPlatform  int       `description:"来源 1小程序,2:网页"`
-	ChartPermissionId int       `description:"行业id"`
-	Way               int       `description:"1报名,取消报名。2到会取消到会 3转正或清零 4取消活动"`
-	Content           string    `description:"内容"`
-	Total             string    `description:"总和"`
+	Id                  int       `orm:"column(id);pk"`
+	UserId              int       `description:"用户id,多个用,隔开"`
+	ActivityId          int       `description:"活动ID"`
+	CreateTime          time.Time `description:"创建时间"`
+	Mobile              string    `description:"手机号"`
+	Email               string    `description:"邮箱号"`
+	CompanyId           int       `description:"公司ID"`
+	CompanyName         string    `description:"公司名称"`
+	RealName            string    `description:"用户实际名称"`
+	AdminId             int       `description:"销售/管理员ID"`
+	Source              int       `description:"来源,1小程序,2后台添加, 3开发人员手动添加"`
+	BillDetailed        int       `description:"流水明细,判断是进账还是出账"`
+	DoType              int       `description:"操作方式,1报名,2取消报名"`
+	RegisterPlatform    int       `description:"来源 1小程序,2:网页"`
+	ChartPermissionId   int       `description:"行业id"`
+	ChartPermissionName string    `description:"行业名称"`
+	Way                 int       `description:"1报名,取消报名。2到会取消到会 3转正或清零 4取消活动"`
+	Content             string    `description:"内容"`
+	Total               string    `description:"总和"`
 }
 
 type CygxActivitySpecialTripBillList struct {

+ 1 - 0
models/cygx/apply_record.go

@@ -37,6 +37,7 @@ type CygxApplyRecord struct {
 
 type CygxApplyRecordResp struct {
 	ApplyRecordId            int    `orm:"column(apply_record_id);pk" description:"申请试用id"`
+	UserId                   int    `description:"用户ID"`
 	BusinessCardUrl          string `description:"名片地址"`
 	RealName                 string `description:"姓名"`
 	CompanyName              string `description:"公司名称"`

+ 78 - 0
models/cygx/article_and_yanxuan_record.go

@@ -0,0 +1,78 @@
+package cygx
+
+import (
+	"fmt"
+	"github.com/beego/beego/v2/client/orm"
+	"hongze/hz_crm_api/utils"
+)
+
+type CygxArticleAndYanxuanRecordResp struct {
+	Id               int    `orm:"column(id);pk"`
+	SourceId         int    `description:"资源ID"`
+	Source           string `description:"资源I类型  文章、研选专栏"`
+	UserId           int    `description:"用户ID"`
+	CreateTime       string `description:"创建时间"`
+	Mobile           string `description:"手机号"`
+	Email            string `description:"邮箱"`
+	CompanyId        int    `description:"公司id"`
+	CompanyName      string `description:"公司名称"`
+	ModifyTime       string `description:"修改时间"`
+	RealName         string `description:"用户实际名称"`
+	SellerName       string `description:"所属销售"`
+	StopTime         int    `description:"停留时间"`
+	RegisterPlatform int    `description:"来源 1小程序,2:网页"`
+}
+
+// 获取数量
+func GetCygxArticleAndYanxuanRecordCount(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_article_and_yanxuan_record as r WHERE 1= 1  `
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount, pars).QueryRow(&count)
+	return
+}
+
+// 获取数量(关联用户跟销售的绑定关系跨库查询)
+func GetCygxArticleAndYanxuanRecordCountWeekly(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_article_and_yanxuan_record as r 
+				  INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+		WHERE 1= 1  `
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount, pars).QueryRow(&count)
+	return
+}
+
+// 列表
+func GetCygxArticleAndYanxuanRecordRespList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxArticleAndYanxuanRecordResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_article_and_yanxuan_record as r WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,?  `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// 列表(关联用户跟销售的绑定关系跨库查询)
+func GetCygxArticleAndYanxuanRecordRespListWeekly(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxArticleAndYanxuanRecordResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT r.* FROM cygx_article_and_yanxuan_record as r 
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+		WHERE 1= 1   `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,?  `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}

+ 46 - 15
models/cygx/chart.go

@@ -1,9 +1,11 @@
 package cygx
 
 import (
+	"fmt"
 	"github.com/beego/beego/v2/client/orm"
 	"github.com/rdlucklib/rdluck_tools/paging"
 	"hongze/hz_crm_api/models/company"
+	"hongze/hz_crm_api/utils"
 	"strconv"
 	"time"
 )
@@ -261,6 +263,20 @@ func GetChartCountByUserMobile(condition string) (count int, err error) {
 	return
 }
 
+func GetChartCountByUserMobileWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT COUNT(1) AS count FROM cygx_chart_collect as r  INNER JOIN cygx_chart_all AS a ON a.chart_id = r.chart_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+WHERE 1= 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	err = o.Raw(sql).QueryRow(&count)
+	return
+}
+
 type CygxChartCollect struct {
 	Mobile string `description:"手机号"`
 	UserId int    `description:"手机号"`
@@ -268,13 +284,6 @@ type CygxChartCollect struct {
 
 // 获取图表列表
 func GetChartCollectList(condition string) (items []*UserInteraction, err error) {
-	//o := orm.NewOrm()
-	//sql := `SELECT u.mobile,u.user_id,u.real_name FROM cygx_chart_collect AS r
-	//		INNER JOIN wx_user AS u ON u.mobile = r.mobile
-	//		LEFT  JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
-	//		WHERE 1= 1 ` + condition + `   GROUP BY r.mobile  ORDER BY ui.chart_count_num DESC `
-	//_, err = o.Raw(sql).QueryRows(&items)
-
 	o := orm.NewOrmUsingDB("hz_cygx")
 	sql := `SELECT  *  FROM cygx_chart_collect AS r
 			WHERE 1= 1 ` + condition + `   GROUP BY r.mobile `
@@ -282,17 +291,22 @@ func GetChartCollectList(condition string) (items []*UserInteraction, err error)
 	return
 }
 
+// 获取图表列表(关联用户跟销售的绑定关系跨库查询)
+func GetChartCollectListWeekly(condition string) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT  r.*  FROM cygx_chart_collect AS r
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2
+			WHERE 1= 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	sql += condition + `   GROUP BY r.mobile `
+	_, err = o.Raw(sql).QueryRows(&items)
+	return
+}
+
 // 获取图表列表
 func GetChartCollectBycompanyList(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
-	//sql := `SELECT u.mobile,u.user_id,u.real_name,r.company_name,
-	//		cp.seller_name FROM cygx_chart_collect AS r
-	//		INNER JOIN wx_user AS u ON u.user_id = r.user_id
-	//		INNER  JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
-	//		LEFT JOIN company_product AS cp ON cp.company_id = r.company_id AND cp.product_id = 2
-	//		INNER JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
-	//		WHERE 1= 1 ` + condition + `   GROUP BY r.mobile  ORDER BY ci.chart_count_num DESC , ui.chart_count_num DESC `
-
 	sql := `SELECT r.*
 			FROM cygx_chart_collect AS r
 			WHERE 1= 1 ` + condition + `   GROUP BY r.mobile   `
@@ -303,6 +317,23 @@ func GetChartCollectBycompanyList(condition string, startSize, pageSize int) (it
 	return
 }
 
+// 获取图表列表
+func GetChartCollectBycompanyListWeekly(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT r.*
+			FROM cygx_chart_collect AS r
+		    INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2
+			WHERE 1= 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	sql += `   GROUP BY r.mobile   `
+	if startSize > 0 || pageSize > 0 {
+		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
+	}
+	_, err = o.Raw(sql).QueryRows(&items)
+	return
+}
+
 // 获取一共有多少用户收藏图表
 func GetChartCountByUserCount(condition string) (count int, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")

+ 7 - 0
models/cygx/config.go

@@ -49,3 +49,10 @@ func CygxConfigUpdateByCode(configValue, newValue string) (err error) {
 	_, err = o.Raw(sql, configValue, newValue).Exec()
 	return
 }
+
+func GetConfigByCode(configCode string) (item *CygxConfig, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_config WHERE config_code=? `
+	err = o.Raw(sql, configCode).QueryRow(&item)
+	return
+}

+ 13 - 13
models/cygx/cygx_tag.go

@@ -43,17 +43,17 @@ func (m *CygxTag) Update(cols []string) (err error) {
 
 type CygxTagList struct {
 	TagId         int64  `orm:"column(tag_id);pk"`
-	TagName       string `orm:"column(tag_name);NOT NULL"`       // 标签名
-	ArticleTypes  string `orm:"column(article_types);NOT NULL"`  // 报告系列
-	ActivityTypes string `orm:"column(activity_types);NOT NULL"` // 活动类型
-	Industries    string `orm:"column(industries);NOT NULL"`     // 产业
-	SubjectNames  string `orm:"column(subject_names);NOT NULL"`  // 标的
-	Sort          int    `orm:"column(sort);"`                   // 优先级
-	ModifyTime    string `orm:"column(modify_time)"`             // 修改时间
-	CreateTime    string `orm:"column(create_time)"`             // 创建时间
-	OnlineTime    string `orm:"column(online_time)"`             // 上线时间
-	OfflineTime   string `orm:"column(offline_time)"`            // 下线时间
-	Status        int    `orm:"column(status);NOT NULL"`         // 状态:0-禁用 1-启用
+	TagName       string `orm:"column(tag_name);"`       // 标签名
+	ArticleTypes  string `orm:"column(article_types);"`  // 报告系列
+	ActivityTypes string `orm:"column(activity_types);"` // 活动类型
+	Industries    string `orm:"column(industries);"`     // 产业
+	SubjectNames  string `orm:"column(subject_names);"`  // 标的
+	Sort          int    `orm:"column(sort);"`           // 优先级
+	ModifyTime    string `orm:"column(modify_time)"`     // 修改时间
+	CreateTime    string `orm:"column(create_time)"`     // 创建时间
+	OnlineTime    string `orm:"column(online_time)"`     // 上线时间
+	OfflineTime   string `orm:"column(offline_time)"`    // 下线时间
+	Status        int    `orm:"column(status);"`         // 状态:0-禁用 1-启用
 	Pv            int    `description:"PV"`
 	Uv            int    `description:"UV"`
 	TagType       int    `description:"1:热门活动、2:海外研究、3:路演回放、4:语音问答"`
@@ -98,8 +98,8 @@ func GetCygxTagListCountByCondition(condition string, pars []interface{}) (count
 func GetCygxTagListPage(cond string, startSize, pageSize int) (items []*CygxTagList, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
 	sql := `SELECT *,
-		(SELECT COUNT(1) FROM cygx_tag_history AS avr WHERE avr.tag_id=cygx_tag.tag_id) AS pv,
-        (SELECT COUNT(DISTINCT user_id) FROM cygx_tag_history AS avr WHERE avr.tag_id=cygx_tag.tag_id) AS uv
+		(SELECT COUNT(1) FROM cygx_tag_history AS avr WHERE avr.tag_id=cygx_tag.tag_id AND avr.company_id != 16  ) AS pv,
+        (SELECT COUNT(DISTINCT user_id) FROM cygx_tag_history AS avr WHERE avr.tag_id=cygx_tag.tag_id AND avr.company_id != 16 ) AS uv
 		FROM cygx_tag  WHERE 1=1 `
 	if cond != "" {
 		sql += cond

+ 82 - 63
models/cygx/cygx_user.go

@@ -4,47 +4,50 @@ import (
 	"github.com/beego/beego/v2/client/orm"
 	"github.com/rdlucklib/rdluck_tools/paging"
 	"hongze/hz_crm_api/models/company"
+	"hongze/hz_crm_api/utils"
 	"strconv"
 	"strings"
 	"time"
 )
 
 type CygxCompanyUser struct {
-	UserId                int64  `orm:"column(user_id);pk"`
-	Mobile                string `description:"手机号"`
-	Email                 string `description:"邮箱"`
-	CompanyId             int    `description:"公司id"`
-	CompanyName           string `description:"公司名称"`
-	RealName              string `description:"姓名"`
-	CreatedTime           string `description:"创建时间"`
-	IsMaker               int    `description:"是否决策人,1:是,0:否"`
-	IsRegister            bool   `description:"是否注册,true:已注册,false:未注册"`
-	Status                string `description:"客户状态"`
-	RegisterTime          string `description:"注册时间"`
-	SellerName            string `description:"销售名称"`
-	InteractionNum        int    `description:"互动量"`
-	CompanyInteractionNum int    `description:"企业互动量"`
-	Labels                string `description:"标签,用英文,隔开"`
-	ActivityLabel         string `description:"活动标签,用英文,隔开"`
-	IsShowSee             bool   `description:"是否展示查看"`
-	IsShowSeeNum          int    `description:"是否展示查看"`
-	HistoryNum            int    `description:"报告阅读"`
-	CountNum              int    `description:"报告收藏"`
-	IndustryFllowNum      int    `description:"产业关注"`
-	DepartmentFollowNum   int    `description:"作者关注"`
-	KeyWordNum            int    `description:"搜索关键词"`
-	OnLineNum             int    `description:"线上互动活动"`
-	OfficeNum             int    `description:"线下互动活动"`
-	ChartNum              int    `description:"图表收藏数量"`
-	TripNum               int    `description:"图表数量"`
-	RoadshowVideoNum      int    `description:"产业视频播放量"`
-	ActivityVideoNum      int    `description:"活动视频播放量"`
-	ActivityVoiceNum      int    `description:"活动音频播放量"`
-	PackageType           int    `description:"套餐类型,0:无,1:大套餐,2:小套餐"`
-	TryStage              int    `description:"试用客户子标签:0全部、1未分类、2 推进、3 跟踪、4 预备"`
-	Content               string `description:"备注信息"`
-	IsRemind              bool   `description:"是否添加互动提醒"`
-	IsSubscribeCygx       int    `description:"是否关注了查研观向微信公众号: 0-未关注; 1-已关注"`
+	UserId                      int64  `orm:"column(user_id);pk"`
+	Mobile                      string `description:"手机号"`
+	Email                       string `description:"邮箱"`
+	CompanyId                   int    `description:"公司id"`
+	CompanyName                 string `description:"公司名称"`
+	RealName                    string `description:"姓名"`
+	CreatedTime                 string `description:"创建时间"`
+	IsMaker                     int    `description:"是否决策人,1:是,0:否"`
+	IsRegister                  bool   `description:"是否注册,true:已注册,false:未注册"`
+	Status                      string `description:"客户状态"`
+	RegisterTime                string `description:"注册时间"`
+	SellerName                  string `description:"销售名称"`
+	InteractionNum              int    `description:"互动量"`
+	CompanyInteractionNum       int    `description:"企业互动量"`
+	CompanyInteractionNumSeller int    `description:"销售可见企业互动量"`
+	Labels                      string `description:"标签,用英文,隔开"`
+	ActivityLabel               string `description:"活动标签,用英文,隔开"`
+	IsShowSee                   bool   `description:"是否展示查看"`
+	IsShowSeeNum                int    `description:"是否展示查看"`
+	HistoryNum                  int    `description:"报告阅读"`
+	CountNum                    int    `description:"报告收藏"`
+	IndustryFllowNum            int    `description:"产业关注"`
+	DepartmentFollowNum         int    `description:"作者关注"`
+	KeyWordNum                  int    `description:"搜索关键词"`
+	OnLineNum                   int    `description:"线上互动活动"`
+	OfficeNum                   int    `description:"线下互动活动"`
+	ChartNum                    int    `description:"图表收藏数量"`
+	TripNum                     int    `description:"图表数量"`
+	RoadshowVideoNum            int    `description:"产业视频播放量"`
+	ActivityVideoNum            int    `description:"活动视频播放量"`
+	ActivityVoiceNum            int    `description:"活动音频播放量"`
+	YanxuanspecialNum           int    `description:"研选专栏查看数量"`
+	PackageType                 int    `description:"套餐类型,0:无,1:大套餐,2:小套餐"`
+	TryStage                    int    `description:"试用客户子标签:0全部、1未分类、2 推进、3 跟踪、4 预备"`
+	Content                     string `description:"备注信息"`
+	IsRemind                    bool   `description:"是否添加互动提醒"`
+	IsSubscribeCygx             int    `description:"是否关注了查研观向微信公众号: 0-未关注; 1-已关注"`
 }
 
 type CompanyUserListResp struct {
@@ -105,6 +108,7 @@ func GetCygxCompanyUserList(userCondition, keyWord, kwywordcondition, condition,
 			c.company_name,
 			c.company_id,
 			c.interaction_num as company_interaction_num,
+			c.interaction_num_seller as company_interaction_num_seller,
 			cp.status,
 			cp.try_stage,
 			cp.package_type,
@@ -180,7 +184,7 @@ func GetCygxCompanyUserListByNoLoss() (items []*CygxCompanyUserAndSellerResp, er
 
 // 对于上面的SQL的拆分优化查询速度
 func GetCygxCompanyUserListSplit(userIds string) (items []*CygxCompanyUser, err error) {
-
+	databaseName := utils.GetWeeklyDatabase()
 	o := orm.NewOrmUsingDB("hz_cygx")
 	sql := `SELECT
 			u.user_id,
@@ -198,24 +202,8 @@ func GetCygxCompanyUserListSplit(userIds string) (items []*CygxCompanyUser, err
 			( SELECT COUNT( 1 ) FROM cygx_micro_roadshow_video_history AS h  INNER JOIN cygx_micro_roadshow_video as v ON v.video_id = h.video_id WHERE  h.mobile = u.mobile  ) AS roadshow_video_num,
 			( SELECT COUNT( 1 ) FROM cygx_activity_video_history AS h  INNER JOIN cygx_activity_video as v ON v.video_id = h.video_id WHERE  h.mobile = u.mobile  ) AS activity_video_num,
 			( SELECT COUNT( 1 ) FROM cygx_activity_voice_history AS h  INNER JOIN cygx_activity_voice as v ON v.activity_voice_id = h.activity_voice_id WHERE  h.mobile = u.mobile  ) AS activity_voice_num,
-			(
-			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,
-			(
-			SELECT
-				GROUP_CONCAT( DISTINCT man.label SEPARATOR ',' ) 
-			FROM
-				cygx_activity AS man 
-			WHERE
-				man.activity_id IN ( SELECT activity_id FROM cygx_activity_signup AS f WHERE f.user_id = u.user_id  AND label != '') 
-			) AS activity_label
-		FROM
-			cygx_user_label AS u WHERE  u.user_id IN (` + userIds + `)  AND u.mobile != ''	GROUP BY u.user_id  `
+			( SELECT COUNT( 1 ) FROM cygx_yanxuan_special_record AS h  INNER JOIN cygx_yanxuan_special as v ON v.id = h.yanxuan_special_id WHERE  h.mobile = u.mobile  ) AS yanxuanspecial_num
+		FROM ` + databaseName + `.wx_user AS u WHERE  u.user_id IN (` + userIds + `)  AND u.mobile != ''	GROUP BY u.user_id  `
 	_, err = o.Raw(sql).QueryRows(&items)
 	return
 }
@@ -371,6 +359,7 @@ type UserInteraction struct {
 	ActivityTypes         string // 活动类型
 	Industries            string // 产业
 	SubjectNames          string // 标的
+	SpecialType           int    `description:"专栏类型 1:笔记,2:观点"`
 }
 
 // 查研观向图表
@@ -445,9 +434,10 @@ func GetCygxArticleHistoryRecordByUser(mobile, email, condition string, startSiz
 }
 
 // 用户阅读记录列表 2023-08-02 优化拆分
-func GetCygxArticleHistoryRecordByUserNew(mobile, email, condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+func GetCygxArticleHistoryRecordByUserNew(condition string, startSize, pageSize int) (total int, items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
-	sql := ` SELECT
+	var sql string
+	sql += `SELECT
 			art.title,
 			art.article_id,
 			art.article_id_md5,
@@ -455,17 +445,44 @@ func GetCygxArticleHistoryRecordByUserNew(mobile, email, condition string, start
 			art.category_name,
 			r.create_time,
 			r.stop_time,
-			r.source as source_platform
+			r.source AS source_platform,
+			'' AS register_platform,
+			'' AS special_type
 		FROM
 			cygx_article_history_record_all AS r
-			INNER JOIN cygx_article AS art ON art.article_id = r.article_id
+			INNER JOIN cygx_article AS art ON art.article_id = r.article_id 
 		WHERE
-			 r.mobile  = ?  AND is_del = 0 ` + condition + `  OR ( email = ? AND email <>''  AND is_del = 0 ` + condition + `  )
-			 ORDER BY  r.create_time DESC   `
+		1= 1
+			AND is_del = 0  ` + condition
+
+	sql += `  UNION ALL `
+	sql += ` 	SELECT
+			art.title,
+			art.id AS article_id,
+			'' AS article_id_md5,
+			art.publish_time AS publish_date,
+			'' AS category_name,
+			r.create_time,
+			r.stop_time,
+			r.register_platform AS source_platform,
+			r.register_platform,
+			art.type AS special_type
+		FROM
+			cygx_yanxuan_special_record AS r
+			INNER JOIN cygx_yanxuan_special AS art ON art.id = r.yanxuan_special_id 
+		WHERE 1 = 1 ` + condition
+
+	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z `
+	err = o.Raw(totalSql).QueryRow(&total)
+	if err != nil {
+		return
+	}
+
+	sql += ` ORDER BY create_time DESC, article_id DESC   `
 	if startSize > 0 || pageSize > 0 {
 		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
 	}
-	_, err = o.Raw(sql, mobile, email).QueryRows(&items)
+	_, err = o.Raw(sql).QueryRows(&items)
 	return
 }
 
@@ -900,6 +917,7 @@ type GetUserInteractionTableCountResp struct {
 	ActivityVideoNum    int `description:"活动视频播放量"`
 	ActivityVoiceNum    int `description:"活动音频播放量"`
 	TagNum              int `description:"首页标签点击量"`
+	YanxuanSpecialNum   int `description:"研选专栏阅读数量"`
 }
 
 // 用户互动总数统计
@@ -920,9 +938,10 @@ func GetUserInteractionTableCount(uid int) (item *GetUserInteractionTableCountRe
 			( SELECT COUNT( 1 ) FROM cygx_micro_roadshow_video_history AS h  INNER JOIN cygx_micro_roadshow_video as v ON v.video_id = h.video_id WHERE  h.user_id = ?  ) AS roadshow_video_num,
 			( SELECT COUNT( 1 ) FROM cygx_activity_video_history AS h  INNER JOIN cygx_activity_video as v ON v.video_id = h.video_id WHERE  h.user_id = ?  ) AS activity_video_num,
 			( SELECT COUNT( 1 ) FROM cygx_activity_voice_history AS h  INNER JOIN cygx_activity_voice as v ON v.activity_id = h.activity_id WHERE  h.user_id = ?  ) AS activity_voice_num,
-			( SELECT COUNT(1) FROM cygx_tag_history as h INNER JOIN cygx_tag AS b ON h.tag_id = b.tag_id WHERE h.user_id = ?  ) AS tag_num
+			( SELECT COUNT(1) FROM cygx_tag_history as h INNER JOIN cygx_tag AS b ON h.tag_id = b.tag_id WHERE h.user_id = ?  ) AS tag_num,
+			( SELECT COUNT(1) FROM cygx_yanxuan_special_record as h INNER JOIN cygx_yanxuan_special AS b ON h.yanxuan_special_id = b.id WHERE h.user_id = ?  ) AS yanxuan_special_num
 			FROM  dual `
-	err = o.Raw(sql, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid).QueryRow(&item)
+	err = o.Raw(sql, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid, uid).QueryRow(&item)
 	return
 }
 

+ 393 - 37
models/cygx/cygx_user_company.go

@@ -1,8 +1,10 @@
 package cygx
 
 import (
+	"fmt"
 	"github.com/beego/beego/v2/client/orm"
 	"hongze/hz_crm_api/models/company"
+	"hongze/hz_crm_api/utils"
 	"strconv"
 )
 
@@ -103,6 +105,27 @@ func GetActivityMeetByCompanyCount(condition string) (count int, err error) {
 	return
 }
 
+// 获取用户参会记录数量(关联用户跟销售的绑定关系跨库查询)
+func GetActivityMeetByCompanyCountWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := `SELECT
+				COUNT(*) AS count 
+			FROM
+				cygx_activity_signup_detail AS r
+				INNER JOIN cygx_activity AS a ON a.activity_id = r.activity_id
+				INNER JOIN cygx_activity_type as t ON t.activity_type_id = a.activity_type_id
+				INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2
+			WHERE 1 = 1 
+				AND r.do_fail_type = 0`
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
 // 获取用户参会记录
 func GetActivityMeetByCompany(condition string, startSize, pageSize int) (item []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
@@ -135,8 +158,44 @@ func GetActivityMeetByCompany(condition string, startSize, pageSize int) (item [
 		GROUP BY
 			r.id 
 		ORDER BY
-			ui.activity_num DESC ,
-			a.activity_time DESC `
+			a.activity_time DESC ,r.id DESC `
+	if startSize > 0 || pageSize > 0 {
+		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
+	}
+	_, err = o.Raw(sql).QueryRows(&item)
+	return
+}
+
+// 获取用户参会记录(关联用户跟销售的绑定关系跨库查询)
+func GetActivityMeetByCompanyWeekly(condition string, startSize, pageSize int) (item []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT
+			t.activity_type,
+			r.signup_type,
+			r.is_meeting,
+			r.mobile,
+			r.real_name,
+			a.activity_name,
+			a.chart_permission_name,
+			a.activity_type_name,
+			a.label,
+			a.activity_time,
+			r.first_meeting_time,
+			r.last_meeting_time,
+			r.meeting_type_str,
+			r.meeting_authentication,
+			r.meeting_status_str,
+			r.duration
+		FROM
+			cygx_activity_signup_detail AS r
+			INNER  JOIN cygx_activity AS a ON a.activity_id = r.activity_id
+			INNER JOIN cygx_activity_type as t ON t.activity_type_id = a.activity_type_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2
+		WHERE
+			1 = 1 AND r.do_fail_type = 0 `
+	sql = fmt.Sprintf(sql, databaseName)
+	sql += condition + ` GROUP BY r.id ORDER BY	a.activity_time DESC ,r.id DESC  `
 	if startSize > 0 || pageSize > 0 {
 		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
 	}
@@ -153,6 +212,22 @@ func GetCygxArticleCollectCountByCompany(condition string) (count int, err error
 	return
 }
 
+// 收藏列表数量(关联用户跟销售的绑定关系跨库查询)
+func GetCygxArticleCollectCountByCompanyWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_article_collect as r 
+					INNER JOIN cygx_article AS art ON art.article_id = r.article_id
+					INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2
+		  WHERE   1=1 `
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
 // 收藏列表
 func GetCygxArticleCollectByCompany(startSize, pageSize int, condition string) (items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
@@ -191,7 +266,55 @@ func GetCygxArticleCollectByCompany(startSize, pageSize int, condition string) (
 			LEFT JOIN cygx_industrial_article_group_management AS man ON man.article_id = art.article_id 
 		WHERE
 			 1=1 ` + condition + ` GROUP BY r.id 
-			ORDER BY ui.article_count_num DESC ,  r.create_time DESC  `
+			ORDER BY r.create_time DESC  `
+	if startSize > 0 || pageSize > 0 {
+		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
+	}
+	_, err = o.Raw(sql).QueryRows(&items)
+	return
+}
+
+// 收藏列表(关联用户跟销售的绑定关系跨库查询)
+func GetCygxArticleCollectByCompanyWeekly(startSize, pageSize int, condition string) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := ` SELECT
+			art.title,
+			art.article_id,
+			art.article_id_md5,
+			art.publish_date,
+			re.chart_permission_name,
+			re.chart_permission_id,
+			r.create_time,
+			r.mobile,
+			r.real_name,
+			re.match_type_name,
+			(
+			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_str,
+			(
+			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_collect AS r
+			INNER JOIN cygx_article AS art ON art.article_id = r.article_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2
+			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
+			 1=1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	sql += condition + ` GROUP BY r.id ORDER BY r.create_time DESC  `
 	if startSize > 0 || pageSize > 0 {
 		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
 	}
@@ -208,6 +331,21 @@ func GetCygxIndustryFllowCountByCompany(condition string) (count int, err error)
 	return
 }
 
+// 关注产业数量(关联用户跟销售的绑定关系跨库查询)
+func GetCygxIndustryFllowCountByCompanyWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_industry_fllow AS r
+			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = r.industrial_management_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 WHERE   type = 1  `
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
 // 关注产业列表
 func GetCygxIndustryFllowByCompany(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
@@ -219,9 +357,32 @@ func GetCygxIndustryFllowByCompany(condition string, startSize, pageSize int) (i
 			( SELECT GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR '/' ) FROM cygx_industrial_subject AS s WHERE s.industrial_management_id = m.industrial_management_id ) AS subject_name_str 
 		FROM
 			cygx_industry_fllow AS r
-			LEFT  JOIN cygx_user_interaction_num as ui  ON ui.user_id = r.user_id
 			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = r.industrial_management_id 
-		WHERE  type = 1 ` + condition + ` ORDER BY ui.industry_fllow_num DESC, r.create_time DESC  LIMIT ?,? `
+		WHERE  type = 1 ` + condition + ` ORDER BY  r.id DESC  LIMIT ?,? `
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// 关注产业列表
+func GetCygxIndustryFllowByCompanyWeekly(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT
+			m.industry_name,
+			r.mobile,
+			r.real_name,
+			r.modify_time as create_time,
+			( SELECT GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR '/' ) FROM cygx_industrial_subject AS s WHERE s.industrial_management_id = m.industrial_management_id ) AS subject_name_str 
+		FROM
+			cygx_industry_fllow AS r
+			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = r.industrial_management_id 
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+		WHERE  type = 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` ORDER BY  r.id DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -235,6 +396,22 @@ func GetCygArticleDepartmentFollowCountByCompany(condition string) (count int, e
 	return
 }
 
+// 关注作者数量
+func GetCygArticleDepartmentFollowCountByCompanyWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_article_department_follow AS r
+			INNER JOIN cygx_article_department AS m ON m.department_id = r.department_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+			WHERE    type = 1  `
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
 // 关注作者列表
 func GetCygArticleDepartmentFollowByCompany(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
@@ -245,21 +422,44 @@ func GetCygArticleDepartmentFollowByCompany(condition string, startSize, pageSiz
 			r.mobile,
 			r.real_name,
 			m.department_id,
-			i.industry_name,
 			a.title,
 			a.article_id,
-			( SELECT MAX( create_time ) FROM cygx_article_department_follow WHERE user_id = r.user_id ) AS max_time,
-			( SELECT GROUP_CONCAT( DISTINCT i.industry_name SEPARATOR '/' ) FROM cygx_industrial_management AS i WHERE i.industrial_management_id = mg.industrial_management_id ) AS industry_name,
-			( SELECT GROUP_CONCAT( DISTINCT s.subject_name SEPARATOR '/' ) FROM cygx_industrial_subject AS s WHERE s.industrial_management_id = i.industrial_management_id ) AS subject_name_str
+			( SELECT MAX( create_time ) FROM cygx_article_department_follow WHERE user_id = r.user_id ) AS max_time
 		FROM
 			cygx_article_department_follow AS r
 			INNER JOIN cygx_article_department AS m ON m.department_id = r.department_id
 			INNER JOIN cygx_article AS a ON a.department_id = m.department_id
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
-			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
-			LEFT JOIN cygx_industrial_management AS i ON i.industrial_management_id = mg.industrial_management_id
 			WHERE  r.type = 1 ` + condition + `  GROUP BY 	r.id  
-			ORDER BY  ui.department_follow_num DESC ,	max_time DESC  LIMIT ?,? `
+			ORDER BY 	max_time DESC  LIMIT ?,? `
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// 关注作者列表
+func GetCygArticleDepartmentFollowByCompanyWeekly(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT
+			m.department_id,
+			m.nick_name,
+			r.modify_time as  create_time,
+			r.mobile,
+			r.real_name,
+			m.department_id,
+			a.title,
+			a.article_id,
+			( SELECT MAX( create_time ) FROM cygx_article_department_follow WHERE user_id = r.user_id ) AS max_time
+		FROM
+			cygx_article_department_follow AS r
+			INNER JOIN cygx_article_department AS m ON m.department_id = r.department_id
+			INNER JOIN cygx_article AS a ON a.department_id = m.department_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+			WHERE  r.type = 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` GROUP BY 	r.id ORDER BY 	max_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -272,6 +472,21 @@ func GetCygxSearchKeyWordCountBuCompany(condition string) (count int, err error)
 	return
 }
 
+// 用户搜索关键词统计
+func GetCygxSearchKeyWordCountBuCompanyWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_search_key_word  as r
+					INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+					WHERE  1= 1  `
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
 // 用户搜索关键词列表
 func GetCygxSearchKeyWordByCompany(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
@@ -282,9 +497,30 @@ func GetCygxSearchKeyWordByCompany(condition string, startSize, pageSize int) (i
 			r.real_name
 		FROM
 			cygx_search_key_word as r
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
 			WHERE 1= 1 ` + condition + `
-			ORDER BY  ui.key_word_num DESC, r.create_time DESC  LIMIT ?,? `
+			ORDER BY   r.create_time DESC  LIMIT ?,? `
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// 用户搜索关键词列表
+func GetCygxSearchKeyWordByCompanyWeekly(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT
+			r.key_word,
+			r.create_time,
+			r.mobile,
+			r.real_name
+		FROM
+			cygx_search_key_word as r
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+			WHERE 1= 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` ORDER BY   r.create_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -299,7 +535,28 @@ func GetCygxActivitySpecialTripCountByCompany(condition string) (count int, err
 			INNER JOIN cygx_activity_special AS a ON a.activity_id = r.activity_id
 		WHERE
 			1 = 1 
-			 AND a.publish_status = 1 AND a.activity_time_end < NOW()   ` + condition
+			 AND a.publish_status = 1   ` + condition
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
+// 用户专项产业调研统计
+func GetCygxActivitySpecialTripCountByCompanyWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT
+			COUNT( 1 ) 
+		FROM
+			cygx_activity_special_meeting_detail AS r
+			INNER JOIN cygx_activity_special AS a ON a.activity_id = r.activity_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+		WHERE
+			1 = 1 
+			 AND a.publish_status = 1   `
+	sqlCount = fmt.Sprintf(sqlCount, databaseName)
+	if condition != "" {
+		sqlCount += condition
+	}
 	err = o.Raw(sqlCount).QueryRow(&count)
 	return
 }
@@ -320,9 +577,36 @@ func CygxActivitySpecialTripByCompany(condition string, startSize, pageSize int)
 		FROM
 			cygx_activity_special_meeting_detail AS r
 			INNER JOIN cygx_activity_special AS a ON a.activity_id = r.activity_id
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
-			WHERE 1= 1   AND a.publish_status = 1 AND a.activity_time_end < NOW() ` + condition + `
-			ORDER BY  ui.trip_num DESC, r.create_time DESC  LIMIT ?,? `
+			WHERE 1= 1   AND a.publish_status = 1  ` + condition + `
+			ORDER BY  r.create_time DESC  LIMIT ?,? `
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// 用户专项产业调研列表
+func CygxActivitySpecialTripByCompanyWeekly(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT
+			a.research_theme AS activity_name,
+			a.chart_permission_name,
+			a.activity_time_text_by_day AS activity_time_text,
+			a.city,
+			a.special_type AS activity_type,
+			r.mobile,
+			r.activity_id,
+			r.real_name,
+			r.is_meeting 
+		FROM
+			cygx_activity_special_meeting_detail AS r
+			INNER JOIN cygx_activity_special AS a ON a.activity_id = r.activity_id
+			INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+			WHERE 1= 1   AND a.publish_status = 1  `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` ORDER BY  r.create_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -356,6 +640,39 @@ FROM
 	return
 }
 
+// 用户音视频浏览统计
+func GetCygxRoadshowCountByCompanyWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := `SELECT
+	COUNT( 1 ) total 
+FROM
+	(
+	SELECT
+		"" 
+	FROM
+		cygx_micro_roadshow_video_history AS r
+		INNER JOIN cygx_micro_roadshow_video AS v ON r.video_id = v.video_id
+		INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+	WHERE 1=1 ` + condition + `  UNION ALL
+	SELECT
+		"" 
+	FROM
+		cygx_activity_video_history AS r
+		INNER JOIN cygx_activity_video AS v ON r.video_id = v.video_id
+		INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+	WHERE 1=1 ` + condition + ` UNION ALL
+	SELECT
+		"" 
+	FROM
+		cygx_activity_voice_history AS r
+		INNER JOIN cygx_activity_voice AS v ON r.activity_id = v.activity_id
+		INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+	WHERE 1=1 ` + condition + `)z  `
+	err = o.Raw(sqlCount).QueryRow(&count)
+	return
+}
+
 // 用户音视频浏览列表
 func GetCygxRoadshowByCompany(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
@@ -364,38 +681,80 @@ func GetCygxRoadshowByCompany(condition string, startSize, pageSize int) (items
 			r.create_time,
 			r.real_name,
 			r.mobile,
-			ui.roadshow_num,
 			"逻辑解析" AS file_type 
 		FROM
 			cygx_micro_roadshow_video_history AS r
 			INNER JOIN cygx_micro_roadshow_video AS v ON r.video_id = v.video_id
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
+
 		WHERE 1=1 ` + condition + `  UNION ALL
 		SELECT
 			v.video_name AS media_title,
 			r.create_time,
 			r.real_name,
 			r.mobile,
-			ui.roadshow_num,
 			"路演回放" AS file_type 
 		FROM
 			cygx_activity_video_history AS r
 			INNER JOIN cygx_activity_video AS v ON r.video_id = v.video_id
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
+
 		WHERE 1=1 ` + condition + `   UNION ALL
 		SELECT
 			v.voice_name AS media_title,
 			r.create_time,
 			r.real_name,
 			r.mobile,
-			ui.roadshow_num,
 			"路演回放" AS file_type 
 		FROM
 			cygx_activity_voice_history AS r
 			INNER JOIN cygx_activity_voice AS v ON r.activity_id = v.activity_id
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
+
+		WHERE 1=1 ` + condition + `  
+		ORDER BY create_time DESC   LIMIT ?,? `
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+// 用户音视频浏览列表
+func GetCygxRoadshowByCompanyWeekly(condition string, startSize, pageSize int) (items []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := `SELECT
+			v.video_name AS media_title,
+			r.create_time,
+			r.real_name,
+			r.mobile,
+			"逻辑解析" AS file_type 
+		FROM
+			cygx_micro_roadshow_video_history AS r
+			INNER JOIN cygx_micro_roadshow_video AS v ON r.video_id = v.video_id
+			INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+
+		WHERE 1=1 ` + condition + `  UNION ALL
+		SELECT
+			v.video_name AS media_title,
+			r.create_time,
+			r.real_name,
+			r.mobile,
+			"路演回放" AS file_type 
+		FROM
+			cygx_activity_video_history AS r
+			INNER JOIN cygx_activity_video AS v ON r.video_id = v.video_id
+			INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+
+		WHERE 1=1 ` + condition + `   UNION ALL
+		SELECT
+			v.voice_name AS media_title,
+			r.create_time,
+			r.real_name,
+			r.mobile,
+			"路演回放" AS file_type 
+		FROM
+			cygx_activity_voice_history AS r
+			INNER JOIN cygx_activity_voice AS v ON r.activity_id = v.activity_id
+			INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+
 		WHERE 1=1 ` + condition + `  
-		ORDER BY roadshow_num DESC ,create_time DESC   LIMIT ?,? `
+		ORDER BY create_time DESC   LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -451,7 +810,7 @@ func GetCygxRoadshowByCompanyList(condition string, startSize, pageSize int) (it
 			LEFT JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
 			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id 
 		WHERE 1=1 ` + condition + `  
-		ORDER BY 	roadshow_num DESC ,ui_roadshow_num DESC ,create_time DESC  LIMIT ?,? `
+		ORDER BY create_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -560,8 +919,6 @@ func GetActivityMeetByCompanyList(condition string, startSize, pageSize int) (it
 			cygx_activity_signup_detail AS r
 			INNER  JOIN cygx_activity AS a ON a.activity_id = r.activity_id
 			INNER JOIN cygx_activity_type as t ON t.activity_type_id = a.activity_type_id
-			LEFT JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
-			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
 		WHERE
 			1 = 1 
 			AND r.do_fail_type = 0
@@ -569,9 +926,8 @@ func GetActivityMeetByCompanyList(condition string, startSize, pageSize int) (it
 		GROUP BY
 			r.id 
 		ORDER BY
-			ci.activity_num DESC ,
-			ui.activity_num DESC ,
-			a.activity_time DESC `
+			a.activity_time DESC,
+			r.id DESC `
 	if startSize > 0 || pageSize > 0 {
 		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
 	}
@@ -620,7 +976,7 @@ func GetCygxArticleCollectByCompanyList(startSize, pageSize int, condition strin
 			LEFT JOIN cygx_industrial_article_group_management AS man ON man.article_id = art.article_id 
 		WHERE
 			 1=1 ` + condition + ` GROUP BY r.id 
-			ORDER BY ui.article_count_num DESC ,ui.article_count_num DESC ,  r.create_time DESC  `
+			ORDER BY  r.create_time DESC  `
 	if startSize > 0 || pageSize > 0 {
 		sql += ` LIMIT ` + strconv.Itoa(startSize) + "," + strconv.Itoa(pageSize)
 	}
@@ -646,7 +1002,7 @@ func GetCygxIndustryFllowByCompanyList(condition string, startSize, pageSize int
 			LEFT JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
 			LEFT  JOIN cygx_user_interaction_num as ui  ON ui.user_id = r.user_id
 			
-		WHERE  type = 1 ` + condition + ` ORDER BY ci.industry_fllow_num DESC,ui.industry_fllow_num DESC, r.create_time DESC  LIMIT ?,? `
+		WHERE  type = 1 ` + condition + ` ORDER BY  r.create_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -678,7 +1034,7 @@ func GetCygArticleDepartmentFollowByCompanyList(condition string, startSize, pag
 			LEFT JOIN cygx_industrial_article_group_management AS mg ON mg.article_id = a.article_id
 			LEFT JOIN cygx_industrial_management AS i ON i.industrial_management_id = mg.industrial_management_id
 			WHERE  r.type = 1 ` + condition + `  GROUP BY 	r.id  
-			ORDER BY  ci.department_follow_num DESC ,ui.department_follow_num DESC ,	max_time DESC  LIMIT ?,? `
+			ORDER BY  	max_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -697,7 +1053,7 @@ func GetCygxSearchKeyWordByCompanyList(condition string, startSize, pageSize int
 			LEFT JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
 			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
 			WHERE 1= 1 ` + condition + `
-			ORDER BY  ci.key_word_num DESC,ui.key_word_num DESC, r.create_time DESC  LIMIT ?,? `
+			ORDER BY r.create_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }
@@ -724,7 +1080,7 @@ func GetCygxActivitySpecialTripByCompanyList(condition string, startSize, pageSi
 			LEFT JOIN cygx_company_interaction_num AS ci ON ci.company_id = r.company_id
 			LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = r.user_id
 			WHERE 1= 1 ` + condition + `
-			ORDER BY  ci.trip_num DESC,ui.trip_num DESC, r.create_time DESC  LIMIT ?,? `
+			ORDER BY  r.create_time DESC  LIMIT ?,? `
 	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
 	return
 }

+ 95 - 31
models/cygx/cygx_yanxuan_special.go

@@ -2,6 +2,7 @@ package cygx
 
 import (
 	"github.com/beego/beego/v2/client/orm"
+	"github.com/rdlucklib/rdluck_tools/paging"
 	"time"
 )
 
@@ -22,31 +23,36 @@ type CygxYanxuanSpecial struct {
 }
 
 type CygxYanxuanSpeciaResplItem struct {
-	Id            int    `orm:"column(id);pk"`
-	UserId        int    // 用户ID
-	CreateTime    string // 创建时间
-	ModifyTime    string // 修改时间
-	PublishTime   string // 提审过审或驳回时间
-	Content       string // 内容
-	Tags          string // 标签
-	Status        int    // 1:未发布,2:审核中 3:已发布 4:驳回
-	ImgUrl        string // 图片链接
-	DocUrl        string // 文档链接
-	SpecialName   string // 专栏名称
-	Introduction  string // 介绍
-	Label         string // 标签
-	NickName      string // 昵称
-	RealName      string // 姓名
-	Mobile        string // 手机号
-	HeadImg       string // 头像
-	BgImg         string // 背景图
-	Reason        string // 理由
-	Title         string // 标题
-	CompanyTags   string
-	IndustryTags  string
-	Type          int // 类型1:笔记,2:观点
-	ContentHasImg int //正文是否包含图片 1包含 0不包含
-	Docs          []Doc
+	Id                int    `orm:"column(id);pk"`
+	UserId            int    // 用户ID
+	CreateTime        string // 创建时间
+	ModifyTime        string // 修改时间
+	PublishTime       string // 提审过审或驳回时间
+	Content           string // 内容
+	Tags              string // 标签
+	Status            int    // 1:未发布,2:审核中 3:已发布 4:驳回
+	ImgUrl            string // 图片链接
+	DocUrl            string // 文档链接
+	SpecialName       string // 专栏名称
+	Introduction      string // 介绍
+	Label             string // 标签
+	NickName          string // 昵称
+	RealName          string // 姓名
+	Mobile            string // 手机号
+	HeadImg           string // 头像
+	BgImg             string // 背景图
+	Reason            string // 理由
+	Title             string // 标题
+	CompanyTags       string
+	IndustryTags      string
+	Type              int // 类型1:笔记,2:观点
+	ContentHasImg     int //正文是否包含图片 1包含 0不包含
+	Docs              []Doc
+	Pv                string `description:"Pv"`
+	Uv                string `description:"Uv"`
+	ArticleCollectNum int    // 文章收藏数量
+	AdminName         string // 审核人员姓名
+	SpecialAuthorId   int    //cygx_yanxuan_special_author 表主键ID 作者专栏ID
 }
 
 type Doc struct {
@@ -56,7 +62,24 @@ type Doc struct {
 	DocIcon   string
 }
 
-func GetYanxuanSpecialList(condition string, pars []interface{}) (items []*CygxYanxuanSpeciaResplItem, err error) {
+type GetCygxYanxuanSpeciaResplItemResp struct {
+	Paging *paging.PagingItem `description:"分页数据"`
+	List   []*CygxYanxuanSpeciaResplItem
+}
+
+// 获取数量
+func GetGetYanxuanSpecialCount(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_yanxuan_special as a 
+				JOIN cygx_yanxuan_special_author AS b ON a.user_id = b.user_id  WHERE 1= 1  `
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount, pars).QueryRow(&count)
+	return
+}
+
+func GetYanxuanSpecialList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpeciaResplItem, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
 	sql := ``
 	sql = `SELECT a.*,b.bg_img,b.head_img,b.introduction,b.label,b.mobile,b.nick_name,b.real_name,b.special_name
@@ -66,8 +89,22 @@ JOIN cygx_yanxuan_special_author AS b ON a.user_id = b.user_id
 	if condition != "" {
 		sql += condition
 	}
-	sql += `ORDER BY a.publish_time `
-	_, err = o.Raw(sql, pars).QueryRows(&items)
+	sql += ` LIMIT ?,? `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+func GetYanxuanSpecialListByCondition(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpeciaResplItem, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := ``
+	sql = `SELECT a.*
+FROM cygx_yanxuan_special AS a
+ WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,? `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
 	return
 }
 
@@ -77,11 +114,11 @@ type EnableCygxYanxuanSpecialReq struct {
 	Reason string //理由
 }
 
-func EnableYanxuanSpecial(id, status int, reason string) (err error) {
+func EnableYanxuanSpecial(id, status int, reason, adminName string) (err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
 	sql := ``
-	sql = `UPDATE cygx_yanxuan_special SET status=?,reason=?,publish_time=NOW() WHERE id = ? `
-	_, err = o.Raw(sql, status, reason, id).Exec()
+	sql = `UPDATE cygx_yanxuan_special SET status=?,reason=?,admin_name = ? , publish_time=NOW() WHERE id = ? `
+	_, err = o.Raw(sql, status, reason, adminName, id).Exec()
 	return
 }
 
@@ -149,3 +186,30 @@ func GetCygxYanxuanSpecialCount(condition string, pars []interface{}) (count int
 	err = o.Raw(sqlCount, pars).QueryRow(&count)
 	return
 }
+
+type CygxYanxuanSpecialShowButton struct {
+	IsShowSpecialAuthor bool // 作者管理的按钮是否
+}
+
+func GetYanxuanSpecialBySpecialId(specialId int) (item *CygxYanxuanSpecialItem, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := ``
+	sql = `SELECT a.* FROM cygx_yanxuan_special AS a WHERE a.id=? `
+	err = o.Raw(sql, specialId).QueryRow(&item)
+	return
+}
+
+func GetYanxuanSpecialListBycondition(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpecial, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT a.* FROM cygx_yanxuan_special AS a WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	if startSize+pageSize > 0 {
+		sql += ` LIMIT ?,? `
+		_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	} else {
+		_, err = o.Raw(sql, pars).QueryRows(&items)
+	}
+	return
+}

+ 86 - 0
models/cygx/cygx_yanxuan_special_approval_log.go

@@ -0,0 +1,86 @@
+package cygx
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+	"github.com/rdlucklib/rdluck_tools/paging"
+	"time"
+)
+
+type CygxYanxuanSpecialApprovalLog struct {
+	ApprovalLogId    int       `orm:"column(approval_log_id);pk"`
+	UserId           int       // 用户ID
+	CreateTime       time.Time // 创建时间
+	ModifyTime       time.Time // 修改时间
+	Content          string    // 内容
+	Tags             string    // 标签
+	ApprovalStatus   int       // 1通过、2驳回
+	ImgUrl           string    // 图片链接
+	DocUrl           string    // 文档链接
+	Reason           string    // 理由
+	Title            string    // 标题
+	Type             int       // 类型1:笔记,2:观点
+	CompanyTags      string    // 公司标签
+	IndustryTags     string    // 行业标签
+	YanxuanSpecialId int       // cygx_yanxuan_special 表主键ID
+	AdminName        string    // 审核人员姓名
+	AdminUserId      int       // 审核人员用户ID
+	SpecialName      string    // 专栏名称
+	NickName         string    // 昵称
+}
+
+type CygxYanxuanSpecialApprovalLogResp struct {
+	ApprovalLogId    int    `orm:"column(approval_log_id);pk"`
+	UserId           int    // 用户ID
+	CreateTime       string // 创建时间
+	ModifyTime       string // 修改时间
+	Content          string // 内容
+	Tags             string // 标签
+	ApprovalStatus   int    // 1通过、2驳回
+	ImgUrl           string // 图片链接
+	DocUrl           string // 文档链接
+	Reason           string // 理由
+	Title            string // 标题
+	Type             int    // 类型1:笔记,2:观点
+	CompanyTags      string // 公司标签
+	IndustryTags     string // 行业标签
+	YanxuanSpecialId int    // cygx_yanxuan_special 表主键ID
+	AdminName        string // 审核人员姓名
+	AdminUserId      int    // 审核人员用户ID
+	SpecialName      string // 专栏名称
+	NickName         string // 昵称
+	SpecialAuthorId  int    //cygx_yanxuan_special_author 表主键ID 作者专栏ID
+}
+
+// 获取数量
+func GetCygxYanxuanSpecialApprovalLogCount(condition string, pars []interface{}) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_yanxuan_special_approval_log as a WHERE 1= 1  `
+	if condition != "" {
+		sqlCount += condition
+	}
+	err = o.Raw(sqlCount, pars).QueryRow(&count)
+	return
+}
+
+func GetCygxYanxuanSpecialApprovalLogList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpecialApprovalLogResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := ``
+	sql = `SELECT * FROM cygx_yanxuan_special_approval_log AS a WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,? `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+type CygxYanxuanSpecialApprovalLogListResp struct {
+	Paging *paging.PagingItem `description:"分页数据"`
+	List   []*CygxYanxuanSpecialApprovalLogResp
+}
+
+func AddCygxYanxuanSpecialApprovalLog(item *CygxYanxuanSpecialApprovalLog) (err error) {
+	o := orm.NewOrm()
+	_, err = o.Insert(item)
+	return
+}

+ 63 - 0
models/cygx/cygx_yanxuan_special_collect.go

@@ -0,0 +1,63 @@
+package cygx
+
+import (
+	"github.com/beego/beego/v2/client/orm"
+)
+
+type CygxYanxuanSpecialCollectResp struct {
+	CygxYanxuanSpecialCollectId int    `orm:"column(cygx_yanxuan_special_collect_id);pk"`
+	UserId                      int    // 用户ID
+	Mobile                      string // 手机号
+	Email                       string // 邮箱
+	CompanyId                   int    // 公司ID
+	CompanyName                 string // 公司名称
+	RealName                    string // 用户实际名称
+	SellerName                  string // 所属销售
+	CreateTime                  string // 创建时间
+	ModifyTime                  string // 修改时间
+	RegisterPlatform            int    // 来源 1小程序,2:网页
+	YanxuanSpecialId            int    // cygx_yanxuan_special 表主键ID
+}
+
+// 列表
+func GetCygxYanxuanSpecialCollectList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpecialCollectResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_yanxuan_special_collect as art WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,?  `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+type GetCygxYanxuanSpecialCollectResp struct {
+	List []*CygxYanxuanSpecialCollectResp
+}
+
+type CygxYanxuanSpecialRecordResp struct {
+	CygxYanxuanSpecialRecordId int    `orm:"column(cygx_yanxuan_special_record_id);pk"`
+	UserId                     int    // 用户ID
+	Mobile                     string // 手机号
+	Email                      string // 邮箱
+	CompanyId                  int    // 公司ID
+	CompanyName                string // 公司名称
+	RealName                   string // 用户实际名称
+	SellerName                 string // 所属销售
+	CreateTime                 string // 创建时间
+	ModifyTime                 string // 修改时间
+	RegisterPlatform           int    // 来源 1小程序,2:网页
+	YanxuanSpecialId           int    // cygx_yanxuan_special 表主键ID
+	StopTime                   int    // 停留时间
+}
+
+// 列表
+func GetCygxYanxuanSpecialRecordList(condition string, pars []interface{}) (items []*CygxYanxuanSpecialRecordResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_yanxuan_special_record  as art WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}

+ 35 - 0
models/cygx/cygx_yanxuan_special_follow.go

@@ -0,0 +1,35 @@
+package cygx
+
+import "github.com/beego/beego/v2/client/orm"
+
+type CygxYanxuanSpecialFollowResp struct {
+	CygxYanxuanSpecialFollowId int    `orm:"column(cygx_yanxuan_special_follow_id);pk"`
+	UserId                     int    // 用户ID
+	FollowUserId               int    // 被关注用户ID
+	Mobile                     string // 手机号
+	Email                      string // 邮箱
+	CompanyId                  int    // 公司ID
+	CompanyName                string // 公司名称
+	RealName                   string // 用户实际名称
+	SellerName                 string // 所属销售
+	CreateTime                 string // 创建时间
+	ModifyTime                 string // 修改时间
+	RegisterPlatform           int    // 来源 1小程序,2:网页
+	YanxuanSpecialId           int    // cygx_yanxuan_special 表主键ID
+}
+
+func GetCygxYanxuanSpecialFollowList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpecialFollowResp, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := ``
+	sql = `SELECT * FROM cygx_yanxuan_special_follow AS a WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,? `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+type GetCygxYanxuanSpecialFollowResp struct {
+	List []*CygxYanxuanSpecialFollowResp
+}

+ 69 - 21
models/cygx/cygx_yanxuan_special_user.go

@@ -2,6 +2,7 @@ package cygx
 
 import (
 	"github.com/beego/beego/v2/client/orm"
+	"github.com/rdlucklib/rdluck_tools/paging"
 	"time"
 )
 
@@ -26,20 +27,27 @@ type CygxYanxuanSpecialAuthor struct {
 }
 
 type CygxYanxuanSpecialAuthorItem struct {
-	Id           int    `orm:"column(id);pk"`
-	UserId       int    // 用户ID
-	CompanyName  string // 公司名
-	SpecialName  string // 专栏名称
-	Introduction string // 介绍
-	Label        string // 标签
-	NickName     string // 昵称
-	RealName     string // 姓名
-	Mobile       string // 手机号
-	CreateTime   string // 创建时间
-	ModifyTime   string // 修改时间
-	HeadImg      string // 头像
-	BgImg        string // 背景图
-	Status       int    // 1启用2禁用
+	Id                 int    `orm:"column(id);pk"`
+	UserId             int    // 用户ID
+	CompanyName        string // 公司名
+	SpecialName        string // 专栏名称
+	Introduction       string // 介绍
+	Label              string // 标签
+	NickName           string // 昵称
+	RealName           string // 姓名
+	Mobile             string // 手机号
+	CreateTime         string // 创建时间
+	ModifyTime         string // 修改时间
+	HeadImg            string // 头像
+	BgImg              string // 背景图
+	Status             int    // 1启用2禁用
+	Pv                 int    // Pv
+	Uv                 int    // Uv
+	ArticleNum         int    // 已发布的文章数量
+	ArticlePublishTime string // 最近发布文章的时间
+	FansNum            int    // 粉丝数量
+	ArticleCollectNum  int    // 文章收藏数量
+	SpecialAuthorId    int    //cygx_yanxuan_special_author 表主键ID 作者专栏ID
 }
 
 func AddCygxYanxuanSpecialAuthor(item *CygxYanxuanSpecialAuthor) (lastId int64, err error) {
@@ -68,14 +76,31 @@ func EnableYanxuanSpecialAuthor(userId, status int) (err error) {
 	return
 }
 
-func GetYanxuanSpecialAuthorList() (items []*CygxYanxuanSpecialAuthorItem, err error) {
+// 获取数量
+func GetYanxuanSpecialAuthorCount(condition string, pars []interface{}) (count int, err error) {
+	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_yanxuan_special_author as art WHERE 1= 1  `
+	if condition != "" {
+		sqlCount += condition
+	}
 	o := orm.NewOrmUsingDB("hz_cygx")
-	sql := ``
-	sql = `SELECT
-	a.*
-FROM
-	cygx_yanxuan_special_author as a ORDER BY create_time DESC `
-	_, err = o.Raw(sql).QueryRows(&items)
+	err = o.Raw(sqlCount, pars).QueryRow(&count)
+	return
+}
+
+type GetCygxYanxuanSpecialAuthorItemResp struct {
+	Paging *paging.PagingItem `description:"分页数据"`
+	List   []*CygxYanxuanSpecialAuthorItem
+}
+
+// 列表
+func GetYanxuanSpecialAuthorList(condition string, pars []interface{}, startSize, pageSize int) (items []*CygxYanxuanSpecialAuthorItem, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_yanxuan_special_author as art WHERE 1= 1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` LIMIT ?,?  `
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
 	return
 }
 
@@ -87,3 +112,26 @@ func UpdateSpecialAuthorComapony(userId, CompanyId int, CompanyName string) (err
 	_, err = o.Raw(sql, CompanyId, CompanyName, userId).Exec()
 	return
 }
+
+// 通过ID获取详情
+func GetCygxYanxuanSpecialAuthorItemById(id int) (item *CygxYanxuanSpecialAuthorItem, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_yanxuan_special_author  WHERE id=? `
+	err = o.Raw(sql, id).QueryRow(&item)
+	return
+}
+
+// 根据用户ID获取专栏详情
+func GetCygxYanxuanSpecialAuthorByUserId(userId int) (item *CygxYanxuanSpecialAuthorItem, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_yanxuan_special_author  WHERE user_id = ? `
+	err = o.Raw(sql, userId).QueryRow(&item)
+	return
+}
+
+type CygxYanxuanSpecialCenterAuthorResp struct {
+	Id          int    //研选专栏ID
+	UserId      int    // 用户ID
+	PublishTime string // 提审过审或驳回时间
+	Title       string // 标题
+}

+ 17 - 0
models/cygx/industrial_article_group_management.go

@@ -2,6 +2,7 @@ package cygx
 
 import (
 	"github.com/beego/beego/v2/client/orm"
+	"hongze/hz_crm_api/utils"
 	"strconv"
 	"time"
 )
@@ -128,6 +129,22 @@ func GetIndustrialArticleGroupListByarticleIds(articleIds string) (items []*Indu
 	return
 }
 
+// 根据文章ID数组获取关联的产业列表
+func GetIndustrialArticleGroupListByarticleIdsArr(articleIds []int) (items []*IndustrialArticleGroupResp, err error) {
+	lenArr := len(articleIds)
+	if lenArr == 0 {
+		return
+	}
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT  mg.*,m.industry_name  FROM
+	        cygx_industrial_article_group_management AS mg
+			INNER JOIN cygx_industrial_management AS m ON m.industrial_management_id = mg.industrial_management_id 
+			WHERE 1 = 1 
+			AND mg.article_id IN  (` + utils.GetOrmInReplace(lenArr) + `)  GROUP BY  mg.article_id,mg.industrial_management_id`
+	_, err = o.Raw(sql, articleIds).QueryRows(&items)
+	return
+}
+
 // 用户收藏榜start
 type IndustrialManagementHotResp struct {
 	IndustrialManagementId int                      `orm:"column(industrial_management_id);pk" description:"产业id"`

+ 22 - 0
models/cygx/industrial_article_group_subject.go

@@ -2,6 +2,7 @@ package cygx
 
 import (
 	"github.com/beego/beego/v2/client/orm"
+	"hongze/hz_crm_api/utils"
 	"time"
 )
 
@@ -81,3 +82,24 @@ func GetSubjectArticleGroupListByarticleIds(articleIds string) (items []*Subject
 	_, err = o.Raw(sql).QueryRows(&items)
 	return
 }
+
+// 列表
+func GetSubjectArticleGroupListByarticleIdsArr(articleIds []int) (items []*SubjectlArticleGroupResp, err error) {
+	lenArr := len(articleIds)
+	if lenArr == 0 {
+		return
+	}
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT
+			sg.*,
+			s.subject_name,
+			s.industrial_management_id 
+		FROM
+			cygx_industrial_article_group_subject AS sg
+			INNER JOIN cygx_industrial_subject AS s ON s.industrial_subject_id = sg.industrial_subject_id 
+		WHERE
+			1 = 1 
+			AND sg.article_id IN  (` + utils.GetOrmInReplace(lenArr) + `)    GROUP BY sg.article_id,sg.industrial_subject_id`
+	_, err = o.Raw(sql, articleIds).QueryRows(&items)
+	return
+}

+ 3 - 0
models/cygx/report_article.go

@@ -463,6 +463,7 @@ type ArticleDetail struct {
 	CreateDate           string `description:"创建时间"`
 	PublishDate          string `description:"发布时间"`
 	Body                 string `description:"内容"`
+	Annotation           string `description:"核心观点"`
 	Abstract             string `description:"摘要"`
 	CategoryName         string `description:"一级分类"`
 	SubCategoryName      string `description:"二级分类"`
@@ -485,6 +486,8 @@ type ArticleDetail struct {
 	TypeName             string `description:"策略平台类型字段名称"`
 	ArticleTypeId        int    `description:"文章类型ID"`
 	ArticleTypeName      string `description:"文章类型名称"`
+	Stock                string `description:"个股标签(上海策略品台同步)"`
+	FieldName            string `description:"产业标签(上海策略品台同步)"`
 }
 
 func GetArticleDetailById(articleId int) (item *ArticleDetail, err error) {

+ 8 - 0
models/cygx/report_mapping_cygx.go

@@ -119,3 +119,11 @@ func GetCygxReportMappingCygxDetailByName(name string) (item *CygxReportMappingC
 	err = o.Raw(sql, name).QueryRow(&item)
 	return
 }
+
+// 通过ID获取详情
+func GetCygxReportMappingCygxDetailByNameAndChartPermissionId(name string, chartPermissionId int) (item *CygxReportMappingCygx, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	sql := `SELECT * FROM cygx_report_mapping_cygx  WHERE match_type_name=?  AND chart_permission_id = ?  LIMIT 1 `
+	err = o.Raw(sql, name, chartPermissionId).QueryRow(&item)
+	return
+}

+ 7 - 1
models/cygx/resource_data.go

@@ -16,12 +16,15 @@ type CygxResourceData struct {
 	Abstract          string    `description:"摘要"`
 	SearchTag         string    `description:"搜索标签"`
 	ChartPermissionId int       `description:"行业id"`
+	SearchTitle       string    `description:"搜索匹配用的标题"`
+	SearchContent     string    `description:"搜索匹配用的内容"`
+	SearchOrderTime   string    `description:"搜索排序时间"`
 }
 
 // 根据资源类型获取列表
 func GetCygxResourceDataListBysource(source string) (items []*CygxResourceData, err error) {
 	o := orm.NewOrmUsingDB("hz_cygx")
-	sql := `SELECT * FROM cygx_resource_data as art WHERE 1= 1  AND  source = ?  AND chart_permission_id = 0   `
+	sql := `SELECT * FROM cygx_resource_data as art WHERE 1= 1  AND  source = ?  AND search_title = ''   `
 	_, err = o.Raw(sql, source).QueryRows(&items)
 	return
 }
@@ -56,6 +59,9 @@ func UpdateResourceDataByItem(item *CygxResourceData) (err error) {
 	updateParams["PublishDate"] = item.PublishDate
 	updateParams["SearchTag"] = item.SearchTag
 	updateParams["ChartPermissionId"] = item.ChartPermissionId
+	updateParams["SearchTitle"] = item.SearchTitle
+	updateParams["SearchContent"] = item.SearchContent
+	updateParams["SearchOrderTime"] = item.SearchOrderTime
 	ptrStructOrTableName := "cygx_resource_data"
 	whereParam := map[string]interface{}{"source_id": item.SourceId, "source": item.Source}
 	qs := o.QueryTable(ptrStructOrTableName)

+ 119 - 20
models/cygx/tag_history.go

@@ -1,7 +1,9 @@
 package cygx
 
 import (
+	"fmt"
 	"github.com/beego/beego/v2/client/orm"
+	"hongze/hz_crm_api/utils"
 	"time"
 )
 
@@ -31,16 +33,16 @@ func GetCygxTagHistoryList(condition string, pars []interface{}) (items []*CygxT
 	return
 }
 
-// 获取数量
-func GetCygxTagHistoryCount(condition string, pars []interface{}) (count int, err error) {
-	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_tag_history as art WHERE 1= 1  `
-	if condition != "" {
-		sqlCount += condition
-	}
-	o := orm.NewOrmUsingDB("hz_cygx")
-	err = o.Raw(sqlCount, pars).QueryRow(&count)
-	return
-}
+//// 获取数量
+//func GetCygxTagHistoryCount(condition string, pars []interface{}) (count int, err error) {
+//	sqlCount := ` SELECT COUNT(1) AS count  FROM cygx_tag_history as art WHERE 1= 1  `
+//	if condition != "" {
+//		sqlCount += condition
+//	}
+//	o := orm.NewOrmUsingDB("hz_cygx")
+//	err = o.Raw(sqlCount, pars).QueryRow(&count)
+//	return
+//}
 
 // 获取数量
 func GetCygxTagHistoryCountUv(tagId int) (count int, err error) {
@@ -83,35 +85,69 @@ WHERE a.user_id=? ORDER BY a.create_time DESC LIMIT ?,? `
 
 // 获取数量
 func GetCygxTagHistoryCountByCompanyId(companyId int, condition string) (count int, err error) {
-	sqlCount := ` SELECT COUNT(1) AS count  FROM (SELECT b.* FROM cygx_tag_history as a 
-	INNER JOIN cygx_tag AS b ON a.tag_id = b.tag_id 
-	LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = a.user_id `
+	sqlCount := ` SELECT COUNT(1) AS count  FROM (SELECT b.* FROM cygx_tag_history as r 
+	INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id  `
 	if condition != "" {
 		sqlCount += condition
 	}
-	sqlCount += ` WHERE a.company_id=? ) AS t `
+	sqlCount += ` WHERE r.company_id=? ) AS t `
 	o := orm.NewOrmUsingDB("hz_cygx")
 	err = o.Raw(sqlCount, companyId).QueryRow(&count)
 	return
 }
 
+// 获取数量
+func GetCygxTagHistoryCountByCompanyIdWeekly(companyId int, condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT COUNT(1) AS count  FROM (SELECT b.* FROM cygx_tag_history as r 
+	INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id
+	INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+`
+	if condition != "" {
+		sqlCount += condition
+	}
+	sqlCount += ` WHERE r.company_id=? ) AS t `
+
+	err = o.Raw(sqlCount, companyId).QueryRow(&count)
+	return
+}
+
 // 获取数量
 func GetCygxTagHistoryByCompanyId(companyId, startSize, pageSize int, condition string) (list []*UserInteraction, err error) {
-	sqlCount := ` SELECT a.real_name,a.mobile,ui.tag_num, a.create_time AS create_time,
+	sqlCount := ` SELECT r.real_name,r.mobile, r.create_time AS create_time,
 b.tag_id,b.tag_name,b.article_types,b.activity_types,b.industries,b.subject_names   
-FROM cygx_tag_history as a 
-	INNER JOIN cygx_tag AS b ON a.tag_id = b.tag_id  
-	LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = a.user_id `
+FROM cygx_tag_history as r 
+	INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id `
 	if condition != "" {
 		sqlCount += condition
 	}
 	sqlCount += ` 
-	WHERE a.company_id=? ORDER BY tag_num DESC ,create_time DESC LIMIT ?,? `
+	WHERE r.company_id=? ORDER BY  create_time DESC LIMIT ?,? `
 	o := orm.NewOrmUsingDB("hz_cygx")
 	_, err = o.Raw(sqlCount, companyId, startSize, pageSize).QueryRows(&list)
 	return
 }
 
+// 获取数量
+func GetCygxTagHistoryByCompanyIdWeekly(companyId, startSize, pageSize int, condition string) (list []*UserInteraction, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sqlCount := ` SELECT r.real_name,a.mobile, r.create_time AS create_time,
+			b.tag_id,b.tag_name,b.article_types,b.activity_types,b.industries,b.subject_names   
+			FROM cygx_tag_history as r
+				INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id 
+			INNER JOIN ` + databaseName + `.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 `
+	if condition != "" {
+		sqlCount += condition
+	}
+	sqlCount += ` 
+	WHERE r.company_id=? ORDER BY  create_time DESC LIMIT ?,? `
+
+	_, err = o.Raw(sqlCount, companyId, startSize, pageSize).QueryRows(&list)
+	return
+}
+
 // 获取数量
 func GetCygxTagHistoryCountByCompanyIds(companyIds, condition string) (count int, err error) {
 	sqlCount := ` SELECT a.real_name,a.mobile,b.*,ci.tag_num,ui.tag_num AS ui_tag_num,a.company_name  FROM cygx_tag_history as a  
@@ -144,7 +180,7 @@ LEFT JOIN cygx_user_interaction_num AS ui ON ui.user_id = a.user_id WHERE 1=1 `
 	if condition != "" {
 		sqlCount += condition
 	}
-	sqlCount += ` ORDER BY tag_num DESC ,ui_tag_num DESC , create_time DESC LIMIT ?,? `
+	sqlCount += `  ORDER BY  create_time DESC LIMIT ?,? `
 	o := orm.NewOrmUsingDB("hz_cygx")
 	_, err = o.Raw(sqlCount, startSize, pageSize).QueryRows(&list)
 	return
@@ -163,3 +199,66 @@ func GetCygxTagHistoryCountByCompanyIdCondition(condition string) (count int, er
 	err = o.Raw(sql).QueryRow(&count)
 	return
 }
+
+// 获取列表
+func GetCygxTagHistoryListBycondition(condition string, startSize, pageSize int) (list []*UserInteraction, err error) {
+	sql := ` SELECT r.real_name,r.mobile,r.company_name, r.create_time AS create_time,
+				b.tag_id,b.tag_name,b.article_types,b.activity_types,b.industries,b.subject_names
+				FROM cygx_tag_history as r 
+				INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id
+				WHERE 1=1 `
+	if condition != "" {
+		sql += condition
+	}
+	sql += `  ORDER BY  create_time DESC LIMIT ?,? `
+	o := orm.NewOrmUsingDB("hz_cygx")
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&list)
+	return
+}
+
+// 获取列表
+func GetCygxTagHistoryListByconditionWeekly(condition string, startSize, pageSize int) (list []*UserInteraction, err error) {
+	databaseName := utils.GetWeeklyDatabase()
+	sql := ` SELECT r.real_name,r.mobile,r.company_name, r.create_time AS create_time,
+				b.tag_id,b.tag_name,b.article_types,b.activity_types,b.industries,b.subject_names
+				FROM cygx_tag_history as r 
+				INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id
+				INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+				WHERE 1=1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	sql += `  ORDER BY  create_time DESC LIMIT ?,? `
+	o := orm.NewOrmUsingDB("hz_cygx")
+	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&list)
+	return
+}
+
+// 获取数量
+func GetCygxTagHistoryCount(condition string) (count int, err error) {
+	sql := ` SELECT COUNT(1) AS count  FROM cygx_tag_history as r 
+			INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id  WHERE 1 = 1 `
+	if condition != "" {
+		sql += condition
+	}
+	o := orm.NewOrmUsingDB("hz_cygx")
+	err = o.Raw(sql).QueryRow(&count)
+	return
+}
+
+// 获取数量
+func GetCygxTagHistoryCountWeekly(condition string) (count int, err error) {
+	o := orm.NewOrmUsingDB("hz_cygx")
+	databaseName := utils.GetWeeklyDatabase()
+	sql := ` SELECT COUNT(1) AS count  FROM cygx_tag_history as r 
+				INNER JOIN cygx_tag AS b ON r.tag_id = b.tag_id
+				INNER JOIN %s.user_seller_relation AS us ON us.user_id = r.user_id   AND us.product_id = 2 
+		WHERE 1 = 1 `
+	sql = fmt.Sprintf(sql, databaseName)
+	if condition != "" {
+		sql += condition
+	}
+	err = o.Raw(sql).QueryRow(&count)
+	return
+}

+ 4 - 0
models/db.go

@@ -260,7 +260,10 @@ func initCompany() {
 		new(company.CompanyNoRenewedNote),                    // 客户未续约记录
 		new(company.CompanyNoRenewedAscribe),                 // 确认不续约记录
 		new(company.CompanyNoRenewedAscribeLog),              // 确认不续约记录日志
+		new(company.CompanyContractNoRenewedAscribe),         // 合同确认不续约记录
+		new(company.CompanyContractNoRenewedAscribeLog),      // 合同确认不续约记录日志
 		new(company.CrmConfig),                               // 管理后台基本配置表
+		new(company.CompanyRenewalRecord),                    // 客户续约状态记录表
 	)
 }
 
@@ -453,6 +456,7 @@ func initCygx() {
 		new(cygx.CygxResourceDataIndustrialGroupManagement),
 		new(cygx.CygxResourceDataIndustrialGroupSubject),
 		new(cygx.CygxYanxuanSpecialAuthor),
+		new(cygx.CygxYanxuanSpecialApprovalLog),
 		new(cygx.CygxAllocationCompanyContract),
 		new(cygx.CygxAllocationCompanyContractLog),
 		new(cygx.CygxAllocationCompanyContractPermission),

+ 1 - 0
models/response/statistic_report.go

@@ -100,6 +100,7 @@ type StackCompanyListResp struct {
 type IncrementalCompanyListResp struct {
 	Paging                            *paging.PagingItem `description:"分页数据"`
 	List                              []*models.IncrementalList
+	ListPermissionName                []*models.CompanyContractPermissionNameGroupCountResp
 	TrialTotal                        int `description:"新增试用客户数"`
 	NewCompanyTotal                   int `description:"新签客户数"`
 	RenewalCompanyTotal               int `description:"续约客户数"`

+ 130 - 31
models/statistic_report.go

@@ -371,36 +371,39 @@ func GetIncomeList(condition string, pars []interface{}, startSize, pageSize int
 
 // 增量客户统计报表列表数据结构
 type IncrementalList struct {
-	CompanyContractId   int                                `description:"合同id"`
-	ContractType        string                             `description:"合同类型"`
-	CompanyId           int                                `description:"企业客户id"`
-	CompanyName         string                             `description:"企业客户名称"`
-	ProductId           int                                `description:"产品id"`
-	ProductName         string                             `description:"产品名称"`
-	CompanyProductId    int                                `description:"客户购买产品授权id"`
-	ContractCode        string                             `description:"合同编码"`
-	StartDate           string                             `description:"合同开始日期"`
-	EndDate             string                             `description:"合同结束日期"`
-	Money               float64                            `description:"合同金额"`
-	PayMethod           string                             `description:"付款方式"`
-	PayChannel          string                             `description:"付款渠道"`
-	ImgUrl              string                             `description:"合同图片"`
-	CreateTime          string                             `description:"合同创建时间"`
-	ModifyTime          string                             `description:"合同修改时间"`
-	Status              string                             `description:"合同审批状态,0:待审批,1:已审批;默认:1"`
-	RegionType          string                             `description:"企业客户所属区域;可选范围:国内,海外"`
-	SellerId            int                                `description:"归属销售id"`
-	SellerName          string                             `description:"归属销售名称"`
-	ExpireDay           string                             `description:"剩余可用天数"`
-	PermissionList      []*company.CompanyReportPermission `description:"产品权限"`
-	Count               int                                `json:"-" description:"合同数"`
-	RenewalReason       string                             `description:"未续约说明"`
-	RenewalTodo         string                             `description:"未续约说明中的待办事项说明"`
-	PackageDifference   string                             `description:"和上一份合同的区别"`
-	AscribeContent      string                             `description:"归因标签说明"`
-	IsShowNoRenewedNote bool                               `description:"是否展示未续约备注按钮"`
-	Content             string                             `description:"归因内容说明"`
-	PermissionName      string                             `description:"权限名"`
+	CompanyContractId    int                                `description:"合同id"`
+	ContractType         string                             `description:"合同类型"`
+	CompanyId            int                                `description:"企业客户id"`
+	CompanyName          string                             `description:"企业客户名称"`
+	ProductId            int                                `description:"产品id"`
+	ProductName          string                             `description:"产品名称"`
+	CompanyProductId     int                                `description:"客户购买产品授权id"`
+	ContractCode         string                             `description:"合同编码"`
+	StartDate            string                             `description:"合同开始日期"`
+	EndDate              string                             `description:"合同结束日期"`
+	Money                float64                            `description:"合同金额"`
+	PayMethod            string                             `description:"付款方式"`
+	PayChannel           string                             `description:"付款渠道"`
+	ImgUrl               string                             `description:"合同图片"`
+	CreateTime           string                             `description:"合同创建时间"`
+	ModifyTime           string                             `description:"合同修改时间"`
+	Status               string                             `description:"合同审批状态,0:待审批,1:已审批;默认:1"`
+	RegionType           string                             `description:"企业客户所属区域;可选范围:国内,海外"`
+	SellerId             int                                `description:"归属销售id"`
+	SellerName           string                             `description:"归属销售名称"`
+	ExpireDay            string                             `description:"剩余可用天数"`
+	PermissionList       []*company.CompanyReportPermission `description:"产品权限"`
+	Count                int                                `json:"-" description:"合同数"`
+	RenewalReason        string                             `description:"未续约说明"`
+	RenewalTodo          string                             `description:"未续约说明中的待办事项说明"`
+	PackageDifference    string                             `description:"和上一份合同的区别"`
+	AscribeContent       string                             `description:"归因标签说明"`
+	IsShowNoRenewedNote  bool                               `description:"是否展示未续约备注按钮"`
+	Content              string                             `description:"归因内容说明"`
+	PermissionName       string                             `description:"权限名"`
+	PermissionNameExport string                             `description:"权限名导出时使用"`
+	PermissionNameStatus string                             `description:"权限状态"`
+	CompanyProductStatus string                             `description:"客户状态"`
 	//CompanyContractIdGroup string                             `description:"表company_contract合并的 company_contract_id"`
 }
 
@@ -889,7 +892,103 @@ func GetIncrementalCompanyListByOperationRecordMerge(condition string, pars []in
 	if condition != "" {
 		sql += condition
 	}
-	sql += ` group by a.company_contract_id  order by start_date desc,company_id desc limit ?,?`
+	sql += ` group by a.company_contract_id  order by end_date desc,company_id desc limit ?,?`
 	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
 	return
 }
+
+// GetIncrementalCompanyListByOperationRecordMerge 未续约合同
+func GetIncrementalCompanyListByOperationRecordMerge879() (items []*IncrementalList, err error) {
+	o := orm.NewOrm()
+	//查询真正的数据
+	sql := `SELECT
+	a.company_contract_id,
+	a.contract_type,
+	a.company_product_id,
+	a.contract_code,
+	a.pay_method,
+	a.pay_channel,
+	a.package_difference,
+	a.company_id,
+	a.start_date,
+	a.end_date,
+	a.money,
+	b.company_name,
+	c.seller_id,
+	c.seller_name,
+	a.product_id,
+	a.product_name,
+	a.create_time,
+	b.region_type,
+	c.renewal_reason,
+	c.renewal_todo,
+	c.STATUS 
+FROM
+	company_contract a
+	RIGHT JOIN company b ON a.company_id = b.company_id
+	JOIN company_product c ON b.company_id = c.company_id 
+	AND a.product_id = c.product_id 
+WHERE
+	1 = 1 
+	AND c.product_id = 2
+	AND a.STATUS = 1 
+	AND a.end_date >= '2017-09-05'
+	AND a.end_date <= '2022-12-31'
+	AND c.STATUS NOT IN ( "永续", "正式", "关闭" ) 
+	AND a.company_contract_id NOT IN (SELECT company_contract_id FROM company_contract_no_renewed_ascribe ) 
+GROUP BY
+	a.company_contract_id 
+ORDER BY
+	end_date DESC,
+	company_id DESC  limit	 10
+`
+	_, err = o.Raw(sql).QueryRows(&items)
+	return
+}
+
+// GetIncrementalNewCompanyList 获取增量客户报表列表数据(根据合同来展示)
+func GetIncrementalCompanyPermissionList(condition string, pars []interface{}, startSize, pageSize int) (items []*IncrementalList, err error) {
+	o := orm.NewOrm()
+
+	sql := `SELECT a.*,b.region_type,c.seller_id,c.seller_name,b.company_name,c.renewal_reason, c.status as  company_product_status, d.permission_name as permission_name_export FROM company_contract a
+		 JOIN company b ON a.company_id = b.company_id
+		 JOIN company_product c ON a.company_id = c.company_id 
+		 JOIN company_contract_permission d ON d.company_contract_id = a.company_contract_id
+		 and a.product_id=c.product_id   WHERE 1 = 1 `
+
+	if condition != "" {
+		sql += condition
+	}
+	sql += ` group by d.company_contract_id,d.permission_name   order by start_date desc,company_id desc limit ?,?`
+	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+type CompanyContractPermissionNameGroupCountResp struct {
+	Total          int    `description:"数量"`
+	PermissionName string `description:"权限名"`
+}
+
+// GetCompanyContractPermissionNameGroupCount 获取增量客户产品报表列表统计数据(根据合同来展示)
+func GetCompanyContractPermissionNameGroupCount(condition string, pars []interface{}) (items []*CompanyContractPermissionNameGroupCountResp, err error) {
+	o := orm.NewOrm()
+	sql := `SELECT
+			COUNT( DISTINCT d.permission_name, d.company_contract_id ) total,
+			d.permission_name 
+		FROM
+			company_contract a
+			JOIN company b ON a.company_id = b.company_id
+			JOIN company_product c ON a.company_id = c.company_id 
+			AND a.product_id = c.product_id
+			JOIN company_contract_permission d ON d.company_contract_id = a.company_contract_id 
+		WHERE
+			1 = 1 
+			AND d.permission_name IN ( '医药', '消费', '科技', '智造', '策略', '买方研选' ) `
+
+	if condition != "" {
+		sql += condition
+	}
+	sql += `GROUP BY d.permission_name `
+	_, err = o.Raw(sql, pars).QueryRows(&items)
+	return
+}

+ 14 - 0
models/wx_user.go

@@ -585,3 +585,17 @@ func GetWxUserList(condition string, pars []interface{}) (items []*WxUser, err e
 	_, err = o.Raw(sql, pars).QueryRows(&items)
 	return
 }
+
+func SetUserFollow(userId, follow int) (err error) {
+	o := orm.NewOrm()
+	sql := ` UPDATE wx_user SET is_follow=? WHERE user_id=? `
+	_, err = o.Raw(sql, follow, userId).Exec()
+	return
+}
+
+func GetCompanyFollowCount(companyId int) (count int, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT COUNT(1) FROM wx_user WHERE company_id=? AND is_follow = 1 `
+	err = o.Raw(sql, companyId).QueryRow(&count)
+	return
+}

+ 90 - 0
routers/commentsRouter.go

@@ -3022,6 +3022,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"],
+        beego.ControllerComments{
+            Method: "ApprovalLogList",
+            Router: `/yanxuan_special/approval_log_list`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"],
         beego.ControllerComments{
             Method: "Add",
@@ -3067,6 +3076,42 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"],
+        beego.ControllerComments{
+            Method: "ListPv",
+            Router: `/yanxuan_special/list_pv`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"],
+        beego.ControllerComments{
+            Method: "ShowButton",
+            Router: `/yanxuan_special/show_button`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"],
+        beego.ControllerComments{
+            Method: "SpecialAuthorFansList",
+            Router: `/yanxuan_special/special_author_fans_list`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/cygx:YanxuanSpecialController"],
+        beego.ControllerComments{
+            Method: "SpecialCollectList",
+            Router: `/yanxuan_special/special_collect/list`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/data_manage/correlation:CorrelationChartClassifyController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers/data_manage/correlation:CorrelationChartClassifyController"],
         beego.ControllerComments{
             Method: "AddChartClassify",
@@ -9421,6 +9466,24 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyRenewalController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyRenewalController"],
+        beego.ControllerComments{
+            Method: "CompanyContractNoRenewedAscribeAdd",
+            Router: `/company_contract_no_renewed_ascribe/add`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyRenewalController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyRenewalController"],
+        beego.ControllerComments{
+            Method: "CompanyContractNoRenewedAscribeAddDetail",
+            Router: `/company_contract_no_renewed_ascribe/detail`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyRenewalController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyRenewalController"],
         beego.ControllerComments{
             Method: "CompanyNoRenewedAscribeAdd",
@@ -9628,6 +9691,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyUserController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyUserController"],
+        beego.ControllerComments{
+            Method: "Follow",
+            Router: `/follow`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyUserController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:CompanyUserController"],
         beego.ControllerComments{
             Method: "GetCompanySellerList",
@@ -10312,6 +10384,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticCompanyMergerController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticCompanyMergerController"],
+        beego.ControllerComments{
+            Method: "CompanyContractPermissionList",
+            Router: `/merge_company/company_contract_permission/list`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticCompanyMergerController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticCompanyMergerController"],
         beego.ControllerComments{
             Method: "MergeCompanyList",
@@ -10465,6 +10546,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"],
+        beego.ControllerComments{
+            Method: "UnusualRenewCompanyStatistics",
+            Router: `/report/unusual_renew_company`,
+            AllowHTTPMethods: []string{"get"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"] = append(beego.GlobalControllerRouter["hongze/hz_crm_api/controllers:StatisticReportController"],
         beego.ControllerComments{
             Method: "StackCompanyList",

+ 80 - 3
services/company_apply/company_approval.go

@@ -419,9 +419,10 @@ func Approved(approvalRecord *contract.ContractApprovalRecord, opUser *system.Ad
 
 				//客户研选行业转正时(王芳审批通过),模板消息提醒汪洋
 				services.AddCompanyApprovalMessageWangYang(recordInfo.CompanyId, recordInfo.CompanyContractId, recordInfo.ApplyRealName, companyInfo.CompanyName)
-				cygxService.YanXuanCompanyApproval(recordInfo.CompanyId)                           //研选审批通过的时候研选扣点更新
-				cygxService.HandleAllocationCompanyContractByYanXuan(recordInfo.CompanyContractId) //如果合同只有研选的时候,自动处理派点
-				cygxService.HandleCompanyContractPackageDifference(recordInfo.CompanyContractId)   // 更新与上一份合同的金额的对比 '增加套餐','减少套餐','维持套餐'
+				cygxService.YanXuanCompanyApproval(recordInfo.CompanyId)                              //研选审批通过的时候研选扣点更新
+				cygxService.HandleAllocationCompanyContractByYanXuan(recordInfo.CompanyContractId)    //如果合同只有研选的时候,自动处理派点
+				cygxService.HandleCompanyContractPackageDifference(recordInfo.CompanyContractId)      // 更新与上一份合同的金额的对比 '增加套餐','减少套餐','维持套餐'
+				cygxService.HandleCompanyContractPermissionContractType(recordInfo.CompanyContractId) // 更新合同权限表中的权限名称,以及对应的行业权限类型(行业新签、行业续约)
 			}
 		}()
 	} else {
@@ -757,6 +758,9 @@ func afterApproved(companyApprovalId int, opUserId int, opUserName string) (err
 
 		//如果合同时间小于等于今天,那么立马执行合同内容
 		if time.Now().After(contractStartDate) {
+			// 合同处理完成后的续约异常记录
+			contactHandleCompanyRenewalRecord(contractInfo)
+
 			startDate = contractInfo.StartDate
 			endDate = contractInfo.EndDate
 			companyReportPermissionList, err = company.ApplyServiceUpdate(recodeInfo.CompanyId, recodeInfo.ProductId, opUser.AdminId, recodeInfo.CompanyApprovalId, recodeInfo.CompanyContractId, companyProduct.StartDate, contractInfo.EndDate, opUser.RealName, companyProduct.ProductName, contractInfo.PackageType, contractInfo.RaiPackageType)
@@ -887,6 +891,79 @@ func afterApproved(companyApprovalId int, opUserId int, opUserName string) (err
 	return
 }
 
+// contactHandleCompanyRenewalRecord
+// @Description: 合同处理完成后的续约异常记录
+// @author: Roc
+// @datetime 2023-12-07 14:24:44
+// @param contractInfo *company_contract.CompanyContract
+// @param day string
+// @return err error
+func contactHandleCompanyRenewalRecord(contractInfo *company.CompanyContractDetail) {
+	var err error
+	defer func() {
+		if err != nil {
+			utils.FileLog.Error("合同处理完成后的续约异常记录," + err.Error())
+		}
+	}()
+	// 判断合同类型是否是续约合同,如果不是的话,就不往下走了
+	if contractInfo.ContractType != `续约合同` {
+		return
+	}
+
+	day := time.Now().Format(utils.FormatDate)
+
+	// 获取早于当前合同结束日期的上一份合同
+	lastContract, tmpErr := company.GetLastContractListByEndDate(contractInfo.CompanyId, contractInfo.ProductId, contractInfo.EndDate)
+	if tmpErr != nil {
+		err = errors.New(fmt.Sprint("合同id:", contractInfo.CompanyContractId, ";通过最近一份合同的日期获取早于该合同的最晚一份合同失败,ERR:", tmpErr))
+		return
+	}
+	// 校验 上一份合同的结束日期 与 今天 相隔的天数
+	betweenDay, tmpErr := utils.GetDaysBetween2Date(utils.FormatDate, day, lastContract.EndDate)
+	if tmpErr != nil {
+		err = errors.New(fmt.Sprint("合同id:", contractInfo.CompanyContractId, ";计算两个日期相差的天数失败,ERR:", tmpErr))
+		return
+	}
+
+	source := 2 // 正常续约
+	// 如果间隔时间超过60天,那么标记为超时续约
+	if betweenDay > 60 {
+		source = 3 // 超时续约
+	}
+
+	// 如果间隔时间超过60天,那么标记为超时续约
+	companyProductItem, tmpErr := company.GetCompanyProductItemByCompanyId(contractInfo.CompanyId, contractInfo.ProductId)
+	if tmpErr != nil {
+		err = errors.New(fmt.Sprint("合同id:", contractInfo.CompanyContractId, ";GetCompanyProductItemByCompanyId失败,ERR:", tmpErr))
+		return
+	}
+
+	var shareSellerId int
+	var shareSellerName string
+	if companyProductItem.IsShare == 1 {
+		shareSellerId = companyProductItem.ShareSellerId
+		shareSellerName = companyProductItem.ShareSeller
+	}
+	item := &company.CompanyRenewalRecord{
+		Id:              0,
+		CompanyId:       contractInfo.CompanyId,
+		ProductId:       contractInfo.ProductId,
+		Source:          source,
+		SellerId:        companyProductItem.SellerId,
+		SellerName:      companyProductItem.SellerName,
+		ShareSellerId:   shareSellerId,
+		ShareSellerName: shareSellerName,
+		CreateTime:      time.Now(),
+		ModifyTime:      time.Now(),
+	}
+	tmpErr = item.Add()
+	if tmpErr != nil {
+		err = errors.New(fmt.Sprint("合同id:", contractInfo.CompanyContractId, ";添加续约异常记录失败,ERR:", tmpErr))
+	}
+
+	return
+}
+
 // afterReject 驳回完成后操作
 func afterReject(companyApprovalId, opUserId int, opUserName, remark string) (err error) {
 	defer func() {

+ 31 - 0
services/company_ascribe.go

@@ -67,3 +67,34 @@ func GetCompanyNoRenewedNoteMap(companyIds []int) (mapResp map[string]bool) {
 	}
 	return
 }
+
+// 处理公司合同归因展示
+func GetCompanyContractAscribeContentMap(companyContractIds []int) (mapResp map[int]string, mapCountResp map[int]string) {
+	var err error
+	defer func() {
+		if err != nil {
+			fmt.Println("err:", err)
+			go alarm_msg.SendAlarmMsg(" 处理公司归因展示失败 GetCompanyContractAscribeContentMap,Err:"+err.Error(), 3)
+		}
+	}()
+	lenArr := len(companyContractIds)
+	if lenArr == 0 {
+		return
+	}
+	var condition string
+	var pars []interface{}
+	condition = ` AND company_contract_id IN (` + utils.GetOrmInReplace(len(companyContractIds)) + `)`
+	pars = append(pars, companyContractIds)
+	list, e := company.GetCompanyContractNoRenewedAscribeList(condition, pars, 0, 0)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCompanyNoRenewedAscribeList, Err: " + e.Error())
+		return
+	}
+	mapResp = make(map[int]string, 0)
+	mapCountResp = make(map[int]string, 0)
+	for _, v := range list {
+		mapResp[v.CompanyContractId] = v.AscribeContent
+		mapCountResp[v.CompanyContractId] = v.Content
+	}
+	return
+}

+ 16 - 11
services/cygx/acitvity.go

@@ -832,17 +832,6 @@ func IsShowAppointmentByadminSet(IsCanAppointmentMinutes int) (isShowAppointment
 
 // 处理活动是否进行模板消息推送
 func DoActivityOnenIdWxTemplateMsg(activityId int) (err error) {
-	//10分钟之内的活动二次编辑不重复推送
-	cacheKey := fmt.Sprint("Source:ADMIN", "_ActivityId:", activityId)
-	isExist := utils.Rc.IsExist(cacheKey)
-	if isExist {
-		return err
-	}
-	setNX := utils.Rc.SetNX(cacheKey, activityId, time.Minute*10)
-	if !setNX {
-		go alarm_msg.SendAlarmMsg("发送模版消息失败,10分钟之内的活动二次编辑不重复推送,设置Redis Key 过期时间失败:key"+cacheKey, 3)
-		return err
-	}
 	var weekday string
 	weekday = time.Now().Weekday().String()
 	if weekday == "Sunday" {
@@ -866,6 +855,22 @@ func DoActivityOnenIdWxTemplateMsg(activityId int) (err error) {
 		return
 	}
 
+	if activityInfo.VisibleRange == 1 {
+		return //只要是仅对本组可见的活动,发布时,模板消息统一不发送, p2_876
+	}
+
+	//10分钟之内的活动二次编辑不重复推送
+	cacheKey := fmt.Sprint("Source:ADMIN", "_ActivityId:", activityId)
+	isExist := utils.Rc.IsExist(cacheKey)
+	if isExist {
+		return err
+	}
+	setNX := utils.Rc.SetNX(cacheKey, activityId, time.Minute*10)
+	if !setNX {
+		go alarm_msg.SendAlarmMsg("发送模版消息失败,10分钟之内的活动二次编辑不重复推送,设置Redis Key 过期时间失败:key"+cacheKey, 3)
+		return err
+	}
+
 	var chartPermissionIds string
 	var chartPermissionName string
 	//专家权限可以查看以参加以下活动的类型 1:专家电话会 、3:公司调研电话会、4:公司线下调研、5:专家线下沙龙

+ 91 - 0
services/cygx/activity_meet.go

@@ -347,3 +347,94 @@ func AddctivitySignupDetailListByHand(itemsDetail []*cygx.CygxActivityAttendance
 
 	return err
 }
+
+// AddctivitySignupDetailListByAdminSignup 已结束的活动,管理员手动添加报名,把信息写入到联系人列表参会信息中
+func AddctivitySignupDetailListByAdminSignup(activityIdsStr string) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println(err)
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("已结束的活动,管理员手动添加报名,把信息写入到联系人列表参会信息中 ErrMsg:"+err.Error(), "activityIds:", activityIdsStr), 2)
+		}
+	}()
+
+	var condition string
+	var pars []interface{}
+	condition = ` AND active_state = 3 AND  activity_id IN (` + activityIdsStr + `)  `
+	list, e := cygx.GetActivityListAll(condition, pars, 0, 9999)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetWxUserOutboundMobiles, Err: " + e.Error())
+		return
+	}
+	if len(list) == 0 {
+		return
+	}
+
+	var activityIds []int
+
+	for _, v := range list {
+		activityIds = append(activityIds, v.ActivityId)
+	}
+
+	actLen := len(activityIds)
+	condition = ` AND activity_id IN (` + utils.GetOrmInReplace(actLen) + `)`
+	pars = append(pars, activityIds)
+
+	//获取已经写入的信息,并建立map
+	signUpDetailList, err := cygx.GetSignupDetailList(condition, pars)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		return err
+	}
+	mapsignUpDetai := make(map[string]string)
+	if len(signUpDetailList) > 0 {
+		for _, v := range signUpDetailList {
+			mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", v.Mobile)] = v.Mobile
+		}
+	}
+
+	pars = make([]interface{}, 0)
+	condition = ` AND activity_id IN (` + utils.GetOrmInReplace(actLen) + `) AND do_fail_type = 0`
+	pars = append(pars, activityIds)
+	//获取成功报名的人员信息
+	signUpList, err := cygx.GetSignupDetailBySignup(condition, pars)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		return err
+	}
+	//建立外呼号与手机号的绑定
+	mapsignUp := make(map[string]string)
+	if len(signUpList) > 0 {
+		for _, v := range signUpList {
+			mapsignUp[fmt.Sprint(v.OutboundMobile)] = v.Mobile
+		}
+	}
+	var items []*cygx.CygxActivitySignupDetail
+	if len(signUpList) > 0 {
+		for _, v := range signUpList {
+			if _, ok := mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", v.Mobile)]; !ok {
+				item := new(cygx.CygxActivitySignupDetail)
+				item.UserId = v.UserId
+				item.RealName = v.RealName
+				item.SellerName = v.SellerName
+				item.ActivityId = v.ActivityId
+				item.CreateTime = v.CreateTime
+				item.Mobile = v.Mobile
+				item.OutboundMobile = v.OutboundMobile
+				item.Email = v.Email
+				item.CompanyId = v.CompanyId
+				item.CompanyName = v.CompanyName
+				item.SignupType = v.SignupType
+				item.FailType = v.FailType
+				item.DoFailType = v.DoFailType
+				items = append(items, item)
+			}
+		}
+	}
+	if len(items) > 0 {
+		e = cygx.AddCygxActivitySignupDetail(items)
+		if e != nil {
+			err = errors.New("AddCygxActivitySignupDetail, Err: " + e.Error())
+			return
+		}
+	}
+
+	return err
+}

+ 2 - 0
services/cygx/activity_ocr.go

@@ -219,6 +219,7 @@ func UpdateActivityVideoAndVoice(activityInfo *cygx.ActivityDetail, itemVoice *c
 				err = errors.New("UpdateCygxActivityVoice" + e.Error())
 				return
 			}
+			go UpdateActivityVoiceResourceData(voiceDetail.ActivityVoiceId) //写入首页最新  cygx_resource_data 表
 		}
 	} else {
 		voiceDetail, e := cygx.GetCygxActivityVoiceReqDetail(activityId)
@@ -293,6 +294,7 @@ func UpdateActivityVideoAndVoice(activityInfo *cygx.ActivityDetail, itemVoice *c
 				err = errors.New("UpdateCygxActivityVideo" + e.Error())
 				return
 			}
+			go UpdateActivityVideoResourceData(videoDetail.VideoId) //写入首页最新  cygx_resource_data 表
 		}
 	} else {
 		//删除原有的视频数据

+ 1 - 1
services/cygx/activity_permission.go

@@ -18,7 +18,7 @@ func GetAdminActivityPermission(adminInfo *system.Admin, condition string) (cond
 	}
 	var adminidStr string
 	adminidStr = strings.Join(adminIdArr, ",")
-	conditionPermission = ` OR (art.activity_type_id = 7 AND  visible_range = 1 AND art.admin_id IN (` + adminidStr + `) ` + condition + `) `
+	conditionPermission = ` OR ( visible_range = 1 AND art.admin_id IN (` + adminidStr + `) ` + condition + `) `
 	//conditionPermission += ` OR (art.activity_type_id = 7 AND  visible_range != 1  ` + condition + `) `
 	return
 }

+ 37 - 37
services/cygx/activity_special.go

@@ -441,11 +441,11 @@ func GetChartPermissionSpecialSurplusByCompany(companyId int) (userType int, tri
 			err = errors.New("GetActivitySpecialTripCountByActivitySpecial, Err: " + e.Error())
 			return
 		}
-		// 获取继承点数
-		inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
-		}
+		//// 获取继承点数
+		//inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
+		//if e != nil && e.Error() != utils.ErrNoRow() {
+		//	err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
+		//}
 		if userType == 2 {
 
 			var tripBillNum int
@@ -455,13 +455,13 @@ func GetChartPermissionSpecialSurplusByCompany(companyId int) (userType int, tri
 				//}
 				tripBillNum += v.BillDetailed
 			}
-			if len(inheritList) > 0 {
-				for _, v := range inheritList {
-					if v.ChartPermissionId == 0 {
-						tripBillNum += v.Points
-					}
-				}
-			}
+			//if len(inheritList) > 0 {
+			//	for _, v := range inheritList {
+			//		if v.ChartPermissionId == 0 {
+			//			tripBillNum += v.Points
+			//		}
+			//	}
+			//}
 
 			tripRemaining = tripBillNum
 			if tripRemaining < 0 {
@@ -517,9 +517,9 @@ func GetChartPermissionSpecialSurplusByCompany(companyId int) (userType int, tri
 				}
 			}
 			// 通过继承获得的加点
-			for _, v := range inheritList {
-				mapInheritChartName[v.ChartPermissionName] = v.Points
-			}
+			//for _, v := range inheritList {
+			//	mapInheritChartName[v.ChartPermissionName] = v.Points
+			//}
 			for k, _ := range chartNameMap {
 				if _, ok := mapChartName[k]; ok {
 					if inherit, ok2 := mapInheritChartName[k]; ok2 {
@@ -543,10 +543,10 @@ func GetChartPermissionSpecialSurplusByCompany(companyId int) (userType int, tri
 func ActivitySpecialCompanyApproval(companyId int, companyName string) (err error) {
 	userType, packageType, _, _, _ := GetUserType(companyId)
 	// 获取继承点数
-	inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
-	if e != nil && e.Error() != utils.ErrNoRow() {
-		err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
-	}
+	//inheritList, e := cygx.GetCygxActivitySpecialInheritPointsByCompanyId(companyId)
+	//if e != nil && e.Error() != utils.ErrNoRow() {
+	//	err = errors.New("GetCygxActivitySpecialInheritPointsByCompanyId, Err: " + e.Error())
+	//}
 	chartNameMap := map[string]int{utils.YI_YAO_NAME: 0, utils.XIAO_FEI_NAME: 0, utils.KE_JI_NAME: 0, utils.ZHI_ZAO_NAME: 0}
 
 	itemBill := new(cygx.CygxActivitySpecialTripBill)
@@ -556,21 +556,21 @@ func ActivitySpecialCompanyApproval(companyId int, companyName string) (err erro
 	itemBill.Source = 2
 	itemBill.DoType = 2
 	itemBill.Way = 3
-	if userType == 2{
+	if userType == 2 {
 		packageTypeMap := map[int]int{1: 16, 2: 10}
 		totalTrip := packageTypeMap[packageType]
-		if len(inheritList) > 0 {
-			for _, v := range inheritList {
-				if v.ChartPermissionId == 0 {
-					itemBill.BillDetailed = totalTrip + v.Points
-				} else {
-					itemBill.BillDetailed = totalTrip
-				}
-			}
-		} else {
-			itemBill.BillDetailed = totalTrip
-		}
-
+		//if len(inheritList) > 0 {
+		//	for _, v := range inheritList {
+		//		if v.ChartPermissionId == 0 {
+		//			itemBill.BillDetailed = totalTrip + v.Points
+		//		} else {
+		//			itemBill.BillDetailed = totalTrip
+		//		}
+		//	}
+		//} else {
+		//	itemBill.BillDetailed = totalTrip
+		//}
+		itemBill.BillDetailed = totalTrip
 		itemBill.Total = strconv.Itoa(itemBill.BillDetailed) + "次"
 		if totalTrip == 10 {
 			itemBill.Content = "45w大套餐转正"
@@ -618,9 +618,9 @@ func ActivitySpecialCompanyApproval(companyId int, companyName string) (err erro
 			}
 		}
 		// 通过继承获得的加点
-		for _, v := range inheritList {
-			mapInheritChartName[v.ChartPermissionName] = v.Points
-		}
+		//for _, v := range inheritList {
+		//	mapInheritChartName[v.ChartPermissionName] = v.Points
+		//}
 		for k, _ := range chartNameMap {
 			if _, ok := mapChartName[k]; ok {
 				if inherit, ok2 := mapInheritChartName[k]; ok2 {
@@ -685,7 +685,7 @@ func GetSpecialSurplusByCompanyNew(companyId int) (specialSurplus string, err er
 	//chartMap := map[int]string{utils.YI_YAO_ID:utils.YI_YAO_NAME, utils.XIAO_FEI_ID:utils.XIAO_FEI_NAME, utils.KE_JI_ID:utils.KE_JI_NAME, utils.ZHI_ZAO_ID:utils.ZHI_ZAO_NAME}
 	//chartNumMap := map[int]int{utils.YI_YAO_ID:0, utils.XIAO_FEI_ID:0, utils.KE_JI_ID:0, utils.ZHI_ZAO_ID:0}
 	if companyDetail.Status == "正式" {
-		billItem,e := cygx.GetCygxActivitySpecialTripBillByCompanyId(companyId)
+		billItem, e := cygx.GetCygxActivitySpecialTripBillByCompanyId(companyId)
 		if e != nil && e.Error() != utils.ErrNoRow() {
 			err = e
 			return
@@ -696,4 +696,4 @@ func GetSpecialSurplusByCompanyNew(companyId int) (specialSurplus string, err er
 		return
 	}
 	return
-}
+}

+ 23 - 0
services/cygx/admin_power.go

@@ -33,6 +33,29 @@ func GetAdminLookUserMobile(adminInfo *system.Admin) (mapMobile map[string]strin
 	return
 }
 
+// 获取这个销售所能查看的手机号权限
+func GetAdminLookUserUserId(adminInfo *system.Admin) (userIds []int, err error) {
+	var conditionMobile string
+	if adminInfo.RoleTypeCode == "rai_group" {
+		//组长查看本组所有组员
+		conditionMobile = ` SELECT user_id FROM user_seller_relation WHERE seller_id IN (SELECT  admin_id FROM admin WHERE group_id = (SELECT group_id FROM admin WHERE admin_id = ` + strconv.Itoa(adminInfo.AdminId) + ` )) `
+	} else {
+		//组员查看自己
+		conditionMobile = ` SELECT user_id FROM user_seller_relation WHERE seller_id  = ` + strconv.Itoa(adminInfo.AdminId)
+	}
+	conditionMobile += " LIMIT 10"
+	userList, e := cygx.GetSellerUserMobile(conditionMobile)
+	if e != nil {
+		err = errors.New("GetSellerUserMobile 获取这个销售所能查看的手机号权限失败, Err: " + e.Error())
+		return
+	}
+	userIds = make([]int, 0)
+	for _, v := range userList {
+		userIds = append(userIds, v.UserId)
+	}
+	return
+}
+
 // 获取这个销售所能查看的手机号权限
 func GetAdminLookUserCompanyIds(sysUser *system.Admin) (companyIds []int, err error) {
 	//如果不是管理员,权益管理员那么就对可见权限范围做处理

+ 211 - 0
services/cygx/article.go

@@ -84,6 +84,217 @@ func GetArticleSourcePlatform(SourcePlatform string) (sourcePlatformResp int) {
 		sourcePlatformResp = 2
 	} else if SourcePlatform == "CELUE" {
 		sourcePlatformResp = 3
+	} else if SourcePlatform == "1" {
+		sourcePlatformResp = 1
+	} else if SourcePlatform == "2" {
+		sourcePlatformResp = 2
+	}
+	return
+}
+
+//func init() {
+//	GetArticleSubjectLabelByArticleId([]int{9551, 9082})
+//}
+
+// 根据文章ID获取文章关联的产业名称
+func GetArticleIndustrialLabelByArticleId(articleIds []int) (respMap map[int][]string) {
+	if len(articleIds) == 0 {
+		return
+	}
+	var err error
+	defer func() {
+		if err != nil {
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据文章ID获取文章关联的产业名称失败 GetArticleIndustrialLabelByArticleId rticleIds: ", articleIds, err.Error()), 2)
+		}
+	}()
+	list, e := cygx.GetIndustrialArticleGroupListByarticleIdsArr(articleIds)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetIndustrialArticleGroupListByarticleIdsArr, Err: " + e.Error())
+		return
+	}
+	respMap = make(map[int][]string, 0)
+	for _, v := range list {
+		respMap[v.ArticleId] = append(respMap[v.ArticleId], v.IndustryName)
+	}
+	return
+}
+
+// 根据文章ID获取文章关联的标的名称
+func GetArticleSubjectLabelByArticleId(articleIds []int) (respMap map[int][]string) {
+	if len(articleIds) == 0 {
+		return
+	}
+	var err error
+	defer func() {
+		if err != nil {
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据文章ID获取文章关联的产业名称 失败 GetArticleSubjectLabelByArticleId rticleIds: ", articleIds, err.Error()), 2)
+		}
+	}()
+
+	list, e := cygx.GetSubjectArticleGroupListByarticleIdsArr(articleIds)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetIndustrialArticleGroupListByarticleIdsArr, Err: " + e.Error())
+		return
+	}
+	respMap = make(map[int][]string, 0)
+	for _, v := range list {
+		respMap[v.ArticleId] = append(respMap[v.ArticleId], v.SubjectName)
+	}
+	return
+}
+
+// 根据作者ID获取关联的文章下面的产业名称
+func GetArticleIndustrialLabelByDepartmentId(departmentIds []int) (respMap map[int][]string) {
+	lenArr := len(departmentIds)
+	if lenArr == 0 {
+		return
+	}
+	var err error
+	defer func() {
+		if err != nil {
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("根据文章ID获取文章关联的产业名称失败 GetArticleIndustrialLabelByDepartmentId departmentIds: ", departmentIds, err.Error()), 2)
+		}
+	}()
+	var condition string
+	var pars []interface{}
+	condition = " AND department_id IN(" + utils.GetOrmInReplace(lenArr) + ")  ORDER BY publish_date DESC "
+	pars = append(pars, departmentIds)
+	//获取作者关联的文章
+	listArticle, e := cygx.GetArticlList(condition, pars, 0, 9999)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetArticlList, Err: " + e.Error())
+		return
+	}
+	var articleIds []int
+	for _, v := range listArticle {
+		articleIds = append(articleIds, v.ArticleId)
+	}
+	//获取文章关联的产业
+	list, e := cygx.GetIndustrialArticleGroupListByarticleIdsArr(articleIds)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetIndustrialArticleGroupListByarticleIdsArr, Err: " + e.Error())
+		return
+	}
+	respMap = make(map[int][]string, 0)
+
+	artMap := make(map[int][]string)
+	for _, v := range list {
+		artMap[v.ArticleId] = append(respMap[v.ArticleId], v.IndustryName)
+	}
+
+	//建立作者与文章、产业的关系
+	for _, v := range listArticle {
+		if len(artMap[v.ArticleId]) == 0 {
+			continue
+		}
+		respMap[v.DepartmentId] = append(respMap[v.DepartmentId], strings.Join(artMap[v.ArticleId], "/"))
+	}
+	return
+}
+
+// 处理文章、研选专栏的查询信息回显
+func HandleArticleAndYanxuanRecordList(items []*cygx.CygxArticleAndYanxuanRecordResp) (itemsResp []*cygx.UserInteraction, err error) {
+	itemsResp = make([]*cygx.UserInteraction, 0)
+	if len(items) > 0 {
+
+		var articleIds []int        // 文章ID
+		var yanxuanSpecialIds []int // 研选专栏ID
+		var sellerCompanyIds []int  // 公司ID
+		for _, v := range items {
+			if v.Source == utils.CYGX_OBJ_ARTICLE {
+				articleIds = append(articleIds, v.SourceId)
+			}
+			if v.Source == utils.CYGX_OBJ_YANXUANSPECIAL {
+				yanxuanSpecialIds = append(yanxuanSpecialIds, v.SourceId)
+			}
+			sellerCompanyIds = append(sellerCompanyIds, v.CompanyId)
+		}
+
+		sellNameMap := services.GetSellNameMapByCompanyIds(sellerCompanyIds)
+
+		mapIndustrialLabel := GetArticleIndustrialLabelByArticleId(articleIds) // 关联产业
+		mapSubjectLabel := GetArticleSubjectLabelByArticleId(articleIds)       // 关联标的
+		var condition string
+		var pars []interface{}
+
+		//获取文章map
+		mapArticle := make(map[int]*cygx.CygxReportArticle)
+		lenarticleIds := len(articleIds)
+		if lenarticleIds > 0 {
+			condition = " AND art.article_id IN  (" + utils.GetOrmInReplace(lenarticleIds) + ")  GROUP  BY art.article_id "
+			pars = append(pars, articleIds)
+			list, e := cygx.GetReportArticleList(condition, pars, 0, lenarticleIds, 1)
+			if e != nil && e.Error() != utils.ErrNoRow() {
+				err = e
+				return
+			}
+
+			if len(list) > 0 {
+				for _, v := range list {
+					mapArticle[v.ArticleId] = v
+				}
+			}
+		}
+
+		//获取研选专栏map
+		mapYanxuanSpecial := make(map[int]*cygx.CygxYanxuanSpeciaResplItem)
+		lenyanxuanSpecialIds := len(yanxuanSpecialIds)
+		if lenyanxuanSpecialIds > 0 {
+			pars = make([]interface{}, 0)
+			condition = " AND a.id IN  (" + utils.GetOrmInReplace(lenyanxuanSpecialIds) + ")"
+			pars = append(pars, yanxuanSpecialIds)
+			list, e := cygx.GetYanxuanSpecialListByCondition(condition, pars, 0, lenyanxuanSpecialIds)
+			if e != nil && e.Error() != utils.ErrNoRow() {
+				err = e
+				return
+			}
+			if len(list) > 0 {
+				for _, v := range list {
+					mapYanxuanSpecial[v.Id] = v
+				}
+			}
+		}
+
+		for _, v := range items {
+			item := new(cygx.UserInteraction)
+			if v.Source == utils.CYGX_OBJ_ARTICLE {
+				item.IndustryName = strings.Join(mapIndustrialLabel[v.SourceId], ",")
+				item.SubjectNameStr = strings.Join(mapSubjectLabel[v.SourceId], ",")
+				if v.SourceId >= utils.SummaryArticleId {
+					item.ArticleType = 1
+				} else {
+					item.ArticleType = 2
+				}
+				//如果对应的map不为空,就赋值
+				if mapArticle[v.SourceId] != nil {
+					item.Title = mapArticle[v.SourceId].Title
+					item.PublishDate = mapArticle[v.SourceId].PublishDate
+					item.PermissionName = mapArticle[v.SourceId].PermissionName
+					item.ArticleIdMd5 = mapArticle[v.SourceId].ArticleIdMd5
+				}
+			}
+			if v.Source == utils.CYGX_OBJ_YANXUANSPECIAL {
+				item.PermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
+				//如果对应的map不为空,就赋值
+				if mapYanxuanSpecial[v.SourceId] != nil {
+					item.Title = mapYanxuanSpecial[v.SourceId].Title
+					item.PublishDate = mapYanxuanSpecial[v.SourceId].PublishTime
+					item.SpecialType = mapYanxuanSpecial[v.SourceId].Type
+				}
+			}
+			item.ArticleId = v.SourceId
+			item.CreateTime = v.CreateTime
+			item.UserId = v.UserId
+			item.RealName = v.RealName
+			item.Mobile = v.Mobile
+			item.CompanyId = v.CompanyId
+			item.CompanyName = v.CompanyName
+			item.SellerName = sellNameMap[v.CompanyId]
+			item.RegisterPlatform = v.RegisterPlatform
+			item.StopTime = strconv.Itoa(v.StopTime)
+			itemsResp = append(itemsResp, item)
+		}
+
 	}
 	return
 }

+ 184 - 2
services/cygx/contract_allocation.go

@@ -185,6 +185,50 @@ func GetCompanyContractPermissionNameMapById(companyContractIds []int) (mapContr
 	return
 }
 
+// GetCompanyPermissionNameStatusMapByCompanyId 通过公司ID,获取公司当下所有权限的状态信息
+func GetCompanyPermissionNameStatusMapByCompanyId(companyIds []int) (mapResp map[string]string, err error) {
+	//return
+	lenArr := len(companyIds)
+	if lenArr == 0 {
+		return
+	}
+	var condition string
+	var pars []interface{}
+
+	condition += " AND  company_id IN (" + utils.GetOrmInReplace(lenArr) + ") AND product_id = 2 "
+	pars = append(pars, companyIds)
+
+	//获取所有开通买方研选正式试用的客户列表
+	listCompanyPermission, e := company.GetCompanyReportPermissionList(condition, pars, 0, 0)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetCompanyReportPermissionList, Err: " + e.Error())
+		return
+	}
+
+	//获取行业权限ID与名称的映射关系
+	permissionList, e := models.GetChartPermissionList()
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetChartPermissionList, Err: " + e.Error())
+		return
+	}
+
+	mapResp = make(map[string]string, 0)
+	mapChartPermission := make(map[int]string)
+	for _, v := range permissionList {
+		mapChartPermission[v.ChartPermissionId] = v.PermissionName
+	}
+
+	for _, v := range listCompanyPermission {
+		if mapChartPermission[v.ChartPermissionId] == "" {
+			continue
+		}
+		//公司ID与权限名称组成映射关系
+		mapResp[fmt.Sprint(v.CompanyId, mapChartPermission[v.ChartPermissionId])] = v.Status
+	}
+
+	return
+}
+
 // 判断合同审核通过时间是否超过九十天
 func GetMapIsGrayByCompanyContractIds(companyContractIds []int) (mapResp map[int]bool, err error) {
 	lenArr := len(companyContractIds)
@@ -335,7 +379,7 @@ func HandleCompanyContractPackageDifference(companyContractId int) (err error) {
 	defer func() {
 		if err != nil {
 			fmt.Println(err)
-			go alarm_msg.SendAlarmMsg(fmt.Sprint("如果合同只有研选的时候,自动处理派点失败,Err:", err.Error(), "companyContractId", companyContractId), 2)
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("更新与上一份合同的金额的对比 '增加套餐','减少套餐','维持套餐'失败,Err:", err.Error(), "companyContractId", companyContractId), 2)
 		}
 	}()
 	var condition string
@@ -373,7 +417,6 @@ func HandleCompanyContractPackageDifference(companyContractId int) (err error) {
 	}
 
 	e = company.UpdateCompanyContractPackageDifference(packageDifference, companyContractId)
-	fmt.Println(packageDifference)
 	if e != nil {
 		err = errors.New("UpdateCompanyContractPackageDifference, Err: " + e.Error())
 		return
@@ -381,3 +424,142 @@ func HandleCompanyContractPackageDifference(companyContractId int) (err error) {
 	return
 
 }
+
+// HandleCompanyContractPermissionContractType 更新合同权限表中的权限名称,以及对应的行业权限类型(行业新签、行业续约)
+func HandleCompanyContractPermissionContractType(companyContractId int) (err error) {
+	defer func() {
+		if err != nil {
+			fmt.Println(err)
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("更新合同权限表中的权限名称,以及对应的行业权限类型(行业新签、行业续约)失败,HandleCompanyContractPermissionContractType Err:", err.Error(), "companyContractId", companyContractId), 2)
+		}
+	}()
+	var condition string
+	var pars []interface{}
+
+	condition = " AND company_contract_id = ?  "
+	pars = append(pars, companyContractId)
+	detail, e := company.GetCompanyContracDetail(condition, pars)
+	if e != nil {
+		err = errors.New("GetCompanyContracDetail,detail Err: " + e.Error())
+		return
+	}
+
+	//获取权限ID与名称的map映射
+	permissionList, e := models.GetChartPermissionList()
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetChartPermissionList Err: " + e.Error())
+		return
+	}
+
+	mapChartPermission := make(map[int]string)
+	for _, v := range permissionList {
+		mapChartPermission[v.ChartPermissionId] = v.PermissionName
+	}
+
+	companyId := detail.CompanyId
+	//如果不是续约合同就不做对比处理
+	pars = make([]interface{}, 0)
+	condition = " AND  company_contract_id  != ?   AND  company_id = ? "
+	pars = append(pars, companyContractId, companyId)
+
+	//获取历史签约信息
+	companyContractPermissionListHistory, e := company.GetCompanyContractPermissionList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("companyContractPermissionListHistory Err: " + e.Error())
+		return
+	}
+
+	var mapHistoryPerssionName []string
+	for _, v := range companyContractPermissionListHistory {
+		mapHistoryPerssionName = append(mapHistoryPerssionName, mapChartPermission[v.ChartPermissionId])
+	}
+
+	pars = make([]interface{}, 0)
+	condition = " AND  company_contract_id  = ?   "
+	pars = append(pars, companyContractId)
+	//获取当前签约的合同信息
+	companyContractPermissionLisThis, e := company.GetCompanyContractPermissionList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("companyContractPermissionLisThis Err: " + e.Error())
+		return
+	}
+
+	var items []*company.CompanyContractPermission
+	for _, v := range companyContractPermissionLisThis {
+		v.PermissionName = mapChartPermission[v.ChartPermissionId]
+		if v.PermissionName == "" {
+			continue
+		}
+		//已经存在的属于行业续约、不存在的属于行业新签
+		if utils.InArrayByStr(mapHistoryPerssionName, v.PermissionName) {
+			v.ContractType = "行业续约"
+		} else {
+			v.ContractType = "行业新签"
+		}
+		items = append(items, v)
+	}
+	//批量更新合同权限表的权限行业名称,以及签约合同时,当前行业类型(行业续约、行业新签)
+	e = company.UpdateCompanyContractPermissionMulti(items)
+	if e != nil {
+		err = errors.New("UpdateCompanyContractPermissionMulti Err: " + e.Error())
+		return
+	}
+	return
+}
+
+func initCRM14_4() {
+	//func init() {
+	permissionList, e := models.GetChartPermissionList()
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		fmt.Println(permissionList)
+		return
+	}
+
+	mapChartPermission := make(map[int]string)
+	for _, v := range permissionList {
+		mapChartPermission[v.ChartPermissionId] = v.PermissionName
+	}
+
+	var condition string
+	var pars []interface{}
+	condition = " AND status = 1    AND  product_id = 2  "
+	companyContractList, e := company.GetCompanyContractList(condition, pars)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		fmt.Println(e)
+		return
+	}
+	fmt.Println(len(companyContractList))
+	for k, v := range companyContractList {
+		fmt.Println(k)
+		HandleCompanyContractPermissionContractType(v.CompanyContractId)
+	}
+
+	//var companyContractIds []int
+	//for _, v := range companyContractList {
+	//	companyContractIds = append(companyContractIds, v.CompanyContractId)
+	//}
+	//condition = " AND  company_contract_id IN (" + utils.GetOrmInReplace(len(companyContractIds)) + ")  "
+	//pars = append(pars, companyContractIds)
+	//
+	//companyContractPermissionList, e := company.GetCompanyContractPermissionList(condition, pars)
+	//if e != nil && e.Error() != utils.ErrNoRow() {
+	//	fmt.Println(e)
+	//	return
+	//}
+	//
+	//var items []*company.CompanyContractPermission
+	//
+	//for _, v := range companyContractPermissionList {
+	//	v.PermissionName = mapChartPermission[v.ChartPermissionId]
+	//
+	//	items = append(items, v)
+	//}
+	//fmt.Println(len(items))
+	////return
+	//e = company.UpdateCompanyContractPermissionMulti(items)
+	//if e != nil && e.Error() != utils.ErrNoRow() {
+	//	fmt.Println(e)
+	//	return
+	//}
+
+}

+ 86 - 0
services/cygx/cygx_yanxuan_special.go

@@ -249,12 +249,21 @@ func UpdateYanxuanSpecialResourceData(sourceId int) {
 			err = errors.New("GetCygxReportSelectionBySourceAndId, Err: " + e.Error())
 			return
 		}
+		detail, e := cygx.GetYanxuanSpecialItemById(sourceId)
+		if e != nil {
+			err = errors.New("GetYanxuanSpecialFollowUserById, Err: " + e.Error())
+			return
+		}
+
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
 		item.SourceId = sourceId
 		item.Source = source
 		item.PublishDate = publishDate
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.Title
+		item.SearchContent = ""
+		item.SearchOrderTime = publishDate
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -271,3 +280,80 @@ func UpdateYanxuanSpecialResourceData(sourceId int) {
 	}
 	return
 }
+
+// 研选专栏审批记录
+func AddAddCygxYanxuanSpecialApprovalLog(user *models.WxUserItem, specialId, status int, reason string) {
+	var err error
+	defer func() {
+		if err != nil {
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("获取研选专栏用户信息失败,GetYanxuanSpecialAuthorInfo Err ", err, "userId", user.UserId), 2)
+		}
+	}()
+	detail, e := cygx.GetYanxuanSpecialBySpecialId(specialId)
+	if e != nil {
+		err = errors.New("GetYanxuanSpecialBySpecialId, Err: " + e.Error())
+		return
+	}
+
+	specialAuthor, e := cygx.GetCygxYanxuanSpecialAuthorByUserId(detail.UserId)
+	if e != nil {
+		err = errors.New("GetCygxYanxuanSpecialAuthorByUserId, Err: " + e.Error())
+		return
+	}
+
+	item := new(cygx.CygxYanxuanSpecialApprovalLog)
+	item.UserId = detail.UserId
+	item.Content = detail.Content
+	item.Tags = detail.Tags
+	item.ApprovalStatus = status
+	item.ImgUrl = detail.ImgUrl
+	item.DocUrl = detail.DocUrl
+	item.Reason = reason
+	item.Title = detail.Title
+	item.Type = detail.Type
+	item.CompanyTags = detail.CompanyTags
+	item.IndustryTags = detail.IndustryTags
+	item.YanxuanSpecialId = specialId
+	item.AdminName = user.RealName
+	item.AdminUserId = user.UserId
+	item.SpecialName = specialAuthor.SpecialName
+	item.NickName = specialAuthor.NickName
+	item.CreateTime = time.Now()
+	item.ModifyTime = time.Now()
+
+	e = cygx.AddCygxYanxuanSpecialApprovalLog(item)
+	if e != nil {
+		err = errors.New("AddCygxYanxuanSpecialApprovalLog, Err: " + e.Error())
+		return
+	}
+	return
+}
+
+// 获取专栏用户最新的一篇文章信息
+func GetBestNewYanxuanSpecialByUserId(userIds []int) (mapResp map[int]string) {
+	lenArr := len(userIds)
+	if lenArr == 0 {
+		return
+	}
+	var err error
+	defer func() {
+		if err != nil {
+			fmt.Println(err)
+			go alarm_msg.SendAlarmMsg(fmt.Sprint("获取研选专栏用户信息失败,GetBestNewYanxuanSpecialByUserId Err ", err, "userIds", userIds), 2)
+		}
+	}()
+	var condition string
+	var pars []interface{}
+	condition += `  AND  a.publish_time = ( SELECT max( b.publish_time ) FROM cygx_yanxuan_special b WHERE a.user_id = b.user_id  AND b.STATUS = 3 )  AND user_id  IN (` + utils.GetOrmInReplace(lenArr) + `) AND a.status = 3  GROUP BY user_id ORDER BY publish_time DESC`
+	pars = append(pars, userIds)
+	list, e := cygx.GetYanxuanSpecialListBycondition(condition, pars, 0, lenArr)
+	if e != nil && e.Error() != utils.ErrNoRow() {
+		err = errors.New("GetYanxuanSpecialListBycondition, Err: " + e.Error())
+		return
+	}
+	mapResp = make(map[int]string, 0)
+	for _, v := range list {
+		mapResp[v.UserId] = v.PublishTime.Format(utils.FormatDateTime)
+	}
+	return
+}

+ 302 - 61
services/cygx/resource_data.go

@@ -26,7 +26,7 @@ import (
 //roadshow
 
 //func init() {
-//	UpdateActivityResourceData(2703)
+//	UpdateMicroRoadshowResourceData(7)
 //}
 
 // 更新活动
@@ -75,14 +75,43 @@ func UpdateActivityResourceData(sourceId int) {
 			return
 		}
 		var resourceDataId int
-		publishDate := time.Now().Format(utils.FormatDateTime)
+		publishDate := detail.CreateTime // 活动创建时间作为排序时间
+
 		item := new(cygx.CygxResourceData)
+
+		var industrialName string
+		var subjectName string
+		//建立首页资源表,与产业的关系
+		industrialList, e := cygx.GetIndustrialActivityGroupManagementList(sourceId, 1)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range industrialList {
+			industrialName += v.IndustryName
+		}
+
+		//建立首页资源表,与标的 的关系
+		subjectList, e := cygx.GetSubjectActivityGroupManagementList(sourceId, 1)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range subjectList {
+			subjectName += v.SubjectName
+		}
+
 		item.SourceId = sourceId
 		item.Source = source
 		//分析师电话会(C类)
 		item.SearchTag = detail.ActivityTypeName
 		item.ChartPermissionId = detail.ChartPermissionId
 		item.PublishDate = publishDate
+		item.SearchTitle = detail.ActivityName
+		item.SearchContent = detail.Label + industrialName + subjectName
+		item.SearchOrderTime = detail.ActivityTime
 		item.CreateTime = time.Now()
 		if totalData == 0 {
 			newId, e := cygx.AddCygxResourceData(item)
@@ -105,12 +134,6 @@ func UpdateActivityResourceData(sourceId int) {
 			resourceDataId = sourceDetail.Id
 		}
 
-		//建立首页资源表,与产业的关系
-		industrialList, e := cygx.GetIndustrialActivityGroupManagementList(sourceId, 1)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(sourceId))
-			return
-		}
 		var industrialItems []*cygx.CygxResourceDataIndustrialGroupManagement
 		for _, v := range industrialList {
 			var industrialItem = new(cygx.CygxResourceDataIndustrialGroupManagement)
@@ -123,11 +146,6 @@ func UpdateActivityResourceData(sourceId int) {
 		}
 
 		//建立首页资源表,与标的 的关系
-		subjectList, e := cygx.GetSubjectActivityGroupManagementList(sourceId, 1)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(sourceId))
-			return
-		}
 		var subjectItems []*cygx.CygxResourceDataIndustrialGroupSubject
 		for _, v := range subjectList {
 			var subjectItem = new(cygx.CygxResourceDataIndustrialGroupSubject)
@@ -194,7 +212,7 @@ func UpdateActivitySpecialResourceData(sourceId int) {
 			return
 		}
 		var resourceDataId int
-		publishDate := time.Now().Format(utils.FormatDateTime)
+		publishDate := activityInfo.PublishDate
 		item := new(cygx.CygxResourceData)
 		item.SourceId = sourceId
 		item.Source = source
@@ -203,6 +221,15 @@ func UpdateActivitySpecialResourceData(sourceId int) {
 		item.PublishDate = publishDate
 		item.ChartPermissionId = activityInfo.ChartPermissionId
 		item.CreateTime = time.Now()
+		item.SearchTitle = activityInfo.ResearchTheme
+		item.SearchContent = activityInfo.Label + activityInfo.IndustrialName + activityInfo.IndustrialSubjectName
+
+		if activityInfo.Days > 0 {
+			item.SearchOrderTime = activityInfo.ActivityTime
+		} else {
+			item.SearchOrderTime = activityInfo.PublishDate
+		}
+
 		if totalData == 0 {
 			newId, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -313,6 +340,7 @@ func UpdateArticleResourceData(sourceId int) {
 		}
 
 		var resourceDataId int
+		//publishDate := detail.CreateDate
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
 		if detail.ArticleTypeId > 0 {
@@ -327,10 +355,47 @@ func UpdateArticleResourceData(sourceId int) {
 			}
 		}
 
+		var industrialName string
+		var subjectName string
+		//建立首页资源表,与产业的关系
+		industrialList, e := cygx.GetIndustrialArticleGroupManagementList(sourceId)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range industrialList {
+			industrialName += v.IndustryName
+		}
+
+		//建立首页资源表,与标的 的关系
+		subjectList, e := cygx.GetSubjectArticleGroupManagementList(sourceId)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetSubjectArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range subjectList {
+			subjectName += v.SubjectName
+		}
+
 		item.SourceId = sourceId
 		item.Source = source
 		item.PublishDate = publishDate
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.Title
+		annotation, e := utils.GetHtmlContentText(detail.Annotation)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetHtmlContentText, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+		abstract, e := utils.GetHtmlContentText(detail.Abstract)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetHtmlContentText, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+		item.SearchContent = annotation + abstract + detail.FieldName + detail.Stock + industrialName + subjectName
+		item.SearchOrderTime = detail.PublishDate
 		if totalData == 0 {
 			newId, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -341,23 +406,17 @@ func UpdateArticleResourceData(sourceId int) {
 		} else {
 			e = cygx.UpdateResourceDataByItem(item)
 			if e != nil {
-				err = errors.New("UpdateResourceData, Err: " + e.Error())
+				err = errors.New("UpdateResourceDataByItem, Err: " + e.Error())
 				return
 			}
 			sourceDetail, e := cygx.GetCygxResourceDataByIdAndSource(sourceId, source)
 			if e != nil {
-				err = errors.New("UpdateResourceData, Err: " + e.Error())
+				err = errors.New("GetCygxResourceDataByIdAndSource, Err: " + e.Error())
 				return
 			}
 			resourceDataId = sourceDetail.Id
 		}
 
-		//建立首页资源表,与产业的关系
-		industrialList, e := cygx.GetIndustrialArticleGroupManagementList(sourceId)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetIndustrialArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
-			return
-		}
 		var industrialItems []*cygx.CygxResourceDataIndustrialGroupManagement
 		for _, v := range industrialList {
 			var industrialItem = new(cygx.CygxResourceDataIndustrialGroupManagement)
@@ -367,14 +426,9 @@ func UpdateArticleResourceData(sourceId int) {
 			industrialItem.ResourceDataId = resourceDataId
 			industrialItem.CreateTime = time.Now()
 			industrialItems = append(industrialItems, industrialItem)
+			industrialName += v.IndustryName
 		}
 
-		//建立首页资源表,与标的 的关系
-		subjectList, e := cygx.GetSubjectArticleGroupManagementList(sourceId)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetSubjectArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
-			return
-		}
 		var subjectItems []*cygx.CygxResourceDataIndustrialGroupSubject
 		for _, v := range subjectList {
 			var subjectItem = new(cygx.CygxResourceDataIndustrialGroupSubject)
@@ -384,6 +438,7 @@ func UpdateArticleResourceData(sourceId int) {
 			subjectItem.ResourceDataId = resourceDataId
 			subjectItem.CreateTime = time.Now()
 			subjectItems = append(subjectItems, subjectItem)
+			subjectName += v.SubjectName
 		}
 
 		//插入关联信息
@@ -443,14 +498,42 @@ func UpdateProductInteriorResourceData(sourceId int) {
 		}
 		mapMatchTypeName := GetCygxReportMappingCygxListMap() //报告匹配类型
 		var resourceDataId int
-		publishDate := time.Now().Format(utils.FormatDateTime)
+		publishDate := detail.CreateTime
 		item := new(cygx.CygxResourceData)
+
+		var industrialName string
+		var subjectName string
+		//建立首页资源表,与产业的关系
+		industrialList, e := cygx.GetProductInteriorIndustrialGroupManagementList(sourceId)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range industrialList {
+			industrialName += v.IndustryName
+		}
+
+		//建立首页资源表,与标的 的关系
+		subjectList, e := cygx.GetProductInteriorIndustrialGroupSubjecttList(sourceId)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetSubjectArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range subjectList {
+			subjectName += v.SubjectName
+		}
+
 		item.SourceId = sourceId
 		item.Source = source
 		item.SearchTag = mapMatchTypeName[detail.MatchTypeId]
 		item.PublishDate = publishDate
 		item.ChartPermissionId = detail.ChartPermissionId
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.Title
+		item.SearchContent = detail.Abstract + industrialName + subjectName
+		item.SearchOrderTime = detail.PublishTime
 		if totalData == 0 {
 			newId, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -472,12 +555,6 @@ func UpdateProductInteriorResourceData(sourceId int) {
 			resourceDataId = sourceDetail.Id
 		}
 
-		//建立首页资源表,与产业的关系
-		industrialList, e := cygx.GetProductInteriorIndustrialGroupManagementList(sourceId)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetIndustrialArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
-			return
-		}
 		var industrialItems []*cygx.CygxResourceDataIndustrialGroupManagement
 		for _, v := range industrialList {
 			var industrialItem = new(cygx.CygxResourceDataIndustrialGroupManagement)
@@ -489,12 +566,6 @@ func UpdateProductInteriorResourceData(sourceId int) {
 			industrialItems = append(industrialItems, industrialItem)
 		}
 
-		//建立首页资源表,与标的 的关系
-		subjectList, e := cygx.GetProductInteriorIndustrialGroupSubjecttList(sourceId)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetSubjectArticleGroupManagementList, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
-			return
-		}
 		var subjectItems []*cygx.CygxResourceDataIndustrialGroupSubject
 		for _, v := range subjectList {
 			var subjectItem = new(cygx.CygxResourceDataIndustrialGroupSubject)
@@ -516,7 +587,7 @@ func UpdateProductInteriorResourceData(sourceId int) {
 	return
 }
 
-// 更新晨会精华
+// 更新晨会精华 (跟踪点评)
 func UpdateMeetingreviewchaptResourceData(sourceId int) {
 	var err error
 	defer func() {
@@ -560,12 +631,54 @@ func UpdateMeetingreviewchaptResourceData(sourceId int) {
 		var resourceDataId int
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
+
+		var industrialName string
+		var subjectName string
+		//建立首页资源表,与产业的关系
+		var condition string
+		var pars []interface{}
+		condition = " AND industrial_management_id = ? "
+		pars = append(pars, detail.IndustryId)
+		//建立首页资源表,与产业的关系
+		industrialList, e := cygx.GetTopOneMonthArtReadNumIndustryAll(condition, pars)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetTopOneMonthArtReadNumIndustryAll, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+
+		for _, v := range industrialList {
+			industrialName += v.IndustryName
+		}
+
+		if detail.IndustrialSubjectIds != "" {
+			condition = ""
+			pars = make([]interface{}, 0)
+			condition = " AND industrial_subject_id  IN (" + detail.IndustrialSubjectIds + ") "
+			//建立首页资源表,与标的 的关系
+			subjectList, e := cygx.GetCygxIndustrialSubjectListCondition(condition, pars)
+			if e != nil && e.Error() != utils.ErrNoRow() {
+				err = errors.New("GetCygxIndustrialSubjectListCondition, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+				return
+			}
+			for _, v := range subjectList {
+				subjectName += v.SubjectName
+			}
+		}
+
 		item.SourceId = sourceId
 		item.Source = source
 		item.SearchTag = "晨会精华"
 		item.PublishDate = publishDate
 		item.ChartPermissionId = detail.ChartPermissionId
 		item.CreateTime = time.Now()
+		item.SearchTitle = industrialName + subjectName
+		content, e := utils.GetHtmlContentText(detail.Content)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetHtmlContentText, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
+			return
+		}
+		item.SearchContent = content
+		item.SearchOrderTime = detail.MeetingTime.Format(utils.FormatDateTime)
 		if totalData == 0 {
 			newId, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -586,16 +699,7 @@ func UpdateMeetingreviewchaptResourceData(sourceId int) {
 			}
 			resourceDataId = sourceDetail.Id
 		}
-		var condition string
-		var pars []interface{}
-		condition = " AND industrial_management_id = ? "
-		pars = append(pars, detail.IndustryId)
-		//建立首页资源表,与产业的关系
-		industrialList, e := cygx.GetTopOneMonthArtReadNumIndustryAll(condition, pars)
-		if e != nil && e.Error() != utils.ErrNoRow() {
-			err = errors.New("GetTopOneMonthArtReadNumIndustryAll, Err: " + e.Error() + "sourceId:" + strconv.Itoa(sourceId))
-			return
-		}
+
 		var industrialItems []*cygx.CygxResourceDataIndustrialGroupManagement
 		for _, v := range industrialList {
 			var industrialItem = new(cygx.CygxResourceDataIndustrialGroupManagement)
@@ -686,6 +790,9 @@ func UpdateReportSelectionResourceData(sourceId int) {
 		item.SearchTag = "重点公司"
 		item.PublishDate = publishDate
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.Title
+		item.SearchContent = ""
+		item.SearchOrderTime = detail.PublishDate
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -736,6 +843,11 @@ func UpdateResearchSummaryResourceData(sourceId int) {
 			err = errors.New("GetCygxReportSelectionBySourceAndId, Err: " + e.Error())
 			return
 		}
+		detail, e := cygx.GetCygxResearchSummaryInfoById(sourceId)
+		if e != nil {
+			err = errors.New("GetCygxResearchSummaryInfoById, Err: " + e.Error())
+			return
+		}
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
 		item.SourceId = sourceId
@@ -743,6 +855,9 @@ func UpdateResearchSummaryResourceData(sourceId int) {
 		item.SearchTag = "本周研究汇总"
 		item.PublishDate = publishDate
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.Title
+		item.SearchContent = ""
+		item.SearchOrderTime = detail.PublishDate
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -793,6 +908,12 @@ func UpdateMinutesSummaryResourceData(sourceId int) {
 			err = errors.New("GetCygxReportSelectionBySourceAndId, Err: " + e.Error())
 			return
 		}
+		detail, e := cygx.GetCygxMinutesSummaryInfoById(sourceId)
+
+		if e != nil {
+			err = errors.New("GetCygxMinutesSummaryInfoById, Err: " + e.Error())
+			return
+		}
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
 		item.SourceId = sourceId
@@ -800,6 +921,9 @@ func UpdateMinutesSummaryResourceData(sourceId int) {
 		item.SearchTag = "上周纪要汇总"
 		item.PublishDate = publishDate
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.Title
+		item.SearchContent = ""
+		item.SearchOrderTime = detail.PublishDate
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -867,6 +991,31 @@ func UpdateActivityVoiceResourceData(sourceId int) {
 		}
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
+
+		var industrialName string
+		var subjectName string
+		//建立首页资源表,与产业的关系
+		industrialList, e := cygx.GetIndustrialActivityGroupManagementList(activityId, 1)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(activityId))
+			return
+		}
+
+		for _, v := range industrialList {
+			industrialName += v.IndustryName
+		}
+
+		//建立首页资源表,与标的 的关系
+		subjectList, e := cygx.GetSubjectActivityGroupManagementList(activityId, 1)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(activityId))
+			return
+		}
+
+		for _, v := range subjectList {
+			subjectName += v.SubjectName
+		}
+
 		item.SourceId = sourceId
 		item.Source = source
 		//易董办会的分析师电话会,为路演回放
@@ -878,6 +1027,9 @@ func UpdateActivityVoiceResourceData(sourceId int) {
 		item.PublishDate = publishDate
 		item.ChartPermissionId = activityInfo.ChartPermissionId
 		item.CreateTime = utils.StrDateToDate(activityInfo.ActivityTime)
+		item.SearchTitle = voiceDetail.VoiceName
+		item.SearchContent = activityInfo.Label + industrialName + subjectName
+		item.SearchOrderTime = activityInfo.ActivityTime
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -943,6 +1095,29 @@ func UpdateActivityVideoResourceData(sourceId int) {
 		}
 		publishDate := time.Now().Format(utils.FormatDateTime)
 		item := new(cygx.CygxResourceData)
+		var industrialName string
+		var subjectName string
+		//建立首页资源表,与产业的关系
+		industrialList, e := cygx.GetIndustrialActivityGroupManagementList(activityId, 1)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(activityId))
+			return
+		}
+
+		for _, v := range industrialList {
+			industrialName += v.IndustryName
+		}
+
+		//建立首页资源表,与标的 的关系
+		subjectList, e := cygx.GetSubjectActivityGroupManagementList(activityId, 1)
+		if e != nil && e.Error() != utils.ErrNoRow() {
+			err = errors.New("GetIndustrialActivityGroupManagementList, Err: " + e.Error() + "activityId:" + strconv.Itoa(activityId))
+			return
+		}
+
+		for _, v := range subjectList {
+			subjectName += v.SubjectName
+		}
 		item.SourceId = sourceId
 		item.Source = source
 		//易董办会的分析师电话会,为路演回放
@@ -955,6 +1130,9 @@ func UpdateActivityVideoResourceData(sourceId int) {
 		item.PublishDate = publishDate
 		item.ChartPermissionId = activityInfo.ChartPermissionId
 		item.CreateTime = utils.StrDateToDate(activityInfo.ActivityTime)
+		item.SearchTitle = videoDetail.VideoName
+		item.SearchContent = activityInfo.Label + industrialName + subjectName
+		item.SearchOrderTime = activityInfo.ActivityTime
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -1018,6 +1196,9 @@ func UpdateMicroRoadshowResourceData(sourceId int) {
 		item.PublishDate = publishDate
 		item.ChartPermissionId = detail.ChartPermissionId
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.VideoName
+		item.SearchContent = detail.IndustryName
+		item.SearchOrderTime = detail.PublishDate.Format(utils.FormatDateTime)
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -1086,6 +1267,9 @@ func UpdateAskserieVideoResourceData(sourceId int) {
 		item.PublishDate = publishDate
 		item.ChartPermissionId = detail.ChartPermissionId
 		item.CreateTime = time.Now()
+		item.SearchTitle = detail.VideoName
+		item.SearchContent = detail.IndustryName
+		item.SearchOrderTime = detail.PublishDate
 		if totalData == 0 {
 			_, e := cygx.AddCygxResourceData(item)
 			if e != nil {
@@ -1103,19 +1287,29 @@ func UpdateAskserieVideoResourceData(sourceId int) {
 	return
 }
 
-func init23() {
+func init300() {
 	//var condition string
 	//var pars []interface{}
 	//
+
 	//{
 	//	//活动
-	//	list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_ACTIVITY)
+	//	var condition string
+	//	var pars []interface{}
+	//	condition = " AND publish_status = 1  AND activity_id NOT IN  (SELECT  source_id FROM cygx_resource_data WHERE source  = 'activity') "
+	//	list, err := cygx.GetActivityListAll(condition, pars, 0, 9999)
 	//	if err != nil {
 	//		fmt.Println(err)
 	//	}
+	//
+	//	//list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_ACTIVITY)
+	//	//if err != nil {
+	//	//	fmt.Println(err)
+	//	//}
+	//	fmt.Println(len(list))
 	//	for _, v := range list {
-	//		fmt.Println(v.Source)
-	//		UpdateActivityResourceData(v.SourceId)
+	//		fmt.Println(v.ActivityId)
+	//		UpdateActivityResourceData(v.ActivityId)
 	//	}
 	//}
 
@@ -1161,14 +1355,25 @@ func init23() {
 	//}
 
 	//{
-	//	//文章
-	//	list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_ARTICLE)
+	//	var condition string
+	//	var pars []interface{}
+	//	condition = " AND publish_status = 1  AND article_id NOT IN  (SELECT  source_id FROM cygx_resource_data WHERE source  = 'article') "
+	//
+	//	list, err := cygx.GetArticleRoadshowEssenceList(condition, pars, 0, 9999)
 	//	if err != nil {
 	//		fmt.Println(err)
+	//		return
 	//	}
+	//	fmt.Println(len(list))
+	//	//return
+	//	//文章
+	//	//list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_ARTICLE)
+	//	//if err != nil {
+	//	//	fmt.Println(err)
+	//	//}
 	//	for _, v := range list {
-	//		fmt.Println(v.Source)
-	//		UpdateArticleResourceData(v.SourceId)
+	//		fmt.Println(v.ArticleId)
+	//		UpdateArticleResourceData(v.ArticleId)
 	//	}
 	//}
 
@@ -1296,7 +1501,7 @@ func init23() {
 	//		fmt.Println(err)
 	//	}
 	//	for _, v := range list {
-	//		fmt.Println(v.Source)
+	//		fmt.Println(v.SourceId)
 	//		UpdateActivityVideoResourceData(v.SourceId)
 	//	}
 	//}
@@ -1313,4 +1518,40 @@ func init23() {
 	//	}
 	//}
 
+	//{
+	//	//问答系列视频
+	//	list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_ASKSERIEVIDEO)
+	//	if err != nil {
+	//		fmt.Println(err)
+	//	}
+	//	for _, v := range list {
+	//		fmt.Println(v.SourceId)
+	//		UpdateAskserieVideoResourceData(v.SourceId)
+	//	}
+	//}
+
+	//{
+	//	//晨会精华
+	//	list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_MEETINGREVIEWCHAPT)
+	//	if err != nil {
+	//		fmt.Println(err)
+	//	}
+	//	for _, v := range list {
+	//		fmt.Println(v.SourceId)
+	//		UpdateMeetingreviewchaptResourceData(v.SourceId)
+	//	}
+	//}
+
+	//{
+	//	//研选专栏
+	//	list, err := cygx.GetCygxResourceDataListBysource(utils.CYGX_OBJ_YANXUANSPECIAL)
+	//	if err != nil {
+	//		fmt.Println(err)
+	//	}
+	//	for _, v := range list {
+	//		fmt.Println(v.SourceId)
+	//		UpdateYanxuanSpecialResourceData(v.SourceId)
+	//	}
+	//}
+
 }

+ 45 - 1
services/elastic/es_comprehensive.go

@@ -113,6 +113,49 @@ func EsAddOrEditComprehensiveData(item *ElasticComprehensiveDetail) (err error)
 	return
 }
 
+// 更新产业资源包
+func UpdateComprehensiveIndustrialResourceData(itemSource *ElasticComprehensiveDetail) {
+	var err error
+	defer func() {
+		if err != nil {
+			go alarm_msg.SendAlarmMsg("更新产业资源包到最新数据表失败,Err:"+err.Error()+"资源ID"+strconv.Itoa(itemSource.SourceId), 3)
+		}
+	}()
+	sourceId := itemSource.SourceId
+	var source = itemSource.Source
+
+	//判断是否存在,如果不存在就新增,存在就更新
+	totalData, e := cygx.GetCygxResourceDataBySourceAndIdCount(sourceId, source)
+	if e != nil {
+		err = errors.New("GetCygxResourceDataBySourceAndIdCount, Err: " + e.Error())
+		return
+	}
+
+	item := new(cygx.CygxResourceData)
+	item.SourceId = sourceId
+	item.Source = source
+	item.PublishDate = itemSource.PublishDate
+	item.CreateTime = time.Now()
+	item.SearchTitle = itemSource.IndustryName + itemSource.SubjectNames
+	item.SearchContent = ""
+	item.SearchOrderTime = itemSource.PublishDate
+
+	if totalData == 0 {
+		_, e = cygx.AddCygxResourceData(item)
+		if e != nil {
+			err = errors.New("AddCygxResourceData, Err: " + e.Error())
+			return
+		}
+	} else {
+		e = cygx.UpdateResourceDataByItem(item)
+		if e != nil {
+			err = errors.New("UpdateResourceData, Err: " + e.Error())
+			return
+		}
+	}
+	return
+}
+
 // 删除数据
 func EsDeleteComprehensiveData(item *ElasticComprehensiveDetail) (err error) {
 	indexName := utils.IndexNameComprehensive // 避免调用错别的项目的索引 ,这里写死
@@ -502,7 +545,7 @@ func AddComprehensiveIndustrialSource(sourceType string, articleId int) {
 	mapActivitySubject := make(map[int][]string, 0)
 	listsubject, e := cygx.GetCygxIndustrialSubjectListCondition(condition, pars)
 	if e != nil {
-		err = errors.New("GetIndustrialManagementRepList, Err: " + e.Error())
+		err = errors.New("GetCygxIndustrialSubjectListCondition, Err: " + e.Error())
 		return
 	}
 	for _, v := range listsubject {
@@ -535,6 +578,7 @@ func AddComprehensiveIndustrialSource(sourceType string, articleId int) {
 		item.SubjectNames = strings.Join(mapActivitySubject[v.IndustrialManagementId], ",")
 		item.PublishDate = v.PublishDate + " 00:00:00"
 		EsAddOrEditComprehensiveData(item)
+		UpdateComprehensiveIndustrialResourceData(item)
 	}
 }
 

+ 91 - 24
services/statistic_report/renew_company.go

@@ -1,6 +1,7 @@
 package statistic_report
 
 import (
+	"fmt"
 	"hongze/hz_crm_api/models/company"
 	"hongze/hz_crm_api/models/contract"
 	"hongze/hz_crm_api/utils"
@@ -9,16 +10,20 @@ import (
 )
 
 type CompanyRenewDataMap struct {
-	NotRenewMap      map[int]int    `description:"未续约客户数"`
-	NotRenewIdMap    map[int]string `description:"未续约客户ids"`
-	RenewFollowMap   map[int]int    `description:"续约跟进客户数"`
-	RenewFollowIdMap map[int]string `description:"续约跟进客户ids"`
-	ExpireMap        map[int]int    `description:"到期客户数"`
-	ExpireIdMap      map[int]string `description:"到期客户ids"`
-	RenewMap         map[int]int    `description:"续约客户数"`
-	RenewIdMap       map[int]string `description:"续约客户ids"`
-	StartDate        string         `description:"开始日期"`
-	EndDate          string         `description:"开始日期"`
+	NotRenewMap        map[int]int    `description:"未续约客户数"`
+	NotRenewIdMap      map[int]string `description:"未续约客户ids"`
+	RenewFollowMap     map[int]int    `description:"续约跟进客户数"`
+	RenewFollowIdMap   map[int]string `description:"续约跟进客户ids"`
+	ExpireMap          map[int]int    `description:"到期客户数"`
+	ExpireIdMap        map[int]string `description:"到期客户ids"`
+	RenewMap           map[int]int    `description:"续约客户数"`
+	RenewIdMap         map[int]string `description:"续约客户ids"`
+	UnusualRenewMap    map[int]int    `description:"续约异常客户数"`
+	UnusualRenewIdMap  map[int]string `description:"续约异常客户ids"`
+	UnusualRenewTotal  int            `description:"续约异常客户总数(去重)"`
+	FormalCompanyTotal int            `description:"当前正常客户总数(去重)"`
+	StartDate          string         `description:"开始日期"`
+	EndDate            string         `description:"开始日期"`
 }
 
 // GetRenewWeekDataNum 周度数据
@@ -104,12 +109,17 @@ func GetRenewTimeIntervalData(productId int, startDate, endDate string) (adminDa
 // getRenewSectionData 获取周期数据
 func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan CompanyRenewDataMap) (adminDataMap CompanyRenewDataMap, err error) {
 	defer func() {
+		if err != nil {
+			utils.FileLog.Error("getRenewSectionData,err:" + err.Error())
+			fmt.Println(err)
+		}
 		ch <- adminDataMap
 	}()
 	notRenewMap := make(map[int]int)
 	renewFollowMap := make(map[int]int)
 	expireMap := make(map[int]int)
 	renewMap := make(map[int]int)
+	unusualRenewMap := make(map[int]int) // 续约异常客户
 
 	//activeMap := make(map[int]int)              //新增的试用客户数量(活跃)
 	//allActiveMap := make(map[int]int)           //全部的试用客户数量(活跃)
@@ -119,6 +129,12 @@ func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan Co
 	renewFollowIdMap := make(map[int]string)
 	expireIdMap := make(map[int]string)
 	renewIdMap := make(map[int]string)
+	unusualRenewCompanyIdMap := make(map[int]string)     // 续约异常客户
+	var unusualRenewCompanyTotal, formalCompanyTotal int //续约异常客户总数  , 当前正式的客户数
+	formalCompanyTotal, err = contract.GetCountFormalCompany(endDate, productId)
+	if err != nil {
+		return
+	}
 
 	//activeIdMap := make(map[int]string)              //新增的试用客户id集合(活跃)
 	//allActiveIdMap := make(map[int]string)           //全部的试用客户id集合(活跃)
@@ -207,7 +223,7 @@ func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan Co
 	//到期
 	//companyIdList := make([]string, 0)
 	{
-		data, tmpErr := company.GetExpiresCompanyGroupList(startDate, endDate, productId)
+		data, tmpErr := contract.GetExpiresCompanyGroupList(startDate, endDate, productId)
 
 		if tmpErr != nil {
 			err = tmpErr
@@ -224,7 +240,7 @@ func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan Co
 		}
 	}
 
-	//续约
+	// 续约
 	//companyIdList := make([]string, 0)
 	{
 		contractIds, tmpErr := contract.GetLatestContractListByProductId(productId)
@@ -235,10 +251,8 @@ func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan Co
 		}
 		contractId := strings.Join(contractIds, ",")
 		data, tmpErr := company.GetRenewCompanyGroupList(startDate, endDate, contractId)
-
 		if tmpErr != nil {
 			err = tmpErr
-			utils.FileLog.Error(err.Error())
 			return
 		}
 		var renewIdSlice []string
@@ -251,17 +265,70 @@ func getRenewSectionData(productId int, startDate, endDate time.Time, ch chan Co
 		}
 	}
 
+	// 续约异常
+	{
+
+		data, tmpErr := company.GetUnusualRenewCompanyList(startDate, endDate, productId)
+
+		if tmpErr != nil {
+			err = tmpErr
+			utils.FileLog.Error(err.Error())
+			return
+		}
+
+		unusualRenewCompanyIdListMap := make(map[int][]string) // 续约异常客户
+		for _, v := range data {
+			tmp, ok := unusualRenewMap[v.SellerId]
+			if !ok {
+				tmp = 0
+			}
+			unusualRenewMap[v.SellerId] = tmp + 1
+
+			// 共享人id不为空,且不是所属销售
+			if v.ShareSellerId > 0 && v.ShareSellerId != v.SellerId {
+				tmp2, ok := unusualRenewMap[v.ShareSellerId]
+				if !ok {
+					tmp = 0
+				}
+				unusualRenewMap[v.ShareSellerId] = tmp2 + 1
+			}
+
+			// 客户id
+			tmpCompanyIdList, ok := unusualRenewCompanyIdListMap[v.SellerId]
+			if !ok {
+				tmpCompanyIdList = make([]string, 0)
+			}
+			unusualRenewCompanyIdListMap[v.SellerId] = append(tmpCompanyIdList, fmt.Sprint(v.CompanyIds))
+
+			tmpCompanyIdList2, ok := unusualRenewCompanyIdListMap[v.ShareSellerId]
+			if !ok {
+				tmpCompanyIdList2 = make([]string, 0)
+			}
+			unusualRenewCompanyIdListMap[v.ShareSellerId] = append(tmpCompanyIdList2, fmt.Sprint(v.CompanyIds))
+
+			unusualRenewCompanyTotal++
+		}
+
+		for sellerId, tmpCompanyIdList := range unusualRenewCompanyIdListMap {
+			unusualRenewCompanyIdMap[sellerId] = strings.Join(tmpCompanyIdList, ",")
+		}
+	}
+
 	adminDataMap = CompanyRenewDataMap{
-		NotRenewMap:      notRenewMap,
-		NotRenewIdMap:    notRenewIdMap,
-		RenewFollowMap:   renewFollowMap,
-		RenewFollowIdMap: renewFollowIdMap,
-		ExpireMap:        expireMap,
-		ExpireIdMap:      expireIdMap,
-		RenewMap:         renewMap,
-		RenewIdMap:       renewIdMap,
-		StartDate:        startDate.Format(utils.FormatDate),
-		EndDate:          endDate.Format(utils.FormatDate),
+		NotRenewMap:        notRenewMap,
+		NotRenewIdMap:      notRenewIdMap,
+		RenewFollowMap:     renewFollowMap,
+		RenewFollowIdMap:   renewFollowIdMap,
+		ExpireMap:          expireMap,
+		ExpireIdMap:        expireIdMap,
+		RenewMap:           renewMap,
+		RenewIdMap:         renewIdMap,
+		UnusualRenewMap:    unusualRenewMap,
+		UnusualRenewIdMap:  unusualRenewCompanyIdMap,
+		UnusualRenewTotal:  unusualRenewCompanyTotal,
+		FormalCompanyTotal: formalCompanyTotal,
+		StartDate:          startDate.Format(utils.FormatDate),
+		EndDate:            endDate.Format(utils.FormatDate),
 	}
 	return
 }

+ 46 - 10
services/statistic_report/reponse.go

@@ -173,16 +173,19 @@ type AdminRenewRecord struct {
 
 // CompanyRenewRecordNum 系统续约客户统计信息
 type CompanyRenewRecordNum struct {
-	NotRenewNum    int    `description:"未续约客户数"`
-	NotRenewIds    string `description:"未续约客户ids"`
-	RenewFollowNum int    `description:"续约跟进客户数"`
-	RenewFollowIds string `description:"续约跟进客户ids"`
-	ExpireNum      int    `description:"到期客户数"`
-	ExpireIds      string `description:"到期客户ids"`
-	RenewNum       int    `description:"续约客户数"`
-	RenewIds       string `description:"续约客户ids"`
-	StartDate      string `description:"开始日期"`
-	EndDate        string `description:"结束日期"`
+	NotRenewNum     int    `description:"未续约客户数"`
+	NotRenewIds     string `description:"未续约客户ids"`
+	RenewFollowNum  int    `description:"续约跟进客户数"`
+	RenewFollowIds  string `description:"续约跟进客户ids"`
+	ExpireNum       int    `description:"到期客户数"`
+	ExpireIds       string `description:"到期客户ids"`
+	RenewNum        int    `description:"续约客户数"`
+	RenewIds        string `description:"续约客户ids"`
+	StartDate       string `description:"开始日期"`
+	EndDate         string `description:"结束日期"`
+	UnusualRenewNum int    `description:"续约异常客户数"`
+	UnusualRenewIds string `description:"续约异常客户ids"`
+	UnusualRate     string `description:"异常率"`
 }
 
 type YbChartCollectListResp struct {
@@ -195,3 +198,36 @@ type YbChartCollectListItem struct {
 	ChartInfo  *data_manage.ChartInfoView
 	CreateTime string
 }
+
+// CompanyUnusualRenewRecordResp
+// @Description: 续约异常客户统计返回
+type CompanyUnusualRenewRecordResp struct {
+	List        []GroupUnusualRenewRecord      `description:"系统用户分组信息"`
+	SummaryList []SummaryUnusualRenewRecordNum `description:"汇总信息"`
+}
+
+// GroupUnusualRenewRecord
+// @Description: 续约异常的分组信息
+type GroupUnusualRenewRecord struct {
+	SellerId                  int                            `description:"销售ID"`
+	SellerName                string                         `description:"销售名称"`
+	CompanyRenewRecordNumList []CompanyUnusualRenewRecordNum `description:"统计次数"`
+}
+
+// CompanyUnusualRenewRecordNum
+// @Description: 续约异常客户统计信息
+type CompanyUnusualRenewRecordNum struct {
+	StartDate       string `description:"开始日期"`
+	EndDate         string `description:"结束日期"`
+	UnusualRenewNum int    `description:"续约异常客户数"`
+	UnusualRenewIds string `description:"续约异常客户ids"`
+	UnusualRate     string `description:"异常率"`
+}
+
+// SummaryUnusualRenewRecordNum
+// @Description: 续约异常客户汇总数据
+type SummaryUnusualRenewRecordNum struct {
+	UnusualRenewNum int    `description:"续约异常客户数"`
+	UnusualRenewIds string `description:"续约异常客户ids"`
+	UnusualRate     string `description:"异常率"`
+}

+ 165 - 0
services/statistic_report/unusual_renew_company.go

@@ -0,0 +1,165 @@
+package statistic_report
+
+import (
+	"fmt"
+	"hongze/hz_crm_api/models/company"
+	"hongze/hz_crm_api/models/contract"
+	"hongze/hz_crm_api/utils"
+	"strings"
+	"time"
+)
+
+type UnusualCompanyRenewDataMap struct {
+	UnusualRenewMap    map[int]int    `description:"续约异常客户数"`
+	UnusualRenewIdMap  map[int]string `description:"续约异常客户ids"`
+	UnusualRenewTotal  int            `description:"续约异常客户总数(去重)"`
+	FormalCompanyTotal int            `description:"当前正常客户总数(去重)"`
+	StartDate          string         `description:"开始日期"`
+	EndDate            string         `description:"开始日期"`
+}
+
+// GetUnusualRenewWeekDataNum 周度数据
+func GetUnusualRenewWeekDataNum(nowWeekMonday time.Time, productId, dataNum int) (adminDataList []UnusualCompanyRenewDataMap, firstDate time.Time, err error) {
+	nowWeekSunday := nowWeekMonday.AddDate(0, 0, 7).Add(-1 * time.Second) //本周周日
+
+	chanList := make([]chan UnusualCompanyRenewDataMap, 0)
+	for i := 0; i < dataNum; i++ {
+		tmpCh := make(chan UnusualCompanyRenewDataMap, 0)
+		chanList = append(chanList, tmpCh)
+
+		lastWeekMonday := nowWeekMonday.AddDate(0, 0, -7*i)
+		lastWeekSunday := nowWeekSunday.AddDate(0, 0, -7*i)
+
+		// 第一个开始日期
+		firstDate = lastWeekMonday
+		go getUnusualRenewSectionData(productId, lastWeekMonday, lastWeekSunday, tmpCh)
+	}
+
+	adminDataList = make([]UnusualCompanyRenewDataMap, 0)
+	for _, vChan := range chanList {
+		var weekUnusualCompanyRenewDataMap UnusualCompanyRenewDataMap
+		weekUnusualCompanyRenewDataMap = <-vChan
+		close(vChan)
+		adminDataList = append(adminDataList, weekUnusualCompanyRenewDataMap)
+	}
+
+	return
+}
+
+// GetUnusualRenewMonthDataNum 月度数据
+func GetUnusualRenewMonthDataNum(nowMonthFirstDay time.Time, productId, dataNum int) (adminDataList []UnusualCompanyRenewDataMap, firstDate time.Time, err error) { //三个协程返回
+	//nowMonthLastDay := nowMonthFirstDay.AddDate(0, 1, 0).Add(-1 * time.Second) //本月最后一天
+
+	chanList := make([]chan UnusualCompanyRenewDataMap, 0)
+
+	for i := 0; i < dataNum; i++ {
+		tmpCh := make(chan UnusualCompanyRenewDataMap, 0)
+		chanList = append(chanList, tmpCh)
+
+		lastMonthFirstDay := nowMonthFirstDay.AddDate(0, -1*i, 0)                          //上个月第一天
+		lastMonthLastDay := nowMonthFirstDay.AddDate(0, -1*(i-1), 0).Add(-1 * time.Second) //上个月最后一天
+
+		// 第一个开始日期
+		firstDate = lastMonthFirstDay
+		go getUnusualRenewSectionData(productId, lastMonthFirstDay, lastMonthLastDay, tmpCh)
+	}
+
+	adminDataList = make([]UnusualCompanyRenewDataMap, 0)
+	for _, vChan := range chanList {
+		var weekUnusualCompanyRenewDataMap UnusualCompanyRenewDataMap
+		weekUnusualCompanyRenewDataMap = <-vChan
+		close(vChan)
+		adminDataList = append(adminDataList, weekUnusualCompanyRenewDataMap)
+	}
+
+	return
+}
+
+// GetUnusualRenewTimeIntervalData 区间数据
+func GetUnusualRenewTimeIntervalData(productId int, startDate, endDate string) (adminDataMapList []UnusualCompanyRenewDataMap, firstDate time.Time, err error) { //三个协程返回
+	startDateTimer, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
+	endDateTimer, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
+	endDateTimer = endDateTimer.AddDate(0, 0, 1).Add(-1 * time.Second) //本月最后一天
+
+	//最早的一天
+	firstDate = startDateTimer
+
+	ch1 := make(chan UnusualCompanyRenewDataMap, 0)
+
+	go getUnusualRenewSectionData(productId, startDateTimer, endDateTimer, ch1)
+
+	var adminDataMap UnusualCompanyRenewDataMap
+
+	adminDataMap = <-ch1
+	close(ch1)
+
+	adminDataMapList = make([]UnusualCompanyRenewDataMap, 0)
+	adminDataMapList = append(adminDataMapList, adminDataMap)
+	return
+}
+
+// getUnusualRenewSectionData 获取周期数据
+func getUnusualRenewSectionData(productId int, startDate, endDate time.Time, ch chan UnusualCompanyRenewDataMap) (adminDataMap UnusualCompanyRenewDataMap, err error) {
+	defer func() {
+		ch <- adminDataMap
+	}()
+	unusualRenewMap := make(map[int]int)                 // 续约异常客户
+	unusualRenewCompanyIdMap := make(map[int]string)     // 续约异常客户id
+	var unusualRenewCompanyTotal, formalCompanyTotal int //续约异常客户总数  , 当前正式的客户数
+
+	// 当前正式的客户数
+	formalCompanyTotal, err = contract.GetCountFormalCompany(endDate, productId)
+	if err != nil {
+		utils.FileLog.Error(err.Error())
+		return
+	}
+
+	// 续约异常
+	{
+
+		data, tmpErr := company.GetUnusualRenewCompanyList(startDate, endDate, productId)
+
+		if tmpErr != nil {
+			err = tmpErr
+			utils.FileLog.Error(err.Error())
+			return
+		}
+
+		unusualRenewCompanyIdListMap := make(map[int][]string) // 续约异常客户
+		for _, v := range data {
+			// 共享人id为空
+			if v.ShareSellerId <= 0 {
+				continue
+			}
+			// 共享人id不为空,且不是所属销售
+			tmp, ok := unusualRenewMap[v.ShareSellerId]
+			if !ok {
+				tmp = 0
+			}
+			unusualRenewMap[v.ShareSellerId] = tmp + 1
+
+			// 客户id
+			tmpCompanyIdList2, ok := unusualRenewCompanyIdListMap[v.ShareSellerId]
+			if !ok {
+				tmpCompanyIdList2 = make([]string, 0)
+			}
+			unusualRenewCompanyIdListMap[v.ShareSellerId] = append(tmpCompanyIdList2, fmt.Sprint(v.CompanyIds))
+
+			unusualRenewCompanyTotal++
+		}
+
+		for sellerId, tmpCompanyIdList := range unusualRenewCompanyIdListMap {
+			unusualRenewCompanyIdMap[sellerId] = strings.Join(tmpCompanyIdList, ",")
+		}
+	}
+
+	adminDataMap = UnusualCompanyRenewDataMap{
+		UnusualRenewMap:    unusualRenewMap,
+		UnusualRenewIdMap:  unusualRenewCompanyIdMap,
+		UnusualRenewTotal:  unusualRenewCompanyTotal,
+		FormalCompanyTotal: formalCompanyTotal,
+		StartDate:          startDate.Format(utils.FormatDate),
+		EndDate:            endDate.Format(utils.FormatDate),
+	}
+	return
+}

+ 18 - 0
utils/common.go

@@ -2151,3 +2151,21 @@ func RemoveFileSuffixName(fileName string) (removedName string) {
 	}
 	return
 }
+
+// 提取的纯文本内容
+func GetHtmlContentText(content string) (contentSub string, err error) {
+	if content == "" {
+		return
+	}
+	content = html.UnescapeString(content)
+	doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
+	if err != nil {
+		return
+	}
+	docText := doc.Text()
+	bodyRune := []rune(docText)
+	bodyRuneLen := len(bodyRune)
+	body := string(bodyRune[:bodyRuneLen])
+	contentSub = body
+	return
+}

+ 13 - 1
utils/constants.go

@@ -400,6 +400,8 @@ const (
 	CYGX_USER_KEY_LABEL                            = "CYGX_USER_KEY_LABEL"              //查研观向用户标签
 	TPL_MSG_WANG_YANG                              = "tpl_msg_wang_yang"                //汪洋手机号地址参数
 	MicroRoadshowDefaultImgKey                     = "micro_roadshow_default_img"       // 音视频封面图
+	TPL_MSG_NEI_RONG_ZU                            = "tpl_msg_nei_rong_zu"              //内容组四人
+	TPL_MSG_WANG_FANG_WANG_YANG                    = "tpl_msg_wang_fang_wang_yang"      //权限模板消息接收人,王芳,汪洋
 	PERMISSION_ID_YANXUAN_DIFF                     = 20000                              // 买方研选区分3w和5w的差值
 	PERMISSION_ID_YANXUAN_10W_DIFF                 = 20032                              // 买方研选区分10W
 	ZHUAN_JIA_NAME                          string = "专家"
@@ -522,7 +524,7 @@ var FrequencyDaysMap = map[string]int{
 }
 
 const (
-	AiChatLimit = 50
+	AiChatLimit = 500
 )
 
 // 系统来源
@@ -556,3 +558,13 @@ const (
 const CrmEtaAuthorization = "NIi1RbEmH0C2rksXtPGDPBBgRgTZY87Q"
 
 const LoginCacheTime = 60 // 登录缓存时长, 分钟
+
+// GetWeeklyDatabase 获取 weekly_report 库名
+func GetWeeklyDatabase() (databaseName string) {
+	if RunMode == "release" {
+		databaseName = `weekly_report`
+	} else {
+		databaseName = `test_v2_weekly_report`
+	}
+	return
+}

Some files were not shown because too many files changed in this diff