edb_data_calculate_ljzzj.go 11 KB

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