edb_data_calculate_ljzzy.go 12 KB

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