edb_data_calculate_cjjx.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/nosixtools/solarlunar"
  8. "github.com/shopspring/decimal"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // AddCalculateCjjx 超季节性
  14. func AddCalculateCjjx(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (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("AddCalculateCjjx,Err:" + err.Error())
  23. _ = to.Rollback()
  24. } else {
  25. _ = to.Commit()
  26. }
  27. }()
  28. fmt.Println("req.EdbInfoId:", req.EdbInfoId)
  29. if req.EdbInfoId <= 0 {
  30. edbInfo = new(EdbInfo)
  31. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_CJJX
  32. edbInfo.SourceName = "超季节性"
  33. edbInfo.EdbCode = edbCode
  34. edbInfo.EdbName = req.EdbName
  35. edbInfo.EdbNameSource = req.EdbName
  36. edbInfo.Frequency = req.Frequency
  37. edbInfo.Unit = req.Unit
  38. edbInfo.ClassifyId = req.ClassifyId
  39. edbInfo.SysUserId = sysUserId
  40. edbInfo.SysUserRealName = sysUserRealName
  41. edbInfo.CreateTime = time.Now()
  42. edbInfo.ModifyTime = time.Now()
  43. edbInfo.UniqueCode = uniqueCode
  44. edbInfo.CalculateFormula = req.Formula
  45. edbInfo.Calendar = req.Calendar
  46. edbInfo.EdbType = 2
  47. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  48. if tmpErr != nil {
  49. err = tmpErr
  50. return
  51. }
  52. edbInfo.EdbInfoId = int(newEdbInfoId)
  53. //关联关系
  54. {
  55. calculateMappingItem := new(EdbInfoCalculateMapping)
  56. calculateMappingItem.CreateTime = time.Now()
  57. calculateMappingItem.ModifyTime = time.Now()
  58. calculateMappingItem.Sort = 1
  59. calculateMappingItem.EdbCode = edbCode
  60. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  61. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  63. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  64. calculateMappingItem.FromSource = fromEdbInfo.Source
  65. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  66. calculateMappingItem.FromTag = ""
  67. calculateMappingItem.Source = edbInfo.Source
  68. calculateMappingItem.SourceName = edbInfo.SourceName
  69. calculateMappingItem.FromSubSource = edbInfo.SubSource
  70. _, err = to.Insert(calculateMappingItem)
  71. if err != nil {
  72. return
  73. }
  74. }
  75. } else {
  76. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  77. if err != nil {
  78. return
  79. }
  80. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_CJJX, utils.DATA_SUB_SOURCE_EDB)
  81. fmt.Println("dataTableName:", dataTableName)
  82. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  83. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  84. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  85. if err != nil {
  86. return
  87. }
  88. }
  89. //计算数据
  90. err = refreshAllCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.Calendar, formulaInt)
  91. return
  92. }
  93. // EditCalculateCjjx 超季节性
  94. func EditCalculateCjjx(req *EdbInfoCalculateBatchEditReq, edbInfo, fromEdbInfo *EdbInfo, formulaInt int) (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("EditCalculateCjjx,Err:" + err.Error())
  103. _ = to.Rollback()
  104. } else {
  105. _ = to.Commit()
  106. }
  107. }()
  108. oldCalculateFormula := edbInfo.CalculateFormula //原先的n值
  109. oldCalendar := edbInfo.Calendar //原先的公历、农历
  110. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  111. if err != nil {
  112. return
  113. }
  114. //修改指标信息
  115. edbInfo.EdbName = req.EdbName
  116. edbInfo.EdbNameSource = req.EdbName
  117. edbInfo.Frequency = req.Frequency
  118. edbInfo.Unit = req.Unit
  119. edbInfo.ClassifyId = req.ClassifyId
  120. edbInfo.CalculateFormula = req.Formula
  121. edbInfo.Calendar = req.Calendar
  122. edbInfo.ModifyTime = time.Now()
  123. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "Calendar", "ModifyTime")
  124. if err != nil {
  125. return
  126. }
  127. //判断计算指标是否被更换
  128. var existCondition string
  129. var existPars []interface{}
  130. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  131. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  132. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  133. if err != nil {
  134. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  135. return
  136. }
  137. if count > 0 && oldCalculateFormula == req.Formula && oldCalendar == req.Calendar { // 指标未被替换,同时N值未修改,同时公历/农历未变更,无需重新计算
  138. return
  139. }
  140. // 指标被替换,或者N值未修改,那么需要重新计算数据
  141. //基础指标被替换了,需要删除原先的 计算指标关联的,基础指标的关联关系
  142. if count <= 0 {
  143. // 需要删除原先的 计算指标关联的,基础指标的关联关系
  144. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  145. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  146. if err != nil {
  147. return
  148. }
  149. // 添加新的关联关系
  150. {
  151. calculateMappingItem := &EdbInfoCalculateMapping{
  152. EdbInfoCalculateMappingId: 0,
  153. EdbInfoId: edbInfo.EdbInfoId,
  154. Source: utils.DATA_SOURCE_CALCULATE_CJJX,
  155. SourceName: "超季节性",
  156. EdbCode: edbInfo.EdbCode,
  157. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  158. FromEdbCode: fromEdbInfo.EdbCode,
  159. FromEdbName: fromEdbInfo.EdbName,
  160. FromSource: fromEdbInfo.Source,
  161. FromSourceName: fromEdbInfo.SourceName,
  162. FromTag: "",
  163. Sort: 1,
  164. CreateTime: time.Now(),
  165. ModifyTime: time.Now(),
  166. FromSubSource: fromEdbInfo.SubSource,
  167. }
  168. _, err = to.Insert(calculateMappingItem)
  169. if err != nil {
  170. return
  171. }
  172. }
  173. }
  174. //清空原有数据
  175. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  176. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
  177. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  178. if err != nil {
  179. return
  180. }
  181. //计算数据
  182. err = refreshAllCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.Calendar, formulaInt)
  183. return
  184. }
  185. // RefreshAllCalculateCjjx 刷新全部超季节性数据
  186. func RefreshAllCalculateCjjx(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, calendar string, formulaInt int) (err error) {
  187. o := orm.NewOrm()
  188. to, err := o.Begin()
  189. if err != nil {
  190. return
  191. }
  192. defer func() {
  193. if err != nil {
  194. fmt.Println("RefreshAllCalculateCjjx,Err:" + err.Error())
  195. _ = to.Rollback()
  196. } else {
  197. _ = to.Commit()
  198. }
  199. }()
  200. // 重新计算
  201. err = refreshAllCalculateCjjx(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, calendar, formulaInt)
  202. return
  203. }
  204. // refreshAllCalculateCjjx 刷新全部超季节性数据
  205. func refreshAllCalculateCjjx(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, calendar string, formulaInt int) (err error) {
  206. if err != nil {
  207. return
  208. }
  209. edbInfoIdStr := strconv.Itoa(edbInfoId)
  210. //计算数据
  211. var condition string
  212. var pars []interface{}
  213. condition += " AND edb_info_id=? "
  214. pars = append(pars, fromEdbInfo.EdbInfoId)
  215. //if startDate != "" {
  216. // condition += " AND data_time>=? "
  217. // pars = append(pars, startDate)
  218. //}
  219. //if endDate != "" {
  220. // condition += " AND data_time<=? "
  221. // pars = append(pars, endDate)
  222. //}
  223. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 1)
  224. if err != nil {
  225. return err
  226. }
  227. var dateArr []string
  228. dataMap := make(map[string]*EdbInfoSearchData)
  229. for _, v := range dataList {
  230. dateArr = append(dateArr, v.DataTime)
  231. dataMap[v.DataTime] = v
  232. }
  233. // 通过插值法补全所有数据(包含周末)
  234. handleDataMap := make(map[string]float64)
  235. _, err = HandleDataByLinearRegression(dataList, handleDataMap)
  236. if err != nil {
  237. return
  238. }
  239. //获取指标所有数据
  240. existDataList := make([]*EdbData, 0)
  241. dataTableName := GetEdbDataTableName(source, subSource)
  242. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  243. sql = fmt.Sprintf(sql, dataTableName)
  244. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  245. if err != nil {
  246. return err
  247. }
  248. existDataMap := make(map[string]string)
  249. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  250. for _, v := range existDataList {
  251. existDataMap[edbCode+v.DataTime] = v.Value
  252. removeDataTimeMap[v.DataTime] = 1
  253. }
  254. addSql := ` INSERT INTO edb_data_calculate_cjjx(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  255. var isAdd bool
  256. //日度/周度/季度/月度
  257. //isCompatibility := false //是否向上下兼容35天
  258. //if utils.InArrayByStr([]string{"日度", "周度", "季度", "月度"}, fromEdbInfo.Frequency) {
  259. // isCompatibility = true
  260. //}
  261. // 每个年份的日期数据需要平移的天数
  262. moveDayMap := make(map[int]int, 0) // 每个年份的春节公历
  263. var lastDataDay time.Time
  264. if len(dataList) > 0 {
  265. lastDataDay, _ = time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  266. }
  267. for _, av := range dateArr {
  268. // 如果遇到闰二月,如2.29,去掉该天数据
  269. if strings.Contains(av, "02-29") {
  270. continue
  271. }
  272. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  273. if tmpErr != nil {
  274. err = tmpErr
  275. return
  276. }
  277. //农历的超季节性运算,只计算11月--次年5月,分段计算,与数据区间和N数值有关
  278. if calendar == "农历" && currentDate.Month() > 5 && currentDate.Month() < 11 {
  279. continue
  280. }
  281. currentItem, ok := dataMap[av]
  282. // 找不到数据就退出当前循环,进入下一循环
  283. if !ok {
  284. continue
  285. }
  286. pastValueList := make([]float64, 0) // 过去几期的数据
  287. //当前日期
  288. pastValueList = append(pastValueList, currentItem.Value)
  289. for i := 1; i < formulaInt; i++ {
  290. //前几年当天公历的日期
  291. historyPreDate := currentDate.AddDate(-i, 0, 0)
  292. moveDay := 0
  293. if calendar == "农历" {
  294. if tmpMoveDay, ok := moveDayMap[historyPreDate.Year()]; !ok {
  295. moveDay, err = getMoveDay(lastDataDay, historyPreDate)
  296. if err != nil {
  297. return
  298. }
  299. } else {
  300. moveDay = tmpMoveDay
  301. }
  302. // 移动天数到对应农历 的 公历 日期
  303. historyPreDate = historyPreDate.AddDate(0, 0, moveDay)
  304. }
  305. historyPreDateStr := historyPreDate.Format(utils.FormatDate)
  306. if tmpValue, ok := handleDataMap[historyPreDateStr]; ok { //上一年同期找到
  307. pastValueList = append(pastValueList, tmpValue)
  308. }
  309. //if findItem, ok := dataMap[hisoryPreDateStr]; ok { //上一年同期找到
  310. // pastValueList = append(pastValueList, findItem.Value)
  311. //} else if isCompatibility { // 如果需要兼容上下35天
  312. // nextDateDay := hisoryPreDate
  313. // preDateDay := hisoryPreDate
  314. // for i := 0; i < 35; i++ {
  315. // nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  316. // if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  317. // pastValueList = append(pastValueList, findItem.Value)
  318. // break
  319. // } else {
  320. // preDateDayStr := preDateDay.Format(utils.FormatDate)
  321. // if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  322. // pastValueList = append(pastValueList, findItem.Value)
  323. // break
  324. // }
  325. // }
  326. // nextDateDay = nextDateDay.AddDate(0, 0, 1)
  327. // preDateDay = preDateDay.AddDate(0, 0, -1)
  328. // }
  329. //}
  330. }
  331. if len(pastValueList) == formulaInt {
  332. delete(removeDataTimeMap, av) //将待删除的日期给移除
  333. val := CjjxSub(currentItem.Value, pastValueList)
  334. if existVal, ok := existDataMap[edbCode+av]; !ok {
  335. timestamp := currentDate.UnixNano() / 1e6
  336. timestampStr := fmt.Sprintf("%d", timestamp)
  337. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  338. isAdd = true
  339. } else {
  340. existValDecimal, err := decimal.NewFromString(existVal)
  341. existStr := existValDecimal.String()
  342. if existStr != val {
  343. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  344. sql = fmt.Sprintf(sql, dataTableName)
  345. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  346. if err != nil {
  347. return err
  348. }
  349. }
  350. }
  351. }
  352. existDataMap[edbCode+av] = av
  353. }
  354. //删除已经不存在的超季节性指标数据(由于该指标当日的数据删除了)
  355. {
  356. removeDateList := make([]string, 0)
  357. for dateTime := range removeDataTimeMap {
  358. removeDateList = append(removeDateList, dateTime)
  359. }
  360. removeNum := len(removeDateList)
  361. if removeNum > 0 {
  362. //如果拼接指标变更了,那么需要删除所有的指标数据
  363. tableName := GetEdbDataTableName(source, subSource)
  364. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, tableName)
  365. _, err = to.Raw(sql, edbInfoId, removeDateList).Exec()
  366. if err != nil {
  367. err = fmt.Errorf("删除不存在的超季节性指标数据失败,Err:" + err.Error())
  368. return
  369. }
  370. }
  371. }
  372. if isAdd {
  373. addSql = strings.TrimRight(addSql, ",")
  374. _, err = to.Raw(addSql).Exec()
  375. if err != nil {
  376. return err
  377. }
  378. }
  379. return
  380. }
  381. // getMoveDay 获取两个日期的平移天数
  382. func getMoveDay(lastDataDay, currentDataDay time.Time) (moveDay int, err error) {
  383. if lastDataDay.Month() >= 11 { //最新数据的日期如果大于等于11月份,那么用的是下一年的春节
  384. lastDataDay = lastDataDay.AddDate(1, 0, 0)
  385. }
  386. currentYear := lastDataDay.Year()
  387. currentYearCjnl := fmt.Sprintf("%d-01-01", currentYear) //当年的春节农历
  388. currentYearCjgl := solarlunar.LunarToSolar(currentYearCjnl, false) //当年的春节公历
  389. currentYearCjglTime, tmpErr := time.ParseInLocation(utils.FormatDate, currentYearCjgl, time.Local)
  390. if tmpErr != nil {
  391. err = errors.New("当前春节公历日期转换失败:" + tmpErr.Error())
  392. return
  393. }
  394. //指定年的春节农历
  395. tmpYearCjnl := fmt.Sprintf("%d-01-01", currentDataDay.Year())
  396. //指定年的春节公历
  397. tmpYearCjgl := solarlunar.LunarToSolar(tmpYearCjnl, false)
  398. tmpYearCjglTime, tmpErr := time.ParseInLocation(utils.FormatDate, tmpYearCjgl, time.Local)
  399. if tmpErr != nil {
  400. err = errors.New(fmt.Sprintf("%d公历日期转换失败:%s", currentDataDay.Year(), tmpErr.Error()))
  401. return
  402. }
  403. // 将两个日期同步到同一年,然后计算两个日期相差的天数
  404. tmpCurrentYearCjglTime := currentYearCjglTime.AddDate(currentDataDay.Year()-currentYear, 0, 0)
  405. moveDay = utils.GetTimeSubDay(tmpYearCjglTime, tmpCurrentYearCjglTime)
  406. return
  407. }
  408. // CjjxSub 计算超季节性值
  409. // 计算公式=现值-过去n年(包括今年)均值,n为取数个数,需大于等于1;
  410. // 举例:A指标 2022-10-13值100,2021-10-13值120,2020-10-13值110,设置n=3,则“超季节性”指标计算值为100-(100+120+110)/3=-10。
  411. func CjjxSub(currValue float64, pastValue []float64) (value string) {
  412. num := len(pastValue)
  413. if num == 0 {
  414. return
  415. }
  416. numDecimal := decimal.NewFromInt(int64(num))
  417. af := decimal.NewFromFloat(currValue)
  418. //fmt.Println(af)
  419. bf := decimal.NewFromFloat(pastValue[0])
  420. for k := 1; k < num; k++ {
  421. tmpVal := decimal.NewFromFloat(pastValue[k])
  422. bf = bf.Add(tmpVal)
  423. }
  424. val, _ := af.Sub(bf.Div(numDecimal)).Float64()
  425. //valStr := utils.SubFloatToString(val, 4)
  426. valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
  427. return valStr
  428. }