predict_edb_data_calculate_kszs.go 13 KB

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