edb_data_calculate_tcz.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/beego/beego/v2/client/orm"
  6. "github.com/shopspring/decimal"
  7. "hongze/hongze_edb_lib/utils"
  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. _, 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_TCZ)
  78. fmt.Println("dataTableName:", dataTableName)
  79. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  80. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  81. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  82. if err != nil {
  83. return
  84. }
  85. }
  86. //计算数据
  87. err = refreshAllCalculateTcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
  88. return
  89. }
  90. // EditCalculateTcz 同差值
  91. func EditCalculateTcz(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  92. o := orm.NewOrm()
  93. to, err := o.Begin()
  94. if err != nil {
  95. return
  96. }
  97. defer func() {
  98. if err != nil {
  99. fmt.Println("EditCalculateTcz,Err:" + err.Error())
  100. _ = to.Rollback()
  101. } else {
  102. _ = to.Commit()
  103. }
  104. }()
  105. //修改指标信息
  106. edbInfo.EdbName = req.EdbName
  107. edbInfo.EdbNameSource = req.EdbName
  108. edbInfo.Frequency = req.Frequency
  109. edbInfo.Unit = req.Unit
  110. edbInfo.ClassifyId = req.ClassifyId
  111. edbInfo.ModifyTime = time.Now()
  112. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  113. if err != nil {
  114. return
  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. //判断计算指标是否被更换
  121. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  122. if err != nil {
  123. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  124. return
  125. }
  126. if count > 0 { // 指标未被替换,无需重新计算
  127. return
  128. }
  129. //删除,计算指标关联的,基础指标的关联关系
  130. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  131. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  132. if err != nil {
  133. return
  134. }
  135. //清空原有数据
  136. sql = ` DELETE FROM edb_data_calculate_tcz WHERE edb_info_id = ? `
  137. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  138. if err != nil {
  139. return
  140. }
  141. //关联关系
  142. {
  143. calculateMappingItem := &EdbInfoCalculateMapping{
  144. EdbInfoCalculateMappingId: 0,
  145. EdbInfoId: edbInfo.EdbInfoId,
  146. Source: utils.DATA_SOURCE_CALCULATE_TCZ,
  147. SourceName: "同差值",
  148. EdbCode: edbInfo.EdbCode,
  149. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  150. FromEdbCode: fromEdbInfo.EdbCode,
  151. FromEdbName: fromEdbInfo.EdbName,
  152. FromSource: fromEdbInfo.Source,
  153. FromSourceName: fromEdbInfo.SourceName,
  154. FromTag: "",
  155. Sort: 1,
  156. CreateTime: time.Now(),
  157. ModifyTime: time.Now(),
  158. }
  159. _, err = to.Insert(calculateMappingItem)
  160. if err != nil {
  161. return
  162. }
  163. }
  164. //计算数据
  165. err = refreshAllCalculateTcz(to, edbInfo.EdbInfoId, edbInfo.Source, fromEdbInfo, edbInfo.EdbCode, "", "")
  166. return
  167. }
  168. // RefreshAllCalculateTcz 刷新全部同差值数据
  169. func RefreshAllCalculateTcz(edbInfoId, source 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("RefreshAllCalculateTcz,Err:" + err.Error())
  178. _ = to.Rollback()
  179. } else {
  180. _ = to.Commit()
  181. }
  182. }()
  183. err = refreshAllCalculateTcz(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
  184. return
  185. }
  186. func refreshAllCalculateTcz(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 := GetEdbDataListAllByTo(to, 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. //获取指标所有数据
  213. existDataList := make([]*EdbData, 0)
  214. dataTableName := GetEdbDataTableName(source)
  215. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  216. sql = fmt.Sprintf(sql, dataTableName)
  217. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  218. if err != nil {
  219. return err
  220. }
  221. existDataMap := make(map[string]string)
  222. for _, v := range existDataList {
  223. existDataMap[v.DataTime] = v.Value
  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. 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. //上一年同期找到
  241. //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  242. timestamp := currentDate.UnixNano() / 1e6
  243. timestampStr := fmt.Sprintf("%d", timestamp)
  244. val := TczSub(currentItem.Value, findItem.Value)
  245. if existVal, ok := existDataMap[av]; !ok {
  246. if _, existOk := existAddDataMap[av]; !existOk {
  247. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  248. isAdd = true
  249. }
  250. existAddDataMap[av] = av
  251. } else {
  252. existValDecimal, err := decimal.NewFromString(existVal)
  253. existStr := existValDecimal.String()
  254. if existStr != val {
  255. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  256. sql = fmt.Sprintf(sql, dataTableName)
  257. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  258. if err != nil {
  259. return err
  260. }
  261. }
  262. }
  263. //utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
  264. continue
  265. } else {
  266. if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
  267. for i := 0; i <= 35; i++ {
  268. nextDateDay := preDate.AddDate(0, 0, i)
  269. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  270. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  271. timestamp := currentDate.UnixNano() / 1e6
  272. timestampStr := fmt.Sprintf("%d", timestamp)
  273. val := TczSub(currentItem.Value, findItem.Value)
  274. if existVal, ok := existDataMap[av]; !ok {
  275. if _, existOk := existAddDataMap[av]; !existOk {
  276. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  277. isAdd = true
  278. }
  279. existAddDataMap[av] = av
  280. } else {
  281. existValDecimal, err := decimal.NewFromString(existVal)
  282. existStr := existValDecimal.String()
  283. if existStr != val {
  284. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  285. sql = fmt.Sprintf(sql, dataTableName)
  286. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  287. if err != nil {
  288. return err
  289. }
  290. }
  291. }
  292. break
  293. } else {
  294. preDateDay := preDate.AddDate(0, 0, -i)
  295. preDateDayStr := preDateDay.Format(utils.FormatDate)
  296. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  297. timestamp := currentDate.UnixNano() / 1e6
  298. timestampStr := fmt.Sprintf("%d", timestamp)
  299. val := TczSub(currentItem.Value, findItem.Value)
  300. if existVal, ok := existDataMap[av]; !ok {
  301. if _, existOk := existAddDataMap[av]; !existOk {
  302. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  303. isAdd = true
  304. }
  305. existAddDataMap[av] = av
  306. } else {
  307. existValDecimal, err := decimal.NewFromString(existVal)
  308. existStr := existValDecimal.String()
  309. if existStr != val {
  310. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  311. sql = fmt.Sprintf(sql, dataTableName)
  312. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  313. if err != nil {
  314. return err
  315. }
  316. }
  317. }
  318. break
  319. }
  320. }
  321. }
  322. } else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
  323. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
  324. timestamp := currentDate.UnixNano() / 1e6
  325. timestampStr := fmt.Sprintf("%d", timestamp)
  326. val := TczSub(currentItem.Value, findItem.Value)
  327. if existVal, ok := existDataMap[av]; !ok {
  328. if _, existOk := existAddDataMap[av]; !existOk {
  329. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  330. isAdd = true
  331. }
  332. existAddDataMap[av] = av
  333. } else {
  334. existValDecimal, err := decimal.NewFromString(existVal)
  335. existStr := existValDecimal.String()
  336. if existStr != val {
  337. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  338. sql = fmt.Sprintf(sql, dataTableName)
  339. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  340. if err != nil {
  341. return err
  342. }
  343. }
  344. }
  345. break
  346. }
  347. } else {
  348. for i := 0; i < 35; i++ {
  349. nextDateDay := preDate.AddDate(0, 0, i)
  350. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  351. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  352. timestamp := currentDate.UnixNano() / 1e6
  353. timestampStr := fmt.Sprintf("%d", timestamp)
  354. val := TczSub(currentItem.Value, findItem.Value)
  355. if existVal, ok := existDataMap[av]; !ok {
  356. if _, existOk := existAddDataMap[av]; !existOk {
  357. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  358. isAdd = true
  359. }
  360. existAddDataMap[av] = av
  361. } else {
  362. existValDecimal, err := decimal.NewFromString(existVal)
  363. existStr := existValDecimal.String()
  364. if existStr != val {
  365. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  366. sql = fmt.Sprintf(sql, dataTableName)
  367. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  368. if err != nil {
  369. return err
  370. }
  371. }
  372. }
  373. break
  374. } else {
  375. preDateDay := preDate.AddDate(0, 0, -i)
  376. preDateDayStr := preDateDay.Format(utils.FormatDate)
  377. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  378. timestamp := currentDate.UnixNano() / 1e6
  379. timestampStr := fmt.Sprintf("%d", timestamp)
  380. val := TczSub(currentItem.Value, findItem.Value)
  381. if existVal, ok := existDataMap[av]; !ok {
  382. if _, existOk := existAddDataMap[av]; !existOk {
  383. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  384. isAdd = true
  385. }
  386. existAddDataMap[av] = av
  387. } else {
  388. existValDecimal, err := decimal.NewFromString(existVal)
  389. existStr := existValDecimal.String()
  390. if existStr != val {
  391. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  392. sql = fmt.Sprintf(sql, dataTableName)
  393. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  394. if err != nil {
  395. return err
  396. }
  397. }
  398. }
  399. break
  400. }
  401. }
  402. }
  403. }
  404. }
  405. }
  406. }
  407. if isAdd {
  408. addSql = strings.TrimRight(addSql, ",")
  409. _, err = to.Raw(addSql).Exec()
  410. if err != nil {
  411. return err
  412. }
  413. }
  414. return
  415. }
  416. // TczSub 计算同差值
  417. func TczSub(a, b float64) string {
  418. af := decimal.NewFromFloat(a)
  419. //fmt.Println(af)
  420. bf := decimal.NewFromFloat(b)
  421. val, _ := af.Sub(bf).Float64()
  422. //valStr := utils.SubFloatToString(val, 4)
  423. valStr := decimal.NewFromFloat(val).RoundCeil(4).String()
  424. return valStr
  425. }