edb_data_calculate_rjz.go 10 KB

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