edb_data_calculate_kszs.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_index_lib/global"
  6. "eta_gn/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/shopspring/decimal"
  9. "gorm.io/gorm"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // AddCalculateKszs 扩散指数
  15. func AddCalculateKszs(req *EdbInfoCalculateBatchSaveReq, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  16. to := global.DEFAULT_DmSQL.Begin()
  17. defer func() {
  18. if err != nil {
  19. to.Rollback()
  20. } else {
  21. to.Commit()
  22. }
  23. }()
  24. if req.EdbInfoId > 0 {
  25. err = errors.New("无法新增")
  26. return
  27. }
  28. edbInfo = new(EdbInfo)
  29. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_KSZS
  30. edbInfo.SourceName = utils.DATA_SOURCE_NAME_CALCULATE_KSZS
  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. tmpErr := to.Create(edbInfo).Error
  48. if tmpErr != nil {
  49. err = tmpErr
  50. return
  51. }
  52. //关联关系
  53. tagMap := make(map[string]int)
  54. relationEdbInfoList := make([]*EdbInfo, 0)
  55. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  56. for _, v := range req.EdbInfoIdArr {
  57. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  58. if tmpErr != nil {
  59. err = tmpErr
  60. return
  61. }
  62. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  63. calculateMappingItem := new(EdbInfoCalculateMapping)
  64. calculateMappingItem.CreateTime = time.Now()
  65. calculateMappingItem.ModifyTime = time.Now()
  66. calculateMappingItem.Sort = 1
  67. calculateMappingItem.EdbCode = edbCode
  68. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  69. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  70. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  71. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  72. calculateMappingItem.FromSource = tmpEdbInfo.Source
  73. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  74. calculateMappingItem.FromTag = v.FromTag
  75. calculateMappingItem.Source = edbInfo.Source
  76. calculateMappingItem.SourceName = edbInfo.SourceName
  77. calculateMappingItem.FromSubSource = edbInfo.SubSource
  78. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  79. tagMap[v.FromTag] = v.EdbInfoId
  80. }
  81. err = to.CreateInBatches(calculateMappingItemList, 500).Error
  82. if err != nil {
  83. return
  84. }
  85. //计算数据
  86. err = refreshAllCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)
  87. return
  88. }
  89. // EditCalculateKszs 修改扩散指数数据
  90. func EditCalculateKszs(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq) (err error) {
  91. to := global.DEFAULT_DmSQL.Begin()
  92. defer func() {
  93. if err != nil {
  94. to.Rollback()
  95. } else {
  96. to.Commit()
  97. }
  98. }()
  99. //修改指标信息
  100. edbInfo.EdbName = req.EdbName
  101. edbInfo.EdbNameSource = req.EdbName
  102. edbInfo.Frequency = req.Frequency
  103. edbInfo.Unit = req.Unit
  104. edbInfo.ClassifyId = req.ClassifyId
  105. edbInfo.CalculateFormula = req.Formula
  106. edbInfo.EdbNameEn = req.EdbNameEn
  107. edbInfo.UnitEn = req.UnitEn
  108. edbInfo.ModifyTime = time.Now()
  109. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  110. if err != nil {
  111. return
  112. }
  113. //删除,计算指标关联的,基础指标的关联关系
  114. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  115. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  116. if err != nil {
  117. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  118. return
  119. }
  120. //清空原有数据
  121. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  122. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  123. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  124. if err != nil {
  125. return
  126. }
  127. //关联关系
  128. tagMap := make(map[string]int)
  129. relationEdbInfoList := make([]*EdbInfo, 0)
  130. calculateMappingItemList := make([]*EdbInfoCalculateMapping, 0)
  131. for _, v := range req.EdbInfoIdArr {
  132. tmpEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  133. if tmpErr != nil {
  134. err = tmpErr
  135. return
  136. }
  137. relationEdbInfoList = append(relationEdbInfoList, tmpEdbInfo)
  138. calculateMappingItem := new(EdbInfoCalculateMapping)
  139. calculateMappingItem.CreateTime = time.Now()
  140. calculateMappingItem.ModifyTime = time.Now()
  141. calculateMappingItem.Sort = 1
  142. calculateMappingItem.EdbCode = edbInfo.EdbCode
  143. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  144. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  145. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  146. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  147. calculateMappingItem.FromSource = tmpEdbInfo.Source
  148. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  149. calculateMappingItem.FromTag = v.FromTag
  150. calculateMappingItem.Source = edbInfo.Source
  151. calculateMappingItem.SourceName = edbInfo.SourceName
  152. calculateMappingItem.FromSubSource = edbInfo.SubSource
  153. calculateMappingItemList = append(calculateMappingItemList, calculateMappingItem)
  154. tagMap[v.FromTag] = v.EdbInfoId
  155. }
  156. err = to.CreateInBatches(calculateMappingItemList, 500).Error
  157. if err != nil {
  158. return
  159. }
  160. //计算数据
  161. err = refreshAllCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)
  162. return
  163. }
  164. func RefreshAllCalculateKszs(edbInfo *EdbInfo) (err error) {
  165. edbInfoCalculateDetailList, err := GetEdbInfoCalculateDetailList(edbInfo.EdbInfoId)
  166. if err != nil {
  167. return
  168. }
  169. tagMap := make(map[string]int)
  170. relationEdbInfoList := make([]*EdbInfo, 0)
  171. for _, v := range edbInfoCalculateDetailList {
  172. tagMap[v.FromTag] = v.FromEdbInfoId
  173. fromEdbInfo, _ := GetEdbInfoById(v.FromEdbInfoId)
  174. relationEdbInfoList = append(relationEdbInfoList, fromEdbInfo)
  175. }
  176. to := global.DEFAULT_DmSQL.Begin()
  177. defer func() {
  178. if err != nil {
  179. to.Rollback()
  180. } else {
  181. to.Commit()
  182. }
  183. }()
  184. // 计算数据
  185. err = refreshAllCalculateKszs(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, relationEdbInfoList, edbInfo.EdbCode, edbInfo.CalculateFormula, tagMap)
  186. return
  187. }
  188. // KszsConfig 扩散指数配置
  189. type KszsConfig struct {
  190. DateType int `description:"扩散指标日期;1:全部指标日期并集;2:部分指标日期并集"`
  191. CheckList []string `description:"选中的数据,A,B,C"`
  192. }
  193. // refreshAllCalculateKszs 刷新扩散指数数据
  194. func refreshAllCalculateKszs(to *gorm.DB, edbInfoId, source, subSource int, relationEdbInfoList []*EdbInfo, edbCode, calculateFormula string, tagMap map[string]int) (err error) {
  195. edbInfoIdStr := strconv.Itoa(edbInfoId)
  196. tableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_KSZS, utils.DATA_SUB_SOURCE_EDB)
  197. // 获取扩散指标关联的指标id
  198. checkEdbInfoIdMap := make(map[int]int)
  199. {
  200. var config KszsConfig
  201. err = json.Unmarshal([]byte(calculateFormula), &config)
  202. if err != nil {
  203. return
  204. }
  205. if config.DateType == 1 {
  206. for _, tmpEdbInfoId := range tagMap {
  207. checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
  208. }
  209. } else {
  210. for _, v := range config.CheckList {
  211. if tmpEdbInfoId, ok := tagMap[v]; ok {
  212. checkEdbInfoIdMap[tmpEdbInfoId] = tmpEdbInfoId
  213. }
  214. }
  215. }
  216. }
  217. //获取扩散指数指标所有数据
  218. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  219. if err != nil {
  220. return
  221. }
  222. //计算指标的map
  223. existDataMap := make(map[string]*EdbData, 0)
  224. removeDateMap := make(map[string]string)
  225. for _, v := range existDataList {
  226. existDataMap[v.DataTime] = v
  227. removeDateMap[v.DataTime] = ``
  228. }
  229. //获取来源指标的数据
  230. relationEdbDataMap := make(map[int]map[string]float64)
  231. // 获取选择指标的 需要数据的 开始日期和结束日期
  232. var startDate, endDate time.Time
  233. for _, v := range relationEdbInfoList {
  234. tmpDataList, tmpErr := GetEdbDataListAllByTo(to, v.Source, v.SubSource, FindEdbDataListAllCond{
  235. EdbInfoId: v.EdbInfoId,
  236. }, 1)
  237. if tmpErr != nil {
  238. err = tmpErr
  239. return err
  240. }
  241. if tmpDataList != nil {
  242. if _, ok2 := checkEdbInfoIdMap[v.EdbInfoId]; ok2 {
  243. lenTmpDataList := len(tmpDataList)
  244. if lenTmpDataList > 0 {
  245. tmpStartTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[0].DataTime, time.Local)
  246. tmpEndTime, _ := time.ParseInLocation(utils.FormatDate, tmpDataList[lenTmpDataList-1].DataTime, time.Local)
  247. if startDate.IsZero() || tmpStartTime.Before(startDate) {
  248. startDate = tmpStartTime
  249. }
  250. if tmpEndTime.IsZero() || tmpEndTime.After(endDate) {
  251. endDate = tmpEndTime
  252. }
  253. }
  254. }
  255. // 用上期的数据补充当期的数据处理
  256. handleDataMap := make(map[string]float64)
  257. err = HandleDataByPreviousData(tmpDataList, handleDataMap)
  258. if err != nil {
  259. return
  260. }
  261. relationEdbDataMap[v.EdbInfoId] = handleDataMap
  262. }
  263. }
  264. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  265. var isAdd bool
  266. for currDate := startDate.AddDate(0, 0, 1); !currDate.After(endDate); currDate = currDate.AddDate(0, 0, 1) {
  267. currDateStr := currDate.Format(utils.FormatDate)
  268. //环差指数列表
  269. tmpValList := make([]float64, 0)
  270. for _, dataMap := range relationEdbDataMap {
  271. currVal, ok := dataMap[currDateStr]
  272. if !ok {
  273. continue
  274. }
  275. perVal, ok := dataMap[currDate.AddDate(0, 0, -1).Format(utils.FormatDate)]
  276. if !ok {
  277. continue
  278. }
  279. var tmpVal float64
  280. if currVal > perVal {
  281. tmpVal = 1
  282. } else if currVal == perVal {
  283. tmpVal = 0.5
  284. } else {
  285. tmpVal = 0
  286. }
  287. tmpValList = append(tmpValList, tmpVal)
  288. }
  289. lenTmpValList := len(tmpValList)
  290. if lenTmpValList <= 0 {
  291. continue
  292. }
  293. currValDeci := decimal.NewFromFloat(0)
  294. for _, tmpVal := range tmpValList {
  295. currValDeci = currValDeci.Add(decimal.NewFromFloat(tmpVal))
  296. }
  297. currVal, _ := currValDeci.Div(decimal.NewFromInt(int64(lenTmpValList))).Round(4).Float64()
  298. // 判断扩散指数指标是否存在数据
  299. if existData, ok := existDataMap[currDateStr]; ok {
  300. // 处理扩散指数数据的值
  301. existValStr := existData.Value
  302. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  303. if tmpErr != nil {
  304. err = tmpErr
  305. return
  306. }
  307. existVal, _ := existValDeci.Round(4).Float64()
  308. // 判断扩散指数数据的值 与 当前计算出来的结果, 如果两个数据结果不相等的话,那么就修改咯
  309. if existVal != currVal {
  310. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  311. if err != nil {
  312. return err
  313. }
  314. }
  315. } else {
  316. // 直接入库
  317. timestamp := currDate.UnixNano() / 1e6
  318. timestampStr := fmt.Sprintf("%d", timestamp)
  319. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timestampStr, fmt.Sprint(currVal))
  320. isAdd = true
  321. }
  322. delete(removeDateMap, currDateStr)
  323. }
  324. if isAdd {
  325. addSql = strings.TrimRight(addSql, ",")
  326. err = to.Exec(addSql).Error
  327. }
  328. // 移除不存在的日期数据
  329. if len(removeDateMap) > 0 {
  330. removeDateList := make([]string, 0) //需要移除的日期
  331. for k := range removeDateMap {
  332. removeDateList = append(removeDateList, k)
  333. }
  334. removeDateStr := strings.Join(removeDateList, `','`)
  335. removeDateStr = `'` + removeDateStr + `'`
  336. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  337. err = to.Raw(sql, edbInfoId).Error
  338. if err != nil {
  339. err = fmt.Errorf("删除扩散指数指标数据失败,Err:" + err.Error())
  340. return
  341. }
  342. }
  343. return
  344. }