edb_data_calculate_cjjx.go 15 KB

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