base_from_python.go 12 KB

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