predict_edb_data_calculate_nszydbpjjs.go 11 KB

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