作者 yangfu

refactor: 代码优化

- 历史生产记录查询修改
- 定时初始化车间生产记录
@@ -37,6 +37,9 @@ func (crontabService *CrontabService) initTask() { @@ -37,6 +37,9 @@ func (crontabService *CrontabService) initTask() {
37 }) 37 })
38 task.AddTask("PullPrdMoK3cloud", PullPrdMoK3cloud) 38 task.AddTask("PullPrdMoK3cloud", PullPrdMoK3cloud)
39 39
  40 + autoInitWorkshopProductRecord := task.NewTask("AutoInitWorkshopProductRecord", "0 0 */4 * * *", AutoInitWorkshopProductRecord)
  41 + task.AddTask("AutoInitWorkshopProductRecord", autoInitWorkshopProductRecord)
  42 +
40 autoApproveAttendanceRecord := task.NewTask("autoApproveAttendanceRecord", "0 */2 * * * *", AutoApproveProductAttendanceRecord) 43 autoApproveAttendanceRecord := task.NewTask("autoApproveAttendanceRecord", "0 */2 * * * *", AutoApproveProductAttendanceRecord)
41 task.AddTask("autoApproveAttendanceRecord", autoApproveAttendanceRecord) 44 task.AddTask("autoApproveAttendanceRecord", autoApproveAttendanceRecord)
42 45
  1 +package crontab
  2 +
  3 +import (
  4 + "context"
  5 + "fmt"
  6 + "github.com/linmadan/egglib-go/transaction/pg"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
  8 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  9 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  10 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
  11 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
  12 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
  13 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  14 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
  15 + "time"
  16 +)
  17 +
  18 +// AutoInitWorkshopProductRecord 自动初始化车间生产记录
  19 +func AutoInitWorkshopProductRecord(ctx context.Context) error {
  20 + defer func() {
  21 + if r := recover(); r != nil {
  22 + log.Logger.Error(fmt.Sprintf("%v", r), map[string]interface{}{"task": "自动初始化车间生产记录"})
  23 + }
  24 + }()
  25 + transactionContext, err := factory.CreateTransactionContext(nil)
  26 + if err != nil {
  27 + return err
  28 + }
  29 + if err := transactionContext.StartTransaction(); err != nil {
  30 + return err
  31 + }
  32 + defer func() {
  33 + if err != nil {
  34 + log.Logger.Error("【自动初始化车间生产记录】 失败:" + err.Error())
  35 + }
  36 + transactionContext.RollbackTransaction()
  37 + }()
  38 + log.Logger.Debug("【自动初始化车间生产记录】 启动")
  39 + _, workshop, err := factory.FastPgWorkshop(transactionContext, constant.MANUFACTURE_DEFAULT_WORKSHOPID)
  40 + if err != nil {
  41 + return err
  42 + }
  43 + productPlanDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(transactionContext.(*pg.TransactionContext))
  44 + productPlans, err := productPlanDispatchRecordDao.ProductPlans(constant.MANUFACTURE_DEFAULT_COMPANYID,
  45 + constant.MANUFACTURE_DEFAULT_ORGID,
  46 + constant.MANUFACTURE_DEFAULT_WORKSHOPID,
  47 + utils.GetZeroTimeWithLocal(time.Now(), time.UTC), "")
  48 + if err != nil {
  49 + return err
  50 + }
  51 + if len(productPlans) == 0 {
  52 + log.Logger.Debug("【自动初始化车间生产记录】 当天执行计划为空")
  53 + return nil
  54 + }
  55 + workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(transactionContext.(*pg.TransactionContext))
  56 + workshopProductRecordRepository, _ := repository.NewWorkshopProductRecordRepository(transactionContext.(*pg.TransactionContext))
  57 + lines := workshop.GetProductLines(domain.NotDeleted)
  58 + for _, line := range lines {
  59 + for _, section := range line.ProductSections {
  60 + if !(section.SectionName == domain.ProductSection1 || section.SectionName == domain.ProductSection2) {
  61 + continue
  62 + }
  63 + if section.Removed == domain.Deleted {
  64 + continue
  65 + }
  66 + workstation := domain.NewWorkStation(workshop, line, section)
  67 + cid := constant.MANUFACTURE_DEFAULT_COMPANYID
  68 + oid := constant.MANUFACTURE_DEFAULT_ORGID
  69 + for _, plan := range productPlans {
  70 + var workshopProductRecord *domain.WorkshopProductRecord
  71 + workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, workstation.WorkStationId, plan.ProductPlanId, time.Now())
  72 + if err == domain.ErrorNotFound {
  73 + workshopProductRecord = domainService.NewWorkshopProductRecord(&domain.ProductRecord{
  74 + CompanyId: constant.MANUFACTURE_DEFAULT_COMPANYID,
  75 + OrgId: constant.MANUFACTURE_DEFAULT_ORGID,
  76 + WorkStation: workstation,
  77 + CreatedAt: time.Now(),
  78 + ProductRecordInfo: &domain.ProductRecordInfo{
  79 + ProductPlanId: plan.ProductPlanId,
  80 + PlanProductName: plan.PlanProductName,
  81 + BatchNumber: plan.BatchNumber,
  82 + },
  83 + }, plan)
  84 + if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
  85 + return err
  86 + }
  87 + log.Logger.Debug(fmt.Sprintf("【自动初始化车间生产记录】 工位:%v(%v) 初始产能:%v kg 日期:%v ID:%v",
  88 + workshopProductRecord.WorkStation.WorkStationId, workshopProductRecord.WorkStation.SectionName,
  89 + workshopProductRecord.ProductWeigh, workshopProductRecord.ProductRecordInfo.ProductDate, workshopProductRecord.WorkshopProductRecordId))
  90 + continue
  91 + }
  92 + if err != nil {
  93 + log.Logger.Error(err.Error())
  94 + return nil
  95 + }
  96 + }
  97 + }
  98 + }
  99 + if err = transactionContext.CommitTransaction(); err != nil {
  100 + return err
  101 + }
  102 + return nil
  103 +}
