employee.go 11.7 KB
package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/unifiedUserCenter/command"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
)

// UserDepartData 用户的部门数据
type UserDepartData struct {
	Id           int64 `json:"id"`
	CompanyId    int64 `json:"company_id"`
	DepartmentId int64 `json:"department_id"`
	UserId       int64 `json:"user_id"`
}

//UserPositionData 用户的职位数据
type UserPositionData struct {
	Id         int64 `json:"id"`
	CompanyId  int64 `json:"company_id"`
	PositionId int64 `json:"position_id"`
	UserId     int64 `json:"user_id"`
}

//EmployeeData 从平台平台接收的数据
type EmployeeData struct {
	Id              int64              `json:"id"`      //用户的id,对应本地的user_company_id
	OpenId          int64              `json:"open_id"` //同一用户中心的用户id
	Phone           string             `json:"phone"`
	Name            string             `json:"name"`
	Sex             int8               `json:"sex"`
	JobNum          string             `json:"job_num"`
	PrivatePhone    string             `json:"private_phone"` //私人手机
	CompanyId       int64              `json:"company_id"`    //总后台的company_id
	Email           string             `json:"email"`
	ExtensionNum    string             `json:"extension_num"` //分机号
	EntryTime       string             `json:"entry_time"`    //入职时间
	WorkSpace       string             `json:"workspace"`
	IsBusiness      int8               `json:"is_business"` //
	Status          int8               `json:"status"`
	Avatar          string             `json:"avatar"`
	ExtraText       string             `json:"extra_text"`
	Remarks         string             `json:"remarks"`
	AdminType       int8               `json:"admin_type"`
	ChargeStatus    int8               `json:"charge_status"`
	UserDepartments []UserDepartData   `json:"user_departments"`
	UserPositions   []UserPositionData `json:"user_positions"`
}

//DeleteUserData 批量删除用户
type DeleteUserData struct {
	CompanyId int64   `json:"companyId"`
	Ids       []int64 `json:"ids"`
}

//ForbidAllowUserData 禁用启用用户
type ForbidAllowUserData struct {
	CompanyId int64   `json:"companyId"`
	Ids       []int64 `json:"ids"`
	Status    int8    `json:"status"`
}

//ImportEmployeeData 批量导入用户
type ImportEmployeeData struct {
	Add  []EmployeeData `json:"add"`
	Edit []EmployeeData `json:"edit"`
}

//SyncEmployeeService 同步用户数据
type SyncEmployeeService struct{}

func NewSyncEmployeeService(option map[string]interface{}) *SyncEmployeeService {
	syncEmployee := new(SyncEmployeeService)
	return syncEmployee
}

var _ SyncAction = (*SyncEmployeeService)(nil)

