edb_data_insert_config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. package data_manage
  2. import (
  3. "errors"
  4. "eta_gn/eta_api/global"
  5. "eta_gn/eta_api/models/mgo"
  6. "eta_gn/eta_api/utils"
  7. "fmt"
  8. "go.mongodb.org/mongo-driver/bson"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "gorm.io/gorm"
  11. "strconv"
  12. "time"
  13. )
  14. // EdbDataInsertConfig 指标数据插入配置表
  15. type EdbDataInsertConfig struct {
  16. EdbInfoId int `orm:"column(edb_info_id);pk" gorm:"primaryKey;autoIncrement:false" description:"指标id"`
  17. Date time.Time `description:"插入的日期"`
  18. Value string `description:"插入的值"`
  19. RealDate time.Time `description:"实际数据的值日期"`
  20. ModifyTime time.Time `description:"数据更新时间"`
  21. CreateTime time.Time `description:"数据插入的时间"`
  22. }
  23. // GetEdbDataInsertConfigByEdbId 根据指标id 获取数据插入配置详情
  24. func GetEdbDataInsertConfigByEdbId(edbInfoId int) (item *EdbDataInsertConfig, err error) {
  25. sql := ` SELECT * FROM edb_data_insert_config WHERE edb_info_id=? `
  26. err = global.DmSQL["data"].Raw(sql, edbInfoId).First(&item).Error
  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 := global.DmSQL["data"]
  36. sql := ` SELECT * FROM edb_data_insert_config WHERE edb_info_id in (` + utils.GetOrmInReplace(num) + `) `
  37. err = o.Raw(sql, edbInfoIdList).Find(&items).Error
  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 := global.DmSQL["data"].Begin()
  60. defer func() {
  61. if err != nil {
  62. _ = to.Rollback()
  63. } else {
  64. _ = to.Commit()
  65. }
  66. }()
  67. var oldConfigDate time.Time //之前配置的日期
  68. // 添加/变更配置
  69. {
  70. var item *EdbDataInsertConfig
  71. sql := ` SELECT * FROM edb_data_insert_config WHERE edb_info_id=? `
  72. err = to.Raw(sql, edbInfo.EdbInfoId).First(&item).Error
  73. if err != nil && !utils.IsErrNoRow(err) {
  74. return
  75. }
  76. err = nil
  77. // 如果是没有配置,那么就需要添加配置
  78. if item == nil || item.EdbInfoId <= 0 {
  79. var currLatestDate time.Time
  80. currLatestDateStr := edbInfo.LatestDate // 实际日期
  81. if currLatestDateStr != `` && currLatestDateStr != `0000-00-00` {
  82. currLatestDate, _ = time.ParseInLocation(utils.FormatDate, currLatestDateStr, time.Local)
  83. }
  84. if !currLatestDate.IsZero() && (currLatestDate.After(date) || currLatestDate.Equal(date)) {
  85. errMsg = `选择日期不能早于/等于数据最新日期`
  86. err = errors.New("选择日期不能早于/等于数据最新日期,数据最新日期:" + utils.TimeToFormatDate(edbInfo.EndDate) + ";填写日期:" + dateStr)
  87. isSendEmail = false
  88. return
  89. }
  90. realDate, _ := time.ParseInLocation(utils.FormatDate, edbInfo.LatestDate, time.Local)
  91. item = &EdbDataInsertConfig{
  92. EdbInfoId: edbInfo.EdbInfoId,
  93. Date: date,
  94. Value: saveValue,
  95. RealDate: realDate,
  96. ModifyTime: time.Now(),
  97. CreateTime: time.Now(),
  98. }
  99. err = to.Create(item).Error
  100. } else {
  101. if date.Equal(item.RealDate) || date.Before(item.RealDate) {
  102. errMsg = `选择日期不能早于/等于数据最新日期`
  103. err = errors.New("选择日期不能早于/等于数据最新日期,数据最新日期:" + utils.TimeToFormatDate(edbInfo.EndDate) + ";填写日期:" + dateStr)
  104. isSendEmail = false
  105. return
  106. }
  107. oldConfigDate = item.Date // 之前配置的日期
  108. item.Date = date
  109. item.Value = saveValue
  110. item.ModifyTime = time.Now()
  111. err = to.Select("Date", "Value", "ModifyTime").Updates(item).Error
  112. }
  113. if err != nil {
  114. return
  115. }
  116. }
  117. // 指标明细数据更新
  118. if edbInfo.Source == utils.DATA_SOURCE_BUSINESS && utils.UseMongo {
  119. dateStr, err = updateInsertConfigValueByMongo(to, edbInfo, oldConfigDate, date, value)
  120. } else if edbInfo.Source == utils.DATA_SOURCE_THS && edbInfo.SubSource == utils.DATA_SUB_SOURCE_HIGH_FREQUENCY && utils.UseMongo {
  121. dateStr, err = updateThsHfInsertConfigValueByMongo(to, edbInfo, oldConfigDate, date, value)
  122. } else {
  123. dateStr, err = updateInsertConfigValueByMysql(to, edbInfo, oldConfigDate, date, value)
  124. }
  125. if err != nil {
  126. return
  127. }
  128. // 指标信息更新
  129. if dateStr != `` {
  130. endDateTime, tmpErr := utils.FormatDateStrToTime(dateStr)
  131. if tmpErr != nil {
  132. err = tmpErr
  133. return
  134. }
  135. edbInfo.EndDate = endDateTime
  136. err = to.Select("EndDate").Updates(edbInfo).Error
  137. }
  138. return
  139. }
  140. // updateInsertConfigValueByMysql
  141. // @Description: 从mysql更新或插入配置值
  142. // @author: Roc
  143. // @datetime 2024-05-09 11:05:41
  144. // @param to orm.TxOrmer
  145. // @param edbInfo *EdbInfo
  146. // @param oldConfigDate
  147. // @param date time.Time
  148. // @param value string
  149. // @return dateStr string
  150. // @return err error
  151. func updateInsertConfigValueByMysql(to *gorm.DB, edbInfo *EdbInfo, oldConfigDate, date time.Time, value string) (dateStr string, err error) {
  152. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  153. if tableName == `` {
  154. err = errors.New("找不到该指标的数据表")
  155. return
  156. }
  157. dateStr = date.Format(utils.FormatDate)
  158. timestamp := date.UnixNano() / 1e6
  159. timeStr := fmt.Sprintf("%d", timestamp)
  160. var saveValue string
  161. if value != "" {
  162. floatValue, e := strconv.ParseFloat(value, 64)
  163. if e != nil {
  164. err = e
  165. fmt.Println("转换失败:", e.Error())
  166. return
  167. }
  168. saveValue = utils.SubFloatToString(floatValue, 30)
  169. }
  170. var offsetDate string
  171. // 更改数据
  172. {
  173. var edbDateData *EdbDataList
  174. if !oldConfigDate.IsZero() {
  175. sql := `SELECT edb_data_id,edb_info_id,data_time,"value",data_timestamp FROM %s WHERE edb_info_id=? AND data_time = ?`
  176. sql = fmt.Sprintf(sql, tableName)
  177. err = to.Raw(sql, edbInfo.EdbInfoId, oldConfigDate.Format(utils.FormatDate)).Scan(&edbDateData).Error
  178. if err != nil && !utils.IsErrNoRow(err) {
  179. return
  180. }
  181. err = nil
  182. }
  183. // 如果是没有历史数据,那么就需要增加数据
  184. if edbDateData == nil {
  185. 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) `
  186. addSql = fmt.Sprintf(addSql, tableName, edbInfo.EdbInfoId, edbInfo.EdbCode, dateStr, saveValue, timeStr)
  187. err = to.Exec(addSql).Error
  188. } else if value == "" {
  189. // 传空值时删除
  190. sql := `SELECT data_time FROM %s WHERE edb_info_id=? ORDER BY data_time DESC LIMIT 1 OFFSET 1`
  191. sql = fmt.Sprintf(sql, tableName)
  192. err = to.Raw(sql, edbInfo.EdbInfoId).Scan(&offsetDate).Error
  193. if err != nil && !utils.IsErrNoRow(err) {
  194. return
  195. }
  196. dateStr = offsetDate
  197. deleteSql := `DELETE FROM %s WHERE edb_data_id = %d;`
  198. deleteSql = fmt.Sprintf(deleteSql, tableName, edbDateData.EdbDataId)
  199. err = to.Exec(deleteSql).Error
  200. } else {
  201. updateSql := `UPDATE %s SET data_time = '%s', value = '%s', modify_time= now(), data_timestamp= %s WHERE edb_data_id = %d;`
  202. updateSql = fmt.Sprintf(updateSql, tableName, dateStr, saveValue, timeStr, edbDateData.EdbDataId)
  203. err = to.Exec(updateSql).Error
  204. }
  205. if err != nil {
  206. return
  207. }
  208. }
  209. return
  210. }
  211. // updateInsertConfigValueByMongo
  212. // @Description: 从mongo更新或插入配置值
  213. // @author: Roc
  214. // @datetime 2024-05-09 11:05:49
  215. // @param to orm.TxOrmer
  216. // @param edbInfo *EdbInfo
  217. // @param oldConfigDate
  218. // @param newDate time.Time
  219. // @param value string
  220. // @return dateStr string
  221. // @return err error
  222. func updateInsertConfigValueByMongo(to *gorm.DB, edbInfo *EdbInfo, oldConfigDate, newDate time.Time, value string) (dateStr string, err error) {
  223. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  224. if tableName == `` {
  225. err = errors.New("找不到该指标的数据表")
  226. return
  227. }
  228. dateStr = newDate.Format(utils.FormatDate)
  229. timestamp := newDate.UnixNano() / 1e6
  230. var floatValue float64
  231. if value != "" {
  232. floatValue, err = strconv.ParseFloat(value, 64)
  233. if err != nil {
  234. fmt.Println("转换失败:", err.Error())
  235. return
  236. }
  237. }
  238. mogDataObj := mgo.EdbDataBusiness{}
  239. coll := mogDataObj.GetCollection()
  240. var edbDateData *mgo.EdbDataBusiness
  241. if !oldConfigDate.IsZero() {
  242. // 构建查询条件
  243. queryConditions := bson.M{
  244. "edb_info_id": edbInfo.EdbInfoId,
  245. "data_time": oldConfigDate,
  246. }
  247. edbDateData, err = mogDataObj.GetItem(queryConditions)
  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 *gorm.DB, 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 err != nil && err != mongo.ErrNoDocuments {
  330. return
  331. }
  332. err = nil
  333. }
  334. // 如果是没有历史数据,那么就需要增加数据
  335. if edbDateData == nil {
  336. addDataItem := mgo.EdbDataThsHf{
  337. //ID: primitive.ObjectID{},
  338. EdbInfoId: edbInfo.EdbInfoId,
  339. EdbCode: edbInfo.EdbCode,
  340. DataTime: newDate,
  341. Value: floatValue,
  342. CreateTime: time.Now(),
  343. ModifyTime: time.Now(),
  344. DataTimestamp: timestamp,
  345. }
  346. err = mogDataObj.InsertDataByColl(coll, addDataItem)
  347. if err != nil {
  348. fmt.Println("mogDataObj.BatchInsertData() Err:" + err.Error())
  349. return
  350. }
  351. return
  352. }
  353. // 数据清空
  354. if value == "" {
  355. queryConditions := bson.M{
  356. "edb_info_id": edbInfo.EdbInfoId,
  357. }
  358. // 获取最新的两条数据
  359. tmpDataList, tmpErr := mogDataObj.GetLimitDataList(queryConditions, 2, []string{"-data_time"})
  360. if tmpErr != nil {
  361. fmt.Println("mogDataObj.GetLimitDataList() Err:" + tmpErr.Error())
  362. return
  363. }
  364. // 如果并没有两条数据,那么就返回
  365. if len(tmpDataList) < 2 {
  366. return
  367. }
  368. // 实际应该是倒数第二条数据的日期
  369. dateStr = tmpDataList[1].DataTime.Format(utils.FormatDate)
  370. // 删除插入的数据
  371. err = mogDataObj.RemoveManyByColl(coll, bson.M{"_id": tmpDataList[0].ID})
  372. return
  373. }
  374. // 更新配置的数据
  375. updateData := bson.M{"$set": bson.M{
  376. "value": floatValue,
  377. "modify_time": time.Now(),
  378. "data_time": newDate,
  379. "data_timestamp": timestamp,
  380. }}
  381. err = mogDataObj.UpdateDataByColl(coll, bson.M{"_id": edbDateData.ID}, updateData)
  382. return
  383. }