123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959 |
- package models
- import (
- "errors"
- "eta/eta_index_lib/utils"
- "fmt"
- "github.com/beego/beego/v2/client/orm"
- "github.com/shopspring/decimal"
- "reflect"
- "strconv"
- "strings"
- "time"
- )
- // PredictTb 预测同比值
- type PredictTb struct {
- }
- // Add 添加
- func (obj PredictTb) Add(params BatchSaveCalculateBatchParams) (edbInfo *EdbInfo, latestDateStr string, latestValue float64, err error, errMsg string) {
- req := params.Req
- fromEdbInfo := params.FromEdbInfo
- edbCode := params.EdbCode
- o := orm.NewOrm()
- to, err := o.Begin()
- if err != nil {
- return
- }
- defer func() {
- if err != nil {
- _ = to.Rollback()
- fmt.Println(reflect.TypeOf(obj).Name(), ";Add,Err:"+err.Error())
- } else {
- _ = to.Commit()
- }
- }()
- edbInfo = &EdbInfo{
- //EdbInfoId: 0,
- SourceName: obj.GetSourceName(),
- Source: obj.GetSource(),
- EdbCode: edbCode,
- EdbName: req.EdbName,
- EdbNameSource: req.EdbName,
- Frequency: req.Frequency,
- Unit: req.Unit,
- StartDate: "",
- EndDate: "",
- ClassifyId: req.ClassifyId,
- SysUserId: params.SysUserId,
- SysUserRealName: params.SysUserRealName,
- UniqueCode: params.UniqueCode,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- MinValue: 0,
- MaxValue: 0,
- CalculateFormula: req.Formula,
- EdbType: 2,
- Sort: GetAddEdbMaxSortByClassifyId(req.ClassifyId, utils.PREDICT_EDB_INFO_TYPE),
- MoveType: 0,
- MoveFrequency: "",
- NoUpdate: 0,
- ServerUrl: "",
- EdbInfoType: 1,
- EdbNameEn: req.EdbName,
- UnitEn: req.Unit,
- LatestDate: "",
- LatestValue: 0,
- ChartImage: "",
- Calendar: "",
- }
- newEdbInfoId, tmpErr := to.Insert(edbInfo)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- edbInfo.EdbInfoId = int(newEdbInfoId)
- //关联关系
- {
- calculateMappingItem := new(EdbInfoCalculateMapping)
- calculateMappingItem.CreateTime = time.Now()
- calculateMappingItem.ModifyTime = time.Now()
- calculateMappingItem.Sort = 1
- calculateMappingItem.EdbCode = edbCode
- calculateMappingItem.EdbInfoId = edbInfo.EdbInfoId
- calculateMappingItem.FromEdbInfoId = fromEdbInfo.EdbInfoId
- calculateMappingItem.FromEdbCode = fromEdbInfo.EdbCode
- calculateMappingItem.FromEdbName = fromEdbInfo.EdbName
- calculateMappingItem.FromSource = fromEdbInfo.Source
- calculateMappingItem.FromSourceName = fromEdbInfo.SourceName
- calculateMappingItem.FromTag = ""
- calculateMappingItem.Source = edbInfo.Source
- calculateMappingItem.SourceName = edbInfo.SourceName
- _, err = to.Insert(calculateMappingItem)
- if err != nil {
- return
- }
- }
- //计算数据
- latestDateStr, latestValue, err = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
- return
- }
- // Edit 编辑
- func (obj PredictTb) Edit(params BatchSaveCalculateBatchParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
- req := params.Req
- edbInfo := params.EdbInfo
- fromEdbInfo := params.FromEdbInfo
- latestDateStr = edbInfo.LatestDate
- latestValue = edbInfo.LatestValue
- if fromEdbInfo.Frequency != req.Frequency {
- errMsg = "生成指标频度与原指标频度不同"
- err = errors.New(errMsg)
- return
- }
- if edbInfo.EdbInfoType != 1 {
- errMsg = `该指标不是预测指标`
- err = errors.New(errMsg)
- return
- }
- latestDateStr = edbInfo.LatestDate
- latestValue = edbInfo.LatestValue
- o := orm.NewOrm()
- to, err := o.Begin()
- if err != nil {
- return
- }
- defer func() {
- if err != nil {
- _ = to.Rollback()
- fmt.Println(reflect.TypeOf(obj).Name(), ";Edit,Err:"+err.Error())
- } else {
- _ = to.Commit()
- }
- }()
- tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
- //修改指标信息
- switch params.Lang {
- case utils.EnLangVersion:
- edbInfo.EdbNameEn = req.EdbName
- edbInfo.UnitEn = req.Unit
- default:
- edbInfo.EdbName = req.EdbName
- edbInfo.Unit = req.Unit
- edbInfo.EdbNameSource = req.EdbName
- }
- edbInfo.Frequency = req.Frequency
- edbInfo.ClassifyId = req.ClassifyId
- edbInfo.ModifyTime = time.Now()
- _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime", "EdbNameEn", "UnitEn")
- if err != nil {
- return
- }
- //判断计算指标是否被更换
- var existCondition string
- var existPars []interface{}
- existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
- existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
- var count int
- count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
- if err != nil {
- err = errors.New("判断指标是否改变失败,Err:" + err.Error())
- return
- }
- if count > 0 { // 指标未被替换,无需重新计算
- return
- }
- //删除,计算指标关联的,基础指标的关联关系
- sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
- _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
- if err != nil {
- return
- }
- // 删除该指标所有的同比数据
- sql = ` DELETE FROM ` + tableName + ` WHERE edb_info_id = ? `
- _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
- if err != nil {
- return
- }
- //关联关系
- {
- calculateMappingItem := &EdbInfoCalculateMapping{
- EdbInfoCalculateMappingId: 0,
- EdbInfoId: edbInfo.EdbInfoId,
- Source: obj.GetSource(),
- SourceName: obj.GetSourceName(),
- EdbCode: edbInfo.EdbCode,
- FromEdbInfoId: fromEdbInfo.EdbInfoId,
- FromEdbCode: fromEdbInfo.EdbCode,
- FromEdbName: fromEdbInfo.EdbName,
- FromSource: fromEdbInfo.Source,
- FromSourceName: fromEdbInfo.SourceName,
- FromTag: "",
- Sort: 1,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- }
- _, err = to.Insert(calculateMappingItem)
- if err != nil {
- return
- }
- }
- //计算数据
- latestDateStr, latestValue, err = obj.refresh(to, edbInfo, fromEdbInfo, edbInfo.EdbCode, "")
- return
- }
- // Refresh 刷新
- func (obj PredictTb) Refresh(params RefreshParams) (latestDateStr string, latestValue float64, err error, errMsg string) {
- calculateMapping, err := GetEdbInfoCalculateMappingDetail(params.EdbInfo.EdbInfoId)
- if err != nil {
- return
- }
- fromEdbInfo, err := GetEdbInfoById(calculateMapping.FromEdbInfoId)
- if err != nil {
- errMsg = "GetEdbInfoById Err:" + err.Error()
- return
- }
- o := orm.NewOrm()
- to, err := o.Begin()
- if err != nil {
- return
- }
- defer func() {
- if err != nil {
- _ = to.Rollback()
- fmt.Println(reflect.TypeOf(obj).Name(), ";Refresh,Err:"+err.Error())
- } else {
- _ = to.Commit()
- }
- }()
- // 计算数据
- latestDateStr, latestValue, err = obj.refresh(to, params.EdbInfo, fromEdbInfo, params.EdbInfo.EdbCode, params.StartDate)
- return
- }
- // GetSource 获取来源编码id
- func (obj PredictTb) GetSource() int {
- return utils.DATA_SOURCE_PREDICT_CALCULATE_TBZ
- }
- // GetSourceName 获取来源名称
- func (obj PredictTb) GetSourceName() string {
- return utils.DATA_SOURCE_NAME_PREDICT_CALCULATE_TBZ
- }
- func (obj PredictTb) refresh(to orm.TxOrmer, edbInfo, fromEdbInfo *EdbInfo, edbCode, startDate string) (latestDateStr string, latestValue float64, err error) {
- edbInfoId := edbInfo.EdbInfoId
- dataTableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
- edbInfoIdStr := strconv.Itoa(edbInfoId)
- // 获取关联指标数据
- dataList, err := GetPredictEdbDataListAllByStartDate(fromEdbInfo, 1, startDate)
- if err != nil {
- return
- }
- latestDateStr = fromEdbInfo.LatestDate
- //计算数据
- var dateArr []string
- dataMap := make(map[string]*EdbInfoSearchData)
- for _, v := range dataList {
- dateArr = append(dateArr, v.DataTime)
- dataMap[v.DataTime] = v
- }
- //获取指标所有数据
- existDataList := make([]*EdbData, 0)
- fmt.Println("dataTableName:", dataTableName)
- sql := `SELECT * FROM %s WHERE edb_info_id=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, edbInfoId).QueryRows(&existDataList)
- if err != nil {
- return
- }
- existDataMap := make(map[string]string)
- removeDataTimeMap := make(map[string]int) //需要移除的日期数据
- for _, v := range existDataList {
- existDataMap[v.DataTime] = v.Value
- removeDataTimeMap[v.DataTime] = 1
- }
- fmt.Println("existDataMap:", existDataMap)
- addSql := ` INSERT INTO edb_data_predict_calculate_tbz (edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
- var isAdd bool
- existAddDataMap := make(map[string]string)
- for _, av := range dateArr {
- //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该日期
- delete(removeDataTimeMap, av)
- currentItem, ok := dataMap[av]
- if !ok || currentItem == nil {
- continue
- }
- //当前日期
- currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- //上一年的日期
- preDate := currentDate.AddDate(-1, 0, 0)
- preDateStr := preDate.Format(utils.FormatDate)
- if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
- //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- if existVal, ok := existDataMap[av]; !ok {
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, tmpErr := decimal.NewFromString(existVal)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existStr := existValDecimal.String()
- if existStr != val {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, val, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- continue
- } else {
- if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
- for i := 0; i <= 35; i++ {
- nextDateDay := preDate.AddDate(0, 0, i)
- nextDateDayStr := nextDateDay.Format(utils.FormatDate)
- if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- if existVal, ok := existDataMap[av]; !ok {
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, tmpErr := decimal.NewFromString(existVal)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existStr := existValDecimal.String()
- if existStr != val {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, val, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- break
- } else {
- preDateDay := preDate.AddDate(0, 0, -i)
- preDateDayStr := preDateDay.Format(utils.FormatDate)
- if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- if existVal, ok := existDataMap[av]; !ok {
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, tmpErr := decimal.NewFromString(existVal)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existStr := existValDecimal.String()
- if existStr != val {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, val, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- break
- }
- }
- }
- } else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
- if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- if existVal, ok := existDataMap[av]; !ok {
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, tmpErr := decimal.NewFromString(existVal)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existStr := existValDecimal.String()
- if existStr != val {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, val, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- break
- }
- } else {
- nextDateDay := preDate.AddDate(0, 0, 1)
- nextDateDayStr := nextDateDay.Format(utils.FormatDate)
- preDateDay := preDate.AddDate(0, 0, -1)
- preDateDayStr := preDateDay.Format(utils.FormatDate)
- for i := 0; i < 35; i++ {
- if i >= 1 {
- nextDateDay = nextDateDay.AddDate(0, 0, i)
- nextDateDayStr = nextDateDay.Format(utils.FormatDate)
- }
- if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- if existVal, ok := existDataMap[av]; !ok {
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, tmpErr := decimal.NewFromString(existVal)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existStr := existValDecimal.String()
- if existStr != val {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, val, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- break
- } else {
- if i >= 1 {
- preDateDay = preDateDay.AddDate(0, 0, -i)
- preDateDayStr = preDateDay.Format(utils.FormatDate)
- }
- if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- if existVal, ok := existDataMap[av]; !ok {
- if _, existOk := existAddDataMap[av]; !existOk {
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existAddDataMap[av] = av
- } else {
- existValDecimal, tmpErr := decimal.NewFromString(existVal)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- existStr := existValDecimal.String()
- if existStr != val {
- sql := ` UPDATE %s SET value=?,modify_time=NOW() WHERE edb_info_id=? AND data_time=? `
- sql = fmt.Sprintf(sql, dataTableName)
- _, err = to.Raw(sql, val, edbInfoId, av).Exec()
- if err != nil {
- return
- }
- }
- }
- break
- }
- }
- }
- }
- }
- }
- //删除已经不存在的指标数据(由于该指标当日的数据删除了)
- {
- removeDateList := make([]string, 0)
- for dateTime := range removeDataTimeMap {
- removeDateList = append(removeDateList, dateTime)
- }
- removeNum := len(removeDateList)
- if removeNum > 0 {
- sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, dataTableName)
- _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
- if err != nil {
- fmt.Println(reflect.TypeOf(obj).Name(), " add data ;delete Err", err.Error())
- err = fmt.Errorf("删除不存在的指标数据失败,Err:" + err.Error())
- return
- }
- }
- }
- // 批量插入
- if isAdd {
- addSql = strings.TrimRight(addSql, ",")
- _, err = to.Raw(addSql).Exec()
- if err != nil {
- return
- }
- }
- //确定实际数据的最终值
- {
- finalLast, tmpErr := GetFinalLastByTo(to, edbInfoId, edbInfo.Source, edbInfo.SubSource, fromEdbInfo.LatestDate)
- if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
- return
- }
- if tmpErr == nil {
- latestDateStr = finalLast.DataTime
- latestValue = finalLast.Value
- }
- }
- return
- }
- // SavePredictCalculateTbz 新增/编辑 预测同比指标
- 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) {
- o := orm.NewOrm()
- to, err := o.Begin()
- if err != nil {
- return
- }
- defer func() {
- if err != nil {
- fmt.Println("AddCalculateTbz,Err:" + err.Error())
- _ = to.Rollback()
- } else {
- _ = to.Commit()
- }
- }()
- if reqEdbInfoId <= 0 {
- edbInfo = &EdbInfo{
- //EdbInfoId: 0,
- EdbInfoType: 1,
- SourceName: "预测同比",
- Source: utils.DATA_SOURCE_PREDICT_CALCULATE_TBZ,
- EdbCode: edbCode,
- EdbName: edbName,
- EdbNameSource: edbName,
- Frequency: frequency,
- Unit: unit,
- //StartDate: "",
- //EndDate: "",
- ClassifyId: classifyId,
- SysUserId: sysUserId,
- SysUserRealName: sysUserRealName,
- UniqueCode: uniqueCode,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- MinValue: 0,
- MaxValue: 0,
- CalculateFormula: formula,
- EdbType: 2,
- Sort: 0,
- MoveType: 0,
- MoveFrequency: "",
- NoUpdate: 0,
- ServerUrl: "",
- EdbNameEn: "",
- UnitEn: "",
- LatestDate: "",
- LatestValue: 0,
- ChartImage: "",
- }
- newEdbInfoId, tmpErr := to.Insert(edbInfo)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- edbInfo.EdbInfoId = int(newEdbInfoId)
- // 添加关联关系
- {
- calculateMappingItem := &EdbInfoCalculateMapping{
- EdbInfoCalculateMappingId: 0,
- EdbInfoId: edbInfo.EdbInfoId,
- Source: edbInfo.Source,
- SourceName: edbInfo.SourceName,
- EdbCode: edbCode,
- FromEdbInfoId: fromEdbInfo.EdbInfoId,
- FromEdbCode: fromEdbInfo.EdbCode,
- FromEdbName: fromEdbInfo.EdbName,
- FromSource: fromEdbInfo.Source,
- FromSourceName: fromEdbInfo.SourceName,
- FromTag: "",
- Sort: 1,
- CreateTime: time.Now(),
- ModifyTime: time.Now(),
- }
- _, err = to.Insert(calculateMappingItem)
- if err != nil {
- return
- }
- }
- } else {
- edbInfo, err = GetEdbInfoById(reqEdbInfoId)
- if err != nil {
- if err.Error() == utils.ErrNoRow() {
- errMsg = `获取指标信息失败`
- }
- return
- }
- if edbInfo.EdbInfoType != 1 {
- errMsg = `该指标不是预测指标`
- err = errors.New(errMsg)
- return
- }
- latestDateStr = edbInfo.LatestDate
- latestValue = edbInfo.LatestValue
- //修改指标信息
- edbInfo.EdbName = edbName
- edbInfo.EdbNameSource = edbName
- edbInfo.Frequency = frequency
- edbInfo.Unit = unit
- edbInfo.ClassifyId = classifyId
- edbInfo.ModifyTime = time.Now()
- _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "ModifyTime")
- if err != nil {
- return
- }
- //判断计算指标是否被更换
- var existCondition string
- var existPars []interface{}
- existCondition += " AND edb_info_id=? AND from_edb_info_id=? "
- existPars = append(existPars, edbInfo.EdbInfoId, fromEdbInfo.EdbInfoId)
- var count int
- count, err = GetEdbInfoCalculateCountByCondition(existCondition, existPars)
- if err != nil {
- err = errors.New("判断指标是否改变失败,Err:" + err.Error())
- return
- }
- if count > 0 { // 指标未被替换,无需重新计算
- return
- }
- //删除,计算指标关联的,基础指标的关联关系
- sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? `
- _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
- if err != nil {
- return
- }
- // 删除该指标所有的同比数据
- dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_PREDICT_CALCULATE_TBZ, utils.DATA_SUB_SOURCE_EDB)
- deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
- deleteSql = fmt.Sprintf(deleteSql, dataTableName)
- _, err = to.Raw(deleteSql, edbInfo.EdbInfoId).Exec()
- if err != nil {
- return
- }
- }
- edbInfoIdStr := strconv.Itoa(edbInfo.EdbInfoId)
- // 获取源指标数据
- dataList, err := GetPredictEdbDataListAll(fromEdbInfo, 0)
- if err != nil {
- return
- }
- latestDateStr = fromEdbInfo.LatestDate
- // 计算数据
- var dateArr []string
- dataMap := make(map[string]*EdbInfoSearchData)
- for _, v := range dataList {
- dateArr = append(dateArr, v.DataTime)
- dataMap[v.DataTime] = v
- }
- addSql := ` INSERT INTO edb_data_predict_calculate_tbz(edb_info_id,edb_code,data_time,value,create_time,modify_time,data_timestamp) values `
- var isAdd bool
- existMap := make(map[string]string)
- for _, av := range dateArr {
- //fmt.Println(ak, av)
- currentItem := dataMap[av]
- if currentItem != nil {
- //当前日期
- currentDate, tmpErr := time.ParseInLocation(utils.FormatDate, av, time.Local)
- if tmpErr != nil {
- err = tmpErr
- return
- }
- //上一年的日期
- preDate := currentDate.AddDate(-1, 0, 0)
- preDateStr := preDate.Format(utils.FormatDate)
- if findItem, ok := dataMap[preDateStr]; ok { //上一年同期找到
- //dataTime, _ := time.ParseInLocation(utils.FormatDate, date, time.Local)
- if _, ok := existMap[edbCode+av]; !ok {
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- utils.FileLog.Info("同期找到:" + av + ";" + preDateStr)
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existMap[edbCode+av] = av
- } else {
- if fromEdbInfo.Frequency == "月度" { //向上和向下,各找一个月
- nextDateDay := preDate
- preDateDay := preDate
- for i := 0; i <= 35; i++ {
- nextDateDayStr := nextDateDay.Format(utils.FormatDate)
- if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
- if _, ok := existMap[edbCode+av]; !ok {
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existMap[edbCode+av] = av
- break
- } else {
- preDateDayStr := preDateDay.Format(utils.FormatDate)
- if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
- if _, ok := existMap[edbCode+av]; !ok {
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existMap[edbCode+av] = av
- break
- }
- }
- nextDateDay = nextDateDay.AddDate(0, 0, 1)
- preDateDay = preDateDay.AddDate(0, 0, -1)
- }
- } else if fromEdbInfo.Frequency == "季度" || fromEdbInfo.Frequency == "年度" {
- if findItem, ok := dataMap[preDateStr]; ok { //上一年同期->下一个月找到
- if _, ok := existMap[edbCode+av]; !ok {
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existMap[edbCode+av] = av
- break
- }
- } else {
- nextDateDay := preDate
- preDateDay := preDate
- for i := 0; i < 35; i++ {
- nextDateDayStr := nextDateDay.Format(utils.FormatDate)
- if findItem, ok := dataMap[nextDateDayStr]; ok { //上一年同期->下一个月找到
- if _, ok := existMap[edbCode+av]; !ok {
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existMap[edbCode+av] = av
- break
- } else {
- preDateDayStr := preDateDay.Format(utils.FormatDate)
- if findItem, ok := dataMap[preDateDayStr]; ok { //上一年同期->上一个月找到
- if _, ok := existMap[edbCode+av]; !ok {
- timestamp := currentDate.UnixNano() / 1e6
- timestampStr := fmt.Sprintf("%d", timestamp)
- val := TbzDiv(currentItem.Value, findItem.Value)
- addSql += GetAddSql(edbInfoIdStr, edbCode, av, timestampStr, val)
- isAdd = true
- // 实际数据的值
- if fromEdbInfo.LatestDate == av {
- latestValueDecimal, tmpErr := decimal.NewFromString(val)
- if tmpErr != nil {
- return
- }
- latestValue, _ = latestValueDecimal.Truncate(4).Float64() //保留4位小数
- }
- }
- existMap[edbCode+av] = av
- break
- } else {
- //fmt.Println("pre not find:", preDateStr, "i:", i)
- }
- }
- nextDateDay = nextDateDay.AddDate(0, 0, 1)
- preDateDay = preDateDay.AddDate(0, 0, -1)
- }
- }
- }
- }
- }
- if isAdd {
- addSql = strings.TrimRight(addSql, ",")
- _, err = to.Raw(addSql).Exec()
- if err != nil {
- return
- }
- }
- return
- }
|