predict_edb_data_calculate_ljzzy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 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.EdbType = 2
  45. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  46. if tmpErr != nil {
  47. err = tmpErr
  48. return
  49. }
  50. edbInfo.EdbInfoId = int(newEdbInfoId)
  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.Insert(calculateMappingItem)
  68. if err != nil {
  69. return
  70. }
  71. }
  72. } else {
  73. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  74. if err != nil {
  75. return
  76. }
  77. latestDateStr = edbInfo.LatestDate
  78. latestValue = edbInfo.LatestValue
  79. //修改指标信息
  80. edbInfo.EdbName = req.EdbName
  81. edbInfo.EdbNameSource = req.EdbName
  82. edbInfo.Frequency = req.Frequency
  83. edbInfo.Unit = req.Unit
  84. edbInfo.ClassifyId = req.ClassifyId
  85. edbInfo.ModifyTime = time.Now()
  86. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  87. if err != nil {
  88. return
  89. }
  90. var existCondition string
  91. var existPars []interface{}
  92. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  93. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  94. var count int
  95. //判断计算指标是否被更换
  96. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  97. if err != nil {
  98. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  99. return
  100. }
  101. if count > 0 { // 指标未被替换,无需重新计算
  102. return
  103. }
  104. //删除,计算指标关联的,基础指标的关联关系
  105. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  106. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  107. if err != nil {
  108. return
  109. }
  110. //清空原有数据
  111. sql = ` DELETE FROM edb_data_predict_calculate_ljzzy WHERE edb_info_id = ? `
  112. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  113. if err != nil {
  114. return
  115. }
  116. //关联关系
  117. {
  118. calculateMappingItem := &EdbInfoCalculateMapping{
  119. EdbInfoCalculateMappingId: 0,
  120. EdbInfoId: edbInfo.EdbInfoId,
  121. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_LJZZY,
  122. SourceName: "预测累计值转月值",
  123. EdbCode: edbInfo.EdbCode,
  124. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  125. FromEdbCode: fromEdbInfo.EdbCode,
  126. FromEdbName: fromEdbInfo.EdbName,
  127. FromSource: fromEdbInfo.Source,
  128. FromSourceName: fromEdbInfo.SourceName,
  129. FromTag: "",
  130. Sort: 1,
  131. CreateTime: time.Now(),
  132. ModifyTime: time.Now(),
  133. }
  134. _, err = to.Insert(calculateMappingItem)
  135. if err != nil {
  136. return
  137. }
  138. }
  139. }
  140. //计算数据
  141. latestDateStr, latestValue, err = refreshAllPredictCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
  142. return
  143. }
  144. // RefreshAllPredictCalculateLjzzy 刷新全部累计值转月数据
  145. func RefreshAllPredictCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  146. o := orm.NewOrm()
  147. to, err := o.Begin()
  148. if err != nil {
  149. return
  150. }
  151. defer func() {
  152. if err != nil {
  153. fmt.Println("refreshAllPredictCalculateLjzzy,Err:" + err.Error())
  154. _ = to.Rollback()
  155. } else {
  156. _ = to.Commit()
  157. }
  158. }()
  159. // 计算数据
  160. latestDateStr, latestValue, err = refreshAllPredictCalculateLjzzy(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
  161. return
  162. }
  163. func refreshAllPredictCalculateLjzzy(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (latestDateStr string, latestValue float64, err error) {
  164. edbInfoIdStr := strconv.Itoa(edbInfoId)
  165. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, startDate)
  166. if err != nil {
  167. return
  168. }
  169. latestDateStr = fromEdbInfo.LatestDate
  170. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  171. dataLen := len(dataList)
  172. for i := 0; i < dataLen; i++ {
  173. item := dataList[i]
  174. //日其中获取年
  175. var itemDate time.Time
  176. itemDate, err = time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  177. if err != nil {
  178. return
  179. }
  180. year := itemDate.Year()
  181. month := int(itemDate.Month())
  182. if monthMap, yok := yearMap[year]; yok {
  183. monthMap[month] = item
  184. yearMap[year] = monthMap
  185. } else {
  186. monthMap = make(map[int]*EdbInfoSearchData)
  187. monthMap[month] = item
  188. yearMap[year] = monthMap
  189. }
  190. }
  191. addSql := ` INSERT INTO edb_data_predict_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  192. var isAdd bool
  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. dataMap := make(map[string]string)
  203. for _, v := range existDataList {
  204. dataMap[v.DataTime] = v.Value
  205. }
  206. existDataMap := make(map[string]string)
  207. for yk, yv := range yearMap {
  208. _, oneMonthOk := yv[1]
  209. _, twoMonthOk := yv[2]
  210. if !oneMonthOk && !twoMonthOk {
  211. continue
  212. }
  213. for i := 1; i <= 12; i++ {
  214. fmt.Println(yk, i, yv[i])
  215. dataCurrentItem := yv[i]
  216. var date string
  217. var val float64
  218. if dataCurrentItem != nil {
  219. if i == 1 || i == 2 {
  220. if _, mok := yv[1]; mok { //1月有值
  221. if i == 1 {
  222. date = dataCurrentItem.DataTime
  223. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  224. }
  225. if i == 2 {
  226. dataOneItem := yv[1]
  227. date = dataCurrentItem.DataTime
  228. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  229. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  230. val, _ = twoMonth.Sub(oneMonth).Float64()
  231. }
  232. } else { //1月无值
  233. dataTwoItem := yv[2]
  234. if i == 1 {
  235. date = strconv.Itoa(yk) + "-01-31"
  236. a := decimal.NewFromFloat(dataTwoItem.Value)
  237. b := decimal.NewFromFloat(2.0)
  238. val, _ = a.Div(b).Float64()
  239. }
  240. if i == 2 {
  241. //1月无值:1月=2月/2
  242. {
  243. date = strconv.Itoa(yk) + "-01-31"
  244. a := decimal.NewFromFloat(dataTwoItem.Value)
  245. b := decimal.NewFromFloat(2.0)
  246. val, _ = a.Div(b).Float64()
  247. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  248. if !isAdd {
  249. isAdd = newAdd
  250. }
  251. addSql = tmpSql
  252. if tmpErr != nil {
  253. err = tmpErr
  254. return
  255. }
  256. }
  257. //end 1月无值
  258. date = dataCurrentItem.DataTime
  259. a := decimal.NewFromFloat(dataTwoItem.Value)
  260. b := decimal.NewFromFloat(2.0)
  261. val, _ = a.Div(b).Float64()
  262. }
  263. }
  264. } else {
  265. dataPreItem := yv[i-1]
  266. if dataPreItem != nil {
  267. date = dataCurrentItem.DataTime
  268. //val = dataCurrentItem.Value - dataPreItem.Value
  269. a := decimal.NewFromFloat(dataCurrentItem.Value)
  270. b := decimal.NewFromFloat(dataPreItem.Value)
  271. val, _ = a.Sub(b).Float64()
  272. }
  273. }
  274. }
  275. if date != "" {
  276. //saveValue := utils.SubFloatToString(val, 4)
  277. ////判断数据是否存在
  278. //if existVal, ok := dataMap[date]; !ok {
  279. // dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  280. // timestamp := dataTime.UnixNano() / 1e6
  281. // timeStr := fmt.Sprintf("%d", timestamp)
  282. // if _, existOk := existDataMap[date]; !existOk {
  283. // addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  284. // isAdd = true
  285. // }
  286. // existDataMap[date] = date
  287. //} else {
  288. // if existVal != saveValue {
  289. // sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  290. // sql = fmt.Sprintf(sql, dataTableName)
  291. // _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  292. // if err != nil {
  293. // return err
  294. // }
  295. // }
  296. //}
  297. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  298. if !isAdd {
  299. isAdd = newAdd
  300. }
  301. addSql = tmpSql
  302. if tmpErr != nil {
  303. err = tmpErr
  304. return
  305. }
  306. }
  307. }
  308. }
  309. if isAdd {
  310. addSql = strings.TrimRight(addSql, ",")
  311. _, err = to.Raw(addSql).Exec()
  312. if err != nil {
  313. fmt.Println("refreshAllPredictCalculateLjzzy add Err", err.Error())
  314. return
  315. }
  316. }
  317. //确定最终值
  318. var finalLast EdbInfoSearchData
  319. sql = ` SELECT data_time , value FROM edb_data_predict_calculate_ljzzy WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `
  320. tmpErr := to.Raw(sql, edbInfoId, latestDateStr).QueryRow(&finalLast)
  321. if tmpErr != nil {
  322. if tmpErr.Error() != utils.ErrNoRow() {
  323. err = tmpErr
  324. }
  325. return
  326. } else {
  327. latestDateStr = finalLast.DataTime
  328. latestValue = finalLast.Value
  329. }
  330. return
  331. }