predict_edb_data_calculate_nszydbpjjs.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  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)
  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, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
  179. return
  180. }
  181. // RefreshAllPredictCalculateNszydpjjs 刷新所有 N数值移动平均计算指标 数据
  182. func RefreshAllPredictCalculateNszydpjjs(edbInfoId, source, 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, formulaInt, fromEdbInfo, edbCode, startDate)
  197. return
  198. }
  199. // refreshAllPredictCalculateNszydpjjs 更新全部N数值移动平均计算
  200. func refreshAllPredictCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, 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)
  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. for _, v := range existDataList {
  213. existDataMap[v.DataTime] = v
  214. }
  215. //计算来源数据
  216. var fromCondition string
  217. var fromPars []interface{}
  218. fromCondition += " AND edb_info_id=? "
  219. fromPars = append(fromPars, fromEdbInfo.EdbInfoId)
  220. if startDate != `` {
  221. fromCondition += " AND data_time>=? "
  222. fromPars = append(fromPars, startDate)
  223. }
  224. //fmt.Println("fromPars:", fromPars)
  225. fromDataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 0, startDate)
  226. if err != nil {
  227. return
  228. }
  229. latestDateStr = fromEdbInfo.LatestDate
  230. var fromDateArr []string
  231. fromDataMap := make(map[string]*EdbInfoSearchData)
  232. for _, v := range fromDataList {
  233. fromDateArr = append(fromDateArr, v.DataTime)
  234. fromDataMap[v.DataTime] = v
  235. }
  236. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  237. var isAdd bool
  238. arrLen := len(fromDateArr)
  239. existAddDataMap := make(map[string]string)
  240. for ak, av := range fromDateArr {
  241. //处理第一个值
  242. var valArr []float64
  243. if findItem, ok := fromDataMap[av]; ok {
  244. valArr = append(valArr, findItem.Value)
  245. } else {
  246. continue
  247. }
  248. if ak+1 != arrLen {
  249. //处理除第一个值之外的N-1个值
  250. for i := 1; i < formulaInt; i++ {
  251. arrIndex := ak + i
  252. if arrIndex >= arrLen {
  253. break
  254. }
  255. arrVal := fromDateArr[arrIndex]
  256. if findItem, ok := fromDataMap[arrVal]; ok {
  257. valArr = append(valArr, findItem.Value)
  258. } else {
  259. continue
  260. }
  261. }
  262. }
  263. valArrLen := len(valArr)
  264. //var totalVal float64
  265. totalVal := decimal.NewFromFloat(0.00)
  266. for _, v := range valArr {
  267. newDecimal := decimal.NewFromFloat(v)
  268. totalVal = totalVal.Add(newDecimal)
  269. }
  270. af := totalVal //decimal.NewFromFloat(totalVal)
  271. bf := decimal.NewFromFloat(float64(valArrLen))
  272. val, _ := af.Div(bf).Float64()
  273. valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
  274. // 实际数据的值
  275. if fromEdbInfo.LatestDate == av {
  276. latestValue = val
  277. }
  278. if existVal, existOk := existDataMap[av]; !existOk {
  279. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  280. if tmpErr != nil {
  281. err = tmpErr
  282. return
  283. }
  284. timestamp := currentDate.UnixNano() / 1e6
  285. timestampStr := fmt.Sprintf("%d", timestamp)
  286. if _, existOk := existAddDataMap[av]; !existOk {
  287. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
  288. isAdd = true
  289. }
  290. existAddDataMap[av] = av
  291. } else {
  292. existValDecimal, _ := decimal.NewFromString(existVal.Value)
  293. existStr := existValDecimal.String()
  294. fmt.Println(existStr, valStr, av)
  295. if existStr != valStr {
  296. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  297. sql = fmt.Sprintf(sql, dataTableName)
  298. _, err = to.Raw(sql, valStr, edbInfoId, av).Exec()
  299. if err != nil {
  300. return
  301. }
  302. }
  303. }
  304. }
  305. if isAdd {
  306. addSql = strings.TrimRight(addSql, ",")
  307. //utils.FileLog.Info("addSql:" + addSql)
  308. _, err = to.Raw(addSql).Exec()
  309. if err != nil {
  310. return
  311. }
  312. }
  313. return
  314. }