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