base_from_fenwei.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. if indexData.Value != fmt.Sprintf("%v", indexInfo.Value) {
  329. indexData.Value = fmt.Sprintf("%v", indexInfo.Value)
  330. indexData.ModifyTime = time.Now()
  331. logs.Info("handleIndexData update indexData : ", indexData)
  332. err = models.UpdateBaseFromFenweiData(indexData)
  333. if err != nil {
  334. return nil, err
  335. }
  336. }
  337. return nil, nil
  338. }
  339. timestamp := time.Now().UnixNano() / 1e6
  340. indexId := indexIdMap[indexInfo.IndexName]
  341. data := new(models.BaseFromFenweiData)
  342. data.FenweiIndexId = int(indexId)
  343. data.IndexCode = indexCode
  344. data.DataTime = format
  345. data.Value = fmt.Sprintf("%v", indexInfo.Value)
  346. data.CreateTime = time.Now()
  347. data.ModifyTime = time.Now()
  348. data.DataTimestamp = timestamp
  349. // 打印data对象日志
  350. logs.Info("handleIndexData data : ", data)
  351. return data, nil
  352. }
  353. func addIndex(info *models.FenWeiNetIndexInfo, classifyId int, indexCode string) (indexId int64, err error) {
  354. byIndexCode, err := models.GetBaseFromFenWeiIndexByIndexCode(indexCode)
  355. if err != nil {
  356. return 0, err
  357. }
  358. if byIndexCode != nil {
  359. return byIndexCode.FenweiIndexId, nil
  360. }
  361. index := new(models.BaseFromFenweiIndex)
  362. index.IndexName = info.IndexName
  363. index.IndexCode = indexCode
  364. index.IndexCode = indexCode
  365. index.Frequency = info.Frequency
  366. index.ClassifyId = classifyId
  367. index.Unit = info.Unit
  368. index.ModifyTime = time.Now()
  369. index.CreateTime = time.Now()
  370. index.TerminalCode = info.TerminalCode
  371. indexId, err = index.Add()
  372. if err != nil {
  373. return 0, err
  374. }
  375. return indexId, nil
  376. }
  377. // addFenWeiClassify 添加分类
  378. func addFenWeiClassify(info *models.FenWeiNetIndexInfo) (int, error) {
  379. // 初始化分类结构
  380. classify := new(models.BaseFromFenweiClassify)
  381. classify.ClassifyName = info.ClassifyName
  382. // 递归处理分类层级
  383. return handleClassify(classify, 0, 1)
  384. }
  385. func handleClassify(classify *models.BaseFromFenweiClassify, parentId int, level int) (int, error) {
  386. // 将分类名按 "-" 分割
  387. classifyArr := strings.Split(classify.ClassifyName, "-")
  388. // 当前分类名称
  389. currentClassifyName := classifyArr[0]
  390. classify.ClassifyName = currentClassifyName
  391. classify.ParentId = parentId
  392. classify.Level = level
  393. // 检查当前分类是否已存在
  394. existingClassifyList, err := classify.GetByClassifyName(currentClassifyName)
  395. if err != nil {
  396. return 0, err
  397. }
  398. var existingClassify *models.BaseFromFenweiClassify
  399. for _, item := range existingClassifyList {
  400. if item.ParentId == parentId {
  401. existingClassify = item
  402. }
  403. }
  404. // 如果分类存在,且父级ID相同,则递归处理下一级
  405. if existingClassify != nil && existingClassify != nil {
  406. // 如果存在且有下一级,则递归处理下一级
  407. if len(classifyArr) > 1 {
  408. nextClassifyName := strings.Join(classifyArr[1:], "-")
  409. nextClassify := new(models.BaseFromFenweiClassify)
  410. nextClassify.ClassifyName = nextClassifyName
  411. return handleClassify(nextClassify, existingClassify.ClassifyId, existingClassify.Level+1)
  412. }
  413. return existingClassify.ClassifyId, nil
  414. }
  415. // 如果不存在,新增当前分类
  416. classify.SysUserId = 0
  417. classify.SysUserRealName = ""
  418. classify.ModifyTime = time.Now()
  419. classify.CreateTime = time.Now()
  420. classifyId, err := models.AddBaseFromFenWeiClassify(classify)
  421. if err != nil {
  422. return 0, err
  423. }
  424. // 如果有下一级,递归处理下一级
  425. if len(classifyArr) > 1 {
  426. nextClassifyName := strings.Join(classifyArr[1:], "-")
  427. nextClassify := new(models.BaseFromFenweiClassify)
  428. nextClassify.ClassifyName = nextClassifyName
  429. return handleClassify(nextClassify, int(classifyId), level+1)
  430. }
  431. return int(classifyId), nil
  432. }
  433. // 判断传入参数 dataText 是否是yyyy-MM格式,如果是则返回true,否则返回false
  434. func isYearMonth(dataText string) bool {
  435. _, err := time.Parse("2006-01", dataText)
  436. if err != nil {
  437. return false
  438. }
  439. return true
  440. }
  441. // 判断传入参数 dataText yyyy-MM-dd格式,是否是该月第一天,如果是则返回true,否则返回false
  442. func isFirstDayOfMonth(dataText string) bool {
  443. t, _ := time.Parse("2006-01-02", dataText)
  444. if t.Day() == 1 {
  445. return true
  446. }
  447. return false
  448. }
  449. // 转换时间 dataText yyyy-MM-dd格式,获取该月最后一天的日期
  450. func convertYearMonthDayToLastDay(dataText string) string {
  451. t, _ := time.Parse("2006-01-02", dataText)
  452. lastDay := t.AddDate(0, 1, -1)
  453. return lastDay.Format("2006-01-02")
  454. }
  455. // 转换时间 dataText 2024-08 yyyy-MM 格式的时间字符串转换为该月最后一天的日期Date --> 2024-08-31
  456. func convertYearMonthToLastDay(dataText string) string {
  457. t, _ := time.Parse("2006-01", dataText)
  458. lastDay := t.AddDate(0, 1, -1)
  459. return lastDay.Format("2006-01-02")
  460. }
  461. // GenerateIndexCode 指标编码规则:指标名称拼音首字母,数字、字母保留,特殊字符拿掉
  462. // 例:美湾:9月U:国际大豆进口成本价:期货收盘:张家港 -----> lyswwmw9yUgjddjkcbjqhspzjg
  463. func GenerateIndexCode(indexName string) string {
  464. // 获取汉字的拼音首字母,保留数字和大写字母
  465. indexCode := getFirstLetters(indexName)
  466. return indexCode
  467. }
  468. // getFirstLetters 获取汉字的拼音首字母,并保留数字和大写字母
  469. func getFirstLetters(input string) string {
  470. // 设置拼音转换选项,只获取首字母
  471. args := pinyin.NewArgs()
  472. args.Style = pinyin.FirstLetter
  473. // 定义用于存储结果的字符串
  474. var result strings.Builder
  475. // 遍历输入字符串中的每个字符
  476. for _, r := range input {
  477. if unicode.IsDigit(r) || unicode.IsUpper(r) {
  478. // 保留数字和大写字母
  479. result.WriteRune(r)
  480. } else if unicode.Is(unicode.Han, r) {
  481. // 如果是汉字,则获取其拼音首字母
  482. py := pinyin.Pinyin(string(r), args)
  483. if len(py) > 0 && len(py[0]) > 0 {
  484. result.WriteString(py[0][0])
  485. }
  486. }
  487. // 对于其他字符,忽略处理
  488. }
  489. return result.String()
  490. }