predict_edb_data_calculate_qjjs.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. type PredictCalculateRangeAnalysis struct {
  14. }
  15. func (obj PredictCalculateRangeAnalysis) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  16. req := params.Req
  17. edbCode := params.EdbCode
  18. uniqueCode := params.UniqueCode
  19. sysUserId := params.SysUserId
  20. sysUserRealName := params.SysUserRealName
  21. //req *EdbInfoCalculateBatchSaveReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName string
  22. o := orm.NewOrm()
  23. to, err := o.Begin()
  24. if err != nil {
  25. return
  26. }
  27. defer func() {
  28. if err != nil {
  29. fmt.Println("AddCalculateRangeAnalysis,Err:" + err.Error())
  30. _ = to.Rollback()
  31. } else {
  32. _ = to.Commit()
  33. }
  34. }()
  35. if req.EdbInfoId > 0 {
  36. err = errors.New("无法新增")
  37. return
  38. }
  39. edbInfo = new(EdbInfo)
  40. edbInfo.Source = obj.GetSource()
  41. edbInfo.SourceName = obj.GetSourceName()
  42. edbInfo.EdbCode = edbCode
  43. edbInfo.EdbName = req.EdbName
  44. edbInfo.EdbNameSource = req.EdbName
  45. edbInfo.Frequency = req.Frequency
  46. edbInfo.Unit = req.Unit
  47. edbInfo.ClassifyId = req.ClassifyId
  48. edbInfo.SysUserId = sysUserId
  49. edbInfo.SysUserRealName = sysUserRealName
  50. edbInfo.CreateTime = time.Now()
  51. edbInfo.ModifyTime = time.Now()
  52. edbInfo.UniqueCode = uniqueCode
  53. edbInfo.CalculateFormula = req.CalculateFormula
  54. edbInfo.EdbNameEn = req.EdbName
  55. edbInfo.UnitEn = req.Unit
  56. edbInfo.EdbType = obj.GetEdbType()
  57. edbInfo.EdbInfoType = 1
  58. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  59. if tmpErr != nil {
  60. err = tmpErr
  61. return
  62. }
  63. edbInfo.EdbInfoId = int(newEdbInfoId)
  64. //关联关系
  65. fromEdbInfo, e := GetEdbInfoById(req.FromEdbInfoId)
  66. if e != nil {
  67. err = fmt.Errorf("获取来源指标失败,Err:%s", e.Error())
  68. return
  69. }
  70. calculateMappingItem := new(EdbInfoCalculateMapping)
  71. calculateMappingItem.CreateTime = time.Now()
  72. calculateMappingItem.ModifyTime = time.Now()
  73. calculateMappingItem.Sort = 1
  74. calculateMappingItem.EdbCode = edbCode
  75. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  76. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  77. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  78. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  79. calculateMappingItem.FromSource = fromEdbInfo.Source
  80. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  81. calculateMappingItem.FromTag = ""
  82. calculateMappingItem.Source = edbInfo.Source
  83. calculateMappingItem.SourceName = edbInfo.SourceName
  84. calculateMappingItem.FromSubSource = edbInfo.SubSource
  85. _, err = to.Insert(calculateMappingItem)
  86. if err != nil {
  87. return
  88. }
  89. //计算数据
  90. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.CalculateFormula)
  91. return
  92. }
  93. func (obj PredictCalculateRangeAnalysis) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  94. edbInfo := params.EdbInfo
  95. req := params.Req
  96. o := orm.NewOrm()
  97. to, err := o.Begin()
  98. if err != nil {
  99. return
  100. }
  101. defer func() {
  102. if err != nil {
  103. fmt.Println("EditCalculateRangeAnalysis,Err:" + err.Error())
  104. _ = to.Rollback()
  105. } else {
  106. _ = to.Commit()
  107. }
  108. }()
  109. //修改指标信息
  110. edbInfo.EdbName = req.EdbName
  111. edbInfo.EdbNameSource = req.EdbName
  112. edbInfo.Frequency = req.Frequency
  113. edbInfo.Unit = req.Unit
  114. edbInfo.ClassifyId = req.ClassifyId
  115. edbInfo.CalculateFormula = req.CalculateFormula
  116. //修改指标信息
  117. switch params.Lang {
  118. case utils.EnLangVersion:
  119. edbInfo.EdbNameEn = req.EdbName
  120. edbInfo.UnitEn = req.Unit
  121. default:
  122. edbInfo.EdbName = req.EdbName
  123. edbInfo.Unit = req.Unit
  124. edbInfo.EdbNameSource = req.EdbName
  125. }
  126. edbInfo.ModifyTime = time.Now()
  127. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  128. if err != nil {
  129. return
  130. }
  131. //删除,计算指标关联的,基础指标的关联关系
  132. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  133. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  134. if err != nil {
  135. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  136. return
  137. }
  138. //清空原有数据
  139. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  140. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  141. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  142. if err != nil {
  143. return
  144. }
  145. fromEdbInfo, e := GetEdbInfoById(req.FromEdbInfoId)
  146. if e != nil {
  147. err = fmt.Errorf("获取来源指标失败,Err:%s", e.Error())
  148. return
  149. }
  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 = fromEdbInfo.EdbInfoId
  157. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  158. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  159. calculateMappingItem.FromSource = fromEdbInfo.Source
  160. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  161. calculateMappingItem.FromTag = ""
  162. calculateMappingItem.Source = edbInfo.Source
  163. calculateMappingItem.SourceName = edbInfo.SourceName
  164. calculateMappingItem.FromSubSource = edbInfo.SubSource
  165. _, err = to.Insert(calculateMappingItem)
  166. if err != nil {
  167. return
  168. }
  169. //计算数据
  170. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.CalculateFormula)
  171. return
  172. }
  173. func (obj PredictCalculateRangeAnalysis) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  174. edbInfo := params.EdbInfo
  175. edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
  176. if err != nil {
  177. return
  178. }
  179. var fromEdbInfo *EdbInfo
  180. for _, v := range edbInfoCalculateDetailList {
  181. fromEdbInfo, _ = GetEdbInfoById(v.FromEdbInfoId)
  182. break
  183. }
  184. if fromEdbInfo == nil {
  185. errMsg = "指标异常"
  186. err = errors.New(errMsg)
  187. return
  188. }
  189. o := orm.NewOrm()
  190. to, err := o.Begin()
  191. if err != nil {
  192. return
  193. }
  194. defer func() {
  195. if err != nil {
  196. fmt.Println("RefreshAllCalculateRangeAnalysis,Err:" + err.Error())
  197. _ = to.Rollback()
  198. } else {
  199. _ = to.Commit()
  200. }
  201. }()
  202. // 计算数据
  203. latestDateStr, latestValue, err, errMsg = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.CalculateFormula)
  204. return
  205. }
  206. func (obj PredictCalculateRangeAnalysis) refresh(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, calculateFormula string) (latestDateStr string, latestValue float64, err error, errMsg string) {
  207. edbInfoIdStr := strconv.Itoa(edbInfoId)
  208. tableName := GetEdbDataTableName(obj.GetSource(), utils.DATA_SUB_SOURCE_EDB)
  209. //获取扩散指数指标所有数据
  210. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  211. if err != nil {
  212. return
  213. }
  214. latestDateStr = fromEdbInfo.LatestDate
  215. //计算指标的map
  216. existDataMap := make(map[string]*EdbData, 0)
  217. removeDateMap := make(map[string]string)
  218. for _, v := range existDataList {
  219. existDataMap[v.DataTime] = v
  220. removeDateMap[v.DataTime] = ``
  221. }
  222. var rangeAnalysisConf RangeAnalysisCalculateFormula
  223. //fmt.Println("calculateFormula:", calculateFormula)
  224. err = json.Unmarshal([]byte(calculateFormula), &rangeAnalysisConf)
  225. if err != nil {
  226. err = fmt.Errorf("解析区间计算公式失败 %s", err.Error())
  227. return
  228. }
  229. rangeAnalysisChartData, err := GetRangeAnalysisChartDataByEdbInfo(fromEdbInfo, rangeAnalysisConf)
  230. if err != nil {
  231. err = fmt.Errorf("获取区间计算数据失败 %s", err.Error())
  232. return
  233. }
  234. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  235. var isAdd bool
  236. for _, item := range rangeAnalysisChartData {
  237. currDateStr := item.DataTime
  238. currVal := item.Value
  239. // 判断扩散指数指标是否存在数据
  240. if existData, ok := existDataMap[currDateStr]; ok {
  241. // 处理扩散指数数据的值
  242. existValStr := existData.Value
  243. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  244. if tmpErr != nil {
  245. err = tmpErr
  246. return
  247. }
  248. existVal, _ := existValDeci.Round(4).Float64()
  249. // 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  250. if existVal != currVal {
  251. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  252. if err != nil {
  253. return
  254. }
  255. }
  256. } else {
  257. // 直接入库
  258. timestamp := item.DataTimestamp
  259. timestampStr := fmt.Sprintf("%d", timestamp)
  260. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  261. isAdd = true
  262. }
  263. delete(removeDateMap, currDateStr)
  264. }
  265. // 数据入库
  266. {
  267. if isAdd {
  268. addSql = strings.TrimRight(addSql, ",")
  269. _, err = to.Raw(addSql).Exec()
  270. }
  271. // 移除不存在的日期数据
  272. if len(removeDateMap) > 0 {
  273. removeDateList := make([]string, 0) //需要移除的日期
  274. for k := range removeDateMap {
  275. removeDateList = append(removeDateList, k)
  276. }
  277. removeDateStr := strings.Join(removeDateList, `","`)
  278. removeDateStr = `"` + removeDateStr + `"`
  279. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  280. _, err = to.Raw(sql, edbInfoId).Exec()
  281. if err != nil {
  282. err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
  283. return
  284. }
  285. }
  286. }
  287. //确定实际数据的最终值
  288. {
  289. finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, obj.GetSource(), utils.DATA_SUB_SOURCE_EDB, fromEdbInfo.LatestDate)
  290. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  291. return
  292. }
  293. if tmpErr == nil {
  294. latestDateStr = finalLast.DataTime
  295. latestValue = finalLast.Value
  296. }
  297. }
  298. return
  299. }
  300. // GetSource 获取来源编码id
  301. func (obj PredictCalculateRangeAnalysis) GetSource() int {
  302. return utils.DATA_SOURCE_PREDICT_CALCULATE_RANGEANLYSIS
  303. }
  304. // GetSourceName 获取来源名称
  305. func (obj PredictCalculateRangeAnalysis) GetSourceName() string {
  306. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_RANGEANLYSIS
  307. }
  308. // GetEdbType 获取指标类型
  309. func (obj PredictCalculateRangeAnalysis) GetEdbType() int {
  310. return utils.CALCULATE_EDB_TYPE
  311. }