edb_data_calculate_zdyfx.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_index_lib/global"
  6. "eta_gn/eta_index_lib/models/excel"
  7. "eta_gn/eta_index_lib/utils"
  8. "fmt"
  9. "github.com/shopspring/decimal"
  10. "gorm.io/gorm"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. // CustomAnalysis 自定义分析
  17. type CustomAnalysis struct{}
  18. // CustomAnalysisData 自定义分析的数据
  19. type CustomAnalysisData struct {
  20. ExcelInfoId int `description:"excel的id"`
  21. DateList []string
  22. DataList []float64
  23. }
  24. // Add 添加
  25. func (obj CustomAnalysis) Add(params AddCalculateBatchParams) (edbInfo *EdbInfo, err error, errMsg string) {
  26. req := params.Req
  27. edbCode := params.EdbCode
  28. // 自定义分析的数据集
  29. jsonByte, err := json.Marshal(req.Data)
  30. if err != nil {
  31. return
  32. }
  33. var customAnalysisData CustomAnalysisData
  34. err = json.Unmarshal(jsonByte, &customAnalysisData)
  35. if err != nil {
  36. return
  37. }
  38. to := global.DEFAULT_DmSQL.Begin()
  39. defer func() {
  40. if err != nil {
  41. to.Rollback()
  42. } else {
  43. to.Commit()
  44. }
  45. }()
  46. edbInfo = new(EdbInfo)
  47. edbInfo.Source = obj.GetSource()
  48. edbInfo.SourceName = obj.GetSourceName()
  49. edbInfo.EdbCode = edbCode
  50. edbInfo.EdbName = req.EdbName
  51. edbInfo.EdbNameSource = req.EdbName
  52. edbInfo.Frequency = req.Frequency
  53. edbInfo.Unit = req.Unit
  54. edbInfo.ClassifyId = req.ClassifyId
  55. edbInfo.SysUserId = params.SysUserId
  56. edbInfo.SysUserRealName = params.SysUserRealName
  57. edbInfo.CreateTime = time.Now()
  58. edbInfo.ModifyTime = time.Now()
  59. edbInfo.UniqueCode = params.UniqueCode
  60. edbInfo.CalculateFormula = req.Formula
  61. edbInfo.EdbNameEn = req.EdbName
  62. edbInfo.UnitEn = req.Unit
  63. edbInfo.EdbType = obj.GetEdbType()
  64. edbInfo.Sort = GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE)
  65. tmpErr := to.Create(edbInfo).Error
  66. if tmpErr != nil {
  67. err = tmpErr
  68. return
  69. }
  70. //关联关系
  71. {
  72. excelEdbMappingItem := new(excel.ExcelEdbMapping)
  73. excelEdbMappingItem.CreateTime = time.Now()
  74. excelEdbMappingItem.ModifyTime = time.Now()
  75. excelEdbMappingItem.ExcelInfoId = customAnalysisData.ExcelInfoId
  76. excelEdbMappingItem.Source = 4
  77. excelEdbMappingItem.EdbInfoId = edbInfo.EdbInfoId
  78. err = to.Create(excelEdbMappingItem).Error
  79. if err != nil {
  80. return
  81. }
  82. }
  83. //计算数据
  84. err = obj.refresh(to, edbInfo, customAnalysisData.DateList, customAnalysisData.DataList)
  85. return
  86. }
  87. // Edit 编辑
  88. func (obj CustomAnalysis) Edit(params EditCalculateBatchParams) (err error, errMsg string) {
  89. req := params.Req
  90. edbInfo := params.EdbInfo
  91. // 自定义分析的数据集
  92. jsonByte, err := json.Marshal(req.Data)
  93. if err != nil {
  94. return
  95. }
  96. var customAnalysisData CustomAnalysisData
  97. err = json.Unmarshal(jsonByte, &customAnalysisData)
  98. if err != nil {
  99. return
  100. }
  101. to := global.DEFAULT_DmSQL.Begin()
  102. defer func() {
  103. if err != nil {
  104. to.Rollback()
  105. } else {
  106. to.Commit()
  107. }
  108. }()
  109. //修改指标信息
  110. edbInfo.EdbName = req.EdbName
  111. edbInfo.EdbNameSource = req.EdbName
  112. edbInfo.Frequency = req.Frequency
  113. edbInfo.Unit = req.Unit
  114. edbInfo.ClassifyId = req.ClassifyId
  115. edbInfo.CalculateFormula = req.Formula
  116. edbInfo.EdbNameEn = req.EdbNameEn
  117. edbInfo.UnitEn = req.UnitEn
  118. edbInfo.ModifyTime = time.Now()
  119. err = to.Model(edbInfo).Select([]string{"EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime", "EdbNameEn", "UnitEn"}).Updates(edbInfo).Error
  120. if err != nil {
  121. return
  122. }
  123. // 只有excel的id有传递,同时有数据的情况下,才去做处理
  124. if customAnalysisData.ExcelInfoId > 0 && len(customAnalysisData.DateList) > 0 && len(customAnalysisData.DataList) > 0 {
  125. //判断计算指标是否被更换
  126. excelEdbMapping, tmpErr := excel.GetExcelEdbMappingByEdbInfoId(edbInfo.EdbInfoId)
  127. if tmpErr != nil {
  128. err = errors.New("获取excel与指标的关系失败,Err:" + tmpErr.Error())
  129. return
  130. }
  131. if excelEdbMapping.ExcelInfoId != customAnalysisData.ExcelInfoId {
  132. errMsg = `excel与指标关系异常`
  133. err = errors.New(errMsg)
  134. return
  135. }
  136. //计算数据
  137. err = obj.refresh(to, edbInfo, customAnalysisData.DateList, customAnalysisData.DataList)
  138. }
  139. return
  140. }
  141. // Refresh 刷新
  142. func (obj CustomAnalysis) Refresh(params RefreshParams) (err error, errMsg string) {
  143. return
  144. }
  145. // GetSource 获取来源编码id
  146. func (obj CustomAnalysis) GetSource() int {
  147. return utils.DATA_SOURCE_CALCULATE_ZDYFX
  148. }
  149. // GetSourceName 获取来源名称
  150. func (obj CustomAnalysis) GetSourceName() string {
  151. return utils.DATA_SOURCE_NAME_CALCULATE_ZDYFX
  152. }
  153. // GetEdbType 获取指标类型
  154. func (obj CustomAnalysis) GetEdbType() int {
  155. return utils.CALCULATE_EDB_TYPE
  156. }
  157. // UpdateEdbDataStr 数据更新结构体
  158. type UpdateEdbDataStr struct {
  159. Value string `description:"数据对应的最新值"`
  160. DataTime string `description:"数据对应的日期"`
  161. }
  162. func (obj CustomAnalysis) refresh(to *gorm.DB, edbInfo *EdbInfo, dateList []string, dataList []float64) (err error) {
  163. edbInfoId := edbInfo.EdbInfoId
  164. dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  165. edbInfoIdStr := strconv.Itoa(edbInfoId)
  166. if len(dateList) != len(dataList) {
  167. err = errors.New("数据集与日期集不匹配")
  168. return
  169. }
  170. //获取指标所有数据
  171. existDataList, err := GetAllEdbDataListByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource)
  172. if err != nil {
  173. return err
  174. }
  175. existDataMap := make(map[string]string)
  176. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  177. for _, v := range existDataList {
  178. existDataMap[v.DataTime] = v.Value
  179. removeDataTimeMap[v.DataTime] = 1
  180. }
  181. needAddDateMap := make(map[time.Time]int)
  182. var isAdd, isUpdate bool
  183. addSql := ` INSERT INTO ` + dataTableName + `(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  184. updateEdbDataStrList := make([]UpdateEdbDataStr, 0)
  185. updateSql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  186. updateSql = fmt.Sprintf(updateSql, dataTableName)
  187. for i, currDateStr := range dateList {
  188. currVal := dataList[i] // 当前日期对应的值
  189. currTime, tmpErr := time.ParseInLocation(utils.FormatDate, currDateStr, time.Local)
  190. if tmpErr != nil {
  191. err = tmpErr
  192. return
  193. }
  194. // 当前的实际值
  195. saveValue := decimal.NewFromFloat(currVal).Round(4).String()
  196. existVal, ok := existDataMap[currDateStr]
  197. // 如果库中已经存在该数据的话,那么就进行值的变更操作
  198. if ok {
  199. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  200. delete(removeDataTimeMap, currDateStr)
  201. existValDec, _ := decimal.NewFromString(existVal)
  202. existVal = existValDec.Round(4).String()
  203. if existVal != saveValue {
  204. isUpdate = true
  205. updateEdbDataStrList = append(updateEdbDataStrList, UpdateEdbDataStr{
  206. Value: saveValue,
  207. DataTime: currDateStr,
  208. })
  209. }
  210. continue
  211. }
  212. // 库中不存在该日期的数据
  213. timestamp := currTime.UnixNano() / 1e6
  214. timeStr := fmt.Sprintf("%d", timestamp)
  215. if _, existOk := needAddDateMap[currTime]; !existOk {
  216. addSql += GetAddSql(edbInfoIdStr, edbInfo.EdbCode, currDateStr, timeStr, saveValue)
  217. isAdd = true
  218. }
  219. needAddDateMap[currTime] = 1
  220. }
  221. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  222. {
  223. removeDateList := make([]string, 0)
  224. for dateTime := range removeDataTimeMap {
  225. removeDateList = append(removeDateList, dateTime)
  226. }
  227. removeNum := len(removeDateList)
  228. if removeNum > 0 {
  229. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  230. err = to.Exec(sql, edbInfo.EdbInfoId, removeDateList).Error
  231. if err != nil {
  232. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  233. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  234. return
  235. }
  236. }
  237. }
  238. // 添加指标数据
  239. if isAdd {
  240. addSql = strings.TrimRight(addSql, ",")
  241. err = to.Exec(addSql).Error
  242. if err != nil {
  243. fmt.Println(reflect.TypeOf(obj).Name(), " add data Err", err.Error())
  244. return
  245. }
  246. }
  247. // 更新指标数据
  248. if isUpdate {
  249. // todo 测试
  250. updateSql = ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  251. updateSql = fmt.Sprintf(updateSql, dataTableName)
  252. for _, v := range updateEdbDataStrList {
  253. if v.Value == "" || v.DataTime == "" {
  254. continue
  255. }
  256. err = to.Exec(updateSql, v.Value, edbInfoId, v.DataTime).Error
  257. if err != nil {
  258. fmt.Println(reflect.TypeOf(obj).Name(), " update data Err", err.Error())
  259. return
  260. }
  261. }
  262. }
  263. return
  264. }
  265. // ResetData 数据重置
  266. func (obj CustomAnalysis) ResetData(edbInfo *EdbInfo, dateList []string, dataList []float64) (err error, errMsg string) {
  267. to := global.DEFAULT_DmSQL.Begin()
  268. defer func() {
  269. if err != nil {
  270. to.Rollback()
  271. } else {
  272. to.Commit()
  273. }
  274. }()
  275. err = obj.refresh(to, edbInfo, dateList, dataList)
  276. return
  277. }
  278. // ResetCustomAnalysisData 数据重置的结构体
  279. type ResetCustomAnalysisData struct {
  280. EdbInfoId int
  281. DateList []string
  282. DataList []float64
  283. }