predict_edb_data_calculate_cjjx.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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/shopspring/decimal"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // SavePredictCalculateCjjx 超季节性
  13. func SavePredictCalculateCjjx(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int, lang string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("SavePredictCalculateCjjx,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. fmt.Println("req.EdbInfoId:", req.EdbInfoId)
  28. if req.EdbInfoId <= 0 {
  29. edbInfo = new(EdbInfo)
  30. edbInfo.EdbInfoType = 1
  31. edbInfo.Source = utils.DATA_SOURCE_PREDICT_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.EdbNameEn = req.EdbName
  47. edbInfo.UnitEn = req.Unit
  48. edbInfo.EdbType = 2
  49. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE)
  50. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  51. if tmpErr != nil {
  52. err = tmpErr
  53. return
  54. }
  55. edbInfo.EdbInfoId = int(newEdbInfoId)
  56. //关联关系
  57. {
  58. calculateMappingItem := new(EdbInfoCalculateMapping)
  59. calculateMappingItem.CreateTime = time.Now()
  60. calculateMappingItem.ModifyTime = time.Now()
  61. calculateMappingItem.Sort = 1
  62. calculateMappingItem.EdbCode = edbCode
  63. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  64. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  65. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  66. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  67. calculateMappingItem.FromSource = fromEdbInfo.Source
  68. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  69. calculateMappingItem.FromTag = ""
  70. calculateMappingItem.Source = edbInfo.Source
  71. calculateMappingItem.SourceName = edbInfo.SourceName
  72. _, err = to.Insert(calculateMappingItem)
  73. if err != nil {
  74. return
  75. }
  76. }
  77. } else {
  78. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  79. if err != nil {
  80. return
  81. }
  82. oldCalculateFormula := edbInfo.CalculateFormula //原先的n值
  83. oldCalendar := edbInfo.Calendar //原先的公历、农历
  84. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  85. if err != nil {
  86. return
  87. }
  88. latestDateStr = edbInfo.LatestDate
  89. latestValue = edbInfo.LatestValue
  90. //修改指标信息
  91. switch lang {
  92. case utils.EnLangVersion:
  93. edbInfo.EdbNameEn = req.EdbName
  94. edbInfo.UnitEn = req.Unit
  95. default:
  96. edbInfo.EdbName = req.EdbName
  97. edbInfo.Unit = req.Unit
  98. edbInfo.EdbNameSource = req.EdbName
  99. }
  100. edbInfo.Frequency = req.Frequency
  101. edbInfo.ClassifyId = req.ClassifyId
  102. edbInfo.CalculateFormula = req.Formula
  103. edbInfo.Calendar = req.Calendar
  104. edbInfo.ModifyTime = time.Now()
  105. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "Calendar", "ModifyTime", "EdbNameEn", "UnitEn")
  106. if err != nil {
  107. return
  108. }
  109. //判断计算指标是否被更换
  110. var existCondition string
  111. var existPars []interface{}
  112. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  113. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  114. var count int
  115. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  116. if err != nil {
  117. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  118. return
  119. }
  120. if count > 0 && oldCalculateFormula == req.Formula && oldCalendar == req.Calendar { // 指标未被替换,同时N值未修改,同时公历/农历未变更,无需重新计算
  121. return
  122. }
  123. // 指标被替换,或者N值未修改,那么需要重新计算数据
  124. //基础指标被替换了,需要删除原先的 计算指标关联的,基础指标的关联关系
  125. if count <= 0 {
  126. // 需要删除原先的 计算指标关联的,基础指标的关联关系
  127. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  128. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  129. if err != nil {
  130. return
  131. }
  132. // 添加新的关联关系
  133. {
  134. calculateMappingItem := &EdbInfoCalculateMapping{
  135. EdbInfoCalculateMappingId: 0,
  136. EdbInfoId: edbInfo.EdbInfoId,
  137. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_CJJX,
  138. SourceName: "预测超季节性",
  139. EdbCode: edbInfo.EdbCode,
  140. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  141. FromEdbCode: fromEdbInfo.EdbCode,
  142. FromEdbName: fromEdbInfo.EdbName,
  143. FromSource: fromEdbInfo.Source,
  144. FromSourceName: fromEdbInfo.SourceName,
  145. FromTag: "",
  146. Sort: 1,
  147. CreateTime: time.Now(),
  148. ModifyTime: time.Now(),
  149. }
  150. _, err = to.Insert(calculateMappingItem)
  151. if err != nil {
  152. return
  153. }
  154. }
  155. }
  156. //清空原有数据
  157. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  158. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
  159. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  160. if err != nil {
  161. return
  162. }
  163. }
  164. //计算数据
  165. latestDateStr, latestValue, err = refreshAllPredictCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "", edbInfo.Calendar, formulaInt)
  166. return
  167. }
  168. // RefreshAllPredictCalculateCjjx 刷新全部超季节性数据
  169. func RefreshAllPredictCalculateCjjx(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, calendar string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  170. o := orm.NewOrm()
  171. to, err := o.Begin()
  172. if err != nil {
  173. return
  174. }
  175. defer func() {
  176. if err != nil {
  177. fmt.Println("RefreshAllPredictCalculateCjjx,Err:" + err.Error())
  178. _ = to.Rollback()
  179. } else {
  180. _ = to.Commit()
  181. }
  182. }()
  183. // 重新计算
  184. latestDateStr, latestValue, err = refreshAllPredictCalculateCjjx(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate, calendar, formulaInt)
  185. return
  186. }
  187. // refreshAllPredictCalculateCjjx 刷新全部超季节性数据
  188. func refreshAllPredictCalculateCjjx(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate, calendar string, formulaInt int) (latestDateStr string, latestValue float64, err error) {
  189. edbInfoIdStr := strconv.Itoa(edbInfoId)
  190. // 获取关联指标数据
  191. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, "")
  192. if err != nil {
  193. return
  194. }
  195. latestDateStr = fromEdbInfo.LatestDate
  196. var dateArr []string
  197. dataMap := make(map[string]*EdbInfoSearchData)
  198. for _, v := range dataList {
  199. dateArr = append(dateArr, v.DataTime)
  200. dataMap[v.DataTime] = v
  201. }
  202. // 通过插值法补全所有数据(包含周末)
  203. handleDataMap := make(map[string]float64)
  204. _, err = HandleDataByLinearRegression(dataList, handleDataMap)
  205. if err != nil {
  206. return
  207. }
  208. //获取指标所有数据
  209. existDataList := make([]*EdbData, 0)
  210. dataTableName := GetEdbDataTableName(source, subSource)
  211. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  212. sql = fmt.Sprintf(sql, dataTableName)
  213. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  214. if err != nil {
  215. return
  216. }
  217. existDataMap := make(map[string]string)
  218. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  219. for _, v := range existDataList {
  220. existDataMap[edbCode+v.DataTime] = v.Value
  221. removeDataTimeMap[v.DataTime] = 1
  222. }
  223. addSql := ` INSERT INTO edb_data_predict_calculate_cjjx(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  224. var isAdd bool
  225. //日度/周度/季度/月度
  226. //isCompatibility := false //是否向上下兼容35天
  227. //if utils.InArrayByStr([]string{"日度", "周度", "季度", "月度"}, fromEdbInfo.Frequency) {
  228. // isCompatibility = true
  229. //}
  230. // 每个年份的日期数据需要平移的天数
  231. moveDayMap := make(map[int]int, 0) // 每个年份的春节公历
  232. var lastDataDay time.Time
  233. if len(dataList) > 0 {
  234. lastDataDay, _ = time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  235. }
  236. for _, av := range dateArr {
  237. currentItem := dataMap[av]
  238. if currentItem != nil {
  239. pastValueList := make([]float64, 0) // 过去几期的数据
  240. //当前日期
  241. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  242. if tmpErr != nil {
  243. err = tmpErr
  244. return
  245. }
  246. pastValueList = append(pastValueList, currentItem.Value)
  247. for i := 1; i < formulaInt; i++ {
  248. //前几年当天公历的日期
  249. hisoryPreDate := currentDate.AddDate(-i, 0, 0)
  250. moveDay := 0
  251. if calendar == "农历" {
  252. if tmpMoveDay, ok := moveDayMap[hisoryPreDate.Year()]; !ok {
  253. moveDay, err = getMoveDay(lastDataDay, hisoryPreDate)
  254. if err != nil {
  255. return
  256. }
  257. } else {
  258. moveDay = tmpMoveDay
  259. }
  260. // 移动天数到对应农历 的 公历 日期
  261. hisoryPreDate = hisoryPreDate.AddDate(0, 0, moveDay)
  262. }
  263. historyPreDateStr := hisoryPreDate.Format(utils.FormatDate)
  264. if tmpValue, ok := handleDataMap[historyPreDateStr]; ok { //上一年同期找到
  265. pastValueList = append(pastValueList, tmpValue)
  266. }
  267. //else if isCompatibility { // 如果需要兼容上下35天
  268. // nextDateDay := hisoryPreDate
  269. // preDateDay := hisoryPreDate
  270. // for i := 0; i < 35; i++ {
  271. // nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  272. // if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  273. // pastValueList = append(pastValueList, findItem.Value)
  274. // break
  275. // } else {
  276. // preDateDayStr := preDateDay.Format(utils.FormatDate)
  277. // if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  278. // pastValueList = append(pastValueList, findItem.Value)
  279. // break
  280. // }
  281. // }
  282. // nextDateDay = nextDateDay.AddDate(0, 0, 1)
  283. // preDateDay = preDateDay.AddDate(0, 0, -1)
  284. // }
  285. //}
  286. //if av == "2023-09-29" {
  287. // fmt.Println(moveDay)
  288. //}
  289. }
  290. //if av == "2023-09-29" {
  291. // fmt.Println(pastValueList)
  292. //}
  293. if len(pastValueList) == formulaInt {
  294. delete(removeDataTimeMap, av) //将待删除的日期给移除
  295. val := CjjxSub(currentItem.Value, pastValueList)
  296. if existVal, ok := existDataMap[edbCode+av]; !ok {
  297. timestamp := currentDate.UnixNano() / 1e6
  298. timestampStr := fmt.Sprintf("%d", timestamp)
  299. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  300. isAdd = true
  301. } else {
  302. var existValDecimal decimal.Decimal
  303. existValDecimal, err = decimal.NewFromString(existVal)
  304. if err != nil {
  305. return
  306. }
  307. existStr := existValDecimal.String()
  308. if existStr != val {
  309. sql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  310. sql = fmt.Sprintf(sql, dataTableName)
  311. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  312. if err != nil {
  313. return
  314. }
  315. }
  316. }
  317. }
  318. existDataMap[edbCode+av] = av
  319. }
  320. }
  321. //删除已经不存在的超季节性指标数据(由于该指标当日的数据删除了)
  322. {
  323. removeDateList := make([]string, 0)
  324. for dateTime := range removeDataTimeMap {
  325. removeDateList = append(removeDateList, dateTime)
  326. }
  327. removeNum := len(removeDateList)
  328. if removeNum > 0 {
  329. //如果拼接指标变更了,那么需要删除所有的指标数据
  330. tableName := GetEdbDataTableName(source, subSource)
  331. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, tableName)
  332. _, err = to.Raw(sql, edbInfoId, removeDateList).Exec()
  333. if err != nil {
  334. err = fmt.Errorf("删除不存在的超季节性指标数据失败,Err:" + err.Error())
  335. return
  336. }
  337. }
  338. }
  339. if isAdd {
  340. addSql = strings.TrimRight(addSql, ",")
  341. _, err = to.Raw(addSql).Exec()
  342. if err != nil {
  343. return
  344. }
  345. }
  346. //确定最终值
  347. var finalLast EdbInfoSearchData
  348. sql = ` SELECT data_time , value FROM edb_data_predict_calculate_cjjx WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `
  349. tmpErr := to.Raw(sql, edbInfoId, latestDateStr).QueryRow(&finalLast)
  350. if tmpErr != nil {
  351. if tmpErr.Error() != utils.ErrNoRow() {
  352. err = tmpErr
  353. } else {
  354. latestDateStr = "0000-00-00"
  355. }
  356. return
  357. } else {
  358. latestDateStr = finalLast.DataTime
  359. latestValue = finalLast.Value
  360. }
  361. return
  362. }