【列车型号管理】

This commit is contained in:
weizhihong 2023-08-22 16:44:34 +08:00
parent 27d0a6710a
commit 7579200104
13 changed files with 1225 additions and 46 deletions

View File

@ -204,7 +204,7 @@ func deleteCategory(c *gin.Context) {
id, err := strconv.Atoi(idStr)
if err != nil {
c.JSON(http.StatusBadRequest, "id参数解析错误")
panic("id参数解析错误")
return
}
zap.S().Debug("id查询草稿的图形数据", id)
service.DeleteCategoryById(id)

View File

@ -217,7 +217,7 @@ func deleteDrafting(c *gin.Context) {
id, err := strconv.Atoi(idStr)
if err != nil {
c.JSON(http.StatusBadRequest, "id参数解析错误")
panic("id参数解析错误")
return
}
zap.S().Debug("id查询草稿的图形数据", id)
service.DeleteDraftingById(id)

View File

@ -183,34 +183,27 @@ func checkSimMapData(c *gin.Context) {
// @Failure 500 {object} dto.ErrorDto
// @Router /api/v1/simulation/train/add [post]
func addTrain(c *gin.Context) {
//user,_:=c.Get(middleware.IdentityKey)
req := dto.AddTrainReqDto{}
if err := c.ShouldBind(&req); err != nil {
panic(err)
}
zap.S().Debug("ATS测试仿真-添加列车,请求:", req)
simulation := checkDeviceDataAndReturn(req.SimulationId)
trainMap := &simulation.Memory.Status.TrainStateMap
// 获取列车ID
i := 1
for {
_, ok := trainMap.Load(strconv.Itoa(i))
if ok {
i++
} else {
break
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: int64(service.CalcTrainLenght(req.TrainModelId, req.CarriageNum)),
}
memory.AddTrainState(simulation, rsp)
c.JSON(http.StatusOK, &rsp)
}
id := strconv.Itoa(i)
rsp := &state.TrainState{
Id: id,
HeadDeviceId: req.Id,
HeadOffset: req.HeadOffset,
DevicePort: req.DevicePort,
RunDirection: req.RunDirection,
}
memory.AddTrainState(simulation, rsp)
c.JSON(http.StatusOK, &rsp)
}
// ATS测试仿真-移除列车
@ -280,3 +273,24 @@ func checkDeviceDataAndReturn(simId string) *memory.VerifySimulation {
}
return deviceMemory
}
// 获取列车主键
func getAddTrainPrimaryKey(simulation *memory.VerifySimulation) int {
trainMap := &simulation.Memory.Status.TrainStateMap
// 获取列车ID
i := 1
for {
t, ok := trainMap.Load(strconv.Itoa(i))
if ok {
ts := t.(*state.TrainState)
if ts.Show {
i = -1
break
}
i++
} else {
break
}
}
return i
}

179
api/trainModel.go Normal file
View File

@ -0,0 +1,179 @@
package api
import (
"net/http"
"strconv"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"joylink.club/bj-rtsts-server/dto"
"joylink.club/bj-rtsts-server/middleware"
"joylink.club/bj-rtsts-server/service"
)
func InitTrainModelRouter(api *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
authed := api.Group("/v1/trainModel").Use(authMiddleware.MiddlewareFunc())
authed.GET("/paging", pageQueryTrainModel)
authed.POST("", createTrainModel)
authed.GET("/:id", queryTrainModel)
authed.PUT("/:id", updateTrainModel)
authed.DELETE("/:id", deleteTrainModel)
}
// 分页查询列车型号列表
//
// @Summary 分页查询列车型号信息列表
//
// @Security JwtAuth
//
// @Description 可以通过列车型号名称过滤,分页查询列车型号信息列表
// @Tags 列车型号Api
// @Accept json
// @Produce json
// @Param pageTrainModelReqDto query dto.PageTrainModelReqDto true "列车型号查询条件带分页信息"
// @Success 200 {object} dto.PageDto
// @Failure 401 {object} dto.ErrorDto
// @Failure 404 {object} dto.ErrorDto
// @Failure 500 {object} dto.ErrorDto
// @Router /api/v1/trainModel/paging [get]
func pageQueryTrainModel(c *gin.Context) {
user, _ := c.Get(middleware.IdentityKey)
zap.S().Debug("分页查询列车组次", user)
req := dto.PageTrainModelReqDto{}
if err := c.ShouldBind(&req); err != nil {
zap.S().Warn("分页查询参数绑定错误,使用默认参数", err)
req.Default()
}
zap.S().Debug("分页查列车组次参数", req)
page, err := service.PageTrainModelQuery(&req)
if err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusOK, page)
}
// 创建列车型号
//
// @Summary 创建列车型号
//
// @Security JwtAuth
//
// @Description 创建列车型号数据
// @Tags 列车型号Api
// @Accept json
// @Produce json
// @Param trainModelDto query dto.TrainModelDto true "创建的列车型号信息"
// @Success 200 {object} nil
// @Failure 401 {object} dto.ErrorDto
// @Failure 404 {object} dto.ErrorDto
// @Failure 500 {object} dto.ErrorDto
// @Router /api/v1/trainModel [post]
func createTrainModel(c *gin.Context) {
req := dto.TrainModelDto{}
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, "传入参数错误")
return
}
zap.S().Debug("保存数据", req)
data, err := service.CreateTrainModel(&req)
if err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
c.JSON(http.StatusOK, data)
}
// 查询列车型号详情
//
// @Summary 查询列车型号详情
//
// @Security JwtAuth
//
// @Description 查询列车型号详情
// @Tags 列车型号Api
// @Accept json
// @Produce json
// @Param id path int true "列车型号ID"
// @Success 200 {object} model.TrainModel
// @Failure 401 {object} dto.ErrorDto
// @Failure 404 {object} dto.ErrorDto
// @Failure 500 {object} dto.ErrorDto
// @Router /api/v1/trainModel/:id [get]
func queryTrainModel(c *gin.Context) {
id, exist := c.Params.Get("id")
if !exist {
c.JSON(http.StatusBadRequest, "必要参数id不存在")
return
}
zap.S().Debug("传入参数id为" + id)
int64Id, _ := strconv.ParseInt(id, 10, 64)
c.JSON(http.StatusOK, service.QueryTrainModel(int32(int64Id)))
}
// 修改列车型号信息
//
// @Summary 修改列车型号信息
//
// @Security JwtAuth
//
// @Description 修改列车型号信息
// @Tags 列车型号Api
// @Accept json
// @Produce json
// @Param id path int true "列车型号ID"
// @Param trainModelDto query dto.TrainModelDto true "修改的列车型号信息"
// @Success 200 {object} nil
// @Failure 401 {object} dto.ErrorDto
// @Failure 404 {object} dto.ErrorDto
// @Failure 500 {object} dto.ErrorDto
// @Router /api/v1/trainModel/:id [put]
func updateTrainModel(c *gin.Context) {
id, exist := c.Params.Get("id")
if !exist {
c.JSON(http.StatusBadRequest, "必要参数id不存在")
return
}
zap.S().Debug("传入参数id为" + id)
req := dto.TrainModelDto{}
if err := c.ShouldBind(&req); err != nil {
c.JSON(http.StatusBadRequest, "保存参数出错")
return
}
int64Id, _ := strconv.ParseInt(id, 10, 64)
result := service.UpdateTrainModel(int32(int64Id), &req)
if !result {
c.JSON(http.StatusInternalServerError, "保存参数出错")
return
}
c.JSON(http.StatusOK, result)
}
// 删除列车型号数据
//
// @Summary 删除列车型号数据
//
// @Security JwtAuth
//
// @Description 删除列车型号数据
// @Tags 列车型号Api
// @Accept json
// @Produce json
// @Param id path int true "列车型号ID"
// @Success 200 {object} nil
// @Failure 401 {object} dto.ErrorDto
// @Failure 404 {object} dto.ErrorDto
// @Failure 500 {object} dto.ErrorDto
// @Router /api/v1/trainModel/:id [delete]
func deleteTrainModel(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil {
c.JSON(http.StatusBadRequest, "id参数解析错误")
return
}
zap.S().Debug("id查询列车型号的图形数据", id)
service.DeleteTrainModelById(id)
c.JSON(http.StatusOK, true)
}

