diff --git a/api/simulation.go b/api/simulation.go index cb05d02..e0a2f42 100644 --- a/api/simulation.go +++ b/api/simulation.go @@ -103,11 +103,8 @@ func createByProjectId(c *gin.Context) { if err := c.ShouldBind(&req); nil != err { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("创建仿真请求:", req) - rsp := dto.SimulationCreateRspDto{ - ProjectId: req.ProjectId, - } - mapInfos := service.QueryPublishedGi(req.ProjectId) + rsp := dto.SimulationCreateRspDto{ProjectId: req.ProjectId} + mapInfos := service.QueryProjectPublishedGi(req.ProjectId) if len(mapInfos) == 0 { panic(dto.ErrorDto{Code: dto.DataNotExist, Message: "项目未关联地图"}) } @@ -203,9 +200,9 @@ func checkSimMapData(c *gin.Context) { err := proto.Unmarshal(rt.Data, &graphicData.RtssGraphicStorage{}) if err != nil { c.JSON(http.StatusInternalServerError, "参数错误") - } else { - c.JSON(http.StatusOK, &dto.CheckMapDataRspDto{Success: true}) + return } + c.JSON(http.StatusOK, &dto.CheckMapDataRspDto{Success: true}) } // ATS测试仿真-添加列车 @@ -232,18 +229,18 @@ func addTrain(c *gin.Context) { id := getAddTrainPrimaryKey(simulation) if id == -1 { c.JSON(http.StatusBadRequest, "已存在在线列车") - } else { - rsp := &state.TrainState{ - Id: strconv.Itoa(id), - HeadDeviceId: req.Id, - HeadOffset: req.HeadOffset, - DevicePort: req.DevicePort, - RunDirection: req.RunDirection, - TrainLength: req.TrainLength, - } - memory.AddTrainState(simulation, rsp) - c.JSON(http.StatusOK, &rsp) + return } + rsp := &state.TrainState{ + Id: strconv.Itoa(id), + HeadDeviceId: req.Id, + HeadOffset: req.HeadOffset, + DevicePort: req.DevicePort, + RunDirection: req.RunDirection, + TrainLength: req.TrainLength, + } + memory.AddTrainState(simulation, rsp) + c.JSON(http.StatusOK, &rsp) } // ATS测试仿真-移除列车 @@ -340,16 +337,15 @@ func getAddTrainPrimaryKey(simulation *memory.VerifySimulation) int { i := 1 for { t, ok := trainMap.Load(strconv.Itoa(i)) - if ok { - ts := t.(*state.TrainState) - if ts.Show { - i = -1 - break - } - i++ - } else { + if !ok { break } + ts := t.(*state.TrainState) + if ts.Show { + i = -1 + break + } + i++ } return i } diff --git a/ats/verify/simulation/simulation_manage.go b/ats/verify/simulation/simulation_manage.go index 378d5c0..d63de13 100644 --- a/ats/verify/simulation/simulation_manage.go +++ b/ats/verify/simulation/simulation_manage.go @@ -25,20 +25,21 @@ func init() { for _, simulation := range GetSimulationArr() { simulation.Memory.Status.TrainStateMap.Range(func(_, value any) bool { train := value.(*state.TrainState) - if train.Show { // 上线列车 - // 拼接列车ID - trainId, err := strconv.Atoi(train.Id) - if err != nil { - panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) - } - trainInfo := decoderVobcTrainState(info) - zap.S().Info("接收到vobc发送的列车消息", trainInfo) - // 发送给动力学 - dynamics.SendDynamicsTrainMsg(append(info, uint8(trainId))) - // 存放至列车中 - train.VobcState = trainInfo + if !train.Show { // 下线列车 + return false } - return false + // 拼接列车ID + trainId, err := strconv.Atoi(train.Id) + if err != nil { + panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) + } + trainInfo := decoderVobcTrainState(info) + zap.S().Info("接收到vobc发送的列车消息", trainInfo) + // 发送给动力学 + dynamics.SendDynamicsTrainMsg(append(info, uint8(trainId))) + // 存放至列车中 + train.VobcState = trainInfo + return true }) } @@ -46,15 +47,15 @@ func init() { dynamics.RegisterTrainInfoHandler(func(info *dynamics.TrainInfo) { for _, simulation := range GetSimulationArr() { sta, ok := simulation.Memory.Status.TrainStateMap.Load(strconv.Itoa(int(info.Number))) - if ok { - trainState := sta.(*state.TrainState) - // 给半实物仿真发送速度 - zap.S().Info("发送到vobc发送的速度", info.Speed*36) - vobc.SendTrainSpeedTask(info.Speed * 36) - // 更新列车状态 - memory.UpdateTrainState(simulation, convert(info, trainState, simulation)) - break + if !ok { + continue } + trainState := sta.(*state.TrainState) + // 给半实物仿真发送速度 + zap.S().Info("发送到vobc发送的速度", info.Speed*36) + vobc.SendTrainSpeedTask(info.Speed * 36) + // 更新列车状态 + memory.UpdateTrainState(simulation, convert(info, trainState, simulation)) } }) } @@ -109,7 +110,7 @@ func createSimulationId(mapId int32) string { // 获取仿真列表 func ListAllSimulations() []*dto.SimulationInfoRspDto { - simArr := []*dto.SimulationInfoRspDto{} + var simArr []*dto.SimulationInfoRspDto simulationMap.Range(func(_, v any) bool { s := v.(*memory.VerifySimulation) simArr = append(simArr, &dto.SimulationInfoRspDto{ @@ -133,7 +134,7 @@ func FindSimulation(simulationId string) *memory.VerifySimulation { // 获取普通仿真数组 func GetSimulationArr() []*memory.VerifySimulation { - result := []*memory.VerifySimulation{} + var result []*memory.VerifySimulation simulationMap.Range(func(_, v any) bool { result = append(result, v.(*memory.VerifySimulation)) return true @@ -152,14 +153,13 @@ func convert(info *dynamics.TrainInfo, sta *state.TrainState, simulation *memory sta.PointTo = pointTo sta.RunDirection = runDirection //判定车头方向 + sta.HeadDirection = runDirection if sta.VobcState != nil { if sta.VobcState.DirectionForward { sta.HeadDirection = info.Up } else if sta.VobcState.DirectionBackward { sta.HeadDirection = !info.Up } - } else { - sta.HeadDirection = runDirection } // 赋值动力学信息 sta.DynamicState.Heartbeat = int32(info.LifeSignal) diff --git a/ats/verify/simulation/wayside/memory/wayside_memory_generate.go b/ats/verify/simulation/wayside/memory/wayside_memory_generate.go index 3198a6d..fbf657d 100644 --- a/ats/verify/simulation/wayside/memory/wayside_memory_generate.go +++ b/ats/verify/simulation/wayside/memory/wayside_memory_generate.go @@ -49,7 +49,7 @@ func BuildCalculateLinkData(gd *graphicData.RtssGraphicStorage) []*graphicData.C // 这里linkPath是排过序的公里标大小 linkPathMap := getGraphicLinkPath(gm, startPointQueue) // 根据路径开始包装结果数据 - resultArr := []*graphicData.CalculateLink{} + var resultArr []*graphicData.CalculateLink for id, pathArr := range linkPathMap { item := &graphicData.CalculateLink{ Common: &graphicData.CommonInfo{}, @@ -316,9 +316,9 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru gm.TurnoutMap[t.Common.Id] = &buildCalcTurnoutStruct{ Data: t, CrossKilometerSystem: op, - axlePoints: make(map[graphicData.RelatedRef_DevicePort]*graphicData.AxleCounting), + axlePoints: make(map[graphicData.RelatedRef_DevicePort]*graphicData.AxleCounting, 3), transponders: make(map[graphicData.RelatedRef_DevicePort][]*graphicData.Transponder), - signals: make(map[graphicData.RelatedRef_DevicePort]*graphicData.Signal), + signals: make(map[graphicData.RelatedRef_DevicePort]*graphicData.Signal, 3), slopes: make(map[graphicData.RelatedRef_DevicePort]map[string]*graphicData.KilometerSystem), curvatures: make(map[graphicData.RelatedRef_DevicePort]map[string]*graphicData.KilometerSystem), } @@ -327,7 +327,7 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru for _, s := range gd.Section { gm.SectionMap[s.Common.Id] = &buildCalcSectionStruct{ Data: s, - axlePoints: make(map[graphicData.RelatedRef_DevicePort]*graphicData.AxleCounting), + axlePoints: make(map[graphicData.RelatedRef_DevicePort]*graphicData.AxleCounting, 2), slopes: make(map[string]*graphicData.KilometerSystem), curvatures: make(map[string]*graphicData.KilometerSystem), } @@ -544,14 +544,15 @@ func judgeKilometerInRange(k1, k2, k3 *graphicData.KilometerSystem) bool { // 处理道岔坡度、曲度信息 func handleSlopeCurvaturesMap(id string, kms []*graphicData.KilometerSystem, m map[graphicData.Direction]map[string]*graphicData.KilometerSystem) { for _, k := range kms { - if judgeKilometerIsVaild(k) { - kmMap := m[k.Direction] - if kmMap == nil { - kmMap = make(map[string]*graphicData.KilometerSystem) - m[k.Direction] = kmMap - } - kmMap[id] = k + if !judgeKilometerIsVaild(k) { + continue } + kmMap := m[k.Direction] + if kmMap == nil { + kmMap = make(map[string]*graphicData.KilometerSystem) + m[k.Direction] = kmMap + } + kmMap[id] = k } } @@ -560,21 +561,22 @@ func handleTurnoutSlopeCurvaturesMap(port graphicData.RelatedRef_DevicePort, scmap map[graphicData.Direction]map[string]*graphicData.KilometerSystem, f func(*buildCalcTurnoutStruct) map[graphicData.RelatedRef_DevicePort]map[string]*graphicData.KilometerSystem) { point := t.axlePoints[port] - if point != nil { - m := f(t) - m[port] = make(map[string]*graphicData.KilometerSystem) - kmMap := scmap[point.KilometerSystem.Direction] - idArr := []string{} - for k, v := range kmMap { - if judgeKilometerInRange(v, point.KilometerSystem, t.CrossKilometerSystem) { - m[port][k] = v - idArr = append(idArr, k) - } - } - for _, id := range idArr { - delete(kmMap, id) + if point == nil { + return + } + m := f(t) + m[port] = make(map[string]*graphicData.KilometerSystem) + kmMap := scmap[point.KilometerSystem.Direction] + var idArr []string + for k, v := range kmMap { + if judgeKilometerInRange(v, point.KilometerSystem, t.CrossKilometerSystem) { + m[port][k] = v + idArr = append(idArr, k) } } + for _, id := range idArr { + delete(kmMap, id) + } } func handleSectionSlopeCurvaturesMap(s *buildCalcSectionStruct, @@ -587,7 +589,7 @@ func handleSectionSlopeCurvaturesMap(s *buildCalcSectionStruct, } m := f(s) kmMap := scmap[pointA.KilometerSystem.Direction] - idArr := []string{} + var idArr []string for k, v := range kmMap { if judgeKilometerInRange(v, pointA.KilometerSystem, pointB.KilometerSystem) { m[k] = v diff --git a/grpcproto/memory_change_server.go b/grpcproto/memory_change_server.go index 790262b..a3cd854 100644 --- a/grpcproto/memory_change_server.go +++ b/grpcproto/memory_change_server.go @@ -50,17 +50,19 @@ func (t *MemoryChangeServer) onTick() []TopicMsg { allSim := make(map[string]bool) for _, v := range simArr { allSim[v.SimulationId] = true - if t.SimulationMap[v.SimulationId] == nil { - status := &state.SimulationStatus{SimulationId: v.SimulationId, MapId: v.MapId, ProjectId: v.ProjectId} - t.SimulationMap[v.SimulationId] = status - addArr = append(addArr, status) + if t.SimulationMap[v.SimulationId] != nil { + continue } + status := &state.SimulationStatus{SimulationId: v.SimulationId, MapId: v.MapId, ProjectId: v.ProjectId} + t.SimulationMap[v.SimulationId] = status + addArr = append(addArr, status) } // 已经移除的仿真 for k, v := range t.SimulationMap { - if !allSim[k] { - delArr = append(delArr, v) + if allSim[k] { + continue } + delArr = append(delArr, v) } // 删除已替换仿真主键 if len(delArr) > 0 { @@ -69,13 +71,12 @@ func (t *MemoryChangeServer) onTick() []TopicMsg { } } if len(addArr) == 0 && len(delArr) == 0 { - return []TopicMsg{} - } else { - msg := &state.MemoryDataStatus{AddSimulations: addArr, RemoveSimulations: delArr} - b, err := proto.Marshal(msg) - if err != nil { - panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) - } - return []TopicMsg{{channalName: t.getChannelName(), data: b}} + return nil } + msg := &state.MemoryDataStatus{AddSimulations: addArr, RemoveSimulations: delArr} + b, err := proto.Marshal(msg) + if err != nil { + panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) + } + return []TopicMsg{{channalName: t.getChannelName(), data: b}} } diff --git a/grpcproto/message.go b/grpcproto/message.go index 68abfbc..e2f4e24 100644 --- a/grpcproto/message.go +++ b/grpcproto/message.go @@ -57,10 +57,11 @@ func RegisterMsgServer(server IMsgServer) { for { <-tick.C topicMsgs := server.onTick() - if len(topicMsgs) != 0 { - for _, msg := range topicMsgs { - PublishMsg(msg.channalName, msg.data) - } + if len(topicMsgs) == 0 { + continue + } + for _, msg := range topicMsgs { + PublishMsg(msg.channalName, msg.data) } select { case <-exitChannel: diff --git a/grpcproto/simulation_server.go b/grpcproto/simulation_server.go index 0879d96..78f3122 100644 --- a/grpcproto/simulation_server.go +++ b/grpcproto/simulation_server.go @@ -48,10 +48,7 @@ func (t *SimulationServer) onTick() []TopicMsg { if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) } - msgArr[i] = TopicMsg{ - channalName: channelName, - data: b, - } + msgArr[i] = TopicMsg{channalName: channelName, data: b} } return msgArr } diff --git a/middleware/auth.go b/middleware/auth.go index 21b3711..8b24cc2 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -22,40 +22,40 @@ func permissionMiddleware() gin.HandlerFunc { user, _ := c.Get(IdentityKey) if user == nil { // 用户未登录 c.Next() - } else { - uid := user.(*model.User).ID - userAuth := userAuthPathMap[uid] - if userAuth == nil { - userAuthPathMap[uid] = service.QueryUserAuthApiPath(uid) - userAuth = userAuthPathMap[uid] - } - if userAuth.IsAdmin { // 用户是超级管理员 - c.Next() - } else { - path, method := c.Request.URL.Path, c.Request.Method - if validateUserPath(path, method, userAuth.AuthPaths) { // 用户有权限 - c.Next() - } else { - zap.S().Errorf("无权限操作请求路径:%s, 方法:%s", path, method) - panic(dto.ErrorDto{Code: dto.NoAuthOperationError, Message: "无权限操作"}) - } - } + return } + uid := user.(*model.User).ID + userAuth := userAuthPathMap[uid] + if userAuth == nil { + userAuthPathMap[uid] = service.QueryUserAuthApiPath(uid) + userAuth = userAuthPathMap[uid] + } + if userAuth.IsAdmin { // 用户是超级管理员 + c.Next() + return + } + path, method := c.Request.URL.Path, c.Request.Method + if validateUserPath(path, method, userAuth.AuthPaths) { // 用户有权限 + c.Next() + return + } + zap.S().Errorf("无权限操作请求路径:%s, 方法:%s", path, method) + panic(dto.ErrorDto{Code: dto.NoAuthOperationError, Message: "无权限操作"}) } } // 验证路径 func validateUserPath(path, method string, paths []*dto.AuthPath) bool { for _, p := range paths { - if p.Method == "*" || strings.Contains(p.Method, method) { // 判断方法是否匹配 - if p.Path == path { - return true - } else { - authReg, _ := regexp.Compile(p.Path) - if authReg.MatchString(path) { // 匹配路径 - return true - } - } + if p.Method != "*" && !strings.Contains(p.Method, method) { // 判断方法是否匹配 + continue + } + if p.Path == path { + return true + } + authReg, _ := regexp.Compile(p.Path) + if authReg.MatchString(path) { // 匹配路径 + return true } } return false @@ -68,7 +68,7 @@ func ClearUserPermission(userId int32) { // 修改角色后清理用户权限 func ClearUserPermissionByRid(roleId int32) { - uids := []int32{} + var uids []int32 for uid, u := range userAuthPathMap { for _, r := range u.RoleIds { if r == roleId { @@ -77,9 +77,10 @@ func ClearUserPermissionByRid(roleId int32) { } } } - if len(uids) > 0 { - for _, uid := range uids { - ClearUserPermission(uid) - } + if len(uids) == 0 { + return + } + for _, uid := range uids { + ClearUserPermission(uid) } } diff --git a/service/auth.go b/service/auth.go index db50813..45a27ff 100644 --- a/service/auth.go +++ b/service/auth.go @@ -31,25 +31,24 @@ func ListAuthRoleQuery() []*dto.AuthRoleRspDto { // 创建权限角色 func CreateAuthRole(a *dto.AuthRoleReqDto) bool { - createTime := time.Now() - d := model.AuthRole{Name: a.Name, CreateTime: createTime} + d := model.AuthRole{Name: a.Name, CreateTime: time.Now()} aq := dbquery.AuthRole err := aq.Save(&d) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) } n := len(a.AddPaths) - if n > 0 { - // 查询刚插入的角色 - newAuthRole, _ := aq.Where(aq.Name.Eq(a.Name), aq.CreateTime.Eq(createTime)).First() - rolePaths := make([]*model.AuthRoleAPIPath, n) - for i, v := range a.AddPaths { - rolePaths[i] = &model.AuthRoleAPIPath{Rid: newAuthRole.ID, Pid: v} - } - dbquery.AuthRoleAPIPath.Save(rolePaths...) - return true + if n == 0 { + return false } - return false + // 查询刚插入的角色 + newAuthRole, _ := aq.Where(aq.Name.Eq(a.Name)).Order(aq.CreateTime).Last() + rolePaths := make([]*model.AuthRoleAPIPath, n) + for i, v := range a.AddPaths { + rolePaths[i] = &model.AuthRoleAPIPath{Rid: newAuthRole.ID, Pid: v} + } + dbquery.AuthRoleAPIPath.Save(rolePaths...) + return true } // 查询角色详情 @@ -66,17 +65,18 @@ func QueryAuthRole(rid int32) *dto.AuthRoleDetailRspDto { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err2.Error()}) } pn := len(linkPids) - if pn > 0 { - pids := make([]int32, pn) - for i, r := range linkPids { - pids[i] = r.Pid - } - apiPaths, err4 := dbquery.AuthAPIPath.Where(dbquery.AuthAPIPath.ID.In(pids...)).Find() - if err4 != nil { - panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err4.Error()}) - } - rsp.Paths = apiPaths + if pn == 0 { // 无关联路径 + return rsp } + pids := make([]int32, pn) + for i, r := range linkPids { + pids[i] = r.Pid + } + apiPaths, err4 := dbquery.AuthAPIPath.Where(dbquery.AuthAPIPath.ID.In(pids...)).Find() + if err4 != nil { + panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err4.Error()}) + } + rsp.Paths = apiPaths return rsp } @@ -87,24 +87,24 @@ func UpdateAuthRole(rid int32, info *dto.AuthRoleReqDto) bool { if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) } - role.Name = info.Name - // 更新名称 + role.Name = info.Name // 更新名称 dbquery.AuthRole.Updates(role) - // 删除关联 dqarap := dbquery.AuthRoleAPIPath + // 删除关联 rn := len(info.DelPaths) if rn > 0 { dqarap.Where(dqarap.Rid.Eq(rid), dqarap.Pid.In(info.DelPaths...)).Delete() } // 增加关联 an := len(info.AddPaths) - if an > 0 { - rolePaths := make([]*model.AuthRoleAPIPath, an) - for i, v := range info.AddPaths { - rolePaths[i] = &model.AuthRoleAPIPath{Rid: rid, Pid: v} - } - dqarap.Save(rolePaths...) + if an == 0 { + return true } + rolePaths := make([]*model.AuthRoleAPIPath, an) + for i, v := range info.AddPaths { + rolePaths[i] = &model.AuthRoleAPIPath{Rid: rid, Pid: v} + } + dqarap.Save(rolePaths...) return true } @@ -216,15 +216,16 @@ func UserLinkRole(linkInfo *dto.AuthRoleUserReqDto) bool { } // 插入关联关系 n := len(linkInfo.AddRids) - if n > 0 { - arul := make([]*model.AuthRoleUser, n) - for i, l := range linkInfo.AddRids { - arul[i] = &model.AuthRoleUser{UID: linkInfo.Uid, Rid: l} - } - err2 := dbar.Save(arul...) - if err2 != nil { - panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err2.Error()}) - } + if n == 0 { + return true + } + arul := make([]*model.AuthRoleUser, n) + for i, l := range linkInfo.AddRids { + arul[i] = &model.AuthRoleUser{UID: linkInfo.Uid, Rid: l} + } + err2 := dbar.Save(arul...) + if err2 != nil { + panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err2.Error()}) } return true } @@ -257,24 +258,27 @@ func QueryUserAuthApiPath(uid int32) *dto.AuthUserStorageDto { rids[i] = r.ID authUser.IsAdmin = authUser.IsAdmin || (r.Weight == int32(dto.ADMIN)) } - if !authUser.IsAdmin { // 非管理员时,查询角色权限路径 - // 查询角色与路径关联信息 - linkPids, err3 := dbquery.AuthRoleAPIPath.Distinct(dbquery.AuthRoleAPIPath.Pid).Where(dbquery.AuthRoleAPIPath.Rid.In(rids...)).Find() - if err3 != nil { - panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err3.Error()}) - } - pn := len(linkPids) - if pn > 0 { - pids := make([]int32, pn) - for i, r := range linkPids { - pids[i] = r.Pid - } - apiPaths, err4 := dbquery.AuthAPIPath.Where(dbquery.AuthAPIPath.ID.In(pids...)).Find() - if err4 != nil { - panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err4.Error()}) - } - authUser.AuthPaths = dto.ConvertFromAuthPath(apiPaths) // 赋值路径数组 - } + if authUser.IsAdmin { // 管理员直接返回 + return authUser } + // 非管理员时,查询角色权限路径 + linkPids, err3 := dbquery.AuthRoleAPIPath.Distinct(dbquery.AuthRoleAPIPath.Pid).Where(dbquery.AuthRoleAPIPath.Rid.In(rids...)).Find() + if err3 != nil { + panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err3.Error()}) + } + // 非管理员路径信息 + pn := len(linkPids) + if pn == 0 { + return authUser + } + pids := make([]int32, pn) + for i, r := range linkPids { + pids[i] = r.Pid + } + apiPaths, err4 := dbquery.AuthAPIPath.Where(dbquery.AuthAPIPath.ID.In(pids...)).Find() + if err4 != nil { + panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err4.Error()}) + } + authUser.AuthPaths = dto.ConvertFromAuthPath(apiPaths) // 赋值路径数组 return authUser } diff --git a/service/category.go b/service/category.go index 7bc0067..3b15001 100644 --- a/service/category.go +++ b/service/category.go @@ -73,15 +73,9 @@ func UpdateCategory(id int32, cd *dto.CategoryDto) bool { if oldD == nil || err != nil { panic(dto.ErrorDto{Code: dto.QueryDBError, Message: err.Error()}) } - if cd.Code != "" { - oldD.Code = cd.Code - } - if cd.Config != "" { - oldD.Config = cd.Config - } - if len(cd.Name) > 0 { - oldD.Name = cd.Name - } + oldD.Code = cd.Code + oldD.Config = cd.Config + oldD.Name = cd.Name oldD.UpdateAt = time.Now() _, error := dbquery.Category.Updates(oldD) if error != nil { diff --git a/service/project.go b/service/project.go index ef2946b..2677ba1 100644 --- a/service/project.go +++ b/service/project.go @@ -98,19 +98,20 @@ func DeleteProjectById(id int) { } func checkProjectInfo(code string, id int32) error { + if code == "" { + return nil + } findNameQuery := dbquery.Project w := findNameQuery.Where() if id != 0 { w = w.Where(findNameQuery.ID.NotIn(id)) } - if code != "" { - count, err := w.Where(findNameQuery.Code.Eq(code)).Debug().Count() - if err != nil { - panic(dto.ErrorDto{Code: dto.QueryDBError, Message: err.Error()}) - } - if count > 0 { - panic(dto.ErrorDto{Code: dto.DataAlreadyExist, Message: "编码已存在"}) - } + count, err := w.Where(findNameQuery.Code.Eq(code)).Debug().Count() + if err != nil { + panic(dto.ErrorDto{Code: dto.QueryDBError, Message: err.Error()}) + } + if count > 0 { + panic(dto.ErrorDto{Code: dto.DataAlreadyExist, Message: "编码已存在"}) } return nil } diff --git a/service/projectLink.go b/service/projectLink.go index 9da4990..0529fe0 100644 --- a/service/projectLink.go +++ b/service/projectLink.go @@ -16,7 +16,7 @@ func QueryProjectLinkInfo(id int32) *dto.ProjectLinkRspDto { // 关联列车尺寸列表 projectLink.TrainSizeLinks = dto.ConvertFromTrainSizeDto(QueryProjectTrainSize(id)) // 关联地图列表 - projectLink.PublishedGiLinks = dto.ConvertFromPublishedGiLink(QueryPublishedGi(id)) + projectLink.PublishedGiLinks = dto.ConvertFromPublishedGiLink(QueryProjectPublishedGi(id)) return projectLink } @@ -51,20 +51,22 @@ func delProjectMapLink(pid int32) { // 保存项目尺寸关联关系 func saveProjectSize(pid int32, sids []*int32) { - for _, sid := range sids { - dbquery.ProjectTrainSizeLink.Save(&model.ProjectTrainSizeLink{ - Pid: pid, - Sid: *sid, - }) + if len(sids) == 0 { + sizeInfos := make([]*model.ProjectTrainSizeLink, len(sids)) + for i, sid := range sids { + sizeInfos[i] = &model.ProjectTrainSizeLink{Pid: pid, Sid: *sid} + } + dbquery.ProjectTrainSizeLink.Save(sizeInfos...) } } // 保存项目地图关联关系 func saveProjectMapLink(pid int32, mids []*int32) { - for _, mid := range mids { - dbquery.ProjectPublishLink.Save(&model.ProjectPublishLink{ - Pid: pid, - Mid: *mid, - }) + if len(mids) == 0 { + mapInfos := make([]*model.ProjectPublishLink, len(mids)) + for i, mid := range mids { + mapInfos[i] = &model.ProjectPublishLink{Pid: pid, Mid: *mid} + } + dbquery.ProjectPublishLink.Save(mapInfos...) } } diff --git a/service/publishedGi.go b/service/publishedGi.go index ba1e2be..4cb2e81 100644 --- a/service/publishedGi.go +++ b/service/publishedGi.go @@ -31,7 +31,7 @@ func PageQueryPublishedGi(req *publishedGi.PublishedGiReqDto) *dto.PageDto { } func ListQueryPublishedGi(req *publishedGi.PublishedGiListReqDto) []*publishedGi.PublishedGiDto { - where := dbquery.PublishedGi.Where(dbquery.PublishedGi.Status.Eq(1)) + where := dbquery.PublishedGi.Omit(dbquery.PublishedGi.Proto).Where(dbquery.PublishedGi.Status.Eq(1)) if req.Name != "" { where = where.Where(dbquery.PublishedGi.Name.Like(fmt.Sprintf("%%%s%%", req.Name))) } @@ -115,20 +115,20 @@ func SaveAsDraftingFromPublish(id int32, user *model.User, name string) { } } -func QueryPublishedGi(id int32) []*model.PublishedGi { +func QueryProjectPublishedGi(id int32) []*model.PublishedGi { // 获取项目关联的发布地图 dppl := dbquery.ProjectPublishLink links, _ := dppl.Select(dppl.Mid).Where(dppl.Pid.Eq(id)).Find() - if len(links) > 0 { - mids := []int32{} - for _, m := range links { - mids = append(mids, m.Mid) - } - dp := dbquery.PublishedGi - publishedGis, _ := dp.Select(dp.ID, dp.Name, dp.Category).Where(dp.ID.In(mids...)).Find() - return publishedGis + if len(links) == 0 { + return nil } - return []*model.PublishedGi{} + mids := make([]int32, len(links)) + for i, m := range links { + mids[i] = m.Mid + } + dp := dbquery.PublishedGi + publishedGis, _ := dp.Select(dp.ID, dp.Name, dp.Category).Where(dp.ID.In(mids...)).Find() + return publishedGis } // 操作地图数据中的link数据 diff --git a/service/trainManage.go b/service/trainManage.go index fd0a879..3e5ea4e 100644 --- a/service/trainManage.go +++ b/service/trainManage.go @@ -75,9 +75,7 @@ func UpdateTrainModel(id int32, td *dto.TrainModelDto) bool { if oldD == nil || err != nil { panic(dto.ErrorDto{Code: dto.QueryDBError, Message: err.Error()}) } - if len(td.Name) > 0 { - oldD.Name = td.Name - } + oldD.Name = td.Name oldD.UpdateAt = time.Now() _, err2 := dbquery.TrainModel.Updates(oldD) if err2 != nil { @@ -171,17 +169,17 @@ func DeleteTrainSizeById(id int) { func QueryProjectTrainSize(id int32) []*model.TrainSize { // 获取项目关联的列车尺寸 ptsl := dbquery.ProjectTrainSizeLink - slinks, _ := ptsl.Select(ptsl.Sid).Where(ptsl.Pid.Eq(id)).Find() - if len(slinks) > 0 { - sids := []int32{} - for _, sid := range slinks { - sids = append(sids, sid.Sid) - } - ts := dbquery.TrainSize - trainSizes, _ := ts.Select(ts.ID, ts.Name, ts.TotalLength, ts.CarriageLength, ts.Description).Where(ts.ID.In(sids...)).Find() - return trainSizes + slinks, _ := ptsl.Select(ptsl.Sid).Distinct(ptsl.Sid).Where(ptsl.Pid.Eq(id)).Find() + if len(slinks) == 0 { + return nil } - return []*model.TrainSize{} + sids := make([]int32, len(slinks)) + for i, sid := range slinks { + sids[i] = sid.Sid + } + ts := dbquery.TrainSize + trainSizes, _ := ts.Select(ts.ID, ts.Name, ts.TotalLength, ts.CarriageLength, ts.Description).Where(ts.ID.In(sids...)).Find() + return trainSizes } // 查询列车轮径信息列表 @@ -267,19 +265,20 @@ func DeleteTrainWheelDiameterById(id int) { // 检查列车型号名称 func checkTrainModel(name string, id int32) error { + if name == "" { + return nil + } findNameQuery := dbquery.TrainModel w := findNameQuery.Where() if id != 0 { w = w.Where(findNameQuery.ID.NotIn(id)) } - if name != "" { - count, err := w.Where(findNameQuery.Name.Eq(name)).Debug().Count() - if err != nil { - panic(dto.ErrorDto{Code: dto.QueryDBError, Message: err.Error()}) - } - if count > 0 { - panic("名称已存在") - } + count, err := w.Where(findNameQuery.Name.Eq(name)).Debug().Count() + if err != nil { + panic(dto.ErrorDto{Code: dto.QueryDBError, Message: err.Error()}) + } + if count > 0 { + panic(dto.ErrorDto{Code: dto.DataAlreadyExist, Message: "名称已存在"}) } return nil }