edb_info_calculate_hcz.go 16 KB

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