base_from_python.go 12 KB

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