base_from_adjust.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "hongze/hongze_edb_lib/services/alarm_msg"
  7. "hongze/hongze_edb_lib/utils"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // EdbDataAdjust 数据调整指标数据结构体
  13. type EdbDataAdjust 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. // AddAdjustEdbData 保存数据调整请求的数据的参数
  24. type AddAdjustEdbData struct {
  25. Date string `description:"数据日期"`
  26. TimestampStr string `description:"日期时间戳"`
  27. Value float64 `description:"数据值"`
  28. }
  29. // SaveAdjustEdb 保存数据调整指标
  30. func SaveAdjustEdb(req SaveAdjustEdbReq) (edbInfo *EdbInfo, err error, errMsg string) {
  31. errMsg = `添加指标失败`
  32. o := orm.NewOrm()
  33. to, err := o.Begin()
  34. if err != nil {
  35. return
  36. }
  37. defer func() {
  38. if err != nil {
  39. _ = to.Rollback()
  40. fmt.Println("SaveAdjustEdb,Err:" + err.Error())
  41. go alarm_msg.SendAlarmMsg(" 保存数据调整指标失败:err:"+err.Error(), 3)
  42. } else {
  43. _ = to.Commit()
  44. }
  45. }()
  46. var edbCode string
  47. if req.EdbInfoId <= 0 {
  48. //指标code生成
  49. randStr := utils.GetRandDigit(4)
  50. edbCode = `C` + time.Now().Format("060102") + randStr
  51. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  52. uniqueCode := utils.MD5(utils.DATA_PREFIX + "_" + timestamp)
  53. edbInfo = &EdbInfo{
  54. Source: utils.DATA_SOURCE_CALCULATE_ADJUST,
  55. SourceName: "数据调整",
  56. EdbCode: edbCode,
  57. EdbName: utils.TrimStr(req.EdbName),
  58. EdbNameSource: utils.TrimStr(req.EdbName),
  59. Frequency: utils.TrimStr(req.Frequency),
  60. Unit: utils.TrimStr(req.Unit),
  61. ClassifyId: req.ClassifyId,
  62. SysUserId: req.AdminId,
  63. SysUserRealName: req.AdminName,
  64. CreateTime: time.Now(),
  65. ModifyTime: time.Now(),
  66. UniqueCode: uniqueCode,
  67. EdbType: 2,
  68. }
  69. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  70. if tmpErr != nil {
  71. err = tmpErr
  72. return
  73. }
  74. edbInfo.EdbInfoId = int(newEdbInfoId)
  75. // 获取来源指标
  76. fromEdbInfo, tmpErr := GetEdbInfoById(req.FromEdbInfoId)
  77. if tmpErr != nil {
  78. err = tmpErr
  79. errMsg = "获取来源指标信息失败"
  80. return
  81. }
  82. //关联关系
  83. {
  84. calculateMappingItem := new(EdbInfoCalculateMapping)
  85. calculateMappingItem.CreateTime = time.Now()
  86. calculateMappingItem.ModifyTime = time.Now()
  87. calculateMappingItem.Sort = 1
  88. calculateMappingItem.EdbCode = edbCode
  89. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  90. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  91. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  92. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  93. calculateMappingItem.FromSource = fromEdbInfo.Source
  94. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  95. calculateMappingItem.FromTag = ""
  96. calculateMappingItem.Source = edbInfo.Source
  97. calculateMappingItem.SourceName = edbInfo.SourceName
  98. _, err = to.Insert(calculateMappingItem)
  99. if err != nil {
  100. return
  101. }
  102. }
  103. //相关配置
  104. {
  105. var fromEdbEndDate time.Time
  106. if fromEdbInfo.EndDate != `0000-00-00` {
  107. fromEdbEndDate, _ = time.Parse(utils.FormatDate, fromEdbInfo.EndDate)
  108. }
  109. edbAdjustConf := &EdbAdjustConf{
  110. EdbInfoId: edbInfo.EdbInfoId,
  111. SourceEndDate: fromEdbEndDate,
  112. ModifyTime: time.Now(),
  113. CreateTime: time.Now(),
  114. }
  115. _, err = to.Insert(edbAdjustConf)
  116. if err != nil {
  117. return
  118. }
  119. }
  120. } else {
  121. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  122. if err != nil {
  123. return
  124. }
  125. // 更新指标信息
  126. edbInfo.EdbName = utils.TrimStr(req.EdbName)
  127. edbInfo.EdbNameSource = utils.TrimStr(req.EdbName)
  128. edbInfo.Frequency = utils.TrimStr(req.Frequency)
  129. edbInfo.Unit = utils.TrimStr(req.Unit)
  130. edbInfo.ClassifyId = req.ClassifyId
  131. edbInfo.ModifyTime = time.Now()
  132. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  133. if err != nil {
  134. return
  135. }
  136. // 指标code
  137. edbCode = edbInfo.EdbCode
  138. // 清除数据
  139. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_ADJUST)
  140. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  141. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  142. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  143. if err != nil {
  144. return
  145. }
  146. //相关配置
  147. {
  148. // 获取来源指标
  149. calculateMapping, tmpErr := GetEdbInfoCalculateMappingDetail(edbInfo.EdbInfoId)
  150. if tmpErr != nil {
  151. errMsg = `关联指标获取异常`
  152. err = tmpErr
  153. return
  154. }
  155. fromEdbInfo, tmpErr := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  156. if tmpErr != nil {
  157. errMsg = `来源指标不存在`
  158. err = tmpErr
  159. return
  160. }
  161. var fromEdbEndDate time.Time
  162. if fromEdbInfo.EndDate != `0000-00-00` {
  163. fromEdbEndDate, _ = time.Parse(utils.FormatDate, fromEdbInfo.EndDate)
  164. }
  165. // 获取之前的配置
  166. var edbAdjustConf *EdbAdjustConf
  167. sql := ` SELECT * FROM edb_adjust_conf WHERE edb_info_id=? `
  168. err = o.Raw(sql, edbInfo.EdbInfoId).QueryRow(&edbAdjustConf)
  169. if err != nil {
  170. errMsg = "获取指标配置失败"
  171. return
  172. }
  173. // 修改配置的最晚日期
  174. edbAdjustConf.SourceEndDate = fromEdbEndDate
  175. edbAdjustConf.ModifyTime = time.Now()
  176. _, err = to.Update(edbAdjustConf, "SourceEndDate", "ModifyTime")
  177. if err != nil {
  178. errMsg = "更新指标配置失败"
  179. return
  180. }
  181. }
  182. }
  183. dataList := req.DataList
  184. dataObj := make(map[string]AddAdjustEdbData)
  185. for _, item := range dataList {
  186. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.Date, time.Local)
  187. if tmpErr != nil {
  188. err = tmpErr
  189. return
  190. }
  191. timestamp := currentDate.UnixNano() / 1e6
  192. timestampStr := fmt.Sprintf("%d", timestamp)
  193. tmpVal, ok := dataObj[item.Date]
  194. if !ok {
  195. tmpVal = AddAdjustEdbData{
  196. Date: item.Date,
  197. TimestampStr: timestampStr,
  198. Value: item.Value,
  199. }
  200. } else {
  201. tmpVal.Value = item.Value
  202. }
  203. dataObj[item.Date] = tmpVal
  204. }
  205. var isAdd bool
  206. dataTableName := GetEdbDataTableName(edbInfo.Source)
  207. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  208. for _, item := range dataObj {
  209. //值
  210. val := item.Value
  211. saveVal := utils.SubFloatToString(val, 20)
  212. addSql += GetAddSql(fmt.Sprint(edbInfo.EdbInfoId), edbCode, item.Date, item.TimestampStr, saveVal)
  213. isAdd = true
  214. }
  215. if isAdd {
  216. addSql = strings.TrimRight(addSql, ",")
  217. _, err = to.Raw(addSql).Exec()
  218. if err != nil {
  219. return
  220. }
  221. }
  222. return
  223. }
  224. // RefreshAllAdjustEdb 刷新所有 数据调整指标
  225. func RefreshAllAdjustEdb(edbInfo *EdbInfo, fromEdbInfo *EdbInfo) (err error) {
  226. o := orm.NewOrm()
  227. to, err := o.Begin()
  228. if err != nil {
  229. return
  230. }
  231. defer func() {
  232. if err != nil {
  233. fmt.Println("RefreshAllPythonEdb,Err:" + err.Error())
  234. _ = to.Rollback()
  235. } else {
  236. _ = to.Commit()
  237. }
  238. }()
  239. // 当前数据表名
  240. dataTableName := GetEdbDataTableName(edbInfo.Source)
  241. // 获取之前的配置
  242. var edbAdjustConf *EdbAdjustConf
  243. sql := ` SELECT * FROM edb_adjust_conf WHERE edb_info_id=? `
  244. err = o.Raw(sql, edbInfo.EdbInfoId).QueryRow(&edbAdjustConf)
  245. if err != nil {
  246. err = errors.New("获取指标配置失败")
  247. return
  248. }
  249. // 查询关联指标的数据
  250. var condition string
  251. var pars []interface{}
  252. condition += " AND edb_info_id=? AND data_time > ? "
  253. pars = append(pars, fromEdbInfo.EdbInfoId, edbAdjustConf.SourceEndDate)
  254. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 1)
  255. if err != nil {
  256. return err
  257. }
  258. // 已经入库的日期数据
  259. existDataMap := make(map[string]float64)
  260. {
  261. var tmpCondition string
  262. var tmpPars []interface{}
  263. condition += " AND edb_info_id=? AND data_time > ? "
  264. pars = append(pars, fromEdbInfo.EdbInfoId, edbAdjustConf.SourceEndDate)
  265. existDataList, tmpErr := GetEdbDataListAllByTo(to, tmpCondition, tmpPars, edbInfo.Source, 1)
  266. if tmpErr != nil {
  267. err = tmpErr
  268. return
  269. }
  270. for _, v := range existDataList {
  271. existDataMap[v.DataTime] = v.Value
  272. }
  273. }
  274. var isAdd bool
  275. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  276. for _, item := range dataList {
  277. currDay := item.DataTime
  278. //值
  279. val := item.Value
  280. saveVal := utils.SubFloatToString(val, 20)
  281. if existVal, ok := existDataMap[currDay]; !ok {
  282. //格式化时间
  283. currentDate, tmpErr := time.Parse(utils.FormatDate, item.DataTime)
  284. if tmpErr != nil {
  285. err = tmpErr
  286. return
  287. }
  288. timestamp := currentDate.UnixNano() / 1e6
  289. timestampStr := fmt.Sprintf("%d", timestamp)
  290. addSql += GetAddSql(fmt.Sprint(edbInfo.EdbInfoId), edbInfo.EdbCode, item.DataTime, timestampStr, saveVal)
  291. isAdd = true
  292. } else {
  293. if existVal != item.Value {
  294. sql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  295. sql = fmt.Sprintf(sql, dataTableName)
  296. _, err = to.Raw(sql, saveVal, edbInfo.EdbInfoId, currDay).Exec()
  297. if err != nil {
  298. return err
  299. }
  300. }
  301. }
  302. }
  303. if isAdd {
  304. addSql = strings.TrimRight(addSql, ",")
  305. _, err = to.Raw(addSql).Exec()
  306. if err != nil {
  307. return
  308. }
  309. }
  310. // 变更数据调整配置表的实际结束日期
  311. {
  312. var fromEdbEndDate time.Time
  313. if fromEdbInfo.EndDate != `0000-00-00` {
  314. fromEdbEndDate, _ = time.Parse(utils.FormatDate, fromEdbInfo.EndDate)
  315. }
  316. edbAdjustConf.SourceEndDate = fromEdbEndDate
  317. edbAdjustConf.ModifyTime = time.Now()
  318. _, err = to.Update(edbAdjustConf, "SourceEndDate", "ModifyTime")
  319. }
  320. return
  321. }
  322. // SaveAdjustEdbReq 保存数据调整请求参数(请求指标服务)
  323. type SaveAdjustEdbReq struct {
  324. AdminId int `description:"添加人id"`
  325. AdminName string `description:"添加人名称"`
  326. EdbInfoId int `description:"指标id"`
  327. FromEdbInfoId int `description:"来源指标id"`
  328. EdbName string `description:"指标名称"`
  329. Frequency string `description:"频度"`
  330. Unit string `description:"单位"`
  331. ClassifyId int `description:"分类id"`
  332. DataList []SaveAdjustEdbDataReq `description:"指标对应的数据值"`
  333. }
  334. // SaveAdjustEdbDataReq 保存数据调整请求的数据的参数
  335. type SaveAdjustEdbDataReq struct {
  336. Date string `description:"数据日期"`
  337. Value float64 `description:"数据值"`
  338. }
  339. // FixData 修复数据
  340. func FixData() {
  341. var list []*EdbInfo
  342. o := orm.NewOrm()
  343. sql := ` SELECT * FROM edb_info WHERE source=? `
  344. _, err := o.Raw(sql, 40).QueryRows(&list)
  345. for _, edbInfo := range list {
  346. // 获取来源指标
  347. calculateMapping, tmpErr := GetEdbInfoCalculateMappingDetail(edbInfo.EdbInfoId)
  348. if tmpErr != nil {
  349. fmt.Println(edbInfo.EdbInfoId, "关联指标获取异常;err:", tmpErr)
  350. continue
  351. }
  352. fromEdbInfo, tmpErr := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  353. if tmpErr != nil {
  354. fmt.Println(edbInfo.EdbInfoId, "来源指标不存在;err:", tmpErr)
  355. continue
  356. }
  357. var fromEdbEndDate time.Time
  358. if fromEdbInfo.EndDate != `0000-00-00` {
  359. fromEdbEndDate, _ = time.Parse(utils.FormatDate, fromEdbInfo.EndDate)
  360. }
  361. // 获取之前的配置
  362. edbAdjustConf := &EdbAdjustConf{
  363. EdbInfoId: edbInfo.EdbInfoId,
  364. SourceEndDate: fromEdbEndDate,
  365. ModifyTime: time.Now(),
  366. CreateTime: time.Now(),
  367. }
  368. _, err = o.Insert(edbAdjustConf)
  369. if err != nil {
  370. fmt.Println(edbInfo.EdbInfoId, "添加失败;err:", tmpErr)
  371. continue
  372. }
  373. }
  374. fmt.Println("end")
  375. }