employee.go 8.6 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/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 (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(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(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)
		}
		// service.addEmployeeData(data.Add)
		// for i := range data.Edit {
		// 	UpdateEmployeeData(data.Edit[i])
		// }
		return nil

	default:
		return errors.New("nothing todo")
	}
	return nil
}

func (service SyncEmployeeService) addEmployeeData(data 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())
	}
	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(data 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())
	}
	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{}{
		"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,
		"EntryTime":    entryTime,
	})
	if err = usersRepository.Edit(&oldUser); err != nil {
		return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = transactionContext.CommitTransaction()
	return err
}

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
}