edb_data_calculate_ljzzy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. // AddCalculateLjzzy 累计值转月
  13. func AddCalculateLjzzy(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("AddCalculateLjzzy,Err:" + err.Error())
  22. _ = to.Rollback()
  23. } else {
  24. _ = to.Commit()
  25. }
  26. }()
  27. if req.EdbInfoId <= 0 {
  28. edbInfo = new(EdbInfo)
  29. edbInfo.Source = utils.DATA_SOURCE_CALCULATE_LJZZY
  30. edbInfo.SourceName = "累计值转月值"
  31. edbInfo.EdbCode = edbCode
  32. edbInfo.EdbName = req.EdbName
  33. edbInfo.EdbNameSource = req.EdbName
  34. edbInfo.Frequency = req.Frequency
  35. edbInfo.Unit = req.Unit
  36. edbInfo.ClassifyId = req.ClassifyId
  37. edbInfo.SysUserId = sysUserId
  38. edbInfo.SysUserRealName = sysUserRealName
  39. edbInfo.CreateTime = time.Now()
  40. edbInfo.ModifyTime = time.Now()
  41. edbInfo.UniqueCode = uniqueCode
  42. edbInfo.CalculateFormula = req.Formula
  43. edbInfo.EdbNameEn = req.EdbName
  44. edbInfo.UnitEn = req.Unit
  45. edbInfo.EdbType = 2
  46. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  47. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  48. if tmpErr != nil {
  49. err = tmpErr
  50. return
  51. }
  52. edbInfo.EdbInfoId = int(newEdbInfoId)
  53. //关联关系
  54. {
  55. calculateMappingItem := new(EdbInfoCalculateMapping)
  56. calculateMappingItem.CreateTime = time.Now()
  57. calculateMappingItem.ModifyTime = time.Now()
  58. calculateMappingItem.Sort = 1
  59. calculateMappingItem.EdbCode = edbCode
  60. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  61. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  62. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  63. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  64. calculateMappingItem.FromSource = fromEdbInfo.Source
  65. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  66. calculateMappingItem.FromTag = ""
  67. calculateMappingItem.Source = edbInfo.Source
  68. calculateMappingItem.SourceName = edbInfo.SourceName
  69. calculateMappingItem.FromSubSource = edbInfo.SubSource
  70. _, err = to.Insert(calculateMappingItem)
  71. if err != nil {
  72. return
  73. }
  74. }
  75. } else {
  76. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  77. if err != nil {
  78. return
  79. }
  80. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_LJZZY, utils.DATA_SUB_SOURCE_EDB)
  81. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  82. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  83. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  84. if err != nil {
  85. return
  86. }
  87. }
  88. //计算数据
  89. err = refreshAllCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "")
  90. return
  91. }
  92. // EditCalculateLjzzy 编辑累计值转月数据
  93. func EditCalculateLjzzy(edbInfo *EdbInfo, req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo) (err error) {
  94. o := orm.NewOrm()
  95. to, err := o.Begin()
  96. if err != nil {
  97. return
  98. }
  99. defer func() {
  100. if err != nil {
  101. fmt.Println("EditCalculateLjzzy,Err:" + err.Error())
  102. _ = to.Rollback()
  103. } else {
  104. _ = to.Commit()
  105. }
  106. }()
  107. //修改指标信息
  108. edbInfo.EdbName = req.EdbName
  109. edbInfo.EdbNameEn = req.EdbNameEn
  110. edbInfo.UnitEn = req.UnitEn
  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_ljzzy 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_LJZZY,
  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 = refreshAllCalculateLjzzy(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode, "", "")
  173. return
  174. }
  175. // RefreshAllCalculateLjzzy 刷新全部累计值转月数据
  176. func RefreshAllCalculateLjzzy(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("RefreshAllCalculateLjzzy,Err:" + err.Error())
  185. _ = to.Rollback()
  186. } else {
  187. _ = to.Commit()
  188. }
  189. }()
  190. // 计算数据
  191. err = refreshAllCalculateLjzzy(to, edbInfoId, source, subSource, fromEdbInfo, edbCode, startDate, endDate)
  192. return
  193. }
  194. func refreshAllCalculateLjzzy(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  195. edbInfoIdStr := strconv.Itoa(edbInfoId)
  196. //计算数据
  197. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource,
  198. FindEdbDataListAllCond{
  199. EdbInfoId: fromEdbInfo.EdbInfoId,
  200. StartDataTime: startDate,
  201. StartDataTimeCond: ">=",
  202. }, 1)
  203. if err != nil {
  204. return err
  205. }
  206. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  207. dataLen := len(dataList)
  208. for i := 0; i < dataLen; i++ {
  209. item := dataList[i]
  210. //日其中获取年
  211. itemDate, err := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  212. if err != nil {
  213. return err
  214. }
  215. year := itemDate.Year()
  216. month := int(itemDate.Month())
  217. if monthMap, yok := yearMap[year]; yok {
  218. monthMap[month] = item
  219. yearMap[year] = monthMap
  220. } else {
  221. monthMap = make(map[int]*EdbInfoSearchData)
  222. monthMap[month] = item
  223. yearMap[year] = monthMap
  224. }
  225. }
  226. addSql := ` INSERT INTO edb_data_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  227. var isAdd bool
  228. //获取指标所有数据
  229. existDataList := make([]*EdbData, 0)
  230. dataTableName := GetEdbDataTableName(source, subSource)
  231. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  232. sql = fmt.Sprintf(sql, dataTableName)
  233. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  234. if err != nil {
  235. return err
  236. }
  237. dataMap := make(map[string]string)
  238. removeDateMap := make(map[string]bool) //需要移除的日期
  239. for _, v := range existDataList {
  240. dataMap[v.DataTime] = v.Value
  241. removeDateMap[v.DataTime] = true
  242. }
  243. existDataMap := make(map[string]string)
  244. for yk, yv := range yearMap {
  245. _, oneMonthOk := yv[1]
  246. _, twoMonthOk := yv[2]
  247. if !oneMonthOk && !twoMonthOk {
  248. continue
  249. }
  250. for i := 1; i <= 12; i++ {
  251. fmt.Println(yk, i, yv[i])
  252. dataCurrentItem := yv[i]
  253. var date string
  254. var val float64
  255. if dataCurrentItem != nil {
  256. if i == 1 || i == 2 {
  257. if _, mok := yv[1]; mok { //1月有值
  258. if i == 1 {
  259. date = dataCurrentItem.DataTime
  260. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  261. }
  262. if i == 2 {
  263. dataOneItem := yv[1]
  264. date = dataCurrentItem.DataTime
  265. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  266. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  267. val, _ = twoMonth.Sub(oneMonth).Float64()
  268. }
  269. } else { //1月无值
  270. dataTwoItem := yv[2]
  271. if i == 1 {
  272. date = strconv.Itoa(yk) + "-01-31"
  273. a := decimal.NewFromFloat(dataTwoItem.Value)
  274. b := decimal.NewFromFloat(2.0)
  275. val, _ = a.Div(b).Float64()
  276. }
  277. if i == 2 {
  278. //1月无值:1月=2月/2
  279. {
  280. date = strconv.Itoa(yk) + "-01-31"
  281. a := decimal.NewFromFloat(dataTwoItem.Value)
  282. b := decimal.NewFromFloat(2.0)
  283. val, _ = a.Div(b).Float64()
  284. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  285. if !isAdd {
  286. isAdd = newAdd
  287. }
  288. addSql = tmpSql
  289. if tmpErr != nil {
  290. return tmpErr
  291. }
  292. }
  293. //end 1月无值
  294. date = dataCurrentItem.DataTime
  295. a := decimal.NewFromFloat(dataTwoItem.Value)
  296. b := decimal.NewFromFloat(2.0)
  297. val, _ = a.Div(b).Float64()
  298. }
  299. }
  300. } else {
  301. dataPreItem := yv[i-1]
  302. if dataCurrentItem != nil && dataPreItem != nil {
  303. date = dataCurrentItem.DataTime
  304. //val = dataCurrentItem.Value - dataPreItem.Value
  305. a := decimal.NewFromFloat(dataCurrentItem.Value)
  306. b := decimal.NewFromFloat(dataPreItem.Value)
  307. val, _ = a.Sub(b).Float64()
  308. }
  309. }
  310. }
  311. if date != "" {
  312. //saveValue := utils.SubFloatToString(val, 4)
  313. ////判断数据是否存在
  314. //if existVal, ok := dataMap[date]; !ok {
  315. // dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  316. // timestamp := dataTime.UnixNano() / 1e6
  317. // timeStr := fmt.Sprintf("%d", timestamp)
  318. // if _, existOk := existDataMap[date]; !existOk {
  319. // addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  320. // isAdd = true
  321. // }
  322. // existDataMap[date] = date
  323. //} else {
  324. // if existVal != saveValue {
  325. // sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  326. // sql = fmt.Sprintf(sql, dataTableName)
  327. // _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  328. // if err != nil {
  329. // return err
  330. // }
  331. // }
  332. //}
  333. delete(removeDateMap, date)
  334. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  335. if !isAdd {
  336. isAdd = newAdd
  337. }
  338. addSql = tmpSql
  339. if tmpErr != nil {
  340. return tmpErr
  341. }
  342. }
  343. }
  344. }
  345. if len(removeDateMap) > 0 {
  346. removeDateList := make([]string, 0) //需要移除的日期
  347. for k := range removeDateMap {
  348. removeDateList = append(removeDateList, k)
  349. }
  350. removeDateStr := strings.Join(removeDateList, `","`)
  351. removeDateStr = `"` + removeDateStr + `"`
  352. //如果拼接指标变更了,那么需要删除所有的指标数据
  353. tableName := GetEdbDataTableName(source, subSource)
  354. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  355. _, err = to.Raw(sql, edbInfoId).Exec()
  356. if err != nil {
  357. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  358. return
  359. }
  360. }
  361. if isAdd {
  362. addSql = strings.TrimRight(addSql, ",")
  363. _, err = to.Raw(addSql).Exec()
  364. if err != nil {
  365. fmt.Println("RefreshAllCalculateLjzzy add Err", err.Error())
  366. return
  367. }
  368. }
  369. return
  370. }
  371. func calculateLjzzy(edbInfoId int, date, edbInfoIdStr, edbCode, dataTableName, addSql string, val float64, dataMap, existDataMap map[string]string, to orm.TxOrmer) (newSql string, isAdd bool, err error) {
  372. newSql = addSql
  373. saveValue := utils.SubFloatToString(val, 4)
  374. //判断数据是否存在
  375. if existVal, ok := dataMap[date]; !ok {
  376. dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  377. timestamp := dataTime.UnixNano() / 1e6
  378. timeStr := fmt.Sprintf("%d", timestamp)
  379. if _, existOk := existDataMap[date]; !existOk {
  380. newSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  381. isAdd = true
  382. }
  383. existDataMap[date] = date
  384. } else {
  385. if existVal != saveValue {
  386. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  387. sql = fmt.Sprintf(sql, dataTableName)
  388. _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  389. }
  390. }
  391. return
  392. }