edb_data_calculate_ljzzy.go 12 KB

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