stl.go 24 KB

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