@@ -5,11 +5,13 @@ import ( @@ -5,11 +5,13 @@ import (
5 "github.com/linmadan/egglib-go/core/application" 5 "github.com/linmadan/egglib-go/core/application"
6 "github.com/linmadan/egglib-go/transaction/pg" 6 "github.com/linmadan/egglib-go/transaction/pg"
7 "github.com/linmadan/egglib-go/utils/tool_funs" 7 "github.com/linmadan/egglib-go/utils/tool_funs"
  8 + "github.com/linmadan/egglib-go/utils/xtime"
8 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory" 9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
9 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/command" 10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/command"
10 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/dto" 11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/dto"
11 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/query" 12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/productPlan/query"
12 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 13 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
  14 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
13 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService" 15 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/domainService"
14 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis" 16 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
15 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 17 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
@@ -514,6 +516,26 @@ func (productPlanService *ProductPlanService) ReturnMaterial(returnMaterialComma @@ -514,6 +516,26 @@ func (productPlanService *ProductPlanService) ReturnMaterial(returnMaterialComma
514 516
515 productRecordService, _ := domainService.NewPGProductRecordService(transactionContext.(*pg.TransactionContext)) 517 productRecordService, _ := domainService.NewPGProductRecordService(transactionContext.(*pg.TransactionContext))
516 518
  519 + productRecordDao, _ := dao.NewProductRecordDao(transactionContext.(*pg.TransactionContext))
  520 + begin := xtime.BeginningOfDay()
  521 + end := time.Now()
  522 + workstationId := domain.WorkstationKey(returnMaterialCommand.WorkshopId, returnMaterialCommand.LineId, returnMaterialCommand.SectionId)
  523 + totalReceive, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReceiveMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
  524 + if err != nil {
  525 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  526 + }
  527 + totalReturn, err := productRecordDao.ProductWeightStatics(returnMaterialCommand.CompanyId, returnMaterialCommand.OrgId, domain.RecordTypeReturnMaterial, returnMaterialCommand.ProductPlanId, workstationId, begin, end)
  528 + if err != nil {
  529 + return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
  530 + }
  531 + allowReturn := totalReceive - totalReturn
  532 + if totalReturn+returnMaterialCommand.Weigh > totalReceive {
  533 + if allowReturn > 0 {
  534 + return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料,当前只允许退料 %v kg", totalReceive-totalReturn))
  535 + }
  536 + return nil, application.ThrowError(application.BUSINESS_ERROR, fmt.Sprintf("当天累计退料大于累计领料"))
  537 + }
  538 +
517 _, err = productRecordService.SubmitProductRecord(domain.RecordTypeReturnMaterial, tool_funs.SimpleStructToMap(returnMaterialCommand)) 539 _, err = productRecordService.SubmitProductRecord(domain.RecordTypeReturnMaterial, tool_funs.SimpleStructToMap(returnMaterialCommand))
518 if err != nil { 540 if err != nil {
519 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error()) 541 return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
@@ -4,6 +4,7 @@ import ( @@ -4,6 +4,7 @@ import (
4 "github.com/linmadan/egglib-go/utils/xtime" 4 "github.com/linmadan/egglib-go/utils/xtime"
5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain" 5 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
6 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils" 6 "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
  7 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
7 ) 8 )
8 9
9 // HistoryProductRecord 历史生成记录 10 // HistoryProductRecord 历史生成记录
@@ -29,13 +30,16 @@ type HistoryProductRecord struct { @@ -29,13 +30,16 @@ type HistoryProductRecord struct {
29 func (d *HistoryProductRecord) LoadDto(m *domain.ProductRecord) *HistoryProductRecord { 30 func (d *HistoryProductRecord) LoadDto(m *domain.ProductRecord) *HistoryProductRecord {
30 d.ProductRecordId = m.ProductRecordId 31 d.ProductRecordId = m.ProductRecordId
31 d.ProductWorker = m.ProductWorker 32 d.ProductWorker = m.ProductWorker
32 - d.Weight = utils.Round(m.ProductRecordInfo.WeighBefore, 1) 33 + d.Weight = utils.Round(m.ProductRecordInfo.Original, 1)
33 d.Status = m.ProductRecordInfo.ApproveStatus 34 d.Status = m.ProductRecordInfo.ApproveStatus
34 d.PlanProductName = m.ProductRecordInfo.PlanProductName 35 d.PlanProductName = m.ProductRecordInfo.PlanProductName
35 d.BatchNumber = m.ProductRecordInfo.BatchNumber 36 d.BatchNumber = m.ProductRecordInfo.BatchNumber
36 d.CreatedAt = m.CreatedAt.Local().Format("2006-01-02 15:04:05") 37 d.CreatedAt = m.CreatedAt.Local().Format("2006-01-02 15:04:05")
37 d.ProductRecordType = m.ProductRecordType 38 d.ProductRecordType = m.ProductRecordType
38 - if m.ProductRecordType != domain.RecordTypeSecondLevelWeigh && m.ProductRecordInfo.ApproveStatus == domain.ProductRecordNotApprove && !xtime.BeginningOfDay().Equal(xtime.New(m.CreatedAt).BeginningOfDay()) { 39 + if m.ProductRecordType != domain.RecordTypeSecondLevelWeigh &&
  40 + m.ProductRecordInfo.ApproveStatus == domain.ProductRecordNotApprove &&
  41 + !(xtime.BeginningOfDay().Equal(xtime.New(m.CreatedAt.Local()).BeginningOfDay())) {
  42 + log.Logger.Debug("not equal", map[string]interface{}{"t1": xtime.BeginningOfDay(), "t2": xtime.New(m.CreatedAt.Local()).BeginningOfDay()})
39 d.Status = domain.ProductRecordLogged 43 d.Status = domain.ProductRecordLogged
40 } 44 }
41 return d 45 return d
@@ -27,12 +27,12 @@ type HistoryProductRecordQuery struct { @@ -27,12 +27,12 @@ type HistoryProductRecordQuery struct {
27 PageNumber int `cname:"页码" json:"pageNumber,omitempty"` 27 PageNumber int `cname:"页码" json:"pageNumber,omitempty"`
28 // 页数 28 // 页数
29 PageSize int `cname:"页数" json:"pageSize,omitempty"` 29 PageSize int `cname:"页数" json:"pageSize,omitempty"`
30 - // 车间名称  
31 - //WorkshopName string `cname:"车间名称" json:"workshopName"`  
32 - // 批号  
33 - //BatchNumber string `cname:"批号" json:"batchNumber"`  
34 - // 姓名  
35 - //UserName string `cname:"姓名" json:"userName"` 30 + // 车间ID
  31 + WorkshopId int `cname:"车间ID" json: workshopId,omitempty"`
  32 + // 生产线ID
  33 + LineId int `cname:"生产线ID" json:"lineId,omitempty"`
  34 + // 工段ID
  35 + SectionId int `json:"sectionId,omitempty"`
36 // 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重 36 // 生产记录类型:1:领料 2:退料 4:称重 8:二级品称重
37 ProductRecordType int `cname:"生产记录类型:1:领料 2:退料 4:称重 8:二级品称重" json:"productRecordType"` 37 ProductRecordType int `cname:"生产记录类型:1:领料 2:退料 4:称重 8:二级品称重" json:"productRecordType"`
38 // 生产线名称 38 // 生产线名称
@@ -92,11 +92,19 @@ func (cmd *HistoryProductRecordQuery) Valid(validation *validation.Validation) { @@ -92,11 +92,19 @@ func (cmd *HistoryProductRecordQuery) Valid(validation *validation.Validation) {
92 cmd.ProductBeginTime = t 92 cmd.ProductBeginTime = t
93 cmd.ProductEndTime = t.AddDate(0, 0, 1) 93 cmd.ProductEndTime = t.AddDate(0, 0, 1)
94 } 94 }
95 - if cmd.Status == domain.ProductRecordLogged { 95 + if cmd.Status == domain.ProductRecordNotApprove {
  96 + cmd.Status = domain.ProductRecordNotApprove
  97 + if xtime.IsZero(cmd.ProductBeginTime) || xtime.BeforeEqual(cmd.ProductBeginTime, xtime.BeginningOfDay()) {
  98 + cmd.ProductBeginTime = xtime.BeginningOfDay()
  99 + }
  100 + } else if cmd.Status == domain.ProductRecordLogged {
96 cmd.Status = domain.ProductRecordNotApprove 101 cmd.Status = domain.ProductRecordNotApprove
97 if len(cmd.Date) == 0 && xtime.IsZero(cmd.ProductEndTime) { 102 if len(cmd.Date) == 0 && xtime.IsZero(cmd.ProductEndTime) {
98 cmd.ProductEndTime = xtime.BeginningOfDay() 103 cmd.ProductEndTime = xtime.BeginningOfDay()
99 } 104 }
  105 + if len(cmd.Date) > 0 && !xtime.BeforeEqual(cmd.ProductEndTime, xtime.BeginningOfDay()) {
  106 + cmd.Status = domain.ProductRecordLogged
  107 + }
100 } 108 }
101 } 109 }
102 110
@@ -14,6 +14,7 @@ var HTTP_PORT int = 8081 @@ -14,6 +14,7 @@ var HTTP_PORT int = 8081
14 var CACHE_PREFIX = "allied-creation-manufacture-dev" 14 var CACHE_PREFIX = "allied-creation-manufacture-dev"
15 var LOG_LEVEL = "debug" 15 var LOG_LEVEL = "debug"
16 var LOG_FILE = "app.log" 16 var LOG_FILE = "app.log"
  17 +var PPROF_ON = true
17 18
18 //天联共创基础模块 19 //天联共创基础模块
19 var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com" 20 var ALLIED_CREATION_BASIC_HOST = "http://localhost:8080" //"http://allied-creation-basic-dev.fjmaimaimai.com"
@@ -45,5 +46,6 @@ func init() { @@ -45,5 +46,6 @@ func init() {
45 SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV) 46 SERVICE_ENV = Configurator.DefaultString("SERVICE_ENV", SERVICE_ENV)
46 HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT) 47 HTTP_PORT = Configurator.DefaultInt("HTTP_PORT", HTTP_PORT)
47 SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV) 48 SERVICE_NAME = fmt.Sprintf("%v-%v", SERVICE_NAME, SERVICE_ENV)
  49 + PPROF_ON = Configurator.DefaultBool("PPROF_ON", PPROF_ON)
48 CACHE_PREFIX = SERVICE_NAME 50 CACHE_PREFIX = SERVICE_NAME
49 } 51 }
@@ -80,7 +80,9 @@ func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTimeBefore(pr @@ -80,7 +80,9 @@ func (productAttendanceRecord *ProductAttendanceRecord) ComputeWorkTimeBefore(pr
80 if !productAttendanceRecord.SignOut.After(productAttendanceRecord.SignIn) { 80 if !productAttendanceRecord.SignOut.After(productAttendanceRecord.SignIn) {
81 return 0 81 return 0
82 } 82 }
83 - wt := utils.Round(productAttendanceRecord.SignOut.Sub(productAttendanceRecord.SignIn).Hours(), 2) 83 + signIn := roundTime(productAttendanceRecord.SignIn)
  84 + signOut := roundTime(productAttendanceRecord.SignOut)
  85 + wt := utils.Round(signOut.Sub(signIn).Hours(), 2)
84 if productCalendar == nil { 86 if productCalendar == nil {
85 return roundWorkTime(wt) 87 return roundWorkTime(wt)
86 } 88 }
@@ -108,6 +110,20 @@ func roundWorkTime(wt float64) float64 { @@ -108,6 +110,20 @@ func roundWorkTime(wt float64) float64 {
108 return i 110 return i
109 } 111 }
110 112
  113 +func roundTime(t time.Time) time.Time {
  114 + hour, min, _ := t.Local().Clock()
  115 + y, m, d := t.Local().Date()
  116 + newTime := time.Date(y, m, d, hour, 0, 0, 0, time.Local)
  117 + if min < 11 {
  118 + min = 0
  119 + } else if min >= 11 && min < 41 {
  120 + min = 30
  121 + } else {
  122 + min = 60
  123 + }
  124 + return newTime.Add(time.Minute * time.Duration(min))
  125 +}
  126 +
111 func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductCalendar(productCalendar *ProductCalendar) error { 127 func (productAttendanceRecord *ProductAttendanceRecord) SetProductTimeByProductCalendar(productCalendar *ProductCalendar) error {
112 now := xtime.New(productAttendanceRecord.SignIn) 128 now := xtime.New(productAttendanceRecord.SignIn)
113 productAttendanceRecord.ProductDate = now.BeginningOfDay() 129 productAttendanceRecord.ProductDate = now.BeginningOfDay()
@@ -11,7 +11,7 @@ const ( @@ -11,7 +11,7 @@ const (
11 ) 11 )
12 12
13 const ( 13 const (
14 - ProductSection1 = "打料" 14 + ProductSection1 = "制模"
15 ProductSection2 = "成型" 15 ProductSection2 = "成型"
16 ProductSection3 = "穿串" 16 ProductSection3 = "穿串"
17 ProductSection4 = "包装" 17 ProductSection4 = "包装"
@@ -29,7 +29,7 @@ func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionC @@ -29,7 +29,7 @@ func NewProductPlanDispatchRecord(transactionContext *pgTransaction.TransactionC
29 // 日期 29 // 日期
30 // 产品编号 30 // 产品编号
31 // 调度状态 status 31 // 调度状态 status
32 -func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) { 32 +func (dao *ProductPlanDispatchRecordDao) ProductPlanDispatchRecord(companyId, orgId int, workStationId string, date time.Time, productCode string, status int) (*domain.ProductPlanDispatchRecord, error) {
33 tx := dao.transactionContext.PgTx 33 tx := dao.transactionContext.PgTx
34 productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord) 34 productPlanDispatchRecordModel := new(models.ProductPlanDispatchRecord)
35 query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{}) 35 query := sqlbuilder.BuildQuery(tx.Model(productPlanDispatchRecordModel), map[string]interface{}{})
@@ -37,7 +37,9 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, @@ -37,7 +37,9 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
37 query.Where("org_id = ?", orgId) 37 query.Where("org_id = ?", orgId)
38 query.Where("work_station->>'workStationId'=?", workStationId) 38 query.Where("work_station->>'workStationId'=?", workStationId)
39 query.Where("product_date = ?", date) 39 query.Where("product_date = ?", date)
  40 + if status > 0 {
40 query.Where("plan_dispatch_status = ?", status) 41 query.Where("plan_dispatch_status = ?", status)
  42 + }
41 query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode) 43 query.Where("plan_dispatch_record_ext->>'productCode'=?", productCode)
42 query.Order("updated_at desc") 44 query.Order("updated_at desc")
43 if err := query.First(); err != nil { 45 if err := query.First(); err != nil {
@@ -53,3 +55,57 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int, @@ -53,3 +55,57 @@ func (dao *ProductPlanDispatchRecordDao) DeviceProductPlan(companyId, orgId int,
53 return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel) 55 return transform.TransformToProductPlanDispatchRecordDomainModelFromPgModels(productPlanDispatchRecordModel)
54 } 56 }
55 } 57 }
  58 +
  59 +func (dao *ProductPlanDispatchRecordDao) ProductPlan(companyId, orgId int, workshopId int, date time.Time, productCode string) (*domain.ProductPlan, error) {
  60 + tx := dao.transactionContext.PgTx
  61 + productPlan := new(models.ProductPlan)
  62 + query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
  63 + query.Where("company_id = ?", companyId)
  64 + query.Where("org_id = ?", orgId)
  65 + query.Where("workshop->>'workshopId'='?'", workshopId)
  66 + query.Where("product_date = ?", date)
  67 + if len(productCode) > 0 {
  68 + query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
  69 + }
  70 + query.Order("updated_at desc")
  71 + if err := query.First(); err != nil {
  72 + if err.Error() == "pg: no rows in result set" {
  73 + return nil, domain.ErrorNotFound
  74 + } else {
  75 + return nil, err
  76 + }
  77 + }
  78 + if productPlan.ProductPlanId == 0 {
  79 + return nil, nil
  80 + } else {
  81 + return transform.TransformToProductPlanDomainModelFromPgModels(productPlan)
  82 + }
  83 +}
  84 +
  85 +func (dao *ProductPlanDispatchRecordDao) ProductPlans(companyId, orgId int, workshopId int, date time.Time, productCode string) ([]*domain.ProductPlan, error) {
  86 + tx := dao.transactionContext.PgTx
  87 + productPlan := new(models.ProductPlan)
  88 + query := sqlbuilder.BuildQuery(tx.Model(productPlan), map[string]interface{}{})
  89 + query.Where("company_id = ?", companyId)
  90 + query.Where("org_id = ?", orgId)
  91 + query.Where("workshop->>'workshopId'='?'", workshopId)
  92 + query.Where("product_date = ?", date)
  93 + if len(productCode) > 0 {
  94 + query.Where("ext #>>'{productPlanExt,productCode}'=?", productCode)
  95 + }
  96 + query.Order("updated_at desc")
  97 + var productPlanModels = make([]*models.ProductPlan, 0)
  98 + var productPlans = make([]*domain.ProductPlan, 0)
  99 + if err := query.Select(&productPlanModels); err != nil {
  100 + return productPlans, err
  101 + } else {
  102 + for _, productPlanModel := range productPlanModels {
  103 + if productPlan, err := transform.TransformToProductPlanDomainModelFromPgModels(productPlanModel); err != nil {
  104 + return productPlans, err
  105 + } else {
  106 + productPlans = append(productPlans, productPlan)
  107 + }
  108 + }
  109 + return productPlans, nil
  110 + }
  111 +}
@@ -117,7 +117,7 @@ select sum(a.weight) item_total,max(sname) sname from ( @@ -117,7 +117,7 @@ select sum(a.weight) item_total,max(sname) sname from (
117 and product_record_info->>'approveStatus'='2' 117 and product_record_info->>'approveStatus'='2'
118 and created_at >=? 118 and created_at >=?
119 and created_at <? 119 and created_at <?
120 - and work_station->>'sectionName' in ('打料','成型','穿串','包装') 120 + and work_station->>'sectionName' in ('制模','成型','穿串','包装')
121 ) a 121 ) a
122 group by a.workStationId 122 group by a.workStationId
123 ) 123 )
@@ -127,10 +127,31 @@ select sname,round(item_total/(select sum(item_total) from item_product)*100, 0) @@ -127,10 +127,31 @@ select sname,round(item_total/(select sum(item_total) from item_product)*100, 0)
127 ) 127 )
128 --select * from item_product_rate 128 --select * from item_product_rate
129 select a.sname, coalesce(b.rate,0) rate from ( 129 select a.sname, coalesce(b.rate,0) rate from (
130 - select unnest(ARRAY ['打料','成型','穿串','包装']) sname 130 + select unnest(ARRAY ['制模','成型','穿串','包装']) sname
131 ) a left join item_product_rate b on a.sname=b.sname`) 131 ) a left join item_product_rate b on a.sname=b.sname`)
132 if _, err := tx.Query(result, sql, companyId, orgId, workshopId, beginTime, endTime); err != nil { 132 if _, err := tx.Query(result, sql, companyId, orgId, workshopId, beginTime, endTime); err != nil {
133 return err 133 return err
134 } 134 }
135 return nil 135 return nil
136 } 136 }
  137 +
  138 +// ProductWeightStatics 产能统计
  139 +func (dao *ProductRecordDao) ProductWeightStatics(companyId, orgId, productRecordType, productPlanId int, workstationId string, beginTime time.Time, endTime time.Time) (float64, error) {
  140 +
  141 + tx := dao.transactionContext.PgTx
  142 + var result = struct {
  143 + Total float64
  144 + }{}
  145 + sql := fmt.Sprintf(`
  146 +select coalesce(sum(cast(product_record_info->>'original' as DECIMAL)),0) total
  147 +from manufacture.product_records
  148 +where company_id = ? and org_id = ? and product_record_type = ?
  149 +and work_station->>'workStationId' = ?
  150 +and product_record_info->>'productPlanId' = '?'
  151 +and created_at >= ? and created_at < ?
  152 +`)
  153 + if _, err := tx.QueryOne(&result, sql, companyId, orgId, productRecordType, workstationId, productPlanId, beginTime, endTime); err != nil {
  154 + return 0, err
  155 + }
  156 + return result.Total, nil
  157 +}
@@ -11,7 +11,7 @@ import ( @@ -11,7 +11,7 @@ import (
11 ) 11 )
12 12
13 const ( 13 const (
14 - ProductSection1 = "打料" 14 + ProductSection1 = "制模" //打料更新为制模
15 ProductSection2 = "成型" 15 ProductSection2 = "成型"
16 ProductSection3 = "穿串" 16 ProductSection3 = "穿串"
17 ProductSection4 = "包装" 17 ProductSection4 = "包装"
@@ -298,7 +298,7 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain. @@ -298,7 +298,7 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
298 workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(ptr.transactionContext) 298 workshopProductRecordDao, _ := dao.NewWorkshopProductRecordDao(ptr.transactionContext)
299 workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, productRecord.WorkStation.WorkStationId, planId, productRecord.CreatedAt) 299 workshopProductRecord, err = workshopProductRecordDao.WorkshopProductRecord(cid, oid, productRecord.WorkStation.WorkStationId, planId, productRecord.CreatedAt)
300 if err == domain.ErrorNotFound { 300 if err == domain.ErrorNotFound {
301 - workshopProductRecord = newWorkshopProductRecord(productRecord, productPlan) 301 + workshopProductRecord = NewWorkshopProductRecord(productRecord, productPlan)
302 } else { 302 } else {
303 if err != nil { 303 if err != nil {
304 log.Logger.Error(err.Error()) 304 log.Logger.Error(err.Error())
@@ -310,9 +310,9 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain. @@ -310,9 +310,9 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
310 workshopProductRecord.ProductWeigh, productRecord.ProductRecordInfo.Weigh, productRecord.ProductRecordInfo.Original)) 310 workshopProductRecord.ProductWeigh, productRecord.ProductRecordInfo.Weigh, productRecord.ProductRecordInfo.Original))
311 workshopProductRecord.UpdateProductWeigh(productRecord) 311 workshopProductRecord.UpdateProductWeigh(productRecord)
312 // 打料 跟 成型工段的初始产能是批次的产能 312 // 打料 跟 成型工段的初始产能是批次的产能
313 - if productRecord.WorkStation.SectionName == ProductSection1 && productRecord.WorkStation.SectionName == ProductSection2 {  
314 - workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)  
315 - } 313 + //if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
  314 + // workshopProductRecord.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
  315 + //}
316 316
317 if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil { 317 if workshopProductRecord, err = workshopProductRecordRepository.Save(workshopProductRecord); err != nil {
318 // TODO:异常处理 318 // TODO:异常处理
@@ -321,8 +321,8 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain. @@ -321,8 +321,8 @@ func (ptr *PGProductRecordService) WorkshopProductStatics(productRecord *domain.
321 return nil, nil 321 return nil, nil
322 } 322 }
323 323
324 -// newEmployeeProductRecord 员工生产记录  
325 -func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord { 324 +// NewWorkshopProductRecord 车间生产记录
  325 +func NewWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *domain.ProductPlan) *domain.WorkshopProductRecord {
326 record := &domain.WorkshopProductRecord{ 326 record := &domain.WorkshopProductRecord{
327 CompanyId: productRecord.CompanyId, 327 CompanyId: productRecord.CompanyId,
328 OrgId: productRecord.OrgId, 328 OrgId: productRecord.OrgId,
@@ -347,7 +347,7 @@ func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan * @@ -347,7 +347,7 @@ func newWorkshopProductRecord(productRecord *domain.ProductRecord, productPlan *
347 } 347 }
348 // 打料、成型有初始值 348 // 打料、成型有初始值
349 if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 { 349 if productRecord.WorkStation.SectionName == ProductSection1 || productRecord.WorkStation.SectionName == ProductSection2 {
350 - record.ProductWeigh = productPlan.PlanDevoted.Weight 350 + record.AddPlanProductWeight(productPlan.PlanDevoted.Weight, productPlan.ProductPlanId)
351 } 351 }
352 return record 352 return record
353 } 353 }
@@ -78,7 +78,7 @@ func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *d @@ -78,7 +78,7 @@ func (ptr *PGWorkshopDataConsumeService) Consume(companyId, orgId int, record *d
78 // 封箱机、串串机需要定位到批次 78 // 封箱机、串串机需要定位到批次
79 if record.DeviceType == domain.DeviceTypeChuanChuanJi { //record.DeviceType == domain.DeviceTypeFengXiangJi || 79 if record.DeviceType == domain.DeviceTypeChuanChuanJi { //record.DeviceType == domain.DeviceTypeFengXiangJi ||
80 datetime, _ := time.ParseInLocation("2006-01-02", deviceRunningData.Date, time.Local) 80 datetime, _ := time.ParseInLocation("2006-01-02", deviceRunningData.Date, time.Local)
81 - if plan, err = ptr.findDeviceProductPlan(companyId, orgId, workStation.WorkStationId, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil { 81 + if plan, err = ptr.findProductPlanAndActive(companyId, orgId, workStation, utils.GetZeroTimeWithLocal(datetime, time.UTC), deviceRunningData.ProductType); err != nil {
82 log.Logger.Error(err.Error(), map[string]interface{}{"workstation": workStation, "product_code": deviceRunningData.ProductType}) 82 log.Logger.Error(err.Error(), map[string]interface{}{"workstation": workStation, "product_code": deviceRunningData.ProductType})
83 } else { 83 } else {
84 planId = plan.PlanDispatchRecordExt.ProductPlanId 84 planId = plan.PlanDispatchRecordExt.ProductPlanId
@@ -326,20 +326,29 @@ func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId, @@ -326,20 +326,29 @@ func (ptr *PGWorkshopDataConsumeService) saveDeviceDailyRunningRecord(companyId,
326 } 326 }
327 327
328 // 查找设备的生产计划,如果计划没有上线的话将他上线 328 // 查找设备的生产计划,如果计划没有上线的话将他上线
329 -func (ptr *PGWorkshopDataConsumeService) findDeviceProductPlan(companyId, orgId int, workStationId string, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) { 329 +func (ptr *PGWorkshopDataConsumeService) findProductPlanAndActive(companyId, orgId int, workStation *domain.WorkStation, date time.Time, productCode string) (*domain.ProductPlanDispatchRecord, error) {
330 planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext) 330 planDispatchRecordDao, _ := dao.NewProductPlanDispatchRecord(ptr.transactionContext)
331 planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext) 331 planDispatchRecordRepository, _ := repository.NewProductPlanDispatchRecordRepository(ptr.transactionContext)
332 - var setPlanOnline = false  
333 - record, err := planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOnline) 332 + record, err := planDispatchRecordDao.ProductPlanDispatchRecord(companyId, orgId, workStation.WorkStationId, date, productCode, 0)
  333 + // 未找到当前工段的调度计划,从计划管理查询是否有匹配记录,如果有在调度计划中上线
  334 + var productPlan *domain.ProductPlan
334 if err == domain.ErrorNotFound { 335 if err == domain.ErrorNotFound {
335 - if record, err = planDispatchRecordDao.DeviceProductPlan(companyId, orgId, workStationId, date, productCode, domain.PlanOffline); err != nil { 336 + if productPlan, err = planDispatchRecordDao.ProductPlan(companyId, orgId, workStation.WorkshopId, date, productCode); err == nil && productPlan != nil {
  337 + var productPlanDispatch = domain.NewProductPlanDispatchRecord(productPlan, workStation)
  338 + if productPlanDispatch, err = planDispatchRecordRepository.Save(productPlanDispatch); err != nil {
  339 + return nil, err
  340 + }
  341 + return productPlanDispatch, nil
  342 + }
336 return nil, err 343 return nil, err
337 - } else {  
338 - setPlanOnline = true  
339 } 344 }
  345 + if err != nil {
  346 + return nil, err
  347 + }
  348 + if record != nil && record.PlanDispatchStatus == domain.PlanOffline {
  349 + if err = record.ChangeStatus(domain.PlanOnline); err != nil {
  350 + return nil, err
340 } 351 }
341 - if setPlanOnline {  
342 - record.ChangeStatus(domain.PlanOnline)  
343 if record, err = planDispatchRecordRepository.Save(record); err != nil { 352 if record, err = planDispatchRecordRepository.Save(record); err != nil {
344 return nil, err 353 return nil, err
345 } 354 }
@@ -147,12 +147,18 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac @@ -147,12 +147,18 @@ func (repository *ProductRecordRepository) Find(queryOptions map[string]interfac
147 query.SetWhereByQueryOption("company_id = ?", "companyId") 147 query.SetWhereByQueryOption("company_id = ?", "companyId")
148 query.SetWhereByQueryOption("org_id = ?", "orgId") 148 query.SetWhereByQueryOption("org_id = ?", "orgId")
149 query.SetWhereByQueryOption("product_record_type & ? >0", "productRecordType") 149 query.SetWhereByQueryOption("product_record_type & ? >0", "productRecordType")
  150 + query.SetWhereByQueryOption("work_station->>'workshopId'='?'", "workshopId")
  151 + query.SetWhereByQueryOption("work_station->>'lineId'='?'", "lineId")
  152 + query.SetWhereByQueryOption("work_station->>'sectionId'='?'", "sectionId")
150 if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int)) > 0 { 153 if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int)) > 0 {
151 query.Where(`org_id in (?)`, pg.In(v)) 154 query.Where(`org_id in (?)`, pg.In(v))
152 } 155 }
153 if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 { 156 if v, ok := queryOptions["userName"]; ok && len(v.(string)) > 0 {
154 query.Where(fmt.Sprintf(`product_worker->>'userName' like '%%%v%%'`, v)) 157 query.Where(fmt.Sprintf(`product_worker->>'userName' like '%%%v%%'`, v))
155 } 158 }
  159 + if v, ok := queryOptions["productWorkerId"]; ok && v.(int) > 0 {
  160 + query.Where(`product_worker->>'userId' = '?'`, v)
  161 + }
156 if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 { 162 if v, ok := queryOptions["workshopName"]; ok && len(v.(string)) > 0 {
157 query.Where(fmt.Sprintf(`work_station->>'workshopName' like '%%%v%%'`, v)) 163 query.Where(fmt.Sprintf(`work_station->>'workshopName' like '%%%v%%'`, v))
158 } 164 }
@@ -3,6 +3,9 @@ package beego @@ -3,6 +3,9 @@ package beego
3 import ( 3 import (
4 "github.com/beego/beego/v2/server/web" 4 "github.com/beego/beego/v2/server/web"
5 "github.com/linmadan/egglib-go/web/beego/filters" 5 "github.com/linmadan/egglib-go/web/beego/filters"
  6 + "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
  7 + "net/http"
  8 + "net/http/pprof"
6 "os" 9 "os"
7 "strconv" 10 "strconv"
8 11
@@ -39,6 +42,22 @@ func init() { @@ -39,6 +42,22 @@ func init() {
39 web.BConfig.Listen.HTTPSPort = port 42 web.BConfig.Listen.HTTPSPort = port
40 } 43 }
41 } 44 }
  45 +
  46 + if constant.PPROF_ON {
  47 + web.Handler("/debug/pprof/", http.HandlerFunc(pprof.Index))
  48 + web.Handler("/debug/cmdline", http.HandlerFunc(pprof.Cmdline))
  49 + web.Handler("/debug/profile", http.HandlerFunc(pprof.Profile))
  50 + web.Handler("/debug/symbol", http.HandlerFunc(pprof.Symbol))
  51 + web.Handler("/debug/trace", http.HandlerFunc(pprof.Trace))
  52 +
  53 + web.Handler("/debug/allocs", pprof.Handler("allocs"))
  54 + web.Handler("/debug/block", pprof.Handler("block"))
  55 + web.Handler("/debug/goroutine", pprof.Handler("goroutine"))
  56 + web.Handler("/debug/heap", pprof.Handler("heap"))
  57 + web.Handler("/debug/mutex", pprof.Handler("mutex"))
  58 + web.Handler("/debug/threadcreate", pprof.Handler("threadcreate"))
  59 + }
  60 +
42 web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt" 61 web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt"
43 web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key" 62 web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key"
44 web.InsertFilter("/*", web.BeforeExec, filters.AllowCors()) 63 web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
@@ -154,6 +154,8 @@ func (controller *StatisticsController) TaskHandler() func(ctx *context.Context) @@ -154,6 +154,8 @@ func (controller *StatisticsController) TaskHandler() func(ctx *context.Context)
154 Response(ctx, nil, err) 154 Response(ctx, nil, err)
155 return 155 return
156 } 156 }
  157 + case "13":
  158 + crontab.AutoInitWorkshopProductRecord(nil)
157 } 159 }
158 Response(ctx, nil, nil) 160 Response(ctx, nil, nil)
159 } 161 }