edb_data_calculate_nszydbpjjs.go 11 KB

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