pg_off_task_service.go 2.9 KB
package domain_service

import (
	"fmt"
	coreDomain "github.com/linmadan/egglib-go/core/domain"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/domain/event"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/repository"
	"time"
)

type OffTaskService struct {
	coreDomain.BaseEventPublisher
	transactionContext *pgTransaction.TransactionContext
}

func (service *OffTaskService) Off(taskId int64, operatorUid int64, offReason string) (*domain.Task, error) {
	var employeeRepository domain.EmployeeRepository
	var taskRepository domain.TaskRepository
	var offTaskRecordRepository domain.OffTaskRecordRepository
	if repository, err := repository.NewEmployeeRepository(service.transactionContext); err != nil {
		return nil, err
	} else {
		employeeRepository = repository
	}
	if repository, err := repository.NewTaskRepository(service.transactionContext); err != nil {
		return nil, err
	} else {
		taskRepository = repository
	}
	if repository, err := repository.NewOffTaskRecordRepository(service.transactionContext); err != nil {
		return nil, err
	} else {
		offTaskRecordRepository = repository
	}
	operator, err := employeeRepository.FindOne(map[string]interface{}{
		"uid": operatorUid,
	})
	if err != nil {
		return nil, err
	}
	if operator == nil {
		return nil, fmt.Errorf("无效的操作者")
	}
	task, err := taskRepository.FindOne(map[string]interface{}{
		"taskId": taskId,
	})
	if err != nil {
		return nil, err
	}
	if task == nil {
		return nil, fmt.Errorf("无效的任务")
	}
	if operator.EmployeeInfo.Uid != task.Sponsor.Uid {
		return nil, fmt.Errorf("无效的操作者")
	}
	if err := task.Off(); err != nil {
		return nil, err
	}
	offTaskRecord := &domain.OffTaskRecord{
		Task:       task,
		Operator:   operator.EmployeeInfo,
		OffReason:  offReason,
		CreateTime: time.Now(),
	}
	if _, err := offTaskRecordRepository.Save(offTaskRecord); err != nil {
		return nil, err
	}
	if task, err := taskRepository.Save(task); err != nil {
		return nil, err
	} else {
		taskClosedEvent := new(event.TaskClosed)
		taskClosedEvent.OccurredOn = time.Now()
		taskClosedEvent.TaskId = task.TaskId
		taskClosedEvent.CompanyId = task.CompanyId
		taskClosedEvent.TaskName = task.TaskName
		taskClosedEvent.TaskType = task.TaskType
		taskClosedEvent.Sponsor = task.Sponsor
		taskClosedEvent.TaskStatus = task.TaskStatus
		taskClosedEvent.ReferenceResource = task.ReferenceResource
		if err := service.Publish(taskClosedEvent); err != nil {
			println(err.Error())
		}
		return task, nil
	}
}

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