predict_edb_data_calculate_cjjx.go 12 KB

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