package controllers import ( "encoding/json" "eta_gn/eta_api/models" "eta_gn/eta_api/models/data_manage" "eta_gn/eta_api/models/system" "eta_gn/eta_api/services/alarm_msg" "eta_gn/eta_api/services/data" "eta_gn/eta_api/utils" "fmt" "os" "path/filepath" "reflect" "sort" "strconv" "strings" "time" "github.com/rdlucklib/rdluck_tools/paging" "github.com/shopspring/decimal" "github.com/tealeg/xlsx" ) type TargetController struct { BaseAuthController } type TargetCommonController struct { BaseCommonController } // @router /data/list [get] func (this *TargetController) DataList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() pageSize, _ := this.GetInt("PageSize") currentIndex, _ := this.GetInt("CurrentIndex") keyWord := this.GetString("KeyWord") startDate := this.GetString("StartDate") endDate := this.GetString("EndDate") frequency := this.GetString("Frequency") tradeCode := this.GetString("TradeCode") classifyId, _ := this.GetInt("ClassifyId") //分类 var startSize int if pageSize <= 0 { pageSize = utils.PageSize20 } if currentIndex <= 0 { currentIndex = 1 } startSize = utils.StartIndex(currentIndex, pageSize) var condition string var pars []interface{} if keyWord != "" { condition += ` AND a.SEC_NAME LIKE ? ` pars = utils.GetLikeKeywordPars(pars, keyWord, 1) } if startDate != "" { condition += ` AND c.DT >= ? ` pars = append(pars, startDate) } if endDate != "" { condition += ` AND c.DT <= ? ` pars = append(pars, endDate) } if frequency != "" { condition += ` AND a.frequency = ? ` pars = append(pars, frequency) } if classifyId > 0 { condition += ` AND a.classify_id = ? ` pars = append(pars, classifyId) } if tradeCode != "" { condition += ` AND c.TRADE_CODE = ? ` pars = append(pars, tradeCode) } total, err := models.GetDataListCount(condition, pars) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } list, err := models.GetDataList(condition, pars, startSize, pageSize) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } page := paging.GetPaging(currentIndex, pageSize, total) resp := new(models.DataListResp) resp.Paging = page if len(list) <= 0 { list = make([]*models.DataList, 0) } resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /data/add [post] func (this *TargetController) DataAdd() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.DataAddReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.TradeCode == "" { br.Msg = "指标编码不可为空!" return } if req.CreateDate == "" { br.Msg = "请选择日期" return } item, err := models.GetDataInfo(req.TradeCode, req.CreateDate) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if item != nil { br.Msg = "该指标当前日期下,数据已录入" return } edbdata := new(models.Edbdata) edbdata.TradeCode = req.TradeCode edbdata.Dt = req.CreateDate edbdata.Close = req.Close edbdata.ModifyTime = time.Now() _, err = models.AddEdbdata(edbdata) if err != nil { br.Msg = "新增失败" br.ErrMsg = "新增失败,Err:" + err.Error() return } go func() { record := &models.EdbinfoOpRecord{ TradeCode: edbdata.TradeCode, Remark: "更新数据", UserId: this.SysUser.AdminId, UserName: this.SysUser.RealName, CreateTime: time.Now(), } data.ModifyManualEdbMaxMinDate(edbdata.TradeCode) _ = record.Create() if utils.Re == nil { err := utils.Rc.LPush(utils.CACHE_IMPORT_MANUAL_DATA, req.TradeCode) if err != nil { fmt.Println("CACHE_IMPORT_MANUAL_DATA LPush Err:" + err.Error()) } } }() br.Ret = 200 br.Success = true br.Msg = "新增成功" } // @router /data/edit [post] func (this *TargetController) DataEdit() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.DataEditReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.TradeCode == "" { br.Msg = "指标编码不可为空!" return } if req.CreateDate == "" { br.Msg = "请选择日期" return } close := "" loc := reflect.ValueOf(req.Close).Kind().String() if loc == "string" { close = req.Close.(string) } else if loc == "int" { closeInt := req.Close.(int) close = strconv.Itoa(closeInt) } else if loc == "float64" { close64 := req.Close.(float64) close = strconv.FormatFloat(close64, 'g', 30, 64) } else { close = "" } edbdata := new(models.Edbdata) edbdata.TradeCode = req.TradeCode edbdata.Dt = req.CreateDate edbdata.Close = close edbdata.ModifyTime = time.Now() if req.OldCreateDate == "" { item, err := models.GetDataInfo(req.TradeCode, req.CreateDate) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if item == nil { //新增 _, err = models.AddEdbdata(edbdata) if err != nil { br.Msg = "新增失败" br.ErrMsg = "新增失败,Err:" + err.Error() return } } else { //修改 err = models.EditEdbdata(edbdata) if err != nil { br.Msg = "编辑失败" br.ErrMsg = "编辑失败,Err:" + err.Error() return } } } else { if req.CreateDate == req.OldCreateDate { //修改 err = models.EditEdbdata(edbdata) if err != nil { br.Msg = "编辑失败" br.ErrMsg = "编辑失败,Err:" + err.Error() return } } else { item, err := models.GetDataInfo(req.TradeCode, req.CreateDate) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if item == nil { _, err = models.AddEdbdata(edbdata) if err != nil { br.Msg = "新增失败" br.ErrMsg = "新增失败,Err:" + err.Error() return } } else { err = models.EditEdbdata(edbdata) if err != nil { br.Msg = "编辑失败" br.ErrMsg = "编辑失败,Err:" + err.Error() return } } oldItem, err := models.GetDataInfo(req.TradeCode, req.OldCreateDate) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if oldItem != nil { record := new(models.EdbdataDeleteRecord) record.TradeCode = oldItem.TradeCode record.Dt = oldItem.Dt record.Close = oldItem.Close record.ModifyTime = oldItem.ModifyTime record.CreateTime = time.Now() record.SysUserId = this.SysUser.AdminId _, err = models.AddEdbdataDeleteRecord(record) if err != nil { br.Msg = "编辑失败" br.ErrMsg = "新增删除记录失败,Err:" + err.Error() return } models.DeleteEdbData(req.TradeCode, req.OldCreateDate) } } } { go func() { data.ModifyManualEdbMaxMinDate(req.TradeCode) if utils.Re == nil { err := utils.Rc.LPush(utils.CACHE_IMPORT_MANUAL_DATA, req.TradeCode) if err != nil { fmt.Println("CACHE_IMPORT_MANUAL_DATA LPush Err:" + err.Error()) } } }() } br.Ret = 200 br.Success = true br.Msg = "编辑成功" } // @router /data/batch_edit [post] func (this *TargetController) BatchDataEdit() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.BatchDataEditReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.CreateDate == req.OldCreateDate { //修改 br.Msg = "开始日期与结束日期一致!" return } edbDataEditList := make([]data.EdbDataEdit, 0) for _, trade := range req.List { if trade.TradeCode == "" { br.Msg = "指标编码不可为空!" return } close := "" loc := reflect.ValueOf(trade.Close).Kind().String() if loc == "string" { close = trade.Close.(string) } else if loc == "int" { closeInt := trade.Close.(int) close = strconv.Itoa(closeInt) } else if loc == "float64" { close64 := trade.Close.(float64) close = strconv.FormatFloat(close64, 'g', 30, 64) } else { close = "" } edbDataEdit := data.EdbDataEdit{ OldCreateDate: req.OldCreateDate, CreateDate: req.CreateDate, TradeCode: trade.TradeCode, Close: close, } edbDataEditList = append(edbDataEditList, edbDataEdit) } failEdbDataList, err := data.BatchEdbData(req.OldCreateDate, req.CreateDate, edbDataEditList, this.SysUser.AdminId) if err != nil { br.Msg = "批量修改失败" br.ErrMsg = "批量修改失败:" + err.Error() return } br.Ret = 200 br.Success = true br.Data = failEdbDataList br.Msg = "编辑成功" } // @router /target/list [get] func (this *TargetController) TargetList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请登录" br.Ret = 408 return } resp := new(models.TargetListResp) pageSize, _ := this.GetInt("PageSize") currentIndex, _ := this.GetInt("CurrentIndex") keyWord := this.GetString("KeyWord") startDate := this.GetString("StartDate") endDate := this.GetString("EndDate") frequency := this.GetString("Frequency") classifyId, _ := this.GetInt("ClassifyId") //分类 var startSize int if pageSize <= 0 { pageSize = utils.PageSize20 } if currentIndex <= 0 { currentIndex = 1 } startSize = utils.StartIndex(currentIndex, pageSize) var condition string var pars []interface{} userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } classifyIdStrList, err := data.GetEdbClassifyListByAdminId(int64(userId)) if err != nil { br.Msg = "获取分类数据失败" return } total := 0 list := make([]*models.EdbinfoItem, 0) if len(classifyIdStrList) > 0 { condition += ` AND a.classify_id in (` + strings.Join(classifyIdStrList, ",") + `) ` if keyWord != "" { condition += ` AND (a.SEC_NAME LIKE '%` + keyWord + `%' or a.TRADE_CODE LIKE '%` + keyWord + `%' )` } if startDate != "" { startDate = startDate + " 00:00:00" condition += ` AND a.create_date >= ? ` pars = append(pars, startDate) } if endDate != "" { endDate = endDate + " 23:59:59" condition += ` AND a.create_date <= ? ` pars = append(pars, endDate) } if frequency != "" { condition += ` AND a.frequency = ? ` pars = append(pars, frequency) } if classifyId > 0 { condition += ` AND a.classify_id = ? ` pars = append(pars, classifyId) } mobile := sysUser.Mobile total, err = models.GetEdbinfoListCount(condition, pars, mobile, sysUser.RoleType) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } tmpList, err := models.GetEdbinfoItemList(condition, pars, startSize, pageSize, mobile, sysUser.RoleType) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } if len(tmpList) <= 0 { list = make([]*models.EdbinfoItem, 0) } else { list = tmpList } systemUserMap := make(map[int]string) for k, v := range list { userName, ok := systemUserMap[v.UserId] if ok == false { systemUser, _ := system.GetSysAdminById(v.UserId) if systemUser != nil { userName = systemUser.RealName } else { userName = `无` } systemUserMap[v.UserId] = userName } list[k].UserName = userName } } page := paging.GetPaging(currentIndex, pageSize, total) resp.Paging = page resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /target/add [post] func (this *TargetController) TargetAdd() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.EdbinfoAddReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } tradeCode, err := models.GetMaxTradeCode() if err != nil { br.Msg = "获取数据失败" br.ErrMsg = "获取最大交易编码失败,Err:" + err.Error() return } maxTradeCode, err := utils.GetMaxTradeCode(tradeCode) if err != nil { br.Msg = "数据异常" br.ErrMsg = "获取编码信息失败,Err:" + err.Error() return } if maxTradeCode == "" { br.Msg = "编码为空,请联系技术" br.ErrMsg = "编码为空,请联系技术" return } if req.SecName == "" { br.Msg = "指标名称不能为空" return } item, err := models.GetEdbinfoBySecName(req.SecName) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if item != nil { br.Msg = "指标名称已存在" return } err = models.AddEdbinfo(maxTradeCode, req.SecName, req.Unit, "手动", req.Frequency, req.NoticeTime, req.ClassifyId, sysUser.AdminId, sysUser.RealName) if err != nil { br.Msg = "新增失败" br.ErrMsg = "新增失败,Err:" + err.Error() return } err = models.AddEdbinfoUser(maxTradeCode, sysUser.Mobile) if err != nil { br.Msg = "新增失败" br.ErrMsg = "新增失败,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "新增成功" } // @router /target/edit [post] func (this *TargetController) TargetEdit() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.EdbinfoEditReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } if req.TradeCode == "" { br.Msg = "数据异常" br.ErrMsg = "最大编码为空" return } if req.SecName == "" { br.Msg = "指标名称不能为空" return } item, err := models.GetEdbinfoBySecName(req.SecName) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if item != nil { if req.TradeCode != item.TradeCode { br.Msg = "指标名称已存在" return } } err = models.EditEdbinfo(req.TradeCode, req.SecName, req.Unit, req.Frequency, req.NoticeTime, req.ClassifyId) if err != nil { br.Msg = "编辑失败" br.ErrMsg = "编辑失败,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "编辑成功" } // @router /target/search [get] func (this *TargetController) TargetSearch() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请登录" br.Ret = 408 return } classifyId, _ := this.GetInt("ClassifyId") keyWord := this.GetString("KeyWord") list, err := models.SearchTargetEntry(classifyId, keyWord) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } resp := new(models.SearchTargetListResp) resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /classify [get] func (this *TargetController) ClassifyList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请登录" br.Ret = 408 return } var wxUserId int64 wxUserId = int64(sysUser.AdminId) if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { wxUserId = 0 } list, err := models.GetEdbdataClassify(wxUserId) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } classifyIdStrList := make([]string, 0) for _, classifyList := range list { if classifyList.Child != nil { for _, classify := range classifyList.Child { classifyIdStrList = append(classifyIdStrList, strconv.Itoa(classify.ClassifyId)) } } } if len(classifyIdStrList) > 0 { edbInfoGroupCountList, err := models.GetEdbInfoGroupCountByClassifyIds(strings.Join(classifyIdStrList, ",")) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取分类下有数据的指标数量失败,Err:" + err.Error() return } edbInfoGroupCountMap := make(map[int]int) for _, edbInfoGroupCount := range edbInfoGroupCountList { edbInfoGroupCountMap[edbInfoGroupCount.ClassifyId] = edbInfoGroupCount.Count } for _, classifyList := range list { classifyList.UniqueCode = utils.MD5(fmt.Sprint(classifyList.ClassifyId)) if classifyList.Child != nil { for _, classify := range classifyList.Child { if total, ok := edbInfoGroupCountMap[classify.ClassifyId]; ok { classify.EdbInfoTotal = total classify.UniqueCode = utils.MD5(fmt.Sprint(classify.ClassifyId)) } } } } } resp := new(models.EdbdataClassifyResp) resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /template [get] func (this *TargetCommonController) TemplateDownload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() source, _ := this.GetInt("Source") switch source { case 2: this.Ctx.Output.Download("./static/template/导入模板2.xlsx", "数据导入模板2.xlsx") default: this.Ctx.Output.Download("./static/template/导入模板1.xlsx", "数据导入模板1.xlsx") } br.Ret = 200 br.Success = true br.Msg = "下载成功" } // @router /template/en [get] func (this *TargetCommonController) TemplateDownloadEn() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() this.Ctx.Output.Download("./static/Data Import Template.xlsx", "Data Import Template.xlsx") br.Ret = 200 br.Success = true br.Msg = "下载成功" } // @router /import/failList [get] func (this *TargetController) ImportFailListDownload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } item, err := models.GetFailList(sysUser.AdminId) if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } xlsxFile := xlsx.NewFile() SheetName := "导入失败数据" if this.Lang == utils.EnLangVersion { SheetName = "Import Fail List" } sheet, err := xlsxFile.AddSheet(SheetName) headRow := sheet.AddRow() headRow.AddCell().SetValue("品种/Variety") headRow.AddCell().SetValue("指标名称/Indicator Name") headRow.AddCell().SetValue("指标日期/Indicator Date") headRow.AddCell().SetValue("值/Value") headRow.AddCell().SetValue("频度/Frequency") headRow.AddCell().SetValue("单位/Unit") headRow.AddCell().SetValue("备注/Note") for _, v := range item { row := sheet.AddRow() row.AddCell().SetValue(v.ClassifyName) row.AddCell().SetValue(v.SecName) row.AddCell().SetValue(v.CreateDate) row.AddCell().SetString(v.Close) row.AddCell().SetValue(v.Frequency) row.AddCell().SetValue(v.Unit) row.AddCell().SetValue(v.Remark) } fileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx" savePath := "./static/" + fileName err = xlsxFile.Save(savePath) if err != nil { br.Msg = "文件保存失败" br.ErrMsg = "文件保存失败,Err:" + err.Error() return } defer func() { os.Remove(savePath) }() finalFileName := "失败列表.xlsx" if this.Lang == utils.EnLangVersion { finalFileName = "Failure List.xlsx" } this.Ctx.Output.Download(savePath, finalFileName) } // @router /export/dataList [get] func (this *TargetController) ExportDataList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } keyWord := this.GetString("KeyWord") startDate := this.GetString("StartDate") endDate := this.GetString("EndDate") frequency := this.GetString("Frequency") classifyId, _ := this.GetInt("ClassifyId") //分类 mobile := this.GetString("Mobile") //分类 tradeCode := this.GetString("TradeCode") //指标唯一编码 var condition string var pars []interface{} if keyWord != "" { condition += ` AND a.SEC_NAME LIKE '%` + keyWord + `%'` } if tradeCode != "" { condition += ` AND a.TRADE_CODE = ? ` pars = append(pars, tradeCode) } if startDate != "" { condition += ` AND c.DT >= ? ` pars = append(pars, startDate) } if endDate != "" { condition += ` AND c.DT <= ? ` pars = append(pars, endDate) } if frequency != "" { condition += ` AND a.frequency = ? ` pars = append(pars, frequency) } permissionUserId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { permissionUserId = 0 } childClassifyIdList := make([]int, 0) if classifyId > 0 { classifyList, err := models.GetEdbdataClassify(int64(permissionUserId)) if err != nil { return } var isParent bool for _, v := range classifyList { if v.ClassifyId == classifyId { isParent = true childClassifyIdList = append(childClassifyIdList, v.ClassifyId) if v.Child != nil && len(v.Child) > 0 { for _, vv := range v.Child { childClassifyIdList = append(childClassifyIdList, vv.ClassifyId) } } break } } if !isParent { childClassifyIdList = append(childClassifyIdList, classifyId) } } num := len(childClassifyIdList) condition += ` AND a.classify_id in (` + utils.GetOrmInReplace(num) + `) ` pars = append(pars, childClassifyIdList) if mobile != "" { condition += ` AND d.mobile=? ` pars = append(pars, mobile) } userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } classifyIdStrList, err := data.GetEdbClassifyListByAdminId(int64(userId)) if err != nil { br.Msg = "获取分类数据失败" return } dir, _ := os.Executable() exPath := filepath.Dir(dir) downloadFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx" xlsxFile := xlsx.NewFile() if err != nil { br.Msg = "生成文件失败" br.ErrMsg = "生成文件失败" return } var frequencies []string if len(childClassifyIdList) > 0 { frequencies, err = models.GetEdbDataFrequencyByClassifyIdList(childClassifyIdList) if err != nil { br.Msg = "查询频度失败" br.ErrMsg = "查询频度失败" return } } else if tradeCode != `` { manualEdb, err := models.GetEdbinfoByTradeCode(tradeCode) if err != nil { br.Msg = "查询指标信息失败" br.ErrMsg = "查询指标信息失败,err:" + err.Error() return } frequencies = append(frequencies, manualEdb.Frequency) } else if keyWord != `` { frequencies, err = models.GetEdbDataFrequencyByKeyord(keyWord) if err != nil { br.Msg = "查询频度失败" br.ErrMsg = "查询频度失败" return } } else { frequencies = append(frequencies, `日度`, `周度`, `月度`, `季度`, `半年度`, `年度`) } fileName := `手工数据` if frequencies == nil { sheet, err := xlsxFile.AddSheet("无数据") if err != nil { br.Msg = "新增Sheet失败" br.ErrMsg = "新增Sheet失败,Err:" + err.Error() return } rowSecName := sheet.AddRow() celSecName := rowSecName.AddCell() celSecName.SetValue("") } for _, frequency := range frequencies { secNameList := make([]*models.EdbdataExportList, 0) if len(classifyIdStrList) > 0 { newCondition := condition newCondition += ` AND a.classify_id in (` + strings.Join(classifyIdStrList, ",") + `) ` newCondition += ` AND a.frequency = ? ` pars := append(pars, frequency) tmpSecNameList, err := models.GetEdbdataSecName(newCondition, pars) if err != nil { br.Msg = "获取数据失败" br.ErrMsg = "获取数据失败,Err:" + err.Error() return } secNameList = tmpSecNameList } var sheet *xlsx.Sheet if len(secNameList) > 0 { sheet, err = xlsxFile.AddSheet(frequency) if err != nil { br.Msg = "新增Sheet失败" br.ErrMsg = "新增Sheet失败,Err:" + err.Error() return } fileName = secNameList[0].ClassifyName } else { continue } rowSecName := sheet.AddRow() celSecName := rowSecName.AddCell() celSecName.SetValue("指标名称") rowFrequency := sheet.AddRow() celFrequency := rowFrequency.AddCell() celFrequency.SetValue("频率") rowUnit := sheet.AddRow() celUnit := rowUnit.AddCell() celUnit.SetValue("单位") rowModifyDate := sheet.AddRow() rowModifyCell := rowModifyDate.AddCell() rowModifyCell.SetValue("更新时间") dataMap := make(map[string]map[string]*models.EdbdataItem) var tradeCodeList []string for _, v := range secNameList { cellSenName := rowSecName.AddCell() cellSenName.SetValue(v.SecName) celFrequency := rowFrequency.AddCell() celFrequency.SetValue(v.Frequency) celUnit := rowUnit.AddCell() celUnit.SetValue(v.Unit) rowModifyCell := rowModifyDate.AddCell() rowModifyCell.SetValue(v.Dt) tradeCodeList = append(tradeCodeList, v.TradeCode) items, err := models.GetEdbdataAllByTradeCode(v.TradeCode) if err != nil && !utils.IsErrNoRow(err) { br.ErrMsg = "GetEdbdataAllByTradeCode,Err:" + err.Error() br.Msg = "获取数据失败" return } for _, item := range items { if dataMap[item.TradeCode] == nil { dataMap[item.TradeCode] = make(map[string]*models.EdbdataItem) } dataMap[item.TradeCode][item.Dt] = item fmt.Println(item.TradeCode, item.Dt) } } tradeCodeStr := strings.Join(tradeCodeList, "','") tradeCodeStr = "'" + tradeCodeStr + "'" dateList, err := models.GetEdbdataList(tradeCodeStr) if err != nil { br.Msg = "获取数据失败" br.ErrMsg = "获取数据失败,Err:" + err.Error() return } for _, n := range dateList { rowData := sheet.AddRow() celDate := rowData.AddCell() celDate.SetValue(n.Dt) for _, m := range secNameList { celData := rowData.AddCell() fmt.Println(m.TradeCode) fmt.Println(n.Dt) if dataMap[m.TradeCode][n.Dt] != nil { celData.SetValue(dataMap[m.TradeCode][n.Dt].Close) } } } } err = xlsxFile.Save(downloadFilePath) if err != nil { sheet, err := xlsxFile.AddSheet("无数据") if err != nil { br.Msg = "新增Sheet失败" br.ErrMsg = "新增Sheet失败,Err:" + err.Error() return } rowSecName := sheet.AddRow() celSecName := rowSecName.AddCell() celSecName.SetValue("") err = xlsxFile.Save(downloadFilePath) if err != nil { br.Msg = "保存文件失败" br.ErrMsg = "保存文件失败" return } } defer func() { os.Remove(downloadFilePath) }() fileName += time.Now().Format("06.01.02") + `.xlsx` //文件名称 this.Ctx.Output.Download(downloadFilePath, fileName) br.Ret = 200 br.Success = true br.Msg = "success" } // @router /dataList [get] func (this *TargetCommonController) DataList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() br.Msg = "成功" br.Ret = 200 } // @router /data/delete [post] func (this *TargetController) DataDelete() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.DataDeleteReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } if req.TradeCode == "" { br.Msg = "指标编码不可为空" br.ErrMsg = "指标编码不可为空" return } if req.CreateDate == "" { br.Msg = "数据录入日期不可为空" return } item, err := models.GetDataInfo(req.TradeCode, req.CreateDate) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取信息失败!" br.ErrMsg = "获取信息失败,Err:" + err.Error() return } if item == nil { br.Msg = "数据不存在" return } err = models.DataDelete(req.TradeCode, req.CreateDate, item.Close, item.ModifyTime, sysUser.AdminId) if err != nil { br.Msg = "删除失败" br.ErrMsg = "删除失败,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "删除成功" } // @router /data/check [get] func (this *TargetController) DataCheck() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() tradeCode := this.GetString("TradeCode") createDate := this.GetString("CreateDate") sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } if tradeCode == "" { br.Msg = "指标编码不可为空" return } if createDate == "" { br.Msg = "请选择日期" return } resp := new(models.DataCheckResp) item, err := models.GetDataInfo(tradeCode, createDate) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } if item != nil { resp.Status = 1 resp.Close = item.Close } else { resp.Status = 0 } br.Ret = 200 br.Success = true br.Msg = "检测成功" br.Data = resp } // @router /target/check [get] func (this *TargetController) TargetCheck() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() tradeCode := this.GetString("TradeCode") sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } if tradeCode == "" { br.Msg = "指标编码不可为空" return } resp := new(models.DataCheckResp) count, err := data_manage.GetEdbInfoCount(utils.DATA_SOURCE_MANUAL, tradeCode) if err != nil && !utils.IsErrNoRow(err) { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } if count > 0 { resp.Status = 1 } else { resp.Status = 0 } br.Ret = 200 br.Success = true br.Msg = "指标不存在关联数据,可直接删除" br.Data = resp } // @router /target/delete [post] func (this *TargetController) TargetDelete() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.TargetDeleteReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.TradeCode == "" { br.Msg = "指标编码不可为空" return } key := "import:edbinfo:data:" + req.TradeCode if utils.Rc.IsExist(key) { br.Msg = "该指标正在导入数据中,请稍后操作" return } err = models.TargetDelete(req.TradeCode) if err != nil { br.Msg = "删除失败" br.Msg = "删除失败,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.IsAddLog = true br.Msg = "删除成功" } // @router /getResearcher [get] func (this *TargetController) GetResearcher() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } var err error list := make([]*models.Researcher, 0) if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN { list, err = models.GetResearcherEntry() if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } } else if sysUser.Role == "hggroup" { mobileStr := "'15888577277','15888856487','15158848535','13651627324' " list, err = models.GetResearcherEntryByMobile(mobileStr) if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } } else if sysUser.AdminName == "dfma" { list, err = models.GetResearcherEntry() if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } } resp := new(models.ResearcherListResp) resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /getTargetItems [get] func (this *TargetController) GetTargetItems() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } mobile := this.GetString("Mobile") if mobile == "" { mobile = sysUser.Mobile } classifyId, _ := this.GetInt("ClassifyId") items, err := models.GetTargetItems(mobile, classifyId) if err != nil { br.ErrMsg = "获取失败,Err:" + err.Error() br.Msg = "获取失败" return } resp := new(models.TargetItemsResp) resp.List = items br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /target/unit_list [get] func (this *TargetController) TargetUnitList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请登录" br.Ret = 408 return } list, err := models.GetEdbUnitList() if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } edbUnitList := make([]string, 0) for _, unit := range list { edbUnitList = append(edbUnitList, unit.Unit) } br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = edbUnitList } // @router /target/frequency_list [get] func (this *TargetController) TargetFrequencyList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请登录" br.Ret = 408 return } classifyId, _ := this.GetInt("ClassifyId") //分类 if classifyId <= 0 { br.Msg = "分类ID必传" return } userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } list, err := models.GetEdbFrequencyList(classifyId, userId) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } edbFrequencyList := make([]string, 0) for _, unit := range list { edbFrequencyList = append(edbFrequencyList, unit.Frequency) } edbFrequencyList = sortEdbFrequency(edbFrequencyList) br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = edbFrequencyList } func sortEdbFrequency(frequencyList []string) (newFrequencyList []string) { var frequencyMap1 = map[string]int{ "日度": 1, "周度": 2, "旬度": 3, "月度": 4, "季度": 5, "半年度": 6, "年度": 7, } var frequencyMap2 = map[int]string{ 1: "日度", 2: "周度", 3: "旬度", 4: "月度", 5: "季度", 6: "半年度", 7: "年度", } idList := make([]int, 0) for _, frequency := range frequencyList { idList = append(idList, frequencyMap1[frequency]) } sort.Ints(idList) for _, id := range idList { newFrequencyList = append(newFrequencyList, frequencyMap2[id]) } return } // @router /target/item_list [get] func (this *TargetController) TargetItemList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } frequency := this.GetString("Frequency") keyword := this.GetString("Keyword") tradeCode := this.GetString("TradeCode") userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } classifyIdStrList, err := data.GetEdbClassifyListByAdminId(int64(userId)) if err != nil { br.Msg = "获取分类数据失败" return } classifyId, _ := this.GetInt("ClassifyId") edbShowType, _ := this.GetInt("EdbShowType") list, err := models.GetTargetItemList(classifyId, edbShowType, frequency, keyword, tradeCode, classifyIdStrList) if err != nil { br.ErrMsg = "获取失败,Err:" + err.Error() br.Msg = "获取失败" return } edbTradeCodeList := make([]string, 0) frequencyMap := make(map[string]int) for _, edb := range list { edbTradeCodeList = append(edbTradeCodeList, edb.TradeCode) frequencyMap[edb.Frequency] = 0 } frequencyList := make([]string, 0) for k := range frequencyMap { frequencyList = append(frequencyList, k) } frequencyList = sortEdbFrequency(frequencyList) if len(edbTradeCodeList) > 0 { edbTradeCodeStr := `"` + strings.Join(edbTradeCodeList, `","`) + `"` edbDataList, err := models.GetEdbDataListByCodes(edbTradeCodeStr) if err != nil { br.ErrMsg = "获取指标数据失败,Err:" + err.Error() br.Msg = "获取失败" return } edbDataMap := make(map[string][]*models.Edbdata, 0) for _, edbData := range edbDataList { if _, ok := edbDataMap[edbData.TradeCode]; ok { edbDataMap[edbData.TradeCode] = append(edbDataMap[edbData.TradeCode], edbData) } else { tmpEdbDataList := make([]*models.Edbdata, 0) tmpEdbDataList = append(tmpEdbDataList, edbData) edbDataMap[edbData.TradeCode] = tmpEdbDataList } } myYear := time.Now().Year() //当前年份 myMonth := time.Now().Format("01") //当前月份 nowWeekFirstDay := utils.GetNowWeekMonday() nowWeekLastDay := utils.GetNowWeekLastDay() nowMonthFirstDay := utils.GetNowMonthFirstDay() nowMonthLastDay := utils.GetNowMonthLastDay() nowQuarterFirstDay := utils.GetNowQuarterFirstDay() nowQuarterLastDay := utils.GetNowQuarterLastDay() nowHalfYearFirstDay := utils.GetNowHalfYearFirstDay() nowHalfYearLastDay := utils.GetNowHalfYearLastDay() nowYearFirstDay := utils.GetNowYearFirstDay() nowYearLastDay := utils.GetNowYearLastDay() for _, edb := range list { edb.Status = "未完成" if dataList, ok := edbDataMap[edb.TradeCode]; ok { edb.DataList = dataList dataDtTime, _ := time.ParseInLocation(utils.FormatDate, dataList[0].Dt, time.Now().Location()) //最近的一条数据时间 switch edb.Frequency { case "日度": if time.Now().After(dataDtTime.AddDate(0, 0, 1)) { edb.ModifyDate = time.Now().Format(utils.FormatDate) } else { edb.ModifyDate = dataDtTime.AddDate(0, 0, 1).Format(utils.FormatDate) edb.Status = "完成" } case "周度": modifyDate := nowWeekLastDay //下次更新日期 if edb.NoticeTime != "" { addDay := 7 noticeArr := strings.Split(edb.NoticeTime, " ") noticeWeek := noticeArr[0] switch noticeWeek { case "周一": addDay = 1 case "周二": addDay = 2 case "周三": addDay = 3 case "周四": addDay = 4 case "周五": addDay = 5 case "周六": addDay = 6 case "周日": addDay = 7 } modifyDate = modifyDate.AddDate(0, 0, addDay-7) } if nowWeekFirstDay.Before(dataDtTime) { edb.ModifyDate = modifyDate.AddDate(0, 0, 7).Format(utils.FormatDate) edb.Status = "完成" } else { edb.ModifyDate = modifyDate.Format(utils.FormatDate) } case "月度": addDay := 0 modifyDate := nowMonthLastDay //下次更新日期 if edb.NoticeTime != "" { strArr := strings.Split(edb.NoticeTime, "日") tmpAddDay, tmpErr := strconv.Atoi(strArr[0]) if tmpErr != nil { continue } addDay = tmpAddDay - 1 modifyDate = nowMonthFirstDay.AddDate(0, 0, addDay) } if nowMonthFirstDay.Before(dataDtTime) { if int(time.Now().Month()) != int(nowMonthFirstDay.Month()) { edb.ModifyDate = nowMonthLastDay.Format(utils.FormatDate) } else { month := nowMonthLastDay.Month() + 1 edb.ModifyDate = time.Date(nowMonthLastDay.Year(), month, 1, 0, 0, 0, 0, modifyDate.Location()).AddDate(0, 1, -1).Format(utils.FormatDate) } edb.Status = "完成" } else { edb.ModifyDate = modifyDate.Format(utils.FormatDate) } case "季度": if nowQuarterFirstDay.After(dataDtTime) { edb.ModifyDate = nowQuarterLastDay.Format(utils.FormatDate) } else { edb.ModifyDate = nowQuarterLastDay.AddDate(0, 3, 0).Format(utils.FormatDate) edb.Status = "完成" } case "半年度": if nowHalfYearFirstDay.After(dataDtTime) { edb.ModifyDate = nowHalfYearLastDay.Format(utils.FormatDate) } else { month := nowHalfYearLastDay.Month() + 1 edb.ModifyDate = time.Date(nowMonthLastDay.Year(), month, 1, 0, 0, 0, 0, nowHalfYearLastDay.Location()).AddDate(0, 6, -1).Format(utils.FormatDate) edb.Status = "完成" } case "年度": if nowYearFirstDay.After(dataDtTime) { edb.ModifyDate = nowYearLastDay.Format(utils.FormatDate) } else { edb.ModifyDate = nowYearLastDay.AddDate(1, 0, 0).Format(utils.FormatDate) edb.Status = "完成" } } } else { edb.DataList = make([]*models.Edbdata, 0) switch edb.Frequency { case "日度": edb.ModifyDate = time.Now().Format(utils.FormatDate) case "周度": modifyDate := nowWeekLastDay //下次更新日期 if edb.NoticeTime != "" { addDay := 7 noticeArr := strings.Split(edb.NoticeTime, " ") noticeWeek := noticeArr[0] switch noticeWeek { case "周一": addDay = 1 case "周二": addDay = 2 case "周三": addDay = 3 case "周四": addDay = 4 case "周五": addDay = 5 case "周六": addDay = 6 case "周日": addDay = 7 } modifyDate = modifyDate.AddDate(0, 0, addDay-7) } edb.ModifyDate = modifyDate.Format(utils.FormatDate) case "月度": if edb.NoticeTime != "" { var modifyDateStr string strArr := strings.Split(edb.NoticeTime, "日") modifyDateStr = strconv.Itoa(myYear) + "-" + myMonth + "-" + strArr[0] edb.ModifyDate = modifyDateStr } else { edb.ModifyDate = nowMonthFirstDay.AddDate(0, 1, -1).Format(utils.FormatDate) } case "季度": edb.ModifyDate = utils.GetNowQuarterLastDay().Format(utils.FormatDate) case "半年度": edb.ModifyDate = utils.GetNowHalfYearLastDay().Format(utils.FormatDate) case "年度": edb.ModifyDate = utils.GetNowYearLastDay().Format(utils.FormatDate) } } } } resp := models.TargetItemListResp{ List: list, FrequencyList: frequencyList, } br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /target/item_name_list [get] func (this *TargetController) TargetItemNameList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } frequency := this.GetString("Frequency") keyword := this.GetString("Keyword") tradeCode := this.GetString("TradeCode") userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } classifyIdStrList, err := data.GetEdbClassifyListByAdminId(int64(userId)) if err != nil { br.Msg = "获取分类数据失败" return } classifyId, _ := this.GetInt("ClassifyId") edbShowType, _ := this.GetInt("EdbShowType") list, err := models.GetTargetItemList(classifyId, edbShowType, frequency, keyword, tradeCode, classifyIdStrList) if err != nil { br.ErrMsg = "获取失败,Err:" + err.Error() br.Msg = "获取失败" return } resp := models.TargetItemListResp{ List: list, } br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /data/batch_delete_by_date [post] func (this *TargetController) BatchDataDeleteByDate() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.BatchDataDeleteReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if len(req.TradeCodeList) <= 0 { br.Msg = "至少传入一个指标编码!" return } if req.CreateDate == "" { br.Msg = "请选择日期" return } TradeCodeStr := `"` + strings.Join(req.TradeCodeList, `","`) + `"` err = models.BatchDeleteEdbDataByDate(TradeCodeStr, req.CreateDate, this.SysUser.AdminId) if err != nil { br.Msg = "删除失败!" br.ErrMsg = "删除失败,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "删除成功" } // @router /data/batch_delete [post] func (this *TargetController) BatchDataDeleteByTradeCode() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req models.TargetDeleteReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.TradeCode == "" { br.Msg = "指标编码不可为空" return } err = models.BatchDeleteEdbData(req.TradeCode, this.SysUser.AdminId) if err != nil { br.Msg = "删除失败!" br.ErrMsg = "删除失败,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "删除成功" } // @router /target/template [get] func (this *TargetCommonController) EdbTemplateDownload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() this.Ctx.Output.Download("./static/指标导入模板.xlsx", "指标导入模板.xlsx") br.Ret = 200 br.Success = true br.Msg = "下载成功" } // @router /target/import [post] func (this *TargetController) ImportTarget() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } file, _, err := this.GetFile("ImportTargetFile") if err != nil { br.Msg = "获取文件失败" br.ErrMsg = "获取文件失败,Err:" + err.Error() return } path := "./static/手工指标数据导入_" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx" defer func() { file.Close() os.Remove(path) }() err = this.SaveToFile("ImportTargetFile", path) if err != nil { br.Msg = "文件保存失败" br.ErrMsg = "文件保存失败,Err:" + err.Error() return } xlFile, err := xlsx.OpenFile(path) if err != nil { fmt.Println(err.Error()) br.Msg = "excel打开失败" br.ErrMsg = "excel打开失败,Err:" + err.Error() return } classifyMap := make(map[string]*models.EdbdataClassify) userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } classifyList, err := models.GetEdbdataClassify(int64(userId)) for _, classify := range classifyList { if classify.Child != nil { for _, child := range classify.Child { classifyMap[child.ClassifyName] = child } } } failDatas := make([]*models.EdbImportFail, 0) for _, sheet := range xlFile.Sheets { fmt.Println("sheet name: ", sheet.Name) maxRow := sheet.MaxRow fmt.Println("maxRow:", maxRow) fmt.Println("maxRow") for i := 0; i < maxRow; i++ { if i > 1 { row := sheet.Row(i) cells := row.Cells if len(cells) >= 4 { cell1 := cells[0].Value //指标名称 secName := strings.Trim(cell1, " ") if secName == "" { //过滤空白行 continue } cell2 := cells[1].Value frequency := strings.Trim(cell2, " ") //频度 classifyName := cells[2].Value //分类 classifyName = strings.Trim(classifyName, " ") unit := cells[3].Value //单位 unit = strings.Trim(unit, " ") classify, ok := classifyMap[classifyName] if !ok { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "分类不存在", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } tradeCode, err := models.GetMaxTradeCode() if err != nil { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "获取数据失败", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } if tradeCode == "" { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "数据异常", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } maxTradeCode, err := utils.GetMaxTradeCode(tradeCode) if err != nil { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "数据异常", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } if maxTradeCode == "" { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "编码为空,请联系技术", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } if secName == "" { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "指标名称不能为空", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } item, err := models.GetEdbinfoBySecName(secName) if err != nil && !utils.IsErrNoRow(err) { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "获取信息失败", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } if item != nil { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "指标已存在", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } err = models.AddEdbinfo(maxTradeCode, secName, unit, "手动", frequency, "", classify.ClassifyId, sysUser.AdminId, sysUser.RealName) if err != nil { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "导入失败", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } err = models.AddEdbinfoUser(maxTradeCode, sysUser.Mobile) if err != nil { failItem := &models.EdbImportFail{ ClassifyName: classifyName, Frequency: frequency, SecName: secName, Unit: unit, Remark: "创建账号关系失败", SysUserId: strconv.Itoa(sysUser.AdminId), } failDatas = append(failDatas, failItem) continue } } } } } resp := new(models.EdbdataImportResp) if len(failDatas) > 0 { _ = models.DelEdbImportFail(sysUser.AdminId) failContents := make([]string, 0) for _, v := range failDatas { failContents = append(failContents, fmt.Sprint(v.SecName, "导入失败:", v.Remark)) err = models.AddEdbImportFail(v) if err != nil { go alarm_msg.SendAlarmMsg("导入数据 新增失败记录失败,Err:"+err.Error(), 3) } } go alarm_msg.SendAlarmMsg("导入数据 存在部分数据导入失败,Err:"+err.Error(), 3) resp.Status = 1 resp.Msg = "存在部分导入失败" } else { resp.Status = 0 } br.Ret = 200 br.Success = true br.Msg = "导入成功" br.Data = resp } // @router /import_target/failList [get] func (this *TargetController) ImportTargetFailListDownload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } item, err := models.GetEdbImportFailList(sysUser.AdminId) if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } xlsxFile := xlsx.NewFile() sheet, err := xlsxFile.AddSheet("导入失败数据") headRow := sheet.AddRow() headRow.AddCell().SetValue("指标名称") headRow.AddCell().SetValue("频度") headRow.AddCell().SetValue("品种分类") headRow.AddCell().SetValue("单位") headRow.AddCell().SetValue("备注") for _, v := range item { row := sheet.AddRow() row.AddCell().SetValue(v.SecName) row.AddCell().SetValue(v.Frequency) row.AddCell().SetValue(v.ClassifyName) row.AddCell().SetValue(v.Unit) row.AddCell().SetValue(v.Remark) } fileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx" savePath := "./static/" + fileName err = xlsxFile.Save(savePath) if err != nil { br.Msg = "文件保存失败" br.ErrMsg = "文件保存失败,Err:" + err.Error() return } defer func() { os.Remove(savePath) }() this.Ctx.Output.Download(savePath, "失败列表.xlsx") } // @router /target/excel_style/add [post] func (this *TargetController) ExcelDataAdd() { br := new(models.BaseResponse).Init() var err error errs := make([]string, 0) defer func() { if len(errs) > 0 { go alarm_msg.SendAlarmMsg("新增复制EXCEL数据 新增或修改数据失败,Err:"+strings.Join(errs, ","), 3) } this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } var req data_manage.ExcelStyleReq err = json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } targetMap := make(map[string]*models.Edbinfo) var cellDataList []map[string]interface{} var dataList [][]map[string]interface{} for _, item := range req.CellData { v := item.(map[string]interface{}) cellDataList = append(cellDataList, v) } valueIndex := 0 var secNameList []string var frequencyList []string var unitList []string var dateList []string dateValueMap := make(map[string]map[int]string) for i := range req.Data { if i > 4 { if req.Data[i] == nil || req.Data[i][0] == nil { continue } dateMap := req.Data[i][0].(map[string]interface{}) _, ok := dateMap["m"] if ok { dateList = append(dateList, dateMap["m"].(string)) } else { continue } } for j, dataArr := range req.Data[i] { if dataArr == nil { continue } dataMap := dataArr.(map[string]interface{}) if dataList == nil { dataList = make([][]map[string]interface{}, len(req.Data)) } if dataList[i] == nil { dataList[i] = make([]map[string]interface{}, len(req.Data[i])) } dataList[i][j] = dataMap v, _ := dataMap["m"] if v == "指标名称" { for nameIndex := 1; nameIndex < len(req.Data[i]); nameIndex++ { if req.Data[i][nameIndex] == nil { break } secNameMap := req.Data[i][nameIndex].(map[string]interface{}) secName, _ := secNameMap["m"] if secName == nil { continue } secNameList = append(secNameList, secNameMap["m"].(string)) } } if v == "频度" { for nameIndex := 1; nameIndex < len(req.Data[i]); nameIndex++ { if req.Data[i][nameIndex] == nil { break } frequencyMap := req.Data[i][nameIndex].(map[string]interface{}) frequency, _ := frequencyMap["m"] if frequency == nil { continue } frequencyList = append(frequencyList, frequencyMap["m"].(string)) } } if v == "单位" { for nameIndex := 1; nameIndex < len(req.Data[i]); nameIndex++ { if req.Data[i][nameIndex] == nil { break } unitMap := req.Data[i][nameIndex].(map[string]interface{}) unit, _ := unitMap["m"] if unit == nil { continue } unitList = append(unitList, unitMap["m"].(string)) } } valueListMap := make(map[int]string) if i > 4 { for index := 1; index < len(req.Data[i]); index++ { if req.Data[i][index] == nil { continue } valueMap := req.Data[i][index].(map[string]interface{}) value, _ := valueMap["m"] if value == nil { continue } valueListMap[index] = valueMap["m"].(string) if ct, ok := valueMap["ct"].(map[string]interface{}); ok { fa, _ := ct["fa"] if fa == "#,##0.000" { value = valueMap["v"] floatValue := valueMap["v"].(float64) valueListMap[index] = strconv.FormatFloat(floatValue, 'f', -1, 64) } } } dateMap := req.Data[i][0].(map[string]interface{}) date := dateMap["m"].(string) dateValueMap[date] = valueListMap } } valueIndex++ } edbCodeDataMap := make(map[string]map[string]string) addEdbTradeMap := make(map[string]bool) updateEdbTradeMap := make(map[string]bool) updateDataTradeMap := make(map[string]bool) defer func() { go func(addEdbTradeMap, updateEdbTradeMap, updateDataTradeMap map[string]bool) { addRecordList := make([]*models.EdbinfoOpRecord, 0) for tradeCode := range addEdbTradeMap { addRecordList = append(addRecordList, &models.EdbinfoOpRecord{ TradeCode: tradeCode, Remark: "创建指标", UserId: sysUser.AdminId, UserName: sysUser.RealName, CreateTime: time.Now(), }) } for tradeCode := range updateEdbTradeMap { addRecordList = append(addRecordList, &models.EdbinfoOpRecord{ TradeCode: tradeCode, Remark: "编辑指标", UserId: sysUser.AdminId, UserName: sysUser.RealName, CreateTime: time.Now(), }) } for tradeCode := range updateDataTradeMap { addRecordList = append(addRecordList, &models.EdbinfoOpRecord{ TradeCode: tradeCode, Remark: "更新数据", UserId: sysUser.AdminId, UserName: sysUser.RealName, CreateTime: time.Now(), }) } if len(addRecordList) > 0 { obj := models.EdbinfoOpRecord{} _ = obj.MulCreate(addRecordList) } if utils.Re == nil { for tradeCode := range updateDataTradeMap { data.ModifyManualEdbMaxMinDate(tradeCode) err := utils.Rc.LPush(utils.CACHE_IMPORT_MANUAL_DATA, tradeCode) if err != nil { fmt.Println("CACHE_IMPORT_MANUAL_DATA LPush Err:" + err.Error()) } } } }(addEdbTradeMap, updateEdbTradeMap, updateDataTradeMap) }() userId := sysUser.AdminId if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN { userId = 0 } classifyIdList, err := data.GetUserManualClassifyIdList(userId) if err != nil { br.Msg = "获取分类数据失败" br.Msg = "获取拥有的分类数据失败,Err:" + err.Error() return } if !utils.InArrayByInt(classifyIdList, req.ClassifyId) { br.Msg = "无权访问" br.ErrMsg = "无权访问" br.IsSendEmail = false return } { for i := 0; i < len(secNameList); i++ { secName := secNameList[i] frequency := frequencyList[i] if len(unitList) < len(secNameList) { br.Msg = "单位填写异常!" br.ErrMsg = "单位填写异常!" return } unit := unitList[i] for j, s := range dateList { var closeVal string valueMap, ok := dateValueMap[s] if ok { createDate := dateList[j] closeVal, ok = valueMap[i+1] target, ok2 := targetMap[secName] if !ok2 { tmpTarget, err := models.GetTargetBySecName(secName) if err != nil { if utils.IsErrNoRow(err) { tmpErr := data.AddEdbInfo(secName, unit, frequency, "", sysUser.Mobile, req.ClassifyId, sysUser.AdminId, sysUser.RealName) if tmpErr != nil { utils.FileLogData.Error("AddEdbInfo err :%s", tmpErr.Error()) continue } tmpTarget, tmpErr := models.GetTargetBySecName(secName) target = tmpTarget targetMap[secName] = target addEdbTradeMap[target.TradeCode] = true } else { fmt.Println("导入数据 获取指标:Err:" + err.Error()) } } else { target = tmpTarget targetMap[secName] = target } } if !utils.InArrayByInt(classifyIdList, target.ClassifyId) { continue } if frequency != target.Frequency || unit != target.Unit || req.ClassifyId != target.ClassifyId { fmt.Println("更新指标频度或单位") err = models.ModifyEdbinfo(target.TradeCode, unit, frequency, req.ClassifyId) if err != nil { fmt.Println("EditEdbinfo err:", err.Error()) return } if _, isAdd := addEdbTradeMap[target.TradeCode]; !isAdd { updateEdbTradeMap[target.TradeCode] = true } } tmpDataMap, ok2 := edbCodeDataMap[target.TradeCode] if !ok2 { tmpDataMap = make(map[string]string) targetDataList, tmpErr := models.GetTargetsDataList(target.TradeCode) if tmpErr != nil { err = tmpErr } for _, tmpData := range targetDataList { tmpDataMap[tmpData.Dt] = tmpData.Close } edbCodeDataMap[target.TradeCode] = tmpDataMap } tmpVal, ok3 := tmpDataMap[createDate] if ok3 { if closeVal != "" { tmpValDecimal, tmpErr := decimal.NewFromString(tmpVal) if tmpErr != nil { fmt.Println("tmpVal Parse err:", tmpErr.Error()) err = tmpErr continue } closeValDecimal, tmpErr := decimal.NewFromString(closeVal) if tmpErr != nil { fmt.Println("closeVal Parse err:", tmpErr.Error()) err = tmpErr continue } if !tmpValDecimal.Equal(closeValDecimal) { fmt.Println("更新数值") err = models.ModifyTargetsDataByImport(target.TradeCode, createDate, closeVal) if err != nil { fmt.Println("ModifyTargetsDataByImport err:", err.Error()) errs = append(errs, err.Error()) } updateDataTradeMap[target.TradeCode] = true } } else { fmt.Println("删除数值") err = models.DeleteTargetsDataByImport(target.TradeCode, createDate) if err != nil { fmt.Println("DeleteTargetsDataByImport err:", err.Error()) errs = append(errs, err.Error()) } updateDataTradeMap[target.TradeCode] = true } } else { //数据不存在,进行新增操作 if target.TradeCode != "" && createDate != "" && closeVal != "" { fmt.Println("新增") models.AddTargetsDataByImport(target.TradeCode, createDate, closeVal) if err != nil { fmt.Println("AddTargetsDataByImport err:", err.Error()) errs = append(errs, err.Error()) } tmpDataMap[createDate] = closeVal edbCodeDataMap[target.TradeCode] = tmpDataMap updateDataTradeMap[target.TradeCode] = true } } } } } } br.Ret = 200 br.Success = true br.Msg = "获取成功" } // @router /target/excel_style/edit [get] func (this *TargetController) ExcelDataEdit() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } classifyId, _ := this.GetInt("ClassifyId") frequency := this.GetString("Frequency") excelId, err := data_manage.GetExcelEdbdataMappingByTradeCode(classifyId, frequency) if err != nil { br.Msg = "查找关联表失败" br.ErrMsg = "GetExcelEdbdataMappingByTradeCode,Err:" + err.Error() return } item, err := data_manage.GetExcelStyleById(*excelId) if err != nil { br.Msg = "查找样式失败" br.ErrMsg = "GetExcelStyleById,Err:" + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = item } //// @router /import/data [post]