predict_edb_data_calculate_ljzzj.go 12 KB

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