edb_data_calculate_zdyfx.go 9.1 KB

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