base_from_python.go 13 KB

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