edb_data_calculate_rjz.go 11 KB

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