edb_data_insert_config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. package data_manage
  2. import (
  3. "errors"
  4. "eta/eta_mobile/models/mgo"
  5. "eta/eta_mobile/utils"
  6. "fmt"
  7. "github.com/beego/beego/v2/client/orm"
  8. "go.mongodb.org/mongo-driver/bson"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "strconv"
  11. "time"
  12. )
  13. // EdbDataInsertConfig 指标数据插入配置表
  14. type EdbDataInsertConfig struct {
  15. EdbInfoId int `orm:"column(edb_info_id);pk" description:"指标id"`
  16. Date time.Time `description:"插入的日期"`
  17. Value string `description:"插入的值"`
  18. RealDate time.Time `description:"实际数据的值日期"`
  19. ModifyTime time.Time `description:"数据更新时间"`
  20. CreateTime time.Time `description:"数据插入的时间"`
  21. }
  22. // GetEdbDataInsertConfigByEdbId 根据指标id 获取数据插入配置详情
  23. func GetEdbDataInsertConfigByEdbId(edbInfoId int) (item *EdbDataInsertConfig, err error) {
  24. o := orm.NewOrmUsingDB("data")
  25. sql := ` SELECT * FROM edb_data_insert_config WHERE edb_info_id=? `
  26. err = o.Raw(sql, edbInfoId).QueryRow(&item)
  27. return
  28. }
  29. // GetEdbDataInsertConfigByEdbIdList 根据指标id列表 获取数据插入配置详情
  30. func GetEdbDataInsertConfigByEdbIdList(edbInfoIdList []int) (items []*EdbDataInsertConfig, err error) {
  31. num := len(edbInfoIdList)
  32. if num <= 0 {
  33. return
  34. }
  35. o := orm.NewOrmUsingDB("data")
  36. sql := ` SELECT * FROM edb_data_insert_config WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  37. _, err = o.Raw(sql, edbInfoIdList).QueryRows(&items)
  38. return
  39. }
  40. // CreateEdbDataInsertConfigAndData 创建数据插入配置规则,及插入数据
  41. func CreateEdbDataInsertConfigAndData(edbInfo *EdbInfo, date time.Time, value string) (err error, errMsg string, isSendEmail bool) {
  42. isSendEmail = true
  43. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  44. if tableName == `` {
  45. err = errors.New("找不到该指标的数据表")
  46. return
  47. }
  48. dateStr := date.Format(utils.FormatDate)
  49. var saveValue string
  50. if value != "" {
  51. floatValue, e := strconv.ParseFloat(value, 64)
  52. if e != nil {
  53. err = e
  54. fmt.Println("转换失败:", e.Error())
  55. return
  56. }
  57. saveValue = utils.SubFloatToString(floatValue, 30)
  58. }
  59. to, err := orm.NewOrmUsingDB("data").Begin()
  60. if err != nil {
  61. return
  62. }
  63. defer func() {
  64. if err != nil {
  65. _ = to.Rollback()
  66. } else {
  67. _ = to.Commit()
  68. }
  69. }()
  70. var oldConfigDate time.Time //之前配置的日期
  71. // 添加/变更配置
  72. {
  73. var item *EdbDataInsertConfig
  74. sql := ` SELECT * FROM edb_data_insert_config WHERE edb_info_id=? `
  75. err = to.Raw(sql, edbInfo.EdbInfoId).QueryRow(&item)
  76. if err != nil && err.Error() != utils.ErrNoRow() {
  77. return
  78. }
  79. err = nil
  80. // 如果是没有配置,那么就需要添加配置
  81. if item == nil {
  82. var currLatestDate time.Time
  83. currLatestDateStr := edbInfo.LatestDate // 实际日期
  84. if currLatestDateStr != `` && currLatestDateStr != `0000-00-00` {
  85. currLatestDate, _ = time.ParseInLocation(utils.FormatDate, currLatestDateStr, time.Local)
  86. }
  87. if !currLatestDate.IsZero() && (currLatestDate.After(date) || currLatestDate.Equal(date)) {
  88. errMsg = `选择日期不能早于/等于数据最新日期`
  89. err = errors.New("选择日期不能早于/等于数据最新日期,数据最新日期:" + edbInfo.EndDate + ";填写日期:" + dateStr)
  90. isSendEmail = false
  91. return
  92. }
  93. realDate, _ := time.ParseInLocation(utils.FormatDate, edbInfo.LatestDate, time.Local)
  94. item = &EdbDataInsertConfig{
  95. EdbInfoId: edbInfo.EdbInfoId,
  96. Date: date,
  97. Value: saveValue,
  98. RealDate: realDate,
  99. ModifyTime: time.Now(),
  100. CreateTime: time.Now(),
  101. }
  102. _, err = to.Insert(item)
  103. } else {
  104. if date.Equal(item.RealDate) || date.Before(item.RealDate) {
  105. errMsg = `选择日期不能早于/等于数据最新日期`
  106. err = errors.New("选择日期不能早于/等于数据最新日期,数据最新日期:" + edbInfo.EndDate + ";填写日期:" + dateStr)
  107. isSendEmail = false
  108. return
  109. }
  110. oldConfigDate = item.Date // 之前配置的日期
  111. item.Date = date
  112. item.Value = saveValue
  113. item.ModifyTime = time.Now()
  114. _, err = to.Update(item, "Date", "Value", "ModifyTime")
  115. }
  116. if err != nil {
  117. return
  118. }
  119. }
  120. // 指标明细数据更新
  121. if edbInfo.Source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  122. dateStr, err = updateInsertConfigValueByMongo(to, edbInfo, oldConfigDate, date, value)
  123. } else if edbInfo.Source == utils.DATA_SOURCE_THS && edbInfo.SubSource == utils.DATA_SUB_SOURCE_HIGH_FREQUENCY && utils.UseMongo {
  124. dateStr, err = updateThsHfInsertConfigValueByMongo(to, edbInfo, oldConfigDate, date, value)
  125. } else {
  126. dateStr, err = updateInsertConfigValueByMysql(to, edbInfo, oldConfigDate, date, value)
  127. }
  128. if err != nil {
  129. return
  130. }
  131. // 指标信息更新
  132. edbInfo.EndDate = dateStr
  133. _, err = to.Update(edbInfo, "EndDate")
  134. return
  135. }
  136. // updateInsertConfigValueByMysql
  137. // @Description: 从mysql更新或插入配置值
  138. // @author: Roc
  139. // @datetime 2024-05-09 11:05:41
  140. // @param to orm.TxOrmer
  141. // @param edbInfo *EdbInfo
  142. // @param oldConfigDate
  143. // @param date time.Time
  144. // @param value string
  145. // @return dateStr string
  146. // @return err error
  147. func updateInsertConfigValueByMysql(to orm.TxOrmer, edbInfo *EdbInfo, oldConfigDate, date time.Time, value string) (dateStr string, err error) {
  148. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  149. if tableName == `` {
  150. err = errors.New("找不到该指标的数据表")
  151. return
  152. }
  153. dateStr = date.Format(utils.FormatDate)
  154. timestamp := date.UnixNano() / 1e6
  155. timeStr := fmt.Sprintf("%d", timestamp)
  156. var saveValue string
  157. if value != "" {
  158. floatValue, e := strconv.ParseFloat(value, 64)
  159. if e != nil {
  160. err = e
  161. fmt.Println("转换失败:", e.Error())
  162. return
  163. }
  164. saveValue = utils.SubFloatToString(floatValue, 30)
  165. }
  166. var offsetDate string
  167. // 更改数据
  168. {
  169. var edbDateData *EdbDataList
  170. if !oldConfigDate.IsZero() {
  171. sql := `SELECT edb_data_id,edb_info_id,data_time,value,data_timestamp FROM %s WHERE edb_info_id=? AND data_time = ?`
  172. sql = fmt.Sprintf(sql, tableName)
  173. err = to.Raw(sql, edbInfo.EdbInfoId, oldConfigDate.Format(utils.FormatDate)).QueryRow(&edbDateData)
  174. if err != nil && err.Error() != utils.ErrNoRow() {
  175. return
  176. }
  177. err = nil
  178. }
  179. // 如果是没有历史数据,那么就需要增加数据
  180. if edbDateData == nil {
  181. addSql := ` INSERT INTO %s (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) VALUES ( %d, "%s", "%s", "%s", now(), now(), %s) `
  182. addSql = fmt.Sprintf(addSql, tableName, edbInfo.EdbInfoId, edbInfo.EdbCode, dateStr, saveValue, timeStr)
  183. _, err = to.Raw(addSql).Exec()
  184. } else if value == "" {
  185. // 传空值时删除
  186. sql := `SELECT data_time FROM %s WHERE edb_info_id=? ORDER BY data_time DESC LIMIT 1 OFFSET 1`
  187. sql = fmt.Sprintf(sql, tableName)
  188. err = to.Raw(sql, edbInfo.EdbInfoId).QueryRow(&offsetDate)
  189. if err != nil && err.Error() != utils.ErrNoRow() {
  190. return
  191. }
  192. dateStr = offsetDate
  193. deleteSql := `DELETE FROM %s WHERE edb_data_id = %d;`
  194. deleteSql = fmt.Sprintf(deleteSql, tableName, edbDateData.EdbDataId)
  195. _, err = to.Raw(deleteSql).Exec()
  196. } else {
  197. updateSql := `UPDATE %s SET data_time = "%s", value = "%s", modify_time= now(), data_timestamp= %s WHERE edb_data_id = %d;`
  198. updateSql = fmt.Sprintf(updateSql, tableName, dateStr, saveValue, timeStr, edbDateData.EdbDataId)
  199. _, err = to.Raw(updateSql).Exec()
  200. }
  201. if err != nil {
  202. return
  203. }
  204. }
  205. return
  206. }
  207. // updateInsertConfigValueByMongo
  208. // @Description: 从mongo更新或插入配置值
  209. // @author: Roc
  210. // @datetime 2024-05-09 11:05:49
  211. // @param to orm.TxOrmer
  212. // @param edbInfo *EdbInfo
  213. // @param oldConfigDate
  214. // @param newDate time.Time
  215. // @param value string
  216. // @return dateStr string
  217. // @return err error
  218. func updateInsertConfigValueByMongo(to orm.TxOrmer, edbInfo *EdbInfo, oldConfigDate, newDate time.Time, value string) (dateStr string, err error) {
  219. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  220. if tableName == `` {
  221. err = errors.New("找不到该指标的数据表")
  222. return
  223. }
  224. dateStr = newDate.Format(utils.FormatDate)
  225. timestamp := newDate.UnixNano() / 1e6
  226. var floatValue float64
  227. if value != "" {
  228. floatValue, err = strconv.ParseFloat(value, 64)
  229. if err != nil {
  230. fmt.Println("转换失败:", err.Error())
  231. return
  232. }
  233. }
  234. mogDataObj := mgo.EdbDataBusiness{}
  235. coll := mogDataObj.GetCollection()
  236. var edbDateData *mgo.EdbDataBusiness
  237. if !oldConfigDate.IsZero() {
  238. // 构建查询条件
  239. queryConditions := bson.M{
  240. "edb_info_id": edbInfo.EdbInfoId,
  241. "data_time": oldConfigDate,
  242. }
  243. edbDateData, err = mogDataObj.GetItem(queryConditions)
  244. //if tmpErr != nil && tmpErr == mongo.ErrNoDocuments {
  245. // err = tmpErr
  246. // return
  247. //}
  248. if err != nil && err != mongo.ErrNoDocuments {
  249. return
  250. }
  251. err = nil
  252. }
  253. // 如果是没有历史数据,那么就需要增加数据
  254. if edbDateData == nil {
  255. addDataItem := mgo.EdbDataBusiness{
  256. //ID: primitive.ObjectID{},
  257. EdbInfoId: edbInfo.EdbInfoId,
  258. EdbCode: edbInfo.EdbCode,
  259. DataTime: newDate,
  260. Value: floatValue,
  261. CreateTime: time.Now(),
  262. ModifyTime: time.Now(),
  263. DataTimestamp: timestamp,
  264. }
  265. err = mogDataObj.InsertDataByColl(coll, addDataItem)
  266. if err != nil {
  267. fmt.Println("mogDataObj.BatchInsertData() Err:" + err.Error())
  268. return
  269. }
  270. return
  271. }
  272. // 数据清空
  273. if value == "" {
  274. queryConditions := bson.M{
  275. "edb_info_id": edbInfo.EdbInfoId,
  276. }
  277. // 获取最新的两条数据
  278. tmpDataList, tmpErr := mogDataObj.GetLimitDataList(queryConditions, 2, []string{"-data_time"})
  279. if tmpErr != nil {
  280. fmt.Println("mogDataObj.GetLimitDataList() Err:" + tmpErr.Error())
  281. return
  282. }
  283. // 如果并没有两条数据,那么就返回
  284. if len(tmpDataList) < 2 {
  285. return
  286. }
  287. // 实际应该是倒数第二条数据的日期
  288. dateStr = tmpDataList[1].DataTime.Format(utils.FormatDate)
  289. // 删除插入的数据
  290. err = mogDataObj.RemoveManyByColl(coll, bson.M{"_id": tmpDataList[0].ID})
  291. return
  292. }
  293. // 更新配置的数据
  294. updateData := bson.M{"$set": bson.M{
  295. "value": floatValue,
  296. "modify_time": time.Now(),
  297. "data_time": newDate,
  298. "data_timestamp": timestamp,
  299. }}
  300. err = mogDataObj.UpdateDataByColl(coll, bson.M{"_id": edbDateData.ID}, updateData)
  301. return
  302. }
  303. func updateThsHfInsertConfigValueByMongo(to orm.TxOrmer, edbInfo *EdbInfo, oldConfigDate, newDate time.Time, value string) (dateStr string, err error) {
  304. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  305. if tableName == `` {
  306. err = errors.New("找不到该指标的数据表")
  307. return
  308. }
  309. dateStr = newDate.Format(utils.FormatDate)
  310. timestamp := newDate.UnixNano() / 1e6
  311. var floatValue float64
  312. if value != "" {
  313. floatValue, err = strconv.ParseFloat(value, 64)
  314. if err != nil {
  315. fmt.Println("转换失败:", err.Error())
  316. return
  317. }
  318. }
  319. mogDataObj := mgo.EdbDataThsHf{}
  320. coll := mogDataObj.GetCollection()
  321. var edbDateData *mgo.EdbDataThsHf
  322. if !oldConfigDate.IsZero() {
  323. // 构建查询条件
  324. queryConditions := bson.M{
  325. "edb_info_id": edbInfo.EdbInfoId,
  326. "data_time": oldConfigDate,
  327. }
  328. edbDateData, err = mogDataObj.GetItem(queryConditions)
  329. //if tmpErr != nil && tmpErr == mongo.ErrNoDocuments {
  330. // err = tmpErr
  331. // return
  332. //}
  333. if err != nil && err != mongo.ErrNoDocuments {
  334. return
  335. }
  336. err = nil
  337. }
  338. // 如果是没有历史数据,那么就需要增加数据
  339. if edbDateData == nil {
  340. addDataItem := mgo.EdbDataThsHf{
  341. //ID: primitive.ObjectID{},
  342. EdbInfoId: edbInfo.EdbInfoId,
  343. EdbCode: edbInfo.EdbCode,
  344. DataTime: newDate,
  345. Value: floatValue,
  346. CreateTime: time.Now(),
  347. ModifyTime: time.Now(),
  348. DataTimestamp: timestamp,
  349. }
  350. err = mogDataObj.InsertDataByColl(coll, addDataItem)
  351. if err != nil {
  352. fmt.Println("mogDataObj.BatchInsertData() Err:" + err.Error())
  353. return
  354. }
  355. return
  356. }
  357. // 数据清空
  358. if value == "" {
  359. queryConditions := bson.M{
  360. "edb_info_id": edbInfo.EdbInfoId,
  361. }
  362. // 获取最新的两条数据
  363. tmpDataList, tmpErr := mogDataObj.GetLimitDataList(queryConditions, 2, []string{"-data_time"})
  364. if tmpErr != nil {
  365. fmt.Println("mogDataObj.GetLimitDataList() Err:" + tmpErr.Error())
  366. return
  367. }
  368. // 如果并没有两条数据,那么就返回
  369. if len(tmpDataList) < 2 {
  370. return
  371. }
  372. // 实际应该是倒数第二条数据的日期
  373. dateStr = tmpDataList[1].DataTime.Format(utils.FormatDate)
  374. // 删除插入的数据
  375. err = mogDataObj.RemoveManyByColl(coll, bson.M{"_id": tmpDataList[0].ID})
  376. return
  377. }
  378. // 更新配置的数据
  379. updateData := bson.M{"$set": bson.M{
  380. "value": floatValue,
  381. "modify_time": time.Now(),
  382. "data_time": newDate,
  383. "data_timestamp": timestamp,
  384. }}
  385. err = mogDataObj.UpdateDataByColl(coll, bson.M{"_id": edbDateData.ID}, updateData)
  386. return
  387. }