predict_edb_data_calculate_ljzzy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. // SavePredictCalculateLjzzy 累计值转月
  13. func SavePredictCalculateLjzzy(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName, 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("SavePredictCalculateLjzzy,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.EdbInfoType = 1
  30. edbInfo.Source = utils.DATA_SOURCE_PREDICT_CALCULATE_LJZZY
  31. edbInfo.SourceName = "预测累计值转月值"
  32. edbInfo.EdbCode = edbCode
  33. edbInfo.EdbName = req.EdbName
  34. edbInfo.EdbNameSource = req.EdbName
  35. edbInfo.Frequency = req.Frequency
  36. edbInfo.Unit = req.Unit
  37. edbInfo.ClassifyId = req.ClassifyId
  38. edbInfo.SysUserId = sysUserId
  39. edbInfo.SysUserRealName = sysUserRealName
  40. edbInfo.CreateTime = time.Now()
  41. edbInfo.ModifyTime = time.Now()
  42. edbInfo.UniqueCode = uniqueCode
  43. edbInfo.CalculateFormula = req.Formula
  44. edbInfo.EdbNameEn = req.EdbName
  45. edbInfo.UnitEn = req.Unit
  46. edbInfo.EdbType = 2
  47. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE)
  48. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  49. if tmpErr != nil {
  50. err = tmpErr
  51. return
  52. }
  53. edbInfo.EdbInfoId = int(newEdbInfoId)
  54. //关联关系
  55. {
  56. calculateMappingItem := new(EdbInfoCalculateMapping)
  57. calculateMappingItem.CreateTime = time.Now()
  58. calculateMappingItem.ModifyTime = time.Now()
  59. calculateMappingItem.Sort = 1
  60. calculateMappingItem.EdbCode = edbCode
  61. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  63. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  64. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  65. calculateMappingItem.FromSource = fromEdbInfo.Source
  66. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  67. calculateMappingItem.FromTag = ""
  68. calculateMappingItem.Source = edbInfo.Source
  69. calculateMappingItem.SourceName = edbInfo.SourceName
  70. _, err = to.Insert(calculateMappingItem)
  71. if err != nil {
  72. return
  73. }
  74. }
  75. } else {
  76. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  77. if err != nil {
  78. return
  79. }
  80. latestDateStr = edbInfo.LatestDate
  81. latestValue = edbInfo.LatestValue
  82. //修改指标信息
  83. switch lang {
  84. case utils.EnLangVersion:
  85. edbInfo.EdbNameEn = req.EdbName
  86. edbInfo.UnitEn = req.Unit
  87. default:
  88. edbInfo.EdbName = req.EdbName
  89. edbInfo.Unit = req.Unit
  90. edbInfo.EdbNameSource = req.EdbName
  91. }
  92. edbInfo.Frequency = req.Frequency
  93. edbInfo.ClassifyId = req.ClassifyId
  94. edbInfo.ModifyTime = time.Now()
  95. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  96. if err != nil {
  97. return
  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. //判断计算指标是否被更换
  105. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  106. if err != nil {
  107. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  108. return
  109. }
  110. if count > 0 { // 指标未被替换,无需重新计算
  111. return
  112. }
  113. //删除,计算指标关联的,基础指标的关联关系
  114. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  115. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  116. if err != nil {
  117. return
  118. }
  119. //清空原有数据
  120. sql = ` DELETE FROM edb_data_predict_calculate_ljzzy WHERE edb_info_id = ? `
  121. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  122. if err != nil {
  123. return
  124. }
  125. //关联关系
  126. {
  127. calculateMappingItem := &EdbInfoCalculateMapping{
  128. EdbInfoCalculateMappingId: 0,
  129. EdbInfoId: edbInfo.EdbInfoId,
  130. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_LJZZY,
  131. SourceName: "预测累计值转月值",
  132. EdbCode: edbInfo.EdbCode,
  133. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  134. FromEdbCode: fromEdbInfo.EdbCode,
  135. FromEdbName: fromEdbInfo.EdbName,
  136. FromSource: fromEdbInfo.Source,
  137. FromSourceName: fromEdbInfo.SourceName,
  138. FromTag: "",
  139. Sort: 1,
  140. CreateTime: time.Now(),
  141. ModifyTime: time.Now(),
  142. }
  143. _, err = to.Insert(calculateMappingItem)
  144. if err != nil {
  145. return
  146. }
  147. }
  148. }
  149. //计算数据
  150. latestDateStr, latestValue, err = refreshAllPredictCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "")
  151. return
  152. }
  153. // RefreshAllPredictCalculateLjzzy 刷新全部累计值转月数据
  154. func RefreshAllPredictCalculateLjzzy(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  155. o := orm.NewOrm()
  156. to, err := o.Begin()
  157. if err != nil {
  158. return
  159. }
  160. defer func() {
  161. if err != nil {
  162. fmt.Println("refreshAllPredictCalculateLjzzy,Err:" + err.Error())
  163. _ = to.Rollback()
  164. } else {
  165. _ = to.Commit()
  166. }
  167. }()
  168. // 计算数据
  169. latestDateStr, latestValue, err = refreshAllPredictCalculateLjzzy(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate)
  170. return
  171. }
  172. func refreshAllPredictCalculateLjzzy(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  173. edbInfoIdStr := strconv.Itoa(edbInfoId)
  174. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, startDate)
  175. if err != nil {
  176. return
  177. }
  178. latestDateStr = fromEdbInfo.LatestDate
  179. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  180. dataLen := len(dataList)
  181. for i := 0; i < dataLen; i++ {
  182. item := dataList[i]
  183. //日其中获取年
  184. var itemDate time.Time
  185. itemDate, err = time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  186. if err != nil {
  187. return
  188. }
  189. year := itemDate.Year()
  190. month := int(itemDate.Month())
  191. if monthMap, yok := yearMap[year]; yok {
  192. monthMap[month] = item
  193. yearMap[year] = monthMap
  194. } else {
  195. monthMap = make(map[int]*EdbInfoSearchData)
  196. monthMap[month] = item
  197. yearMap[year] = monthMap
  198. }
  199. }
  200. addSql := ` INSERT INTO edb_data_predict_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  201. var isAdd bool
  202. //获取指标所有数据
  203. existDataList := make([]*EdbData, 0)
  204. dataTableName := GetEdbDataTableName(source, subSource)
  205. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  206. sql = fmt.Sprintf(sql, dataTableName)
  207. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  208. if err != nil {
  209. return
  210. }
  211. dataMap := make(map[string]string)
  212. removeDateMap := make(map[string]bool) //需要移除的日期
  213. for _, v := range existDataList {
  214. dataMap[v.DataTime] = v.Value
  215. removeDateMap[v.DataTime] = true
  216. }
  217. existDataMap := make(map[string]string)
  218. for yk, yv := range yearMap {
  219. _, oneMonthOk := yv[1]
  220. _, twoMonthOk := yv[2]
  221. if !oneMonthOk && !twoMonthOk {
  222. continue
  223. }
  224. for i := 1; i <= 12; i++ {
  225. fmt.Println(yk, i, yv[i])
  226. dataCurrentItem := yv[i]
  227. var date string
  228. var val float64
  229. if dataCurrentItem != nil {
  230. if i == 1 || i == 2 {
  231. if _, mok := yv[1]; mok { //1月有值
  232. if i == 1 {
  233. date = dataCurrentItem.DataTime
  234. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  235. }
  236. if i == 2 {
  237. dataOneItem := yv[1]
  238. date = dataCurrentItem.DataTime
  239. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  240. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  241. val, _ = twoMonth.Sub(oneMonth).Float64()
  242. }
  243. } else { //1月无值
  244. dataTwoItem := yv[2]
  245. if i == 1 {
  246. date = strconv.Itoa(yk) + "-01-31"
  247. a := decimal.NewFromFloat(dataTwoItem.Value)
  248. b := decimal.NewFromFloat(2.0)
  249. val, _ = a.Div(b).Float64()
  250. }
  251. if i == 2 {
  252. //1月无值:1月=2月/2
  253. {
  254. date = strconv.Itoa(yk) + "-01-31"
  255. a := decimal.NewFromFloat(dataTwoItem.Value)
  256. b := decimal.NewFromFloat(2.0)
  257. val, _ = a.Div(b).Float64()
  258. delete(removeDateMap, date)
  259. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  260. if !isAdd {
  261. isAdd = newAdd
  262. }
  263. addSql = tmpSql
  264. if tmpErr != nil {
  265. err = tmpErr
  266. return
  267. }
  268. }
  269. //end 1月无值
  270. date = dataCurrentItem.DataTime
  271. a := decimal.NewFromFloat(dataTwoItem.Value)
  272. b := decimal.NewFromFloat(2.0)
  273. val, _ = a.Div(b).Float64()
  274. }
  275. }
  276. } else {
  277. dataPreItem := yv[i-1]
  278. if dataPreItem != nil {
  279. date = dataCurrentItem.DataTime
  280. //val = dataCurrentItem.Value - dataPreItem.Value
  281. a := decimal.NewFromFloat(dataCurrentItem.Value)
  282. b := decimal.NewFromFloat(dataPreItem.Value)
  283. val, _ = a.Sub(b).Float64()
  284. }
  285. }
  286. }
  287. if date != "" {
  288. //saveValue := utils.SubFloatToString(val, 4)
  289. ////判断数据是否存在
  290. //if existVal, ok := dataMap[date]; !ok {
  291. // dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  292. // timestamp := dataTime.UnixNano() / 1e6
  293. // timeStr := fmt.Sprintf("%d", timestamp)
  294. // if _, existOk := existDataMap[date]; !existOk {
  295. // addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  296. // isAdd = true
  297. // }
  298. // existDataMap[date] = date
  299. //} else {
  300. // if existVal != saveValue {
  301. // sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  302. // sql = fmt.Sprintf(sql, dataTableName)
  303. // _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  304. // if err != nil {
  305. // return err
  306. // }
  307. // }
  308. //}
  309. delete(removeDateMap, date)
  310. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  311. if !isAdd {
  312. isAdd = newAdd
  313. }
  314. addSql = tmpSql
  315. if tmpErr != nil {
  316. err = tmpErr
  317. return
  318. }
  319. }
  320. }
  321. }
  322. if len(removeDateMap) > 0 {
  323. removeDateList := make([]string, 0) //需要移除的日期
  324. for k := range removeDateMap {
  325. removeDateList = append(removeDateList, k)
  326. }
  327. removeDateStr := strings.Join(removeDateList, `","`)
  328. removeDateStr = `"` + removeDateStr + `"`
  329. //如果拼接指标变更了,那么需要删除所有的指标数据
  330. tableName := GetEdbDataTableName(source, subSource)
  331. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  332. _, err = to.Raw(sql, edbInfoId).Exec()
  333. if err != nil {
  334. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  335. return
  336. }
  337. }
  338. if isAdd {
  339. addSql = strings.TrimRight(addSql, ",")
  340. _, err = to.Raw(addSql).Exec()
  341. if err != nil {
  342. fmt.Println("refreshAllPredictCalculateLjzzy add Err", err.Error())
  343. return
  344. }
  345. }
  346. //确定最终值
  347. var finalLast EdbInfoSearchData
  348. sql = ` SELECT data_time , value FROM edb_data_predict_calculate_ljzzy 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. }
  354. return
  355. } else {
  356. latestDateStr = finalLast.DataTime
  357. latestValue = finalLast.Value
  358. }
  359. return
  360. }