edb_data_calculate_ljzzy.go 10 KB

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