predict_edb_data_calculate_ljzzj.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. for _, v := range existDataList {
  263. dataMap[v.DataTime] = v.Value
  264. }
  265. existDataMap := make(map[string]string)
  266. for yk, yv := range yearMap {
  267. _, oneQuarterOk := yv[1]
  268. _, twoQuarterOk := yv[2]
  269. if !oneQuarterOk && !twoQuarterOk {
  270. continue
  271. }
  272. for i := 1; i <= 4; i++ {
  273. fmt.Println(yk, i, yv[i])
  274. dataCurrentItem := yv[i]
  275. var date string
  276. var val float64
  277. if dataCurrentItem != nil {
  278. if i == 1 || i == 2 {
  279. if _, mok := yv[1]; mok { //第1个季度有值
  280. if i == 1 {
  281. date = dataCurrentItem.DataTime
  282. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  283. }
  284. if i == 2 {
  285. dataOneItem := yv[1]
  286. date = dataCurrentItem.DataTime
  287. twoQuarter := decimal.NewFromFloat(dataCurrentItem.Value)
  288. oneQuarter := decimal.NewFromFloat(dataOneItem.Value)
  289. val, _ = twoQuarter.Sub(oneQuarter).Float64()
  290. }
  291. } else { //第1个季度无值
  292. dataTwoItem := yv[2]
  293. if i == 1 {
  294. date = strconv.Itoa(yk) + "-03-31"
  295. a := decimal.NewFromFloat(dataTwoItem.Value)
  296. b := decimal.NewFromFloat(2.0)
  297. val, _ = a.Div(b).Float64()
  298. }
  299. if i == 2 {
  300. //第1个季度无值:第1个季度=第2个季度/2
  301. {
  302. date = strconv.Itoa(yk) + "-03-31"
  303. a := decimal.NewFromFloat(dataTwoItem.Value)
  304. b := decimal.NewFromFloat(2.0)
  305. val, _ = a.Div(b).Float64()
  306. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  307. if !isAdd {
  308. isAdd = newAdd
  309. }
  310. addSql = tmpSql
  311. if tmpErr != nil {
  312. err = tmpErr
  313. return
  314. }
  315. }
  316. //end 第1个季度无值
  317. date = dataCurrentItem.DataTime
  318. a := decimal.NewFromFloat(dataTwoItem.Value)
  319. b := decimal.NewFromFloat(2.0)
  320. val, _ = a.Div(b).Float64()
  321. }
  322. }
  323. } else {
  324. dataPreItem := yv[i-1]
  325. if dataCurrentItem != nil && dataPreItem != nil {
  326. date = dataCurrentItem.DataTime
  327. //val = dataCurrentItem.Value - dataPreItem.Value
  328. a := decimal.NewFromFloat(dataCurrentItem.Value)
  329. b := decimal.NewFromFloat(dataPreItem.Value)
  330. val, _ = a.Sub(b).Float64()
  331. }
  332. }
  333. }
  334. if date != "" {
  335. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  336. if !isAdd {
  337. isAdd = newAdd
  338. }
  339. addSql = tmpSql
  340. if tmpErr != nil {
  341. err = tmpErr
  342. return
  343. }
  344. }
  345. }
  346. }
  347. if isAdd {
  348. addSql = strings.TrimRight(addSql, ",")
  349. _, err = to.Raw(addSql).Exec()
  350. if err != nil {
  351. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  352. return
  353. }
  354. }
  355. //确定实际数据的最终值
  356. {
  357. var finalLast EdbInfoSearchData
  358. sql = fmt.Sprintf(` SELECT data_time , value FROM %s WHERE edb_info_id=? and data_time<=? ORDER BY data_time DESC `, dataTableName)
  359. err = to.Raw(sql, edbInfoId, fromEdbInfo.LatestDate).QueryRow(&finalLast)
  360. if err != nil && err.Error() != utils.ErrNoRow() {
  361. return
  362. } else {
  363. latestDateStr = finalLast.DataTime
  364. latestValue = finalLast.Value
  365. }
  366. if err != nil {
  367. err = nil
  368. } else {
  369. latestDateStr = finalLast.DataTime
  370. latestValue = finalLast.Value
  371. }
  372. }
  373. return
  374. }
  375. 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) {
  376. newSql = addSql
  377. saveValue := utils.SubFloatToString(val, 4)
  378. //判断数据是否存在
  379. if existVal, ok := dataMap[date]; !ok {
  380. dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  381. timestamp := dataTime.UnixNano() / 1e6
  382. timeStr := fmt.Sprintf("%d", timestamp)
  383. if _, existOk := existDataMap[date]; !existOk {
  384. newSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  385. isAdd = true
  386. }
  387. existDataMap[date] = date
  388. } else {
  389. if existVal != saveValue {
  390. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  391. sql = fmt.Sprintf(sql, dataTableName)
  392. _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  393. }
  394. }
  395. return
  396. }