attendance.go 2.6 KB
package service

import (
	"github.com/gookit/event"
	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/user/command"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/log"
)

func (userService *UserService) SyncToAttendanceMachine(cmd *command.SyncToAttendanceMachineCommand) (interface{}, error) {
	if err := cmd.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	userRepository, _, _ := factory.FastPgUser(transactionContext, 0)
	//orgRepository, _, _ := factory.FastPgOrg(transactionContext, 0)
	var users []*domain.User
	// 指定用户进行同步
	if len(cmd.Users) > 0 {
		_, users, err = userRepository.Find(map[string]interface{}{"companyId": cmd.OperateInfo.CompanyId, "inUserIds": utils.ToArrayInt64(cmd.Users)})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
	} else {
		//org, _ := orgRepository.FindOne(map[string]interface{}{"companyId": cmd.OperateInfo.CompanyId, "orgName": "制造中心"})
		//if org == nil {
		//	return nil, nil
		//}
		_, users, err = userRepository.Find(map[string]interface{}{"companyId": cmd.OperateInfo.CompanyId, "icCardNumberNotEqual": ""})
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
	}

	for i := range users {
		_, userBase, err := factory.FastPgUserBase(transactionContext, users[i].UserBaseId)
		if err != nil {
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
		if err, _ := event.Fire(domain.UserSyncEvent, event.M{"user": users[i], "userBase": userBase}); err != nil {
			log.Logger.Error(err.Error())
			return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
		}
	}

	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return struct{}{}, nil
}