pg_common_statistics_service.go 10.9 KB
package domainService

import (
	"fmt"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/repository"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"time"
)

const (
	// 时段产能统计
	HourProductiveStatistics = "HourProductiveStatistics"
	// 产能对比
	DailyProductiveStatistics = "DailyProductiveStatistics"
	// 二级品比重
	ProportionOfSecondLevelStatistics = "ProportionOfSecondLevelStatistics"
	// 车间生产效率
	WorkshopProductionEfficiencyStatistics = "WorkshopProductionEfficiencyStatistics"
	// 设备运行统计
	DeviceRunningStatistics = "DeviceRunningStatistics"
)

const (
	SectionNameCCJ = "穿串"
)

type PGCommonStatisticsService struct {
	transactionContext *pgTransaction.TransactionContext
}

func (ptr *PGCommonStatisticsService) CommonStatistics(actionType string, queryOptions map[string]interface{}) (interface{}, error) {
	var result interface{}
	var err error
	switch actionType {
	case HourProductiveStatistics:
		result, err = ptr.HourProductiveStatistics(queryOptions)
		break
	case DailyProductiveStatistics:
		result, err = ptr.DailyProductiveStatistics(queryOptions)
		break
	case ProportionOfSecondLevelStatistics:
		result, err = ptr.ProportionOfSecondLevelStatistics(queryOptions)
		break
	case WorkshopProductionEfficiencyStatistics:
		result, err = ptr.WorkshopProductionEfficiencyStatistics(queryOptions)
		break
	case DeviceRunningStatistics:
		result, err = ptr.DeviceRunningStatistics(queryOptions)
		break
	}
	return result, err
}

// 时段产能-统计 (传串设备)
func (ptr *PGCommonStatisticsService) HourProductiveStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	var request = &HourProductiveStatisticsRequest{}
	if err := utils.LoadQueryObject(queryOptions, request); err != nil {
		return nil, err
	}

	workshopRepository, _ := repository.NewWorkshopRepository(ptr.transactionContext)
	type record struct {
		Ts    string  `json:"ts"`
		Total float64 `json:"total"`
	}

	workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
	if err != nil || workshop == nil {
		return nil, nil
	}
	productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)

	var response = make([]interface{}, 0)
	var tmpXData = make([]string, 0)
	for _, v := range workshop.GetProductLines(domain.NotDeleted) {
		var result = make([]*record, 0)
		if err := productRecordDao.TimeSectionProductRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, time.Now().Add(-time.Hour*5), &result); err != nil {
			log.Logger.Error(err.Error())
			continue
		}
		var xData []string = make([]string, 0)
		var values []interface{} = make([]interface{}, 0)
		for _, r := range result {
			xData = append(xData, r.Ts)
			values = append(values, r.Total)
		}
		if len(tmpXData) == 0 {
			tmpXData = xData
		}
		response = append(response, map[string]interface{}{
			"lineName": v.LineName,
			"data":     NewXYData(xData, values),
		})
	}
	return map[string]interface{}{
		"xAxis": tmpXData,
		"list":  response,
	}, nil
}

type HourProductiveStatisticsRequest struct {
	CompanyId  int `json:"companyId" valid:"Required"`
	OrgId      int `json:"orgId" valid:"Required"`
	WorkshopId int `json:"workshopId" valid:"Required"`
}

func NewXYData(xData []string, values interface{}) interface{} {
	//return map[string]interface{}{
	//"xAxis": map[string]interface{}{
	//	"data": xData,
	//},
	//"source": map[string]interface{}{
	//	"value": values,
	//},
	//}
	return values
}

// 时段产能-统计 (传串设备)
func (ptr *PGCommonStatisticsService) DailyProductiveStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	var request = &HourProductiveStatisticsRequest{}
	if err := utils.LoadQueryObject(queryOptions, request); err != nil {
		return nil, err
	}

	workshopRepository, _ := repository.NewWorkshopRepository(ptr.transactionContext)
	type record struct {
		Ts    string  `json:"ts"`
		Total float64 `json:"total"`
	}

	workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
	if err != nil || workshop == nil {
		return nil, nil
	}
	productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)

	var response = make([]interface{}, 0)
	var tmpXData = make([]string, 0)

	for _, v := range workshop.GetProductLines(domain.NotDeleted) {
		var result = make([]*record, 0)
		if err := productRecordDao.TimeSectionRunningRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.LineId, SectionNameCCJ, time.Now().Add(-time.Hour*24*7), &result); err != nil {
			log.Logger.Error(err.Error())
			continue
		}
		var xData []string = make([]string, 0)
		var values []interface{} = make([]interface{}, 0)
		for _, r := range result {
			xData = append(xData, r.Ts)
			values = append(values, utils.Round(r.Total*DefaultCCJUnitQuantity, 1))
		}
		if len(tmpXData) == 0 {
			tmpXData = xData
		}
		response = append(response, map[string]interface{}{
			"lineName": v.LineName,
			"data":     NewXYData(xData, values),
		})
	}
	return map[string]interface{}{
		"recent_7_day": map[string]interface{}{
			"xAxis": tmpXData,
			"list":  response,
		},
	}, nil
}

