base_from_calculate.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_index_lib/utils"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/dengsgo/math-engine/engine"
  11. "github.com/beego/beego/v2/client/orm"
  12. "github.com/shopspring/decimal"
  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. // CheckFormula2 校验公式是否正常(比如说除法的分母不能为0之类的,实际上就是用预设的字段数据做一次计算)
  681. func CheckFormula2(edbInfoArr []*EdbInfo, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string) (ok bool, err error) {
  682. valArr := make(map[int]float64)
  683. for k, v := range edbInfoArr {
  684. valArr[v.EdbInfoId] = 100 + float64(k)
  685. }
  686. formulaStr = strings.ToUpper(formulaStr)
  687. // 预设里的max和min无需特殊处理
  688. valArrMax := make(map[int]float64)
  689. formulaFormStr := ReplaceFormula(edbInfoArr, valArr, valArrMax, formulaMap, formulaStr, edbInfoIdBytes, false)
  690. if formulaFormStr == "" {
  691. return
  692. }
  693. _, err = engine.ParseAndExec(formulaFormStr)
  694. if err != nil {
  695. fmt.Println(err)
  696. } else {
  697. ok = true
  698. }
  699. //expression := formula.NewExpression(formulaFormStr)
  700. //_, err = expression.Evaluate()
  701. //if err != nil {
  702. //} else {
  703. // ok = true
  704. //}
  705. return
  706. }
  707. // 处理整个数据
  708. func HandleDateSaveDataMap(dateList []string, maxStartDate, minLatestDate time.Time, realSaveDataMap, saveDataMap map[string]map[int]float64, edbInfoIdArr []*EdbInfo, emptyType int) {
  709. for _, date := range dateList {
  710. dateTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  711. // 如果当前日期早于数据的最大开始日期,那么不处理,进入下一个循环
  712. if dateTime.Before(maxStartDate) {
  713. continue
  714. }
  715. // todo 规则是否生效如果当前日期晚于数据的最小结束日期,那么不处理,直接返回了
  716. if dateTime.After(minLatestDate) {
  717. return
  718. }
  719. tmpDataMap := realSaveDataMap[date]
  720. for _, edbInfo := range edbInfoIdArr {
  721. tmpEdbInfoId := edbInfo.EdbInfoId // 当前指标id
  722. // 如果该日期不存在该指标数据,那么需要找寻前后日期的数据,进行填补
  723. if _, ok := tmpDataMap[tmpEdbInfoId]; !ok {
  724. //day := 0
  725. //switch edbInfo.Frequency {
  726. //case "周度":
  727. // day = 7
  728. //case "旬度":
  729. // day = 15
  730. //case "月度":
  731. // day = 30
  732. //case "季度":
  733. // day = 90
  734. //case "年度":
  735. // day = 365
  736. //}
  737. // 需求池 255 指标运算文案修改,补数据遍历区间修改(2023-3-7 09:37:23修改)
  738. switch emptyType {
  739. case 0:
  740. handleDateDataMap(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, 35)
  741. case 2:
  742. handleDateDataMapBefore(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, edbInfo.StartDate, edbInfo.EndDate)
  743. case 3:
  744. handleDateDataMapAfter(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, edbInfo.StartDate, edbInfo.EndDate)
  745. case 4:
  746. handleDateDataMapZero(saveDataMap, date, tmpEdbInfoId)
  747. }
  748. }
  749. }
  750. }
  751. }
  752. // handleDateDataMap 前后35天 处理单个日期的数据
  753. func handleDateDataMap(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId, day int) {
  754. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  755. // 后一天
  756. nextDateDayStr := currDate.AddDate(0, 0, 1).Format(utils.FormatDate)
  757. // 前一天
  758. preDateDayStr := currDate.AddDate(0, 0, -1).Format(utils.FormatDate)
  759. for i := 1; i <= day; i++ {
  760. // 下个日期的数据
  761. {
  762. if i >= 1 {
  763. nextDateDayStr = currDate.AddDate(0, 0, i).Format(utils.FormatDate)
  764. }
  765. if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
  766. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  767. fmt.Println(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, nextDateDayStr, val))
  768. saveDataMap[date][edbInfoId] = val
  769. return
  770. }
  771. }
  772. }
  773. // 上个日期的数据
  774. {
  775. if i >= 1 {
  776. preDateDayStr = currDate.AddDate(0, 0, -i).Format(utils.FormatDate)
  777. }
  778. if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
  779. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  780. fmt.Println(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, preDateDayStr, val))
  781. saveDataMap[date][edbInfoId] = val
  782. return
  783. }
  784. }
  785. }
  786. }
  787. }
  788. // handleDateDataMapBefore 前值填充:空值优先以最近的前值填充,没有前值时,用后值填充
  789. func handleDateDataMapBefore(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId int, startDate, endDate string) {
  790. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  791. // 前一天
  792. preDateDay := currDate
  793. startDateT, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  794. endDateT, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  795. if currDate.Before(startDateT) {
  796. if findDataMap, hasFindDataMap := realSaveDataMap[startDate]; hasFindDataMap { // 下一个日期有数据
  797. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  798. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, startDate, val))
  799. saveDataMap[date][edbInfoId] = val
  800. return
  801. }
  802. }
  803. return
  804. }
  805. if currDate.After(endDateT) {
  806. if findDataMap, hasFindDataMap := realSaveDataMap[endDate]; hasFindDataMap { // 下一个日期有数据
  807. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  808. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, endDate, val))
  809. saveDataMap[date][edbInfoId] = val
  810. return
  811. }
  812. }
  813. }
  814. for i := 1; preDateDay.After(startDateT) || preDateDay == startDateT; i++ {
  815. // 上个日期的数据
  816. {
  817. preDateDay = currDate.AddDate(0, 0, -i)
  818. preDateDayStr := preDateDay.Format(utils.FormatDate)
  819. if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
  820. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  821. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, preDateDayStr, val))
  822. saveDataMap[date][edbInfoId] = val
  823. return
  824. }
  825. }
  826. }
  827. }
  828. return
  829. }
  830. // handleDateDataMapAfter 后值填充:空值优先以最近的后值填充,没有后值时,用前值填充
  831. func handleDateDataMapAfter(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId int, startDate, endDate string) {
  832. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  833. // 后一天
  834. nextDateDay := currDate
  835. startDateT, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  836. endDateT, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  837. if currDate.Before(startDateT) {
  838. if findDataMap, hasFindDataMap := realSaveDataMap[startDate]; hasFindDataMap { // 下一个日期有数据
  839. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  840. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, startDate, val))
  841. saveDataMap[date][edbInfoId] = val
  842. return
  843. }
  844. }
  845. return
  846. }
  847. if currDate.After(endDateT) {
  848. if findDataMap, hasFindDataMap := realSaveDataMap[endDate]; hasFindDataMap { // 下一个日期有数据
  849. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  850. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, endDate, val))
  851. saveDataMap[date][edbInfoId] = val
  852. return
  853. }
  854. }
  855. }
  856. for i := 1; nextDateDay.Before(endDateT) || nextDateDay == endDateT; i++ {
  857. // 下个日期的数据
  858. {
  859. nextDateDay = currDate.AddDate(0, 0, i)
  860. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  861. if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
  862. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  863. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, nextDateDayStr, val))
  864. saveDataMap[date][edbInfoId] = val
  865. return
  866. }
  867. }
  868. }
  869. }
  870. return
  871. }
  872. // handleDateDataMapZero 等于0
  873. func handleDateDataMapZero(saveDataMap map[string]map[int]float64, date string, edbInfoId int) {
  874. saveDataMap[date][edbInfoId] = 0
  875. return
  876. }
  877. func GetMaxMinEdbInfo(formula string) string {
  878. flag := 0
  879. for k, v := range formula {
  880. if v >= 65 && v <= 122 {
  881. // 从左边找到第一个左括号的位置,往前截取三个字符,判断是不是max或者min,如果是的话,把该入参改成小写
  882. for i := k; i >= 4; i-- {
  883. if formula[i:i+1] == "(" && flag >= 1 {
  884. t := formula[i-4 : i]
  885. if t == "[@@]" || t == "[@!]" {
  886. formula = formula[:k] + strings.ToLower(formula[k:k+1]) + formula[k+1:]
  887. }
  888. break
  889. }
  890. }
  891. } else if formula[k:k+1] == "(" {
  892. flag += 1
  893. } else if formula[k:k+1] == ")" {
  894. flag -= 1
  895. }
  896. }
  897. return formula
  898. }
  899. // PredictRuleCalculateByNineResp 获取预测指标规则9的绘图数据返回
  900. type PredictRuleCalculateByNineResp struct {
  901. LatestDate string
  902. DataList interface{}
  903. }
  904. // BatchEdbInfoCalculateBatchSaveResp 批量添加 计算指标 返回数据
  905. type BatchEdbInfoCalculateBatchSaveResp struct {
  906. Fail []BatchEdbInfoCalculateBatchSaveFailResp `description:"添加失败的指标"`
  907. Success []BatchEdbInfoCalculateBatchSaveSuccessResp `description:"添加成功的指标"`
  908. }
  909. // BatchEdbInfoCalculateBatchSaveFailResp 添加失败的指标信息
  910. type BatchEdbInfoCalculateBatchSaveFailResp struct {
  911. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  912. Msg string `description:"用户提示信息"`
  913. ErrMsg string `description:"错误信息,内部查看"`
  914. }
  915. // BatchEdbInfoCalculateBatchSaveSuccessResp 添加成功的指标信息
  916. type BatchEdbInfoCalculateBatchSaveSuccessResp struct {
  917. ClassifyId int `description:"分类id"`
  918. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  919. EdbInfoId int `description:"指标ID"`
  920. UniqueCode string `description:"指标唯一编码"`
  921. }