View File

@ -250,42 +250,36 @@ func getGraphicTurnoutRefDevices(refVal *graphicData.RelatedRef, deviceMap map[s
}
// 处理道岔上的应答器
transponders := turnout.transponders[refVal.DevicePort]
if transponders != nil {
for _, t := range transponders {
if judgeKilometerIsVaild(t.KilometerSystem) && deviceMap[t.Common.Id] == nil {
deviceMap[t.Common.Id] = &graphicData.CalculateLink_DevicePosition{
DeviceId: t.Common.Id,
Offset: offset + int32(math.Abs(float64(t.KilometerSystem.Kilometer-prevKm))),
DeviceType: "Transponder",
}
for _, t := range transponders {
if judgeKilometerIsVaild(t.KilometerSystem) && deviceMap[t.Common.Id] == nil {
deviceMap[t.Common.Id] = &graphicData.CalculateLink_DevicePosition{
DeviceId: t.Common.Id,
Offset: offset + int32(math.Abs(float64(t.KilometerSystem.Kilometer-prevKm))),
DeviceType: "Transponder",
}
}
}
// 坡度
sm := turnout.slopes[refVal.DevicePort]
if sm != nil {
for id, s := range sm {
if judgeKilometerIsVaild(s) && deviceMap[id] == nil {
deviceMap[id] = &graphicData.CalculateLink_DevicePosition{
DeviceId: id,
Offset: offset + int32(math.Abs(float64(s.Kilometer-prevKm))),
DeviceType: "slopes",
}
for id, s := range sm {
if judgeKilometerIsVaild(s) && deviceMap[id] == nil {
deviceMap[id] = &graphicData.CalculateLink_DevicePosition{
DeviceId: id,
Offset: offset + int32(math.Abs(float64(s.Kilometer-prevKm))),
DeviceType: "slopes",
}
}
}
// 曲度
cm := turnout.curvatures[refVal.DevicePort]
if cm != nil {
for id, c := range cm {
if judgeKilometerIsVaild(c) && deviceMap[id] == nil {
deviceMap[id] = &graphicData.CalculateLink_DevicePosition{
DeviceId: id,
Offset: offset + int32(math.Abs(float64(c.Kilometer-prevKm))),
DeviceType: "curvatures",
}
for id, c := range cm {
if judgeKilometerIsVaild(c) && deviceMap[id] == nil {
deviceMap[id] = &graphicData.CalculateLink_DevicePosition{
DeviceId: id,
Offset: offset + int32(math.Abs(float64(c.Kilometer-prevKm))),
DeviceType: "curvatures",
}
}
}

View File

@ -20,6 +20,7 @@ var (
Category *category
Drafting *drafting
PublishedGi *publishedGi
TrainModel *trainModel
User *user
)
@ -28,6 +29,7 @@ func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
Category = &Q.Category
Drafting = &Q.Drafting
PublishedGi = &Q.PublishedGi
TrainModel = &Q.TrainModel
User = &Q.User
}
@ -37,6 +39,7 @@ func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
Category: newCategory(db, opts...),
Drafting: newDrafting(db, opts...),
PublishedGi: newPublishedGi(db, opts...),
TrainModel: newTrainModel(db, opts...),
User: newUser(db, opts...),
}
}
@ -47,6 +50,7 @@ type Query struct {
Category category
Drafting drafting
PublishedGi publishedGi
TrainModel trainModel
User user
}
@ -58,6 +62,7 @@ func (q *Query) clone(db *gorm.DB) *Query {
Category: q.Category.clone(db),
Drafting: q.Drafting.clone(db),
PublishedGi: q.PublishedGi.clone(db),
TrainModel: q.TrainModel.clone(db),
User: q.User.clone(db),
}
}
@ -76,6 +81,7 @@ func (q *Query) ReplaceDB(db *gorm.DB) *Query {
Category: q.Category.replaceDB(db),
Drafting: q.Drafting.replaceDB(db),
PublishedGi: q.PublishedGi.replaceDB(db),
TrainModel: q.TrainModel.replaceDB(db),
User: q.User.replaceDB(db),
}
}
@ -84,6 +90,7 @@ type queryCtx struct {
Category ICategoryDo
Drafting IDraftingDo
PublishedGi IPublishedGiDo
TrainModel ITrainModelDo
User IUserDo
}
@ -92,6 +99,7 @@ func (q *Query) WithContext(ctx context.Context) *queryCtx {
Category: q.Category.WithContext(ctx),
Drafting: q.Drafting.WithContext(ctx),
PublishedGi: q.PublishedGi.WithContext(ctx),
TrainModel: q.TrainModel.WithContext(ctx),
User: q.User.WithContext(ctx),
}
}

View File

@ -0,0 +1,396 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package dbquery
import (
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
"joylink.club/bj-rtsts-server/db/model"
)
func newTrainGroup(db *gorm.DB, opts ...gen.DOOption) trainGroup {
_trainGroup := trainGroup{}
_trainGroup.trainGroupDo.UseDB(db, opts...)
_trainGroup.trainGroupDo.UseModel(&model.TrainGroup{})
tableName := _trainGroup.trainGroupDo.TableName()
_trainGroup.ALL = field.NewAsterisk(tableName)
_trainGroup.ID = field.NewInt32(tableName, "id")
_trainGroup.Name = field.NewString(tableName, "name")
_trainGroup.CarriageLength = field.NewInt32(tableName, "carriage_length")
_trainGroup.CreatedAt = field.NewTime(tableName, "created_at")
_trainGroup.UpdateAt = field.NewTime(tableName, "update_at")
_trainGroup.fillFieldMap()
return _trainGroup
}
type trainGroup struct {
trainGroupDo
ALL field.Asterisk
ID field.Int32
Name field.String // 组次名称
CarriageLength field.Int32 // 单个车厢长度
CreatedAt field.Time // 创建时间
UpdateAt field.Time // 更新时间
fieldMap map[string]field.Expr
}
func (t trainGroup) Table(newTableName string) *trainGroup {
t.trainGroupDo.UseTable(newTableName)
return t.updateTableName(newTableName)
}
func (t trainGroup) As(alias string) *trainGroup {
t.trainGroupDo.DO = *(t.trainGroupDo.As(alias).(*gen.DO))
return t.updateTableName(alias)
}
func (t *trainGroup) updateTableName(table string) *trainGroup {
t.ALL = field.NewAsterisk(table)
t.ID = field.NewInt32(table, "id")
t.Name = field.NewString(table, "name")
t.CarriageLength = field.NewInt32(table, "carriage_length")
t.CreatedAt = field.NewTime(table, "created_at")
t.UpdateAt = field.NewTime(table, "update_at")
t.fillFieldMap()
return t
}
func (t *trainGroup) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := t.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (t *trainGroup) fillFieldMap() {
t.fieldMap = make(map[string]field.Expr, 5)
t.fieldMap["id"] = t.ID
t.fieldMap["name"] = t.Name
t.fieldMap["carriage_length"] = t.CarriageLength
t.fieldMap["created_at"] = t.CreatedAt
t.fieldMap["update_at"] = t.UpdateAt
}
func (t trainGroup) clone(db *gorm.DB) trainGroup {
t.trainGroupDo.ReplaceConnPool(db.Statement.ConnPool)
return t
}
func (t trainGroup) replaceDB(db *gorm.DB) trainGroup {
t.trainGroupDo.ReplaceDB(db)
return t
}
type trainGroupDo struct{ gen.DO }
type ITrainGroupDo interface {
gen.SubQuery
Debug() ITrainGroupDo
WithContext(ctx context.Context) ITrainGroupDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() ITrainGroupDo
WriteDB() ITrainGroupDo
As(alias string) gen.Dao
Session(config *gorm.Session) ITrainGroupDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) ITrainGroupDo
Not(conds ...gen.Condition) ITrainGroupDo
Or(conds ...gen.Condition) ITrainGroupDo
Select(conds ...field.Expr) ITrainGroupDo
Where(conds ...gen.Condition) ITrainGroupDo
Order(conds ...field.Expr) ITrainGroupDo
Distinct(cols ...field.Expr) ITrainGroupDo
Omit(cols ...field.Expr) ITrainGroupDo
Join(table schema.Tabler, on ...field.Expr) ITrainGroupDo
LeftJoin(table schema.Tabler, on ...field.Expr) ITrainGroupDo
RightJoin(table schema.Tabler, on ...field.Expr) ITrainGroupDo
Group(cols ...field.Expr) ITrainGroupDo
Having(conds ...gen.Condition) ITrainGroupDo
Limit(limit int) ITrainGroupDo
Offset(offset int) ITrainGroupDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) ITrainGroupDo
Unscoped() ITrainGroupDo
Create(values ...*model.TrainGroup) error
CreateInBatches(values []*model.TrainGroup, batchSize int) error
Save(values ...*model.TrainGroup) error
First() (*model.TrainGroup, error)
Take() (*model.TrainGroup, error)
Last() (*model.TrainGroup, error)
Find() ([]*model.TrainGroup, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.TrainGroup, err error)
FindInBatches(result *[]*model.TrainGroup, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.TrainGroup) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) ITrainGroupDo
Assign(attrs ...field.AssignExpr) ITrainGroupDo
Joins(fields ...field.RelationField) ITrainGroupDo
Preload(fields ...field.RelationField) ITrainGroupDo
FirstOrInit() (*model.TrainGroup, error)
FirstOrCreate() (*model.TrainGroup, error)
FindByPage(offset int, limit int) (result []*model.TrainGroup, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) ITrainGroupDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (t trainGroupDo) Debug() ITrainGroupDo {
return t.withDO(t.DO.Debug())
}
func (t trainGroupDo) WithContext(ctx context.Context) ITrainGroupDo {
return t.withDO(t.DO.WithContext(ctx))
}
func (t trainGroupDo) ReadDB() ITrainGroupDo {
return t.Clauses(dbresolver.Read)
}
func (t trainGroupDo) WriteDB() ITrainGroupDo {
return t.Clauses(dbresolver.Write)
}
func (t trainGroupDo) Session(config *gorm.Session) ITrainGroupDo {
return t.withDO(t.DO.Session(config))
}
func (t trainGroupDo) Clauses(conds ...clause.Expression) ITrainGroupDo {
return t.withDO(t.DO.Clauses(conds...))
}
func (t trainGroupDo) Returning(value interface{}, columns ...string) ITrainGroupDo {
return t.withDO(t.DO.Returning(value, columns...))
}
func (t trainGroupDo) Not(conds ...gen.Condition) ITrainGroupDo {
return t.withDO(t.DO.Not(conds...))
}
func (t trainGroupDo) Or(conds ...gen.Condition) ITrainGroupDo {
return t.withDO(t.DO.Or(conds...))
}
func (t trainGroupDo) Select(conds ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.Select(conds...))
}
func (t trainGroupDo) Where(conds ...gen.Condition) ITrainGroupDo {
return t.withDO(t.DO.Where(conds...))
}
func (t trainGroupDo) Order(conds ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.Order(conds...))
}
func (t trainGroupDo) Distinct(cols ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.Distinct(cols...))
}
func (t trainGroupDo) Omit(cols ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.Omit(cols...))
}
func (t trainGroupDo) Join(table schema.Tabler, on ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.Join(table, on...))
}
func (t trainGroupDo) LeftJoin(table schema.Tabler, on ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.LeftJoin(table, on...))
}
func (t trainGroupDo) RightJoin(table schema.Tabler, on ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.RightJoin(table, on...))
}
func (t trainGroupDo) Group(cols ...field.Expr) ITrainGroupDo {
return t.withDO(t.DO.Group(cols...))
}
func (t trainGroupDo) Having(conds ...gen.Condition) ITrainGroupDo {
return t.withDO(t.DO.Having(conds...))
}
func (t trainGroupDo) Limit(limit int) ITrainGroupDo {
return t.withDO(t.DO.Limit(limit))
}
func (t trainGroupDo) Offset(offset int) ITrainGroupDo {
return t.withDO(t.DO.Offset(offset))
}
func (t trainGroupDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ITrainGroupDo {
return t.withDO(t.DO.Scopes(funcs...))
}
func (t trainGroupDo) Unscoped() ITrainGroupDo {
return t.withDO(t.DO.Unscoped())
}
func (t trainGroupDo) Create(values ...*model.TrainGroup) error {
if len(values) == 0 {
return nil
}
return t.DO.Create(values)
}
func (t trainGroupDo) CreateInBatches(values []*model.TrainGroup, batchSize int) error {
return t.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (t trainGroupDo) Save(values ...*model.TrainGroup) error {
if len(values) == 0 {
return nil
}
return t.DO.Save(values)
}
func (t trainGroupDo) First() (*model.TrainGroup, error) {
if result, err := t.DO.First(); err != nil {
return nil, err
} else {
return result.(*model.TrainGroup), nil
}
}
func (t trainGroupDo) Take() (*model.TrainGroup, error) {
if result, err := t.DO.Take(); err != nil {
return nil, err
} else {
return result.(*model.TrainGroup), nil
}
}
func (t trainGroupDo) Last() (*model.TrainGroup, error) {
if result, err := t.DO.Last(); err != nil {
return nil, err
} else {
return result.(*model.TrainGroup), nil
}
}
func (t trainGroupDo) Find() ([]*model.TrainGroup, error) {
result, err := t.DO.Find()
return result.([]*model.TrainGroup), err
}
func (t trainGroupDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.TrainGroup, err error) {
buf := make([]*model.TrainGroup, 0, batchSize)
err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (t trainGroupDo) FindInBatches(result *[]*model.TrainGroup, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return t.DO.FindInBatches(result, batchSize, fc)
}
func (t trainGroupDo) Attrs(attrs ...field.AssignExpr) ITrainGroupDo {
return t.withDO(t.DO.Attrs(attrs...))
}
func (t trainGroupDo) Assign(attrs ...field.AssignExpr) ITrainGroupDo {
return t.withDO(t.DO.Assign(attrs...))
}
func (t trainGroupDo) Joins(fields ...field.RelationField) ITrainGroupDo {
for _, _f := range fields {
t = *t.withDO(t.DO.Joins(_f))
}
return &t
}
func (t trainGroupDo) Preload(fields ...field.RelationField) ITrainGroupDo {
for _, _f := range fields {
t = *t.withDO(t.DO.Preload(_f))
}
return &t
}
func (t trainGroupDo) FirstOrInit() (*model.TrainGroup, error) {
if result, err := t.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*model.TrainGroup), nil
}
}
func (t trainGroupDo) FirstOrCreate() (*model.TrainGroup, error) {
if result, err := t.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*model.TrainGroup), nil
}
}
func (t trainGroupDo) FindByPage(offset int, limit int) (result []*model.TrainGroup, count int64, err error) {
result, err = t.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = t.Offset(-1).Limit(-1).Count()
return
}
func (t trainGroupDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = t.Count()
if err != nil {
return
}
err = t.Offset(offset).Limit(limit).Scan(result)
return
}
func (t trainGroupDo) Scan(result interface{}) (err error) {
return t.DO.Scan(result)
}
func (t trainGroupDo) Delete(models ...*model.TrainGroup) (result gen.ResultInfo, err error) {
return t.DO.Delete(models)
}
func (t *trainGroupDo) withDO(do gen.Dao) *trainGroupDo {
t.DO = *do.(*gen.DO)
return t
}

