base_from_python.go 12 KB

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