作者 yangfu

增加车间工位管理

... ... @@ -34,10 +34,76 @@ func FastPgWorkshop(transactionContext application.TransactionContext, id int, o
return rep, mod, err
}
// FastPgWorkstation 快速返回工作定位对象
//
// transactionContext 事务
// workshopId 车间ID
// lineId 生产线ID
// sectionId 对象ID
func FastPgWorkstation(transactionContext application.TransactionContext, workshopId, lineId, sectionId int, options ...option) (domain.WorkshopRepository, *domain.WorkStation, error) {
var rep domain.WorkshopRepository
var mod *domain.Workshop
var err error
if value, err := CreateWorkshopRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
rep = value
}
if mod, err = rep.FindOne(map[string]interface{}{"workshopId": workshopId}); err != nil {
if err == domain.ErrorNotFound {
return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该车间不存在")
}
return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
workStation, err := mod.FindWorkStation(workshopId, lineId, sectionId)
if err != nil {
return rep, nil, err
}
o := NewFastOptions(options...)
if o.SetPrincipal {
workStation.Principal = mod.Principal
}
return rep, workStation, err
}
// FastPgProductJob 快速返回工位对象
//
// transactionContext 事务
// id 对象唯一标识
func FastPgProductJob(transactionContext application.TransactionContext, id int, options ...option) (domain.ProductJobRepository, *domain.ProductJob, error) {
var rep domain.ProductJobRepository
var mod *domain.ProductJob
var err error
if value, err := CreateProductJobRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
rep = value
}
if id > 0 {
if mod, err = rep.FindOne(map[string]interface{}{"productJobId": id}); err != nil {
if err == domain.ErrorNotFound {
return nil, nil, application.ThrowError(application.RES_NO_FIND_ERROR, "该车间不存在")
}
return nil, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
}
//if err = fastPgDataAuth(transactionContext, mod, options...); err != nil {
// return nil, nil, err
//}
return rep, mod, err
}
/***** 2.配置 *****/
type FastOptions struct {
DataAuthRequired bool
SetPrincipal bool
OperateInfo *domain.OperateInfo
}
... ... @@ -66,3 +132,10 @@ func WithOperator(op *domain.OperateInfo) option {
options.OperateInfo = op
}
}
// WithOperator 操作人
func WithSetPrincipal() option {
return func(options *FastOptions) {
options.SetPrincipal = true
}
}
... ...
... ... @@ -10,11 +10,13 @@ import (
type CreateProductJobCommand struct {
// 企业id
CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
//CompanyId int `cname:"企业id" json:"companyId" valid:"Required"`
// 组织ID
OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
//OrgId int `cname:"组织ID" json:"orgId" valid:"Required"`
// 工位名称
JobName string `cname:"工位名称" json:"jobName" valid:"Required"`
// 工位名称
ProcessName string `cname:"工位名称" json:"processName" valid:"Required"`
// 车间ID
WorkshopId int `cname:"车间ID" json:"workshopId" valid:"Required"`
// 生产线ID
... ... @@ -26,7 +28,7 @@ type CreateProductJobCommand struct {
}
func (createProductJobCommand *CreateProductJobCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (createProductJobCommand *CreateProductJobCommand) ValidateCommand() error {
... ...
... ... @@ -14,7 +14,7 @@ type RemoveProductJobCommand struct {
}
func (removeProductJobCommand *RemoveProductJobCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (removeProductJobCommand *RemoveProductJobCommand) ValidateCommand() error {
... ...
... ... @@ -24,7 +24,7 @@ type UpdateProductJobCommand struct {
}
func (updateProductJobCommand *UpdateProductJobCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateProductJobCommand *UpdateProductJobCommand) ValidateCommand() error {
... ...
package dto
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
type ProductJobDto struct {
// 工位ID
ProductJobId int `json:"productJobId,omitempty"`
// 工位名称
JobName string `json:"jobName,omitempty"`
// 工序名称
ProcessName string `json:"processName,omitempty"`
//// 工作位置键值 (车间ID+'.'+生产线ID+'.'+工段ID)
//WorkStationId string `json:"workStationId,omitempty"`
//// 车间ID
//WorkshopId int `json:"workshopId,omitempty"`
//// 车间名称
//WorkshopName string `json:"workshopName,omitempty"`
//// 生产线ID
//LineId int `json:"lineId,omitempty"`
//// 生产线名称
//LineName string `json:"lineName,omitempty"`
//// 工段ID
//SectionId int `json:"sectionId,omitempty"`
//// 工段名称
//SectionName string `json:"sectionName,omitempty"`
//// 负责人 (用户对象)
//Principal *domain.User `json:"principal,omitempty"`
*domain.WorkStation
}
func (m *ProductJobDto) LoadDto(job *domain.ProductJob) {
m.ProductJobId = job.ProductJobId
m.JobName = job.JobName
m.ProcessName = job.ProcessName
m.WorkStation = job.WorkStation
}
... ...
... ... @@ -14,7 +14,7 @@ type GetProductJobQuery struct {
}
func (getProductJobQuery *GetProductJobQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getProductJobQuery *GetProductJobQuery) ValidateQuery() error {
... ...
... ... @@ -2,6 +2,7 @@ package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"reflect"
"strings"
... ... @@ -10,23 +11,37 @@ import (
type ListProductJobQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset" valid:"Required"`
Offset int `cname:"查询偏离量" json:"offset,omitempty"`
// 查询限制
Limit int `cname:"查询限制" json:"limit" valid:"Required"`
Limit int `cname:"查询限制" json:"limit,omitempty"`
// 当前公司
CompanyId int `json:"-"`
// 当前登录的组织
OrgId int `json:"-"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 工位名称
JobName string `cname:"车间名称" json:"jobName,omitempty"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
}
func (listProductJobQuery *ListProductJobQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
func (cmd *ListProductJobQuery) Valid(validation *validation.Validation) {
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
}
func (listProductJobQuery *ListProductJobQuery) ValidateQuery() error {
func (cmd *ListProductJobQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(listProductJobQuery)
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(listProductJobQuery).Elem()
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
... ...
package query
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type SearchProductJobQuery struct {
// 查询偏离量
Offset int `cname:"查询偏离量" json:"offset,omitempty"`
// 查询限制
Limit int `cname:"查询限制" json:"limit,omitempty"`
// 当前公司
CompanyId int `cname:"当前公司" json:"companyId,omitempty" valid:"Required"`
// 当前登录的组织
OrgId int `cname:"当前登录的组织" json:"orgId,omitempty" valid:"Required"`
// 页码
PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
// 页数
PageSize int `cname:"页数" json:"pageSize,omitempty"`
// 工位名称
JobName string `cname:"车间名称" json:"jobName,omitempty"`
// 车间名称
WorkshopName string `cname:"车间名称" json:"workshopName,omitempty"`
// 生产线名称
LineName string `cname:"生产线名称" json:"lineName,omitempty"`
}
func (cmd *SearchProductJobQuery) Valid(validation *validation.Validation) {
cmd.Offset, cmd.Limit = domain.Pagination(cmd.PageNumber, cmd.PageSize)
}
func (cmd *SearchProductJobQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(cmd)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(cmd).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
... ... @@ -6,8 +6,11 @@ import (
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productJob/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productJob/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productJob/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
"time"
)
// 工位服务
... ... @@ -15,8 +18,8 @@ type ProductJobService struct {
}
// 创建工位服务
func (productJobService *ProductJobService) CreateProductJob(createProductJobCommand *command.CreateProductJobCommand) (interface{}, error) {
if err := createProductJobCommand.ValidateCommand(); err != nil {
func (productJobService *ProductJobService) CreateProductJob(operateInfo *domain.OperateInfo, cmd *command.CreateProductJobCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
... ... @@ -29,24 +32,36 @@ func (productJobService *ProductJobService) CreateProductJob(createProductJobCom
defer func() {
transactionContext.RollbackTransaction()
}()
newProductJob := &domain.ProductJob{
CompanyId: createProductJobCommand.CompanyId,
OrgId: createProductJobCommand.OrgId,
JobName: createProductJobCommand.JobName,
//WorkshopId: createProductJobCommand.WorkshopId,
//LineId: createProductJobCommand.LineId,
//SectionId: createProductJobCommand.SectionId,
RelatedDevices: createProductJobCommand.RelatedDevices,
//var workshopRepository domain.WorkshopRepository
var workStation *domain.WorkStation
_, workStation, err = factory.FastPgWorkstation(transactionContext, cmd.WorkshopId, cmd.LineId, cmd.SectionId, factory.WithSetPrincipal())
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var productJobRepository domain.ProductJobRepository
if value, err := factory.CreateProductJobRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productJobRepository = value
var productJob *domain.ProductJob
productJobRepository, productJob, _ = factory.FastPgProductJob(transactionContext, 0)
if job, err := productJobRepository.FindOne(map[string]interface{}{
"jobName": cmd.JobName,
"workStationId": workStation.WorkStationId,
}); err == nil && job != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "有重复的工位")
}
productJob = &domain.ProductJob{
CompanyId: operateInfo.CompanyId,
OrgId: operateInfo.OrgId,
JobName: cmd.JobName,
ProcessName: cmd.ProcessName,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
WorkStation: workStation,
RelatedDevices: cmd.RelatedDevices,
}
if productJob, err := productJobRepository.Save(newProductJob); err != nil {
if productJob, err := productJobRepository.Save(productJob); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := transactionContext.CommitTransaction(); err != nil {
... ... @@ -71,26 +86,17 @@ func (productJobService *ProductJobService) GetProductJob(getProductJobQuery *qu
defer func() {
transactionContext.RollbackTransaction()
}()
var productJobRepository domain.ProductJobRepository
if value, err := factory.CreateProductJobRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productJobRepository = value
}
productJob, err := productJobRepository.FindOne(map[string]interface{}{"productJobId": getProductJobQuery.ProductJobId})
//var productJobRepository domain.ProductJobRepository
_, productJob, err := factory.FastPgProductJob(transactionContext, getProductJobQuery.ProductJobId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productJob == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(getProductJobQuery.ProductJobId)))
} else {
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return productJob, nil
}
newJobDto := &dto.ProductJobDto{}
newJobDto.LoadDto(productJob)
return newJobDto, nil
}
// 返回工位服务列表
... ... @@ -170,8 +176,8 @@ func (productJobService *ProductJobService) RemoveProductJob(removeProductJobCom
}
// 更新工位服务
func (productJobService *ProductJobService) UpdateProductJob(updateProductJobCommand *command.UpdateProductJobCommand) (interface{}, error) {
if err := updateProductJobCommand.ValidateCommand(); err != nil {
func (productJobService *ProductJobService) UpdateProductJob(cmd *command.UpdateProductJobCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
... ... @@ -184,24 +190,41 @@ func (productJobService *ProductJobService) UpdateProductJob(updateProductJobCom
defer func() {
transactionContext.RollbackTransaction()
}()
var productJobRepository domain.ProductJobRepository
if value, err := factory.CreateProductJobRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productJobRepository = value
}
productJob, err := productJobRepository.FindOne(map[string]interface{}{"productJobId": updateProductJobCommand.ProductJobId})
//var workshopRepository domain.WorkshopRepository
var workStation *domain.WorkStation
_, workStation, err = factory.FastPgWorkstation(transactionContext, cmd.WorkshopId, cmd.LineId, cmd.SectionId, factory.WithSetPrincipal())
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if productJob == nil {
return nil, application.ThrowError(application.RES_NO_FIND_ERROR, fmt.Sprintf("%s", string(updateProductJobCommand.ProductJobId)))
var productJobRepository domain.ProductJobRepository
var productJob *domain.ProductJob
var checkDuplicateJobName = false
productJobRepository, productJob, _ = factory.FastPgProductJob(transactionContext, cmd.ProductJobId)
if cmd.JobName != productJob.JobName {
checkDuplicateJobName = true
}
if workStation.WorkStationId != productJob.WorkStation.WorkStationId {
checkDuplicateJobName = true
}
if err := productJob.Update(tool_funs.SimpleStructToMap(updateProductJobCommand)); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
if checkDuplicateJobName {
if job, err := productJobRepository.FindOne(map[string]interface{}{
"jobName": cmd.JobName,
"companyId": productJob.CompanyId,
"orgId": productJob.OrgId,
"workStationId": workStation.WorkStationId,
}); err == nil && job != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "有重复的工位")
}
}
productJob.WorkStation = workStation
productJob.JobName = cmd.JobName
productJob.RelatedDevices = cmd.RelatedDevices
productJob.UpdatedAt = time.Now()
if productJob, err := productJobRepository.Save(productJob); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
... ... @@ -212,6 +235,46 @@ func (productJobService *ProductJobService) UpdateProductJob(updateProductJobCom
}
}
// 搜索工位服务列表
func (productJobService *ProductJobService) SearchProductJob(operateInfo *domain.OperateInfo, listProductJobQuery *query.SearchProductJobQuery) (int64, interface{}, error) {
listProductJobQuery.OrgId = operateInfo.OrgId
listProductJobQuery.CompanyId = operateInfo.CompanyId
if err := listProductJobQuery.ValidateQuery(); err != nil {
return 0, nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var productJobRepository domain.ProductJobRepository
if value, err := factory.CreateProductJobRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
productJobRepository = value
}
count, productJobs, err := productJobRepository.Find(utils.ObjectToMap(listProductJobQuery))
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var result = make([]*dto.ProductJobDto, 0)
for i := range productJobs {
item := productJobs[i]
newJobDto := &dto.ProductJobDto{}
newJobDto.LoadDto(item)
result = append(result, newJobDto)
}
return count, result, nil
}
func NewProductJobService(options map[string]interface{}) *ProductJobService {
newProductJobService := &ProductJobService{}
return newProductJobService
... ...
... ... @@ -133,8 +133,8 @@ func (productSectionService *ProductSectionService) ListProductSection(listProdu
}
// 移除工段服务
func (productSectionService *ProductSectionService) RemoveProductSection(removeProductSectionCommand *command.RemoveProductSectionCommand) (interface{}, error) {
if err := removeProductSectionCommand.ValidateCommand(); err != nil {
func (productSectionService *ProductSectionService) RemoveProductSection(cmd *command.RemoveProductSectionCommand) (interface{}, error) {
if err := cmd.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
... ... @@ -149,13 +149,25 @@ func (productSectionService *ProductSectionService) RemoveProductSection(removeP
}()
var workshopRepository domain.WorkshopRepository
var workshop *domain.Workshop
workshopRepository, workshop, err = factory.FastPgWorkshop(transactionContext, removeProductSectionCommand.WorkshopId)
workshopRepository, workshop, err = factory.FastPgWorkshop(transactionContext, cmd.WorkshopId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err = workshop.RemoveSection(removeProductSectionCommand.LineId, removeProductSectionCommand.SectionId); err != nil {
workStation, err := workshop.FindWorkStation(workshop.WorkshopId, cmd.LineId, cmd.SectionId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var productJobRepository domain.ProductJobRepository
productJobRepository, _, _ = factory.FastPgProductJob(transactionContext, 0)
if count, _, err := productJobRepository.Find(map[string]interface{}{"workStationId": workStation.WorkStationId, "limit": 1}); err == nil && count > 0 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "该工段下存在工位")
}
if err = workshop.RemoveSection(cmd.LineId, cmd.SectionId); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if workshop, err = workshopRepository.Save(workshop); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
... ...
... ... @@ -70,3 +70,11 @@ func (info OperateInfo) GetUserId(userId int) int {
func (info OperateInfo) String() string {
return fmt.Sprintf("UserId: %v OrgId:%v CompanyId:%v", info.UserId, info.OrgId, info.CompanyId)
}
func Pagination(pageNumber, pageSize int) (offset int, limit int) {
if pageSize != 0 {
offset = (pageNumber - 1) * pageSize
limit = pageSize
}
return
}
... ...
... ... @@ -12,6 +12,8 @@ type ProductJob struct {
OrgId int `json:"orgId,omitempty"`
// 工位名称
JobName string `json:"jobName,omitempty"`
// 工序名称
ProcessName string `json:"processName,omitempty"`
// 创建时间
CreatedAt time.Time `json:"createdAt,omitempty"`
// 更新时间
... ... @@ -39,50 +41,12 @@ func (productJob *ProductJob) Identify() interface{} {
}
func (productJob *ProductJob) Update(data map[string]interface{}) error {
if productJobId, ok := data["productJobId"]; ok {
productJob.ProductJobId = productJobId.(int)
}
if companyId, ok := data["companyId"]; ok {
productJob.CompanyId = companyId.(int)
}
if orgId, ok := data["orgId"]; ok {
productJob.OrgId = orgId.(int)
}
if jobName, ok := data["jobName"]; ok {
productJob.JobName = jobName.(string)
}
if createdAt, ok := data["createdAt"]; ok {
productJob.CreatedAt = createdAt.(time.Time)
}
if updatedAt, ok := data["updatedAt"]; ok {
productJob.UpdatedAt = updatedAt.(time.Time)
}
if deletedAt, ok := data["deletedAt"]; ok {
productJob.DeletedAt = deletedAt.(time.Time)
}
if workStationId, ok := data["workStationId"]; ok {
productJob.WorkStation.WorkStationId = workStationId.(string)
}
if workshopId, ok := data["workshopId"]; ok {
productJob.WorkStation.WorkshopId = workshopId.(int)
}
if workshopName, ok := data["workshopName"]; ok {
productJob.WorkStation.WorkshopName = workshopName.(string)
}
if lineId, ok := data["lineId"]; ok {
productJob.WorkStation.LineId = lineId.(int)
}
if lineName, ok := data["lineName"]; ok {
productJob.WorkStation.LineName = lineName.(string)
}
if sectionId, ok := data["sectionId"]; ok {
productJob.WorkStation.SectionId = sectionId.(int)
}
if sectionName, ok := data["sectionName"]; ok {
productJob.WorkStation.SectionName = sectionName.(string)
if relatedDevices, ok := data["relatedDevices"]; ok {
productJob.RelatedDevices = relatedDevices.([]int)
}
//if relatedDevices, ok := data["relatedDevices"]; ok {
// productJob.RelatedDevices = relatedDevices.(array)
//}
productJob.UpdatedAt = time.Now()
return nil
}
... ...
package domain
import "fmt"
// 工作位置(车间、生产线、工段组成),唯一标识工作位置
type WorkStation struct {
// 工作位置键值 (车间ID+'.'+生产线ID+'.'+工段ID)
... ... @@ -16,4 +18,18 @@ type WorkStation struct {
SectionId int `json:"sectionId,omitempty"`
// 工段名称
SectionName string `json:"sectionName,omitempty"`
// 负责人 (用户对象)
Principal *User `json:"principal,omitempty"`
}
func NewWorkStation(w *Workshop, l *ProductLine, s *ProductSection) *WorkStation {
return &WorkStation{
WorkStationId: fmt.Sprintf("%v.%v.%v", w.WorkshopId, l.LineId, s.SectionId),
WorkshopId: w.WorkshopId,
WorkshopName: w.WorkshopName,
LineId: l.LineId,
LineName: l.LineName,
SectionId: s.SectionId,
SectionName: s.SectionName,
}
}
... ...
... ... @@ -187,3 +187,19 @@ func (workshop *Workshop) FindSection(lineId, sectionId int) (*ProductSection, e
}
return nil, fmt.Errorf("工段不存在")
}
// 查询生产线
func (workshop *Workshop) FindWorkStation(workshopId, lineId, sectionId int) (*WorkStation, error) {
if workshop.WorkshopId != workshopId {
return nil, fmt.Errorf("不存在")
}
line, err := workshop.FindLine(lineId)
if err != nil {
return nil, err
}
section, err := workshop.FindSection(lineId, sectionId)
if err != nil {
return nil, err
}
return NewWorkStation(workshop, line, section), nil
}
... ...
... ... @@ -20,9 +20,11 @@ type ProductJob struct {
// 更新时间
UpdatedAt time.Time `comment:"更新时间"`
// 删除时间
DeletedAt time.Time `comment:"删除时间"`
DeletedAt time.Time `pg:",soft_delete" comment:"删除时间"`
// 工作位置
WorkStation *domain.WorkStation `comment:"工作位置"`
// 关联设备列表
RelatedDevices []int `pg:",soft_delete" comment:"关联设备列表" pg:",array"`
RelatedDevices []int ` comment:"关联设备列表"`
// 工序名称
ProcessName string ` comment:"工序名称"`
}
... ...
... ... @@ -16,5 +16,6 @@ func TransformToProductJobDomainModelFromPgModels(productJobModel *models.Produc
DeletedAt: productJobModel.DeletedAt,
WorkStation: productJobModel.WorkStation,
RelatedDevices: productJobModel.RelatedDevices,
ProcessName: productJobModel.ProcessName,
}, nil
}
... ...
... ... @@ -35,20 +35,15 @@ func (repository *ProductJobRepository) Save(productJob *domain.ProductJob) (*do
"deleted_at",
"work_station",
"related_devices",
"process_name",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_job_id", "deleted_at"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_job_id", "deleted_at"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "productJob_id")
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "product_job_id", "deleted_at")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if productJob.Identify() == nil {
productJobId, err := repository.nextIdentify()
if err != nil {
return productJob, err
} else {
productJob.ProductJobId = int(productJobId)
}
if _, err := tx.QueryOne(
pg.Scan(
&productJob.ProductJobId,
... ... @@ -59,18 +54,18 @@ func (repository *ProductJobRepository) Save(productJob *domain.ProductJob) (*do
&productJob.UpdatedAt,
&productJob.DeletedAt,
&productJob.WorkStation,
pg.Array(&productJob.RelatedDevices),
&productJob.RelatedDevices,
&productJob.ProcessName,
),
fmt.Sprintf("INSERT INTO product_jobs (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
productJob.ProductJobId,
fmt.Sprintf("INSERT INTO manufacture.product_job (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
productJob.CompanyId,
productJob.OrgId,
productJob.JobName,
productJob.CreatedAt,
productJob.UpdatedAt,
productJob.DeletedAt,
productJob.WorkStation,
pg.Array(productJob.RelatedDevices),
productJob.RelatedDevices,
productJob.ProcessName,
); err != nil {
return productJob, err
}
... ... @@ -85,18 +80,18 @@ func (repository *ProductJobRepository) Save(productJob *domain.ProductJob) (*do
&productJob.UpdatedAt,
&productJob.DeletedAt,
&productJob.WorkStation,
pg.Array(&productJob.RelatedDevices),
&productJob.RelatedDevices,
&productJob.ProcessName,
),
fmt.Sprintf("UPDATE product_jobs SET %s WHERE product_job_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
productJob.ProductJobId,
fmt.Sprintf("UPDATE manufacture.product_job SET %s WHERE product_job_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
productJob.CompanyId,
productJob.OrgId,
productJob.JobName,
productJob.CreatedAt,
productJob.UpdatedAt,
productJob.DeletedAt,
productJob.WorkStation,
pg.Array(productJob.RelatedDevices),
productJob.RelatedDevices,
productJob.ProcessName,
productJob.Identify(),
); err != nil {
return productJob, err
... ... @@ -118,6 +113,10 @@ func (repository *ProductJobRepository) FindOne(queryOptions map[string]interfac
productJobModel := new(models.ProductJob)
query := sqlbuilder.BuildQuery(tx.Model(productJobModel), queryOptions)
query.SetWhereByQueryOption("product_job.product_job_id = ?", "productJobId")
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("org_id = ?", "orgId")
query.SetWhereByQueryOption("job_name=?", "jobName")
query.SetWhereByQueryOption("work_station->>'workStationId'=?", "workStationId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
... ... @@ -136,7 +135,23 @@ func (repository *ProductJobRepository) Find(queryOptions map[string]interface{}
var productJobModels []*models.ProductJob
productJobs := make([]*domain.ProductJob, 0)
query := sqlbuilder.BuildQuery(tx.Model(&productJobModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("org_id = ?", "orgId")
query.SetWhereByQueryOption("work_station->>'workStationId'=?", "workStationId")
if v, ok := queryOptions["jobName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`job_name like '%%%v%%'`, v))
}
if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`work_station->>'workshopName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["lineName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`work_station->>'lineName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["sectionName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`work_station->>'sectionName' like '%%%v%%'`, v))
}
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetOrderDirect("product_job_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, productJobs, err
... ...
package utils
import (
"bytes"
"encoding/json"
"fmt"
jsonlib "github.com/linmadan/egglib-go/utils/json"
"io"
"reflect"
"strconv"
"strings"
"time"
)
func CamelCase(name string, firstUpper bool) string {
array := []byte(name)
if len(array) == 0 {
return ""
}
rspArray := make([]byte, len(array))
if firstUpper {
copy(rspArray[:1], strings.ToUpper(string(array[:1])))
} else {
copy(rspArray[:1], strings.ToLower(string(array[:1])))
}
copy(rspArray[1:], array[1:])
return string(rspArray)
}
func ObjectToMap(o interface{}) map[string]interface{} {
if o == nil {
return nil
}
value := reflect.ValueOf(o)
if value.Kind() != reflect.Ptr {
return nil
}
elem := value.Elem()
relType := elem.Type()
m := make(map[string]interface{})
for i := 0; i < relType.NumField(); i++ {
field := relType.Field(i)
if elem.Field(i).IsZero() {
continue
}
m[CamelCase(field.Name, false)] = elem.Field(i).Interface()
}
return m
}
// AssertString convert v to string value
func AssertString(v interface{}) string {
if v == nil {
return ""
}
// if func (v *Type) String() string, we can't use Elem()
switch vt := v.(type) {
case fmt.Stringer:
return vt.String()
}
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr && !val.IsNil() {
val = val.Elem()
}
switch vt := val.Interface().(type) {
case bool:
return strconv.FormatBool(vt)
case error:
return vt.Error()
case float32:
return strconv.FormatFloat(float64(vt), 'f', -1, 32)
case float64:
return strconv.FormatFloat(vt, 'f', -1, 64)
case fmt.Stringer:
return vt.String()
case int:
return strconv.Itoa(vt)
case int8:
return strconv.Itoa(int(vt))
case int16:
return strconv.Itoa(int(vt))
case int32:
return strconv.Itoa(int(vt))
case int64:
return strconv.FormatInt(vt, 10)
case string:
return vt
case uint:
return strconv.FormatUint(uint64(vt), 10)
case uint8:
return strconv.FormatUint(uint64(vt), 10)
case uint16:
return strconv.FormatUint(uint64(vt), 10)
case uint32:
return strconv.FormatUint(uint64(vt), 10)
case uint64:
return strconv.FormatUint(vt, 10)
case []byte:
return string(vt)
default:
return fmt.Sprint(val.Interface())
}
}
// ValidatePtr validate v is a ptr value
func ValidatePtr(v *reflect.Value) error {
// sequence is very important, IsNil must be called after checking Kind() with reflect.Ptr,
// panic otherwise
if !v.IsValid() || v.Kind() != reflect.Ptr || v.IsNil() {
return fmt.Errorf("not a valid pointer: %v", v)
}
return nil
}
func LoadCustomFieldToMap(src interface{}, fields ...string) map[string]interface{} {
rsp := LoadCustomField(src, fields...)
if rsp == nil {
return map[string]interface{}{}
}
return rsp.(map[string]interface{})
}
func LoadCustomField(src interface{}, fields ...string) interface{} {
typeSrc := reflect.TypeOf(src)
valueSrc := reflect.ValueOf(src)
if v, ok := src.(reflect.Value); ok {
valueSrc = v
typeSrc = v.Type()
}
if typeSrc.Kind() == reflect.Ptr {
valueSrc = valueSrc.Elem()
}
k := valueSrc.Kind()
switch k {
case reflect.Array, reflect.Slice:
len := valueSrc.Len()
retSliceMap := make([]map[string]interface{}, 0)
if len == 0 {
return retSliceMap
}
for i := 0; i < len; i++ {
v := valueSrc.Index(i)
retSliceMap = append(retSliceMap, (LoadCustomField(v, fields...)).(map[string]interface{}))
}
return retSliceMap
case reflect.Struct:
retSliceMap := make(map[string]interface{})
for _, filed := range fields {
f := valueSrc.FieldByName(filed)
if !f.IsValid() {
continue
}
v := f.Interface()
if t, ok := v.(time.Time); ok {
v = t.Local().Format("2006-01-02 15:04:05")
}
retSliceMap[CamelCase(filed, false)] = v
}
return retSliceMap
default:
return src
}
return src
}
func AppendCustomField(src interface{}, options map[string]interface{}) interface{} {
var mapSrc map[string]interface{}
var ok bool
mapSrc, ok = src.(map[string]interface{})
if !ok {
jsonlib.Unmarshal([]byte(jsonlib.MarshalToString(src)), &mapSrc)
}
for field, value := range options {
mapSrc[CamelCase(field, false)] = value
}
return mapSrc
}
/*
json 格式化
*/
func Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func Unmarshal(data []byte, v interface{}) error {
decoder := json.NewDecoder(bytes.NewReader(data))
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(string(data), err)
}
return nil
}
func UnmarshalFromString(str string, v interface{}) error {
decoder := json.NewDecoder(strings.NewReader(str))
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(str, err)
}
return nil
}
func UnmarshalFromReader(reader io.Reader, v interface{}) error {
var buf strings.Builder
teeReader := io.TeeReader(reader, &buf)
decoder := json.NewDecoder(teeReader)
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(buf.String(), err)
}
return nil
}
func unmarshalUseNumber(decoder *json.Decoder, v interface{}) error {
decoder.UseNumber()
return decoder.Decode(v)
}
func formatError(v string, err error) error {
return fmt.Errorf("string: `%s`, error: `%s`", v, err.Error())
}
type ReflectVal struct {
T reflect.Type
V reflect.Value
}
/*
拷贝当前对象到目标对象,具有相同属性的值
*/
func CopyObject(src, dst interface{}) {
var srcMap = make(map[string]ReflectVal)
vs := reflect.ValueOf(src)
ts := reflect.TypeOf(src)
vd := reflect.ValueOf(dst)
td := reflect.TypeOf(dst)
ls := vs.Elem().NumField()
for i := 0; i < ls; i++ {
srcMap[ts.Elem().Field(i).Name] = ReflectVal{
T: vs.Elem().Field(i).Type(),
V: vs.Elem().Field(i),
}
}
ld := vd.Elem().NumField()
for i := 0; i < ld; i++ {
n := td.Elem().Field(i).Name
t := vd.Elem().Field(i).Type()
if v, ok := srcMap[n]; ok && v.T == t && vd.Elem().Field(i).CanSet() {
vd.Elem().Field(i).Set(v.V)
}
}
}
... ...
... ... @@ -10,22 +10,22 @@ import (
"strconv"
)
func ResponseGrid(c beego.BaseController, data interface{}, err error) {
func ResponseGrid(c beego.BaseController, total int64, data interface{}, err error) {
var response utils.JsonResponse
if err != nil {
response = utils.ResponseError(c.Ctx, err)
} else {
response = ResponseGridData(c.Ctx, data)
response = ResponseGridData(c.Ctx, total, data)
}
c.Data["json"] = response
c.ServeJSON()
}
func ResponseGridData(ctx *context.Context, data interface{}) utils.JsonResponse {
func ResponseGridData(ctx *context.Context, total int64, data interface{}) utils.JsonResponse {
jsonResponse := utils.JsonResponse{}
jsonResponse["code"] = 0
jsonResponse["msg"] = "ok"
jsonResponse["data"] = map[string]interface{}{"grid": data}
jsonResponse["data"] = map[string]interface{}{"total": total, "grid": data}
ctx.Input.SetData("outputData", jsonResponse)
return jsonResponse
}
... ... @@ -42,6 +42,13 @@ func ParseOperateInfo(c beego.BaseController) *domain.OperateInfo {
opt.UserId = header(c, constant.HeaderUserId)
opt.CompanyId = header(c, constant.HeaderCompanyId)
opt.OrgId = header(c, constant.HeaderOrgId)
// 默认公司组织
if opt.CompanyId == 0 {
opt.CompanyId = 1
}
if opt.OrgId == 0 {
opt.OrgId = 1
}
return opt
}
... ...
... ... @@ -15,7 +15,7 @@ func (controller *ProductJobController) CreateProductJob() {
productJobService := service.NewProductJobService(nil)
createProductJobCommand := &command.CreateProductJobCommand{}
controller.Unmarshal(createProductJobCommand)
data, err := productJobService.CreateProductJob(createProductJobCommand)
data, err := productJobService.CreateProductJob(ParseOperateInfo(controller.BaseController), createProductJobCommand)
controller.Response(data, err)
}
... ... @@ -58,3 +58,11 @@ func (controller *ProductJobController) ListProductJob() {
data, err := productJobService.ListProductJob(listProductJobQuery)
controller.Response(data, err)
}
func (controller *ProductJobController) SearchProductJob() {
productJobService := service.NewProductJobService(nil)
listProductJobQuery := &query.SearchProductJobQuery{}
controller.Unmarshal(listProductJobQuery)
total, data, err := productJobService.SearchProductJob(ParseOperateInfo(controller.BaseController), listProductJobQuery)
ResponseGrid(controller.BaseController, total, data, err)
}
... ...
... ... @@ -11,4 +11,5 @@ func init() {
web.Router("/product-jobs/:productJobId", &controllers.ProductJobController{}, "Get:GetProductJob")
web.Router("/product-jobs/:productJobId", &controllers.ProductJobController{}, "Delete:RemoveProductJob")
web.Router("/product-jobs/", &controllers.ProductJobController{}, "Get:ListProductJob")
web.Router("/product-jobs/search", &controllers.ProductJobController{}, "Post:SearchProductJob")
}
... ...