base_from_calculate.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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: 0,
  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. err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  450. fmt.Println(err)
  451. return err
  452. }
  453. nanCheck := fmt.Sprintf("%0.f", calVal)
  454. // 分母为0.0的报错
  455. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  456. continue
  457. }
  458. // 有计算出来值,那么就从待删除指标中移除
  459. delete(removeDateMap, sk)
  460. saveValue := decimal.NewFromFloat(calVal).Round(4).String() //utils.SubFloatToString(calVal, 4)
  461. if existVal, ok := dataMap[sk]; !ok {
  462. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  463. timestamp := dataTime.UnixNano() / 1e6
  464. timeStr := fmt.Sprintf("%d", timestamp)
  465. if _, existOk := existDataMap[sk]; !existOk {
  466. addSql += GetAddSql(edbInfoIdStr, edbCode, sk, timeStr, saveValue)
  467. isAdd = true
  468. }
  469. existDataMap[sk] = sk
  470. } else {
  471. existValDecimal, err := decimal.NewFromString(existVal)
  472. existStr := existValDecimal.String()
  473. if existStr != saveValue {
  474. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  475. sql = fmt.Sprintf(sql, dataTableName)
  476. _, err = to.Raw(sql, saveValue, edbInfoId, sk).Exec()
  477. if err != nil {
  478. return err
  479. }
  480. }
  481. }
  482. }
  483. if isAdd {
  484. addSql = strings.TrimRight(addSql, ",")
  485. _, err = to.Raw(addSql).Exec()
  486. if err != nil {
  487. fmt.Println("RefreshAllCalculate add Err", err.Error())
  488. return
  489. }
  490. }
  491. if len(removeDateMap) > 0 {
  492. removeDateList := make([]string, 0) //需要移除的日期
  493. for k := range removeDateMap {
  494. removeDateList = append(removeDateList, k)
  495. }
  496. removeDateStr := strings.Join(removeDateList, `","`)
  497. removeDateStr = `"` + removeDateStr + `"`
  498. //如果拼接指标变更了,那么需要删除所有的指标数据
  499. tableName := GetEdbDataTableName(source, subSource)
  500. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (%s) `, tableName, removeDateStr)
  501. _, err = to.Raw(sql, edbInfoId).Exec()
  502. if err != nil {
  503. err = fmt.Errorf("删除计算失败的计算指标数据失败,Err:" + err.Error())
  504. return
  505. }
  506. }
  507. return
  508. }
  509. // ReplaceFormula 替换计算方式
  510. func ReplaceFormula(edbInfoIdArr []*EdbInfo, valArr, valArrMax map[int]float64, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string, maxDealFlag bool) string {
  511. // todo 先处理max和min函数的特殊情况
  512. //if strings.Contains(formulaStr, "MAX") || strings.Contains(formulaStr, "MIN") {
  513. funMap := GetFormulaMap()
  514. for k, v := range funMap {
  515. formulaStr = strings.Replace(formulaStr, k, v, -1)
  516. }
  517. if maxDealFlag {
  518. formulaStr = GetMaxMinEdbInfo(formulaStr)
  519. }
  520. replaceCount := 0
  521. for dk := len(edbInfoIdArr) - 1; dk >= 0; dk-- {
  522. dv := edbInfoIdArr[dk]
  523. //for dk, dv := range edbInfoIdArr {
  524. var isReplace bool
  525. formulaStr, isReplace = GetFormulaReplace(dk, dv.EdbInfoId, formulaStr, edbInfoIdBytes, formulaMap, valArr, valArrMax, maxDealFlag)
  526. if isReplace {
  527. replaceCount++
  528. }
  529. }
  530. for k, v := range funMap {
  531. formulaStr = strings.Replace(formulaStr, v, k, -1)
  532. }
  533. if strings.Contains(formulaStr, "MAX()") || strings.Contains(formulaStr, "MIN()") {
  534. return ""
  535. }
  536. formulaStr = strings.Replace(formulaStr, "MAX", "max", -1)
  537. formulaStr = strings.Replace(formulaStr, "MIN", "min", -1)
  538. formulaStr = strings.Replace(formulaStr, "LN", "ln", -1)
  539. formulaStr = strings.Replace(formulaStr, "LOG", "log", -1)
  540. formulaStr = strings.Replace(formulaStr, "SIN", "sin", -1)
  541. formulaStr = strings.Replace(formulaStr, "COS", "cos", -1)
  542. formulaStr = strings.Replace(formulaStr, "TAN", "tan", -1)
  543. formulaStr = strings.Replace(formulaStr, "COT", "cot", -1)
  544. formulaStr = strings.Replace(formulaStr, "SEC", "sec", -1)
  545. formulaStr = strings.Replace(formulaStr, "CSC", "csc", -1)
  546. formulaStr = strings.Replace(formulaStr, "ABS", "abs", -1)
  547. formulaStr = strings.Replace(formulaStr, "CEIL", "ceil", -1)
  548. formulaStr = strings.Replace(formulaStr, "FLOOR", "floor", -1)
  549. formulaStr = strings.Replace(formulaStr, "ROUND", "round", -1)
  550. formulaStr = strings.Replace(formulaStr, "SQRT", "sqrt", -1)
  551. formulaStr = strings.Replace(formulaStr, "CBRT", "cbrt", -1)
  552. formulaStr = strings.Replace(formulaStr, "NOERR", "noerr", -1)
  553. formulaStr = strings.Replace(formulaStr, "DOUBLE", "double", -1)
  554. if replaceCount == len(formulaMap) {
  555. return formulaStr
  556. } else {
  557. return ""
  558. }
  559. }
  560. func GetFormulaReplace(index, edbInfoId int, formulaStr string, edbInfoIdBytes []string, formulaMap map[string]string, valArr, valArrMax map[int]float64, maxDealFlag bool) (formulaResult string, isReplace bool) {
  561. formulaResult = formulaStr
  562. dKey := edbInfoIdBytes[index]
  563. if _, ok := formulaMap[dKey]; ok { //公式中存在
  564. if val, valOk := valArr[edbInfoId]; valOk { //值存在
  565. dvStr := fmt.Sprintf("%v", val)
  566. formulaResult = strings.Replace(formulaResult, dKey, dvStr, -1)
  567. isReplace = true
  568. if maxDealFlag {
  569. if valM, valMOk := valArrMax[edbInfoId]; valMOk { //值存在
  570. dvMStr := fmt.Sprintf("%v", valM)
  571. formulaResult = strings.Replace(formulaResult, strings.ToLower(dKey), dvMStr, -1)
  572. } else {
  573. formulaResult = strings.Replace(formulaResult, strings.ToLower(dKey)+",", "", -1)
  574. formulaResult = strings.Replace(formulaResult, ","+strings.ToLower(dKey), "", -1)
  575. }
  576. }
  577. }
  578. }
  579. return
  580. }
  581. // GetFormulaMap 获取计算公式的map
  582. func GetFormulaMap() map[string]string {
  583. funMap := make(map[string]string)
  584. funMap["MAX"] = "[@@]"
  585. funMap["MIN"] = "[@!]"
  586. funMap["ABS"] = "[@#]"
  587. funMap["CEIL"] = "[@$]"
  588. funMap["COS"] = "[@%]"
  589. funMap["FLOOR"] = "[@^]"
  590. funMap["MOD"] = "[@&]"
  591. funMap["POW"] = "[@*]"
  592. funMap["ROUND"] = "[@`]"
  593. funMap["LN"] = "[@-]"
  594. funMap["EXP"] = "[@+]"
  595. return funMap
  596. }
  597. // CalculateBatchSaveReq 添加计算指标的请求参数
  598. type CalculateBatchSaveReq struct {
  599. EdbList []*CalculateEdbInfoItem //需要批量计算的指标列表
  600. AdminId int `description:"添加人id"`
  601. AdminName string `description:"添加人名称"`
  602. Formula string `description:"N值/移动天数"`
  603. Source int `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,12:环比值,13:环差值,14:升频"`
  604. CalculateFormula string `description:"计算公式"`
  605. EdbInfoIdArr []EdbInfoCalculateEdbInfoIdReq `description:"关联指标列表"`
  606. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  607. MoveFrequency string `description:"移动频度:天/周/月/季/年"`
  608. Calendar string `description:"公历/农历"`
  609. Data interface{} `description:"数据"`
  610. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  611. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  612. Extra string `description:"指标额外配置"`
  613. }
  614. type CalculateEdbInfoItem struct {
  615. EdbInfoId int `description:"指标id"`
  616. EdbName string `description:"指标名称"`
  617. Frequency string `description:"频度"`
  618. Unit string `description:"单位"`
  619. ClassifyId int `description:"分类id"`
  620. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  621. FromEdbInfoId int `description:"计算来源指标id"`
  622. }
  623. // EdbInfoCalculateBatchSaveReq 添加计算指标的请求参数
  624. type EdbInfoCalculateBatchSaveReq struct {
  625. AdminId int `description:"添加人id"`
  626. AdminName string `description:"添加人名称"`
  627. EdbInfoId int `description:"指标id"`
  628. EdbName string `description:"指标名称"`
  629. Frequency string `description:"频度"`
  630. Unit string `description:"单位"`
  631. ClassifyId int `description:"分类id"`
  632. Formula string `description:"N值/移动天数"`
  633. FromEdbInfoId int `description:"计算来源指标id"`
  634. Source int `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,12:环比值,13:环差值,14:升频"`
  635. CalculateFormula string `description:"计算公式"`
  636. EdbInfoIdArr []EdbInfoCalculateEdbInfoIdReq `description:"关联指标列表"`
  637. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  638. MoveFrequency string `description:"移动频度:天/周/月/季/年"`
  639. Calendar string `description:"公历/农历"`
  640. Data interface{} `description:"数据"`
  641. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  642. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  643. Extra string `description:"指标额外配置"`
  644. }
  645. // EdbInfoCalculateEdbInfoIdReq 新增/编辑请求 关联的指标列表
  646. type EdbInfoCalculateEdbInfoIdReq struct {
  647. EdbInfoId int `description:"指标id"`
  648. FromTag string `description:"指标对应标签"`
  649. MoveValue int `description:"移动的值"`
  650. }
  651. // EdbInfoCalculateBatchEditReq 编辑计算指标的请求参数
  652. type EdbInfoCalculateBatchEditReq struct {
  653. EdbName string `description:"指标名称"`
  654. EdbNameEn string `description:"英文指标名称"`
  655. Frequency string `description:"频度"`
  656. Unit string `description:"单位"`
  657. UnitEn string `description:"英文单位"`
  658. ClassifyId int `description:"分类id"`
  659. Formula string `description:"N值"`
  660. EdbInfoId int `description:"编辑指标id"`
  661. FromEdbInfoId int `description:"计算来源指标id"`
  662. Source int `description:"来源:1:同花顺,2:wind,3:彭博,4:指标运算,5:累计值转月,6:同比值,7:同差值,8:N数值移动平均计算,12:环比值,13:环差值,14:升频"`
  663. MoveType int `description:"移动方式:1:领先(默认),2:滞后"`
  664. MoveFrequency string `description:"移动频度:天/周/月/季/年"`
  665. EdbInfoIdArr []EdbInfoCalculateEdbInfoIdReq `description:"关联指标列表"`
  666. Calendar string `description:"公历/农历" orm:"default(公历)"`
  667. Extra string `description:"指标的额外配置"`
  668. Data interface{} `description:"数据"`
  669. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  670. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  671. CalculateFormula string `description:"计算公式"`
  672. }
  673. // CheckFormula2 校验公式是否正常(比如说除法的分母不能为0之类的,实际上就是用预设的字段数据做一次计算)
  674. func CheckFormula2(edbInfoArr []*EdbInfo, formulaMap map[string]string, formulaStr string, edbInfoIdBytes []string) (ok bool, err error) {
  675. valArr := make(map[int]float64)
  676. for k, v := range edbInfoArr {
  677. valArr[v.EdbInfoId] = 100 + float64(k)
  678. }
  679. formulaStr = strings.ToUpper(formulaStr)
  680. // 预设里的max和min无需特殊处理
  681. valArrMax := make(map[int]float64)
  682. formulaFormStr := ReplaceFormula(edbInfoArr, valArr, valArrMax, formulaMap, formulaStr, edbInfoIdBytes, false)
  683. if formulaFormStr == "" {
  684. return
  685. }
  686. _, err = engine.ParseAndExec(formulaFormStr)
  687. if err != nil {
  688. fmt.Println(err)
  689. } else {
  690. ok = true
  691. }
  692. //expression := formula.NewExpression(formulaFormStr)
  693. //_, err = expression.Evaluate()
  694. //if err != nil {
  695. //} else {
  696. // ok = true
  697. //}
  698. return
  699. }
  700. // 处理整个数据
  701. func HandleDateSaveDataMap(dateList []string, maxStartDate, minLatestDate time.Time, realSaveDataMap, saveDataMap map[string]map[int]float64, edbInfoIdArr []*EdbInfo, emptyType int) {
  702. for _, date := range dateList {
  703. dateTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  704. // 如果当前日期早于数据的最大开始日期,那么不处理,进入下一个循环
  705. if dateTime.Before(maxStartDate) {
  706. continue
  707. }
  708. // todo 规则是否生效如果当前日期晚于数据的最小结束日期,那么不处理,直接返回了
  709. if dateTime.After(minLatestDate) {
  710. return
  711. }
  712. tmpDataMap := realSaveDataMap[date]
  713. for _, edbInfo := range edbInfoIdArr {
  714. tmpEdbInfoId := edbInfo.EdbInfoId // 当前指标id
  715. // 如果该日期不存在该指标数据,那么需要找寻前后日期的数据,进行填补
  716. if _, ok := tmpDataMap[tmpEdbInfoId]; !ok {
  717. //day := 0
  718. //switch edbInfo.Frequency {
  719. //case "周度":
  720. // day = 7
  721. //case "旬度":
  722. // day = 15
  723. //case "月度":
  724. // day = 30
  725. //case "季度":
  726. // day = 90
  727. //case "年度":
  728. // day = 365
  729. //}
  730. // 需求池 255 指标运算文案修改,补数据遍历区间修改(2023-3-7 09:37:23修改)
  731. switch emptyType {
  732. case 0:
  733. handleDateDataMap(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, 35)
  734. case 2:
  735. handleDateDataMapBefore(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, edbInfo.StartDate, edbInfo.EndDate)
  736. case 3:
  737. handleDateDataMapAfter(realSaveDataMap, saveDataMap, date, tmpEdbInfoId, edbInfo.StartDate, edbInfo.EndDate)
  738. case 4:
  739. handleDateDataMapZero(saveDataMap, date, tmpEdbInfoId)
  740. }
  741. }
  742. }
  743. }
  744. }
  745. // handleDateDataMap 前后35天 处理单个日期的数据
  746. func handleDateDataMap(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId, day int) {
  747. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  748. // 后一天
  749. nextDateDayStr := currDate.AddDate(0, 0, 1).Format(utils.FormatDate)
  750. // 前一天
  751. preDateDayStr := currDate.AddDate(0, 0, -1).Format(utils.FormatDate)
  752. for i := 1; i <= day; i++ {
  753. // 下个日期的数据
  754. {
  755. if i >= 1 {
  756. nextDateDayStr = currDate.AddDate(0, 0, i).Format(utils.FormatDate)
  757. }
  758. if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
  759. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  760. fmt.Println(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, nextDateDayStr, val))
  761. saveDataMap[date][edbInfoId] = val
  762. return
  763. }
  764. }
  765. }
  766. // 上个日期的数据
  767. {
  768. if i >= 1 {
  769. preDateDayStr = currDate.AddDate(0, 0, -i).Format(utils.FormatDate)
  770. }
  771. if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
  772. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  773. fmt.Println(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, preDateDayStr, val))
  774. saveDataMap[date][edbInfoId] = val
  775. return
  776. }
  777. }
  778. }
  779. }
  780. }
  781. // handleDateDataMapBefore 前值填充:空值优先以最近的前值填充,没有前值时,用后值填充
  782. func handleDateDataMapBefore(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId int, startDate, endDate string) {
  783. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  784. // 前一天
  785. preDateDay := currDate
  786. startDateT, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  787. endDateT, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  788. if currDate.Before(startDateT) {
  789. if findDataMap, hasFindDataMap := realSaveDataMap[startDate]; hasFindDataMap { // 下一个日期有数据
  790. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  791. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, startDate, val))
  792. saveDataMap[date][edbInfoId] = val
  793. return
  794. }
  795. }
  796. return
  797. }
  798. if currDate.After(endDateT) {
  799. if findDataMap, hasFindDataMap := realSaveDataMap[endDate]; hasFindDataMap { // 下一个日期有数据
  800. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  801. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, endDate, val))
  802. saveDataMap[date][edbInfoId] = val
  803. return
  804. }
  805. }
  806. }
  807. for i := 1; preDateDay.After(startDateT) || preDateDay == startDateT; i++ {
  808. // 上个日期的数据
  809. {
  810. preDateDay = currDate.AddDate(0, 0, -i)
  811. preDateDayStr := preDateDay.Format(utils.FormatDate)
  812. if findDataMap, hasFindDataMap := realSaveDataMap[preDateDayStr]; hasFindDataMap { // 下一个日期有数据
  813. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  814. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, preDateDayStr, val))
  815. saveDataMap[date][edbInfoId] = val
  816. return
  817. }
  818. }
  819. }
  820. }
  821. return
  822. }
  823. // handleDateDataMapAfter 后值填充:空值优先以最近的后值填充,没有后值时,用前值填充
  824. func handleDateDataMapAfter(realSaveDataMap, saveDataMap map[string]map[int]float64, date string, edbInfoId int, startDate, endDate string) {
  825. currDate, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  826. // 后一天
  827. nextDateDay := currDate
  828. startDateT, _ := time.ParseInLocation(utils.FormatDate, startDate, time.Local)
  829. endDateT, _ := time.ParseInLocation(utils.FormatDate, endDate, time.Local)
  830. if currDate.Before(startDateT) {
  831. if findDataMap, hasFindDataMap := realSaveDataMap[startDate]; hasFindDataMap { // 下一个日期有数据
  832. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  833. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, startDate, val))
  834. saveDataMap[date][edbInfoId] = val
  835. return
  836. }
  837. }
  838. return
  839. }
  840. if currDate.After(endDateT) {
  841. if findDataMap, hasFindDataMap := realSaveDataMap[endDate]; hasFindDataMap { // 下一个日期有数据
  842. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  843. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, endDate, val))
  844. saveDataMap[date][edbInfoId] = val
  845. return
  846. }
  847. }
  848. }
  849. for i := 1; nextDateDay.Before(endDateT) || nextDateDay == endDateT; i++ {
  850. // 下个日期的数据
  851. {
  852. nextDateDay = currDate.AddDate(0, 0, i)
  853. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  854. if findDataMap, hasFindDataMap := realSaveDataMap[nextDateDayStr]; hasFindDataMap { // 下一个日期有数据
  855. if val, hasFindItem := findDataMap[edbInfoId]; hasFindItem {
  856. //utils.FileLog.Info(fmt.Sprintf("date:%s, 无值,取%s的值%.4f", date, nextDateDayStr, val))
  857. saveDataMap[date][edbInfoId] = val
  858. return
  859. }
  860. }
  861. }
  862. }
  863. return
  864. }
  865. // handleDateDataMapZero 等于0
  866. func handleDateDataMapZero(saveDataMap map[string]map[int]float64, date string, edbInfoId int) {
  867. saveDataMap[date][edbInfoId] = 0
  868. return
  869. }
  870. func GetMaxMinEdbInfo(formula string) string {
  871. flag := 0
  872. for k, v := range formula {
  873. if v >= 65 && v <= 122 {
  874. // 从左边找到第一个左括号的位置,往前截取三个字符,判断是不是max或者min,如果是的话,把该入参改成小写
  875. for i := k; i >= 4; i-- {
  876. if formula[i:i+1] == "(" && flag >= 1 {
  877. t := formula[i-4 : i]
  878. if t == "[@@]" || t == "[@!]" {
  879. formula = formula[:k] + strings.ToLower(formula[k:k+1]) + formula[k+1:]
  880. }
  881. break
  882. }
  883. }
  884. } else if formula[k:k+1] == "(" {
  885. flag += 1
  886. } else if formula[k:k+1] == ")" {
  887. flag -= 1
  888. }
  889. }
  890. return formula
  891. }
  892. // PredictRuleCalculateByNineResp 获取预测指标规则9的绘图数据返回
  893. type PredictRuleCalculateByNineResp struct {
  894. LatestDate string
  895. DataList interface{}
  896. }
  897. // BatchEdbInfoCalculateBatchSaveResp 批量添加 计算指标 返回数据
  898. type BatchEdbInfoCalculateBatchSaveResp struct {
  899. Fail []BatchEdbInfoCalculateBatchSaveFailResp `description:"添加失败的指标"`
  900. Success []BatchEdbInfoCalculateBatchSaveSuccessResp `description:"添加成功的指标"`
  901. }
  902. // BatchEdbInfoCalculateBatchSaveFailResp 添加失败的指标信息
  903. type BatchEdbInfoCalculateBatchSaveFailResp struct {
  904. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  905. Msg string `description:"用户提示信息"`
  906. ErrMsg string `description:"错误信息,内部查看"`
  907. }
  908. // BatchEdbInfoCalculateBatchSaveSuccessResp 添加成功的指标信息
  909. type BatchEdbInfoCalculateBatchSaveSuccessResp struct {
  910. ClassifyId int `description:"分类id"`
  911. CalculateId string `description:"当前请求时,单个计算的唯一标识"`
  912. EdbInfoId int `description:"指标ID"`
  913. UniqueCode string `description:"指标唯一编码"`
  914. }