edb_data_calculate_kszs.go 12 KB

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