predict_edb_data_calculate_cjjx.go 11 KB

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