pg_rob_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/dao"
	"gitlab.fjmaimaimai.com/linmadan/mmm-worth/pkg/infrastructure/repository"
	"time"
)

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

func (service *RobTaskService) Rob(taskId int64, receiverUid int64) (*domain.Task, error) {
	var employeeRepository domain.EmployeeRepository
	var taskRepository domain.TaskRepository
	var taskDao *dao.TaskDao
	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 dao, err := dao.NewTaskDao(service.transactionContext); err != nil {
		return nil, err
	} else {
		taskDao = dao
	}
	receiver, err := employeeRepository.FindOne(map[string]interface{}{
		"uid": receiverUid,
	})
	if err != nil {
		return nil, err
	}
	if receiver == 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 receiver.EmployeeInfo.Uid == task.Sponsor.Uid {
		return nil, fmt.Errorf("无法领取自己发布的任务")
	}
	if task.RobInfo != nil && task.RobInfo.Receiver != nil {
		return nil, fmt.Errorf("任务已经被人领取")
	}
	if err := task.Rob(receiver.EmployeeInfo); err != nil {
		return nil, err
	}
	if err := taskDao.AddRobInfo(taskId, receiver.EmployeeInfo); err != nil {
		return nil, fmt.Errorf("抢单失败,任务可能已经被人领取")
	}
	if task, err := taskRepository.Save(task); err != nil {
		return nil, err
	} else {
		taskRobedEvent := new(event.TaskRobed)
		taskRobedEvent.OccurredOn = time.Now()
		taskRobedEvent.TaskId = task.TaskId
		taskRobedEvent.CompanyId = task.CompanyId
		taskRobedEvent.TaskName = task.TaskName
		taskRobedEvent.TaskType = task.TaskType
		taskRobedEvent.Sponsor = task.Sponsor
		taskRobedEvent.TaskStatus = task.TaskStatus
		taskRobedEvent.ReferenceResource = task.ReferenceResource
		taskRobedEvent.RobInfo = task.RobInfo
		if err := service.Publish(taskRobedEvent); err != nil {
			return nil, err
		}
		return task, nil
	}
}

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