edb_data_calculate_ljzzj.go 11 KB

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