edb_data_calculate_ljznczj.go 11 KB

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