edb_data_calculate_hcz.go 10 KB

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