zhangqian
2023-10-09 468ceb8a9bfe9e15e3be470b23809dde83a11f0d
merge master
1个文件已添加
14个文件已修改
515 ■■■■ 已修改文件
api/v1/process_model.go 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
api/v1/task.go 104 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/docs.go 90 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/swagger.json 90 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/swagger.yaml 62 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
model/procedures.go 24 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
model/process_model.go 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
model/request/task.go 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pkg/contextx/contextx.go 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/index.go 19 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
service/cache_store.go 17 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
service/process_model.go 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
service/task.go 27 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
test/task_test.go 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
test/test.go 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
api/v1/process_model.go
@@ -15,23 +15,12 @@
// @Summary   获取工艺模型列表
// @Produce   application/json
// @Param     object  query    request.ProcessModelList true  "查询参数"
// @Success   200   {object}  contextx.Response{data=response.TaskCountdown}  "成功"
// @Success   200   {object}  contextx.Response{data=[]model.ProcessModel}  "成功"
// @Router    /v1/processModel/list [get]
func (slf *ProcessModelApi) List(c *gin.Context) {
    var params request.ProcessModelList
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    procedure, code := service.NewTaskService().GetProcedureById(params.ProcedureId)
    if code != ecode.OK {
        ctx.Fail(code)
        return
    }
    order, err := service.NewTaskService().GetOrderByWorkOrderId(procedure.WorkOrderID)
    if err != nil {
        ctx.Fail(ecode.DBErr)
        return
    }
@@ -40,10 +29,16 @@
        ctx.Fail(ecode.DBErr)
        return
    }
    oldProcessModel, _ := service.GetProcessModelByNumber(params.Number)
    for _, processModel := range list {
        if processModel.Procedure == procedure.ProceduresInfo.ProcedureName && processModel.Product == order.ProductName {
        if processModel.Procedure == oldProcessModel.Procedure && processModel.Product == oldProcessModel.Product {
            processModel.IsUpdate = processModel.Number != params.Number
        }
        if processModel.IsUpdate {
            processModel.NewNumber, processModel.NewParamsMap = processModel.Number, processModel.ParamsMap
            processModel.Number, processModel.ParamsMap = oldProcessModel.Number, oldProcessModel.ParamsMap
        }
    }
    ctx.ResultList(list, total)
api/v1/task.go
@@ -68,10 +68,14 @@
        return
    }
    taskCount := service.NewTaskService().NewTaskCount()
    params.Page = 1
    if params.PageSize <= 0 {
        params.PageSize = channelAmount
        if params.TaskMode == constvar.TaskModeUnStarted {
            params.PageSize = int(taskCount)
        } else {
            params.PageSize = channelAmount
        }
    }
    taskMode := constvar.TaskModeCurrent
