edb_data_calculate_hcz.go 9.8 KB

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