base_from_calculate.go 34 KB

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