edb_data_calculate_kszs.go 12 KB

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