residual_analysis_service.go 30 KB

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