edb_info_calculate_nszydpjjs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. package data_manage
  2. import (
  3. "errors"
  4. "eta/eta_api/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. type EdbInfoCalculateNszydpjjs struct {
  13. EdbInfoCalculateNszydpjjsId int `orm:"column(edb_info_calculate_nszydpjjs_id);pk"`
  14. EdbInfoId int `description:"指标id"`
  15. EdbCode string `description:"指标编码"`
  16. FromEdbInfoId int `description:"计算指标id"`
  17. FromEdbCode string `description:"计算指标编码"`
  18. FromEdbName string `description:"计算指标名称"`
  19. FromSource int `description:"计算指标来源"`
  20. FromSourceName string `description:"计算指标来源名称"`
  21. FromTag string `description:"来源指标标签"`
  22. Sort int `description:"计算指标名称排序"`
  23. CreateTime time.Time `description:"创建时间"`
  24. ModifyTime time.Time `description:"修改时间"`
  25. }
  26. // N数值移动平均计算
  27. func AddCalculateNszydpjjs(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
  28. o := orm.NewOrmUsingDB("data")
  29. to, err := o.Begin()
  30. if err != nil {
  31. return
  32. }
  33. defer func() {
  34. if err != nil {
  35. _ = to.Rollback()
  36. } else {
  37. _ = to.Commit()
  38. }
  39. }()
  40. if req.EdbInfoId <= 0 {
  41. edbInfo := new(EdbInfo)
  42. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_NSZYDPJJS
  43. edbInfo.SourceName = "N数值移动平均计算"
  44. edbInfo.EdbCode = edbCode
  45. edbInfo.EdbName = req.EdbName
  46. edbInfo.EdbNameSource = req.EdbName
  47. edbInfo.Frequency = req.Frequency
  48. edbInfo.Unit = req.Unit
  49. edbInfo.ClassifyId = req.ClassifyId
  50. edbInfo.SysUserId = sysUserId
  51. edbInfo.SysUserRealName = sysUserRealName
  52. edbInfo.CreateTime = time.Now()
  53. edbInfo.ModifyTime = time.Now()
  54. edbInfo.UniqueCode = uniqueCode
  55. edbInfo.CalculateFormula = req.Formula
  56. edbInfo.EdbType = 2
  57. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  58. if tmpErr != nil {
  59. return edbInfoId, tmpErr
  60. }
  61. edbInfoId = int(newEdbInfoId)
  62. //calculateItem := new(EdbInfoCalculateNszydpjjs)
  63. //calculateItem.CreateTime = time.Now()
  64. //calculateItem.ModifyTime = time.Now()
  65. //calculateItem.Sort = 1
  66. //calculateItem.EdbCode = edbCode
  67. //calculateItem.EdbInfoId = edbInfoId
  68. //calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  69. //calculateItem.FromEdbCode = fromEdbInfo.EdbCode
  70. //calculateItem.FromEdbName = fromEdbInfo.EdbName
  71. //calculateItem.FromSource = fromEdbInfo.Source
  72. //calculateItem.FromSourceName = fromEdbInfo.SourceName
  73. //
  74. //_, err = to.Insert(calculateItem)
  75. //if err != nil {
  76. // return edbInfoId, err
  77. //}
  78. //关联关系
  79. {
  80. calculateMappingItem := new(EdbInfoCalculateMapping)
  81. calculateMappingItem.CreateTime = time.Now()
  82. calculateMappingItem.ModifyTime = time.Now()
  83. calculateMappingItem.Sort = 1
  84. calculateMappingItem.EdbCode = edbCode
  85. calculateMappingItem.EdbInfoId = edbInfoId
  86. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  87. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  88. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  89. calculateMappingItem.FromSource = fromEdbInfo.Source
  90. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  91. calculateMappingItem.FromTag = ""
  92. calculateMappingItem.Source = edbInfo.Source
  93. calculateMappingItem.SourceName = edbInfo.SourceName
  94. _, err = to.Insert(calculateMappingItem)
  95. if err != nil {
  96. return
  97. }
  98. }
  99. } else {
  100. edbInfoId = req.EdbInfoId
  101. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_NSZYDPJJS, utils.DATA_SUB_SOURCE_EDB)
  102. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  103. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  104. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  105. }
  106. edbInfoIdStr := strconv.Itoa(edbInfoId)
  107. //计算数据
  108. var condition string
  109. var pars []interface{}
  110. condition += " AND edb_info_id=? "
  111. if req.EdbInfoId <= 0 {
  112. pars = append(pars, req.FromEdbInfoId)
  113. } else {
  114. pars = append(pars, fromEdbInfo.EdbInfoId)
  115. }
  116. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  117. if err != nil {
  118. return edbInfoId, err
  119. }
  120. var dateArr []string
  121. dataMap := make(map[string]*EdbInfoSearchData)
  122. for _, v := range dataList {
  123. dateArr = append(dateArr, v.DataTime)
  124. dataMap[v.DataTime] = v
  125. }
  126. addSql := ` INSERT INTO edb_data_calculate_nszydpjjs(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  127. var isAdd bool
  128. arrLen := len(dateArr)
  129. for ak, av := range dateArr {
  130. //处理第一个值
  131. var valArr []float64
  132. if findItem, ok := dataMap[av]; ok {
  133. valArr = append(valArr, findItem.Value)
  134. } else {
  135. continue
  136. }
  137. if ak+1 != arrLen {
  138. //处理除第一个值之外的N-1个值
  139. for i := 1; i < formulaInt; i++ {
  140. arrIndex := ak + i
  141. if arrIndex >= arrLen {
  142. break
  143. }
  144. arrVal := dateArr[arrIndex]
  145. if findItem, ok := dataMap[arrVal]; ok {
  146. valArr = append(valArr, findItem.Value)
  147. } else {
  148. continue
  149. }
  150. }
  151. }
  152. valArrLen := len(valArr)
  153. totalVal := decimal.NewFromFloat(0.00)
  154. for _, v := range valArr {
  155. newDecimal := decimal.NewFromFloat(v)
  156. totalVal = totalVal.Add(newDecimal)
  157. }
  158. af := totalVal //decimal.NewFromFloat(totalVal)
  159. bf := decimal.NewFromFloat(float64(valArrLen))
  160. val, _ := af.Div(bf).Float64()
  161. currentDate, err := time.Parse(utils.FormatDate, av)
  162. if err != nil {
  163. return edbInfoId, err
  164. }
  165. timestamp := currentDate.UnixNano() / 1e6
  166. timestampStr := fmt.Sprintf("%d", timestamp)
  167. valStr := utils.SubFloatToString(val, 4)
  168. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
  169. isAdd = true
  170. }
  171. if isAdd {
  172. addSql = strings.TrimRight(addSql, ",")
  173. _, err = to.Raw(addSql).Exec()
  174. if err != nil {
  175. return edbInfoId, err
  176. }
  177. }
  178. return
  179. }
  180. // 修改N数值移动平均计算
  181. func EditCalculateNszydpjjs(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, formulaInt int, oldCalculateFormula string) (edbInfoId int, err error) {
  182. edbInfoId = req.EdbInfoId
  183. o := orm.NewOrmUsingDB("data")
  184. to, err := o.Begin()
  185. if err != nil {
  186. return
  187. }
  188. defer func() {
  189. if err != nil {
  190. _ = to.Rollback()
  191. } else {
  192. _ = to.Commit()
  193. }
  194. }()
  195. //修改指标信息
  196. sql := ` UPDATE edb_info
  197. SET
  198. edb_name =?,
  199. edb_name_source=?,
  200. frequency = ?,
  201. unit = ?,
  202. classify_id = ?,
  203. calculate_formula=?,
  204. modify_time = NOW()
  205. WHERE edb_info_id = ? `
  206. _, err = to.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
  207. if err != nil {
  208. return
  209. }
  210. var existCondition string
  211. var existPars []interface{}
  212. existCondition += " AND edb_info_id=? "
  213. existPars = append(existPars, edbInfoId)
  214. existCondition += " AND from_edb_info_id=? "
  215. existPars = append(existPars, req.FromEdbInfoId)
  216. //判断计算指标是否被更换
  217. count, err := GetEdbInfoCalculateCountByCondition(req.Source, existCondition, existPars)
  218. if err != nil && err.Error() != utils.ErrNoRow() {
  219. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  220. return
  221. }
  222. if count <= 0 || oldCalculateFormula != req.Formula {
  223. //删除,计算指标关联的,基础指标的关联关系
  224. sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  225. _, err = to.Raw(sql, edbInfoId).Exec()
  226. if err != nil {
  227. return edbInfoId, err
  228. }
  229. //清空原有数据
  230. sql = ` DELETE FROM edb_data_calculate_nszydpjjs WHERE edb_info_id = ? `
  231. _, err = to.Raw(sql, edbInfoId).Exec()
  232. if err != nil {
  233. return edbInfoId, err
  234. }
  235. //关联关系
  236. {
  237. calculateMappingItem := new(EdbInfoCalculateMapping)
  238. calculateMappingItem.CreateTime = time.Now()
  239. calculateMappingItem.ModifyTime = time.Now()
  240. calculateMappingItem.Sort = 1
  241. calculateMappingItem.EdbCode = edbCode
  242. calculateMappingItem.EdbInfoId = edbInfoId
  243. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  244. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  245. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  246. calculateMappingItem.FromSource = fromEdbInfo.Source
  247. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  248. calculateMappingItem.FromTag = ""
  249. calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_NSZYDPJJS
  250. calculateMappingItem.SourceName = "N数值移动平均计算"
  251. _, err = to.Insert(calculateMappingItem)
  252. if err != nil {
  253. return
  254. }
  255. }
  256. edbInfoIdStr := strconv.Itoa(edbInfoId)
  257. //计算数据
  258. var condition string
  259. var pars []interface{}
  260. condition += " AND edb_info_id=? "
  261. pars = append(pars, req.FromEdbInfoId)
  262. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  263. if err != nil {
  264. return edbInfoId, err
  265. }
  266. var dateArr []string
  267. dataMap := make(map[string]*EdbInfoSearchData)
  268. for _, v := range dataList {
  269. dateArr = append(dateArr, v.DataTime)
  270. dataMap[v.DataTime] = v
  271. }
  272. addSql := ` INSERT INTO edb_data_calculate_nszydpjjs(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  273. var isAdd bool
  274. arrLen := len(dateArr)
  275. for ak, av := range dateArr {
  276. //处理第一个值
  277. var valArr []float64
  278. if findItem, ok := dataMap[av]; ok {
  279. valArr = append(valArr, findItem.Value)
  280. } else {
  281. continue
  282. }
  283. if ak+1 != arrLen {
  284. //处理除第一个值之外的N-1个值
  285. for i := 1; i < formulaInt; i++ {
  286. arrIndex := ak + i
  287. if arrIndex >= arrLen {
  288. break
  289. }
  290. arrVal := dateArr[arrIndex]
  291. if findItem, ok := dataMap[arrVal]; ok {
  292. valArr = append(valArr, findItem.Value)
  293. } else {
  294. continue
  295. }
  296. }
  297. }
  298. valArrLen := len(valArr)
  299. totalVal := decimal.NewFromFloat(0.00)
  300. for _, v := range valArr {
  301. newDecimal := decimal.NewFromFloat(v)
  302. totalVal = totalVal.Add(newDecimal)
  303. }
  304. af := totalVal
  305. bf := decimal.NewFromFloat(float64(valArrLen))
  306. val, _ := af.Div(bf).Float64()
  307. currentDate, err := time.Parse(utils.FormatDate, av)
  308. if err != nil {
  309. return edbInfoId, err
  310. }
  311. timestamp := currentDate.UnixNano() / 1e6
  312. timestampStr := fmt.Sprintf("%d", timestamp)
  313. valStr := utils.SubFloatToString(val, 4)
  314. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, valStr)
  315. isAdd = true
  316. }
  317. if isAdd {
  318. addSql = strings.TrimRight(addSql, ",")
  319. _, err = to.Raw(addSql).Exec()
  320. if err != nil {
  321. return edbInfoId, err
  322. }
  323. }
  324. }
  325. return
  326. }
  327. type EdbInfoCalculateNszydpjjsDetail struct {
  328. EdbInfoCalculateNszydpjjsId int `orm:"column(edb_info_calculate_nszydpjjs_id);pk"`
  329. EdbInfoId int `description:"指标id"`
  330. EdbCode string `description:"指标编码"`
  331. FromEdbInfoId int `description:"计算指标id"`
  332. FromEdbCode string `description:"计算指标编码"`
  333. FromEdbName string `description:"计算指标名称"`
  334. FromSource int `description:"计算指标来源"`
  335. FromSourceName string `description:"计算指标来源名称"`
  336. FromTag string `description:"来源指标标签"`
  337. Sort int `description:"计算指标名称排序"`
  338. CreateTime time.Time `description:"创建时间"`
  339. ModifyTime time.Time `description:"修改时间"`
  340. StartDate string `description:"开始日期"`
  341. EndDate string `description:"结束日期"`
  342. }
  343. func GetEdbInfoCalculateNszydpjjsDetail(edbInfoId int) (item *EdbInfoCalculateNszydpjjsDetail, err error) {
  344. o := orm.NewOrmUsingDB("data")
  345. sql := ` SELECT a.*,b.start_date,b.end_date FROM edb_info_calculate_mapping AS a
  346. INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
  347. WHERE a.edb_info_id=? `
  348. err = o.Raw(sql, edbInfoId).QueryRow(&item)
  349. return
  350. }