作者 yangfu

refactor:1.代码优化

... ... @@ -43,11 +43,14 @@ func (crontabService *CrontabService) initTask() {
autoApproveRecord := task.NewTask("autoApproveRecord", "0 */2 * * * *", AutoApproveProductRecord)
task.AddTask("autoApproveRecord", autoApproveRecord)
autoFlushDeviceDailyRunningRecord := task.NewTask("autoFlushDeviceDailyRunningRecord", "0 */1 * * * *", AutoFlushDeviceDailyRunningRecord)
autoFlushDeviceDailyRunningRecord := task.NewTask("定时刷新设备每日运行记录", "0 */1 * * * *", AutoFlushDeviceDailyRunningRecord)
task.AddTask("autoFlushDeviceDailyRunningRecord", autoFlushDeviceDailyRunningRecord)
autoWorkshopPlanCompletionRecord := task.NewTask("autoFlushDeviceDailyRunningRecord", "0 1 1-10/3 * * *", AutoWorkshopPlanCompletionRecord)
autoWorkshopPlanCompletionRecord := task.NewTask("定时刷新昨日车间计划完成纪录", "0 5 1-15/3 * * *", AutoWorkshopPlanCompletionRecord)
task.AddTask("autoWorkshopPlanCompletionRecord", autoWorkshopPlanCompletionRecord)
autoTodayWorkshopPlanCompletionRecord := task.NewTask("定时刷新当天车间计划完成纪录", "0 0 1-23/3 * * *", AutoTodayWorkshopPlanCompletionRecord) // 1:00, 4:00, 每三个小时运行一次
task.AddTask("autoTodayWorkshopPlanCompletionRecord", autoTodayWorkshopPlanCompletionRecord)
}
func (crontabService *CrontabService) StartCrontabTask() {
... ...
package crontab
import (
"context"
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
"time"
)
// 定时刷新设备每日运行记录
func AutoFlushDeviceDailyRunningRecordOEE(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r))
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【定时刷新设备每日运行记录-OEE】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【定时刷新设备每日运行记录-OEE】 启动")
deviceDailyRunningRecordRepository, _, _ := factory.FastPgDeviceDailyRunningRecord(transactionContext, 0)
// 获取redis里当天的记录
span := time.Duration(20)
t := time.Now().Add(-time.Minute * span)
records, err := redis.GetDeviceDailyAllRecord(t)
if err != nil {
log.Logger.Error(err.Error())
return err
}
for _, v := range records {
//if v.UpdatedAt.Add(time.Minute * 5).Before(time.Now()) {
// log.Logger.Debug(fmt.Sprintf("【定时刷新设备每日运行记录-OEE】 跳过记录 %v 最后更新时间:%v", v, v.UpdatedAt))
// continue
//}
// 更新设备效率 OEE = tu * pu * qu
/*
pu 性能利用
设备标准工时,
没有配置设备标准工时的为100
*/
//pu :=100
//if v.DeviceRunningRecordInfo
// 设备数据(标准工时)
// 工段对应二级品数据
v.DeviceRunningRecordInfo.ResetOEE(0, 0)
if _, err := deviceDailyRunningRecordRepository.Save(v); err != nil {
log.Logger.Error(err.Error())
continue
} else {
log.Logger.Debug(fmt.Sprintf("【定时刷新设备每日运行记录-OEE】 刷新记录 %v", v))
}
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
... ... @@ -27,12 +27,12 @@ func AutoWorkshopPlanCompletionRecord(ctx context.Context) error {
}
defer func() {
if err != nil {
log.Logger.Error("【定时刷新备每日运行记录】 失败:" + err.Error())
log.Logger.Error("【定时刷新车间计划备每日运行记录】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【定时刷新设备每日运行记录】 启动")
log.Logger.Debug("【定时刷新车间计划每日运行记录】 启动")
end := utils.GetZeroTime(time.Now())
begin := utils.GetZeroTime(end.Add(-time.Second))
approveAttendanceRecordsService, _ := domainService.NewPGWorkshopPlanCompletionRecordService(transactionContext.(*pgTransaction.TransactionContext))
... ... @@ -46,3 +46,39 @@ func AutoWorkshopPlanCompletionRecord(ctx context.Context) error {
}
return nil
}
// 定时刷新当天车间计划完成纪录
func AutoTodayWorkshopPlanCompletionRecord(ctx context.Context) error {
defer func() {
if r := recover(); r != nil {
log.Logger.Error(fmt.Sprintf("%v", r))
}
}()
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return err
}
if err := transactionContext.StartTransaction(); err != nil {
return err
}
defer func() {
if err != nil {
log.Logger.Error("【定时刷新车间计划今日运行记录】 失败:" + err.Error())
}
transactionContext.RollbackTransaction()
}()
log.Logger.Debug("【定时刷新车间计划今日运行记录】 启动")
begin := utils.GetZeroTime(time.Now())
end := time.Now()
approveAttendanceRecordsService, _ := domainService.NewPGWorkshopPlanCompletionRecordService(transactionContext.(*pgTransaction.TransactionContext))
if err = approveAttendanceRecordsService.WorkshopPlanCompletion(begin, end); err != nil {
return err
}
if err = transactionContext.CommitTransaction(); err != nil {
return err
}
return nil
}
... ...
... ... @@ -28,6 +28,8 @@ type SearchDeviceQuery struct {
DeviceName string `json:"deviceName,omitempty"`
// 设备状态 1:正常 2:封存 3:报废
DeviceStatus int `json:"deviceStatus,omitempty"`
// 排除的设备列表
IncludeDevices []int `cname:"排除的设备列表" json:"includeDevices"`
}
func (cmd *SearchDeviceQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -363,6 +363,67 @@ func (deviceService *DeviceService) SearchDevice(operateInfo *domain.OperateInfo
return count, result, nil
}
// 返回设备服务列表
func (deviceService *DeviceService) SelectorDeviceUnbounded(operateInfo *domain.OperateInfo, listDeviceQuery *query.SearchDeviceQuery) (int64, interface{}, error) {
if err := listDeviceQuery.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()
}()
deviceRepository, _, _ := factory.FastPgDevice(transactionContext, 0)
count, devices, err := deviceRepository.Find(utils.ObjectToMap(listDeviceQuery))
if err != nil {
return 0, nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
workshops, _ := factory.FastPgWorkshops(transactionContext, operateInfo.CompanyId)
productJobRepository, _, _ := factory.FastPgProductJob(transactionContext, 0)
_, productJobs, _ := productJobRepository.Find(map[string]interface{}{"companyId": listDeviceQuery.CompanyId})
var excludeMap = make(map[int]int)
var allBoundedDevice = make([]int, 0)
for i := range productJobs {
allBoundedDevice = append(allBoundedDevice, productJobs[i].RelatedDevices...)
}
for _, v := range allBoundedDevice {
exclude := false
for _, j := range listDeviceQuery.IncludeDevices {
if j == v {
exclude = true
}
}
if exclude {
continue
}
excludeMap[v] = v
}
var result = make([]*dto.DeviceDto, 0)
for i := range devices {
item := devices[i]
newJobDto := &dto.DeviceDto{}
if _, ok := excludeMap[item.DeviceId]; ok {
continue
}
if item.WorkStation != nil && item.WorkStation.WorkshopId > 0 {
newJobDto.WorkStation = workshops.FindWorkStationOrNil(item.WorkStation.WorkshopId, item.WorkStation.LineId, item.WorkStation.SectionId)
}
newJobDto.LoadDto(item, operateInfo.OrgId)
result = append(result, newJobDto)
}
if err := transactionContext.CommitTransaction(); err != nil {
return 0, nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return count, result, nil
}
// 批量添加产品服务
func (deviceService *DeviceService) BatchAddProduct(opt *domain.OperateInfo, list []*domain.ImportDeviceItem) ([]interface{}, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
... ...
... ... @@ -20,7 +20,7 @@ type UpdateProductCalendarCommand struct {
// 上班班次 1:全天 2:白班 4:中班 8:夜班
WorkOn int `cname:"上班班次 1:全天 2:白班 4:中班 8:夜班" json:"workOn" valid:"Required"`
// 日历选择
CalendarSelected []string `cname:"日历选择" json:"calendarSelected" valid:"Required"`
CalendarSelected []int `cname:"日历选择" json:"calendarSelected" valid:"Required"`
// 上岗时间
InWorkAt string `cname:"上岗时间" json:"inWorkAt" valid:"Required"`
// 下岗时间
... ...
... ... @@ -23,9 +23,9 @@ type ProductCalendarDto struct {
// 下岗时间
OutWorkAt string `json:"outWorkAt,omitempty"`
// 休息时间 (单位 h)
BreakTime float64 `json:"breakTime,omitempty"`
BreakTime float64 `json:"breakTime"`
// 工时 (单位 h)
WorkTime float64 `json:"workTime,omitempty"`
WorkTime float64 `json:"workTime"`
// 已选择日历
//CalendarSelectedString string `json:"calendarSelectedString,omitempty"`
// 组织名称
... ...
... ... @@ -302,7 +302,7 @@ func (productCalendarService *ProductCalendarService) UpdateProductCalendar(cmd
productCalendar.WorkStation = workStation
productCalendar.WorkOn = cmd.WorkOn
productCalendar.CalendarSelected = cmd.CalendarSelected
productCalendar.CalendarSelected = utils.ToArrayString(cmd.CalendarSelected)
productCalendar.InWorkAt = cmd.InWorkAt
productCalendar.OutWorkAt = cmd.OutWorkAt
productCalendar.BreakTime = cmd.BreakTime
... ...
... ... @@ -57,7 +57,11 @@ func (productLineService *ProductLineService) CreateProductLine(createProductLin
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return createProductLineCommand, nil
return map[string]interface{}{
"lineId": newProductLine.LineId,
"lineName": newProductLine.LineName,
"workshopId": createProductLineCommand.WorkshopId,
}, nil
}
// 返回生产线
... ...
... ... @@ -55,7 +55,12 @@ func (productSectionService *ProductSectionService) CreateProductSection(createP
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return newProductSection, nil
return map[string]interface{}{
"workshopId": workshop.WorkshopId,
"lineId": createProductSectionCommand.LineId,
"sectionId": newProductSection.SectionId,
"sectionName": newProductSection.SectionName,
}, nil
}
// 返回工段服务
... ...
... ... @@ -57,7 +57,7 @@ func (workshopService *WorkshopService) CreateWorkshop(operateInfo *domain.Opera
if item, err := workshopRepository.FindOne(map[string]interface{}{
"workshopName": createWorkshopCommand.WorkshopName,
"companyId": operateInfo.CompanyId,
"orgId": operateInfo.OrgId,
//"orgId": operateInfo.OrgId,
}); err == nil && item != nil && strings.EqualFold(item.WorkshopName, createWorkshopCommand.WorkshopName) {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "车间名称已存在")
}
... ...
... ... @@ -35,6 +35,10 @@ var (
DeviceTypeMianBaoXieJi = "MBXJ"
// 油炸机
DeviceTypeYouZhaJi = "YZJ"
// 油炸机
DeviceTypeYouZhaJi1 = "YZJ1"
// 油炸机
DeviceTypeYouZhaJi2 = "YZJ2"
// 串串机
DeviceTypeChuanChuanJi = "CCJ"
// 速冻线
... ...
... ... @@ -17,6 +17,13 @@ type DeviceYouZhaJi struct {
TubeTemp float64 `json:"TubeTemp"` // 管路温度:管路当前温度
}
// 油炸机2
type DeviceYouZhaJi2 struct {
Temp1 float64 `json:"Temp1"` // 温度1当前温度
Temp2 float64 `json:"Temp2"` // 温度2当前温度
Temp3 float64 `json:"Temp3"` // 温度3当前温度
}
// 串串机
type DeviceChuanChuanJi struct {
Count int64 `json:"Count"` // 生产计数:生产统计数量
... ...
... ... @@ -79,7 +79,7 @@ type DeviceRunningRecordInfo struct {
// 1. 当前设备实际产出数量/理论数量(理论数量=60*60*12/标准工时)
// 2. 没有数量100%
PerformanceUtilization float64 `json:"pu"`
// 合格率 QualificationUtilization ?设备提交的二级品事串 、 机器上报的是kg
// 合格率 QualificationUtilization 设备提交的二级品是kg 、 机器上报的是串
// 1.按工段的合格率
// 2.默认100%
QualificationUtilization float64 `json:"qu"`
... ... @@ -87,8 +87,10 @@ type DeviceRunningRecordInfo struct {
UpTime float64 `json:"upTime"`
// 生成数量
Count int `json:"count"`
// 设备温度 单位:摄氏度
Temp float64 `json:"temp"`
// 设备温度 单位:摄氏度 (前端温度、温度1)
Temp1 float64 `json:"temp"`
// 设备温度 单位:摄氏度 (后断温度、温度2)
Temp2 float64 `json:"temp1"`
// 时间点
//TimeLine []string `json:"timeLine"`
... ... @@ -103,6 +105,10 @@ type DeviceRunningRecordInfo struct {
DeviceName string `json:"deviceName"`
// 组织名称
OrgName string `json:"orgName"`
// 额外数据
// 单位数据 比如:1串/0.1kg weight = count * unitQuantity
UnitQuantity float64 `json:"unitQuantity"`
}
func NewDeviceRunningRecordInfo() *DeviceRunningRecordInfo {
... ... @@ -116,7 +122,8 @@ func (d *DeviceRunningRecordInfo) AddDeviceRunningData(t time.Time, data *Device
d.Count += data.Count
//d.Temp = data.FrontTemp
d.Temp = data.Temp1
d.Temp1 = data.Temp1
d.Temp2 = data.Temp2
d.AddTimeLineDeviceStatus(t, data)
//d.OEE
... ...
... ... @@ -28,6 +28,8 @@ type DeviceRunningData struct {
//FrontTemp float64 `json:"frontTemp"`
// 炸机前段温度:炸机前段当前温度 YZJ2 油炸机
Temp1 float64 `json:"temp1"`
// 炸机前段温度:炸机前段当前温度 YZJ2 油炸机
Temp2 float64 `json:"temp2"`
// 当前产品种类(产品编号)
ProductType string `json:"productType"`
// 日期
... ...
... ... @@ -79,6 +79,14 @@ func (dao *WorkshopPlanCompletionRecordDao) Save(record *models.WorkshopPlanComp
return nil
}
func (dao *WorkshopPlanCompletionRecordDao) Update(record *models.WorkshopPlanCompletionRecord) error {
tx := dao.transactionContext.PgTx
if _, err := tx.Model(record).WherePK().Update(); err != nil {
return err
}
return nil
}
func NewWorkshopPlanCompletionRecordDao(transactionContext *pgTransaction.TransactionContext) (*WorkshopPlanCompletionRecordDao, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
... ...
... ... @@ -152,6 +152,17 @@ func (ptr *PGWorkshopDataConsumeService) newDeviceRunningData(record *domain.Dev
break
}
data.Temp1 = deviceYouZhaJi.FrontTemp
data.Temp2 = deviceYouZhaJi.BackTemp
break
//油炸机
case domain.DeviceTypeYouZhaJi2:
deviceYouZhaJi := &domain.DeviceYouZhaJi2{}
err = json.Unmarshal(mBytes, deviceYouZhaJi)
if err != nil {
break
}
data.Temp1 = deviceYouZhaJi.Temp1
data.Temp2 = deviceYouZhaJi.Temp2
break
//串串机
case domain.DeviceTypeChuanChuanJi:
... ...
... ... @@ -77,6 +77,13 @@ func (ptr *PGWorkshopPlanCompletionRecordService) WorkshopPlanCompletion(begin t
if err := workshopProductRecordDao.Save(record); err != nil {
return err
}
} else if record != nil {
record.Plan = totalPlan
record.Real = totalReal
record.Rate = completionRate
if err := workshopProductRecordDao.Update(record); err != nil {
return err
}
}
}
... ...
... ... @@ -164,7 +164,7 @@ func (repository *DeviceRepository) Find(queryOptions map[string]interface{}) (i
var deviceModels []*models.Device
devices := make([]*domain.Device, 0)
query := sqlbuilder.BuildQuery(tx.Model(&deviceModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOffsetAndLimit(domain.MaxQueryRow)
query.SetOrderDirect("device_id", "DESC")
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("org_id = ?", "orgId")
... ...
... ... @@ -109,7 +109,7 @@ func (repository *DeviceRunningRecordRepository) FindOne(queryOptions map[string
query.SetWhereByQueryOption("device_running_record.device_running_record_id = ?", "deviceRunningRecordId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
return nil, domain.ErrorNotFound
} else {
return nil, err
}
... ...
... ... @@ -174,7 +174,7 @@ func (repository *ProductPlanRepository) Find(queryOptions map[string]interface{
query := sqlbuilder.BuildQuery(tx.Model(&productPlanModels), queryOptions)
query.SetWhereByQueryOption("company_id = ?", "companyId")
query.SetWhereByQueryOption("org_id = ?", "orgId")
query.SetWhereByQueryOption("work_station->>'workshopId'='?'", "workshopId")
query.SetWhereByQueryOption("workshop->>'workshopId'='?'", "workshopId")
if v, ok := queryOptions["batchNumber"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`batch_number like '%%%v%%'`, v))
}
... ...
... ... @@ -29,6 +29,10 @@ func init() {
//https支持
web.BConfig.Listen.EnableHTTPS = true
web.BConfig.Listen.HTTPSPort = 443
//进程内监控
web.BConfig.Listen.EnableAdmin = true
web.BConfig.Listen.AdminPort = 8088
if os.Getenv("HTTPS_PORT") != "" {
portStr := os.Getenv("HTTPS_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
... ...
... ... @@ -80,6 +80,18 @@ func (controller *DeviceController) SearchDevice() {
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *DeviceController) SelectorDeviceUnbounded() {
deviceService := service.NewDeviceService(nil)
cmd := &query.SearchDeviceQuery{}
Must(controller.Unmarshal(cmd))
operateInfo := ParseOperateInfo(controller.BaseController)
//cmd.OrgId = operateInfo.OrgId
cmd.CompanyId = operateInfo.CompanyId
cmd.InOrgIds = operateInfo.OrgIds
total, data, err := deviceService.SelectorDeviceUnbounded(ParseOperateInfo(controller.BaseController), cmd)
ResponseGrid(controller.BaseController, total, data, err)
}
func (controller *DeviceController) BatchAddDevice() {
productService := service.NewDeviceService(nil)
cmd := &struct {
... ...
... ... @@ -13,11 +13,12 @@ func init() {
web.Router("/devices/batch-remove", &controllers.DeviceController{}, "Post:BatchRemoveDevice")
web.Router("/devices/", &controllers.DeviceController{}, "Get:ListDevice")
web.Router("/devices/search", &controllers.DeviceController{}, "Post:SearchDevice")
web.Router("/devices/search-unbounded", &controllers.DeviceController{}, "Post:SelectorDeviceUnbounded")
web.Router("/devices/batch-add", &controllers.DeviceController{}, "Post:BatchAddDevice")
//考勤机
web.Router("/zkteco/iclock/cdata", &controllers.DeviceZKTecoController{}, "Post:PostCdata")
web.Router("/zkteco/iclock/cdata", &controllers.DeviceZKTecoController{}, "Get:GetCdata")
web.Router("/zkteco/iclock/getrequest", &controllers.DeviceZKTecoController{}, "Get:GetRequest")
web.Router("/zkteco/iclock/ping",&controllers.DeviceZKTecoController{},"Get:Ping")
web.Router("/zkteco/iclock/ping", &controllers.DeviceZKTecoController{}, "Get:Ping")
}
... ...
... ... @@ -53,7 +53,7 @@ func Start() {
deviceCollection.Values = deviceBaoXianJi
break
//油炸机
case domain.DeviceTypeYouZhaJi:
case domain.DeviceTypeYouZhaJi1:
deviceYouZhaJi := &domain.DeviceYouZhaJi{}
err = json.Unmarshal(mBytes, deviceYouZhaJi)
if err != nil {
... ... @@ -61,6 +61,15 @@ func Start() {
}
deviceCollection.Values = deviceYouZhaJi
break
//油炸机
case domain.DeviceTypeYouZhaJi2:
deviceYouZhaJi := &domain.DeviceYouZhaJi2{}
err = json.Unmarshal(mBytes, deviceYouZhaJi)
if err != nil {
continue
}
deviceCollection.Values = deviceYouZhaJi
break
//串串机
case domain.DeviceTypeChuanChuanJi:
deviceChuanChuanJi := &domain.DeviceChuanChuanJi{}
... ...