base_from_calculate.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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/dengsgo/math-engine/engine"
  9. "github.com/shopspring/decimal"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // EdbInfoCalculateSaveReq 计算(运算)指标请求参数
  15. type EdbInfoCalculateSaveReq struct {
  16. AdminId int `description:"添加人id"`
  17. AdminName string `description:"添加人名称"`
  18. EdbInfoId int `description:"指标id"`
  19. EdbName string `description:"指标名称"`
  20. EdbNameEn string `description:"英文指标名称"`
  21. Frequency string `description:"频率"`
  22. Unit string `description:"单位"`
  23. UnitEn string `description:"英文单位"`
  24. ClassifyId int `description:"分类id"`
  25. CalculateFormula string `description:"计算公式"`
  26. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  27. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  28. Extra string `description:"指标额外配置"`
  29. EdbInfoIdArr []EdbInfoFromTag
  30. }
  31. // EdbInfoFromTag 计算指标的关联指标
  32. type EdbInfoFromTag struct {
  33. EdbInfoId int `description:"指标id"`
  34. FromTag string `description:"指标对应标签"`
  35. }
  36. // CalculateItems 计算(运算)指标信息
  37. type CalculateItems struct {
  38. EdbInfoId int
  39. DataMap map[string]float64
  40. }
  41. // AddCalculateInfo 新增计算(运算)指标
  42. func AddCalculateInfo(req EdbInfoCalculateSaveReq, calculateMappingList []*EdbInfoCalculateMapping, edbInfoList []*EdbInfo, edbCode, uniqueCode string, edbInfoIdBytes []string) (edbInfo *EdbInfo, err error) {
  43. o := orm.NewOrm()
  44. to, err := o.Begin()
  45. if err != nil {
  46. return
  47. }
  48. defer func() {
  49. if err != nil {
  50. fmt.Println("AddCalculateHcz,Err:" + err.Error())
  51. _ = to.Rollback()
  52. } else {
  53. _ = to.Commit()
  54. }
  55. }()
  56. edbInfo = &EdbInfo{
  57. EdbInfoId: 0,
  58. SourceName: "指标运算",
  59. Source: utils.DATA_SOURCE_CALCULATE,
  60. EdbCode: edbCode,
  61. EdbName: req.EdbName,
  62. EdbNameSource: req.EdbName,
  63. Frequency: req.Frequency,
  64. Unit: req.Unit,
  65. StartDate: "",
  66. EndDate: "",
  67. ClassifyId: req.ClassifyId,
  68. SysUserId: req.AdminId,
  69. SysUserRealName: req.AdminName,
  70. UniqueCode: uniqueCode,
  71. CreateTime: time.Now(),
  72. ModifyTime: time.Now(),
  73. MinValue: 0,
  74. MaxValue: 0,
  75. CalculateFormula: req.CalculateFormula,
  76. EdbType: 2,
  77. Sort: GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.EDB_INFO_TYPE),
  78. MoveType: 0,
  79. MoveFrequency: "",
  80. NoUpdate: 0,
  81. ServerUrl: "",
  82. EdbInfoType: 0,
  83. EdbNameEn: req.EdbName,
  84. UnitEn: req.Unit,
  85. LatestDate: "",
  86. LatestValue: 0,
  87. ChartImage: "",
  88. EmptyType: req.EmptyType,
  89. MaxEmptyType: req.MaxEmptyType,
  90. Extra: req.Extra,
  91. }
  92. lastId, err := to.Insert(edbInfo)
  93. if err != nil {
  94. return
  95. }
  96. edbInfo.EdbInfoId = int(lastId)
  97. edbInfoTag := make(map[string]int)
  98. //关联关系表
  99. {
  100. //处理关联指标
  101. for _, v := range calculateMappingList {
  102. edbInfoTag[v.FromTag] = v.FromEdbInfoId
  103. v.EdbCode = edbCode
  104. v.EdbInfoId = edbInfo.EdbInfoId
  105. }
  106. if len(calculateMappingList) > 0 {
  107. _, err = to.InsertMulti(len(calculateMappingList), calculateMappingList)
  108. if err != nil {
  109. return
  110. }
  111. }
  112. }
  113. //计算数据
  114. err = refreshAllCalculate(to, edbInfoList, edbInfoTag, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode, edbInfo.CalculateFormula, "", "", edbInfoIdBytes, edbInfo.EmptyType, edbInfo.MaxEmptyType, edbInfo.Extra)
  115. return
  116. }
  117. // EditCalculateInfo 编辑计算(运算)指标
  118. func EditCalculateInfo(edbInfo *EdbInfo, req EdbInfoCalculateSaveReq, formulaSlice []string, edbInfoIdBytes []string, needCalculate bool) (err error, errMsg string) {
  119. o := orm.NewOrm()
  120. to, err := o.Begin()
  121. if err != nil {
  122. return
  123. }
  124. defer func() {
  125. if err != nil {
  126. fmt.Println("AddCalculateHcz,Err:" + err.Error())
  127. _ = to.Rollback()
  128. } else {
  129. _ = to.Commit()
  130. }
  131. }()
  132. // 修改指标信息
  133. edbInfo.EdbName = req.EdbName
  134. edbInfo.EdbNameEn = req.EdbNameEn
  135. edbInfo.EdbNameSource = req.EdbName
  136. edbInfo.Frequency = req.Frequency
  137. edbInfo.Unit = req.Unit
  138. edbInfo.UnitEn = req.UnitEn
  139. edbInfo.ClassifyId = req.ClassifyId
  140. edbInfo.CalculateFormula = req.CalculateFormula
  141. edbInfo.ModifyTime = time.Now()
  142. edbInfo.EmptyType = req.EmptyType
  143. edbInfo.MaxEmptyType = req.MaxEmptyType
  144. edbInfo.Extra = req.Extra
  145. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "EdbNameEn", "UnitEn", "ClassifyId", "CalculateFormula", "ModifyTime", "EmptyType", "MaxEmptyType", "Extra")
  146. if err != nil {
  147. return
  148. }
  149. if needCalculate {
  150. // 清除计算数据
  151. sql := `DELETE FROM edb_data_calculate WHERE edb_info_id=?`
  152. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  153. if err != nil {
  154. return
  155. }
  156. // 清除关联关系表
  157. sql = `DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=?`
  158. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  159. if err != nil {
  160. return
  161. }
  162. edbInfoList := make([]*EdbInfo, 0)
  163. calculateMappingList := make([]*EdbInfoCalculateMapping, 0)
  164. edbInfoTag := make(map[string]int)
  165. for k, v := range req.EdbInfoIdArr {
  166. edbInfoTag[v.FromTag] = v.EdbInfoId
  167. fromEdbInfo, tmpErr := GetEdbInfoById(v.EdbInfoId)
  168. if tmpErr != nil {
  169. err = tmpErr
  170. return
  171. }
  172. edbInfoList = append(edbInfoList, fromEdbInfo)
  173. //关联关系表
  174. {
  175. calculateMappingItem := &EdbInfoCalculateMapping{
  176. EdbInfoCalculateMappingId: 0,
  177. EdbInfoId: req.EdbInfoId,
  178. Source: edbInfo.Source,
  179. SourceName: edbInfo.SourceName,
  180. EdbCode: edbInfo.EdbCode,
  181. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  182. FromEdbCode: fromEdbInfo.EdbCode,
  183. FromEdbName: fromEdbInfo.EdbName,
  184. FromSource: fromEdbInfo.Source,
  185. FromSourceName: fromEdbInfo.SourceName,
  186. FromTag: v.FromTag,
  187. Sort: k + 1,
  188. CreateTime: time.Now(),
  189. ModifyTime: time.Now(),
  190. }
  191. calculateMappingList = append(calculateMappingList, calculateMappingItem)
  192. }
  193. }
  194. for _, v := range formulaSlice {
  195. formulaMap, e := utils.CheckFormula(v)
  196. if e != nil {
  197. err = fmt.Errorf("公式错误,请重新填写")
  198. return
  199. }
  200. //预先计算,判断公式是否正常
  201. ok, _ := CheckFormula2(edbInfoList, formulaMap, v, edbInfoIdBytes)
  202. if !ok {
  203. errMsg = "生成计算指标失败,请使用正确的计算公式"
  204. err = errors.New(errMsg)
  205. return
  206. }
  207. }
  208. //关联关系表
  209. {
  210. if len(calculateMappingList) > 0 {
  211. _, err = to.InsertMulti(len(calculateMappingList), calculateMappingList)
  212. if err != nil {
  213. return
  214. }
  215. }
  216. }
  217. //计算数据
  218. err = refreshAllCalculate(to, edbInfoList, edbInfoTag, edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode, edbInfo.CalculateFormula, "", "", edbInfoIdBytes, edbInfo.EmptyType, edbInfo.MaxEmptyType, edbInfo.Extra)
  219. }
  220. return
  221. }
  222. // GetCalculateEdbInfo 获取计算指标的关联指标id
  223. func GetCalculateEdbInfo(edbInfoId int) (from_edb_info_id string, err error) {
  224. o := orm.NewOrm()
  225. sql := ` SELECT GROUP_CONCAT(from_edb_info_id ORDER BY sort ASC SEPARATOR ',') AS from_edb_info_id
  226. FROM edb_info_calculate_mapping
  227. WHERE edb_info_id=?
  228. GROUP BY edb_info_id
  229. `
  230. err = o.Raw(sql, edbInfoId).QueryRow(&from_edb_info_id)
  231. return
  232. }
  233. // DeleteCalculateEdbInfo 删除指标信息
  234. func DeleteCalculateEdbInfo(edbInfoId int) (err error) {
  235. o := orm.NewOrm()
  236. to, err := o.Begin()
  237. if err != nil {
  238. return
  239. }
  240. defer func() {
  241. if err != nil {
  242. _ = to.Rollback()
  243. } else {
  244. _ = to.Commit()
  245. }
  246. }()
  247. sql := `DELETE FROM edb_data_calculate WHERE edb_info_id=?`
  248. _, err = to.Raw(sql, edbInfoId).Exec()
  249. if err != nil {
  250. return
  251. }
  252. sql = `DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=?`
  253. _, err = to.Raw(sql, edbInfoId).Exec()
  254. return
  255. }
  256. // RefreshAllCalculate 刷新全部数据
  257. func RefreshAllCalculate(edbInfoIdArr []*EdbInfo, edbInfoTag map[string]int, edbInfoId, source, subSource int, edbCode, formulaStr, startDate, endDate string, edbInfoIdBytes []string, emptyType, maxEmptyType int, extra string) (err error) {
  258. o := orm.NewOrm()
  259. to, err := o.Begin()
  260. if err != nil {
  261. return
  262. }
  263. defer func() {
  264. if err != nil {
  265. fmt.Println("RefreshAllCalculate,Err:" + err.Error())
  266. _ = to.Rollback()
  267. } else {
  268. _ = to.Commit()
  269. }
  270. }()
  271. fmt.Println(startDate, endDate)
  272. //计算数据
  273. err = refreshAllCalculate(to, edbInfoIdArr, edbInfoTag, edbInfoId, source, subSource, edbCode, formulaStr, startDate, endDate, edbInfoIdBytes, emptyType, maxEmptyType, extra)
  274. return
  275. }
  276. // refreshAllCalculate 刷新全部数据
  277. func refreshAllCalculate(to orm.TxOrmer, edbInfoIdArr []*EdbInfo, edbInfoTag map[string]int, edbInfoId, source, subSource int, edbCode, formulaStr, startDate, endDate string, edbInfoIdBytes []string, emptyType, maxEmptyType int, extra string) (err error) {
  278. realSaveDataMap := make(map[string]map[int]float64)
  279. saveDataMap := make(map[string]map[int]float64)
  280. // 最小的结束日期 , 最晚的数据开始日期
  281. var minLatestDate, maxStartDate time.Time
  282. dateList := make([]string, 0) // 最终的日期数据
  283. dateMap := make(map[string]struct{}) // 最终的日期数据
  284. dateTagConfig := ""
  285. if extra != "" {
  286. var dateConfig CalculateEdbExtra
  287. err = json.Unmarshal([]byte(extra), &dateConfig)
  288. if err != nil {
  289. err = fmt.Errorf("refreshAllCalculate,extra解析失败,Err:%s", err.Error())
  290. return
  291. }
  292. dateTagConfig = dateConfig.DateTag
  293. }
  294. for edbInfoIndex, v := range edbInfoIdArr {
  295. dataList, err := GetEdbDataListAllByTo(to, v.Source, v.SubSource, FindEdbDataListAllCond{
  296. EdbInfoId: v.EdbInfoId,
  297. StartDataTime: startDate,
  298. StartDataTimeCond: ">=",
  299. }, 1)
  300. if err != nil {
  301. return err
  302. }
  303. for _, dv := range dataList {
  304. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  305. if _, ok := val[v.EdbInfoId]; !ok {
  306. val[v.EdbInfoId] = dv.Value
  307. }
  308. } else {
  309. temp := make(map[int]float64)
  310. temp[v.EdbInfoId] = dv.Value
  311. realSaveDataMap[dv.DataTime] = temp
  312. }
  313. // saveDataMap
  314. if val, ok := saveDataMap[dv.DataTime]; ok {
  315. if _, ok := val[v.EdbInfoId]; !ok {
  316. val[v.EdbInfoId] = dv.Value
  317. }
  318. } else {
  319. temp2 := make(map[int]float64)
  320. temp2[v.EdbInfoId] = dv.Value
  321. saveDataMap[dv.DataTime] = temp2
  322. }
  323. if dateTagConfig == "all" {
  324. if _, ok := dateMap[dv.DataTime]; !ok {
  325. dateList = append(dateList, dv.DataTime)
  326. dateMap[dv.DataTime] = struct{}{}
  327. }
  328. } else if dateTagConfig == "" { // 默认取第一个指标的时间序列
  329. if edbInfoIndex == 0 {
  330. if _, ok := dateMap[dv.DataTime]; !ok {
  331. dateList = append(dateList, dv.DataTime)
  332. dateMap[dv.DataTime] = struct{}{}
  333. }
  334. }
  335. } else {
  336. if eId, ok := edbInfoTag[dateTagConfig]; ok {
  337. if v.EdbInfoId == eId {
  338. if _, ok1 := dateMap[dv.DataTime]; !ok1 {
  339. dateList = append(dateList, dv.DataTime)
  340. dateMap[dv.DataTime] = struct{}{}
  341. }
  342. }
  343. }
  344. }
  345. }
  346. }
  347. // 处理最大日期和最小日期
  348. for _, v := range dateList {
  349. tmpDate, _ := time.ParseInLocation(utils.FormatDate, v, time.Local)
  350. if minLatestDate.IsZero() || tmpDate.After(minLatestDate) {
  351. minLatestDate = tmpDate
  352. }
  353. if maxStartDate.IsZero() || tmpDate.Before(maxStartDate) {
  354. maxStartDate = tmpDate
  355. }
  356. }
  357. //数据处理,将日期内不全的数据做补全
  358. HandleDateSaveDataMap(dateList, maxStartDate, minLatestDate, realSaveDataMap, saveDataMap, edbInfoIdArr, emptyType)
  359. formulaDateSlice, formulaDateMap, err := utils.HandleFormulaJson(formulaStr, minLatestDate)
  360. if err != nil {
  361. return
  362. }
  363. addSql := ` INSERT INTO edb_data_calculate(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  364. var isAdd bool
  365. //获取指标所有数据
  366. dataList := make([]*EdbData, 0)
  367. dataTableName := GetEdbDataTableName(source, subSource)
  368. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  369. sql = fmt.Sprintf(sql, dataTableName)
  370. _, err = to.Raw(sql, edbInfoId).QueryRows(&dataList)
  371. if err != nil {
  372. return err
  373. }
  374. dataMap := make(map[string]string)
  375. removeDateMap := make(map[string]string) //需要移除的日期
  376. for _, v := range dataList {
  377. dataMap[v.DataTime] = v.Value
  378. removeDateMap[v.DataTime] = v.DataTime
  379. }
  380. edbInfoIdStr := strconv.Itoa(edbInfoId)
  381. existDataMap := make(map[string]string)
  382. // 判断是否特殊处理max和min函数
  383. maxDealFlag := false
  384. if emptyType == 4 && maxEmptyType == 2 {
  385. maxDealFlag = true
  386. }
  387. for sk, sv := range saveDataMap {
  388. // 当空值处理类型选择了不计算时,只要有一个指标在某个日期没有值(即空值),则计算指标在该日期没有值
  389. if emptyType == 1 {
  390. if len(sv) != len(edbInfoIdArr) {
  391. continue
  392. }
  393. }
  394. //fmt.Println(sk, sv)
  395. // 根据时间范围,选择对应的公式
  396. formulaMap := make(map[string]string)
  397. formulaStr = ""
  398. for _, fv := range formulaDateSlice {
  399. if sk < fv {
  400. if f, ok := formulaDateMap[fv]; ok {
  401. formulaStr = f
  402. formulaMap, err = utils.CheckFormula(formulaStr)
  403. if err != nil {
  404. err = fmt.Errorf("公式错误,请重新填写")
  405. return
  406. }
  407. }
  408. break
  409. }
  410. }
  411. if formulaStr == "" {
  412. continue
  413. }
  414. svMax := make(map[int]float64)
  415. if maxDealFlag {
  416. // 特殊处理max和min函数,如果原本的值为空,则选择空值参与运算
  417. if svMaxData, ok := realSaveDataMap[sk]; ok {
  418. svMax = svMaxData
  419. }
  420. }
  421. formulaStr = strings.ToUpper(formulaStr)
  422. formulaFormStr := ReplaceFormula(edbInfoIdArr, sv, svMax, formulaMap, formulaStr, edbInfoIdBytes, maxDealFlag)
  423. //计算公式异常,那么就移除该指标
  424. if formulaFormStr == `` {
  425. //removeDateList = append(removeDateList, sk)
  426. continue
  427. }
  428. //utils.FileLog.Info(fmt.Sprintf("formulaFormStr:%s", formulaFormStr))
  429. fmt.Println(fmt.Sprintf("%s:formulaFormStr:%s", sk, formulaFormStr))
  430. //expression := formula.NewExpression(formulaFormStr)
  431. //calResult, err := expression.Evaluate()
  432. //if err != nil {
  433. // // 分母为0的报错
  434. // if strings.Contains(err.Error(), "divide by zero") {
  435. // //removeDateList = append(removeDateList, sk)
  436. // continue
  437. // }
  438. // err = errors.New("计算失败:Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  439. // fmt.Println(err)
  440. // return err
  441. //}
  442. //// 如果计算结果是NAN,那么就退出当前循环
  443. //if calResult.IsNan() {
  444. // continue
  445. //}
  446. calVal, err := engine.ParseAndExec(formulaFormStr)
  447. //calVal, err := calResult.Float64()
  448. if err != nil {
  449. // 分母为0的报错,忽略该循环
  450. if utils.IsDivideZero(err) {
  451. //removeDateList = append(removeDateList, sk)
  452. continue
  453. }
  454. err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  455. fmt.Println(err)
  456. return err
  457. }
  458. nanCheck := fmt.Sprintf("%0.f", calVal)
  459. // 分母为0.0的报错
  460. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  461. continue
  462. }
  463. // 有计算出来值,那么就从待删除指标中移除
  464. delete(removeDateMap, sk)
  465. saveValue := decimal.NewFromFloat(calVal).Round(4).String() //utils.SubFloatToString(calVal, 4)
  466. if existVal, ok := dataMap[sk]; !ok {
  467. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  468. timestamp := dataTime.UnixNano() / 1e6
  469. timeStr := fmt.Sprintf("%d", timestamp)
  470. if _, existOk := existDataMap[sk]; !existOk {
  471. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  472. isAdd = true
  473. }
  474. existDataMap[sk] = sk
  475. } else {
  476. existValDecimal, err := decimal.NewFromString(existVal)
  477. existStr := existValDecimal.String()
  478. if existStr != saveValue {
  479. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  480. sql = fmt.Sprintf(sql, dataTableName)
  481. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  482. if err != nil {
  483. return err
  484. }
  485. }
  486. }
  487. }
  488. if isAdd {
  489. addSql = strings.TrimRight(addSql, ",")
  490. _, err = to.Raw(addSql).Exec()
  491. if err != nil {
  492. fmt.Println("RefreshAllCalculate add Err", err.Error())
  493. return
  494. }
  495. }
  496. if len(removeDateMap) > 0 {
  497. removeDateList := make([]string, 0) //需要移除的日期
  498. for k := range removeDateMap {
  499. removeDateList = append(removeDateList, k)
  500. }
  501. removeDateStr := strings.Join(removeDateList, `","`)
  502. removeDateStr = `"` + removeDateStr + `"`
  503. //如果拼接指标变更了,那么需要删除所有的指标数据
  504. tableName := GetEdbDataTableName(source, subSource)
  505. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  506. _, err = to.Raw(sql, edbInfoId).Exec()
  507. if err != nil {
  508. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  509. return
  510. }
  511. }
  512. return
  513. }
  514. // ReplaceFormula 替换计算方式
  515. func ReplaceFormula(edbInfoIdArr []*EdbInfo, valArr, valArrMax map[int]float64, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string, maxDealFlag bool) string {
  516. // todo 先处理max和min函数的特殊情况
  517. //if strings.Contains(formulaStr, "MAX") || strings.Contains(formulaStr, "MIN") {
  518. funMap := GetFormulaMap()
  519. for k, v := range funMap {
  520. formulaStr = strings.Replace(formulaStr, k, v, -1)
  521. }
  522. if maxDealFlag {
  523. formulaStr = GetMaxMinEdbInfo(formulaStr)
  524. }
  525. replaceCount := 0
  526. for dk := len(edbInfoIdArr) - 1; dk >= 0; dk-- {
  527. dv := edbInfoIdArr[dk]
  528. //for dk, dv := range edbInfoIdArr {
  529. var isReplace bool
  530. formulaStr, isReplace = GetFormulaReplace(dk, dv.EdbInfoId, formulaStr, edbInfoIdBytes, formulaMap, valArr, valArrMax, maxDealFlag)
  531. if isReplace {
  532. replaceCount++
  533. }
  534. }
  535. for k, v := range funMap {
  536. formulaStr = strings.Replace(formulaStr, v, k, -1)
  537. }
  538. if strings.Contains(formulaStr, "MAX()") || strings.Contains(formulaStr, "MIN()") {
  539. return ""
  540. }
  541. formulaStr = strings.Replace(formulaStr, "MAX", "max", -1)
  542. formulaStr = strings.Replace(formulaStr, "MIN", "min", -1)
  543. formulaStr = strings.Replace(formulaStr, "LN", "ln", -1)
  544. formulaStr = strings.Replace(formulaStr, "LOG", "log", -1)
  545. formulaStr = strings.Replace(formulaStr, "SIN", "sin", -1)
  546. formulaStr = strings.Replace(formulaStr, "COS", "cos", -1)
  547. formulaStr = strings.Replace(formulaStr, "TAN", "tan", -1)
  548. formulaStr = strings.Replace(formulaStr, "COT", "cot", -1)
  549. formulaStr = strings.Replace(formulaStr, "SEC", "sec", -1)
  550. formulaStr = strings.Replace(formulaStr, "CSC", "csc", -1)
  551. formulaStr = strings.Replace(formulaStr, "ABS", "abs", -1)
  552. formulaStr = strings.Replace(formulaStr, "CEIL", "ceil", -1)
  553. formulaStr = strings.Replace(formulaStr, "FLOOR", "floor", -1)
  554. formulaStr = strings.Replace(formulaStr, "ROUND", "round", -1)
  555. formulaStr = strings.Replace(formulaStr, "SQRT", "sqrt", -1)
  556. formulaStr = strings.Replace(formulaStr, "CBRT", "cbrt", -1)
  557. formulaStr = strings.Replace(formulaStr, "NOERR", "noerr", -1)
  558. formulaStr = strings.Replace(formulaStr, "DOUBLE", "double", -1)
  559. if replaceCount == len(formulaMap) {
  560. return formulaStr
  561. } else {
  562. return ""
  563. }
  564. }
  565. func GetFormulaReplace(index, edbInfoId int, formulaStr string, edbInfoIdBytes []string, formulaMap map[string]string, valArr, valArrMax map[int]float64, maxDealFlag bool) (formulaResult string, isReplace bool) {
  566. formulaResult = formulaStr
  567. dKey := edbInfoIdBytes[index]
  568. if _, ok := formulaMap[dKey]; ok { //公式中存在
  569. if val, valOk := valArr[edbInfoId]; valOk { //值存在
  570. dvStr := fmt.Sprintf("%v", val)
  571. formulaResult = strings.Replace(formulaResult, dKey, dvStr, -1)
  572. isReplace = true
  573. if maxDealFlag {
  574. if valM, valMOk := valArrMax[edbInfoId]; valMOk { //值存在
  575. dvMStr := fmt.Sprintf("%v", valM)
  576. formulaResult = strings.Replace(formulaResult, strings.ToLower(dKey), dvMStr, -1)
  577. } else {
  578. formulaResult = strings.Replace(formulaResult, strings.ToLower(dKey)+",", "", -1)
  579. formulaResult = strings.Replace(formulaResult, ","+strings.ToLower(dKey), "", -1)
  580. }
  581. }
  582. }
  583. }
  584. return
  585. }
  586. // GetFormulaMap 获取计算公式的map
  587. func GetFormulaMap() map[string]string {
  588. funMap := make(map[string]string)
  589. funMap["MAX"] = "[@@]"
  590. funMap["MIN"] = "[@!]"
  591. funMap["ABS"] = "[@#]"
  592. funMap["CEIL"] = "[@$]"
  593. funMap["COS"] = "[@%]"
  594. funMap["FLOOR"] = "[@^]"
  595. funMap["MOD"] = "[@&]"
  596. funMap["POW"] = "[@*]"
  597. funMap["ROUND"] = "[@`]"
  598. funMap["LN"] = "[@-]"
  599. funMap["EXP"] = "[@+]"
  600. return funMap
  601. }
  602. // CalculateBatchSaveReq 添加计算指标的请求参数
  603. type CalculateBatchSaveReq struct {
  604. EdbList []*CalculateEdbInfoItem //需要批量计算的指标列表
  605. AdminId int `description:"添加人id"`
  606. AdminName string `description:"添加人名称"`
  607. Formula string `description:"N值/移动天数"`
  608. Source int `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,12:环比值,13:环差值,14:升频"`
  609. CalculateFormula string `description:"计算公式"`
  610. EdbInfoIdArr []EdbInfoCalculateEdbInfoIdReq `description:"关联指标列表"`
  611. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  612. MoveFrequency string `description:"移动频度:天/周/月/季/年"`
  613. Calendar string `description:"公历/农历"`
  614. Data interface{} `description:"数据"`
  615. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  616. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  617. Extra string `description:"指标额外配置"`
  618. }
  619. type CalculateEdbInfoItem struct {
  620. EdbInfoId int `description:"指标id"`
  621. EdbName string `description:"指标名称"`
  622. Frequency string `description:"频度"`
  623. Unit string `description:"单位"`
  624. ClassifyId int `description:"分类id"`
  625. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  626. FromEdbInfoId int `description:"计算来源指标id"`
  627. }
  628. // EdbInfoCalculateBatchSaveReq 添加计算指标的请求参数
  629. type EdbInfoCalculateBatchSaveReq struct {
  630. AdminId int `description:"添加人id"`
  631. AdminName string `description:"添加人名称"`
  632. EdbInfoId int `description:"指标id"`
  633. EdbName string `description:"指标名称"`
  634. Frequency string `description:"频度"`
  635. Unit string `description:"单位"`
  636. ClassifyId int `description:"分类id"`
  637. Formula string `description:"N值/移动天数"`
  638. FromEdbInfoId int `description:"计算来源指标id"`
  639. Source int `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,12:环比值,13:环差值,14:升频"`
  640. CalculateFormula string `description:"计算公式"`
  641. EdbInfoIdArr []EdbInfoCalculateEdbInfoIdReq `description:"关联指标列表"`
  642. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  643. MoveFrequency string `description:"移动频度:天/周/月/季/年/交易日/自然日"`
  644. Calendar string `description:"公历/农历"`
  645. Data interface{} `description:"数据"`
  646. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  647. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  648. Extra string `description:"指标额外配置"`
  649. }
  650. // EdbInfoCalculateEdbInfoIdReq 新增/编辑请求 关联的指标列表
  651. type EdbInfoCalculateEdbInfoIdReq struct {
  652. EdbInfoId int `description:"指标id"`
  653. FromTag string `description:"指标对应标签"`
  654. MoveValue int `description:"移动的值"`
  655. }
  656. // EdbInfoCalculateBatchEditReq 编辑计算指标的请求参数
  657. type EdbInfoCalculateBatchEditReq struct {
  658. EdbName string `description:"指标名称"`
  659. EdbNameEn string `description:"英文指标名称"`
  660. Frequency string `description:"频度"`
  661. Unit string `description:"单位"`
  662. UnitEn string `description:"英文单位"`
  663. ClassifyId int `description:"分类id"`
  664. AdminId int `description:"操作人id"`
  665. AdminName string `description:"操作人姓名"`
  666. Formula string `description:"N值"`
  667. EdbInfoId int `description:"编辑指标id"`
  668. FromEdbInfoId int `description:"计算来源指标id"`
  669. Source int `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,12:环比值,13:环差值,14:升频"`
  670. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  671. MoveFrequency string `description:"移动频度:天/周/月/季/年"`
  672. EdbInfoIdArr []EdbInfoCalculateEdbInfoIdReq `description:"关联指标列表"`
  673. Calendar string `description:"公历/农历" orm:"default(公历)"`
  674. Extra string `description:"指标的额外配置"`
  675. Data interface{} `description:"数据"`
  676. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  677. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  678. CalculateFormula string `description:"计算公式"`
  679. }
  680. // DeleteCalculateData 删除计算数据
  681. func DeleteCalculateData(edbInfoId int) (err error) {
  682. o := orm.NewOrm()
  683. sql := `DELETE FROM edb_data_calculate WHERE edb_info_id=?`
  684. _, err = o.Raw(sql, edbInfoId).Exec()
  685. return
  686. }
  687. // CheckFormula2 校验公式是否正常(比如说除法的分母不能为0之类的,实际上就是用预设的字段数据做一次计算)
  688. func CheckFormula2(edbInfoArr []*EdbInfo, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string) (ok bool, err error) {
  689. valArr := make(map[int]float64)
  690. for k, v := range edbInfoArr {
  691. valArr[v.EdbInfoId] = 100 + float64(k)
  692. }
  693. formulaStr = strings.ToUpper(formulaStr)
  694. // 预设里的max和min无需特殊处理
  695. valArrMax := make(map[int]float64)
  696. formulaFormStr := ReplaceFormula(edbInfoArr, valArr, valArrMax, formulaMap, formulaStr, edbInfoIdBytes, false)
  697. if formulaFormStr == "" {
  698. return
  699. }
  700. _, err = engine.ParseAndExec(formulaFormStr)
  701. if err != nil {
  702. fmt.Println(err)
  703. } else {
  704. ok = true
  705. }
  706. //expression := formula.NewExpression(formulaFormStr)
  707. //_, err = expression.Evaluate()
  708. //if err != nil {
  709. //} else {
  710. // ok = true
  711. //}
  712. return
  713. }
  714. // 处理整个数据
  715. func HandleDateSaveDataMap(dateList []string, maxStartDate, minLatestDate time.Time, realSaveDataMap, saveDataMap map[string]map[int]float64, edbInfoIdArr []*EdbInfo, emptyType int) {
  716. for _, date := range dateList {
  717. dateTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  718. // 如果当前日期早于数据的最大开始日期,那么不处理,进入下一个循环
  719. if dateTime.Before(maxStartDate) {
  720. continue
  721. }
  722. // todo 规则是否生效如果当前日期晚于数据的最小结束日期,那么不处理,直接返回了
  723. if dateTime.After(minLatestDate) {
  724. return
  725. }
  726. tmpDataMap := realSaveDataMap[date]
  727. for _, edbInfo := range edbInfoIdArr {
  728. tmpEdbInfoId := edbInfo.EdbInfoId // 当前指标id
  729. // 如果该日期不存在该指标数据,那么需要找寻前后日期的数据,进行填补
  730. if _, ok := tmpDataMap[tmpEdbInfoId]; !ok {
  731. //day := 0
  732. //switch edbInfo.Frequency {
  733. //case "周度":
  734. // day = 7
  735. //case "旬度":
  736. // day = 15
  737. //case "月度":
  738. // day = 30
  739. //case "季度":
  740. // day = 90
  741. //case "年度":
  742. // day = 365
  743. //}
  744. // 需求池 255 指标运算文案修改,补数据遍历区间修改(2023-3-7 09:37:23修改)
  745. switch emptyType {
  746. case 0:
  747. handleDateDataMap(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, 35)
  748. case 2:
  749. handleDateDataMapBefore(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, edbInfo.StartDate, edbInfo.EndDate)
  750. case 3:
  751. handleDateDataMapAfter(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, edbInfo.StartDate, edbInfo.EndDate)
  752. case 4:
  753. handleDateDataMapZero(saveDataMap, date, tmpEdbInfoId)
  754. }
  755. }
  756. }
  757. }
  758. }
  759. // handleDateDataMap 前后35天 处理单个日期的数据
  760. func handleDateDataMap(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId, day int) {
  761. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  762. // 后一天
  763. nextDateDayStr := currDate.AddDate(0, 0, 1).Format(utils.FormatDate)
  764. // 前一天
  765. preDateDayStr := currDate.AddDate(0, 0, -1).Format(utils.FormatDate)
  766. for i := 1; i <= day; i++ {
  767. // 下个日期的数据
  768. {
  769. if i >= 1 {
  770. nextDateDayStr = currDate.AddDate(0, 0, i).Format(utils.FormatDate)
  771. }
  772. if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
  773. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  774. fmt.Println(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, nextDateDayStr, val))
  775. saveDataMap[date][edbInfoId] = val
  776. return
  777. }
  778. }
  779. }
  780. // 上个日期的数据
  781. {
  782. if i >= 1 {
  783. preDateDayStr = currDate.AddDate(0, 0, -i).Format(utils.FormatDate)
  784. }
  785. if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
  786. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  787. fmt.Println(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, preDateDayStr, val))
  788. saveDataMap[date][edbInfoId] = val
  789. return
  790. }
  791. }
  792. }
  793. }
  794. }
  795. // handleDateDataMapBefore 前值填充:空值优先以最近的前值填充,没有前值时,用后值填充
  796. func handleDateDataMapBefore(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId int, startDate, endDate string) {
  797. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  798. // 前一天
  799. preDateDay := currDate
  800. startDateT, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  801. endDateT, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  802. if currDate.Before(startDateT) {
  803. if findDataMap, hasFindDataMap := realSaveDataMap[startDate]; hasFindDataMap { // 下一个日期有数据
  804. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  805. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, startDate, val))
  806. saveDataMap[date][edbInfoId] = val
  807. return
  808. }
  809. }
  810. return
  811. }
  812. if currDate.After(endDateT) {
  813. if findDataMap, hasFindDataMap := realSaveDataMap[endDate]; hasFindDataMap { // 下一个日期有数据
  814. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  815. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, endDate, val))
  816. saveDataMap[date][edbInfoId] = val
  817. return
  818. }
  819. }
  820. }
  821. for i := 1; preDateDay.After(startDateT) || preDateDay == startDateT; i++ {
  822. // 上个日期的数据
  823. {
  824. preDateDay = currDate.AddDate(0, 0, -i)
  825. preDateDayStr := preDateDay.Format(utils.FormatDate)
  826. if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
  827. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  828. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, preDateDayStr, val))
  829. saveDataMap[date][edbInfoId] = val
  830. return
  831. }
  832. }
  833. }
  834. }
  835. return
  836. }
  837. // handleDateDataMapAfter 后值填充:空值优先以最近的后值填充,没有后值时,用前值填充
  838. func handleDateDataMapAfter(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId int, startDate, endDate string) {
  839. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  840. // 后一天
  841. nextDateDay := currDate
  842. startDateT, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  843. endDateT, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  844. if currDate.Before(startDateT) {
  845. if findDataMap, hasFindDataMap := realSaveDataMap[startDate]; hasFindDataMap { // 下一个日期有数据
  846. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  847. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, startDate, val))
  848. saveDataMap[date][edbInfoId] = val
  849. return
  850. }
  851. }
  852. return
  853. }
  854. if currDate.After(endDateT) {
  855. if findDataMap, hasFindDataMap := realSaveDataMap[endDate]; hasFindDataMap { // 下一个日期有数据
  856. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  857. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, endDate, val))
  858. saveDataMap[date][edbInfoId] = val
  859. return
  860. }
  861. }
  862. }
  863. for i := 1; nextDateDay.Before(endDateT) || nextDateDay == endDateT; i++ {
  864. // 下个日期的数据
  865. {
  866. nextDateDay = currDate.AddDate(0, 0, i)
  867. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  868. if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
  869. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  870. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, nextDateDayStr, val))
  871. saveDataMap[date][edbInfoId] = val
  872. return
  873. }
  874. }
  875. }
  876. }
  877. return
  878. }
  879. // handleDateDataMapZero 等于0
  880. func handleDateDataMapZero(saveDataMap map[string]map[int]float64, date string, edbInfoId int) {
  881. saveDataMap[date][edbInfoId] = 0
  882. return
  883. }
  884. func GetMaxMinEdbInfo(formula string) string {
  885. flag := 0
  886. for k, v := range formula {
  887. if v >= 65 && v <= 122 {
  888. // 从左边找到第一个左括号的位置,往前截取三个字符,判断是不是max或者min,如果是的话,把该入参改成小写
  889. for i := k; i >= 4; i-- {
  890. if formula[i:i+1] == "(" && flag >= 1 {
  891. t := formula[i-4 : i]
  892. if t == "[@@]" || t == "[@!]" {
  893. formula = formula[:k] + strings.ToLower(formula[k:k+1]) + formula[k+1:]
  894. }
  895. break
  896. }
  897. }
  898. } else if formula[k:k+1] == "(" {
  899. flag += 1
  900. } else if formula[k:k+1] == ")" {
  901. flag -= 1
  902. }
  903. }
  904. return formula
  905. }
  906. // PredictRuleCalculateByNineResp 获取预测指标规则9的绘图数据返回
  907. type PredictRuleCalculateByNineResp struct {
  908. LatestDate string
  909. DataList interface{}
  910. }
  911. // BatchEdbInfoCalculateBatchSaveResp 批量添加 计算指标 返回数据
  912. type BatchEdbInfoCalculateBatchSaveResp struct {
  913. Fail []BatchEdbInfoCalculateBatchSaveFailResp `description:"添加失败的指标"`
  914. Success []BatchEdbInfoCalculateBatchSaveSuccessResp `description:"添加成功的指标"`
  915. }
  916. // BatchEdbInfoCalculateBatchSaveFailResp 添加失败的指标信息
  917. type BatchEdbInfoCalculateBatchSaveFailResp struct {
  918. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  919. Msg string `description:"用户提示信息"`
  920. ErrMsg string `description:"错误信息,内部查看"`
  921. }
  922. // BatchEdbInfoCalculateBatchSaveSuccessResp 添加成功的指标信息
  923. type BatchEdbInfoCalculateBatchSaveSuccessResp struct {
  924. ClassifyId int `description:"分类id"`
  925. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  926. EdbInfoId int `description:"指标ID"`
  927. UniqueCode string `description:"指标唯一编码"`
  928. }