predict_edb_data_calculate_tbz.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. "reflect"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. // PredictTb 预测同比值
  14. type PredictTb struct {
  15. }
  16. // Add 添加
  17. func (obj PredictTb) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  18. req := params.Req
  19. fromEdbInfo := params.FromEdbInfo
  20. edbCode := params.EdbCode
  21. o := orm.NewOrm()
  22. to, err := o.Begin()
  23. if err != nil {
  24. return
  25. }
  26. defer func() {
  27. if err != nil {
  28. _ = to.Rollback()
  29. fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
  30. } else {
  31. _ = to.Commit()
  32. }
  33. }()
  34. edbInfo = &EdbInfo{
  35. //EdbInfoId: 0,
  36. SourceName: obj.GetSourceName(),
  37. Source: obj.GetSource(),
  38. EdbCode: edbCode,
  39. EdbName: req.EdbName,
  40. EdbNameSource: req.EdbName,
  41. Frequency: req.Frequency,
  42. Unit: req.Unit,
  43. StartDate: "",
  44. EndDate: "",
  45. ClassifyId: req.ClassifyId,
  46. SysUserId: params.SysUserId,
  47. SysUserRealName: params.SysUserRealName,
  48. UniqueCode: params.UniqueCode,
  49. CreateTime: time.Now(),
  50. ModifyTime: time.Now(),
  51. MinValue: 0,
  52. MaxValue: 0,
  53. CalculateFormula: req.Formula,
  54. EdbType: 2,
  55. Sort: 0,
  56. MoveType: 0,
  57. MoveFrequency: "",
  58. NoUpdate: 0,
  59. ServerUrl: "",
  60. EdbInfoType: 1,
  61. EdbNameEn: req.EdbName,
  62. UnitEn: req.Unit,
  63. LatestDate: "",
  64. LatestValue: 0,
  65. ChartImage: "",
  66. Calendar: "",
  67. }
  68. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  69. if tmpErr != nil {
  70. err = tmpErr
  71. return
  72. }
  73. edbInfo.EdbInfoId = int(newEdbInfoId)
  74. //关联关系
  75. {
  76. calculateMappingItem := new(EdbInfoCalculateMapping)
  77. calculateMappingItem.CreateTime = time.Now()
  78. calculateMappingItem.ModifyTime = time.Now()
  79. calculateMappingItem.Sort = 1
  80. calculateMappingItem.EdbCode = edbCode
  81. calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
  82. calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
  83. calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
  84. calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
  85. calculateMappingItem.FromSource = fromEdbInfo.Source
  86. calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
  87. calculateMappingItem.FromTag = ""
  88. calculateMappingItem.Source = edbInfo.Source
  89. calculateMappingItem.SourceName = edbInfo.SourceName
  90. _, err = to.Insert(calculateMappingItem)
  91. if err != nil {
  92. return
  93. }
  94. }
  95. //计算数据
  96. latestDateStr, latestValue, err = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  97. return
  98. }
  99. // Edit 编辑
  100. func (obj PredictTb) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  101. req := params.Req
  102. edbInfo := params.EdbInfo
  103. fromEdbInfo := params.FromEdbInfo
  104. latestDateStr = edbInfo.LatestDate
  105. latestValue = edbInfo.LatestValue
  106. if fromEdbInfo.Frequency != req.Frequency {
  107. errMsg = "生成指标频度与原指标频度不同"
  108. err = errors.New(errMsg)
  109. return
  110. }
  111. if edbInfo.EdbInfoType != 1 {
  112. errMsg = `该指标不是预测指标`
  113. err = errors.New(errMsg)
  114. return
  115. }
  116. latestDateStr = edbInfo.LatestDate
  117. latestValue = edbInfo.LatestValue
  118. o := orm.NewOrm()
  119. to, err := o.Begin()
  120. if err != nil {
  121. return
  122. }
  123. defer func() {
  124. if err != nil {
  125. _ = to.Rollback()
  126. fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
  127. } else {
  128. _ = to.Commit()
  129. }
  130. }()
  131. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  132. //修改指标信息
  133. switch params.Lang {
  134. case utils.EnLangVersion:
  135. edbInfo.EdbNameEn = req.EdbName
  136. edbInfo.UnitEn = req.Unit
  137. default:
  138. edbInfo.EdbName = req.EdbName
  139. edbInfo.Unit = req.Unit
  140. edbInfo.EdbNameSource = req.EdbName
  141. }
  142. edbInfo.Frequency = req.Frequency
  143. edbInfo.ClassifyId = req.ClassifyId
  144. edbInfo.ModifyTime = time.Now()
  145. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
  146. if err != nil {
  147. return
  148. }
  149. //判断计算指标是否被更换
  150. var existCondition string
  151. var existPars []interface{}
  152. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  153. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  154. var count int
  155. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  156. if err != nil {
  157. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  158. return
  159. }
  160. if count > 0 { // 指标未被替换,无需重新计算
  161. return
  162. }
  163. //删除,计算指标关联的,基础指标的关联关系
  164. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  165. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  166. if err != nil {
  167. return
  168. }
  169. // 删除该指标所有的同比数据
  170. sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
  171. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  172. if err != nil {
  173. return
  174. }
  175. //关联关系
  176. {
  177. calculateMappingItem := &EdbInfoCalculateMapping{
  178. EdbInfoCalculateMappingId: 0,
  179. EdbInfoId: edbInfo.EdbInfoId,
  180. Source: obj.GetSource(),
  181. SourceName: obj.GetSourceName(),
  182. EdbCode: edbInfo.EdbCode,
  183. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  184. FromEdbCode: fromEdbInfo.EdbCode,
  185. FromEdbName: fromEdbInfo.EdbName,
  186. FromSource: fromEdbInfo.Source,
  187. FromSourceName: fromEdbInfo.SourceName,
  188. FromTag: "",
  189. Sort: 1,
  190. CreateTime: time.Now(),
  191. ModifyTime: time.Now(),
  192. }
  193. _, err = to.Insert(calculateMappingItem)
  194. if err != nil {
  195. return
  196. }
  197. }
  198. //计算数据
  199. latestDateStr, latestValue, err = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
  200. return
  201. }
  202. // Refresh 刷新
  203. func (obj PredictTb) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
  204. calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
  205. if err != nil {
  206. return
  207. }
  208. fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
  209. if err != nil {
  210. errMsg = "GetEdbInfoById Err:" + err.Error()
  211. return
  212. }
  213. o := orm.NewOrm()
  214. to, err := o.Begin()
  215. if err != nil {
  216. return
  217. }
  218. defer func() {
  219. if err != nil {
  220. _ = to.Rollback()
  221. fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
  222. } else {
  223. _ = to.Commit()
  224. }
  225. }()
  226. // 计算数据
  227. latestDateStr, latestValue, err = obj.refresh(to, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
  228. return
  229. }
  230. // GetSource 获取来源编码id
  231. func (obj PredictTb) GetSource() int {
  232. return utils.DATA_SOURCE_PREDICT_CALCULATE_TBZ
  233. }
  234. // GetSourceName 获取来源名称
  235. func (obj PredictTb) GetSourceName() string {
  236. return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_TBZ
  237. }
  238. func (obj PredictTb) refresh(to orm.TxOrmer, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
  239. edbInfoId := edbInfo.EdbInfoId
  240. dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  241. edbInfoIdStr := strconv.Itoa(edbInfoId)
  242. // 获取关联指标数据
  243. dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, startDate)
  244. if err != nil {
  245. return
  246. }
  247. latestDateStr = fromEdbInfo.LatestDate
  248. //计算数据
  249. var dateArr []string
  250. dataMap := make(map[string]*EdbInfoSearchData)
  251. for _, v := range dataList {
  252. dateArr = append(dateArr, v.DataTime)
  253. dataMap[v.DataTime] = v
  254. }
  255. //获取指标所有数据
  256. existDataList := make([]*EdbData, 0)
  257. fmt.Println("dataTableName:", dataTableName)
  258. sql := `SELECT * FROM %s WHERE edb_info_id=? `
  259. sql = fmt.Sprintf(sql, dataTableName)
  260. _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
  261. if err != nil {
  262. return
  263. }
  264. existDataMap := make(map[string]string)
  265. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  266. for _, v := range existDataList {
  267. existDataMap[v.DataTime] = v.Value
  268. removeDataTimeMap[v.DataTime] = 1
  269. }
  270. fmt.Println("existDataMap:", existDataMap)
  271. addSql := ` INSERT INTO edb_data_predict_calculate_tbz (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  272. var isAdd bool
  273. existAddDataMap := make(map[string]string)
  274. for _, av := range dateArr {
  275. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
  276. delete(removeDataTimeMap, av)
  277. currentItem, ok := dataMap[av]
  278. if !ok || currentItem == nil {
  279. continue
  280. }
  281. //当前日期
  282. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  283. if tmpErr != nil {
  284. err = tmpErr
  285. return
  286. }
  287. //上一年的日期
  288. preDate := currentDate.AddDate(-1, 0, 0)
  289. preDateStr := preDate.Format(utils.FormatDate)
  290. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
  291. //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  292. timestamp := currentDate.UnixNano() / 1e6
  293. timestampStr := fmt.Sprintf("%d", timestamp)
  294. val := TbzDiv(currentItem.Value, findItem.Value)
  295. if existVal, ok := existDataMap[av]; !ok {
  296. if _, existOk := existAddDataMap[av]; !existOk {
  297. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  298. isAdd = true
  299. // 实际数据的值
  300. if fromEdbInfo.LatestDate == av {
  301. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  302. if tmpErr != nil {
  303. return
  304. }
  305. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  306. }
  307. }
  308. existAddDataMap[av] = av
  309. } else {
  310. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  311. if tmpErr != nil {
  312. err = tmpErr
  313. return
  314. }
  315. existStr := existValDecimal.String()
  316. if existStr != val {
  317. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  318. sql = fmt.Sprintf(sql, dataTableName)
  319. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  320. if err != nil {
  321. return
  322. }
  323. }
  324. }
  325. continue
  326. } else {
  327. if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
  328. for i := 0; i <= 35; i++ {
  329. nextDateDay := preDate.AddDate(0, 0, i)
  330. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  331. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  332. timestamp := currentDate.UnixNano() / 1e6
  333. timestampStr := fmt.Sprintf("%d", timestamp)
  334. val := TbzDiv(currentItem.Value, findItem.Value)
  335. if existVal, ok := existDataMap[av]; !ok {
  336. if _, existOk := existAddDataMap[av]; !existOk {
  337. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  338. isAdd = true
  339. // 实际数据的值
  340. if fromEdbInfo.LatestDate == av {
  341. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  342. if tmpErr != nil {
  343. return
  344. }
  345. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  346. }
  347. }
  348. existAddDataMap[av] = av
  349. } else {
  350. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  351. if tmpErr != nil {
  352. err = tmpErr
  353. return
  354. }
  355. existStr := existValDecimal.String()
  356. if existStr != val {
  357. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  358. sql = fmt.Sprintf(sql, dataTableName)
  359. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  360. if err != nil {
  361. return
  362. }
  363. }
  364. }
  365. break
  366. } else {
  367. preDateDay := preDate.AddDate(0, 0, -i)
  368. preDateDayStr := preDateDay.Format(utils.FormatDate)
  369. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  370. timestamp := currentDate.UnixNano() / 1e6
  371. timestampStr := fmt.Sprintf("%d", timestamp)
  372. val := TbzDiv(currentItem.Value, findItem.Value)
  373. if existVal, ok := existDataMap[av]; !ok {
  374. if _, existOk := existAddDataMap[av]; !existOk {
  375. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  376. isAdd = true
  377. // 实际数据的值
  378. if fromEdbInfo.LatestDate == av {
  379. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  380. if tmpErr != nil {
  381. return
  382. }
  383. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  384. }
  385. }
  386. existAddDataMap[av] = av
  387. } else {
  388. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  389. if tmpErr != nil {
  390. err = tmpErr
  391. return
  392. }
  393. existStr := existValDecimal.String()
  394. if existStr != val {
  395. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  396. sql = fmt.Sprintf(sql, dataTableName)
  397. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  398. if err != nil {
  399. return
  400. }
  401. }
  402. }
  403. break
  404. }
  405. }
  406. }
  407. } else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
  408. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
  409. timestamp := currentDate.UnixNano() / 1e6
  410. timestampStr := fmt.Sprintf("%d", timestamp)
  411. val := TbzDiv(currentItem.Value, findItem.Value)
  412. if existVal, ok := existDataMap[av]; !ok {
  413. if _, existOk := existAddDataMap[av]; !existOk {
  414. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  415. isAdd = true
  416. // 实际数据的值
  417. if fromEdbInfo.LatestDate == av {
  418. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  419. if tmpErr != nil {
  420. return
  421. }
  422. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  423. }
  424. }
  425. existAddDataMap[av] = av
  426. } else {
  427. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  428. if tmpErr != nil {
  429. err = tmpErr
  430. return
  431. }
  432. existStr := existValDecimal.String()
  433. if existStr != val {
  434. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  435. sql = fmt.Sprintf(sql, dataTableName)
  436. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  437. if err != nil {
  438. return
  439. }
  440. }
  441. }
  442. break
  443. }
  444. } else {
  445. nextDateDay := preDate.AddDate(0, 0, 1)
  446. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  447. preDateDay := preDate.AddDate(0, 0, -1)
  448. preDateDayStr := preDateDay.Format(utils.FormatDate)
  449. for i := 0; i < 35; i++ {
  450. if i >= 1 {
  451. nextDateDay = nextDateDay.AddDate(0, 0, i)
  452. nextDateDayStr = nextDateDay.Format(utils.FormatDate)
  453. }
  454. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  455. timestamp := currentDate.UnixNano() / 1e6
  456. timestampStr := fmt.Sprintf("%d", timestamp)
  457. val := TbzDiv(currentItem.Value, findItem.Value)
  458. if existVal, ok := existDataMap[av]; !ok {
  459. if _, existOk := existAddDataMap[av]; !existOk {
  460. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  461. isAdd = true
  462. // 实际数据的值
  463. if fromEdbInfo.LatestDate == av {
  464. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  465. if tmpErr != nil {
  466. return
  467. }
  468. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  469. }
  470. }
  471. existAddDataMap[av] = av
  472. } else {
  473. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  474. if tmpErr != nil {
  475. err = tmpErr
  476. return
  477. }
  478. existStr := existValDecimal.String()
  479. if existStr != val {
  480. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  481. sql = fmt.Sprintf(sql, dataTableName)
  482. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  483. if err != nil {
  484. return
  485. }
  486. }
  487. }
  488. break
  489. } else {
  490. if i >= 1 {
  491. preDateDay = preDateDay.AddDate(0, 0, -i)
  492. preDateDayStr = preDateDay.Format(utils.FormatDate)
  493. }
  494. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  495. timestamp := currentDate.UnixNano() / 1e6
  496. timestampStr := fmt.Sprintf("%d", timestamp)
  497. val := TbzDiv(currentItem.Value, findItem.Value)
  498. if existVal, ok := existDataMap[av]; !ok {
  499. if _, existOk := existAddDataMap[av]; !existOk {
  500. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  501. isAdd = true
  502. // 实际数据的值
  503. if fromEdbInfo.LatestDate == av {
  504. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  505. if tmpErr != nil {
  506. return
  507. }
  508. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  509. }
  510. }
  511. existAddDataMap[av] = av
  512. } else {
  513. existValDecimal, tmpErr := decimal.NewFromString(existVal)
  514. if tmpErr != nil {
  515. err = tmpErr
  516. return
  517. }
  518. existStr := existValDecimal.String()
  519. if existStr != val {
  520. sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
  521. sql = fmt.Sprintf(sql, dataTableName)
  522. _, err = to.Raw(sql, val, edbInfoId, av).Exec()
  523. if err != nil {
  524. return
  525. }
  526. }
  527. }
  528. break
  529. }
  530. }
  531. }
  532. }
  533. }
  534. }
  535. //删除已经不存在的指标数据(由于该指标当日的数据删除了)
  536. {
  537. removeDateList := make([]string, 0)
  538. for dateTime := range removeDataTimeMap {
  539. removeDateList = append(removeDateList, dateTime)
  540. }
  541. removeNum := len(removeDateList)
  542. if removeNum > 0 {
  543. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
  544. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  545. if err != nil {
  546. fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
  547. err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
  548. return
  549. }
  550. }
  551. }
  552. // 批量插入
  553. if isAdd {
  554. addSql = strings.TrimRight(addSql, ",")
  555. _, err = to.Raw(addSql).Exec()
  556. if err != nil {
  557. return
  558. }
  559. }
  560. //确定实际数据的最终值
  561. {
  562. finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo.LatestDate)
  563. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  564. return
  565. }
  566. if tmpErr == nil {
  567. latestDateStr = finalLast.DataTime
  568. latestValue = finalLast.Value
  569. }
  570. }
  571. return
  572. }
  573. // SavePredictCalculateTbz 新增/编辑 预测同比指标
  574. func SavePredictCalculateTbz(reqEdbInfoId, classifyId int, edbName, frequency, unit, formula string, fromEdbInfo *EdbInfo, edbCode, uniqueCode string, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
  575. o := orm.NewOrm()
  576. to, err := o.Begin()
  577. if err != nil {
  578. return
  579. }
  580. defer func() {
  581. if err != nil {
  582. fmt.Println("AddCalculateTbz,Err:" + err.Error())
  583. _ = to.Rollback()
  584. } else {
  585. _ = to.Commit()
  586. }
  587. }()
  588. if reqEdbInfoId <= 0 {
  589. edbInfo = &EdbInfo{
  590. //EdbInfoId: 0,
  591. EdbInfoType: 1,
  592. SourceName: "预测同比",
  593. Source: utils.DATA_SOURCE_PREDICT_CALCULATE_TBZ,
  594. EdbCode: edbCode,
  595. EdbName: edbName,
  596. EdbNameSource: edbName,
  597. Frequency: frequency,
  598. Unit: unit,
  599. //StartDate: "",
  600. //EndDate: "",
  601. ClassifyId: classifyId,
  602. SysUserId: sysUserId,
  603. SysUserRealName: sysUserRealName,
  604. UniqueCode: uniqueCode,
  605. CreateTime: time.Now(),
  606. ModifyTime: time.Now(),
  607. MinValue: 0,
  608. MaxValue: 0,
  609. CalculateFormula: formula,
  610. EdbType: 2,
  611. Sort: 0,
  612. MoveType: 0,
  613. MoveFrequency: "",
  614. NoUpdate: 0,
  615. ServerUrl: "",
  616. EdbNameEn: "",
  617. UnitEn: "",
  618. LatestDate: "",
  619. LatestValue: 0,
  620. ChartImage: "",
  621. }
  622. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  623. if tmpErr != nil {
  624. err = tmpErr
  625. return
  626. }
  627. edbInfo.EdbInfoId = int(newEdbInfoId)
  628. // 添加关联关系
  629. {
  630. calculateMappingItem := &EdbInfoCalculateMapping{
  631. EdbInfoCalculateMappingId: 0,
  632. EdbInfoId: edbInfo.EdbInfoId,
  633. Source: edbInfo.Source,
  634. SourceName: edbInfo.SourceName,
  635. EdbCode: edbCode,
  636. FromEdbInfoId: fromEdbInfo.EdbInfoId,
  637. FromEdbCode: fromEdbInfo.EdbCode,
  638. FromEdbName: fromEdbInfo.EdbName,
  639. FromSource: fromEdbInfo.Source,
  640. FromSourceName: fromEdbInfo.SourceName,
  641. FromTag: "",
  642. Sort: 1,
  643. CreateTime: time.Now(),
  644. ModifyTime: time.Now(),
  645. }
  646. _, err = to.Insert(calculateMappingItem)
  647. if err != nil {
  648. return
  649. }
  650. }
  651. } else {
  652. edbInfo, err = GetEdbInfoById(reqEdbInfoId)
  653. if err != nil {
  654. if err.Error() == utils.ErrNoRow() {
  655. errMsg = `获取指标信息失败`
  656. }
  657. return
  658. }
  659. if edbInfo.EdbInfoType != 1 {
  660. errMsg = `该指标不是预测指标`
  661. err = errors.New(errMsg)
  662. return
  663. }
  664. latestDateStr = edbInfo.LatestDate
  665. latestValue = edbInfo.LatestValue
  666. //修改指标信息
  667. edbInfo.EdbName = edbName
  668. edbInfo.EdbNameSource = edbName
  669. edbInfo.Frequency = frequency
  670. edbInfo.Unit = unit
  671. edbInfo.ClassifyId = classifyId
  672. edbInfo.ModifyTime = time.Now()
  673. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
  674. if err != nil {
  675. return
  676. }
  677. //判断计算指标是否被更换
  678. var existCondition string
  679. var existPars []interface{}
  680. existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
  681. existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
  682. var count int
  683. count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
  684. if err != nil {
  685. err = errors.New("判断指标是否改变失败,Err:" + err.Error())
  686. return
  687. }
  688. if count > 0 { // 指标未被替换,无需重新计算
  689. return
  690. }
  691. //删除,计算指标关联的,基础指标的关联关系
  692. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
  693. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  694. if err != nil {
  695. return
  696. }
  697. // 删除该指标所有的同比数据
  698. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_TBZ, utils.DATA_SUB_SOURCE_EDB)
  699. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  700. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  701. _, err = to.Raw(deleteSql, edbInfo.EdbInfoId).Exec()
  702. if err != nil {
  703. return
  704. }
  705. }
  706. edbInfoIdStr := strconv.Itoa(edbInfo.EdbInfoId)
  707. // 获取源指标数据
  708. dataList, err := GetPredictEdbDataListAll(fromEdbInfo, 0)
  709. if err != nil {
  710. return
  711. }
  712. latestDateStr = fromEdbInfo.LatestDate
  713. // 计算数据
  714. var dateArr []string
  715. dataMap := make(map[string]*EdbInfoSearchData)
  716. for _, v := range dataList {
  717. dateArr = append(dateArr, v.DataTime)
  718. dataMap[v.DataTime] = v
  719. }
  720. addSql := ` INSERT INTO edb_data_predict_calculate_tbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
  721. var isAdd bool
  722. existMap := make(map[string]string)
  723. for _, av := range dateArr {
  724. //fmt.Println(ak, av)
  725. currentItem := dataMap[av]
  726. if currentItem != nil {
  727. //当前日期
  728. currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
  729. if tmpErr != nil {
  730. err = tmpErr
  731. return
  732. }
  733. //上一年的日期
  734. preDate := currentDate.AddDate(-1, 0, 0)
  735. preDateStr := preDate.Format(utils.FormatDate)
  736. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
  737. //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
  738. if _, ok := existMap[edbCode+av]; !ok {
  739. timestamp := currentDate.UnixNano() / 1e6
  740. timestampStr := fmt.Sprintf("%d", timestamp)
  741. val := TbzDiv(currentItem.Value, findItem.Value)
  742. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  743. isAdd = true
  744. utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
  745. // 实际数据的值
  746. if fromEdbInfo.LatestDate == av {
  747. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  748. if tmpErr != nil {
  749. return
  750. }
  751. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  752. }
  753. }
  754. existMap[edbCode+av] = av
  755. } else {
  756. if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
  757. nextDateDay := preDate
  758. preDateDay := preDate
  759. for i := 0; i <= 35; i++ {
  760. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  761. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  762. if _, ok := existMap[edbCode+av]; !ok {
  763. timestamp := currentDate.UnixNano() / 1e6
  764. timestampStr := fmt.Sprintf("%d", timestamp)
  765. val := TbzDiv(currentItem.Value, findItem.Value)
  766. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  767. isAdd = true
  768. // 实际数据的值
  769. if fromEdbInfo.LatestDate == av {
  770. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  771. if tmpErr != nil {
  772. return
  773. }
  774. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  775. }
  776. }
  777. existMap[edbCode+av] = av
  778. break
  779. } else {
  780. preDateDayStr := preDateDay.Format(utils.FormatDate)
  781. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  782. if _, ok := existMap[edbCode+av]; !ok {
  783. timestamp := currentDate.UnixNano() / 1e6
  784. timestampStr := fmt.Sprintf("%d", timestamp)
  785. val := TbzDiv(currentItem.Value, findItem.Value)
  786. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  787. isAdd = true
  788. // 实际数据的值
  789. if fromEdbInfo.LatestDate == av {
  790. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  791. if tmpErr != nil {
  792. return
  793. }
  794. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  795. }
  796. }
  797. existMap[edbCode+av] = av
  798. break
  799. }
  800. }
  801. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  802. preDateDay = preDateDay.AddDate(0, 0, -1)
  803. }
  804. } else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
  805. if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
  806. if _, ok := existMap[edbCode+av]; !ok {
  807. timestamp := currentDate.UnixNano() / 1e6
  808. timestampStr := fmt.Sprintf("%d", timestamp)
  809. val := TbzDiv(currentItem.Value, findItem.Value)
  810. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  811. isAdd = true
  812. // 实际数据的值
  813. if fromEdbInfo.LatestDate == av {
  814. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  815. if tmpErr != nil {
  816. return
  817. }
  818. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  819. }
  820. }
  821. existMap[edbCode+av] = av
  822. break
  823. }
  824. } else {
  825. nextDateDay := preDate
  826. preDateDay := preDate
  827. for i := 0; i < 35; i++ {
  828. nextDateDayStr := nextDateDay.Format(utils.FormatDate)
  829. if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
  830. if _, ok := existMap[edbCode+av]; !ok {
  831. timestamp := currentDate.UnixNano() / 1e6
  832. timestampStr := fmt.Sprintf("%d", timestamp)
  833. val := TbzDiv(currentItem.Value, findItem.Value)
  834. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  835. isAdd = true
  836. // 实际数据的值
  837. if fromEdbInfo.LatestDate == av {
  838. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  839. if tmpErr != nil {
  840. return
  841. }
  842. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  843. }
  844. }
  845. existMap[edbCode+av] = av
  846. break
  847. } else {
  848. preDateDayStr := preDateDay.Format(utils.FormatDate)
  849. if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
  850. if _, ok := existMap[edbCode+av]; !ok {
  851. timestamp := currentDate.UnixNano() / 1e6
  852. timestampStr := fmt.Sprintf("%d", timestamp)
  853. val := TbzDiv(currentItem.Value, findItem.Value)
  854. addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
  855. isAdd = true
  856. // 实际数据的值
  857. if fromEdbInfo.LatestDate == av {
  858. latestValueDecimal, tmpErr := decimal.NewFromString(val)
  859. if tmpErr != nil {
  860. return
  861. }
  862. latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
  863. }
  864. }
  865. existMap[edbCode+av] = av
  866. break
  867. } else {
  868. //fmt.Println("pre not find:", preDateStr, "i:", i)
  869. }
  870. }
  871. nextDateDay = nextDateDay.AddDate(0, 0, 1)
  872. preDateDay = preDateDay.AddDate(0, 0, -1)
  873. }
  874. }
  875. }
  876. }
  877. }
  878. if isAdd {
  879. addSql = strings.TrimRight(addSql, ",")
  880. _, err = to.Raw(addSql).Exec()
  881. if err != nil {
  882. return
  883. }
  884. }
  885. return
  886. }