stl.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. package stl
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/models/data_manage"
  6. "eta/eta_api/models/data_manage/stl"
  7. "eta/eta_api/models/data_manage/stl/request"
  8. "eta/eta_api/models/data_manage/stl/response"
  9. "eta/eta_api/services/data"
  10. "eta/eta_api/services/data/data_manage_permission"
  11. "eta/eta_api/services/elastic"
  12. "eta/eta_api/utils"
  13. "fmt"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/rdlucklib/rdluck_tools/paging"
  21. "github.com/tealeg/xlsx"
  22. )
  23. const (
  24. ALL_DATE = iota + 1
  25. LAST_N_YEARS
  26. RANGE_DATE
  27. RANGE_DATE_TO_NOW
  28. )
  29. var EDB_DATA_CALCULATE_STL_TREND_CACHE = `eta:stl_decompose:trend:config_id:`
  30. var EDB_DATA_CALCULATE_STL_SEASONAL_CACHE = `eta:stl_decompose:seasonal:config_id:`
  31. var EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE = `eta:stl_decompose:residual:config_id:`
  32. func GenerateStlEdbData(req *request.StlConfigReq, adminId int) (resp *response.StlPreviewResp, msg string, err error) {
  33. config, err := stl.GetCalculateStlConfigById(req.CalculateStlConfigId)
  34. if err != nil {
  35. if err.Error() == utils.ErrNoRow() {
  36. msg = "配置信息不存在,请重新计算"
  37. return
  38. }
  39. msg = "获取配置信息失败"
  40. return
  41. }
  42. var confReq request.StlConfigReq
  43. if err = json.Unmarshal([]byte(config.Config), &confReq); err != nil {
  44. msg = "预览失败"
  45. err = fmt.Errorf("配置信息解析失败, err:%s", err.Error())
  46. return
  47. }
  48. edbInfo, err := data_manage.GetEdbInfoById(confReq.EdbInfoId)
  49. if err != nil {
  50. if err.Error() == utils.ErrNoRow() {
  51. msg = "指标不存在"
  52. return
  53. }
  54. msg = "获取指标信息失败"
  55. return
  56. }
  57. var condition string
  58. var pars []interface{}
  59. switch confReq.DataRangeType {
  60. case ALL_DATE:
  61. case LAST_N_YEARS:
  62. condition += " AND data_time >=?"
  63. year := time.Now().Year()
  64. lastDate := time.Date(year-confReq.LastNYear, 1, 1, 0, 0, 0, 0, time.Local)
  65. pars = append(pars, lastDate)
  66. case RANGE_DATE:
  67. condition = " AND data_time >=? AND data_time <=?"
  68. pars = append(pars, confReq.StartDate, confReq.EndDate)
  69. case RANGE_DATE_TO_NOW:
  70. condition = " AND data_time >=?"
  71. pars = append(pars, confReq.StartDate)
  72. }
  73. condition += " AND edb_code =?"
  74. pars = append(pars, edbInfo.EdbCode)
  75. edbData, err := data_manage.GetAllEdbDataListByCondition(condition, pars, edbInfo.Source, edbInfo.SubSource)
  76. if err != nil {
  77. msg = "获取指标数据失败"
  78. return
  79. }
  80. var condMsg string
  81. if confReq.Period < 2 || confReq.Period > len(edbData) {
  82. condMsg += "period必须是一个大于等于2的正整数,且必须小于时间序列的长度"
  83. }
  84. if confReq.Seasonal < 3 || confReq.Seasonal%2 == 0 || confReq.Seasonal <= confReq.Period {
  85. if condMsg != "" {
  86. condMsg += "\n"
  87. }
  88. condMsg += "seasonal必须是一个大于等于3的奇整数,且必须大于period"
  89. }
  90. if confReq.Trend < 3 || confReq.Trend%2 == 0 || confReq.Trend <= confReq.Period {
  91. if condMsg != "" {
  92. condMsg += "\n"
  93. }
  94. condMsg += "trend必须是一个大于等于3的奇整数,且必须大于period"
  95. }
  96. if confReq.Fraction < 0 || confReq.Fraction > 1 {
  97. if condMsg != "" {
  98. condMsg += "\n"
  99. }
  100. condMsg += "fraction必须是一个介于[0-1]之间"
  101. }
  102. if 1 > confReq.TrendDeg || confReq.TrendDeg > 5 {
  103. if condMsg != "" {
  104. condMsg += "\n"
  105. }
  106. condMsg += "trend_deg请设置成1-5的整数"
  107. }
  108. if 1 > confReq.SeasonalDeg || confReq.SeasonalDeg > 5 {
  109. if condMsg != "" {
  110. condMsg += "\n"
  111. }
  112. condMsg += "seasonal_deg请设置成1-5的整数"
  113. }
  114. if 1 > confReq.LowPassDeg || confReq.LowPassDeg > 5 {
  115. if condMsg != "" {
  116. condMsg += "\n"
  117. }
  118. condMsg += "low_pass_deg请设置成1-5的整数"
  119. }
  120. if condMsg != "" {
  121. msg = condMsg
  122. err = fmt.Errorf("参数错误")
  123. return
  124. }
  125. dir, _ := os.Executable()
  126. exPath := filepath.Dir(dir) + "/static/stl_tmp"
  127. err = CheckOsPathAndMake(exPath)
  128. if err != nil {
  129. msg = "计算失败"
  130. return
  131. }
  132. loadFilePath := exPath + "/" + strconv.Itoa(adminId) + "_" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  133. err = SaveToExcel(edbData, loadFilePath)
  134. if err != nil {
  135. msg = "保存数据到Excel失败"
  136. return
  137. }
  138. defer os.Remove(loadFilePath)
  139. saveFilePath := exPath + "/" + strconv.Itoa(adminId) + "_" + time.Now().Format(utils.FormatDateTimeUnSpace) + "_res" + ".xlsx"
  140. result, err := execStlPythonCode(loadFilePath, saveFilePath, confReq.Period, confReq.Seasonal, confReq.Trend, confReq.TrendDeg, confReq.SeasonalDeg, confReq.LowPassDeg, confReq.Fraction, confReq.Robust)
  141. if err != nil {
  142. msg = "计算失败,请重新选择指标和参数后计算"
  143. }
  144. trendChart, seasonalChart, residualChart, err := ParseStlExcel(saveFilePath)
  145. if err != nil {
  146. msg = "解析Excel失败"
  147. return
  148. }
  149. defer os.Remove(saveFilePath)
  150. resp = new(response.StlPreviewResp)
  151. resp.OriginEdbInfo.Title = edbInfo.EdbName
  152. resp.OriginEdbInfo.Frequency = edbInfo.Frequency
  153. resp.OriginEdbInfo.Unit = edbInfo.Unit
  154. resp.OriginEdbInfo.DataList = formatEdbData(edbData)
  155. resp.TrendChartInfo.DataList = trendChart.DataList
  156. resp.TrendChartInfo.Title = edbInfo.EdbName + "Trend"
  157. resp.TrendChartInfo.Frequency = edbInfo.Frequency
  158. resp.TrendChartInfo.Unit = edbInfo.Unit
  159. resp.SeasonalChartInfo.DataList = seasonalChart.DataList
  160. resp.SeasonalChartInfo.Title = edbInfo.EdbName + "Seasonal"
  161. resp.SeasonalChartInfo.Frequency = edbInfo.Frequency
  162. resp.SeasonalChartInfo.Unit = edbInfo.Unit
  163. resp.ResidualChartInfo.DataList = residualChart.DataList
  164. resp.ResidualChartInfo.Title = edbInfo.EdbName + "Residual"
  165. resp.ResidualChartInfo.Frequency = edbInfo.Frequency
  166. resp.ResidualChartInfo.Unit = edbInfo.Unit
  167. resp.EvaluationResult.Mean = strconv.FormatFloat(result.ResidualMean, 'f', 4, 64)
  168. resp.EvaluationResult.Std = strconv.FormatFloat(result.ResidualVar, 'f', 4, 64)
  169. resp.EvaluationResult.AdfPValue = strconv.FormatFloat(result.AdfPValue, 'f', -1, 64)
  170. resp.EvaluationResult.LjungBoxPValue = strconv.FormatFloat(result.LbTestPValue, 'f', -1, 64)
  171. bTrend, _ := json.Marshal(trendChart.DataList)
  172. bSeasonal, _ := json.Marshal(seasonalChart.DataList)
  173. bResidual, _ := json.Marshal(residualChart.DataList)
  174. utils.Rc.Put(EDB_DATA_CALCULATE_STL_TREND_CACHE+strconv.Itoa(confReq.CalculateStlConfigId), bTrend, time.Hour*2)
  175. utils.Rc.Put(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE+strconv.Itoa(confReq.CalculateStlConfigId), bSeasonal, time.Hour*2)
  176. utils.Rc.Put(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE+strconv.Itoa(confReq.CalculateStlConfigId), bResidual, time.Hour*2)
  177. return
  178. }
  179. func formatEdbData(items []*data_manage.EdbData) []*response.EdbData {
  180. res := make([]*response.EdbData, 0, len(items))
  181. for _, item := range items {
  182. t, _ := time.Parse(utils.FormatDate, item.DataTime)
  183. res = append(res, &response.EdbData{
  184. DataTime: item.DataTime,
  185. Value: strconv.FormatFloat(item.Value, 'f', -1, 64),
  186. DataTimestamp: t.UnixMilli(),
  187. })
  188. }
  189. return res
  190. }
  191. func CheckOsPathAndMake(path string) (err error) {
  192. if _, er := os.Stat(path); os.IsNotExist(er) {
  193. err = os.MkdirAll(path, os.ModePerm)
  194. }
  195. return
  196. }
  197. func ParseStlExcel(excelPath string) (TrendChart, SeasonalChart, ResidualChart response.ChartEdbInfo, err error) {
  198. file, err := xlsx.OpenFile(excelPath)
  199. if err != nil {
  200. return
  201. }
  202. for _, sheet := range file.Sheets {
  203. switch sheet.Name {
  204. case "季节":
  205. for i, row := range sheet.Rows {
  206. if i == 0 {
  207. continue
  208. }
  209. var date string
  210. var dataTimestamp int64
  211. if row.Cells[0].Type() == xlsx.CellTypeNumeric {
  212. dataNum, _ := strconv.ParseFloat(row.Cells[0].Value, 64)
  213. tmpTime := xlsx.TimeFromExcelTime(dataNum, false)
  214. date = tmpTime.Format(utils.FormatDate)
  215. dataTimestamp = tmpTime.UnixMilli()
  216. } else {
  217. timeDate, _ := time.Parse(utils.FormatDateTime, date)
  218. date = timeDate.Format(utils.FormatDate)
  219. dataTimestamp = timeDate.UnixMilli()
  220. }
  221. fv, _ := row.Cells[1].Float()
  222. value := strconv.FormatFloat(fv, 'f', 4, 64)
  223. SeasonalChart.DataList = append(SeasonalChart.DataList, &response.EdbData{DataTime: date, Value: value, DataTimestamp: dataTimestamp})
  224. }
  225. case "趋势":
  226. for i, row := range sheet.Rows {
  227. if i == 0 {
  228. continue
  229. }
  230. var date string
  231. var dataTimestamp int64
  232. if row.Cells[0].Type() == xlsx.CellTypeNumeric {
  233. dataNum, _ := strconv.ParseFloat(row.Cells[0].Value, 64)
  234. tmpTime := xlsx.TimeFromExcelTime(dataNum, false)
  235. date = tmpTime.Format(utils.FormatDate)
  236. dataTimestamp = tmpTime.UnixMilli()
  237. } else {
  238. timeDate, _ := time.Parse(utils.FormatDateTime, date)
  239. date = timeDate.Format(utils.FormatDate)
  240. dataTimestamp = timeDate.UnixMilli()
  241. }
  242. fv, _ := row.Cells[1].Float()
  243. value := strconv.FormatFloat(fv, 'f', 4, 64)
  244. TrendChart.DataList = append(TrendChart.DataList, &response.EdbData{DataTime: date, Value: value, DataTimestamp: dataTimestamp})
  245. }
  246. case "残差":
  247. for i, row := range sheet.Rows {
  248. if i == 0 {
  249. continue
  250. }
  251. var date string
  252. var dataTimestamp int64
  253. if row.Cells[0].Type() == xlsx.CellTypeNumeric {
  254. dataNum, _ := strconv.ParseFloat(row.Cells[0].Value, 64)
  255. tmpTime := xlsx.TimeFromExcelTime(dataNum, false)
  256. date = tmpTime.Format(utils.FormatDate)
  257. dataTimestamp = tmpTime.UnixMilli()
  258. } else {
  259. timeDate, _ := time.Parse(utils.FormatDateTime, date)
  260. date = timeDate.Format(utils.FormatDate)
  261. dataTimestamp = timeDate.UnixMilli()
  262. }
  263. fv, _ := row.Cells[1].Float()
  264. value := strconv.FormatFloat(fv, 'f', 4, 64)
  265. ResidualChart.DataList = append(ResidualChart.DataList, &response.EdbData{DataTime: date, Value: value, DataTimestamp: dataTimestamp})
  266. }
  267. }
  268. }
  269. return
  270. }
  271. func SaveToExcel(data []*data_manage.EdbData, filePath string) (err error) {
  272. xlsxFile := xlsx.NewFile()
  273. sheetNew, err := xlsxFile.AddSheet("Tmp")
  274. if err != nil {
  275. return
  276. }
  277. titleRow := sheetNew.AddRow()
  278. titleRow.AddCell().SetString("日期")
  279. titleRow.AddCell().SetString("值")
  280. for i, d := range data {
  281. row := sheetNew.Row(i + 1)
  282. row.AddCell().SetString(d.DataTime)
  283. row.AddCell().SetFloat(d.Value)
  284. }
  285. err = xlsxFile.Save(filePath)
  286. if err != nil {
  287. return
  288. }
  289. return
  290. }
  291. type STLResult struct {
  292. ResidualMean float64 `json:"residual_mean"`
  293. ResidualVar float64 `json:"residual_var"`
  294. AdfPValue float64 `json:"adf_p_value"`
  295. LbTestPValue float64 `json:"lb_test_p_value"`
  296. LbTestStat float64 `json:"lb_test_stat"`
  297. }
  298. func execStlPythonCode(path, toPath string, period, seasonal, trend, trendDeg, seasonalDeg, lowPassDeg int, fraction float64, robust bool) (stlResult *STLResult, err error) {
  299. pythonCode := `
  300. import pandas as pd
  301. from statsmodels.tsa.seasonal import STL
  302. from statsmodels.nonparametric.smoothers_lowess import lowess
  303. from statsmodels.tsa.stattools import adfuller
  304. from statsmodels.stats.diagnostic import acorr_ljungbox
  305. import numpy as np
  306. import json
  307. import warnings
  308. warnings.filterwarnings('ignore')
  309. file_path = r"%s"
  310. df = pd.read_excel(file_path, parse_dates=['日期'])
  311. df.set_index('日期', inplace=True)
  312. period = %d
  313. seasonal = %d
  314. trend = %d
  315. fraction = %g
  316. seasonal_deg = %d
  317. trend_deg = %d
  318. low_pass_deg = %d
  319. robust = %s
  320. stl = STL(
  321. df['值'],
  322. period=period,
  323. seasonal=seasonal,
  324. trend=trend,
  325. low_pass=None,
  326. seasonal_deg=seasonal_deg,
  327. trend_deg=trend_deg,
  328. low_pass_deg=low_pass_deg,
  329. seasonal_jump=1,
  330. trend_jump=1,
  331. low_pass_jump=1,
  332. robust=robust
  333. )
  334. result = stl.fit()
  335. smoothed = lowess(df['值'], df.index, frac=fraction)
  336. trend_lowess = smoothed[:, 1]
  337. # 季节图
  338. seasonal_component = result.seasonal
  339. # 趋势图
  340. trend_lowess_series = pd.Series(trend_lowess, index=df.index)
  341. # 残差图
  342. residual_component = df['值'] - trend_lowess - seasonal_component
  343. # 计算打印残差的均值
  344. residual_mean = np.mean(residual_component)
  345. # 计算打印残差的方差
  346. residual_var = np.std(residual_component)
  347. # 计算打印残差的ADF检验结果, 输出p-value
  348. adf_result = adfuller(residual_component)
  349. # 根据p-value判断是否平稳
  350. lb_test = acorr_ljungbox(residual_component, lags=period, return_df=True)
  351. output_file = r"%s"
  352. with pd.ExcelWriter(output_file) as writer:
  353. # 保存季节图
  354. pd.Series(seasonal_component, index=df.index, name='值').to_frame().reset_index().rename(columns={'index': '日期'}).to_excel(writer, sheet_name='季节', index=False)
  355. # 保存趋势图
  356. trend_lowess_series.to_frame(name='值').reset_index().rename(columns={'index': '日期'}).to_excel(writer, sheet_name='趋势', index=False)
  357. # 保存残差图
  358. pd.Series(residual_component, index=df.index, name='值').to_frame().reset_index().rename(columns={'index': '日期'}).to_excel(writer, sheet_name='残差', index=False)
  359. output = json.dumps({
  360. 'residual_mean': residual_mean,
  361. 'residual_var': residual_var,
  362. 'adf_p_value': adf_result[1],
  363. 'lb_test_p_value': lb_test['lb_pvalue'].values[0],
  364. 'lb_test_stat': lb_test['lb_stat'].values[0]
  365. })
  366. print(output)
  367. `
  368. robustStr := "True"
  369. if !robust {
  370. robustStr = "False"
  371. }
  372. pythonCode = fmt.Sprintf(pythonCode, path, period, seasonal, trend, fraction, seasonalDeg, trendDeg, lowPassDeg, robustStr, toPath)
  373. cmd := exec.Command(`python3`, "-c", pythonCode)
  374. output, err := cmd.CombinedOutput()
  375. if err != nil {
  376. return
  377. }
  378. defer cmd.Process.Kill()
  379. if err = json.Unmarshal(output, &stlResult); err != nil {
  380. return
  381. }
  382. return
  383. }
  384. func SaveStlConfig(req *request.StlConfigReq, adminId int) (configId int64, msg string, err error) {
  385. edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
  386. if err != nil {
  387. if err.Error() == utils.ErrNoRow() {
  388. msg = "指标不存在"
  389. return
  390. }
  391. msg = "获取指标信息失败"
  392. return
  393. }
  394. var condition string
  395. var pars []interface{}
  396. switch req.DataRangeType {
  397. case ALL_DATE:
  398. case LAST_N_YEARS:
  399. condition += " AND data_time >=?"
  400. year := time.Now().Year()
  401. lastDate := time.Date(year-req.LastNYear, 1, 1, 0, 0, 0, 0, time.Local)
  402. pars = append(pars, lastDate)
  403. case RANGE_DATE:
  404. condition = " AND data_time >=? AND data_time <=?"
  405. pars = append(pars, req.StartDate, req.EndDate)
  406. case RANGE_DATE_TO_NOW:
  407. condition = " AND data_time >=?"
  408. pars = append(pars, req.StartDate)
  409. }
  410. condition += " AND edb_code =?"
  411. pars = append(pars, edbInfo.EdbCode)
  412. edbData, err := data_manage.GetAllEdbDataListByCondition(condition, pars, edbInfo.Source, edbInfo.SubSource)
  413. if err != nil {
  414. msg = "获取指标数据失败"
  415. return
  416. }
  417. var condMsg string
  418. if req.Period < 2 || req.Period > len(edbData) {
  419. condMsg += "period必须是一个大于等于2的正整数,且必须小于时间序列的长度"
  420. }
  421. if req.Seasonal < 3 || req.Seasonal%2 == 0 || req.Seasonal <= req.Period {
  422. if condMsg != "" {
  423. condMsg += "\n"
  424. }
  425. condMsg += "seasonal必须是一个大于等于3的奇整数,且必须大于period"
  426. }
  427. if req.Trend < 3 || req.Trend%2 == 0 || req.Trend <= req.Period {
  428. if condMsg != "" {
  429. condMsg += "\n"
  430. }
  431. condMsg += "trend必须是一个大于等于3的奇整数,且必须大于period"
  432. }
  433. if req.Fraction < 0 || req.Fraction > 1 {
  434. if condMsg != "" {
  435. condMsg += "\n"
  436. }
  437. condMsg += "fraction必须是一个介于[0-1]之间"
  438. }
  439. if 1 > req.TrendDeg || req.TrendDeg > 5 {
  440. if condMsg != "" {
  441. condMsg += "\n"
  442. }
  443. condMsg += "trend_deg请设置成1-5的整数"
  444. }
  445. if 1 > req.SeasonalDeg || req.SeasonalDeg > 5 {
  446. if condMsg != "" {
  447. condMsg += "\n"
  448. }
  449. condMsg += "seasonal_deg请设置成1-5的整数"
  450. }
  451. if 1 > req.LowPassDeg || req.LowPassDeg > 5 {
  452. if condMsg != "" {
  453. condMsg += "\n"
  454. }
  455. condMsg += "low_pass_deg请设置成1-5的整数"
  456. }
  457. if condMsg != "" {
  458. msg = condMsg
  459. err = fmt.Errorf("参数错误")
  460. return
  461. }
  462. b, err := json.Marshal(req)
  463. if err != nil {
  464. return
  465. }
  466. conf := new(stl.CalculateStlConfig)
  467. if req.CalculateStlConfigId > 0 {
  468. conf.CalculateStlConfigId = req.CalculateStlConfigId
  469. conf.Config = string(b)
  470. conf.ModifyTime = time.Now()
  471. err = conf.Update([]string{"Config", "ModifyTime"})
  472. configId = int64(req.CalculateStlConfigId)
  473. } else {
  474. conf.Config = string(b)
  475. conf.SysUserId = adminId
  476. conf.CreateTime = time.Now()
  477. conf.ModifyTime = time.Now()
  478. configId, err = conf.Insert()
  479. }
  480. return
  481. }
  482. func SearchEdbInfoWithStl(adminId int, keyWord string, currentIndex, pageSize int) (resp data_manage.EdbInfoFilterDataResp, msg string, err error) {
  483. var edbInfoList []*data_manage.EdbInfoList
  484. noPermissionEdbInfoIdList := make([]int, 0) //无权限指标
  485. // 获取当前账号的不可见指标
  486. {
  487. obj := data_manage.EdbInfoNoPermissionAdmin{}
  488. confList, er := obj.GetAllListByAdminId(adminId)
  489. if er != nil && er.Error() != utils.ErrNoRow() {
  490. msg = "获取失败"
  491. err = fmt.Errorf("获取不可见指标配置数据失败,Err:" + er.Error())
  492. return
  493. }
  494. for _, v := range confList {
  495. noPermissionEdbInfoIdList = append(noPermissionEdbInfoIdList, v.EdbInfoId)
  496. }
  497. }
  498. if currentIndex <= 0 {
  499. currentIndex = 1
  500. }
  501. startSize := utils.StartIndex(currentIndex, pageSize)
  502. // 是否走ES
  503. isEs := false
  504. var total int64
  505. if keyWord != "" {
  506. frequencyList := []string{"日度", "周度", "旬度", "月度", "季度"}
  507. // 普通的搜索
  508. total, edbInfoList, err = elastic.SearchEdbInfoDataByfrequency(utils.DATA_INDEX_NAME, keyWord, startSize, pageSize, 0, frequencyList, noPermissionEdbInfoIdList)
  509. isEs = true
  510. } else {
  511. var condition string
  512. var pars []interface{}
  513. // 普通指标
  514. condition += ` AND edb_info_type = ? `
  515. pars = append(pars, 0)
  516. // 无权限指标id
  517. lenNoPermissionEdbInfoIdList := len(noPermissionEdbInfoIdList)
  518. if lenNoPermissionEdbInfoIdList > 0 {
  519. condition += ` AND edb_info_id not in (` + utils.GetOrmInReplace(lenNoPermissionEdbInfoIdList) + `) `
  520. pars = append(pars, noPermissionEdbInfoIdList)
  521. }
  522. //频度
  523. condition += ` AND frequency IN ('日度', '周度', '旬度', '月度', '季度') `
  524. total, edbInfoList, err = data_manage.GetEdbInfoFilterList(condition, pars, startSize, pageSize)
  525. }
  526. if err != nil {
  527. edbInfoList = make([]*data_manage.EdbInfoList, 0)
  528. }
  529. page := paging.GetPaging(currentIndex, pageSize, int(total))
  530. edbInfoListLen := len(edbInfoList)
  531. classifyIdList := make([]int, 0)
  532. for i := 0; i < edbInfoListLen; i++ {
  533. edbInfoList[i].EdbNameAlias = edbInfoList[i].EdbName
  534. classifyIdList = append(classifyIdList, edbInfoList[i].ClassifyId)
  535. }
  536. // 当前列表中的分类map
  537. classifyMap := make(map[int]*data_manage.EdbClassify)
  538. if edbInfoListLen > 0 {
  539. classifyList, er := data_manage.GetEdbClassifyByIdList(classifyIdList)
  540. if er != nil {
  541. msg = "获取失败"
  542. err = fmt.Errorf("获取分类列表失败,Err:" + er.Error())
  543. return
  544. }
  545. for _, v := range classifyList {
  546. classifyMap[v.ClassifyId] = v
  547. }
  548. // 获取所有有权限的指标和分类
  549. permissionEdbIdList, permissionClassifyIdList, er := data_manage_permission.GetUserEdbAndClassifyPermissionList(adminId, 0, 0)
  550. if er != nil {
  551. msg = "获取失败"
  552. err = fmt.Errorf("获取所有有权限的指标和分类失败,Err:" + er.Error())
  553. return
  554. }
  555. // 如果是ES的话,需要重新查一下指标的信息,主要是为了把是否授权字段找出来
  556. if isEs {
  557. edbInfoIdList := make([]int, 0)
  558. for i := 0; i < edbInfoListLen; i++ {
  559. edbInfoIdList = append(edbInfoIdList, edbInfoList[i].EdbInfoId)
  560. tmpEdbInfo := edbInfoList[i]
  561. if currClassify, ok := classifyMap[tmpEdbInfo.ClassifyId]; ok {
  562. edbInfoList[i].HaveOperaAuth = data_manage_permission.CheckEdbPermissionByPermissionIdList(tmpEdbInfo.IsJoinPermission, currClassify.IsJoinPermission, tmpEdbInfo.EdbInfoId, tmpEdbInfo.ClassifyId, permissionEdbIdList, permissionClassifyIdList)
  563. }
  564. }
  565. tmpEdbList, er := data_manage.GetEdbInfoByIdList(edbInfoIdList)
  566. if er != nil {
  567. msg = "获取失败"
  568. err = fmt.Errorf("获取所有有权限的指标失败,Err:" + er.Error())
  569. return
  570. }
  571. edbInfoMap := make(map[int]*data_manage.EdbInfo)
  572. for _, v := range tmpEdbList {
  573. edbInfoMap[v.EdbInfoId] = v
  574. }
  575. for i := 0; i < edbInfoListLen; i++ {
  576. tmpEdbInfo, ok := edbInfoMap[edbInfoList[i].EdbInfoId]
  577. if !ok {
  578. continue
  579. }
  580. edbInfoList[i].IsJoinPermission = tmpEdbInfo.IsJoinPermission
  581. }
  582. }
  583. // 权限校验
  584. for i := 0; i < edbInfoListLen; i++ {
  585. tmpEdbInfoItem := edbInfoList[i]
  586. if currClassify, ok := classifyMap[tmpEdbInfoItem.ClassifyId]; ok {
  587. edbInfoList[i].HaveOperaAuth = data_manage_permission.CheckEdbPermissionByPermissionIdList(tmpEdbInfoItem.IsJoinPermission, currClassify.IsJoinPermission, tmpEdbInfoItem.EdbInfoId, tmpEdbInfoItem.ClassifyId, permissionEdbIdList, permissionClassifyIdList)
  588. }
  589. }
  590. }
  591. for i := 0; i < edbInfoListLen; i++ {
  592. for j := 0; j < edbInfoListLen; j++ {
  593. if (edbInfoList[i].EdbNameAlias == edbInfoList[j].EdbNameAlias) &&
  594. (edbInfoList[i].EdbInfoId != edbInfoList[j].EdbInfoId) &&
  595. !(strings.Contains(edbInfoList[i].EdbName, edbInfoList[i].SourceName)) {
  596. edbInfoList[i].EdbName = edbInfoList[i].EdbName + "(" + edbInfoList[i].SourceName + ")"
  597. }
  598. }
  599. }
  600. //新增搜索词记录
  601. {
  602. searchKeyword := new(data_manage.SearchKeyword)
  603. searchKeyword.KeyWord = keyWord
  604. searchKeyword.CreateTime = time.Now()
  605. go data_manage.AddSearchKeyword(searchKeyword)
  606. }
  607. resp = data_manage.EdbInfoFilterDataResp{
  608. Paging: page,
  609. List: edbInfoList,
  610. }
  611. return
  612. }
  613. func SaveStlEdbInfo(req *request.SaveStlEdbInfoReq, adminId int, adminRealName, lang string) (isSendEmail bool, msg string, err error) {
  614. conf, err := stl.GetCalculateStlConfigById(req.CalculateStlConfigId)
  615. if err != nil {
  616. if err.Error() == utils.ErrNoRow() {
  617. msg = "未找到配置,请先进行计算"
  618. err = fmt.Errorf("配置不存在")
  619. return
  620. }
  621. msg = "获取失败"
  622. return
  623. }
  624. var edbInfoData []*response.EdbData
  625. switch req.StlEdbType {
  626. case 1:
  627. // 趋势指标
  628. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(req.CalculateStlConfigId)); !ok {
  629. msg = "计算已过期,请重新计算"
  630. err = fmt.Errorf("not found")
  631. return
  632. }
  633. trendData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(req.CalculateStlConfigId))
  634. if er != nil {
  635. msg = "获取失败"
  636. err = fmt.Errorf("获取redis数据失败,Err:" + er.Error())
  637. return
  638. }
  639. if er := json.Unmarshal(trendData, &edbInfoData); er != nil {
  640. msg = "获取失败"
  641. err = fmt.Errorf("json解析失败,Err:" + er.Error())
  642. return
  643. }
  644. case 2:
  645. // 季节性指标
  646. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(req.CalculateStlConfigId)); !ok {
  647. msg = "计算已过期,请重新计算"
  648. err = fmt.Errorf("not found")
  649. return
  650. }
  651. seasonalData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(req.CalculateStlConfigId))
  652. if er != nil {
  653. msg = "获取失败"
  654. err = fmt.Errorf("获取redis数据失败,Err:" + er.Error())
  655. return
  656. }
  657. if er := json.Unmarshal(seasonalData, &edbInfoData); er != nil {
  658. msg = "获取失败"
  659. err = fmt.Errorf("json解析失败,Err:" + er.Error())
  660. return
  661. }
  662. case 3:
  663. // 残差性指标
  664. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(req.CalculateStlConfigId)); !ok {
  665. msg = "计算已过期,请重新计算"
  666. err = fmt.Errorf("not found")
  667. return
  668. }
  669. residualData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(req.CalculateStlConfigId))
  670. if er != nil {
  671. msg = "获取失败"
  672. err = fmt.Errorf("获取redis数据失败,Err:" + er.Error())
  673. return
  674. }
  675. if er := json.Unmarshal(residualData, &edbInfoData); er != nil {
  676. msg = "获取失败"
  677. err = fmt.Errorf("json解析失败,Err:" + er.Error())
  678. return
  679. }
  680. }
  681. indexObj := new(stl.EdbDataCalculateStl)
  682. edbCode, err := utils.GenerateEdbCode(1, "stl")
  683. if err != nil {
  684. msg = "生成指标代码失败"
  685. return
  686. }
  687. var dataList []*stl.EdbDataCalculateStl
  688. var startDate, endDate time.Time
  689. for _, v := range edbInfoData {
  690. dataTime, _ := time.Parse(utils.FormatDate, v.DataTime)
  691. value, _ := strconv.ParseFloat(v.Value, 64)
  692. if startDate.IsZero() || dataTime.Before(startDate) {
  693. startDate = dataTime
  694. }
  695. if endDate.IsZero() || dataTime.After(endDate) {
  696. endDate = dataTime
  697. }
  698. dataList = append(dataList, &stl.EdbDataCalculateStl{
  699. EdbInfoId: req.EdbInfoId,
  700. EdbCode: edbCode,
  701. DataTime: dataTime,
  702. Value: value,
  703. CreateTime: time.Now(),
  704. ModifyTime: time.Now(),
  705. DataTimestamp: dataTime.UnixMilli(),
  706. })
  707. }
  708. err = indexObj.BatchInsert(dataList)
  709. if err != nil {
  710. msg = "保存失败"
  711. return
  712. }
  713. startDateStr := startDate.Format(utils.FormatDate)
  714. endDateStr := endDate.Format(utils.FormatDate)
  715. //判断指标名称是否存在
  716. ok, err := CheckDulplicateEdbInfoName(req.EdbName, lang)
  717. if err != nil {
  718. msg = "保存失败"
  719. return
  720. }
  721. if ok {
  722. msg = "指标名称已存在"
  723. err = fmt.Errorf("指标名称已存在")
  724. return
  725. }
  726. source := utils.DATA_SOURCE_CALCULATE_STL
  727. subSource := utils.DATA_SUB_SOURCE_EDB
  728. edbInfo := new(data_manage.EdbInfo)
  729. //获取该层级下最大的排序数
  730. maxSort, err := data.GetEdbClassifyMaxSort(req.ClassifyId, 0)
  731. if err != nil {
  732. msg = "获取失败"
  733. err = fmt.Errorf("获取最大排序失败,Err:" + err.Error())
  734. return
  735. }
  736. edbInfo.EdbCode = edbCode
  737. edbInfo.EdbName = req.EdbName
  738. edbInfo.EdbNameEn = req.EdbName
  739. edbInfo.EdbNameSource = req.EdbName
  740. edbInfo.Frequency = req.Frequency
  741. edbInfo.Unit = req.Unit
  742. edbInfo.UnitEn = req.Unit
  743. edbInfo.StartDate = startDateStr
  744. edbInfo.EndDate = endDateStr
  745. edbInfo.CalculateFormula = conf.Config
  746. edbInfo.ClassifyId = req.ClassifyId
  747. edbInfo.SysUserId = adminId
  748. edbInfo.SysUserRealName = adminRealName
  749. edbInfo.CreateTime = time.Now()
  750. edbInfo.ModifyTime = time.Now()
  751. edbInfo.Sort = maxSort + 1
  752. edbInfo.DataDateType = `交易日`
  753. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  754. edbInfo.UniqueCode = utils.MD5(utils.DATA_PREFIX + "_" + timestamp)
  755. itemVal, err := data_manage.GetEdbInfoMaxAndMinInfo(source, subSource, edbCode)
  756. if itemVal != nil && err == nil {
  757. edbInfo.MaxValue = itemVal.MaxValue
  758. edbInfo.MinValue = itemVal.MinValue
  759. }
  760. edbInfo.EdbType = 2
  761. edbInfo.Source = source
  762. edbInfo.SubSource = subSource
  763. extra, _ := json.Marshal(req)
  764. edbInfo.Extra = string(extra)
  765. edbInfoId, err := data_manage.AddEdbInfo(edbInfo)
  766. if err != nil {
  767. msg = "保存失败"
  768. err = errors.New("保存失败,Err:" + err.Error())
  769. return
  770. }
  771. edbInfo.EdbInfoId = int(edbInfoId)
  772. //保存数据
  773. data_manage.ModifyEdbInfoDataStatus(edbInfoId, source, subSource, edbCode)
  774. maxAndMinItem, _ := data_manage.GetEdbInfoMaxAndMinInfo(source, subSource, edbCode)
  775. if maxAndMinItem != nil {
  776. err = data_manage.ModifyEdbInfoMaxAndMinInfo(int(edbInfoId), maxAndMinItem)
  777. if err != nil {
  778. msg = "保存失败"
  779. err = errors.New("保存失败,Err:" + err.Error())
  780. return
  781. }
  782. }
  783. // 保存配置映射
  784. {
  785. stlMapping := new(stl.CalculateStlConfigMapping)
  786. stlMapping.EdbInfoId = int(edbInfoId)
  787. stlMapping.CalculateStlConfigId = req.CalculateStlConfigId
  788. stlMapping.CreateTime = time.Now()
  789. stlMapping.ModifyTime = time.Now()
  790. _, err = stlMapping.Insert()
  791. if err != nil {
  792. msg = "保存失败"
  793. err = errors.New("保存配置映射失败,Err:" + err.Error())
  794. return
  795. }
  796. }
  797. // 保存溯源信息
  798. {
  799. fromEdbInfo, er := data_manage.GetEdbInfoById(req.EdbInfoId)
  800. if er != nil {
  801. if er.Error() == utils.ErrNoRow() {
  802. msg = "未找到指标,请刷新后重试"
  803. err = fmt.Errorf("指标不存在,err:" + er.Error())
  804. return
  805. }
  806. msg = "获取失败"
  807. err = er
  808. return
  809. }
  810. edbCalculateMappingInfo := new(data_manage.EdbInfoCalculateMapping)
  811. edbCalculateMappingInfo.EdbInfoId = int(edbInfoId)
  812. edbCalculateMappingInfo.Source = source
  813. edbCalculateMappingInfo.SourceName = "STL趋势分解"
  814. edbCalculateMappingInfo.EdbCode = edbCode
  815. edbCalculateMappingInfo.FromEdbInfoId = req.EdbInfoId
  816. edbCalculateMappingInfo.FromEdbCode = fromEdbInfo.EdbCode
  817. edbCalculateMappingInfo.FromEdbName = fromEdbInfo.EdbName
  818. edbCalculateMappingInfo.FromSource = fromEdbInfo.Source
  819. edbCalculateMappingInfo.FromSourceName = fromEdbInfo.SourceName
  820. edbCalculateMappingInfo.CreateTime = time.Now()
  821. edbCalculateMappingInfo.ModifyTime = time.Now()
  822. err = edbCalculateMappingInfo.Insert()
  823. if err != nil {
  824. msg = "保存失败"
  825. err = errors.New("保存溯源信息失败,Err:" + err.Error())
  826. return
  827. }
  828. }
  829. //添加es
  830. data.AddOrEditEdbInfoToEs(int(edbInfoId))
  831. return
  832. }
  833. func GetStlConfig(configId int) (resp *response.StlConfigResp, msg string, err error) {
  834. conf, err := stl.GetCalculateStlConfigById(configId)
  835. if err != nil {
  836. if err.Error() == utils.ErrNoRow() {
  837. msg = "未找到配置,请刷新后重试"
  838. return
  839. }
  840. msg = "获取失败"
  841. return
  842. }
  843. var req request.StlConfigReq
  844. if err = json.Unmarshal([]byte(conf.Config), &req); err != nil {
  845. msg = "获取失败"
  846. return
  847. }
  848. edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
  849. if err != nil {
  850. if err.Error() == utils.ErrNoRow() {
  851. msg = "未找到指标,请刷新后重试"
  852. return
  853. }
  854. msg = "获取失败"
  855. return
  856. }
  857. resp = &response.StlConfigResp{
  858. CalculateStlConfigId: conf.CalculateStlConfigId,
  859. EdbInfoId: req.EdbInfoId,
  860. EdbInfoName: edbInfo.EdbName,
  861. DataRangeType: req.DataRangeType,
  862. StartDate: req.StartDate,
  863. EndDate: req.EndDate,
  864. LastNYear: req.LastNYear,
  865. Period: req.Period,
  866. Seasonal: req.Seasonal,
  867. Trend: req.Trend,
  868. Fraction: req.Fraction,
  869. Robust: req.Robust,
  870. TrendDeg: req.TrendDeg,
  871. SeasonalDeg: req.SeasonalDeg,
  872. LowPassDeg: req.LowPassDeg,
  873. }
  874. return
  875. }
  876. func CheckDulplicateEdbInfoName(edbName, lang string) (ok bool, err error) {
  877. var count int
  878. var condition string
  879. var pars []interface{}
  880. switch lang {
  881. case utils.EnLangVersion:
  882. condition += " AND edb_name_en = ? "
  883. default:
  884. condition += " AND edb_name=? "
  885. }
  886. pars = append(pars, edbName)
  887. count, err = data_manage.GetEdbInfoCountByCondition(condition, pars)
  888. if err != nil {
  889. return
  890. }
  891. if count > 0 {
  892. ok = true
  893. return
  894. }
  895. return
  896. }