// 二级品占比
func (ptr *PGCommonStatisticsService) ProportionOfSecondLevelStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	var request = &HourProductiveStatisticsRequest{}
	if err := utils.LoadQueryObject(queryOptions, request); err != nil {
		return nil, err
	}

	workshopRepository, _ := repository.NewWorkshopRepository(ptr.transactionContext)
	type record struct {
		Sname string  `json:"sname"`
		Rate  float64 `json:"rate"`
	}

	workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
	if err != nil || workshop == nil {
		return nil, nil
	}
	productRecordDao, _ := dao.NewProductRecordDao(ptr.transactionContext)

	var input = []struct {
		name string
		t    time.Time
	}{
		{"today", utils.GetZeroTime(time.Now())},
		{"current_week", utils.GetCurrentWeekFirstDay(time.Now())},
		{"current_month", utils.GetCurrentMonthFirstDay(time.Now())},
	}

	var response = make(map[string]interface{})
	for _, v := range input {
		var result = make([]*record, 0)
		if err := productRecordDao.ProportionOfSecondLevelRecord(request.CompanyId, request.OrgId, request.WorkshopId, v.t, &result); err != nil {
			log.Logger.Error(err.Error())
			return nil, err
		}
		response[v.name] = result
	}

	return response, nil
}

// 车间生产效率统计
func (ptr *PGCommonStatisticsService) WorkshopProductionEfficiencyStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	var request = &HourProductiveStatisticsRequest{}
	if err := utils.LoadQueryObject(queryOptions, request); err != nil {
		return nil, err
	}

	workshopRepository, _ := repository.NewWorkshopRepository(ptr.transactionContext)
	type record struct {
		Oee float64 `json:"oee"`
		Pu  float64 `json:"pu"`
		Tu  float64 `json:"tu"`
		Qu  float64 `json:"qu"`
	}

	workshop, err := workshopRepository.FindOne(map[string]interface{}{"workshopId": request.WorkshopId})
	if err != nil || workshop == nil {
		return nil, nil
	}
	productRecordDao, _ := dao.NewDeviceDailyRunningRecordDao(ptr.transactionContext)

	var input = []struct {
		name string
		t    time.Time
	}{
		{"today", utils.GetZeroTime(time.Now())},
		{"current_week", utils.GetCurrentWeekFirstDay(time.Now())},
		{"current_month", utils.GetCurrentMonthFirstDay(time.Now())},
	}

	var response = make(map[string]interface{})
	for _, v := range input {
		var result = record{}
		if err := productRecordDao.WorkshopProductionEfficiencyStatistics(request.CompanyId, request.OrgId, request.WorkshopId, v.t, &result); err != nil {
			log.Logger.Error(err.Error())
			return nil, err
		}
		response[v.name] = result
	}

	return response, nil
}

// 设备运行统计
func (ptr *PGCommonStatisticsService) DeviceRunningStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	var request = &DeviceRunningStatisticRequest{}
	if err := utils.LoadQueryObject(queryOptions, request); err != nil {
		return nil, err
	}

	deviceRepository, _ := repository.NewDeviceRepository(ptr.transactionContext)
	deviceRunningRecordRepository, _ := repository.NewDeviceDailyRunningRecordRepository(ptr.transactionContext)

	var t time.Time
	var err error
	if len(request.Date) > 0 {
		t, err = time.ParseInLocation("2006-01-02", request.Date, time.Local)
		if err != nil {
			log.Logger.Error(err.Error())
		}
	}
	_, devices, err := deviceRepository.Find(map[string]interface{}{
		"companyId":  request.CompanyId,
		"orgId":      request.OrgId,
		"workshopId": request.WorkshopId,
		"lineId":     request.LineId,
		"orderBy":    "device_name asc"})
	if err != nil {
		return nil, err
	}

	var response = make([]interface{}, 0)
	_, dailyRecords, err := deviceRunningRecordRepository.Find(map[string]interface{}{"companyId": request.CompanyId, "orgId": request.OrgId, "productDate": t})
	for i := 0; i < len(devices); i++ {
		d := devices[i]
		if d.Ext == nil || d.Ext.DeviceExt == nil || d.Ext.DeviceExt.IsProductDevice == 0 {
			continue
		}
		var r *domain.DeviceDailyRunningRecord
		item := make(map[string]interface{})
		//item["id"] = uuid.New().String()
		item["orgName"] = d.Ext.OrgName
		if d.WorkStation != nil {
			item["workshopName"] = d.WorkStation.WorkshopName
			item["lineName"] = d.WorkStation.LineName
			item["deviceName"] = d.DeviceName
			item["oee"] = 0
			item["status"] = []struct{}{}
		}
		for j := 0; j < len(dailyRecords); j++ {
			if d.DeviceCode == dailyRecords[j].DeviceCode {
				r = dailyRecords[j]
				item["oee"] = r.DeviceRunningRecordInfo.OEE
				break
			}
		}
		if r != nil {
			//log.Logger.Debug(fmt.Sprintf("%v %v",r.UpdatedAt.Local().Hour(),r.UpdatedAt.Local().Minute()))
			m := r.UpdatedAt.Local().Hour()*60 + r.UpdatedAt.Local().Minute()
			if r.UpdatedAt.Before(utils.GetZeroTime(time.Now())) {
				m = 60 * 24
			}
			item["status"] = r.DeviceRunningRecordInfo.HourDeviceStatusDetail(m)
			item["status_info"] = r.DeviceRunningRecordInfo.TimeLineDeviceStatus
		}
		response = append(response, item)
	}
	return map[string]interface{}{
		"devices": response,
	}, nil
}

type DeviceRunningStatisticRequest struct {
	CompanyId  int    `json:"companyId" valid:"Required"`
	OrgId      int    `json:"orgId" valid:"Required"`
	WorkshopId int    `json:"workshopId"`
	LineId     int    `json:"lineId""`
	Date       string `json:"date"`
}

func NewPGCommonStatisticsService(transactionContext *pgTransaction.TransactionContext) (*PGCommonStatisticsService, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &PGCommonStatisticsService{
			transactionContext: transactionContext,
		}, nil
	}
}