predict_edb_data_calculate_nszydbpjjs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // SavePredictCalculateNszydpjjs 新增/编辑 预测 N数值移动平均计算指标
  13. func SavePredictCalculateNszydpjjs(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("SavePredictCalculateNszydpjjs,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. var formulaInt int
  28. formulaInt, _ = strconv.Atoi(formula)
  29. if formulaInt <= 0 {
  30. err = errors.New("N值输入错误,请重新输入")
  31. return
  32. }
  33. if reqEdbInfoId <= 0 {
  34. edbInfo = &EdbInfo{
  35. //EdbInfoId: 0,
  36. EdbInfoType: 1,
  37. SourceName: "预测N数值移动平均计算",
  38. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS,
  39. EdbCode: edbCode,
  40. EdbName: edbName,
  41. EdbNameSource: edbName,
  42. Frequency: frequency,
  43. Unit: unit,
  44. //StartDate: "",
  45. //EndDate: "",
  46. ClassifyId: classifyId,
  47. SysUserId: sysUserId,
  48. SysUserRealName: sysUserRealName,
  49. UniqueCode: uniqueCode,
  50. CreateTime: time.Now(),
  51. ModifyTime: time.Now(),
  52. MinValue: 0,
  53. MaxValue: 0,
  54. CalculateFormula: formula,
  55. EdbType: 2,
  56. Sort: 0,
  57. MoveType: 0,
  58. MoveFrequency: "",
  59. NoUpdate: 0,
  60. ServerUrl: "",
  61. EdbNameEn: edbName,
  62. UnitEn: unit,
  63. LatestDate: "",
  64. LatestValue: 0,
  65. ChartImage: "",
  66. }
  67. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  68. if tmpErr != nil {
  69. err = tmpErr
  70. return
  71. }
  72. edbInfo.EdbInfoId = int(newEdbInfoId)
  73. // 添加关联关系
  74. {
  75. calculateMappingItem := &EdbInfoCalculateMapping{
  76. EdbInfoCalculateMappingId: 0,
  77. EdbInfoId: edbInfo.EdbInfoId,
  78. Source: edbInfo.Source,
  79. SourceName: edbInfo.SourceName,
  80. EdbCode: edbCode,
  81. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  82. FromEdbCode: fromEdbInfo.EdbCode,
  83. FromEdbName: fromEdbInfo.EdbName,
  84. FromSource: fromEdbInfo.Source,
  85. FromSourceName: fromEdbInfo.SourceName,
  86. FromTag: "",
  87. Sort: 1,
  88. CreateTime: time.Now(),
  89. ModifyTime: time.Now(),
  90. }
  91. _, err = to.Insert(calculateMappingItem)
  92. if err != nil {
  93. return
  94. }
  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. latestDateStr = edbInfo.LatestDate
  110. latestValue = edbInfo.LatestValue
  111. oldCalculateFormula := edbInfo.CalculateFormula //原先的n值
  112. switch lang {
  113. case utils.EnLangVersion:
  114. edbInfo.EdbNameEn = edbName
  115. edbInfo.UnitEn = unit
  116. default:
  117. edbInfo.EdbName = edbName
  118. edbInfo.Unit = unit
  119. edbInfo.EdbNameSource = edbName
  120. }
  121. edbInfo.Frequency = frequency
  122. edbInfo.ClassifyId = classifyId
  123. edbInfo.CalculateFormula = formula
  124. edbInfo.ModifyTime = time.Now()
  125. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  126. if err != nil {
  127. return
  128. }
  129. //判断计算指标是否被更换
  130. var existCondition string
  131. var existPars []interface{}
  132. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  133. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  134. latestDateStr = edbInfo.LatestDate
  135. latestValue = edbInfo.LatestValue
  136. count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  137. if tmpErr != nil {
  138. err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
  139. return
  140. }
  141. if count > 0 && oldCalculateFormula == formula { // 指标未被替换,同时N值未修改,无需重新计算
  142. return
  143. }
  144. if count <= 0 {
  145. // 需要删除原先的 计算指标关联的,基础指标的关联关系
  146. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  147. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  148. if err != nil {
  149. return
  150. }
  151. // 添加新的关联关系
  152. {
  153. calculateMappingItem := &EdbInfoCalculateMapping{
  154. EdbInfoCalculateMappingId: 0,
  155. EdbInfoId: edbInfo.EdbInfoId,
  156. Source: edbInfo.Source,
  157. SourceName: edbInfo.SourceName,
  158. EdbCode: edbInfo.EdbCode,
  159. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  160. FromEdbCode: fromEdbInfo.EdbCode,
  161. FromEdbName: fromEdbInfo.EdbName,
  162. FromSource: fromEdbInfo.Source,
  163. FromSourceName: fromEdbInfo.SourceName,
  164. FromTag: "",
  165. Sort: 1,
  166. CreateTime: time.Now(),
  167. ModifyTime: time.Now(),
  168. }
  169. _, err = to.Insert(calculateMappingItem)
  170. if err != nil {
  171. return
  172. }
  173. }
  174. }
  175. // 删除该指标所有的同比数据
  176. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS, utils.DATA_SUB_SOURCE_EDB)
  177. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  178. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  179. _, err = to.Raw(deleteSql, edbInfo.EdbInfoId).Exec()
  180. if err != nil {
  181. return
  182. }
  183. }
  184. latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
  185. return
  186. }
  187. // RefreshAllPredictCalculateNszydpjjs 刷新所有 N数值移动平均计算指标 数据
  188. func RefreshAllPredictCalculateNszydpjjs(edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  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("RefreshAllPredictCalculateNszydpjjs,Err:" + err.Error())
  197. _ = to.Rollback()
  198. } else {
  199. _ = to.Commit()
  200. }
  201. }()
  202. latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfoId, source, subSource, formulaInt, fromEdbInfo, edbCode, startDate)
  203. return
  204. }
  205. // refreshAllPredictCalculateNszydpjjs 更新全部N数值移动平均计算
  206. func refreshAllPredictCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  207. edbInfoIdStr := strconv.Itoa(edbInfoId)
  208. fmt.Println(edbInfoIdStr)
  209. fmt.Println("refreshAllCalculateNszydpjjs startDate:", startDate)
  210. // 获取关联指标数据
  211. existDataList := make([]*EdbData, 0)
  212. dataTableName := GetEdbDataTableName(source, subSource)
  213. fmt.Println("dataTableName:", dataTableName)
  214. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  215. sql = fmt.Sprintf(sql, dataTableName)
  216. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  217. existDataMap := make(map[string]*EdbData)
  218. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  219. for _, v := range existDataList {
  220. existDataMap[v.DataTime] = v
  221. removeDataTimeMap[v.DataTime] = 1
  222. }
  223. //计算来源数据
  224. var fromCondition string
  225. var fromPars []interface{}
  226. fromCondition += " AND edb_info_id=? "
  227. fromPars = append(fromPars, fromEdbInfo.EdbInfoId)
  228. if startDate != `` {
  229. fromCondition += " AND data_time>=? "
  230. fromPars = append(fromPars, startDate)
  231. }
  232. //fmt.Println("fromPars:", fromPars)
  233. fromDataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, startDate)
  234. if err != nil {
  235. return
  236. }
  237. latestDateStr = fromEdbInfo.LatestDate
  238. var fromDateArr []string
  239. fromDataMap := make(map[string]*EdbInfoSearchData)
  240. for _, v := range fromDataList {
  241. fromDateArr = append(fromDateArr, v.DataTime)
  242. fromDataMap[v.DataTime] = v
  243. }
  244. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  245. var isAdd bool
  246. arrLen := len(fromDateArr)
  247. existAddDataMap := make(map[string]string)
  248. for ak, av := range fromDateArr {
  249. //处理第一个值
  250. var valArr []float64
  251. if findItem, ok := fromDataMap[av]; ok {
  252. valArr = append(valArr, findItem.Value)
  253. } else {
  254. continue
  255. }
  256. if ak+1 != arrLen {
  257. //处理除第一个值之外的N-1个值
  258. for i := 1; i < formulaInt; i++ {
  259. arrIndex := ak + i
  260. if arrIndex >= arrLen {
  261. break
  262. }
  263. arrVal := fromDateArr[arrIndex]
  264. if findItem, ok := fromDataMap[arrVal]; ok {
  265. valArr = append(valArr, findItem.Value)
  266. } else {
  267. continue
  268. }
  269. }
  270. }
  271. valArrLen := len(valArr)
  272. //var totalVal float64
  273. totalVal := decimal.NewFromFloat(0.00)
  274. for _, v := range valArr {
  275. newDecimal := decimal.NewFromFloat(v)
  276. totalVal = totalVal.Add(newDecimal)
  277. }
  278. af := totalVal //decimal.NewFromFloat(totalVal)
  279. bf := decimal.NewFromFloat(float64(valArrLen))
  280. val, _ := af.Div(bf).Float64()
  281. valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
  282. // 实际数据的值
  283. if fromEdbInfo.LatestDate == av {
  284. latestValue = val
  285. }
  286. if existVal, existOk := existDataMap[av]; !existOk {
  287. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  288. if tmpErr != nil {
  289. err = tmpErr
  290. return
  291. }
  292. timestamp := currentDate.UnixNano() / 1e6
  293. timestampStr := fmt.Sprintf("%d", timestamp)
  294. if _, existOk := existAddDataMap[av]; !existOk {
  295. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
  296. isAdd = true
  297. }
  298. existAddDataMap[av] = av
  299. } else {
  300. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  301. delete(removeDataTimeMap, av)
  302. existValDecimal, _ := decimal.NewFromString(existVal.Value)
  303. existStr := existValDecimal.String()
  304. fmt.Println(existStr, valStr, av)
  305. if existStr != valStr {
  306. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  307. sql = fmt.Sprintf(sql, dataTableName)
  308. _, err = to.Raw(sql, valStr, edbInfoId, av).Exec()
  309. if err != nil {
  310. return
  311. }
  312. }
  313. }
  314. }
  315. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  316. {
  317. removeDateList := make([]string, 0)
  318. for dateTime := range removeDataTimeMap {
  319. removeDateList = append(removeDateList, dateTime)
  320. }
  321. removeNum := len(removeDateList)
  322. if removeNum > 0 {
  323. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  324. _, err = to.Raw(sql, edbInfoId, removeDateList).Exec()
  325. if err != nil {
  326. fmt.Println("refreshAllPredictCalculateNszydpjjs add data ;delete Err", err.Error())
  327. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  328. return
  329. }
  330. }
  331. }
  332. if isAdd {
  333. addSql = strings.TrimRight(addSql, ",")
  334. //utils.FileLog.Info("addSql:" + addSql)
  335. _, err = to.Raw(addSql).Exec()
  336. if err != nil {
  337. return
  338. }
  339. }
  340. return
  341. }