edb_data_calculate_ljzzy.go 11 KB

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