edb_data_calculate_tcz.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. for _, v := range existDataList {
  221. existDataMap[v.DataTime] = v.Value
  222. }
  223. addSql := ` INSERT INTO edb_data_calculate_tcz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  224. var isAdd bool
  225. existAddDataMap := make(map[string]string)
  226. for _, av := range dateArr {
  227. currentItem := dataMap[av]
  228. if currentItem != nil {
  229. //当前日期
  230. currentDate, err := time.ParseInLocation(utils.FormatDate, av, time.Local)
  231. if err != nil {
  232. return err
  233. }
  234. //上一年的日期
  235. preDate := currentDate.AddDate(-1, 0, 0)
  236. preDateStr := preDate.Format(utils.FormatDate)
  237. if findItem, ok := dataMap[preDateStr]; ok {
  238. //上一年同期找到
  239. //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  240. timestamp := currentDate.UnixNano() / 1e6
  241. timestampStr := fmt.Sprintf("%d", timestamp)
  242. val := TczSub(currentItem.Value, findItem.Value)
  243. if existVal, ok := existDataMap[av]; !ok {
  244. if _, existOk := existAddDataMap[av]; !existOk {
  245. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  246. isAdd = true
  247. }
  248. existAddDataMap[av] = av
  249. } else {
  250. existValDecimal, err := decimal.NewFromString(existVal)
  251. existStr := existValDecimal.String()
  252. if existStr != val {
  253. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  254. sql = fmt.Sprintf(sql, dataTableName)
  255. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  256. if err != nil {
  257. return err
  258. }
  259. }
  260. }
  261. //utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
  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 := TczSub(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 := TczSub(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 := TczSub(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. for i := 0; i < 35; i++ {
  347. nextDateDay := preDate.AddDate(0, 0, i)
  348. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  349. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  350. timestamp := currentDate.UnixNano() / 1e6
  351. timestampStr := fmt.Sprintf("%d", timestamp)
  352. val := TczSub(currentItem.Value, findItem.Value)
  353. if existVal, ok := existDataMap[av]; !ok {
  354. if _, existOk := existAddDataMap[av]; !existOk {
  355. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  356. isAdd = true
  357. }
  358. existAddDataMap[av] = av
  359. } else {
  360. existValDecimal, err := decimal.NewFromString(existVal)
  361. existStr := existValDecimal.String()
  362. if existStr != val {
  363. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  364. sql = fmt.Sprintf(sql, dataTableName)
  365. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  366. if err != nil {
  367. return err
  368. }
  369. }
  370. }
  371. break
  372. } else {
  373. preDateDay := preDate.AddDate(0, 0, -i)
  374. preDateDayStr := preDateDay.Format(utils.FormatDate)
  375. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  376. timestamp := currentDate.UnixNano() / 1e6
  377. timestampStr := fmt.Sprintf("%d", timestamp)
  378. val := TczSub(currentItem.Value, findItem.Value)
  379. if existVal, ok := existDataMap[av]; !ok {
  380. if _, existOk := existAddDataMap[av]; !existOk {
  381. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  382. isAdd = true
  383. }
  384. existAddDataMap[av] = av
  385. } else {
  386. existValDecimal, err := decimal.NewFromString(existVal)
  387. existStr := existValDecimal.String()
  388. if existStr != val {
  389. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  390. sql = fmt.Sprintf(sql, dataTableName)
  391. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  392. if err != nil {
  393. return err
  394. }
  395. }
  396. }
  397. break
  398. }
  399. }
  400. }
  401. }
  402. }
  403. }
  404. }
  405. if isAdd {
  406. addSql = strings.TrimRight(addSql, ",")
  407. _, err = to.Raw(addSql).Exec()
  408. if err != nil {
  409. return err
  410. }
  411. }
  412. return
  413. }
  414. // TczSub 计算同差值
  415. func TczSub(a, b float64) string {
  416. af := decimal.NewFromFloat(a)
  417. //fmt.Println(af)
  418. bf := decimal.NewFromFloat(b)
  419. val, _ := af.Sub(bf).Float64()
  420. //valStr := utils.SubFloatToString(val, 4)
  421. valStr := decimal.NewFromFloat(val).Round(4).String()
  422. return valStr
  423. }