edb_data_calculate_zdyfx.go 9.4 KB

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