edb_data_calculate_cjjx.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // AddCalculateCjjx 超季节性
  13. func AddCalculateCjjx(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (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("AddCalculateCjjx,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. fmt.Println("req.EdbInfoId:", req.EdbInfoId)
  28. if req.EdbInfoId <= 0 {
  29. edbInfo = new(EdbInfo)
  30. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_CJJX
  31. edbInfo.SourceName = "超季节性"
  32. edbInfo.EdbCode = edbCode
  33. edbInfo.EdbName = req.EdbName
  34. edbInfo.EdbNameSource = req.EdbName
  35. edbInfo.Frequency = req.Frequency
  36. edbInfo.Unit = req.Unit
  37. edbInfo.ClassifyId = req.ClassifyId
  38. edbInfo.SysUserId = sysUserId
  39. edbInfo.SysUserRealName = sysUserRealName
  40. edbInfo.CreateTime = time.Now()
  41. edbInfo.ModifyTime = time.Now()
  42. edbInfo.UniqueCode = uniqueCode
  43. edbInfo.CalculateFormula = req.Formula
  44. edbInfo.EdbType = 2
  45. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  46. if tmpErr != nil {
  47. err = tmpErr
  48. return
  49. }
  50. edbInfo.EdbInfoId = int(newEdbInfoId)
  51. //关联关系
  52. {
  53. calculateMappingItem := new(EdbInfoCalculateMapping)
  54. calculateMappingItem.CreateTime = time.Now()
  55. calculateMappingItem.ModifyTime = time.Now()
  56. calculateMappingItem.Sort = 1
  57. calculateMappingItem.EdbCode = edbCode
  58. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  59. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  60. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  61. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  62. calculateMappingItem.FromSource = fromEdbInfo.Source
  63. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  64. calculateMappingItem.FromTag = ""
  65. calculateMappingItem.Source = edbInfo.Source
  66. calculateMappingItem.SourceName = edbInfo.SourceName
  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_CJJX)
  78. fmt.Println("dataTableName:", dataTableName)
  79. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  80. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  81. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  82. if err != nil {
  83. return
  84. }
  85. }
  86. //计算数据
  87. err = refreshAllCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  88. return
  89. }
  90. // EditCalculateCjjx 超季节性
  91. func EditCalculateCjjx(req *EdbInfoCalculateBatchEditReq, edbInfo, fromEdbInfo *EdbInfo, formulaInt int) (err error) {
  92. o := orm.NewOrm()
  93. to, err := o.Begin()
  94. if err != nil {
  95. return
  96. }
  97. defer func() {
  98. if err != nil {
  99. fmt.Println("EditCalculateCjjx,Err:" + err.Error())
  100. _ = to.Rollback()
  101. } else {
  102. _ = to.Commit()
  103. }
  104. }()
  105. oldCalculateFormula := edbInfo.CalculateFormula //原先的n值
  106. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  107. if err != nil {
  108. return
  109. }
  110. //修改指标信息
  111. edbInfo.EdbName = req.EdbName
  112. edbInfo.EdbNameSource = req.EdbName
  113. edbInfo.Frequency = req.Frequency
  114. edbInfo.Unit = req.Unit
  115. edbInfo.ClassifyId = req.ClassifyId
  116. edbInfo.CalculateFormula = req.Formula
  117. edbInfo.ModifyTime = time.Now()
  118. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  119. if err != nil {
  120. return
  121. }
  122. //判断计算指标是否被更换
  123. var existCondition string
  124. var existPars []interface{}
  125. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  126. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  127. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  128. if err != nil {
  129. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  130. return
  131. }
  132. if count > 0 && oldCalculateFormula == req.Formula { // 指标未被替换,同时N值未修改,无需重新计算
  133. return
  134. }
  135. // 指标被替换,或者N值未修改,那么需要重新计算数据
  136. //基础指标被替换了,需要删除原先的 计算指标关联的,基础指标的关联关系
  137. if count <= 0 {
  138. // 需要删除原先的 计算指标关联的,基础指标的关联关系
  139. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  140. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  141. if err != nil {
  142. return
  143. }
  144. // 添加新的关联关系
  145. {
  146. calculateMappingItem := &EdbInfoCalculateMapping{
  147. EdbInfoCalculateMappingId: 0,
  148. EdbInfoId: edbInfo.EdbInfoId,
  149. Source: utils.DATA_SOURCE_CALCULATE_CJJX,
  150. SourceName: "超季节性",
  151. EdbCode: edbInfo.EdbCode,
  152. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  153. FromEdbCode: fromEdbInfo.EdbCode,
  154. FromEdbName: fromEdbInfo.EdbName,
  155. FromSource: fromEdbInfo.Source,
  156. FromSourceName: fromEdbInfo.SourceName,
  157. FromTag: "",
  158. Sort: 1,
  159. CreateTime: time.Now(),
  160. ModifyTime: time.Now(),
  161. }
  162. _, err = to.Insert(calculateMappingItem)
  163. if err != nil {
  164. return
  165. }
  166. }
  167. }
  168. //清空原有数据
  169. tableName := GetEdbDataTableName(edbInfo.Source)
  170. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
  171. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  172. if err != nil {
  173. return
  174. }
  175. //计算数据
  176. err = refreshAllCalculateCjjx(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "", formulaInt)
  177. return
  178. }
  179. // RefreshAllCalculateCjjx 刷新全部超季节性数据
  180. func RefreshAllCalculateCjjx(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  181. o := orm.NewOrm()
  182. to, err := o.Begin()
  183. if err != nil {
  184. return
  185. }
  186. defer func() {
  187. if err != nil {
  188. fmt.Println("RefreshAllCalculateCjjx,Err:" + err.Error())
  189. _ = to.Rollback()
  190. } else {
  191. _ = to.Commit()
  192. }
  193. }()
  194. // 重新计算
  195. err = refreshAllCalculateCjjx(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate, formulaInt)
  196. return
  197. }
  198. // refreshAllCalculateCjjx 刷新全部超季节性数据
  199. func refreshAllCalculateCjjx(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  200. if err != nil {
  201. return
  202. }
  203. edbInfoIdStr := strconv.Itoa(edbInfoId)
  204. //计算数据
  205. var condition string
  206. var pars []interface{}
  207. condition += " AND edb_info_id=? "
  208. pars = append(pars, fromEdbInfo.EdbInfoId)
  209. if startDate != "" {
  210. condition += " AND data_time>=? "
  211. pars = append(pars, startDate)
  212. }
  213. //if endDate != "" {
  214. // condition += " AND data_time<=? "
  215. // pars = append(pars, endDate)
  216. //}
  217. dataList, err := GetEdbDataListAllByTo(to, condition, pars, fromEdbInfo.Source, 0)
  218. if err != nil {
  219. return err
  220. }
  221. var dateArr []string
  222. dataMap := make(map[string]*EdbInfoSearchData)
  223. for _, v := range dataList {
  224. dateArr = append(dateArr, v.DataTime)
  225. dataMap[v.DataTime] = v
  226. }
  227. //获取指标所有数据
  228. existDataList := make([]*EdbData, 0)
  229. dataTableName := GetEdbDataTableName(source)
  230. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  231. sql = fmt.Sprintf(sql, dataTableName)
  232. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  233. if err != nil {
  234. return err
  235. }
  236. existDataMap := make(map[string]string)
  237. for _, v := range existDataList {
  238. existDataMap[edbCode+v.DataTime] = v.Value
  239. }
  240. addSql := ` INSERT INTO edb_data_calculate_cjjx(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  241. var isAdd bool
  242. //日度/周度/季度/月度
  243. isCompatibility := false //是否向上下兼容35天
  244. if utils.InArrayByStr([]string{"日度", "周度", "季度", "月度"}, fromEdbInfo.Frequency) {
  245. isCompatibility = true
  246. }
  247. for _, av := range dateArr {
  248. currentItem := dataMap[av]
  249. if currentItem != nil {
  250. pastValueList := make([]float64, 0) // 过去几期的数据
  251. //当前日期
  252. currentDate, tmpErr := time.Parse(utils.FormatDate, av)
  253. if tmpErr != nil {
  254. err = tmpErr
  255. return
  256. }
  257. pastValueList = append(pastValueList, currentItem.Value)
  258. for i := 1; i < formulaInt; i++ {
  259. //前几年的日期
  260. preDate := currentDate.AddDate(-i, 0, 0)
  261. preDateStr := preDate.Format(utils.FormatDate)
  262. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
  263. pastValueList = append(pastValueList, findItem.Value)
  264. } else if isCompatibility { // 如果需要兼容上下35天
  265. nextDateDay := preDate
  266. preDateDay := preDate
  267. for i := 0; i < 35; i++ {
  268. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  269. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  270. pastValueList = append(pastValueList, findItem.Value)
  271. break
  272. } else {
  273. preDateDayStr := preDateDay.Format(utils.FormatDate)
  274. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  275. pastValueList = append(pastValueList, findItem.Value)
  276. break
  277. }
  278. }
  279. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  280. preDateDay = preDateDay.AddDate(0, 0, -1)
  281. }
  282. }
  283. }
  284. if len(pastValueList) == formulaInt {
  285. val := CjjxSub(currentItem.Value, pastValueList)
  286. if existVal, ok := existDataMap[edbCode+av]; !ok {
  287. timestamp := currentDate.UnixNano() / 1e6
  288. timestampStr := fmt.Sprintf("%d", timestamp)
  289. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  290. isAdd = true
  291. } else {
  292. existValDecimal, err := decimal.NewFromString(existVal)
  293. existStr := existValDecimal.String()
  294. if existStr != val {
  295. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  296. sql = fmt.Sprintf(sql, dataTableName)
  297. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  298. if err != nil {
  299. return err
  300. }
  301. }
  302. }
  303. }
  304. existDataMap[edbCode+av] = av
  305. }
  306. }
  307. if isAdd {
  308. addSql = strings.TrimRight(addSql, ",")
  309. _, err = to.Raw(addSql).Exec()
  310. if err != nil {
  311. return err
  312. }
  313. }
  314. return
  315. }
  316. // CjjxSub 计算超季节性值
  317. // 计算公式=现值-过去n年(包括今年)均值,n为取数个数,需大于等于1;
  318. //举例:A指标 2022-10-13值100,2021-10-13值120,2020-10-13值110,设置n=3,则“超季节性”指标计算值为100-(100+120+110)/3=-10。
  319. func CjjxSub(currValue float64, pastValue []float64) (value string) {
  320. num := len(pastValue)
  321. if num == 0 {
  322. return
  323. }
  324. numDecimal := decimal.NewFromInt(int64(num))
  325. af := decimal.NewFromFloat(currValue)
  326. fmt.Println(af)
  327. bf := decimal.NewFromFloat(pastValue[0])
  328. for k := 1; k < num; k++ {
  329. tmpVal := decimal.NewFromFloat(pastValue[k])
  330. bf = bf.Add(tmpVal)
  331. }
  332. val, _ := af.Sub(bf.Div(numDecimal)).Float64()
  333. //valStr := utils.SubFloatToString(val, 4)
  334. valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
  335. return valStr
  336. }