View File

@ -0,0 +1,396 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package dbquery
import (
"context"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
"gorm.io/gen"
"gorm.io/gen/field"
"gorm.io/plugin/dbresolver"
"joylink.club/bj-rtsts-server/db/model"
)
func newTrainModel(db *gorm.DB, opts ...gen.DOOption) trainModel {
_trainModel := trainModel{}
_trainModel.trainModelDo.UseDB(db, opts...)
_trainModel.trainModelDo.UseModel(&model.TrainModel{})
tableName := _trainModel.trainModelDo.TableName()
_trainModel.ALL = field.NewAsterisk(tableName)
_trainModel.ID = field.NewInt32(tableName, "id")
_trainModel.Name = field.NewString(tableName, "name")
_trainModel.CarriageLength = field.NewInt32(tableName, "carriage_length")
_trainModel.CreatedAt = field.NewTime(tableName, "created_at")
_trainModel.UpdateAt = field.NewTime(tableName, "update_at")
_trainModel.fillFieldMap()
return _trainModel
}
type trainModel struct {
trainModelDo
ALL field.Asterisk
ID field.Int32
Name field.String // 组次名称
CarriageLength field.Int32 // 单个车厢长度
CreatedAt field.Time // 创建时间
UpdateAt field.Time // 更新时间
fieldMap map[string]field.Expr
}
func (t trainModel) Table(newTableName string) *trainModel {
t.trainModelDo.UseTable(newTableName)
return t.updateTableName(newTableName)
}
func (t trainModel) As(alias string) *trainModel {
t.trainModelDo.DO = *(t.trainModelDo.As(alias).(*gen.DO))
return t.updateTableName(alias)
}
func (t *trainModel) updateTableName(table string) *trainModel {
t.ALL = field.NewAsterisk(table)
t.ID = field.NewInt32(table, "id")
t.Name = field.NewString(table, "name")
t.CarriageLength = field.NewInt32(table, "carriage_length")
t.CreatedAt = field.NewTime(table, "created_at")
t.UpdateAt = field.NewTime(table, "update_at")
t.fillFieldMap()
return t
}
func (t *trainModel) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
_f, ok := t.fieldMap[fieldName]
if !ok || _f == nil {
return nil, false
}
_oe, ok := _f.(field.OrderExpr)
return _oe, ok
}
func (t *trainModel) fillFieldMap() {
t.fieldMap = make(map[string]field.Expr, 5)
t.fieldMap["id"] = t.ID
t.fieldMap["name"] = t.Name
t.fieldMap["carriage_length"] = t.CarriageLength
t.fieldMap["created_at"] = t.CreatedAt
t.fieldMap["update_at"] = t.UpdateAt
}
func (t trainModel) clone(db *gorm.DB) trainModel {
t.trainModelDo.ReplaceConnPool(db.Statement.ConnPool)
return t
}
func (t trainModel) replaceDB(db *gorm.DB) trainModel {
t.trainModelDo.ReplaceDB(db)
return t
}
type trainModelDo struct{ gen.DO }
type ITrainModelDo interface {
gen.SubQuery
Debug() ITrainModelDo
WithContext(ctx context.Context) ITrainModelDo
WithResult(fc func(tx gen.Dao)) gen.ResultInfo
ReplaceDB(db *gorm.DB)
ReadDB() ITrainModelDo
WriteDB() ITrainModelDo
As(alias string) gen.Dao
Session(config *gorm.Session) ITrainModelDo
Columns(cols ...field.Expr) gen.Columns
Clauses(conds ...clause.Expression) ITrainModelDo
Not(conds ...gen.Condition) ITrainModelDo
Or(conds ...gen.Condition) ITrainModelDo
Select(conds ...field.Expr) ITrainModelDo
Where(conds ...gen.Condition) ITrainModelDo
Order(conds ...field.Expr) ITrainModelDo
Distinct(cols ...field.Expr) ITrainModelDo
Omit(cols ...field.Expr) ITrainModelDo
Join(table schema.Tabler, on ...field.Expr) ITrainModelDo
LeftJoin(table schema.Tabler, on ...field.Expr) ITrainModelDo
RightJoin(table schema.Tabler, on ...field.Expr) ITrainModelDo
Group(cols ...field.Expr) ITrainModelDo
Having(conds ...gen.Condition) ITrainModelDo
Limit(limit int) ITrainModelDo
Offset(offset int) ITrainModelDo
Count() (count int64, err error)
Scopes(funcs ...func(gen.Dao) gen.Dao) ITrainModelDo
Unscoped() ITrainModelDo
Create(values ...*model.TrainModel) error
CreateInBatches(values []*model.TrainModel, batchSize int) error
Save(values ...*model.TrainModel) error
First() (*model.TrainModel, error)
Take() (*model.TrainModel, error)
Last() (*model.TrainModel, error)
Find() ([]*model.TrainModel, error)
FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.TrainModel, err error)
FindInBatches(result *[]*model.TrainModel, batchSize int, fc func(tx gen.Dao, batch int) error) error
Pluck(column field.Expr, dest interface{}) error
Delete(...*model.TrainModel) (info gen.ResultInfo, err error)
Update(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
Updates(value interface{}) (info gen.ResultInfo, err error)
UpdateColumn(column field.Expr, value interface{}) (info gen.ResultInfo, err error)
UpdateColumnSimple(columns ...field.AssignExpr) (info gen.ResultInfo, err error)
UpdateColumns(value interface{}) (info gen.ResultInfo, err error)
UpdateFrom(q gen.SubQuery) gen.Dao
Attrs(attrs ...field.AssignExpr) ITrainModelDo
Assign(attrs ...field.AssignExpr) ITrainModelDo
Joins(fields ...field.RelationField) ITrainModelDo
Preload(fields ...field.RelationField) ITrainModelDo
FirstOrInit() (*model.TrainModel, error)
FirstOrCreate() (*model.TrainModel, error)
FindByPage(offset int, limit int) (result []*model.TrainModel, count int64, err error)
ScanByPage(result interface{}, offset int, limit int) (count int64, err error)
Scan(result interface{}) (err error)
Returning(value interface{}, columns ...string) ITrainModelDo
UnderlyingDB() *gorm.DB
schema.Tabler
}
func (t trainModelDo) Debug() ITrainModelDo {
return t.withDO(t.DO.Debug())
}
func (t trainModelDo) WithContext(ctx context.Context) ITrainModelDo {
return t.withDO(t.DO.WithContext(ctx))
}
func (t trainModelDo) ReadDB() ITrainModelDo {
return t.Clauses(dbresolver.Read)
}
func (t trainModelDo) WriteDB() ITrainModelDo {
return t.Clauses(dbresolver.Write)
}
func (t trainModelDo) Session(config *gorm.Session) ITrainModelDo {
return t.withDO(t.DO.Session(config))
}
func (t trainModelDo) Clauses(conds ...clause.Expression) ITrainModelDo {
return t.withDO(t.DO.Clauses(conds...))
}
func (t trainModelDo) Returning(value interface{}, columns ...string) ITrainModelDo {
return t.withDO(t.DO.Returning(value, columns...))
}
func (t trainModelDo) Not(conds ...gen.Condition) ITrainModelDo {
return t.withDO(t.DO.Not(conds...))
}
func (t trainModelDo) Or(conds ...gen.Condition) ITrainModelDo {
return t.withDO(t.DO.Or(conds...))
}
func (t trainModelDo) Select(conds ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.Select(conds...))
}
func (t trainModelDo) Where(conds ...gen.Condition) ITrainModelDo {
return t.withDO(t.DO.Where(conds...))
}
func (t trainModelDo) Order(conds ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.Order(conds...))
}
func (t trainModelDo) Distinct(cols ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.Distinct(cols...))
}
func (t trainModelDo) Omit(cols ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.Omit(cols...))
}
func (t trainModelDo) Join(table schema.Tabler, on ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.Join(table, on...))
}
func (t trainModelDo) LeftJoin(table schema.Tabler, on ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.LeftJoin(table, on...))
}
func (t trainModelDo) RightJoin(table schema.Tabler, on ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.RightJoin(table, on...))
}
func (t trainModelDo) Group(cols ...field.Expr) ITrainModelDo {
return t.withDO(t.DO.Group(cols...))
}
func (t trainModelDo) Having(conds ...gen.Condition) ITrainModelDo {
return t.withDO(t.DO.Having(conds...))
}
func (t trainModelDo) Limit(limit int) ITrainModelDo {
return t.withDO(t.DO.Limit(limit))
}
func (t trainModelDo) Offset(offset int) ITrainModelDo {
return t.withDO(t.DO.Offset(offset))
}
func (t trainModelDo) Scopes(funcs ...func(gen.Dao) gen.Dao) ITrainModelDo {
return t.withDO(t.DO.Scopes(funcs...))
}
func (t trainModelDo) Unscoped() ITrainModelDo {
return t.withDO(t.DO.Unscoped())
}
func (t trainModelDo) Create(values ...*model.TrainModel) error {
if len(values) == 0 {
return nil
}
return t.DO.Create(values)
}
func (t trainModelDo) CreateInBatches(values []*model.TrainModel, batchSize int) error {
return t.DO.CreateInBatches(values, batchSize)
}
// Save : !!! underlying implementation is different with GORM
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
func (t trainModelDo) Save(values ...*model.TrainModel) error {
if len(values) == 0 {
return nil
}
return t.DO.Save(values)
}
func (t trainModelDo) First() (*model.TrainModel, error) {
if result, err := t.DO.First(); err != nil {
return nil, err
} else {
return result.(*model.TrainModel), nil
}
}
func (t trainModelDo) Take() (*model.TrainModel, error) {
if result, err := t.DO.Take(); err != nil {
return nil, err
} else {
return result.(*model.TrainModel), nil
}
}
func (t trainModelDo) Last() (*model.TrainModel, error) {
if result, err := t.DO.Last(); err != nil {
return nil, err
} else {
return result.(*model.TrainModel), nil
}
}
func (t trainModelDo) Find() ([]*model.TrainModel, error) {
result, err := t.DO.Find()
return result.([]*model.TrainModel), err
}
func (t trainModelDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.TrainModel, err error) {
buf := make([]*model.TrainModel, 0, batchSize)
err = t.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
defer func() { results = append(results, buf...) }()
return fc(tx, batch)
})
return results, err
}
func (t trainModelDo) FindInBatches(result *[]*model.TrainModel, batchSize int, fc func(tx gen.Dao, batch int) error) error {
return t.DO.FindInBatches(result, batchSize, fc)
}
func (t trainModelDo) Attrs(attrs ...field.AssignExpr) ITrainModelDo {
return t.withDO(t.DO.Attrs(attrs...))
}
func (t trainModelDo) Assign(attrs ...field.AssignExpr) ITrainModelDo {
return t.withDO(t.DO.Assign(attrs...))
}
func (t trainModelDo) Joins(fields ...field.RelationField) ITrainModelDo {
for _, _f := range fields {
t = *t.withDO(t.DO.Joins(_f))
}
return &t
}
func (t trainModelDo) Preload(fields ...field.RelationField) ITrainModelDo {
for _, _f := range fields {
t = *t.withDO(t.DO.Preload(_f))
}
return &t
}
func (t trainModelDo) FirstOrInit() (*model.TrainModel, error) {
if result, err := t.DO.FirstOrInit(); err != nil {
return nil, err
} else {
return result.(*model.TrainModel), nil
}
}
func (t trainModelDo) FirstOrCreate() (*model.TrainModel, error) {
if result, err := t.DO.FirstOrCreate(); err != nil {
return nil, err
} else {
return result.(*model.TrainModel), nil
}
}
func (t trainModelDo) FindByPage(offset int, limit int) (result []*model.TrainModel, count int64, err error) {
result, err = t.Offset(offset).Limit(limit).Find()
if err != nil {
return
}
if size := len(result); 0 < limit && 0 < size && size < limit {
count = int64(size + offset)
return
}
count, err = t.Offset(-1).Limit(-1).Count()
return
}
func (t trainModelDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
count, err = t.Count()
if err != nil {
return
}
err = t.Offset(offset).Limit(limit).Scan(result)
return
}
func (t trainModelDo) Scan(result interface{}) (err error) {
return t.DO.Scan(result)
}
func (t trainModelDo) Delete(models ...*model.TrainModel) (result gen.ResultInfo, err error) {
return t.DO.Delete(models)
}
func (t *trainModelDo) withDO(do gen.Dao) *trainModelDo {
t.DO = *do.(*gen.DO)
return t
}

