base_from_python.go 12 KB

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