base_from_calculate.go 32 KB

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