func (service SyncEmployeeService) DoAction(action string, byteData []byte) error {
	switch action {
	case "add":
		//添加
		var (
			data EmployeeData
			err  error
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		err = service.addEmployeeData([]EmployeeData{data})
		return err
	case "edit":
		//编辑更新
		var (
			data EmployeeData
			err  error
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		err = service.updateEmployeeData([]EmployeeData{data})
		return err
	case "batchDelete":
		//批量删除
		var (
			err  error
			data DeleteUserData
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		return service.deleteEmployeeData(data)
	case "batchForbid":
		//启用禁用
		var (
			err  error
			data ForbidAllowUserData
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		return service.updateUsersStatus(data)
	// case "batchRemove":
	// 	//移动通讯录用户部门 暂时不需要
	// 	return nil
	case "import":
		//批量导入
		var (
			data ImportEmployeeData
			err  error
		)
		err = json.Unmarshal(byteData, &data)
		if err != nil {
			return fmt.Errorf("数据解析失败:%s", err)
		}
		err1 := service.addEmployeeData(data.Add)
		err2 := service.updateEmployeeData(data.Edit)
		if err1 != nil || err2 != nil {
			return fmt.Errorf("添加用户错误:%s,更新用户发生错误:%s", err1, err2)
		}
		return nil
	default:
		return errors.New("action not found")
	}
}

func (service SyncEmployeeService) addEmployeeData(datas []EmployeeData) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var usersRepository domain.UsersRepository
	if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	for i := range datas {
		data := datas[i]
		newUser := domain.Users{
			Id:             data.Id,
			CompanyId:      data.CompanyId,
			OpenId:         data.OpenId,
			Name:           data.Name,
			Sex:            data.Sex,
			JobNum:         data.JobNum,
			Phone:          data.Phone,
			PrivatePhone:   data.PrivatePhone,
			Email:          data.Email,
			ExtensionNum:   data.ExtensionNum,
			Workspace:      data.WorkSpace,
			Status:         data.Status,
			Avatar:         data.Avatar,
			Remarks:        data.Remarks,
			ChargeStatus:   data.ChargeStatus,
			Permission:     []domain.AdminPermissionBase{}, //初始化权限
			AccessPartners: []domain.Partner{},             //默认初始化
		}
		newUser.EntryTime, _ = time.Parse("2006-01-02", data.EntryTime)
		if err = usersRepository.Add(&newUser); err != nil {
			return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	err = transactionContext.CommitTransaction()
	return err
}

func (service SyncEmployeeService) updateEmployeeData(datas []EmployeeData) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var usersRepository domain.UsersRepository
	if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	for i := range datas {
		data := datas[i]
		var oldUser domain.Users
		oldUser, err = usersRepository.FindOne(domain.UsersFindOneQuery{
			Id: data.Id,
		})
		if err != nil {
			return lib.ThrowError(lib.BUSINESS_ERROR, err.Error())
		}
		entryTime, _ := time.Parse("2006-01-02", data.EntryTime)
		_ = oldUser.Update(map[string]interface{}{
			"CompanyId":    data.CompanyId,
			"OpenId":       data.OpenId,
			"Name":         data.Name,
			"Sex":          data.Sex,
			"JobNum":       data.JobNum,
			"Phone":        data.Phone,
			"PrivatePhone": data.PrivatePhone,
			"Email":        data.Email,
			"ExtensionNum": data.ExtensionNum,
			"Workspace":    data.WorkSpace,
			"Status":       data.Status,
			"Avatar":       data.Avatar,
			"Remarks":      data.Remarks,
			"ChargeStatus": data.ChargeStatus,
			"EntryTime":    entryTime,
		})
		if err = usersRepository.Edit(&oldUser); err != nil {
			return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
		}
	}
	err = transactionContext.CommitTransaction()
	return err
}

//deleteEmployeeData 删除用户
func (service SyncEmployeeService) deleteEmployeeData(data DeleteUserData) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var usersRepository domain.UsersRepository
	if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err = usersRepository.Remove(data.Ids); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = transactionContext.CommitTransaction()
	return err
}

//UpdateUsersStatus 批量更新用户的状态
func (service SyncEmployeeService) updateUsersStatus(data ForbidAllowUserData) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var uDao *dao.UsersDao
	if uDao, err = factory.CreateUsersDao(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err = uDao.UpdateUserStatus(data.Ids, data.Status); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = transactionContext.CommitTransaction()
	return err
}

//ChangeAdmin 变更公司负责人,超级管理员
func (service SyncEmployeeService) ChangeSuperAdmin(cmd command.ChanceSuperAdminCommand) error {
	var (
		transactionContext, _ = factory.CreateTransactionContext(nil)
		err                   error
	)
	if err = transactionContext.StartTransaction(); err != nil {
		return err
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()
	var usersRepository domain.UsersRepository
	if usersRepository, err = factory.CreateUsersRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	}); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	var (
		oldSuperUser domain.Users
		newSuperUser domain.Users
		userList     []domain.Users
	)
	_, userList, err = usersRepository.Find(domain.UsersFindQuery{
		CompanyId: cmd.CompanyId,
		AdminType: domain.UserIsAdmin,
	})
	if err != nil {
		e := fmt.Sprintf("获取用户(admin_type=%d;company_id=%d)数据失败:%s",
			domain.UserIsAdmin, cmd.CompanyId, err.Error())
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e)
	}
	if len(userList) == 0 {
		e := fmt.Sprintf("没有获得公司主管数据(admin_type=%d;company_id=%d)",
			domain.UserIsAdmin, cmd.CompanyId)
		return lib.ThrowError(lib.BUSINESS_ERROR, e)
	}
	if len(userList) > 1 {
		e := fmt.Sprintf("存在复数公司主管数据(admin_type=%d;company_id=%d)",
			domain.UserIsAdmin, cmd.CompanyId)
		return lib.ThrowError(lib.BUSINESS_ERROR, e)
	}
	oldSuperUser = userList[0]
	newSuperUser, err = usersRepository.FindOne(domain.UsersFindOneQuery{
		CompanyId: cmd.CompanyId,
		Phone:     cmd.Phone,
	})
	if err != nil {
		e := fmt.Sprintf("获取公司用户数据(phone=%s;company_id=%d)",
			cmd.Phone, cmd.CompanyId)
		return lib.ThrowError(lib.BUSINESS_ERROR, e)
	}
	err = oldSuperUser.Update(map[string]interface{}{
		"AdminType": domain.UserIsNotAdmin,
	})
	if err != nil {
		return lib.ThrowError(lib.BUSINESS_ERROR, err.Error())
	}
	err = newSuperUser.Update(map[string]interface{}{
		"AdminType": domain.UserIsAdmin,
	})
	if err != nil {
		return lib.ThrowError(lib.BUSINESS_ERROR, err.Error())
	}
	err = usersRepository.Edit(&oldSuperUser)
	if err != nil {
		e := fmt.Sprintf("更新公司主管user数据(id=%d)",
			oldSuperUser.Id)
		return lib.ThrowError(lib.BUSINESS_ERROR, e)
	}
	err = usersRepository.Edit(&newSuperUser)
	if err != nil {
		e := fmt.Sprintf("更新公司主管user数据(id=%d)",
			newSuperUser.Id)
		return lib.ThrowError(lib.BUSINESS_ERROR, e)
	}
	err = transactionContext.CommitTransaction()
	return nil
}