edb_data_calculate_tcz.go 14 KB

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