edb_data_calculate_ljzzy.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. "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(req *EdbInfoCalculateBatchEditReq, fromEdbInfo *EdbInfo, edbCode string) (edbInfoId int, err error) {
  90. edbInfoId = req.EdbInfoId
  91. o := orm.NewOrm()
  92. to, err := o.Begin()
  93. if err != nil {
  94. return
  95. }
  96. defer func() {
  97. if err != nil {
  98. fmt.Println("EditCalculateLjzzy,Err:" + err.Error())
  99. _ = to.Rollback()
  100. } else {
  101. _ = to.Commit()
  102. }
  103. }()
  104. //修改指标信息
  105. sql := ` UPDATE edb_info
  106. SET
  107. edb_name =?,
  108. edb_name_source=?,
  109. frequency = ?,
  110. unit = ?,
  111. classify_id = ?,
  112. modify_time = NOW()
  113. WHERE edb_info_id = ? `
  114. _, err = o.Raw(sql, req.EdbName, req.EdbName, req.Frequency, req.Unit, req.ClassifyId, edbInfoId).Exec()
  115. if err != nil {
  116. return
  117. }
  118. var existCondition string
  119. var existPars []interface{}
  120. existCondition += " AND edb_info_id=? "
  121. existPars = append(existPars, edbInfoId)
  122. existCondition += " AND from_edb_info_id=? "
  123. existPars = append(existPars, req.FromEdbInfoId)
  124. //判断计算指标是否被更换
  125. count, err := GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  126. if err != nil {
  127. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  128. return
  129. }
  130. if count <= 0 {
  131. //删除指标关联计算指标
  132. //sql := ` DELETE FROM edb_info_calculate_ljzzy WHERE edb_info_id = ? `
  133. //_, err = o.Raw(sql, edbInfoId).Exec()
  134. //if err != nil {
  135. // return
  136. //}
  137. //calculateItem := new(EdbInfoCalculateLjzzy)
  138. //calculateItem.CreateTime = time.Now()
  139. //calculateItem.ModifyTime = time.Now()
  140. //calculateItem.Sort = 1
  141. //calculateItem.EdbCode = edbCode
  142. //calculateItem.EdbInfoId = edbInfoId
  143. //calculateItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  144. //calculateItem.FromEdbCode = fromEdbInfo.EdbCode
  145. //calculateItem.FromEdbName = fromEdbInfo.EdbName
  146. //calculateItem.FromSource = fromEdbInfo.Source
  147. //calculateItem.FromSourceName = fromEdbInfo.SourceName
  148. //_, err = o.Insert(calculateItem)
  149. //if err != nil {
  150. // return
  151. //}
  152. //删除,计算指标关联的,基础指标的关联关系
  153. sql = ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  154. _, err = o.Raw(sql, edbInfoId).Exec()
  155. if err != nil {
  156. return
  157. }
  158. //清空原有数据
  159. sql = ` DELETE FROM edb_data_calculate_ljzzy WHERE edb_info_id = ? `
  160. _, err = o.Raw(sql, edbInfoId).Exec()
  161. if err != nil {
  162. return edbInfoId, err
  163. }
  164. //关联关系
  165. {
  166. calculateMappingItem := new(EdbInfoCalculateMapping)
  167. calculateMappingItem.CreateTime = time.Now()
  168. calculateMappingItem.ModifyTime = time.Now()
  169. calculateMappingItem.Sort = 1
  170. calculateMappingItem.EdbCode = edbCode
  171. calculateMappingItem.EdbInfoId = edbInfoId
  172. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  173. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  174. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  175. calculateMappingItem.FromSource = fromEdbInfo.Source
  176. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  177. calculateMappingItem.FromTag = ""
  178. calculateMappingItem.Source = utils.DATA_SOURCE_CALCULATE_LJZZY
  179. calculateMappingItem.SourceName = "累计值转月"
  180. _, err = o.Insert(calculateMappingItem)
  181. if err != nil {
  182. return
  183. }
  184. }
  185. //计算数据
  186. var condition string
  187. var pars []interface{}
  188. condition += " AND edb_info_id=? "
  189. pars = append(pars, req.FromEdbInfoId)
  190. fmt.Println("EdbInfoId:", req.FromEdbInfoId)
  191. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
  192. if err != nil {
  193. return edbInfoId, err
  194. }
  195. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  196. dataLen := len(dataList)
  197. for i := 0; i < dataLen; i++ {
  198. item := dataList[i]
  199. //日其中获取年
  200. itemDate, err := time.Parse(utils.FormatDate, item.DataTime)
  201. if err != nil {
  202. return edbInfoId, err
  203. }
  204. year := itemDate.Year()
  205. month := int(itemDate.Month())
  206. if monthMap, yok := yearMap[year]; yok {
  207. monthMap[month] = item
  208. yearMap[year] = monthMap
  209. } else {
  210. monthMap = make(map[int]*EdbInfoSearchData)
  211. monthMap[month] = item
  212. yearMap[year] = monthMap
  213. }
  214. }
  215. addSql := ` INSERT INTO edb_data_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  216. nowStr := time.Now().Format(utils.FormatDateTime)
  217. var isAdd bool
  218. for yk, yv := range yearMap {
  219. _, oneMonthOk := yv[1]
  220. _, twoMonthOk := yv[2]
  221. if !oneMonthOk && !twoMonthOk {
  222. continue
  223. }
  224. for i := 1; i <= 12; i++ {
  225. fmt.Println(yk, i, yv[i])
  226. dataCurrentItem := yv[i]
  227. var date string
  228. var val float64
  229. if i == 1 || i == 2 {
  230. if _, mok := yv[1]; mok { //1月有值
  231. if i == 1 {
  232. date = dataCurrentItem.DataTime
  233. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  234. }
  235. if i == 2 {
  236. dataOneItem := yv[1]
  237. date = dataCurrentItem.DataTime
  238. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  239. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  240. val, _ = twoMonth.Sub(oneMonth).Float64()
  241. }
  242. } else { //1月无值
  243. dataTwoItem := yv[2]
  244. if i == 1 {
  245. date = strconv.Itoa(yk) + "-01-31"
  246. a := decimal.NewFromFloat(dataTwoItem.Value)
  247. b := decimal.NewFromFloat(2.0)
  248. val, _ = a.Div(b).Float64()
  249. }
  250. if i == 2 {
  251. date = dataCurrentItem.DataTime
  252. a := decimal.NewFromFloat(dataTwoItem.Value)
  253. b := decimal.NewFromFloat(2.0)
  254. val, _ = a.Div(b).Float64()
  255. }
  256. }
  257. } else {
  258. dataPreItem := yv[i-1]
  259. if dataCurrentItem != nil && dataPreItem != nil {
  260. date = dataCurrentItem.DataTime
  261. //val = dataCurrentItem.Value - dataPreItem.Value
  262. a := decimal.NewFromFloat(dataCurrentItem.Value)
  263. b := decimal.NewFromFloat(dataPreItem.Value)
  264. val, _ = a.Sub(b).Float64()
  265. }
  266. }
  267. if date != "" {
  268. dataTime, _ := time.Parse(utils.FormatDate, date)
  269. timestamp := dataTime.UnixNano() / 1e6
  270. timeStr := fmt.Sprintf("%d", timestamp)
  271. addSql += "("
  272. addSql += strconv.Itoa(edbInfoId) + "," + "'" + edbCode + "'" + "," + "'" + date + "'" + "," + utils.SubFloatToString(val, 4) + "," + "'" + nowStr + "'" +
  273. "," + "'" + nowStr + "'" + "," + "1"
  274. addSql += "," + "'" + timeStr + "'"
  275. addSql += "),"
  276. isAdd = true
  277. }
  278. }
  279. }
  280. if isAdd {
  281. addSql = strings.TrimRight(addSql, ",")
  282. _, err = o.Raw(addSql).Exec()
  283. if err != nil {
  284. return edbInfoId, err
  285. }
  286. }
  287. }
  288. return
  289. }
  290. // RefreshAllCalculateLjzzy 刷新全部累计值转月数据
  291. func RefreshAllCalculateLjzzy(edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  292. o := orm.NewOrm()
  293. to, err := o.Begin()
  294. if err != nil {
  295. return
  296. }
  297. defer func() {
  298. if err != nil {
  299. fmt.Println("RefreshAllCalculateLjzzy,Err:" + err.Error())
  300. _ = to.Rollback()
  301. } else {
  302. _ = to.Commit()
  303. }
  304. }()
  305. // 计算数据
  306. err = refreshAllCalculateLjzzy(to, edbInfoId, source, fromEdbInfo, edbCode, startDate, endDate)
  307. return
  308. }
  309. func refreshAllCalculateLjzzy(to orm.TxOrmer, edbInfoId, source int, fromEdbInfo *EdbInfo, edbCode, startDate, endDate string) (err error) {
  310. edbInfoIdStr := strconv.Itoa(edbInfoId)
  311. //计算数据
  312. var condition string
  313. var pars []interface{}
  314. condition += " AND edb_info_id=? "
  315. pars = append(pars, fromEdbInfo.EdbInfoId)
  316. if startDate != "" {
  317. condition += " AND data_time>=? "
  318. pars = append(pars, startDate)
  319. }
  320. //if endDate != "" {
  321. // condition += " AND data_time<=? "
  322. // pars = append(pars, endDate)
  323. //}
  324. dataList, err := GetEdbDataListAll(condition, pars, fromEdbInfo.Source, 1)
  325. if err != nil {
  326. return err
  327. }
  328. yearMap := make(map[int]map[int]*EdbInfoSearchData)
  329. dataLen := len(dataList)
  330. for i := 0; i < dataLen; i++ {
  331. item := dataList[i]
  332. //日其中获取年
  333. itemDate, err := time.Parse(utils.FormatDate, item.DataTime)
  334. if err != nil {
  335. return err
  336. }
  337. year := itemDate.Year()
  338. month := int(itemDate.Month())
  339. if monthMap, yok := yearMap[year]; yok {
  340. monthMap[month] = item
  341. yearMap[year] = monthMap
  342. } else {
  343. monthMap = make(map[int]*EdbInfoSearchData)
  344. monthMap[month] = item
  345. yearMap[year] = monthMap
  346. }
  347. }
  348. addSql := ` INSERT INTO edb_data_calculate_ljzzy(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  349. var isAdd bool
  350. //获取指标所有数据
  351. existDataList := make([]*EdbData, 0)
  352. dataTableName := GetEdbDataTableName(source)
  353. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  354. sql = fmt.Sprintf(sql, dataTableName)
  355. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  356. if err != nil {
  357. return err
  358. }
  359. dataMap := make(map[string]string)
  360. for _, v := range existDataList {
  361. dataMap[v.DataTime] = v.Value
  362. }
  363. existDataMap := make(map[string]string)
  364. for yk, yv := range yearMap {
  365. _, oneMonthOk := yv[1]
  366. _, twoMonthOk := yv[2]
  367. if !oneMonthOk && !twoMonthOk {
  368. continue
  369. }
  370. for i := 1; i <= 12; i++ {
  371. fmt.Println(yk, i, yv[i])
  372. dataCurrentItem := yv[i]
  373. var date string
  374. var val float64
  375. if dataCurrentItem != nil {
  376. if i == 1 || i == 2 {
  377. if _, mok := yv[1]; mok { //1月有值
  378. if i == 1 {
  379. date = dataCurrentItem.DataTime
  380. val, _ = decimal.NewFromFloat(dataCurrentItem.Value).Float64() //a.Div(b).Float64()
  381. }
  382. if i == 2 {
  383. dataOneItem := yv[1]
  384. date = dataCurrentItem.DataTime
  385. twoMonth := decimal.NewFromFloat(dataCurrentItem.Value)
  386. oneMonth := decimal.NewFromFloat(dataOneItem.Value)
  387. val, _ = twoMonth.Sub(oneMonth).Float64()
  388. }
  389. } else { //1月无值
  390. dataTwoItem := yv[2]
  391. if i == 1 {
  392. date = strconv.Itoa(yk) + "-01-31"
  393. a := decimal.NewFromFloat(dataTwoItem.Value)
  394. b := decimal.NewFromFloat(2.0)
  395. val, _ = a.Div(b).Float64()
  396. }
  397. if i == 2 {
  398. //1月无值:1月=2月/2
  399. {
  400. date = strconv.Itoa(yk) + "-01-31"
  401. a := decimal.NewFromFloat(dataTwoItem.Value)
  402. b := decimal.NewFromFloat(2.0)
  403. val, _ = a.Div(b).Float64()
  404. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  405. if !isAdd {
  406. isAdd = newAdd
  407. }
  408. addSql = tmpSql
  409. if tmpErr != nil {
  410. return tmpErr
  411. }
  412. }
  413. //end 1月无值
  414. date = dataCurrentItem.DataTime
  415. a := decimal.NewFromFloat(dataTwoItem.Value)
  416. b := decimal.NewFromFloat(2.0)
  417. val, _ = a.Div(b).Float64()
  418. }
  419. }
  420. } else {
  421. dataPreItem := yv[i-1]
  422. if dataCurrentItem != nil && dataPreItem != nil {
  423. date = dataCurrentItem.DataTime
  424. //val = dataCurrentItem.Value - dataPreItem.Value
  425. a := decimal.NewFromFloat(dataCurrentItem.Value)
  426. b := decimal.NewFromFloat(dataPreItem.Value)
  427. val, _ = a.Sub(b).Float64()
  428. }
  429. }
  430. }
  431. if date != "" {
  432. //saveValue := utils.SubFloatToString(val, 4)
  433. ////判断数据是否存在
  434. //if existVal, ok := dataMap[date]; !ok {
  435. // dataTime, _ := time.Parse(utils.FormatDate, date)
  436. // timestamp := dataTime.UnixNano() / 1e6
  437. // timeStr := fmt.Sprintf("%d", timestamp)
  438. // if _, existOk := existDataMap[date]; !existOk {
  439. // addSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  440. // isAdd = true
  441. // }
  442. // existDataMap[date] = date
  443. //} else {
  444. // if existVal != saveValue {
  445. // sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  446. // sql = fmt.Sprintf(sql, dataTableName)
  447. // _, err = o.Raw(sql, saveValue, edbInfoId, date).Exec()
  448. // if err != nil {
  449. // return err
  450. // }
  451. // }
  452. //}
  453. tmpSql, newAdd, tmpErr := calculateLjzzy(edbInfoId, date, edbInfoIdStr, edbCode, dataTableName, addSql, val, dataMap, existDataMap, to)
  454. if !isAdd {
  455. isAdd = newAdd
  456. }
  457. addSql = tmpSql
  458. if tmpErr != nil {
  459. return tmpErr
  460. }
  461. }
  462. }
  463. }
  464. if isAdd {
  465. addSql = strings.TrimRight(addSql, ",")
  466. _, err = to.Raw(addSql).Exec()
  467. if err != nil {
  468. fmt.Println("RefreshAllCalculateLjzzy add Err", err.Error())
  469. return
  470. }
  471. }
  472. return
  473. }
  474. func calculateLjzzy(edbInfoId int, date, edbInfoIdStr, edbCode, dataTableName, addSql string, val float64, dataMap, existDataMap map[string]string, o orm.TxOrmer) (newSql string, isAdd bool, err error) {
  475. newSql = addSql
  476. saveValue := utils.SubFloatToString(val, 4)
  477. //判断数据是否存在
  478. if existVal, ok := dataMap[date]; !ok {
  479. dataTime, _ := time.Parse(utils.FormatDate, date)
  480. timestamp := dataTime.UnixNano() / 1e6
  481. timeStr := fmt.Sprintf("%d", timestamp)
  482. if _, existOk := existDataMap[date]; !existOk {
  483. newSql += GetAddSql(edbInfoIdStr, edbCode, date, timeStr, saveValue)
  484. isAdd = true
  485. }
  486. existDataMap[date] = date
  487. } else {
  488. if existVal != saveValue {
  489. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  490. sql = fmt.Sprintf(sql, dataTableName)
  491. _, err = o.Raw(sql, saveValue, edbInfoId, date).Exec()
  492. }
  493. }
  494. return
  495. }