edb_data_calculate_tcz.go 14 KB

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