edb_data_calculate_tcz.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. // AddCalculateTcz 同差值
  13. func AddCalculateTcz(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("AddCalculateTcz,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. fmt.Println("req.EdbInfoId:", req.EdbInfoId)
  28. if req.EdbInfoId <= 0 {
  29. edbInfo = new(EdbInfo)
  30. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_TCZ
  31. edbInfo.SourceName = "同差值"
  32. edbInfo.EdbCode = edbCode
  33. edbInfo.EdbName = req.EdbName
  34. edbInfo.EdbNameSource = req.EdbName
  35. edbInfo.Frequency = req.Frequency
  36. edbInfo.Unit = req.Unit
  37. edbInfo.ClassifyId = req.ClassifyId
  38. edbInfo.SysUserId = sysUserId
  39. edbInfo.SysUserRealName = sysUserRealName
  40. edbInfo.CreateTime = time.Now()
  41. edbInfo.ModifyTime = time.Now()
  42. edbInfo.UniqueCode = uniqueCode
  43. edbInfo.CalculateFormula = req.Formula
  44. edbInfo.EdbNameEn = req.EdbName
  45. edbInfo.UnitEn = req.Unit
  46. edbInfo.EdbType = 2
  47. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  48. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  49. if tmpErr != nil {
  50. err = tmpErr
  51. return
  52. }
  53. edbInfo.EdbInfoId = int(newEdbInfoId)
  54. //关联关系
  55. {
  56. calculateMappingItem := new(EdbInfoCalculateMapping)
  57. calculateMappingItem.CreateTime = time.Now()
  58. calculateMappingItem.ModifyTime = time.Now()
  59. calculateMappingItem.Sort = 1
  60. calculateMappingItem.EdbCode = edbCode
  61. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  63. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  64. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  65. calculateMappingItem.FromSource = fromEdbInfo.Source
  66. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  67. calculateMappingItem.FromTag = ""
  68. calculateMappingItem.Source = edbInfo.Source
  69. calculateMappingItem.SourceName = edbInfo.SourceName
  70. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  71. _, err = to.Insert(calculateMappingItem)
  72. if err != nil {
  73. return
  74. }
  75. }
  76. } else {
  77. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  78. if err != nil {
  79. return
  80. }
  81. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_TCZ, utils.DATA_SUB_SOURCE_EDB)
  82. fmt.Println("dataTableName:", dataTableName)
  83. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  84. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  85. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  86. if err != nil {
  87. return
  88. }
  89. }
  90. //计算数据
  91. err = refreshAllCalculateTcz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "")
  92. return
  93. }
  94. // EditCalculateTcz 同差值
  95. func EditCalculateTcz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  96. o := orm.NewOrm()
  97. to, err := o.Begin()
  98. if err != nil {
  99. return
  100. }
  101. defer func() {
  102. if err != nil {
  103. fmt.Println("EditCalculateTcz,Err:" + err.Error())
  104. _ = to.Rollback()
  105. } else {
  106. _ = to.Commit()
  107. }
  108. }()
  109. //修改指标信息
  110. edbInfo.EdbName = req.EdbName
  111. edbInfo.EdbNameSource = req.EdbName
  112. edbInfo.Frequency = req.Frequency
  113. edbInfo.Unit = req.Unit
  114. edbInfo.ClassifyId = req.ClassifyId
  115. edbInfo.EdbNameEn = req.EdbNameEn
  116. edbInfo.UnitEn = req.UnitEn
  117. edbInfo.ModifyTime = time.Now()
  118. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  119. if err != nil {
  120. return
  121. }
  122. var existCondition string
  123. var existPars []interface{}
  124. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  125. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  126. //判断计算指标是否被更换
  127. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  128. if err != nil {
  129. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  130. return
  131. }
  132. if count > 0 { // 指标未被替换,无需重新计算
  133. return
  134. }
  135. //删除,计算指标关联的,基础指标的关联关系
  136. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  137. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  138. if err != nil {
  139. return
  140. }
  141. //清空原有数据
  142. sql = ` DELETE FROM edb_data_calculate_tcz WHERE edb_info_id = ? `
  143. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  144. if err != nil {
  145. return
  146. }
  147. //关联关系
  148. {
  149. calculateMappingItem := &EdbInfoCalculateMapping{
  150. EdbInfoCalculateMappingId: 0,
  151. EdbInfoId: edbInfo.EdbInfoId,
  152. Source: utils.DATA_SOURCE_CALCULATE_TCZ,
  153. SourceName: "同差值",
  154. EdbCode: edbInfo.EdbCode,
  155. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  156. FromEdbCode: fromEdbInfo.EdbCode,
  157. FromEdbName: fromEdbInfo.EdbName,
  158. FromSource: fromEdbInfo.Source,
  159. FromSourceName: fromEdbInfo.SourceName,
  160. FromTag: "",
  161. Sort: 1,
  162. CreateTime: time.Now(),
  163. ModifyTime: time.Now(),
  164. FromSubSource: fromEdbInfo.SubSource,
  165. }
  166. _, err = to.Insert(calculateMappingItem)
  167. if err != nil {
  168. return
  169. }
  170. }
  171. //计算数据
  172. err = refreshAllCalculateTcz(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "")
  173. return
  174. }
  175. // RefreshAllCalculateTcz 刷新全部同差值数据
  176. func RefreshAllCalculateTcz(edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  177. o := orm.NewOrm()
  178. to, err := o.Begin()
  179. if err != nil {
  180. return
  181. }
  182. defer func() {
  183. if err != nil {
  184. fmt.Println("RefreshAllCalculateTcz,Err:" + err.Error())
  185. _ = to.Rollback()
  186. } else {
  187. _ = to.Commit()
  188. }
  189. }()
  190. err = refreshAllCalculateTcz(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate)
  191. return
  192. }
  193. func refreshAllCalculateTcz(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  194. edbInfoIdStr := strconv.Itoa(edbInfoId)
  195. //计算数据
  196. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource, FindEdbDataListAllCond{
  197. EdbInfoId: fromEdbInfo.EdbInfoId,
  198. StartDataTime: startDate,
  199. StartDataTimeCond: ">=",
  200. }, 0)
  201. if err != nil {
  202. return err
  203. }
  204. var dateArr []string
  205. dataMap := make(map[string]*EdbInfoSearchData)
  206. for _, v := range dataList {
  207. dateArr = append(dateArr, v.DataTime)
  208. dataMap[v.DataTime] = v
  209. }
  210. //获取指标所有数据
  211. existDataList := make([]*EdbData, 0)
  212. dataTableName := GetEdbDataTableName(source, subSource)
  213. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  214. sql = fmt.Sprintf(sql, dataTableName)
  215. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  216. if err != nil {
  217. return err
  218. }
  219. existDataMap := make(map[string]string)
  220. removeDateMap := make(map[string]bool) //需要移除的日期
  221. for _, v := range existDataList {
  222. existDataMap[v.DataTime] = v.Value
  223. removeDateMap[v.DataTime] = true
  224. }
  225. addSql := ` INSERT INTO edb_data_calculate_tcz(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. delete(removeDateMap, av)
  231. if currentItem != nil {
  232. //当前日期
  233. currentDate, err := time.ParseInLocation(utils.FormatDate, av, time.Local)
  234. if err != nil {
  235. return err
  236. }
  237. //上一年的日期
  238. preDate := currentDate.AddDate(-1, 0, 0)
  239. preDateStr := preDate.Format(utils.FormatDate)
  240. if findItem, ok := dataMap[preDateStr]; ok {
  241. //上一年同期找到
  242. //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  243. timestamp := currentDate.UnixNano() / 1e6
  244. timestampStr := fmt.Sprintf("%d", timestamp)
  245. val := TczSub(currentItem.Value, findItem.Value)
  246. if existVal, ok := existDataMap[av]; !ok {
  247. if _, existOk := existAddDataMap[av]; !existOk {
  248. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  249. isAdd = true
  250. }
  251. existAddDataMap[av] = av
  252. } else {
  253. existValDecimal, err := decimal.NewFromString(existVal)
  254. existStr := existValDecimal.String()
  255. if existStr != val {
  256. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  257. sql = fmt.Sprintf(sql, dataTableName)
  258. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  259. if err != nil {
  260. return err
  261. }
  262. }
  263. }
  264. //utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
  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 := TczSub(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 := TczSub(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 := TczSub(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. for i := 0; i < 35; i++ {
  350. nextDateDay := preDate.AddDate(0, 0, i)
  351. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  352. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  353. timestamp := currentDate.UnixNano() / 1e6
  354. timestampStr := fmt.Sprintf("%d", timestamp)
  355. val := TczSub(currentItem.Value, findItem.Value)
  356. if existVal, ok := existDataMap[av]; !ok {
  357. if _, existOk := existAddDataMap[av]; !existOk {
  358. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  359. isAdd = true
  360. }
  361. existAddDataMap[av] = av
  362. } else {
  363. existValDecimal, err := decimal.NewFromString(existVal)
  364. existStr := existValDecimal.String()
  365. if existStr != val {
  366. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  367. sql = fmt.Sprintf(sql, dataTableName)
  368. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  369. if err != nil {
  370. return err
  371. }
  372. }
  373. }
  374. break
  375. } else {
  376. preDateDay := preDate.AddDate(0, 0, -i)
  377. preDateDayStr := preDateDay.Format(utils.FormatDate)
  378. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  379. timestamp := currentDate.UnixNano() / 1e6
  380. timestampStr := fmt.Sprintf("%d", timestamp)
  381. val := TczSub(currentItem.Value, findItem.Value)
  382. if existVal, ok := existDataMap[av]; !ok {
  383. if _, existOk := existAddDataMap[av]; !existOk {
  384. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  385. isAdd = true
  386. }
  387. existAddDataMap[av] = av
  388. } else {
  389. existValDecimal, err := decimal.NewFromString(existVal)
  390. existStr := existValDecimal.String()
  391. if existStr != val {
  392. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  393. sql = fmt.Sprintf(sql, dataTableName)
  394. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  395. if err != nil {
  396. return err
  397. }
  398. }
  399. }
  400. break
  401. }
  402. }
  403. }
  404. }
  405. }
  406. }
  407. }
  408. if len(removeDateMap) > 0 {
  409. removeDateList := make([]string, 0) //需要移除的日期
  410. for k := range removeDateMap {
  411. removeDateList = append(removeDateList, k)
  412. }
  413. removeDateStr := strings.Join(removeDateList, `","`)
  414. removeDateStr = `"` + removeDateStr + `"`
  415. //如果拼接指标变更了,那么需要删除所有的指标数据
  416. tableName := GetEdbDataTableName(source, subSource)
  417. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  418. _, err = to.Raw(sql, edbInfoId).Exec()
  419. if err != nil {
  420. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  421. return
  422. }
  423. }
  424. if isAdd {
  425. addSql = strings.TrimRight(addSql, ",")
  426. _, err = to.Raw(addSql).Exec()
  427. if err != nil {
  428. return err
  429. }
  430. }
  431. return
  432. }
  433. // TczSub 计算同差值
  434. func TczSub(a, b float64) string {
  435. af := decimal.NewFromFloat(a)
  436. //fmt.Println(af)
  437. bf := decimal.NewFromFloat(b)
  438. val, _ := af.Sub(bf).Float64()
  439. //valStr := utils.SubFloatToString(val, 4)
  440. valStr := decimal.NewFromFloat(val).Round(4).String()
  441. return valStr
  442. }