edb_data_calculate_ljznczj.go 13 KB

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