edb_data_calculate_ljzzj.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // Ljzzj 累计值转季度
  14. type Ljzzj struct {
  15. }
  16. // Add 添加
  17. func (obj Ljzzj) Add(params AddCalculateBatchParams) (edbInfo *EdbInfo, err error, errMsg string) {
  18. req := params.Req
  19. fromEdbInfo := params.FromEdbInfo
  20. edbCode := params.EdbCode
  21. if fromEdbInfo.Frequency != "季度" {
  22. errMsg = "请选择季度指标"
  23. err = errors.New(errMsg)
  24. return
  25. }
  26. o := orm.NewOrm()
  27. to, err := o.Begin()
  28. if err != nil {
  29. return
  30. }
  31. defer func() {
  32. if err != nil {
  33. _ = to.Rollback()
  34. fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
  35. } else {
  36. _ = to.Commit()
  37. }
  38. }()
  39. edbInfo = new(EdbInfo)
  40. edbInfo.Source = obj.GetSource()
  41. edbInfo.SourceName = obj.GetSourceName()
  42. edbInfo.EdbCode = edbCode
  43. edbInfo.EdbName = req.EdbName
  44. edbInfo.EdbNameSource = req.EdbName
  45. edbInfo.Frequency = req.Frequency
  46. edbInfo.Unit = req.Unit
  47. edbInfo.ClassifyId = req.ClassifyId
  48. edbInfo.SysUserId = params.SysUserId
  49. edbInfo.SysUserRealName = params.SysUserRealName
  50. edbInfo.CreateTime = time.Now()
  51. edbInfo.ModifyTime = time.Now()
  52. edbInfo.UniqueCode = params.UniqueCode
  53. edbInfo.CalculateFormula = req.Formula
  54. edbInfo.EdbNameEn = req.EdbName
  55. edbInfo.UnitEn = req.Unit
  56. edbInfo.EdbType = obj.GetEdbType()
  57. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  58. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  59. if tmpErr != nil {
  60. err = tmpErr
  61. return
  62. }
  63. edbInfo.EdbInfoId = int(newEdbInfoId)
  64. //关联关系
  65. {
  66. calculateMappingItem := new(EdbInfoCalculateMapping)
  67. calculateMappingItem.CreateTime = time.Now()
  68. calculateMappingItem.ModifyTime = time.Now()
  69. calculateMappingItem.Sort = 1
  70. calculateMappingItem.EdbCode = edbCode
  71. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  72. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  73. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  74. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  75. calculateMappingItem.FromSource = fromEdbInfo.Source
  76. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  77. calculateMappingItem.FromTag = ""
  78. calculateMappingItem.Source = edbInfo.Source
  79. calculateMappingItem.SourceName = edbInfo.SourceName
  80. calculateMappingItem.FromSubSource = fromEdbInfo.SubSource
  81. _, err = to.Insert(calculateMappingItem)
  82. if err != nil {
  83. return
  84. }
  85. }
  86. //计算数据
  87. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode)
  88. return
  89. }
  90. // Edit 编辑
  91. func (obj Ljzzj) Edit(params EditCalculateBatchParams) (err error, errMsg string) {
  92. req := params.Req
  93. edbInfo := params.EdbInfo
  94. fromEdbInfo := params.FromEdbInfo
  95. if fromEdbInfo.Frequency != "季度" {
  96. errMsg = "请选择季度指标"
  97. err = errors.New(errMsg)
  98. return
  99. }
  100. o := orm.NewOrm()
  101. to, err := o.Begin()
  102. if err != nil {
  103. return
  104. }
  105. defer func() {
  106. if err != nil {
  107. _ = to.Rollback()
  108. fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
  109. } else {
  110. _ = to.Commit()
  111. }
  112. }()
  113. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  114. //修改指标信息
  115. edbInfo.EdbName = req.EdbName
  116. edbInfo.EdbNameSource = req.EdbName
  117. edbInfo.Frequency = req.Frequency
  118. edbInfo.Unit = req.Unit
  119. edbInfo.ClassifyId = req.ClassifyId
  120. edbInfo.EdbNameEn = req.EdbNameEn
  121. edbInfo.UnitEn = req.UnitEn
  122. edbInfo.ModifyTime = time.Now()
  123. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  124. if err != nil {
  125. return
  126. }
  127. var existCondition string
  128. var existPars []interface{}
  129. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  130. existPars = append(existPars, edbInfo.EdbInfoId, req.FromEdbInfoId)
  131. //判断计算指标是否被更换
  132. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  133. if err != nil {
  134. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  135. return
  136. }
  137. if count > 0 { // 指标未被替换,无需重新计算
  138. return
  139. }
  140. //删除,计算指标关联的,基础指标的关联关系
  141. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  142. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  143. if err != nil {
  144. return
  145. }
  146. //清空原有数据
  147. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  148. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  149. if err != nil {
  150. return
  151. }
  152. //关联关系
  153. {
  154. calculateMappingItem := &EdbInfoCalculateMapping{
  155. EdbInfoCalculateMappingId: 0,
  156. EdbInfoId: edbInfo.EdbInfoId,
  157. Source: obj.GetSource(),
  158. SourceName: obj.GetSourceName(),
  159. EdbCode: edbInfo.EdbCode,
  160. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  161. FromEdbCode: fromEdbInfo.EdbCode,
  162. FromEdbName: fromEdbInfo.EdbName,
  163. FromSource: fromEdbInfo.Source,
  164. FromSourceName: fromEdbInfo.SourceName,
  165. FromTag: "",
  166. Sort: 1,
  167. CreateTime: time.Now(),
  168. ModifyTime: time.Now(),
  169. FromSubSource: fromEdbInfo.SubSource,
  170. }
  171. _, err = to.Insert(calculateMappingItem)
  172. if err != nil {
  173. return
  174. }
  175. }
  176. //计算数据
  177. err = obj.refresh(to, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo, edbInfo.EdbCode)
  178. return
  179. }
  180. // Refresh 刷新
  181. func (obj Ljzzj) Refresh(params RefreshParams) (err error, errMsg string) {
  182. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  183. if err != nil {
  184. errMsg = "GetEdbInfoCalculateLjzzyDetail Err:" + err.Error()
  185. return
  186. }
  187. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  188. if err != nil {
  189. errMsg = "GetEdbInfoById Err:" + err.Error()
  190. return
  191. }
  192. o := orm.NewOrm()
  193. to, err := o.Begin()
  194. if err != nil {
  195. return
  196. }
  197. defer func() {
  198. if err != nil {
  199. _ = to.Rollback()
  200. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  201. } else {
  202. _ = to.Commit()
  203. }
  204. }()
  205. // 计算数据
  206. err = obj.refresh(to, params.EdbInfo.EdbInfoId, params.EdbInfo.Source, params.EdbInfo.SubSource, fromEdbInfo, params.EdbInfo.EdbCode)
  207. return
  208. }
  209. // GetSource 获取来源编码id
  210. func (obj Ljzzj) GetSource() int {
  211. return utils.DATA_SOURCE_CALCULATE_LJZZJ
  212. }
  213. // GetSourceName 获取来源名称
  214. func (obj Ljzzj) GetSourceName() string {
  215. return utils.DATA_SOURCE_NAME_CALCULATE_LJZZJ
  216. }
  217. // GetEdbType 获取指标类型
  218. func (obj Ljzzj) GetEdbType() int {
  219. return utils.CALCULATE_EDB_TYPE
  220. }
  221. func (obj Ljzzj) refresh(to orm.TxOrmer, edbInfoId, source, subSource int, fromEdbInfo *EdbInfo, edbCode string) (err error) {
  222. dataTableName := GetEdbDataTableName(source, subSource)
  223. edbInfoIdStr := strconv.Itoa(edbInfoId)
  224. // 获取来源指标的数据
  225. dataList, err := GetEdbDataListAllByTo(to, fromEdbInfo.Source, fromEdbInfo.SubSource,
  226. FindEdbDataListAllCond{
  227. EdbInfoId: fromEdbInfo.EdbInfoId,
  228. }, 1)
  229. if err != nil {
  230. return err
  231. }
  232. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  233. dataLen := len(dataList)
  234. for i := 0; i < dataLen; i++ {
  235. item := dataList[i]
  236. //日其中获取年
  237. itemDate, err := time.ParseInLocation(utils.FormatDate, item.DataTime, time.Local)
  238. if err != nil {
  239. return err
  240. }
  241. year := itemDate.Year()
  242. quarter := utils.MonthQuarterMap[int(itemDate.Month())]
  243. if quarterMap, yok := yearMap[year]; yok {
  244. quarterMap[quarter] = item
  245. yearMap[year] = quarterMap
  246. } else {
  247. quarterMap = make(map[int]*EdbInfoSearchData)
  248. quarterMap[quarter] = item
  249. yearMap[year] = quarterMap
  250. }
  251. }
  252. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  253. var isAdd bool
  254. //获取指标所有数据
  255. existDataList := make([]*EdbData, 0)
  256. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  257. sql = fmt.Sprintf(sql, dataTableName)
  258. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  259. if err != nil {
  260. return err
  261. }
  262. dataMap := make(map[string]string)
  263. removeDateMap := make(map[string]bool) //需要移除的日期
  264. for _, v := range existDataList {
  265. dataMap[v.DataTime] = v.Value
  266. removeDateMap[v.DataTime] = true
  267. }
  268. existDataMap := make(map[string]string)
  269. for yk, yv := range yearMap {
  270. _, oneQuarterOk := yv[1]
  271. _, twoQuarterOk := yv[2]
  272. if !oneQuarterOk && !twoQuarterOk {
  273. continue
  274. }
  275. for i := 1; i <= 4; i++ {
  276. fmt.Println(yk, i, yv[i])
  277. dataCurrentItem := yv[i]
  278. var date string
  279. var val float64
  280. if dataCurrentItem != nil {
  281. if i == 1 || i == 2 {
  282. if _, mok := yv[1]; mok { //第1个季度有值
  283. if i == 1 {
  284. date = dataCurrentItem.DataTime
  285. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  286. }
  287. if i == 2 {
  288. dataOneItem := yv[1]
  289. date = dataCurrentItem.DataTime
  290. twoQuarter := decimal.NewFromFloat(dataCurrentItem.Value)
  291. oneQuarter := decimal.NewFromFloat(dataOneItem.Value)
  292. val, _ = twoQuarter.Sub(oneQuarter).Float64()
  293. }
  294. } else { //第1个季度无值
  295. dataTwoItem := yv[2]
  296. if i == 1 {
  297. date = strconv.Itoa(yk) + "-03-31"
  298. a := decimal.NewFromFloat(dataTwoItem.Value)
  299. b := decimal.NewFromFloat(2.0)
  300. val, _ = a.Div(b).Float64()
  301. }
  302. if i == 2 {
  303. //第1个季度无值:第1个季度=第2个季度/2
  304. {
  305. date = strconv.Itoa(yk) + "-03-31"
  306. a := decimal.NewFromFloat(dataTwoItem.Value)
  307. b := decimal.NewFromFloat(2.0)
  308. val, _ = a.Div(b).Float64()
  309. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  310. if !isAdd {
  311. isAdd = newAdd
  312. }
  313. addSql = tmpSql
  314. if tmpErr != nil {
  315. return tmpErr
  316. }
  317. }
  318. //end 第1个季度无值
  319. date = dataCurrentItem.DataTime
  320. a := decimal.NewFromFloat(dataTwoItem.Value)
  321. b := decimal.NewFromFloat(2.0)
  322. val, _ = a.Div(b).Float64()
  323. }
  324. }
  325. } else {
  326. dataPreItem := yv[i-1]
  327. if dataCurrentItem != nil && dataPreItem != nil {
  328. date = dataCurrentItem.DataTime
  329. //val = dataCurrentItem.Value - dataPreItem.Value
  330. a := decimal.NewFromFloat(dataCurrentItem.Value)
  331. b := decimal.NewFromFloat(dataPreItem.Value)
  332. val, _ = a.Sub(b).Float64()
  333. }
  334. }
  335. }
  336. if date != "" {
  337. delete(removeDateMap, date)
  338. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  339. if !isAdd {
  340. isAdd = newAdd
  341. }
  342. addSql = tmpSql
  343. if tmpErr != nil {
  344. return tmpErr
  345. }
  346. }
  347. }
  348. }
  349. if len(removeDateMap) > 0 {
  350. removeDateList := make([]string, 0) //需要移除的日期
  351. for k := range removeDateMap {
  352. removeDateList = append(removeDateList, k)
  353. }
  354. removeDateStr := strings.Join(removeDateList, `","`)
  355. removeDateStr = `"` + removeDateStr + `"`
  356. //如果拼接指标变更了,那么需要删除所有的指标数据
  357. tableName := GetEdbDataTableName(source, subSource)
  358. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  359. _, err = to.Raw(sql, edbInfoId).Exec()
  360. if err != nil {
  361. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  362. return
  363. }
  364. }
  365. if isAdd {
  366. addSql = strings.TrimRight(addSql, ",")
  367. _, err = to.Raw(addSql).Exec()
  368. if err != nil {
  369. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  370. return
  371. }
  372. }
  373. return
  374. }
  375. func (obj Ljzzj) calculate(edbInfoId int, date, edbInfoIdStr, edbCode, dataTableName, addSql string, val float64, dataMap, existDataMap map[string]string, to orm.TxOrmer) (newSql string, isAdd bool, err error) {
  376. newSql = addSql
  377. saveValue := utils.SubFloatToString(val, 4)
  378. //判断数据是否存在
  379. if existVal, ok := dataMap[date]; !ok {
  380. dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  381. timestamp := dataTime.UnixNano() / 1e6
  382. timeStr := fmt.Sprintf("%d", timestamp)
  383. if _, existOk := existDataMap[date]; !existOk {
  384. newSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  385. isAdd = true
  386. }
  387. existDataMap[date] = date
  388. } else {
  389. if existVal != saveValue {
  390. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  391. sql = fmt.Sprintf(sql, dataTableName)
  392. _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  393. }
  394. }
  395. return
  396. }