predict_edb_data_calculate_kszs.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_index_lib/global"
  6. "eta_gn/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/shopspring/decimal"
  9. "gorm.io/gorm"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // SavePredictCalculateKszs 预测扩散指数
  15. func SavePredictCalculateKszs(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, relationCalculateEdbInfoIdList []EdbInfoCalculateEdbInfoIdReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  16. to := global.DEFAULT_DmSQL.Begin()
  17. defer func() {
  18. if err != nil {
  19. to.Rollback()
  20. } else {
  21. to.Commit()
  22. }
  23. }()
  24. fmt.Println("reqEdbInfoId:", reqEdbInfoId)
  25. tagMap := make(map[string]int) //指标的标签map
  26. relationEdbInfoList := make([]*EdbInfo, 0)
  27. if reqEdbInfoId <= 0 {
  28. edbInfo = &EdbInfo{
  29. //EdbInfoId: 0,
  30. EdbInfoType: 1,
  31. SourceName: utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_KSZS,
  32. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_KSZS,
  33. EdbCode: edbCode,
  34. EdbName: edbName,
  35. EdbNameSource: edbName,
  36. Frequency: frequency,
  37. Unit: unit,
  38. //StartDate: "",
  39. //EndDate: "",
  40. ClassifyId: classifyId,
  41. SysUserId: sysUserId,
  42. SysUserRealName: sysUserRealName,
  43. UniqueCode: uniqueCode,
  44. CreateTime: time.Now(),
  45. ModifyTime: time.Now(),
  46. MinValue: 0,
  47. MaxValue: 0,
  48. CalculateFormula: formula,
  49. EdbType: 2,
  50. Sort: GetAddEdbMaxSortByClassifyId(classifyId, utils.PREDICT_EDB_INFO_TYPE),
  51. MoveType: 0,
  52. MoveFrequency: "",
  53. NoUpdate: 0,
  54. ServerUrl: "",
  55. EdbNameEn: edbName,
  56. UnitEn: unit,
  57. LatestDate: "",
  58. LatestValue: 0,
  59. ChartImage: "",
  60. }
  61. tmpErr := to.Create(edbInfo).Error
  62. if tmpErr != nil {
  63. err = tmpErr
  64. return
  65. }
  66. //关联关系
  67. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  68. for _, v := range relationCalculateEdbInfoIdList {
  69. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  70. if tmpErr != nil {
  71. err = tmpErr
  72. return
  73. }
  74. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  75. calculateMappingItem := new(EdbInfoCalculateMapping)
  76. calculateMappingItem.CreateTime = time.Now()
  77. calculateMappingItem.ModifyTime = time.Now()
  78. calculateMappingItem.Sort = 1
  79. calculateMappingItem.EdbCode = edbCode
  80. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  81. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  82. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  83. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  84. calculateMappingItem.FromSource = tmpEdbInfo.Source
  85. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  86. calculateMappingItem.FromTag = v.FromTag
  87. calculateMappingItem.Source = edbInfo.Source
  88. calculateMappingItem.SourceName = edbInfo.SourceName
  89. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  90. tagMap[v.FromTag] = v.EdbInfoId
  91. }
  92. err = to.CreateInBatches(calculateMappingItemList, 500).Error
  93. if err != nil {
  94. return
  95. }
  96. } else {
  97. edbInfo, err = GetEdbInfoById(reqEdbInfoId)
  98. if err != nil {
  99. if err.Error() == utils.ErrNoRow() {
  100. errMsg = `获取指标信息失败`
  101. }
  102. return
  103. }
  104. if edbInfo.EdbInfoType != 1 {
  105. errMsg = `该指标不是预测指标`
  106. err = errors.New(errMsg)
  107. return
  108. }
  109. //修改指标信息
  110. switch lang {
  111. case utils.EnLangVersion:
  112. edbInfo.EdbNameEn = edbName
  113. edbInfo.UnitEn = unit
  114. default:
  115. edbInfo.EdbName = edbName
  116. edbInfo.Unit = unit
  117. edbInfo.EdbNameSource = edbName
  118. }
  119. edbInfo.Frequency = frequency
  120. edbInfo.ClassifyId = classifyId
  121. edbInfo.CalculateFormula = formula
  122. edbInfo.ModifyTime = time.Now()
  123. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  124. if err != nil {
  125. return
  126. }
  127. //删除,计算指标关联的,基础指标的关联关系
  128. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  129. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  130. if err != nil {
  131. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  132. return
  133. }
  134. //清空原有数据
  135. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  136. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  137. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  138. if err != nil {
  139. return
  140. }
  141. //关联关系
  142. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  143. for _, v := range relationCalculateEdbInfoIdList {
  144. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  145. if tmpErr != nil {
  146. err = tmpErr
  147. return
  148. }
  149. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  150. calculateMappingItem := new(EdbInfoCalculateMapping)
  151. calculateMappingItem.CreateTime = time.Now()
  152. calculateMappingItem.ModifyTime = time.Now()
  153. calculateMappingItem.Sort = 1
  154. calculateMappingItem.EdbCode = edbInfo.EdbCode
  155. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  156. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  157. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  158. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  159. calculateMappingItem.FromSource = tmpEdbInfo.Source
  160. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  161. calculateMappingItem.FromTag = v.FromTag
  162. calculateMappingItem.Source = edbInfo.Source
  163. calculateMappingItem.SourceName = edbInfo.SourceName
  164. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  165. tagMap[v.FromTag] = v.EdbInfoId
  166. }
  167. err = to.CreateInBatches(calculateMappingItemList, 500).Error
  168. if err != nil {
  169. return
  170. }
  171. }
  172. // 计算数据
  173. latestDateStr, latestValue, err = refreshAllPredictCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbCode, formula, tagMap)
  174. return
  175. }
  176. // RefreshAllPredictCalculateKszs 刷新全部预测扩散指数数据
  177. func RefreshAllPredictCalculateKszs(edbInfo *EdbInfo) (latestDateStr string, latestValue float64, err error) {
  178. edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
  179. if err != nil {
  180. return
  181. }
  182. tagMap := make(map[string]int)
  183. relationEdbInfoList := make([]*EdbInfo, 0)
  184. for _, v := range edbInfoCalculateDetailList {
  185. tagMap[v.FromTag] = v.FromEdbInfoId
  186. fromEdbInfo, _ := GetEdbInfoById(v.FromEdbInfoId)
  187. relationEdbInfoList = append(relationEdbInfoList, fromEdbInfo)
  188. }
  189. to := global.DEFAULT_DmSQL.Begin()
  190. defer func() {
  191. if err != nil {
  192. to.Rollback()
  193. } else {
  194. to.Commit()
  195. }
  196. }()
  197. // 计算数据
  198. latestDateStr, latestValue, err = refreshAllPredictCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)
  199. return
  200. }
  201. // refreshAllPredictCalculateKszs 刷新预测年化数据
  202. func refreshAllPredictCalculateKszs(to *gorm.DB, edbInfoId, source, subSource int, relationEdbInfoList []*EdbInfo, edbCode, calculateFormula string, tagMap map[string]int) (latestDateStr string, latestValue float64, err error) {
  203. edbInfoIdStr := strconv.Itoa(edbInfoId)
  204. tableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_KSZS, subSource)
  205. // 获取扩散指标关联的指标id
  206. checkEdbInfoIdMap := make(map[int]int)
  207. {
  208. var config KszsConfig
  209. err = json.Unmarshal([]byte(calculateFormula), &config)
  210. if err != nil {
  211. return
  212. }
  213. if config.DateType == 1 {
  214. for _, tmpEdbInfoId := range tagMap {
  215. checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
  216. }
  217. } else {
  218. for _, v := range config.CheckList {
  219. if tmpEdbInfoId, ok := tagMap[v]; ok {
  220. checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
  221. }
  222. }
  223. }
  224. }
  225. //获取当前指标的所有数据
  226. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  227. if err != nil {
  228. return
  229. }
  230. //计算指标的map
  231. existDataMap := make(map[string]*EdbData, 0)
  232. removeDateMap := make(map[string]string)
  233. for _, v := range existDataList {
  234. existDataMap[v.DataTime] = v
  235. removeDateMap[v.DataTime] = ``
  236. }
  237. var latestDateTime time.Time //真实数据的最后日期
  238. var hasValLatestDateTime time.Time // 存在数据的真实日期(正常情况下,这两个值是相等的,除非出现一种情况:真实数据的最后日期当天 计算不出结果,那么 hasValLatestDateTime 不等于 latestDateTime)
  239. //获取来源指标的数据
  240. relationEdbDataMap := make(map[int]map[string]float64)
  241. // 获取选择指标的 需要数据的 开始日期和结束日期
  242. var startDate, endDate time.Time
  243. for _, v := range relationEdbInfoList {
  244. tmpLatestDate, _ := time.ParseInLocation(utils.FormatDate, v.LatestDate, time.Local)
  245. if latestDateTime.IsZero() || latestDateTime.After(tmpLatestDate) {
  246. // 真实数据的最后日期
  247. latestDateTime = tmpLatestDate
  248. }
  249. tmpDataList, tmpErr := GetPredictEdbDataListAll(v, 1)
  250. if tmpErr != nil {
  251. err = tmpErr
  252. return
  253. }
  254. if tmpDataList != nil {
  255. if _, ok2 := checkEdbInfoIdMap[v.EdbInfoId]; ok2 {
  256. lenTmpDataList := len(tmpDataList)
  257. if lenTmpDataList > 0 {
  258. tmpStartTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[0].DataTime, time.Local)
  259. tmpEndTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[lenTmpDataList-1].DataTime, time.Local)
  260. if startDate.IsZero() || tmpStartTime.Before(startDate) {
  261. startDate = tmpStartTime
  262. }
  263. if tmpEndTime.IsZero() || tmpEndTime.After(endDate) {
  264. endDate = tmpEndTime
  265. }
  266. }
  267. }
  268. // 用上期的数据补充当期的数据处理
  269. handleDataMap := make(map[string]float64)
  270. err = HandleDataByPreviousData(tmpDataList, handleDataMap)
  271. if err != nil {
  272. return
  273. }
  274. relationEdbDataMap[v.EdbInfoId] = handleDataMap
  275. }
  276. }
  277. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  278. var isAdd bool
  279. for currDate := startDate.AddDate(0, 0, 1); !currDate.After(endDate); currDate = currDate.AddDate(0, 0, 1) {
  280. currDateStr := currDate.Format(utils.FormatDate)
  281. //环差指数列表
  282. tmpValList := make([]float64, 0)
  283. for _, dataMap := range relationEdbDataMap {
  284. currVal, ok := dataMap[currDateStr]
  285. if !ok {
  286. continue
  287. }
  288. perVal, ok := dataMap[currDate.AddDate(0, 0, -1).Format(utils.FormatDate)]
  289. if !ok {
  290. continue
  291. }
  292. var tmpVal float64
  293. if currVal > perVal {
  294. tmpVal = 1
  295. } else if currVal == perVal {
  296. tmpVal = 0.5
  297. } else {
  298. tmpVal = 0
  299. }
  300. tmpValList = append(tmpValList, tmpVal)
  301. }
  302. lenTmpValList := len(tmpValList)
  303. if lenTmpValList <= 0 {
  304. continue
  305. }
  306. currValDeci := decimal.NewFromFloat(0)
  307. for _, tmpVal := range tmpValList {
  308. currValDeci = currValDeci.Add(decimal.NewFromFloat(tmpVal))
  309. }
  310. currVal, _ := currValDeci.Div(decimal.NewFromInt(int64(lenTmpValList))).Round(4).Float64()
  311. // 如果存在数据的真实日期为空,或者 当前日期 早于或等于 实际数据的日期,那么就给 存在数据的真实日期 赋值
  312. if hasValLatestDateTime.IsZero() || currDate.Before(latestDateTime) || currDate.Equal(latestDateTime) {
  313. latestValue = currVal
  314. hasValLatestDateTime = currDate
  315. }
  316. // 判断扩散指数指标是否存在数据
  317. if existData, ok := existDataMap[currDateStr]; ok {
  318. // 处理扩散指数数据的值
  319. existValStr := existData.Value
  320. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  321. if tmpErr != nil {
  322. err = tmpErr
  323. return
  324. }
  325. existVal, _ := existValDeci.Round(4).Float64()
  326. // 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  327. if existVal != currVal {
  328. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  329. if err != nil {
  330. return
  331. }
  332. }
  333. } else {
  334. // 直接入库
  335. timestamp := currDate.UnixNano() / 1e6
  336. timestampStr := fmt.Sprintf("%d", timestamp)
  337. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  338. isAdd = true
  339. }
  340. delete(removeDateMap, currDateStr)
  341. }
  342. if isAdd {
  343. addSql = strings.TrimRight(addSql, ",")
  344. err = to.Exec(addSql).Error
  345. }
  346. // 移除不存在的日期数据
  347. if len(removeDateMap) > 0 {
  348. removeDateList := make([]string, 0) //需要移除的日期
  349. for k := range removeDateMap {
  350. removeDateList = append(removeDateList, k)
  351. }
  352. removeDateStr := strings.Join(removeDateList, `','`)
  353. removeDateStr = `'` + removeDateStr + `'`
  354. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  355. err = to.Exec(sql, edbInfoId).Error
  356. if err != nil {
  357. err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
  358. return
  359. }
  360. }
  361. // 真实数据的最后日期
  362. latestDateStr = hasValLatestDateTime.Format(utils.FormatDate)
  363. return
  364. }