predict_edb_data_calculate_ljzzj.go 12 KB

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