edb_data_calculate_hcz.go 10 KB

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