edb_data_calculate_ljznczj.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. // LjzNczj 累计值年初至今
  14. type LjzNczj struct {
  15. }
  16. // Add 添加
  17. func (obj LjzNczj) Add(params AddCalculateBatchParams) (edbInfo *EdbInfo, 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. if fromEdbInfo.Frequency != req.Frequency {
  27. errMsg = "生成指标频度与原指标频度不同"
  28. err = errors.New(errMsg)
  29. return
  30. }
  31. o := orm.NewOrm()
  32. to, err := o.Begin()
  33. if err != nil {
  34. return
  35. }
  36. defer func() {
  37. if err != nil {
  38. _ = to.Rollback()
  39. fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
  40. } else {
  41. _ = to.Commit()
  42. }
  43. }()
  44. edbInfo = &EdbInfo{
  45. //EdbInfoId: 0,
  46. SourceName: obj.GetSourceName(),
  47. Source: obj.GetSource(),
  48. EdbCode: edbCode,
  49. EdbName: req.EdbName,
  50. EdbNameSource: req.EdbName,
  51. Frequency: req.Frequency,
  52. Unit: req.Unit,
  53. StartDate: "",
  54. EndDate: "",
  55. ClassifyId: req.ClassifyId,
  56. SysUserId: params.SysUserId,
  57. SysUserRealName: params.SysUserRealName,
  58. UniqueCode: params.UniqueCode,
  59. CreateTime: time.Now(),
  60. ModifyTime: time.Now(),
  61. MinValue: 0,
  62. MaxValue: 0,
  63. CalculateFormula: req.Formula,
  64. EdbType: 2,
  65. Sort: 0,
  66. MoveType: 0,
  67. MoveFrequency: "",
  68. NoUpdate: 0,
  69. ServerUrl: "",
  70. EdbInfoType: 0,
  71. EdbNameEn: "",
  72. UnitEn: "",
  73. LatestDate: "",
  74. LatestValue: 0,
  75. ChartImage: "",
  76. Calendar: "",
  77. }
  78. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  79. if tmpErr != nil {
  80. err = tmpErr
  81. return
  82. }
  83. edbInfo.EdbInfoId = int(newEdbInfoId)
  84. //关联关系
  85. {
  86. calculateMappingItem := new(EdbInfoCalculateMapping)
  87. calculateMappingItem.CreateTime = time.Now()
  88. calculateMappingItem.ModifyTime = time.Now()
  89. calculateMappingItem.Sort = 1
  90. calculateMappingItem.EdbCode = edbCode
  91. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  92. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  93. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  94. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  95. calculateMappingItem.FromSource = fromEdbInfo.Source
  96. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  97. calculateMappingItem.FromTag = ""
  98. calculateMappingItem.Source = edbInfo.Source
  99. calculateMappingItem.SourceName = edbInfo.SourceName
  100. _, err = to.Insert(calculateMappingItem)
  101. if err != nil {
  102. return
  103. }
  104. }
  105. //计算数据
  106. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  107. return
  108. }
  109. // Edit 编辑
  110. func (obj LjzNczj) Edit(params EditCalculateBatchParams) (err error, errMsg string) {
  111. req := params.Req
  112. edbInfo := params.EdbInfo
  113. fromEdbInfo := params.FromEdbInfo
  114. if fromEdbInfo.Frequency == `年度` {
  115. errMsg = "年初至今累计值计算中,可选指标范围为非年度指标"
  116. err = errors.New(errMsg)
  117. return
  118. }
  119. if fromEdbInfo.Frequency != req.Frequency {
  120. errMsg = "生成指标频度与原指标频度不同"
  121. err = errors.New(errMsg)
  122. return
  123. }
  124. o := orm.NewOrm()
  125. to, err := o.Begin()
  126. if err != nil {
  127. return
  128. }
  129. defer func() {
  130. if err != nil {
  131. _ = to.Rollback()
  132. fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
  133. } else {
  134. _ = to.Commit()
  135. }
  136. }()
  137. tableName := GetEdbDataTableName(edbInfo.Source)
  138. var isRecalculate bool
  139. if edbInfo.Frequency != req.Frequency {
  140. isRecalculate = true
  141. }
  142. //修改指标信息
  143. edbInfo.EdbName = req.EdbName
  144. edbInfo.EdbNameSource = req.EdbName
  145. edbInfo.Frequency = req.Frequency
  146. edbInfo.Unit = req.Unit
  147. edbInfo.ClassifyId = req.ClassifyId
  148. edbInfo.ModifyTime = time.Now()
  149. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  150. if err != nil {
  151. return
  152. }
  153. var existCondition string
  154. var existPars []interface{}
  155. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  156. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  157. //判断计算指标是否被更换
  158. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  159. if err != nil {
  160. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  161. return
  162. }
  163. if count > 0 { // 指标未被替换,无需删除关联数据
  164. // 频度被换了,需要重新计算
  165. if isRecalculate {
  166. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  167. }
  168. return
  169. }
  170. //删除,计算指标关联的,基础指标的关联关系
  171. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  172. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  173. if err != nil {
  174. return
  175. }
  176. //清空原有数据
  177. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  178. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  179. if err != nil {
  180. return
  181. }
  182. //关联关系
  183. {
  184. calculateMappingItem := &EdbInfoCalculateMapping{
  185. EdbInfoCalculateMappingId: 0,
  186. EdbInfoId: edbInfo.EdbInfoId,
  187. Source: obj.GetSource(),
  188. SourceName: obj.GetSourceName(),
  189. EdbCode: edbInfo.EdbCode,
  190. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  191. FromEdbCode: fromEdbInfo.EdbCode,
  192. FromEdbName: fromEdbInfo.EdbName,
  193. FromSource: fromEdbInfo.Source,
  194. FromSourceName: fromEdbInfo.SourceName,
  195. FromTag: "",
  196. Sort: 1,
  197. CreateTime: time.Now(),
  198. ModifyTime: time.Now(),
  199. }
  200. _, err = to.Insert(calculateMappingItem)
  201. if err != nil {
  202. return
  203. }
  204. }
  205. //计算数据
  206. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  207. return
  208. }
  209. // Refresh 刷新
  210. func (obj LjzNczj) Refresh(params RefreshParams) (err error, errMsg string) {
  211. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  212. if err != nil {
  213. errMsg = "GetEdbInfoCalculateLjzNczjzyDetail Err:" + err.Error()
  214. return
  215. }
  216. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  217. if err != nil {
  218. errMsg = "GetEdbInfoById Err:" + err.Error()
  219. return
  220. }
  221. o := orm.NewOrm()
  222. to, err := o.Begin()
  223. if err != nil {
  224. return
  225. }
  226. defer func() {
  227. if err != nil {
  228. _ = to.Rollback()
  229. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  230. } else {
  231. _ = to.Commit()
  232. }
  233. }()
  234. // 计算数据
  235. err = obj.refresh(to, params.EdbInfo.EdbInfoId, params.EdbInfo.Source, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  236. return
  237. }
  238. // GetSource 获取来源编码id
  239. func (obj LjzNczj) GetSource() int {
  240. return utils.DATA_SOURCE_CALCULATE_LJZNCZJ
  241. }
  242. // GetSourceName 获取来源名称
  243. func (obj LjzNczj) GetSourceName() string {
  244. return utils.DATA_SOURCE_NAME_CALCULATE_LJZNCZJ
  245. }
  246. func (obj LjzNczj) refresh(to orm.TxOrmer, edbInfoId, source int, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (err error) {
  247. dataTableName := GetEdbDataTableName(source)
  248. edbInfoIdStr := strconv.Itoa(edbInfoId)
  249. //计算数据
  250. var condition string
  251. var pars []interface{}
  252. condition += " AND edb_info_id=? "
  253. pars = append(pars, fromEdbInfo.EdbInfoId)
  254. //if startDate != "" {
  255. // condition += " AND data_time>=? "
  256. // pars = append(pars, startDate)
  257. //}
  258. var isWeekData bool // 是否周度数据,如果是周度数据的话,是需要变频的,最后结果还需要除以7
  259. // 周度数据需要先变成日度的
  260. if fromEdbInfo.Frequency == `周度` {
  261. isWeekData = true
  262. }
  263. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 1)
  264. if err != nil {
  265. return err
  266. }
  267. fromEdbDataMap := make(map[string]float64)
  268. if isWeekData {
  269. dataList, err = HandleDataByLinearRegression(dataList, fromEdbDataMap)
  270. if err != nil {
  271. return
  272. }
  273. }
  274. //日度数据年初至今:日期同原日度数据。将每年1月1日(含)到日度数据所在日期含间的日度值,进行加总。
  275. //周度数据年初至今:日期同原周度数据。将周度值转成日度频率,空值用插值法插值,然后算法同日度年度至今,再除以7
  276. //月度/季度数据年初至今:日期同原月度/季度数据,将每年1月1日(含)到月度数据所在日期(含)之间的月度/季度值,进行加总
  277. //以此类推
  278. dateList := make([]time.Time, 0)
  279. valueMap := make(map[time.Time]float64)
  280. yearMap := make(map[int]float64)
  281. switch edbInfo.Frequency {
  282. case "周度":
  283. tmpDateDataMap := make(map[time.Time]float64)
  284. tmpDateList := make([]time.Time, 0)
  285. for _, item := range dataList {
  286. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  287. if tmpErr != nil {
  288. err = tmpErr
  289. return
  290. }
  291. var currTime time.Time
  292. // 周六周日,这是下一个周五的数据
  293. if itemDate.Weekday() == 0 {
  294. currTime = itemDate.AddDate(0, 0, 5)
  295. } else if itemDate.Weekday() == 6 {
  296. currTime = itemDate.AddDate(0, 0, 6)
  297. } else {
  298. currTime = itemDate.AddDate(0, 0, 5-int(itemDate.Weekday()))
  299. }
  300. year := itemDate.Year()
  301. yearVal, ok := yearMap[year]
  302. if ok {
  303. yearMap[year] = item.Value + yearVal
  304. } else {
  305. yearMap[year] = item.Value
  306. }
  307. if itemDate.Equal(currTime) {
  308. tmpDateDataMap[itemDate] = yearMap[year]
  309. tmpDateList = append(tmpDateList, itemDate)
  310. }
  311. }
  312. for _, currTime := range tmpDateList {
  313. dateList = append(dateList, currTime)
  314. valueMap[currTime] = tmpDateDataMap[currTime]
  315. }
  316. default:
  317. for _, item := range dataList {
  318. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  319. if tmpErr != nil {
  320. err = tmpErr
  321. return
  322. }
  323. year := itemDate.Year()
  324. yearVal, ok := yearMap[year]
  325. if ok {
  326. yearMap[year] = item.Value + yearVal
  327. } else {
  328. yearMap[year] = item.Value
  329. }
  330. valueMap[itemDate] = yearMap[year]
  331. dateList = append(dateList, itemDate)
  332. }
  333. }
  334. //获取指标所有数据
  335. existDataList := make([]*EdbData, 0)
  336. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  337. sql = fmt.Sprintf(sql, dataTableName)
  338. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  339. if err != nil {
  340. return err
  341. }
  342. existDataMap := make(map[string]string)
  343. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  344. for _, v := range existDataList {
  345. existDataMap[v.DataTime] = v.Value
  346. removeDataTimeMap[v.DataTime] = 1
  347. }
  348. needAddDateMap := make(map[time.Time]int)
  349. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  350. var isAdd bool
  351. for _, currTime := range dateList {
  352. currDateStr := currTime.Format(utils.FormatDate)
  353. existVal, ok := existDataMap[currDateStr]
  354. tmpVal, ok2 := valueMap[currTime]
  355. if !ok2 {
  356. err = errors.New("数据异常,date:" + currDateStr)
  357. return
  358. }
  359. var saveValue string
  360. if isWeekData { //周度指标转的话,最后结果要除以7
  361. saveValue = decimal.NewFromFloat(tmpVal).Div(decimal.NewFromInt(7)).Round(4).String()
  362. } else {
  363. saveValue = decimal.NewFromFloat(tmpVal).Round(4).String()
  364. }
  365. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  366. if ok {
  367. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  368. delete(removeDataTimeMap, currDateStr)
  369. if existVal != saveValue {
  370. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  371. sql = fmt.Sprintf(sql, dataTableName)
  372. _, err = to.Raw(sql, saveValue, edbInfoId, currDateStr).Exec()
  373. if err != nil {
  374. return
  375. }
  376. }
  377. continue
  378. }
  379. // 库中不存在该日期的数据
  380. timestamp := currTime.UnixNano() / 1e6
  381. timeStr := fmt.Sprintf("%d", timestamp)
  382. if _, existOk := needAddDateMap[currTime]; !existOk {
  383. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  384. isAdd = true
  385. }
  386. needAddDateMap[currTime] = 1
  387. }
  388. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  389. {
  390. removeDateList := make([]string, 0)
  391. for dateTime := range removeDataTimeMap {
  392. removeDateList = append(removeDateList, dateTime)
  393. }
  394. removeNum := len(removeDateList)
  395. if removeNum > 0 {
  396. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  397. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  398. if err != nil {
  399. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  400. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  401. return
  402. }
  403. }
  404. }
  405. if isAdd {
  406. addSql = strings.TrimRight(addSql, ",")
  407. _, err = to.Raw(addSql).Exec()
  408. if err != nil {
  409. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  410. return
  411. }
  412. }
  413. return
  414. }