View File

@ -0,0 +1,25 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package model
import (
"time"
)
const TableNameTrainGroup = "train_group"
// TrainGroup mapped from table <train_group>
type TrainGroup struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Name string `gorm:"column:name;comment:组次名称" json:"name"` // 组次名称
CarriageLength int32 `gorm:"column:carriage_length;comment:单个车厢长度" json:"carriage_length"` // 单个车厢长度
CreatedAt time.Time `gorm:"column:created_at;comment:创建时间" json:"created_at"` // 创建时间
UpdateAt time.Time `gorm:"column:update_at;comment:更新时间" json:"update_at"` // 更新时间
}
// TableName TrainGroup's table name
func (*TrainGroup) TableName() string {
return TableNameTrainGroup
}

View File

@ -0,0 +1,25 @@
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
// Code generated by gorm.io/gen. DO NOT EDIT.
package model
import (
"time"
)
const TableNameTrainModel = "train_model"
// TrainModel mapped from table <train_model>
type TrainModel struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
Name string `gorm:"column:name;comment:组次名称" json:"name"` // 组次名称
CarriageLength int32 `gorm:"column:carriage_length;comment:单个车厢长度" json:"carriage_length"` // 单个车厢长度
CreatedAt time.Time `gorm:"column:created_at;comment:创建时间" json:"created_at"` // 创建时间
UpdateAt time.Time `gorm:"column:update_at;comment:更新时间" json:"update_at"` // 更新时间
}
// TableName TrainModel's table name
func (*TrainModel) TableName() string {
return TableNameTrainModel
}

