edb_info_calculate_hbz.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. package data_manage
  2. import (
  3. "errors"
  4. "eta/eta_api/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/shopspring/decimal"
  11. )
  12. type EdbInfoCalculateHbz struct {
  13. EdbInfoCalculateHbzId int `orm:"column(edb_info_calculate_hbz_id);pk"`
  14. EdbInfoId int `description:"指标id"`
  15. EdbCode string `description:"指标编码"`
  16. FromEdbInfoId int `description:"计算指标id"`
  17. FromEdbCode string `description:"计算指标编码"`
  18. FromEdbName string `description:"计算指标名称"`
  19. FromSource int `description:"计算指标来源"`
  20. FromSourceName string `description:"计算指标来源名称"`
  21. FromTag string `description:"来源指标标签"`
  22. Sort int `description:"计算指标名称排序"`
  23. CreateTime time.Time `description:"创建时间"`
  24. ModifyTime time.Time `description:"修改时间"`
  25. }
  26. // 环比值
  27. func AddCalculateHbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string, formulaInt int) (edbInfoId int, err error) {
  28. fmt.Println("AddCalculateHbz")
  29. o := orm.NewOrmUsingDB("data")
  30. to, err := o.Begin()
  31. if err != nil {
  32. return
  33. }
  34. defer func() {
  35. if err != nil {
  36. fmt.Println("AddCalculateHbz,Err:" + err.Error())
  37. _ = to.Rollback()
  38. } else {
  39. _ = to.Commit()
  40. }
  41. }()
  42. if req.EdbInfoId <= 0 {
  43. edbInfo := new(EdbInfo)
  44. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_HBZ
  45. edbInfo.SourceName = "环比值"
  46. edbInfo.EdbCode = edbCode
  47. edbInfo.EdbName = req.EdbName
  48. edbInfo.EdbNameSource = req.EdbName
  49. edbInfo.Frequency = req.Frequency
  50. edbInfo.Unit = req.Unit
  51. edbInfo.ClassifyId = req.ClassifyId
  52. edbInfo.SysUserId = sysUserId
  53. edbInfo.SysUserRealName = sysUserRealName
  54. edbInfo.CreateTime = time.Now()
  55. edbInfo.ModifyTime = time.Now()
  56. edbInfo.UniqueCode = uniqueCode
  57. edbInfo.CalculateFormula = req.Formula
  58. edbInfo.EdbType = 2
  59. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  60. if tmpErr != nil {
  61. return edbInfoId, tmpErr
  62. }
  63. edbInfoId = int(newEdbInfoId)
  64. //关联关系
  65. {
  66. calculateMappingItem := new(EdbInfoCalculateMapping)
  67. calculateMappingItem.CreateTime = time.Now()
  68. calculateMappingItem.ModifyTime = time.Now()
  69. calculateMappingItem.Sort = 1
  70. calculateMappingItem.EdbCode = edbCode
  71. calculateMappingItem.EdbInfoId = edbInfoId
  72. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  73. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  74. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  75. calculateMappingItem.FromSource = fromEdbInfo.Source
  76. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  77. calculateMappingItem.FromTag = ""
  78. calculateMappingItem.Source = edbInfo.Source
  79. calculateMappingItem.SourceName = edbInfo.SourceName
  80. _, err = to.Insert(calculateMappingItem)
  81. if err != nil {
  82. return
  83. }
  84. }
  85. } else {
  86. edbInfoId = req.EdbInfoId
  87. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_HBZ, utils.DATA_SUB_SOURCE_EDB)
  88. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  89. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  90. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  91. }
  92. edbInfoIdStr := strconv.Itoa(edbInfoId)
  93. fmt.Println("edbInfoIdStr:" + edbInfoIdStr)
  94. //计算数据
  95. var condition string
  96. var pars []interface{}
  97. condition += " AND edb_info_id=? "
  98. if req.EdbInfoId <= 0 {
  99. pars = append(pars, req.FromEdbInfoId)
  100. } else {
  101. pars = append(pars, fromEdbInfo.EdbInfoId)
  102. }
  103. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  104. if err != nil {
  105. return edbInfoId, err
  106. }
  107. addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  108. var isAdd bool
  109. existMap := make(map[string]string)
  110. dataLen := len(dataList)
  111. for i := 0; i < dataLen; i++ {
  112. j := i + formulaInt
  113. if j < dataLen {
  114. //当期
  115. currentItem := dataList[i]
  116. preItem := dataList[j]
  117. fmt.Println("preItem.Value:", preItem.Value)
  118. if currentItem != nil && preItem != nil && preItem.Value != 0 {
  119. existKey := edbCode + currentItem.DataTime
  120. if _, ok := existMap[existKey]; !ok {
  121. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  122. timestamp := currentDate.UnixNano() / 1e6
  123. timestampStr := fmt.Sprintf("%d", timestamp)
  124. val := HbzDiv(currentItem.Value, preItem.Value)
  125. if val != "" {
  126. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  127. isAdd = true
  128. }
  129. }
  130. existMap[existKey] = currentItem.DataTime
  131. }
  132. }
  133. }
  134. if isAdd {
  135. addSql = strings.TrimRight(addSql, ",")
  136. _, err = to.Raw(addSql).Exec()
  137. if err != nil {
  138. return edbInfoId, err
  139. }
  140. }
  141. return
  142. }
  143. // 环比值,current:当期,pre:上期 公式: (当期-上期)/上期
  144. func HbzDiv(current, pre float64) string {
  145. if pre == 0 {
  146. return ""
  147. }
  148. currentVal := decimal.NewFromFloat(float64(current))
  149. preVal := decimal.NewFromFloat(float64(pre))
  150. val, _ := currentVal.Sub(preVal).Div(preVal).Float64()
  151. valStr := utils.SubFloatToString(val, 4)
  152. return valStr
  153. }
  154. // 环比值
  155. func EditCalculateHbz(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string, formulaInt int, calculateFormula string) (edbInfoId int, err error) {
  156. edbInfoId = req.EdbInfoId
  157. o := orm.NewOrmUsingDB("data")
  158. to, err := o.Begin()
  159. if err != nil {
  160. return
  161. }
  162. defer func() {
  163. if err != nil {
  164. _ = to.Rollback()
  165. } else {
  166. _ = to.Commit()
  167. }
  168. }()
  169. //修改指标信息
  170. sql := ` UPDATE edb_info
  171. SET
  172. edb_name =?,
  173. edb_name_source=?,
  174. frequency = ?,
  175. unit = ?,
  176. classify_id = ?,
  177. calculate_formula=?,
  178. modify_time = NOW()
  179. WHERE edb_info_id = ? `
  180. _, err = to.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, req.Formula, edbInfoId).Exec()
  181. if err != nil {
  182. return
  183. }
  184. var existCondition string
  185. var existPars []interface{}
  186. existCondition += " AND edb_info_id=? "
  187. existPars = append(existPars, edbInfoId)
  188. existCondition += " AND from_edb_info_id=? "
  189. existPars = append(existPars, req.FromEdbInfoId)
  190. //判断计算指标是否被更换
  191. count, err := GetEdbInfoCalculateCountByCondition(req.Source, existCondition, existPars)
  192. if err != nil {
  193. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  194. return
  195. }
  196. if count <= 0 || strconv.Itoa(formulaInt) != calculateFormula {
  197. //删除,计算指标关联的,基础指标的关联关系
  198. if count <= 0 {
  199. sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  200. _, err = to.Raw(sql, edbInfoId).Exec()
  201. if err != nil {
  202. return
  203. }
  204. //关联关系
  205. {
  206. calculateMappingItem := new(EdbInfoCalculateMapping)
  207. calculateMappingItem.CreateTime = time.Now()
  208. calculateMappingItem.ModifyTime = time.Now()
  209. calculateMappingItem.Sort = 1
  210. calculateMappingItem.EdbCode = edbCode
  211. calculateMappingItem.EdbInfoId = edbInfoId
  212. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  213. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  214. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  215. calculateMappingItem.FromSource = fromEdbInfo.Source
  216. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  217. calculateMappingItem.FromTag = ""
  218. calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_HBZ
  219. calculateMappingItem.SourceName = "环比值"
  220. _, err = to.Insert(calculateMappingItem)
  221. if err != nil {
  222. return
  223. }
  224. }
  225. }
  226. //清空原有数据
  227. sql = ` DELETE FROM edb_data_calculate_hbz WHERE edb_info_id = ? `
  228. _, err = to.Raw(sql, edbInfoId).Exec()
  229. if err != nil {
  230. return edbInfoId, err
  231. }
  232. edbInfoIdStr := strconv.Itoa(edbInfoId)
  233. //计算数据
  234. var condition string
  235. var pars []interface{}
  236. condition += " AND edb_info_id=? "
  237. pars = append(pars, req.FromEdbInfoId)
  238. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  239. if err != nil {
  240. return edbInfoId, err
  241. }
  242. addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  243. var isAdd bool
  244. existMap := make(map[string]string)
  245. dataLen := len(dataList)
  246. for i := 0; i < dataLen; i++ {
  247. j := i + formulaInt
  248. if j < dataLen {
  249. //当期
  250. currentItem := dataList[i]
  251. preItem := dataList[j]
  252. if currentItem != nil && preItem != nil {
  253. existKey := edbCode + currentItem.DataTime
  254. if _, ok := existMap[existKey]; !ok {
  255. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  256. timestamp := currentDate.UnixNano() / 1e6
  257. timestampStr := fmt.Sprintf("%d", timestamp)
  258. val := HbzDiv(currentItem.Value, preItem.Value)
  259. if val != "" {
  260. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  261. isAdd = true
  262. }
  263. }
  264. existMap[existKey] = currentItem.DataTime
  265. }
  266. }
  267. }
  268. if isAdd {
  269. addSql = strings.TrimRight(addSql, ",")
  270. _, err = to.Raw(addSql).Exec()
  271. if err != nil {
  272. return edbInfoId, err
  273. }
  274. }
  275. }
  276. return
  277. }
  278. // 刷新环比值数据
  279. func RefreshCalculateHbz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  280. o := orm.NewOrmUsingDB("data")
  281. to, err := o.Begin()
  282. if err != nil {
  283. return
  284. }
  285. defer func() {
  286. if err != nil {
  287. _ = to.Rollback()
  288. } else {
  289. _ = to.Commit()
  290. }
  291. }()
  292. if err != nil {
  293. return
  294. }
  295. edbInfoIdStr := strconv.Itoa(edbInfoId)
  296. var condition string
  297. var pars []interface{}
  298. condition += " AND edb_info_id=? "
  299. pars = append(pars, fromEdbInfo.EdbInfoId)
  300. if startDate != "" {
  301. condition += " AND data_time>=? "
  302. pars = append(pars, startDate)
  303. }
  304. if endDate != "" {
  305. condition += " AND data_time<=? "
  306. pars = append(pars, endDate)
  307. }
  308. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  309. if err != nil {
  310. return err
  311. }
  312. //获取指标所有数据
  313. existDataList := make([]*EdbDataBase, 0)
  314. dataTableName := GetEdbDataTableName(source, subSource)
  315. fmt.Println("dataTableName:", dataTableName)
  316. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  317. sql = fmt.Sprintf(sql, dataTableName)
  318. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  319. if err != nil {
  320. return err
  321. }
  322. existDataMap := make(map[string]string)
  323. for _, v := range existDataList {
  324. existDataMap[v.DataTime] = v.Value
  325. }
  326. addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  327. var isAdd bool
  328. existMap := make(map[string]string)
  329. dataLen := len(dataList)
  330. fmt.Println("dataLen:", dataLen)
  331. for i := 0; i < dataLen; i++ {
  332. j := i + 1
  333. if j < dataLen {
  334. //当期
  335. currentItem := dataList[i]
  336. preItem := dataList[j]
  337. if currentItem != nil && preItem != nil {
  338. existKey := edbCode + currentItem.DataTime
  339. if _, ok := existMap[existKey]; !ok {
  340. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  341. timestamp := currentDate.UnixNano() / 1e6
  342. timestampStr := fmt.Sprintf("%d", timestamp)
  343. val := HbzDiv(currentItem.Value, preItem.Value)
  344. if val != "" {
  345. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  346. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  347. isAdd = true
  348. } else {
  349. if existVal != val {
  350. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  351. sql = fmt.Sprintf(sql, dataTableName)
  352. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  353. if err != nil {
  354. return err
  355. }
  356. }
  357. }
  358. }
  359. }
  360. existMap[existKey] = currentItem.DataTime
  361. }
  362. }
  363. }
  364. if isAdd {
  365. addSql = strings.TrimRight(addSql, ",")
  366. _, err = to.Raw(addSql).Exec()
  367. if err != nil {
  368. return err
  369. }
  370. }
  371. return
  372. }
  373. type EdbInfoCalculateHbzDetail struct {
  374. EdbInfoCalculateTbzId int `orm:"column(edb_info_calculate_tbz_id);pk"`
  375. EdbInfoId int `description:"指标id"`
  376. EdbCode string `description:"指标编码"`
  377. FromEdbInfoId int `description:"计算指标id"`
  378. FromEdbCode string `description:"计算指标编码"`
  379. FromEdbName string `description:"计算指标名称"`
  380. FromSource int `description:"计算指标来源"`
  381. FromSourceName string `description:"计算指标来源名称"`
  382. FromTag string `description:"来源指标标签"`
  383. Sort int `description:"计算指标名称排序"`
  384. CreateTime time.Time `description:"创建时间"`
  385. ModifyTime time.Time `description:"修改时间"`
  386. StartDate string `description:"开始日期"`
  387. EndDate string `description:"结束日期"`
  388. }
  389. func GetEdbInfoCalculateHbzDetail(edbInfoId int) (item *EdbInfoCalculateTbzDetail, err error) {
  390. o := orm.NewOrmUsingDB("data")
  391. sql := ` SELECT a.*,b.start_date,b.end_date FROM edb_info_calculate_mapping AS a
  392. INNER JOIN edb_info AS b ON a.from_edb_info_id=b.edb_info_id
  393. WHERE a.edb_info_id=? `
  394. err = o.Raw(sql, edbInfoId).QueryRow(&item)
  395. return
  396. }
  397. // 刷新所有环比值数据
  398. func RefreshAllCalculateHbz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string, formulaInt int) (err error) {
  399. o := orm.NewOrmUsingDB("data")
  400. to, err := o.Begin()
  401. if err != nil {
  402. return
  403. }
  404. defer func() {
  405. if err != nil {
  406. _ = to.Rollback()
  407. } else {
  408. _ = to.Commit()
  409. }
  410. }()
  411. if err != nil {
  412. return
  413. }
  414. edbInfoIdStr := strconv.Itoa(edbInfoId)
  415. //计算数据
  416. //计算数据
  417. var condition string
  418. var pars []interface{}
  419. condition += " AND edb_info_id=? "
  420. pars = append(pars, fromEdbInfo.EdbInfoId)
  421. if startDate != "" {
  422. condition += " AND data_time>=? "
  423. pars = append(pars, startDate)
  424. }
  425. if endDate != "" {
  426. condition += " AND data_time<=? "
  427. pars = append(pars, endDate)
  428. }
  429. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, fromEdbInfo.SubSource, 0)
  430. if err != nil {
  431. return err
  432. }
  433. var dateArr []string
  434. dataMap := make(map[string]*EdbInfoSearchData)
  435. for _, v := range dataList {
  436. dateArr = append(dateArr, v.DataTime)
  437. dataMap[v.DataTime] = v
  438. }
  439. fmt.Println("source:", source)
  440. //获取指标所有数据
  441. existDataList := make([]*EdbDataBase, 0)
  442. dataTableName := GetEdbDataTableName(source, subSource)
  443. fmt.Println("dataTableName:", dataTableName)
  444. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  445. sql = fmt.Sprintf(sql, dataTableName)
  446. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  447. if err != nil {
  448. return err
  449. }
  450. existDataMap := make(map[string]string)
  451. for _, v := range existDataList {
  452. existDataMap[v.DataTime] = v.Value
  453. }
  454. addSql := ` INSERT INTO edb_data_calculate_hbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,status,data_timestamp) values `
  455. var isAdd bool
  456. existMap := make(map[string]string)
  457. dataLen := len(dataList)
  458. fmt.Println("dataLen:", dataLen)
  459. for i := 0; i < dataLen; i++ {
  460. j := i + formulaInt
  461. if j < dataLen {
  462. //当期
  463. currentItem := dataList[i]
  464. preItem := dataList[j]
  465. if currentItem != nil && preItem != nil {
  466. existKey := edbCode + currentItem.DataTime
  467. if _, ok := existMap[existKey]; !ok {
  468. currentDate, _ := time.Parse(utils.FormatDate, currentItem.DataTime)
  469. timestamp := currentDate.UnixNano() / 1e6
  470. timestampStr := fmt.Sprintf("%d", timestamp)
  471. val := HbzDiv(currentItem.Value, preItem.Value)
  472. if val != "" {
  473. if existVal, findOk := existDataMap[currentItem.DataTime]; !findOk {
  474. addSql += GetAddSql(edbInfoIdStr, edbCode, currentItem.DataTime, timestampStr, val)
  475. isAdd = true
  476. } else {
  477. if existVal != val {
  478. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  479. sql = fmt.Sprintf(sql, dataTableName)
  480. _, err = to.Raw(sql, val, edbInfoId, currentItem.DataTime).Exec()
  481. if err != nil {
  482. return err
  483. }
  484. }
  485. }
  486. }
  487. }
  488. existMap[existKey] = currentItem.DataTime
  489. }
  490. }
  491. }
  492. if isAdd {
  493. addSql = strings.TrimRight(addSql, ",")
  494. _, err = to.Raw(addSql).Exec()
  495. if err != nil {
  496. return err
  497. }
  498. }
  499. return
  500. }