edb_data_calculate_tbz.go 15 KB

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