edb_data_calculate_nszydbpjjs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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.EdbNameEn = req.EdbName
  41. edbInfo.UnitEn = req.Unit
  42. edbInfo.EdbType = 2
  43. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  44. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  45. if tmpErr != nil {
  46. err = tmpErr
  47. return
  48. }
  49. edbInfo.EdbInfoId = int(newEdbInfoId)
  50. //关联关系
  51. {
  52. calculateMappingItem := new(EdbInfoCalculateMapping)
  53. calculateMappingItem.CreateTime = time.Now()
  54. calculateMappingItem.ModifyTime = time.Now()
  55. calculateMappingItem.Sort = 1
  56. calculateMappingItem.EdbCode = edbCode
  57. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  58. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  59. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  60. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  61. calculateMappingItem.FromSource = fromEdbInfo.Source
  62. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  63. calculateMappingItem.FromTag = ""
  64. calculateMappingItem.Source = edbInfo.Source
  65. calculateMappingItem.SourceName = edbInfo.SourceName
  66. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  67. _, err = to.Insert(calculateMappingItem)
  68. if err != nil {
  69. return
  70. }
  71. }
  72. } else {
  73. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  74. if err != nil {
  75. return
  76. }
  77. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_NSZYDPJJS, utils.DATA_SUB_SOURCE_EDB)
  78. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  79. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  80. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  81. if err != nil {
  82. return
  83. }
  84. }
  85. //计算数据
  86. err = refreshAllCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
  87. return
  88. }
  89. // EditCalculateNszydpjjs 修改N数值移动平均计算
  90. func EditCalculateNszydpjjs(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, formulaInt int, oldCalculateFormula string) (err error) {
  91. o := orm.NewOrm()
  92. to, err := o.Begin()
  93. defer func() {
  94. if err != nil {
  95. fmt.Println("EditCalculateNszydpjjs,Err:" + err.Error())
  96. _ = to.Rollback()
  97. } else {
  98. _ = to.Commit()
  99. }
  100. }()
  101. //修改指标信息
  102. edbInfo.EdbName = req.EdbName
  103. edbInfo.EdbNameSource = req.EdbName
  104. edbInfo.Frequency = req.Frequency
  105. edbInfo.Unit = req.Unit
  106. edbInfo.ClassifyId = req.ClassifyId
  107. edbInfo.CalculateFormula = req.Formula
  108. edbInfo.EdbNameEn = req.EdbNameEn
  109. edbInfo.UnitEn = req.UnitEn
  110. edbInfo.ModifyTime = time.Now()
  111. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn")
  112. if err != nil {
  113. return
  114. }
  115. var existCondition string
  116. var existPars []interface{}
  117. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  118. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  119. //判断计算指标是否被更换
  120. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  121. if err != nil && err.Error() != utils.ErrNoRow() {
  122. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  123. return
  124. }
  125. fmt.Println("oldCalculateFormula:", oldCalculateFormula)
  126. fmt.Println("req.Formula:", req.Formula)
  127. fmt.Println("count:", count)
  128. if count > 0 && oldCalculateFormula == req.Formula { // 指标未被替换,同时N值未修改,无需重新计算
  129. return
  130. }
  131. if count <= 0 {
  132. // 需要删除原先的 计算指标关联的,基础指标的关联关系
  133. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  134. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  135. if err != nil {
  136. return
  137. }
  138. // 添加新的关联关系
  139. {
  140. calculateMappingItem := &EdbInfoCalculateMapping{
  141. EdbInfoCalculateMappingId: 0,
  142. EdbInfoId: edbInfo.EdbInfoId,
  143. Source: utils.DATA_SOURCE_CALCULATE_NSZYDPJJS,
  144. SourceName: "N数值移动平均计算",
  145. EdbCode: edbInfo.EdbCode,
  146. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  147. FromEdbCode: fromEdbInfo.EdbCode,
  148. FromEdbName: fromEdbInfo.EdbName,
  149. FromSource: fromEdbInfo.Source,
  150. FromSourceName: fromEdbInfo.SourceName,
  151. FromTag: "",
  152. Sort: 1,
  153. CreateTime: time.Now(),
  154. ModifyTime: time.Now(),
  155. FromSubSource: fromEdbInfo.SubSource,
  156. }
  157. _, err = to.Insert(calculateMappingItem)
  158. if err != nil {
  159. return
  160. }
  161. }
  162. }
  163. //清空原有数据
  164. sql := ` DELETE FROM edb_data_calculate_nszydpjjs WHERE edb_info_id = ? `
  165. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  166. if err != nil {
  167. return
  168. }
  169. //计算数据
  170. err = refreshAllCalculateNszydpjjs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, formulaInt, fromEdbInfo, edbInfo.EdbCode, "")
  171. return
  172. }
  173. // RefreshAllCalculateNszydpjjs 刷新全部N数值移动平均计算
  174. func RefreshAllCalculateNszydpjjs(edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (err error) {
  175. o := orm.NewOrm()
  176. to, err := o.Begin()
  177. defer func() {
  178. if err != nil {
  179. fmt.Println("RefreshCalculateNszydpjjs Err:" + err.Error())
  180. utils.FileLog.Info("RefreshCalculateNszydpjjs Err:" + err.Error())
  181. _ = to.Rollback()
  182. } else {
  183. _ = to.Commit()
  184. }
  185. }()
  186. //计算数据
  187. err = refreshAllCalculateNszydpjjs(to, edbInfoId, source, subSource, formulaInt, fromEdbInfo, edbCode, startDate)
  188. return
  189. }
  190. // refreshAllCalculateNszydpjjs 更新全部N数值移动平均计算
  191. func refreshAllCalculateNszydpjjs(to orm.TxOrmer, edbInfoId, source, subSource, formulaInt int, fromEdbInfo *EdbInfo, edbCode, startDate string) (err error) {
  192. edbInfoIdStr := strconv.Itoa(edbInfoId)
  193. fmt.Println(edbInfoIdStr)
  194. fmt.Println("refreshAllCalculateNszydpjjs startDate:", startDate)
  195. //计算数据
  196. var condition string
  197. var pars []interface{}
  198. condition += " AND edb_info_id=? "
  199. pars = append(pars, edbInfoId)
  200. existDataList, err := GetEdbDataListAllV1ByTo(to, condition, pars, source, subSource, 0)
  201. if err != nil {
  202. fmt.Println("existDataList GetEdbDataListAll Err:" + err.Error())
  203. return err
  204. }
  205. existDataMap := make(map[string]*EdbInfoSearchDataV1)
  206. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  207. for _, v := range existDataList {
  208. existDataMap[v.DataTime] = v
  209. removeDataTimeMap[v.DataTime] = 1
  210. }
  211. // 获取来源数据
  212. fromDataList, err := GetEdbDataListAll(fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  213. EdbInfoId: fromEdbInfo.EdbInfoId,
  214. }, 0)
  215. if err != nil {
  216. fmt.Println("from GetEdbDataListAll Err:" + err.Error())
  217. return err
  218. }
  219. //fmt.Println("fromPars:", fromPars)
  220. //fromDataList, err := GetEdbDataListAllV1ByTo(to, fromCondition, fromPars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  221. var fromDateArr []string
  222. fromDataMap := make(map[string]*EdbInfoSearchData)
  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 []float64
  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.NewFromFloat(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).Round(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. }