predict_edb_data_calculate_nszydbpjjs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 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: "",
  62. UnitEn: "",
  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. edbInfo.EdbName = edbName
  113. edbInfo.EdbNameSource = edbName
  114. edbInfo.Frequency = frequency
  115. edbInfo.Unit = unit
  116. edbInfo.ClassifyId = classifyId
  117. edbInfo.CalculateFormula = formula
  118. edbInfo.ModifyTime = time.Now()
  119. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  120. if err != nil {
  121. return
  122. }
  123. //判断计算指标是否被更换
  124. var existCondition string
  125. var existPars []interface{}
  126. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  127. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  128. latestDateStr = edbInfo.LatestDate
  129. latestValue = edbInfo.LatestValue
  130. count, tmpErr := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  131. if tmpErr != nil {
  132. err = errors.New("判断指标是否改变失败,Err:" + tmpErr.Error())
  133. return
  134. }
  135. if count > 0 && oldCalculateFormula == formula { // 指标未被替换,同时N值未修改,无需重新计算
  136. return
  137. }
  138. if count <= 0 {
  139. // 需要删除原先的 计算指标关联的,基础指标的关联关系
  140. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  141. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  142. if err != nil {
  143. return
  144. }
  145. // 添加新的关联关系
  146. {
  147. calculateMappingItem := &EdbInfoCalculateMapping{
  148. EdbInfoCalculateMappingId: 0,
  149. EdbInfoId: edbInfo.EdbInfoId,
  150. Source: edbInfo.Source,
  151. SourceName: edbInfo.SourceName,
  152. EdbCode: edbInfo.EdbCode,
  153. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  154. FromEdbCode: fromEdbInfo.EdbCode,
  155. FromEdbName: fromEdbInfo.EdbName,
  156. FromSource: fromEdbInfo.Source,
  157. FromSourceName: fromEdbInfo.SourceName,
  158. FromTag: "",
  159. Sort: 1,
  160. CreateTime: time.Now(),
  161. ModifyTime: time.Now(),
  162. }
  163. _, err = to.Insert(calculateMappingItem)
  164. if err != nil {
  165. return
  166. }
  167. }
  168. }
  169. // 删除该指标所有的同比数据
  170. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_NSZYDPJJS, utils.DATA_SUB_SOURCE_EDB)
  171. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  172. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  173. _, err = to.Raw(deleteSql, edbInfo.EdbInfoId).Exec()
  174. if err != nil {
  175. return
  176. }
  177. }
  178. latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
  179. return
  180. }
  181. // RefreshAllPredictCalculateNszydpjjs 刷新所有 N数值移动平均计算指标 数据
  182. func RefreshAllPredictCalculateNszydpjjs(edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  183. o := orm.NewOrm()
  184. to, err := o.Begin()
  185. if err != nil {
  186. return
  187. }
  188. defer func() {
  189. if err != nil {
  190. fmt.Println("RefreshAllPredictCalculateNszydpjjs,Err:" + err.Error())
  191. _ = to.Rollback()
  192. } else {
  193. _ = to.Commit()
  194. }
  195. }()
  196. latestDateStr, latestValue, err = refreshAllPredictCalculateNszydpjjs(to, edbInfoId, source, subSource, formulaInt, fromEdbInfo, edbCode, startDate)
  197. return
  198. }
  199. // refreshAllPredictCalculateNszydpjjs 更新全部N数值移动平均计算
  200. func refreshAllPredictCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  201. edbInfoIdStr := strconv.Itoa(edbInfoId)
  202. fmt.Println(edbInfoIdStr)
  203. fmt.Println("refreshAllCalculateNszydpjjs startDate:", startDate)
  204. // 获取关联指标数据
  205. existDataList := make([]*EdbData, 0)
  206. dataTableName := GetEdbDataTableName(source, subSource)
  207. fmt.Println("dataTableName:", dataTableName)
  208. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  209. sql = fmt.Sprintf(sql, dataTableName)
  210. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  211. existDataMap := make(map[string]*EdbData)
  212. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  213. for _, v := range existDataList {
  214. existDataMap[v.DataTime] = v
  215. removeDataTimeMap[v.DataTime] = 1
  216. }
  217. //计算来源数据
  218. var fromCondition string
  219. var fromPars []interface{}
  220. fromCondition += " AND edb_info_id=? "
  221. fromPars = append(fromPars, fromEdbInfo.EdbInfoId)
  222. if startDate != `` {
  223. fromCondition += " AND data_time>=? "
  224. fromPars = append(fromPars, startDate)
  225. }
  226. //fmt.Println("fromPars:", fromPars)
  227. fromDataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, startDate)
  228. if err != nil {
  229. return
  230. }
  231. latestDateStr = fromEdbInfo.LatestDate
  232. var fromDateArr []string
  233. fromDataMap := make(map[string]*EdbInfoSearchData)
  234. for _, v := range fromDataList {
  235. fromDateArr = append(fromDateArr, v.DataTime)
  236. fromDataMap[v.DataTime] = v
  237. }
  238. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  239. var isAdd bool
  240. arrLen := len(fromDateArr)
  241. existAddDataMap := make(map[string]string)
  242. for ak, av := range fromDateArr {
  243. //处理第一个值
  244. var valArr []float64
  245. if findItem, ok := fromDataMap[av]; ok {
  246. valArr = append(valArr, findItem.Value)
  247. } else {
  248. continue
  249. }
  250. if ak+1 != arrLen {
  251. //处理除第一个值之外的N-1个值
  252. for i := 1; i < formulaInt; i++ {
  253. arrIndex := ak + i
  254. if arrIndex >= arrLen {
  255. break
  256. }
  257. arrVal := fromDateArr[arrIndex]
  258. if findItem, ok := fromDataMap[arrVal]; ok {
  259. valArr = append(valArr, findItem.Value)
  260. } else {
  261. continue
  262. }
  263. }
  264. }
  265. valArrLen := len(valArr)
  266. //var totalVal float64
  267. totalVal := decimal.NewFromFloat(0.00)
  268. for _, v := range valArr {
  269. newDecimal := decimal.NewFromFloat(v)
  270. totalVal = totalVal.Add(newDecimal)
  271. }
  272. af := totalVal //decimal.NewFromFloat(totalVal)
  273. bf := decimal.NewFromFloat(float64(valArrLen))
  274. val, _ := af.Div(bf).Float64()
  275. valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
  276. // 实际数据的值
  277. if fromEdbInfo.LatestDate == av {
  278. latestValue = val
  279. }
  280. if existVal, existOk := existDataMap[av]; !existOk {
  281. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  282. if tmpErr != nil {
  283. err = tmpErr
  284. return
  285. }
  286. timestamp := currentDate.UnixNano() / 1e6
  287. timestampStr := fmt.Sprintf("%d", timestamp)
  288. if _, existOk := existAddDataMap[av]; !existOk {
  289. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
  290. isAdd = true
  291. }
  292. existAddDataMap[av] = av
  293. } else {
  294. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  295. delete(removeDataTimeMap, av)
  296. existValDecimal, _ := decimal.NewFromString(existVal.Value)
  297. existStr := existValDecimal.String()
  298. fmt.Println(existStr, valStr, av)
  299. if existStr != valStr {
  300. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  301. sql = fmt.Sprintf(sql, dataTableName)
  302. _, err = to.Raw(sql, valStr, edbInfoId, av).Exec()
  303. if err != nil {
  304. return
  305. }
  306. }
  307. }
  308. }
  309. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  310. {
  311. removeDateList := make([]string, 0)
  312. for dateTime := range removeDataTimeMap {
  313. removeDateList = append(removeDateList, dateTime)
  314. }
  315. removeNum := len(removeDateList)
  316. if removeNum > 0 {
  317. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  318. _, err = to.Raw(sql, edbInfoId, removeDateList).Exec()
  319. if err != nil {
  320. fmt.Println("refreshAllPredictCalculateNszydpjjs add data ;delete Err", err.Error())
  321. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  322. return
  323. }
  324. }
  325. }
  326. if isAdd {
  327. addSql = strings.TrimRight(addSql, ",")
  328. //utils.FileLog.Info("addSql:" + addSql)
  329. _, err = to.Raw(addSql).Exec()
  330. if err != nil {
  331. return
  332. }
  333. }
  334. return
  335. }