View File

@ -32,6 +32,10 @@ type AddTrainReqDto struct {
DevicePort string `json:"devicePort" form:"devicePort"`
//车头所在link内的偏移量单位为mm
HeadOffset int64 `json:"headOffset" form:"headOffset"`
//列车信号ID
TrainModelId int32 `json:"trainModelId" from:"trainModelId"`
//列车车厢数
CarriageNum int32 `json:"carriageNum" from:"carriageNum"`
}
// 为仿真添加测试车请求

16
dto/trainModel.go Normal file
View File

@ -0,0 +1,16 @@
package dto
type PageTrainModelReqDto struct {
PageQueryDto
Name string `json:"name" form:"name"`
}
type TrainModelReqDto struct {
Name string `json:"name" form:"name"`
}
type TrainModelDto struct {
Id int `json:"id" form:"id"`
Name string `json:"name" form:"name"`
CarriageLength int32 `json:"carriageLength" form:"carriageLength"`
}

122
service/trainModel.go Normal file
View File

@ -0,0 +1,122 @@
package service
import (
"fmt"
"time"
"joylink.club/bj-rtsts-server/db/dbquery"
"joylink.club/bj-rtsts-server/db/model"
"joylink.club/bj-rtsts-server/dto"
)
// 查询列车型号信息列表
func PageTrainModelQuery(query *dto.PageTrainModelReqDto) (*dto.PageDto, error) {
d := dbquery.TrainModel
dq := d.Where()
if query.Name != "" {
dq = dq.Where(d.Name.Like(fmt.Sprintf("%%%s%%", query.Name)))
}
records, total, err := dq.Debug().Select(d.ID, d.Name, d.CarriageLength, d.UpdateAt, d.CreatedAt).FindByPage(query.Offset(), query.Size)
if err != nil {
panic(err)
}
return &dto.PageDto{Total: int(total), PageQueryDto: query.PageQueryDto, Records: records}, nil
}
// 查询列车型号信息列表
func ListTrainModelQuery(query *dto.TrainModelReqDto) ([]*model.TrainModel, error) {
d := dbquery.TrainModel
dq := d.Where()
if query.Name != "" {
dq = dq.Where(d.Name.Like(fmt.Sprintf("%%%s%%", query.Name)))
}
records, err := dq.Debug().Select(d.ID, d.Name, d.CarriageLength, d.UpdateAt, d.CreatedAt).Find()
if err != nil {
panic(err)
}
return records, nil
}
// 创建列车型号信息
func CreateTrainModel(dto *dto.TrainModelDto) (*model.TrainModel, error) {
if err := checkTrainModel(dto.Name, 0); err != nil {
panic(err)
}
d := model.TrainModel{
Name: dto.Name,
CarriageLength: dto.CarriageLength,
CreatedAt: time.Now(),
UpdateAt: time.Now(),
}
dt := dbquery.TrainModel
err := dt.Save(&d)
if err != nil {
panic(err)
}
return dt.Where(dt.Name.Eq(dto.Name)).Order(dt.CreatedAt).Debug().First()
}
// 查询列车型号信息
func QueryTrainModel(id int32) *model.TrainModel {
dt := dbquery.TrainModel
data, err := dt.Where(dt.ID.Eq(id)).Debug().First()
if err != nil {
panic(err)
}
return data
}
// 更新列车型号信息
func UpdateTrainModel(id int32, dto *dto.TrainModelDto) bool {
if err := checkTrainModel(dto.Name, id); err != nil {
panic(err)
}
findOldQuery := dbquery.TrainModel
oldD, err := findOldQuery.Where(findOldQuery.ID.Eq(id)).Debug().First()
if oldD == nil || err != nil {
panic(err)
}
if len(dto.Name) > 0 {
oldD.Name = dto.Name
}
oldD.UpdateAt = time.Now()
_, error := dbquery.TrainModel.Updates(oldD)
if error != nil {
panic(error)
}
return true
}
// 删除列车型号
func DeleteTrainModelById(id int) {
_, _ = dbquery.TrainModel.Debug().Where(dbquery.TrainModel.ID.Eq(int32(id))).Delete()
}
// 根据列车型号跟车厢数量计算列车长度
func CalcTrainLenght(id, num int32) int32 {
dt := dbquery.TrainModel
data, err := dt.Select(dt.CarriageLength).Where(dt.ID.Eq(id)).Debug().First()
if err != nil {
panic(err)
}
return data.CarriageLength * num
}
// 检查列车型号名称
func checkTrainModel(name string, id int32) error {
findNameQuery := dbquery.TrainModel
w := findNameQuery.Where()
if id != 0 {
w = w.Where(findNameQuery.ID.Eq(id))
}
if name != "" {
count, err := w.Where(findNameQuery.Name.Eq(name)).Debug().Count()
if err != nil {
panic(err)
}
if count > 0 {
panic("名称已存在")
}
}
return nil
}