edb_data_calculate_tbz.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "strconv"
  9. "strings"
  10. "time"
  11. )
  12. // AddCalculateTbz 同比值
  13. func AddCalculateTbz(req *EdbInfoCalculateBatchSaveReq, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error) {
  14. o := orm.NewOrm()
  15. to, err := o.Begin()
  16. if err != nil {
  17. return
  18. }
  19. defer func() {
  20. if err != nil {
  21. fmt.Println("AddCalculateTbz,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TBZ
  30. edbInfo.SourceName = "同比值"
  31. edbInfo.EdbCode = edbCode
  32. edbInfo.EdbName = req.EdbName
  33. edbInfo.EdbNameSource = req.EdbName
  34. edbInfo.Frequency = req.Frequency
  35. edbInfo.Unit = req.Unit
  36. edbInfo.ClassifyId = req.ClassifyId
  37. edbInfo.SysUserId = sysUserId
  38. edbInfo.SysUserRealName = sysUserRealName
  39. edbInfo.CreateTime = time.Now()
  40. edbInfo.ModifyTime = time.Now()
  41. edbInfo.UniqueCode = uniqueCode
  42. edbInfo.CalculateFormula = req.Formula
  43. edbInfo.EdbType = 2
  44. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  45. if tmpErr != nil {
  46. err = tmpErr
  47. return
  48. }
  49. edbInfo.EdbInfoId = int(newEdbInfoId)
  50. //关联关系
  51. {
  52. calculateMappingItem := new(EdbInfoCalculateMapping)
  53. calculateMappingItem.CreateTime = time.Now()
  54. calculateMappingItem.ModifyTime = time.Now()
  55. calculateMappingItem.Sort = 1
  56. calculateMappingItem.EdbCode = edbCode
  57. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  58. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  59. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  60. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  61. calculateMappingItem.FromSource = fromEdbInfo.Source
  62. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  63. calculateMappingItem.FromTag = ""
  64. calculateMappingItem.Source = edbInfo.Source
  65. calculateMappingItem.SourceName = edbInfo.SourceName
  66. _, err = to.Insert(calculateMappingItem)
  67. if err != nil {
  68. return
  69. }
  70. }
  71. } else {
  72. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  73. if err != nil {
  74. return
  75. }
  76. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TBZ)
  77. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  78. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  79. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  80. if err != nil {
  81. return
  82. }
  83. }
  84. //计算数据
  85. err = refreshAllCalculateTbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbCode, "", "")
  86. return
  87. }
  88. // EditCalculateTbz 同比值
  89. func EditCalculateTbz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  90. o := orm.NewOrm()
  91. to, err := o.Begin()
  92. if err != nil {
  93. return
  94. }
  95. defer func() {
  96. if err != nil {
  97. fmt.Println("EditCalculateTbz,Err:" + err.Error())
  98. _ = to.Rollback()
  99. } else {
  100. _ = to.Commit()
  101. }
  102. }()
  103. //修改指标信息
  104. edbInfo.EdbName = req.EdbName
  105. edbInfo.EdbNameSource = req.EdbName
  106. edbInfo.Frequency = req.Frequency
  107. edbInfo.Unit = req.Unit
  108. edbInfo.ClassifyId = req.ClassifyId
  109. edbInfo.ModifyTime = time.Now()
  110. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  111. if err != nil {
  112. return
  113. }
  114. //判断计算指标是否被更换
  115. var existCondition string
  116. var existPars []interface{}
  117. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  118. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  119. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  120. if err != nil {
  121. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  122. return
  123. }
  124. if count > 0 { // 指标未被替换,无需重新计算
  125. return
  126. }
  127. //删除,计算指标关联的,基础指标的关联关系
  128. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  129. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  130. if err != nil {
  131. return
  132. }
  133. //清空原有数据
  134. sql = ` DELETE FROM edb_data_calculate_tbz WHERE edb_info_id = ? `
  135. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  136. if err != nil {
  137. return
  138. }
  139. //关联关系
  140. {
  141. calculateMappingItem := &EdbInfoCalculateMapping{
  142. EdbInfoCalculateMappingId: 0,
  143. EdbInfoId: edbInfo.EdbInfoId,
  144. Source: utils.DATA_SOURCE_CALCULATE_TBZ,
  145. SourceName: "同比值",
  146. EdbCode: edbInfo.EdbCode,
  147. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  148. FromEdbCode: fromEdbInfo.EdbCode,
  149. FromEdbName: fromEdbInfo.EdbName,
  150. FromSource: fromEdbInfo.Source,
  151. FromSourceName: fromEdbInfo.SourceName,
  152. FromTag: "",
  153. Sort: 1,
  154. CreateTime: time.Now(),
  155. ModifyTime: time.Now(),
  156. }
  157. _, err = to.Insert(calculateMappingItem)
  158. if err != nil {
  159. return
  160. }
  161. }
  162. //计算数据
  163. err = refreshAllCalculateTbz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
  164. return
  165. }
  166. // RefreshAllCalculateTbz 刷新所有同比值数据
  167. func RefreshAllCalculateTbz(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  168. o := orm.NewOrm()
  169. to, err := o.Begin()
  170. if err != nil {
  171. return
  172. }
  173. defer func() {
  174. if err != nil {
  175. fmt.Println("RefreshAllCalculateTbz,Err:" + err.Error())
  176. _ = to.Rollback()
  177. } else {
  178. _ = to.Commit()
  179. }
  180. }()
  181. //计算数据
  182. err = refreshAllCalculateTbz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
  183. return
  184. }
  185. // refreshAllCalculateTbz
  186. func refreshAllCalculateTbz(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  187. edbInfoIdStr := strconv.Itoa(edbInfoId)
  188. //计算数据
  189. //计算数据
  190. var condition string
  191. var pars []interface{}
  192. condition += " AND edb_info_id=? "
  193. pars = append(pars, fromEdbInfo.EdbInfoId)
  194. if startDate != "" {
  195. condition += " AND data_time>=? "
  196. pars = append(pars, startDate)
  197. }
  198. //if endDate != "" {
  199. // condition += " AND data_time<=? "
  200. // pars = append(pars, endDate)
  201. //}
  202. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 0)
  203. if err != nil {
  204. return err
  205. }
  206. var dateArr []string
  207. dataMap := make(map[string]*EdbInfoSearchData)
  208. for _, v := range dataList {
  209. dateArr = append(dateArr, v.DataTime)
  210. dataMap[v.DataTime] = v
  211. }
  212. fmt.Println("source:", source)
  213. //获取指标所有数据
  214. existDataList := make([]*EdbData, 0)
  215. dataTableName := GetEdbDataTableName(source)
  216. fmt.Println("dataTableName:", dataTableName)
  217. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  218. sql = fmt.Sprintf(sql, dataTableName)
  219. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  220. if err != nil {
  221. return err
  222. }
  223. existDataMap := make(map[string]string)
  224. for _, v := range existDataList {
  225. existDataMap[v.DataTime] = v.Value
  226. }
  227. fmt.Println("existDataMap:", existDataMap)
  228. addSql := ` INSERT INTO edb_data_calculate_tbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  229. var isAdd bool
  230. existAddDataMap := make(map[string]string)
  231. for _, av := range dateArr {
  232. currentItem := dataMap[av]
  233. if currentItem != nil {
  234. //当前日期
  235. currentDate, err := time.ParseInLocation(utils.FormatDate, av, time.Local)
  236. if err != nil {
  237. return err
  238. }
  239. //上一年的日期
  240. preDate := currentDate.AddDate(-1, 0, 0)
  241. preDateStr := preDate.Format(utils.FormatDate)
  242. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
  243. //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  244. timestamp := currentDate.UnixNano() / 1e6
  245. timestampStr := fmt.Sprintf("%d", timestamp)
  246. val := TbzDiv(currentItem.Value, findItem.Value)
  247. if existVal, ok := existDataMap[av]; !ok {
  248. if _, existOk := existAddDataMap[av]; !existOk {
  249. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  250. isAdd = true
  251. }
  252. existAddDataMap[av] = av
  253. } else {
  254. existValDecimal, err := decimal.NewFromString(existVal)
  255. existStr := existValDecimal.String()
  256. if existStr != val {
  257. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  258. sql = fmt.Sprintf(sql, dataTableName)
  259. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  260. if err != nil {
  261. return err
  262. }
  263. }
  264. }
  265. continue
  266. } else {
  267. if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
  268. for i := 0; i <= 35; i++ {
  269. nextDateDay := preDate.AddDate(0, 0, i)
  270. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  271. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  272. timestamp := currentDate.UnixNano() / 1e6
  273. timestampStr := fmt.Sprintf("%d", timestamp)
  274. val := TbzDiv(currentItem.Value, findItem.Value)
  275. if existVal, ok := existDataMap[av]; !ok {
  276. if _, existOk := existAddDataMap[av]; !existOk {
  277. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  278. isAdd = true
  279. }
  280. existAddDataMap[av] = av
  281. } else {
  282. existValDecimal, err := decimal.NewFromString(existVal)
  283. existStr := existValDecimal.String()
  284. if existStr != val {
  285. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  286. sql = fmt.Sprintf(sql, dataTableName)
  287. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  288. if err != nil {
  289. return err
  290. }
  291. }
  292. }
  293. break
  294. } else {
  295. preDateDay := preDate.AddDate(0, 0, -i)
  296. preDateDayStr := preDateDay.Format(utils.FormatDate)
  297. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  298. timestamp := currentDate.UnixNano() / 1e6
  299. timestampStr := fmt.Sprintf("%d", timestamp)
  300. val := TbzDiv(currentItem.Value, findItem.Value)
  301. if existVal, ok := existDataMap[av]; !ok {
  302. if _, existOk := existAddDataMap[av]; !existOk {
  303. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  304. isAdd = true
  305. }
  306. existAddDataMap[av] = av
  307. } else {
  308. existValDecimal, err := decimal.NewFromString(existVal)
  309. existStr := existValDecimal.String()
  310. if existStr != val {
  311. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  312. sql = fmt.Sprintf(sql, dataTableName)
  313. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  314. if err != nil {
  315. return err
  316. }
  317. }
  318. }
  319. break
  320. }
  321. }
  322. }
  323. } else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
  324. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
  325. timestamp := currentDate.UnixNano() / 1e6
  326. timestampStr := fmt.Sprintf("%d", timestamp)
  327. val := TbzDiv(currentItem.Value, findItem.Value)
  328. if existVal, ok := existDataMap[av]; !ok {
  329. if _, existOk := existAddDataMap[av]; !existOk {
  330. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  331. isAdd = true
  332. }
  333. existAddDataMap[av] = av
  334. } else {
  335. existValDecimal, err := decimal.NewFromString(existVal)
  336. existStr := existValDecimal.String()
  337. if existStr != val {
  338. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  339. sql = fmt.Sprintf(sql, dataTableName)
  340. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  341. if err != nil {
  342. return err
  343. }
  344. }
  345. }
  346. break
  347. }
  348. } else {
  349. nextDateDay := preDate.AddDate(0, 0, 1)
  350. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  351. preDateDay := preDate.AddDate(0, 0, -1)
  352. preDateDayStr := preDateDay.Format(utils.FormatDate)
  353. for i := 0; i < 35; i++ {
  354. if i >= 1 {
  355. nextDateDay = nextDateDay.AddDate(0, 0, i)
  356. nextDateDayStr = nextDateDay.Format(utils.FormatDate)
  357. }
  358. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  359. timestamp := currentDate.UnixNano() / 1e6
  360. timestampStr := fmt.Sprintf("%d", timestamp)
  361. val := TbzDiv(currentItem.Value, findItem.Value)
  362. if existVal, ok := existDataMap[av]; !ok {
  363. if _, existOk := existAddDataMap[av]; !existOk {
  364. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  365. isAdd = true
  366. }
  367. existAddDataMap[av] = av
  368. } else {
  369. existValDecimal, err := decimal.NewFromString(existVal)
  370. existStr := existValDecimal.String()
  371. if existStr != val {
  372. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  373. sql = fmt.Sprintf(sql, dataTableName)
  374. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  375. if err != nil {
  376. return err
  377. }
  378. }
  379. }
  380. break
  381. } else {
  382. if i >= 1 {
  383. preDateDay = preDateDay.AddDate(0, 0, -i)
  384. preDateDayStr = preDateDay.Format(utils.FormatDate)
  385. }
  386. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  387. timestamp := currentDate.UnixNano() / 1e6
  388. timestampStr := fmt.Sprintf("%d", timestamp)
  389. val := TbzDiv(currentItem.Value, findItem.Value)
  390. if existVal, ok := existDataMap[av]; !ok {
  391. if _, existOk := existAddDataMap[av]; !existOk {
  392. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  393. isAdd = true
  394. }
  395. existAddDataMap[av] = av
  396. } else {
  397. existValDecimal, err := decimal.NewFromString(existVal)
  398. existStr := existValDecimal.String()
  399. if existStr != val {
  400. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  401. sql = fmt.Sprintf(sql, dataTableName)
  402. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  403. if err != nil {
  404. return err
  405. }
  406. }
  407. }
  408. break
  409. }
  410. }
  411. }
  412. }
  413. }
  414. }
  415. }
  416. if isAdd {
  417. addSql = strings.TrimRight(addSql, ",")
  418. _, err = to.Raw(addSql).Exec()
  419. if err != nil {
  420. return err
  421. }
  422. }
  423. return
  424. }
  425. func TbzDiv(a, b float64) string {
  426. var valStr string
  427. if b != 0 {
  428. af := decimal.NewFromFloat(a)
  429. bf := decimal.NewFromFloat(b)
  430. val, _ := af.Div(bf).Float64()
  431. val = val - 1
  432. valStr = decimal.NewFromFloat(val).RoundCeil(4).String()
  433. } else {
  434. valStr = "0"
  435. }
  436. return valStr
  437. }