pg_batch_add_device_service.go 2.5 KB
package domainService

import (
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	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/repository"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	"time"
)

type PGBatchAddDeviceService struct {
	transactionContext *pgTransaction.TransactionContext
}

func (ptr *PGBatchAddDeviceService) BatchAddDevice(opt *domain.OperateInfo, list []*domain.ImportDeviceItem) ([]interface{}, error) {
	var failRows = make([]interface{}, 0)

	var userService = NewUserService()
	var org *domain.Org
	org, err := userService.Organization(opt.OrgId)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	deviceRepository, _ := repository.NewDeviceRepository(ptr.transactionContext)
	_, devices, _ := deviceRepository.Find(map[string]interface{}{"companyId": opt.CompanyId, "orgId": opt.OrgId})
	var mapProduct = make(map[string]*domain.Device)
	for i := range devices {
		mapProduct[devices[i].DeviceCode] = devices[i]
	}

	for i := range list {
		item := list[i]
		if err := item.Valid(); err != nil {
			item.FailReason = err.Error()
			failRows = append(failRows, item)
			continue
		}
		newItem := &domain.Device{
			CompanyId:    opt.CompanyId,
			OrgId:        opt.OrgId,
			DeviceCode:   item.DeviceCode,
			DeviceName:   item.DeviceName,
			DeviceModel:  item.DeviceCode,
			DeviceType:   item.DeviceType,
			Brand:        item.Brand,
			DeviceStatus: item.DeviceStatus,
			RiskLevel:    item.RiskLevel,
			CreatedAt:    time.Now(),
			UpdatedAt:    time.Now(),
			WorkStation:  &domain.WorkStation{},
			Ext:          domain.NewExt(org.OrgName),
		}
		if _, ok := mapProduct[newItem.DeviceCode]; !ok {
			mapProduct[newItem.DeviceCode] = newItem
		} else {
			item.FailReason = "导入的设备编号已存在"
			failRows = append(failRows, item)
			continue
		}
		if _, err := deviceRepository.Save(newItem); err != nil {
			log.Logger.Error(err.Error())
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "服务器异常")
		}
	}

	return failRows, nil
}

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