edb_data_calculate_kszs.go 12 KB

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