edb_data_calculate_ljzzj.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. for _, v := range existDataList {
  264. dataMap[v.DataTime] = v.Value
  265. }
  266. existDataMap := make(map[string]string)
  267. for yk, yv := range yearMap {
  268. _, oneQuarterOk := yv[1]
  269. _, twoQuarterOk := yv[2]
  270. if !oneQuarterOk && !twoQuarterOk {
  271. continue
  272. }
  273. for i := 1; i <= 4; i++ {
  274. fmt.Println(yk, i, yv[i])
  275. dataCurrentItem := yv[i]
  276. var date string
  277. var val float64
  278. if dataCurrentItem != nil {
  279. if i == 1 || i == 2 {
  280. if _, mok := yv[1]; mok { //第1个季度有值
  281. if i == 1 {
  282. date = dataCurrentItem.DataTime
  283. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  284. }
  285. if i == 2 {
  286. dataOneItem := yv[1]
  287. date = dataCurrentItem.DataTime
  288. twoQuarter := decimal.NewFromFloat(dataCurrentItem.Value)
  289. oneQuarter := decimal.NewFromFloat(dataOneItem.Value)
  290. val, _ = twoQuarter.Sub(oneQuarter).Float64()
  291. }
  292. } else { //第1个季度无值
  293. dataTwoItem := yv[2]
  294. if i == 1 {
  295. date = strconv.Itoa(yk) + "-03-31"
  296. a := decimal.NewFromFloat(dataTwoItem.Value)
  297. b := decimal.NewFromFloat(2.0)
  298. val, _ = a.Div(b).Float64()
  299. }
  300. if i == 2 {
  301. //第1个季度无值:第1个季度=第2个季度/2
  302. {
  303. date = strconv.Itoa(yk) + "-03-31"
  304. a := decimal.NewFromFloat(dataTwoItem.Value)
  305. b := decimal.NewFromFloat(2.0)
  306. val, _ = a.Div(b).Float64()
  307. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  308. if !isAdd {
  309. isAdd = newAdd
  310. }
  311. addSql = tmpSql
  312. if tmpErr != nil {
  313. return tmpErr
  314. }
  315. }
  316. //end 第1个季度无值
  317. date = dataCurrentItem.DataTime
  318. a := decimal.NewFromFloat(dataTwoItem.Value)
  319. b := decimal.NewFromFloat(2.0)
  320. val, _ = a.Div(b).Float64()
  321. }
  322. }
  323. } else {
  324. dataPreItem := yv[i-1]
  325. if dataCurrentItem != nil && dataPreItem != nil {
  326. date = dataCurrentItem.DataTime
  327. //val = dataCurrentItem.Value - dataPreItem.Value
  328. a := decimal.NewFromFloat(dataCurrentItem.Value)
  329. b := decimal.NewFromFloat(dataPreItem.Value)
  330. val, _ = a.Sub(b).Float64()
  331. }
  332. }
  333. }
  334. if date != "" {
  335. tmpSql, newAdd, tmpErr := obj.calculate(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  336. if !isAdd {
  337. isAdd = newAdd
  338. }
  339. addSql = tmpSql
  340. if tmpErr != nil {
  341. return tmpErr
  342. }
  343. }
  344. }
  345. }
  346. if isAdd {
  347. addSql = strings.TrimRight(addSql, ",")
  348. _, err = to.Raw(addSql).Exec()
  349. if err != nil {
  350. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  351. return
  352. }
  353. }
  354. return
  355. }
  356. 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) {
  357. newSql = addSql
  358. saveValue := utils.SubFloatToString(val, 4)
  359. //判断数据是否存在
  360. if existVal, ok := dataMap[date]; !ok {
  361. dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  362. timestamp := dataTime.UnixNano() / 1e6
  363. timeStr := fmt.Sprintf("%d", timestamp)
  364. if _, existOk := existDataMap[date]; !existOk {
  365. newSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  366. isAdd = true
  367. }
  368. existDataMap[date] = date
  369. } else {
  370. if existVal != saveValue {
  371. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  372. sql = fmt.Sprintf(sql, dataTableName)
  373. _, err = to.Raw(sql, saveValue, edbInfoId, date).Exec()
  374. }
  375. }
  376. return
  377. }