predict_edb_data_calculate_cjjx.go 12 KB

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