edb_data_calculate_tbz.go 15 KB

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