residual_analysis_service.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. package residual_analysis_service
  2. import (
  3. "encoding/json"
  4. "eta/eta_api/models/data_manage"
  5. "eta/eta_api/models/residual_analysis_model"
  6. "eta/eta_api/models/system"
  7. "eta/eta_api/utils"
  8. "fmt"
  9. "math"
  10. "strconv"
  11. "time"
  12. )
  13. func ResidualAnalysisPreview(req residual_analysis_model.ResidualAnalysisReq) (residual_analysis_model.ResidualAnalysisResp, error) {
  14. mappingList, err := data_manage.GetChartEdbMappingListByEdbInfoIdList([]int{req.EdbInfoIdA, req.EdbInfoIdB})
  15. if err != nil {
  16. return residual_analysis_model.ResidualAnalysisResp{}, fmt.Errorf("获取图表,指标信息失败,Err:%s", err.Error())
  17. }
  18. var edbInfoMappingA, edbInfoMappingB *data_manage.ChartEdbInfoMapping
  19. for _, v := range mappingList {
  20. if v.EdbInfoId == req.EdbInfoIdA {
  21. edbInfoMappingA = v
  22. }
  23. if v.EdbInfoId == req.EdbInfoIdB {
  24. edbInfoMappingB = v
  25. }
  26. }
  27. if edbInfoMappingA == nil {
  28. return residual_analysis_model.ResidualAnalysisResp{}, fmt.Errorf("指标A不存在")
  29. }
  30. if edbInfoMappingB == nil {
  31. return residual_analysis_model.ResidualAnalysisResp{}, fmt.Errorf("指标B不存在")
  32. }
  33. // 时间处理
  34. var startDate, endDate string
  35. switch req.DateType {
  36. case 0:
  37. startDate = req.StartDate
  38. endDate = req.EndDate
  39. case 1:
  40. startDate = req.StartDate
  41. endDate = ""
  42. default:
  43. startDate = utils.GetPreYearTime(req.DateType)
  44. endDate = ""
  45. }
  46. resp := residual_analysis_model.ResidualAnalysisResp{}
  47. // 原始图表信息
  48. originalEdbList := make([]residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, 0)
  49. originalEdbList, err = fillOriginalChart(req, mappingList, startDate, endDate, edbInfoMappingA, edbInfoMappingB, originalEdbList)
  50. if err != nil {
  51. return residual_analysis_model.ResidualAnalysisResp{}, err
  52. }
  53. originalChartInfo := createChartInfoResp(req, startDate, endDate, edbInfoMappingA.EdbName+"与"+edbInfoMappingB.EdbName)
  54. resp.OriginalChartData = residual_analysis_model.ChartResp{
  55. ChartInfo: originalChartInfo,
  56. EdbInfoList: originalEdbList,
  57. }
  58. // 如果只需要第一张图表的数据 直接返回,避免继续处理
  59. if req.QueryType == 1 {
  60. return resp, nil
  61. }
  62. dataAList, ok := edbInfoMappingA.DataList.([]*data_manage.EdbDataList)
  63. if !ok {
  64. return residual_analysis_model.ResidualAnalysisResp{}, fmt.Errorf("数据类型转换失败")
  65. }
  66. indexADataMap := map[string]*data_manage.EdbDataList{}
  67. for _, indexData := range dataAList {
  68. indexADataMap[indexData.DataTime] = indexData
  69. }
  70. // 映射图表信息
  71. mappingEdbList, a, b, r, err := fillMappingChartInfo(req, edbInfoMappingA, edbInfoMappingB, originalEdbList, indexADataMap)
  72. if err != nil {
  73. return residual_analysis_model.ResidualAnalysisResp{}, err
  74. }
  75. mappingChartInfo := createChartInfoResp(req, startDate, endDate, edbInfoMappingA.EdbName+"与"+edbInfoMappingB.EdbName+"映射"+edbInfoMappingA.EdbName)
  76. resp.MappingChartData = residual_analysis_model.ChartResp{
  77. ChartInfo: mappingChartInfo,
  78. EdbInfoList: mappingEdbList,
  79. }
  80. // 残差图表信息
  81. residualEdbList, R2, err := fillResidualChartInfo(edbInfoMappingA, edbInfoMappingB, mappingEdbList)
  82. if err != nil {
  83. return residual_analysis_model.ResidualAnalysisResp{}, err
  84. }
  85. residualChartInfo := createChartInfoResp(req, startDate, endDate, edbInfoMappingA.EdbName+"与"+edbInfoMappingA.EdbName+"映射残差/"+edbInfoMappingB.EdbName)
  86. resp.ResidualChartData = residual_analysis_model.ChartResp{
  87. ChartInfo: residualChartInfo,
  88. EdbInfoList: residualEdbList,
  89. }
  90. if req.ResidualType == 2 {
  91. resp.A = a
  92. resp.B = b
  93. resp.R = r
  94. resp.R2 = R2
  95. }
  96. return resp, nil
  97. }
  98. func createChartInfoResp(req residual_analysis_model.ResidualAnalysisReq, startDate, endDate, chartName string) residual_analysis_model.ResidualAnalysisChartInfo {
  99. return residual_analysis_model.ResidualAnalysisChartInfo{
  100. Calendar: `公历`,
  101. Source: utils.CHART_SOURCE_DEFAULT,
  102. DateType: req.DateType,
  103. StartDate: startDate,
  104. EndDate: endDate,
  105. ChartType: utils.CHART_TYPE_CURVE,
  106. ChartName: chartName,
  107. }
  108. }
  109. func fillResidualChartInfo(edbInfoMappingA *data_manage.ChartEdbInfoMapping, edbInfoMappingB *data_manage.ChartEdbInfoMapping, mappingEdbList []residual_analysis_model.ResidualAnalysisChartEdbInfoMapping) ([]residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, float64, error) {
  110. // 计算公式 映射残差 = 因变量指标 - 映射指标
  111. var edbInfoA, edbInfoB residual_analysis_model.ResidualAnalysisChartEdbInfoMapping
  112. if mappingEdbList[0].EdbInfoId == edbInfoMappingA.EdbInfoId {
  113. edbInfoA = mappingEdbList[0]
  114. edbInfoB = mappingEdbList[1]
  115. } else {
  116. edbInfoA = mappingEdbList[1]
  117. edbInfoB = mappingEdbList[0]
  118. }
  119. dataAList, ok := edbInfoA.DataList.([]*data_manage.EdbDataList)
  120. if !ok {
  121. return nil, 0, fmt.Errorf("数据类型转换失败")
  122. }
  123. edbData := make([]*data_manage.EdbDataList, len(dataAList))
  124. for i, data := range dataAList {
  125. edbData[i] = &data_manage.EdbDataList{
  126. Value: data.Value, // 确保为每个元素创建一个新的对象
  127. DataTimestamp: data.DataTimestamp,
  128. DataTime: data.DataTime,
  129. EdbInfoId: data.EdbInfoId,
  130. EdbDataId: data.EdbDataId,
  131. }
  132. }
  133. dataBList, ok := edbInfoB.DataList.([]*data_manage.EdbDataList)
  134. if !ok {
  135. return nil, 0, fmt.Errorf("数据类型转换失败")
  136. }
  137. var indexDataBMap = make(map[string]*data_manage.EdbDataList)
  138. for _, data := range dataBList {
  139. indexDataBMap[data.DataTime] = data
  140. }
  141. // 求R2
  142. var valueB, sumValueA, averageValueA, residualQuadraticSum, totalQuadraticSum, R2 float64
  143. for _, indexData := range edbData {
  144. // 因变量的值总和
  145. sumValueA += indexData.Value
  146. }
  147. // 因变量平均值
  148. averageValueA = sumValueA / float64(len(edbData))
  149. for _, indexData := range edbData {
  150. if dataB, ok := indexDataBMap[indexData.DataTime]; ok {
  151. valueB = dataB.Value
  152. } else {
  153. valueB = 0
  154. }
  155. // 总因变量平方和
  156. totalQuadraticSum += math.Pow(indexData.Value-averageValueA, 2)
  157. // 补全残差值
  158. indexData.Value = indexData.Value - valueB
  159. // 残差平方和
  160. residualQuadraticSum += math.Pow(indexData.Value, 2)
  161. }
  162. // 计算R2 公式:R2=1-SSE/SST R2越大,越符合线性 R2 = 1 - 残差平方和/总平方和
  163. R2 = 1 - residualQuadraticSum/totalQuadraticSum
  164. mappingEdb := make([]residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, len(mappingEdbList))
  165. copy(mappingEdb, mappingEdbList)
  166. for i, mapping := range mappingEdb {
  167. if mapping.EdbInfoId != edbInfoMappingA.EdbInfoId {
  168. mappingEdb[i].DataList = edbData
  169. mappingEdb[i].EdbName = edbInfoMappingA.EdbName + "映射残差/" + edbInfoMappingB.EdbName
  170. mappingEdb[i].IsAxis = 1
  171. mappingEdb[i].ChartColor = `#00F`
  172. mappingEdb[i].IsOrder = false
  173. } else {
  174. mappingEdb[i].IsAxis = 0
  175. mappingEdb[i].ChartColor = `#F00`
  176. }
  177. }
  178. return mappingEdb, R2, nil
  179. }
  180. func fillMappingChartInfo(req residual_analysis_model.ResidualAnalysisReq, edbInfoMappingA *data_manage.ChartEdbInfoMapping, edbInfoMappingB *data_manage.ChartEdbInfoMapping, originalEdbList []residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, indexADataMap map[string]*data_manage.EdbDataList) ([]residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, float64, float64, float64, error) {
  181. // 计算公式:Y=aX+b,Y为映射后的指标,X为自变量指标
  182. // 正序:a=(L2-L1)/(R2-R1) b=L2-R2*a
  183. // 逆序:a=(L2-L1)/(R1-R2) b=L2-R1*a
  184. // L2:左轴下限 R2:右轴上限 L1:左轴上限 R1:右轴下限
  185. var a, b, r float64
  186. // 映射残差 计算a,b
  187. if req.ResidualType == 1 {
  188. if req.IsOrder {
  189. a = (req.LeftIndexMax - req.LeftIndexMin) / (req.RightIndexMin - req.RightIndexMax)
  190. b = req.LeftIndexMax - req.RightIndexMin*a
  191. } else {
  192. a = (req.LeftIndexMax - req.LeftIndexMin) / (req.RightIndexMax - req.RightIndexMin)
  193. b = req.LeftIndexMax - req.RightIndexMax*a
  194. }
  195. }
  196. dataList, ok := edbInfoMappingB.DataList.([]*data_manage.EdbDataList)
  197. if !ok {
  198. return nil, a, b, r, fmt.Errorf("数据类型转换失败")
  199. }
  200. // 领先指标 dataList进行数据处理
  201. if req.IndexType == 2 {
  202. if req.LeadValue < 0 {
  203. return nil, a, b, r, fmt.Errorf("领先值不能小于0")
  204. } else if req.LeadValue > 0 {
  205. for _, indexData := range dataList {
  206. switch req.LeadFrequency {
  207. case "天":
  208. indexData.DataTime = utils.GetNextDayN(indexData.DataTime, req.LeadValue)
  209. case "周":
  210. indexData.DataTime = utils.GetNextDayN(indexData.DataTime, req.LeadValue*7)
  211. case "月":
  212. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), 0, req.LeadValue), utils.YearMonthDay)
  213. case "季":
  214. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), 0, req.LeadValue*3), utils.YearMonthDay)
  215. case "年":
  216. indexData.DataTime = utils.TimeToString(utils.AddDate(utils.StringToTime(indexData.DataTime), req.LeadValue, 0), utils.YearMonthDay)
  217. }
  218. }
  219. }
  220. }
  221. // 指标B数据补充
  222. for index := 0; index < len(dataList)-1; index++ {
  223. // 获取当前数据和下一个数据
  224. beforeIndexData := dataList[index]
  225. afterIndexData := dataList[index+1]
  226. // 从最早时间开始,补充时间为自然日
  227. if utils.IsMoreThanOneDay(beforeIndexData.DataTime, afterIndexData.DataTime) {
  228. // 创建补充数据
  229. replenishIndexData := data_manage.EdbDataList{
  230. DataTime: utils.GetNextDay(beforeIndexData.DataTime),
  231. DataTimestamp: time.Now().UnixMilli(),
  232. Value: beforeIndexData.Value,
  233. }
  234. // 将补充数据插入到数据列表
  235. dataList = append(dataList, &replenishIndexData)
  236. }
  237. }
  238. // 拟合残差 计算a,b
  239. var coordinateList []utils.Coordinate
  240. if req.ResidualType == 2 {
  241. for _, indexData := range dataList {
  242. if _, ok := indexADataMap[indexData.DataTime]; ok {
  243. coordinate := utils.Coordinate{
  244. X: indexData.Value,
  245. Y: indexADataMap[indexData.DataTime].Value,
  246. }
  247. coordinateList = append(coordinateList, coordinate)
  248. }
  249. }
  250. a, b = utils.GetLinearResult(coordinateList)
  251. r = utils.CalculationDecisive(coordinateList)
  252. }
  253. // 根据指标A的时间key,在B的映射指标中筛选出对应的值
  254. var dataBList []*data_manage.EdbDataList
  255. for _, indexData := range dataList {
  256. if _, ok := indexADataMap[indexData.DataTime]; ok {
  257. indexDataCopy := *indexData
  258. // 计算指标B映射值
  259. indexDataCopy.Value = math.Round((a*indexData.Value+b)*10000) / 10000
  260. // 将副本添加到 dataBList
  261. dataBList = append(dataBList, &indexDataCopy)
  262. }
  263. }
  264. mappingEdbList := make([]residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, len(originalEdbList))
  265. copy(mappingEdbList, originalEdbList)
  266. for i, mapping := range mappingEdbList {
  267. if mapping.EdbInfoId != req.EdbInfoIdA {
  268. mappingEdbList[i].EdbInfoId = 0
  269. mappingEdbList[i].EdbCode = ""
  270. mappingEdbList[i].IsAxis = 1
  271. mappingEdbList[i].EdbName = edbInfoMappingB.EdbName + "映射" + edbInfoMappingA.EdbName
  272. mappingEdbList[i].DataList = dataBList
  273. }
  274. }
  275. return mappingEdbList, a, b, r, nil
  276. }
  277. func fillOriginalChart(req residual_analysis_model.ResidualAnalysisReq, mappingList []*data_manage.ChartEdbInfoMapping, startDate string, endDate string, edbInfoMappingA *data_manage.ChartEdbInfoMapping, edbInfoMappingB *data_manage.ChartEdbInfoMapping, originalEdbList []residual_analysis_model.ResidualAnalysisChartEdbInfoMapping) ([]residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, error) {
  278. for _, v := range mappingList {
  279. var edbInfoMapping residual_analysis_model.ResidualAnalysisChartEdbInfoMapping
  280. edbInfoMapping.EdbInfoType = 1
  281. edbInfoMapping.IsOrder = false
  282. edbInfoMapping.IsAxis = 1
  283. edbInfoMapping.ChartColor = `#00F`
  284. edbInfoMapping.ChartWidth = 3
  285. // 获取图表中的指标数据
  286. dataList, err := data_manage.GetEdbDataList(v.Source, v.SubSource, v.EdbInfoId, startDate, endDate)
  287. if err != nil {
  288. return nil, fmt.Errorf("获取指标数据失败,Err:%s", err.Error())
  289. }
  290. if v.EdbInfoId == req.EdbInfoIdB {
  291. edbInfoMapping.LeadValue = req.LeadValue
  292. edbInfoMapping.LeadUnit = req.LeadFrequency
  293. edbInfoMapping.EdbInfoType = req.IndexType
  294. edbInfoMapping.IsOrder = req.IsOrder
  295. edbInfoMapping.IsAxis = 0
  296. edbInfoMapping.ChartColor = `#F00`
  297. edbInfoMapping.ChartWidth = 1
  298. edbInfoMappingB.DataList = dataList
  299. } else {
  300. edbInfoMappingA.DataList = dataList
  301. }
  302. edbInfoMapping.EdbInfoId = v.EdbInfoId
  303. edbInfoMapping.EdbName = v.EdbName
  304. edbInfoMapping.EdbCode = v.EdbCode
  305. edbInfoMapping.Unit = v.Unit
  306. edbInfoMapping.Frequency = v.Frequency
  307. edbInfoMapping.Source = v.Source
  308. edbInfoMapping.SourceName = v.SourceName
  309. edbInfoMapping.MinValue = v.MinValue
  310. edbInfoMapping.MaxValue = v.MaxValue
  311. edbInfoMapping.LatestDate = v.LatestDate
  312. edbInfoMapping.LatestValue = v.LatestValue
  313. edbInfoMapping.DataList = dataList
  314. originalEdbList = append(originalEdbList, edbInfoMapping)
  315. }
  316. return originalEdbList, nil
  317. }
  318. func ContrastPreview(indexCode string) (residual_analysis_model.ResidualAnalysisChartEdbInfoMapping, error) {
  319. var condition string
  320. var pars []interface{}
  321. if indexCode != "" {
  322. condition += " and edb_code=?"
  323. pars = append(pars, indexCode)
  324. }
  325. edbInfo, err := data_manage.GetEdbInfoByCondition(condition, pars)
  326. if err != nil {
  327. return residual_analysis_model.ResidualAnalysisChartEdbInfoMapping{}, err
  328. }
  329. if edbInfo == nil {
  330. return residual_analysis_model.ResidualAnalysisChartEdbInfoMapping{}, fmt.Errorf("指标不存在")
  331. }
  332. dataList, err := data_manage.GetEdbDataList(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbInfoId, "", "")
  333. var resp residual_analysis_model.ResidualAnalysisChartEdbInfoMapping
  334. resp.EdbInfoId = edbInfo.EdbInfoId
  335. resp.EdbCode = edbInfo.EdbCode
  336. resp.ChartColor = "#F00"
  337. resp.SourceName = edbInfo.SourceName
  338. resp.EdbName = edbInfo.EdbName
  339. resp.Unit = edbInfo.Unit
  340. resp.Frequency = edbInfo.Frequency
  341. resp.MinValue = edbInfo.MinValue
  342. resp.MaxValue = edbInfo.MaxValue
  343. resp.DataList = dataList
  344. return resp, nil
  345. }
  346. func SaveResidualAnalysis(req residual_analysis_model.ResidualAnalysisIndexSaveReq, sysUser *system.Admin) error {
  347. // 验证分类是否存在
  348. classifyCount, err := data_manage.GetEdbClassifyCountById(req.ClassifyId)
  349. if err != nil {
  350. return err
  351. }
  352. if classifyCount <= 0 {
  353. return fmt.Errorf("分类不存在")
  354. }
  355. // 校验名称是否重复
  356. var condition string
  357. var pars []interface{}
  358. condition += " and source = ? AND edb_name=?"
  359. pars = append(pars, req.Source, req.EdbName)
  360. edbInfoByCondition, err := data_manage.GetEdbInfoByCondition(condition, pars)
  361. if err != nil && err.Error() != utils.ErrNoRow() {
  362. return err
  363. }
  364. // 获取指标数据最大值 最小值 最后更新时间 最后更新时间对应的值
  365. var indexMax, indexMin, indexLatestValue float64
  366. var indexLatestDate string
  367. if len(req.DataList) > 0 {
  368. latestTime, _ := time.Parse(utils.YearMonthDay, req.DataList[0].DataTime)
  369. for _, data := range req.DataList {
  370. // 比较最大值
  371. if data.Value > indexMax {
  372. indexMax = data.Value
  373. }
  374. // 比较最小值
  375. if data.Value < indexMin {
  376. indexMin = data.Value
  377. }
  378. // 比较最新时间和对应值
  379. currentTime, err := time.Parse(utils.YearMonthDay, data.DataTime)
  380. if err != nil {
  381. // 时间解析失败,跳过此项
  382. continue
  383. }
  384. // 如果当前时间更晚
  385. if currentTime.After(latestTime) {
  386. latestTime = currentTime
  387. indexLatestDate = data.DataTime
  388. indexLatestValue = data.Value
  389. }
  390. }
  391. }
  392. // 更新保存指标和配置的映射关系
  393. mappingList, err := residual_analysis_model.GetConfigMappingListByConfigId(req.ConfigId)
  394. if err != nil {
  395. return err
  396. }
  397. // 判断是更新还是修改 看指标配置映射中,是否存在对应指标 存在 则更新 不存在 则新增
  398. var edbInfoMapping residual_analysis_model.CalculateResidualAnalysisConfigMapping
  399. for _, mapping := range mappingList {
  400. if req.IndexType == mapping.IndexType && req.IndexType != 0 {
  401. edbInfoMapping = mapping
  402. }
  403. }
  404. var edbInfoId int64
  405. var edbCode string
  406. // 更新or新增
  407. if edbInfoMapping.EdbInfoId > 0 {
  408. // 查询指标库指标
  409. edbInfo, err := data_manage.GetEdbInfoById(int(edbInfoMapping.EdbInfoId))
  410. if err != nil {
  411. return err
  412. }
  413. if edbInfo == nil {
  414. return fmt.Errorf("指标不存在")
  415. }
  416. edbInfoId = int64(edbInfo.EdbInfoId)
  417. edbCode = edbInfo.EdbCode
  418. if edbInfoByCondition != nil && edbInfoByCondition.EdbInfoId != edbInfo.EdbInfoId {
  419. return fmt.Errorf("指标名称重复")
  420. }
  421. // 须补充更新指标最大值,最小值,数据最新时间,数据最新值
  422. edbInfo.MaxValue = indexMax
  423. edbInfo.MinValue = indexMin
  424. edbInfo.LatestDate = indexLatestDate
  425. edbInfo.LatestValue = indexLatestValue
  426. edbInfo.Unit = req.Unit
  427. edbInfo.Frequency = req.Frequency
  428. edbInfo.ClassifyId = req.ClassifyId
  429. edbInfo.EdbName = req.EdbName
  430. err = edbInfo.Update([]string{"min_value", "max_value", "latest_date", "latest_value", "unit", "frequency", "classify_id", "edb_name"})
  431. if err != nil {
  432. return err
  433. }
  434. // 删除对应得指标数据
  435. err = residual_analysis_model.DeleteResidualAnalysisDataByEdbCode(edbInfo.EdbCode)
  436. if err != nil {
  437. return fmt.Errorf("删除指标数据失败")
  438. }
  439. } else {
  440. if edbInfoByCondition != nil {
  441. return fmt.Errorf("指标名称重复")
  442. }
  443. // 新增指标
  444. edbCode, err = utils.GenerateEdbCode(1, "")
  445. if err != nil {
  446. return err
  447. }
  448. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  449. edbInfoId, err = data_manage.AddEdbInfo(&data_manage.EdbInfo{
  450. EdbCode: edbCode,
  451. UniqueCode: utils.MD5(utils.CHART_PREFIX + "_" + timestamp),
  452. EdbName: req.EdbName,
  453. EdbNameEn: req.EdbNameEn,
  454. ClassifyId: req.ClassifyId,
  455. EdbType: req.EdbType,
  456. Unit: req.Unit,
  457. UnitEn: req.UnitEn,
  458. Frequency: req.Frequency,
  459. Source: req.Source,
  460. SourceName: "残差分析",
  461. Calendar: req.Calendar,
  462. SysUserRealName: sysUser.RealName,
  463. SysUserId: sysUser.AdminId,
  464. LatestDate: indexLatestDate,
  465. LatestValue: indexLatestValue,
  466. MinValue: indexMin,
  467. MaxValue: indexMax,
  468. CreateTime: time.Now(),
  469. ModifyTime: time.Now(),
  470. })
  471. if err != nil {
  472. return err
  473. }
  474. // 新增指标配置关系
  475. _, err = residual_analysis_model.SaveConfigMapping(residual_analysis_model.CalculateResidualAnalysisConfigMapping{
  476. CalculateResidualAnalysisConfigId: req.ConfigId,
  477. EdbInfoId: edbInfoId,
  478. ResidualType: req.ResidualType,
  479. IndexType: req.IndexType,
  480. CreateTime: time.Now(),
  481. ModifyTime: time.Now(),
  482. })
  483. if err != nil {
  484. return err
  485. }
  486. }
  487. // 新增数据
  488. for i := range req.DataList {
  489. req.DataList[i].EdbDataId = 0
  490. req.DataList[i].EdbInfoId = int(edbInfoId)
  491. req.DataList[i].EdbCode = edbCode
  492. }
  493. _, err = residual_analysis_model.AddResidualAnalysisData(req.DataList)
  494. if err != nil {
  495. return err
  496. }
  497. // 新增自变量 因变量与配置得关系 配置中不存在该指标,则新增
  498. var indexMap = make(map[int64]residual_analysis_model.CalculateResidualAnalysisConfigMapping)
  499. for _, mapping := range mappingList {
  500. indexMap[mapping.EdbInfoId] = mapping
  501. }
  502. if _, ok := indexMap[int64(req.EdbInfoIdA)]; !ok {
  503. _, err = residual_analysis_model.SaveConfigMapping(residual_analysis_model.CalculateResidualAnalysisConfigMapping{
  504. CalculateResidualAnalysisConfigId: req.ConfigId,
  505. EdbInfoId: int64(req.EdbInfoIdA),
  506. ResidualType: req.ResidualType,
  507. IndexType: 3,
  508. CreateTime: time.Now(),
  509. ModifyTime: time.Now(),
  510. })
  511. if err != nil {
  512. return err
  513. }
  514. }
  515. if _, ok := indexMap[int64(req.EdbInfoIdB)]; !ok {
  516. _, err = residual_analysis_model.SaveConfigMapping(residual_analysis_model.CalculateResidualAnalysisConfigMapping{
  517. CalculateResidualAnalysisConfigId: req.ConfigId,
  518. EdbInfoId: int64(req.EdbInfoIdB),
  519. ResidualType: req.ResidualType,
  520. IndexType: 4,
  521. CreateTime: time.Now(),
  522. ModifyTime: time.Now(),
  523. })
  524. if err != nil {
  525. return err
  526. }
  527. }
  528. return nil
  529. }
  530. func ResidualAnalysisDetail(edbInfoId int) (residual_analysis_model.ResidualAnalysisDetailResp, error) {
  531. // 通过指标配置映射表 拿到配置id,再获取关联的所有指标信息
  532. var condition string
  533. var pars []interface{}
  534. condition += " and edb_info_id=?"
  535. pars = append(pars, edbInfoId)
  536. mappingList, err := residual_analysis_model.GetConfigMappingListByCondition(condition, pars)
  537. if err != nil {
  538. return residual_analysis_model.ResidualAnalysisDetailResp{}, err
  539. }
  540. if len(mappingList) <= 0 {
  541. return residual_analysis_model.ResidualAnalysisDetailResp{}, fmt.Errorf("指标不存在")
  542. }
  543. mapping := mappingList[0]
  544. configMappingList, err := residual_analysis_model.GetConfigMappingListByConfigId(mapping.CalculateResidualAnalysisConfigId)
  545. if err != nil {
  546. return residual_analysis_model.ResidualAnalysisDetailResp{}, err
  547. }
  548. var edbInfoIdList []int64
  549. var edbInfoMap = make(map[int64]residual_analysis_model.CalculateResidualAnalysisConfigMapping)
  550. var mappgingFlag = false
  551. var residualFlag = false
  552. for _, v := range configMappingList {
  553. edbInfoIdList = append(edbInfoIdList, v.EdbInfoId)
  554. edbInfoMap[v.EdbInfoId] = v
  555. if v.IndexType == 1 {
  556. mappgingFlag = true
  557. } else if v.IndexType == 2 {
  558. residualFlag = true
  559. }
  560. }
  561. condition = ""
  562. pars = []interface{}{}
  563. condition += ` and edb_info_id in(` + utils.GetOrmInReplace(len(edbInfoIdList)) + `)`
  564. for _, id := range edbInfoIdList {
  565. pars = append(pars, id)
  566. }
  567. edbInfoList, err := data_manage.GetEdbInfoListByCond(condition, pars)
  568. if err != nil {
  569. return residual_analysis_model.ResidualAnalysisDetailResp{}, err
  570. }
  571. // 获取配置
  572. configInfo, err := residual_analysis_model.GetResidualAnalysisConfigById(mapping.CalculateResidualAnalysisConfigId)
  573. if err != nil {
  574. return residual_analysis_model.ResidualAnalysisDetailResp{}, err
  575. }
  576. var edbInfoListResp []*residual_analysis_model.DetailEdbInfoList
  577. var dependentEdbInfo residual_analysis_model.DetailEdbInfoList
  578. var independentEdbInfo residual_analysis_model.DetailEdbInfoList
  579. for _, edbInfo := range edbInfoList {
  580. var indexType int
  581. if _, ok := edbInfoMap[int64(edbInfo.EdbInfoId)]; ok {
  582. indexType = edbInfoMap[int64(edbInfo.EdbInfoId)].IndexType
  583. }
  584. info := residual_analysis_model.DetailEdbInfoList{
  585. EdbInfoId: edbInfo.EdbInfoId,
  586. EdbInfoType: edbInfo.EdbInfoType,
  587. IndexType: indexType,
  588. SourceName: edbInfo.SourceName,
  589. Source: edbInfo.Source,
  590. EdbCode: edbInfo.EdbCode,
  591. EdbName: edbInfo.EdbName,
  592. EdbNameEn: edbInfo.EdbNameEn,
  593. Unit: edbInfo.Unit,
  594. UnitEn: edbInfo.UnitEn,
  595. Frequency: edbInfo.Frequency,
  596. FrequencyEn: edbInfo.FrequencyEn,
  597. ClassifyId: edbInfo.ClassifyId,
  598. }
  599. edbInfoListResp = append(edbInfoListResp, &info)
  600. if indexType == 3 {
  601. dependentEdbInfo = info
  602. } else if indexType == 4 {
  603. independentEdbInfo = info
  604. }
  605. }
  606. // 补充表格中 映射指标或者残差指标
  607. if mappgingFlag && !residualFlag {
  608. info := residual_analysis_model.DetailEdbInfoList{
  609. IndexType: 2,
  610. EdbName: independentEdbInfo.EdbName + "映射残差/" + dependentEdbInfo.EdbName,
  611. EdbNameEn: dependentEdbInfo.EdbNameEn,
  612. Unit: dependentEdbInfo.Unit,
  613. UnitEn: dependentEdbInfo.UnitEn,
  614. Frequency: dependentEdbInfo.Frequency,
  615. FrequencyEn: dependentEdbInfo.FrequencyEn,
  616. ClassifyId: dependentEdbInfo.ClassifyId,
  617. }
  618. edbInfoListResp = append(edbInfoListResp, &info)
  619. } else if !mappgingFlag && residualFlag {
  620. info := residual_analysis_model.DetailEdbInfoList{
  621. IndexType: 1,
  622. EdbName: dependentEdbInfo.EdbName + "映射" + independentEdbInfo.EdbName,
  623. EdbNameEn: dependentEdbInfo.EdbNameEn,
  624. Unit: dependentEdbInfo.Unit,
  625. UnitEn: dependentEdbInfo.UnitEn,
  626. Frequency: dependentEdbInfo.Frequency,
  627. FrequencyEn: dependentEdbInfo.FrequencyEn,
  628. ClassifyId: dependentEdbInfo.ClassifyId,
  629. }
  630. edbInfoListResp = append(edbInfoListResp, &info)
  631. }
  632. resp := residual_analysis_model.ResidualAnalysisDetailResp{
  633. ConfigInfo: &configInfo,
  634. EdbInfoList: edbInfoListResp,
  635. ResidualType: mapping.ResidualType,
  636. }
  637. return resp, nil
  638. }
  639. func SaveResidualAnalysisConfig(req residual_analysis_model.ResidualAnalysisReq, sysUser *system.Admin) (int64, error) {
  640. config := residual_analysis_model.ResidualAnalysisConfigVo{
  641. DateType: req.DateType,
  642. StartDate: req.StartDate,
  643. EndDate: req.EndDate,
  644. IsOrder: req.IsOrder,
  645. IndexType: req.IndexType,
  646. LeadValue: req.LeadValue,
  647. LeadFrequency: req.LeadFrequency,
  648. LeftIndexMin: req.LeftIndexMin,
  649. LeftIndexMax: req.LeftIndexMax,
  650. RightIndexMin: req.RightIndexMin,
  651. RightIndexMax: req.RightIndexMax,
  652. ResidualIndexMin: req.ResidualIndexMin,
  653. ResidualIndexMax: req.ResidualIndexMax,
  654. ContrastIndexMin: req.ContrastIndexMin,
  655. ContrastIndexMax: req.ContrastIndexMax,
  656. }
  657. // 转换为json格式
  658. configJson, err := json.Marshal(config)
  659. if err != nil {
  660. return 0, err
  661. }
  662. // 新增or更新
  663. /*
  664. var condition string
  665. var pars []interface{}
  666. if req.EdbInfoId > 0 {
  667. condition += " and edb_info_id=?"
  668. pars = append(pars, req.EdbInfoId)
  669. configMappings, err := residual_analysis_model.GetConfigMappingListByCondition(condition, pars)
  670. if err != nil {
  671. return 0, err
  672. }
  673. if len(configMappings) > 0 {
  674. mapping := configMappings[0]
  675. configInfo, err := residual_analysis_model.GetResidualAnalysisConfigById(mapping.CalculateResidualAnalysisConfigId)
  676. if err != nil {
  677. return 0, err
  678. }
  679. configInfo.Config = string(configJson)
  680. err = residual_analysis_model.UpdateResidualAnalysisConfig(configInfo)
  681. if err != nil {
  682. return 0, err
  683. }
  684. }
  685. }*/
  686. var configId int64
  687. if req.ConfigId > 0 {
  688. configInfo, err := residual_analysis_model.GetResidualAnalysisConfigById(req.ConfigId)
  689. if err != nil {
  690. return 0, err
  691. }
  692. if configInfo.CalculateResidualAnalysisConfigId == 0 {
  693. return 0, fmt.Errorf("未找到配置信息")
  694. }
  695. configId = int64(configInfo.CalculateResidualAnalysisConfigId)
  696. configInfo.Config = string(configJson)
  697. err = residual_analysis_model.UpdateResidualAnalysisConfig(configInfo)
  698. if err != nil {
  699. return 0, err
  700. }
  701. } else {
  702. analysisConfig := residual_analysis_model.CalculateResidualAnalysisConfig{
  703. Config: string(configJson),
  704. SysUserId: sysUser.AdminId,
  705. CreateTime: time.Now(),
  706. ModifyTime: time.Now(),
  707. }
  708. configId, err = residual_analysis_model.SaveResidualAnalysisConfig(analysisConfig)
  709. if err != nil {
  710. return 0, err
  711. }
  712. }
  713. return configId, nil
  714. }
  715. func CheckResidualAnalysisExist(configId int) (int64, error) {
  716. configMappingList, err := residual_analysis_model.GetConfigMappingListByConfigId(configId)
  717. if err != nil {
  718. return 0, err
  719. }
  720. var configMapping residual_analysis_model.CalculateResidualAnalysisConfigMapping
  721. for _, mapping := range configMappingList {
  722. if mapping.IndexType == 2 {
  723. configMapping = mapping
  724. }
  725. }
  726. return configMapping.EdbInfoId, nil
  727. }