edb_data_calculate_rjz.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // AddCalculateRjz 日均值
  13. func AddCalculateRjz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("AddCalculateRjz,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_RJZ
  30. edbInfo.SourceName = "日均值"
  31. edbInfo.EdbCode = edbCode
  32. edbInfo.EdbName = req.EdbName
  33. edbInfo.EdbNameSource = req.EdbName
  34. edbInfo.Frequency = req.Frequency
  35. edbInfo.Unit = req.Unit
  36. edbInfo.ClassifyId = req.ClassifyId
  37. edbInfo.SysUserId = sysUserId
  38. edbInfo.SysUserRealName = sysUserRealName
  39. edbInfo.CreateTime = time.Now()
  40. edbInfo.ModifyTime = time.Now()
  41. edbInfo.UniqueCode = uniqueCode
  42. edbInfo.CalculateFormula = req.Formula
  43. edbInfo.EdbNameEn = req.EdbName
  44. edbInfo.UnitEn = req.Unit
  45. edbInfo.EdbType = 2
  46. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  47. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  48. if tmpErr != nil {
  49. err = tmpErr
  50. return
  51. }
  52. edbInfo.EdbInfoId = int(newEdbInfoId)
  53. //关联关系
  54. {
  55. calculateMappingItem := new(EdbInfoCalculateMapping)
  56. calculateMappingItem.CreateTime = time.Now()
  57. calculateMappingItem.ModifyTime = time.Now()
  58. calculateMappingItem.Sort = 1
  59. calculateMappingItem.EdbCode = edbCode
  60. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  61. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  63. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  64. calculateMappingItem.FromSource = fromEdbInfo.Source
  65. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  66. calculateMappingItem.FromTag = ""
  67. calculateMappingItem.Source = edbInfo.Source
  68. calculateMappingItem.SourceName = edbInfo.SourceName
  69. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  70. _, err = to.Insert(calculateMappingItem)
  71. if err != nil {
  72. return
  73. }
  74. }
  75. } else {
  76. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  77. if err != nil {
  78. return
  79. }
  80. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_RJZ, utils.DATA_SUB_SOURCE_EDB)
  81. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  82. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  83. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  84. if err != nil {
  85. return
  86. }
  87. }
  88. //计算数据
  89. err = refreshAllCalculateRjz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbCode, "", "")
  90. return
  91. }
  92. // EditCalculateRjz 日均值
  93. func EditCalculateRjz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  94. o := orm.NewOrm()
  95. to, err := o.Begin()
  96. if err != nil {
  97. return
  98. }
  99. defer func() {
  100. if err != nil {
  101. fmt.Println("EditCalculateRjz,Err:" + err.Error())
  102. _ = to.Rollback()
  103. } else {
  104. _ = to.Commit()
  105. }
  106. }()
  107. //修改指标信息
  108. edbInfo.EdbName = req.EdbName
  109. edbInfo.EdbNameSource = req.EdbName
  110. edbInfo.Frequency = req.Frequency
  111. edbInfo.Unit = req.Unit
  112. edbInfo.ClassifyId = req.ClassifyId
  113. edbInfo.EdbNameEn = req.EdbNameEn
  114. edbInfo.UnitEn = req.UnitEn
  115. edbInfo.ModifyTime = time.Now()
  116. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  117. if err != nil {
  118. return
  119. }
  120. //判断计算指标是否被更换
  121. var existCondition string
  122. var existPars []interface{}
  123. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  124. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  125. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  126. if err != nil {
  127. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  128. return
  129. }
  130. if count > 0 { // 指标未被替换,无需重新计算
  131. return
  132. }
  133. //删除,计算指标关联的,基础指标的关联关系
  134. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  135. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  136. if err != nil {
  137. return
  138. }
  139. //清空原有数据
  140. sql = ` DELETE FROM edb_data_calculate_rjz WHERE edb_info_id = ? `
  141. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  142. if err != nil {
  143. return
  144. }
  145. //关联关系
  146. {
  147. calculateMappingItem := &EdbInfoCalculateMapping{
  148. EdbInfoCalculateMappingId: 0,
  149. EdbInfoId: edbInfo.EdbInfoId,
  150. Source: utils.DATA_SOURCE_CALCULATE_RJZ,
  151. SourceName: "日均值",
  152. EdbCode: edbInfo.EdbCode,
  153. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  154. FromEdbCode: fromEdbInfo.EdbCode,
  155. FromEdbName: fromEdbInfo.EdbName,
  156. FromSource: fromEdbInfo.Source,
  157. FromSourceName: fromEdbInfo.SourceName,
  158. FromTag: "",
  159. Sort: 1,
  160. CreateTime: time.Now(),
  161. ModifyTime: time.Now(),
  162. FromSubSource: fromEdbInfo.SubSource,
  163. }
  164. _, err = to.Insert(calculateMappingItem)
  165. if err != nil {
  166. return
  167. }
  168. }
  169. //计算数据
  170. err = refreshAllCalculateRjz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
  171. return
  172. }
  173. // RefreshAllCalculateRjz 刷新所有日均值数据
  174. func RefreshAllCalculateRjz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  175. o := orm.NewOrm()
  176. to, err := o.Begin()
  177. if err != nil {
  178. return
  179. }
  180. defer func() {
  181. if err != nil {
  182. fmt.Println("RefreshAllCalculateRjz,Err:" + err.Error())
  183. _ = to.Rollback()
  184. } else {
  185. _ = to.Commit()
  186. }
  187. }()
  188. //计算数据
  189. err = refreshAllCalculateRjz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
  190. return
  191. }
  192. // refreshAllCalculateRjz
  193. func refreshAllCalculateRjz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  194. edbInfoIdStr := strconv.Itoa(edbInfoId)
  195. //计算数据
  196. dataList, err := GetEdbDataListAll(fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  197. EdbInfoId: fromEdbInfo.EdbInfoId,
  198. StartDataTime: startDate,
  199. StartDataTimeCond: ">=",
  200. }, 0)
  201. if err != nil {
  202. return err
  203. }
  204. var dateArr []string
  205. dataMap := make(map[string]*EdbInfoSearchData)
  206. for _, v := range dataList {
  207. dateArr = append(dateArr, v.DataTime)
  208. dataMap[v.DataTime] = v
  209. }
  210. fmt.Println("source:", source)
  211. //获取指标所有数据
  212. existDataList := make([]*EdbData, 0)
  213. dataTableName := GetEdbDataTableName(source, utils.DATA_SUB_SOURCE_EDB)
  214. fmt.Println("dataTableName:", dataTableName)
  215. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  216. sql = fmt.Sprintf(sql, dataTableName)
  217. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  218. if err != nil {
  219. return err
  220. }
  221. existDataMap := make(map[string]string)
  222. removeDateMap := make(map[string]bool) //需要移除的日期
  223. for _, v := range existDataList {
  224. existDataMap[v.DataTime] = v.Value
  225. removeDateMap[v.DataTime] = true
  226. }
  227. fmt.Println("existDataMap:", existDataMap)
  228. addSql := ` INSERT INTO edb_data_calculate_rjz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  229. var isAdd bool
  230. existAddDataMap := make(map[string]string)
  231. for _, av := range dateArr {
  232. currentItem := dataMap[av]
  233. if currentItem != nil {
  234. //当前日期
  235. currentDate, err := time.ParseInLocation(utils.FormatDate, av, time.Local)
  236. if err != nil {
  237. return err
  238. }
  239. delete(removeDateMap, av)
  240. //根据频度计算需要均分的天数
  241. days := GetRjzFrequencyDays(currentDate, fromEdbInfo.Frequency)
  242. val := rjzDiv(currentItem.Value, days)
  243. timestamp := currentDate.UnixNano() / 1e6
  244. timestampStr := fmt.Sprintf("%d", timestamp)
  245. if existVal, ok := existDataMap[av]; !ok {
  246. if _, existOk := existAddDataMap[av]; !existOk {
  247. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  248. isAdd = true
  249. }
  250. existAddDataMap[av] = av
  251. } else {
  252. existValDecimal, err := decimal.NewFromString(existVal)
  253. existStr := existValDecimal.String()
  254. if existStr != val {
  255. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  256. sql = fmt.Sprintf(sql, dataTableName)
  257. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  258. if err != nil {
  259. return err
  260. }
  261. }
  262. }
  263. }
  264. }
  265. if len(removeDateMap) > 0 {
  266. removeDateList := make([]string, 0) //需要移除的日期
  267. for k := range removeDateMap {
  268. removeDateList = append(removeDateList, k)
  269. }
  270. removeDateStr := strings.Join(removeDateList, `","`)
  271. removeDateStr = `"` + removeDateStr + `"`
  272. //如果拼接指标变更了,那么需要删除所有的指标数据
  273. tableName := GetEdbDataTableName(source, utils.DATA_SUB_SOURCE_EDB)
  274. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  275. _, err = to.Raw(sql, edbInfoId).Exec()
  276. if err != nil {
  277. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  278. return
  279. }
  280. }
  281. if isAdd {
  282. addSql = strings.TrimRight(addSql, ",")
  283. _, err = to.Raw(addSql).Exec()
  284. if err != nil {
  285. return err
  286. }
  287. }
  288. return
  289. }
  290. func GetRjzFrequencyDays(currDate time.Time, frequency string) (days int) {
  291. switch frequency {
  292. case "周度", "周":
  293. days = 7
  294. case "旬度":
  295. if currDate.Day() <= 20 { // 1旬和2旬都是10天
  296. days = 10
  297. } else {
  298. // 下旬,多种可能,最大天数可能存在8天,9天,10天,11天,
  299. currT := time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, time.Local)
  300. nextT := time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  301. days = utils.GetTimeSubDay(currT, nextT)
  302. }
  303. case "月度":
  304. //统计当月的天数
  305. currMonthFd := time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Local)
  306. nextMonthFd := time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, time.Local)
  307. days = utils.GetTimeSubDay(currMonthFd, nextMonthFd)
  308. case "季度":
  309. curr0T := time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, time.Local)
  310. curr1T := time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, time.Local)
  311. curr2T := time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, time.Local)
  312. curr3T := time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, time.Local)
  313. curr4T := time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  314. if currDate.Month() < 4 { // 1季度
  315. days = utils.GetTimeSubDay(curr0T, curr1T)
  316. } else if currDate.Month() < 7 { // 2季度
  317. days = utils.GetTimeSubDay(curr1T, curr2T)
  318. } else if currDate.Month() < 10 { // 3季度
  319. days = utils.GetTimeSubDay(curr2T, curr3T)
  320. } else {
  321. // 4季度
  322. days = utils.GetTimeSubDay(curr3T, curr4T)
  323. }
  324. case "年度":
  325. //统计当前年份的天数,明年1月1日-今天年1月1日
  326. currentYearFd := time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, time.Local)
  327. nextYearFd := currentYearFd.AddDate(1, 0, 0)
  328. days = utils.GetTimeSubDay(currentYearFd, nextYearFd)
  329. case "半年度":
  330. curr0T := time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, time.Local)
  331. curr1T := time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, time.Local)
  332. curr2T := time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  333. if currDate.Month() <= 6 { // 上半年
  334. days = utils.GetTimeSubDay(curr0T, curr1T)
  335. } else {
  336. // 下半年
  337. days = utils.GetTimeSubDay(curr1T, curr2T)
  338. }
  339. default:
  340. days = 1
  341. return
  342. }
  343. return
  344. }
  345. func rjzDiv(a float64, b int) string {
  346. var valStr string
  347. if b != 0 {
  348. af := decimal.NewFromFloat(a)
  349. bf := decimal.NewFromFloat(float64(b))
  350. val, _ := af.Div(bf).Float64()
  351. valStr = decimal.NewFromFloat(val).Round(4).String()
  352. } else {
  353. valStr = "0"
  354. }
  355. return valStr
  356. }