@@ -107,15 +111,18 @@
        return taskResponse.Tasks[i].Channel < taskResponse.Tasks[i].Channel
    })
    nowTs := time.Now().Unix()
    flagMap := make(map[int32]struct{}, 0)
    for _, task := range taskResponse.Tasks {
        if !service.TaskFlagGet(task.Channel) {
        if _, ok := flagMap[task.Channel]; !ok && !service.TaskFlagGet(task.Channel) && task.Procedure.StartTime <= nowTs {
            task.CanStarted = true
            flagMap[task.Channel] = struct{}{}
        }
    }
    taskResponse.Prompt = conf.Conf.Prompt
    taskResponse.ChannelAmount = channelAmount
    taskResponse.TaskCount = service.NewTaskService().NewTaskCount()
    taskResponse.TaskCount = taskCount
    ctx.OkWithDetailed(taskResponse)
}
@@ -149,11 +156,19 @@
        ctx.Fail(ecode.DBErr)
        return
    }
    processModel, err := service.NewTaskService().GetProcessParams(procedure, order)
    if err != nil || processModel == nil || processModel.ParamsMap == nil {
        ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!")
        return
    var processModel *model.ProcessModel
    if procedure.ProcessModelNumber != "" {
        processModel, err = service.GetProcessModelByNumber(procedure.ProcessModelNumber)
        if err != nil || processModel == nil || processModel.ParamsMap == nil {
            ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!")
            return
        }
    } else {
        processModel, err = service.NewTaskService().GetProcessParams(procedure, order)
        if err != nil || processModel == nil || processModel.ParamsMap == nil {
            ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!")
            return
        }
    }
    processParamsArr := make([]response.ProcessParams, 0, len(processModel.ParamsMap))
@@ -272,16 +287,15 @@
    }
    processModel, err := taskService.GetProcessParams(procedure, order)
    if err != nil || processModel == nil || processModel.ParamsMap == nil {
        ctx.Fail(ecode.UnknownErr)
        ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!")
        return
    }
    err = model.WithTransaction(func(db *gorm.DB) error {
        err = taskService.UpdateProcedureStatusAndChannel(db, params.ProcedureId, model.ProcedureStatusProcessing, params.Channel)
        err = taskService.UpdateProcedureStatusAndChannel(db, params.ProcedureId, model.ProcedureStatusProcessing, procedure.Channel, processModel.Number)
        if err != nil {
            return err
        }
        procedure.Channel = params.Channel
        err = taskService.UpdateOrderStatus(db, order.ID, model.OrderStatusProcessing)
        if err != nil {
            return err
@@ -303,12 +317,7 @@
    if err != nil {
        logx.Errorf("SendProcessParams: %v", err.Error())
        err = model.WithTransaction(func(db *gorm.DB) error {
            err = taskService.UpdateProcedureStatusAndChannel(db, params.ProcedureId, model.ProcedureStatusWaitProcess, params.Channel)
            if err != nil {
                return err
            }
            procedure.Channel = params.Channel
            err = taskService.UpdateOrderStatus(db, order.ID, model.OrderStatusWaitProcess)
            err = taskService.UpdateProcedureStatusAndChannel(db, params.ProcedureId, model.ProcedureStatusWaitProcess, procedure.Channel, "")
            if err != nil {
                return err
            }
@@ -317,12 +326,8 @@
        ctx.FailWithMsg(ecode.NeedConfirmedErr, "PLC请求失败,请检查PLC配置!")
        return
    }
    if code != ecode.OK {
        logx.Errorf("get plcConfig err: %v", err.Error())
        return
    }
    plcConfig.CurrentTryTimes = 0
    err = service.PlcWrite(plcConfig, constvar.PlcStartAddressTypeTotalNumber, params.Channel, order.Amount.IntPart())
    err = service.PlcWrite(plcConfig, constvar.PlcStartAddressTypeTotalNumber, procedure.Channel, order.Amount.IntPart())
    if err != nil {
        ctx.FailWithMsg(ecode.NeedConfirmedErr, "PLC请求失败,请检查PLC配置")
        return
@@ -345,6 +350,59 @@
    ctx.Ok()
}
// UpdateProcessParams
// @Tags      Task
// @Summary   更新工艺参数(进行中的任务)
// @Produce   application/json
// @Param     object  body    request.SendProcessParams true  "查询参数"
// @Success   200   {object}  contextx.Response{}  "成功"
// @Router    /v1/task/updateProcessParams [post]
func (slf *TaskApi) UpdateProcessParams(c *gin.Context) {
    mutex.Lock()
    defer mutex.Unlock()
    var params request.SendProcessParams
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    taskService := service.NewTaskService()
    procedure, code := taskService.GetProcedureById(params.ProcedureId)
    if code != ecode.OK {
        ctx.Fail(code)
        return
    }
    order, err := taskService.GetOrderByWorkOrderId(procedure.WorkOrderID)
    if err != nil {
        ctx.Fail(ecode.UnknownErr)
        return
    }
    if procedure.Status != model.ProcedureStatusProcessing { //只能进行中的可以更新
        ctx.FailWithMsg(ecode.ParamsErr, "只能进行中的工序可以更新工艺参数")
        return
    }
    processModel, err := taskService.GetProcessParams(procedure, order)
    if err != nil || processModel == nil || processModel.ParamsMap == nil {
        ctx.FailWithMsg(ecode.ParamsErr, "未获取到工艺参数,请在工艺模型库中上传!")
        return
    }
    plcConfig, code := service.NewDevicePlcService().GetDevicePlc()
    if code != ecode.OK || plcConfig.Id == 0 {
        ctx.FailWithMsg(ecode.NeedConfirmedErr, "请先配置PLC")
        return
    }
    plcConfig.MaxTryTimes = 2
    err = SendParams(processModel.ParamsMap, plcConfig)
    if err != nil {
        logx.Errorf("update process params err: %v", err.Error())
        ctx.FailWithMsg(ecode.NeedConfirmedErr, "PLC请求失败,请检查PLC配置!")
        return
    }
    _ = taskService.UpdateProcedureStatusAndChannel(nil, params.ProcedureId, model.ProcedureStatusProcessing, procedure.Channel, processModel.Number)
    ctx.Ok()
}
func SendParams(paramsMap map[string]interface{}, plcConfig *model.DevicePlc) error {
    if len(paramsMap) == 0 {
        return errors.New("empty params")
docs/docs.go
@@ -415,7 +415,10 @@
                                    "type": "object",
                                    "properties": {
                                        "data": {
                                            "$ref": "#/definitions/response.TaskCountdown"
                                            "type": "array",
                                            "items": {
                                                "$ref": "#/definitions/model.ProcessModel"
                                            }
                                        }
                                    }
                                }
@@ -614,6 +617,36 @@
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        },
        "/v1/task/updateProcessParams": {
            "post": {
                "produces": [
                    "application/json"
                ],
                "tags": [
                    "Task"
                ],
                "summary": "更新工艺参数(进行中的任务)",
                "parameters": [
                    {
                        "description": "查询参数",
                        "name": "object",
                        "in": "body",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/request.SendProcessParams"
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "成功",
                        "schema": {
                            "$ref": "#/definitions/contextx.Response"
                        }
                    }
                }
@@ -1038,11 +1071,54 @@
                "procedureId": {
                    "type": "string"
                },
                "processModelNumber": {
                    "description": "工艺模型编号",
                    "type": "string"
                },
                "startTime": {
                    "type": "integer"
                },
                "status": {
                    "$ref": "#/definitions/model.ProcedureStatus"
                }
            }
        },
        "model.ProcessModel": {
            "type": "object",
            "properties": {
                "deviceId": {
                    "description": "用于过滤获取nsq消息",
                    "type": "string"
                },
                "isUpdate": {
                    "description": "前端用",
                    "type": "boolean"
                },
                "newNumber": {
                    "type": "string"
                },
                "newParamsMap": {
                    "type": "object",
                    "additionalProperties": true
                },
                "number": {
                    "description": "工艺模型编号",
                    "type": "string"
                },
                "params": {
                    "type": "string"
                },
                "paramsMap": {
                    "type": "object",
                    "additionalProperties": true
                },
                "procedure": {
                    "description": "工序",
                    "type": "string"
                },
                "product": {
                    "description": "产品名称",
                    "type": "string"
                }
            }
        },
@@ -1063,9 +1139,6 @@
                "procedureId"
            ],
            "properties": {
                "channel": {
                    "type": "integer"
                },
                "procedureId": {
                    "type": "integer"
                }
@@ -1132,15 +1205,6 @@
                },
                "data": {},
                "msg": {
                    "type": "string"
                }
            }
        },
        "response.Message": {
            "type": "object",
            "properties": {
                "data": {},
                "event": {
                    "type": "string"
                }
            }
docs/swagger.json
@@ -403,7 +403,10 @@
                                    "type": "object",
                                    "properties": {
                                        "data": {
                                            "$ref": "#/definitions/response.TaskCountdown"
                                            "type": "array",
                                            "items": {
                                                "$ref": "#/definitions/model.ProcessModel"
                                            }
                                        }
                                    }
                                }
@@ -602,6 +605,36 @@
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        },
        "/v1/task/updateProcessParams": {
            "post": {
                "produces": [
                    "application/json"
                ],
                "tags": [
                    "Task"
                ],
                "summary": "更新工艺参数(进行中的任务)",
                "parameters": [
                    {
                        "description": "查询参数",
                        "name": "object",
                        "in": "body",
                        "required": true,
                        "schema": {
                            "$ref": "#/definitions/request.SendProcessParams"
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "成功",
                        "schema": {
                            "$ref": "#/definitions/contextx.Response"
                        }
                    }
                }
@@ -1026,11 +1059,54 @@
                "procedureId": {
                    "type": "string"
                },
                "processModelNumber": {
                    "description": "工艺模型编号",
                    "type": "string"
                },
                "startTime": {
                    "type": "integer"
                },
                "status": {
                    "$ref": "#/definitions/model.ProcedureStatus"
                }
            }
        },
        "model.ProcessModel": {
            "type": "object",
            "properties": {
                "deviceId": {
                    "description": "用于过滤获取nsq消息",
                    "type": "string"
                },
                "isUpdate": {
                    "description": "前端用",
                    "type": "boolean"
                },
                "newNumber": {
                    "type": "string"
                },
                "newParamsMap": {
                    "type": "object",
                    "additionalProperties": true
                },
                "number": {
                    "description": "工艺模型编号",
                    "type": "string"
                },
                "params": {
                    "type": "string"
                },
                "paramsMap": {
                    "type": "object",
                    "additionalProperties": true
                },
                "procedure": {
                    "description": "工序",
                    "type": "string"
                },
                "product": {
                    "description": "产品名称",
                    "type": "string"
                }
            }
        },
@@ -1051,9 +1127,6 @@
                "procedureId"
            ],
            "properties": {
                "channel": {
                    "type": "integer"
                },
                "procedureId": {
                    "type": "integer"
                }
@@ -1120,15 +1193,6 @@
                },
                "data": {},
                "msg": {
                    "type": "string"
                }
            }
        },
        "response.Message": {
            "type": "object",
            "properties": {
                "data": {},
                "event": {
                    "type": "string"
                }
            }
docs/swagger.yaml
@@ -287,10 +287,41 @@
        description: common.ProductProcedure  对象
      procedureId:
        type: string
      processModelNumber:
        description: 工艺模型编号
        type: string
      startTime:
        type: integer
      status:
        $ref: '#/definitions/model.ProcedureStatus'
    type: object
  model.ProcessModel:
    properties:
      deviceId:
        description: 用于过滤获取nsq消息
        type: string
      isUpdate:
        description: 前端用
        type: boolean
      newNumber:
        type: string
      newParamsMap:
        additionalProperties: true
        type: object
      number:
        description: 工艺模型编号
        type: string
      params:
        type: string
      paramsMap:
        additionalProperties: true
        type: object
      procedure:
        description: 工序
        type: string
      product:
        description: 产品名称
        type: string
    type: object
  request.AddPlcBrand:
    properties:
@@ -301,8 +332,6 @@
    type: object
  request.SendProcessParams:
    properties:
      channel:
        type: integer
      procedureId:
        type: integer
    required:
@@ -352,12 +381,6 @@
        type: integer
      data: {}
      msg:
        type: string
    type: object
  response.Message:
    properties:
      data: {}
      event:
        type: string
    type: object
  response.ProcessParams:
@@ -679,7 +702,9 @@
            - $ref: '#/definitions/contextx.Response'
            - properties:
                data:
                  $ref: '#/definitions/response.TaskCountdown'
                  items:
                    $ref: '#/definitions/model.ProcessModel'
                  type: array
              type: object
      summary: 获取工艺模型列表
      tags:
@@ -802,4 +827,23 @@
      summary: 任务开始(获取工艺参数)
      tags:
      - Task
  /v1/task/updateProcessParams:
    post:
      parameters:
      - description: 查询参数
        in: body
        name: object
        required: true
        schema:
          $ref: '#/definitions/request.SendProcessParams'
      produces:
      - application/json
      responses:
        "200":
          description: 成功
          schema:
            $ref: '#/definitions/contextx.Response'
      summary: 更新工艺参数(进行中的任务)
      tags:
      - Task
swagger: "2.0"
model/procedures.go
@@ -11,17 +11,19 @@
type (
    Procedures struct {
        gorm.Model
        WorkOrderID    string `gorm:"index;type:varchar(191);not null;comment:工单ID" json:"-"`
        OrderID        string `gorm:"index;type:varchar(191);not null;comment:订单ID" json:"-"`
        DeviceID       string `gorm:"index;type:varchar(191);comment:设备ID" json:"deviceId"`
        ProcedureID    string `gorm:"index;type:varchar(191);comment:工序ID" json:"procedureId"`
        Channel        int32  `gorm:"index;comment:通道" json:"channel"` //通道
        StartTime      int64  `gorm:"comment:计划开始时间" json:"startTime"`
        EndTime        int64  `gorm:"comment:计划结束时间" json:"endTime"`
        Status         ProcedureStatus
        ProcedureData  string                  `json:"-"`                  //common.ProductProcedure  json串
        ProceduresInfo common.ProductProcedure `json:"procedure" gorm:"-"` //common.ProductProcedure  对象
        gorm.Model         `json:"-"`
        ID                 int    `gorm:"primarykey"`
        WorkOrderID        string `gorm:"index;type:varchar(191);not null;comment:工单ID" json:"-"`
        OrderID            string `gorm:"index;type:varchar(191);not null;comment:订单ID" json:"-"`
        DeviceID           string `gorm:"index;type:varchar(191);comment:设备ID" json:"deviceId"`
        ProcedureID        string `gorm:"index;type:varchar(191);comment:工序ID" json:"procedureId"`
        Channel            int32  `gorm:"index;comment:通道" json:"channel"`                //通道
        ProcessModelNumber string `gorm:"index;comment:工艺模型编号" json:"processModelNumber"` //工艺模型编号
        StartTime          int64  `gorm:"comment:计划开始时间" json:"startTime"`
        EndTime            int64  `gorm:"comment:计划结束时间" json:"endTime"`
        Status             ProcedureStatus
        ProcedureData      string                  `json:"-"`                  //common.ProductProcedure  json串
        ProceduresInfo     common.ProductProcedure `json:"procedure" gorm:"-"` //common.ProductProcedure  对象
    }
    ProceduresSearch struct {
model/process_model.go
@@ -11,15 +11,17 @@
type (
    // ProcessModel 工艺参数
    ProcessModel struct {
        gorm.Model
        Number    string                 `gorm:"index;column:number;type:varchar(255);not null;default '';comment:工艺模型编号" json:"number"` //工艺模型编号
        Product   string                 `gorm:"column:product;type:varchar(255);not null;default '';comment:产品名称" json:"product"`       //产品名称
        Procedure string                 `gorm:"column:procedure;type:varchar(255);not null;default '';comment:工序" json:"procedure"`     //工序
        Params    string                 `gorm:"type:text;comment:工艺参数键值对json串"`
        ParamsMap map[string]interface{} `json:"paramsMap" gorm:"-"`
        DeviceId  string                 `json:"deviceId" gorm:"-"`                        //用于过滤获取nsq消息
        IsNew     bool                   `json:"isNew" gorm:"column:is_new;comment:是否最新的"` //是否最新的
        IsUpdate  bool                   `json:"isUpdate" gorm:"-"`                        //前端用
        gorm.Model   `json:"-"`
        Number       string                 `gorm:"index;column:number;type:varchar(255);not null;default '';comment:工艺模型编号" json:"number"` //工艺模型编号
        Product      string                 `gorm:"column:product;type:varchar(255);not null;default '';comment:产品名称" json:"product"`       //产品名称
        Procedure    string                 `gorm:"column:procedure;type:varchar(255);not null;default '';comment:工序" json:"procedure"`     //工序
        Params       string                 `gorm:"type:text;comment:工艺参数键值对json串"`
        ParamsMap    map[string]interface{} `json:"paramsMap" gorm:"-"`
        DeviceId     string                 `json:"deviceId" gorm:"-"`                    //用于过滤获取nsq消息
        IsNew        bool                   `json:"-" gorm:"column:is_new;comment:是否最新的"` //是否最新的
        IsUpdate     bool                   `json:"isUpdate" gorm:"-"`                    //前端用
        NewParamsMap map[string]interface{} `json:"newParamsMap" gorm:"-"`
        NewNumber    string                 `json:"newNumber" gorm:"-"`
    }
    ProcessModelSearch struct {
model/request/task.go
@@ -18,8 +18,7 @@
}
type SendProcessParams struct {
    ProcedureId uint  `json:"procedureId" binding:"required"`
    Channel     int32 `json:"channel"`
    ProcedureId int `json:"procedureId" binding:"required"`
}
type GetProductProgress struct {
pkg/contextx/contextx.go
@@ -81,6 +81,7 @@
    slf.ctx.JSON(http.StatusOK, ResponseList{
        Data:  data,
        Total: total,
        Code:  ecode.OK,
    })
}
router/index.go
@@ -35,11 +35,12 @@
    taskApi := new(v1.TaskApi)
    taskGroup := v1Group.Group("task")
    {
        taskGroup.GET("countdown", taskApi.TaskCountdown)      // 新任务倒计时
        taskGroup.GET("get", taskApi.TaskGet)                  // 获取工序
        taskGroup.GET("start/:id", taskApi.GetProcessParams)   // 获取工艺参数
        taskGroup.POST("sendProcessParams", taskApi.TaskStart) // 下发工艺参数并开始工序
        taskGroup.PUT("finish/:id", taskApi.TaskFinish)        // 完成工序
        taskGroup.GET("countdown", taskApi.TaskCountdown)                  // 新任务倒计时
        taskGroup.GET("get", taskApi.TaskGet)                              // 获取工序
        taskGroup.GET("start/:id", taskApi.GetProcessParams)               // 获取工艺参数
        taskGroup.POST("sendProcessParams", taskApi.TaskStart)             // 下发工艺参数并开始工序
        taskGroup.POST("updateProcessParams", taskApi.UpdateProcessParams) // 更新工艺参数
        taskGroup.PUT("finish/:id", taskApi.TaskFinish)                    // 完成工序
    }
    configApi := new(v1.ConfigApi)
@@ -54,15 +55,15 @@
    plcApi := new(v1.PlcApi)
    plcGroup := v1Group.Group("plc")
    {
        plcGroup.POST("productProgress", plcApi.GetProductProgress)                 // 获取生产进度
        plcGroup.POST("productProgressRealTime", plcApi.GetProductProgressRealTime) // 实时获取生产进度
        plcGroup.POST("setProductNumber", plcApi.SetProductNumber)                  // 下发生产总量
        plcGroup.POST("productProgress", plcApi.GetProductProgress) // 获取生产进度
        //plcGroup.POST("productProgressRealTime", plcApi.GetProductProgressRealTime) // 实时获取生产进度
        plcGroup.POST("setProductNumber", plcApi.SetProductNumber) // 下发生产总量
    }
    processModelApi := new(v1.ProcessModelApi)
    processModelGroup := v1Group.Group("processModel")
    {
        processModelGroup.GET("list", processModelApi.List) // 新任务倒计时
        processModelGroup.GET("list", processModelApi.List) // 工艺参数列表
    }
    //eventsApi := new(v1.EventsApi)
service/cache_store.go
@@ -1,9 +1,11 @@
package service
import (
    "apsClient/conf"
    "apsClient/constvar"
    "apsClient/model"
    "fmt"
    "github.com/jinzhu/gorm"
    "github.com/spf13/cast"
    "sync"
    "time"
@@ -79,18 +81,25 @@
}
func TaskFlagSet(channel int32) {
    defaultCacheStore.Add(fmt.Sprintf(CurrentTaskCacheKey, channel), struct{}{})
    defaultCacheStore.Add(fmt.Sprintf(CurrentTaskCacheKey, channel), true)
}
func TaskFlagUnset(channel int32) {
    defaultCacheStore.Remove(fmt.Sprintf(CurrentTaskCacheKey, channel))
    defaultCacheStore.Add(fmt.Sprintf(CurrentTaskCacheKey, channel), false)
}
func TaskFlagGet(channel int32) bool {
    if _, ok := defaultCacheStore.Get(fmt.Sprintf(CurrentTaskCacheKey, channel)); ok {
    if v, ok := defaultCacheStore.Get(fmt.Sprintf(CurrentTaskCacheKey, channel)); ok {
        return v.(bool)
    }
    _, err := model.NewProceduresSearch(nil).SetDeviceId(conf.Conf.System.DeviceId).SetStatus(model.ProcedureStatusProcessing).SetChannels([]int32{channel}).First()
    if err == gorm.ErrRecordNotFound {
        defaultCacheStore.Add(fmt.Sprintf(CurrentTaskCacheKey, channel), false)
        return false
    } else {
        defaultCacheStore.Add(fmt.Sprintf(CurrentTaskCacheKey, channel), true)
        return true
    }
    return false
}
func ProgressCacheGet(channel int32) (*model.ProductionProgress, bool) {
service/process_model.go
@@ -15,3 +15,7 @@
        SetPage(page, pageSize).SetProcedures(device.ProceduresArr).Find()
    return
}
func GetProcessModelByNumber(num string) (record *model.ProcessModel, err error) {
    return model.NewProcessModelSearch().SetNumber(num).First()
}
service/task.go
@@ -34,7 +34,6 @@
        Workers:   slf.WorkerDistinct(workers),
    }
    nowTs := time.Now().Unix()
    var (
        err          error
        orders       []*model.Order
@@ -47,14 +46,10 @@
    if mode == constvar.TaskModeUnStarted {
        search.SetStatus(model.ProcedureStatusWaitProcess).
            SetStartTimeMax(nowTs).
            SetEndTimeMin(nowTs).
            SetOrder("start_time asc")
    } else if mode == constvar.TaskModeCurrent {
        search.SetStatus(model.ProcedureStatusProcessing).
            SetStartTimeMax(nowTs).
            SetEndTimeMin(nowTs).
            SetOrder("status desc, start_time asc")
            SetOrder("start_time asc")
    } else if mode == constvar.TaskModeLastFinished {
        search.SetStatus(model.ProcedureStatusFinished).SetOrder("updated_at desc")
        if len(channels) > 0 {
@@ -112,8 +107,7 @@
    return taskResp, ecode.OK
}
func (slf TaskService) NewTaskCount() (count int64) {
    nowTs := time.Now().Unix()
    count, _ = model.NewProceduresSearch(nil).SetDeviceId(conf.Conf.System.DeviceId).SetStatus(model.ProcedureStatusWaitProcess).SetEndTimeMin(nowTs).Count()
    count, _ = model.NewProceduresSearch(nil).SetDeviceId(conf.Conf.System.DeviceId).SetStatus(model.ProcedureStatusWaitProcess).Count()
    return count
}
@@ -137,14 +131,19 @@
    return procedure, ecode.OK
}
func (slf TaskService) UpdateProcedureStatusAndChannel(db *gorm.DB, id uint, status model.ProcedureStatus, channel int32) error {
    if status == model.ProcedureStatusFinished {
func (slf TaskService) UpdateProcedureStatusAndChannel(db *gorm.DB, id int, status model.ProcedureStatus, channel int32, processModelNumber string) error {
    if status == model.ProcedureStatusFinished || status == model.ProcedureStatusWaitProcess {
        ProgressCacheUnset(channel)
    }
    return model.NewProceduresSearch(db).SetId(id).UpdateByMap(map[string]interface{}{
        "status":  status,
        "channel": channel,
    })
    upMap := map[string]interface{}{"status": status}
    if status == model.ProcedureStatusProcessing {
        upMap["process_model_number"] = processModelNumber
    } else if status == model.ProcedureStatusWaitProcess {
        upMap["process_model_number"] = ""
    }
    return model.NewProceduresSearch(db).SetId(id).UpdateByMap(upMap)
}
func (slf TaskService) UpdateProcedureStatus(db *gorm.DB, id uint, status model.ProcedureStatus, channel int32) error {
test/task_test.go
New file
@@ -0,0 +1,31 @@
package test
import (
    "apsClient/conf"
    "apsClient/constvar"
    "apsClient/model/common"
    "apsClient/nsq"
    "apsClient/pkg/logx"
    "apsClient/service"
    "fmt"
    "testing"
)
func TestTaskStatusUpdate(t *testing.T) {
    Init()
    procedureId := 1
    taskService := service.NewTaskService()
    procedure, _ := taskService.GetProcedureById(procedureId)
    msg := &common.MsgTaskStatusUpdate{
        WorkOrderId:  procedure.WorkOrderID,
        ProcedureID:  procedure.ProceduresInfo.ProcedureID,
        DeviceId:     procedure.ProceduresInfo.DeviceID,
        IsProcessing: false,
        IsFinish:     true,
    }
    caller := nsq.NewCaller(fmt.Sprintf(constvar.NsqTopicTaskProcedureStatusUpdate, conf.Conf.NsqConf.NodeId), "")
    err := caller.Send(msg)
    if err != nil {
        logx.Errorf("send task status update msg error:%v", err.Error())
    }
}
test/test.go
@@ -10,7 +10,7 @@
func Init() {
    logx.Init(conf.Conf.Log)
    defer logx.Sync()
    conf.Conf.Sqlite.Dsn = "../aps.db"
    if err := model.Init(); err != nil {
        logx.Errorf("model Init err:%v", err)
        return