edb_data_calculate_jp.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. func CheckFrequency(fromEdbFrequency, edbFrequency string) (ok bool) {
  14. frequencyList := make([]string, 0)
  15. switch fromEdbFrequency {
  16. case "日度":
  17. frequencyList = []string{"日度"}
  18. case "周度":
  19. frequencyList = []string{"日度", "周度"}
  20. case "旬度":
  21. frequencyList = []string{"日度", "周度", "旬度"}
  22. case "月度":
  23. frequencyList = []string{"日度", "周度", "旬度", "月度"}
  24. case "季度":
  25. frequencyList = []string{"日度", "周度", "旬度", "月度", "季度"}
  26. default:
  27. return
  28. }
  29. if utils.InArrayByStr(frequencyList, edbFrequency) {
  30. return
  31. }
  32. ok = true
  33. return
  34. }
  35. func AddCalculateJp(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  36. to := global.DEFAULT_DmSQL.Begin()
  37. defer func() {
  38. if err != nil {
  39. to.Rollback()
  40. } else {
  41. to.Commit()
  42. }
  43. }()
  44. if req.EdbInfoId <= 0 {
  45. edbInfo = new(EdbInfo)
  46. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_JP
  47. edbInfo.SourceName = utils.DATA_SOURCE_NAME_CALCULATE_JP
  48. edbInfo.EdbCode = edbCode
  49. edbInfo.EdbName = req.EdbName
  50. edbInfo.EdbNameSource = req.EdbName
  51. edbInfo.Frequency = req.Frequency
  52. edbInfo.Unit = req.Unit
  53. edbInfo.ClassifyId = req.ClassifyId
  54. edbInfo.SysUserId = sysUserId
  55. edbInfo.SysUserRealName = sysUserRealName
  56. edbInfo.CreateTime = time.Now()
  57. edbInfo.ModifyTime = time.Now()
  58. edbInfo.UniqueCode = uniqueCode
  59. edbInfo.CalculateFormula = req.Formula
  60. edbInfo.EdbNameEn = req.EdbName
  61. edbInfo.UnitEn = req.Unit
  62. edbInfo.EdbType = 2
  63. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  64. tmpErr := to.Create(edbInfo).Error
  65. if tmpErr != nil {
  66. err = tmpErr
  67. return
  68. }
  69. {
  70. calculateMappingItem := new(EdbInfoCalculateMapping)
  71. calculateMappingItem.CreateTime = time.Now()
  72. calculateMappingItem.ModifyTime = time.Now()
  73. calculateMappingItem.Sort = 1
  74. calculateMappingItem.EdbCode = edbCode
  75. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  76. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  77. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  78. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  79. calculateMappingItem.FromSource = fromEdbInfo.Source
  80. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  81. calculateMappingItem.FromTag = ""
  82. calculateMappingItem.Source = edbInfo.Source
  83. calculateMappingItem.SourceName = edbInfo.SourceName
  84. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  85. err = to.Create(calculateMappingItem).Error
  86. if err != nil {
  87. return
  88. }
  89. }
  90. } else {
  91. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  92. if err != nil {
  93. return
  94. }
  95. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_JP, utils.DATA_SUB_SOURCE_EDB)
  96. fmt.Println("dataTableName:" + dataTableName)
  97. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  98. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  99. err = to.Exec(deleteSql, req.EdbInfoId).Error
  100. if err != nil {
  101. return
  102. }
  103. }
  104. err = refreshAllCalculateJp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.Frequency, edbInfo.CalculateFormula)
  105. return
  106. }
  107. func EditCalculateJp(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  108. to := global.DEFAULT_DmSQL.Begin()
  109. defer func() {
  110. if err != nil {
  111. to.Rollback()
  112. } else {
  113. to.Commit()
  114. }
  115. }()
  116. edbInfo.EdbName = req.EdbName
  117. edbInfo.EdbNameSource = req.EdbName
  118. edbInfo.Frequency = req.Frequency
  119. edbInfo.Unit = req.Unit
  120. edbInfo.ClassifyId = req.ClassifyId
  121. edbInfo.CalculateFormula = req.Formula
  122. edbInfo.EdbNameEn = req.EdbNameEn
  123. edbInfo.UnitEn = req.UnitEn
  124. edbInfo.ModifyTime = time.Now()
  125. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  126. if err != nil {
  127. return
  128. }
  129. var existCondition string
  130. var existPars []interface{}
  131. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  132. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  133. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  134. if err != nil {
  135. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  136. return
  137. }
  138. if count > 0 { // 指标未被替换,无需重新计算
  139. return
  140. }
  141. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  142. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  143. if err != nil {
  144. err = errors.New("删除计算指标关联关系失败,Err:" + err.Error())
  145. return
  146. }
  147. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  148. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  149. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  150. if err != nil {
  151. return
  152. }
  153. {
  154. calculateMappingItem := &EdbInfoCalculateMapping{
  155. EdbInfoCalculateMappingId: 0,
  156. EdbInfoId: edbInfo.EdbInfoId,
  157. Source: edbInfo.Source,
  158. SourceName: edbInfo.SourceName,
  159. EdbCode: edbInfo.EdbCode,
  160. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  161. FromEdbCode: fromEdbInfo.EdbCode,
  162. FromEdbName: fromEdbInfo.EdbName,
  163. FromSource: fromEdbInfo.Source,
  164. FromSourceName: fromEdbInfo.SourceName,
  165. FromTag: "",
  166. Sort: 1,
  167. CreateTime: time.Now(),
  168. ModifyTime: time.Now(),
  169. FromSubSource: fromEdbInfo.SubSource,
  170. }
  171. err = to.Create(calculateMappingItem).Error
  172. if err != nil {
  173. return
  174. }
  175. }
  176. err = refreshAllCalculateJp(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, edbInfo.Frequency, edbInfo.CalculateFormula)
  177. return
  178. }
  179. func RefreshAllCalculateJp(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (err error) {
  180. to := global.DEFAULT_DmSQL.Begin()
  181. defer func() {
  182. if err != nil {
  183. to.Rollback()
  184. } else {
  185. to.Commit()
  186. }
  187. }()
  188. err = refreshAllCalculateJp(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, edbFrequency, formula)
  189. return
  190. }
  191. func refreshAllCalculateJp(to *gorm.DB, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, edbFrequency, formula string) (err error) {
  192. edbInfoIdStr := strconv.Itoa(edbInfoId)
  193. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  194. EdbInfoId: fromEdbInfo.EdbInfoId,
  195. }, 1)
  196. if err != nil {
  197. return err
  198. }
  199. var dateArr []string
  200. dataMap := make(map[string]*EdbInfoSearchData)
  201. fromDataMap := make(map[string]float64)
  202. for _, v := range dataList {
  203. dateArr = append(dateArr, v.DataTime)
  204. dataMap[v.DataTime] = v
  205. fromDataMap[v.DataTime] = v.Value
  206. }
  207. fmt.Println("source:", source)
  208. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, source, subSource)
  209. if err != nil {
  210. return
  211. }
  212. existDataMap := make(map[string]*EdbData)
  213. existDelDateMap := make(map[string]string)
  214. for _, v := range existDataList {
  215. existDataMap[v.DataTime] = v
  216. existDelDateMap[v.DataTime] = v.DataTime
  217. }
  218. tableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_JP, subSource)
  219. addSql := ` INSERT INTO ` + tableName + ` (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  220. var isAdd bool
  221. dataLen := len(dataList)
  222. if dataLen <= 0 {
  223. return
  224. }
  225. startDataTime, _ := time.ParseInLocation(utils.FormatDate, dataList[0].DataTime, time.Local)
  226. endDataTime, _ := time.ParseInLocation(utils.FormatDate, dataList[dataLen-1].DataTime, time.Local)
  227. nextEndDate := utils.GetFrequencyEndDay(startDataTime, edbFrequency) // 下一个节点的日期
  228. weekDayDataList := make([]float64, 0)
  229. for tmpStartDataTime := startDataTime; !tmpStartDataTime.After(endDataTime); tmpStartDataTime = tmpStartDataTime.AddDate(0, 0, 1) {
  230. if tmpData, ok := dataMap[tmpStartDataTime.Format(utils.FormatDate)]; ok {
  231. tmpValue := decimal.NewFromFloat(tmpData.Value)
  232. tmpValueFloat, _ := tmpValue.Round(4).Float64()
  233. weekDayDataList = append(weekDayDataList, tmpValueFloat)
  234. }
  235. switch edbFrequency {
  236. case "周度":
  237. if tmpStartDataTime.Weekday() != 5 {
  238. continue
  239. } else {
  240. nextEndDate = tmpStartDataTime.AddDate(0, 0, 7)
  241. }
  242. case "旬度":
  243. nextDay := tmpStartDataTime.AddDate(0, 0, 1)
  244. if nextDay.Day() != 1 && nextDay.Day() != 11 && nextDay.Day() != 21 {
  245. continue
  246. } else {
  247. if nextDay.Day() == 1 || nextDay.Day() == 11 {
  248. nextEndDate = nextDay.AddDate(0, 0, 9)
  249. } else {
  250. tmpNextMonth := nextDay.AddDate(0, 1, 0)
  251. nextEndDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  252. }
  253. }
  254. case "月度":
  255. nextDay := tmpStartDataTime.AddDate(0, 0, 1)
  256. if nextDay.Day() != 1 {
  257. continue
  258. } else {
  259. nextEndDate = nextDay.AddDate(0, 1, -1)
  260. }
  261. case "季度":
  262. nextDay := tmpStartDataTime.AddDate(0, 0, 1)
  263. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  264. nextEndDate = nextDay.AddDate(0, 3, -1)
  265. } else {
  266. continue
  267. }
  268. case "年度":
  269. if tmpStartDataTime.Month() == 12 && tmpStartDataTime.Day() == 31 {
  270. nextEndDate = tmpStartDataTime.AddDate(1, 0, 0)
  271. } else {
  272. continue
  273. }
  274. default:
  275. err = errors.New("错误的频度:" + edbFrequency)
  276. return
  277. }
  278. lenWeekDayDataList := len(weekDayDataList)
  279. if lenWeekDayDataList <= 0 {
  280. continue
  281. }
  282. var currVal float64
  283. if formula == "期末值" { // 期末值,取区间最后一个日期的数据值
  284. currVal = weekDayDataList[lenWeekDayDataList-1]
  285. } else {
  286. sumValDeci := decimal.NewFromFloat(0)
  287. for _, v := range weekDayDataList {
  288. tmpValDeci := decimal.NewFromFloat(v)
  289. sumValDeci = sumValDeci.Add(tmpValDeci)
  290. }
  291. lenDeci := decimal.NewFromInt(int64(lenWeekDayDataList))
  292. currVal, _ = sumValDeci.Div(lenDeci).Round(4).Float64()
  293. }
  294. tmpStartDataTimeStr := tmpStartDataTime.Format(utils.FormatDate)
  295. if existData, ok := existDataMap[tmpStartDataTimeStr]; ok {
  296. existValStr := existData.Value
  297. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  298. if tmpErr != nil {
  299. err = tmpErr
  300. return
  301. }
  302. existVal, _ := existValDeci.Round(4).Float64()
  303. if existVal != currVal {
  304. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  305. if err != nil {
  306. return err
  307. }
  308. }
  309. delete(existDelDateMap, tmpStartDataTimeStr)
  310. } else {
  311. timestamp := tmpStartDataTime.UnixNano() / 1e6
  312. timestampStr := fmt.Sprintf("%d", timestamp)
  313. addSql += GetAddSql(edbInfoIdStr, edbCode, tmpStartDataTimeStr, timestampStr, fmt.Sprint(currVal))
  314. isAdd = true
  315. delete(existDelDateMap, tmpStartDataTimeStr)
  316. }
  317. weekDayDataList = make([]float64, 0)
  318. }
  319. lenWeekDayDataList := len(weekDayDataList)
  320. if lenWeekDayDataList > 0 {
  321. var currVal float64
  322. if formula == "期末值" {
  323. currVal = weekDayDataList[lenWeekDayDataList-1]
  324. } else {
  325. sumValDeci := decimal.NewFromFloat(0)
  326. for _, v := range weekDayDataList {
  327. tmpValDeci := decimal.NewFromFloat(v)
  328. sumValDeci = sumValDeci.Add(tmpValDeci)
  329. }
  330. lenDeci := decimal.NewFromInt(int64(lenWeekDayDataList))
  331. currVal, _ = sumValDeci.Div(lenDeci).Round(4).Float64()
  332. }
  333. nextEndDateStr := nextEndDate.Format(utils.FormatDate)
  334. if existData, ok := existDataMap[nextEndDateStr]; ok {
  335. existValStr := existData.Value
  336. existValDeci, tmpErr := decimal.NewFromString(existValStr)
  337. if tmpErr != nil {
  338. err = tmpErr
  339. return
  340. }
  341. existVal, _ := existValDeci.Round(4).Float64()
  342. if existVal != currVal {
  343. err = ModifyEdbDataById(source, subSource, existData.EdbDataId, fmt.Sprint(currVal))
  344. if err != nil {
  345. return err
  346. }
  347. }
  348. delete(existDelDateMap, nextEndDateStr)
  349. } else {
  350. timestamp := nextEndDate.UnixNano() / 1e6
  351. timestampStr := fmt.Sprintf("%d", timestamp)
  352. addSql += GetAddSql(edbInfoIdStr, edbCode, nextEndDate.Format(utils.FormatDate), timestampStr, fmt.Sprint(currVal))
  353. isAdd = true
  354. delete(existDelDateMap, nextEndDate.Format(utils.FormatDate))
  355. }
  356. }
  357. if isAdd {
  358. addSql = strings.TrimRight(addSql, ",")
  359. err = to.Exec(addSql).Error
  360. }
  361. if len(existDelDateMap) > 0 {
  362. removeDateList := make([]string, 0) //需要移除的日期
  363. for k := range existDelDateMap {
  364. removeDateList = append(removeDateList, k)
  365. }
  366. removeDateStr := strings.Join(removeDateList, `","`)
  367. removeDateStr = `"` + removeDateStr + `"`
  368. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  369. err = to.Exec(sql, edbInfoId).Error
  370. if err != nil {
  371. err = fmt.Errorf("删除年化指标数据失败,Err:" + err.Error())
  372. return
  373. }
  374. }
  375. return
  376. }