作者 yangfu

feat:

1.数据采集汇报
2.文档修改
正在显示 34 个修改的文件 包含 1006 行增加60 行删除
1 -#project  
  1 +# 生产制造项目说明
  2 +
  3 +## 1.数据导入导出模块
  4 +
  5 +### 1.1.Excel导入流程
  6 +
  7 +- 原型说明
  8 +
  9 +选择模板下载、文件上传
  10 +![](https://doc-press.fjmaimaimai.com/team/frontend/plugins/data-transfer-upload.png)
  11 +
  12 +导入数据检验有错,显示具体错误
  13 +![](https://timeless-world.oss-cn-shenzhen.aliyuncs.com/opportunity/dev_online/20220225/object/1645791913_Rz2JJkkx6xEXtAFdXDH5eH6NTjfhtjxf.jpg)
  14 +
  15 +- [导入接口文档地址](https://doc-press.fjmaimaimai.com/team/frontend/plugins/business/import.html)
  16 +
  17 +
  18 +```
  19 +POST/v1/web/file-import
  20 +
  21 +Content-Type multipart/form-data
  22 +
  23 +params:
  24 +
  25 +file 文件
  26 +code 对应导入模块的编码
  27 +```
  28 +
  29 +- ``对接步骤``以导入公司用户模块为例
  30 +
  31 +1.定义接口导入的``code``为``ADMIN_SYSTEM-MANAGE_BASE_USER``
  32 +2.根据接口解析导入文件的数据
  33 +3.调用基础库解析数据并传到后台
  34 +```go
  35 +
  36 +// 1.解析列
  37 +excelImport := excel.NewExcelImport()
  38 +excelImport.RowBegin = 3 //第二行开始读取
  39 +excelImport.DataFields = []excel.DataField{
  40 + {EnName: "userCode", CnName: "*用户编码"},
  41 + {EnName: "userName", CnName: "*用户姓名"},
  42 + {EnName: "org", CnName: "*组织机构"},
  43 + {EnName: "department", CnName: "*所属部门"},
  44 + {EnName: "enableStatus", CnName: "*用户状态"},
  45 + {EnName: "phone", CnName: "*手机号"},
  46 + {EnName: "employeeType", CnName: "*员工类型"},
  47 + {EnName: "icCardNumber", CnName: "IC卡号"},
  48 + {EnName: "email", CnName: "邮箱"},
  49 +}
  50 +excelData, err := excelImport.OpenExcelFromIoReader(importDataCommand.Reader)
  51 +if err != nil {
  52 + return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
  53 +}
  54 +users := make([]allied_creation_user.BatchAddUserItem, 0)
  55 +for _, v := range excelData {
  56 + if srv.fieldValueAllEmpty(v) {
  57 + continue
  58 + }
  59 + item := allied_creation_user.BatchAddUserItem{
  60 + CompanyId: importDataCommand.Operator.CompanyId,
  61 + UserType: domain.UserTypeEmployee,
  62 + UserCode: strings.TrimSpace(v["userCode"]),
  63 + Org: strings.TrimSpace(v["org"]),
  64 + Department: strings.TrimSpace(v["department"]),
  65 + UserName: strings.TrimSpace(v["userName"]),
  66 + Phone: strings.TrimSpace(v["phone"]),
  67 + Email: strings.TrimSpace(v["email"]),
  68 + EnableStatus: strings.TrimSpace(v["enableStatus"]),
  69 + EmployeeType: strings.TrimSpace(v["employeeType"]),
  70 + IcCardNumber: strings.TrimSpace(v["icCardNumber"]),
  71 + }
  72 + users = append(users, item)
  73 +}
  74 +// 2.向后台服务发起批量添加请求
  75 +userGateway := allied_creation_user.NewHttplibAlliedCreationUser(importDataCommand.Operator)
  76 +result, err := userGateway.UserBatchAdd(allied_creation_user.ReqBatchAddUser{
  77 + Users: users,
  78 + Password: initPassword,
  79 +})
  80 +```
  81 +
  82 +```go
  83 +```
  84 +
  85 +### 2.2 Excel导出流程
  86 +
  87 +- 功能原型说明
  88 +
  89 +实现可以自定义选择列进行导出,以及选择导出格式,导出格式有 ``xlsx``\\``csv``,功能如下图所示:
  90 +
  91 +![](https://timeless-world.oss-cn-shenzhen.aliyuncs.com/opportunity/dev_online/20220225/object/1645789890_JbTa22EtANsD3fm2nJ4aH6FJkHzXaHJB.png)
  92 +
  93 +- 前后端交互说明
  94 +
  95 +``接口定义``
  96 +
  97 +导出接口
  98 +```shell
  99 +POST /v1/web/file-export
  100 +
  101 +// request 请求参数
  102 +{
  103 + // 业务编码
  104 + "code":"string"
  105 + // 选择的导出的列
  106 + "fields":[]
  107 + // 导出文件格式
  108 + "format":"xlsx"
  109 + // 业务查询条件
  110 + "where":{}
  111 +}
  112 +```
  113 +
  114 +导出列查询接口
  115 +
  116 +```shell
  117 +GET/v1/web/file-export/fields/:code
  118 +
  119 +// response 应答数据
  120 +{
  121 + "fields":[
  122 + {
  123 + "enName":"字段键名",
  124 + "cnName":"字段展示名称",
  125 + "selected":true // 默认勾选
  126 + }
  127 + ]
  128 +}
  129 +```
  130 +
  131 +- 交互流程
  132 +
  133 +1.前台根据 ``导出列查询接口`` 获取可以导出的列;
  134 +2.勾选需要导出的列、文件格式,调用 ``导出接口`` 向后台发起导出数据请求;
  135 +
  136 +
  137 +#### 2.2.1 后端导出实现
  138 +
  139 +1. 导出数据实现接口
  140 +
  141 +```
  142 +type ExcelMaker interface {
  143 + DataFieldList() []DataField //字段元数据列表
  144 + CellValue(index int, enName string) (value interface{}) //获取单元格字段值
  145 + DataListLen() int //数据列表大小
  146 + TableTitle() []string //列表顶部自定义内容
  147 +}
  148 +```
  149 +
  150 +如下所示
  151 +```go
  152 +//ExportCooperationUserData 导出共创用户数据
  153 +type ExportCooperationUserData struct {
  154 + SourceData []allied_creation_user.UserDetail //具体数据
  155 + SelectedField []string
  156 +}
  157 +
  158 +var _ excel.ExcelMaker = (*ExportCooperationUserData)(nil)
  159 +
  160 +func (data ExportCooperationUserData) AllFields() []DataFieldOptions {
  161 + return []DataFieldOptions{
  162 + {EnName: "UserCode", CnName: "用户编码"},
  163 + {EnName: "UserName", CnName: "用户姓名"},
  164 + {EnName: "Phone", CnName: "手机号"},
  165 + {EnName: "CooperationCompany", CnName: "共创公司"},
  166 + {EnName: "CooperationDeadline", CnName: "共创到期"},
  167 + {EnName: "EnableStatus", CnName: "状态"},
  168 + }
  169 +}
  170 +
  171 +func (data ExportCooperationUserData) DataFieldList() []excel.DataField {
  172 + fields := []excel.DataField{}
  173 + allFields := data.AllFields()
  174 + for _, value2 := range allFields {
  175 + if len(data.SelectedField) == 0 || value2.IsDefault {
  176 + fields = append(fields, excel.DataField{EnName: value2.EnName, CnName: value2.CnName})
  177 + continue
  178 + }
  179 + for _, value3 := range data.SelectedField {
  180 + if value2.EnName == value3 {
  181 + fields = append(fields, excel.DataField{EnName: value2.EnName, CnName: value2.CnName})
  182 + }
  183 + }
  184 + }
  185 + return fields
  186 +}
  187 +
  188 +func (data ExportCooperationUserData) CellValue(index int, enName string) (value interface{}) {
  189 + if index > data.DataListLen() {
  190 + return ""
  191 + }
  192 + switch enName {
  193 + case "UserCode":
  194 + return data.SourceData[index].UserCode
  195 + case "UserName":
  196 + return data.SourceData[index].UserInfo.UserName
  197 + case "CooperationCompany":
  198 + return data.SourceData[index].CooperationInfo.CooperationCompany
  199 + case "CooperationDeadline":
  200 + if data.SourceData[index].CooperationInfo.CooperationDeadline.IsZero() || data.SourceData[index].CooperationInfo.CooperationDeadline.Unix() == 0 {
  201 + return ""
  202 + }
  203 + return data.SourceData[index].CooperationInfo.CooperationDeadline.Format("2006-01-02")
  204 + case "Phone":
  205 + return data.SourceData[index].UserInfo.Phone
  206 + case "Email":
  207 + return data.SourceData[index].UserInfo.Email
  208 + case "EnableStatus":
  209 + status := data.SourceData[index].EnableStatus
  210 + statusName := ""
  211 + // 状态(1:启用 2:禁用 3:注销)
  212 + switch status {
  213 + case 1:
  214 + statusName = "启用"
  215 + case 2:
  216 + statusName = "禁用"
  217 + case 3:
  218 + statusName = "注销"
  219 + }
  220 + return statusName
  221 + }
  222 + return nil
  223 +}
  224 +
  225 +func (data ExportCooperationUserData) DataListLen() int {
  226 + return len(data.SourceData)
  227 +}
  228 +
  229 +func (data ExportCooperationUserData) TableTitle() []string {
  230 + return nil
  231 +}
  232 +```
  233 +
  234 +2. 返回文件
  235 +
  236 +```go
  237 +//返回文件
  238 +excelTool := excel.NewExcelExport()
  239 +err = excelTool.ExportData(data, "")
  240 +controller.responseExcelByFile(controller.Ctx, excelTool, filename)
  241 +
  242 +
  243 +func (controller *ExcelDataController) responseExcelByFile(ctx *context.Context, excelExport *excel.ExcelExport, fileName string) error {
  244 + ctx.Output.Header("Content-Disposition", "attachment; filename="+fileName)
  245 + ctx.Output.Header("Content-Description", "File Transfer")
  246 + ctx.Output.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  247 + ctx.Output.Header("Content-Transfer-Encoding", "binary")
  248 + ctx.Output.Header("Expires", "0")
  249 + ctx.Output.Header("Cache-Control", "must-revalidate")
  250 + ctx.Output.Header("Pragma", "public")
  251 + //跳过保存文件,直接写入ctx.ResponseWriter
  252 + excelExport.ExcelFile.Write(ctx.ResponseWriter)
  253 + return nil
  254 +}
  255 +```
@@ -2,6 +2,7 @@ package main @@ -2,6 +2,7 @@ package main
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/mqtt"
5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task" 6 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/port/task"
6 7
7 "github.com/beego/beego/v2/server/web" 8 "github.com/beego/beego/v2/server/web"
@@ -33,7 +34,7 @@ func main() { @@ -33,7 +34,7 @@ func main() {
33 log.Logger.Debug("server start ....") 34 log.Logger.Debug("server start ....")
34 log.Logger.Debug(fmt.Sprintf("ENABLE_KAFKA_LOG:%v", constant.ENABLE_KAFKA_LOG)) 35 log.Logger.Debug(fmt.Sprintf("ENABLE_KAFKA_LOG:%v", constant.ENABLE_KAFKA_LOG))
35 36
36 - //go mqtt.Start() 37 + go mqtt.Start()
37 go task.Run() 38 go task.Run()
38 cron := crontab.NewCrontabService(nil) 39 cron := crontab.NewCrontabService(nil)
39 cron.StartCrontabTask() 40 cron.StartCrontabTask()
@@ -2,6 +2,7 @@ package dto @@ -2,6 +2,7 @@ package dto
2 2
3 import ( 3 import (
4 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 4 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  5 + "time"
5 ) 6 )
6 7
7 type AttendanceRecordDto struct { 8 type AttendanceRecordDto struct {
@@ -15,7 +16,10 @@ type AttendanceRecordDto struct { @@ -15,7 +16,10 @@ type AttendanceRecordDto struct {
15 AttendanceType int `json:"attendanceType,omitempty"` 16 AttendanceType int `json:"attendanceType,omitempty"`
16 // 生产工人 17 // 生产工人
17 ProductWorker *domain.User `json:"productWorker,omitempty"` 18 ProductWorker *domain.User `json:"productWorker,omitempty"`
18 - *domain.ProductAttendanceRecordExt 19 + // 审核人
  20 + ApproveUser *domain.User `json:"approveUser"`
  21 + //*domain.ProductAttendanceRecordExt
  22 + ApproveAt string `json:"approveAt"`
19 // 工作位置 23 // 工作位置
20 *domain.WorkStation 24 *domain.WorkStation
21 // 签到 25 // 签到
@@ -54,7 +58,20 @@ func (d *AttendanceRecordDto) LoadDto(m *domain.ProductAttendanceRecord, orgId i @@ -54,7 +58,20 @@ func (d *AttendanceRecordDto) LoadDto(m *domain.ProductAttendanceRecord, orgId i
54 d.AuthFlag = domain.CheckOrgAuth(orgId, m.OrgId) 58 d.AuthFlag = domain.CheckOrgAuth(orgId, m.OrgId)
55 if m.Ext != nil { 59 if m.Ext != nil {
56 d.OrgName = m.Ext.OrgName 60 d.OrgName = m.Ext.OrgName
57 - d.ProductAttendanceRecordExt = m.Ext.AttendanceExt 61 + //d.ProductAttendanceRecordExt = m.Ext.AttendanceExt
  62 + //if
  63 + if m.Ext.AttendanceExt != nil {
  64 + if m.Ext.AttendanceExt.ApproveUserId > 0 {
  65 + d.ApproveUser = &domain.User{
  66 + UserId: m.Ext.AttendanceExt.ApproveUserId,
  67 + UserName: m.Ext.AttendanceExt.ApproveUserName,
  68 + }
  69 + }
  70 + if m.Ext.AttendanceExt.ApproveAt > 0 {
  71 + t := time.Unix(m.Ext.AttendanceExt.ApproveAt, 0)
  72 + d.ApproveAt = t.Format("2006-01-02 15:04:05")
  73 + }
  74 + }
58 } 75 }
59 return d 76 return d
60 } 77 }
  1 +package crontab
  2 +
  3 +import (
  4 + "context"
  5 + "fmt"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  8 +)
  9 +
  10 +// 定时刷新设备每日运行记录
  11 +func AutoFreshDeviceDailyRunningRecord(ctx context.Context) error {
  12 + defer func() {
  13 + if r := recover(); r != nil {
  14 + log.Logger.Error(fmt.Sprintf("%v", r))
  15 + }
  16 + }()
  17 + transactionContext, err := factory.CreateTransactionContext(nil)
  18 + if err != nil {
  19 + return err
  20 + }
  21 + if err := transactionContext.StartTransaction(); err != nil {
  22 + return err
  23 + }
  24 + defer func() {
  25 + if err != nil {
  26 + log.Logger.Error("【定时刷新设备每日运行记录】 失败:" + err.Error())
  27 + }
  28 + transactionContext.RollbackTransaction()
  29 + }()
  30 +
  31 + //deviceDailyRunningRecordRepository,_,_:= factory.FastPgDeviceDailyRunningRecord(transactionContext,0)
  32 + //
  33 + //// 获取redis里当天的记录
  34 + //t :=time.Now().Add(-time.Minute*20)
  35 +
  36 + if err = transactionContext.CommitTransaction(); err != nil {
  37 + return err
  38 + }
  39 + return nil
  40 +}
@@ -387,6 +387,32 @@ func FastPgWorkshopWorkTimeRecord(transactionContext application.TransactionCont @@ -387,6 +387,32 @@ func FastPgWorkshopWorkTimeRecord(transactionContext application.TransactionCont
387 return rep, mod, err 387 return rep, mod, err
388 } 388 }
389 389
  390 +// FastPgDeviceDailyRunningRecord 快速返回设备每日运行记录
  391 +//
  392 +// transactionContext 事务
  393 +// id 对象唯一标识
  394 +func FastPgDeviceDailyRunningRecord(transactionContext application.TransactionContext, id int, options ...option) (domain.DeviceDailyRunningRecordRepository, *domain.DeviceDailyRunningRecord, error) {
  395 + var rep domain.DeviceDailyRunningRecordRepository
  396 + var mod *domain.DeviceDailyRunningRecord
  397 + var err error
  398 + if value, err := CreateDeviceDailyRunningRecordRepository(map[string]interface{}{
  399 + "transactionContext": transactionContext,
  400 + }); err != nil {
  401 + return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  402 + } else {
  403 + rep = value
  404 + }
  405 + if id > 0 {
  406 + if mod, err = rep.FindOne(map[string]interface{}{"deviceDailyRunningRecordId": id}); err != nil {
  407 + if err == domain.ErrorNotFound {
  408 + return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该记录不存在")
  409 + }
  410 + return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  411 + }
  412 + }
  413 + return rep, mod, err
  414 +}
  415 +
390 /***** 2.配置 *****/ 416 /***** 2.配置 *****/
391 417
392 type FastOptions struct { 418 type FastOptions struct {
@@ -20,6 +20,8 @@ type ProductLevelTwoRecord struct { @@ -20,6 +20,8 @@ type ProductLevelTwoRecord struct {
20 WeighAfter float64 `json:"weighAfter"` 20 WeighAfter float64 `json:"weighAfter"`
21 // 审核状态 1:未审核 2:已审核 21 // 审核状态 1:未审核 2:已审核
22 ApproveStatus int `json:"approveStatus"` 22 ApproveStatus int `json:"approveStatus"`
  23 + // 审核人
  24 + ApproveUser *domain.User `json:"approveUser"`
23 // 审核时间 25 // 审核时间
24 ApproveAt string `json:"approveAt"` 26 ApproveAt string `json:"approveAt"`
25 // 计划的产品名称 27 // 计划的产品名称
@@ -46,6 +48,7 @@ func (d *ProductLevelTwoRecord) LoadDto(m *domain.ProductRecord, orgId int) *Pro @@ -46,6 +48,7 @@ func (d *ProductLevelTwoRecord) LoadDto(m *domain.ProductRecord, orgId int) *Pro
46 d.ApproveStatus = m.ProductRecordInfo.ApproveStatus 48 d.ApproveStatus = m.ProductRecordInfo.ApproveStatus
47 if m.ProductRecordInfo.ApproveAt > 0 { 49 if m.ProductRecordInfo.ApproveAt > 0 {
48 d.ApproveAt = time.Unix(m.ProductRecordInfo.ApproveAt, 0).Format("2006-01-02 15:04:05") 50 d.ApproveAt = time.Unix(m.ProductRecordInfo.ApproveAt, 0).Format("2006-01-02 15:04:05")
  51 + d.ApproveUser = m.ProductRecordInfo.ApproveUser
49 } 52 }
50 d.PlanProductName = m.ProductRecordInfo.PlanProductName 53 d.PlanProductName = m.ProductRecordInfo.PlanProductName
51 d.BatchNumber = m.ProductRecordInfo.BatchNumber 54 d.BatchNumber = m.ProductRecordInfo.BatchNumber
  1 +package command
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  6 + "reflect"
  7 + "strings"
  8 +
  9 + "github.com/beego/beego/v2/core/validation"
  10 +)
  11 +
  12 +type WorkshopDataConsumeCommand struct {
  13 + *domain.DeviceCollection
  14 + // 企业id
  15 + CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
  16 + // 组织ID
  17 + OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
  18 +}
  19 +
  20 +func (updateWorkshopCommand *WorkshopDataConsumeCommand) Valid(validation *validation.Validation) {
  21 +
  22 +}
  23 +
  24 +func (updateWorkshopCommand *WorkshopDataConsumeCommand) ValidateCommand() error {
  25 + valid := validation.Validation{}
  26 + b, err := valid.Valid(updateWorkshopCommand)
  27 + if err != nil {
  28 + return err
  29 + }
  30 + if !b {
  31 + elem := reflect.TypeOf(updateWorkshopCommand).Elem()
  32 + for _, validErr := range valid.Errors {
  33 + field, isExist := elem.FieldByName(validErr.Field)
  34 + if isExist {
  35 + return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
  36 + } else {
  37 + return fmt.Errorf(validErr.Message)
  38 + }
  39 + }
  40 + }
  41 + return nil
  42 +}
  1 +package service
  2 +
  3 +import (
  4 + "github.com/linmadan/egglib-go/core/application"
  5 + "github.com/linmadan/egglib-go/transaction/pg"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/workshop/command"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  10 +)
  11 +
  12 +func (workshopService *WorkshopService) WorkshopConsume(cmd *command.WorkshopDataConsumeCommand) (interface{}, error) {
  13 + if err := cmd.ValidateCommand(); err != nil {
  14 + return nil, application.ThrowError(application.ARG_ERROR, err.Error())
  15 + }
  16 + transactionContext, err := factory.CreateTransactionContext(nil)
  17 + if err != nil {
  18 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  19 + }
  20 + if err := transactionContext.StartTransaction(); err != nil {
  21 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  22 + }
  23 + defer func() {
  24 + transactionContext.RollbackTransaction()
  25 + }()
  26 +
  27 + consumeService, _ := domainService.NewPGWorkshopDataConsumeService(transactionContext.(*pg.TransactionContext))
  28 + if _, err := consumeService.Consume(cmd.CompanyId, cmd.OrgId, cmd.DeviceCollection); err != nil {
  29 + log.Logger.Error(err.Error())
  30 + return nil, err
  31 + }
  32 +
  33 + if err := transactionContext.CommitTransaction(); err != nil {
  34 + return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
  35 + }
  36 + return struct{}{}, nil
  37 +}
1 package domain 1 package domain
2 2
3 -import "time" 3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  6 + "time"
  7 +)
4 8
5 // 设备采集数据 9 // 设备采集数据
6 type DeviceCollection struct { 10 type DeviceCollection struct {
@@ -76,3 +80,7 @@ func (deviceCollection *DeviceCollection) Update(data map[string]interface{}) er @@ -76,3 +80,7 @@ func (deviceCollection *DeviceCollection) Update(data map[string]interface{}) er
76 } 80 }
77 return nil 81 return nil
78 } 82 }
  83 +
  84 +func TaskDeviceCollection() string {
  85 + return fmt.Sprintf("%v:task:device-collection:report", constant.CACHE_PREFIX)
  86 +}
@@ -22,6 +22,8 @@ type DeviceDailyRunningRecord struct { @@ -22,6 +22,8 @@ type DeviceDailyRunningRecord struct {
22 DeviceId int `json:"deviceId"` 22 DeviceId int `json:"deviceId"`
23 // 设备编号 23 // 设备编号
24 DeviceCode string `json:"deviceCode"` 24 DeviceCode string `json:"deviceCode"`
  25 + // 生产日期
  26 + ProductDate time.Time `json:"productDate"`
25 // 设备运行记录信息 27 // 设备运行记录信息
26 DeviceRunningRecordInfo *DeviceRunningRecordInfo `json:"deviceRunningRecordInfo"` 28 DeviceRunningRecordInfo *DeviceRunningRecordInfo `json:"deviceRunningRecordInfo"`
27 // 创建时间 29 // 创建时间
@@ -79,6 +81,10 @@ type DeviceRunningRecordInfo struct { @@ -79,6 +81,10 @@ type DeviceRunningRecordInfo struct {
79 //TimeLine []string `json:"timeLine"` 81 //TimeLine []string `json:"timeLine"`
80 // 时间点对应的设备状态 按小时 1 82 // 时间点对应的设备状态 按小时 1
81 TimeLineDeviceStatus map[string]*HourDeviceStatus `json:"timeLineDeviceStatus"` 83 TimeLineDeviceStatus map[string]*HourDeviceStatus `json:"timeLineDeviceStatus"`
  84 +
  85 + // 批次数据
  86 + // 生产计划ID
  87 + ProductPlanId int `json:"productPlanId,omitempty"`
82 } 88 }
83 89
84 func NewDeviceRunningRecordInfo() *DeviceRunningRecordInfo { 90 func NewDeviceRunningRecordInfo() *DeviceRunningRecordInfo {
@@ -87,15 +93,12 @@ func NewDeviceRunningRecordInfo() *DeviceRunningRecordInfo { @@ -87,15 +93,12 @@ func NewDeviceRunningRecordInfo() *DeviceRunningRecordInfo {
87 } 93 }
88 } 94 }
89 func (d *DeviceRunningRecordInfo) AddDeviceRunningData(t time.Time, data *DeviceRunningData) { 95 func (d *DeviceRunningRecordInfo) AddDeviceRunningData(t time.Time, data *DeviceRunningData) {
90 - d.CurrentStatus = data.StartupState | (1 << data.ComStatus) 96 + d.CurrentStatus = data.StartupStatus | (1 << data.ComStatus)
91 d.ResetUpTime() 97 d.ResetUpTime()
92 d.Count += data.Count 98 d.Count += data.Count
93 //d.Temp = data.FrontTemp 99 //d.Temp = data.FrontTemp
94 - if data.Temp1 > 0 {  
95 - d.Temp = data.Temp1  
96 - } else if data.FrontTemp > 0 {  
97 - d.Temp = data.FrontTemp  
98 - } 100 +
  101 + d.Temp = data.Temp1
99 d.AddTimeLineDeviceStatus(t, data) 102 d.AddTimeLineDeviceStatus(t, data)
100 103
101 //d.OEE 104 //d.OEE
@@ -116,7 +119,7 @@ func (d *DeviceRunningRecordInfo) AddTimeLineDeviceStatus(t time.Time, data *Dev @@ -116,7 +119,7 @@ func (d *DeviceRunningRecordInfo) AddTimeLineDeviceStatus(t time.Time, data *Dev
116 v = NewHourDeviceStatus() 119 v = NewHourDeviceStatus()
117 d.TimeLineDeviceStatus[key] = v 120 d.TimeLineDeviceStatus[key] = v
118 } 121 }
119 - v.UpdateUp(t, data.StartupState) 122 + v.UpdateUp(t, data.StartupStatus)
120 v.UpdateCom(t, data.ComStatus) 123 v.UpdateCom(t, data.ComStatus)
121 } 124 }
122 125
1 package domain 1 package domain
2 2
  3 +import "time"
  4 +
3 // 设备运行数据 5 // 设备运行数据
4 type DeviceRunningData struct { 6 type DeviceRunningData struct {
  7 + // 数据采集ID
  8 + DeviceCollectionId int64 `json:"deviceCollectionId,string"`
  9 + // 车间名
  10 + WorkShopName string `json:"workShopName"`
  11 + // 采集时间
  12 + CollectionTime time.Time `json:"collectionTime"`
  13 + // 设备名
  14 + //DeviceSn string `json:"deviceSn"`
  15 + // 设备编号
  16 + DeviceCode string `json:"deviceCode"`
  17 + // 设备类型
  18 + DeviceType string `json:"deviceType"`
5 // 启动状态:1:启动,0:停止 19 // 启动状态:1:启动,0:停止
6 - StartupState int `json:"startupState"` 20 + StartupStatus int `json:"startupStatus"`
7 // 通讯状态:1:通讯正常,0:设备未上电或与采集端通讯故障 21 // 通讯状态:1:通讯正常,0:设备未上电或与采集端通讯故障
8 ComStatus int `json:"comStatus"` 22 ComStatus int `json:"comStatus"`
  23 +
  24 + // 附加数据
9 // 匹配数目 25 // 匹配数目
10 Count int `json:"count"` 26 Count int `json:"count"`
11 // 炸机前段温度:炸机前段当前温度 YZJ1 油炸机 27 // 炸机前段温度:炸机前段当前温度 YZJ1 油炸机
12 - FrontTemp float64 `json:"frontTemp"` 28 + //FrontTemp float64 `json:"frontTemp"`
13 // 炸机前段温度:炸机前段当前温度 YZJ2 油炸机 29 // 炸机前段温度:炸机前段当前温度 YZJ2 油炸机
14 Temp1 float64 `json:"temp1"` 30 Temp1 float64 `json:"temp1"`
15 // 当前产品种类(产品编号) 31 // 当前产品种类(产品编号)
16 ProductType string `json:"productType"` 32 ProductType string `json:"productType"`
17 - // 设备编号  
18 - DeviceCode string `json:"deviceCode"` 33 + // 日期
  34 + Date string `json:"date"`
19 } 35 }
@@ -17,7 +17,7 @@ type DeviceRunningRecord struct { @@ -17,7 +17,7 @@ type DeviceRunningRecord struct {
17 // 设备编号 17 // 设备编号
18 DeviceCode string `json:"deviceCode"` 18 DeviceCode string `json:"deviceCode"`
19 // 设备运行记录信息 19 // 设备运行记录信息
20 - DeviceRunningRecordInfo string `json:"deviceRunningRecordInfo"` 20 + DeviceRunningRecordInfo *DeviceRunningData `json:"deviceRunningRecordInfo"`
21 // 创建时间 21 // 创建时间
22 CreatedAt time.Time `json:"createdAt"` 22 CreatedAt time.Time `json:"createdAt"`
23 } 23 }
@@ -83,7 +83,10 @@ func (productAttendanceRecord *ProductAttendanceRecord) Approve(approveUser *Use @@ -83,7 +83,10 @@ func (productAttendanceRecord *ProductAttendanceRecord) Approve(approveUser *Use
83 } 83 }
84 productAttendanceRecord.AttendanceStatus = status 84 productAttendanceRecord.AttendanceStatus = status
85 productAttendanceRecord.WorkTimeAfter = workTimeAfter 85 productAttendanceRecord.WorkTimeAfter = workTimeAfter
86 - if productAttendanceRecord.Ext != nil && productAttendanceRecord.Ext.AttendanceExt != nil { 86 + if productAttendanceRecord.Ext != nil {
  87 + if productAttendanceRecord.Ext.AttendanceExt == nil {
  88 + productAttendanceRecord.Ext.AttendanceExt = &ProductAttendanceRecordExt{}
  89 + }
87 productAttendanceRecord.Ext.AttendanceExt.ApproveUserId = approveUser.UserId 90 productAttendanceRecord.Ext.AttendanceExt.ApproveUserId = approveUser.UserId
88 productAttendanceRecord.Ext.AttendanceExt.ApproveUserName = approveUser.UserName 91 productAttendanceRecord.Ext.AttendanceExt.ApproveUserName = approveUser.UserName
89 productAttendanceRecord.Ext.AttendanceExt.ApproveAt = time.Now().Unix() 92 productAttendanceRecord.Ext.AttendanceExt.ApproveAt = time.Now().Unix()
@@ -39,6 +39,8 @@ type PlanDispatchRecordExt struct { @@ -39,6 +39,8 @@ type PlanDispatchRecordExt struct {
39 ProductPlanId int `json:"productPlanId,omitempty"` 39 ProductPlanId int `json:"productPlanId,omitempty"`
40 // 计划的产品名称 40 // 计划的产品名称
41 PlanProductName string `json:"planProductName,omitempty"` 41 PlanProductName string `json:"planProductName,omitempty"`
  42 + // 产品编号 编码规则为“CP”+2 位年+2 位月+2 位日+3 位流水码,如 CP211229001
  43 + ProductCode string `json:"productCode,omitempty"`
42 // 上班班次 1:全天 2:白班 4:中班 8:夜班 44 // 上班班次 1:全天 2:白班 4:中班 8:夜班
43 WorkOn int `json:"workOn,omitempty"` 45 WorkOn int `json:"workOn,omitempty"`
44 // 机台 (A、B、C、D 区分机器大小) 46 // 机台 (A、B、C、D 区分机器大小)
@@ -80,7 +82,7 @@ func (productPlanDispatchRecord *ProductPlanDispatchRecord) ChangeStatus(status @@ -80,7 +82,7 @@ func (productPlanDispatchRecord *ProductPlanDispatchRecord) ChangeStatus(status
80 } 82 }
81 83
82 func NewProductPlanDispatchRecord(productPlan *ProductPlan, workStation *WorkStation) *ProductPlanDispatchRecord { 84 func NewProductPlanDispatchRecord(productPlan *ProductPlan, workStation *WorkStation) *ProductPlanDispatchRecord {
83 - return &ProductPlanDispatchRecord{ 85 + record := &ProductPlanDispatchRecord{
84 CompanyId: productPlan.CompanyId, 86 CompanyId: productPlan.CompanyId,
85 OrgId: productPlan.OrgId, 87 OrgId: productPlan.OrgId,
86 BatchNumber: productPlan.BatchNumber, 88 BatchNumber: productPlan.BatchNumber,
@@ -92,10 +94,16 @@ func NewProductPlanDispatchRecord(productPlan *ProductPlan, workStation *WorkSta @@ -92,10 +94,16 @@ func NewProductPlanDispatchRecord(productPlan *ProductPlan, workStation *WorkSta
92 PlanDispatchRecordExt: &PlanDispatchRecordExt{ 94 PlanDispatchRecordExt: &PlanDispatchRecordExt{
93 ProductPlanId: productPlan.ProductPlanId, 95 ProductPlanId: productPlan.ProductPlanId,
94 PlanProductName: productPlan.PlanProductName, 96 PlanProductName: productPlan.PlanProductName,
95 - WorkOn: productPlan.WorkOn,  
96 - Machine: productPlan.Machine,  
97 - Remark: productPlan.Remark, 97 + //ProductCode: productPlan.Ext.ProductPlanExt.ProductCode,
  98 + WorkOn: productPlan.WorkOn,
  99 + Machine: productPlan.Machine,
  100 + Remark: productPlan.Remark,
98 }, 101 },
99 Ext: productPlan.Ext, 102 Ext: productPlan.Ext,
100 } 103 }
  104 + if productPlan.Ext != nil && productPlan.Ext.ProductPlanExt != nil {
  105 + record.PlanDispatchRecordExt.ProductCode = productPlan.Ext.ProductPlanExt.ProductCode
  106 + }
  107 +
  108 + return record
101 } 109 }
  1 +package dao
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
  6 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
  10 + "time"
  11 +)
  12 +
  13 +type ProductPlanDispatchRecordDao struct {
  14 + transactionContext *pgTransaction.TransactionContext
  15 +}
  16 +
  17 +func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionContext) (*ProductPlanDispatchRecordDao, error) {
  18 + if transactionContext == nil {
  19 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  20 + } else {
  21 + return &ProductPlanDispatchRecordDao{
  22 + transactionContext: transactionContext,
  23 + }, nil
  24 + }
  25 +}
  26 +
  27 +// 生产计划对应的批次
  28 +// 工段
  29 +// 日期
  30 +// 产品编号
  31 +// 调度状态 status
  32 +func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
  33 + tx := dao.transactionContext.PgTx
  34 + productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord)
  35 + query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{})
  36 + query.Where("company_id = ?", companyId)
  37 + query.Where("org_id = ?", orgId)
  38 + query.Where("work_station->>'workStationId'=?", workStationId)
  39 + query.Where("product_date = ?", date)
  40 + query.Where("plan_dispatch_status = ?", status)
  41 + query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode)
  42 + query.Order("updated_at desc")
  43 + if err := query.First(); err != nil {
  44 + if err.Error() == "pg: no rows in result set" {
  45 + return nil, domain.ErrorNotFound
  46 + } else {
  47 + return nil, err
  48 + }
  49 + }
  50 + if productPlanDispatchRecordModel.ProductPlanDispatchRecordId == 0 {
  51 + return nil, nil
  52 + } else {
  53 + return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel)
  54 + }
  55 +}
  1 +package domainService
  2 +
  3 +import (
  4 + "github.com/hibiken/asynq"
  5 + "github.com/linmadan/egglib-go/utils/json"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  8 +)
  9 +
  10 +func SendWorkshopWorkTimeStaticJob(productRecord *domain.ProductAttendanceRecord) error {
  11 + return SendAsyncJob(domain.TaskKeyWorkshopWorkTimeRecordStatics(), productRecord)
  12 +}
  13 +
  14 +func SendDeviceZkTecoReportJob(productRecord *domain.DeviceZkTeco) error {
  15 + return SendAsyncJob(domain.TaskDeviceZkTecoReport(), productRecord)
  16 +}
  17 +
  18 +func SendWorkshopDeviceData(productRecord *domain.DeviceCollection) error {
  19 + return SendAsyncJob(domain.TaskDeviceCollection(), productRecord)
  20 +}
  21 +
  22 +func SendAsyncJob(queueName string, job interface{}) error {
  23 + task := asynq.NewTask(queueName, []byte(json.MarshalToString(job)))
  24 +
  25 + client := asynq.NewClient(asynq.RedisClientOpt{Addr: constant.REDIS_ADDRESS})
  26 + _, err := client.Enqueue(task)
  27 + return err
  28 +}
  1 +package domainService
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  12 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  13 + "strconv"
  14 + "time"
  15 +)
  16 +
  17 +type PGWorkshopDataConsumeService struct {
  18 + transactionContext *pgTransaction.TransactionContext
  19 +}
  20 +
  21 +// 消费设备生产数据
  22 +func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *domain.DeviceCollection) (interface{}, error) {
  23 + var (
  24 + deviceRunningData *domain.DeviceRunningData
  25 + deviceRunningRecord *domain.DeviceRunningRecord
  26 + deviceDailyRecord *domain.DeviceDailyRunningRecord
  27 + workStation *domain.WorkStation
  28 + device *domain.Device
  29 + planId int
  30 + err error
  31 + plan *domain.ProductPlanDispatchRecord
  32 + datetime time.Time
  33 + )
  34 + var (
  35 + deviceRepository, _ = repository.NewDeviceRepository(ptr.transactionContext)
  36 + deviceRunningRecordRepository, _ = repository.NewDeviceRunningRecordRepository(ptr.transactionContext)
  37 + )
  38 +
  39 + if deviceRunningData, err = ptr.newDeviceRunningData(record); err != nil {
  40 + return nil, err
  41 + }
  42 +
  43 + // 0.初始化 从缓存捞数据、没取到查询库
  44 + deviceDailyRecord, err = redis.GetDeviceDailyRunningRecord(time.Now(), deviceRunningData.DeviceCode)
  45 + if err == domain.ErrorNotFound {
  46 + err = nil
  47 + }
  48 + if err != nil {
  49 + return nil, err
  50 + }
  51 + if deviceDailyRecord != nil {
  52 + workStation = deviceDailyRecord.WorkStation
  53 + planId = deviceDailyRecord.DeviceRunningRecordInfo.ProductPlanId
  54 + device = &domain.Device{
  55 + DeviceId: deviceDailyRecord.DeviceId,
  56 + DeviceCode: deviceDailyRecord.DeviceCode,
  57 + }
  58 + } else {
  59 +
  60 + // 0.1.查询记录对应的工段、批次
  61 + // 0.2.保存一天当日记录
  62 + if device, err = deviceRepository.FindOne(map[string]interface{}{"companyId": companyId, "orgId": orgId, "deviceCode": deviceRunningData.DeviceCode}); err != nil {
  63 + log.Logger.Error(fmt.Sprintf("【设备数据-消费】 未找到设备:%v 数据数据", deviceRunningData.DeviceCode))
  64 + return nil, nil
  65 + }
  66 + workStation = device.WorkStation
  67 + // 封箱机、串串机需要定位到批次
  68 + if record.DeviceType == domain.DeviceTypeFengXiangJi && record.DeviceType == domain.DeviceTypeChuanChuanJi {
  69 + datetime, _ = time.Parse("2006-01-02", deviceRunningData.Date)
  70 + if plan, err = ptr.findDeviceProductPlan(companyId, orgId, workStation.WorkStationId, datetime, deviceRunningData.DeviceCode); err != nil {
  71 + log.Logger.Error(err.Error())
  72 + } else {
  73 + planId = plan.PlanDispatchRecordExt.ProductPlanId
  74 + }
  75 + }
  76 + var saveErr error
  77 + if deviceDailyRecord, saveErr = ptr.saveDeviceDailyRunningRecord(companyId, orgId, workStation, device, planId, deviceRunningData); err != nil {
  78 + return nil, err
  79 + }
  80 + defer func() {
  81 + if saveErr != nil {
  82 + redis.RemoveDeviceDailyRunningRecord(time.Now(), deviceRunningData.DeviceCode)
  83 + }
  84 + }()
  85 + }
  86 +
  87 + // 1.保存设备运行记录
  88 + deviceRunningRecord, _ = ptr.newDeviceRunningRecord(companyId, orgId, workStation, device, deviceRunningData)
  89 + if _, err = deviceRunningRecordRepository.Save(deviceRunningRecord); err != nil {
  90 + return nil, err
  91 + }
  92 + // 2.保存设备生产记录
  93 +
  94 + // 3.更新 设备每日运行记录(汇总) - redis更新 十分钟异步刷库
  95 + deviceDailyRecord.DeviceRunningRecordInfo.AddDeviceRunningData(deviceRunningData.CollectionTime, deviceRunningData)
  96 + if err = redis.SaveDeviceDailyRunningRecord(deviceDailyRecord); err != nil {
  97 + return nil, err
  98 + }
  99 + return nil, nil
  100 +}
  101 +
  102 +func (ptr *PGWorkshopDataConsumeService) newDeviceRunningData(record *domain.DeviceCollection) (*domain.DeviceRunningData, error) {
  103 + var err error
  104 + var data = &domain.DeviceRunningData{
  105 + DeviceCollectionId: record.DeviceCollectionId,
  106 + WorkShopName: record.WorkShopName,
  107 + CollectionTime: record.CollectionTime,
  108 + DeviceCode: record.DeviceSn,
  109 + DeviceType: record.DeviceType,
  110 + StartupStatus: int(record.StartupStatus),
  111 + ComStatus: int(record.ComStatus),
  112 + }
  113 + var mBytes []byte
  114 + if mBytes, err = json.Marshal(record.Values); err != nil {
  115 + return nil, err
  116 + }
  117 + var formatDate = func(y, m, d string) (string, error) {
  118 + yd, _ := strconv.Atoi(y)
  119 + md, _ := strconv.Atoi(m)
  120 + dd, _ := strconv.Atoi(d)
  121 + t := time.Date(yd, time.Month(md), dd, 0, 0, 0, 0, time.Local)
  122 + return t.Format("2006-01-02"), nil
  123 + }
  124 + switch record.DeviceType {
  125 + //包馅机
  126 + case domain.DeviceTypeBaoXianJi:
  127 + deviceBaoXianJi := &domain.DeviceBaoXianJi{}
  128 + err = json.Unmarshal(mBytes, deviceBaoXianJi)
  129 + if err != nil {
  130 + break
  131 + }
  132 + data.Count = int(deviceBaoXianJi.Count)
  133 + break
  134 + //油炸机
  135 + case domain.DeviceTypeYouZhaJi:
  136 + deviceYouZhaJi := &domain.DeviceYouZhaJi{}
  137 + err = json.Unmarshal(mBytes, deviceYouZhaJi)
  138 + if err != nil {
  139 + break
  140 + }
  141 + data.Temp1 = deviceYouZhaJi.FrontTemp
  142 + break
  143 + //串串机
  144 + case domain.DeviceTypeChuanChuanJi:
  145 + deviceChuanChuanJi := &domain.DeviceChuanChuanJi{}
  146 + err = json.Unmarshal(mBytes, deviceChuanChuanJi)
  147 + if err != nil {
  148 + break
  149 + }
  150 + data.Count = int(deviceChuanChuanJi.Count)
  151 + data.ProductType = deviceChuanChuanJi.ProductType
  152 + if data.Date, err = formatDate(deviceChuanChuanJi.Year, deviceChuanChuanJi.Month, deviceChuanChuanJi.Day); err != nil {
  153 + return nil, err
  154 + }
  155 + break
  156 + //速冻线
  157 + case domain.DeviceTypeSuDongXian:
  158 + deviceSuDongXian := &domain.DeviceSuDongXian{}
  159 + err = json.Unmarshal(mBytes, deviceSuDongXian)
  160 + if err != nil {
  161 + break
  162 + }
  163 + data.Temp1 = deviceSuDongXian.CurrTemp
  164 + break
  165 + //封口机
  166 + case domain.DeviceTypeFengKouJi:
  167 + deviceFengKouJi := &domain.DeviceFengKouJi{}
  168 + err = json.Unmarshal(mBytes, deviceFengKouJi)
  169 + if err != nil {
  170 + break
  171 + }
  172 + data.Count = int(deviceFengKouJi.Count)
  173 + data.ProductType = deviceFengKouJi.ProductType
  174 + if data.Date, err = formatDate(deviceFengKouJi.Year, deviceFengKouJi.Month, deviceFengKouJi.Day); err != nil {
  175 + return nil, err
  176 + }
  177 + break
  178 + //封箱机
  179 + case domain.DeviceTypeFengXiangJi:
  180 + deviceFengXiangJi := &domain.DeviceFengXiangJi{}
  181 + err = json.Unmarshal(mBytes, deviceFengXiangJi)
  182 + if err != nil {
  183 + break
  184 + }
  185 + data.Count = int(deviceFengXiangJi.Count)
  186 + data.ProductType = deviceFengXiangJi.ProductType
  187 + if data.Date, err = formatDate(deviceFengXiangJi.Year, deviceFengXiangJi.Month, deviceFengXiangJi.Day); err != nil {
  188 + return nil, err
  189 + }
  190 + break
  191 + //打浆机
  192 + case domain.DeviceTypeDaJiangJi:
  193 + default:
  194 + }
  195 + return data, nil
  196 +}
  197 +
  198 +func (ptr *PGWorkshopDataConsumeService) newDeviceRunningRecord(companyId, orgId int, workStation *domain.WorkStation, device *domain.Device, data *domain.DeviceRunningData) (*domain.DeviceRunningRecord, error) {
  199 + return &domain.DeviceRunningRecord{
  200 + CompanyId: companyId,
  201 + OrgId: orgId,
  202 + WorkStation: workStation,
  203 + DeviceId: device.DeviceId,
  204 + DeviceCode: device.DeviceCode,
  205 + DeviceRunningRecordInfo: data,
  206 + CreatedAt: time.Now(),
  207 + }, nil
  208 +}
  209 +
  210 +func (ptr *PGWorkshopDataConsumeService) newProductRecord(companyId int, org *domain.Org, workStation *domain.WorkStation, device *domain.Device, data *domain.DeviceRunningData, planId int) (*domain.ProductRecord, error) {
  211 + return &domain.ProductRecord{
  212 + CompanyId: companyId,
  213 + OrgId: org.OrgId,
  214 + WorkStation: workStation,
  215 + ProductRecordType: domain.RecordTypeWeigh,
  216 + ProductWorker: &domain.User{},
  217 + CreatedAt: time.Now(),
  218 + UpdatedAt: time.Now(),
  219 + ProductRecordInfo: &domain.ProductRecordInfo{
  220 + ProductDate: data.CollectionTime.Format("2006-01-02"),
  221 + Original: float64(data.Count),
  222 + Weigh: float64(data.Count),
  223 + WeighBefore: float64(data.Count),
  224 + ApproveStatus: domain.AttendanceNotApprove,
  225 + ProductPlanId: planId,
  226 + },
  227 + Ext: domain.NewExt(org.OrgName),
  228 + }, nil
  229 +}
  230 +
  231 +func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId, orgId int, workStation *domain.WorkStation, device *domain.Device, planId int, data *domain.DeviceRunningData) (*domain.DeviceDailyRunningRecord, error) {
  232 + var (
  233 + record *domain.DeviceDailyRunningRecord
  234 + err error
  235 + )
  236 + deviceDailyRunningRecordRepository, _ := repository.NewDeviceDailyRunningRecordRepository(ptr.transactionContext)
  237 + if record, err = deviceDailyRunningRecordRepository.FindOne(map[string]interface{}{
  238 + "workStationId": workStation.WorkStationId,
  239 + "deviceCode": data.DeviceCode,
  240 + "productDate": utils.GetZeroTime(time.Now()),
  241 + }); err != nil {
  242 + if err != domain.ErrorNotFound {
  243 + return nil, err
  244 + }
  245 + }
  246 + if record != nil {
  247 + return record, nil
  248 + }
  249 + recordInfo := domain.NewDeviceRunningRecordInfo()
  250 + recordInfo.ProductPlanId = planId
  251 + record = &domain.DeviceDailyRunningRecord{
  252 + CompanyId: companyId,
  253 + OrgId: orgId,
  254 + WorkStation: workStation,
  255 + DeviceId: device.DeviceId,
  256 + DeviceCode: device.DeviceCode,
  257 + ProductDate: utils.GetZeroTime(time.Now()),
  258 + DeviceRunningRecordInfo: recordInfo,
  259 + CreatedAt: time.Now(),
  260 + UpdatedAt: time.Now(),
  261 + }
  262 + if record, err = deviceDailyRunningRecordRepository.Save(record); err != nil {
  263 + return nil, err
  264 + }
  265 + return record, nil
  266 +}
  267 +
  268 +// 查找设备的生产计划,如果计划没有上线的话将他上线
  269 +func (ptr *PGWorkshopDataConsumeService) findDeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
  270 + planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext)
  271 + planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext)
  272 + var setPlanOnline = false
  273 + record, err := planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOnline)
  274 + if err == domain.ErrorNotFound {
  275 + if record, err = planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOffline); err != nil {
  276 + return nil, err
  277 + } else {
  278 + setPlanOnline = true
  279 + }
  280 + }
  281 + if setPlanOnline {
  282 + record.ChangeStatus(domain.PlanOnline)
  283 + if record, err = planDispatchRecordRepository.Save(record); err != nil {
  284 + return nil, err
  285 + }
  286 + }
  287 + return record, nil
  288 +}
  289 +
  290 +func NewPGWorkshopDataConsumeService(transactionContext *pgTransaction.TransactionContext) (*PGWorkshopDataConsumeService, error) {
  291 + if transactionContext == nil {
  292 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  293 + } else {
  294 + return &PGWorkshopDataConsumeService{
  295 + transactionContext: transactionContext,
  296 + }, nil
  297 + }
  298 +}
@@ -3,10 +3,7 @@ package domainService @@ -3,10 +3,7 @@ package domainService
3 import ( 3 import (
4 "errors" 4 "errors"
5 "fmt" 5 "fmt"
6 - "github.com/hibiken/asynq"  
7 pgTransaction "github.com/linmadan/egglib-go/transaction/pg" 6 pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
8 - "github.com/linmadan/egglib-go/utils/json"  
9 - "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"  
10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 7 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository" 8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
@@ -58,22 +55,6 @@ func (ptr *PGWorkshopWorkTimeStaticService) WorkshopWorkTimeStatic(productRecord @@ -58,22 +55,6 @@ func (ptr *PGWorkshopWorkTimeStaticService) WorkshopWorkTimeStatic(productRecord
58 return record, nil 55 return record, nil
59 } 56 }
60 57
61 -func SendWorkshopWorkTimeStaticJob(productRecord *domain.ProductAttendanceRecord) error {  
62 - return SendAsyncJob(domain.TaskKeyWorkshopWorkTimeRecordStatics(), productRecord)  
63 -}  
64 -  
65 -func SendDeviceZkTecoReportJob(productRecord *domain.DeviceZkTeco) error {  
66 - return SendAsyncJob(domain.TaskDeviceZkTecoReport(), productRecord)  
67 -}  
68 -  
69 -func SendAsyncJob(queueName string, job interface{}) error {  
70 - task := asynq.NewTask(queueName, []byte(json.MarshalToString(job)))  
71 -  
72 - client := asynq.NewClient(asynq.RedisClientOpt{Addr: constant.REDIS_ADDRESS})  
73 - _, err := client.Enqueue(task)  
74 - return err  
75 -}  
76 -  
77 func NewPGWorkshopWorkTimeStaticService(transactionContext *pgTransaction.TransactionContext) (*PGWorkshopWorkTimeStaticService, error) { 58 func NewPGWorkshopWorkTimeStaticService(transactionContext *pgTransaction.TransactionContext) (*PGWorkshopWorkTimeStaticService, error) {
78 if transactionContext == nil { 59 if transactionContext == nil {
79 return nil, fmt.Errorf("transactionContext参数不能为nil") 60 return nil, fmt.Errorf("transactionContext参数不能为nil")
@@ -44,6 +44,8 @@ func init() { @@ -44,6 +44,8 @@ func init() {
44 (*models.WorkshopProductRecord)(nil), 44 (*models.WorkshopProductRecord)(nil),
45 (*models.WorkshopWorkTimeRecord)(nil), 45 (*models.WorkshopWorkTimeRecord)(nil),
46 (*models.ProductPlanDispatchRecord)(nil), 46 (*models.ProductPlanDispatchRecord)(nil),
  47 + (*models.DeviceDailyRunningRecord)(nil),
  48 + (*models.DeviceRunningRecord)(nil),
47 } { 49 } {
48 err := DB.Model(model).CreateTable(&orm.CreateTableOptions{ 50 err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
49 Temp: false, 51 Temp: false,
@@ -19,6 +19,8 @@ type DeviceDailyRunningRecord struct { @@ -19,6 +19,8 @@ type DeviceDailyRunningRecord struct {
19 DeviceId int `comment:"设备Id"` 19 DeviceId int `comment:"设备Id"`
20 // 设备编号 20 // 设备编号
21 DeviceCode string `comment:"设备编号"` 21 DeviceCode string `comment:"设备编号"`
  22 + // 生产日期
  23 + ProductDate time.Time `json:"productDate"`
22 // 设备运行记录信息 24 // 设备运行记录信息
23 DeviceRunningRecordInfo *domain.DeviceRunningRecordInfo `comment:"设备运行记录信息"` 25 DeviceRunningRecordInfo *domain.DeviceRunningRecordInfo `comment:"设备运行记录信息"`
24 // 创建时间 26 // 创建时间
@@ -20,7 +20,7 @@ type DeviceRunningRecord struct { @@ -20,7 +20,7 @@ type DeviceRunningRecord struct {
20 // 设备编号 20 // 设备编号
21 DeviceCode string `comment:"设备编号"` 21 DeviceCode string `comment:"设备编号"`
22 // 设备运行记录信息 22 // 设备运行记录信息
23 - DeviceRunningRecordInfo string `comment:"设备运行记录信息"` 23 + DeviceRunningRecordInfo *domain.DeviceRunningData `comment:"设备运行记录信息"`
24 // 创建时间 24 // 创建时间
25 CreatedAt time.Time `comment:"创建时间"` 25 CreatedAt time.Time `comment:"创建时间"`
26 } 26 }
@@ -13,6 +13,7 @@ func TransformToDeviceDailyRunningRecordDomainModelFromPgModels(deviceDailyRunni @@ -13,6 +13,7 @@ func TransformToDeviceDailyRunningRecordDomainModelFromPgModels(deviceDailyRunni
13 WorkStation: deviceDailyRunningRecordModel.WorkStation, 13 WorkStation: deviceDailyRunningRecordModel.WorkStation,
14 DeviceId: deviceDailyRunningRecordModel.DeviceId, 14 DeviceId: deviceDailyRunningRecordModel.DeviceId,
15 DeviceCode: deviceDailyRunningRecordModel.DeviceCode, 15 DeviceCode: deviceDailyRunningRecordModel.DeviceCode,
  16 + ProductDate: deviceDailyRunningRecordModel.ProductDate,
16 DeviceRunningRecordInfo: deviceDailyRunningRecordModel.DeviceRunningRecordInfo, 17 DeviceRunningRecordInfo: deviceDailyRunningRecordModel.DeviceRunningRecordInfo,
17 CreatedAt: deviceDailyRunningRecordModel.CreatedAt, 18 CreatedAt: deviceDailyRunningRecordModel.CreatedAt,
18 UpdatedAt: deviceDailyRunningRecordModel.UpdatedAt, 19 UpdatedAt: deviceDailyRunningRecordModel.UpdatedAt,
  1 +package redis
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + "github.com/go-redis/redis"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  9 + "time"
  10 +)
  11 +
  12 +// 获取每日设备运行数据
  13 +func GetDeviceDailyRunningRecord(t time.Time, deviceCode string) (*domain.DeviceDailyRunningRecord, error) {
  14 + client := GetRedis()
  15 + key := DeviceDailyRunningRecordKey(t, deviceCode)
  16 + result := client.Get(key)
  17 + data, err := result.Bytes()
  18 + if err == redis.Nil {
  19 + return nil, domain.ErrorNotFound
  20 + }
  21 + var record = &domain.DeviceDailyRunningRecord{}
  22 + if err = json.Unmarshal(data, record); err != nil {
  23 + return nil, err
  24 + }
  25 + return record, nil
  26 +}
  27 +
  28 +// 保存每日设备运行数据
  29 +func SaveDeviceDailyRunningRecord(record *domain.DeviceDailyRunningRecord) error {
  30 + client := GetRedis()
  31 + key := DeviceDailyRunningRecordKey(record.CreatedAt, record.DeviceCode)
  32 + recordData, err := json.Marshal(record)
  33 + result := client.Set(key, recordData, time.Hour*24*5)
  34 + _, err = result.Result()
  35 + return err
  36 +}
  37 +
  38 +// 保存每日设备运行数据
  39 +func RemoveDeviceDailyRunningRecord(t time.Time, deviceCode string) error {
  40 + client := GetRedis()
  41 + key := DeviceDailyRunningRecordKey(t, deviceCode)
  42 + result := client.Del(key)
  43 + _, err := result.Result()
  44 + return err
  45 +}
  46 +
  47 +func DeviceDailyRunningRecordKey(t time.Time, deviceCode string) string {
  48 + str := fmt.Sprintf("%v:device-daily-record:%v-%v:%v:%v", constant.CACHE_PREFIX, constant.MANUFACTURE_DEFAULT_COMPANYID, constant.MANUFACTURE_DEFAULT_ORGID, t.Format("2006-01-02"), deviceCode)
  49 + return str
  50 +}
@@ -32,15 +32,16 @@ func (repository *DeviceDailyRunningRecordRepository) Save(deviceDailyRunningRec @@ -32,15 +32,16 @@ func (repository *DeviceDailyRunningRecordRepository) Save(deviceDailyRunningRec
32 "work_station", 32 "work_station",
33 "device_id", 33 "device_id",
34 "device_code", 34 "device_code",
  35 + "product_date",
35 "device_running_record_info", 36 "device_running_record_info",
36 "created_at", 37 "created_at",
37 "updated_at", 38 "updated_at",
38 "deleted_at", 39 "deleted_at",
39 } 40 }
40 - insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)  
41 - insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields) 41 + insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "device_daily_running_record_id", "deleted_at"))
  42 + insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "device_daily_running_record_id", "deleted_at"))
42 returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields) 43 returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
43 - updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "deviceDailyRunningRecord_id") 44 + updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "device_daily_running_record_id", "deleted_at")
44 updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields) 45 updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
45 tx := repository.transactionContext.PgTx 46 tx := repository.transactionContext.PgTx
46 if deviceDailyRunningRecord.Identify() == nil { 47 if deviceDailyRunningRecord.Identify() == nil {
@@ -52,22 +53,24 @@ func (repository *DeviceDailyRunningRecordRepository) Save(deviceDailyRunningRec @@ -52,22 +53,24 @@ func (repository *DeviceDailyRunningRecordRepository) Save(deviceDailyRunningRec
52 &deviceDailyRunningRecord.WorkStation, 53 &deviceDailyRunningRecord.WorkStation,
53 &deviceDailyRunningRecord.DeviceId, 54 &deviceDailyRunningRecord.DeviceId,
54 &deviceDailyRunningRecord.DeviceCode, 55 &deviceDailyRunningRecord.DeviceCode,
  56 + &deviceDailyRunningRecord.ProductDate,
55 &deviceDailyRunningRecord.DeviceRunningRecordInfo, 57 &deviceDailyRunningRecord.DeviceRunningRecordInfo,
56 &deviceDailyRunningRecord.CreatedAt, 58 &deviceDailyRunningRecord.CreatedAt,
57 &deviceDailyRunningRecord.UpdatedAt, 59 &deviceDailyRunningRecord.UpdatedAt,
58 &deviceDailyRunningRecord.DeletedAt, 60 &deviceDailyRunningRecord.DeletedAt,
59 ), 61 ),
60 fmt.Sprintf("INSERT INTO manufacture.device_daily_running_record (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet), 62 fmt.Sprintf("INSERT INTO manufacture.device_daily_running_record (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
61 - deviceDailyRunningRecord.DeviceDailyRunningRecordId, 63 + //deviceDailyRunningRecord.DeviceDailyRunningRecordId,
62 deviceDailyRunningRecord.CompanyId, 64 deviceDailyRunningRecord.CompanyId,
63 deviceDailyRunningRecord.OrgId, 65 deviceDailyRunningRecord.OrgId,
64 deviceDailyRunningRecord.WorkStation, 66 deviceDailyRunningRecord.WorkStation,
65 deviceDailyRunningRecord.DeviceId, 67 deviceDailyRunningRecord.DeviceId,
66 deviceDailyRunningRecord.DeviceCode, 68 deviceDailyRunningRecord.DeviceCode,
  69 + deviceDailyRunningRecord.ProductDate,
67 deviceDailyRunningRecord.DeviceRunningRecordInfo, 70 deviceDailyRunningRecord.DeviceRunningRecordInfo,
68 deviceDailyRunningRecord.CreatedAt, 71 deviceDailyRunningRecord.CreatedAt,
69 deviceDailyRunningRecord.UpdatedAt, 72 deviceDailyRunningRecord.UpdatedAt,
70 - deviceDailyRunningRecord.DeletedAt, 73 + //deviceDailyRunningRecord.DeletedAt,
71 ); err != nil { 74 ); err != nil {
72 return deviceDailyRunningRecord, err 75 return deviceDailyRunningRecord, err
73 } 76 }
@@ -80,22 +83,24 @@ func (repository *DeviceDailyRunningRecordRepository) Save(deviceDailyRunningRec @@ -80,22 +83,24 @@ func (repository *DeviceDailyRunningRecordRepository) Save(deviceDailyRunningRec
80 &deviceDailyRunningRecord.WorkStation, 83 &deviceDailyRunningRecord.WorkStation,
81 &deviceDailyRunningRecord.DeviceId, 84 &deviceDailyRunningRecord.DeviceId,
82 &deviceDailyRunningRecord.DeviceCode, 85 &deviceDailyRunningRecord.DeviceCode,
  86 + &deviceDailyRunningRecord.ProductDate,
83 &deviceDailyRunningRecord.DeviceRunningRecordInfo, 87 &deviceDailyRunningRecord.DeviceRunningRecordInfo,
84 &deviceDailyRunningRecord.CreatedAt, 88 &deviceDailyRunningRecord.CreatedAt,
85 &deviceDailyRunningRecord.UpdatedAt, 89 &deviceDailyRunningRecord.UpdatedAt,
86 &deviceDailyRunningRecord.DeletedAt, 90 &deviceDailyRunningRecord.DeletedAt,
87 ), 91 ),
88 fmt.Sprintf("UPDATE manufacture.device_daily_running_record SET %s WHERE device_daily_running_record_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet), 92 fmt.Sprintf("UPDATE manufacture.device_daily_running_record SET %s WHERE device_daily_running_record_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
89 - deviceDailyRunningRecord.DeviceDailyRunningRecordId, 93 + //deviceDailyRunningRecord.DeviceDailyRunningRecordId,
90 deviceDailyRunningRecord.CompanyId, 94 deviceDailyRunningRecord.CompanyId,
91 deviceDailyRunningRecord.OrgId, 95 deviceDailyRunningRecord.OrgId,
92 deviceDailyRunningRecord.WorkStation, 96 deviceDailyRunningRecord.WorkStation,
93 deviceDailyRunningRecord.DeviceId, 97 deviceDailyRunningRecord.DeviceId,
94 deviceDailyRunningRecord.DeviceCode, 98 deviceDailyRunningRecord.DeviceCode,
  99 + deviceDailyRunningRecord.ProductDate,
95 deviceDailyRunningRecord.DeviceRunningRecordInfo, 100 deviceDailyRunningRecord.DeviceRunningRecordInfo,
96 deviceDailyRunningRecord.CreatedAt, 101 deviceDailyRunningRecord.CreatedAt,
97 deviceDailyRunningRecord.UpdatedAt, 102 deviceDailyRunningRecord.UpdatedAt,
98 - deviceDailyRunningRecord.DeletedAt, 103 + //deviceDailyRunningRecord.DeletedAt,
99 deviceDailyRunningRecord.Identify(), 104 deviceDailyRunningRecord.Identify(),
100 ); err != nil { 105 ); err != nil {
101 return deviceDailyRunningRecord, err 106 return deviceDailyRunningRecord, err
@@ -116,10 +121,13 @@ func (repository *DeviceDailyRunningRecordRepository) FindOne(queryOptions map[s @@ -116,10 +121,13 @@ func (repository *DeviceDailyRunningRecordRepository) FindOne(queryOptions map[s
116 tx := repository.transactionContext.PgTx 121 tx := repository.transactionContext.PgTx
117 deviceDailyRunningRecordModel := new(models.DeviceDailyRunningRecord) 122 deviceDailyRunningRecordModel := new(models.DeviceDailyRunningRecord)
118 query := sqlbuilder.BuildQuery(tx.Model(deviceDailyRunningRecordModel), queryOptions) 123 query := sqlbuilder.BuildQuery(tx.Model(deviceDailyRunningRecordModel), queryOptions)
  124 + query.SetWhereByQueryOption("work_station->>'workStationId'=?", "workStationId")
  125 + query.SetWhereByQueryOption("device_code=? ", "deviceCode")
  126 + query.SetWhereByQueryOption("product_date=? ", "productDate")
119 query.SetWhereByQueryOption("device_daily_running_record.device_daily_running_record_id = ?", "deviceDailyRunningRecordId") 127 query.SetWhereByQueryOption("device_daily_running_record.device_daily_running_record_id = ?", "deviceDailyRunningRecordId")
120 if err := query.First(); err != nil { 128 if err := query.First(); err != nil {
121 if err.Error() == "pg: no rows in result set" { 129 if err.Error() == "pg: no rows in result set" {
122 - return nil, fmt.Errorf("没有此资源") 130 + return nil, domain.ErrorNotFound
123 } else { 131 } else {
124 return nil, err 132 return nil, err
125 } 133 }
@@ -53,7 +53,7 @@ func (repository *DeviceRunningRecordRepository) Save(deviceRunningRecord *domai @@ -53,7 +53,7 @@ func (repository *DeviceRunningRecordRepository) Save(deviceRunningRecord *domai
53 &deviceRunningRecord.DeviceRunningRecordInfo, 53 &deviceRunningRecord.DeviceRunningRecordInfo,
54 &deviceRunningRecord.CreatedAt, 54 &deviceRunningRecord.CreatedAt,
55 ), 55 ),
56 - fmt.Sprintf("INSERT INTO device_running_records (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet), 56 + fmt.Sprintf("INSERT INTO manufacture.device_running_record (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
57 //deviceRunningRecord.DeviceRunningRecordId, 57 //deviceRunningRecord.DeviceRunningRecordId,
58 deviceRunningRecord.CompanyId, 58 deviceRunningRecord.CompanyId,
59 deviceRunningRecord.OrgId, 59 deviceRunningRecord.OrgId,
@@ -77,7 +77,7 @@ func (repository *DeviceRunningRecordRepository) Save(deviceRunningRecord *domai @@ -77,7 +77,7 @@ func (repository *DeviceRunningRecordRepository) Save(deviceRunningRecord *domai
77 &deviceRunningRecord.DeviceRunningRecordInfo, 77 &deviceRunningRecord.DeviceRunningRecordInfo,
78 &deviceRunningRecord.CreatedAt, 78 &deviceRunningRecord.CreatedAt,
79 ), 79 ),
80 - fmt.Sprintf("UPDATE device_running_records SET %s WHERE device_running_record_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet), 80 + fmt.Sprintf("UPDATE manufacture.device_running_record SET %s WHERE device_running_record_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
81 //deviceRunningRecord.DeviceRunningRecordId, 81 //deviceRunningRecord.DeviceRunningRecordId,
82 deviceRunningRecord.CompanyId, 82 deviceRunningRecord.CompanyId,
83 deviceRunningRecord.OrgId, 83 deviceRunningRecord.OrgId,
@@ -150,6 +150,15 @@ func (repository *ProductPlanDispatchRecordRepository) Find(queryOptions map[str @@ -150,6 +150,15 @@ func (repository *ProductPlanDispatchRecordRepository) Find(queryOptions map[str
150 var productPlanDispatchRecordModels []*models.ProductPlanDispatchRecord 150 var productPlanDispatchRecordModels []*models.ProductPlanDispatchRecord
151 productPlanDispatchRecords := make([]*domain.ProductPlanDispatchRecord, 0) 151 productPlanDispatchRecords := make([]*domain.ProductPlanDispatchRecord, 0)
152 query := sqlbuilder.BuildQuery(tx.Model(&productPlanDispatchRecordModels), queryOptions) 152 query := sqlbuilder.BuildQuery(tx.Model(&productPlanDispatchRecordModels), queryOptions)
  153 + query.SetWhereByQueryOption("company_id = ?", "companyId")
  154 + query.SetWhereByQueryOption("org_id = ?", "orgId")
  155 + query.SetWhereByQueryOption("work_station->>'workshopId'='?'", "workshopId")
  156 + if v, ok := queryOptions["batchNumber"]; ok && len(v.(string)) > 0 {
  157 + query.Where(fmt.Sprintf(`batch_number like '%%%v%%'`, v))
  158 + }
  159 + if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
  160 + query.Where(fmt.Sprintf(`workshop->>'workshopName' like '%%%v%%'`, v))
  161 + }
153 query.SetWhereByQueryOption("plan_dispatch_status=?", "planDispatchStatus") 162 query.SetWhereByQueryOption("plan_dispatch_status=?", "planDispatchStatus")
154 query.SetOffsetAndLimit(domain.MaxQueryRow) 163 query.SetOffsetAndLimit(domain.MaxQueryRow)
155 query.SetOrderDirect("product_plan_dispatch_record_id", "DESC") 164 query.SetOrderDirect("product_plan_dispatch_record_id", "DESC")
@@ -63,6 +63,10 @@ func (controller *AttendanceController) ApproveAttendance() { @@ -63,6 +63,10 @@ func (controller *AttendanceController) ApproveAttendance() {
63 attendanceService := service.NewAttendanceService(nil) 63 attendanceService := service.NewAttendanceService(nil)
64 approveAttendanceCommand := &command.ApproveAttendanceCommand{} 64 approveAttendanceCommand := &command.ApproveAttendanceCommand{}
65 controller.Unmarshal(approveAttendanceCommand) 65 controller.Unmarshal(approveAttendanceCommand)
  66 + if approveAttendanceCommand.ApproveUserId == 0 {
  67 + operateInfo := ParseOperateInfo(controller.BaseController)
  68 + approveAttendanceCommand.ApproveUserId = operateInfo.UserId
  69 + }
66 data, err := attendanceService.ApproveAttendance(approveAttendanceCommand) 70 data, err := attendanceService.ApproveAttendance(approveAttendanceCommand)
67 controller.Response(data, err) 71 controller.Response(data, err)
68 } 72 }
@@ -63,6 +63,10 @@ func (controller *ProductRecordController) ApproveProductRecord() { @@ -63,6 +63,10 @@ func (controller *ProductRecordController) ApproveProductRecord() {
63 productRecordService := service.NewProductRecordService(nil) 63 productRecordService := service.NewProductRecordService(nil)
64 approveProductRecordCommand := &command.ApproveProductRecordCommand{} 64 approveProductRecordCommand := &command.ApproveProductRecordCommand{}
65 controller.Unmarshal(approveProductRecordCommand) 65 controller.Unmarshal(approveProductRecordCommand)
  66 + if approveProductRecordCommand.ApproveUserId == 0 {
  67 + operateInfo := ParseOperateInfo(controller.BaseController)
  68 + approveProductRecordCommand.ApproveUserId = operateInfo.UserId
  69 + }
66 data, err := productRecordService.ApproveProductRecord(approveProductRecordCommand) 70 data, err := productRecordService.ApproveProductRecord(approveProductRecordCommand)
67 controller.Response(data, err) 71 controller.Response(data, err)
68 } 72 }
@@ -3,6 +3,8 @@ package controllers @@ -3,6 +3,8 @@ package controllers
3 import ( 3 import (
4 "github.com/linmadan/egglib-go/web/beego" 4 "github.com/linmadan/egglib-go/web/beego"
5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata" 5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/syncdata"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
6 ) 8 )
7 9
8 type TestController struct { 10 type TestController struct {
@@ -26,3 +28,10 @@ func (c *TestController) InvokPullPrdMoNewest() { @@ -26,3 +28,10 @@ func (c *TestController) InvokPullPrdMoNewest() {
26 err := srv.PullPrdMoNewest() 28 err := srv.PullPrdMoNewest()
27 c.Response(nil, err) 29 c.Response(nil, err)
28 } 30 }
  31 +
  32 +func (c *TestController) CreateDeviceCollection() {
  33 + data := &domain.DeviceCollection{}
  34 + Must(c.Unmarshal(data))
  35 + domainService.SendWorkshopDeviceData(data)
  36 + c.Response(nil, nil)
  37 +}
@@ -9,4 +9,6 @@ func init() { @@ -9,4 +9,6 @@ func init() {
9 web.Router("/TestController/PullMaterialNewest", &controllers.TestController{}, "Get:InvokPullMaterialNewest") 9 web.Router("/TestController/PullMaterialNewest", &controllers.TestController{}, "Get:InvokPullMaterialNewest")
10 web.Router("/TestController/PullMaterialGroup", &controllers.TestController{}, "Get:InvokPullMaterialGroup") 10 web.Router("/TestController/PullMaterialGroup", &controllers.TestController{}, "Get:InvokPullMaterialGroup")
11 web.Router("/TestController/InvokPullPrdMoNewest", &controllers.TestController{}, "Get:InvokPullPrdMoNewest") 11 web.Router("/TestController/InvokPullPrdMoNewest", &controllers.TestController{}, "Get:InvokPullPrdMoNewest")
  12 +
  13 + web.Router("/test/create-device-collection", &controllers.TestController{}, "Post:CreateDeviceCollection")
12 } 14 }
@@ -6,8 +6,8 @@ import ( @@ -6,8 +6,8 @@ import (
6 "github.com/tidwall/gjson" 6 "github.com/tidwall/gjson"
7 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant" 7 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/mqtt" 10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/mqtt"
10 - "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"  
11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log" 12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
13 "time" 13 "time"
@@ -101,11 +101,15 @@ func Start() { @@ -101,11 +101,15 @@ func Start() {
101 case domain.DeviceTypeDaJiangJi: 101 case domain.DeviceTypeDaJiangJi:
102 default: 102 default:
103 } 103 }
104 - workShopBytes, err := json.Marshal(deviceCollection)  
105 - if err != nil {  
106 - continue  
107 - }  
108 - err = redis.GetRedis().LPush(constant.REDIS_WORKSHOP_KEY, string(workShopBytes)).Err() 104 + //workShopBytes, err := json.Marshal(deviceCollection)
  105 + //if err != nil {
  106 + // continue
  107 + //}
  108 + //err = redis.GetRedis().LPush(constant.REDIS_WORKSHOP_KEY, string(workShopBytes)).Err()
  109 + //if err != nil {
  110 + // log.Logger.Error("车间设备数据加入redis失败:" + err.Error())
  111 + //}
  112 + err = domainService.SendWorkshopDeviceData(deviceCollection)
109 if err != nil { 113 if err != nil {
110 log.Logger.Error("车间设备数据加入redis失败:" + err.Error()) 114 log.Logger.Error("车间设备数据加入redis失败:" + err.Error())
111 } 115 }
@@ -21,6 +21,7 @@ func Run() { @@ -21,6 +21,7 @@ func Run() {
21 h.HandleFunc(domain.TaskKeyPatternProductRecordStatics(), HandlerProductRecordStatics) 21 h.HandleFunc(domain.TaskKeyPatternProductRecordStatics(), HandlerProductRecordStatics)
22 h.HandleFunc(domain.TaskKeyWorkshopWorkTimeRecordStatics(), WorkshopWorkTimeRecordStatics) 22 h.HandleFunc(domain.TaskKeyWorkshopWorkTimeRecordStatics(), WorkshopWorkTimeRecordStatics)
23 h.HandleFunc(domain.TaskDeviceZkTecoReport(), WorkerAttendanceReport) 23 h.HandleFunc(domain.TaskDeviceZkTecoReport(), WorkerAttendanceReport)
  24 + h.HandleFunc(domain.TaskDeviceCollection(), WorkshopDataConsumer)
24 log.Logger.Info("aysnq task running ...") 25 log.Logger.Info("aysnq task running ...")
25 // Run blocks and waits for os signal to terminate the program. 26 // Run blocks and waits for os signal to terminate the program.
26 if err := srv.Run(h); err != nil { 27 if err := srv.Run(h); err != nil {
@@ -14,8 +14,9 @@ import ( @@ -14,8 +14,9 @@ import (
14 func WorkshopWorkTimeRecordStatics(c context.Context, t *asynq.Task) error { 14 func WorkshopWorkTimeRecordStatics(c context.Context, t *asynq.Task) error {
15 svr := service.NewAttendanceService(nil) 15 svr := service.NewAttendanceService(nil)
16 cmd := &command.WorkshopWorkTimeRecordStaticsCommand{} 16 cmd := &command.WorkshopWorkTimeRecordStaticsCommand{}
17 - if err := json.Unmarshal(t.Payload(), cmd); err != nil || cmd == nil {  
18 - return err 17 + if err := json.Unmarshal(t.Payload(), cmd); err != nil {
  18 + log.Logger.Error("【考勤记录统计】 数据解析" + err.Error())
  19 + return nil
19 } 20 }
20 log.Logger.Debug(fmt.Sprintf("【考勤记录统计】 消费 记录ID:%v 时间:%v", cmd.ProductAttendanceId, cmd.WorkTimeBefore)) 21 log.Logger.Debug(fmt.Sprintf("【考勤记录统计】 消费 记录ID:%v 时间:%v", cmd.ProductAttendanceId, cmd.WorkTimeBefore))
21 _, err := svr.WorkshopWorkTimeRecordStatics(cmd) 22 _, err := svr.WorkshopWorkTimeRecordStatics(cmd)
  1 +package task
  2 +
  3 +import (
  4 + "context"
  5 + "encoding/json"
  6 + "fmt"
  7 + "github.com/hibiken/asynq"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/workshop/command"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/workshop/service"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  12 +)
  13 +
  14 +// 车间数据消费
  15 +func WorkshopDataConsumer(c context.Context, t *asynq.Task) error {
  16 + svr := service.NewWorkshopService(nil)
  17 + cmd := &command.WorkshopDataConsumeCommand{}
  18 + if err := json.Unmarshal(t.Payload(), cmd); err != nil {
  19 + return err
  20 + }
  21 + log.Logger.Debug(fmt.Sprintf("【车间数据消费】 消费 设备:%v 消息号:%v 时间:%v ", cmd.DeviceCollection.DeviceSn, cmd.DeviceCollectionId, cmd.CollectionTime))
  22 + cmd.CompanyId = constant.MANUFACTURE_DEFAULT_COMPANYID
  23 + cmd.OrgId = constant.MANUFACTURE_DEFAULT_ORGID
  24 + _, err := svr.WorkshopConsume(cmd)
  25 + if err != nil {
  26 + log.Logger.Error(err.Error())
  27 + }
  28 + return nil
  29 +}