edb_data_calculate_ljznczj.go 13 KB

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