base_from_fenwei.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. package services
  2. import (
  3. "eta/eta_index_lib/logic"
  4. "eta/eta_index_lib/models"
  5. "eta/eta_index_lib/services/alarm_msg"
  6. "eta/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/beego/beego/v2/core/logs"
  9. "github.com/mozillazg/go-pinyin"
  10. "strings"
  11. "time"
  12. "unicode"
  13. )
  14. // HandleFenweiIndex 处理汾渭数据的excel数据
  15. func HandleFenweiIndex(req *models.HandleFenweiExcelDataReq) (err error) {
  16. errMsgList := make([]string, 0)
  17. defer func() {
  18. if len(errMsgList) > 0 {
  19. msg := fmt.Sprint("数据源-汾渭数据数据处理失败, err:", strings.Join(errMsgList, "\n"))
  20. utils.FileLog.Info(msg)
  21. go alarm_msg.SendAlarmMsg(msg, 3)
  22. }
  23. }()
  24. for _, v := range req.List {
  25. if v.IndexName == "" || v.IndexCode == "" {
  26. errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常,指标编码%s或者指标ID%s为空:", v.IndexCode, v.IndexName))
  27. continue
  28. }
  29. err = handleFenweiIndex(v, req.TerminalCode)
  30. if err != nil {
  31. errMsgList = append(errMsgList, fmt.Sprintf("新增指标异常,指标编码:%s, Err: %s", v.IndexCode, err))
  32. return
  33. }
  34. }
  35. return
  36. }
  37. func handleFenweiIndex(req *models.HandleFenweiExcelData, terminalCode string) (err error) {
  38. indexName := req.IndexName
  39. indexCode := req.IndexCode
  40. excelDataMap := req.ExcelDataMap
  41. errMsgList := make([]string, 0)
  42. defer func() {
  43. if len(errMsgList) > 0 {
  44. msg := fmt.Sprint("数据源-汾渭数据数据处理失败,err:", strings.Join(errMsgList, "\n"))
  45. utils.FileLog.Info(msg)
  46. go alarm_msg.SendAlarmMsg(msg, 3)
  47. }
  48. }()
  49. indexObj := new(models.BaseFromFenweiIndex)
  50. dataObj := new(models.BaseFromFenweiData)
  51. //classifyObj := new(models.BaseFromFenweiClassify)
  52. var indexId int64
  53. addDataList := make([]*models.BaseFromFenweiData, 0)
  54. updateDataList := make([]*models.BaseFromFenweiData, 0)
  55. exitDataMap := make(map[string]*models.BaseFromFenweiData)
  56. // 修改指标信息
  57. if indexName == "" {
  58. utils.FileLog.Info("未刷新到指标数据:indexName:" + indexName)
  59. return
  60. }
  61. // 判断目录是否存在
  62. //var classifyId int64
  63. //now := time.Now()
  64. //if req.ClassifyName != "" {
  65. // classifyObj, err = classifyObj.GetByClassifyName(req.ClassifyName)
  66. // if err != nil {
  67. // if err.Error() == utils.ErrNoRow() {
  68. // //新增分类
  69. // classifyObj = &models.BaseFromFenweiClassify{
  70. // ClassifyName: req.ClassifyName,
  71. // ParentId: 0,
  72. // SysUserId: 0,
  73. // SysUserRealName: "",
  74. // Level: 1,
  75. // Sort: req.ClassifySort,
  76. // ModifyTime: now,
  77. // CreateTime: now,
  78. // }
  79. //
  80. // classifyId, err = classifyObj.Add()
  81. // if err != nil {
  82. // err = fmt.Errorf("新增分类失败 Err:%s", err)
  83. // return
  84. // }
  85. // classifyObj.ClassifyId = classifyId
  86. // } else {
  87. // return
  88. // }
  89. // } else {
  90. // classifyId = classifyObj.ClassifyId
  91. // }
  92. //}
  93. //判断指标是否存在
  94. var isAdd int
  95. item, err := indexObj.GetByIndexCode(indexCode)
  96. if err != nil {
  97. if err.Error() == utils.ErrNoRow() {
  98. isAdd = 1
  99. err = nil
  100. } else {
  101. isAdd = -1
  102. err = fmt.Errorf("查询数据源指标库失败 GetByIndexCode Err:%s", err)
  103. return
  104. }
  105. }
  106. if item != nil && item.FenweiIndexId > 0 {
  107. fmt.Println("item:", item)
  108. isAdd = 2
  109. } else {
  110. isAdd = 1
  111. }
  112. if isAdd == 1 {
  113. indexObj.IndexCode = indexCode
  114. indexObj.IndexName = indexName
  115. indexObj.Frequency = req.Frequency
  116. indexObj.ClassifyId = req.ClassifyId
  117. indexObj.Unit = req.Unit
  118. indexObj.Sort = req.Sort
  119. indexObj.ModifyTime = time.Now()
  120. indexObj.CreateTime = time.Now()
  121. indexObj.TerminalCode = terminalCode
  122. indexId, err = indexObj.Add()
  123. if err != nil {
  124. err = fmt.Errorf("数据源新增涌溢指标失败 Err:%s", err)
  125. return
  126. }
  127. indexObj.FenweiIndexId = indexId
  128. } else if isAdd == 2 {
  129. if item.TerminalCode == `` && terminalCode != `` {
  130. item.TerminalCode = terminalCode
  131. err = item.Update([]string{"TerminalCode"})
  132. if err != nil {
  133. err = fmt.Errorf("数据源更新涌溢指标失败 Err:%s", err)
  134. return
  135. }
  136. }
  137. //获取已存在的所有数据
  138. var exitDataList []*models.BaseFromFenweiData
  139. exitDataList, err = dataObj.GetByIndexCode(indexCode)
  140. if err != nil {
  141. err = fmt.Errorf("数据源查询涌溢指标数据失败 Err:%s", err)
  142. return
  143. }
  144. fmt.Println("exitDataListLen:", len(exitDataList))
  145. for _, v := range exitDataList {
  146. dateStr := v.DataTime
  147. exitDataMap[dateStr] = v
  148. }
  149. indexId = item.FenweiIndexId
  150. }
  151. // 遍历excel数据,然后跟现有的数据做校验,不存在则入库
  152. for date, value := range excelDataMap {
  153. if findData, ok := exitDataMap[date]; !ok {
  154. _, err = time.ParseInLocation(utils.FormatDate, date, time.Local)
  155. if err != nil {
  156. err = fmt.Errorf("%s 转换日期格式失败 Err:%s", date, err)
  157. return
  158. }
  159. if !strings.Contains(value, "#N/A") {
  160. var saveDataTime time.Time
  161. if strings.Contains(date, "00:00:00") {
  162. saveDataTime, err = time.Parse(utils.FormatDateTime, date)
  163. } else {
  164. saveDataTime, err = time.Parse(utils.FormatDate, date)
  165. }
  166. if err != nil {
  167. err = fmt.Errorf("%s 转换日期格式失败 Err:%s", date, err)
  168. continue
  169. }
  170. timestamp := saveDataTime.UnixNano() / 1e6
  171. dataItem := new(models.BaseFromFenweiData)
  172. dataItem.FenweiIndexId = int(indexId)
  173. dataItem.IndexCode = indexCode
  174. dataItem.DataTime = date
  175. dataItem.Value = value
  176. dataItem.CreateTime = time.Now()
  177. dataItem.ModifyTime = time.Now()
  178. dataItem.DataTimestamp = timestamp
  179. addDataList = append(addDataList, dataItem)
  180. }
  181. } else {
  182. if findData != nil && findData.Value != value && !strings.Contains(value, "#N/A") { //修改数据
  183. findData.Value = value
  184. findData.ModifyTime = time.Now().Local()
  185. updateDataList = append(updateDataList, findData)
  186. }
  187. }
  188. }
  189. if len(addDataList) > 0 {
  190. err = dataObj.AddMulti(addDataList)
  191. if err != nil {
  192. err = fmt.Errorf("批量新增指标失败 Err:%s", err)
  193. return
  194. }
  195. var dateItem *models.EdbInfoMaxAndMinInfo
  196. dateItem, err = dataObj.GetMaxAndMinDateByIndexCode(indexCode)
  197. if err != nil {
  198. err = fmt.Errorf("查询指标最新日期失败 Err:%s", err)
  199. return
  200. }
  201. go func() {
  202. indexObj.ModifyIndexMaxAndMinDate(indexCode, dateItem)
  203. }()
  204. }
  205. // 批量更新数据
  206. if len(updateDataList) > 0 {
  207. e := models.MultiUpdateBaseFromFenweiDataValue(updateDataList)
  208. if e != nil {
  209. err = fmt.Errorf("MultiUpdateBaseFromSmmDataValue err: %s", e.Error())
  210. return
  211. }
  212. }
  213. // 同步刷新ETA指标库的指标
  214. {
  215. // 获取指标详情
  216. baseObj := new(models.BaseFromFenwei)
  217. var edbInfo *models.EdbInfo
  218. edbInfo, err = models.GetEdbInfoByEdbCode(baseObj.GetSource(), indexCode)
  219. if err != nil {
  220. if err.Error() != utils.ErrNoRow() {
  221. errMsgList = append(errMsgList, fmt.Sprint("刷新ETA指标异常,指标编码:", indexCode, err.Error()))
  222. return
  223. } else {
  224. err = nil
  225. }
  226. }
  227. // 已经加入到指标库的话,那么就去更新ETA指标库吧
  228. if edbInfo != nil {
  229. go logic.RefreshBaseEdbInfo(edbInfo, ``)
  230. }
  231. }
  232. return
  233. }
  234. func NetDataHandle(req models.HandleFenWeiNetDataReq) error {
  235. indexInfoList := req.List
  236. classifyObj := new(models.BaseFromFenweiClassify)
  237. // 因为传递过来得List是 指标数据 维度得,获取全量得指标数据比对,会导致分类和指标 频繁查询,会频繁访问数据库,做个简单优化吧
  238. classifyMap := make(map[string]models.FenWeiNetIndexInfo)
  239. indexMap := make(map[string]models.FenWeiNetIndexInfo)
  240. for _, indexInfo := range indexInfoList {
  241. classifyMap[indexInfo.ClassifyName] = *indexInfo
  242. indexMap[indexInfo.IndexName] = *indexInfo
  243. }
  244. // 处理分类信息
  245. classifyIdMap := make(map[string]int)
  246. for classifyName, reqData := range classifyMap {
  247. var classifyId int
  248. classify, err := classifyObj.GetByClassifyName(classifyName)
  249. if err != nil {
  250. return err
  251. }
  252. if classify == nil {
  253. logs.Info("NetDataHandle addClassify classifyName: ", classifyName)
  254. classifyId, err = addFenWeiClassify(&reqData)
  255. if err != nil {
  256. return err
  257. }
  258. } else {
  259. classifyId = classify[0].ClassifyId
  260. }
  261. // 保存分类ID
  262. classifyIdMap[classifyName] = classifyId
  263. }
  264. // 处理指标信息
  265. indexIdMap := make(map[string]int64)
  266. indexCodeMap := make(map[string]string)
  267. for indexName, reqData := range indexMap {
  268. indexCode := GenerateIndexCode(indexName)
  269. indexCodeMap[indexName] = indexCode
  270. index, err := models.GetBaseFromFenWeiIndexByIndexName(indexName)
  271. if err != nil {
  272. return err
  273. }
  274. if index == nil {
  275. logs.Info("NetDataHandle indexName: ", indexName)
  276. classifyId := classifyIdMap[reqData.ClassifyName]
  277. logs.Info("NetDataHandle addIndex indexName: ", indexName)
  278. indexId, err := addIndex(&reqData, classifyId, indexCode)
  279. if err != nil {
  280. return err
  281. }
  282. indexIdMap[reqData.IndexName] = indexId
  283. } else {
  284. logs.Info("NetDataHandle exist indexName: ", indexName)
  285. indexIdMap[reqData.IndexName] = index.FenweiIndexId
  286. }
  287. }
  288. indexDataList := make([]*models.BaseFromFenweiData, 0)
  289. for _, indexInfo := range indexInfoList {
  290. // 处理指标数据
  291. indexData, err := handleIndexData(indexInfo, indexIdMap, indexCodeMap)
  292. if err != nil {
  293. return err
  294. }
  295. if indexData != nil {
  296. indexDataList = append(indexDataList, indexData)
  297. }
  298. }
  299. // 批量插入指标数据
  300. logs.Info("NetDataHandle addIndexData indexDataList.size: ", len(indexDataList))
  301. if len(indexDataList) == 0 {
  302. return nil
  303. }
  304. err := models.BatchAddBaseFromFenWeiData(indexDataList)
  305. if err != nil {
  306. return err
  307. }
  308. logs.Info("NetDataHandle addIndexData success")
  309. return nil
  310. }
  311. func handleIndexData(indexInfo *models.FenWeiNetIndexInfo, indexIdMap map[string]int64, indexCodeMap map[string]string) (*models.BaseFromFenweiData, error) {
  312. var format string
  313. if isYearMonth(indexInfo.DataTime) {
  314. format = convertYearMonthToLastDay(indexInfo.DataTime)
  315. } else if indexInfo.Frequency == "月度" && isFirstDayOfMonth(indexInfo.DataTime) {
  316. format = convertYearMonthDayToLastDay(indexInfo.DataTime)
  317. } else {
  318. format = indexInfo.DataTime
  319. }
  320. // 获取指标数据
  321. indexCode := indexCodeMap[indexInfo.IndexName]
  322. indexData, err := models.GetBaseFromFenweiDataByIndexCodeAndDataTime(indexCode, format)
  323. if err != nil {
  324. return nil, err
  325. }
  326. if indexData != nil {
  327. // 汾渭不存在数据更新和预测值情况,所以此处未做更新逻辑
  328. return nil, nil
  329. }
  330. timestamp := time.Now().UnixNano() / 1e6
  331. indexId := indexIdMap[indexInfo.IndexName]
  332. data := new(models.BaseFromFenweiData)
  333. data.FenweiIndexId = int(indexId)
  334. data.IndexCode = indexCode
  335. data.DataTime = format
  336. data.Value = fmt.Sprintf("%v", indexInfo.Value)
  337. data.CreateTime = time.Now()
  338. data.ModifyTime = time.Now()
  339. data.DataTimestamp = timestamp
  340. // 打印data对象日志
  341. logs.Info("handleIndexData data : ", data)
  342. return data, nil
  343. }
  344. func addIndex(info *models.FenWeiNetIndexInfo, classifyId int, indexCode string) (indexId int64, err error) {
  345. byIndexCode, err := models.GetBaseFromFenWeiIndexByIndexCode(indexCode)
  346. if err != nil {
  347. return 0, err
  348. }
  349. if byIndexCode != nil {
  350. return byIndexCode.FenweiIndexId, nil
  351. }
  352. index := new(models.BaseFromFenweiIndex)
  353. index.IndexName = info.IndexName
  354. index.IndexCode = indexCode
  355. index.IndexCode = indexCode
  356. index.Frequency = info.Frequency
  357. index.ClassifyId = classifyId
  358. index.Unit = info.Unit
  359. index.ModifyTime = time.Now()
  360. index.CreateTime = time.Now()
  361. index.TerminalCode = info.TerminalCode
  362. indexId, err = index.Add()
  363. if err != nil {
  364. return 0, err
  365. }
  366. return indexId, nil
  367. }
  368. // addFenWeiClassify 添加分类
  369. func addFenWeiClassify(info *models.FenWeiNetIndexInfo) (int, error) {
  370. // 初始化分类结构
  371. classify := new(models.BaseFromFenweiClassify)
  372. classify.ClassifyName = info.ClassifyName
  373. // 递归处理分类层级
  374. return handleClassify(classify, 0, 1)
  375. }
  376. func handleClassify(classify *models.BaseFromFenweiClassify, parentId int, level int) (int, error) {
  377. // 将分类名按 "-" 分割
  378. classifyArr := strings.Split(classify.ClassifyName, "-")
  379. // 当前分类名称
  380. currentClassifyName := classifyArr[0]
  381. classify.ClassifyName = currentClassifyName
  382. classify.ParentId = parentId
  383. classify.Level = level
  384. // 检查当前分类是否已存在
  385. existingClassifyList, err := classify.GetByClassifyName(currentClassifyName)
  386. if err != nil {
  387. return 0, err
  388. }
  389. var existingClassify *models.BaseFromFenweiClassify
  390. for _, item := range existingClassifyList {
  391. if item.ParentId == parentId {
  392. existingClassify = item
  393. }
  394. }
  395. // 如果分类存在,且父级ID相同,则递归处理下一级
  396. if existingClassify != nil && existingClassify != nil {
  397. // 如果存在且有下一级,则递归处理下一级
  398. if len(classifyArr) > 1 {
  399. nextClassifyName := strings.Join(classifyArr[1:], "-")
  400. nextClassify := new(models.BaseFromFenweiClassify)
  401. nextClassify.ClassifyName = nextClassifyName
  402. return handleClassify(nextClassify, existingClassify.ClassifyId, existingClassify.Level+1)
  403. }
  404. return existingClassify.ClassifyId, nil
  405. }
  406. // 如果不存在,新增当前分类
  407. classify.SysUserId = 0
  408. classify.SysUserRealName = ""
  409. classify.ModifyTime = time.Now()
  410. classify.CreateTime = time.Now()
  411. classifyId, err := models.AddBaseFromFenWeiClassify(classify)
  412. if err != nil {
  413. return 0, err
  414. }
  415. // 如果有下一级,递归处理下一级
  416. if len(classifyArr) > 1 {
  417. nextClassifyName := strings.Join(classifyArr[1:], "-")
  418. nextClassify := new(models.BaseFromFenweiClassify)
  419. nextClassify.ClassifyName = nextClassifyName
  420. return handleClassify(nextClassify, int(classifyId), level+1)
  421. }
  422. return int(classifyId), nil
  423. }
  424. // 判断传入参数 dataText 是否是yyyy-MM格式,如果是则返回true,否则返回false
  425. func isYearMonth(dataText string) bool {
  426. _, err := time.Parse("2006-01", dataText)
  427. if err != nil {
  428. return false
  429. }
  430. return true
  431. }
  432. // 判断传入参数 dataText yyyy-MM-dd格式,是否是该月第一天,如果是则返回true,否则返回false
  433. func isFirstDayOfMonth(dataText string) bool {
  434. t, _ := time.Parse("2006-01-02", dataText)
  435. if t.Day() == 1 {
  436. return true
  437. }
  438. return false
  439. }
  440. // 转换时间 dataText yyyy-MM-dd格式,获取该月最后一天的日期
  441. func convertYearMonthDayToLastDay(dataText string) string {
  442. t, _ := time.Parse("2006-01-02", dataText)
  443. lastDay := t.AddDate(0, 1, -1)
  444. return lastDay.Format("2006-01-02")
  445. }
  446. // 转换时间 dataText 2024-08 yyyy-MM 格式的时间字符串转换为该月最后一天的日期Date --> 2024-08-31
  447. func convertYearMonthToLastDay(dataText string) string {
  448. t, _ := time.Parse("2006-01", dataText)
  449. lastDay := t.AddDate(0, 1, -1)
  450. return lastDay.Format("2006-01-02")
  451. }
  452. // GenerateIndexCode 指标编码规则:指标名称拼音首字母,数字、字母保留,特殊字符拿掉
  453. // 例:美湾:9月U:国际大豆进口成本价:期货收盘:张家港 -----> lyswwmw9yUgjddjkcbjqhspzjg
  454. func GenerateIndexCode(indexName string) string {
  455. // 获取汉字的拼音首字母,保留数字和大写字母
  456. indexCode := getFirstLetters(indexName)
  457. return indexCode
  458. }
  459. // getFirstLetters 获取汉字的拼音首字母,并保留数字和大写字母
  460. func getFirstLetters(input string) string {
  461. // 设置拼音转换选项,只获取首字母
  462. args := pinyin.NewArgs()
  463. args.Style = pinyin.FirstLetter
  464. // 定义用于存储结果的字符串
  465. var result strings.Builder
  466. // 遍历输入字符串中的每个字符
  467. for _, r := range input {
  468. if unicode.IsDigit(r) || unicode.IsUpper(r) {
  469. // 保留数字和大写字母
  470. result.WriteRune(r)
  471. } else if unicode.Is(unicode.Han, r) {
  472. // 如果是汉字,则获取其拼音首字母
  473. py := pinyin.Pinyin(string(r), args)
  474. if len(py) > 0 && len(py[0]) > 0 {
  475. result.WriteString(py[0][0])
  476. }
  477. }
  478. // 对于其他字符,忽略处理
  479. }
  480. return result.String()
  481. }