base_from_python.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. package models
  2. import (
  3. "errors"
  4. "eta_gn/eta_index_lib/global"
  5. "eta_gn/eta_index_lib/services/alarm_msg"
  6. "eta_gn/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/shopspring/decimal"
  9. "strings"
  10. "time"
  11. )
  12. type EdbDataPython struct {
  13. EdbDataId int `gorm:"column:edb_data_id;primaryKey"` // 指标数据ID
  14. EdbInfoId int `gorm:"column:edb_info_id"` // 指标信息ID
  15. EdbCode string `gorm:"column:edb_code"` // 指标编码
  16. DataTime string `gorm:"column:data_time"` // 数据时间
  17. Value float64 `gorm:"column:value"` // 数据值
  18. CreateTime time.Time `gorm:"column:create_time"` // 创建时间
  19. ModifyTime time.Time `gorm:"column:modify_time"` // 修改时间
  20. DataTimestamp int64 `gorm:"column:data_timestamp"` // 数据时间戳
  21. }
  22. // TableName
  23. func (m *EdbDataPython) TableName() string {
  24. return "edb_data_python"
  25. }
  26. // EdbDataFromPython 通过python代码获取到的指标数据
  27. type EdbDataFromPython struct {
  28. Date map[int]string `json:"date"`
  29. Value map[int]float64 `json:"value"`
  30. }
  31. // AddPythonEdb 新增python运算指标
  32. func AddPythonEdb(edbInfo *EdbInfo, item EdbDataFromPython, edbInfoList []*EdbInfo) (err error) {
  33. //添加指标关系
  34. for _, tmpEdbInfo := range edbInfoList {
  35. calculateMappingItem := new(EdbInfoCalculateMapping)
  36. calculateMappingItem.CreateTime = time.Now()
  37. calculateMappingItem.ModifyTime = time.Now()
  38. calculateMappingItem.Sort = 1
  39. calculateMappingItem.EdbCode = edbInfo.EdbCode
  40. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  41. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  42. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  43. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  44. calculateMappingItem.FromSource = tmpEdbInfo.Source
  45. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  46. calculateMappingItem.Source = edbInfo.Source
  47. calculateMappingItem.SourceName = edbInfo.SourceName
  48. err = global.DEFAULT_DmSQL.Create(calculateMappingItem).Error
  49. if err != nil {
  50. return
  51. }
  52. }
  53. var isAdd bool
  54. addSql := ` INSERT INTO edb_data_python (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  55. for k, dateTimeStr := range item.Date {
  56. //格式化时间
  57. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, dateTimeStr, time.Local)
  58. if tmpErr != nil {
  59. err = tmpErr
  60. return
  61. }
  62. timestamp := currentDate.UnixNano() / 1e6
  63. timestampStr := fmt.Sprintf("%d", timestamp)
  64. //值
  65. val := item.Value[k]
  66. saveVal := utils.SubFloatToString(val, 20)
  67. addSql += GetAddSql(fmt.Sprint(edbInfo.EdbInfoId), edbInfo.EdbCode, dateTimeStr, timestampStr, saveVal)
  68. isAdd = true
  69. }
  70. if isAdd {
  71. addSql = strings.TrimRight(addSql, ",")
  72. err = global.DEFAULT_DmSQL.Exec(addSql).Error
  73. if err != nil {
  74. return
  75. }
  76. }
  77. return
  78. }
  79. // RefreshAllPythonEdb 刷新所有 python运算指标
  80. func RefreshAllPythonEdb(edbInfo *EdbInfo, item EdbDataFromPython) (err error) {
  81. pythonDataMap := make(map[string]float64)
  82. pythonDate := make([]string, 0)
  83. for k, dateTimeStr := range item.Date {
  84. pythonDataMap[dateTimeStr] = item.Value[k]
  85. pythonDate = append(pythonDate, dateTimeStr)
  86. }
  87. //查询当前指标现有的数据
  88. var condition string
  89. var pars []interface{}
  90. condition += " AND edb_info_id=? "
  91. pars = append(pars, edbInfo.EdbInfoId)
  92. //所有的数据
  93. dataList, err := GetAllEdbDataPythonByEdbInfoId(edbInfo.EdbInfoId)
  94. if err != nil {
  95. return err
  96. }
  97. //待修改的指标数据map(index:日期,value:值)
  98. updateEdbDataMap := make(map[string]float64)
  99. removeDateList := make([]string, 0) //需要删除的日期
  100. for _, v := range dataList {
  101. currDataTime := v.DataTime
  102. pythonData, ok := pythonDataMap[currDataTime]
  103. if !ok {
  104. // 如果python运算出来的数据中没有该日期,那么需要移除该日期的数据
  105. removeDateList = append(removeDateList, currDataTime)
  106. } else {
  107. currValue, _ := decimal.NewFromFloat(pythonData).Truncate(4).Float64() //保留4位小数
  108. //如果计算出来的值与库里面的值不匹配,那么就去修改该值
  109. if v.Value != currValue {
  110. //将计算后的数据存入待拼接指标map里面,以便后续计算
  111. updateEdbDataMap[currDataTime] = currValue
  112. }
  113. }
  114. //移除python指标数据中当天的日期
  115. delete(pythonDataMap, currDataTime)
  116. }
  117. //sort.Strings(tbzEdbDataTimeList)
  118. //新增的数据入库
  119. {
  120. addDataList := make([]*EdbDataPython, 0)
  121. for dataTime, dataValue := range pythonDataMap {
  122. //时间戳
  123. currentDate, _ := time.ParseInLocation(utils.FormatDate, dataTime, time.Local)
  124. timestamp := currentDate.UnixNano() / 1e6
  125. edbDataPython := &EdbDataPython{
  126. EdbInfoId: edbInfo.EdbInfoId,
  127. EdbCode: edbInfo.EdbCode,
  128. DataTime: dataTime,
  129. Value: dataValue,
  130. CreateTime: time.Now(),
  131. ModifyTime: time.Now(),
  132. DataTimestamp: timestamp,
  133. }
  134. addDataList = append(addDataList, edbDataPython)
  135. }
  136. //最后如果还有需要新增的数据,那么就统一入库
  137. if len(addDataList) > 0 {
  138. tmpErr := global.DEFAULT_DmSQL.CreateInBatches(addDataList, 500).Error
  139. if tmpErr != nil {
  140. err = tmpErr
  141. return
  142. }
  143. }
  144. }
  145. //删除已经不存在的累计同比拼接指标数据(由于同比值当日的数据删除了)
  146. {
  147. if len(removeDateList) > 0 {
  148. removeDateStr := strings.Join(removeDateList, `","`)
  149. removeDateStr = `"` + removeDateStr + `"`
  150. //如果拼接指标变更了,那么需要删除所有的指标数据
  151. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  152. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  153. err = global.DEFAULT_DmSQL.Exec(sql, edbInfo.EdbInfoId).Error
  154. if err != nil {
  155. err = errors.New("删除不存在的Python运算指标数据失败,Err:" + err.Error())
  156. return
  157. }
  158. }
  159. }
  160. //修改现有的数据中对应的值
  161. {
  162. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  163. for edbDate, edbDataValue := range updateEdbDataMap {
  164. sql := fmt.Sprintf(` UPDATE %s set value = ?,modify_time=now() WHERE edb_info_id = ? and data_time = ? `, tableName)
  165. err = global.DEFAULT_DmSQL.Exec(sql, edbDataValue, edbInfo.EdbInfoId, edbDate).Error
  166. if err != nil {
  167. err = errors.New("更新现有的Python运算指标数据失败,Err:" + err.Error())
  168. return
  169. }
  170. }
  171. }
  172. return
  173. }
  174. // EditEdbInfoCalculateMapping 更新关联关系表
  175. func EditEdbInfoCalculateMapping(edbInfo *EdbInfo, edbInfoList []*EdbInfo) (err error) {
  176. var existCondition string
  177. var existPars []interface{}
  178. existCondition += " AND edb_info_id=? "
  179. existPars = append(existPars, edbInfo.EdbInfoId)
  180. //查询出所有的关联指标
  181. existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
  182. if err != nil {
  183. err = fmt.Errorf("判断指标是否改变失败,Err:" + err.Error())
  184. return
  185. }
  186. existEdbInfoIdMap := make(map[int]int)
  187. isOpEdbInfoIdMap := make(map[int]int)
  188. for _, v := range existList {
  189. existEdbInfoIdMap[v.FromEdbInfoId] = v.FromEdbInfoId
  190. }
  191. //添加指标关系
  192. for _, tmpEdbInfo := range edbInfoList {
  193. //如果该指标id已经处理过了,那么就不处理了
  194. if _, ok := isOpEdbInfoIdMap[tmpEdbInfo.EdbInfoId]; ok {
  195. continue
  196. }
  197. if _, ok := existEdbInfoIdMap[tmpEdbInfo.EdbInfoId]; ok {
  198. //如果存在,那么就移除map里面的东西
  199. delete(existEdbInfoIdMap, tmpEdbInfo.EdbInfoId)
  200. isOpEdbInfoIdMap[tmpEdbInfo.EdbInfoId] = tmpEdbInfo.EdbInfoId
  201. } else {
  202. calculateMappingItem := new(EdbInfoCalculateMapping)
  203. calculateMappingItem.CreateTime = time.Now()
  204. calculateMappingItem.ModifyTime = time.Now()
  205. calculateMappingItem.Sort = 1
  206. calculateMappingItem.EdbCode = edbInfo.EdbCode
  207. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  208. calculateMappingItem.FromEdbInfoId = tmpEdbInfo.EdbInfoId
  209. calculateMappingItem.FromEdbCode = tmpEdbInfo.EdbCode
  210. calculateMappingItem.FromEdbName = tmpEdbInfo.EdbName
  211. calculateMappingItem.FromSource = tmpEdbInfo.Source
  212. calculateMappingItem.FromSourceName = tmpEdbInfo.SourceName
  213. calculateMappingItem.Source = edbInfo.Source
  214. calculateMappingItem.SourceName = edbInfo.SourceName
  215. err = global.DEFAULT_DmSQL.Create(calculateMappingItem).Error
  216. if err != nil {
  217. return
  218. }
  219. }
  220. }
  221. for _, v := range existEdbInfoIdMap {
  222. //删除,计算指标关联的,基础指标的关联关系
  223. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id=?`
  224. err = global.DEFAULT_DmSQL.Exec(sql, edbInfo.EdbInfoId, v).Error
  225. if err != nil {
  226. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  227. return
  228. }
  229. }
  230. return
  231. }
  232. // GetAllEdbDataPythonByEdbInfoId 根据指标id获取全部的数据
  233. func GetAllEdbDataPythonByEdbInfoId(edbInfoId int) (items []*EdbDataPython, err error) {
  234. sql := ` SELECT * FROM edb_data_python WHERE edb_info_id=? ORDER BY data_time DESC `
  235. err = global.DEFAULT_DmSQL.Raw(sql, edbInfoId).Scan(&items).Error
  236. return
  237. }
  238. // EdbInfoPythonSaveReq 计算(运算)指标请求参数
  239. type EdbInfoPythonSaveReq struct {
  240. AdminId int `description:"添加人id"`
  241. AdminName string `description:"添加人名称"`
  242. EdbName string `description:"指标名称"`
  243. Frequency string `description:"频率"`
  244. Unit string `description:"单位"`
  245. ClassifyId int `description:"分类id"`
  246. CalculateFormula string `description:"计算公式"`
  247. EdbInfoIdArr []struct {
  248. EdbInfoId int `description:"指标id"`
  249. FromTag string `description:"指标对应标签"`
  250. }
  251. }
  252. // ExecPythonEdbReq 执行python代码运算指标的请求参数
  253. type ExecPythonEdbReq struct {
  254. PythonCode string `description:"python代码"`
  255. }
  256. // AddPythonEdbReq 添加python代码运算指标的请求参数
  257. type AddPythonEdbReq struct {
  258. AdminId int `description:"添加人id"`
  259. AdminName string `description:"添加人名称"`
  260. EdbInfoId int `description:"指标id"`
  261. EdbName string `description:"指标名称"`
  262. Frequency string `description:"频度"`
  263. Unit string `description:"单位"`
  264. ClassifyId int `description:"分类id"`
  265. PythonCode string `description:"python代码"`
  266. }
  267. // AnalysisPythonCode 解析Python代码,获取关联code
  268. func AnalysisPythonCode(pythonCode, edbName string) (edbInfoList []*EdbInfo) {
  269. tmpEdbCodeList := make([]string, 0) //临时指标code
  270. edbCodeLen := 0 //指标数
  271. tmpList := strings.Split(pythonCode, "\n")
  272. for _, v := range tmpList {
  273. if strings.Contains(v, "edb_code") {
  274. edbCodeLen++
  275. tmpCodeStrList := strings.Split(v, "edb_code")
  276. if len(tmpCodeStrList) > 1 {
  277. //根据单引号获取
  278. tmpCodeStrList2 := strings.Split(tmpCodeStrList[1], "'")
  279. if len(tmpCodeStrList2) > 1 {
  280. if tmpCodeStrList2[1] != "" {
  281. tmpEdbCodeList = append(tmpEdbCodeList, tmpCodeStrList2[1])
  282. }
  283. }
  284. //根据双引号获取
  285. tmpCodeStrList3 := strings.Split(tmpCodeStrList[1], `"`)
  286. if len(tmpCodeStrList3) > 1 {
  287. if tmpCodeStrList3[1] != "" {
  288. tmpEdbCodeList = append(tmpEdbCodeList, tmpCodeStrList3[1])
  289. }
  290. }
  291. }
  292. }
  293. }
  294. for _, v := range tmpEdbCodeList {
  295. fmt.Println(v)
  296. item, _ := GetEdbInfoOnlyByEdbCode(v)
  297. if item != nil {
  298. edbInfoList = append(edbInfoList, item)
  299. }
  300. }
  301. if len(edbInfoList) != edbCodeLen {
  302. //code匹配失败,需要短信提醒
  303. go alarm_msg.SendAlarmMsg(fmt.Sprintf("python代码关联指标匹配失败,指标名称:%s;实际关联%d个,匹配上%d个", edbName, edbCodeLen, len(edbInfoList)), 3)
  304. }
  305. return
  306. }