edb_data_calculate_ljznczj.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. "reflect"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // LjzNczj 累计值年初至今
  15. type LjzNczj struct {
  16. }
  17. // Add 添加
  18. func (obj LjzNczj) Add(params AddCalculateBatchParams) (edbInfo *EdbInfo, err error, errMsg string) {
  19. req := params.Req
  20. fromEdbInfo := params.FromEdbInfo
  21. edbCode := params.EdbCode
  22. if fromEdbInfo.Frequency == `年度` {
  23. errMsg = "年初至今累计值计算中,可选指标范围为非年度指标"
  24. err = errors.New(errMsg)
  25. return
  26. }
  27. if fromEdbInfo.Frequency != req.Frequency {
  28. errMsg = "生成指标频度与原指标频度不同"
  29. err = errors.New(errMsg)
  30. return
  31. }
  32. to := global.DEFAULT_DmSQL.Begin()
  33. defer func() {
  34. if err != nil {
  35. to.Rollback()
  36. } else {
  37. to.Commit()
  38. }
  39. }()
  40. edbInfo = &EdbInfo{
  41. //EdbInfoId: 0,
  42. SourceName: obj.GetSourceName(),
  43. Source: obj.GetSource(),
  44. EdbCode: edbCode,
  45. EdbName: req.EdbName,
  46. EdbNameSource: req.EdbName,
  47. Frequency: req.Frequency,
  48. Unit: req.Unit,
  49. StartDate: "",
  50. EndDate: "",
  51. ClassifyId: req.ClassifyId,
  52. SysUserId: params.SysUserId,
  53. SysUserRealName: params.SysUserRealName,
  54. UniqueCode: params.UniqueCode,
  55. CreateTime: time.Now(),
  56. ModifyTime: time.Now(),
  57. MinValue: 0,
  58. MaxValue: 0,
  59. CalculateFormula: req.Formula,
  60. EdbType: obj.GetEdbType(),
  61. Sort: GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE),
  62. MoveType: 0,
  63. MoveFrequency: "",
  64. NoUpdate: 0,
  65. ServerUrl: "",
  66. EdbInfoType: 0,
  67. EdbNameEn: req.EdbName,
  68. UnitEn: req.Unit,
  69. LatestDate: "",
  70. LatestValue: 0,
  71. ChartImage: "",
  72. Calendar: "",
  73. }
  74. tmpErr := to.Create(edbInfo).Error
  75. if tmpErr != nil {
  76. err = tmpErr
  77. return
  78. }
  79. //关联关系
  80. {
  81. calculateMappingItem := new(EdbInfoCalculateMapping)
  82. calculateMappingItem.CreateTime = time.Now()
  83. calculateMappingItem.ModifyTime = time.Now()
  84. calculateMappingItem.Sort = 1
  85. calculateMappingItem.EdbCode = edbCode
  86. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  87. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  88. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  89. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  90. calculateMappingItem.FromSource = fromEdbInfo.Source
  91. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  92. calculateMappingItem.FromTag = ""
  93. calculateMappingItem.Source = edbInfo.Source
  94. calculateMappingItem.SourceName = edbInfo.SourceName
  95. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  96. err = to.Create(calculateMappingItem).Error
  97. if err != nil {
  98. return
  99. }
  100. }
  101. //计算数据
  102. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  103. return
  104. }
  105. // Edit 编辑
  106. func (obj LjzNczj) Edit(params EditCalculateBatchParams) (err error, errMsg string) {
  107. req := params.Req
  108. edbInfo := params.EdbInfo
  109. fromEdbInfo := params.FromEdbInfo
  110. if fromEdbInfo.Frequency == `年度` {
  111. errMsg = "年初至今累计值计算中,可选指标范围为非年度指标"
  112. err = errors.New(errMsg)
  113. return
  114. }
  115. if fromEdbInfo.Frequency != req.Frequency {
  116. errMsg = "生成指标频度与原指标频度不同"
  117. err = errors.New(errMsg)
  118. return
  119. }
  120. to := global.DEFAULT_DmSQL.Begin()
  121. defer func() {
  122. if err != nil {
  123. to.Rollback()
  124. } else {
  125. to.Commit()
  126. }
  127. }()
  128. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  129. var isRecalculate bool
  130. if edbInfo.Frequency != req.Frequency {
  131. isRecalculate = true
  132. }
  133. //修改指标信息
  134. edbInfo.EdbName = req.EdbName
  135. edbInfo.EdbNameSource = req.EdbName
  136. edbInfo.Frequency = req.Frequency
  137. edbInfo.Unit = req.Unit
  138. edbInfo.ClassifyId = req.ClassifyId
  139. edbInfo.EdbNameEn = req.EdbNameEn
  140. edbInfo.UnitEn = req.UnitEn
  141. edbInfo.ModifyTime = time.Now()
  142. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  143. if err != nil {
  144. return
  145. }
  146. var existCondition string
  147. var existPars []interface{}
  148. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  149. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  150. //判断计算指标是否被更换
  151. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  152. if err != nil {
  153. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  154. return
  155. }
  156. if count > 0 { // 指标未被替换,无需删除关联数据
  157. // 频度被换了,需要重新计算
  158. if isRecalculate {
  159. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  160. }
  161. return
  162. }
  163. //删除,计算指标关联的,基础指标的关联关系
  164. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  165. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  166. if err != nil {
  167. return
  168. }
  169. //清空原有数据
  170. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  171. err = to.Exec(sql, edbInfo.EdbInfoId).Error
  172. if err != nil {
  173. return
  174. }
  175. //关联关系
  176. {
  177. calculateMappingItem := &EdbInfoCalculateMapping{
  178. EdbInfoCalculateMappingId: 0,
  179. EdbInfoId: edbInfo.EdbInfoId,
  180. Source: obj.GetSource(),
  181. SourceName: obj.GetSourceName(),
  182. EdbCode: edbInfo.EdbCode,
  183. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  184. FromEdbCode: fromEdbInfo.EdbCode,
  185. FromEdbName: fromEdbInfo.EdbName,
  186. FromSource: fromEdbInfo.Source,
  187. FromSourceName: fromEdbInfo.SourceName,
  188. FromTag: "",
  189. Sort: 1,
  190. CreateTime: time.Now(),
  191. ModifyTime: time.Now(),
  192. FromSubSource: fromEdbInfo.SubSource,
  193. }
  194. err = to.Create(calculateMappingItem).Error
  195. if err != nil {
  196. return
  197. }
  198. }
  199. //计算数据
  200. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  201. return
  202. }
  203. // Refresh 刷新
  204. func (obj LjzNczj) Refresh(params RefreshParams) (err error, errMsg string) {
  205. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  206. if err != nil {
  207. errMsg = "GetEdbInfoCalculateLjzNczjzyDetail Err:" + err.Error()
  208. return
  209. }
  210. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  211. if err != nil {
  212. errMsg = "GetEdbInfoById Err:" + err.Error()
  213. return
  214. }
  215. to := global.DEFAULT_DmSQL.Begin()
  216. defer func() {
  217. if err != nil {
  218. to.Rollback()
  219. } else {
  220. to.Commit()
  221. }
  222. }()
  223. // 计算数据
  224. err = obj.refresh(to, params.EdbInfo.EdbInfoId, params.EdbInfo.Source, params.EdbInfo.SubSource, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  225. return
  226. }
  227. // GetSource 获取来源编码id
  228. func (obj LjzNczj) GetSource() int {
  229. return utils.DATA_SOURCE_CALCULATE_LJZNCZJ
  230. }
  231. // GetSourceName 获取来源名称
  232. func (obj LjzNczj) GetSourceName() string {
  233. return utils.DATA_SOURCE_NAME_CALCULATE_LJZNCZJ
  234. }
  235. // GetEdbType 获取指标类型
  236. func (obj LjzNczj) GetEdbType() int {
  237. return utils.CALCULATE_EDB_TYPE
  238. }
  239. func (obj LjzNczj) refresh(to *gorm.DB, edbInfoId, source, subSource int, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (err error) {
  240. dataTableName := GetEdbDataTableName(source, subSource)
  241. edbInfoIdStr := strconv.Itoa(edbInfoId)
  242. //计算数据
  243. var isWeekData bool // 是否周度数据,如果是周度数据的话,是需要变频的,最后结果还需要除以7
  244. // 周度数据需要先变成日度的
  245. if fromEdbInfo.Frequency == `周度` {
  246. isWeekData = true
  247. }
  248. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  249. EdbInfoId: fromEdbInfo.EdbInfoId,
  250. }, 1)
  251. if err != nil {
  252. return err
  253. }
  254. fromEdbDataMap := make(map[string]float64)
  255. if isWeekData {
  256. dataList, err = HandleDataByLinearRegression(dataList, fromEdbDataMap)
  257. if err != nil {
  258. return
  259. }
  260. }
  261. //日度数据年初至今:日期同原日度数据。将每年1月1日(含)到日度数据所在日期含间的日度值,进行加总。
  262. //周度数据年初至今:日期同原周度数据。将周度值转成日度频率,空值用插值法插值,然后算法同日度年度至今,再除以7
  263. //月度/季度数据年初至今:日期同原月度/季度数据,将每年1月1日(含)到月度数据所在日期(含)之间的月度/季度值,进行加总
  264. //以此类推
  265. dateList := make([]time.Time, 0)
  266. valueMap := make(map[time.Time]float64)
  267. yearMap := make(map[int]float64)
  268. switch edbInfo.Frequency {
  269. case "周度":
  270. tmpDateDataMap := make(map[time.Time]float64)
  271. tmpDateList := make([]time.Time, 0)
  272. for _, item := range dataList {
  273. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  274. if tmpErr != nil {
  275. err = tmpErr
  276. return
  277. }
  278. var currTime time.Time
  279. // 周六周日,这是下一个周五的数据
  280. if itemDate.Weekday() == 0 {
  281. currTime = itemDate.AddDate(0, 0, 5)
  282. } else if itemDate.Weekday() == 6 {
  283. currTime = itemDate.AddDate(0, 0, 6)
  284. } else {
  285. currTime = itemDate.AddDate(0, 0, 5-int(itemDate.Weekday()))
  286. }
  287. year := itemDate.Year()
  288. yearVal, ok := yearMap[year]
  289. if ok {
  290. yearMap[year] = item.Value + yearVal
  291. } else {
  292. yearMap[year] = item.Value
  293. }
  294. if itemDate.Equal(currTime) {
  295. tmpDateDataMap[itemDate] = yearMap[year]
  296. tmpDateList = append(tmpDateList, itemDate)
  297. }
  298. }
  299. for _, currTime := range tmpDateList {
  300. dateList = append(dateList, currTime)
  301. valueMap[currTime] = tmpDateDataMap[currTime]
  302. }
  303. default:
  304. for _, item := range dataList {
  305. itemDate, tmpErr := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  306. if tmpErr != nil {
  307. err = tmpErr
  308. return
  309. }
  310. year := itemDate.Year()
  311. yearVal, ok := yearMap[year]
  312. if ok {
  313. yearMap[year] = item.Value + yearVal
  314. } else {
  315. yearMap[year] = item.Value
  316. }
  317. valueMap[itemDate] = yearMap[year]
  318. dateList = append(dateList, itemDate)
  319. }
  320. }
  321. //获取指标所有数据
  322. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource)
  323. if err != nil {
  324. return err
  325. }
  326. existDataMap := make(map[string]string)
  327. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  328. for _, v := range existDataList {
  329. existDataMap[v.DataTime] = v.Value
  330. removeDataTimeMap[v.DataTime] = 1
  331. }
  332. needAddDateMap := make(map[time.Time]int)
  333. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  334. var isAdd bool
  335. for _, currTime := range dateList {
  336. currDateStr := currTime.Format(utils.FormatDate)
  337. existVal, ok := existDataMap[currDateStr]
  338. tmpVal, ok2 := valueMap[currTime]
  339. if !ok2 {
  340. err = errors.New("数据异常,date:" + currDateStr)
  341. return
  342. }
  343. var saveValue string
  344. if isWeekData { //周度指标转的话,最后结果要除以7
  345. saveValue = decimal.NewFromFloat(tmpVal).Div(decimal.NewFromInt(7)).Round(4).String()
  346. } else {
  347. saveValue = decimal.NewFromFloat(tmpVal).Round(4).String()
  348. }
  349. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  350. if ok {
  351. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  352. delete(removeDataTimeMap, currDateStr)
  353. if existVal != saveValue {
  354. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  355. sql = fmt.Sprintf(sql, dataTableName)
  356. err = to.Exec(sql, saveValue, edbInfoId, currDateStr).Error
  357. if err != nil {
  358. return
  359. }
  360. }
  361. continue
  362. }
  363. // 库中不存在该日期的数据
  364. timestamp := currTime.UnixNano() / 1e6
  365. timeStr := fmt.Sprintf("%d", timestamp)
  366. if _, existOk := needAddDateMap[currTime]; !existOk {
  367. addSql += GetAddSql(edbInfoIdStr, edbCode, currDateStr, timeStr, saveValue)
  368. isAdd = true
  369. }
  370. needAddDateMap[currTime] = 1
  371. }
  372. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  373. {
  374. removeDateList := make([]string, 0)
  375. for dateTime := range removeDataTimeMap {
  376. removeDateList = append(removeDateList, dateTime)
  377. }
  378. removeNum := len(removeDateList)
  379. if removeNum > 0 {
  380. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  381. err = to.Exec(sql, edbInfo.EdbInfoId, removeDateList).Error
  382. if err != nil {
  383. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  384. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  385. return
  386. }
  387. }
  388. }
  389. if isAdd {
  390. addSql = strings.TrimRight(addSql, ",")
  391. err = to.Exec(addSql).Error
  392. if err != nil {
  393. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  394. return
  395. }
  396. }
  397. return
  398. }