1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186 |
- package report
- import (
- "encoding/json"
- "eta/eta_mini_ht_api/common/component/config"
- "eta/eta_mini_ht_api/common/component/es"
- logger "eta/eta_mini_ht_api/common/component/log"
- "eta/eta_mini_ht_api/common/contants"
- "eta/eta_mini_ht_api/common/utils/page"
- stringUtils "eta/eta_mini_ht_api/common/utils/string"
- configService "eta/eta_mini_ht_api/domian/config"
- analystService "eta/eta_mini_ht_api/domian/financial_analyst"
- messageDomian "eta/eta_mini_ht_api/domian/message"
- userService "eta/eta_mini_ht_api/domian/user"
- "eta/eta_mini_ht_api/models"
- configDao "eta/eta_mini_ht_api/models/config"
- permissionDao "eta/eta_mini_ht_api/models/config"
- "eta/eta_mini_ht_api/models/eta"
- etaDao "eta/eta_mini_ht_api/models/eta"
- "eta/eta_mini_ht_api/models/ht"
- mediaDao "eta/eta_mini_ht_api/models/image"
- merchantDao "eta/eta_mini_ht_api/models/merchant"
- "eta/eta_mini_ht_api/models/message"
- messageDao "eta/eta_mini_ht_api/models/message"
- reportDao "eta/eta_mini_ht_api/models/report"
- userDao "eta/eta_mini_ht_api/models/user"
- "math/rand"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- const (
- SourceETA = "ETA"
- SourceHT = "HT"
- DESC models.Order = "desc"
- ASC models.Order = "asc"
- ESColumn = "title"
- ESRangeColumn = "reportId"
- )
- var (
- sortField = []string{"_score:desc"}
- htConfig = config.GetConfig(contants.HT).(*config.HTBizConfig)
- )
- func elastic() *es.ESClient {
- return es.GetInstance()
- }
- // ESReport Report ES研报mapping
- type ESReport struct {
- ReportID int `json:"reportId"`
- OrgId int `json:"orgId"`
- Title string `json:"title"`
- Author string `json:"author"`
- Source reportDao.ReportSource `json:"source"`
- Abstract string `json:"abstract"`
- CoverSrc int `json:"coverSrc"`
- Status reportDao.ReportStatus `json:"status"`
- PublishedTime string `json:"publishedTime"`
- }
- type ReportDTO struct {
- Type string `json:"type"`
- ReportID int `json:"reportId"`
- OrgId int `json:"orgId"`
- Title string `json:"title"`
- Author string `json:"author"`
- AuthorInfo []Anthor `json:"authorInfo"`
- Source string `json:"source"`
- Abstract string `json:"abstract"`
- PublishedTime string `json:"publishedTime"`
- RiskLevel string `json:"riskLevel"`
- PlateName string `json:"-"`
- ClassifyId int `json:"-"`
- SecondPermission map[int]string `json:"-"`
- Permissions map[int]string `json:"-"`
- PermissionNames interface {
- } `json:"permissionNames"`
- Highlight []string `json:"highlight"`
- Detail json.RawMessage `json:"detail"`
- PdfUrl string `json:"pdfUrl"`
- CoverSrc int `json:"coverSrc"`
- CoverUrl string `json:"coverUrl"`
- Login bool `json:"login"`
- RiskLevelStatus string `json:"riskLevelStatus"`
- IsFree bool `json:"isFree"`
- IsSubscribe bool `json:"isSubscribe"`
- SubscribeStatus string `json:"subscribeStatus"`
- Price string `json:"price"`
- ProductId int `json:"productId"`
- IsPackage bool `json:"isPackage"`
- Score float64 `json:"score"`
- Show bool `json:"-"`
- IsCollect bool `json:"isCollected"`
- }
- type Detail struct {
- }
- type Anthor struct {
- Id int `json:"id"`
- Name string `json:"name"`
- HeadImgUrl string `json:"headImgUrl"`
- Following string `json:"following"`
- }
- func GetReportById(reportId int, userId int) (ReportDTO ReportDTO, err error) {
- report, err := reportDao.GetReportById(reportId)
- if err != nil {
- return
- }
- ReportDTO = convertReportDTO(report, true)
- authorStr := ReportDTO.Author
- authorNames := strings.Split(authorStr, ",")
- authorNames = stringUtils.RemoveEmptyStrings(authorNames)
- var authorList []Anthor
- if len(authorNames) > 0 {
- for _, name := range authorNames {
- var author analystService.FinancialAnalystDTO
- author, err = analystService.GetAnalystByName(name)
- var item Anthor
- if err != nil {
- item = Anthor{
- Id: 0,
- Name: name,
- HeadImgUrl: "",
- Following: string(userDao.Unfollowed),
- }
- } else {
- item = Anthor{
- Id: author.Id,
- Name: author.Name,
- HeadImgUrl: author.HeadImgUrl,
- Following: userDao.GetFollowing(userId, author.Id),
- }
- }
- authorList = append(authorList, item)
- }
- }
- ReportDTO.AuthorInfo = authorList
- return
- }
- func GetTotalPageCountByAnalyst(analyst string, permissionIds []int) (total int64, latestId int64, ids []int) {
- ids, err := reportDao.GetReportsByAnalyst(analyst)
- if err != nil {
- logger.Error("查询研究研报告列表id失败:%v", err)
- return
- }
- var wg sync.WaitGroup
- wg.Add(2)
- var htOrgIds []int
- var etaOrgIds []int
- go func() {
- defer wg.Done()
- htOrgIds, err = getHtOrgIds(permissionIds)
- if err != nil {
- logger.Error("品种筛选ht报告id失败:%v", err)
- }
- }()
- go func() {
- defer wg.Done()
- etaOrgIds, err = getEtaOrgIds(permissionIds)
- if err != nil {
- logger.Error("品种筛选eta报告id失败:%v", err)
- }
- }()
- wg.Wait()
- totalCol := int64(len(etaOrgIds) + len(htOrgIds))
- if totalCol == 0 {
- latestId = 0
- return
- }
- if len(etaOrgIds) == 0 && len(htOrgIds) == 0 {
- logger.Info("没有符合权限的研报")
- return
- }
- orgIds := make(map[string][]int, 2)
- if len(etaOrgIds) == 0 {
- orgIds["ETA"] = []int{}
- } else {
- orgIds["ETA"] = etaOrgIds
- }
- if len(htOrgIds) == 0 {
- orgIds["HT"] = []int{}
- } else {
- orgIds["HT"] = htOrgIds
- }
- permitReportIds, err := reportDao.GetReportIdListByOrgIds(orgIds)
- if err != nil {
- logger.Error("根据原始报告id获取报告id列表失败:%v", err)
- return
- }
- var filterReportIds []int
- for _, id := range ids {
- for _, permitReportId := range permitReportIds {
- if id == permitReportId {
- filterReportIds = append(filterReportIds, id)
- }
- }
- }
- if len(filterReportIds) == 0 {
- logger.Info("没有符合权限的研究员研报")
- return
- }
- ids = filterReportIds
- //获取一下下架的报告产品
- var disCardReportIds []int
- offSaleProducts, err := merchantDao.GetOffSaleProducts([]merchantDao.MerchantProductType{merchantDao.Report, merchantDao.Package})
- if err != nil {
- logger.Error("获取下架的报告产品失败:%v", err)
- return
- }
- var ProductPermissionIds []int
- for _, product := range offSaleProducts {
- if product.Type == "package" {
- ProductPermissionIds = append(ProductPermissionIds, product.SourceId)
- }
- if product.Type == "report" {
- disCardReportIds = append(disCardReportIds, product.SourceId)
- }
- }
- if len(ProductPermissionIds) > 0 {
- wg.Add(2)
- var permissionNames []string
- var classifyIds []int
- go func() {
- defer wg.Done()
- var permissionErr error
- permissionNames, permissionErr = GetPermissionNamesByPermissionIds(ProductPermissionIds)
- if permissionErr != nil {
- logger.Error("获取ETA品种名称失败:%v", err)
- }
- }()
- go func() {
- defer wg.Done()
- var classifyErr error
- classifyIds, classifyErr = permissionDao.GetClassifyIdsByPermissionIds(ProductPermissionIds)
- if classifyErr != nil {
- logger.Error("获取ETA报告分类id失败:%v", err)
- }
- }()
- wg.Wait()
- disCardIds, _ := reportDao.GetHiddenReportIds(classifyIds, permissionNames)
- if len(disCardIds) > 0 {
- disCardReportIds = append(disCardReportIds, disCardIds...)
- }
- }
- //对数据去重
- disCardReportIds = uniqueArray(disCardReportIds)
- //获取报告中还包含上架套餐的id
- if len(disCardReportIds) > 0 {
- reportIdsSalePackage, _ := merchantDao.GetReportOnSalePackageIds(disCardReportIds)
- reportIdsSaleProduct, _ := merchantDao.GetOnSaleReportIds(disCardReportIds)
- showReportMap := make(map[int]bool)
- disCardMap := make(map[int]bool)
- for _, reportId := range reportIdsSalePackage {
- showReportMap[reportId] = true
- }
- for _, reportId := range reportIdsSaleProduct {
- showReportMap[reportId] = true
- }
- var filterDisCardReportIds []int
- for _, id := range disCardReportIds {
- if _, ok := showReportMap[id]; !ok {
- filterDisCardReportIds = append(filterDisCardReportIds, id)
- disCardMap[id] = true
- }
- }
- disCardReportIds = filterDisCardReportIds
- var cardReportIds []int
- for _, id := range filterReportIds {
- if _, ok := disCardMap[id]; !ok {
- cardReportIds = append(cardReportIds, id)
- }
- }
- filterReportIds = cardReportIds
- }
- total = int64(len(filterReportIds))
- latestId = int64(findMax(filterReportIds))
- return
- }
- // findMaxWithError 函数用于找到整型数组中的最大值,并返回错误信息
- func findMax(nums []int) (max int) {
- if len(nums) == 0 {
- return 0
- }
- // 初始化最大值为数组的第一个元素
- max = nums[0]
- // 遍历数组,找到最大值
- for _, num := range nums {
- if num > max {
- max = num
- }
- }
- return
- }
- func SearchMaxReportIdWithRange(key string, reportIds []int) (total int64) {
- sort := []string{"reportId:desc"}
- var docIds []string
- for _, reportId := range reportIds {
- docIds = append(docIds, strconv.Itoa(reportId))
- }
- request := CountByDocId(key, sort, docIds)
- //同步es
- re, err := elastic().Count(request)
- if err != nil {
- logger.Error("es搜索异常:%v", err)
- }
- count := re.Count
- total = int64(count)
- if total > 0 {
- request = match(key, 0, count, sort)
- re, err = elastic().Search(request)
- if err != nil {
- logger.Error("es搜索异常:%v", err)
- }
- hits := elastic().GetSource(re.Hits)
- data := hits[0].Source
- report := ReportDTO{}
- err = json.Unmarshal(data, &report)
- if err != nil {
- logger.Error("获取当前最大研报id失败:%v", err)
- return
- }
- }
- return
- }
- func SearchReportList(key string, ids []int, from int, size int, max int64) (reports []ReportDTO, err error) {
- //同步es
- var docIds []string
- for _, id := range ids {
- docIds = append(docIds, strconv.Itoa(id))
- }
- sorts := append(sortField, "publishedTime:desc")
- var request *es.ESQueryRequest
- if max == -1 {
- request = matchRangeWithDocIds(key, from, size, sorts, docIds)
- } else {
- request = matchRangeByDocId(key, from, size, max, sorts, docIds)
- }
- re, err := elastic().Search(request)
- if err != nil {
- logger.Error("es搜索异常:%v", err)
- }
- hits := elastic().GetSource(re.Hits)
- if len(hits) == 0 {
- reports = []ReportDTO{}
- return
- }
- for _, hit := range hits {
- var content map[string][]string
- err = json.Unmarshal(hit.Highlight, &content)
- report := ReportDTO{}
- err = json.Unmarshal(hit.Source, &report)
- if err != nil {
- logger.Error("解析研报数据失败:%v", err)
- continue
- }
- report.Highlight = content[ESColumn]
- report.Title = report.Highlight[0]
- report.PublishedTime = report.PublishedTime[:10]
- reports = append(reports, report)
- }
- return
- }
- func GetReportPageByAnalyst(pageInfo page.PageInfo, analyst string, reportIds []int) (list []ReportDTO, err error) {
- offset := page.StartIndex(pageInfo.Current, pageInfo.PageSize)
- reports, err := reportDao.GetReportPageByAnalyst(pageInfo.LatestId, pageInfo.PageSize, offset, analyst, reportIds)
- if err != nil {
- logger.Error("分页查询报告列表失败:%v", err)
- return
- }
- list = make([]ReportDTO, 0)
- if reports != nil {
- for _, report := range reports {
- dto := convertReportDTO(report, false)
- list = append(list, dto)
- }
- }
- return
- }
- func GetReportPageByOrgIds(pageInfo page.PageInfo, orgIds map[string][]int, discardIds []int) (list []ReportDTO, err error) {
- offset := page.StartIndex(pageInfo.Current, pageInfo.PageSize)
- reports, err := reportDao.GetReportPageByOrgIds(pageInfo.LatestId, pageInfo.PageSize, offset, orgIds, discardIds)
- if err != nil {
- logger.Error("分页查询报告列表失败:%v", err)
- return
- }
- list = make([]ReportDTO, 0)
- if reports != nil {
- for _, report := range reports {
- dto := convertReportDTO(report, false)
- list = append(list, dto)
- }
- }
- return
- }
- func getETAReportFirstPermissions(id int) (permissionDTOs []configService.PermissionDTO) {
- classifyId, err := etaDao.GetReportClassifyById(id)
- if err != nil || classifyId == 0 {
- logger.Error("获取研报分类信息失败:%v", err)
- return
- }
- permissions, err := permissionDao.GetFirstPermissionsByClassifyID(classifyId)
- if err != nil {
- logger.Error("获取研报一级品种信息失败:%v", err)
- return
- }
- for _, permission := range permissions {
- permissionDTOs = append(permissionDTOs, convertPermissionDTO(permission))
- }
- return
- }
- func getHTReportFirstPermissions(id int) (permissionDTOs []configService.PermissionDTO) {
- report, err := reportDao.GetReportByOrgId(id, SourceHT)
- if err != nil {
- logger.Error("获取报告失败:%v", err)
- }
- permissionName := report.PlateName
- plateName, err := reportDao.GetPlateNameByPermissionName(permissionName)
- if err != nil {
- return []configService.PermissionDTO{}
- }
- return []configService.PermissionDTO{
- {
- PermissionId: 0,
- PermissionName: plateName,
- ParentId: 0,
- },
- }
- }
- func getETAReportSecondPermissions(id int) (permissionDTOs []configService.PermissionDTO) {
- classifyId, err := reportDao.GetReportClassifyById(id)
- //classifyId, err := etaDao.GetReportClassifyById(id)
- if err != nil || classifyId == 0 {
- logger.Error("获取研报分类信息失败:%v", err)
- return
- }
- permissions, err := permissionDao.GetSecondPermissionsByClassifyID(classifyId)
- //permissions, err := eta.GetSecondPermissionsByClassifyID(classifyId)
- if err != nil {
- logger.Error("获取研报二级品种信息失败:%v", err)
- return
- }
- for _, permission := range permissions {
- permissionDTOs = append(permissionDTOs, convertPermissionDTO(permission))
- }
- return
- }
- func getHTReportSecondPermissions(id int) (permissionDTOs []configService.PermissionDTO) {
- report, err := reportDao.GetReportByOrgId(id, SourceHT)
- if err != nil {
- logger.Error("获取报告失败:%v", err)
- }
- var permission permissionDao.Permission
- if report.PlateName != "" {
- permission, err = permissionDao.GetPermissionByName(report.PlateName)
- if err != nil {
- logger.Error("获取品种信息失败:%v", err)
- }
- }
- return []configService.PermissionDTO{
- {
- PermissionId: permission.PermissionId,
- PermissionName: report.PlateName,
- ParentId: permission.ParentId,
- RiskLevel: permission.RiskLevel,
- },
- }
- }
- func (es ESReport) GetId() string {
- return strconv.Itoa(es.ReportID)
- }
- func GetETALatestReportId() (id int, err error) {
- return reportDao.GetLatestReportIdBySource(reportDao.SourceETA)
- }
- func GetHTLatestReportId() (id int, err error) {
- return reportDao.GetLatestReportIdBySource(reportDao.SourceHT)
- }
- func InitETAReportList(list []eta.ETAReport) (err error) {
- logger.Info("同步研报数量%d", len(list))
- var reports []reportDao.Report
- for _, etaRp := range list {
- var coverSrc int
- //var permissions []etaDao.ChartPermission
- //permissions, err = etaDao.GetSecondPermissionsByClassifyID(etaRp.ClassifyID)
- var permissions []permissionDao.Permission
- permissions, err = permissionDao.GetSecondPermissionsByClassifyID(etaRp.ClassifyID)
- if err != nil || len(permissions) == 0 {
- logger.Error("获取研报二级品种信息失败:%v", err)
- coverSrc = 0
- } else {
- coverSrc = 0
- for _, permission := range permissions {
- permissionsId := permission.PermissionId
- var ids []int
- ids, err = mediaDao.GetIdsByPermissionId(permissionsId)
- if err != nil {
- logger.Error("获取图片资源失败:%v", err)
- continue
- }
- if ids == nil || len(ids) == 0 {
- continue
- }
- src := rand.NewSource(time.Now().UnixNano())
- r := rand.New(src)
- // 从切片中随机选择一个元素
- randomIndex := r.Intn(len(ids))
- coverSrc = ids[randomIndex]
- break
- }
- }
- destRp := convertEtaReport(etaRp, reportDao.StatusPublish)
- //destRp.Author = authorName
- destRp.CoverSrc = coverSrc
- reports = append(reports, destRp)
- //}
- }
- err = reportDao.BatchInsertReport(&reports)
- if err != nil {
- logger.Error("同步ETA研报失败:%v", err)
- return
- }
- return initES(reports)
- }
- func etaStatus(status int) reportDao.ReportStatus {
- if status == etaDao.Passed || status == etaDao.Published {
- return reportDao.StatusPublish
- } else {
- return reportDao.StatusUnPublish
- }
- }
- func SyncETAReportList(list []eta.ETAReport) (err error) {
- logger.Info("同步研报数量%d", len(list))
- var reports []reportDao.Report
- for _, etaRp := range list {
- var coverSrc int
- //var permissions []etaDao.ChartPermission
- //permissions, err = etaDao.GetSecondPermissionsByClassifyID(etaRp.ClassifyID)
- var permissions []permissionDao.Permission
- permissions, err = permissionDao.GetSecondPermissionsByClassifyID(etaRp.ClassifyID)
- if err != nil || len(permissions) == 0 {
- logger.Error("获取研报二级品种信息失败:%v", err)
- coverSrc = 0
- } else {
- coverSrc = 0
- for _, permission := range permissions {
- permissionsId := permission.PermissionId
- var ids []int
- ids, err = mediaDao.GetIdsByPermissionId(permissionsId)
- if err != nil {
- logger.Error("获取图片资源失败:%v", err)
- continue
- }
- if ids == nil || len(ids) == 0 {
- continue
- }
- src := rand.NewSource(time.Now().UnixNano())
- r := rand.New(src)
- // 从切片中随机选择一个元素
- randomIndex := r.Intn(len(ids))
- coverSrc = ids[randomIndex]
- break
- }
- }
- status := etaStatus(etaRp.State)
- destRp := convertEtaReport(etaRp, status)
- destRp.CoverSrc = coverSrc
- reports = append(reports, destRp)
- }
- esList, err := reportDao.InsertOrUpdateReport(reports, SourceETA)
- if esList == nil {
- return
- }
- return syncESAndSendMessage(esList)
- }
- type UpdateESReport struct {
- Title string `json:"title"`
- Author string `json:"author"`
- Abstract string `json:"abstract"`
- PublishedTime string `json:"publishedTime"`
- Status string `json:"status"`
- }
- func syncESAndSendMessage(reports []reportDao.Report) (err error) {
- var esReports []es.ESBase
- for _, etaRp := range reports {
- esRp := convertEsReport(etaRp)
- esReports = append(esReports, esRp)
- }
- //同步es
- for _, report := range reports {
- var exist bool
- exist, err = elastic().Exist(htConfig.GetReportIndex(), report.ID)
- if err != nil {
- logger.Error("查询es失败,reportId::%d,err:%v", report.ID, err)
- }
- if exist {
- update := UpdateESReport{
- Title: report.Title,
- Author: report.Author,
- PublishedTime: report.PublishedTime,
- Abstract: report.Abstract,
- Status: string(report.Status),
- }
- success := elastic().Update(htConfig.GetReportIndex(), report.ID, update)
- if !success {
- logger.Error("更新es失败,reportId::%d,err:%v", report.ID, err)
- }
- if report.Status == reportDao.StatusUnPublish || report.Status == reportDao.StatusDeleted {
- //隐藏热度搜索
- err = userDao.HiddenFlows(report.ID, message.ReportSourceType)
- if err != nil {
- logger.Error("隐藏热度搜索失败,reportId::%d,err:%v", report.ID, err)
- }
- } else {
- err = userDao.ShowFlows(report.ID, message.ReportSourceType)
- if err != nil {
- logger.Error("重置热度搜索失败,reportId::%d,err:%v", report.ID, err)
- }
- }
- } else {
- insert := ESReport{
- ReportID: report.ID,
- OrgId: report.OrgID,
- Title: report.Title,
- Author: report.Author,
- Source: report.Source,
- Abstract: report.Abstract,
- CoverSrc: report.CoverSrc,
- Status: report.Status,
- PublishedTime: report.PublishedTime,
- }
- success := elastic().CreateDocument(htConfig.GetReportIndex(), report.ID, insert)
- if !success {
- logger.Error("创建es文档失败,reportId::%d,err:%v", report.ID, err)
- }
- }
- }
- //err = elastic().BulkInsert(htConfig.GetReportIndex(), esReports)
- if err != nil {
- logger.Error("同步ETA研报到es失败:%v", err)
- return
- }
- //生产meta信息
- logger.Info("生成推送META信息")
- for _, report := range reports {
- if report.Status == reportDao.StatusUnPublish || report.Status == reportDao.StatusDeleted {
- logger.Info("报告取消发布或删除" +
- ",不需要生成推送消息")
- continue
- }
- var From string
- switch report.Source {
- case SourceETA:
- From = "ETA"
- case SourceHT:
- From = "HT"
- default:
- From = "UNKNOWN"
- }
- authors := strings.Split(report.Author, ",")
- authors = stringUtils.RemoveEmptyStrings(authors)
- if len(authors) > 0 {
- for _, authorName := range authors {
- userIds := userService.GetPostUser(authorName, report.PublishedTime)
- if len(userIds) > 0 {
- logger.Info("推送META信息,用户ID:%v", userIds)
- var author analystService.FinancialAnalystDTO
- author, err = analystService.GetAnalystByName(authorName)
- if err != nil {
- logger.Error("获取研报作者失败:%v", err)
- continue
- }
- usersStr := stringUtils.IntToStringSlice(userIds)
- Meta := messageDao.MetaData{
- AuthorName: author.Name,
- AuthorId: author.Id,
- SourceId: report.ID,
- PublishedTime: report.PublishedTime,
- }
- metaStr, _ := json.Marshal(Meta)
- toStr := strings.Join(usersStr, ",")
- metaContent := messageDomian.MetaInfoDTO{
- From: From,
- Meta: string(metaStr),
- MetaType: "USER_NOTICE",
- SourceType: "REPORT",
- To: toStr,
- }
- err = messageDomian.CreateMetaInfo(metaContent)
- if err != nil {
- logger.Error("创建Meta信息失败:%v", err)
- return err
- }
- }
- }
- }
- }
- return
- }
- func initES(reports []reportDao.Report) (err error) {
- var esReports []es.ESBase
- for _, etaRp := range reports {
- esRp := convertEsReport(etaRp)
- esReports = append(esReports, esRp)
- }
- //同步es
- err = elastic().BulkInsert(htConfig.GetReportIndex(), esReports)
- if err != nil {
- logger.Error("同步ETA研报到es失败:%v", err)
- return
- }
- return
- }
- func InitHTReportList(list []ht.HTReport) (noRecord bool, err error) {
- var reports []reportDao.Report
- //获取系统中ht品种名
- permissions, err := reportDao.GetGLAuthorNames()
- if err != nil {
- logger.Error("获取钢联研报作者失败:%v", err)
- return
- }
- for _, htRp := range list {
- for _, permission := range permissions {
- if htRp.PermissionName == permission.Permission {
- if permission.AuthorNames != "" {
- htRp.PublishUserName = permission.AuthorNames
- }
- destRp := convertHTReport(htRp, reportDao.StatusPublish)
- var coverSrc int
- var permissionId int
- permissionId, err = permissionDao.GetPermissionIdByName(htRp.PermissionName)
- //permissionId, err = etaDao.GetPermissionIdByName(htRp.PermissionName)
- if err != nil {
- logger.Error("HT获取eta品种id失败:%v", err)
- coverSrc = 0
- }
- var ids []int
- ids, err = mediaDao.GetIdsByPermissionId(permissionId)
- if err != nil {
- logger.Error("获取图片资源失败:%v", err)
- coverSrc = 0
- }
- if ids == nil || len(ids) == 0 {
- coverSrc = 0
- } else {
- src := rand.NewSource(time.Now().UnixNano())
- r := rand.New(src)
- // 从切片中随机选择一个元素
- randomIndex := r.Intn(len(ids))
- coverSrc = ids[randomIndex]
- }
- destRp.CoverSrc = coverSrc
- destRp.PlateName = htRp.PermissionName
- reports = append(reports, destRp)
- }
- //}
- }
- }
- if len(reports) == 0 {
- return true, nil
- } else {
- logger.Info("同步研报数量%d", len(reports))
- err = reportDao.BatchInsertReport(&reports)
- if err != nil {
- logger.Error("同步HT研报失败:%v", err)
- return false, err
- }
- return false, initES(reports)
- }
- }
- func htStatus(status int, isDelete int) reportDao.ReportStatus {
- if isDelete == 1 {
- return reportDao.StatusDeleted
- }
- if status != ht.Publish {
- return reportDao.StatusUnPublish
- }
- return reportDao.StatusPublish
- }
- func SyncHTReportList(list []ht.HTReport) (noRecord bool, err error) {
- var reports []reportDao.Report
- permissions, err := reportDao.GetGLAuthorNames()
- if err != nil {
- logger.Error("获取钢联研报作者失败:%v", err)
- return
- }
- for _, htRp := range list {
- for _, permission := range permissions {
- if htRp.PermissionName == permission.Permission {
- if permission.AuthorNames != "" {
- htRp.PublishUserName = permission.AuthorNames
- }
- status := htStatus(htRp.Status, htRp.IsDelete)
- destRp := convertHTReport(htRp, status)
- var coverSrc int
- var permissionId int
- permissionId, err = permissionDao.GetPermissionIdByName(htRp.PermissionName)
- //permissionId, err = etaDao.GetPermissionIdByName(htRp.PermissionName)
- if err != nil {
- logger.Error("HT获取eta品种id失败:%v", err)
- coverSrc = 0
- }
- var ids []int
- ids, err = mediaDao.GetIdsByPermissionId(permissionId)
- if err != nil {
- logger.Error("获取图片资源失败:%v", err)
- coverSrc = 0
- }
- if ids == nil || len(ids) == 0 {
- coverSrc = 0
- } else {
- src := rand.NewSource(time.Now().UnixNano())
- r := rand.New(src)
- // 从切片中随机选择一个元素
- randomIndex := r.Intn(len(ids))
- coverSrc = ids[randomIndex]
- }
- destRp.CoverSrc = coverSrc
- destRp.PlateName = htRp.PermissionName
- reports = append(reports, destRp)
- }
- //}
- }
- }
- if len(reports) == 0 {
- return true, nil
- } else {
- logger.Info("同步研报数量%d", len(list))
- }
- esList, err := reportDao.InsertOrUpdateReport(reports, SourceHT)
- if esList == nil {
- return false, err
- }
- return false, syncESAndSendMessage(reports)
- }
- func GetListOrderByConditionWeekly(week bool, column string, limit int, order models.Order) (dtoList []ReportDTO, err error) {
- reports, err := reportDao.GetListOrderByCondition(week, column, limit, order)
- if err != nil {
- logger.Error("获取研报失败:%v", err)
- return
- }
- for _, reportItem := range reports {
- dto := convertReportDTO(reportItem, false)
- dtoList = append(dtoList, dto)
- }
- return
- }
- func GetListByCondition[T any](column string, ids []T) (dtoList []ReportDTO, err error) {
- var values []interface{}
- for _, id := range ids {
- values = append(values, id)
- }
- reports, err := reportDao.GetListByCondition(column, ids)
- if err != nil {
- logger.Error("获取研报失败:%v", err)
- return
- }
- for _, reportItem := range reports {
- dto := convertReportDTO(reportItem, false)
- dtoList = append(dtoList, dto)
- }
- return
- }
- func GetReportByIdListByOrgIds(orgIds map[string][]int) (ids []int, err error) {
- return reportDao.GetReportIdListByOrgIds(orgIds)
- }
- func getHtOrgIds(permissionIds []int) (htOrgIds []int, err error) {
- return GetHTReportIdsByPermissionIdsWithRiskLevel(permissionIds)
- }
- func getEtaOrgIds(permissionIds []int) (htOrgIds []int, err error) {
- return GetETAReportIdsByPermissionIdsWithRiskLevel(permissionIds)
- }
- func GetTotalPageCountByPermissionIds(permissionIds []int) (total int64, latestId int64, ids map[string][]int, disCardReportIds []int) {
- var wg sync.WaitGroup
- wg.Add(2)
- var htOrgIds []int
- var etaOrgIds []int
- go func() {
- defer wg.Done()
- var err error
- htOrgIds, err = getHtOrgIds(permissionIds)
- if err != nil {
- logger.Error("品种筛选ht报告id失败:%v", err)
- }
- }()
- go func() {
- defer wg.Done()
- var err error
- etaOrgIds, err = getEtaOrgIds(permissionIds)
- if err != nil {
- logger.Error("品种筛选eta报告id失败:%v", err)
- }
- }()
- wg.Wait()
- totalCol := int64(len(etaOrgIds) + len(htOrgIds))
- if totalCol == 0 {
- latestId = 0
- return
- }
- ids = make(map[string][]int, 2)
- if len(etaOrgIds) == 0 {
- ids["ETA"] = []int{}
- } else {
- ids["ETA"] = etaOrgIds
- }
- if len(htOrgIds) == 0 {
- ids["HT"] = []int{}
- } else {
- ids["HT"] = htOrgIds
- }
- //获取一下下架的报告产品
- offSaleProducts, err := merchantDao.GetOffSaleProducts([]merchantDao.MerchantProductType{merchantDao.Report, merchantDao.Package})
- if err != nil {
- logger.Error("获取下架的报告产品失败:%v", err)
- return
- }
- var ProductPermissionIds []int
- for _, product := range offSaleProducts {
- if product.Type == "package" {
- ProductPermissionIds = append(ProductPermissionIds, product.SourceId)
- }
- if product.Type == "report" {
- disCardReportIds = append(disCardReportIds, product.SourceId)
- }
- }
- if len(ProductPermissionIds) > 0 {
- wg.Add(2)
- var permissionNames []string
- var classifyIds []int
- go func() {
- defer wg.Done()
- var permissionErr error
- permissionNames, permissionErr = GetPermissionNamesByPermissionIds(ProductPermissionIds)
- if permissionErr != nil {
- logger.Error("获取ETA品种名称失败:%v", err)
- }
- }()
- go func() {
- defer wg.Done()
- var classifyErr error
- classifyIds, classifyErr = permissionDao.GetClassifyIdsByPermissionIds(ProductPermissionIds)
- if classifyErr != nil {
- logger.Error("获取ETA报告分类id失败:%v", err)
- }
- }()
- wg.Wait()
- disCardIds, _ := reportDao.GetHiddenReportIds(classifyIds, permissionNames)
- if len(disCardIds) > 0 {
- disCardReportIds = append(disCardReportIds, disCardIds...)
- }
- }
- //对数据去重
- disCardReportIds = uniqueArray(disCardReportIds)
- //获取报告中还包含上架套餐的id
- if len(disCardReportIds) > 0 {
- reportIdsSalePackage, _ := merchantDao.GetReportOnSalePackageIds(disCardReportIds)
- reportIdsSaleProduct, _ := merchantDao.GetOnSaleReportIds(disCardReportIds)
- showReportMap := make(map[int]bool)
- for _, reportId := range reportIdsSalePackage {
- showReportMap[reportId] = true
- }
- for _, reportId := range reportIdsSaleProduct {
- showReportMap[reportId] = true
- }
- var filterDisCardReportIds []int
- for _, id := range disCardReportIds {
- if _, ok := showReportMap[id]; !ok {
- filterDisCardReportIds = append(filterDisCardReportIds, id)
- }
- }
- disCardReportIds = filterDisCardReportIds
- }
- //获取这些id的产品
- total, latestId, err = reportDao.GetMaxIdByPermissionIds(ids, disCardReportIds)
- if err != nil {
- logger.Error("获取筛选报告的最大记录和记录数失败:%v", err)
- return
- }
- return
- }
- type etaReport struct {
- Id int `json:"id"`
- ClassifyId int `json:"classifyId"`
- PermissionIds []int `json:"permissionIds"`
- }
- type htReport struct {
- Id int `json:"id"`
- PlateName string `json:"plateName"`
- PermissionId []int `json:"permissionId"`
- }
- func uniqueArray(arr []int) []int {
- uniqueMap := make(map[int]bool)
- var result []int
- for _, value := range arr {
- if _, exists := uniqueMap[value]; !exists {
- uniqueMap[value] = true
- result = append(result, value)
- }
- }
- return result
- }
- func convertEtaReport(etaRp eta.ETAReport, status reportDao.ReportStatus) reportDao.Report {
- return reportDao.Report{
- OrgID: etaRp.ID,
- Title: etaRp.Title,
- Abstract: etaRp.Abstract,
- Author: etaRp.Author,
- ClassifyId: etaRp.ClassifyID,
- CoverSrc: 0,
- PublishedTime: etaRp.PublishTime.Format(time.DateTime),
- Source: reportDao.SourceETA,
- SendStatus: reportDao.UNSEND,
- Status: status,
- }
- }
- func convertHTReport(etaRp ht.HTReport, status reportDao.ReportStatus) reportDao.Report {
- return reportDao.Report{
- OrgID: etaRp.Id,
- Title: etaRp.ReportName,
- Author: etaRp.PublishUserName,
- PublishedTime: etaRp.PublishedTime,
- CoverSrc: 0,
- Source: reportDao.SourceHT,
- SendStatus: reportDao.UNSEND,
- Status: status,
- }
- }
- func convertEsReport(report reportDao.Report) ESReport {
- return ESReport{
- ReportID: report.ID,
- Title: report.Title,
- OrgId: report.OrgID,
- Author: report.Author,
- Source: report.Source,
- Abstract: report.Abstract,
- Status: report.Status,
- CoverSrc: report.CoverSrc,
- PublishedTime: report.PublishedTime,
- }
- }
- func convertReportDTO(report reportDao.Report, fullTime bool) (reportDTO ReportDTO) {
- reportDTO = ReportDTO{
- ReportID: report.ID,
- Title: report.Title,
- OrgId: report.OrgID,
- Author: report.Author,
- Source: string(report.Source),
- CoverSrc: report.CoverSrc,
- Abstract: report.Abstract,
- PublishedTime: report.PublishedTime,
- PlateName: report.PlateName,
- ClassifyId: report.ClassifyId,
- }
- publishDate, err := time.Parse(time.DateTime, reportDTO.PublishedTime)
- if err == nil && !fullTime {
- reportDTO.PublishedTime = publishDate.Format(time.DateOnly)
- }
- return
- }
- func matchAll(sorts []string, key string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, 0, 1, sorts, es.MatchAllByCondition).ByCondition("status", "PUBLISH")
- }
- func match(key string, from int, to int, sorts []string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, from, to, sorts, es.MatchAllByCondition).ByCondition("status", "PUBLISH")
- }
- func matchRange(key string, from int, to int, max int64, sorts []string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, from, to, sorts, es.RangeByCondition).Range(0, max, ESRangeColumn).ByCondition("status", "PUBLISH")
- }
- func matchRangeByDocId(key string, from int, to int, max int64, sorts []string, docIds []string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, from, to, sorts, es.RangeByConditionWithDocIds).Range(0, max, ESRangeColumn).ByCondition("status", "PUBLISH").WithDocs(docIds)
- }
- func matchRangeWithDocIds(key string, from int, to int, sorts []string, docIds []string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, from, to, sorts, es.RangeByConditionWithDocIdsNoLimit).ByCondition("status", "PUBLISH").WithDocs(docIds)
- }
- func CountByDocId(key string, sorts []string, docIds []string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, 0, 1, sorts, es.CountWithDocIds).WithDocs(docIds)
- }
- func matchLimitByScore(key string, limit int, score float64, docIds []string) (request *es.ESQueryRequest) {
- req := new(es.ESQueryRequest)
- return req.CreateESQueryRequest(htConfig.GetReportIndex(), ESColumn, key, 0, limit, sortField, es.LimitByScore).WithScore(score).WithDocs(docIds)
- }
- func SearchReportProduct(key string, limit int, score float64, docIds []int) (reports []ReportDTO, err error) {
- var docStrIds []string
- for _, id := range docIds {
- docStrIds = append(docStrIds, strconv.Itoa(id))
- }
- request := matchLimitByScore(key, limit, score, docStrIds)
- re, err := elastic().Search(request)
- if err != nil {
- logger.Error("es搜索异常:%v", err)
- }
- hits := elastic().GetSource(re.Hits)
- if len(hits) == 0 {
- reports = []ReportDTO{}
- return
- }
- for _, hit := range hits {
- var content map[string][]string
- err = json.Unmarshal(hit.Highlight, &content)
- report := ReportDTO{}
- err = json.Unmarshal(hit.Source, &report)
- if err != nil {
- logger.Error("解析研报数据失败:%v", err)
- continue
- }
- report.Score = hit.Score
- report.Highlight = content[ESColumn]
- report.Title = report.Highlight[0]
- report.PublishedTime = report.PublishedTime[:10]
- reports = append(reports, report)
- }
- return
- }
- type ProductSearchDTO struct {
- HighLight string
- SourceId int
- SourceType string
- Score float64
- }
- func CountPermissionWeight(ids []int) (list []configDao.PermissionWeight, err error) {
- return reportDao.CountPermissionWeight(ids)
- }
- func FilterReportIds(sourceIds []int) (total int64, reportIds []int, err error) {
- return reportDao.FilterReportIds(sourceIds)
- }
- func GetReportListById(reportIds []int) (reportList []ReportDTO, err error) {
- reports, err := reportDao.GetReportListById(reportIds)
- if err != nil {
- return
- }
- for _, report := range reports {
- reportList = append(reportList, convertReportDTO(report, false))
- }
- return
- }
- func DeleteReport(reportId int) (err error) {
- return reportDao.DeleteReport(reportId)
- }
|