edb_data_calculate_hcz.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. // AddCalculateHcz 新增环差值指标
  13. func AddCalculateHcz(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. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("AddCalculateHcz,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_HCZ
  30. edbInfo.SourceName = "环差值"
  31. edbInfo.EdbCode = edbCode
  32. edbInfo.EdbName = req.EdbName
  33. edbInfo.EdbNameSource = req.EdbName
  34. edbInfo.Frequency = req.Frequency
  35. edbInfo.Unit = req.Unit
  36. edbInfo.ClassifyId = req.ClassifyId
  37. edbInfo.SysUserId = sysUserId
  38. edbInfo.SysUserRealName = sysUserRealName
  39. edbInfo.CreateTime = time.Now()
  40. edbInfo.ModifyTime = time.Now()
  41. edbInfo.UniqueCode = uniqueCode
  42. edbInfo.CalculateFormula = req.Formula
  43. edbInfo.EdbType = 2
  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. _, err = to.Insert(calculateMappingItem)
  67. if err != nil {
  68. return
  69. }
  70. }
  71. } else {
  72. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  73. if err != nil {
  74. return
  75. }
  76. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HCZ)
  77. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  78. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  79. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  80. if err != nil {
  81. return
  82. }
  83. }
  84. //计算数据
  85. err = refreshAllCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  86. return
  87. }
  88. // EditCalculateHcz 修改环差值指标
  89. func EditCalculateHcz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, formulaInt int, oldCalculateFormula string) (err error) {
  90. o := orm.NewOrm()
  91. to, err := o.Begin()
  92. if err != nil {
  93. return
  94. }
  95. defer func() {
  96. if err != nil {
  97. fmt.Println("EditCalculateHcz,Err:" + err.Error())
  98. _ = to.Rollback()
  99. } else {
  100. _ = to.Commit()
  101. }
  102. }()
  103. //修改指标信息
  104. edbInfo.EdbName = req.EdbName
  105. edbInfo.EdbNameSource = req.EdbName
  106. edbInfo.Frequency = req.Frequency
  107. edbInfo.Unit = req.Unit
  108. edbInfo.ClassifyId = req.ClassifyId
  109. edbInfo.CalculateFormula = req.Formula
  110. edbInfo.ModifyTime = time.Now()
  111. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  112. if err != nil {
  113. return
  114. }
  115. //判断计算指标是否被更换
  116. var existCondition string
  117. var existPars []interface{}
  118. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  119. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  120. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  121. if err != nil {
  122. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  123. return
  124. }
  125. if count > 0 && strconv.Itoa(formulaInt) == oldCalculateFormula { // 指标未被替换,同时N值未修改,无需重新计算
  126. return
  127. }
  128. //删除,计算指标关联的,基础指标的关联关系
  129. if count <= 0 {
  130. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  131. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  132. if err != nil {
  133. return
  134. }
  135. //关联关系
  136. {
  137. calculateMappingItem := &EdbInfoCalculateMapping{
  138. EdbInfoCalculateMappingId: 0,
  139. EdbInfoId: edbInfo.EdbInfoId,
  140. Source: utils.DATA_SOURCE_CALCULATE_HCZ,
  141. SourceName: "环差值",
  142. EdbCode: edbInfo.EdbCode,
  143. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  144. FromEdbCode: fromEdbInfo.EdbCode,
  145. FromEdbName: fromEdbInfo.EdbName,
  146. FromSource: fromEdbInfo.Source,
  147. FromSourceName: fromEdbInfo.SourceName,
  148. FromTag: "",
  149. Sort: 1,
  150. CreateTime: time.Now(),
  151. ModifyTime: time.Now(),
  152. }
  153. _, err = to.Insert(calculateMappingItem)
  154. if err != nil {
  155. return
  156. }
  157. }
  158. }
  159. //清空原有数据
  160. sql := ` DELETE FROM edb_data_calculate_hcz WHERE edb_info_id = ? `
  161. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  162. if err != nil {
  163. return
  164. }
  165. //计算数据
  166. err = refreshAllCalculateHcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  167. return
  168. }
  169. // RefreshAllCalculateHcz 刷新所有环差值数据
  170. func RefreshAllCalculateHcz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  171. o := orm.NewOrm()
  172. to, err := o.Begin()
  173. if err != nil {
  174. return
  175. }
  176. defer func() {
  177. if err != nil {
  178. fmt.Println("RefreshAllCalculateHcz,Err:" + err.Error())
  179. _ = to.Rollback()
  180. } else {
  181. _ = to.Commit()
  182. }
  183. }()
  184. //计算数据
  185. err = refreshAllCalculateHcz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  186. return
  187. }
  188. // refreshAllCalculateHcz 刷新所有环差值数据
  189. func refreshAllCalculateHcz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  190. edbInfoIdStr := strconv.Itoa(edbInfoId)
  191. //计算数据
  192. var condition string
  193. var pars []interface{}
  194. condition += " AND edb_info_id=? "
  195. pars = append(pars, fromEdbInfo.EdbInfoId)
  196. //if startDate != "" {
  197. // condition += " AND data_time>=? "
  198. // pars = append(pars, startDate)
  199. //}
  200. //if endDate != "" {
  201. // condition += " AND data_time<=? "
  202. // pars = append(pars, endDate)
  203. //}
  204. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
  205. if err != nil {
  206. return err
  207. }
  208. var dateArr []string
  209. dataMap := make(map[string]*EdbInfoSearchData)
  210. for _, v := range dataList {
  211. dateArr = append(dateArr, v.DataTime)
  212. dataMap[v.DataTime] = v
  213. }
  214. fmt.Println("source:", source)
  215. //获取指标所有数据
  216. existDataList := make([]*EdbData, 0)
  217. dataTableName := GetEdbDataTableName(source)
  218. fmt.Println("dataTableName:", dataTableName)
  219. var existPars []interface{}
  220. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  221. //if startDate != "" {
  222. // sql += " AND data_time>=? "
  223. // existPars = append(existPars, startDate)
  224. //}
  225. sql = fmt.Sprintf(sql, dataTableName)
  226. _, err = to.Raw(sql, edbInfoId, existPars).QueryRows(&existDataList)
  227. if err != nil {
  228. return err
  229. }
  230. existDataMap := make(map[string]string)
  231. removeDateMap := make(map[string]string) //需要移除的日期
  232. for _, v := range existDataList {
  233. existDataMap[v.DataTime] = v.Value
  234. removeDateMap[v.DataTime] = v.DataTime
  235. }
  236. //fmt.Println("existDataMap:", existDataMap)
  237. addSql := ` INSERT INTO edb_data_calculate_hcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  238. var isAdd bool
  239. existMap := make(map[string]string)
  240. dataLen := len(dataList)
  241. fmt.Println("dataLen:", dataLen)
  242. for i := 0; i < dataLen; i++ {
  243. j := i + formulaInt
  244. if j < dataLen {
  245. //当期
  246. currentItem := dataList[i]
  247. preItem := dataList[j]
  248. if currentItem != nil && preItem != nil {
  249. existKey := edbCode + currentItem.DataTime
  250. if _, ok := existMap[existKey]; !ok {
  251. currentDate, _ := time.ParseInLocation(utils.FormatDate, currentItem.DataTime, time.Local)
  252. //fmt.Println(currentDate)
  253. timestamp := currentDate.UnixNano() / 1e6
  254. timestampStr := fmt.Sprintf("%d", timestamp)
  255. val := HczDiv(currentItem.Value, preItem.Value)
  256. if val != "" {
  257. // 有计算出来值,那么就从待删除指标中移除
  258. delete(removeDateMap, currentItem.DataTime)
  259. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  260. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  261. isAdd = true
  262. } else {
  263. existValDecimal, err := decimal.NewFromString(existVal)
  264. existStr := existValDecimal.String()
  265. if existStr != val {
  266. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  267. sql = fmt.Sprintf(sql, dataTableName)
  268. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  269. if err != nil {
  270. return err
  271. }
  272. }
  273. }
  274. }
  275. }
  276. existMap[existKey] = currentItem.DataTime
  277. }
  278. }
  279. }
  280. if isAdd {
  281. addSql = strings.TrimRight(addSql, ",")
  282. _, err = to.Raw(addSql).Exec()
  283. if err != nil {
  284. return err
  285. }
  286. }
  287. //fmt.Println(removeDateMap)
  288. if len(removeDateMap) > 0 {
  289. removeDateList := make([]string, 0) //需要移除的日期
  290. for k := range removeDateMap {
  291. removeDateList = append(removeDateList, k)
  292. }
  293. removeDateStr := strings.Join(removeDateList, `","`)
  294. removeDateStr = `"` + removeDateStr + `"`
  295. //如果拼接指标变更了,那么需要删除所有的指标数据
  296. tableName := GetEdbDataTableName(source)
  297. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  298. _, err = to.Raw(sql, edbInfoId).Exec()
  299. if err != nil {
  300. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  301. return
  302. }
  303. }
  304. return
  305. }
  306. // HczDiv 环差值计算,current:当期,pre:上期 公式:当期-上期
  307. func HczDiv(current, pre float64) string {
  308. if pre == 0 {
  309. return ""
  310. }
  311. currentVal := decimal.NewFromFloat(current)
  312. preVal := decimal.NewFromFloat(pre)
  313. val, _ := currentVal.Sub(preVal).Float64()
  314. valStr := decimal.NewFromFloat(val).RoundCeil(4).String() //utils.SubFloatToString(val, 4)
  315. return valStr
  316. }