predict_edb_data_calculate_ljzzj.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // PredictLjzzj 预测累计值转季度
  14. type PredictLjzzj struct {
  15. }
  16. // Add 添加
  17. func (obj PredictLjzzj) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  18. req := params.Req
  19. fromEdbInfo := params.FromEdbInfo
  20. edbCode := params.EdbCode
  21. if fromEdbInfo.Frequency != "季度" {
  22. errMsg = "请选择季度指标"
  23. err = errors.New(errMsg)
  24. return
  25. }
  26. o := orm.NewOrm()
  27. to, err := o.Begin()
  28. if err != nil {
  29. return
  30. }
  31. defer func() {
  32. if err != nil {
  33. _ = to.Rollback()
  34. fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
  35. } else {
  36. _ = to.Commit()
  37. }
  38. }()
  39. edbInfo = new(EdbInfo)
  40. edbInfo.Source = obj.GetSource()
  41. edbInfo.SourceName = obj.GetSourceName()
  42. edbInfo.EdbCode = edbCode
  43. edbInfo.EdbInfoType = 1
  44. edbInfo.EdbName = req.EdbName
  45. edbInfo.EdbNameSource = req.EdbName
  46. edbInfo.Frequency = req.Frequency
  47. edbInfo.Unit = req.Unit
  48. edbInfo.ClassifyId = req.ClassifyId
  49. edbInfo.SysUserId = params.SysUserId
  50. edbInfo.SysUserRealName = params.SysUserRealName
  51. edbInfo.CreateTime = time.Now()
  52. edbInfo.ModifyTime = time.Now()
  53. edbInfo.UniqueCode = params.UniqueCode
  54. edbInfo.CalculateFormula = req.Formula
  55. edbInfo.EdbNameEn = req.EdbName
  56. edbInfo.UnitEn = req.Unit
  57. edbInfo.EdbType = 2
  58. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE)
  59. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  60. if tmpErr != nil {
  61. err = tmpErr
  62. return
  63. }
  64. edbInfo.EdbInfoId = int(newEdbInfoId)
  65. //关联关系
  66. {
  67. calculateMappingItem := new(EdbInfoCalculateMapping)
  68. calculateMappingItem.CreateTime = time.Now()
  69. calculateMappingItem.ModifyTime = time.Now()
  70. calculateMappingItem.Sort = 1
  71. calculateMappingItem.EdbCode = edbCode
  72. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  73. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  74. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  75. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  76. calculateMappingItem.FromSource = fromEdbInfo.Source
  77. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  78. calculateMappingItem.FromTag = ""
  79. calculateMappingItem.Source = edbInfo.Source
  80. calculateMappingItem.SourceName = edbInfo.SourceName
  81. _, err = to.Insert(calculateMappingItem)
  82. if err != nil {
  83. return
  84. }
  85. }
  86. //计算数据
  87. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode)
  88. return
  89. }
  90. // Edit 编辑
  91. func (obj PredictLjzzj) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  92. req := params.Req
  93. edbInfo := params.EdbInfo
  94. fromEdbInfo := params.FromEdbInfo
  95. if fromEdbInfo.Frequency != "季度" {
  96. errMsg = "请选择季度指标"
  97. err = errors.New(errMsg)
  98. return
  99. }
  100. latestDateStr = edbInfo.LatestDate
  101. latestValue = edbInfo.LatestValue
  102. o := orm.NewOrm()
  103. to, err := o.Begin()
  104. if err != nil {
  105. return
  106. }
  107. defer func() {
  108. if err != nil {
  109. _ = to.Rollback()
  110. fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
  111. } else {
  112. _ = to.Commit()
  113. }
  114. }()
  115. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  116. //修改指标信息
  117. switch params.Lang {
  118. case utils.EnLangVersion:
  119. edbInfo.EdbNameEn = req.EdbName
  120. edbInfo.UnitEn = req.Unit
  121. default:
  122. edbInfo.EdbName = req.EdbName
  123. edbInfo.Unit = req.Unit
  124. edbInfo.EdbNameSource = req.EdbName
  125. }
  126. edbInfo.Frequency = req.Frequency
  127. edbInfo.ClassifyId = req.ClassifyId
  128. edbInfo.ModifyTime = time.Now()
  129. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  130. if err != nil {
  131. return
  132. }
  133. var existCondition string
  134. var existPars []interface{}
  135. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  136. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  137. //判断计算指标是否被更换
  138. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  139. if err != nil {
  140. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  141. return
  142. }
  143. if count > 0 { // 指标未被替换,无需重新计算
  144. return
  145. }
  146. //删除,计算指标关联的,基础指标的关联关系
  147. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  148. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  149. if err != nil {
  150. return
  151. }
  152. //清空原有数据
  153. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  154. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  155. if err != nil {
  156. return
  157. }
  158. //关联关系
  159. {
  160. calculateMappingItem := &EdbInfoCalculateMapping{
  161. EdbInfoCalculateMappingId: 0,
  162. EdbInfoId: edbInfo.EdbInfoId,
  163. Source: obj.GetSource(),
  164. SourceName: obj.GetSourceName(),
  165. EdbCode: edbInfo.EdbCode,
  166. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  167. FromEdbCode: fromEdbInfo.EdbCode,
  168. FromEdbName: fromEdbInfo.EdbName,
  169. FromSource: fromEdbInfo.Source,
  170. FromSourceName: fromEdbInfo.SourceName,
  171. FromTag: "",
  172. Sort: 1,
  173. CreateTime: time.Now(),
  174. ModifyTime: time.Now(),
  175. }
  176. _, err = to.Insert(calculateMappingItem)
  177. if err != nil {
  178. return
  179. }
  180. }
  181. //计算数据
  182. latestDateStr, latestValue, err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode)
  183. return
  184. }
  185. // Refresh 刷新
  186. func (obj PredictLjzzj) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  187. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  188. if err != nil {
  189. errMsg = "GetEdbInfoCalculateLjzzyDetail Err:" + err.Error()
  190. return
  191. }
  192. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  193. if err != nil {
  194. errMsg = "GetEdbInfoById Err:" + err.Error()
  195. return
  196. }
  197. o := orm.NewOrm()
  198. to, err := o.Begin()
  199. if err != nil {
  200. return
  201. }
  202. defer func() {
  203. if err != nil {
  204. _ = to.Rollback()
  205. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  206. } else {
  207. _ = to.Commit()
  208. }
  209. }()
  210. // 计算数据
  211. latestDateStr, latestValue, err = obj.refresh(to, params.EdbInfo.EdbInfoId, params.EdbInfo.Source, params.EdbInfo.SubSource, fromEdbInfo, params.EdbInfo.EdbCode)
  212. return
  213. }
  214. // GetSource 获取来源编码id
  215. func (obj PredictLjzzj) GetSource() int {
  216. return utils.DATA_SOURCE_PREDICT_CALCULATE_LJZZJ
  217. }
  218. // GetSourceName 获取来源名称
  219. func (obj PredictLjzzj) GetSourceName() string {
  220. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_LJZZJ
  221. }
  222. func (obj PredictLjzzj) refresh(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode string) (latestDateStr string, latestValue float64, err error) {
  223. dataTableName := GetEdbDataTableName(source, subSource)
  224. edbInfoIdStr := strconv.Itoa(edbInfoId)
  225. // 获取来源指标的数据
  226. dataList, err := GetPredictEdbDataListAll(fromEdbInfo, 1)
  227. if err != nil {
  228. return
  229. }
  230. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  231. dataLen := len(dataList)
  232. for i := 0; i < dataLen; i++ {
  233. item := dataList[i]
  234. //日其中获取年
  235. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  236. if tmpErr != nil {
  237. err = tmpErr
  238. return
  239. }
  240. year := itemDate.Year()
  241. quarter := utils.MonthQuarterMap[int(itemDate.Month())]
  242. if quarterMap, yok := yearMap[year]; yok {
  243. quarterMap[quarter] = item
  244. yearMap[year] = quarterMap
  245. } else {
  246. quarterMap = make(map[int]*EdbInfoSearchData)
  247. quarterMap[quarter] = item
  248. yearMap[year] = quarterMap
  249. }
  250. }
  251. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  252. var isAdd bool
  253. //获取指标所有数据
  254. existDataList := make([]*EdbData, 0)
  255. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  256. sql = fmt.Sprintf(sql, dataTableName)
  257. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  258. if err != nil {
  259. return
  260. }
  261. dataMap := make(map[string]string)
  262. removeDateMap := make(map[string]bool) //需要移除的日期
  263. for _, v := range existDataList {
  264. dataMap[v.DataTime] = v.Value
  265. removeDateMap[v.DataTime] = true
  266. }
  267. existDataMap := make(map[string]string)
  268. for yk, yv := range yearMap {
  269. _, oneQuarterOk := yv[1]
  270. _, twoQuarterOk := yv[2]
  271. if !oneQuarterOk && !twoQuarterOk {
  272. continue
  273. }
  274. for i := 1; i <= 4; i++ {
  275. fmt.Println(yk, i, yv[i])
  276. dataCurrentItem := yv[i]
  277. var date string
  278. var val float64
  279. if dataCurrentItem != nil {
  280. if i == 1 || i == 2 {
  281. if _, mok := yv[1]; mok { //第1个季度有值
  282. if i == 1 {
  283. date = dataCurrentItem.DataTime
  284. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  285. }
  286. if i == 2 {
  287. dataOneItem := yv[1]
  288. date = dataCurrentItem.DataTime
  289. twoQuarter := decimal.NewFromFloat(dataCurrentItem.Value)
  290. oneQuarter := decimal.NewFromFloat(dataOneItem.Value)
  291. val, _ = twoQuarter.Sub(oneQuarter).Float64()
  292. }
  293. } else { //第1个季度无值
  294. dataTwoItem := yv[2]
  295. if i == 1 {
  296. date = strconv.Itoa(yk) + "-03-31"
  297. a := decimal.NewFromFloat(dataTwoItem.Value)
  298. b := decimal.NewFromFloat(2.0)
  299. val, _ = a.Div(b).Float64()
  300. }
  301. if i == 2 {
  302. //第1个季度无值:第1个季度=第2个季度/2
  303. {
  304. date = strconv.Itoa(yk) + "-03-31"
  305. a := decimal.NewFromFloat(dataTwoItem.Value)
  306. b := decimal.NewFromFloat(2.0)
  307. val, _ = a.Div(b).Float64()
  308. // 有计算出来值,那么就从待删除指标中移除
  309. delete(removeDateMap, date)
  310. tmpSql, newAdd, tmpErr := obj.calculate(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. //end 第1个季度无值
  321. date = dataCurrentItem.DataTime
  322. a := decimal.NewFromFloat(dataTwoItem.Value)
  323. b := decimal.NewFromFloat(2.0)
  324. val, _ = a.Div(b).Float64()
  325. }
  326. }
  327. } else {
  328. dataPreItem := yv[i-1]
  329. if dataCurrentItem != nil && dataPreItem != nil {
  330. date = dataCurrentItem.DataTime
  331. //val = dataCurrentItem.Value - dataPreItem.Value
  332. a := decimal.NewFromFloat(dataCurrentItem.Value)
  333. b := decimal.NewFromFloat(dataPreItem.Value)
  334. val, _ = a.Sub(b).Float64()
  335. }
  336. }
  337. }
  338. if date != "" {
  339. // 有计算出来值,那么就从待删除指标中移除
  340. delete(removeDateMap, date)
  341. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  342. if !isAdd {
  343. isAdd = newAdd
  344. }
  345. addSql = tmpSql
  346. if tmpErr != nil {
  347. err = tmpErr
  348. return
  349. }
  350. }
  351. }
  352. }
  353. if len(removeDateMap) > 0 {
  354. removeDateList := make([]string, 0) //需要移除的日期
  355. for k := range removeDateMap {
  356. removeDateList = append(removeDateList, k)
  357. }
  358. removeDateStr := strings.Join(removeDateList, `","`)
  359. removeDateStr = `"` + removeDateStr + `"`
  360. //如果拼接指标变更了,那么需要删除所有的指标数据
  361. tableName := GetEdbDataTableName(source, subSource)
  362. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  363. _, err = to.Raw(sql, edbInfoId).Exec()
  364. if err != nil {
  365. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  366. return
  367. }
  368. }
  369. if isAdd {
  370. addSql = strings.TrimRight(addSql, ",")
  371. _, err = to.Raw(addSql).Exec()
  372. if err != nil {
  373. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  374. return
  375. }
  376. }
  377. //确定实际数据的最终值
  378. {
  379. var finalLast EdbInfoSearchData
  380. sql = fmt.Sprintf(` SELECT data_time , value FROM %s WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `, dataTableName)
  381. err = to.Raw(sql, edbInfoId, fromEdbInfo.LatestDate).QueryRow(&finalLast)
  382. if err != nil && err.Error() != utils.ErrNoRow() {
  383. return
  384. } else {
  385. latestDateStr = finalLast.DataTime
  386. latestValue = finalLast.Value
  387. }
  388. if err != nil {
  389. err = nil
  390. } else {
  391. latestDateStr = finalLast.DataTime
  392. latestValue = finalLast.Value
  393. }
  394. }
  395. return
  396. }
  397. func (obj PredictLjzzj) calculate(edbInfoId int, date, edbInfoIdStr, edbCode, dataTableName, addSql string, val float64, dataMap, existDataMap map[string]string, to orm.TxOrmer) (newSql string, isAdd bool, err error) {
  398. newSql = addSql
  399. saveValue := utils.SubFloatToString(val, 4)
  400. //判断数据是否存在
  401. if existVal, ok := dataMap[date]; !ok {
  402. dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  403. timestamp := dataTime.UnixNano() / 1e6
  404. timeStr := fmt.Sprintf("%d", timestamp)
  405. if _, existOk := existDataMap[date]; !existOk {
  406. newSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  407. isAdd = true
  408. }
  409. existDataMap[date] = date
  410. } else {
  411. if existVal != saveValue {
  412. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  413. sql = fmt.Sprintf(sql, dataTableName)
  414. _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  415. }
  416. }
  417. return
  418. }